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
7698354657
import sqlalchemy as sa from sqlalchemy.dialects import mysql from alembic import op # revision identifiers, used by Alembic. revision = '564e4bcf092' down_revision = '1be0dd01f559' def upgrade(): """Upgrade database schema and/or data, creating a new revision.""" op.drop_index('fk_risk_objects_secondary_contac...
saalimzafar/ggrc-core
src/ggrc_risks/migrations/versions/20171020105922_564e4bcf092_remove_contact_columns.py
20171020105922_564e4bcf092_remove_contact_columns.py
py
2,394
python
en
code
null
github-code
90
17944317329
from collections import defaultdict N, M = map(int, input().split()) G = defaultdict(list) AB = [] for _ in range(M): a, b = map(int, input().split()) a, b = a, b G[a].append(b) G[b].append(a) AB.append((a, b)) # print(f'{G=}') def f(a, b): S = set([]) Q = [1] while True: Q...
Aasthaengg/IBMdataset
Python_codes/p03575/s532242670.py
s532242670.py
py
821
python
en
code
0
github-code
90
32939356334
## Intro to Reinforcement Learning Example - by Genevieve Hayes ## ## Use Q-Learning to find the optimal policy for a simple maze environment ## # Import libraries import numpy as np import mdp # Create transition and reward matrices def create_matrices(maze, reward, penalty_s, penalty_l, prob): """Create reward ...
gkhayes/maze_reinforcement_learning
intro_to_rl_example.py
intro_to_rl_example.py
py
4,073
python
en
code
13
github-code
90
21373997237
import pandas as pd """Dataframe with Bay Area segregation statistics. Courtesy of Othering and Belonging Institute (hence OBI)""" OBI_DATA = None ZILLOW_DATA = None SFZ_DATA = None SFZ_HO_DATA = None def get_obi_data(): """Load OBI data only once.""" global OBI_DATA if OBI_DATA is not None: retu...
sdamerdji/affh_letters
utils.py
utils.py
py
6,095
python
en
code
1
github-code
90
42717726983
import sys c = 0 b = '' minC=sys.argv[1] N=int(sys.argv[2]) for i in open(sys.argv[1],'r'): c += 1 if c == 1: b += i else: d = [] spl = i.strip().split('\t') for k in spl[1:]: if int(k) < minC : d.append(k) if len(d) != N :continue ...
DYqwert/ARFPOP
filtering.py
filtering.py
py
503
python
en
code
0
github-code
90
23617796330
from time import sleep def main(driver, page): driver.get(page) element = driver.find_element_by_id("button") sleep(3) element.click() sleep(3) driver.back() sleep(3) driver.forward() sleep(3)
MarioMarinDev/PythonCourse
bdd/examples/navigation.py
navigation.py
py
231
python
en
code
1
github-code
90
26034658956
import logging import sys import unittest from test_support import test_env test_env.setup_test_env() import endpoints from protorpc import message_types from protorpc import messages from protorpc import remote from components import utils from components.auth import api from components.auth import b64 from compone...
luci/luci-py
appengine/components/components/auth/endpoints_support_test.py
endpoints_support_test.py
py
7,397
python
en
code
74
github-code
90
32661299181
''' Mix and Match Adapter using recommended settings from https://arxiv.org/abs/2110.04366 ''' import logging import torch import torch.nn as nn import torch.nn.functional as F from transformers.models.t5.modeling_t5 import ( T5LayerCrossAttention, T5LayerSelfAttention, T5Block ) from transformers import P...
allenai/data-efficient-finetuning
attribution/mam.py
mam.py
py
11,152
python
en
code
27
github-code
90
30499916453
import datetime from flask_cors import cross_origin from flask_restful import Resource, request from app import db from serializers.event_schema import Event_Schema from models.event_model import Event class SingleEventAPI( Resource ): def __init__( self ): self.post_schema = Event_Schema() def ge...
sergiocanalesm1/proyecto0_cloud_computing
api/event_api.py
event_api.py
py
2,882
python
en
code
0
github-code
90
18240098883
""" WARNING: Please make sure you install the bot with `pip install -e .` in order to get all the dependencies on your Python environment. Also, if you are using PyCharm or another IDE, make sure that you use the SAME Python interpreter as your IDE. If you get an error like: ModuleNotFoundError: No module named 'bo...
Matag-e/rpaIngressos
bot.py
bot.py
py
4,378
python
en
code
0
github-code
90
17983932959
from math import factorial as f n, m = map(int, input().split()) mod = 10 ** 9 + 7 if abs(n - m) == 1: res = f(n) * f(m) print(res % mod) elif n == m: res = f(n) * f(m) * 2 print(res % mod) else: print(0)
Aasthaengg/IBMdataset
Python_codes/p03681/s646258133.py
s646258133.py
py
225
python
en
code
0
github-code
90
18562046239
import itertools n = int(input()) d = {'M':0, 'A':1, 'R':2, 'C':3, 'H':4} h = [0, 0, 0, 0, 0] for _ in range(n): name = input() if name[0] in d.keys(): h[d[name[0]]] += 1 ans = 0 for i, j, k in itertools.combinations([0, 1, 2, 3, 4], 3): ans += h[i] * h[j] * h[k] print(ans)
Aasthaengg/IBMdataset
Python_codes/p03425/s862889510.py
s862889510.py
py
286
python
en
code
0
github-code
90
32361686976
""" 8.5 Recursive Multiply Write a recursive function to multiply two positive integers without using the * operator (or / operator). You can use addition, subtraction, and bit shifting, but you should minimize the number of those operations. Solution 1 """ def min_product(a, b): if a < b: bigger = b ...
simranjmodi/cracking-the-coding-interview-in-python
chapter-08/exercise-8.5.1.py
exercise-8.5.1.py
py
761
python
en
code
0
github-code
90
5465829655
import os import xml.etree.ElementTree as ET #程序功能:批量修改VOC数据集中xml标签文件的标签名称 def changelabelname(inputpath): listdir = os.listdir(inputpath) for file in listdir: if file.endswith('xml'): file = os.path.join(inputpath,file) tree = ET.parse(file) root = tree.getroot() ...
GDzhu01/DIY-detreg-domain
voc2name.py
voc2name.py
py
1,719
python
en
code
0
github-code
90
73090192295
# Prefix Sum is a powerful algorithm to do problem 2367 of Leet code - Number of Arithmetic Triplets arr = [0, 1, 2, 3, 4, 5] res = [] for i in range(len(arr)): if i == 0: res.append(arr[i]) if i < len(arr)-1: res.append(res[i]+arr[i+1]) print(res)
devWorldDivey/mypythonprogrammingtutorials
Python Tricks/Algorithm-PrefixSum-Implementation.py
Algorithm-PrefixSum-Implementation.py
py
274
python
en
code
0
github-code
90
37950872138
import numpy as np import torch import torch.nn as nn from ObjectSegWithRL.src.pytorch_stuff import GregDataset from torch.optim import Adam from torch.utils.data import DataLoader from torchvision import transforms # from ObjectSegWithRL.src.greg_cnn import GregNet from ObjectSegWithRL.src.models.other.greg_cnn_cSigm...
ghov/ObjectSegWithRL
src/train/other/pytorch_training.py
pytorch_training.py
py
4,462
python
en
code
0
github-code
90
18487710623
from typing import List class Solution: def putMarbles(self, weights: List[int], k: int) -> int: def put_jewels_in_bags(weights, k): def dfs(start, k, score): nonlocal max_score, min_score if k == 1: max_score = max(max_score, score + weights[s...
comeonboi/algorithm-practise
loong's code/leetcode/editor/cn/6339将珠子放入背包中.py
6339将珠子放入背包中.py
py
719
python
en
code
5
github-code
90
20622637347
import os import sys from _utils import get_changelog, get_commit_log, get_project_dir, read_gradle_version if __name__ == "__main__": if len(sys.argv) < 2: print("usage: extract_changelogs.py <project dir>") exit(-1) project_dir = get_project_dir() (version_code, version_name) = read_gr...
szkolny-eu/szkolny-android
.github/utils/extract_changelogs.py
extract_changelogs.py
py
2,807
python
en
code
153
github-code
90
35469134626
##Data Exploration/Clean Up/Transformation #data manipulation libraries import pandas as pd import numpy as np import itertools as iter from scipy import stats import pickle from sklearn.preprocessing import OneHotEncoder class transform_data(object): def __init__(self,conf): self.conf=conf def encod...
kanjasaha/churn_prediction_template
machine_learning_classes/transform_data.py
transform_data.py
py
2,657
python
en
code
0
github-code
90
24632109165
from deep_translator import GoogleTranslator from terminaltables import AsciiTable from time import sleep #Option to save the translation as a file def main(): while True: try: table_data = [ ['Translate your file into:'], ['French'], ['German'],...
AC899/text-translator
main.py
main.py
py
1,000
python
en
code
0
github-code
90
40426333804
from fastapi.testclient import TestClient from gapi import gapi client = TestClient(gapi) def test_read_main(): response = client.get("/") assert response.status_code == 200 def test_predict_request(): train_x = [[1, 2, 3], [4, 5, 6]] train_y = [1, 2] x_to_predict = [[1, 1, 3], [5, 4, 3]] da...
pjpollot/gapi
tests/test_api.py
test_api.py
py
699
python
en
code
0
github-code
90
17961455319
from collections import Counter def main(): A = input() N = len(A) ans = N * (N-1) // 2 + 1 cnt = Counter(A) for c in cnt: ans -= cnt[c] * (cnt[c] - 1) // 2 print(ans) if __name__ == "__main__": main()
Aasthaengg/IBMdataset
Python_codes/p03618/s746946168.py
s746946168.py
py
241
python
en
code
0
github-code
90
5203530291
from socket import * from select import * from threading import Thread import tkinter BUFFSIZE = 1024 serverName = 'localhost' serverPort = 5050 clientSocket = socket(AF_INET, SOCK_STREAM) clientSocket.connect((serverName, serverPort)) clientSocket.send(bytes(input('Enter Username: '), 'utf8')) def r...
damoboyle/TCPServerSocket
AdvancedClient.py
AdvancedClient.py
py
1,744
python
en
code
0
github-code
90
74363762856
import csv from flask import Flask, request app = Flask(__name__) @app.route('/create_account', methods=['POST']) def create_account(): # retrieve data from the AJAX call status = request.form['status'] subjects = request.getlist['subject'] courses = request.form.getlist('courses[]') p...
Ahan132/ScholarVault
create_account.py
create_account.py
py
1,025
python
en
code
0
github-code
90
13393784208
import torch from torch import nn from torch.nn import init import torch.nn.functional as F from torch.autograd import Variable from config import * # vgg choice base = {'dss': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M']} # extend vgg choice --- follow the paper, you can ...
zhuxinang/MLMSNet
multi.py
multi.py
py
16,347
python
en
code
2
github-code
90
16619064466
#!/usr/bin/env python3 import sys, os from pandas.io.parsers import read_csv import numpy as np import pandas as pd import matplotlib.pyplot as plt import multiprocessing mycolors = ["#008941", "#FFFF00", "#1CE6FF", "#FF34FF", "#FF4A46", "#006FA6", "#A30059", "#FFDBE5", "#7A4900", "#0000A6", "#63FFAC", "#B79762", "#00...
anna-alemany/mouseGastruloids_scRNAseq_tomoseq
scRNAseq_scripts/cellcluster_annotation.py
cellcluster_annotation.py
py
4,949
python
en
code
6
github-code
90
33703219647
# 문제 : 부분 문자열 # 길이가 K인 문자열 S가 있을 때, S의 연속된 일부분을 부분 문자열이라고 한다. # 부분 문자열은 원래의 순서가 바뀌거나 중간에 있는 글자가 빠져서는 안된다. # 주어진 문자열의 부분 문자열을 사전순으로 정렬한 후, # N번째 부분 문자열의 첫 글자와 글자 수를 출력하는 프로그램을 완성하시오. # 예를 들어 abac의 부분 문자열은 사전순으로 정렬하면 다음과 같다. # a ab aba abac ac b ba bac c # 3번째 부분 문자열은 aba가 된다. # [입력] # 첫 줄에 테스트 케이스의 개수 T가 주어지고, 다음 줄부터 각 ...
kimujinu/python_PS
SW_Expert_Problem21.py
SW_Expert_Problem21.py
py
2,067
python
ko
code
0
github-code
90
42119783027
import pyqrcode as qr import cv2 as cv from pyzbar.pyzbar import decode ##barcode making url=qr.create('Test Barcode') #saving as svg url.svg('test.svg', scale=8) print(url.terminal(quiet_zone=1)) #saving as png url.png('test.png',8) barkod=cv.imread('test.png') cv.imshow('barkod',barkod) cv.waitKey(0) #decoding qrc...
Necro-U/barcodeCreater-reader
barcode.py
barcode.py
py
402
python
en
code
2
github-code
90
3733348610
import json import subprocess import shlex import os import base64 from jpapi import API, APIHandler, Endpoint from .gpt import GPT GPT_OBJ = None API_OBJ = None FAILURE_TEMPLATE = { "error": {"code": 400, "message": "Invalid input"}, "status": "fail", } RESPONSE_TEMPLATE = {"data": {"response": ""}, "status"...
eb3095/athena
athena-server/athena_server/__init__.py
__init__.py
py
6,978
python
en
code
3
github-code
90
18130459790
class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: hashmap={} for i in strs: val="".join(sorted(i)) if val not in hashmap: hashmap[val]=[] hashmap[val].append(i) ans=[val for val in hashmap.values()] return...
narendrasingodia1998/LeetCode
0049-group-anagrams/0049-group-anagrams.py
0049-group-anagrams.py
py
333
python
en
code
0
github-code
90
18530917559
# ABC098 D - Xor Sum 2 n=int(input()) a=list(map(int,input().split())) l=0 r=1 tmp=a[0] ans=0 while l<n: if r==n: ans+=(r-l) l+=1 continue if tmp+a[r]==tmp^a[r]: tmp=tmp+a[r] r+=1 else: ans+=(r-l) tmp=tmp-a[l] l+=1 print(ans)
Aasthaengg/IBMdataset
Python_codes/p03340/s302151835.py
s302151835.py
py
311
python
zh
code
0
github-code
90
29955476595
# coding=utf-8 import numpy as np import pandas as pd from wKit.stat.infer import stat_dtype def discretize(measurement, how='std', alpha=(0, 0.5, 1, 2), nbins=10, retn_bins=False): """ Parameters ---------- measurement: array-like of discrete or continuous measurement how: {'std', 'bin'}, defaul...
JHWu92/my_toolkit
wKit/ML/dprep.py
dprep.py
py
3,590
python
en
code
0
github-code
90
20876737355
from heapq import heappop, heappush, heapify def main(): count_treads, size = map(int, input().split()) h = list(map(int, input().split())) process = [] for i in range(count_treads): if not h: break process.append([h.pop(0), i]) print(i, 0) heapify(process) ...
YFatMR/Algorithms
SanDiego/course_2/week3/parallel_pocessing.py
parallel_pocessing.py
py
516
python
en
code
1
github-code
90
71582699817
import re from json import dumps from pathlib import Path from requests import get from tqdm import tqdm """ Scrape Sefaria for the Tanakh. I used this to create `tanakhbot/data/tanakh.json` You don't need to run this unless you want a different translation or if someone adds/removes a book in the Tanakh. To run th...
subalterngames/tanakhbot
scrape.py
scrape.py
py
4,068
python
en
code
0
github-code
90
31415627358
from typing import List class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: intervals = sorted(intervals, key=lambda x:x[0] ) merged = intervals[0] start = 0 end = len(merged)-1 for interval in intervals[1:]: # interval 0 ...
ktandon91/leetcode
prob_73_merge_intervals_ARRAY.py
prob_73_merge_intervals_ARRAY.py
py
1,389
python
en
code
1
github-code
90
28135194030
import bson import os def get_fullpath(): for root, dirs, files in os.walk("<PATH>"): fullpath = list() root = root + '/' for file in files: path = root + file fullpath.append(path) return fullpath def extract_bson(fullpath): for index in range(len(fullpat...
roytravel/Cybersecurity
01. Parser/parser_bson.py
parser_bson.py
py
770
python
en
code
0
github-code
90
18321137909
mod=10**9+7 x,y=map(int,input().split()) if (x+y)%3!=0: print(0) exit() a=min(x,y) b=max(x,y) if 2*a<b: print(0) exit() k=(x+y)//3 left_x=2*k left_y=k r=left_x-x def factorialmod(n,mod): ans=1 for i in range(2,n+1): ans*=i ans%=mod return ans fac_k=factorialmod(k,mod) fac_...
Aasthaengg/IBMdataset
Python_codes/p02862/s335584115.py
s335584115.py
py
433
python
en
code
0
github-code
90
23254433815
import psutil import os import requests import time from threading import Lock lock=Lock() def Singleton(cls): _instance = {} def _singleton(*args, **kargs): if cls not in _instance: _instance[cls] = cls(*args, **kargs) return _instance[cls] return _singleton # @Singleton clas...
wuchf/wda-automation
WDAserver.py
WDAserver.py
py
3,081
python
en
code
0
github-code
90
32538987498
""" A list of built in conditions to be used in contracts. Can be used by the module users and also helpful for testing. The best way to extend the module is by adding conditions and a accompaniying test. """ from functools import partial from collections import Iterable from .helpers import instance_of, all_satisfy...
wilbertom/contracts
contratos/conditions.py
conditions.py
py
1,311
python
en
code
0
github-code
90
26479369831
import cv2 import numpy as np from os import path, listdir from keras.optimizers import Adam from keras.utils import np_utils from keras.layers import ( Activation, Dropout, Convolution2D, GlobalAveragePooling2D ) from keras.models import Sequential from keras.models import load_model from keras_squeeze...
HiagoAdao/PedraPapelTesoura
pedra_papel_tesoura/classificador/pedra_papel_tesoura.py
pedra_papel_tesoura.py
py
5,511
python
pt
code
1
github-code
90
18296602419
import sys def Prime(x): for i in range(2, x): if(x%i==0): return False return True if (__name__=='__main__'): X = int(input()) i = 0 while True: if Prime(X+i): print(X+i) sys.exit() i += 1
Aasthaengg/IBMdataset
Python_codes/p02819/s926708850.py
s926708850.py
py
230
python
en
code
0
github-code
90
18149295329
str = input() lstr = list(str) num = int(input()) for i in range(num): order = input().split() if (order[0] == "print"): onum = list(map(int,order[1:3])) for i in range(onum[0],onum[1]+1): print(lstr[i],end = "") print("") elif (order[0] == "reverse"): onum =...
Aasthaengg/IBMdataset
Python_codes/p02422/s349278901.py
s349278901.py
py
888
python
en
code
0
github-code
90
32207122268
from __future__ import absolute_import from mirror.celery import celery import logging log = logging.getLogger(__name__) class ShellTask(celery.Task): def __init__(self, *args, **kwargs): self.name = 'mirror.tasks.ShellTask' def run(self, commandline): self.cmd = commandline return ...
chancez/osl-ftp
mirror/tasks.py
tasks.py
py
1,381
python
en
code
1
github-code
90
23516810962
from App.database import db class Listing(db.Model): id = db.Column(db.Integer, primary_key=True) farmerID = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=False) name = db.Column(db.String(20), nullable=False) html = db.Column(db.Text(), nullable=True) def __init__(self, farmerID, name,...
vedkm/Info2602-Project
App/models/listing.py
listing.py
py
588
python
en
code
0
github-code
90
24316902963
# coding: utf-8 import json search = u"イギリス" f = open('jawiki-country.json', 'r') #ファイルの読み込み t = open('england.txt', 'w') for line in f: data = json.loads(line) if data['title'] == search: d = json.dumps(data, ensure_ascii=False) #print d.encode('utf-8') print >> t, d.encode('utf-8') #すいません、コマンドプロンプトで文字化けさせない方...
pyonnogi/100knock
20.py
20.py
py
430
python
ja
code
0
github-code
90
70523334378
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Usage: db_prep.py -d <data> -l <label> -n <ndim> -o <outfile> Options: -h --help show this message """ def parse_args(): args = docopt(__doc__) data = args['<data>'] label = args['<label>'] ndim = int(args['<ndim>']) outfile = args['<outfile...
fpeder/mscr
bin/db_prep.py
db_prep.py
py
628
python
en
code
1
github-code
90
17208483966
#! /usr/bin/env python3 from PyQt4 import QtGui, QtCore class GridLayout(QtGui.QLayout): def __init__(self, grid=[8, 5], parent=None): super().__init__(parent) try: grid[1] self.grid= grid except TypeError: self.grid= [grid, grid] self.rows =...
luxusv/quadcopter-basestation
widgets/gridlayout.py
gridlayout.py
py
2,025
python
en
code
0
github-code
90
20907473302
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from __future__ import absolute_import import collections import unicodedata import six import pickle import nltk import numpy as np import random import re from utils i...
PaddlePaddle/Research
ST_DM/KDD2021-MSTPAC/code/MST-PAC/utils/tokenization.py
tokenization.py
py
26,446
python
en
code
1,671
github-code
90
13011301022
import datasets from sklearn.metrics import f1_score, matthews_corrcoef from .record_evaluation import evaluate as evaluate_record _CITATION = """\ @article{wang2019superglue, title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems}, author={Wang, Alex and Pruksachatkun, Yada an...
adapter-hub/efficient-task-transfer
itrain/ext/super_glue.py
super_glue.py
py
6,212
python
en
code
33
github-code
90
18470763779
#!/usr/bin/env python # coding: utf-8 # In[30]: S = list(input()) # In[31]: w_count = S.count("W") print(sum([idx for idx,x in enumerate(S) if x == "W"]) - (w_count-1)*w_count//2) # In[ ]:
Aasthaengg/IBMdataset
Python_codes/p03200/s748864895.py
s748864895.py
py
202
python
en
code
0
github-code
90
18814572527
import os import re import pytz import collections import datetime as dt from utils import LXMLMixin from openstates.utils import convert_pdf from openstates.scrape import Scraper, VoteEvent motion_re = r"(?i)On motion of .*, .*" bill_re = r"(H|S)(C|J)?(R|M|B) (\d+)" date_re = ( r"(MONDAY|TUESDAY|WEDNESDAY|THURS...
openstates/openstates-scrapers
scrapers/mo/votes.py
votes.py
py
7,398
python
en
code
820
github-code
90
15921036437
import requests import json import uuid import os from os import system system("title " + "Session ID") username = input("Username: ") password = input("Password: ") uid = str(uuid.uuid4()) coo = "" h = { 'User-Agent': 'Instagram 113.0.0.39.122 Android (24/5.0; 515dpi; 1440x2416; huawei/google; Nexus 6P; angler; a...
3zp/Session-ID
session.py
session.py
py
1,268
python
en
code
2
github-code
90
36910342405
import unittest from networkx import recursive_simple_cycles from pychoco.model import Model from pychoco.objects.graphs.directed_graph import create_directed_graph, create_complete_directed_graph class TestGraphMinOutDegree(unittest.TestCase): def test1(self): m = Model() lb = create_directed_...
chocoteam/pychoco
tests/graph_constraints/test_graph_no_circuit.py
test_graph_no_circuit.py
py
614
python
en
code
9
github-code
90
25251516719
# -*- coding: utf-8 -*- """ __author__ = 'wangdawei' __time__ = '18-4-12 上午7:14' """ from itertools import combinations import math class Solution: def largestTriangleArea(self, points): """ :type points: List[List[int]] :rtype: float """ def count_triangle_area(p1, p2, p3):...
sevenseablue/leetcode
src/leet/largest-triangle-area.py
largest-triangle-area.py
py
1,210
python
en
code
0
github-code
90
18274477169
N,K=map(int,input().split()) P=list(map(int,input().split())) probability=[] sums=[0] total=0 for i in range(N): num=0 prob=1/P[i] for j in range(1,P[i]+1): num+=j*prob probability.append(num) total+=num sums.append(total) ans=0 for j in range(N-K+1): if ans<sums[j+K]-sums[j]: ...
Aasthaengg/IBMdataset
Python_codes/p02780/s529264545.py
s529264545.py
py
377
python
en
code
0
github-code
90
27282552648
class Solution: def numPairsDivisibleBy60(self, time: List[int]) -> int: result = 0 durations = [0] * 60 for t in time: t %= 60 result += durations[(60 - t) % 60] durations[t] += 1 return result
Nayald/algorithm-portfolio
leetcode/daily challenges/2020-12/08-pairs of songs-with-total-duration-divisible-by-60.py
08-pairs of songs-with-total-duration-divisible-by-60.py
py
300
python
en
code
0
github-code
90
18441779029
from bisect import bisect_left INF = 10 ** 11 a, b, q = map(int, input().split()) s = [-INF] + [int(input()) for _ in range(a)] + [INF] t = [-INF] + [int(input()) for _ in range(b)] + [INF] x = [int(input()) for _ in range(q)] for e in x: si = bisect_left(s, e) ti = bisect_left(t, e) ans = INF for s...
Aasthaengg/IBMdataset
Python_codes/p03112/s823179344.py
s823179344.py
py
518
python
en
code
0
github-code
90
2207090870
import urllib.request as ur url = "http://www.weather.go.kr/weather/earthquake_volcano/domesticlist_download.jsp?startSize=999&endSize=999&pNo=1&startLat=999.0&endLat=999.0&startLon=999.0&endLon=999.0&lat=999.0&lon=999.0&dist=999.0&keyword=&startTm={}&endTm={}" rng = input("Input the start and end date>> ") rngs = rn...
pidokige02/Python_study
hello-master/crawl/down4.py
down4.py
py
576
python
en
code
1
github-code
90
40431783821
#!/usr/bin/env python3 import numpy as np import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.optim as optim import itertools from copy import deepcopy import sys sys.path.insert(0, '../') import optimization_lib as optim_lib import rao_blackwellization_lib as rb_lib import baselines_l...
Runjing-Liu120/RaoBlackwellizedSGD
rb_utils/tests/test_gradients.py
test_gradients.py
py
5,588
python
en
code
22
github-code
90
71499086697
# 문제 : https://leetcode.com/problems/distribute-coins-in-binary-tree/ # 시간복잡도 : O(N) # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def distributeCoins(self, root: TreeNode) -> int: ...
fpdjsns/Algorithm
leetcode/medium/979. Distribute Coins in Binary Tree.py
979. Distribute Coins in Binary Tree.py
py
761
python
en
code
11
github-code
90
40112456534
import math from dataclasses import dataclass from typing import Any, Callable, List, Optional, Tuple, Union import pytorchvideo_trainer.module.distributed_utils as du import torch import torch.nn as nn import torch.nn.functional as F from hydra.core.config_store import ConfigStore from omegaconf import MISSING from p...
facebookresearch/pytorchvideo
pytorchvideo_trainer/pytorchvideo_trainer/module/moco_v2.py
moco_v2.py
py
17,085
python
en
code
3,050
github-code
90
70349037097
from inspect import trace from navigation.utilities import query as navigation_query from navigation.utilities.transformations import transform_to_world from bots import models from navigation import models as navigation_models from navigation.utilities.level import Level from navigation.utilities.thread_pool import T...
SquarerFive/bf3-bots
AIHelper/bots/utilities/behaviour.py
behaviour.py
py
23,220
python
en
code
17
github-code
90
12692135217
import platform import numpy as np try: from PyQt6 import QtCore except: from PyQt5 import QtCore from learning_fc import safe_rescale from learning_fc.live_vis import VisBase, PlotItemWrapper as PIWrapper class PIVis(VisBase): def __init__(self, env): VisBase.__init__( self, ...
llach/learning_fc
learning_fc/live_vis/pi_vis.py
pi_vis.py
py
4,265
python
en
code
0
github-code
90
24061587149
file1 = open("query_output.txt") dic = {} try: for line in file1: line = line.strip() words = line.split(' ') if words[0] != "DocId" and words[0] != "Rank": continue if words[0] == "DocId": DocId = words[1] else: Rank = words[1] ...
BismarckDD/HihoCoder
analyze_doc.py
analyze_doc.py
py
538
python
en
code
0
github-code
90
40452182089
from django.urls import path from . import views urlpatterns=[ path('',views.index,name='index'), path('login',views.login_view,name='login'), path('logout',views.logout_view,name='logout'), path('register',views.register,name='register'), path('group/<int:groupID>',views.group,name='group'), p...
cidann/chatApp
group/urls.py
urls.py
py
663
python
en
code
0
github-code
90
31663675095
import sys class Solution: def replaceSpace(self,s): if not s: return s ss = '' for i in s: if i == ' ': ss += '%20' else: ss += i return ss if __name__ == "__main__": try: while True: line =...
wzwhit/leetcode
剑指offer/面5替换空格.py
面5替换空格.py
py
487
python
en
code
0
github-code
90
37215111407
# -*- coding: utf-8 -*- # @Time : 2019/10/16 11:02 # @Author : Deng Wenxing # @Email : dengwenxingae86@163.com # @File : binary_tree_test.py # @Software: PyCharm import sys import binary_search import tools from sort_source.decoration_source import * if sys.version_info[0] == 2: reload(sys) sys.setdef...
maketubu7/python_imooc_alg
binary_search_tree_source/binary_tree_test.py
binary_tree_test.py
py
923
python
en
code
0
github-code
90
19472242555
from django import template from geofluxus.apps.login.models import GroupDataset register = template.Library() @register.filter def datasets(user): # check all user groups groups = user.groups.values_list('id', flat=True) # retrieve datasets for these groups datasets = GroupDataset.objects.filter(gro...
geoFluxus/geofluxusApp
geofluxus/apps/login/templatetags/custom_tags.py
custom_tags.py
py
1,054
python
en
code
1
github-code
90
1544170122
''' Created on 2011-02-25 @author: iris chen ''' from TestBase1 import TestBase1 import AddCart import FunctionCommon import PublicFunctions import Mutil_Selection import Payment import unittest import time import HTMLTestRunner ### Test cases class OpenSite(TestBase1): def test010_OpenSite(self): sel ...
nirvana-info/old_bak
AutoTestingScripts/CongoWorld_iris/OpenSiteTestCases.py
OpenSiteTestCases.py
py
1,210
python
en
code
1
github-code
90
73466922856
#!/usr/bin/env python3 # -*- coding: utf-8 -*- cantidad = 0 x = 1 n = int(input("Cuantas piezas cargara: \n")) caliente = "caliente" falso = "No se una medida que se pueda contar, ingrese la otra \t" while x<=n: largo = float(input("Ingrese la medida \t \n")) if largo >= 1.2 and largo<=1.3: cantidad=can...
D1egoS4nchez/Ejercicios
Ejercicios/ejercicio31.py
ejercicio31.py
py
463
python
es
code
0
github-code
90
40591440694
# codereference =https://aetperf.github.io/2020/09/18/Logistic-regression-with-JAX.html import warnings warnings.filterwarnings("ignore", category=UserWarning) import jax.numpy as jnp from jax import grad from sklearn.datasets import load_breast_cancer from sklearn.preprocessing import StandardScaler from sklearn.mod...
rajathpatel23/ml-aglorithms
Logistic-regression/python/logistic-regression.py
logistic-regression.py
py
2,554
python
en
code
0
github-code
90
17441569700
import os import sys import numpy as np import tensorflow as tf # Allow import of top level python files import inspect currentdir = os.path.dirname( os.path.abspath(inspect.getfile(inspect.currentframe())) ) parentdir = os.path.dirname(currentdir) parentdir = os.path.dirname(parentdir) sys.path.insert(0, paren...
tensorflow/tensorrt
tftrt/benchmarking-python/tf_hub/movinet/infer.py
infer.py
py
3,690
python
en
code
717
github-code
90
26527017797
#usage --> python telnet.py replace_ip_or_host_here replace_input_port_number_here import sys import telnetlib #host=sys.argv[1] #portno=sys.argv[2] host=input("enter hostname:") portno=input("enter host number:") try: conn = telnetlib.Telnet(host,portno) response = host+' ' + portno +' - Success' except: ...
thennarasug/python-telnet-test
telnet.py
telnet.py
py
394
python
en
code
1
github-code
90
33309306656
# -*- coding: utf-8 -*- import ConfigParser import os from elasticsearch_dsl import Index, DocType, MetaField from elasticsearch_dsl.connections import connections __hosts = [] def get_hosts(): global __hosts if not __hosts: config_file = os.path.join(os.path.dirname(__file__), '../setup.cfg') ...
li-go/6spider
sixspider/elasticsearch/__init__.py
__init__.py
py
2,111
python
en
code
0
github-code
90
16601324066
import gzip import random def reservoir_sampling(se): file = gzip.open("youtube.ungraph.txt.gz", "rb") #file = open("toy_graph.txt", "r") # init the reservoir array edge_res = [None] * se # fill the reservoir array for i in range(se): contents = file.readline() from_node = con...
webel/Data-Mining
homework_3/reservoir_sampling.py
reservoir_sampling.py
py
1,121
python
en
code
0
github-code
90
42192924209
from annoy import AnnoyIndex from Mesh_Reading import * import pandas as pd from Compute_Features import compute_all_features_one_shape from Normalization import normalise_mesh_step2 from Standardise_Features import normalise_feat from Mesh_refining import refine_single_mesh from utils import * import csv """ There ar...
Saeden/MR-code
ANN.py
ANN.py
py
8,326
python
en
code
0
github-code
90
18487756353
""" <p>给定一个长度为&nbsp;<code>n</code>&nbsp;的链表&nbsp;<code>head</code></p> <p>对于列表中的每个节点,查找下一个 <strong>更大节点</strong> 的值。也就是说,对于每个节点,找到它旁边的第一个节点的值,这个节点的值 <strong>严格大于</strong> 它的值。</p> <p>返回一个整数数组 <code>answer</code> ,其中 <code>answer[i]</code> 是第 <code>i</code> 个节点( <strong>从1开始</strong> )的下一个更大的节点的值。如果第 <code>i</code> 个节...
comeonboi/algorithm-practise
loong's code/leetcode/editor/cn/[1019]链表中的下一个更大节点.py
[1019]链表中的下一个更大节点.py
py
3,222
python
en
code
5
github-code
90
37788323584
""" """ ############################################################################ # No user customization below this line ############################################################################ # Do nothing if old vcs is not loader import GPS if hasattr(GPS, "VCS"): from gps_utils import hook # Named...
AaronC98/PlaneSystem
Code/share/gps/support/core/vcs/__init__.py
__init__.py
py
5,577
python
en
code
0
github-code
90
44750436329
#! /Users/sheng/anaconda2/bin/python # -*-coding:utf-8-*- from __future__ import print_function import sys import json reload(sys) sys.setdefaultencoding('utf-8') class NFSA(object): """ NFSA 是封装好的非确定自动机,自动机的定义格式参考cow.json """ def __init__(self, path): self.path = path self.compil...
P79N6A/Summer
Python/NLP/FSA/NFSA.py
NFSA.py
py
2,359
python
en
code
0
github-code
90
18038316689
s=input()[::-1] a=["dreamer"[::-1],"eraser"[::-1],"dream"[::-1],"erase"[::-1]] st=1 en=0 while st>en: st=len(s) for m in a: if s.find(m)==0: s=s[len(m):] en=len(s) print("YES" if s=="" else "NO")
Aasthaengg/IBMdataset
Python_codes/p03854/s014754635.py
s014754635.py
py
224
python
en
code
0
github-code
90
4838333356
import json import os from googleapiclient.discovery import build class Channel: """Класс выводящий информацию о канале по id""" api_key: str = os.getenv('API_KEY') # API_KEY скопирован из гугла youtube = build('youtube', 'v3', developerKey=api_key) # специальный объект для работы с API def __init_...
Ivan-Koltsov1994/YouTube_analytics
src/channel.py
channel.py
py
4,064
python
ru
code
0
github-code
90
42268136524
# 문제: 모든 조직원의 수익 파악하기 # 조건: 1) 1 <= len(enroll) <= 10000 # 2) len(referral) == len(enroll) # 3) 1 <= len(seller) <= 100000 # 4) len(amount) == len(seller) # 5) 칫솔 가격 = 100 # 방법: 1) union 재귀를 통해서 10%를 뺀 수익금만 해당 조직원 금액에 추가하기 def union(recommend, seller_no, answer, s, m): # 방법 1 if m == 0: ...
junhong625/TIL
Algorithm/Programmers/다단계 칫솔 판매.py
다단계 칫솔 판매.py
py
1,011
python
en
code
2
github-code
90
18543684213
import binascii, sys, appfs def openAppfs(filename): print(filename) print("----------------------------------------") with open(filename, "rb") as f: appfsData = f.read() obj = appfs.AppFS(appfsData) obj.extract_files() if len(sys.argv) != 2: print("Usage: " + sys.argv[0] + " <fi...
badgeteam/esp32-component-appfs
tools/appfs_extract.py
appfs_extract.py
py
374
python
en
code
1
github-code
90
41726677264
import re import traceback from CoeuSearch.main import * from django.contrib import messages from django.shortcuts import render def home(request): return render(request,'CoeuSearch/home.html') def search(request): if request.method == 'POST': err_flag = 0 start_time = time.time() path...
abhinav-bohra/CoeuSearch
CoeuSearch/views.py
views.py
py
2,302
python
en
code
1
github-code
90
23304884770
# Intializing our blockchain list blockchain = [] open_transactions = [] owner = 'Max' def get_last_blockchain_value(): """ Returns the last value of the current blockchain """ if len(blockchain) < 1: return None return blockchain[-1] # This function accepts two arguments. # One required one (tran...
steffanjensen/python-blockchain
blockchain.py
blockchain.py
py
3,018
python
en
code
0
github-code
90
36127625186
"""Revert refresh token handling Revision ID: fceb6686c112 Revises: 119d8d9a324c Create Date: 2021-04-06 09:27:42.213070 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = "fceb6686c112" down_revision = "119d8d9a324c" bran...
MTES-MCT/mobilic-api
migrations/versions/fceb6686c112_revert_refresh_token_handling.py
fceb6686c112_revert_refresh_token_handling.py
py
1,235
python
en
code
1
github-code
90
23561838864
""" - Author: Sharif Ehsani - Date: September 2020 - https://github.com/sharifehsani Checkpoint 9.19 Assume the following statement appears in a program: values = 'one$two$three$four' Write a statement that splits the string, creating the following list: ['one', 'two', 'three', 'four'] """ # main function to start th...
sharifehsani/starting-out-with-python
chapter9/checkpoint_9_19.py
checkpoint_9_19.py
py
648
python
en
code
0
github-code
90
73172403177
class Node: """ Noh para uma arvore AVL """ def __init__(self, data): self.data = data self.right = None self.left = None # altura do noh. Usado para calcular o balanceamento da arvore self.height = 1 class AVLTree: """ Arvore AVL ...
Luiz-01/Estrutura-de-Dados
Arvore.py/arvore_AVL.py
arvore_AVL.py
py
11,616
python
pt
code
1
github-code
90
1732028806
""" Student portion of Zombie Apocalypse mini-project """ import random import poc_grid import poc_queue import poc_zombie_gui # global constants EMPTY = 0 FULL = 1 FOUR_WAY = 0 EIGHT_WAY = 1 OBSTACLE = "obstacle" HUMAN = "human" ZOMBIE = "zombie" class Zombie(poc_grid.Grid): """ Class for simulating zombi...
claraqqqq/p_o_c_a_t_r_i_c_e
p5_z_o_m_b_i_e_a_p_o_c_a_l_y_p_s_e.py
p5_z_o_m_b_i_e_a_p_o_c_a_l_y_p_s_e.py
py
5,999
python
en
code
0
github-code
90
29410660135
import json import subprocess import numpy as np config = { 'in_channels': 1360, 'out_channels': 1360, 'kernel_size': 1, 'stride': 1, 'groups': 1, 'hw': 7, 'gpu_id': 0, 'num_warmups': 200, 'num_iters': 1000, 'gpu_sampler': 0, } python_args = ' '.join([f'--{k}={v}' for k, v in c...
Starmys/CUDAKernelEnergyPredictor
test_stability.py
test_stability.py
py
745
python
en
code
0
github-code
90
33662702867
# https://leetcode-cn.com/problems/valid-sudoku/ class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: rows = [{} for i in range(9)] cols = [{} for i in range(9)] block = [{} for i in range(9)] for i in range(9): for j in range(9): num ...
algorithm004-04/algorithm004-04
Week 06/id_049/LeetCode_36_049.py
LeetCode_36_049.py
py
798
python
en
code
66
github-code
90
29053898890
def encoder(code,shift_key): #encode the message new_code='' alphabet="abcdefghijklmnopqrstuvwxyz" for cha in range(len(code)): index = code[cha] if index in alphabet:#position present_condition=alphabet.find(index) new_condition=(present_condition+shift_key) % 26 ...
ChamathPeiris/Histogram-for-Exam-Marks-and-Encoding-Decoding-Strings
Part 2B.py
Part 2B.py
py
2,162
python
en
code
0
github-code
90
25240665105
''' Problem 231: Power of Two Given an integer, write a function to determine if it is a power of two. Example 1: Input: 1 Output: true Explanation: 2^0 = 1 Example 2: Input: 16 Output: true Explanation: 2^4 = 16 Example 3: Input: 218 Output: false Solution runtime: 28ms, faster than 92.33% of Python3 submissions...
yichuanma95/leetcode-solns
python3/powerOf2.py
powerOf2.py
py
553
python
en
code
2
github-code
90
70494199657
import tensorflow as tf import os import pathlib import time import datetime from matplotlib import pyplot as plt from IPython import display #%% #Download CMP Facade Database data (30MB) #Di Colab, Anda dapat memilih set data lain dari menu drop-down. #Perhatikan bahwa beberapa kumpulan data lain seca...
zakyyusuff/artificial-intelligence
Chapter8/zaky_stgan.py
zaky_stgan.py
py
1,775
python
en
code
0
github-code
90
72113132776
#! /usr/bin/env python import argparse import subprocess import sys import tempfile from typing import IO from openmm import NonbondedForce, VariableLangevinIntegrator, unit from openmm.app import AmberInpcrdFile, AmberPrmtopFile, HBonds, PDBFile, Simulation def bootstrap_amber(pdb_file: IO): with tempfile.Named...
tzok/openmm-utils
compute_energy.py
compute_energy.py
py
5,348
python
en
code
0
github-code
90
44575093973
""" Blackjack game. """ import random class bcolors: HEADER = '\033[95m' BLUE = '\033[94m' CYAN = '\033[96m' GREEN = '\033[92m' RED = '\033[91m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def create_deck(num_decks :int) -> li...
Mattyfreshy/BlackJack
BlackJack.py
BlackJack.py
py
4,196
python
en
code
0
github-code
90
73795609898
import requests from bs4 import BeautifulSoup from splinter import Browser import datetime as dt import numpy as np import pandas as pd import pymongo from flask import Flask, jsonify, render_template, request import scrapemars conn = "mongodb://admin:password@ds143245.mlab.com:43245/heroku_2xxf76ft" client = pymong...
paulrizzuto/mission_to_mars
app.py
app.py
py
3,273
python
en
code
0
github-code
90
70379115498
import cv2 as cv # opencv import copy # for deepcopy on images import numpy as np # numpy from random import randint # for random values import threading # for deamon processing from pathlib import Path # for directory information import os # for directory information from constants import constants # const...
julzerinos/python-opencv-leaf-detection
PlantDetector.py
PlantDetector.py
py
14,876
python
en
code
19
github-code
90
684335825
import os import networkx as nx from pytest import fixture from solar.orchestration import graph from solar.orchestration import limits @fixture def dg(): ex = nx.DiGraph() ex.add_node('t1', status='PENDING', target='1', resource_type='node', t...
Mirantis/solar
solar/test/test_limits.py
test_limits.py
py
1,927
python
en
code
8
github-code
90
18171608796
import numpy as np import os import math import torch from torch.utils.data import Dataset, DataLoader import random def read_data(task, domain, lbl_percentage, data_path): ''' domain: source or target ''' assert domain in ['source', 'target'] labeled_x_filename = 'processed_file_not_one_hot_%s_%1....
stevenliu000/time-series-domain-adaptation
data_utils.py
data_utils.py
py
8,591
python
en
code
5
github-code
90