blob_id
large_string
repo_name
large_string
path
large_string
src_encoding
large_string
length_bytes
int64
score
float64
int_score
int64
detected_licenses
large list
license_type
large_string
text
string
download_success
bool
9cf1483da4f49ec386bee105166d3ff17729a194
lizhilizhi/python-study
/44_pytest.py
UTF-8
630
2.96875
3
[]
no_license
import pytest @pytest.fixture(scope = 'function') def setup_function(request): def teardown_function(): print("1") request.addfinalizer(teardown_function) print(2) @pytest.fixture(scope = 'module') def setup_module(request): def teardown_function(): print("1") request.addfinaliz...
true
77dfa5d8b870f2117bd826928ce1a4c4e32e9fa9
israelelchdad/alllesenalex
/lesen25/t6.py
UTF-8
170
3.28125
3
[]
no_license
def up(): for i in range(1,5): print ("*"*i) def down(): for i in range(1,3): for i in range(5,0,-1): print("*"*i) up() down() #down()
true
443207a7010d0fd496b13dcdfc3ee532825b129d
techsparksguru/python_ci_automation
/Class4/behave-basics/features/steps/addition_outline.py
UTF-8
553
3.75
4
[ "MIT" ]
permissive
from behave import * use_step_matcher('re') @given("I have two integers (?P<integerA>.+) and (?P<integerB>.+)") def step_impl(context, integerA, integerB): context.integerA = int(integerA) context.integerB = int(integerB) @when("I add the two numbers") def step_impl(context): context.result = int(context...
true
edb669c615659d63f0117e8baf820cafe152ee37
Chunshan-Theta/bert_mulit_label_chinese_pytorch
/tool/multi_label_conftrix.py
UTF-8
1,037
2.671875
3
[]
no_license
from sklearn.metrics import confusion_matrix import seaborn as sn import pandas as pd import numpy as np import matplotlib.pyplot as plt # y_pred = [0,0,2,3,0,1,0] # y_true = [0,1,2,0,0,1,0] def multi_label_confusion_matrix(y_pred,y_true): y2_pred = [] y2_true = [] for y_p, y_t in zip(y_pred,y_true): for i...
true
692c920990ab3db8bc1f6c27462a5f05d36fdba2
tdsymonds/codeeval
/python/easy/(227) real-fake.py
UTF-8
646
3.234375
3
[ "MIT" ]
permissive
import sys def main(filepath): with open(filepath, 'r') as f: for line in f.readlines(): if line: line = line.strip() print is_card_real(line.replace(' ', '')) def is_card_real(num_str): doubled_num_sum = 0 other_sum = 0 for i, c...
true
2853956df0b6d716859420b8eed857223a4aed8f
GA1/python-algs
/test/algs/test_fib_frog.py
UTF-8
536
2.984375
3
[]
no_license
from src.algs.fib_frog import steps_lower_or_equal_than, solution def test_steps_lower_than_1(): assert steps_lower_or_equal_than(1) == [1] def test_steps_lower_than_2(): assert steps_lower_or_equal_than(2) == [1, 2] def test_steps_lower_than_13(): assert steps_lower_or_equal_than(13) == [1, 2, 3, 5, ...
true
855f2065b9bdffdec57b3727208b61abdd6a4ada
ashutoshkmr21/CSCI567
/PA2/Part2/bm_classify.py
UTF-8
9,801
3.046875
3
[]
no_license
import numpy as np def binary_train(X, y, loss="perceptron", w0=None, b0=None, step_size=0.5, max_iterations=1000): """ Inputs: - X: training features, a N-by-D numpy array, where N is the number of training points and D is the dimensionality of features - y: binary training labels, a N dimension...
true
0d1aaef05d2c7254de1594681e45770d13387f65
gusenov/examples-pandas
/dataframe-with-2-col/program.py
UTF-8
665
3.53125
4
[ "MIT" ]
permissive
import pandas as pd def test1(): # вариант 1 data = [['A', 10], ['A', 14], ['B', 12], ['B', 23]] my_data = pd.DataFrame(data, columns = ['type', 'value']) print(my_data) print() ''' type value 0 A 10 1 A 14 2 B 12 3 B 23 ''...
true
10f31931af745a744b438cfc60cc395fc3b3a47d
podhmo/individual-sandbox
/daily/20180822/example_mypy/05fn.py
UTF-8
621
3.4375
3
[]
no_license
import typing as t import mypy_extensions as mx # (x: int, y:int, verbose: bool=...) -> int みたいな型 F = t.Callable[[int, int, mx.DefaultArg(bool, "verbose")], int] # error: Argument 1 to "use" has incompatible type "Callable[[int, int, DefaultNamedArg(bool, 'verbose')], int]"; expected "Callable[[int, int, bool], int...
true
566d90314428a717db5567747a8f83c2b43bc58c
petioptrv/automated-trading
/algotradepy/brokers/base.py
UTF-8
5,082
2.953125
3
[ "MIT" ]
permissive
from abc import ABC, abstractmethod from datetime import datetime from typing import Callable, Optional, Dict, Tuple, List from algotradepy.contracts import AContract from algotradepy.trade import Trade class NoPaperTradeException(Exception): pass class ABroker(ABC): """The Abstract Broker class defining t...
true
466fe258445574a759a463c5b6a752821fdb7bac
wmyw96/multisource-sr
/utils.py
UTF-8
2,499
2.59375
3
[]
no_license
import numpy as np import time def print_metrics(readouts, domain=None): ''' Printing the losses from a sess.run() call Args: readouts: losses and train_ops : dict Returns: ''' spacing = 17 print_str = '' if domain is not None: print_str += domain + '>\n' for k_, v...
true
48081c8011fdaac1d426473d5033fd0c3a80bcf0
NMGRL/pychron
/pychron/core/geometry/affine.py
UTF-8
6,181
3.171875
3
[ "Apache-2.0" ]
permissive
# =============================================================================== # Copyright 2011 Jake Ross # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses...
true
897e07b44f25a4697fdfed29d7c326d611c66e69
Sammyalhashe/CSC_Course_Work
/priorityQueue-DESKTOP-VE2FF62.py
UTF-8
479
3.453125
3
[]
no_license
from maxHeapInheritance import maxHeap class PQ(maxHeap): """Put stuff in and take stuff out with Highest priority [Inherits from maxHeap class to remove with highest priority] Extends: maxHeap """ def __init__(self, key=None): super().__init__(key) if __name__ == '__main__': ...
true
070cccc5cd3f8adca56416906235a01507d153de
jingmouren/MingkaiLee-MultiFactorModel
/step1_factor_expo.py
UTF-8
5,301
2.515625
3
[]
no_license
# 多因子风险模型第一步: 生成因子暴露、因子收益率、特质收益率 # 1) 默认采用增量运行模式, 回溯窗长为ParamSet.backLength参数, 一般应用场景为月度更新,所以默认回溯长度为23个交易日 # 2) 如需重头开始运行, 可以将ParamSet.backLength设置为-1 # 导入包 import numpy as np from scipy.io import loadmat import gc # 导入其他部分代码 # 欲导入部分的路径置入 import sys sys.path.append("module_1/utils") sys.path.append("module_1/factor") fro...
true
d4d7e8240e52c6806b832470d91867e9650fcb81
Alekseysk/Lesson3
/Task3.py
UTF-8
443
4.0625
4
[]
no_license
""" Реализовать функцию my_func(), которая принимает три позиционных аргумента, и возвращает сумму наибольших двух аргументов. """ def my_func(*n): """ Сумма двух наибольших """ m_list = list(n) min_ind = m_list.index(min(m_list)) m_list.pop(min_ind) return sum(m_list) print(my_func(3, 1...
true
89e2648562d88f192f54355fed4aa499b648bcb1
fmurshed07/Python-Random-Password-Generator
/Python_and_MySQL/5.0 Select From a Table.py
UTF-8
525
3.453125
3
[]
no_license
''' To select from a table in MySQL, use the "SELECT" statement Select all records from the "customers" table, and display the result Note: We use the fetchall() method, which fetches all rows from the last executed statement. ''' import mysql.connector mydb = mysql.connector.connect( host="localhost", user="ad...
true
3ad1eb09ca8b9ffedecce4192fa16b44f1bc3b5d
SaiMadhukar/Encrypted-File-Transfer
/server.py
UTF-8
2,105
3.015625
3
[]
no_license
import socket import threading import os from Crypto.Cipher import AES import base64 key = "This is a key123" iv = "This is an IV456" obj = AES.new(key, AES.MODE_CBC, iv) def RetrFile(name, sock): lineNo = 0 filename = sock.recv(1024) if os.path.isfile(filename): sock.send("EXISTS " + str(os.path...
true
6b4bcc936d5d4308d6d75db3c8476610b4096993
txdao/krz_player
/krz_player.py
UTF-8
4,755
3.15625
3
[]
no_license
#!/usr/bin/python # -*- coding: utf-8 -*- import pygame import time import random file_dir = '' pygame.mixer.init() def play(file): song = pygame.mixer.Sound(file) song.set_volume(1) song.play() # print('playing ' + file) return song def loop(): pass def wait_for_input(): pass def play_...
true
839367ddda0137650fafd28686406d4186807e0d
824zzy/Leetcode
/I_Searching/DFS/Tree/L2_968_Binary_Tree_Cameras.py
UTF-8
685
3.25
3
[]
no_license
""" https://leetcode.com/problems/binary-tree-cameras/ post-order traversal, there are three conditions for any node: 0 - leaf node 1 - covered node without camera 2 - covered node with camera """ class Solution: def minCameraCover(self, root: Optional[TreeNode]) -> int: self.ans = 0 def d...
true
1cc8ab1f403f307146d86e61e066d08443a9bab9
ejstronge/nlm_data_import
/nlm_data_import/test/test_nlm_data_import.py
UTF-8
9,281
2.59375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# -*- coding: utf-8 -*- """ test_nlm_data_import.py ======================= Test suite for the archive downloading module (c) 2014, Edward J. Stronge Available under the GPLv3 - see LICENSE for details. """ from collections import namedtuple import os import shutil import tempfile import unittest from .. import nlm_...
true
effce22f180c26a563829b2ab298b30870427eec
shashikiran-sk/HackerRank-Challenges
/smartest_set.py
UTF-8
1,807
3.859375
4
[]
no_license
test_cases=int(input()) for m in range(test_cases): tot_num=int(input()) numbers=list(map(int,input().split())) dicts={} res=[] for i in numbers: binary=str('{0:b}'.format(i)) count=binary.count('1') if count in dicts: dicts[count].append(i) else: ...
true
22de3c49309e83147a531c8df211f8c722fd9f23
SandeepKumarShaw/python_tutorial
/new folder/single_input.py
UTF-8
152
3.640625
4
[]
no_license
# name = input("enter your name :-") # age = input("enter your age :-") name , age = input("enter your name and age").split(" ") print(name) print(age)
true
39fd54528e69c6ce09f385ad0fe1899d532106bc
leynier/inferfuzzy
/inferfuzzy/memberships/l_membership.py
UTF-8
321
2.9375
3
[ "MIT" ]
permissive
from ..membership import Membership class LMembership(Membership): def __init__(self, a, m): def func(x): if x <= a: return 1 if a <= x and x <= m: return (m - x) / (m - a) return 0 super(LMembership, self).__init__(func, [a, m])...
true
af9f7ec52e51e6b962436c80671126edf8a63e16
SwarajRenghe/Mario
/config.py
UTF-8
4,767
3.09375
3
[]
no_license
import os import random # Position Vector : Defines a co-ordinate and an abscissa class positionVector: def __init__(self, x=0, y=0): self.x = x self.y = y """ Miscellaneous Important Functions """ # def randomIntegerBetween (a1, a2): # return random.randint (a1, a2) def clear(): _ ...
true
aa1e1c29cc9b02c52499ebce37a8c9d236efd582
OkamotoDaiki/InfsPreprocessing
/script/subscript/correlation/correlation.py
UTF-8
2,489
2.6875
3
[]
no_license
import numpy as np import sys from ..debug_functions import DebugModeCorrelation #limit rate against all data of correlation data because of few probably distribution save_rate = 0.8 #class object debug_mode = DebugModeCorrelation() def CrossCorrelation(*args): """ Cross Correlation function. ...
true
b4480182560b47990f5f31a7d489342ccc6736fe
manusri2430/manasa
/angle.py
UTF-8
81
3.0625
3
[]
no_license
import math g = int(input()) rad = math.radians(g) print(round(math.sin(rad),3))
true
11abd6d326b6786aee6548e562c2296a466169ff
andef4/thesis-code
/nhs-chest-xray/analyze/visual_attribution/explainer/feedback.py
UTF-8
2,605
2.625
3
[ "MIT" ]
permissive
import torch.nn.functional as F from torch.nn import Parameter from torch.autograd import Variable from torch import optim import torch import types from explainer.backprop import SaliencyExplainer def first_forward(self, x): out = F.relu(x) self.control_gate = Parameter(out.data.clone()) self.control_gat...
true
17913dd28204541518d92ca5263750d1e693ff0e
rahulpd101/UdacityP1
/project2/4_active_dir.py
UTF-8
2,359
3.796875
4
[]
no_license
""" 4_active_directory.py In Windows Active Directory, a group can consist of user(s) and group(s) themselves. We can construct this hierarchy as such. Where User is represented by a string representing their ids. """ import time class Group(object): def __init__(self, _name): self.name = _name s...
true
f945f9649c5dad0df7055e14bd79e1a33452f2b0
ketankishore27/Titanic
/solution.py
UTF-8
8,541
3.265625
3
[]
no_license
# -------------------------> Importing the required Libraries ------------------------------ import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection import cross_val_score from sklearn.metrics import confusion_matrix # ------------------------...
true
890b287858f77677349249e4fcd4c1ade59f71fe
josmejia2401/angox-media-api-speech-to-text
/src/core_lib/dto/dto.py
UTF-8
1,560
2.734375
3
[ "MIT" ]
permissive
import json import datetime class DTO(object): def __init__(self, dataAsJson={}, ignored_none=False): self.ignored_none = ignored_none self.id = None if dataAsJson is None: return if 'id' in dataAsJson and dataAsJson['id']: self.id = dataAsJson['id'] def...
true
f8c0b4061c494ced3d917ae3770723a4122d1138
taniavill/python_init
/triangles/triangle.py
UTF-8
172
3.859375
4
[]
no_license
def draw(n): triangulo = [] for i in range (0,n): triangulo.append(line(i+1)) return '\n'.join(triangulo) def line(x): return ' '.join(['*'] * x)
true
6105cf9b6e832ae8d4f0f5cab830e4272a91056a
a362389462/me
/set3/exercise3.py
UTF-8
2,972
4.5
4
[]
no_license
"""Set 3, Exercise 3. Steps on the way to making your own guessing game. """ import random def advancedGuessingGame(): """Play a guessing game with a user. The exercise here is to rewrite the exampleGuessingGame() function from exercise 3, but to allow for: * a lower bound to be entered, e.g. guess...
true
9a2b8fb4782774d3bfb357467dcb7f188b1828ab
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_136/1043.py
UTF-8
796
3.34375
3
[]
no_license
def solve(C, F, X): """ solve the problem """ seconds = 0.0 rate = 2.0 buildings = 0 while True: seconds += C / rate remains = X - C # s1: dont buy new building strategy1 = remains / rate # s2: buy new building strategy2 = ( remains + C ) / ( rate...
true
517f10e34e13fbcf38678cbbbdbad0d4ef92e67f
RaymoneYe/SpectrumSharing
/20190315SS/FP+SF.py
UTF-8
7,848
2.640625
3
[]
no_license
import numpy as np import math import matplotlib.pyplot as plt from itertools import chain # N = 500 p = 1 Gt = 2.5 Gr = 2.5 Ptdbm = 40 fmhz = 2400 NdBm = -184 Noise = (10 ** (NdBm/10))*0.001 w = 1 region = 500 B = 5e6 def linkpair(N): t = np.random.random(N) * 2 * np.pi - np.pi t = np.expand_dims(t, axis=1)...
true
297038d952181c5e74fbe1db8fb617bb1cc169ec
rohanhg91/feature_engineering_project
/q02_outlier_removal/build.py
UTF-8
569
3.078125
3
[]
no_license
# Default imports import pandas as pd # Data ny_housing = pd.read_csv('data/train.csv') # Selecting 4 most relevant variables from the dataset fot the Cleaning and Preprocessing. housing_data = ny_housing[['MasVnrArea', 'GrLivArea', 'LotShape', 'GarageType', 'SalePrice']] # Write your code here: def outlier_removal(...
true
10c5ca7a57a3c907f9a44753a10bfc8c7a989e13
larslevity/GeckoBot
/Code/Src/PiCamera/server.py
UTF-8
1,246
2.546875
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Tue Nov 06 15:44:41 2018 @author: AmP """ import socket import time import picamera import pickler # max_res = (2592, 1944) resolution = (1648, 1232) # Halle # Start a socket listening for connections on 0.0.0.0:8000 server_socket = socket.socket() server_socket.bind(('',...
true
7547807898bc4f808e1eaa1da5a0d2570ead24fe
Seth1Briney/forestfire_data
/pvals.py
UTF-8
2,585
3.125
3
[]
no_license
import numpy as np import scipy.stats # X not to be confused with the 'X' spatial feature which is represented in the first column of X. Confusing, but I like having feature data represented as X. X = np.load('archive.ics.uci...forestfires_features.npy') Y = np.load('archive.ics.uci...forestfires_area.npy') keys = n...
true
f42a5fb281e28d5f478dd95d0b1dbaf07f509bcc
gineer01/programming-challenges
/python/UVA/11332_summing_digits.py
UTF-8
234
2.75
3
[ "MIT" ]
permissive
import fileinput def solve(n): while n > 9: n = sum(int(x) for x in str(n)) return n def main(): f = fileinput.input() for l in f: n = int(l) if n > 0: print(solve(n)) main()
true
1155baba80053d42d2bdd8a8c3368ec7092bea1e
anton-bannykh/ml-2013
/elena.podgornova/main.py
UTF-8
2,887
2.65625
3
[]
no_license
import numpy import perceptrone import svm import svm_smo import kernels import lr import nw def split(data, part): temp_data = [x.split(',') for x in data] numpy.random.shuffle(temp_data) b = int(len(temp_data) * part) train_x = [numpy.array([float(i) for i in x[2:]]) for x in temp_data[:b]] train_y = [1.0 if x[...
true
a21ea259681f3d5a1426348871917a7a4c3568d6
SamMuq/LKS-Dataset
/prepro_wsi.py
UTF-8
3,120
2.84375
3
[ "CC-BY-4.0" ]
permissive
""" This module can be used to preprocess the LKS Dataset (https://github.com/cradleai/LKS-Dataset) as described in the paper - SOS: Selective Objective Switch for Rapid Immunofluorescence Whole Slide Image Classification (DOI: 10.1109/CVPR42600.2020.00392). Dependencies: This module requires the libvips image p...
true
dc82a618fe2253501552bad94ec38af189b58b10
mcvenkat/Python-Programs
/amicable numbers array.py
UTF-8
1,003
4.09375
4
[ "MIT", "CC0-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# -*- coding: utf-8 -*- """ Created on Thu Jan 16 11:11:29 2020 @author: 766810 """ # Python3 program to count # amicable pairs in an array # Calculate the sum # of proper divisors def sumOfDiv(x): sum = 1 for i in range(2, x): if x % i == 0: sum += i return s...
true
9c571c35d8e039ef56869e803c435af7d4ce2993
JoaoZati/ListaDeExerciciosPythonPro
/EstruturaSequencial/Ex_18.py
UTF-8
738
4
4
[]
no_license
#%% 18 - Tamanho do arquivo MB """ Faça um programa que peça o tamanho de um arquivo para download (em MB) e a velocidade de um link de Internet (em Mbps), calcule e informe o tempo aproximado de download do arquivo usando este link (em minutos). """ tamanho_arquivo = float(input('Digite o tamanho do arquivo em MB:...
true
1c9cfd200f157853b04e8ddc3870d7b6c69909c2
GuySrinivasan/oeis
/scripts/print-factorials
UTF-8
180
2.8125
3
[ "MIT" ]
permissive
#!/usr/bin/env python import oeis print oeis.factorial(0) print oeis.factorial(1) print oeis.factorial(2) print oeis.factorial(3) print oeis.factorial(4) print oeis.factorial(5)
true
541953091809b98b72097308136ed8380d36a236
privong/Astronomy
/DataReduction/Optical/opt_red.py
UTF-8
12,196
2.71875
3
[]
no_license
#!/usr/bin/env python # # opt_red.py # # Batch optical reduction for a single night of data from astropy.io import fits as pyfits import numpy as np import sys import os import re import glob import shutil import datetime import matplotlib.pyplot as plt import mysci import argparse def imageCombine(imgnames, framety...
true
410cd3460135622e6230214927d0da2e4b5c43ca
2gisprojectT/kaygorodov-twitter
/twitter-test/helpers/home_page.py
UTF-8
1,156
2.546875
3
[]
no_license
from selenium.common.exceptions import NoSuchElementException class HomePage(): selectors = { 'logged_in': '.logged-in', 'logged_out': '.logged-out' } def __init__(self, driver): self.driver = driver self.url = 'http://twitter.com' self._modal_tweet_box = None ...
true
1b39fd06e11ed3e81688d189eb77aef2094547b6
dianecw/cs170-nptsp
/supreme_mst.py
UTF-8
1,625
2.703125
3
[]
no_license
def mst_solver(edges, N, num_branches=5, fill_bias=float('inf')): pruned = [[fill_bias] * N for i in range(N)] for i in range(N): best = [fill_bias] * num_branches best_loc = [0]*num_branches for j in range(N): largest = best[0] largest_index = 0 for k...
true
46ca1b67bad4f559d3b0b6578f0b23d26d6b925c
kawsarhussen16/Data-Structures
/binary_search_tree/binary_search_tree.py
UTF-8
1,196
3.5625
4
[]
no_license
class BinarySearchTree: def __init__(self, value): self.value = value self.left = None self.right = None def insert(self, value): if not self.value: self.value=value else: pointer = self finished = False while not finished: if value > pointer.value: if ...
true
cac209fe2ed81912439ce26a4f6e396af3e4dff7
ImaginaryStargazer/acid.nvim
/rplugin/python3/acid/pure/__init__.py
UTF-8
2,023
2.703125
3
[]
no_license
import os import re from acid.nvim.log import log_debug, log_warning def path_to_ns(path, stop_paths=None, base_files=None): log_debug("Supplied path is {}", str(path)) if not path: log_debug("Possibly empty or scratch buffer. Skipping") return if stop_paths is None: stop_paths =...
true
fec05f1c13a891954e1e428514f212c96038d5a9
SegFault2017/Leetcode2020
/905.sort-array-by-parity.py
UTF-8
661
3.3125
3
[]
no_license
# # @lc app=leetcode id=905 lang=python3 # # [905] Sort Array By Parity # # @lc code=start class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: """ Strategey 1: 2 Pointers Runtime: O(n), where n is the size of A Space: O(1) Args: A (List[int]): a list...
true
a2c1b63307c567c0c33a20ef62f6fae3b3619dcf
gmweinberg/pymnash
/util.py
UTF-8
5,602
3.28125
3
[]
no_license
import numpy from fractions import Fraction from itertools import combinations, product def coords_from_pos(thearray, pos): """Get the corrdinates from a one-dimensional position and shape. We will make the first index most signifcant.""" # we should probably replace this with iterindices where it is used. ...
true
7dc045dd59c498e82da55e7b8a90faa7fce7e80f
armanvural/Computational-Neuroscience
/HW4_AVB/arman_budunoglu_21602635_hw4.py
UTF-8
27,460
3.125
3
[]
no_license
import numpy as np import matplotlib.pyplot as plt import os import h5py from sklearn.decomposition import PCA from sklearn.decomposition import FastICA from sklearn.decomposition import NMF question = input("Enter Relevant Question Number to Display its Respective Output \n") def arman_budunoglu_21602635_hw4(questio...
true
c4f8a9ee88d91741287791e33517e396786831fe
C-SON-TC1028-001-2113/listas---tarea-6-BryantOchoa
/assignments/09SerieFibonacciListas/src/exercise.py
UTF-8
548
3.34375
3
[]
no_license
def main(): x = -1 y = 0 a = 1 b = 1 serie = [] while x <= -1: x = int(input()) if x == 0: print(serie) elif x==1: serie.append(0) print(serie) elif x==2: serie.append(0) serie.append(1) print(serie) else : serie.app...
true
63f4e0d5b272c6f1aaf1eaab72ce5f4d73f18c48
ZeratuuLL/Natural-Language-Processing
/QS Digestion and Inference/clean_data.py
UTF-8
3,815
2.671875
3
[]
no_license
''' This file: reads in proprocessed data and get X and y apply cutting and padding update Word2Vec model weights save new data and new weights ''' import config import utils import pandas as pd import numpy as np import pickle import ast from gensim.models import Word2Vec REMOVE = config.REMOVE # l...
true
c18b534120c00668e23602d9cf39c025971d6a4d
patrickdemers6/usa-vaccine-alerter
/script.py
UTF-8
2,721
2.75
3
[]
no_license
from twilio.rest import Client import requests import threading import datetime import sys import json from twilio.base.exceptions import TwilioRestException import signal # load configuration data try: file = open('config.json') except IOError: print("config.json file not found.") exit(1) config = json.lo...
true
113aef92228d37a92837162ba553c18756183c1a
AntonOcean/Simple_blockchain
/block.py
UTF-8
1,979
2.96875
3
[]
no_license
from datetime import datetime import hashlib import json import os from config import * class Block: def __init__(self, index, timestamp, data, pre_hash=None, nonce=None, block_hash=None): self.index = index self.timestamp = timestamp.strftime("%Y.%m.%d %H:%M:%S") self.data = data s...
true
935ec276198f34d47c141fb172dd1b9fadf837c7
sarvasvarora/advent-of-code-2020
/day1/1.py
UTF-8
704
3.640625
4
[ "MIT" ]
permissive
def binary_search(a, val, start, end): mid = (start + end)//2 if start >= end: return val == a[mid] if val == a[mid]: return True elif val < a[mid]: return binary_search(a, val, start, mid - 1) elif val > a[mid]: return binary_search(a, val, mid + 1, end) def main()...
true
cf1415400e73dc5ce26e0b824036610df789810f
thra4974/holbertonschool-higher_level_programming
/0x05-python-exceptions/5-raise_exception.py
UTF-8
140
2.984375
3
[]
no_license
#!/usr/bin/python3 def raise_exception(): str1 = "Holberton" if not type(str) is int: raise TypeError("Exception raised")
true
74f36f53030f6a252bb12ac60a94b33ac37cbf15
bio33/euler
/34.py
UTF-8
553
3.296875
3
[]
no_license
# upper bound - > 2540161 (9!*7) reason being thats the maximum sum of factorials can go of each digit as 9999999 def memoize(f): memory = {} def helper(x): if x not in memory: memory[x] = f(x) return memory[x] return helper @memoize def fact(n): if n <= 1: return 1 else: return n * fac...
true
7989d9ef6d23c07dcc604e8e42a24f75ebe54652
Vifespoir/webscrapping
/ProductHunt_get_makers.py
UTF-8
9,280
2.796875
3
[]
no_license
#!python3 """This script will call ProductHunt API and gather information. It'll collect Maker names and from a specific topic by looping through all the posts of this topic. """ # importing libraries import requests import pprint import shared_functions import logging import shelve # TO DO: keep a list of topics an...
true
b13a8e4ee8f5495fb59eb0f99571334ac7ed2af0
nomuramasahir0/neldermead
/examples/demo_sphere.py
UTF-8
1,162
3.109375
3
[ "MIT" ]
permissive
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np from neldermead import NelderMead def get_regular_simplex(dimension, centroid, gamma): angle = -1.0 / dimension regular_simplex = np.zeros([dimension+1, dimension]) init_norm = 1 tmp = 0.0 for i in range(dimension): n_coord...
true
3e49cbd6ffb7e61bcc13088a43fa2738c02be06b
jdrubin91/GROAnalysis
/src/Phosphoproteomics_analysis.py
UTF-8
1,700
2.640625
3
[]
no_license
__author__ = 'Jonathan Rubin' import matplotlib.pyplot as plt import math def run(file1,figuredir): fcs = list() PEPs = list() Intensities = list() genes = list() rankedlist = list() with open(file1) as F: F.readline() F.readline() for line in F: line = line...
true
5a3b800b9f71f7d95af85f1f7de4ff9884485c78
grewy/practice_py
/leetcode/DP/medium/lis.py
UTF-8
620
2.921875
3
[]
no_license
class Solution(object): def lengthOfLIS(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 dp = [nums[0]] lnp = 1 for i in range(1, len(nums)): l, r = 0, len(dp) - 1 while l < r: ...
true
86947d77fa8538330b2ab8661c4391c85b2bea92
galantal1995/Automated-EMC-station
/2. Robot Control by Mouse/Spectrum_analyzer_control.py
UTF-8
9,609
2.5625
3
[]
no_license
# This script contains all the necessary functions to control the spectrum analyzer. # The definitions under the classes are called from the main scripts so basically all the fuctions that controls the analyzer are executed from this code. # There are two different classes, one that is responsible for the control of ...
true
195b256b66be757c68e209d5b6c26885ab32d3f3
AndreSilvazm/GO-TO-MARKETLAND-FINALIZADO-PATCH---1.0
/Interface Grafica.py
UTF-8
25,733
2.671875
3
[]
no_license
from tkinter import * from tkinter import ttk from tkinter import messagebox import pymysql import random from time import sleep class Cadastrar(): def CadastrarBackend(self): Certa = True nomec = self.nome.get() sobrec = self.sobrenome.get() usuac = self.usuario...
true
d1f0e09da18ded5b47120a562575d1fe4809712e
calchemyst/scc_covid19_graphs
/cv19graphs/ca_data_parser.py
UTF-8
6,950
2.59375
3
[]
no_license
import logging import math import time from datetime import datetime, timedelta from typing import Iterable, List, Optional import matplotlib.pyplot as plt import pandas as pd logger = logging.getLogger(__name__) NYC_COUNTY = "New York City" NYC_FIPS = 36061 CHARTS = { "cases_log": {"chart_title": "COVID19 Total...
true
3fbc35f4758e745ce739b7586cc872bc83b67a20
xxduck/xcar
/xcar/spider/reply_page.py
UTF-8
1,785
2.75
3
[ "MIT" ]
permissive
"""这是帖子回复页的抓取模块""" from spider.base import Parent import logging import sys import time import re class Reply(Parent): # def __new__(cls, *args, **kwargs): # # """单例模式""" # # if not hasattr(cls, "_cls"): # # cls._cls = super(Reply, cls).__new__(cls, *args, **kwargs) # # return ...
true
2fd5d3026ef11ce204f25df79fac869d5641197c
vrnvu/hr
/hackerrank/divisible-sum-pairs.py
UTF-8
354
3.34375
3
[]
no_license
# https://www.hackerrank.com/challenges/divisible-sum-pairs/problem # Complete the divisibleSumPairs function below. def divisibleSumPairs(n, k, ar): r = 0 for i in range(n): for j in range(i + 1, n): if (ar[i] + ar[j]) % k == 0: r += 1 return r r = divisibleSumPairs(6...
true
e9648071c4c05958c3106320cf4bbe1f315a3b1b
JohnHanna86/pyTester
/CorpusReader.py
UTF-8
4,923
3.109375
3
[]
no_license
''' Created on Feb 23, 2010 This module is used for manipulating the data in the UN Corpus, which is in tmx format, and also can be useful in any tmx parallel corpus @author: johnnabil ''' import xml.dom.minidom from xml.sax import saxutils, handler, make_parser class CorpusHandler(handler.ContentHandler): def...
true
31454f65131dc8350d42aee29373e8a2e60ac625
Oneforallll/BT30-10-VuCongHoan
/pandas1.py
UTF-8
111
3.15625
3
[]
no_license
import pandas as pd s = pd.Series([0,1,2,3], index=["a","b","c","d"]) print(s) #a 0 #b 1 #c 2 #d 3
true
1e46eb2d7e48052b1c92623414ff36650992bae2
drkarthi/algo
/generate_subsets.py
UTF-8
582
3.90625
4
[]
no_license
import math def int_to_binary(n, num_elements): binary_digits = [] for x in range(num_elements): digit = n%2 binary_digits.append(digit) n = n >> 1 return binary_digits def generate_subsets(s): num_possibilities = pow(2,len(s)) subsets = {} for x in range(num_possibilities): subsets[x] = [] print("x =...
true
b50a23b4fea2300444308e536b6da24f801aa100
TrendingTechnology/apysc
/apysc/console/assertion.py
UTF-8
17,715
3.546875
4
[ "MIT", "CC-BY-4.0" ]
permissive
"""Each js assertion (console.assert) interface implementations. Mainly following interfaces are defined: - assert_equal JavaScript assertion interface for equal condition. - assert_not_equal JavaScript assertion interface for not equal condition. - assert_true JavaScript assertion interface for ...
true
dfc1ee996156f5aa626f0bb78c9b6feffdeb5125
lostinmilkshake/StarLine
/dot.py
UTF-8
1,440
4.1875
4
[]
no_license
class Dot2d: def __init__(self, x=0, y=0): try: self.__x = float(x) # Инициализация точки х self.__y = float(y) # Инициализация точки y except Exception: # Кидаем ошибку, если переданные данные не являются числами raise ValueError("Invalid values") ...
true
0563f124ca93e2453bd7eb23f545e00969595d97
ehpessoa/Python
/Automate-The-Boring-Stuff-With-Python/Chapter 13 - Working with PDF and Word Documents/brute_force_pdf_breaker.py
UTF-8
1,539
3.8125
4
[]
no_license
#! python3 # brute_force_pdf_breaker.py # usage: python brute_force_pdf_breaker.py {pdf_file} {dictionary.txt} import sys import PyPDF2 def main(): """ Checks for inputs via sys.argv :return: Calls pdf_brute_force or prints usage statement. """ if len(sys.argv) > 2: pdf_file...
true
54ba19d16bb280244d2387a916841d06d05946bc
harmannd/Codewars
/StringMatchup/test_solve.py
UTF-8
434
2.828125
3
[]
no_license
from unittest import TestCase from string_matchup import solve class TestSolve(TestCase): def test_solve(self): self.assertEqual(solve(['abc', 'abc', 'xyz', 'abcd', 'cde'], ['abc', 'cde', 'uap']), [2, 1, 0]) self.assertEqual(solve(['abc', 'xyz', 'abc', 'xyz', 'cde'], ['abc', 'cde', 'xyz']), [2, 1, ...
true
f3695de5fc6afa363b8084574f84f03e0274a80d
EnotionZ/PongAttack
/main.py
UTF-8
4,922
2.640625
3
[]
no_license
import sys import os import math import pyglet import cocos from cocos.director import director from cocos.sprite import Sprite import cocos.euclid as eu import cocos.collision_model as cm sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) class CollidableRectSprite(cocos.sprite.Sprite): def __i...
true
b07dc0fccefbb8d048518b7523f89cb7ae96f611
mattioiscattio/Python-Collection
/Fibonacci.py
UTF-8
98
3.40625
3
[]
no_license
sequence = [1] for i in range(500): sequence.append(sequence[i]+sequence[i-1]) print(sequence)
true
65d2cd7b9c44781f8189b5e365bfa1f44c916327
vsx-gh/ruckroulette
/app.py
UTF-8
2,385
3.015625
3
[ "MIT" ]
permissive
''' Program: app.py Author: Jeff VanSickle Created: 20190530 Program selects a random three ruck PT exercises from a collection based on user input for the body area they would like to work ''' from flask import Flask, render_template, request import random app = Flask(__name__) app.debug = True # PT m...
true
09b1e8896ccc8a4f6f01176bcdc0782b95e14724
Nivethika7623/sample2
/B74.py
UTF-8
39
2.828125
3
[]
no_license
n=float(input()) x=int(n+0.5) print(x)
true
0e68b4b0ccab944ebea07a1c2d85aa69860e6894
abigailbishop/AST443-F18-BBY
/Lab0/DataAnalysis4p2-p10.py
UTF-8
11,254
2.796875
3
[]
no_license
# Lab 0 Data Analysis for part 4.2 # Creates and analyzes DARK frames set at +10C # September 7, 2018 # Imports import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt from astropy.io import fits from scipy import stats from scipy.stats import norm # Open Files dark_f_0 = fits.ope...
true
892ef337178d83a279a9aabc09d43179a7787192
wslgqq277g/FRSKD
/segmentation/utils/distill.py
UTF-8
885
2.75
3
[]
no_license
import torch.nn as nn import torch.nn.functional as F class DistillKL(nn.Module): def __init__(self, args): super(DistillKL, self).__init__() self.T = args.temp def forward(self, y_s, y_t): B, C, H, W = y_s.size() p_s = F.log_softmax(y_s/self.T, dim=1) p_t = F.softmax(...
true
15b3b3e68c0e13ccabfa5cc43bc4ee862061b023
MitCandy/PythonNotes
/Basics/strings.py
UTF-8
807
4.71875
5
[]
no_license
# SimpleString print("Get Good") # Backslash for using quotation inside quotation print("Get\"Good") # Can be assigned on variable and execute name = "Roy" print(name) # Concenateable w/without variable name1 = "Burnett" print("Your name is " + name1) # String w function word = "klen" print(word.upper()) # Capitali...
true
e9a427d4dcb7b326ba8bef40d353e208cbb0e7ed
jaredLunde/radar-server
/radar_server_legacy/utils.py
UTF-8
1,540
2.578125
3
[ "MIT" ]
permissive
import re import json from vital.cache import memoize from vital.tools import strings as string_tools __all__ = ( 'to_js_keys', 'transform_keys', 'to_js_shape', 'get_class_attrs', 'to_js_key', 'to_python_key' ) js_keys_re = re.compile(r"""([^\\])"([A-Za-z]+[A-Za-z0-9_]*?)":""") js_records_re...
true
06bb49cd00695a63ae97883b633cf854789d94a5
BradleyMidd/learnwithbrad
/shop_list.py
UTF-8
1,612
4.25
4
[]
no_license
# Basic Shopping list products = ["Apple", "Pear", "Cornflakes", "Cookie", "Chips", "Ice Cream"] my_list = [] while len(my_list) < 3: pro_list = print("\n".join(products) + "\n") choose = input("Pick the products available above: ").upper() # Short way of adding products to your list for i in range(l...
true
1ddd9fac30f5b766bf8cd335c7675a25cfcd1335
saymoniphal/django
/assignment1_2-apps-no-serialization/sales/models.py
UTF-8
1,095
2.59375
3
[]
no_license
from django.db import models from django.core.exceptions import ValidationError from model_utils import Choices # Create your models here. def validate_gender(value): # validating gender field if len(value) > 1: raise ValidationError('Gender must be of 1 char') class Customer(models.Model): ...
true
fc6f6afae7975c7e8bdf5d89a815f53e78cd3c25
axo318/hackathonway
/lib/Classes/symptom.py
UTF-8
440
3.46875
3
[]
no_license
class Symptom(object): # Variables # # id: (int) id associated with symptom # name: (string) name of this symptom def __init__(self, id, name): self._initialise_variables(id,name) def _initialise_variables(self, id, name): self.ID = id self.NAME = name # -- Gette...
true
af3c100edf16fed0651fe8527c65c35e7ba2ff86
ezhang-dev/competitive-programming
/DMOJ/Fun Math/Infinity.py
UTF-8
70
2.640625
3
[]
no_license
print("Yes" if (int(input(),16)+int(input(),16)>1061109567) else "No")
true
d275ef7a1009703d30123d3f29e2fb410cbd7b55
zhujingyuan0925/PGY
/getPath.py
UTF-8
390
2.8125
3
[]
no_license
import os def get_basepath(): #获取当前项目文件绝对路径 #这样的做目的:直接获取项目路径,方便使用,后面文件直接拿过去引用 basepath = os.path.split(os.path.realpath(__file__))[0] return basepath ''' if __name__ == '__main__': print('当前项目文件绝对路径为:',os.path.split(os.path.realpath(__file__))[0]) '''
true
5d5fd4a25ca203500fc74f78db172f4524561354
alphagov/github-organisation-administration
/tests/test_get_items_for_repo.py
UTF-8
1,917
3.15625
3
[ "MIT", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-unknown-license-reference" ]
permissive
from src.make_data.get_items_for_repo import get_items_for_repo from unittest.mock import MagicMock import pytest # Define test cases for the `TestGetItemsForRepo` test class args_test_get_item_for_repo_repository_name = [ ("hello", "world"), ("foo", "bar") ] @pytest.mark.parametrize("test_input_method_name,...
true
f2bc7300262e8bd01f9e1f8ba079d092dfc8afcd
JAreina/python
/4_py_libro_1_pydroid/venv/4_py_libro_1_pydroid/dictionary/dictionary__2.py
UTF-8
255
3.46875
3
[]
no_license
list1 = [1, 2, 3, 4, 5] list2 = ["a", "b", "c","d", "e"] dict1 = {} for i in range(len(list1)): dict1[list1[i]] = list2[i] print (dict1) print("\n zip() ..............\n") dict18={} dict18 = dict([k for k in zip(list1,list2)]) print(dict18)
true
ec9fd6910c915aecd92ffdbb4e0d390a2c57facc
AdamZhouSE/pythonHomework
/Code/CodeRecords/2238/60742/260396.py
UTF-8
97
2.96875
3
[]
no_license
a = [int(i)+1 for i in input().split(',')] s = set(a) res = 0 for i in s: res += i print(res)
true
61227563a36b062cf2a77aaebe2e6b53f14a82c5
meisteregor/python
/05_generator,censor/05_1_generator_restyled.py
UTF-8
273
2.859375
3
[]
no_license
import sys from os import walk, path def your_wrapper(*args): for root, dirs, files in args[0]: for name in files: text = path.join(root, name) yield text return lazy = your_wrapper(os.walk("c:\\")) print(list(lazy))
true
9b341e6dcae58d664c9b97631eddcdfe7bfb6ba6
JaeGyu/PythonEx_1
/unittestEx1.py
UTF-8
293
2.9375
3
[ "MIT" ]
permissive
import unittest def add(a,b): return a+b def sub(a,b): return a-b class unit_test(unittest.TestCase): def test_add(self): self.assertEqual(3, add(1,2)) def test_sub(self): self.assertEqual(2,sub(4,2)) if __name__ == "__main__": unittest.main()
true
053e1735d8f7a5a8381e346cd8960c1a305747e3
wnku/bandcamp-dl
/bandcamp-dl.py
UTF-8
2,039
2.625
3
[ "MIT" ]
permissive
import argparse as ap import requests import re import urllib.request import shutil from lxml import html import os request_header = { 'User-Agent': "Mozilla/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20100101 Firefox/12.0" } audioRegex = r"(https:\/\/t4.bcbits.com\/stream\/[a-z0-9]{32}\/mp3-128\/[0-9]{10}\?p=[0-9]&...
true
0f0db1dfbd8d451fb04197e7ad57c1e9ab8338bc
Kang-Hoon/Python_reviews
/190405_lec/190405_0_shell.py
UTF-8
4,868
2.75
3
[]
no_license
Python 3.7.2 (v3.7.2:9a3ffc0492, Dec 24 2018, 02:44:43) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license()" for more information. >>> a=1 >>> b=2 >>> c=3 >>> d=4 >>> print(a+b) 3 >>> print('c'+'d') cd >>> =============================== RESTART: Shell ============================...
true
b2ba292a32c858f4587d69087cfa0e1af9968807
mmrahman21/loss-patterns
/tests/test_utils.py
UTF-8
508
2.5625
3
[ "MIT" ]
permissive
import sys; sys.path.append('.') import torch from src.utils import orthogonalize def test_orthogonalization(): v1 = torch.rand(10 ** 6) v2 = torch.rand(10 ** 6) assert torch.dot(v1, orthogonalize(v1, v2)).abs() <= 1e-2 assert (v1.norm() - orthogonalize(v1, v2, adjust_len_to_v1=True).norm()) <= 1e-2 ...
true
8a110bdce9553aef194dea2fd4d03215f6fa52b3
mustaphatidooyussif/career-fair-2020
/task2.py
UTF-8
10,903
3.578125
4
[]
no_license
import csv import sys from os.path import isfile """ Authors: Mustapha Tidoo Yussif and Samuel Atule class of 2020 """ class TaskTwo: def __init__(self): self._pattern = [] self._pattern_len = 0 self.good_suffix_table = [] #suffix table as required by boyer moore algorithm. ...
true
9d68168c66bb088e95a6b334d535a07532eefaff
edt-yxz-zzd/python3_src
/nn_ns/parsing/FS/FSM_prime.py
UTF-8
5,880
2.765625
3
[]
no_license
__all__ = ''' RawFSM_ABC WrapFSM BasicBufferedFSM DFABufferedFSM_ABC DFABufferedFSM '''.split() from sand.types.ToProcess import FILOOnce from sand import unsafe_last from abc import ABCMeta, abstractmethod from .Maybe import * from .FA_prime import SimpleDFA class RawFSM_ABC(metaclass=ABCMeta)...
true
1577fd3c3fe153cdfeef47ba20921ecd981c25c4
aseafamily/Coding
/Emily/FunctionsDay24/interestandothers/AugustThreeHomework.py
UTF-8
177
2.921875
3
[]
no_license
import random from time import sleep for i in range(1, 11): print(random.random()) sleep(1) # import random # for i in range(1, 6): # print(random.randint(1, 20))
true
10e8be618ae46d87f1c51d5cb6a6f217c71760c9
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_116/1408.py
UTF-8
1,417
3.140625
3
[]
no_license
import sys import numpy as np def test_items(a): a.discard('T') if len(a) > 1: return False, "Nopes" val = a.pop() if val == 'O': return True, "O won" if val == 'X': return True, "X won" return False, "Nopes" def solve_board(board): for row in range(4): t...
true
3987aff4d5be49c857bc043a1f0c3d651b45b0cd
drdilyor/loxothon
/test/parser/test_expression.py
UTF-8
3,312
2.921875
3
[]
no_license
import pytest from lox import expr, Parser, Scanner, TokenType as TT, ParseError # noqa import lox.lox as lox scan = lambda s: Scanner(s).scan_tokens() # noqa # note that expression is private api def parse(s): try: return Parser(scan(s)).expression() except ParseError: return None @pytest....
true