text stringlengths 8 6.05M |
|---|
from loc import nearby_search
from flask import Flask
import json
import requests
# 2. Create the app object
app = Flask(__name__)
@app.route('/')
def home():
return 'Server is Online"'
@app.route('/article',methods = ['get'])
def art():
# Opening JSON file
f = open('article.json')
# returns JSON... |
import util_tools
from pathlib import Path
files = Path('../outputs_santi/class_outputs/').glob('*')
|
print("pastrami has been sold out\n")
sandwish_orders=['StrawBerry','pastrami','Banana','pastrami','pastrami','Apple','Pine','watermelon']
while 'pastrami' in sandwish_orders:
sandwish_orders.remove('pastrami')
print("Here are left sandwish")
for sandwish in sandwish_orders:
print(sandwish)
|
# -*- coding: utf-8 -*-
from architect.repository.client import BaseClient
from celery.utils.log import get_logger
logger = get_logger(__name__)
class EspClient(BaseClient):
def __init__(self, **kwargs):
super(EspClient, self).__init__(**kwargs)
def check_status(self):
return True
def... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 4 10:27:24 2019
@author: se14
"""
# simple ROC analysis of results (not the FROC analysis!)
import pandas as pd
import sklearn.metrics
import matplotlib
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'qt5')
matplotlib.... |
import pygame, sys
from pygame.locals import *
pygame.init()
DISPLAYSURF = pygame.display.set_mode ((400, 300))
MYSURF = pygame.display.set_mode((500,800))
pygame.display.set_caption ('Hello World')
pygame.draw.line(DISPLAYSURF, (255,255,255), (0,0), (50,50))
pygame.draw.rect(DISPLAYSURF, (255,255,255), (0,0,25,25))
p... |
"""
# 计数排序
"""
import os
import logging
import itertools
logger = logging.getLogger(__name__)
def counting_sort(arr: list):
"""计数排序"""
counts = [0] * (max(arr) + 1) # 0~max包含max+1个元素
for element in arr:
# 计数,统计每个元素出现的次数, counts的索引代表arr中的元素值
counts[element] += 1
counts = list(itertoo... |
from typing import Callable, Tuple, Union, Optional, Dict
import numpy as np
from inspect import signature
class Op:
def __init__(self, name: str, description: str, op: Callable, partial_difs: Tuple[Callable]):
assert len(signature(op).parameters) == len(partial_difs)
self._name = name
se... |
# coding=utf-8
from myspider.items import QiushiItem
from scrapy.http import Request
from scrapy.spiders import CrawlSpider
class qiushi(CrawlSpider):
name = 'qiushi'
allowed_domains = ['www.qiushibaike.com']
start_urls = ['https://www.qiushibaike.com/8hr/']
# 糗事百科
def parse(self, response):
... |
from django.db import models
from django.contrib.auth.models import User
from stocks.models import Stock
from cryptocurrencies.models import Cryptocurrency
class StockInvestment(models.Model):
investor = models.ForeignKey(User, on_delete=models.CASCADE)
asset = models.ForeignKey(Stock, on_delete=models.CASCADE... |
# coding=utf-8
#####################################
# Imports
#####################################
# Python native imports
from PyQt5 import QtCore, QtWidgets, QtGui
import logging
from time import time
import paramiko
#####################################
# Global Variables
#####################################
TH... |
import scapy.all as scapy
def sniff(interface):
scapy.sniff(iface = interface, store = False, prn = process_sniffed_packet, filter = 'port 22')
def process_sniffed_packet(packet):
print(packet.summary())
sniff("eth0")
|
import argparse
import numpy as np
import tensorflow as tf
import tensorflow_compression as tfc
import os
from scipy import misc
import CNN_recurrent
import motion
import functions
import helper
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
config = tf.ConfigProto(allow_soft_placement=True)
sess = tf.Session(config=config... |
from celery import shared_task
@shared_task
def debug_task(msg: str) -> None:
print(msg)
|
import random
from PiratesTreasure.ServerPackage import Cell
from PiratesTreasure.ServerPackage import Player
class World:
def __init__(self,players = []):
self.M_rows = 10
self.N_columns = (10 + len(players))
#self.listOfPlayersOnBoard = self.makeListOfPlayersOnTheBoard(players)
se... |
from django.contrib import admin
from . models import Produto, Pedido, InformacaoPedido
# Register your models here.
admin.site.register(Produto)
admin.site.register(Pedido)
admin.site.register(InformacaoPedido) |
def myFunc():
print("Inside mainFn.py and myFunc")
print("Inside mainFn.py")
if __name__=="__main__":
print("Inside mainFn.py, main is called")
else:
print("Inside mainFn.py, main is not called") |
from django.apps import AppConfig
class MantenimientotablaConfig(AppConfig):
name = 'mantenimientoTabla'
|
dicto = dict()
|
import os
import time
from ..utils import PublicKey
import toml
server_key_filename = "~/_mypaas/authorized_keys"
config_filename = "~/_mypaas/config.toml"
last_key_read = 0
_authorized_keys = {}
def get_public_key(fingerprint):
"""Get the public key for the given fingerprint"""
# Read the keys from the ... |
import timeit
start = timeit.default_timer()
A=[9,12,33,47,53,67,78,92]
B=[48,81]
C=[13,41,62]
D=[1,3,45,79]
E=[14,16,24,44,46,55,57,64,74,82,87,98]
F=[10,31]
G=[6,25]
H=[23,39,50,56,65,68]
I=[32,70,73,83,88,93]
J=[15]
K=[4]
L=[26,37,51,84]
M=[22,27]
N=[18,58,59,66,71,91]
O=[0,5,7,54,72,90,99]
P=[3... |
from django.shortcuts import render, get_object_or_404
from .serializers import SnsSerializer, TodoSerializer, SnsSerializer, SnsCreateSerializer, CommentSerializer
from rest_framework.decorators import api_view, permission_classes, authentication_classes
from django.http import JsonResponse, HttpResponse
from rest_fra... |
#coding:utf-8
from PyQt5.QtCore import *
import FLUS_Utils
import numpy as np
import time, os
import xml.etree.cElementTree as ET
from sklearn.externals import joblib
from gdalconst import *
class NNTrainingThread(QThread):
"""
采样 + NN 训练 + 预测的外部线程,与界面主线程不同,可以引入防止界面假死
"""
# 结束信号
finished = pyqtSig... |
#!/home/pi/.pyenv/shims/python
# 电子书项目
# 提供电子书下载
# 提供kindle电子书推送服务
# 提供epub电子书在线阅读服务
import aiopg
import os.path
import psycopg2
import tornado.escape
import tornado.httpserver
import tornado.ioloop
import tornado.locks
import tornado.options
import tornado.web
import unicodedata
# define
from tornado.options import... |
# Copyright Amazon.com, Inc. and its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT
#
# Licensed under the MIT License. See the LICENSE accompanying this file
# for the specific language governing permissions and limitations under
# the License.
from datalake_library.commons import init_logger
... |
import math
import unittest
from game import Game
from model.maps.generators.forest_generator import ForestGenerator
from model.maps.area_map import AreaMap
class TestForestGenerator(unittest.TestCase):
def test_generate_generates_trees(self):
Game()
width, height = (10, 10)
expected_num_... |
from rlpy.Tools.run import run
run("examples/mdp_chain/mdp_chain_post.py","./Results/Tests/mdp_chain/PSRL",ids=range(5), parallelization ="joblib")
run("examples/mdp_chain/mdp_chain_lspi.py","./Results/Tests/mdp_chain/LSPI",ids=range(5), parallelization ="joblib")
run("examples/mdp_chain/mdp_chain_sarsa.py","./Resu... |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 11 15:03:17 2021
An example shows how to write pd.DataFram into excel through openpyxl
@author: renfo
"""
import pandas as pd
import numpy as np
import random
import openpyxl
from openpyxl.utils.dataframe import dataframe_to_rows
import os
mainfolder = ... |
# Copyright 2021 DAI Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
# Generated by Django 2.2.2 on 2019-08-10 17:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0003_chart'),
]
operations = [
migrations.CreateModel(
name='Option_Chain',
fields=[
('id', m... |
from flask import Blueprint
from flask import jsonify
from shutil import copyfile, move
from google.cloud import storage
from google.cloud import bigquery
from google.oauth2 import service_account
from flask import request
from google.auth.transport.requests import AuthorizedSession
import dataflow_pipeline.gestion_hum... |
# import logging
#
# # create a file handler
# handler = logging.FileHandler('hello.log')
# # handler.setLevel(logging.INFO)
#
# # create a logging format
# formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# handler.setFormatter(formatter)
#
# logger = logging.getLogger(__name__)
# ... |
import Queue
def update_queue(current_time, tasks, queue):
# This ugly implementation is to solve the problem raised below
new_queue = Queue.Queue()
while tasks and tasks[0].arrive_time <= current_time:
new_queue.put(tasks[0])
tasks = tasks[1:]
while not queue.empty():
new_queue... |
#!/usr/bin/python3
from dns import reversename, resolver
import sys
import argparse
import csv
import socket
import xlrd
from xlutils.copy import copy
file_name_input = ""
file_name_output = ""
rnd_nw = "10.12." # default network pattern
firstrow = 1 # default second row
dnscolumn = 1 # default second column
parser ... |
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> #alistirma3
>>>
>>> n=1000
>>> x=0
>>> f=1
>>> for i in range(2,n):
f=f*i
x=x+(1/f)
e=2+x
>>> e
2.718281828459045
>>>
>>>... |
import os
import time
import cv2
import albumentations as A
from albumentations.pytorch import ToTensorV2
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
from sklearn.model_selection import train_test_split
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data im... |
import torch
import torch.nn as nn
import torchvision.models as models
class MyModelA(nn.Module):
def __init__(self):
super(MyModelA, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(1, 6, 5, 1),
nn.ReLU(),
... |
# Generated by Django 3.0.7 on 2020-08-20 22:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('qualification', '0003_staffdocument_docname'),
]
operations = [
migrations.AddField(
model_name='maindocument',
name... |
import asyncio
from azure.eventhub.aio import EventHubProducerClient
from azure.eventhub import EventData
async def run():
# Connection string for namespace and name for event hub
VAR_CONN_STR = "Connection string for namespace"
VAR_EVENTHUB_NAME = "Name for event hub"
# Create a produce... |
# -*- coding: utf-8 -*-
"""
We are going to use a simple form with an edit action to edit a comment.
Monkeypatch i18n
>>> import zope.i18n
>>> import zope.i18n.config
>>> old_1, old_2 = zope.i18n.negotiate, zope.i18n.config.ALLOWED_LANGUAGES
>>> zope.i18n.negotiate = lambda context: 'en'
>>> zope.i18n.confi... |
import PIL.Image
import math
class MapHelper(object):
@staticmethod
def new_image(width, height, alpha=False):
"""
Generates a new image using PIL.Image module
returns PIL.IMAGE OBJECT
"""
if alpha is True:
return PIL.Image.new('RGBA', (width, height), (0,... |
class Employee:
num_of_emps=0
raise_amt=1.04
def __init__(self,first,last,pay):
self.first=first
self.last=last
self.email=first+'.'+last+'@gmail.com'
self.pay=pay
Employee.num_of_emps += 1
def apply_raise(self):
self.pay=self.pay*self.raise_amt
... |
paisA = 80000
paisB = 200000
count = 0
while paisA < paisB:
A = paisA * 0.03
B = paisB * 0.015
paisA = paisA + A
paisB = paisB + B
count = count + 1
print(f'O país A ultrapassa o país B em {count} anos')
|
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... |
import requests
IPINFO_URL = 'http://ipinfo.io/{ip}/json'
def get_ip_country(ip_address):
"""Receives ip address string, use IPINFO_URL to get geo data,
parse the json response returning the country code of the IP"""
return requests.get(IPINFO_URL.format(ip = ip_address)).json()['country']
|
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import os
from pants.backend.docker.target_types import DockerImageInstructionsField, DockerImageSourceField
from pants.engine.fs import CreateDigest, ... |
import sys
import os
f = open("C:/Users/user/Documents/python/atcoder/ABC118/import.txt","r")
sys.stdin = f
# -*- coding: utf-8 -*-
n = int(input())
s = list(input())
x = 0
max_x = 0
for i in range(len(s)):
if s[i] == "I":
x += 1
elif s[i] == "D":
x -= 1
max_x = max(max... |
from script.base_api.service_descartes.lessons import *
from script.base_api.service_descartes.examine import *
|
from django.db import models
class Var(models.Model):
"""Persistent app variables."""
name = models.CharField(max_length=255, primary_key=True)
value = models.CharField(max_length=255)
|
from django.shortcuts import render
from django.utils import timezone
from .models import Post
def base(request):
return render(request, 'blog/front.html', {})
def blog_list(request):
posts = Post.objects.get(title="self_Improvement")
return render(request, 'blog/blog_list.html', {'posts'... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-08-29 11:50
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mastermind', '0001_initial'),
]
operations = [
migrations.AddField(
... |
__author__ = "Narwhale"
import string
s = string.ascii_lowercase
def alphabet_position(text):
string_l = []
t = text.split()
for j in t:
t = "".join(t)
for i in t:
if i.lower() in s:
result = s.index(i.lower()) + 1
string_l.append(str(result))
date_str = "... |
def rotateArray(array, n, d):
for i in range(0, d):
x = array[0]
for j in range(0, n-1):
array[j] = array[j+1]
array[n-1]= x
def printarray(array):
for i in range(0, n):
print(array[i])
array= [12,10,5,6,52,36]
n= len(array)
rotateArray(array, n, 2)
printarr... |
'''
fib series: 0 1 1 2 3 5 8 13 21 34 55 89
Ex: 30
21+8+1
Ex: 10
8+2
algo approach:
Ex:30
21
30-21=9
8
9-8=1
1
'''
'''
def nearfib(n): #30,9
a,b=0,1
while n>=b:
if n==b:
return b
a,b=b,a+b
print(a) #21,8,1
return nearfib(n-a) #9,1
... |
# SPDX-License-Identifier: MIT
# Copyright (c) 2021 scmanjarrez. All rights reserved.
# This work is licensed under the terms of the MIT license.
from contextlib import closing
import sqlite3 as sql
import util as ut
DB = 'paimon.db'
def setup_db():
with closing(sql.connect(DB)) as db:
with closing(db.... |
# -*- coding: utf-8 -*-
"""
Default model implementations. Custom database or OAuth backends need to
implement these models with fields and and methods to be compatible with the
views in :attr:`provider.views`.
"""
from __future__ import unicode_literals
import os
from django.conf import settings
from django.core.val... |
#!/usr/bin/python3
def fizzbuzz():
for numbers in range(1, 101):
if (numbers % 15 == 0):
print("FizzBuzz ", end="")
elif (numbers % 3 == 0):
print("Fizz ", end="")
elif (numbers % 5 == 0):
print("Buzz ", end="")
else:
print("{:d} ".form... |
from bird_manager import BirdManager
import numpy as np
birdManager = BirdManager();
filenames, captions = birdManager.get_captions('/data1/BIRD/captions/train')
traindata = np.append(filenames[:, None], captions, axis = 1)
print filenames.shape
print captions.shape
|
""" I'm sorry.
"""
def walk_stack_for(var_name):
import inspect
frame = None
try:
for f in inspect.stack()[1:]:
frame = f[0]
code = frame.f_code
if code.co_varnames[:1] == (var_name, ):
return frame.f_locals[var_name]
elif code.co_va... |
'''
Find duplicate glyphs in selected font
'''
from collections import Counter
def find(font_glyphs):
'''Check if there are duplicate glyphs'''
print '***Find Duplicate glyphs in selected font***'
glyphs_count = Counter(font_glyphs)
if len(set(glyphs_count.values())) >= 2:
for glyph in glyphs_... |
__author__ = 'iceke'
class Util(object):
def a(self):
pass
'''
transform all kinds of time to minute
'''
@staticmethod
def format_time(time_str):
final_time = 0.0
time_array = time_str.split(' ')
unit = time_array[1]
value = float(time_array[0])
... |
#!/usr/bin/python
# Copyright 2008-2012 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
from __future__ import print_function
import sys
from os import path as osp
pym_path = osp.join(osp.dirname(osp.dirname(osp.realpath(__file__))), "pym")
sys.path.insert(0, pym_path)
import por... |
import DigitalMicrograph as DM
print("Initializing DigitalMicrograph environmnet...")
# the name of the tag is used, this is deleted so it shouldn't matter anyway
file_tag_name = "__python__file__"
# the dm-script to execute, double curly brackets are used because of the
# python format function
script = ("\n".join(... |
# Submitter: loganw1(Wang, Logan)
import prompt
import goody
# Use these global variables to index the list associated with each name in the dictionary.
# e.g., if men is a dictionary, men['m1'][match] is the woman who matches man 'm1', and
# men['m1'][prefs] is the list of preference for man 'm1'.
# It would seems t... |
import sys
FIB = [0,1,1]
def fib(n):
if n < len(FIB):
return FIB[n]
else:
l = len(FIB)
for i in xrange(l,n+1):
FIB.append(FIB[-1]+FIB[-2])
return FIB[-1]
with open(sys.argv[1],'r') as f:
for line in f:
print fib(int(line.strip()))
|
import math
from decimal import *
def golden():
getcontext().prec = 100
gr = Decimal(1+Decimal(math.sqrt(Decimal(5))))/2
return gr
print(golden())
|
import os
import numpy as np
import time
import argparse
# import logging
from mpi4py import MPI
from math import ceil
from random import Random
import networkx as nx
import torch
import torch.distributed as dist
import torch.utils.data.distributed
import torch.nn as nn
import torch.nn.functional as F
import torch.op... |
D = {
1: 5.6,
2: 7.8,
3: 6.6,
4: 8.7,
5: 7.7
}
# i
D[8] = 8.8
print(D)
# ii
D.pop(2)
print(D)
# iii
if 6 in D: print("yes")
else : print("no")
# iv
print(len(D))
# v
sum = 0
for v in D.values(): sum += v
print(sum)
# vi
D[3] = 7.1
print(D)
# vii
D.clear()
print(D)
|
from girder.models.setting import Setting
from girder.plugins.imagespace.settings import ImageSpaceSetting
class GeorgetownSetting(ImageSpaceSetting):
requiredSettings = ('IMAGE_SPACE_GEORGETOWN_DOMAIN_DYNAMICS_SEARCH',)
def validateImageSpaceGeorgetownDomainDynamicsSearch(self, doc):
return doc.rstri... |
import dataPuller
# import helpers
# this will get the acutal data once the url is figured out
dataPuller.getData(2006, 11, 1, 54)
# helpers.getUrl(2013, 10, 15) |
def armstrong_num(num):
num_1 = num
res=0
while num != 0:
rem = num % 10
res = res + rem ** 3
num = num // 10
return num_1 == res
input_num = int(input("enter a number"))
if(armstrong_num(input_num)):
print(f"given num {input_num} is armstrong")
else:
print(f"given num ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__license__ = ''
__version__ = '1.0.1'
update_permission_element_query = """
UPDATE public.permission AS pmr
SET (module, action, active, updated_on) = (
$2::VARCHAR, $3::VARCHAR, $4::BOOLEAN, now())
WHERE pmr.id::BIGINT = $1
RETURNING *;
"""
|
from clpy.types.string import String
from clpy.space import Space
def test_string():
space = Space()
assert space.hash(String('a')) == space.hash(String('a'))
assert space.eq(String('a'), String('a'))
assert not space.eq(String('a'), String('b'))
|
from flask import Blueprint, render_template, abort, session, request, jsonify, url_for, redirect
from jinja2 import TemplateNotFound
from flaskConfiguration import monDB
from datetime import datetime, date, timedelta
import application.codechefAPI as helper
from flaskConfiguration import monDB
notifications_page = Bl... |
from equadratures import *
import numpy as np
import matplotlib.pyplot as plt
VALUE = 15
plt.rcParams.update({'font.size': VALUE})
order = 4
s1 = Parameter(lower=-1, upper=1, order=order, distribution='Uniform')
myBasis = Basis('univariate')
myPoly = Poly(s1, myBasis, method='numerical-integration')
points, weights = ... |
from flask import request, Blueprint, json, Response
from ..models.VehicleModel import VehicleModel, VehicleSchema
vehicle_api = Blueprint('vehicle_api', __name__)
vehicle_schema = VehicleSchema()
@vehicle_api.route('/', methods=['POST'])
def create():
req_data = request.get_json()
data, error = vehicle_sche... |
x = "there are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "those who know %d and those who %d." % (binary, do_not)
print(x)
print(y)
print("i said: %r." % x)
print("i also said: '%s'." % y)# 如果删去‘’,则输出这句话中没有引号。但是上一句话仍旧有。%r 和 %s差异导致?
hilarious = False
joke_evaluatoin = "isn't that jo... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import OpenGL.GL as gl
import OpenGL.GLU as glu
#local imports
from common import COLORS
from screen import Screen
class CheckerBoard:
def __init__(self,
nrows,
check_width = 1.0,
check_height = None... |
# -*- coding: utf-8 -*-
import smtplib
mail_server = "smtp.rambler.ru"
mail_server_port = 465
from_addr = 'EMAIL_FROM'
to_addr = 'EMAIL_TO'
from_header = 'From: %s\r\n' % from_addr
to_header = 'To: %s\r\n\r\n' % to_addr
subject_header = 'Subject: Testing SMTP Authentication'
body = 'This mail tests SMTP Authenticati... |
def test_import():
from instapi import Client
from instapi import ClientCompatPatch
from instapi import (
ClientError,
ClientLoginError,
ClientLoginRequiredError,
ClientCookieExpiredError,
ClientThrottledError,
ClientConnectionError,
ClientCheckpointRe... |
import os
import yaml
curdir = os.path.dirname(__file__)
specs_dir = os.path.join(curdir, 'specs')
def load_spec(spec):
return yaml.load(open(os.path.join(specs_dir, spec+'.yaml')))
# Different specs
SPECS = [
load_spec('empty'),
load_spec('local'),
]
# Different configs
CONFIGS = [
dict(allowed_t... |
# Generated by Django 2.2.5 on 2020-02-24 08:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('data_app', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='students',
name='mobile',
... |
#coding: utf-8
from scrapy.cmdline import execute
import os
import urllib
import requests
if __name__ == '__main__':
project_name = "zyh"
spider_name = "test"
s = "scrapy crawl dmoz"
# s = "scrapy crawl %s -o %s -t json" % (spider_name, results_name)
execute(s.split())
|
from django.contrib import admin
# Register your models here.
from .models import BlogMeta
class BlogMetaAdmin(admin.ModelAdmin):
list_display = ('key', "value")
admin.site.register(BlogMeta, BlogMetaAdmin)
|
class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
"""
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/
"""
sum = 0
for w in words:
n = len(w)
i = 0
while i < n:
if w.co... |
"""
https://github.com/microsoft/DeepSpeed
deepspeed/ops/sparse_attention/sparsity_config.py
"""
import json
import random
import torch
MAX_SEQ_LENGTH = 512
def setup_layout(num_heads, max_position, block):
if max_position % block != 0:
raise ValueError(
f"Sequence Length, {max_position}, ... |
import random
from enum import Enum
class Suit(Enum):
"""
Suit start from 0 to 3
"""
Spades = 0
Hearts = 1
Clubs = 2
Diamonds = 3
class Value(Enum):
"""
Value start from 1 to 13
"""
Ace, Two, Three, Four = 1, 2, 3, 4
Five, Six, Seven, Eight = 5, 6, 7, 8
Nine, Ten, ... |
import sys
import os
f = open("C:/Users/user/Documents/python/atcoder/ABC118/import.txt","r")
sys.stdin = f
# -*- coding: utf-8 -*-
import math
n = int(input())
def factorize(n):
fct = [] # prime factor
b, e = 2, 0 # base, exponent
while b * b <= n:
while n % b == 0:
... |
# -*- coding: utf-8 -*-
import numpy as np
# from DataProcessor.QASent import QASentdataPreprocess
from DataProcessor.QASentForServer import QASentForServerdataPreprocess
from DataProcessor.WikiQA import WikiQAdataPreprocess
from DataProcessor.insuranceQA import insuranceQAPreprocess
from NeuralModel.IAGRU_WORD import... |
def validate_ean(code):
checksum = int(code[-1])
total = 0
for i, a in enumerate(code[:-1]):
number = int(a)
if i % 2 != 0:
number *= 3
total += number
total = 0 if total % 10 == 0 else 10 - (total % 10)
return total == checksum
|
import random
import numpy as np
import tensorflow as tf
import scipy.sparse as sp
from .base_sequence import Sequence
class MiniBatchSequence(Sequence):
def __init__(
self,
x,
y,
out_weight=None,
shuffle=False,
batch_size=1,
*args, **kwargs
):
... |
#lib import
import sys, os
sys.path.append('..\\..\\')
import derpapi
import pygame
RUN = False
y = 30
c = 0
optpos = {}
optkeys = []
set_stor = [{'name':'Airplane Mode', 'type':'switch', 'default':False}, {'name':'WiFi','type':'custom','default':None}]
#screen init
try:
pygame.init()
except:
p... |
import json
from . import utils
from .post_request import post_request
from .config_param import config_param
def upload_sector(filename, sector_name):
"""
Upload sector to the simulator host.
Parameters
----------
filename : str
A string indicating path to sector geojson file on the loc... |
import numpy as np
from signum import sign
################################################################################
# class Perceptron
################################################################################
class Perceptron(object):
def __init__(self, dim = 0, avg_flag = False):
self.dim = dim... |
def crc16(data: str, poly: hex = 0xA001) -> str:
'''
CRC-16 MODBUS HASHING ALGORITHM
'''
crc = 0xFFFF
for byte in data:
crc ^= ord(byte)
for _ in range(8):
crc = ((crc >> 1) ^ poly
if (crc & 0x0001)
else crc >> 1)
hv = hex(c... |
"""
This script implements a pH calibration protocol that involves mixing Phosphoric Acid and water, and then adaptively adding NaOH until the solution reaches as target pH. The protocols includes several cases for expected conditions, such as requiring pH meter re-calibration, failures in Provision steps, failures in... |
from collections import Counter
from matplotlib import pyplot as plt
grades = [83, 95, 91, 87, 70, 0, 85, 82, 100, 67, 73, 77, 0]
histogram = Counter(min(grade // 10 * 10, 90) for grade in grades) #Dict for students with marks
plt.bar([x+5 for x in histogram.keys()],histogram.values(), 10, edgecolor=(0,0,0))
plt.axi... |
from django import forms
from django.contrib.auth.forms import UserCreationForm
from reddituser.models import RedditUser
class SignUpForm(UserCreationForm):
class Meta:
model = RedditUser
fields = UserCreationForm.Meta.fields + ('email', 'bio')
class LoginForm(forms.Form):
username = forms.C... |
from panda3d.core import ModelNode, NodePath, Vec4, CKeyValues, Vec3
from panda3d.bsp import BSPMaterialAttrib
from .MapHelper import MapHelper
class ModelHelper(MapHelper):
ChangeWith = [
"model"
]
def __init__(self, mapObject):
MapHelper.__init__(self, mapObject)
self.modelRoot... |
#! -*- coding: utf-8 -*-
from datetime import datetime
from main import db, ma
from marshmallow import fields
author_abstracts = db.Table('author_abstracts',
db.Column('author_id', db.Integer,
db.ForeignKey('scopus_authors.id')),
db.Column('abstract_id', db.Integer,
db.ForeignKe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.