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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
71154449436 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 2 08:45:19 2021
@author: jbclark8
"""
# main program for ICM-DOM-PD for python
# a highly modularized code based on Cerco and Coel 1993 estuarine model
# of Chesapeake Bay
# Modified from Clark et al. 2020 to include more complex
# light reac... | bclark805/pyICM | code/ICM_main.py | ICM_main.py | py | 12,956 | python | en | code | 0 | github-code | 50 |
19979045520 | """
Local settings
- Run in Debug mode
- Use console backend for emails
- Add Django Debug Toolbar
- Add django-extensions as app
"""
from .base import * # noqa
# DEBUG
# ------------------------------------------------------------------------------
DEBUG = env.bool('DJANGO_DEBUG', default=True)
TEMPLATES[0]['OPT... | nfletton/bvspca | config/settings/local.py | local.py | py | 4,814 | python | en | code | 8 | github-code | 50 |
22422593023 | import math
import random
class UncorrNoiseConso:
def __init__(self, muconso=None, sigmaConso=None):
self.e = math.exp(1)
self.need_init_ = sigmaConso is None or muconso is None # need to be initialized with the variation of loads
self.sigmaConso = sigmaConso
self.muconso = muconso... | BDonnot/data_generation | pgdg/UncorrNoise.py | UncorrNoise.py | py | 1,298 | python | en | code | 0 | github-code | 50 |
72883410075 | # Elabore um programa que efetue a apresentação do valor da conversão em dólar de um valor lido em real.
# O programa deve solicitar a cotação do dólar e também a quantidade de reais disponível com o usuário,
# para que seja apresentado o valor em moeda americana.
valor_cotacao = float(input('Digite o valor da cotac... | TITYCOCO123HOT/VALTER | 13.py | 13.py | py | 552 | python | pt | code | 0 | github-code | 50 |
8338455192 | import lws
import librosa
import random
import numpy as np
import math
def _random_occlusion(mags, min_amount, max_amount):
width, height = mags.shape
def random_from_exp(amount_min, amount_max, exp):
return random.uniform(amount_min, math.sqrt(amount_max))**exp
min_width = int(min... | fedden/pytorch_seq2seq_audio | lws_comparison/augmentor.py | augmentor.py | py | 3,594 | python | en | code | 9 | github-code | 50 |
15328769814 | # -*- coding: utf-8 -*-
"""
Created on Sat May 09 17:04:16 2015
@author: Gonçalo
"""
import pandas as pd
import matplotlib.pyplot as plt
from infotables import names,control,lesion,lesionordermap
from activitytables import posturebias, getballistictrials, info_key
from activitytables import normalize, medi... | kampff-lab/shuttling-analysis | paper/figures/randombias3dtrajectory.py | randombias3dtrajectory.py | py | 2,935 | python | en | code | 0 | github-code | 50 |
25181212306 | from tkinter import *
from game import game
from tkinter import messagebox
def rules():
root = Tk() # open main window (here "root" works as an object)
root.title('Rock Paper Scissor Lizard and Spock')
root.resizable(False, False)
root.config(background='black')
bg = PhotoImage(file='pl... | MeghanaKallepalli/Rock-Paper-Scissor-Lizard-Spock | Rules.py | Rules.py | py | 1,560 | python | en | code | 0 | github-code | 50 |
32008112238 | import math
from shapely.geometry import Polygon, LineString
coords_tile = dict()
def coord_from_tile(x, y=None, level=14):
n = 2 ** level
if y is None:
s = x.split('_')
x = int(s[0])
y = int(s[1])
lat = math.atan(math.sinh(math.pi * (1 - 2 * y / n))) * 180.0 / math.pi
lon = ... | BenoitBouillard/computeFillRatio | common/tile.py | tile.py | py | 2,953 | python | en | code | 0 | github-code | 50 |
38554558108 | import time
import math
from datetime import timedelta, tzinfo
class UTC(tzinfo):
"""
UTC timezone to set for UTC datetime.
"""
def utcoffset(self, dt):
return timedelta(0)
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return timedelta(0)
# timeframe to st... | simhaonline/siis-rev | connectors/common/utils.py | utils.py | py | 3,814 | python | en | code | 2 | github-code | 50 |
32759579838 | import datetime
import io
import json
import logging
import os
import pydoc
import sys
import time
from types import SimpleNamespace
from typing import Any
import jsonargparse
import xarray as xr
LOGGER = logging.getLogger("pplbench")
def load_class_or_exit(class_name: str) -> Any:
"""
Load the given `clas... | facebookresearch/pplbench | pplbench/lib/utils.py | utils.py | py | 4,740 | python | en | code | 92 | github-code | 50 |
3210785300 | import unittest
class Node(object):
def __init__(self, val=None, next=None, prev=None, child=None):
self.val = val
self.next = next
self.prev = prev
self.child = child
class LinkedList(object):
def __init__(self, head=None):
self.head = head
self.tail = head
... | EugeneStill/PythonCodeChallenges | helpers/doubly_linked_list.py | doubly_linked_list.py | py | 2,990 | python | en | code | 0 | github-code | 50 |
12974027203 |
ANUSVAARA = 'ANUSVAARA'
VISARGA = 'VISARGA'
ANUNAASIKA = 'ANUNAASIKA'
ACH_HRASVA = 'ACH_HRASVA'
ACH_DEERGHA = 'ACH_DEERGHA'
HAL = 'HAL'
# akshara_suffix = ANUSVAARA | VISARGA
# deergha_an = (ACH_DEERGHA ANUNAASIKA) | (ACH_DEERGHA)
# deergha = (deergha_an) | deergha_an
# hrasva_an = (ACH_HRASVA ANUNAASIK... | ramprax/sanskrit-chandas-ganas | ganas.py | ganas.py | py | 13,329 | python | en | code | 1 | github-code | 50 |
26397167556 | class IterMain(object):
def __iter__(self):
print('return an iterator')
# global instA
return K
class Iterator(object):
def __init__(self, i):
self.num = i
def __next__(self):
self.num = self.num + 1
if self.num <= 10:
return self.num
e... | steve3ussr/PyCharmProject | RunnobBasic/iter_class_test.py | iter_class_test.py | py | 419 | python | en | code | 0 | github-code | 50 |
32008128378 | import os
from pathlib import Path
import json
from common.config import load_users, GEN_PUBLIC_PATH, load_config, GEN_ZONES, GEN_USERS, GEN_RESULTS, GEN_PATH, \
PUBLIC_PATH, GEN_COMMUNITY
from common.statshunters import tiles_from_activities
from common.zones import load_zones_outer
from common.fileutils import F... | BenoitBouillard/computeFillRatio | data_json_gen.py | data_json_gen.py | py | 11,667 | python | en | code | 0 | github-code | 50 |
21019828079 | import collections
import six
from sqlian import Parsable, Sql, is_single_row
from sqlian.utils import (
is_flat_tuple, is_flat_two_tuple,
is_non_string_sequence, is_partial_of,
)
from .compositions import Assign, Join, List, Ordering
from .expressions import (
Condition, Identifier, Value,
get_condi... | uranusjr/sqlian | sqlian/standard/clauses.py | clauses.py | py | 7,189 | python | en | code | 0 | github-code | 50 |
22354097666 | import sys
import csv
from collections import OrderedDict
from time import sleep
from PyQt5 import QtWidgets
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtGui import QIcon
from mainwindow import Ui_MainWindow
emit_inc = 1000
class CSVEditor(Ui_MainWindow):
def __init__(self, window):
super()... | ScriptSmith/csveditor | csveditor.py | csveditor.py | py | 7,838 | python | en | code | 5 | github-code | 50 |
3032408596 | import libomni as robot #Library tha handles all the serial commands to arduino AtMega
import time
import serial
import math
import numpy as np
robot.enablePID(1)
count = 0
#ultrasonic setup
us = [0,0,0,0,0,0]
d = [0,0,0,0,0,0]
#odemetry setup
oldEncoder0 = 0
oldEncoder1 = 0
oldEncoder2 = 0
newEncoder0 = 0
newEnco... | huantianh/OMRE-SIUE | OMRE_Python/g2g&OA/obstacleAvoidance/obstacleAvoidance.py | obstacleAvoidance.py | py | 5,919 | python | en | code | 2 | github-code | 50 |
16806034536 | import logging
logger = logging.getLogger(__name__)
from sklearn.pipeline import Pipeline
from sklearn.base import TransformerMixin
import cudf
cat_features = ["B_30","B_38","D_114","D_116","D_117","D_120","D_126","D_63","D_64","D_66","D_68"]
class CuDFTransforms(TransformerMixin):
def __init__(self, cat_featur... | sajwankit/amex | data/pipelines.py | pipelines.py | py | 1,457 | python | en | code | 0 | github-code | 50 |
22147381814 | import pandas as pd
df = pd.read_csv('data2.csv')
df.fillna(130, inplace = True)
print(df.to_string())
#Notice in the result: empty cells got the value 130 (in row 18, 22 and 28).
# Replace Empty Values
# Another way of dealing with empty cells is to insert a new value instead.
# This way you do not ... | StumbledUponCS/10_Python_Examples | Python Examples/05) Pandas/index307.py | index307.py | py | 504 | python | en | code | 0 | github-code | 50 |
16635289362 | from torch.utils.data import Dataset
import torch
import pandas as pd
class make_dataset(Dataset):
def __init__(self, data_path, tokenizer, run_type):
if data_path.endswith("csv"):
self._data = pd.read_csv(data_path)
elif data_path.endswith("tsv"):
self._data = pd.read_csv(... | sondonghup/TextClassification | dataset.py | dataset.py | py | 2,130 | python | en | code | 0 | github-code | 50 |
41236633369 | import torch
import torchvision.ops.misc as misc
from torchvision.models import resnet18, resnet50, resnet101
from torchvision.models.resnet import ResNet18_Weights, ResNet50_Weights, ResNet101_Weights
from torchvision.models._utils import IntermediateLayerGetter
from utils import is_main_process
class ResN... | JeremyZhao1998/MRT-release | models/backbones.py | backbones.py | py | 2,297 | python | en | code | 5 | github-code | 50 |
72854789916 | import os
import time
import datetime
import torch
import argparse
from src.data import *
import warnings
import torch.distributed as dist
from src.defined_external_iterator import ExternalInputIterator
from src.defined_external_source import ExternalSourcePipeline
from src.COCOIterator import DALICOCOIterator
# from s... | cs-heibao/DALI-examples | dali_demo/train_multigpu.py | train_multigpu.py | py | 4,427 | python | en | code | 1 | github-code | 50 |
25331559022 | 'Chapter 6 Data Encoding and Processing'
import csv
"""
The main focus of this chapter is using Python to process data presented in different kinds of common encodings, such as CSV files, JSON, XML, and binary packed records. Unlike the chapter on data structures, this chapter is not focused on specific algorithms,... | jradd/pycookbook | old_Cookbook/Chapter6.py | Chapter6.py | py | 3,602 | python | en | code | 0 | github-code | 50 |
8087459285 |
"""
File: gen_wav.py
Date: 2017/03/24 12:36:27
Brief: 通过麦克风录音 生成 wav文件
"""
import machine
import array
import wave
from ulab import numpy as np
import struct
class GenAudio(object):
def __init__(self):
self.num_samples = 1000 #pyaudio内置缓冲大小
self.sampling_rate = 2000 #取样频率
self.l... | blackjackgg/mpython_raspberry | record.py | record.py | py | 2,971 | python | en | code | 0 | github-code | 50 |
11891810694 |
# this code is for half screen http://www.trex-game.skipser.com/ game
import numpy as np
import cv2
from mss import mss
from PIL import Image # grab screen
from pyautogui import press, keyDown,keyUp, hotkey # for keyboard
import time
########### change the distance between dino and points########
dist_x=25
########... | palashbhusari/dinosaur_game_opencv | half_screen.py | half_screen.py | py | 2,197 | python | en | code | 0 | github-code | 50 |
40158252720 | import FWCore.ParameterSet.Config as cms
process = cms.Process('Test')
process.source = cms.Source('EmptySource')
process.failing = cms.EDProducer('FailingProducer')
process.i = cms.EDProducer('IntProducer',
ivalue = cms.int32(10) )
process.out = cms.OutputModule('PoolOutputModule',
... | cms-sw/cmssw | FWCore/Integration/python/test/unscheduled_fail_on_output_cfg.py | unscheduled_fail_on_output_cfg.py | py | 623 | python | en | code | 985 | github-code | 50 |
20471493060 | ## IMPORT BASIC LIBS FOR SCRIPT
import scipy as sc
from scipy import io
from scipy import linalg
import bstates as bs
import pickle
import numpy as np
import feather
import h5py
import pandas as pd
from sklearn.decomposition import PCA
import os
from sys import argv
## TREATING ARGV VARS
nPats = int(argv[1]) # NUMBE... | CoDe-Neuro/neonatal_dfc | src/run_pca.py | run_pca.py | py | 4,714 | python | en | code | 1 | github-code | 50 |
10718863127 | x=2
y=2
z=2
i="y*z**2"
j="x*y"
k="y*z"
def Ry(k,x,y,z,h):
ry=k.replace("x",str(x))
ry=ry.replace("z",str(z))
s1=ry.replace("y",str(y))
s2=ry.replace("y",str(y+h))
return (eval(s2)-eval(s1))/h
def Qz(j,x,y,z,h):
qz=j.replace("x",str(x))
qz=qz.replace("y",str(y))
s1=... | BryceP-44/ncalc | curl.py | curl.py | py | 1,296 | python | en | code | 0 | github-code | 50 |
23338484338 |
class Solution(object):
def kidsWithCandies(candies, extraCandies):
maxCandies=max(candies)
for i in range(len(candies)):
if candies[i] + extraCandies >= maxCandies:
candies[i]=True
else:
candies[i]=False
return candies
candi... | lovepreetmultani/DS_Algo_Coding | Python/Arrays/max-candies.py | max-candies.py | py | 423 | python | en | code | 0 | github-code | 50 |
42145716064 | #!/usr/bin/python
# initializing string
test_str = "Gfg, is best : for ! Geeks ;"
# printing original string
print("The original string is : " + test_str)
# initializing punctuations string
punc = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
# Removing punctuations in string
# Using loop + punctuation string
for ele in test_s... | vishhaldawane/python | punctuation.py | punctuation.py | py | 459 | python | en | code | 0 | github-code | 50 |
22975654443 | import sys
try:
shell = sys.argv[1]
alias = sys.argv[2]
run = sys.argv[3]
run = run.replace('"', "")
run = run.replace("'", "")
except:
print("Usage: \n\tmkalias <shell> <alias> <command>")
sys.exit()
if shell == "zsh" or shell == "bash" or shell == "sh":
print("alias " + alias + "=\"... | XiKuuKy/mkalias | mkalias.py | mkalias.py | py | 524 | python | en | code | 2 | github-code | 50 |
41039690281 | # Un petit programme illustrant la détection de bords.
# Pour cela nous allons utiliser l'algorithme Canny de la librairie OpenCV.
# Sur une image en noir et blanc I, Canny fonctionne de la manière suivante:
# 1) Calculer la norme du gradient sur l'image I
# 2) Garder tous les maximums locaux du gradient sur I
# 3) App... | Molugan/AI_summer_school | Demo_1/demo_canny.py | demo_canny.py | py | 1,868 | python | fr | code | 0 | github-code | 50 |
22453374695 | import re
from abc import ABC
import spacy
from bs4 import BeautifulSoup
from spacy.tokens import Span,Token
from utils import switcher_color_entities,switcher_color_semantics
class WordProcessing():
def __init__(self,soup, languaje,regex):
if languaje == "en":
self.nlp = spacy.load("en_cor... | miguel-kjh/WebWordProcessing | WordProcessing.py | WordProcessing.py | py | 4,994 | python | en | code | 0 | github-code | 50 |
42363993534 | #!/usr/bin/env python
import os
import argparse
import numpy as np
# Parse session directories
parser = argparse.ArgumentParser()
parser.add_argument('--session_directory', dest='session_directory', action='store', type=str, help='path to session directory for which to measure performance')
args = parser.parse_args()... | choicelab/grasping-invisible | evaluate.py | evaluate.py | py | 1,591 | python | en | code | 43 | github-code | 50 |
4518453475 | """ Runs automech instancs for tests
"""
import os
# import tempfile
import numpy
from _util import run_mechdriver
# from _util import chk_therm
# from _util import chk_rates
# Set path where test input files and output data comparison exist
PATH = os.path.dirname(os.path.realpath(__file__))
DAT_PATH = os.path.join(... | Auto-Mech/mechdriver | tests/test_workflow.py | test_workflow.py | py | 2,558 | python | en | code | 2 | github-code | 50 |
28645224843 | from sqrt import *
import numpy as np
import math
def check(n):
assert np.isclose(sqrt(n), math.sqrt(n))
def test_sqrt():
check(125348)
check(100)
check(1)
check(0)
| parrt/msan501-starterkit | stats/test_sqrt.py | test_sqrt.py | py | 189 | python | en | code | 5 | github-code | 50 |
4006519574 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
from itertools import *
from xapi.symbol import get_product
def get_fields_columns_formats(struct):
# 想转成DataFrame
# 对于单个的C,在转换的时候是看不出来的,这种应当转换成数字方便
columns = []
formats = []
for f in struct._fields_:
co... | sagpant/XAPI2 | languages/Python/xapi/utils.py | utils.py | py | 11,842 | python | zh | code | 1 | github-code | 50 |
16529096231 | import pandas as pd
import sys
import os
if len(sys.argv) != 2:
print("need results path arg")
df = pd.read_csv(sys.argv[1])
algos = ['ppo', 'ppo-x3', 'ppo-cma', 'ppo-dma', 'ou', 'zero']
blue_exp = df.iloc[0].blue_experiment
yellow_exp = df.iloc[0].yellow_experiment
blue_algos = [f'{blue_exp}_' + a for a in alg... | FelipeMartins96/rsoccer-isaac | get_stats.py | get_stats.py | py | 1,587 | python | en | code | 0 | github-code | 50 |
73027640475 | # This command will create the body for a PR from a template environmental variable in GitHub Actions
# using jinja2 for the template engine
import os
from jinja2 import Template
# Get the template from the templates directory
def create_pr_body(test=False):
# find the path in the dir structure to the template '... | xn4p4lm/Books | scripts/issue_body_template.py | issue_body_template.py | py | 1,723 | python | en | code | 6 | github-code | 50 |
17731789852 | import sys
import collections
def read_data(fpath):
data = []
with open(fpath, "r") as fp:
lines = fp.readlines()
for i, line in enumerate(lines):
if not line.strip():
break
template = str(line.strip())
for line in lines[i:]:
if line... | collinb9/advent-of-code | 2021/14.py | 14.py | py | 1,885 | python | en | code | 0 | github-code | 50 |
20487089679 | # -*- coding: utf-8 -*-
# @Time : 2022/1/23 6:37 下午
# @Author : zuokuijun
# @Email : zuokuijun13@163.com
"""
获取翼型拟合后的X以及Y坐标
这里将拟合数据点设置为70个
"""
import os
import numpy as np
from scipy.interpolate import splev, splprep, interp1d
from scipy.integrate import cumtrapz
from matplotlib import pyplot as plt
from Utils.... | zuokuijun/Multi-head-attention-network | get_XY_coordinate.py | get_XY_coordinate.py | py | 4,182 | python | en | code | 7 | github-code | 50 |
2880577003 | from itertools import permutations
def check(perm, banned):
for i in range(len(perm)):
ui, bi = perm[i], banned[i]
if len(bi) != len(ui):
return False
for i in range(len(bi)):
if bi[i] != '*' and bi[i] != ui[i]:
return False
return True
def solut... | GeonHyeongKim/2022-2-Algorithm-Study | src/chanhyun/week5/불량 사용자.py | 불량 사용자.py | py | 528 | python | en | code | 2 | github-code | 50 |
40513989039 | from tkinter import *
from PIL import ImageTk, Image
import tkinter.messagebox
import mysql.connector as mysql
def game(player1id, player2id, mainwindow):
window = Toplevel(mainwindow)
window.geometry("600x300")
p1 = PhotoImage(file='./turtle/assets/turtle1.png')
window.iconphoto(False, p1)
... | tavignesh/school-project | turtle/turtle.py | turtle.py | py | 3,027 | python | en | code | 3 | github-code | 50 |
37778678677 | from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
X,Y,Z,value = [],[],[],[]
table = open("4_columns.csv").readlines()[1:]
for line in table:
x,y,z,val = line.split(',')[0],line.split(',')[1],line.split(',')[2],line.split(',')[3].strip()
X.append(int(x))
Y.append(int(y))
Z.append(in... | D-Barradas/DataViz | 3D_numpy_array_cardinalities/surface_test.py | surface_test.py | py | 521 | python | en | code | 0 | github-code | 50 |
15821268458 | import os
from math import pi, sin
NAMES_FILE = './generators/data/names.txt'
ORIGINAL_CUSTOMERS = './generators/data/original_data.txt'
ORIGINAL_PRODUCTS = './generators/data/products.txt'
EXPORT_PATH = './generated_data'
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
DEVELOPMENT = os.getenv('DEVELOPMENT', 'false')
DEVELOP... | tejones/retailstoreofthefuture | artificial-data-generator/config.py | config.py | py | 12,333 | python | en | code | 4 | github-code | 50 |
32314142737 | import datetime
import pytz
from django.shortcuts import render, get_object_or_404
from django.views.generic.edit import CreateView
from django.contrib.auth.decorators import login_required
from .models import Post, Category, Meal
from django.contrib.postgres.search import SearchVector
from .forms import SearchForm... | musaddiqaskira/cookwithme | recipe/views.py | views.py | py | 2,791 | python | en | code | 0 | github-code | 50 |
42979075369 | from dataloader_init import dataloader
from models import netG, netD
from config import image_size, batch_size, nz, lr, beta1, lsf, checkpoint_path
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.utils as vutils
import sys
loadCheckpnt = sys.argv[1]
num_epochs = int(sys.argv[2])
d... | shaunfinn/movieGAN | GAN/project1/scripts/train.py | train.py | py | 5,104 | python | en | code | 0 | github-code | 50 |
14405368245 | import numpy as np
import time
import multiprocessing as mp
import matplotlib.pyplot as plt
"""
Paralellizing "MCI_multivar.py" to get
a distribution of multiple values for
integral.
"""
# Start points, end points of integrals
a = [0, 0, 0]
b = [np.pi, np.pi, np.pi]
# Number of points in arrays
ni = int(1e3... | AntonBrekke/Code-resume | Python/Single Python-files/MCI_multivar_paralell.py | MCI_multivar_paralell.py | py | 2,204 | python | en | code | 0 | github-code | 50 |
2183611490 | import xxteaModule
import os
import shutil
import random
def ReadFile(filePath):
file_object = open(filePath,'rb')
all_the_text = file_object.read()
file_object.close()
return all_the_text
def WriteFile(filePath,all_the_text):
file_object = open(filePath,'wb')
file_object.write(all_the... | siwenHT/workCode | 项目打包/资源包生成/z_script_ios/xxteaDecrypt.py | xxteaDecrypt.py | py | 3,123 | python | en | code | 0 | github-code | 50 |
3210653490 | import unittest
class TwoSumBinarySearch(unittest.TestCase):
"""
Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order,
find two numbers such that they add up to a specific target number.
Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index... | EugeneStill/PythonCodeChallenges | binary_search_two_sum.py | binary_search_two_sum.py | py | 1,348 | python | en | code | 0 | github-code | 50 |
4825974242 | from functools import cached_property
from web3.contract.contract import ContractEvent
from web3.types import BlockIdentifier, EventData
from contract.base import Contract
class ERC20Contract(Contract):
@property
def abi(self) -> list[dict]:
return [
{
"name": "balanceOf"... | curvefi/curve-snapshot | contract/erc20.py | erc20.py | py | 9,005 | python | en | code | 4 | github-code | 50 |
71929184476 | from maps.models import Marker
from closet.models import Subcategory
from django.contrib.gis.geos import Point
import csv
mapping = {
'name': "NOM",
'lat': "LAT",
'lon': "LONG",
'comment': "DESCRIPTION",
'rue': 'RUE',
'code': 'CODE',
'commune': 'COMMUNE',
'web': 'WEBSITE',
'phone': ... | couleurmate/DeweyMaps | importer.py | importer.py | py | 1,501 | python | en | code | 0 | github-code | 50 |
27338371650 | import numpy as np
import cv2
import scipy.spatial
from utils.transform import get_matrix_rotate_point_around_x, \
get_matrix_rotate_point_around_y, \
get_matrix_rotate_point_around_z
def render_mesh(image_ori, point_cloud_data, blank_background = True):
imag... | nguyentrongvan/MedFace3D | utils/render_mesh.py | render_mesh.py | py | 3,080 | python | en | code | 0 | github-code | 50 |
39442430150 | from tkinter import *
from tkinter.ttk import *
from tkinter.messagebox import *
import pyperclip as pc
from Log.log import *
import data
from data_base.database_manager import DatabaseManager
class FrameCommonThings(data.Data):
def Save(self, l, **kwargs):
b = 1
array = []
for j, i in ... | yashrasniya/collage-project-fees-submission- | Frame/frameCommanThings.py | frameCommanThings.py | py | 4,213 | python | en | code | 0 | github-code | 50 |
13720437642 | import tkinter as tk
from tkinter import ttk
def prev_ord(conn, username):
cur = conn.cursor()
def fetch_previous_orders():
query = """
SELECT o.orderid, o.orderdate, o.ordertype, a.albumname, a.albumver, g.pcname
FROM ordalb oa
INNER JOIN orders o ON oa.orderid = o... | andricevaaa/bmstu-DBCP | src/previousorders.py | previousorders.py | py | 1,522 | python | en | code | 0 | github-code | 50 |
28070998645 | import pandas as pd
def get_mapping_dict(metadata):
metadata_path = metadata#"../metadata/metabolites_names.txt"
name_col = 1 #started from 0
metabolite_col=-1
map_dict = {}
with open(metadata_path, 'r') as f:
f.readline()
for line in f.readlines():
line = line.strip... | movingpictures83/MetaboliteMap | MetaboliteMapPlugin.py | MetaboliteMapPlugin.py | py | 1,910 | python | en | code | 0 | github-code | 50 |
9107962004 | # ----------------------- PARHAM KHOSSRAVI ------------------------
import tkinter
import sqlite3
import datetime
x=sqlite3.Connection("shop82.db")
print("connect to database!!")
#------------- create users-----------------
# query='''create table user82
# (id integer primary key,
# user char(30) not n... | parham82/login_shop822 | project.mian.py | project.mian.py | py | 9,172 | python | en | code | 0 | github-code | 50 |
11139716277 | from django.forms.models import model_to_dict
from django.shortcuts import redirect, render
from django.views import View
from marketplace.models import Marketplace as MMarketplace
from marketplace.models import MarketplaceForm
from marketplace.models import MarketplaceSettings as MMarketplaceSettings
from marketplace... | mamazinho/sellermp | marketplace/views.py | views.py | py | 3,271 | python | en | code | 0 | github-code | 50 |
608269358 | import requests
import json
import os
baseurl = "https://circabc.acceptance.europa.eu/share"
API_KEY = "YOUR-API-KEY"
file_to_upload = "./text.txt"
##### login #####
url = baseurl+"/webservice/login"
headers = {
"Content-Type": "application/json",
"X-API-KEY": API_KEY
}
response = requests.post(url, headers=h... | CIRCABC/EUShare | client/python/client.py | client.py | py | 1,808 | python | en | code | 3 | github-code | 50 |
36556420690 |
# void foo(){ z = x + y; cout << x; return 0; } Ctrl + /
"""
def foo():
z = x + y
print(z)
return 0
"""
# base_year = 1000
#
# year = 5 + 2 * 3 - base_year
# year_in_different_form = 5 + 20 * 3 - base_year
#
# epoch = year / year_in_different_form
#
# x = (year,
# epoch,
# year_in_different_for... | AH0HIM/hillel_ikonnikov | 2_lesson/2_1_classwork/2_1_1_main.py | 2_1_1_main.py | py | 1,158 | python | en | code | 0 | github-code | 50 |
31476452534 | import os
from time import sleep
import sys
containers = int(sys.argv[1])
ram_limit = 1.5
for i in range(containers):
command = f"docker run --rm -d -p 5{i:03d}:5000 " \
f"--mount type=bind,source=C:\\SatelliteImagesBIGDATA,target=/SatelliteImagesBIGDATA " \
f"--cpus=1 " \
... | ignacyr/NDVI-distributed-compute | auto-test.py | auto-test.py | py | 585 | python | en | code | 0 | github-code | 50 |
36339178903 | import asyncio
import unittest
from k2.aeon import Aeon, SiteModule, Response
class SimpleSiteModule(SiteModule):
async def handle(self, request):
return Response(
data='{method}: url={url},args={args},data={data},headers={headers}'.format(
method=request.method,
... | moff4/k2 | test/aeon/sm.py | sm.py | py | 1,911 | python | en | code | 0 | github-code | 50 |
33087601051 | """Tools for retrieving the user's configs for the ospool tools"""
import sqlite3
import os
import pwd
import pathlib
def _get_home_dir():
home = os.environ.get("HOME")
if home:
return home
return pwd.getpwuid(os.geteuid()).pw_dir
def _get_state_dir():
state_base = pathlib.Path(os.env... | bbockelm/ospool | src/ospool/utils/config.py | config.py | py | 1,822 | python | en | code | 0 | github-code | 50 |
6480794989 | import datetime
from random import randint
import pytest
from hamcrest import assert_that, calling, raises
from mongoengine.errors import ValidationError
from backend_tests.framework.asserts import assert_data_are_equal
from database.models import User
def check_review_data(review_document, exp_data):
owner_id ... | nelaluno/lunch_menu | backend_tests/tests_models/test_review.py | test_review.py | py | 2,354 | python | en | code | 0 | github-code | 50 |
5083019881 | import shutil
import tempfile
from ..forms import PostForm
from ..models import Post, Group
from django.test import Client, TestCase, override_settings
from django.urls import reverse
from django.contrib.auth import get_user_model
from http import HTTPStatus
from django.core.files.uploadedfile import SimpleUploadedFile... | Xostyara/hw05_final | yatube/posts/tests/test_forms.py | test_forms.py | py | 5,879 | python | ru | code | 0 | github-code | 50 |
14952718570 | class Solution1(object):
def setZeroes(self, matrix):
r_set, c_set = set(), set()
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == 0:
r_set.add(i)
c_set.add(j)
for i in r_set:
for ... | mei-t/algorithm_study | LeetCode/set_matrix_zeroes.py | set_matrix_zeroes.py | py | 1,698 | python | en | code | 0 | github-code | 50 |
42275532853 | import time
import numpy as np
import torch
import torchcontrol as toco
from torchcontrol.transform import Rotation as R
from torchcontrol.transform import Transformation as T
from polymetis import RobotInterface, GripperInterface
DEFAULT_MAX_ITERS = 3
# Sampling params
GP_RANGE_UPPER = [0.7, 0.1, np.pi / 2]
GP_RA... | PradeepKadubandi/fairo | polymetis/polymetis/python/polymetis/utils/continuous_grasper.py | continuous_grasper.py | py | 6,536 | python | en | code | null | github-code | 50 |
21485553153 | from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
app_name = 'users_regs'
urlpatterns = [
path('register', views.register, name='Register'),
path('register/add_lib', views.AddLibraryUser, name='add_libuser'),
path('register/con... | rafaeldtr41/Alexandria | Alexandria/users_regs/urls.py | urls.py | py | 639 | python | en | code | 4 | github-code | 50 |
11317546725 | # encoding: utf-8
import torch
import cv2
import numpy as np
import pdb
def detection_collate(batch):
"""Custom collate fn for dealing with batches of images that have a different
number of associated object annotations (bounding boxes).
Arguments:
batch: (tuple) A tuple of tensor image... | dd604/refinedet.pytorch | libs/data_layers/transform.py | transform.py | py | 1,659 | python | en | code | 36 | github-code | 50 |
31058614829 | import sys
import os
import http.client
import urllib.request
import json
import importlib
from datetime import datetime
import time
import VersionDetect.detect as version_detect # Version detection
import deepscans.core as advanced # Deep scan and Version Detection functions
import cmseekdb.basic as cmseek # All the ... | Tuhinshubhra/CMSeeK | cmseekdb/core.py | core.py | py | 9,184 | python | en | code | 2,100 | github-code | 50 |
17814324509 | """
config.py
author: gsatas
date: 2020-05-04
"""
from decifer.process_input import PURITY
THRESHOLD=0.05
class Config:
def __init__(self, mut_state, other_states, cn_props, desc_set, dcf_mode = True):
'''
mut_state: 2-tuple that indicates the CN state that the
mutation occurs in
... | raphael-group/decifer | src/decifer/config.py | config.py | py | 7,278 | python | en | code | 19 | github-code | 50 |
45690606129 | from locust import HttpLocust, TaskSet, task
from flask import json
class UserBehaviour(TaskSet):
@task(10)
def returnall(self):
self.client.get("/lang")
@task(20)
def health_check(self):
self.client.get("/health-check")
@task(30)
def add_one(self):
headers =... | sathish108/pipeline | locustfile.py | locustfile.py | py | 1,296 | python | en | code | 0 | github-code | 50 |
29578740955 | from collection import util
class Star():
def __init__(self):
pass
def __repr__(self):
return '{:1} {:3} {:1} {:>2}'.format(
self.rank,
self.team,
self.position,
self.player
)
def set_stars(self, soup):
star_table = soup.table.table
stars = []
for tr in star_table('tr'):
(rank, team, po... | thebend/fantasy | collection/nhlreport/gs/gs_star.py | gs_star.py | py | 650 | python | en | code | 0 | github-code | 50 |
1952734128 | #
from __future__ import division
import _config
import sys, os, fnmatch, datetime, subprocess, math, pickle, imp
sys.path.append('/home/unix/maxwshen/')
import fnmatch
import numpy as np
from collections import defaultdict
from mylib import util
import pandas as pd
import _data
# Default params
inp_dir ... | maxwshen/lib-analysis | be2_combin_12kChar_simbys_combine.py | be2_combin_12kChar_simbys_combine.py | py | 1,378 | python | en | code | 2 | github-code | 50 |
17293847208 | from nmtwizard.preprocess import prepoperator
@prepoperator.register_operator("length_filter")
class LengthFilter(prepoperator.Filter):
def __init__(self, config, process_type, build_state):
source_config = _get_side_config(config, 'source')
target_config = _get_side_config(config, 'target')
... | alexisdoualle/nmt-serving | nmtwizard/preprocess/operators/length_filter.py | length_filter.py | py | 1,820 | python | en | code | 0 | github-code | 50 |
26977311897 | import random
num_problems = int(input("How many addition problems would you like? "))
total_correct = 0
total_incorrect = 0
for i in range(1, num_problems + 1):
print("Problem %d" % i)
num1 = int(random.random() * 11)
num2 = int(random.random() * 11)
user_response = int(input("%d + %d = " % (num1, ... | palenq/usc_summerCamp_labs | additionTest.py | additionTest.py | py | 604 | python | en | code | 0 | github-code | 50 |
17371375584 | """
Implemente um programa que gere aleatoriamente um CAPTCHA de seis caracteres, o qual obrigatoriamente deve conter: letras
maiúsculas, letras minúscula e dígitos. O programa deve exibir o CAPTCHA gerado e solicitar que o usuário digite o valor
exibido. Em seguida, o programa deve ler o texto digitado pelo usuário... | ItaloRamillys/Trabalhos-Python-UFC---FUP---2017.1 | 1.13.py | 1.13.py | py | 1,819 | python | pt | code | 0 | github-code | 50 |
33553866817 | import sqlite3
import time
import zlib
import string
conn = sqlite3.connect('airq3.sqlite')
cur = conn.cursor()
#future update, values=list() from the start
cur.execute('SELECT County.name, Yr03.value FROM County JOIN Yr03 ON County.id = Yr03.county_id ORDER BY value DESC')
values = dict()
for val_row in cur :
va... | SaltyHobo/Capstone-Python | gword.py | gword.py | py | 1,166 | python | en | code | 0 | github-code | 50 |
74627642396 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('flashcards', '0004_merge'),
]
operations = [
migrations.RemoveField(
model_name='user_history',
name... | latreides/SE_Team3 | flashcards/migrations/0005_auto_20141006_0132.py | 0005_auto_20141006_0132.py | py | 2,205 | python | en | code | 0 | github-code | 50 |
4521912815 | """ miscellaneous utilities
"""
import itertools
from phydat import ptab
def is_odd_permutation(seq1, seq2):
""" Determine whether a permutation of a sequence is odd.
:param seq1: the first sequence
:param seq2: the second sequence, which must be a permuation of the first
:returns: True if the permut... | Auto-Mech/autochem | automol/util/_util.py | _util.py | py | 6,901 | python | en | code | 3 | github-code | 50 |
17847099395 | #!/usr/bin/env python
#_*_coding:utf-8_*_
import argparse
import re
from collections import Counter
import numpy
import itertools
def readFasta(file):
with open(file) as f:
records = f.read()
if re.search('>', records) == None:
print('The input file seems not in fasta format.')
sys.exit(1)
records = records.s... | samnooij/PathoFact | scripts/CTDC.py | CTDC.py | py | 4,014 | python | en | code | 3 | github-code | 50 |
39455640742 | import socket
s = socket.socket()
port = 8458
s.connect(('127.0.0.1', port))
print("\n Connected !!!")
opt = input("ARP or RARP : ")
if opt == "ARP":
inp = input("EnterIP : ")
elif opt == 'RARP':
inp = input('Enter Mac : ')
s.sendall(bytes(inp,'utf-8'))
if opt == 'ARP':
print("Mac ID : ",s.rec... | cdaman123/BTech_6_Lab | dccn/arp_client.py | arp_client.py | py | 408 | python | en | code | 3 | github-code | 50 |
33120973307 | from os import path, remove
from importlib import import_module
from sys import executable, path as syspath, argv
from time import sleep
from .config import Config
from .plugin import Plugin
from . import utils
class cmdQ (object):
def __init__ (self, configfile):
self.config = Config(configfile)
self.logger ... | pwwang/cmdQueue | cmdQueue/cmdq.py | cmdq.py | py | 4,701 | python | en | code | 5 | github-code | 50 |
40058706462 | import geopandas
import trim_fifteen
import load_data
from trim_fifteen import *
parcels = load_data.parcels
envelope_trim = trim(parcels, 15)
assert(isinstance(envelope_trim.dtype, geopandas.array.GeometryDtype))
usable = trim_fifteen.trim_unusable_space(envelope_trim, 8)
usable_file = geopandas.GeoDataFrame(
{
... | wnavarre/medford_gis | script/script.py | script.py | py | 773 | python | en | code | 1 | github-code | 50 |
13860489804 | from const import puntos_botones, color_botones, bolsa
class Puntaje:
def __init__(self):
self._dificultad = ''
def _set_dificultad(self, dificultad):
self._dificultad = dificultad
def calcular_puntos(self, quien, palabra):
''' CALCULA Y DEVUELVE EL PUNTAJE DE LA PALABRA ENTRANT... | agustjn/Juego-Scrabble | mod_puntos.py | mod_puntos.py | py | 1,716 | python | es | code | 0 | github-code | 50 |
43504055769 | # -*- coding: utf-8 -*-
import cv2
from pytesseract import pytesseract #outil de reconnaissance de caractères (OCR)
from pytesseract import Output
from tkinter import *
import tkinter as tk # création d'interfaces graphiques.
from tkinter import filedialog
import pandas as pd # l'analyse des données
import sy... | Le0Mast3r/Reconnaissance-Objet-Texte | projet.py | projet.py | py | 10,288 | python | en | code | 1 | github-code | 50 |
14437309270 | from sysdata.data_blob import dataBlob
from syscore.constants import arg_not_supplied
from syscore.interactive.menus import print_menu_of_values_and_get_response
from sysproduction.data.positions import diagPositions
from sysproduction.data.optimal_positions import dataOptimalPositions
from sysproduction.data.generic_... | robcarver17/pysystemtrade | sysproduction/data/strategies.py | strategies.py | py | 3,364 | python | en | code | 2,180 | github-code | 50 |
27907094259 | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 18 10:58:20 2019
@author: KainingSheng
2D CNN for MRI zone prostate detection
This work is a 2D conversion of the model architecture found in:
Aldoj, N., Lukas, S., Dewey, M., Penzkofer, T., 2019.
Semi-automatic classification of prostate cancer on m... | KainingSheng/mr-prostate-zone-classifier | 2DCNN.py | 2DCNN.py | py | 5,241 | python | en | code | 1 | github-code | 50 |
40092509120 | import FWCore.ParameterSet.Config as cms
AlignmentMonitorMuonSystemMap1D = cms.untracked.PSet(
muonCollectionTag = cms.InputTag(""),
beamSpotTag = cms.untracked.InputTag("offlineBeamSpot"),
minTrackPt = cms.double(100.),
maxTrackPt = cms.double(200.),
minTrackP = cms.double(0.),
maxTrackP = cms... | cms-sw/cmssw | Alignment/CommonAlignmentMonitor/python/AlignmentMonitorMuonSystemMap1D_cfi.py | AlignmentMonitorMuonSystemMap1D_cfi.py | py | 744 | python | en | code | 985 | github-code | 50 |
472951717 | #!/usr/bin/env python3
import json
import logging
import os
import subprocess
import shutil
import sys
from tarfile import TarFile
from time import sleep
import yaml
import docker
log_filename = "ar_inference_entry.log"
logging.basicConfig(
handlers=[logging.FileHandler(log_filename, mode="w"), logging.Stream... | openem-team/openem | scripts/tator/ar_inference_entry.py | ar_inference_entry.py | py | 3,281 | python | en | code | 11 | github-code | 50 |
24693899978 | import numpy as np #for feature extraction
import pandas as pd #for storing data
import matplotlib.pyplot as plt #for visualizing data
from datetime import datetime, timedelta #for timestamp storage
from scipy.fftpack import... | mekroesche/Senior-Design | Main.py | Main.py | py | 21,847 | python | en | code | 0 | github-code | 50 |
25680441335 | import unittest
from abc import ABC
from dataclasses import dataclass, is_dataclass
from __seedwork.domain.entities import Entity
from __seedwork.domain.value_objects import UniqueEntityId
@dataclass(frozen=True, kw_only=True)
class StubEntity(Entity):
prop1: str
prop2: str
class TestEntityUnit(unittest.Te... | andremagui/micro-admin-videos-python | src/__seedwork/tests/unit/domain/test_unit_entities.py | test_unit_entities.py | py | 1,766 | python | en | code | 0 | github-code | 50 |
26379844030 | # https://www.acmicpc.net/problem/7512
'''
1. 아이디어 :
1) (시간초과)에라토스테네스의 체로 소수를 구한다.
해시맵을 만들어서 연속돼는 n의 합을 슬라이딩 윈도우로 구하고,
소수인지 확인한다음, 해시맵에 넣는다. value가 m인 첫번째 key를 출력한다.
2) (틀림) 에라토스테네스의 체를 너무 많이 연산했더니 시간초과가 난다. 각 n에 대해 1000가지만 셋에 저장해봤다.
3) 1000이상으로 가면 시간초과, 그 이하는 답이 안나온다.
다른 방법으로 에라토스테네스의 체로 소수를 1... | 724thomas/CodingChallenge_Python | baekjoon/7512.py | 7512.py | py | 3,638 | python | ko | code | 0 | github-code | 50 |
74639911515 | """
To run flow:
python timeslice_cluster_network_flow.py run --lib_network_name "G_library.pickle" --lib_time "G_timeslices.pickle" --time_interval 10 --min_time 1945 --n_top 3
"""
from metaflow import FlowSpec, step, project, Parameter, S3, pip
import json
import pickle
@project(name="pec_library")
class TimesliceC... | nestauk/pec-library | pec_library/pipeline/timeslice_cluster_network_flow.py | timeslice_cluster_network_flow.py | py | 5,120 | python | en | code | 0 | github-code | 50 |
10410594388 | import os
import sys
import shutil
import tempfile
import argparse
from rgitools import funcs
def run(input_dir, output_file):
"""Zips an RGI directory and makes it look like a real one.
Parameters
----------
input_dir : str
path to the RGI directory
output_file : str
path to the... | GLIMS-RGI/rgitools | rgitools/cli/zip_rgi_dir.py | zip_rgi_dir.py | py | 1,800 | python | en | code | 14 | github-code | 50 |
23216568117 | from typing import List, Mapping
from pyspark import sql
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
from pyspark.sql.types import StringType, StructField, StructType
def get_null_perc(spark: SparkSession, df: sql.DataFrame, null_cols: List[str]) -> sql.DataFrame:
"""Get null/empt... | vsocrates/ed-pipeline | src/ed_pipeline/qc/quality_checks.py | quality_checks.py | py | 4,349 | python | en | code | 1 | github-code | 50 |
71786695514 | def solution(commands):
answer = []
arr = ["EMPTY" for _ in range(2500)]
parent = list(range(2500))
for cmd in commands:
c, *a = cmd.split()
if c == "UPDATE":
# 병합된 상태일수 있으니 참조하는 부분을 찾고 그 부분에 업데이트 한다.
if len(a) == 3:
target = parent[(int(a[0])... | JH-TT/Coding_Practice | Programmers/Implementation_P/150366.py | 150366.py | py | 3,676 | python | ko | code | 0 | github-code | 50 |
40629548752 | #coding = 'utf-8'
'''
模块功能:爬虫主模块,实现爬虫配置功能,爬虫GUI
作者:Li Yu
创建时间:2019/05/02
创建地点:武汉大学,湖北,武汉
作者邮箱:2014301610173@whu.edu.cn
'''
from tkinter import *
from tkinter import ttk,Listbox
from tkinter.ttk import *
from dbopr import *
from spider import *
from visualization import *
import os
from datetime import *
# 配置类
class C... | ly15927086342/qqzoneSpider | __init__.py | __init__.py | py | 11,459 | python | en | code | 6 | github-code | 50 |
14602816900 | """Add deleted flag to materials
Revision ID: 023d07fbeaf2
Revises: 9a69c04ab912
Create Date: 2019-12-15 00:54:19.931299
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '023d07fbeaf2'
down_revision = '9a69c04ab912'
branch_labels = None
depends_on = None
def u... | AnvarGaliullin/LSP | migrations/versions/023d07fbeaf2_add_deleted_flag_to_materials.py | 023d07fbeaf2_add_deleted_flag_to_materials.py | py | 688 | python | en | code | 0 | github-code | 50 |
70523627035 | import gettext
import logging
import os
import sys
import osol_install.auto_install.ai_smf_service as aismf
import osol_install.auto_install.create_client as create_client
import osol_install.auto_install.client_control as clientctrl
import osol_install.auto_install.service as svc
import osol_install.auto_install.serv... | aszeszo/caiman | usr/src/cmd/installadm/set_service.py | set_service.py | py | 9,634 | python | en | code | 3 | github-code | 50 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.