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
30905711413
import pygame from settings import Settings from beatmap import Beatmap from note import Note from lane import Lane class Rhythm: def __init__(self, beatmap, resolution=(1280, 2000)): pygame.mixer.pre_init(44100, -16, 2, 2048) pygame.init() pygame.mixer.init() pygame.font.init() ...
zkxjzmswkwl/osu-mania-but-worse
main.py
main.py
py
3,019
python
en
code
0
github-code
13
71004552977
import argparse import importlib import logging import os import types from dataclasses import dataclass from typing import Tuple import numpy as np import pandas as pd import torch import torch.nn as nn import torch.utils.data as data_utils from tqdm import tqdm from transformers import HerbertTokenizer, RobertaModel...
Kacprate/Intent-classification-Polish-language
test.py
test.py
py
4,862
python
en
code
0
github-code
13
17755401630
import atexit import time import requests from requests.auth import HTTPBasicAuth from .queues import _get_queue from ..connection import get_connection from ..utils import pprint, get_config def publish_message(credentials: HTTPBasicAuth, uri: str, vhost: str, exchange: str, routing_key: str, message: str, output:...
brianou7/rabbitmqcli
rabbitmqcli/modules/exchanges.py
exchanges.py
py
1,855
python
en
code
0
github-code
13
73603481296
class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ idx = [-1] * 256 length = 0 i = 0 for j in range(len(s)): i = max(i, idx[ord(s[j])] + 1) length = max(length, j - i + 1) ...
BenjaminAnding/leetcodesolutions
Medium/LongestSubstringWithoutRepeatingCharacters/LongestSubstringWithoutRepeatingCharacters.py
LongestSubstringWithoutRepeatingCharacters.py
py
362
python
en
code
0
github-code
13
10976822103
# -*- coding: utf-8 -*- """ Created on Tue May 26 14:41:28 2020 @author: luist """ import numpy.random as rng import numpy as np import keras from sklearn.linear_model import LinearRegression from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier from skle...
larngroup/One_Shot_Siamese_Net_Drug_Discovery
Validate_models.py
Validate_models.py
py
5,517
python
en
code
2
github-code
13
38720252962
import os import sys import numpy as np ignore_attrs=['True Label','CHR','Nuc-Pos','REF-Nuc','ALT-Nuc','Ensembl-Gene-ID','Uniprot-Accession'] #id_names=["Ensembl_geneid","Uniprot_id_Polyphen2"] #id_names_prefix=["ENSMNL","Uniprot_id_Polyphen2"] label_name="True Label" def is_nan_symbol(el): return el=="" or el=="-"...
clinfo/PathoGN
script/03totable.py
03totable.py
py
1,801
python
en
code
1
github-code
13
26068889668
n = int(input()) array = [-1 for i in range(n)] oper = [] tmp = input().split() while tmp[0] != 'S' : oper.append(tmp) tmp = input().split() def is_connected(oper1, oper2, array): if Counter(array)[-1] == 0: return 'yes' father1 = oper1 while array[father1] != -1: father1 = array[fa...
piglaker/PTA_ZJU_mooc
src13.py
src13.py
py
1,490
python
en
code
0
github-code
13
7147556099
import OpenGL.GL as gl class Texture(object): def __init__(self, data=None, width=None, height=None, filt=gl.GL_NEAREST, dtype=gl.GL_UNSIGNED_BYTE): """ Texture object. If data is None an empty texture will be created """ self._data = data # format of ...
ElsevierSoftwareX/SOFTX_2018_174
fieldanimation/texture.py
texture.py
py
2,453
python
en
code
1
github-code
13
34141176062
import pandas as pd import numpy as np import tensorflow as tf from biom import load_table from tensorflow import keras from keras.layers import MultiHeadAttention, LayerNormalization, Dropout, Layer from keras.layers import Embedding, Input, GlobalAveragePooling1D, Dense from keras.models import Sequential, Model BAT...
kwcantrell/scale-16s
transformer-util.py
transformer-util.py
py
2,166
python
en
code
0
github-code
13
39871266214
"""Integration tests for the kingpin.actors.support.api module""" from nose.plugins.attrib import attr from tornado import testing from tornado import httpclient from kingpin.actors import exceptions from kingpin.actors.support import api __author__ = 'Matt Wise <matt@nextdoor.com>' HTTPBIN = { 'path': '/', ...
smmorneau/kingpin
kingpin/actors/support/test/integration_api.py
integration_api.py
py
5,538
python
en
code
null
github-code
13
28303152448
import json from tqdm import tqdm import concurrent.futures from costante_gral import URL_BASE, RUTA_BUSQUEDA, RUTA_DATOS, RUTA_INFORMES from funciones.api import consumir_api from funciones.csv_funciones import guardar_csv from funciones.json_funciones import leer_json, guardar_json from funciones.parses import parse_...
leosant027/proyecto_hiper
funciones/producto.py
producto.py
py
2,439
python
es
code
0
github-code
13
30880992898
def raizCuadradaEnt (numero): valor=0 if (numero ==0): return numero i=1 while(i*i <= numero): ## complejidad O(log N) i*=2 #voy multiplicando por 2 valor= busquedaBinaria(numero,i//2,i) #cuando me pase, llamo a la busqueda. ## uso // pues quiero un resultado entero, sino tendria que c...
eduardost/p3
raizCuadradaEnt.py
raizCuadradaEnt.py
py
826
python
es
code
0
github-code
13
17054446894
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.DiscountInfos import DiscountInfos from alipay.aop.api.domain.DishList import DishList from alipay.aop.api.domain.OtherAmountInfos import OtherAmountInfos from alipay.aop.api.domain...
alipay/alipay-sdk-python-all
alipay/aop/api/domain/KoubeiCateringOrderSyncModel.py
KoubeiCateringOrderSyncModel.py
py
20,534
python
en
code
241
github-code
13
17015102955
from collections import defaultdict from typing import DefaultDict, List, Tuple from queue import Queue def bfs(graph: DefaultDict[int, List[int]], num_nodes: int) -> List[int]: result = [] seen = defaultdict(bool) q = Queue() q.put(0) seen[0] = True while not q.empty(): node_id = ...
chrisjdavie/interview_practice
geeksforgeeks/graph/bfs/iterative/run.py
run.py
py
776
python
en
code
0
github-code
13
26783638804
""" One-time migration script from sqlalchemy models and sqlite database to custom ORM & PostgreSQL. Not designed to work as part of the regular alembic system, merely placed here for archive purposes. Should never need to run this again. 2021-05-03 """ from datetime import datetime, timedelta import sqlite3 from d...
r-anime/modbot
scripts/frontpage_sqlite_migration.py
frontpage_sqlite_migration.py
py
4,011
python
en
code
3
github-code
13
36461137075
from csv import reader if __name__ == '__main__': with open('prog1.csv', 'r') as emp_obj: # pass the file object to reader() to get the reader object csv_emp = reader(emp_obj) my_dict = {} header = next(csv_emp) if header != None: list = [] for row in csv...
Anushadsilva/python_practice
dictionary/csv_read2.py
csv_read2.py
py
1,435
python
en
code
0
github-code
13
26348800393
# Calculate the multiplication and sum of two numbers # Given two integer numbers return their product only if the product is equal to or lower than 1000, else return their sum. number1 = int(input("Give the first number \n")) number2 = int(input("Give the Second number")) result = number1 * number2 if result <= 1000: ...
suniledupuganti/Python_Basics
Exercise1.py
Exercise1.py
py
475
python
en
code
0
github-code
13
29581534605
from helpers.mock_data import gen_array from search import linear_search, binary_search, exponential_search, interpolation_search from sort import quick_sort def test_linear_search(): array = gen_array(length=10) item = linear_search(array=array, element=array[5]) assert item == 5, item def test_binary_...
LANneeer/algorithms
test/test_search.py
test_search.py
py
1,071
python
en
code
0
github-code
13
39230222973
import os import subprocess import sys import tempfile from lxml import etree log = sys.stderr.write trans = {i: i + "_" for i in ("node", "graph", "subgraph", "edge")} def dotgraph(xml_, output=None, links_only=False, title=""): dot = makedot(xml_, links_only=links_only, title=title) if output: w...
tbnorth/dml
dml/dotgraph.py
dotgraph.py
py
5,155
python
en
code
0
github-code
13
38020634878
from AthenaCommon.Logging import logging logConfigDigitization = logging.getLogger( 'ConfigDigitization' ) #check job configuration from Digitization.DigiConfigCheckers import checkDetFlagConfiguration checkDetFlagConfiguration() #Pool input from AthenaCommon.AppMgr import ServiceMgr if not hasattr(ServiceMgr, 'Even...
rushioda/PIXELVALID_athena
athena/Simulation/Digitization/share/ConfigDigitization.py
ConfigDigitization.py
py
6,099
python
en
code
1
github-code
13
39255234691
ROCK = 0 PAPER = 1 SCISSORS = 3 type_score = [1, 2, 3] LOST = 0 DRAW = 1 WON = 2 win_score = [0, 3, 6] hands = {'A' : 0, 'B' : 1, 'C' : 2, 'X' : 0, 'Y' : 1, 'Z' : 2} win_values = [-2, 1] win_hands = {'A': 'Y', 'B': 'Z', 'C': 'X'} lose_hands = {'A': 'Z', 'B': 'X', 'C': 'Y'} def win(you, me): if you == me: ...
orikam/advantcoding_2022
day2/d2q1.py
d2q1.py
py
948
python
en
code
0
github-code
13
11900178154
import numpy as np import tensorflow as tf import os from dataloader import DataLoader import utils from Networks.imagenet_traintest import TrainTestHelper import argparse def train(dataloader, trainer, validator, batches, max_iteration, print_freq): np.random.seed(1234) tf.random.set_seed(1234) tra...
LotanLevy/ImageNetFineTuning
imagenet_fine_tuning.py
imagenet_fine_tuning.py
py
3,972
python
en
code
0
github-code
13
21263885236
from operator import attrgetter class Business(object): def __init__(self, chain_name, location, id): self.chain_name = chain_name self.location = location self.id = id class Chain(object): def __init__(self, chain_name, frequency): self.chain_name = chain_name self.f...
sundaycat/Leetcode-Practice
legacy/Interview Preparation/BusinessChain.py
BusinessChain.py
py
4,457
python
en
code
0
github-code
13
21094385541
from ipdb import set_trace from os import system from pprint import pp from helpers import term_wrap, star_line, center_string_stars # ! BIG O NOTATION # * TIME COMPLEXITY class ConstantTime(): # O(1) def first_func(self): # TOTAL OPS => O(6) x = 1 # O(1) y = 2 # O(1) ...
rothberry/west-050123-live
4-phase/06-big-o/lib/big_o.py
big_o.py
py
4,333
python
en
code
0
github-code
13
25141396493
import re from flask import json from tools.datetime_convertations import DateTime from tools.for_db.work_with_booking_info import query_booking_info_by_id from tools.for_db.work_with_links import add_link from tools.for_db.work_with_slots import add_slot_and_get_id start = '2021-10-07T15:00:56.273Z' end = '2021-10-...
meetingbook/meetingbook
backend/tests/test_guest_calendars.py
test_guest_calendars.py
py
4,413
python
en
code
3
github-code
13
35224837284
import cv2 import torch from detectron2.engine import DefaultPredictor from detectron2 import model_zoo from detectron2.config import get_cfg cfg = get_cfg() cfg.MODEL.DEVICE = 'cpu' cfg.merge_from_file( model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml"), ) cfg.DATALOADER.NUM_WORKERS...
vinaykudari/car-health-score
api/helper.py
helper.py
py
1,672
python
en
code
0
github-code
13
9350585295
#!/usr/bin/python3 from fontParts.world import * import sys # Open UFO ufo = sys.argv[1] font = OpenFont(ufo) print(f'Kern virama in {ufo}') # Modify UFO kern = int(sys.argv[2]) virama = font['virama'] # virama.leftMargin += kern for contour in virama.contours: for point in contour.points: if point.x < 0...
nlci/knda-font-badami
tools/kern_virama.py
kern_virama.py
py
573
python
en
code
3
github-code
13
72732857939
from rivertopo.burning import burn_lines from osgeo import gdal, ogr import argparse import logging import numpy as np # Entry point for use in setup.py def main(): argument_parser = argparse.ArgumentParser() argument_parser.add_argument('lines', type=str, help='linestring features with DEM-sampled Z') ar...
SDFIdk/rivertopo
rivertopo/burn_line_z.py
burn_line_z.py
py
2,534
python
en
code
3
github-code
13
14791914603
import random def create_deck(): deck = [] for i in range(2, 11): for e in ('C', 'P', 'B', 'X'): deck.append(str(i)+e) for i in ('V', 'D', 'K', 'T'): for e in ('C', 'P', 'B', 'X'): deck.append(i+e) return deck def start(deck): hand = [] for i in range(2):...
Anakkobitskaya/Anak
jed.py
jed.py
py
503
python
en
code
0
github-code
13
39403268082
"""Matcha repository - search and recommend""" from datetime import date from databases.interfaces import Record from backend.models import models_enums, models_matcha, models_user from backend.repositories import (BaseAsyncRepository, postgres_reconnect, repo_interfaces) from backe...
LsHanaha/matcha
backend/repositories/repo_matcha.py
repo_matcha.py
py
9,000
python
en
code
2
github-code
13
2968899230
import pyglet.gl as GL from numpy.random import randint class Pipe(): def __init__(self, x, size, height): """Class that defines a pair of pipes, top and bottom.""" self.x, self.height, self.size = x, height, size self.spacing = randint(low=2*self.size, high=4*self.size) self.veloc...
israelcamp/GeneticAlgorithms
FlappyPacman/pipe.py
pipe.py
py
1,204
python
en
code
0
github-code
13
689794044
######################################################## # Rename new names in MCWeightDict to old one # # If you want to use old names in I3MCWeightDict, # add this module just before your hdfwriter (or rootwriter) # from icecube import icetray, dataclasses import math class fill_old_weights(icetray.I3ConditionalMo...
wardVD/IceSimV05
src/neutrino-generator/resources/examples/fill_old_weights.py
fill_old_weights.py
py
1,625
python
en
code
1
github-code
13
71685105619
import math class Item: def __init__(self, image, x, y): self.image = image self.x = x self.y = y self.size = (image.get_height()+image.get_width())/2 def collides(self, other): if math.sqrt((self.x-other.x)*(self.x-other.x)+ \ (self.y-other.y)*(self.y-other.y...
JoePrezioso/NeuroPi
neuropi/objects.py
objects.py
py
394
python
en
code
12
github-code
13
10313430445
import pandas as pd customers = pd.read_csv("noahs-customers.csv") products = pd.read_csv("noahs-products.csv") # they bought the same thing at the same time, except diff colours orders = pd.read_csv("noahs-orders.csv") orders_items = pd.read_csv("noahs-orders_items.csv") # only items in-store orders = orders[orders...
wolframalexa/HanukkahOfData
day7.py
day7.py
py
1,850
python
en
code
1
github-code
13
24991415636
# A complication by Ben # Since this isn't timed, I'll put in comments. import sys l = [list(map(int, s.strip())) for s in sys.stdin] # the initial world def step(old): new = [[i + 1 for i in x] for x in old] extinct = set() # extinction set--positions that have already flashed nxt, fla = doflashes(new, ...
Grissess/aoc2021
day11c.py
day11c.py
py
2,296
python
en
code
0
github-code
13
19351970326
#! /usr/bin/env python import argparse from collections import defaultdict from tools import templates from tools.experiment_parser import parse_all from tools.table_generator import format_table SEPARATE_EF = True def kmer_to_read_coverage(c, k, read_length=100): if c is not None: return c * read_lengt...
mhozza/covest
tools/experiment_table.py
experiment_table.py
py
4,557
python
en
code
5
github-code
13
9678999510
#!/usr/bin/env python # coding: utf-8 # In[39]: import numpy as np # import time as time # In[40]: def Rdecomp (MD, OD): alpha=np.ones(len(MD)) beta=np.ones(len(OD)) alpha[0]=(MD[0])**0.5 # tic=time.time() for i in range(len(OD)): beta[i]= OD[i]/alpha[i] alpha[i+1] = (MD[i+1]-...
MobinaSedaghat/Exercises
Alliance/Assignment 1, Exercise 3, Part 7&8- Efficient Version.py
Assignment 1, Exercise 3, Part 7&8- Efficient Version.py
py
1,032
python
en
code
0
github-code
13
35219274365
import time import numpy as np import cupy as cp from cupy.cuda import Device from cupy.cuda.runtime import getDeviceCount from ..common import _start, _finish # 計測開始 def start(method_name: str = '', k: int = None) -> float: _start(method_name, k) return time.perf_counter() # 計測終了 def finish(start_time: f...
5enxia/parallel-krylov
v3/gpu/common.py
common.py
py
3,653
python
en
code
1
github-code
13
10155745334
from collections import defaultdict import itertools class determinizeAFND: def __init__(self, pTokens): self.NameFile = 'tokens.txt' #ptokens self.states = 0 self.done = False self.automaton = defaultdict(list) self.mapGramatic = {} self.symbols = list() se...
Ivairpuerari/Compiladores
Afnd.py
Afnd.py
py
14,129
python
en
code
0
github-code
13
11097993345
year_tax = int(input()) tennis_racquets = int(input()) sneaker_pairs = int(input()) sneakers = year_tax / 6 tracksuit = sneaker_pairs * 0.80 basketball = tracksuit * 1/4 accessories = basketball * 1/5 total = year_tax + sneakers + tracksuit + basketball + accessories price_djokovic = total / 8 sponsor = total * 7/8 ...
tanchevtony/SoftUni_Python_basic
More exercises/exam 9-10 march 2019/01 basketball equipment.py
01 basketball equipment.py
py
425
python
en
code
0
github-code
13
30138442802
from tests.base import ApiDBTestCase from zou.app.utils import fields from zou.app.models.project import Project class ProjectTestCase(ApiDBTestCase): def setUp(self): super(ProjectTestCase, self).setUp() self.generate_fixture_project_status() self.generate_fixture_project() self....
cgwire/zou
tests/models/test_project.py
test_project.py
py
3,215
python
en
code
152
github-code
13
72545240659
# create by fanfan on 2018/8/15 0015 import os from glob import glob import numpy as np from scipy.misc import imread import tensorflow as tf import math from tensorflow.contrib.layers import conv2d as conv2d_1 from tensorflow.contrib.layers import conv2d_transpose from tensorflow.contrib.layers import fully_connected...
fanfanfeng/nlp_research
GAN/cartoon/dcgan1.py
dcgan1.py
py
27,183
python
en
code
8
github-code
13
33817370006
import os, stat #-------------# # Import Vars # #-------------# Import('*') #---------# # Sources # #---------# src = [] for root, dirs, files in os.walk("."): if root.find('.svn') == -1: for file in [f for f in files if not f.endswith('~')]: src.append(os.path.join(root, file)) install = env.Insta...
vtereshkov/vdrift-data-short
data/SConscript
SConscript
1,159
python
en
code
0
github-code
13
71685850579
import json import logging import time import flask import flask_cors import numpy as np import podsearch import scann import transformers log = logging.getLogger(__name__) search_fn = None def load_search_fn(): global search_fn if search_fn is not None: return load_search_fn_in_progress = Tru...
joepatmckenna/podsearch
py/podsearch/services/search_v1.py
search_v1.py
py
1,931
python
en
code
0
github-code
13
70149606738
import csv import logging from dataclasses import dataclass from pathlib import Path from PIL import Image from tqdm import tqdm logging.basicConfig(filename='ViVQA_sanity_check.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s') logger = logging.getLogger() l...
dinhanhx/VL-datasets
vivqa_data.py
vivqa_data.py
py
4,461
python
en
code
1
github-code
13
23989928630
import torch DEFAULT_DEVICE = 'cuda:0' if torch.cuda.is_available() else 'cpu' from durbango.nb_utils import is_iterable def num_parameters(module, only_trainable: bool = False) -> int: """ Get number of (optionally, trainable) parameters in the module. """ params = filter(lambda x: x.requires_grad, mo...
sshleifer/durbango
durbango/torch_utils.py
torch_utils.py
py
5,385
python
en
code
3
github-code
13
17537756502
import networkx as nx from cdlib import algorithms, evaluation, NodeClustering, TemporalClustering # communities number to be taken from louvain to be used in temporal clustering communities_number = 5 # score to be taken in consideration, starting from the value set score_lower_limit = 0.5 def get_communities(netwo...
FilipeHenrique/DNMV-Dynamic-Networks-Modeling-and-Visualization
pipeline/report.py
report.py
py
3,628
python
en
code
0
github-code
13
24268074446
import pandas as pd import numpy as np from settings import perch_config,rsna_config,chestray_config,label_var,path_var,label_sep import json import os class Dataset: def __init__(self,train_csv,test_csv=None,multilabel=False): self.train_csv=train_csv self.test_csv=test_csv self.train=pd....
pmwaniki/perch-analysis
data/datasets.py
datasets.py
py
2,575
python
en
code
0
github-code
13
29784234280
from model.contact import New_contact import re class ContactHelper: def __init__(self, app): self.app = app def open_home_page(self): wd = self.app.wd if not (wd.current_url == "http://localhost/addressbook/" and len(wd.find_elements_by_name("add")) > 0): wd.find_element_...
TheMastere/PDT_training_b14
fixture/contact.py
contact.py
py
9,362
python
en
code
0
github-code
13
41633657269
""" This file is part of nand2tetris, as taught in The Hebrew University, and was written by Aviv Yaish. It is an extension to the specifications given [here](https://www.nand2tetris.org) (Shimon Schocken and Noam Nisan, 2017), as allowed by the Creative Common Attribution-NonCommercial-ShareAlike 3.0 Unported [License...
xrahoo/nand2tetris-python
10/compilation_engine.py
compilation_engine.py
py
15,493
python
en
code
6
github-code
13
34785463338
from rct229.rulesets.ashrae9012019.data.schema_enums import schema_enums from rct229.utils.jsonpath_utils import find_all, find_one from rct229.utils.utility_functions import find_exactly_one_hvac_system EXTERNAL_FLUID_SOURCE = schema_enums["ExternalFluidSourceOptions"] def is_hvac_sys_fluid_loop_purchased_heating(r...
pnnl/ruleset-checking-tool
rct229/rulesets/ashrae9012019/ruleset_functions/baseline_systems/baseline_hvac_sub_functions/is_hvac_sys_fluid_loop_purchased_heating.py
is_hvac_sys_fluid_loop_purchased_heating.py
py
1,640
python
en
code
6
github-code
13
17079770464
# -*- coding: utf-8 -*- from odoo import models, fields, api class Courses_course(models.Model): _name = 'courses.course' _description = 'Courses' name = fields.Char('Title', required=True) professor = fields.Char('Professor', required=True) price = fields.Float('Price', required=True) date_i...
jdolz/Courses_app_Odoo
models/courses_app.py
courses_app.py
py
807
python
en
code
0
github-code
13
8097424777
import cv2 def create_dir(_dir) -> str: """ Create directory if it doesn't exist Args: _dir: str """ import os if not os.path.exists(_dir): os.makedirs(_dir) return _dir def create_video_writer(video_path, output_path, fps=None) -> cv2.VideoWriter: """ This func...
akashAD98/autoflip_py_yolo
utils.py
utils.py
py
1,024
python
en
code
1
github-code
13
27710475620
#!/usr/bin/env python # Author: Guillaume VIDOT # # This file is licensed under the license found in the # LICENSE file in the root directory of this source tree. import re import argparse import numpy as np import logging import pickle from learner.attack_gradient_descent_learner import AttackGradientDescentLearner f...
paulviallard/NeurIPS21-PB-Robustness
learn_model.py
learn_model.py
py
8,922
python
en
code
4
github-code
13
5608168526
from django.http import HttpResponse from django.shortcuts import render # Create your views here. from django.template import loader from Three.models import Student, Grade def index(request): three_index = loader.get_template("three_index.html") context = { "student_name": "TOM", } # 下边用ren...
wkiii/HelloDjango
Three/views.py
views.py
py
937
python
en
code
0
github-code
13
33608340862
import random from random import randint, sample import datetime print('Добро пожаловать в казино') start = datetime.datetime.now() try: cash = int(input('Внесите вашу ставку ')) print(f'Вы внесли - {cash}') if cash <= 0: print('Не пытайтесь меня обмануть вводите нормальные деньги!') except: pri...
narmuhamedov/alexander
lesson7.1.py
lesson7.1.py
py
1,478
python
ru
code
0
github-code
13
75056464016
# Filename: q6_determine_prime.py # Author: Jason Hong # Created: 20130222 # Modified: 20120222 # Description: Program to determine whether an intger is a prime number from math import * def is_prime(n): for d in range (2, int(sqrt(n)+1)): if n % d == 0: return False return True a = 0 b =...
xJINC/cpy5python
practical03/q6_determine_prime.py
q6_determine_prime.py
py
593
python
en
code
0
github-code
13
42223805611
import datetime import logging DATE_FORMAT = '%d.%m.%Y %H:%M%p' logger = logging.getLogger() def parse_date(date: str) -> datetime.datetime: if date is None: return None date: datetime = datetime.datetime.strptime(date, DATE_FORMAT) logger.debug("parsed date:{}".format(date)) return date
alonastik/esmi
esmi/utils.py
utils.py
py
318
python
en
code
null
github-code
13
41634416046
""" negative_paren -------------- Given a file as input, treat each '(' as 1, and each ')' as -1. Print out position when the running sum becomes negative. Day 1 of the 2015 Advent of Code game! """ from __future__ import print_function import os import sys import argparse def find_neg_paren(paren_str): """ ...
briehl/advent-of-code
2015/day1/negative_paren.py
negative_paren.py
py
1,476
python
en
code
0
github-code
13
6489541743
# -*- coding: utf-8 -*- """ Created on Wed Feb 3 10:46:13 2021 This python module holds basic functions needed for data preprocessing of meteorological measurements from LoggerNet (in the form of .dat files ). The main utilities are to calculate downwelling longwave radiation from measured body temperature, to...
geovetarcentrum/climate-stations
python/utils.py
utils.py
py
14,276
python
en
code
1
github-code
13
73755488657
# Create Error Types class DuplicateError(Exception): """Raised when there is a duplicate of a node.""" pass class NodeDoesNotExist(Exception): """Raised when a node does not exist.""" pass class IDsDoNotMatch(Exception): """Raised when two IDs do not match.""" pass class EmptyTreeError(Excep...
Fyssion/PyBinaryTree
bintree/binarytree.py
binarytree.py
py
12,967
python
en
code
1
github-code
13
12329900278
# # @lc app=leetcode.cn id=71 lang=python # # [71] 简化路径 # # @lc code=start class Solution(object): def simplifyPath(self, path): """ :type path: str :rtype: str """ item_list = path.split("/") stack = [] for item in item_list: if len(item) == 0: ...
Llunch4w/leetcode-cn
71.简化路径.py
71.简化路径.py
py
607
python
en
code
0
github-code
13
24769990971
# context checking # "r" will put return at new line, and reversed othervise # custom command execution # "rs" will result re.search plus inserting "import" at beginning # call from snippet palette for element in set: _process(element)
shagabutdinov/sublime-snippet-caller
demo/demo.py
demo.py
py
241
python
en
code
6
github-code
13
133402702
import math def floyd(n: int) -> int: def simple_trial_div(n: int) -> int: small_primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47) return next((prime_number for prime_number in small_primes if n % prime_number == 0), n) def gcd(a: int, b: int) -> int: wh...
whitearmorq/lab1_ivanilov
factorize.py
factorize.py
py
1,139
python
en
code
0
github-code
13
74667626897
import streamlit as st import pandas as pd formatacao_colunas={ "operadora": st.column_config.SelectboxColumn( "Operadora", help="Operadora: 0=Nenhuma 1=Claro 2=BR-Digital", width="small", required=True, default="0", options=[ "0", ...
danielcancelier/deslig
grid.py
grid.py
py
1,793
python
en
code
0
github-code
13
37787161906
def merge_sort(numbers_list): # Checking that the length of the (split) list is grater than 1 if len(numbers_list) > 1: # Calculate the middle point t = len(numbers_list) // 2 # Dividing the list of numbers, recursively pass it to merge_sort and making it iterable # Instead of us...
lmartinez7/masters
module_i/assignments/fucking sorting thing/fucksort2.py
fucksort2.py
py
1,533
python
en
code
0
github-code
13
35834259559
import numpy as np import matplotlib.pyplot as plt from genome_plot import CircosObject import argparse def parse_nodes(nodes_fn): nodes = [] for line in open(nodes_fn,"r"): fields = line.strip().split("\t") name = fields[0] length = float(fields[1]) try: co...
kylessmith/python_circos
python_circos/python_circos.py
python_circos.py
py
1,643
python
en
code
1
github-code
13
20182534822
import random from pygame import image, Color from random import randint from math import sqrt moveimage = image.load('images/move_map.png') dotimage = image.load('images/dot_map.png') #(x,y),(index to move) -> miejsca na mapie do których duszki mogą się przenieś map_point=[((35,100),(1,6)), ((130,100),(0...
hadesto92/CursGame-Python
gold_pacman/map.py
map.py
py
5,890
python
en
code
0
github-code
13
24724731536
from os import system import alminer import pandas as pd from astroquery.alma import Alma from astropy.io import fits import numpy as np import os # Below license is for ALminer since we have modified some code from there """ MIT License Copyright (c) 2021 Aida Ahmadi , Alvaro Hacar Permission is hereby granted , fr...
nkatshiba/Alma-bachelor-project
alma-classifier/alma_classifier/data_acquisition/alminer_mod.py
alminer_mod.py
py
10,072
python
en
code
0
github-code
13
14275574486
import bpy import bmesh import math from . import object_manager from . import settings_manager def set_normals_to_outside(context, objects, only_recalculate_if_flagged = True): ''' Set normals of objects so that they point outside of the mesh (convex direction). Set normals is an issue with planes, ...
Tilapiatsu/blender-custom_config
scripts/addon_library/local/BystedtsBlenderBaker/mesh_manager.py
mesh_manager.py
py
5,907
python
en
code
5
github-code
13
42904322000
import cv2 from object_detector import * import numpy as np import pyrebase config={ "apiKey": "AIzaSyC89FK4pNLaftno-VAKpCPJVQxIKDi7ung", "authDomain": "pythondbtest-8bff7.firebaseapp.com", "databaseURL": "https://pythondbtest-8bff7-default-rtdb.firebaseio.com", "databseURL":"https://pythondbt...
roysonLobo/fishSizeAndWeight
measure_object_size.py
measure_object_size.py
py
2,840
python
en
code
0
github-code
13
37882382440
from collections import defaultdict, deque read = lambda: int(input()) readline = lambda: list(map(int, input().split())) APPLE = 1 rotates = defaultdict(str) N = read() K = read() board = [[0] * (N + 1) for _ in range(N + 1)] for _ in range(K): r, c = readline() board[r][c] = APPLE L = read() for _ in range...
kod4284/kod-algo-note
백준/3190-뱀/solution.py
solution.py
py
1,186
python
en
code
0
github-code
13
69899904657
#!/usr/local/bin/python3 #coding: utf-8 #extrac ################################################################################################################################################################## # Created on 21 de Julho de 2021 # # Projeto base: Banco Braavos # Repositorio: Origem # Author:...
batestin1/SPARK
script/create_dataset.py
create_dataset.py
py
16,595
python
en
code
4
github-code
13
31466468712
# Given a binary tree # struct TreeLinkNode { # TreeLinkNode *left; # TreeLinkNode *right; # TreeLinkNode *next; # } # Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. # Initially, all next pointers are set to...
han8909227/leetcode
tree/sibling_pointer_lc116.py
sibling_pointer_lc116.py
py
1,569
python
en
code
3
github-code
13
39481178645
from functools import reduce def filemap(filename, func = int, sep='\n'): ''' Reads in the filename and returns a list with all the rows mapped by the function func, which defaults to int(). That is returns a list containing one integer for every row of the file with def arguments. ''' with op...
kordaniel/AoC
2020/helpers.py
helpers.py
py
1,064
python
en
code
0
github-code
13
24682455594
import numpy as np from sklearn import datasets from sklearn import metrics from sklearn import model_selection as modsel from sklearn import linear_model import matplotlib.pyplot as plt plt.style.use('ggplot') boston = datasets.load_boston() linreg = linear_model.LinearRegression() X_train, X_test, y_train, y_test ...
fw23t9/MachineLearningStudy
2.Linear regression/boston.py
boston.py
py
937
python
en
code
0
github-code
13
74436839698
from luxcena_neo import NeoBehaviour, FloatVariable, IntegerVariable, ColorVariable, BooleanVariable from time import perf_counter class Main(NeoBehaviour): def declare_variables(self): self.declare(FloatVariable("delay", 0.07, min_val=0.000001, max_val=0.5, step=0.000001)) self.declare(IntegerVar...
JakobST1n/Luxcena-Neo
NeoRuntime/builtin/strobe/script.py
script.py
py
1,418
python
en
code
0
github-code
13
18610843143
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="lorem_ipsum_auth", version="1.0", author="Adrian Dolha", packages=[], author_email="adriandolha@eyahoo.com", description="Lorem Ipsum Demo App Auth", long_description=long_descript...
adriandolha/cloud-demo
lorem-ipsum/lorem-ipsum-authentication/setup.py
setup.py
py
494
python
en
code
0
github-code
13
14799395488
from fastapi import FastAPI import uvicorn from endpoints import sql, create_er_diagram, get_schema from fastapi.middleware.cors import CORSMiddleware app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.i...
Forwall100/queryquest
backend/sqlite_query_service/main.py
main.py
py
526
python
en
code
0
github-code
13
32270420943
# -*- coding: utf-8 -*- """ Created on Fri Jan 21 11:08:14 2022 @author: sarak """ def main(): fname = ['Graham', 'Eric', 'Terry', 'Terry', 'John', 'Michael'] lname = ['Chapman', 'Idle', 'Gilliam', 'Jones', 'Cleese', 'Palin'] born = ['8 January 1941', '29 March 1943', '22 November 1940', '1 February 1942'...
sara-kassani/1000_Python_example
11_functional_programming/21_zip.py
21_zip.py
py
932
python
en
code
1
github-code
13
22991386993
""" ID: vip_1001 LANG: PYTHON3 TASK: milk """ def left(string): rs = int(string[0:string.find(" ")]) return rs def right(string): rs = int(string[string.find(" ")+1:len(string)]) return rs def takeFirst(elem): return elem[0] inputfile = open("milk.in", "r").readlines() outputfile = open("milk.out", ...
JacquesVonHamsterviel/USACO
11.milk/milk.py
milk.py
py
1,238
python
en
code
0
github-code
13
74564326738
""" _ResultSet_ A class to read in a SQLAlchemy result proxy and hold the data, such that the SQLAlchemy result sets (aka cursors) can be closed. Make this class look as much like the SQLAlchemy class to minimise the impact of adding this class. """ from builtins import object import threading class ResultSet(objec...
dmwm/WMCore
src/python/WMCore/Database/ResultSet.py
ResultSet.py
py
1,078
python
en
code
44
github-code
13
38033121966
from django.contrib import admin from django.urls import path ,include from django.conf import settings from django.conf.urls.static import static from rest_framework_simplejwt import views as jwt_views from cab_g import views urlpatterns = [ path('admin/', admin.site.urls), path('api/token/', views.MyTokenOb...
simofane4/suivi_back_1
suivi_back/urls.py
urls.py
py
5,226
python
en
code
0
github-code
13
5489289452
import matplotlib import matplotlib.pyplot as plt import numpy as np def plot_mean_val_comparisons(dict1, dict2, name1, name2, error_bar = 'std'): ''' plots a bar graph that compares the mean absolute error of two segmentation sources relative to a gold standard source inputs: dict1: dictionary sp...
kathoma/AutomaticKneeMRISegmentation
figure_utils.py
figure_utils.py
py
3,380
python
en
code
10
github-code
13
7947190875
# -*- coding:utf-8 -*- from mako import runtime, filters, cache UNDEFINED = runtime.UNDEFINED STOP_RENDERING = runtime.STOP_RENDERING __M_dict_builtin = dict __M_locals_builtin = locals _magic_number = 10 _modified_time = 1521485842.978504 _enable_loop = True _template_filename = '/Users/hollyholland/PycharmProjects/FO...
hollyh95/FOMO_sprint0
catalog/templates/.cached_templates/index.html.py
index.html.py
py
3,691
python
en
code
0
github-code
13
73474892499
# #____Results__availabe___are: # # Nodal outputs # coo = [1,2,3] x, y, z # disp = [1,2,3] dx, dy, dz # vel = [1,2,3] vx, vy, vz # Element outputs (mesh,entity) # crss = [1,2,...,n] where n=12,18,32 for bcc/fcc,hcp,bct respectively # defrate = [1,2,3,4,...
EMengiste/data_reduction_scripts
python/objects.py
objects.py
py
18,141
python
en
code
0
github-code
13
12103897129
from django.contrib import admin from .models import Araba # Register your models here. class PostAdmin(admin.ModelAdmin): list_display= ['arabaismi','ilantarihi'] search_fields=['arabaismi', 'ozellikler','ilantarihi'] class Meta: model = Araba admin.site.register(Araba, PostAdmin)
muzafferkadir/Django_Car_Dealer_Site
araba/admin.py
admin.py
py
311
python
en
code
0
github-code
13
41490352899
import configparser import pandas as pd def open_audit(audit_file): return pd.read_csv(audit_file) class ReadLogs: def __init__(self): # Read from config.ini to import our Audit log file, user and commands to alert on config = configparser.ConfigParser() config.read("/app/config.ini...
racerman300zx/audit_log
modules/auditreader.py
auditreader.py
py
1,730
python
en
code
0
github-code
13
40166133253
import main def menu(): print("Welcome to Nim Game\n") print("\n") print("****************************\n") print(" Welcome to Menu \n") print(" Please choose a Option \n") print("****************************\n") print(" 1) MinMax \n") print(" 2) Tree ...
lancal/TallerIA
TallerIA.py
TallerIA.py
py
1,644
python
en
code
0
github-code
13
37313694815
import openpyxl import os wb = openpyxl.Workbook() wb.get_sheet_names() sheet = wb.get_sheet_by_name('Sheet') sheet['A1'].value sheet['A2'] = 'Hello' os.chdir('c:\\Users\\All\\Documents') wb.save('example.xlsx')
MagsMagnoli/automate-boring-stuff-python
5_excel_spreadsheets.py
5_excel_spreadsheets.py
py
213
python
en
code
0
github-code
13
18375678051
import os from dotenv import load_dotenv import datetime import csv import openai def openai_request(): # Prompt the user for text input prompt = input("Enter your prompt: ") keyword = input("Enter your keyword: ") openai.api_key = os.getenv("OPENAI_API_KEY") response = openai.ChatCompletion.cre...
ctuguinay/AutomaticTiktok
openai_api.py
openai_api.py
py
1,842
python
en
code
0
github-code
13
35327057288
# -*- coding: utf-8 -*- # ------------------------------------------------------------------- # # --------------- Importations --------------- # # ------------------------------------------------------------------- # import torch import torch.nn as nn import torch.optim as optim from tor...
Timbar84/Projet_Spiruline_2A
pytorch_spiruline.py
pytorch_spiruline.py
py
4,998
python
en
code
0
github-code
13
16084642622
""" Author: Missy Shi Course: math 458 Date: 04/23/2020 Project: A3 - 1 Description: Write a Python function which, given n, returns a list of all the primes less than n. There should be 25 primes less than 100, for instance. Task: How many prime numbers are there which are less than 367400? """ i...
missystem/math-crypto
prime.py
prime.py
py
1,158
python
en
code
0
github-code
13
38917916659
""" Titanic prediction script """ import sys from prediction import train, predict if __name__ == "__main__": test = "data/" + sys.argv[1] model = sys.argv[2] if model not in {"glm", "rf", "gb"}: raise ValueError("Not valid option for model") model = train("data/train.csv", model) predi...
MenciusChin/Kaggle
titanic/titanic.py
titanic.py
py
336
python
en
code
1
github-code
13
36509398264
#%% import numpy import tensorflow as tf import matplotlib.pyplot as plt # Initializes arrays of values for the training session celsius = numpy.array([-40, -10, 0, 8, 15, 22, 38], dtype=float) fahrenheit = numpy.array([-40, 14, 32, 46, 59, 72, 100], dtype=float) # Initializes a simple neural network with 3 dense lay...
miquel-gb/neural-network-tests
neural_network_temp_improved.py
neural_network_temp_improved.py
py
1,622
python
en
code
1
github-code
13
33038211606
import sys from pprint import pprint sys.stdin =open("input.txt","r",encoding='UTF8') #encoding= UTF 8 필수 T = 10 for test_case in range(1, T + 1): t = int(input()) cnt = 0 str2 = input() str1 = input() A=len(str1)-len(str2) for i in range(A+1): cnt2 = 0 B=str1[i] C=str...
Seobway23/Laptop
Algorithm/february_class/0209/string array.py
string array.py
py
587
python
en
code
0
github-code
13
19737829302
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html import pymysql from mafengwoSpider.items import MafengwospiderItem, SpotItem from scrapy.utils.project import get_project_sett...
tianzhencong/scrapy_with_mafengwo
mafengwoSpider/mafengwoSpider/pipelines.py
pipelines.py
py
1,915
python
en
code
1
github-code
13
2726148255
# Simple Measure Program Execution Time 1.2 # Original Code by Udacity (https://www.udacity.com/blog/2021/09/create-a-timer-in-python-step-by-step-guide.html) import time our_list = list(range(1000000)) element = 898989 start = time.time() for el in our_list: if el == element: break end = time.time() ...
adrhmdlz/Python-timer
timer4.py
timer4.py
py
338
python
en
code
0
github-code
13
35185132781
import requests from urllib.request import urlopen from bs4 import BeautifulSoup from csv import reader import pandas as pd import csv import re from urllib.request import urlopen url = "" counter = 0 with open('topmillion.csv', newline='') as csvfile: with open('scraped_robots.txt', 'w') as file...
Destroyer7s/robot-skimmer
scraper.py
scraper.py
py
1,631
python
en
code
0
github-code
13
5339577405
import streamlit as st import pandas as pd import joblib def app(): st.title("Zomato Restaurant Rating Prediction") # Load the train.csv file train_df = pd.read_csv("artifacts/train.csv") # Get the unique values from the location column unique_locations = train_df["location"].unique() # Crea...
Nimish3011/Restaurant-Rating-Prediction
static/App.py
App.py
py
2,595
python
en
code
0
github-code
13