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
d8d884a89b1db04045d68db9a5a30adde06966b1
hookeyplayer/exercise.io
/算法/笔记10_插入排序.py
UTF-8
678
3.796875
4
[]
no_license
# 打扑克,将后面的牌(抽出来)插入前面已经排好的牌中 # 插入排序有一种优化:折半插入 # 但是折半不改变元素移动次数,只是减少了比较次数 # 移除:n-1次 # 比较:1+2+3+...+(n-1)=n(n-1)/2,约为N^2/2 # 平移:=比较的次数 # 插入:n-1次 # 共计(N^2 + 2N -2), 记作O(N^2) def insertionSort(array): for i in range(len(array) - 1): # curNum是当前待插入的数 curNum, preIndex = array[i+1], i while preIndex >= 0 and curNum < arr...
true
89aa77cdcb35f34b2617b1b39917bea2d1c2a805
Laferu/Python-Listar-Jogadores-do-FIFA-2017
/main.py
UTF-8
2,973
3.625
4
[ "MIT" ]
permissive
# coding: utf-8 # Todas as perguntas são referentes ao arquivo `data.csv` # Você ** não ** pode utilizar o pandas e nem o numpy para este desafio. def compose(f, g): return lambda *a, **k: g(f(*a, **k)) import csv import operator with open('data.csv', encoding="utf8") as documento: dados = csv.reader(documen...
true
0df34a4752c45b6170d04a304f7261b474ead664
aaronuhmgmailcom/-3000-download-zip-file-from-internet-by-python-request
/ppt/maze.py
UTF-8
1,623
3.890625
4
[]
no_license
# 迷宫 maze = [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 0, 1, 0, 0, 0, 1, 0, 1], [1, 0, 0, 1, 0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 1, 1, 0, 0, 1], [1, 0, 1, 1, 1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 0, 1, 0, 0, 0, 1, 0, 0, 1], [1, 0, 1, 1, 1, 0, 1, 1, 0, 1], [1, 1, 0, 0, 0...
true
f6d1593e009a0eff7c433059d18b612e22e43fcc
Thiruvenkatesh-B-Palanisamy/cp5632practicals
/prac_4/lists_warmup.py
UTF-8
217
3.28125
3
[]
no_license
numbers = [3, 1, 4, 1, 5, 9, 2] numbers[0] = "ten" print(numbers) numbers[-1] = 0 print(numbers) num_slice = numbers[2:] print(num_slice) for number in numbers: if number == 9: print("yes") break
true
18264b3c06f7e49623c0c435733720f92f189bb6
aquatiger/LaunchCode
/random list creation.py
UTF-8
483
4.4375
4
[]
no_license
""" Create a list containing 100 random integers between 0 and 1000 (use iteration, append, and the random module). Write a function called average that will take the list as a parameter and return the average. """ import random listing = [] for i in range(100): listing.append(random.randint(0, 1000)) print(lis...
true
2ec3d9847679d16cf05b4c8fdcc1ba70bf0d8ffa
upcomputer/up1
/img_recv.py
UTF-8
1,155
2.625
3
[]
no_license
# coding: utf-8 import serial import sys import os from PIL import Image from datetime import datetime if len(sys.argv) < 4: print('[用法]: {} <port> <ccc> <rrr>'.format(sys.argv[0])) exit() try: nc = int(sys.argv[2], 10) # 列数 nr = int(sys.argv[3], 10) # 行数 baudrate = 1...
true
b83c10e5033dda5108818e4a8cd7d25ae27f2f05
Milan-Chicago/ds-guide
/random_selection/single_number.py
UTF-8
931
3.953125
4
[]
no_license
""" Single Number Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. You must implement a solution with a linear runtime complexity and use only constant extra space. Example 1: Input: nums = [2,2,1] Output: 1 Example 2: Input: nums = [4,1,2,1,2] Output: 4...
true
88bf4df3f039ef53ddebc1b77bc010d4a5f14273
Lischero/Atcoder
/IndeedNowQualB/q2.py
UTF-8
275
2.703125
3
[]
no_license
# -*- coding:utf-8 -*- import sys s = list(input()) t = list(input()) sentence = s*2 for tmp in range(len(s)): index = len(s)-tmp if ''.join(t) == ''.join(sentence[index:index+len(s)]): print(tmp) sys.exit() else: pass else: print(-1)
true
5e0a370d58d371371abda6f8cb283d5c013988bb
yashrane/DiscordScraper
/ParseIntros.py
UTF-8
915
3.40625
3
[ "MIT" ]
permissive
import csv import re #parses a string to get all introduction data from it #returns an array of introduction tuples def get_intros(intros): pattern = re.compile('2.(.+)[,\/-](.+)[,\/-](.+)\s3.(.+)\s4.(.+)') result = pattern.findall(intros) if result is not None: return result #prints introduction da...
true
5281abf4247f56b09ab97cfc7ede106fe36b5a42
monkeynova/learn-python
/codejam/2014/decietful-war/decietful-war.py
UTF-8
2,202
3.203125
3
[]
no_license
#!/usr/bin/env python import sys def playNaomi( naomiWeights ): return naomiWeights[0] def playDeceitfulNaomi( naomiWeights, kenWeights ): epsilon = 1e-7 worstNaomi = min( naomiWeights ) bestKen = max( kenWeights ) if worstNaomi > bestKen: return ( naomiWeights[0], naomiWeights[0] ) ...
true
af1ab629ed2af14428ceaf6dc6d1450710d6e903
hail-linda/Scientific-computing-2-hours-in-Python
/airbnbSpider_scrapy/airbnbSpider_us/airbnbSpider/calendarTest.py
UTF-8
627
2.53125
3
[]
no_license
# -*- coding: UTF-8 -*- import json # import dbSettings import requests # def getListingId(): # db = dbSettings.db_connect() # cursor = db.cursor() # sql = "SELECT house_id FROM `houselist_us` ORDER BY RAND() LIMIT 30000" # cursor.execute(sql) # db.commit() # result = cursor.fetchall() # ...
true
7800ab170d6d9c5b857f2bd076ecfc16e24dc823
maxmhuggins/Assorted_Scripts
/uControllers/Final Project/Finding binary functions.py
UTF-8
1,923
2.9375
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sun Apr 28 02:04:16 2019 @author: maxhu """ import numpy as np import matplotlib.pyplot as plt def A(x): return np.cos(x) def B(y): return np.cos(y) x = np.linspace(-1,10,5000) y = x*2.7 plt.plot(A(y), A(x), 'm') def convert_to_bin(x): new =...
true
d8be88eb8ffd1003a7742eefda557f22632dbfef
nischalshrestha/automatic_wat_discovery
/Notebooks/py/tovarischsukhov/first-steps-in-datascience/first-steps-in-datascience.py
UTF-8
4,188
2.765625
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 # First steps in DataScience with Titanic.csv # In[ ]: # This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to ...
true
f3aeb35b97f91583b6194c22b3e7570f870547cd
aidanwen/radiology
/checkForPneumonia.py
UTF-8
3,653
2.828125
3
[]
no_license
# import the necessary packages from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from keras.models import Sequential from keras.layers import Activation from keras.optimizers import SGD from keras.layers import Dense from keras.utils import np_utils from imutils import...
true
bca0013607d8c4c32231a5c3db2f4436a9ecf788
Andy-Lv/Python-Learning
/06_语法进阶/04_多值参数.py
UTF-8
446
4.03125
4
[]
no_license
# 参数名前加“*”可以接收元组 # 参数名前加“**”可以接收字典 def demo(num, *nums, **person): print(num) print(nums) print(person) demo(1) demo(1, 2, 3, 4) # num=1,其他的是元组 demo(1, 2, 3, 4, name="xiaoming") # num=1,其他的数字是元组,最后是字典 # 多值参数求和 def sum_num(*args): num = 0 for n in args: num += n return num result ...
true
5e470e4cc39ba161a1a2ece3e209f21e3cccdca4
maundergit/textmining
/ja_depndency_analysis.py
UTF-8
11,484
2.609375
3
[ "MIT" ]
permissive
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ---------------------------------------------------------------------- # Name: ja_depndency_analysis.py # Description: # # Author: m.akei # Copyright: (c) 2021 by m.na.akei # Time-stamp: <2021-06-06 12:03:21> # Licence: # ------------------------------...
true
c60ad77b8e392eb62f9f68016d877ee0242ea53a
impradeeparya/python-getting-started
/array/MaximumScore.py
UTF-8
3,354
3.53125
4
[]
no_license
# You are given nums, an array of positive integers of size 2 * n. You must perform n operations on this array. # # In the ith operation (1-indexed), you will: # # Choose two elements, x and y. # Receive a score of i * gcd(x, y). # Remove x and y from nums. # Return the maximum score you can receive after performing n ...
true
7fc97a79094435e4206891b6e724b4c475b540d4
LauraRuis/multimodal_seq2seq_gSCAN
/seq2seq/predict.py
UTF-8
7,024
2.640625
3
[]
no_license
import torch import torch.nn as nn import torch.nn.functional as F import logging from typing import Iterator import time import json from seq2seq.helpers import sequence_accuracy from seq2seq.gSCAN_dataset import GroundedScanDataset import pdb device = torch.device("cuda" if torch.cuda.is_available() else "cpu") logg...
true
0eb2ccf8754a953e70de8efd6811323a7d0d5da5
22842219/SQL2Cypher
/utils/AbsSQL.py
UTF-8
388
2.875
3
[ "MIT" ]
permissive
from abc import ABC, abstractmethod class AbsSQL(ABC): def __init__(self, cypher): self.cypher = cypher super().__init__() def get_cypher(self): return self.cypher + " " @staticmethod def check_data(data): if data is None: raise ValueError("Incorrect data"...
true
92fd4458429b5dad10fd55301037b48626cd98d0
jiwonMe/pheonix
/game/game.py
UTF-8
3,082
3.546875
4
[ "MIT" ]
permissive
import card class Player: def __init__(self, name): self.name = name self.cards = [] def set_hands(self, cards): self.cards = cards def set_exchange(self, left, across, right): self.selected = [ self.cards[left], self.cards[across], ...
true
ba8275446cd51ed2dccffd36949317369eb39118
bastianf19/progjar-b-its-2020
/tugas4/ActionHandler.py
UTF-8
793
2.75
3
[]
no_license
import shelve import uuid import os import socket import base64 class Action: def __init__(self): if not os.path.exists("file"): os.makedirs("file") def get_data(self,nama=None): tmp = [] filenya = open('file/'+nama, 'rb') hasilfile = filenya.read() # print(...
true
b4817bcf0ca43fa5b279f64f71c1b26c96b47e32
gmclove/GA-CFD-MO
/cases/NSGA_joukowskyCLCD/initialization.py
UTF-8
3,419
3.125
3
[ "MIT" ]
permissive
# Package importation import numpy as np import math import random import scipy.stats as stats import optunity from problemSetup import * ################################################################################ # FUNCTION DEFINITION # ##################...
true
58f02e9a00d839af512cb0a5cb3f05a509d6a788
ak47av/Digital-Signal-Processing
/periodical1.py
UTF-8
699
3.359375
3
[]
no_license
import numpy as np import matplotlib.pyplot as plt def dft(x): N = len(x) out = [] for k in range(N): temp = 0 for n in range(N): temp += x[n]*np.exp(-2j*np.pi*n*k/N) out.append(temp) return np.round(out,3) k = np.arange(0,6) def sampledTransform(k): N=len(k) ...
true
3e06daab97a890fa207d6e44a8dedd83675d6dcf
aronvis/Python-Projects
/stack.py
UTF-8
767
4.34375
4
[]
no_license
class Stack: def __init__(self): self.stack = [] # Insert item on top of the stack (end of array) def appendItem(self, value): self.stack.append(value) # Remove item on top of the stack (end of array) def popItem(self): return self.stack.pop() # Prints the items inside the stack def printStack(self): for...
true
9f3463106606b20addafea13ba8ee5040b5b1168
Lxydev/Euler
/Euler_014.py
WINDOWS-1252
1,287
3.765625
4
[]
no_license
#!/usr/bin/python # -*- coding: cp936 -*- #Filename: Euler14.py ''' The following iterative sequence is defined for the set of positive integers: n n/2 (n is even) n 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 40 20 10 5 16 8 4 2 1 It c...
true
3b1dba86812867ef37d17408cb990180dc5bd7ec
saurabhkawli/ComputerVisionBasics
/5_Segmentation/test_debug.py
UTF-8
1,064
2.875
3
[]
no_license
import math import os import sys import cv2 import numpy as np import matplotlib.pyplot as plt def RMSD(target, master): # Note: use grayscale images only # Get width, height, and number of channels of the master image master_height, master_width = master.shape[:2] master_channel = len(master.shape) ...
true
22cbb1e158a68969ad817f8b84a109d21364398d
mhaupt63/Python
/session_5.py
UTF-8
2,026
3
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Thu Oct 4 15:23:35 2018 @author: s99931 """ import numpy as np import pandas as pd import math as mt import plotly as py import plotly.graph_objs as go import matplotlib.pyplot as plt # import sample data: actual location will depend on where you have it saved. ...
true
9d9a874bc5727e4824b97c227e3b8849978b0314
JarrodAMcEvers/advent_of_code_2020
/day1/day1.py
UTF-8
953
3.65625
4
[]
no_license
magic_number = 2020 f = open('./input.txt', 'r') lines = [ int(item) for item in f.read().splitlines() ] f.close() def multiply_two_values_that_add_to_2020(): for index1, line in enumerate(lines): for index2 in range(1, len(lines)): if index2 == index1: continue if (...
true
d582d0b5ed4a77b9be6107a3df2999081691dc43
arnie-robot/Spine
/src/Thread/streamedinput.py
UTF-8
923
2.65625
3
[ "MIT" ]
permissive
### Spine by Chris Alexander # Standard imports # Custom imports import Interface import Thread # Input Thread class class StreamedInput(Thread.Input): # Init the interface def configureInterface(self, host, port, converter, transform): if self.interface is None or self.interface.host != host or sel...
true
63356d972441054256d9d3a1c9fd8b7b0d4116d8
DongShanHu/pythonpratice
/Test/threading test.py
UTF-8
2,702
3.046875
3
[]
no_license
##python threading #多線層可以分批量做很多事,節省computing time) import threading import time import copy from queue import Queue def main(): print(threading.active_count()) if __name__=='_main_': main() ##def thread_job(): ## print('T1 start\n') ## for i in range(10): ## time.sleep(0.1) ## print('t1 finish...
true
4ea31834bfb9cc38155fc81061468c5dcf3493b9
dseferiadis/jamfHelper
/azure.py
UTF-8
4,599
2.578125
3
[]
no_license
import requests import json import pandas as pd import datetime import pytz import os AZURE_TENANT = "ellismarsaliscenter.org" AZURE_CLIENT_ID = os.getenv('AZURE_CLIENT_ID') AZURE_CLIENT_SECRET = os.getenv('AZURE_CLIENT_SECRET') def get_ms_graph_access_token(): url = 'https://login.microsoftonline.com/' + AZURE_...
true
d5bcb1f601c326bbf661990966c9c77d2ed63c3b
kobergj/TheGame
/models/anomaly_models.py
UTF-8
4,297
3.234375
3
[]
no_license
# class Anomaly(): # # Generic Anomaly in Space. # def __init__(self, name, enemies=list()): # # Identifier # self.name = name # # Coordinates # self.coordinates = None # # Enemies in Orbit # self.enemies = enemies # # Enemy Graveyard # self.dead_...
true
8db23624e16ed890bd58531a52624ef46cc407da
Valerdzhan/geekproject
/lesson_4/exercise_4_7.py
UTF-8
1,497
4.375
4
[]
no_license
""" Реализовать генератор с помощью функции с ключевым словом yield, создающим очередное значение. При вызове функции должен создаваться объект-генератор. Функция должна вызываться следующим образом: for el in fact(n). Функция отвечает за получение факториала числа, а в цикле необходимо выводить только первые n чисел, ...
true
2a56fbb1668441a1d1422e84c83eba5fb1ce84dd
shivam4312/Shivam-Raj
/naeme23.py
UTF-8
304
3.4375
3
[]
no_license
name="Anubhav Singh" print (name[1]) print (name[-2]) print (name[1:-1]) print (len(name)) print ((2+2)+(10%3)) print (name.title()) print (name.strip()) print(name.find("Singh")) print(name.replace("Singh","k")) if "Anubhav" in name: print("Yes it is a first name.") else: print("No.")
true
d29ceec4694ed12eeb1f1a3cd4ae8be0513ddb32
chao-shi/lclc
/017_phone_combination_m/main.py
UTF-8
438
3.21875
3
[]
no_license
class Solution(object): def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ if not digits: return [] alphas = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"] ret = [""] for ch in digits: ...
true
517e8d625af46f71b441d6fb7aa125937f5b7987
David-Chatelard/ICC-UnB
/Lista 4 icc/Questão_C.py
UTF-8
250
3.453125
3
[]
no_license
def pares(a): if a == 2: print(a) return elif a == 0: return else: print(a) return pares(a-2) n = int(input()) if n == 0 or n == 1: n = 0 elif n % 2 != 0: n -= 1 pares(n)
true
3aea46699fac0ba39cf481146aa64364b5834ac6
Carsmaniac/paintjob-packer
/library/webhook/webhook.py
UTF-8
16,642
2.796875
3
[ "MIT" ]
permissive
import logging import json import time import datetime import requests from .webhookexceptions import * logger = logging.getLogger(__name__) class DiscordWebhook: """ Webhook for Discord """ def __init__(self, url=None, content=None, username=None, avatar_url=None, **kwargs): """ In...
true
3a6a0d8d0fb1fc6309d7ad01b99d05e308005995
zodang/python_practice
/high_challenge/심화문제 4.3.py
UTF-8
143
3.515625
4
[]
no_license
age = int(input("나이를 입력하세요: ")) if age >= 20: print("Adult") elif age >=10: print("Youth") else: print("Kid")
true
52a342fb87558a5c0deac4b9010c3e6bdd9f0286
lucasjurado/Alura-Python-OO
/main.py
UTF-8
2,135
3.6875
4
[ "MIT" ]
permissive
from ExtratorArgumentosUrl import ExtratorArgumentoUrl url = 'http://www.byte.com.br/cambio?moedaoRigem=moedadestino&moedadestino=dolar&valor=1500' argumento = ExtratorArgumentoUrl(url) # Retorna a string do OBJETO (argumento) print(argumento.get_url) # Constroi duas variáveis do OBJETO (argumento), # as quais rece...
true
c6bac4fb82a70fd0d5b0220f038251a5f8783af7
Junior743/alquimia
/python-main/main.py
UTF-8
240
3.140625
3
[ "Apache-2.0" ]
permissive
# # tentando entender a diferenca entre if __name__ == '__main__' e __init__() # class Principal(object): def __init__(self): print('__init__') if __name__ == '__main__': print('__name__ == \'__main__\'') Principal()
true
d553073af277fcaddfce1164049ba11403df1247
yxx94/2020-
/jianzhioffer/数组/旋转数组.py
UTF-8
349
3.34375
3
[]
no_license
# coding=utf-8 # leetcode 189 ''' 输入: [1,2,3,4,5,6,7] 和 k = 3 输出: [5,6,7,1,2,3,4] 解释: 向右旋转 1 步: [7,1,2,3,4,5,6] 向右旋转 2 步: [6,7,1,2,3,4,5] 向右旋转 3 步: [5,6,7,1,2,3,4] ''' class Solution(object): def rotate(self, nums, k): nums[:] = nums[-k%len(nums): ] + nums[: -k%len(nums)] return nums
true
98cc010588e94297fdc36f83988e1a3b984c732c
matcom-chacha/comp_type_inference
/src/ast_nodes.py
UTF-8
3,266
2.671875
3
[]
no_license
class Node: pass class ProgramNode(Node): def __init__(self, declarations): self.declarations = declarations class ExpressionNode(Node): pass class ClassDeclarationNode: def __init__(self, idx, features, parent=None): self.id = idx self.parent = parent ...
true
c2023ac917ee7c085cb8080a287c2e3a6453255a
ShayanZarif/FunProjectsInPython
/sinVcosin.py
UTF-8
272
3.5625
4
[]
no_license
import numpy import matplotlib.pyplot as plt x = numpy.arange(0,4*numpy.pi,0.01) y = numpy.sin(x) plt.plot(x,y) y1 = numpy.cos(x) plt.plot(x,y1) plt.xlabel("X values from 0pi to 4pi") plt.ylabel("sin(X) and cos(X)") plt.legend(["Sin(X)","Cos(X)"]) plt.show()
true
82080b16c96403223c3abc41c3f5434d3b499b5a
bobby-lin/BlackHatPythonProject
/Utils/rsa_example.py
UTF-8
778
2.921875
3
[]
no_license
import rsa def run_example(keysize): print("Generating RSA Key pair") public_key, private_key = rsa.newkeys(keysize, poolsize=8) print("Public key:", public_key) print("Public Key (Modulus n) =", public_key.n) print("Public Key (Exponent e) =", public_key.e) print("Private key:", private_key) ...
true
b8f561891ad69ca89a7c8337ba389b90051c0328
nihal-singh/Image_recognition
/script.py
UTF-8
2,555
3.28125
3
[]
no_license
#Python Program for Image recognition (only numbers) import numpy as np import matplotlib.pyplot as plt import time from PIL import Image from collections import Counter def createExamples(): createFile = open('exFile.txt','a') numberEx = range(0,10) numberVer = range(1,10) for eachNum in numberEx: for eachVe...
true
4fa74609438c7fe2f1378ea1ea6a136d442a37e2
KaloyankerR/python-advanced-repository
/Assignments/Comprehensions/Exercise/07. Flatten Lists.py
UTF-8
176
3.5
4
[ "MIT" ]
permissive
elements = [[i for i in x.split()] for x in input().split("|")] elements_reversed = [x for x in reversed(elements)] [[print(i, end=" ") for i in x] for x in elements_reversed]
true
5ed33ebb9367829a8d6df1e4021c258c81d55987
semanscoj/Zero_Interface
/Gui/StatusBar.py
UTF-8
541
2.515625
3
[]
no_license
from tkinter import * from tkinter import ttk class StatusBar(ttk.Frame): def __init__(self, parent, state): self.parent = parent self.state = state self.scrolling = None self.react_buttons = [] self.react = None self.react_ready = None self.button_default ...
true
041570b559b54f2b7f74c840c00d10a41ff488fb
zinph/NetBuilder
/netbuilder/NeuralNet.py
UTF-8
25,389
3.265625
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- """@author: andresberejnoi TODO: During training, if the network gets stuck in a local minima for several epochs, then randomly modify certain weights in the matrix. This might allow the network to get out of that minima and converge. """ import numpy as np from . import _param_keys as keys #...
true
2a2b8e7ec715690c431d186d8ca44cb3e77d7fde
arkarkark/copyclipper
/test_copyclipper.py
UTF-8
1,152
2.71875
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/python """Test copyclipper.""" import unittest import copyclipper class TestCopyClipper(unittest.TestCase): """Test copyclipper.""" def test_load_config(self): """Can we load a config?""" config = copyclipper.LoadConfig() self.assertTrue(len(config) > 0) def test_patterns(self): ""...
true
db6ec2884bc8901b4725984371a812bd2b7c551e
yanhongliu/DARLAB
/InvTL/lm_py/pypy/module/_ast/test/test_ast.py
UTF-8
5,814
2.765625
3
[]
no_license
import py class AppTestAST: def setup_class(cls): cls.w_ast = cls.space.appexec([], """(): import _ast return _ast""") cls.w_get_ast = cls.space.appexec([], """(): def get_ast(source, mode="exec"): import _ast as ast mod = compile(source, "<test>", mode, ast.PyCF_AST_O...
true
8ae18ac2a1c9a39c7c7357e4a2257913c7d48b52
glosoftgroup/school-erp
/loglib/logging.py
UTF-8
2,059
3
3
[]
no_license
import json import datetime import decimal from django.utils.timezone import is_aware def _serializer(obj): """ Render particular types in an appropriate way for logging. Allow the json module to handle the rest as usual. """ # Datetime-like objects if hasattr(obj, 'isoformat'): return...
true
5128ae09c64955ccbeb6f84f2a56d0e75c67fdd4
ed-villani/pattern_recognition_20201
/commons/classifiers.py
UTF-8
2,461
2.578125
3
[]
no_license
import warnings import numpy as np from commons.pdf import PDF, PDFTypes from commons.solver import solver def bayesian_classifier(points, classes, pdf, type='simple', **kwargs): def prior_probability(): n = None if type == 'simple': n = np.array([len(c.T) for c in classes]) ...
true
32e6b66bdf691c34a15d9b5c8ee7af851673ade1
manavnarang/HackerrankCertifications
/Python (Basic) Skills Certification Test/1.Python: Reverse Words and Swap Cases.py
UTF-8
1,876
4.46875
4
[ "BSD-3-Clause" ]
permissive
#Python: Reverse Words and Swap Cases #Implement a function that takes a string consisting of words separated by single spaces and returns a string containing all those words but in the reverse order and such that all cases of letters in the original string are swapped, i.e. lowercase letters become uppercase and upper...
true
fdf5387d2740beae9c266d11b31be09441e50a4c
ahnsoheee/Algorithm
/Baekjoon/10988.py
UTF-8
214
3.296875
3
[]
no_license
#No.10988 '팰린드롬인지 확인하기' word = list(input()) length = len(word) reverse = [] for i in range(length-1, -1, -1): reverse.append(word[i]) if word == reverse: print(1) else: print(0)
true
de823bc2e5d7d8606b64d35201c258aa99970da4
KMurphs/100DaysOf_ProjectEuler
/python/ProjectEuler_8.py
UTF-8
12,315
2.703125
3
[]
no_license
# The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. data = "\ 73167176531330624919225119674426574742355349194934=\ 96983520312774506326239578318016984801869478851843=\ 85861560789112949495459501737958331952853208805511=\ 12540698747158523863050715693290963295227...
true
286f66da3a67add5ec3229e08a6371636f28d785
AshWije/Computer-Vision-In-Python
/Basics/AdaptiveLinearStretching.py
UTF-8
2,454
3.53125
4
[]
no_license
# AdaptiveLinearStretching.py # # Description: # This program gets as inputs a window parameter (w) and names of the input and the # output images. The output image is computed from the input image by changing only # the L values such that L(i, j) is computed by applying linear stretching to the # window ...
true
53258422f0f9013a6dedd60674e2fd0026bcb724
nylocx/adventofcode2020
/day_16.py
UTF-8
1,925
3.03125
3
[]
no_license
#%% Part 1 import math import re import pandas as pd with open("day_16_input.txt") as input_data: rules_dict = {} while match := re.match(r"^((?:\w+\s?)+):\s(\d+-\d+)\sor\s(\d+-\d+)", input_data.readline()): rules_dict[match.group(1)] = [pd.Interval(*map(int, g.split("-")), closed="both") for g in mat...
true
6c916a15137d7ff279542fd9b6c82ced9328bd48
Killianmancheron/ReinforcementLearning
/Environnment/multi_controller.py
UTF-8
10,745
2.9375
3
[]
no_license
import numpy as np from .move import Move from .snake import Snake from .grid import Grid from random import randint class Abstract_Controller(): def __init__(self, grid_size=(15,15), nb_snakes=1, nb_apples=1): """Classe abstraite du controleur pour l'encapsulation de la grille Args: grid_size (tup...
true
b626842d49f0558eae400e4250760f1afc495ee3
migeed-z/benchmark_tools
/build/lib/benchmark_tools/Reader.py
UTF-8
7,024
2.609375
3
[]
no_license
import os import sys from copy import deepcopy from ast import FunctionDef, parse, ClassDef, Module, Assign from astor import to_source from os import listdir from os.path import isfile, join from benchmark_tools.constants import * from random import getrandbits, choice from benchmark_tools.constants import * def dat...
true
b170b5054e708d9d6758b0ccc97f0b3a93de6db1
Nirvedh/DeepPlaque
/resize.py
UTF-8
15,593
2.859375
3
[]
no_license
import SimpleITK as sitk import numpy as np def setup2d (array,img3d): """ This is to make the image 2d for resizing """ img = sitk.GetImageFromArray(array) img.SetSpacing(img3d.GetSpacing()[0:-1]) img.SetOrigin(img3d.GetOrigin()[0:-1]) #img.SetDirection(img3d.GetDirection()[0:-1]) cant do this so hoping direction...
true
d60faf475189a4ce5dedb8db5b6a8d3a24aab346
uchicago-cs/chiventure
/src/dsl/src/graphcode/graph_tests.py
UTF-8
2,055
3.234375
3
[]
no_license
""" This python file provides a test interface for testing all the different permutations of valid and invalid graphs that are checked for in the graph_validator.py file. The testing framework used is unittests and runs 7 different test cases on different graph inputs to check if the graph algorithms are working. To r...
true
7e12a490d982932e88ca202d7066dd898e8790b0
Manusp06/MachineLearningModelForDiabeticPrediction
/app.py
UTF-8
1,519
2.578125
3
[]
no_license
from flask import Flask, render_template,request import joblib #initialise the app app = Flask(__name__) model = joblib.load('dib_79.pkl') @app.route('/') def hello(): return render_template('form.html') @app.route('/home') def home(): return render_template('index.html') @app.route('/contact...
true
a78a73c0df6a1230466ae22b314dc6c95fad838e
berkercaner/pythonTraining
/Chap03/types.py
UTF-8
1,049
3.71875
4
[]
no_license
#!/usr/bin/env python3 # Copyright 2009-2017 BHG http://bw.org/ x = 7 y = """berker caner {}""".upper().format(9) print('x is {} {}'.format(x,y)) print(type(x),type(y)) z = 'berker "{1:<09}" "{0:>010}"'.format(8,1232) print(z) a = 8 w = f"it's {a} not {3}" print(w) b = 7 * 3.1415 #numeric type c = 7 / 3 d = 7 // 3 ...
true
3bf0efee2e0ca805ad52f606ec1d9a85384abdc1
GranthamImperial/silicone_examples
/src/plotting.py
UTF-8
8,112
3
3
[ "BSD-3-Clause" ]
permissive
"""Utility plotting functions""" import itertools import os.path import matplotlib.pyplot as plt import numpy as np from silicone.stats import rolling_window_find_quantiles def _plot_emission_correlations_quantile_rolling_windows( emms_df, output_dir, years, x_gas="Emissions|CO2", quantiles=None...
true
575f119373ac124323bdb8e2aed2f95bf35eaef7
shanetaz/budget_constrained_bidding
/src/gym-auction_emulator/gym_auction_emulator/envs/auction_emulator_env.py
UTF-8
3,344
2.609375
3
[ "MIT" ]
permissive
""" Auction Emulator to generate bid requests from iPinYou DataSet. """ import gym from gym import error, spaces, utils from gym.utils import seeding import configparser import json import os import pandas as pd class AuctionEmulatorEnv(gym.Env): """     AuctionEmulatorEnv can be used with Open AI Gym Env and...
true
ed113c020feb501ebab6bb152e76aabf46755c3d
Anth0nyWu/PythonSpider
/lianjia/lianjia/spiders/erShouFang.py
UTF-8
4,701
2.578125
3
[ "MIT" ]
permissive
import scrapy from ..items import LianjiaItem from ..settings import URL_FILE import csv import math import re class erShouFangSpider(scrapy.Spider): name = 'erShouFang' allowed_domains = ['lianjia.com'] # start_urls = ['https://www.lianjia.com/city/'] def start_requests(self): with open(URL_...
true
2f92a004e6fea2ee8d601bb4c4857f8c3a2a16bc
Aasavmp/Engmaths2
/partial_differentiation_functions.py
UTF-8
9,827
3.203125
3
[]
no_license
import sympy as sym import numpy as np import re import matplotlib.pyplot as plt from sympy import cos, sin, pi, sympify, exp from sympy import pprint, init_printing init_printing() x, y, z, i, j, k, t, u, v, r, a, b, c, n, L, w, T, s \ = sym.symbols('x y z i j k t u v r a b c n L w T s') A = sym.symbols('A', real...
true
3be9456eb0b396fc048489fa023a2424e4c36f4d
hoomanfor/python-crash-course
/02-variables-and-simple-data-types/2-6_famouse_quote_2.py
UTF-8
176
3.53125
4
[]
no_license
quote = "If you can't explain it to a six year old, you don't understand it yourself." famous_person = "Albert Einstein" message = f'{famous_person} once said, "{quote}"' print(message)
true
aaba1efce6a48d276904413f6100d08d2984962b
vignek/CodePractice
/Python-Recap/basics/tuples.py
UTF-8
202
3.78125
4
[]
no_license
""" Tuples : is similar to list. but it is immutable. """ a_tuple = ('a', 'b', 1, 2.0, '3') print(a_tuple) print(a_tuple[3]) print(a_tuple[3:]) print(a_tuple.index(2.0)) print(a_tuple.count(3))
true
af4714e3787a9af24a7dbc39d6334f4e555f5459
gregory-chatelier/fuzzy-logic
/app1_plot_linguistic_values.py
UTF-8
1,064
3.171875
3
[]
no_license
from matplotlib import pyplot as plt from fuzzy_system import * lfs = LeftFuzzySet(0, 35, 10, 12) tfs1 = TrapezoidalFuzzySet(0, 35, 10, 12, 15, 17) tfs2 = TrapezoidalFuzzySet(0, 35, 15, 17, 20, 25) rfs = RightFuzzySet(0, 35, 20, 25) # Plot 1 - Each linguistic value fig, axs = plt.subplots(1, 4, figsize=(14, 2.2),...
true
6949c4adbb6b15d95df094e5892c7976b66e09ce
dyf102/LC-daily
/dp/python/shortest-path-visiting-all-nodes.py
UTF-8
1,070
3.453125
3
[]
no_license
from collections import defaultdict, deque from typing import List def shortestPathLength(graph: List[List[int]]) -> int: """LC 847 Time complexity: O(N*2^N) Space: O(N*2^N) A pure BFS solution. It uses bit covery to store the status. Args: graph (List[List[int]]): [description] Return...
true
9d4530717bbb9f9a61c94c990dd899ec29bc3f3d
johanijbabaj/datamatrix_example
/Datamatrix.py
UTF-8
1,526
2.78125
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 18 23:40:23 2020 @author: eugeniy """ from pylibdmtx.pylibdmtx import encode from PIL import Image from docx import Document from docx.shared import Mm def marks_download (data=''): marks = [['123123323133dsfsdds3213ssdcfsdvsd12312','Обувь мужс...
true
31363c25d2ee774baae32e8f109526fd95b94944
JayWu7/Code
/leetcode_343.py
UTF-8
1,417
3.140625
3
[]
no_license
# class Solution: # def integerBreak(self, n: int) -> int: # ''' # # change the n to as more as possible number three. left transfer to two # ''' # # class Solution: def integerBreak(self, n: int) -> int: if n < 4: return n - 1 if n == 4: return 4 ...
true
6e5217fb591b002e36335b38b221e6deb388bdae
nicolashahn/set-solver
/classify_card.py
UTF-8
4,467
2.796875
3
[]
no_license
#!/usr/bin/env python """Classify a SET card image's color, shape, shade, number.""" import os import sys import cv2 from extract_shapes import extract_shapes_from_im from label_all_cards import manually_label_card from process_card import noteshrink_card_from_im from common import ALL_SHAPES_DIR, mean, jpgs_in_dir fr...
true
6eeae00d254da5dd8401d1abcf504b4107552b25
giandifra/vetrina
/main.py
UTF-8
15,955
3.0625
3
[]
no_license
import cv2 import numpy as np import time from PIL import ImageFont, ImageDraw, Image def overlay_with_opacity(bg, overlay, opacity): bg_copy = bg.copy() overaly_copy = overlay.copy() bg_h, bg_w, bg_c = bg_copy.shape base = np.zeros((bg_h, bg_w, bg_c), dtype='uint8') print(1 - opacity) cv2.add...
true
73e474694f1d49db985fd62932dc47afb028fbd1
Akavov/PythonDss
/Bones/bones.py
UTF-8
207
3.203125
3
[]
no_license
#demonstrate random func import random die1=random.randint(1,6) die2=random.randrange(6)+1 total=die1+die2 print("Pri broske vipalo",die1," and ",die2,"points, total",total) input("\n\nPush Enter to exit")
true
f9b6777ca85bfb4440c00d223087c3f675549b7d
wolganens/Computer-Science
/Artificial-Intelligence/TSP/main.py
UTF-8
1,391
3.359375
3
[ "MIT" ]
permissive
import sys # Pilha class Stack(object): def __init__(self): self.queue = list() def push(self, index): self.queue.insert(0, index) class TSP(object): """docstring for TSP""" def __init__(self, distances, src, target): self.distances = distances self.src = src self.target = target self.visited = set(...
true
09478669feff96af2cd8f6ec63969e1fae3db33d
huangyingw/submissions
/281/281.zigzag-iterator.233199355.Runtime-Error.leetcode.py
UTF-8
622
3.296875
3
[]
no_license
class Solution(object): def __init__(self, v1, v2): self.v1 = v1 self.v2 = v2 self.index_v1 = 0 self.index_v2 = 0 def next(self): result = -1 if self.index_v1 != len(self.v1) and self.index_v1 <= self.index_v2: result = self.v1[self.index_v1] ...
true
56b1e9028d486d877979db94a122c14781e95184
TakeaimK/TakeaimK.github.io
/assets/baekjoon/15629_Africa/python_15629.py
UTF-8
1,176
2.90625
3
[ "MIT" ]
permissive
def trip(): cost = 0 goSA = False goZam = False goZim = False num = int(input()) for _ in range(num): country = input() if country == "botswana" : cost = cost+0 if country == "ethiopia" : cost = cost+50 if country == "kenya" : ...
true
1b414e2a56eddddf3b0ddb4abdb070255b8f84c6
KataBharat/guvi
/codekata/print_specific_char_in_string.py
UTF-8
47
3.015625
3
[]
no_license
a,b = input().split() b = int(b) print(a[0:b])
true
1050ec14290b53cb30d202a63ac28b5b461b0716
Ghani-Haider/Algorithm-Design-and-Analysis-Project
/Kruskal.py
UTF-8
2,010
4
4
[]
no_license
# Kruskal's algorithm in Python import time class Graph_K: def __init__(self, vertices): self.V = vertices self.graph = [] def addedge(self, edge): self.graph.append(edge) # Search function def find(self, parent, i): if parent[i] == i: retur...
true
5395941e3f663b70afecead6bc49b5be9cd997b8
dguido1/cpsc471-ftp-project
/cli.py
UTF-8
15,908
2.921875
3
[]
no_license
""" *********************************************************************** Project: Programming Assignment School: California State University, Fullerton Course: CPSC-471 Term: Spring 2021 Authors: 1. Anthony Berton acberton1@csu.fullerton.edu 2. David Guido ...
true
0543279c00337293a099889977b561653e38ecf9
August1s/LeetCode
/Array/No26删除排序数组中的重复项.py
UTF-8
610
3.84375
4
[]
no_license
def removeDuplicates(nums) -> int: ''' # 由于删除操作会导致数组变化,所以反向遍历,这样前边元素下标不变 for index in range(len(nums)-1,0,-1): if nums[index] == nums[index-1]: nums.pop(index) return len(nums)''' # 题目说明不用考虑新长度之后的元素,所以可以使用双指针记录位置 if nums == []: return 0 i = 0 for j in rang...
true
6f861e620fc259085dd39a0b6ede210b24be5991
kushalj1997/interview-prep
/daily-coding-problem/1/dcp1.py
UTF-8
716
3.78125
4
[]
no_license
# Daily Coding Problem 1 # Given a list of numbers and a number k, return whether any two numbers from list # add up to k # example: given [10, 15, 3, 7] and k = 17 # return true since 10 + 7 is 17 def main(): nums = [10, 16, 3, 7] k = 17 # # brute force soln # for num in nums: # for num2 i...
true
463766ac4397e2684417f2e1ca951103eabd8f3d
tame0001/purdue
/ECE60146/Examples/DLStudio/playing_with_reconfig.py
UTF-8
2,179
2.640625
3
[]
no_license
#!/usr/bin/env python ## playing_with_reconfig.py """ Shows how you can specify a convolution network with a configuration string. The DLStudio module parses the string constructs the network. """ import random import numpy import torch import os, sys """ seed = 0 random.seed(seed) torch.manual_seed(se...
true
768ac11c99ace68664884210d56d7d6ea7237217
caldarolamartin/hyperion
/hyperion/view/simple_gui_examples/example_graph_gui.py
UTF-8
2,651
3.15625
3
[ "BSD-3-Clause" ]
permissive
import sys import pyqtgraph as pg from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout from hyperion.view.base_guis import BaseGraph, TimeAxisItem from pyqtgraph.Qt import QtGui class Example_graph(BaseGraph): """" This class exists to have a 'large' widget where a graph can be drawn upon. """ ...
true
d3981a4fbc508cfa478130d040080b372a7a5e5e
Aasthaengg/IBMdataset
/Python_codes/p02723/s884385960.py
UTF-8
127
3.421875
3
[]
no_license
# -*- coding: utf-8 -*- s = input() if s[0] != s[1] and s[2] == s[3] and s[4] == s[5]: print('Yes') else: print('No')
true
6604ae4097b81d7759cb69fc8c7378c15f17364f
girishkumaral/leet
/[977]Squares of a Sorted Array.py
UTF-8
997
3.546875
4
[]
no_license
# Given an integer array nums sorted in non-decreasing order, return an array # of the squares of each number sorted in non-decreasing order. # # # Example 1: # # # Input: nums = [-4,-1,0,3,10] # Output: [0,1,9,16,100] # Explanation: After squaring, the array becomes [16,1,0,9,100]. # After sorting, it become...
true
a4eb6d6902a4fb5f564794196b1d1fc66cc3851d
Ghalicb/AWGN-channel-text-transmission
/src/utility.py
UTF-8
3,569
3.6875
4
[]
no_license
import math import numpy as np def create_hadamard_matrix(N): """ Create a Hadamard matrix of size N. Parameters ---------- N : int Size of the Hadamard matrix (A power of 2) Returns ------- H_i : :py:class:`~numpy.ndarray` A NxN Hadamard matrix """ ...
true
9d44c0c5d196d15c88d33bdc6d8885f0541d8922
magcox5/Project2-Pandemic
/app.py
UTF-8
2,121
2.671875
3
[]
no_license
from flask import Flask, jsonify import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func ################################################# # Database Setup ################################################# engine = create_engine("...
true
a60e9ef7559291f83015f6cfdd18705a7899fedd
liangyongshi/pointCloudlectures
/lesson7/new_iss.py
UTF-8
4,813
2.59375
3
[]
no_license
import pandas as pd import argparse import open3d as o3d import os import numpy as np from pyntcloud import PyntCloud from open3d.open3d.geometry import PointCloud from open3d.open3d.utility import Vector3dVector from open3d.open3d.visualization import draw_geometries def load_data(): pointWithNormal=pd.read_cs...
true
e3f4ce970fe8b9e29e08faf612dc383e789498a2
sid-agrawal/ipop-ble-gsoc
/src/bt_on_device.py
UTF-8
2,013
2.78125
3
[ "MIT" ]
permissive
#!/usr/bin/python ''' This program is meant to be run on a BT enabled device, which is already connected to the BT enabled hub. This simulates a sensor pushed data to the BT enabled hub. ''' import argparse import datetime import logging import sys import time import bluetooth def device_handler(argv): ''' ...
true
da76b593040fa568328d53068cc71cabdf24dace
lesimon74/PeptideMovement
/2.Mobility_Score_1/Plot_2obi.py
UTF-8
1,753
2.53125
3
[]
no_license
# For 2obi numAA = 165 plt.figure() #SetToZero = np.array([0, 1, 2, numAA-3, numAA-2, numAA-1]) #mobility[SetToZero] = 0 plt.xlabel('AA No. from 0 to 164', fontsize=18) plt.ylabel('Mobility [arb. unit]', fontsize=18) plt.plot(mobility) plt.plot(mobility2) plt.legend(['old fit', 'new fit'], loc='upper left') #plt.legend...
true
9c4106438ff870bb3a73894402807dad46a831d1
jagannathbalachandran/websiteblocker
/block_websites.py
UTF-8
527
2.671875
3
[]
no_license
from shutil import copyfile def block(website): return "127.0.0.1\t" + website.replace("\n", "") + "\n" def block_websites_func(): print("Blocking websites") copyfile("/etc/hosts" ,"/etc/hosts_backup_before_blocking") with open("/etc/hosts", "a") as hostsFile: websitesFile = open("websites.txt...
true
06268a93869e57bd470e1d69bfefb998ee9ff173
JosephAlonzo/Proyecto-Python
/addNonWorkingDays.py
UTF-8
5,300
2.828125
3
[]
no_license
import tkinter as tk from tkinter import ttk import json import datetime import time from datetime import date,timedelta from tkinter import messagebox from Clases.calendarioExamenes import CalendarioExamenes from Clases.jsonConverter import jsonConverter from tkcalendar import Calendar, DateEntry class SubWindow(tk...
true
7d036b2f623041f3f9f42f1deb9f1bc4daf707e7
oleglr/algorithmic_toolbox
/week4_divide_and_conquer/2_majority_element/majority_element.py
UTF-8
615
3.625
4
[]
no_license
# Uses python3 # O(n) -- two consecutive loops def has_majority_element(vote_list): # make dictionary of counts avg_total_count = len(vote_list) // 2 votes_count = {} for vote in vote_list: if vote in votes_count: votes_count[vote] += 1 else: votes_count[vote] = ...
true
dbc446683a125aaebd7783d0ad1ccfc8f4ab81c7
pstjuste/pt_analysis
/scripts/p2p2012.py
UTF-8
5,007
2.75
3
[]
no_license
#!/usr/bin/env python import random import sys import math import networkx as nx import socialModels as sm out_file = None ids = None churn_rate = 0.000000 def add_random_ids(g): global ids ids = {} max_int = pow(2,64) for n in g.nodes_iter(): ids[n] = random.randint(0, max_int) def get_ra...
true
2894073976f83f3e15b860933622836bb4e3ad8f
SexChrLab/Cayo_X_inactivation
/archive/06_compare_distribution_btw_2_chr/chr10_chr16/scripts/determine_significant.py
UTF-8
905
2.671875
3
[]
no_license
# In this script, we want to determine whether the pvalue of the statistics tests are significant. Specifically, in the file /agavescratch/tphung3/Cayo_x_inactivation/compare_distribution_btw_2_chr/chrX_chr16/stats/PT101159/PT101159_heart_pvalues.txt, we want to add a column to indicate whether the pvalues are signific...
true
d14b6970de226ee089aaa2d4676cce3c0e0477f1
francomozo/fuaa
/practicos/practico3/visualizacion.py
UTF-8
2,018
3.4375
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 13 07:50:55 2019 @author: fuaa """ from matplotlib import pyplot as plt import numpy as np def visualizar_conjunto_entrenamiento(X, y): ''' Entrada: X: matriz de tamaño Nx3 que contiene el conjunto de puntos de entrenamiento expr...
true
be3e1e0a85425ff6e863a65d982bbbeb1b693318
Sidney2408/AI_miniproject
/eval.py
UTF-8
9,740
2.625
3
[]
no_license
import argparse import os import pickle import time import numpy as np import torch import torch.nn as nn import dataloader import mappings import model def evaluate_accuracy(net_answers, gt_answers): """Compute list of accuracies of all questions in minibatch. net_answers is the classification weights....
true