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
23934877636
from django_cron import CronJobBase, Schedule from django.db.models import Q from .models import Device class UpdateDeviceStatuses(CronJobBase): devices = [] RUN_EVERY_MINS = 1 schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'ARM.update_device_statuses' def do(self): devices =...
tayotoki/arm-kip
ARM/cron.py
cron.py
py
684
python
en
code
1
github-code
1
18805300498
##################################################### Import system libraries ###################################################### import matplotlib as mpl mpl.rcdefaults() mpl.rcParams.update(mpl.rc_params_from_file('meine-matplotlibrc')) import matplotlib.pyplot as plt import numpy as np import scipy.constants as c...
Jean1995/Praktikum
V501/PythonSkript.py
PythonSkript.py
py
21,644
python
de
code
1
github-code
1
1829982870
import ROOT ROOT.gStyle.SetOptStat(1) ROOT.gStyle.SetOptFit(1) ROOT.gROOT.SetBatch(ROOT.kTRUE) ROOT.gStyle.SetLabelFont(42,"xyz") ROOT.gStyle.SetLabelSize(0.05,"xyz") #ROOT.gStyle.SetTitleFont(42) ROOT.gStyle.SetTitleFont(42,"xyz") ROOT.gStyle.SetTitleFont(42,"t") #ROOT.gStyle.SetTitleSize(0.05) ROOT.gStyle.SetTitleSiz...
kdipetri/BNL_AC_LGADs
util/time_res.py
time_res.py
py
16,575
python
en
code
0
github-code
1
71131652193
import sys N = int(sys.stdin.readline().strip()) dp = [0 for _ in range(N + 2)] # dp[i] 배열은 i의 길이를 갖는 이친수의 개수 dp[1] = 1 # 초기값 세팅 dp[2] = 1 # 초기값 세팅 # N = 1 -> 1 # N = 2 -> 10 # N = 3 -> 100, 101 (앞에 10은 고정) # N = 4 -> 1010(N이 2인 경우의 2자리를 가져옴), 1000(N이 3인 경우의 뒤에서 2자리를 가져옴), 1001(N이 3인 경우의 뒤에서 2자리를 가져옴) (앞에 10은 고정) ...
cookie-god/algorithm
baekjoon/dynamic-programming/2193.py
2193.py
py
616
python
ko
code
0
github-code
1
74825614112
""" HikerDataToCSV.py Aggregates the data contained in the 'ValidatedHikers' directory. This script reads in every hiker in the directory and modifies each data structure in memory by adding and calculating the fields required for hiker distance prediciton. The updated data structures are then written in CSV form a...
campellcl/APMAT
Program/DataManipulation/HikerDataToCSV.py
HikerDataToCSV.py
py
14,187
python
en
code
0
github-code
1
20831591596
from flask import Flask, render_template, url_for, jsonify, request from http import HTTPStatus from jinja2 import Template import pymysql.cursors import json import os app = Flask(__name__) def get_connection(): connection = pymysql.connect( host='localhost', user=os.environ['dbuser'], ...
pdmarc7/analytica
app.py
app.py
py
3,312
python
en
code
0
github-code
1
12733435188
class RequiredInput(object): """ This class represents required input that is needed from i.e. the user. """ def __init__(self, name, required_fields, additional_data={}, error_text=None): """ :param name: the reference name of the input. :type name: str :param required_...
devos50/ipv8-android-app
app/src/main/jni/lib/python2.7/site-packages/internetofmoney/RequiredInput.py
RequiredInput.py
py
1,422
python
en
code
0
github-code
1
33493058365
import logging import numpy as np from sklearn.metrics import pairwise_distances class PointCorresponder(): def point_correspond_3d_to_2d(self, projected_pts, visible_indces, keypoints, top_closest=1): """ Args: projected_pts: visible_indces: keypoints: ...
Mikhail-Klochkov/face3dmorphablemodel
morphable_model/point_correspond.py
point_correspond.py
py
1,436
python
en
code
1
github-code
1
15850480850
def rope_bridge(part = 1): if part == 1: tail = (0, 0) stepped = {tail} if part == 2: tail = [(0, 0) for x in range(10)] stepped = {tail[-1]} return stepped_maker(part, stepped, tail) def stepped_maker(part, stepped, tail, head = (0, 0)): steps = ((y, int(x)) f...
HungryVovka/Advent-of-Code
2022/Day 9 Rope Bridge/Day 9 Rope Bridge.py
Day 9 Rope Bridge.py
py
1,574
python
en
code
0
github-code
1
30005077930
import torch from torch.nn import Module, Linear, LayerNorm class LSTMCellLayerNorm(Module): """ A lstm cell that layer norms the cell state https://github.com/seba-1511/lstms.pth/blob/master/lstms/lstm.py for reference. Original License Apache 2.0 """ def __init__(self, input_size, hidden_si...
heronsystems/adeptRL
adept/modules/sequence.py
sequence.py
py
1,770
python
en
code
202
github-code
1
28949575640
import json import os from bs4 import BeautifulSoup import requests import time from typing import List,Dict import socket def extract_urls(path_to_urls_json): with open(path_to_urls_json) as f : json_list = json.load(f) return json_list def download_url(url:str): try: x = reques...
fwallyn1/SimpleIndex
index/utils.py
utils.py
py
1,263
python
en
code
0
github-code
1
39745820789
import nose import subprocess import os _epochdir = os.path.dirname(os.path.abspath(__file__)) _epochdir = os.path.join(_epochdir, '..') _subdir = None def setcwd(relative=None): ''' resets the current working directiory to the path of this file. ''' os.chdir(_epochdir) os.chdir(_subdir) ...
Warwick-Plasma/epoch
scripts/run-tests.py
run-tests.py
py
2,754
python
en
code
143
github-code
1
31226951252
# Flask utils from flask import Flask, request, render_template from werkzeug.utils import secure_filename import os from model_file import * from whale_title import * model.load_state_dict(torch.load('./model/VGG-whaleFin_ImageClassification_model.pt',map_location ='cpu')) model.eval() # Define a flask app app = Fla...
sclee0724/Whale_Fin_Image_Classification_Project
app.py
app.py
py
1,852
python
en
code
1
github-code
1
12657959262
"""Dataset Handler.""" import os import torch from datasets import cifar_handler from datasets import tinyimagenet_handler from datasets import imagenet2012_handler from datasets import stl10_handler import numpy as np class DataHandler: """Handler for datasets.""" def __init__( self, dataset_name, ...
ajaysub110/satbench
cnet/datasets/dataset_handler.py
dataset_handler.py
py
7,854
python
en
code
0
github-code
1
16116080693
import sys import pickle predictions = open('predictions.txt','r') hugeDict = {} businesses = open('businessIDs.txt','r') userDict = {} for restaurantHash in businesses: userDict[restaurantHash[:-1]] = float(predictions.readline()[:-1]) pickle.dump(userDict,open("predictionary.p","wb"))
singular-value/YelpGroupRecommendations
makeSuperUserPredictionary.py
makeSuperUserPredictionary.py
py
302
python
en
code
1
github-code
1
39164509106
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLabel import sys from PyQt5.QtGui import QIcon, QFont from PyQt5.QtCore import QRect, QSize class Window(QMainWindow): def __init__(self): super().__init__() self.create_ui() def create_ui(self): self.setWindowTitle...
BjornChrisnach/Pinterest_course_GUI
Mywindow.py/Mywindow.py
Mywindow.py
py
1,315
python
en
code
0
github-code
1
2715999025
# start # find highly selected genes in one species across populations and donors import os import glob import copy from Bio import SeqIO from Bio.Seq import Seq import argparse ############################################ Arguments and declarations ############################################## parser = argparse.Argum...
caozhichongchong/snp_finder
snp_finder/scripts/oldscripts/parallel_evolution.py
parallel_evolution.py
py
24,817
python
en
code
2
github-code
1
9528154926
from PyQt5.QtWidgets import * from PyQt5 import uic from crawler.web_crawler import WebCrawler from crawler.popup_window import PopupWindowClass from crawler.qthread_worker import QThreadWorker from bs4 import BeautifulSoup from PyQt5.QtCore import QCoreApplication, QMutex, QThread, QWaitCondition, pyqtSignal import...
chunppo/WebCrawler
main.py
main.py
py
3,166
python
en
code
0
github-code
1
34953688010
# -*- coding: utf-8 -*- """Common test case for all message based resources. """ import ctypes import gc import logging import time from types import ModuleType from typing import Optional import pytest from pyvisa import constants, errors from pyvisa.constants import EventType, ResourceAttribute from pyvisa.resourc...
pyvisa/pyvisa
pyvisa/testsuite/keysight_assisted_tests/messagebased_resource_utils.py
messagebased_resource_utils.py
py
34,742
python
en
code
721
github-code
1
24603531031
import pandas as pd if __name__ == '__main__': # 读取文件 参数1 文件的位置 可以是绝对或者相对路径 \表示转移 # 附加,计算这行代码需要的时间 df = pd.read_excel("./Online Retail.xlsx") # 清洗数据 找到需要的数据,移除不需要的数据 # 清除带空值的行 how的值 any表示表示清除带空值的行, all表示所有是空值的情况下,再清除 df.dropna(how='any') df['InvoiceDate'] = pd.to_datetime...
miaozilong/ruantong-xinagjianguniversity
上课演示/2023-07-01/下午/35.py
35.py
py
1,218
python
zh
code
0
github-code
1
15162365309
import numpy as np import pygplates from scipy import spatial def marsaglias_method(N): ## Marsaglia's method dim = 3 norm = np.random.normal normal_deviates = norm(size=(dim, N)) radius = np.sqrt((normal_deviates**2).sum(axis=0)) points = normal_deviates/radius return points ...
atom-model/ATOM
reconstruction/sphere_tools.py
sphere_tools.py
py
2,408
python
en
code
13
github-code
1
25505264845
from telemetry.page import page as page_module from telemetry.page import shared_page_state class KeyMobileSitesPage(page_module.Page): def __init__(self, url, page_set, name='', labels=None): super(KeyMobileSitesPage, self).__init__( url=url, page_set=page_set, name=name, shared_page_state_cla...
hanpfei/chromium-net
tools/perf/page_sets/key_mobile_sites_pages.py
key_mobile_sites_pages.py
py
7,467
python
en
code
289
github-code
1
10652448500
import socket # Server's address HOST = "localhost" PORT = 8081 c_sock = socket.socket() c_sock.connect((HOST, PORT)) c_sock.sendall(b"Hello, world!") response = c_sock.recv(1024) print(response) c_sock.close()
rahulgrover99/SocketProgramming
client.py
client.py
py
214
python
en
code
0
github-code
1
40007208098
# coding=utf-8 """ Time : 2016/7/29 16:18 Author : Jia Jielin Company: fhhy.co File : fhConstant.py Description: """ # system module # third party module # own module # 任务状态 STATUS_NOTTRADED = '未成交' # STATUS_PARTTRADED = '部分成交' STATUS_ALLTRADED = '已成交' STATUS_CANCELLED = '已撤销' # STATUS_PARTCANCELLED = '部分成交并撤销' ...
jiajielin/FHTRADER
fhConstant.py
fhConstant.py
py
2,392
python
en
code
0
github-code
1
26426713407
#어른상어 2시 from collections import defaultdict,deque global n,m,k,g,shark,sdir,smell # INITIALIZE shark = defaultdict(list) dir = [(-1,0), (1,0), (0,-1), (0,1)] # 위, 아래, 왼쪽, 오른쪽 n,m,k = map(int ,input().split()) gg = [[*map(int,input().split())] for _ in range(n)] g = [[[0,0] for _ in range(n)] for _ in range(n)] init...
dohui-son/Python-Algorithms
simulation_samsung/b19237_어른상어.py
b19237_어른상어.py
py
2,283
python
en
code
0
github-code
1
185739374
import pyarrow as pa from petastorm.local_disk_cache import LocalDiskCache class LocalDiskArrowTableCache(LocalDiskCache): """A disk cache implementation """ def __init__(self, *args, **kwargs): super(LocalDiskArrowTableCache, self).__init__(*args, **kwargs) # Workaround for https://issues.ap...
jem0101/BigSwag-SQA2022-AUBURN
TestOrchestrator4ML-main/resources/Data/supervised/GITLAB_REPOS/chaitanya_kaul@petastorm/petastorm/local_disk_arrow_table_cache.py
local_disk_arrow_table_cache.py
py
1,022
python
en
code
2
github-code
1
14069614681
from functools import lru_cache lines = [] best = 0 for line in open('input.txt'): line = line.strip() lines.append(line) M = len(lines) N = max(len(line) for line in lines) prev = {None} curr = set() def get(i, j): if i < 0 or i >= len(lines): return '.', 0 if j < 0 or j >= len(lines[i]): return '...
funkyt/AoC
2020/11/p11.py
p11.py
py
1,343
python
en
code
1
github-code
1
34577004526
#!/usr/bin/python import sys, os, argparse import asyncio import traceback import rulebook from .util import * from .libnetconf import NetworkState import rulebook.runtime import logging logger = logging.getLogger(__name__) logging.basicConfig(level=logging.DEBUG) try: from IPython.kernel.zmq.kernelapp import I...
regnarg/networksecretary
networksecretary/daemon.py
daemon.py
py
6,292
python
en
code
1
github-code
1
17928255590
"""empty message Revision ID: b2a4b30fdece Revises: 0a6d3d1508a5 Create Date: 2021-03-04 18:52:11.795274 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'b2a4b30fdece' down_revision = '0a6d3d1508a5' branch_labels = None depends_on = None def upgrade(): # ...
amankumar4real/ticketing
backend/migrations/versions/b2a4b30fdece_.py
b2a4b30fdece_.py
py
1,526
python
en
code
0
github-code
1
1531002913
import time from metadrive.component.map.pg_map import PGMap from metadrive.engine.engine_utils import initialize_engine, close_engine from metadrive.envs import MetaDriveEnv try: from reprlib import repr except ImportError: pass from metadrive.tests.test_functionality.test_memory_leak_engine import process_...
metadriverse/metadrive
metadrive/tests/test_functionality/test_memory_leak_pg_map.py
test_memory_leak_pg_map.py
py
1,913
python
en
code
471
github-code
1
28418502484
#link - https://www.hackerrank.com/challenges/iterables-and-iterators/problem?isFullScreen=true from itertools import combinations n = int(input()) arr = [x for x in input().split()] k = int(input()) combi = list(combinations(arr, k)) total = len(combi) count = [1 for each in combi if 'a' in each] pri...
prince001996/Hackerrank
Python/iterables_and_iterators.py
iterables_and_iterators.py
py
340
python
en
code
0
github-code
1
7790807669
import csv import string import chess import chess.pgn import random import json from random import randint import pandas as pd # Flask and WSGI import flask from flask import Flask, Blueprint, jsonify from flask import request from flask_cors import CORS, cross_origin app = Flask(__name__) CORS(app) ...
kapilpownikar/QCRI-Chess-Project
backend.py
backend.py
py
3,095
python
en
code
0
github-code
1
39904934377
from db.base import Base, engine, session from db.tables import Sport, Championship, Match, Duplicate class Receive: """Класс получение данных из бд""" def __init__(self): self.session = session() def get_all_ids_match(self, external_match_id): """получение всех id матча (с дубликатами)"...
AlexUndead/parser_sport_data
db/receive.py
receive.py
py
1,166
python
en
code
0
github-code
1
73508896035
#!/usr/bin/env python # +=========================================+ # | @author Cole Dapprich, 2018-2020 (AMDG) | # +=========================================+ from sys import argv, exit import csv import re # 0 = wr, 1 = rb, 2 = te, 3 = qb, 4 = dst/def, 5 = k TODO: make order dynamic positionalRankings = [ [], [], ...
cdsoftw/fantasy-draft
src/draft.py
draft.py
py
5,146
python
en
code
0
github-code
1
72462326114
import unittest import matrix import random import numpy as np class TestMatrix(unittest.TestCase): def test_initialize(self): mat_a = matrix.random(2, 3) mat_b = matrix.ones(2, 3) mat_c = matrix.zeros(2, 3) assert mat_a.colunm == mat_b.colunm == mat_c.colunm == 3 assert...
BrightXiaoHan/CMakeTutorial
PythonExtention/test_matrix.py
test_matrix.py
py
1,521
python
en
code
1,211
github-code
1
26827467096
import os import pandas as pd import numpy as np from numpy.linalg import inv import matplotlib.pyplot as plt # root mean square error metric between predictions and the ground truth def rmse(pred, true): assert pred.shape == true.shape n, = true.shape return np.sqrt(np.sum((pred - true) ** 2) / n) def pr...
JianhuanZeng/Machine-Learning-NLP
NLP-Lab2-MovieRecomendation/FM.py
FM.py
py
4,720
python
en
code
0
github-code
1
12921162394
# -*- coding: utf-8 -*- """ Created on Wed Feb 13 20:23:59 2019 @author: de-sinnett """ # Import random, operator and plotting modules import random import operator import matplotlib.pyplot # Create a new empty list agents = [] # Set up variables to start at random coordinates in a 100x100 grid (agent 1) agents.appe...
DanielleSinnett/AgentBasedModellingTest
model2.py
model2.py
py
1,432
python
en
code
0
github-code
1
38701737553
''' A simple python calculation question generator usg: python calculator.py -d "+,-" -c 3 -l 200 -t 30 usg: python calculator.py --op_type="+,-" --op_count=3 --limit=20 --total=30 ''' import sys, getopt, random def auto_cal_generator(limit=100, op_count=1, op_type=["+"], total=100): print("Here are today's %d wor...
jessychen1984/MiniProj
src/misc/calculator/calculator.py
calculator.py
py
1,930
python
en
code
0
github-code
1
30129633086
number_of_soldiers = int(input()) a = list(map(int, input().split())) # number of weapons x1 = 0 x2 = 0 for i in range(0, len(a)): if a[i] % 2 == 0: x1 += 1 else: x2 += 1 if x1 > x2: print("READY FOR BATTLE") else: print("NOT READY")
AkankshaRakeshJain/CodeChef
AMR15A_Mahasena.py
AMR15A_Mahasena.py
py
280
python
en
code
0
github-code
1
22025109541
import boto3 import json import logging import os import cv2 import ast from botocore.exceptions import ClientError s3 = boto3.client('s3') s3inputbucket = 'inputvideobucket2022' sourcefile = 'source.mp4' sourceoutputfile = 'source.mp4' labelidentifier = 'Human' labelconfidence = 80 jsonsource = '0data.json' def S3Ex...
sidraj2002/RekognitionSid
HumanVideoDetect/FrameExtracter.py
FrameExtracter.py
py
3,090
python
en
code
0
github-code
1
34395246788
class node: key = "" value = 0 def __init__(self, key, value): self.key = key self.value = value def set(self, value): self.value = value def output(self): print("'" + self.key + "' : '" + self.value + "'") class hashTable: # bucket is the container for all...
swapnil0/Python
HashTableImpl/Hashtable/HashTable.py
HashTable.py
py
3,634
python
en
code
0
github-code
1
26067512419
import importlib.resources from pathlib import Path import numpy as np import scipy.linalg as sla from hivpy.sex_behaviour_data import SexualBehaviourData def test_probability_loading(): # Load example file data_path = Path(__file__).parent / "test_data" / "sbd_testing.yaml" SBD = SexualBehaviourData(da...
UCL/hivpy
src/tests/test_sex_behaviour_data.py
test_sex_behaviour_data.py
py
2,640
python
en
code
0
github-code
1
34526289955
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/2/28 3:56 PM # @Author : huxiaoman # @File : 21_MergeTwoSortedLists.py # @Package : LeetCode # @E-mail : charlotte77_hu@sina.com # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # ...
huxiaoman7/leetcodebook
python/21_MergeTwoSortedLists.py
21_MergeTwoSortedLists.py
py
867
python
en
code
588
github-code
1
19153093382
from django.db import models class AudioTourModel(models.Model): title = models.CharField(max_length=200, blank=False, help_text='Title for audio tour area') soundcloud_id = models.IntegerField( blank=False, help_text='Specific Id from SoundCloud service to embed') index = models.DecimalFi...
imagreenplant/beacon-food-forest
tours/models.py
models.py
py
546
python
en
code
2
github-code
1
72143444195
import datetime from typing import Any, Dict, List, Optional, Type, TypeVar, Union, cast import attr from dateutil.parser import isoparse from ..types import UNSET, Unset T = TypeVar("T", bound="PatchedApplication") @attr.s(auto_attribs=True) class PatchedApplication: """Dynamically removes fields from seriali...
caltechads/brigid-api-client
brigid_api_client/models/patched_application.py
patched_application.py
py
5,315
python
en
code
0
github-code
1
72004877475
#!/usr/bin/env python # -*- coding: UTF-8 -*- from distutils.core import setup import py2exe #@UnusedImport import sys, time sys.path.append(r"d:\work\cm2\src") reload(sys) if hasattr(sys, "setdefaultencoding"): sys.setdefaultencoding("utf-8") if len(sys.argv) == 1: sys.argv.append("py2exe") s...
helljump/cm2
src/yadd/_bin.py
_bin.py
py
1,398
python
en
code
0
github-code
1
43719343533
# # This is an example script to plot seconday chemical shifts. # by Woonghee Lee, Ph.D. (woonghee.lee@ucdenver.edu) # # To run this script: # In Poky Notepad, # File -> Run Python Module print('\n\n\n------------------------------------------------------') print('POKY Secondary Shift Plot') print('by Woonghee L...
pokynmr/POKY
User_Modules/plot_secondary_shift_script.py
plot_secondary_shift_script.py
py
3,395
python
en
code
8
github-code
1
31637375221
# coding=utf-8 import copy import os import glob import shutil import unittest from mock import patch from testfixtures import TempDirectory from ddt import ddt, data from provider import cleaner import activity.activity_AcceptedSubmissionStrikingImages as activity_module from activity.activity_AcceptedSubmissionStrik...
elifesciences/elife-bot
tests/activity/test_activity_accepted_submission_striking_images.py
test_activity_accepted_submission_striking_images.py
py
8,187
python
en
code
19
github-code
1
33608410850
import shutil import string import torch import torch.nn.functional as F import torch.utils.data as data import tqdm import numpy as np import json from collections import Counter class SQuAD(): def __init__(self): self.contexts = [] self.questions = [] def loadSquad(self, data_p...
Onepierre/Context-detection
dataloader.py
dataloader.py
py
1,113
python
en
code
0
github-code
1
71317076194
import os import numpy as np from scipy import signal from scipy.io import loadmat import torch from torch import nn import torch.nn.functional as F import conv from layers.modules import * from layers.functions import ConvMotionFunction class Pooling(nn.Module): def __init__(self, n_in): super(Pooling...
teboli/CPCR
networks.py
networks.py
py
8,025
python
en
code
25
github-code
1
29927242862
""" while em python - aula 7 utilizado para realizar ações enquanto uma condição for verdadeira. """ # loop infinito """while True: # nesse modo o loop nunca irá para de rodar. nome = input('Digite seu nome: ') print(f'Seu nome é: {nome}')""" """x = 0 # variável para contar o loop while x < 10: if x =...
gutembergdomingos13/CursoPythonUdemy
aula7/aula7.py
aula7.py
py
1,081
python
pt
code
0
github-code
1
16265335340
class LinkedListQueue: ''' Queue data structre based on linked lists. Items are added to the end of the list and are pulled from the beginning of the list enqueue: O(1) adds to the queue dequeue: O(1) removes oldest from the queue isEmpty: O(1) stack_size: O(1) ...
jmcs811/interview_prep
data_structures/queues/linked_list_queue.py
linked_list_queue.py
py
1,725
python
en
code
0
github-code
1
11559234229
#!/usr/bin/env python # encoding: utf-8 """ @version: v1.0 @author: xag @license: Apache Licence @contact: xinganguo@gmail.com @site: http://www.xingag.top @software: PyCharm @file: js2py_demo.py @time: 2020-07-22 17:49 @description:js2py """ # 依赖 # pip3 install js2py import js2py from js_code import ...
xingag/tools_python
Python执行JS总结/js2py_demo.py
js2py_demo.py
py
1,012
python
en
code
148
github-code
1
70662958755
from collections import deque d = [deque() for _ in range(0, 5)] d[3].appendleft(1) d[3].appendleft(2) d[3].appendleft(3) d[3].append(1) print(d[1].maxlen) print(d) e = [deque() for _ in range(0, 5)] e[2].appendleft('world') e[2].appendleft('hello') def write_chain(chain): print(' '.join(chain)) write_chain(e...
ashrielbrian/coursera-algorithms-specialization
02 Data Structures/03 Week 3/test.py
test.py
py
475
python
en
code
0
github-code
1
28138890438
import json import inspect import urllib.parse from longitude.core.data_sources.base import DataSource class DisabledCache: data_source = None def __init__(self, ds): if ds and not isinstance(ds, DataSource): raise TypeError('DisabledCache can only be applied to DataSource subclasses.') ...
GeographicaGS/Longitude
longitude/core/common/helpers.py
helpers.py
py
2,596
python
en
code
1
github-code
1
7972926046
# Author: Leandro Cruz Hermida <hermidal@cs.umd.edu> """ sksurv_extensions is a library of custom extensions and core improvements to scikit-survival """ from sklearn.utils.metaestimators import if_delegate_has_method from sklearn_extensions.pipeline import ExtendedPipeline @if_delegate_has_method(delegate='_final_...
ruppinlab/tcga-microbiome-prediction
sksurv_extensions/__init__.py
__init__.py
py
2,183
python
en
code
11
github-code
1
41239470101
#!/usr/bin/python # -*- coding: utf-8 -*- from http://www.python.org/peps/pep-0263.html (http://www.python.org/dev/peps/pep-0263/) import sys from analhtml import analhtml import re import subprocess class webdic(analhtml): # // { AUDIO_PATH = '/home/icentrik/work/word/vocabulary_mp3/' mute = False verbose = False...
LowerCode/Code-Samples
Python/dick/webdic0.py
webdic0.py
py
1,562
python
en
code
0
github-code
1
1918021365
#!/usr/bin/env python # coding=utf-8 """ TBW """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from wiktts.pronunciationlexicon import PronunciationLexicon from wiktts.pronunciationlexicon import PronunciationLexiconEntry from wiktts.wordpronunciationpai...
pettarin/wiktts
wiktts/cleanedpronunciationlexicon.py
cleanedpronunciationlexicon.py
py
4,143
python
en
code
5
github-code
1
4623410677
import operator from bolt.db.backends.base.features import BaseDatabaseFeatures from bolt.utils.functional import cached_property class DatabaseFeatures(BaseDatabaseFeatures): empty_fetchmany_value = () allows_group_by_selected_pks = True related_fields_match_type = True # MySQL doesn't support slice...
dropseed/bolt
bolt-db/bolt/db/backends/mysql/features.py
features.py
py
8,480
python
en
code
1
github-code
1
6235823673
"""Client to interface with Rito API.""" import os from typing import Any, Dict, Optional from absl import logging import requests def call(endpoint: str, api_key: str, params: Optional[Dict[str, Any]] = None, data: Optional[Any] = None, platform_id: str = 'americas'): """Helpe...
vilhelm/icl-bot
server/riot_client.py
riot_client.py
py
1,458
python
en
code
1
github-code
1
73512600673
def predict(estimator, all_matrix, train_length, output_csv): """ Predict the test and validation text, and write to csv. The estimator should be a prediction estimator, instead of a classifier. """ # Read the text # `all_matrix` has already contained all the test and vali text x_predict = a...
xiaohk/stat333_project_2
model/mlr/mlr.py
mlr.py
py
714
python
en
code
6
github-code
1
28537510778
''' Runtime: time: binary search recursion takes O(logn), n is total number of nodes space: recursion stack takes O(n) Analysis: Given: a binary tree, and a val Ask: return the node that has val == the given val, if not exists, return [] To accomplish this: since binary...
aquariumm/Coding-Interview-Prep
Naive Solution/Search in a Binary Search Tree.py
Search in a Binary Search Tree.py
py
1,265
python
en
code
0
github-code
1
1443274025
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Author : alex Created : 2020-09-11 15:18:05 Comments : """ # %% IMPORTS # -- global import logging import time from PyQt5 import QtWidgets from PyQt5.QtGui import QFont, QIcon from PyQt5.QtWidgets import QShortcut, QMessageBox, QAction, QMenu from pathlib import Pat...
adareau/HAL
HAL/gui/main.py
main.py
py
25,565
python
en
code
2
github-code
1
70342931234
import json import logging import os import shutil import sys # pylint: disable=no-name-in-module # No name 'tar' in module 'sh' from sh import tar try: from tempfile import TemporaryDirectory except ImportError: from s2e_env.utils.tempdir import TemporaryDirectory from s2e_env import CONSTANTS from s2e_env....
S2E/s2e-env
s2e_env/commands/export_project.py
export_project.py
py
5,889
python
en
code
89
github-code
1
28090021112
#Python Program to convert USD to different currencies using Tkinter from tkinter import * #this creates a GUI Window window = Tk() #Function to convert USD to Euro (EUR), Yen (JPY), Pound (GBP), and Australian Dollar (AUD) def from_usd(): # USD to Euro (EUR) euro = float(e2_value.get())*.88 # USD to Yen...
meyer2rn/it3038c-scripts
project1/project3.py
project3.py
py
1,748
python
en
code
0
github-code
1
73111178914
# -*- coding: utf-8 -*- import scrapy import json import time from scrapy.http import FormRequest from loguru import logger from SafetyInformation.items import SafeInfoItem from SafetyInformation.settings import SLEEP_TIME, TOTAL_PAGES class NosecSpider(scrapy.Spider): name = 'nosec' allowed_domains = ['nose...
Silentsoul04/SafetyInformation
SafetyInformation/spiders/nosec.py
nosec.py
py
2,793
python
en
code
0
github-code
1
32205094518
import os import torch import argparse import numpy as np import PIL.Image as Image from matplotlib import pyplot as plt from torch.utils.data import DataLoader from torch import nn, optim, autograd from torchvision.transforms import transforms from dataset import Train_Dataset, Validation_Dataset, Test_Datase...
Jichao-Wang/MDOAU2-net
wjc_core.py
wjc_core.py
py
16,861
python
en
code
0
github-code
1
34564509479
# Path generator by Team Griffin from __future__ import print_function import pyvisgraph as vg import itertools import time import sys if (len(sys.argv) > 1): instance_number = int(sys.argv[1]) # Import instance information execfile("instance_%d.py" % instance_number) # Calculate shortest paths...
tsuiwwwayne/move-and-tag-competition
py/loadgraph.py
loadgraph.py
py
2,120
python
en
code
0
github-code
1
33091530038
import solution from math import log class Solution(solution.Solution): def solve(self, test_input=None): return self.pathInZigZagTree(label=test_input) def pathInZigZagTree(self, label): """ :type label: int :rtype: List[int] """ ans = [label] # 初始入口端点...
QuBenhao/LeetCode
problems/1104/solution.py
solution.py
py
1,160
python
zh
code
8
github-code
1
1588805635
import xarray as xr import numpy as np import matplotlib.pyplot as plt import pandas as pd import cartopy.crs as ccrs import cartopy.io.shapereader as shpreader from mask_shape_border import mask_shape_border DS_y=xr.open_dataset("yield_soy_1979-2012.nc",decode_times=False).sel(lon=slice(-61,-44),lat=slice(-5,-33)) ...
dumontgoulart/agr_cli
model_data_yield.py
model_data_yield.py
py
5,932
python
en
code
2
github-code
1
34724927724
from fastapi import HTTPException from pydantic import BaseModel, EmailStr, constr from datetime import date, timedelta from db_mysql.Connection_mysql import conecction_mysql class UserRegister(BaseModel): sexo: constr(max_length=10) fecha_de_nacimiento: date nombre: constr(max_length=100) apellido: c...
Warriors2021/FormUserCRUD
Dependencies/Register.py
Register.py
py
2,323
python
es
code
0
github-code
1
31014597352
#!usr/bin/env python # -*- coding:utf-8 _*- """ @Created by sublime_text at home on 2018/2/28—20:12! @Gnome: Live and learn! @Author: 葛绪涛 @Nickname: wordGe @QQ: 690815818 @Filename: web.py @Blog: http://higexutao.blog.163.com """ import os.path from tornado import httpserver, web, ioloop # 功能模块 实现具体的功能 cla...
tagxt/WenZiShiBie_tornado
web.py
web.py
py
1,860
python
en
code
0
github-code
1
9893919789
from typing import Any, List, Dict import xlwt import xlrd2 import openpyxl from ..basic.exClass import CommonException from ..exFunc import * from .fileFunc import readLines, isExist, createFile, deleteFile, writeAppend class XlsWriter(): def __init__(self, path: str) -> None: self.path = path ...
Logic-Orz/logicFun
logicFun/common/excelFunc.py
excelFunc.py
py
4,595
python
en
code
0
github-code
1
33543635651
#Universidad de la Fuerzas Armadas-ESPE #Autor:Pamela Jesabel Carriel Mier """Modifica la función buscar_valor en Python para que reciba un árbol binario y un valor como parámetros, y devuelva True si el valor se encuentra en el árbol, y False en caso contrario.""" #Fecha : 23 de junio del 2023 class Nodo: def __i...
PamelaCarriel/Repositorio_2P
Árboles/Buscar_Valor.py
Buscar_Valor.py
py
1,184
python
es
code
0
github-code
1
71632601315
#!/usr/bin/env python import argparse import glob import os import re import cv2 import numpy as np import pandas as pd from skimage import transform as tf from utils import create_dictionary_lang CHROME_PATH = "/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome" lang_code_dict = create_dictionary_lang(...
facebookresearch/flores
ocr/data_collection/augment_data.py
augment_data.py
py
10,099
python
en
code
623
github-code
1
70320373153
#!/usr/etc/env python3 def main(): marvelchars= { "Starlord": {"real name": "peter quill", "powers": "dance moves", "archenemy": "Thanos"}, "Mystique": {"real name": "raven darkholme", "powers": "shape shifter", "archenemy": "Professor X"}, "Hulk": ...
JMRacke/mycode
dict01/dictChallenge.py
dictChallenge.py
py
935
python
en
code
0
github-code
1
31415576748
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('promotions_app', '0002_promotionmanager')...
mvpgomes/shopit-app
promotions_app/migrations/0003_auto_20150223_2016.py
0003_auto_20150223_2016.py
py
1,029
python
en
code
0
github-code
1
11724257482
# -*- coding: utf-8 -*- """ Preppin' Data 2023: Week 15 - Easter Dates https://preppindata.blogspot.com/2023/04/2023-week-15-easter-dates.html - Input the data - Reshape it so that we have a list of Easter Sunday dates - Filter the dataset so that we only have past dates - i.e. 1700 - 2023 - Output the da...
kelly-gilbert/preppin-data-challenge
2023/preppin-data-2023-15/preppin-data-2023-15.py
preppin-data-2023-15.py
py
3,450
python
en
code
19
github-code
1
13103595331
import numpy as np import pathlib, os, time class Neuron: def __init__(self, numofinputs, weights=[-999], layerName="undefined"): """ initialises neuron class type. weights MUST be list, not integer. If only 1 weighting of n then pass [n] """ self.activation = tanh self.layerName = layerN...
lloydarnold/a-level-coursework
old_neural_network.py
old_neural_network.py
py
6,296
python
en
code
0
github-code
1
38281618825
def train_epoch(model, dataloader, criterion, reg_criterion, optimizer, scheduler, device, wandb): losses = [] model.train() for i, (img_names, images, genders, ages) in enumerate(dataloader): images = images.to(device) gt_genders = genders.to(device) gt_ages = ages.to(device) ...
ashish-roopan/Lightweight-Gaze-Estimation
AgeGenderNet/scripts/train.py
train.py
py
820
python
en
code
0
github-code
1
43467543395
import time from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.proxy import Proxy, ProxyType from selenium.webdriver.chrome.options import Options from fake_useragent import UserAgent from undetected_chromedriver import Chrome, ChromeOptions from getCar...
Sankhay/Estudos
Python/selenium/app4.py
app4.py
py
7,174
python
en
code
0
github-code
1
32160389406
import uwwwauth # Example from https://tools.ietf.org/html/rfc2617#section-2 headers = {"WWW-Authenticate": 'Basic realm="WallyWorld"'} auth_req = uwwwauth.parse_auth_req(headers["WWW-Authenticate"]) print(auth_req) assert auth_req == {'realm': 'WallyWorld', 'type': 'Basic'} resp = uwwwauth.basic_resp("Aladdin", "o...
pfalcon/pycopy-lib
uwwwauth/test.py
test.py
py
1,762
python
en
code
229
github-code
1
28718690425
#!/usr/bin/env python3 # We are an import and import company import sys # Variable Setup count = 0 # initial card count elevens = 0 # counter, for aces counting as 11 in hand # Prints the player's current hand, the total value, and the running count def gui(cards, total, count): print(f"Player Hand: {cards}"...
MasterChenb0x/blackjack-trainer
blk_jak_functions.py
blk_jak_functions.py
py
1,985
python
en
code
8
github-code
1
38639297269
#!/usr/bin/env python from setuptools import find_packages, setup with open('README.rst') as readme_file: readme = readme_file.read() requirements = ['scitools-iris', 'numpy', 'scipy', 'matplotlib', 'metpy'] setup_requirements = [] test_requirements = [] setup( author="Leo Saffin", author_email='str...
leosaffin/scripts
setup.py
setup.py
py
1,150
python
en
code
2
github-code
1
36235255031
# -*- coding: utf-8 -*- """ Created on Mon Nov 6 15:32:24 2017 @author: vidyag """ import tensorflow as tf import numpy as np import math from scipy import misc import glob from autoencode import AutoEncoder from layer_defs import variable_on_cpu, getConvInitializer def fftshift(mat2D, dim0, dim1): #fftshift == i...
Mualpha7/Engineering_JupyterFiles
ENGR 090. Fourier ptychographic microscopy for biological samples/TensorFlowFunctions.py
TensorFlowFunctions.py
py
58,048
python
en
code
0
github-code
1
16891021353
EnsureSConsVersion(1, 1, 0) import os import re from os.path import join as pjoin opts = Variables('build.py') env = Environment(options=opts, ENV = os.environ.copy(), tools=['default']) conf = Configure(env, custom_tests = {}) conf.env['NODE'] = conf.env.WhereIs('node') conf.env...
cloudkick/nodul.es
SConstruct
SConstruct
702
python
en
code
4
github-code
1
15141641723
import requests import json import sys import urllib.parse import os.path import hashlib import argparse # import sqlite3 # from tplib3 import * # import datetime # import time import platform from sqlite3 import Error # updategroupconfig # # Fetches siteconfig from config file # fetches groupconf...
bios62/ha_hytta
python-scripts/updategroupconfig.py
updategroupconfig.py
py
5,476
python
en
code
0
github-code
1
15691361971
import sys from PyQt4.QtGui import * from PyQt4.QtCore import * from remote_class import * from timelapse_class import * class DollyProject(QWidget): def __init__(self, stack): #super(DollyProject, self).__init__() QWidget.__init__(self, stack) self.stack = stack self.initUI() ...
summonbenz/dollyproject-pyqt
main.py
main.py
py
6,720
python
en
code
0
github-code
1
12086094939
import sys sys.path.append("../") import pymysql import math import pandas as pd import numpy as np from scipy.spatial import distance import csv from InsertDataBase.CreateTables import * from DBtools.init_db import init_DB def GetMinDistanceLane(local_x, local_y): radius = 5 node_list = list() ...
THU-changc17/MetaScenario
InsertDataBase/Argoverse_MIA_InsertTrafficParticipant.py
Argoverse_MIA_InsertTrafficParticipant.py
py
6,690
python
en
code
13
github-code
1
32034222849
"""Open merge example. Trains a a small percentage of rl vehicles to dissipate shockwaves caused by on-ramp merge to a single lane open highway network. """ from flow.core.params import SumoParams, EnvParams, InitialConfig from flow.core.params import NetParams, InFlows, SumoCarFollowingParams from SingalNetwork impor...
lim-it-ing/lane_change_sumo
singal_custom_env/scenario.py
scenario.py
py
2,436
python
en
code
1
github-code
1
412075890
# pylint: disable=W0621,C0114,C0116,W0212,W0613 import pathlib import textwrap import pytest import numpy as np from dae.genomic_resources.testing import build_inmemory_test_repository from dae.genomic_resources.repository import GR_CONF_FILE_NAME, \ GenomicResourceRepo from dae.gene.gene_scores import build_gene_...
iossifovlab/gpf
dae/dae/gene/tests/test_gene_score.py
test_gene_score.py
py
8,621
python
en
code
1
github-code
1
43073520173
import sys from PyQt4.QtGui import (QApplication, QWidget, QFont, QListWidget, QHBoxLayout, QVBoxLayout, QShortcut, QKeySequence) import numpy as np from spyderlib.widgets.sourcecode.codeeditor import CodeEditor from spyderlib.widgets.internalshell import InternalShell from spyderlib.widgets.dicteditor import DictE...
UpSea/midProjects
BasicOperations/11_Spyder/useOfSpyderShell.py
useOfSpyderShell.py
py
2,085
python
en
code
1
github-code
1
2421960407
from odoo import fields, models class ResPartnerAcademy(models.Model): """ National Education Academy """ _name = 'res.partner.academy' _description = 'Academy' _rec_name = 'name' _order = 'name' partner_id = fields.Many2one('res.partner', 'Rectorate') name = fields.Text('Name', required...
decgroupe/odoo-addons-dec
partner_academy/models/res_partner_academy.py
res_partner_academy.py
py
1,144
python
en
code
2
github-code
1
4415210155
import numpy as np import _pickle as pickle import copy from collections import OrderedDict from ConstantVariables import * from pathlib import Path class Network: def __init__(self, name='', inputs=0, outputs=0): self.name = name self.inputs = inputs self.outputs = outputs self.l...
Robinamixan/Goblins-pygame
Networks/Network.py
Network.py
py
5,303
python
en
code
0
github-code
1
33093318888
import solution class Solution(solution.Solution): def solve(self, test_input=None): logs, k = test_input return self.findingUsersActiveMinutes([x[:] for x in logs], k) def findingUsersActiveMinutes(self, logs, k): """ :type logs: List[List[int]] :type k: int :...
QuBenhao/LeetCode
problems/1817/solution.py
solution.py
py
572
python
en
code
8
github-code
1
71109080994
""" This module contains the implementation of the Classes: BaseEnvironment, BaseWrapper, BaseObservationWrapper, BaseActionWrapper, BaseRewardWrapper, BaseGridWorld, BaseCarOnHill, BaseCartPole, BaseInvertedPendulum and LQG. Then there are the Mujoco Environments Wrappers: BaseMujoco, BaseHalfCheetah, BaseAnt, BaseHo...
arlo-lib/ARLO
ARLO/environment/environment.py
environment.py
py
49,674
python
en
code
10
github-code
1
2623807423
#!/usr/bin/env python # coding: utf-8 # #### 배열 안 단어에서 특정 글자들을 옮겨서 모두가 같은 단어가 되도록 만들기 # # #### 가능하면 true return, 안되면 false return # In[ ]: words = ["abc","aabc","bc"] # true words = ["ab","a"] # false # #### words의 총 길이가 n일때, n의 배수 개수만큼 만큼 각 문자들이 존재한다면 이동으로 같아질 수 있음 # In[39]: class Solution(object): def m...
dohi1004/Algorithm_1
week9/1-1) LEET 1897 Redistribute Characters to Make All Strings Equal.py
1-1) LEET 1897 Redistribute Characters to Make All Strings Equal.py
py
1,373
python
ko
code
0
github-code
1
29325045935
from app import db class Board(db.Model): __tablename__ = "board" id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String) owner = db.Column(db.String) cards = db.relationship("Card", back_populates="board", cascade="all, delete-orph...
lisabethu88/be-task-list
app/models/board.py
board.py
py
662
python
en
code
0
github-code
1
40319161924
#! /usr/bin/env python # -*- coding: utf-8 -*- import logging from src.ui.winsWidgetView import WinsWidgetView logging.basicConfig(level=logging.DEBUG) # change to 'DEBUG' to see more from PyQt5 import QtWidgets, QtGui def setFontFamily(font): allFamillies = QtGui.QFontDatabase().families() familyName = ...
winsomexiao/PyDemo
src/ui/mainView.py
mainView.py
py
792
python
en
code
0
github-code
1
73909948834
__author__ = 'Médéric Ribreux' __date__ = 'April 2016' __copyright__ = '(C) 2016, Médéric Ribreux' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' from processing.core.parameters import ParameterRaster, getParameterFromString from processing.tools.system import isWindo...
nextgis/nextgisqgis
python/plugins/processing/algs/grass7/ext/i.py
i.py
py
7,663
python
en
code
27
github-code
1