seq_id
stringlengths
4
11
text
stringlengths
113
2.92M
repo_name
stringlengths
4
125
sub_path
stringlengths
3
214
file_name
stringlengths
3
160
file_ext
stringclasses
18 values
file_size_in_byte
int64
113
2.92M
program_lang
stringclasses
1 value
lang
stringclasses
93 values
doc_type
stringclasses
1 value
stars
int64
0
179k
dataset
stringclasses
3 values
pt
stringclasses
78 values
5138543046
import Queue class FifoBuffer(object): ''' >>> f = FifoBuffer() >>> f.write('01') >>> f.write('234') >>> f.read(3) '012' >>> f.read(0) '' >>> f.read(2) '34' ''' def __init__(self, empty_cb=None): ''' Make an empty fifo buffer. ''' self._first = '' self._index = 0 self._rest = Queue.Queue() s...
yingted/wai-fi
src/server/fifobuffer.py
fifobuffer.py
py
1,124
python
en
code
1
github-code
13
33266670700
# -*- coding: utf-8 -*- from django.db import models from Users.models import CustomUser class HostGroup(models.Model): name = models.CharField(u'主机组', max_length=128, blank=False, null=False, unique=True) def __unicode__(self): return self.name class Meta: db_table = 'hosts_groups' cla...
Donyintao/SoilServer
assets/models.py
models.py
py
6,207
python
en
code
7
github-code
13
3583833233
import logging from pdf2image import convert_from_bytes from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient, __version__ import io import os import azure.functions as func def pdf_to_png(company_name, document_name, pdf_file_blob): pages = convert_from_bytes(pdf_file_blob.read(), fmt...
eonduplessis/pdf-to-png-function
new_pdf_file/__init__.py
__init__.py
py
2,555
python
en
code
0
github-code
13
2322312191
import logging import boto from boto.ec2 import cloudwatch import time import datetime from services import aws_ec2 from utils import aws_utils from utils.cw_classes import EnvMetric, InstanceMetric def get_start_end_statistics_time(config): end = aws_utils.apply_time_difference(datetime.datetime.now()) delta...
dzzh/IN4392
aws/services/aws_cw.py
aws_cw.py
py
2,024
python
en
code
0
github-code
13
34855241945
import numpy as np from sklearn.datasets import load_iris import matplotlib.pyplot as plt from sklearn.linear_model import LogisticRegression, LinearRegression from sklearn.datasets import make_regression from sklearn.model_selection import train_test_split from matplotlib import cm s=20 X, y = load_iris(return_X_y=Tr...
data-psl/lectures2020
slides/03_machine_learning_models/linear_models.py
linear_models.py
py
2,904
python
en
code
42
github-code
13
7579962732
#!/usr/bin/python3 '''reads stdin line by line and computes metrics:''' import sys def print_metrics(status_codes, total_size): ''' Print the computed metrics ''' print(f'File size: {total_size}') for err_code in sorted(status_codes.keys()): if status_codes[err_code]: print(f...
janymuong/alx-higher_level_programming
0x0B-python-input_output/test_files/101-stats.py
101-stats.py
py
1,177
python
en
code
0
github-code
13
34226927884
import string, praw, OAuth2Util, time, datetime from operator import itemgetter #Variables to Change subs = [ ['korbendallas', ''] #['photoshopbattles', 'battletalk'], #['cfb', ''], #['Yogscast', 'Fonjask'], #['MilitaryGfys', ''], #['conspiracy'...
korbendallas-reddit/WeeklyReport
WeeklyReport.py
WeeklyReport.py
py
15,203
python
en
code
4
github-code
13
71404260497
# pylint: disable=W0621 """Asynchronous Python client for GLIMMR.""" import asyncio from glimmr import Glimmr async def main(): """Show example on controlling your GLIMMR device.""" async with Glimmr("192.168.1.34") as led: await led.update() print(led.system_data) await led.set_mode...
d8ahazard/glimmr-python
examples/control_example.py
control_example.py
py
740
python
en
code
0
github-code
13
37998229868
import TruthD3PDMaker import D3PDMakerCoreComps from D3PDMakerCoreComps.D3PDObject import D3PDObject from D3PDMakerCoreComps.IndexMultiAssociation import IndexMultiAssociation from D3PDMakerCoreComps.IndexAssociation import IndexAssociation from D3PDMakerConfig.D3PDMakerFlags import D3PDMakerFlags from TruthD3PDAnaly...
rushioda/PIXELVALID_athena
athena/PhysicsAnalysis/D3PDMaker/TruthD3PDMaker/python/GenVertexD3PDObject.py
GenVertexD3PDObject.py
py
4,104
python
en
code
1
github-code
13
7722492485
#! /usr/bin/env python import os import sys import getopt import filecmp def strict_comparator(argv): print() print("---------------------------------------------") print("| |") print("| S T R I C T C O M P A R A T O R |") print("| ...
johnportiz14/pyDiffusionFDM
testingPackage/strict_comparator.py
strict_comparator.py
py
1,797
python
en
code
0
github-code
13
40963718152
# # -*- coding: UTF-8 -*- # # """ # # @Time : 2019-09-17 17:40 # # @Author : yanlei # # @FileName: test.py # """ # import sys # import collections # # # def func(s): # count = collections.Counter(s) # stack = [] # visited = collections.defaultdict(bool) # for num in s: # count[num] -= 1 # ...
Yanl05/FullStack
笔试/test.py
test.py
py
2,079
python
en
code
0
github-code
13
983695480
with open('2016/2.txt') as f: input = f.read().strip() first = ''' 123 456 789 '''.strip().split('\n') second = ''' 00100 02340 56789 0ABC0 00D00 '''.strip('\n').split('\n') commands = {'U': [0, -1], 'R': [1, 0], 'D': [0, 1], 'L': [-1, 0]} def getCode(pad, pos): for line in input.split('\n'): for c...
andrewgreenh/advent-of-code
Python/2016/2.py
2.py
py
670
python
en
code
2
github-code
13
73944520659
def find_line(binary_warped): haff= binary_warped[binary_warped.shape[0] // 2:, :] histogram = np.sum(binary_warped[binary_warped.shape[0] // 2:, :], axis=0) #plt.plot(histogram) #plt.imshow(binary_warped) #plt.show() midpoint = np.int(histogram.shape[0] / 2) leftx_base = np.argmax(...
QuyenPham1131998/self-driving-car
Sliding Window.py
Sliding Window.py
py
8,535
python
en
code
0
github-code
13
26260452533
# -*- coding: utf-8 -*- """ Created on Sun Nov 15 20:34:21 2020 @author: vinmue """ import numpy as np from tensorflow.keras.layers import Dense,LSTM,Input,Dropout from tensorflow.keras.models import Sequential from tensorflow.keras.models import load_model, clone_model from tensorflow.keras.optimizers impor...
ViniTheSwan/ReinforcementTrading
parent/Trading/RL/DeepQLearning.py
DeepQLearning.py
py
5,489
python
en
code
1
github-code
13
1083577863
import MapReduce import sys mr = MapReduce.MapReduce() # ============================= # Do not modify above this line def mapper(record): # key: document identifier # value: document contents key = record[1] value = record #words = value.split() mr.emit_intermediate(key, record) def r...
fawadrashid/coursera
assignments/datasci-002/assignment3/join.py
join.py
py
813
python
en
code
0
github-code
13
7183809230
#!/usr/bin/Python3.9 import json import openpyxl import os from JsonToExcel import * import platform base_path = getattr(sys, '_MEIPASS', os.path.dirname( os.path.abspath(__file__))) ACCOUNT_HISTORY_PATH = os.path.join(base_path, 'accountHistory.json') def updateMemory(filePATH): with open(ACCOUNT_HISTORY_...
Gwendalda/BankDocParser
updateAccountHistory.py
updateAccountHistory.py
py
1,115
python
en
code
0
github-code
13
27469795834
def safe_int_input(text): try: data = int(input(text).strip()) return data except: return safe_int_input(text) print("#"*50) print(" Is Leap Year ".center(50,"#")) print("#"*50) print("") current_year = safe_int_input("What year do you want to check? ") if(current_year % 4 == 0): ...
GameMill/100DaysOfPython
day003/05.is_leap_year.py
05.is_leap_year.py
py
553
python
en
code
1
github-code
13
19691607224
# @encoding: utf-8 # @author : wissingcc # @contact : chen867820261@gmail.com # @software: PyCharm # @file : _svm.py # @time : 4/2/2022 下午8:11 import numpy as np from utils.param import init_params from utils.metric.binary import acc_v2 from utils.metric.regression import mse from .kernel_func import RBFKernel, ...
WissingChen/Machine-Learning-Algorithms
model/svm/_svm.py
_svm.py
py
8,658
python
en
code
0
github-code
13
70138178898
######################## IMPORTS ######################## import dataclasses import re from enum import Enum from ecom.datatypes import TypeInfo # ------------------- PyQt Modules -------------------- # from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * from sources.common.widgets.Wid...
EnguerranVidal/PyStrato
sources/databases/sharedtypes.py
sharedtypes.py
py
28,824
python
en
code
3
github-code
13
35935406253
#!/usr/bin/env python2 from __init__ import load_config import sys, os sys.path.append(os.environ['MAGPHASE']) import magphase as mp import libutils as lu import libaudio as la from os import path from argparse import ArgumentParser if __name__ == '__main__': p = ArgumentParser() p.add_argument('-s', '--senls...
KurtAhn/SLCV
src/realign-states.py
realign-states.py
py
1,319
python
en
code
2
github-code
13
26318244592
import random import copy import math import time from tkinter.constants import W import numpy as np def Print(worduko): for i in range(9): for j in range(9): print(worduko[i][j], end=' '), print('\n') def count_conflict(worduko,irow,icol): # print(worduko) # print...
pankajk22/Artificial-Intelligence-Assignments
Assigment-1/WordokuSolver/WordokuSolver_minconflict.py
WordokuSolver_minconflict.py
py
10,903
python
en
code
0
github-code
13
636916815
import os import time from api.batcher_api import post_pop_batch host = os.environ["BATCHER_HOST"] def job(): try: batch = post_pop_batch(host) print(batch) except ConnectionError: print("Exited with network error") exit(1) if __name__ == "__main__": while True: ...
oMalyugina/send_less_than_4_messages_per_day
src/collector.py
collector.py
py
348
python
en
code
0
github-code
13
11540853229
from Bio import Entrez from datetime import datetime Entrez.email = "270992395@qq.com" def name_to_gcfs(term): term=term.replace('(',' ').replace(')',' ') #provide your own mail here term += ' AND (latest[filter] AND all[filter] NOT anomalous[filter] "refseq has annotation"[Properties])' ...
Achuan-2/phage-host
00_data/00_scripts/ncbi_assembly.py
ncbi_assembly.py
py
6,195
python
en
code
0
github-code
13
42208305829
import random a1 = input('nome do aluno um:') a2 = input('o nome do segundo aluno:') a3 = input('nome do terceiro aluno:') a4 = input('nome do quarto aluno:') lista = [a1, a2, a3, a4] escolhido = random.choice(lista) print('O aluno escolhido foi {} '.format(escolhido)) #para o python um lista de objetos...
lightluigui/PyhtonExercises
ex019.py
ex019.py
py
401
python
pt
code
1
github-code
13
13632417103
def divisors(n): a = 1 divisors = [] count = 0 while a <= n: if n%a==0: divisors.append(a) count = count + 1 print(a) a = a + 1 print (count, divisors) b = int(input("Fdfsdfs")) divisors(b)
kieczkowska/codewars
exercise.py
exercise.py
py
279
python
en
code
0
github-code
13
39303089690
import random # Getting a random number def guess_the_no(): magic_no= random.randint(0,100) for i in range(5): guess= int(input('Guess the no: ')) if magic_no == guess: print("You won! Congrats!") elif guess < magic_no: print("Hint! Go UP!!!") ...
harshad317/Python_projects
guess_the_number.py
guess_the_number.py
py
675
python
en
code
0
github-code
13
40366398465
# -*- coding: utf-8 -*- from malha.models import Linha from malha.models import Parada from malha.models import Veiculo from malha.models import ParadaVeiculo from django.conf import settings from celery.task.schedules import crontab from celery.decorators import periodic_task from celery import task import json impor...
dgtechfactory/comfortbus-web
malha/tasks.py
tasks.py
py
5,150
python
en
code
0
github-code
13
34739488549
import numpy as np import datetime def datestr2num(s): return datetime.datetime.strptime(s.decode("ascii"), "%d-%m-%Y").toordinal() # 载入收盘价和日期数据。 dates,closes=np.loadtxt('AAPL.csv', delimiter=',', usecols=(1, 6), converters={1:datestr2num}, unpack=True) # 使用lexsort函数按照收盘价排序: indices = np.lexsort((dates, c...
lucelujiaming/numpyDataProcess
numpyDataProcess/test_lex.py
test_lex.py
py
498
python
en
code
0
github-code
13
21293760269
start = int(input()) end = int(input()) magic_num = int(input()) flag = False counter = 0 for x in range(start, end+1): for y in range(start, end+1): counter += 1 result = x + y if result == magic_num: print(f"Combination N:{counter} ({x} + {y} = {magic_num})") fl...
SJeliazkova/SoftUni
Programming-Basic-Python/Exercises-and-Labs/Nested_Loops_Lab/04. Sum of Two Numbers.py
04. Sum of Two Numbers.py
py
456
python
en
code
0
github-code
13
10453243380
""" 本部分代码实现: 1.Blast结果整理 2.计算三指标权重并进行一致性检验 后续单菌种风险和综合风险于excel中完成 """ import numpy as np import pandas as pd import os from pandas.errors import EmptyDataError def blast_sort(sheet_name): """ 1.读取Blast结果并处理数据,统计数据库中识别到的基因个数 :param sheet_name:CARD:固有耐药;ResFinder:获...
XiaoMaGoGoGo/PRCE-PS
Data_deal_AHP.py
Data_deal_AHP.py
py
3,343
python
zh
code
0
github-code
13
25285160941
import itertools from numpy import linspace from pylinal import VectorFunc from math import cos, sin, pi center = (0, 0, 0) x0, y0, z0 = center r = 1 # radius # theta in [0, pi]; phi in [0, 2*pi] x = lambda theta, phi: x0 + r * sin(theta) * cos(phi) y = lambda theta, phi: y0 + r * sin(theta) * sin(phi) z = lambda t...
PegasusHunter/pylinal
examples/sphere.py
sphere.py
py
535
python
en
code
0
github-code
13
73744203538
import time start_time = time.time() f = open('./names/names_1.txt', 'r') names_1 = f.read().split("\n") # List containing 10000 names f.close() f = open('./names/names_2.txt', 'r') names_2 = f.read().split("\n") # List containing 10000 names f.close() duplicates = [] hash = {} for name1 in names_1: hash[nam...
erin-koen/Sprint-Challenge--Data-Structures-Python
names/names.py
names.py
py
1,187
python
en
code
0
github-code
13
73531013457
''' Numa eleição existem quatro candidatos. Os códigos utilizados são: 1 , 2, 3, 4 - Votos para os respectivos candidatos (você deve montar a tabela ex: 1 - Jose/ 2- João/etc) 5 - Voto Nulo 6 - Voto em Branco Faça um programa que peça o número total de eleitores, receba o voto de cada eleitor em seguida calcule e m...
tspolli/exercises
eleicao.py
eleicao.py
py
2,783
python
pt
code
0
github-code
13
14386249255
# # @lc app=leetcode.cn id=160 lang=python3 # # [160] 相交链表 # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: ...
largomst/leetcode-problem-solution
160.相交链表.2.py
160.相交链表.2.py
py
1,322
python
en
code
0
github-code
13
29316023726
import torch.nn as nn import torch.nn.functional as F import torch import gym import numpy as np """ 损失函数交叉熵杀我,reduction='none' """ class NN(nn.Module): def __init__(self, input_dim=4, output_dim=2): super(NN, self).__init__() self.input_dim = input_dim self.output_dim = ...
Girapath/RL
PolicyGradient_try1.py
PolicyGradient_try1.py
py
4,175
python
en
code
0
github-code
13
38774935199
import pandas as pd def format_accs(fn): df = pd.read_csv( fn, low_memory=False, dtype={ "MISPRIME": str, "VISDATE": str, "DISDATE": str, "DISTIME": str, 'DOCSVC1': str, 'DOCSVC2': str, 'DOCSVC3': str, ...
LewisResearchGroup/LSARP-api
lsarp_api/ahs/formatters.py
formatters.py
py
10,344
python
en
code
0
github-code
13
30610099330
import cv2 import numpy as np import time import matplotlib.pyplot as plt import matplotlib.image as mpimg import random import os, sys cam=cv2.VideoCapture("line.mp4") time.sleep(2) fit_result, l_fit_result, r_fit_result, L_lane,R_lane = [], [], [], [], [] def Collect_points(lines): # reshape [:4] to [:2] ...
yondini/Test
Project/ys_test/YS_line.py
YS_line.py
py
5,204
python
en
code
0
github-code
13
19239598267
''' 사용자가 킥보드를 선택하면, 선택에 따라 user_taste 값을 업데이트함 필요한 정보 - 선택한 킥보드에 대한 (price, kickboard_time, walk_time) - user_taste price, kickboard_time, walk_time 에 대한 각 최댓값 5000, 500, 100 learning_rate(alpha): 0.01 ''' import json import sys def main_(argv): price = int(argv[1]) kickboard_time = int...
kimdo331/KNU-software-design
kickboard-back/python_calc/user_taste_update.py
user_taste_update.py
py
1,244
python
en
code
0
github-code
13
73494016336
''' Напишите программу, которая умеет шифровать и расшифровывать шифр подстановки. Программа принимает на вход две строки одинаковой длины, на первой строке записаны символы исходного алфавита, на второй строке — символы конечного алфавита, после чего идёт строка, которую нужно зашифровать переданным ключом, и ещё одна...
luckychaky/py_stepik
3_7_2.py
3_7_2.py
py
1,838
python
ru
code
1
github-code
13
2886854339
import cv2 # Reading image file img = cv2.imread('lena.png') cv2.imshow('ori.jpg', img) cv2.waitKey(0) print(f'\nImg : {img}\n---------------') # Applying NumPy scalar multiplication on image imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) print(f'\nImgRGB : {imgRGB}\n---------------') fimg = cv2.divide(imgRGB, 0.9)...
LuceRest/pcdp
6th Meet (Monday, November, 1st 2021)/Task/Code/Question 2.py
Question 2.py
py
543
python
en
code
0
github-code
13
74030570579
import inspect def check(fn): def wrapper(*args, **kwargs): sig = inspect.signature(fn) params = sig.parameters # Ordereddict print(params) # values = list(params.values()) # keys = list(params.keys()) # for i, p in enumerate(args): # if valu...
sqsxwj520/python
高阶函数和装饰器/day2/参数注解检查.py
参数注解检查.py
py
1,124
python
en
code
1
github-code
13
2142636246
#!/usr/bin/python # (c) 2018 Jim Hawkins. MIT licensed, see https://opensource.org/licenses/MIT # Part of Blender Driver, see https://github.com/sjjhsjjh/blender-driver """Python module for Blender Driver demonstration application. This code illustrates: - HTTP server in Blender Game Engine as back end. - JavaScr...
sjjhsjjh/blender-driver
applications/httpdemonstration.py
httpdemonstration.py
py
2,820
python
en
code
2
github-code
13
23607768402
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/7/16 21:40 # @Author : xiezheng # @Site : # @File : test_model.py import os import numpy as np import torch from tensorboardX import SummaryWriter from torch import nn from torch import optim import torch.backends.cudnn as cudnn from prefetch_ge...
CN1Ember/feathernet_mine
quan_table/insightface_v2/test_on_lfw/test_model.py
test_model.py
py
5,309
python
en
code
1
github-code
13
10567678486
import os import yaml from dotenv import load_dotenv import schemas as k8s from .utils import encode_base64 def create_configmaps_and_secrets( applications_conf: k8s.ApplicationConfList, shared_conf: k8s.SharedConf, output_configmap_path: str, output_secret_path: str, ): yaml_configmap: str = "...
WujuMaster/K8S-Pydantic
functions/configmaps_secrets.py
configmaps_secrets.py
py
1,518
python
en
code
0
github-code
13
14430833405
''' Complete exercises in section 8.7 (p.75) CODE: word = 'banana' count = 0 for letter in word: if letter == 'a': count = count + 1 print(count) 1) - Encapsulate this code in a function named count, and generalize it so that it accepts the string and the letter as arguments. 2) - Rewrite this function ...
lauramayol/laura_python_core
week_03/labs/06_strings/Exercise_06.py
Exercise_06.py
py
614
python
en
code
0
github-code
13
8690768832
import os import librosa # specify the directory where the music files are located directory = '/path/to/music/files' # loop through all files in the directory for filename in os.listdir(directory): # check if the file is a music file (e.g. .mp3, .wav, etc.) if filename.endswith('.mp3') or filename.endswith('...
aeonborealis/Pangea-Sound-Lab
analyzesound.py
analyzesound.py
py
736
python
en
code
1
github-code
13
21898361986
''' Created on Apr 1, 2012 @author: greg ''' # Django settings for SBServer project. import os def configure(presets): DEBUG = False TEMPLATE_DEBUG = DEBUG ADMINS = ( ('Greg Soltis', 'greg@tinyfunstudios.com'), ) MANAGERS = ADMINS DB_CONFIG_FILE = 'prod_db.cfg' SHARD_CONFIG_FI...
yixu34/PlutoShareServer
src/plutoshare/config/prod.py
prod.py
py
619
python
en
code
1
github-code
13
71084028179
class StrMixin(): def __str__(self): items = self.__dict__.items() return ';'.join([f'{key}={value}' for key, value in items]) def sleep(object): # return object.name + ' is sleeping' try: return object.name + ' is sleeping' except: pass class A...
bobsan42/SoftUni-Learning-42
PythonOOP/oop03inheritance/strMixin.py
strMixin.py
py
713
python
en
code
0
github-code
13
47724177834
# -*- coding: utf-8 -*- import logging if __name__ == '__main__': logging.basicConfig() _log = logging.getLogger(__name__) import unittest import pyxb import sample from pyxb.namespace.builtin import XMLSchema_instance as xsi class TestTrac0202 (unittest.TestCase): def tearDown (self): pyxb.utils.domut...
pabigot/pyxb
tests/trac/trac-0202/check.py
check.py
py
1,553
python
en
code
128
github-code
13
27184056063
#%% from web_scrap_tracker import Tracker class Main(): def __init__(self,): pass def __new__(self,): return self.initiate(self,) def initiate(self,): user_name= str(input('')) hashtag= str(input('')) options= str(input('Escolha uma das opções entre [ 1 /...
nalyking/tracker_scraping
main.py
main.py
py
1,108
python
en
code
0
github-code
13
18232768924
""" Получить сборочные задания в поставке https://openapi.wildberries.ru/#tag/Marketplace-Postavki/paths/~1api~1v3~1supplies~1{supplyId}~1orders/get Возвращает сборочные задания, закреплённые за поставкой. Path Parameters supplyId (REQUIRED) -- string -- Example: WB-GI-1234567 -- ID поставки Response Schema: applic...
BeliaevAndrey/WB_scripts
scripts/marketplace/supplies/market_get_supplies_order_tasks_by_id.py
market_get_supplies_order_tasks_by_id.py
py
2,611
python
ru
code
0
github-code
13
73936577939
import jax import jax.numpy as jnp import flax.linen as nn from flax import struct from jax.nn.initializers import Initializer from typing import Optional from utils import get_2d_sincos_pos_embed, apply_masks, repeat_interleave_batch @struct.dataclass class iJEPAConfig: img_shape: int = (28, 28, 1) patch_s...
wbrenton/nanax
nanax/ijepa/model.py
model.py
py
9,469
python
en
code
0
github-code
13
41471740795
''' We can also pass arguments to the function using args keyword. In this example, we create two process that calculates the cube and squares of numbers and prints all results to the console. ''' import time import multiprocessing def calc_square(numbers): for n in numbers: print('square ' + st...
SumanMore/Multiprocessing-in-python
P3 Multiprocessing demonstrating args.py
P3 Multiprocessing demonstrating args.py
py
1,202
python
en
code
0
github-code
13
25038307711
import speech_recognition as sr r = sr.Recognizer() file = sr.AudioFile('..\AudioFiles\harvard1_5sec.wav') with file as source: audio = r.record(source, duration=4.0) try: recog = r.recognize_wit(audio, key = "6Y4KLO4YTWDQSYQXGONPHAVB3IRSWFRN") print("You said: " + recog) except sr.UnknownValueE...
msalem-twoway/TwoWayVoice
AudioFiles/transcribeFile.py
transcribeFile.py
py
456
python
en
code
0
github-code
13
27212656142
# _*_ coding: utf-8 _*_ """ inst_proxies.py by xianhu """ from ..utilities import ResultProxies class Proxieser(object): """ class of Proxieser, must include function working() """ def working(self) -> ResultProxies: """ working function, must "try-except" and return ResultProxies()...
xianhu/PSpider
spider/instances/inst_proxies.py
inst_proxies.py
py
827
python
en
code
1,804
github-code
13
22444991507
from typing import Callable, List, Optional from .base import BaseEngine, TResult class SingleThreadEngine(BaseEngine): def __init__(self, func: Callable[..., TResult], *args, **kwargs): super().__init__(func) def run( self, args_list: Optional[List[tuple]] = None, ...
minato-ellie/matrix-runner
matrunner/engine/single_thread.py
single_thread.py
py
740
python
en
code
0
github-code
13
70160338577
# coding=utf8 """Continuous analog input task with optional logging (TDMS files). Demo script for acquiring a continuous set of analog values with a National Instruments DAQ device. To test this script, the NI MAX (Measurement & Automation Explorer) has been used to create simulated devices. In this test, a simulat...
itom-project/plugins
niDAQmx/demo/demo_ai_tdms_logging.py
demo_ai_tdms_logging.py
py
5,676
python
en
code
1
github-code
13
10333481807
from fastapi import FastAPI, HTTPException, UploadFile, File from fastapi.responses import StreamingResponse from typing import List, Optional from datetime import datetime import os app = FastAPI() files = [] upload_folder = "uploaded_files" if not os.path.exists(upload_folder): os.makedirs(upload_folder) def...
insane4u00/dropbox-equivalent-service
main.py
main.py
py
2,826
python
en
code
0
github-code
13
74556971538
from dataclasses import fields from tkinter import Widget from django import forms from .models import Employee, Trained class EmployeeForm(forms.ModelForm): class Meta: model = Employee fields = "name", "surname", "card" labels = { "name": "Jméno:", "surname": "Pří...
KvetoslavPrikryl/Prace
Information/forms.py
forms.py
py
2,123
python
cs
code
0
github-code
13
5574317566
from django.urls import path from . import views urlpatterns = [ path('',views.index,name='index'), path('tickets',views.tickets,name='tickets'), path('view_ticket/<int:id>',views.view_ticket,name='view_ticket'), path('change_ticket_status/<int:id>',views.change_ticket_status,name='change_ticket_status...
wkigenyi/helpdesk
support/urls.py
urls.py
py
1,796
python
en
code
0
github-code
13
74562933458
""" _InsertRun_ Oracle implementation of InsertRun """ from WMCore.Database.DBFormatter import DBFormatter class InsertRun(DBFormatter): def execute(self, binds, conn = None, transaction = False): sql = """INSERT INTO run (RUN_ID, HLTKEY) SELECT :RUN, ...
dmwm/T0
src/python/T0/WMBS/Oracle/RunConfig/InsertRun.py
InsertRun.py
py
605
python
en
code
6
github-code
13
30302986
from numpy import ndarray from entities.common.text_position import TextPosition from invoice_processing_utils.common_utils import get_ocr_response, create_position, save_image_with_bounding_boxes class TextReader: __EXTRACTED_TEXTS_OUTPUT_PATH_PREFIX = "7.Extracted texts.png" def __init__(self, invoice: nda...
AdrianC2000/InvoiceScannerApp
text_handler/text_reader.py
text_reader.py
py
971
python
en
code
0
github-code
13
19145776544
import os import subprocess from typing import List, Optional, Sequence def rsync( src: str, dst: str, opt: List[str], host: Optional[str] = None, excludes: Optional[Sequence[str]] = None, filters: Optional[Sequence[str]] = None, mkdirs: bool = False, ): if excludes is None: ex...
ethanluoyc/lxm3
lxm3/xm_cluster/execution/utils.py
utils.py
py
937
python
en
code
6
github-code
13
37965559818
############################################################### # # Job options file # #============================================================== #-------------------------------------------------------------- # ATLAS default Application Configuration options #-----------------------------------------------------...
rushioda/PIXELVALID_athena
athena/LArCalorimeter/LArBadChannelTool/share/BadChannelToolTestOptions.py
BadChannelToolTestOptions.py
py
3,111
python
en
code
1
github-code
13
24281086079
# importing modules import os import sys import re import pandas as pd import csv import numpy as np from matplotlib import pyplot as plt from matplotlib.pyplot import figure from scipy.optimize import curve_fit """ This code takes the total energy obtained from the simulation model and fit an exponential function...
Rajscript/Curvature-Propelled-thin-film
Curvefit_model.py
Curvefit_model.py
py
4,921
python
en
code
0
github-code
13
4043382267
from unittest import TestCase from src.main.part1.rps_evaluator import RPSEvaluator class TestRockPaperScissorsEvaluator(TestCase): def test_get_winning_move(self): move: str = "rock" expected: str = "paper" actual: str = RPSEvaluator.get_winning_move(move) self.assertEqual(expec...
ElBell/Assessment1
src/tests/test_part1/test_rps_evaluator.py
test_rps_evaluator.py
py
758
python
en
code
0
github-code
13
37775277395
from hpp.environments import Buggy robot = Buggy("buggy") robot.setJointBounds ("base_joint_xy", [-5, 16, -4.5, 4.5]) from hpp.corbaserver import ProblemSolver ps = ProblemSolver (robot) from hpp.gepetto import ViewerFactory gui = ViewerFactory (ps) gui.loadObstacleModel ('hpp_environments', "scene", "scene") q_in...
heidydallard/hpp-environments
examples/buggy.py
buggy.py
py
666
python
en
code
0
github-code
13
28203926425
from StringIO import StringIO import gzip def parse_url_params(url): data = {} for params in url.split('&'): el = params.split('=') if el is not None and len(el)>1: data[el[0]] = el[1] return data def convert_to_utf8_str(arg): # written by Michael Norton (http://docondev.blogspot.com/) if isinstance(a...
scalaview/pyPixiv
utils.py
utils.py
py
668
python
en
code
0
github-code
13
7497847791
from django.urls import path from django.shortcuts import redirect from django.views.decorators.cache import cache_page from .views import * urlpatterns = [ path('', cache_page(60)(PostList.as_view()), name='news'), path('create/', PostCreate.as_view(), name='post_create'), path('search/', Post...
PavelUmanskiy/NewsPaper
NewsPaper/news/urls.py
urls.py
py
966
python
en
code
0
github-code
13
17919155465
# Decode A Web Page # This is the first 4-chili exercise of this blog! We’ll see what people think, and decide whether or not to continue with 4-chili exercises in the future. # Exercise 17 (and Solution) # Use the BeautifulSoup and requests Python packages to print out a list of all the article titles on the ...
alexjulian1227/python-learning
python-exercises/exercise-17/main.py
main.py
py
675
python
en
code
0
github-code
13
40885468935
"""(S)HeteroFL""" import os, argparse, time import numpy as np import wandb from tqdm import tqdm import torch from torch import nn, optim from torch.nn.modules.batchnorm import _NormBase # federated from federated.learning import train_slimmable, test, refresh_bn # utils from utils.utils import set_seed, AverageMeter,...
illidanlab/SplitMix
fed_hfl.py
fed_hfl.py
py
15,257
python
en
code
29
github-code
13
4682703613
__struct_classes = {} from sydpy.types._type_base import TypeBase def Enum(*args): if args not in __struct_classes: __struct_classes[args] = type('enum', (enum,), dict(vals=args)) return __struct_classes[args] class enum(TypeBase): vals = None def __init__(self, val=None): ...
bogdanvuk/sydpy
sydpy/types/enum.py
enum.py
py
1,730
python
en
code
12
github-code
13
13670900243
DOCUMENTATION = r""" --- module: s3_logging version_added: 1.0.0 short_description: Manage logging facility of an s3 bucket in AWS description: - Manage logging facility of an s3 bucket in AWS author: - Rob White (@wimnat) options: name: description: - "Name of the s3 bucket." required: true typ...
ansible-collections/community.aws
plugins/modules/s3_logging.py
s3_logging.py
py
6,782
python
en
code
174
github-code
13
3957146057
# Desafio 44 # Elabore um programa que calcule o valor a ser pago por um produto, considerando o seu preço normal e condição de pagamento: #  Avista dinheiro/cheque: 10% de desconto #  Avista no cartão: 5% de desconto #  Em até 2x no cartão: Preço normal #  3x ou mais no cartão: 20% de juros preço = float(input('T...
mozart-jr/Python
Desafio 41 ao 50/Desafio 44.py
Desafio 44.py
py
1,050
python
pt
code
0
github-code
13
7631301572
# G[2] 메모리 30840 KB 시간 1708 ms import sys MOVE = [(-1, 0), (1, 0), (0, -1), (0, 1)] # 위 아 왼 오 N, M, K = map(int, sys.stdin.readline().split()) space = [[[0, 0] for _ in range(N)] for _ in range(N)] shark = {idx: [-1, -1, -1] for idx in range(1, M+1)} shark_priority = [[]] for i in range(N): for j, val in enumer...
nuuuri/algorithm
구현/BOJ_19237.py
BOJ_19237.py
py
2,133
python
en
code
0
github-code
13
35295670258
a = int(input()) b = int(input()) c = int(input()) list_ = [a, b, c] list_.sort(reverse=True) ans = [0, 0, 0] for i in range(len(list_)): if list_[i]==a: ans[0] = i+1 elif list_[i]==b: ans[1] = i+1 else: ans[2] = i+1 for i in ans: print(i)
nozomuorita/atcoder-workspace-python
abc/abc018/a.py
a.py
py
290
python
en
code
0
github-code
13
34785457958
from rct229.rulesets.ashrae9012019.data.schema_enums import schema_enums from rct229.utils.assertions import getattr_ from rct229.utils.jsonpath_utils import find_all, find_one from rct229.utils.utility_functions import ( find_exactly_one_child_loop, find_exactly_one_fluid_loop, find_exactly_one_hvac_system...
pnnl/ruleset-checking-tool
rct229/rulesets/ashrae9012019/ruleset_functions/baseline_systems/baseline_hvac_sub_functions/is_hvac_sys_fluid_loop_attached_to_chiller.py
is_hvac_sys_fluid_loop_attached_to_chiller.py
py
2,200
python
en
code
6
github-code
13
35320235448
#!/usr/bin/python #coding:utf-8 ''' name : testPlot.py author : ykita date : Sat Feb 13 12:27:58 JST 2016 memo : ''' import os, os.path import sys import sqlite3 import ROOT from ROOT import * hOp = TH1D('hOp','',100,0,50000) hHi = TH1D('hHi','',100,0,50000) hLo = TH1D('hLo','',100,0,50000) hCl = TH1D('hCl',''...
ykita0000/20160212_nikkei225
py/testPlot.py
testPlot.py
py
725
python
en
code
0
github-code
13
25967576192
import os from pathlib import Path import astropy.constants as const import h5py import numpy as np from tqdm import tqdm from pyvisgen.fits.data import fits_data from pyvisgen.gridding.alt_gridder import ms2dirty_python_fast from pyvisgen.utils.config import read_data_set_conf from pyvisgen.utils.data import load_bu...
radionets-project/pyvisgen
pyvisgen/gridding/gridder.py
gridder.py
py
10,426
python
en
code
2
github-code
13
31228855737
from django.contrib.auth import get_user_model from django.core.validators import MinValueValidator from django.db import models User = get_user_model() class Ingredients(models.Model): name = models.CharField( max_length=200, verbose_name='Название' ) measurement_unit = models.CharField( ...
palmage/foodgram-project-react
backend/recipes/models.py
models.py
py
4,917
python
en
code
0
github-code
13
27812813973
# 0. 导入需要的包和模块 from PyQt5.Qt import * class Window(QWidget): def __init__(self): super().__init__() self.setWindowTitle("交互状态的学习") self.resize(500, 500) self.setup_ui() def setup_ui(self): # 添加三个子控件 label = QLabel(self) label.setText('标签') labe...
zhangzhaozhe/test-demo
04-QWidget-交互状态的案例.py
04-QWidget-交互状态的案例.py
py
1,350
python
zh
code
0
github-code
13
7631363442
# G[3] PyPy3 메모리 115364 KB 시간 192 ms / Python3 메모리 30840 KB 시간 600 ms import sys input = sys.stdin.readline dice = [[0, 2, 0], [4, 1, 3], [0, 5, 0], [0, 6, 0]] MOVE = [(0, 1), (1, 0), (0, -1), (-1, 0)] x, y, d = 0, 0, 0 ans = 0 def rollTheDice(d): if d == 0: temp = dice[1][2] dice[1] = [dice[3]...
nuuuri/algorithm
그래프/BOJ_23288.py
BOJ_23288.py
py
1,732
python
en
code
0
github-code
13
6337497562
''' User Story 06 Divorce before death ''' from datetime import datetime def indivDeaths(input, newFam): fams = [] indivs = [] for i, b in zip(input, newFam): if i[2] != "NA": fams = [] fams.append(b[0]) fams.append(i[0]) ...
chloequinto/SSW_555_Project
package/userStories/us06.py
us06.py
py
1,572
python
en
code
0
github-code
13
3086645915
""" WebConfiguration -- Singleton for holding global configuration This file defines the global configuration and makes it accessible as a singleton variable. Any changes made to an instance of the configuration are propagated to all other instances. A default configuration is loaded, if not specified otherwise. Aut...
UKPLab/CARE_broker
broker/config/WebConfiguration.py
WebConfiguration.py
py
4,648
python
en
code
2
github-code
13
72220141778
import os import numpy as np from tempfile import TemporaryFile BASE_DIR = '.' GLOVE_DIR = BASE_DIR + '/glove.840B/' embeddings_index = {} f = open(os.path.join(GLOVE_DIR, 'glove.840B.300d.txt')) for line in f: values = line.split() word = values[0] coefs = np.asarray(values[1:], dtype='float32') emb...
jin1205/CMPT741-sentiment-analysis
wordembedding.py
wordembedding.py
py
803
python
en
code
0
github-code
13
10508409714
import datetime import json import os from os import path import random import sys import time import itertools import matplotlib as mpl from matplotlib import pyplot import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np from numpy import linalg as LA import pandas as pd from sc...
tflaherty/tflaherty3-CS-7641-Assignment3
UnsupervisedLearningAndDimensionalityReduction.py
UnsupervisedLearningAndDimensionalityReduction.py
py
92,303
python
en
code
0
github-code
13
17080206334
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse from alipay.aop.api.domain.SchoolSimpleInfo import SchoolSimpleInfo from alipay.aop.api.domain.SchoolBaseInfo import SchoolBaseInfo class AlipayCommerceEducateCampusInstitutionsQueryResponse(Al...
alipay/alipay-sdk-python-all
alipay/aop/api/response/AlipayCommerceEducateCampusInstitutionsQueryResponse.py
AlipayCommerceEducateCampusInstitutionsQueryResponse.py
py
1,679
python
en
code
241
github-code
13
1748174730
import decimal import json import logging import urllib.parse as urlparse from requests import auth, Session, codes from requests.adapters import HTTPAdapter from requests.exceptions import ConnectionError, Timeout, RequestException USER_AGENT = "AuthServiceProxy/0.1" HTTP_TIMEOUT = 30 MAX_RETRIES = 3 log = loggin...
normoes/python-monerorpc
monerorpc/authproxy.py
authproxy.py
py
7,172
python
en
code
7
github-code
13
21604474206
""" Do the raffle! TODO add docs for how this mess actually works and maybe even refactor """ import random import re from collections import defaultdict import pandas as pd # Name of the column in raffle.csv whose values we will match with tickets.csv # It doesn't need to be emails-- can be any string pretty much ...
calico-team/raffle-sp23-public
raffle.py
raffle.py
py
5,549
python
en
code
3
github-code
13
21933654976
from librosa import cqt, convert import numpy as np from common import FeatureModule class MCQT(FeatureModule): def __init__(self, sample_rate=22050, hop_size=441, bins_per_octave=96, n_bins=558, fmin=196, average=True, keep_range=[], log=True, quartile=[]): self.sample_rate = sample_rat...
mjhydri/Singing-Vocal-Beat-Tracking
scripts/melodic_cqt.py
melodic_cqt.py
py
2,577
python
en
code
21
github-code
13
72856916498
# -*- coding: utf-8 -*- from app import create_app, db def before_feature(context, feature): context.app = create_app('test') context.client = context.app.test_client() context.ctx = context.app.test_request_context() context.ctx.push() db.create_all() def after_feature(context, feature): db...
fgimian/flaskage
flaskage/templates/bdd/features/environment.py
environment.py
py
378
python
en
code
37
github-code
13
38053332023
import cv2 import numpy as np from win32api import GetSystemMetrics import math as m def getV(vec): vecV = [] vecSup = vec.copy() vecSup.sort(key=lambda x:x[0]) vecV = vecSup[:15] vecV.sort(key=lambda x:x[1]) return vecV def getH(vec): vecH = [] vecSup = vec.copy() vecSup.sort(key=lambda x:x[1])#ordena de ac...
Davibeltrao/ICV
tp1.py
tp1.py
py
6,399
python
en
code
0
github-code
13
15603143472
import nibabel as nib import numpy as np import tensorflow as tf from termcolor import colored def f1(y_true, y_pred): return 1 def save_liver_segmentation(liver_image_path, model_path): print("Application started! Loading data...") min_img_bound = -1000 max_img_bound = 3000 img = ni...
MaksOpp/tomography-image-segmentation
src/liver_segmentation_script_final.py
liver_segmentation_script_final.py
py
1,858
python
en
code
1
github-code
13
38927684056
from setting.models import * from django.db import models from company.models import Branch from user.models import Employee from django.core import serializers import json class Customer(models.Model): identification_number = models.IntegerField() dv = models.IntegerField(default = 0) name = models.CharField(max_l...
cdavid58/api_new_invoice
customer/models.py
models.py
py
4,728
python
en
code
0
github-code
13
74387209618
import os import sys import numpy as np import scipy.sparse as sp import trimesh import cv2 def sparse_to_tuple(sparse_mx): """Convert sparse matrix to tuple representation.""" def to_tuple(mx): if not sp.isspmatrix_coo(mx): mx = mx.tocoo() coords = np.vstack((mx.row, mx.col)).trans...
Gorilla-Lab-SCUT/SkeletonBridgeRecon
Mesh_refinement/deformation/utils.py
utils.py
py
2,602
python
en
code
76
github-code
13
15736352273
import seaborn as sns import matplotlib.pyplot as plt import pandas from scipy.stats import ttest_1samp, wilcoxon def plot_correlation(variable1,variable2, name1,name2,rValue,year): df = pandas.DataFrame({'x':variable1,'y':variable2}) # plt.figure() sns.lmplot(x="x",y="y",data=df,fit_reg=True,height = 6) ...
jinchen1036/VisualizationProject
Functions.py
Functions.py
py
1,612
python
en
code
0
github-code
13
31466382632
# Write a program to find the node at which the intersection of two singly linked lists begins. # For example, the following two linked lists: # A: a1 → a2 # ↘ # c1 → c2 → c3 # ↗ # B: b1 → b2 → b3 # begin to intersect at node c1. # Notes: # I...
han8909227/leetcode
linked_list/intersection_two_ll_lc160.py
intersection_two_ll_lc160.py
py
2,111
python
en
code
3
github-code
13
29314449881
import numpy as np from numpy.random import default_rng class GMM: def __init__(self, num_components, dimensionality, **kwargs): """ kwargs: can supply the regularizer for the determinant of the covariance matrix """ self.num_components=num_components self.dimensionality=dimensionality mixing_coeffs=np...
rVSaxena/gmm
gmm.py
gmm.py
py
2,392
python
en
code
0
github-code
13
32734155424
import random import json import csv def save_game_data(data): with open('data.json', 'w') as file: json.dump(data, file) def load_game_data(): try: with open('data.json', 'r') as file: data = json.load(file) except FileNotFoundError: data = {} return ...
Kobrar0112/python14112023
Igra.py
Igra.py
py
3,787
python
ru
code
0
github-code
13
5151955279
# This program uses the Turtle module to draw repeating squares # 17 October 2019 # CTI-110 P4T1a - Shapes # John Fueyo # Import turtle # Outer loop "count" iterates 100 times # Inner loop "square" makes a square # After "square" exits, complete outer loop "count" # Store turtle (x-cord - 3). in var. "x" to move t...
Jfueyo/cti110
p4t1a_fueyo.py
p4t1a_fueyo.py
py
1,049
python
en
code
0
github-code
13