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
8fd2a020e45532cc4bccb93ed468fe3bf4386e1b
berrybab6/Gebeta
/display/views.py
UTF-8
861
2.515625
3
[]
no_license
from django.shortcuts import render from .models import Food,Chief import random # Create your views here. def addchief(request): ch=Chief.objects.all() return render(request,'aboutus.html',{'chief':ch}) def addfood(request): foodP=Food.objects.all().filter(promot=True) lis_prom=list(foodP) ch...
true
78472bfde934b95786cd00fb85babc13dd915db7
yashbhosale789/Jarvis
/Jarvis.py
UTF-8
1,890
2.859375
3
[]
no_license
import speech_recognition as sr import pyttsx3 import pywhatkit import datetime import wikipedia import pyjokes listener = sr.Recognizer() engine = pyttsx3.init() voices = engine.getProperty('voices') engine.setProperty('voice' , voices[0].id) s = pyttsx3.init() s.say('Hello Yash, I am jarvis, your persona...
true
5d464b45a80cf3ba0edd3cce341cb3ffcbb77d83
SuryaGitHub20/Python-pracetice1-Surya
/Add a new item dict.py
UTF-8
105
3.140625
3
[]
no_license
user={"Name":"Surya","Age":21} print(user) #add a new item and print user["Height"]=154 print(user)
true
2dbb767a3ff80e9c49f74c4c8f1b7d27cc11e7df
skylarstein/kitten-scraper
/kitten_report_reader.py
UTF-8
3,423
3.0625
3
[ "MIT" ]
permissive
from datetime import datetime import xlrd from kitten_utils import Log class KittenReportReader: ''' KittenReportReader will load animal numbers from the incoming daily foster report. All other data will be queried during runtime since other data in the report may already be outdated (or even initially inc...
true
9bb1fd1caca5383257d3bc77d561442ad0f62e74
ichan266/Code-Challenges
/Leetcode/Past Code Challenges/06-07-21 degreeOfArr.py
UTF-8
881
3.65625
4
[]
no_license
# Leetcode # 697 # % Easy (not for me...) # https://leetcode.com/problems/degree-of-an-array/ # Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements. # Your task is to find the smallest possible length of a (contiguous) subarray...
true
5df223033ef738e24fb0cd1cc925481ecff84b23
tartinesKiller/SFC-i18n-extractor
/main.py
UTF-8
1,468
2.640625
3
[]
no_license
import json import xml.etree.ElementTree import sys import os import glob def get_i18n_block(filepath): res = "" with open(filepath) as in_fh: while True: line = in_fh.readline() if not line: break if line.startswith('<i18n'): while True: ...
true
fc1bbeb2067e98f92527ec868b1d60f1c43a2845
paheimann/Data_Wrangling_Course_Project
/Lesson 6 Quizzes.py
UTF-8
3,398
2.796875
3
[]
no_license
##Exercise: Iterative Parsing def count_tags(filename): dict = {} for event, elem in ET.iterparse(filename): if elem.tag in dict: dict[elem.tag] += 1 else: dict[elem.tag] = 1 return dict ##Exercise: Tag Types lower = re.compile(r'^([a-z]|_)*$') lower_colon = re.co...
true
d1a53b8480e8cc25a462cfcefc3a80961839e92b
sharabhshukla/room_occupancy_prediction
/room_occupancy_model/preprocessors/pipe_preprocessors.py
UTF-8
1,502
2.78125
3
[ "MIT" ]
permissive
import numpy as np import pandas as pd from sklearn.base import TransformerMixin, BaseEstimator from feature_engine import missing_data_imputers as mdi from catboost import CatBoostClassifier def add_time_features(df): df['hour'] = df.index.hour df['dayofweek'] = df.index.dayofweek df['dayofmont...
true
077b8fb45a14e94997441827f630a1c1265f5c49
MorryGun/Rating
/dummy/calculator.py
UTF-8
1,431
2.546875
3
[]
no_license
from dummy.models import Result, ResultSchema from dummy.rate import check_current_rates, update_rate def calculate_rate(match_id): names = [] selected_matches = Result.query.filter(Result.match_id == match_id).all() points = [] players_points = {} for selected_match in selected_matches: ...
true
933fe7ded8f9b66d4557fd71b2ff2dc06ee5fa20
ssanbu08/RecSys_Implicit
/Iteration_3_DockerBuild/sparsematrix_V2.py
UTF-8
3,461
3.21875
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Fri Mar 24 16:53:41 2017 @author: anbarasan.selvarasu """ import pandas as pd import scipy as sp from scipy import sparse import numpy as np class UtilityMatrix(object): ''' This class takes the dataset and returns in a matrix format, Rows => Users ...
true
e3d447e6376c6612412149bb9593936d19166930
Shaigift/Python-Practice-1
/Chapt 5: If Statements/5-10 Checking Usernames.py
UTF-8
374
3.265625
3
[]
no_license
current_users = ['Pete', 'Kendra', 'Kia' , 'Kourtney' , 'Kiki'] new_users = ['Chris', 'Cody' , 'Carl', 'Charles' , 'Kourtney', 'KIKI'] current_users_lower = [user.lower() for user in current_users] for name in new_users: if name.lower() in current_users_lower: print(f' {name} new username required.') ...
true
aeeb6a0fd684337d4fe97f85d5d9f8d0276b9a00
AntoRojo16/Ejercicio3Unidad2
/claseMenu.py
UTF-8
1,119
3.09375
3
[]
no_license
import os class Menu: __switcher:None def __init__(self): self.__switcher={ 1: self.opcion1, 2: self.opcion2, 3: self.salir} def getSwitcher (self): return self.__switcher def opcion (self,op,cosechas,camiones): ...
true
f4600dca053961b155c0ba7f69df2ea0d22b8ae9
3xian/seiya-algolib
/graph/maxflow_dinic.py
UTF-8
1,180
2.890625
3
[]
no_license
from collections import deque inf = float('inf') def add_edge(graph, u, v, cap): graph[u].setdefault(v, [0, 0])[1] += cap graph[v].setdefault(u, [0, 0]) def dinic(graph, source, sink): flow = 0 dis = [-1] * len(graph) def bfs(): for i in xrange(len(dis)): dis[i] = -1 dis[source]...
true
250a4d8bacce4bc182d243196d1a472cba559035
vprusso/toqito
/tests/test_matrix_ops/test_outer_product.py
UTF-8
1,199
2.953125
3
[ "MIT" ]
permissive
"""Test outer_product.""" import numpy as np from toqito.matrix_ops import outer_product def test_outer_product(): """Test with two vectors, no complications.""" v1, v2 = np.array([1, 2, 3]), np.array([4, 5, 6]) expected_res = np.array([[4, 5, 6], [8, 10, 12], [12, 15, 18]]) np.testing.assert_equal(...
true
c0be523e32ae6cc7a5636b80b0b1e1df31f8927c
betarixm/visitor-log-bot
/src/db.py
UTF-8
2,203
2.875
3
[]
no_license
import sqlite3 class Database: def __init__(self, name): self.table = name self.con = sqlite3.connect(f"{name}.db") self.con.execute(f"CREATE TABLE IF NOT EXISTS {name} (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, display_name TEXT, io TEXT, datetime DEFAULT CURRENT_TIMESTAMP)")...
true
b7eb8069073a40c2555b8aba52c333d8f608c72c
carlosjdd/printer
/src/on_off.py
UTF-8
1,479
2.703125
3
[]
no_license
#!/usr/bin/python import rospy from std_msgs.msg import Bool from std_msgs.msg import Int16MultiArray import RPi.GPIO as GPIO # Callback for switching on the printer def callback_on(data): rec = data.data if rec == True: GPIO.output(14,GPIO.LOW) elif rec == False: GPIO.output(14,GPIO.HIGH) # Callback...
true
086d430c31330338e4014696f8c06b5b37c0712d
20after4/mpp-solar
/mppsolar/outputs/hass_mqtt.py
UTF-8
2,028
2.546875
3
[ "MIT" ]
permissive
import logging from .mqtt import mqtt log = logging.getLogger("MPP-Solar") class hass_mqtt(mqtt): def __str__(self): return """hass_mqtt - outputs the to the supplied mqtt broker in hass format: eg "homeassistant/sensor/pm_{tag}_{key}/state" """ def __init__(self, *args, **kwargs) -> None: ...
true
4fbcae44c2a31ef240772e5a27e90b345846fb32
tumugip/kolab
/kolab/pj/string.py
UTF-8
12,885
2.875
3
[ "MIT" ]
permissive
import csv import pathlib # Read DIC DIC = {} base = pathlib.Path(__file__).parent.resolve() def load_dic_from_file(filename): with open(f'{base / filename}') as f: d = [] for w in f.readlines(): w = w.strip() if len(w) == 0 or w.startswith('#'): continue ...
true
ca1a21b0fe7a87e35f09145b30ca0d0f826a95fe
athletejuan/TIL
/Algorithm/BOJ/13_brute_force/10819.py
UTF-8
521
2.78125
3
[]
no_license
N = int(input()) arr = list(map(int, input().split())) sel = [0] * N check = [0] * N max_val = 0 def perm(idx): global max_val if idx == N: total = 0 for i in range(N-1): total += abs(sel[i] - sel[i+1]) if not max_val or total > max_val: max_val = total else...
true
5720f12f64bde5e6f3f732e899684cab4cdf5ff4
DaHuO/Supergraph
/codes/CodeJamCrawler/CJ_16_2/16_2_1_noidgoten_main.py
UTF-8
1,253
2.8125
3
[]
no_license
file = open('put.in', 'r') fil3 = open('put.out', 'w') t = int(file.readline()) toString = ["ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"] toInt = {} i = 0 for s in toString: toInt[s] = i i += 1 def count(string, res): for chr in string: if chr i...
true
db3a85e42d096ec7e132484d9771cd75f7d51d2a
MateuszBelczowski/warsztaty-python-snake
/slajdy/build/for2.py
UTF-8
86
3
3
[]
no_license
print("początek") imie = "" for litera in imie: print(litera) print("koniec")
true
bf7bdbad04c41790c1a11037a1cb9d8a3cad577d
strigazi/athena
/Trigger/TriggerCommon/TriggerMenu/scripts/compare_rulebook_xml.py
UTF-8
3,181
2.546875
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env python # Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration import sys import os import commands import time import xml.etree.cElementTree as ET if len(sys.argv)<3: print "Need to give RuleBook and rel (e.g. rel_1) in the input" sys.exit() file = sys.argv[1] rel = s...
true
3c8b9cc2d4041edda5698b4d00f264b5641d759a
jonaths/pythonrisk
/riskmapper.py
UTF-8
841
3.40625
3
[]
no_license
#!/usr/bin/python import sys class RiskMapper: def __init__(self): self.riskmap = [] @staticmethod def getMap(state): # Hacer esto bien. Las minas las deberia recibir del constructor # y el constructor se deberia de generar en el programa principal para # poder almacenar...
true
69a4325b7501358098973b59809331f7c7de4ca2
ayushprd/Air-O-Analysis
/converter.py
UTF-8
757
3.359375
3
[]
no_license
#Converts a CSV file to list of dictionaries #To access elements based on keys stored the list index and then # simply print with the key as show below #dict=dict_list[0] #print(dict['Year']) import csv import sys import pprint row = ['Year', ' Month', ' Date' ,'Latitude','longitude','AOD1','AOD2','STD3'] with o...
true
2df3c703d34f5d6c235728250275dc4312e373be
xtian0/NovelSpider
/Novel.py
UTF-8
617
2.609375
3
[]
no_license
import requests from lxml import etree urls =['https://www.qishulou.com/dushi/zhang/{}.html'.format(i) for i in range(5294878,5295019)] path = r'zhangzhongzhiwu/' def get_txt(url): r = requests.get(url) r.encoding = 'utf-8' selector = etree.HTML(r.text) title = selector.xpath('//*[@id="nr_title"]/tex...
true
5190ca05874de9fac24bf6835139019010b00a56
pnerbun/data-wrangle-openstreetmaps-data
/users.py
UTF-8
536
2.71875
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sat Jun 06 16:21:49 2015 @author: Home """ import xml.etree.ElementTree as ET import pprint def get_user(element): return def process_map(filename): users = set() for _, element in ET.iterparse(filename): if "uid" in element.attrib: ...
true
4d6f8332adbfb6f19ca12ff7f33d94d4c9dcab9b
a2k-Oleksii/itvdn_python_starter
/less_5_list/list_task_1.py
UTF-8
146
3.5625
4
[]
no_license
my_list = [1, 2, 3, 4, 5, 6] even_list = [] for element in my_list: if element % 2 == 0: even_list.append(element) print(even_list)
true
e6fa870ca95dcd69dc112164f8a1a094576f631c
s-gpu/Hackerrank.com
/Python 2/Diagonal Difference.py
UTF-8
200
2.953125
3
[]
no_license
#!/usr/bin/python n = input() ar = [] for _ in xrange(n): ar.append(map(int, raw_input().split())) s1 = 0; s2 = 0 for i in xrange(n): s1 += ar[i][i] s2 += ar[n-i-1][i] print abs(s1 - s2)
true
78f45c8df6a3c8dc278d45937d1df4b89fc36337
elielkoutinho/miniblog_II
/learning_logs/models.py
UTF-8
828
2.546875
3
[]
no_license
from django.db import models # Para deixar cada assunto e entrada com seus respectivos usuários from django.contrib.auth.models import User class Topic(models.Model): text = models.CharField(max_length=200, verbose_name='assunto') date_added = models.DateTimeField(auto_now_add=True, verbose_name='Data') owner = ...
true
0e71d69af18611aec60d84e1d28b1286024c5a40
Hydrospheredata/hydro-serving-integrations
/hydro_integrations/aws/sagemaker/utils.py
UTF-8
534
3.125
3
[]
no_license
import urllib.parse def validate_non_empty_uri( uri: str, require_schema: bool, require_netloc: bool, require_path: bool ): """ Validate uri for non-empty schema/netloc/path. """ parse = urllib.parse.urlparse(uri) if require_schema: assert parse.scheme, f"Schema sho...
true
67c3db33f9d08c42c5e40bba7a2b570e6a3e634b
YC-Hsu/BI
/split.py
UTF-8
418
2.921875
3
[]
no_license
file_list = ['dict/index.adj','dict/index.adv','dict/index.noun','dict/index.verb'] d = dict() for file_index in file_list: f = open(file_index) index = 0 while True : i = f.readline() if i=='': break reg = i.split() if index>=29 and reg[0] not in d: #print(reg[0]) d[reg[0]] = -1 index += 1 f.clo...
true
bd6b134b5fc64cf2a71bb6f7709c3af90f559dd7
rgresia-umd/fml-wright
/fmlwright/core/data_sources/images.py
UTF-8
672
2.90625
3
[]
no_license
import matplotlib.pyplot as plt def save_image_gdf(areas_gdf, file_path): """Save a geodataframe as an image. Args: areas_gdf (gpd.GeoDataFrame): geodataframe to store. expects a 'colors' column. file_path (str): File name and path. """ fig, ax = plt.subplots(figsize=(10, 10)) are...
true
0807e1a3ce696ef894b0ec921179c2427fcfe524
LukeMoll/pyuoyweek
/uoyweek/__init__.py
UTF-8
5,382
3.609375
4
[ "BSD-3-Clause" ]
permissive
#!/usr/bin/env python3 from datetime import date, timedelta from calendar import day_name, day_abbr from argparse import ArgumentParser from typing import Union def main() -> None: parser = ArgumentParser() parser.add_argument("-s", "--short", help="Prints a shortened version of the date, abbreviating the ter...
true
75e19d660b11d862ac9c7b872abe7e8df8010510
Im-OMkar/Skin-Cancer-Detection
/process_data.py
UTF-8
1,312
2.828125
3
[]
no_license
#Sort images to subfolders first import pandas as pd import os import shutil #skin_df = pd.read_csv('data/HAM10000/HAM10000_metadata.csv') data_dir = os.getcwd() + "/data/all_images/" dest_dir = os.getcwd() + "/data/reorganized/" skin_df2 = pd.read_csv('data/HAM10000/HAM10000_metadata.csv') print(skin_df2['dx'].v...
true
f3b9fd750af79558aa491ea907e32a33a68716cc
GanapathiAmbore/Python_Programms
/convert_list_to_file.py
UTF-8
104
3.40625
3
[]
no_license
with open("numbers.txt",'w') as f: for i in range(101): f.write("%s\n"%i) print(i)
true
ab00cc3a1f7786680976e09df5d82e320f9b702e
MasnekovIvan/Algorithms-in-Python
/Algorithms_14.py
UTF-8
1,566
3.984375
4
[]
no_license
# Tony Hoare`s sort (Quicksort) def hoare_sort(A): """ Сортировка Тони Хоара (Quicksort) """ if len(A) <= 1: return barrier = A[0] L = [] M = [] R = [] for x in A: if x < barrier: L.append(x) elif x == barrier: M.append(x) else: ...
true
9ff654607d2a6ee3e6d830429490606b85e81152
bert799/EP1-Craps
/Craps.py
UTF-8
8,487
3.546875
4
[]
no_license
""" Exercício 1 design de software EP1 objetivo: simular jogo de apostas Craps Autor: Bernardo Cunha Capoferri python ver.: 3.7.4 64-bit, Coded in VScode """ # Importa Funções das apostas e randint import FuncaoApostas as FA from random import randint # Começo do jogo def comeco_jogo(): # valor booleano que decide s...
true
47beba34b26c96a9fc7348080cf25ca67691d3b0
Linus-MK/AtCoder
/ABC_6q/abc163d.py
UTF-8
257
2.859375
3
[]
no_license
n, k = list(map(int, input().split())) mod = 10 ** 9 + 7 ans = 0 for p in range(k, n+2): minimum = p * (p-1) // 2 # 0〜(p-1)の和 maximum = p * (2*n - p + 1) // 2 # (n-p+1)〜nの和 ans += maximum - minimum + 1 ans %= mod print(ans)
true
d4a565a64fcdc8bd9fc27f900cda67da4fa9c4a0
felipecgonc/deephack2019
/streamlit/renda_e_gastos.py
UTF-8
6,987
3.078125
3
[ "Apache-2.0" ]
permissive
import streamlit as st import pandas as pd from matplotlib import pyplot as plt import seaborn as sns from fbprophet import Prophet from datetime import datetime def get_last_day_of_month(month): if month == 2: return 28 elif month in [1, 3, 5, 7, 8, 10, 12]: return 31 elif month in [4, 6,...
true
285e562734d88224f328342f9acc752ae99d780d
swapnilsude/footballapp
/footballapp.py
UTF-8
4,863
2.578125
3
[]
no_license
#!/usr/bin/env python3 import argparse import json from bs4 import BeautifulSoup import urllib.request import pandas as pd class FootballApp(object): def __init__(self, league, team, results, fixture): super(FootballApp, self).__init__() self.league = league self.team = team self.results = results self.fix...
true
e2eff8dce63bc74af628f1e79c8cc272e6858fab
tps12/Dorftris
/globe.py
UTF-8
1,407
3.203125
3
[]
no_license
from math import pi, sin from numpy.fft import fft class GlobeFreq(object): res = 128 @classmethod def sample(cls, globe): samples = [] dphi = pi / cls.res for i in range(cls.res): phi = i * dphi - pi/2 n = int(2 * cls.res * sin(phi + pi/2) + 0.5)...
true
005197a6b4008d040c21bb05c51a8fc20c728ca0
ak-sergeev/Learn-Algorithms-and-data-structures
/Search/Binary-Search/Binary-Search-Recursive.py
UTF-8
1,360
4.1875
4
[]
no_license
def binary_search(array, value, min_index=None, max_index=None): """ Возвращает индекс искомого элемента (value) в отсортированном массиве (array). Если в массиве более одного искомого элемента, то функция не гарантирует, что найденный будет первым. Возвращает -1 если элемент не найден. """ ...
true
b547314ec529f2fe15f0ad36c5a821333336dac8
egeodaci/comp551-2020-p1-logistic_regression_and_naive_bayes
/code/plotting/cost_vs_iterations.py
UTF-8
1,679
3.109375
3
[]
no_license
import time import matplotlib.pyplot as plt from datasets.load_dataset import get_dataset from linear_model.logistic_regression import LogisticRegression from model_selection.train_test_split import train_test_split from preprocessing.standard_scaler import feature_scaling from utils.datasets_enum import Datasets def...
true
74ef0c2e3e064e2556be8d9291e1cc31887661da
dblanchet/Bug-Arena
/kinect.py
UTF-8
8,603
2.828125
3
[]
no_license
""" Kinect.py Interface to the kinect hardware. """ from collections import namedtuple import numpy try: import freenect except ImportError: freenect = None print "Kinect module not found. Faking it" __all__ = ['get_buffers', 'set_default_data', 'z_to_cm', 'x_to_cm', ...
true
45a2626383bc0c625ed90b1541217573f14b4534
cybertengu/Puzzles2020
/day15.py
UTF-8
1,910
3.28125
3
[]
no_license
def SolveDay15(filepath): print('Start of day 15 part 1.') SolveDay15A(filepath, 2020) #SolveDay15A(filepath, 10) print('End of day 15 part 1.') print('Start of day 15 part 2.') SolveDay15A(filepath, 30000000) print('End of day 15 part 2.') print('End of day 15.') def SolveDay15A(filepa...
true
b07789534dea645ae3a6b295f84d7acb84ba6a1f
Matos-V/PDS_UFCG
/Filtros/Python/filtro_rejeita_faixa_3khz.py
UTF-8
2,426
2.640625
3
[ "MIT" ]
permissive
#%% import numpy as np import matplotlib.pyplot as plt from numpy import ones,zeros, pi # %% plt.rcParams['lines.linewidth'] = 3 plt.rcParams['font.size'] = 25 plt.rcParams['figure.figsize'] = [16,12] #%% M = 300 N = M + 1 wc1 = 20 wc2 = 55 ws = 3000 kp = int(N*wc1/ws) kr = int(N*wc2/ws)+1 #%% A = ones(N) A[kp:kr] ...
true
792e3c4204692ad8d7e813104f4b3139d48a871e
joeyism/Yahoo-Fantasy-NBA-simulator
/lib/cache.py
UTF-8
543
2.703125
3
[]
no_license
import os import pickle CACHE_FOLDER = './.cache' if not os.path.exists(CACHE_FOLDER): os.makedirs(CACHE_FOLDER) def get_cache(path, fn, verbose=False, *args, **kwargs): filepath = os.path.join(CACHE_FOLDER, path) if os.path.exists(filepath): if verbose: print(f"Cache found in {filepath}. Loading...")...
true
b78f0c4091a68f22155bb450981806238da9b9ae
Nooralwachi/almost_equal.py
/check_eq.py
UTF-8
1,463
3.328125
3
[]
no_license
from collections import defaultdict def check_eq(filename): with open(filename, 'r') as f: for line in f: words=defaultdict(list) flag=0 items= line.strip().split(', ') if len(items) <2: x=items[0] y=' ' else: x,y=items print() print(x,y) print(almost_equal(x,y)) def almost_equa...
true
da6d130d4865210bb56ba6f3118bd888c912f6aa
martincmartin/MathematiciansAssistant
/Parser.py
UTF-8
7,835
3.078125
3
[ "Apache-2.0" ]
permissive
from Expression import * from tokenize import * # type: ignore from typing import List import io import token # Look! A yak! I think I'll shave it... class Parser: type: Union[int, str] token: TokenInfo tokens: List[TokenInfo] keywords = {"in", "and", "or", "not", "==>", "<==>", "forall", "exist...
true
08d8dd872eb46809a6b9f0951d4f0a574174d964
adongxu/Python-Data-Visualization
/demo15.py
UTF-8
543
3.03125
3
[]
no_license
import matplotlib.pyplot as plt plt.figure(0) # from index 0 while figure.add_aubplot from index 1 axes1 = plt.subplot2grid((3,3),(0,0),colspan=3) axes2 = plt.subplot2grid((3,3),(1,0),colspan=2) axes3 = plt.subplot2grid((3,3),(1,2)) axes4 = plt.subplot2grid((3,3),(2,0)) axes5 = plt.subplot2grid((3,3),(2,1),colspan=2) ...
true
d152916196ff4743c4a07146039cbfb920f19b6a
Tishacy/Algorithms
/code/0 pick_based_on_prob.py
UTF-8
2,648
4.34375
4
[]
no_license
# -*- coding: utf-8 -*- """Given an array with each element has a probability, choose one element according to its probability. 0.1 Giant array pool method step 1: Generate a new array by repeating the each element for multiple times according to its probability. step 2: Randomly pick one from the array. 0.2 ...
true
de03c8b1a39526baae4d16af41c470f8616daedc
todd-trowbridge/python-rpg-game
/Goblin.py
UTF-8
280
3.515625
4
[]
no_license
from Character import Character from random import randrange class Goblin(Character): def __init__(self): self.health = 18 self.max_power = 6 self.power = 6 def print_status(self): print(f'The goblin has {self.health} health and {self.power} power.'.upper())
true
c819b15c7961c176e1c425212d7509a3a58677e5
JStocke12/pillow_test
/test.py
UTF-8
308
2.671875
3
[]
no_license
from PIL import Image width = 256 height = 144 img = Image.new('RGB', (width, height)) px = img.load() for i in range(width): for j in range(height): px[i,j] = (0, 0, 0) if (height/2-j)**2+(i-width/2)**2>4096 or (height/2-j)**2+(i-width/2)**2<3136 else (255, 255, 255) img.save('image.png')
true
3df4871093cd28ecaa841e2ddf71fafb94f7190b
arall/wwitt
/python/dns_solver.py
UTF-8
2,812
2.96875
3
[]
no_license
# Async DNS solver # Solves DNS by using a thread and blocking import socket import select import time import re from threading import Thread from threading import Semaphore # Status: 0,1,2,3 (working) 98,99,100 done (or err) class DNS_Solver(Thread): class dns_item: def __init__(self,host): self._host = hos...
true
d36085ff00a4da4d241328b01b997280797dee2a
aswinichejarla/python
/42.py
UTF-8
96
2.859375
3
[]
no_license
n,m=map(str,raw_input().split()) if(n==m): print n elif(n>m): print n else: print m
true
5d4c80645049a21ac4ff24ed62a7c5b053e9f832
SnehankaDhamale/Python-Assg-WFH-
/Assignment6/ex9.py
UTF-8
200
4.09375
4
[]
no_license
#Write a Python program to print multiplication table of any number. no=int(input("Enter the number:")) print("Multiplication table of ",no) for i in range(1,11): no1=no*i print(no1,end=' ')
true
14f5b853dcd6219ccae38b79a5b13793ea504d26
sshahrier/genone
/projects/ragnaturn/classes/util/character.py
UTF-8
1,155
3.75
4
[]
no_license
class Status: def __init__(self): # Initial Stats Properties self.stats = {'hp': 1500, 'atk': 5, 'agi': 5, 'vit': 5, 'dex': 5, 'luk': 5} def stat_assign(self, stat, val): self.stats[stat] += val class Character(Status): def __init__(self, name): # Initial Char Properties ...
true
dd524ec8f4d3ce53291821f0a42830b7f496f0ed
Developerdanish/Practical
/Practical/Data File Handeling/Text Operation.py
UTF-8
71
2.734375
3
[]
no_license
f = open('sample.txt', 'r') a = f.read().split() print a f.close()
true
9d352cba2ec39ab9faa0b75c7a59bbc06551cf92
asmodehn/hungry_happy_pets
/app/schemas/animals.py
UTF-8
3,533
2.75
3
[]
no_license
try: from ._bootstrap import ma from .models import Animal, Species from .species import SpeciesSchema except SystemError: # in case we call this module directly (doctest) from _bootstrap import ma from models import Animal, Species from species import SpeciesSchema from marshmallow import fi...
true
acc200c479941759928ad3a8ad1540a9d1fe1e8d
Wahakalaka/flow-algo-trader
/fa_trader/__init__.py
UTF-8
3,223
2.65625
3
[]
no_license
from datetime import datetime class FATrade: """Represent trades as objects for ease of filtering and calculating""" def __init__(self, date, time, ticker, expiry, strike, cp, spot, qty, price, trade_type, volume, oi, premium, sector, unusual): self.unusual = False if unusual == 'FALSE' else True ...
true
2a5e1406894e19f222c16867fa3830cf434c7547
paulgarias/RutgersGroupProject1
/rudatasciproject1/geoTime.py
UTF-8
2,601
2.96875
3
[]
no_license
import numpy as np from datetime import datetime from uszipcode import ZipcodeSearchEngine search = ZipcodeSearchEngine() def createLatitude(latlng): try: #print(latlng) # This removes paranthesis latlngArray = latlng.strip("(").strip(")").split(",") lat,lon = np.round(np.float(lat...
true
4292a5fd2ffe92334f34f09968fcce9f0680f9d6
HiradEmami/MARL
/network.py
UTF-8
6,690
3.1875
3
[]
no_license
import numpy as np import tensorflow as tf import os, time os.environ['CUDA_VISIBLE_DEVICES'] = '' # Disables GPU - likely more efficient when feeding one by one # Possible activation functions hid_act = {"linear": None, "sigmoid": tf.nn.sigmoid, "relu": tf.nn.relu} out_act = {"linear": None, "softmax": tf.nn.softma...
true
cc90585d241e0239a5e657967cea54310cb807f7
ajuravle/Chatbot
/memory/memory.py
UTF-8
4,394
2.53125
3
[]
no_license
from spacy.symbols import * first_person = ["me", "i", "mine", "my", "we", "ours"] pron_translate = dict() pron_translate["me"] = "you" pron_translate["i"] = "you" pron_translate["mine"] = "your" pron_translate["my"] = "your" pron_translate["ours"] = "your" pron_translate["we"] = "you" class Memory: def __init_...
true
f939c93023dca893cafb8a07e562a067ea5854fb
cSchubes/speedwaybricks-sxsw19
/hit_obstacle.py
UTF-8
1,117
3.90625
4
[]
no_license
import LowPassFilter This basically just a filter to check to make sure the robot pitch and roll angles do't change too fast. If they do, we probably hit an obstacle. ## To implement: create one of these classes for pitch, and one for roll ## Then in every control loop cycle, get the new roll and pitch and call ## t...
true
ad82792ddfe5f97fc080a66da27d5fa1430f7ff8
sagarkar10/smartDocScanner
/detect_and_segment.py
UTF-8
1,907
3.015625
3
[ "MIT" ]
permissive
# %%writefile detect_and_segment.py #imports import glob import cv2 import numpy as np from operator import itemgetter import matplotlib.pyplot as plt import tqdm # visualize better inline %config InlineBackend.figure_format = 'retina' def img_thresh(path): image = cv2.imread(path, 0) # read grayscale directly ...
true
093a30655fa37e8d886507fbb70bc594ca5cea5f
KseniiaKarpova/memristive-spinal-cord
/GRAS/plot_results.py
UTF-8
4,205
2.703125
3
[ "MIT" ]
permissive
import os import sys import pylab as plt import logging as log from matplotlib.ticker import MaxNLocator log.basicConfig(format='[%(funcName)s]: %(message)s', level=log.INFO) logger = log.getLogger() def read_data(path): names = [] voltage = [] g_exc = [] g_inh = [] spikes = [] for filename in filter(lambda ...
true
13b415bc13a93572f8794631c68f2aa36ad10930
listar0810/jupyterlab-snippets-multimenus
/example_snippets/multimenus_snippets/Snippets/SciPy/Interpolation and smoothing splines/splrep splrev.py
UTF-8
174
2.59375
3
[ "BSD-3-Clause" ]
permissive
x = np.arange(0, 2*np.pi+np.pi/4, 2*np.pi/8) y = np.sin(x) tck = interpolate.splrep(x, y, s=0) xnew = np.arange(0,2*np.pi,np.pi/50) ynew = interpolate.splev(xnew, tck, der=0)
true
29829a8af3c4303923a781fcf359a5e2bec44c4f
cjeiy/Wumpus
/Wump_Graph.py
UTF-8
30,769
3.109375
3
[]
no_license
import sys from tkinter import * import random import sys import time import os from random import choice from operator import attrgetter root = Tk() root.after(1000, lambda: root.focus_force()) root.wm_attributes("-topmost", 1) root.geometry("500x400") root.wm_title("Wumpus") root.configure(background='black') cla...
true
24ec0661d6edaa684b236a71804c72c13faf1a15
samhithaaaa/Hashing-1
/groupanagrams.py
UTF-8
983
4.09375
4
[]
no_license
class Solution(object): def groupAnagrams(self, strings): """ create a hashmap with key as sorted string and value as a list of values when a new string comes, check whether it exists in the hashmap or not, if it exists add the values to the list of the values for that hashed string ...
true
a2f61bf83d991e7ff7cd19b264bbc543904488d8
martinohanlon/adventofcode
/2020/2/day2.py
UTF-8
880
3.390625
3
[]
no_license
from collections import namedtuple Password = namedtuple('Password', ['letter', 'lower', 'upper', 'password']) with open("day2passwords.txt") as f: data = f.readlines() # parse passwords passwords = [] for line in data: # split out the parts rule = line.split(": ")[0] password = line.split(": ")[1].s...
true
7bffac8b5c5979a06dff4ad13a985d15dd489e8f
inteq13/lec2-demo
/fd-accuracy.py
UTF-8
750
3
3
[]
no_license
from __future__ import division import numpy as np import numpy.linalg as la c = 20*2*np.pi def f(x): return np.sin(c*x) def df(x): return c*np.cos(c*x) h_values = [] err_values = [] for n_exp in xrange(5, 24): n = 2**n_exp h = (1/n) x = np.linspace(0, 1, n, endpoint=False).astype(np.float...
true
8ba8c19d5bdccf270739f7df30756928dbc5997c
stevenhorsman/advent-of-code-2019
/day-24/test_planet_of_discord.py
UTF-8
613
2.6875
3
[]
no_license
import planet_of_discord import fileinput def test_part1_example_1(): data = """ ....# #..#. #..## ..#.. #...."""[1:] assert planet_of_discord.part1(data) == 2129920 def test_part1(): with open(planet_of_discord.input_file) as f: data = f.read() expected = 1151290 assert planet_of_discord.part1(data) ==...
true
48b6932b779a5582c91f0e1fb10008bfe96c1681
vasil-panoff/Python_Fundamentals_SoftUni_May_2020
/PYTHON_FUNDAMENTALS_May_August_2020/Exersice_22_05_2020__Python_Fundamentals_Basic Syntax_Conditional_Statements_Loops/Jenny's_Secret_Message.py
UTF-8
245
3.8125
4
[]
no_license
name = input() if name == "Johnny": print("Hello, my love!") else: print(f"Hello, {name}!") #alt solution #name = input() #message = "Hello, " #if name == "Johnny": # message += "my love!" #else: # message += f"{name}!" #print(message)
true
822e0ee20936a2ad25e51f47550d6870455ffcff
ibanknatoPrad/Rolex-RocketLeague
/bot_code/trainer/utils/floating_setup/floating_setup.py
UTF-8
2,005
2.9375
3
[ "MIT" ]
permissive
""" A utility function such that you can test/train in-air controls without ever landing. """ import time from bot_code.trainer.utils.floating_setup import bakkes from random import random # Calling bakkesmod too often may cause a crash. # Therefore ratelimit it by dropping some calls. MIN_DELAY_BETWEEN_BAKKES_CALLS ...
true
9a49b978396339ea53d75630e09bba3f8554b3cb
maede97/MinusMinusEnergy
/src/client/broker/fillBulkData.py
UTF-8
2,110
3.125
3
[ "MIT" ]
permissive
#!/usr/bin/env python3 import random import sqlite3 from sqlite3 import Error import numpy as np def create_connection(db_file): """ create a database connection to the SQLite database specified by db_file :param db_file: database file :return: Connection object or None """ try: con...
true
a2a1c82c949679df069000f1a984afd38f3474d3
tggithub619/Codewars_Python
/7 kyu The Baby Years I - Baby Counting.py
UTF-8
894
3.75
4
[]
no_license
#https://www.codewars.com/kata/5bc9951026f1cdc77400011c def baby_count(x): x = x.lower() b = x.count("b") // 2 a = x.count("a") y = x.count("y") return min(b, a, y) if min(b, a, y) > 0 else 'Where\'s the baby?!' # Test.assert_equals(baby_count('baby'), 1) # Test.assert_equals(baby_count('abby'), ...
true
6107b688d206014e6186374b742cba193480a6d8
starcigi/MyProjectPythonLearn
/nianjisuan.py
UTF-8
140
3.25
3
[]
no_license
DaysPerYear = 365 HoursPerDay = 24 MinutesPerHour = 60 SecondsPerMinute = 60 print(DaysPerYear*HoursPerDay*MinutesPerHour*SecondsPerMinute)
true
1b78313d1e6687ef76ec9a45907976c242bc4c03
HumKariuki/Data-Structures
/prac29.py
UTF-8
487
3.234375
3
[]
no_license
Username='hum' password='9679' access=False attempts=0 while True: access=True attempts+=1 pin=input('Enter your password: ') username=input('Enter you username: ') if attempts<=3 and pin==password and username==Username: print(f'attempt {attempts}') print(f'welcome {username}') ...
true
63548192d34528f1bb66469d82698ed55ffbf9e5
adwitiya/hashcode_pizza
/pizza.py
UTF-8
2,207
2.59375
3
[]
no_license
from __future__ import print_function import sys import numpy as np def read_file(filename): '''Read File''' with open(filename, 'r') as f: line = f.readline() rows, cols, min_ingr, max_size = [int(n) for n in line.split()] pizza = np.zeros([rows, cols]) for row in range(rows...
true
b97988b42ca244804b6d351a6366ff0309120908
jjdenis/diagrama_caja
/src/html.py
UTF-8
2,129
2.640625
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- import codecs from string import Template class Html(object): def __init__(self): self.rows = '' self.pars = '' def add_line1(self, filename1, filename2): html_svg1 = IMG.substitute(path=filename1, nombre=filename1) html_svg2 = I...
true
16243c67a5dfdf7623698d5e25e9e8f2edfe0ecc
StevenDuffy/Flask-Python-Weather-Forecast-App
/FlaskWeatherStation/main.py
UTF-8
3,638
2.703125
3
[]
no_license
from flask import Flask, render_template, url_for, flash, redirect, request, session, abort import requests import simplejson as json from urllib.request import urlopen from getforecast import get_forecast import datetime from database import database from functools import wraps import os from hash import hash...
true
f0a33ae4e196f3512b93182541001de2dfa40634
Hygens/hackerearth_hackerrank_solutions
/python_problems_competitive/roy_and_profile_picture.py
UTF-8
224
2.75
3
[]
no_license
L=int(raw_input()) N=int(raw_input()) while N>0: N-=1 W,H=map(int,raw_input().split()) if (W>=L and H>=L and W==H): print("ACCEPTED") elif (W<L or H<L): print("UPLOAD ANOTHER") else: print("CROP IT")
true
79ba6b402b383092a71f43d4d5fe0c86eb089392
leaffan/geo
/polygon_point_sampler/utils.py
UTF-8
621
3.25
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- from random import random from bisect import bisect_right class WeightedRandomGenerator(): def __init__(self, weights): self.totals = list() running_total = 0 for w in weights: running_total += w self.total...
true
2d50eec28ae59d03c10aee2503b1f882ad6ccf6c
chenhao-ZZU/DGL_Zachary
/mod.py
UTF-8
1,142
3.296875
3
[]
no_license
import dgl import warnings import torch as th import matplotlib.pyplot as plt import networkx as nx warnings.filterwarnings('ignore') # 创建DGL图对象g g = dgl.DGLGraph() # 添加10个节点 g.add_nodes(10) # 添加10条边,且让每条边都是从对应编号的节点指向0节点 src = th.tensor(list(range(1, 10))) g.add_edges(src, 0) # # 画图,首先设置宽和高,然后将DGL图转化为networkx图 # pl...
true
75df250ae46580ba09e3b026345c38c512d9b059
niccokunzmann/cannon
/cannon2/modules/version.py
UTF-8
1,038
2.9375
3
[]
no_license
__doc__=""" ein versionstupel sollte so aussehen: (name,v1,v2,v3,...) name ist der name, als welcher dieses document von main importiert wird v1,v2,v3,... sind die einzelnen versionsnummern, in der rangliste ihrer indexe. so ist ( version(("c",1,2,3,4))<version(("c",2,1,2)) )==True jedes so importierte modul sollt...
true
b110683884c21ce6ba13421958fa9623db17d6b9
Kawser-nerd/CLCDSA
/Source Codes/CodeJamData/15/63/1.py
UTF-8
1,886
2.53125
3
[]
no_license
from sys import * from functools import * def print_args(*args, **kwargs): return ','.join(value for value in [','.join(map(repr, args)),','.join("%s=%s" % (k, repr(v)) for k, v in kwargs.items())] if value) def print_result(before=False, after=True): def fc(func): @wraps(func) def f(*args, **...
true
3a98a4649aee3b07cc232659a4ab127ccc10450f
ResolveWang/algorithm_qa
/dp/q15.py
UTF-8
911
4.09375
4
[ "MIT" ]
permissive
""" 问题描述:给定一个数组arr,arr[i]=k代表可以从位置i向右跳1~k个距离。比如,arr[2]==3, 代表可以从位置2跳到位置3、位置4或者位置5.如果从位置0出发,返回最少跳几次能跳到arr最后的 位置上。 举例: arr=[3,2,3,1,1,4] arr[0]=3,选择跳到位置2;arr[2]=3,可以跳到最后的位置,所以返回2。 要求: 如果arr长度为N,要求实现时间复杂度为O(N)、额外空间复杂度为O(1)的方法。 """ class JumpSteps: @classmethod def get_steps(cls, arr): if not arr: ...
true
6f5b647de36e9cb1b8b8a7c53e9ae302bc5da6a2
retr0h/tribe
/tribe/util.py
UTF-8
4,297
2.625
3
[ "MIT" ]
permissive
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2014 John Dewey # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # t...
true
6715c519b2719dbfb02b4b03d637441b0fb0f41f
yemenlinux/simobility
/simobility/routers/route.py
UTF-8
1,749
3.1875
3
[ "MIT" ]
permissive
from typing import List from .utils import linear_approximation from ..core.geo_position import GeographicPosition from .base_route import BaseRoute class Route(BaseRoute): def __init__( self, created_at: int, coordinates: List[GeographicPosition], duration: int, distance:...
true
5c2b27be2f103e3dc16da5c4b43dc8686237732f
masiro97/Python
/week/6주차_선형재귀와 반복/6-4.py
UTF-8
90
3.390625
3
[]
no_license
def power(b,n): if n >0: return b * power(b,n-1) else: return 1
true
12c937a4e6c4ad9ee40fe90fecbfeac055b818c2
sethcenterbar/appsync-gql-resolver-fun
/ddb.py
UTF-8
1,352
3.03125
3
[]
no_license
import boto3 import pprint # Let's try out the meta client https://twitter.com/jsaryer/status/1380593403705065486 client = boto3.resource("dynamodb").meta.client def get_event(): pass class Comment: def __init__(self, pk, sk, type, content) -> None: self.pk = pk self.sk = sk self.ty...
true
4f54bb14990311565245969d06330407539686da
MFry/pyAlgoDataStructures
/hacker_rank/WoC_25/append_and_delete.py
UTF-8
845
3.484375
3
[ "MIT" ]
permissive
""" Ref: https://www.hackerrank.com/contests/w25/challenges/baby-step-giant-step """ import unittest def continuous_similarity(s1, s2): size_to_check = min(len(s1), len(s2)) for i in range(size_to_check): if s1[i] != s2[i]: return i return size_to_check def changes_needed(s1, s2): ...
true
d377c9186e19e8522f4dddd2907ea7a9f1ee3c6c
pprados/cookiecutter-datascience
/examples.template/flower_classifier/flower_classifier/visualize.py
UTF-8
3,936
2.625
3
[]
no_license
# -*- coding: utf-8 -*- """ Treatment in charge of training visualize the results. """ import logging import pickle import sys from pathlib import Path from typing import Mapping, Iterable, Tuple from typing import Sequence import click import click_pathlib import dotenv import numpy as np from PIL import Image fr...
true
13a15197f902f5bbb9e57a58f593c5faf2dfa2b1
kMatejak/knowledge-hub
/daftacademy-python4beginners-autumn2019/03.Programowanie_z_klasa/zadania_3.py
UTF-8
2,729
4.46875
4
[ "MIT" ]
permissive
""" W tym zadaniu zawsze będą poprawne dane. Nie ma potrzeby obsługiwania sytuacji wyjątkowych. Napisz klasę MyPolynomial → https://pl.wikipedia.org/wiki/Wielomian Ta klasa ma reprezentować wielomian. Ta klasa ma być mutowalna. Ta klasa ma mieć jedno pole `prywatne`(prywatne przez konwencję). Nazwa pola - dowolna 1....
true
9b134ce9d7437b6a5a95854f0e6140153af954a1
StudioCommunity/CustomModules
/dstest/dstest/utils/ioutils.py
UTF-8
3,826
2.8125
3
[]
no_license
import logging import os import json import pandas as pd import numpy as np logging.info(f"in {__file__}") logger = logging.getLogger(__name__) def read_parquet(data_path): """ :param file_name: str, :return: pandas.DataFrame """ logger.info("start reading parquet.") df = pd.read_parquet(os.p...
true
faa1ce50d2d508c2c88e9807022b1768065c6780
karolyiar/ProjectEuler
/euler112.py
UTF-8
1,021
3.890625
4
[]
no_license
# https://projecteuler.net/problem=112 ''' Returns True if the number is bouncy ''' def bouncy(n): bounce = False num = str(n) ''' Under 100 cant be bouncy ''' if n < 100: return False j = 1 ''' The equivalent digits arent important ''' while n/10%10 == n%10 and n>10: n /= 1...
true
f17184b5d4539f2f480e5f89b44fd6eb40ed728d
TebogoNakampe/transfer-learning-for-sign-language-recognition
/datasets/inspection/display.py
UTF-8
1,271
3.296875
3
[ "MIT" ]
permissive
import cv2 _FONT = cv2.QT_FONT_NORMAL, 0.5, (60, 60, 60), 1, cv2.LINE_AA def _display_frames(frames, show_frame_number=True, delay=0): """Displays a sequence of frames. Arguments: frames: The frames to display. show_frame_number: Whether to display the frame number of the current frame displ...
true
f58dc45a278b086fb71ca3faaca2f7bb718601ae
TrashyTips/disposal-info
/maps/scrapers/usagain.py
UTF-8
2,928
2.921875
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- import re import json import time import random import collections import requests from bs4 import BeautifulSoup # http://www.usagain.com/find-a-collection-bin # Post with data: # cityInput=&stateInput=%23&zipInput=11207&Submit.x=48&Submit.y=4 class BinLocation(): @staticmethod def from_di...
true
2e918f871475d35a789e3c1d0df365cd73d33910
theotsif/GoogleMaps_Firestore
/GooglePlacesAPI.py
UTF-8
4,837
2.796875
3
[]
no_license
import googlemaps import pandas as pd import requests import time #Connect to the API def google_map_API_connection(API_KEY=None): gmaps = googlemaps.Client(key = API_KEY) return gmaps class PlaceSearchMatrix: def __init__(self, gmaps): self.gmaps = gmaps def...
true
0ebe62d5381062517d424b247f4f43e5125ac09f
chrishefele/kaggle-sample-code
/WhaleRedux2/src/leakage_features.py
UTF-8
4,263
2.6875
3
[]
no_license
import os, os.path, sys import pandas TRAIN_DIR = '../download/train2/' TEST_DIR = '../download/test2/' TRAIN_FEATURES_FILE = '../features/leakage_features_train.csv' TEST_FEATURES_FILE = '../features/leakage_features_test.csv' TRAIN_TEMPLATE_FILE = '../data/train2_template.csv' TEST_TEMPLAT...
true