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
ad6fba8c24a92ffc4316f05fc7b36949933b615a
cyberkid30/contact-book
/objects/contact.py
UTF-8
342
3.265625
3
[]
no_license
class Contact: def __init__(self, name: str, phone_num: str) -> None: self.name = name self.phone_num = phone_num def __repr__(self) -> str: return (f'{self.get_clsname()}({self.name!r}, ' f'{self.phone_num!r})') @classmethod def get_clsname(cls): ...
true
35e72c057733cd7e8eefe43f3a3a0e4d3a3bbd7d
mdisner/Python-Programming-
/Tarea1.3-Primos.py
UTF-8
1,143
4.34375
4
[]
no_license
#!/usr/bin/python print "Este programa imprime los primeros n numeros primos" n = input("Dame la cantidad de numeros primos que deseas: ") lista = [2] def primos2(): print lista[:n] """ Esta funcion se encarga de imprimir la cantidad de elementos n, solicitada por el usuario de la lista que contiene solo numeros...
true
eb286d928564132347e158c00b03e5277fa4dcc4
SfilD/Michael_Dawson__Python_Programming
/ch09_simple_game.py
UTF-8
789
3.578125
4
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- # Простая игра # Демонстрирует импорт модулей import ch09_games, random print("Добро пожаловать в самую простую игру!") again = None while again != "n": players = [] num = ch09_games.ask_number(question="Сколько игроков участвует? (2 - 5): ", low=2, high=6) f...
true
ba81ef89b411bab4fc7ede3f6eafcd55da600ed6
SazontovDmitriy/lecture01
/zadanie1.py
UTF-8
500
3.359375
3
[]
no_license
import math b: str = input ("Длина первой стороны b= ") C: str = input ("Длина второй стороны c= ") d: str = input ("Введите величину угла d в радианах= ") from math import pi d: str = (float(d))*(180/pi) import math as m a= math.sqrt((pow(float(C), 2)) + (pow(float(b), 2)) - (2 * (float(b)) * (float(C)) * (...
true
83c372fee460efb212f458a69e10cc286c6298c6
tempuser1909/proxies
/ftpproxy.py
UTF-8
816
2.640625
3
[]
no_license
#!/usr/bin/python import socket import sys import os args = sys.argv mySocket = socket.socket() mySocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) myHost = '0.0.0.0'#socket.gethostbyname(socket.gethostname()) myPort = args[1] serverSocket = socket.socket() serverHost = "192.168.56.101" serverPort = args[2...
true
3228031c88209978b1e268a747ec5b0a487e7058
aflyingwolf/decoder
/decoder-python/src/slice_nps.py
UTF-8
1,829
2.953125
3
[]
no_license
import numpy as np import os def slice_nps(in_path: str, desti_path, K: int): name = in_path.split("/")[-1].split(".")[-2] name += ".txt" data = np.load(in_path) file_path = os.path.join(desti_path, name) f = open(file_path, "w") for i in range(data.shape[0]): line = str() temp...
true
79c6eb92ba8c2b79b57efe4520d72506fb865e1f
aravind598/mini_project
/lifang2/menupickler.py
UTF-8
796
2.59375
3
[]
no_license
#Joshua Coded this lines 1 to 17 import pickle menus = {'mc_donalds':[{'Hotcakes':'$4.95', 'Sausage McMuffin with Egg':'$4.20', 'Big Breakfast':'$5.90'}, {'Cheeseburger Meal':'$8.95', 'McChicken':'$2.00', 'Big Mac':'$5.75', 'McSpicy':'$5.25'}], 'kfc_':{'2 pcs Chicken Meal':'$10.15', 'Mac N Cheese':'$10.45', 'Zinger':'...
true
4f5ab02dd9975cd064b3d37f5d26e062058fc0dd
YangLiyli131/Leetcode2020
/in_Python/1365 How Many Numbers Are Smaller Than the Current Number.py
UTF-8
311
3.03125
3
[]
no_license
class Solution(object): def smallerNumbersThanCurrent(self, nums): """ :type nums: List[int] :rtype: List[int] """ res = nums L = sorted(nums) for i in range(len(L)): res[i] = L.index(nums[i]) return res
true
2479542a8979451f64edc6817bba5a5ff1af7591
DaiJitao/test_openCV
/src/stevedoreDemo/testFile.py
UTF-8
339
3.453125
3
[]
no_license
class tracer: def __init__(self, func): self.calls = 0 self.func = func def __call__(self, *args, **kwargs): self.calls += 1 print self.calls, self.func.__name__ self.func(*args) @tracer def spam(a, b, c): print "a=",a , "b=",b, "c=",c def myfun(): print "myfun...
true
4bdafab9028a9fec423ad50ce817c9278c0e8017
akinteebaylor/machine_learning
/CLAASS.PY
UTF-8
2,185
3.375
3
[]
no_license
from sklearn.datasets import fetch_california_housing california = fetch_california_housing() # print(california.target.shape) import pandas as pd pd.set_option("precision",4) pd.set_option("max_columns",9) pd.set_option("display.width",None) california_df = pd.DataFrame(california.data , columns = california.fe...
true
c076694a4075b0aba3b30ddf9d2f92eb6470ee5a
nguyenmq/yt_box
/backend/schedulers/roundrobin.py
UTF-8
4,158
3.421875
3
[]
no_license
import heapq import time from schedulers.scheduler_base import SchedulerBase class RoundRobin(SchedulerBase): """ Implements a round-robin scheduling for ordering the videos in the queue. """ class _RRVidData: """ Internal round robin video data class """ def __init__...
true
552084466734f463c780ed6f742859399a010681
johny5w/PyDwarf
/settings.py
UTF-8
3,483
2.546875
3
[ "Zlib" ]
permissive
import os import sys import platform import logging from datetime import datetime import pydwarf def getsettings(): # Will be used for assignment of some file paths datetimeformat = '%Y.%m.%d.%H.%M.%S' timestamp = datetime.now().strftime(datetimeformat) # To what file should logs be outp...
true
3ed87a5a29d9b1b134da771303bedd06d0353370
umeshjn/IntroductionToMachineLearning-CourseWork
/final_project/explore_enron_data.py
UTF-8
3,885
3.25
3
[]
no_license
#!/usr/bin/python """ starter code for exploring the Enron dataset (emails + finances) loads up the dataset (pickled dict of dicts) the dataset has the form enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict } {features_dict} is a dictionary of features associated with that person...
true
91b698046fd6de3dc5d5d194e7168f6e119f85b9
Haimchen/tu
/mpgi4/aufgabe03/Gruppe87/aufgabe3.py
UTF-8
6,438
2.671875
3
[]
no_license
# -*- coding: utf-8 -*- import numpy as np import stickguy """ Sarah Köhler (sarah.c.koehler@gmail.com) Dora Szücs (szuucs.dora@gmail.com) """ # new animation: """ Computes positions of joints for the stick guy. Inputs: param : list of parameters describing the pose param[0]: height of hip param[1]: angle of spine to...
true
37f0d3c8788383ecc3de51effc2d689da041f8cf
Rudavinp/tceh_python
/homework4/sort_arrey.py
UTF-8
858
3.828125
4
[]
no_license
"""Функция сортирует список чисел по убыванию""" def sort_array(some_array): result_array = [] array_1 = some_array[:len(some_array)//2] array_2 = some_array[len(array_1):] if len(array_1) > 1: array_1 = sort_array(array_1) if len(array_2) > 1: array_2 = sort_array(array_2) wh...
true
f667a4e17175bf39d61b5e8ab3ff624b89f600c1
dutraleonardo/avl-python
/avl-python.py
UTF-8
2,428
3.796875
4
[]
no_license
#!/usr/bin/env python2 # -*- coding: utf-8 -*- ######################## ## Python AVL Tree ## ## Leonardo Dutra ## ######################## class Node: def __init__(self, data): self.data = data self.setChilds(None, None) def setChilds(self, left, right): self.left = left ...
true
c9bc9b6ca2df9b4a7c22e9596daf4bad4e4e4f0d
mgoldenisc/iknow
/actions/updatelib.py
UTF-8
3,079
2.671875
3
[ "MIT" ]
permissive
"""Common functions for autoupdate bot. Requires Python 3.6 or higher.""" import os import random import string import sys def _rand_string(length): """Return a random alphanumeric string with a given length.""" return ''.join(random.choice(ALPHANUMERIC) for _ in range(length)) def get_vars(): """Retur...
true
2915f9172fda6f7d3e6138b52c29c2e2ffdc5014
forest-float/FreeKindle
/kindle.py
UTF-8
1,975
2.6875
3
[]
no_license
#!/usr/bin/env python3 import io import json import re import requests from bs4 import Tag import config from book import Book def fetch(url, headers, cookies): r = requests.get(url, headers=headers, cookies=cookies) from bs4 import BeautifulSoup import lxml bs = BeautifulSoup(r.text, lxml.__name__...
true
720f2ff8f46cbe15bc9691ad37f51f616309f428
ookull/reflexec
/reflexec/output/plugin/chained.py
UTF-8
5,703
2.546875
3
[ "MIT" ]
permissive
"""Reflexec output plugins - chain plugin to handle other plugins. .. autoclass:: ChainedOutputPlugin :members: :show-inheritance: """ import datetime import importlib import time from .base import OutputPlugin, log class ChainedOutputPlugin(OutputPlugin): """Chained output plugin. Joins multiple ou...
true
e66826caaf2761bca90a35dbd23d4ba7e6be14af
Aasthaengg/IBMdataset
/Python_codes/p03273/s612239299.py
UTF-8
371
2.78125
3
[]
no_license
h, w = map(int, input().split()) tizu = [input() for _ in range(h)] h_s = [False for _ in range(h)] w_s = [False for _ in range(w)] for i in range(h): for j in range(w): if tizu[i][j] == "#": h_s[i] = True w_s[j] = True for i in range(h): if not h_s[i]: continue row = "" for j in range(w): ...
true
47f959c2d4f9a3cc7da414655abb2779282e40dc
npmitchell/lepm
/lepm/stringformat.py
UTF-8
4,310
3.59375
4
[]
no_license
import numpy as np '''Module for string format handling and transformations''' ########################################## # String Formatting ########################################## def is_number(s): """Check if a string can be represented as a number; works for floats""" try: float(s) re...
true
dfd05951df170f30870eae320d13d0934180e436
j5int/j5basic
/j5basic/test_TimeCache.py
UTF-8
5,268
2.734375
3
[ "Apache-2.0" ]
permissive
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from future import standard_library standard_library.install_aliases() from builtins import * from builtins import object from j5basic import TimeCache from j5test.Utils i...
true
94ad41c2056305558c2a9a153834c5079f99630f
masonweld/Algorithms
/Sudoku_Solver/sudoku_cplex.py
UTF-8
3,284
3.34375
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Thu Jul 2 09:39:14 2020 @author: weldm """ # Sudoku Solver with CPLEX from docplex.mp.model import Model from docplex.util.environment import get_environment import numpy as np from numpy import genfromtxt import pandas as pd # ---------------------------------...
true
84a422a9f3727e19f7f1356d400369d742a76813
leehs96/2020.08.19
/blogproject/blog/FAKE/fake.py
UTF-8
157
2.578125
3
[]
no_license
from faker import Faker ifake = Faker() print(ifake.name()) print(ifake.address()) print(ifake.text()) print(ifake.random_number()) print(ifake.sentence())
true
6362d9a8016a0239f2f1ee205655bcbc478540a2
juseus03/Corsika-RootMonografia
/plotPrimaryFlux.py
UTF-8
893
2.625
3
[]
no_license
import matplotlib.pyplot as plt import pandas as pd import numpy as np from matplotlib.colors import LinearSegmentedColormap #Color map cm_data = np.loadtxt("./ScientificColourMaps3/ScientificColourMaps3/berlin/berlin.txt") CBname_map = LinearSegmentedColormap.from_list('CBname', cm_data) data = pd.read_tabl...
true
8712a06783a8aaf9d3d1d6baa776a7e298d7ebda
lyg95/tflite
/scripts/update-importing.py
UTF-8
1,441
2.53125
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env python import os import git """Auto-generate the submodule importing from `tflite/tflite`""" here = os.path.abspath(os.path.dirname(__file__)) repo_dir = os.path.abspath(os.path.join(here, '..')) submodule_dir = os.path.join(repo_dir, 'tflite') the_file = os.path.join(repo_dir, 'tflite/__init__.py') B...
true
99b334b198ccd5adc04bf0c6af8e956346ec33aa
richardqa/django-ex
/phr/mpitoken/validators.py
UTF-8
306
2.5625
3
[ "CC0-1.0", "LicenseRef-scancode-public-domain" ]
permissive
import ipaddress from django.core.exceptions import ValidationError def validate_ip(value): for ip in value.split(','): try: ipaddress.ip_address(ip) except ValueError: raise ValidationError( "{} no es una IP válida".format(ip) )
true
495bac7600dafc7e25e418ec45a15b1110e2c13e
viniielopes/uri
/iniciante/1115.py
UTF-8
477
4.21875
4
[]
no_license
# x- positivo, y positivo = primeiro quadrante # x - negativo, y positivo = segundo quadrante # x - negativo, y negattivo = terceiro quadrante # x positivo, y negativo = quarto quadrante x = 1 y = 1 while x != 0 and y != 0: valor = input() x = int(valor.split()[0]) y = int(valor.split()[1]) if x > 0: if...
true
58f6c0880a9c32efc991e8611204f9f7a510f11c
pedramamini/chatbot
/handlers/calculators.py
UTF-8
5,006
2.96875
3
[]
no_license
import re import requests import simplejson # bot helpers. import helpers ######################################################################################################################## class handler: """ Various calculator functionality. """ #################################################...
true
5e47b27f1f1addf861cfb9c9d308b46085bdf6fc
mbuesch/misc
/geophabet.py
UTF-8
971
3.15625
3
[]
no_license
#!/usr/bin/env python3 """ # Convert words into numbers, geocaching-like # Copyright (c) 2009-2022 Michael Buesch <m@bues.ch> # Licensed under the # GNU General Public license version 2 or (at your option) any later version """ import sys def convertChar(c): c = ord(c) if c >= ord('a') and c <= ord('z'): ...
true
450cd76ab43c346059d4dc338c8923d7bdbc6ca1
sarangbishal/Competitive-Coding-Solutions
/Codefights/cyclicString.py
UTF-8
160
3.578125
4
[]
no_license
def cyclicString(s): for i in range(len(s)): t = s[0: i + 1] m = len(s) // (i + 1) + 1 if s in t * m: return i + 1
true
6da7a6f6bc9610b51d9f13a82496a18a06e4fc20
la96bikal/River-Problem
/main.py
UTF-8
4,545
3.40625
3
[]
no_license
import River #This is a library for the GUI i have used for output import tkinter as tk # THe GUI Window root = tk.Tk() root.geometry("%dx%d+%d+%d" % (800, 600, 0, 0)) # the title of the window root.title("The River Problem Name: Bikal Lamichhane ID: 1481000 ©") # The label for the north sh...
true
1ce112b683bb741696326799cf343d137211defa
ioi-2019/tools
/telegram/ioi2019bot.py
UTF-8
1,343
2.8125
3
[]
no_license
import telebot # file with comma delimited data filepath = "contestant-list.txt" fields = ["MAC","IP","Seat","User","Name","Surname"] f = open("ioi2019bot.key", "r") botKey = f.read(45) print(botKey) bot = telebot.TeleBot(botKey) @bot.message_handler(content_types=["text"]) def start_reading(message): try: ...
true
5e6d9f57639831063830cccfeff127d6e6045820
Aasthaengg/IBMdataset
/Python_codes/p03994/s460612600.py
UTF-8
1,181
2.875
3
[]
no_license
import sys read = sys.stdin.read readlines = sys.stdin.readlines from itertools import accumulate from bisect import bisect def main(): s = input() k = int(input()) s2 = [] s2a = s2.append for se in s: if ord(se) - 97: s2a(123 - ord(se)) else: s2a(0) s2_ac...
true
025442553f1a1e330bc89e1cff92f05cac3e9076
athomaz00/Super-resolution
/cluster/cluster python/cluster center.py
UTF-8
3,580
3.09375
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Fri Nov 17 17:57:43 2017 @author: Andre Thomaz """ # ============================================================================= # This code calculates cluster based positions points detected using DBSCAN # and K-means methods to calculate centers, both from sklearn #input = ...
true
ffcfb786c86c890ad56e95ee65f69f5c01aaaa7a
daniel-reich/turbo-robot
/ygeGjszQEdEXE8R8d_7.py
UTF-8
2,192
4.34375
4
[]
no_license
""" Create a function which takes a parameter `mat`, where `mat` is a matrix (`list` of `list`s) such that all but one entry equals `0` (and the non-zero entry equals `1`). The function, after being passed a matrix, should be repeatedly callable with the following `str` commands: * `"up"` ➞ Move the `1` to the ce...
true
bb998cfe71ea889907dede184b6e30f295760a71
AK-1121/code_extraction
/python/python_6929.py
UTF-8
111
3.0625
3
[]
no_license
# I have a problem with pprint in python &gt;&gt;&gt; pprint.pprint([[1,2],[3,4]], width=10) [[1, 2], [3, 4]]
true
80c0b086175da4fd5415e3a34ecb76537cf7d9bf
Nikolaychik/study
/getattribute.py
UTF-8
364
3.390625
3
[]
no_license
class GentleClass(object): def __getattribute__(self, item): if '_please' in item: return object.__getattribute__(self, item.split('_please')[0]) else: return "Say a magic word!" # def __getattr__(self, item): # return item GClass = GentleClass() GClass.x = 'Som...
true
d5f8cff0655e1cf80cdb1c4402a8a477095e511d
TradeAutomatic/py-trader
/models/MySQL.py
UTF-8
1,039
3.015625
3
[]
no_license
import mysql.connector class MySQL : """ Cette classe me permettra d'éffectuer des requettes vers ma base des données MySQL """ def __init__(self) : self.host = "localhost" self.database = "trade" self.user = "root" self.password = "" def select(self, ta...
true
49e8a7916d8ad0435e89798eb15814904facb47f
hec9527/notebook
/python/python/七段数码管_无缝刷新版.py
UTF-8
3,405
3.171875
3
[]
no_license
#!/usr/bin/env python3 # -*- coding=utf-8 -*- # coding=utf-8 import turtle import time def draw_str(tur, Str): tur.penup() tur.goto(tur.cpos[0], tur.cpos[1]) tur.pencolor(tuple(tur.color)) tur.clear() for i in Str: draw_one(tur, i) draw_text(tur) def draw_one(tur, num): global l...
true
90955a6970facd3e548ca74799187b2ca5cde7a0
droneRL2020/AI-Study_SNU-bdi
/2nd semester/Basic Machine Learning_Prof. Kim Sun/W3/Practice_1-2_SplitDecisionTree.py
UTF-8
1,295
2.71875
3
[]
no_license
import numpy as np from sklearn.datasets import load_iris def gini(arr): classCounts = np.unique(arr, return_counts=True)[1] sampleNum = arr.shape[0] p_arr = classCounts / float(sampleNum) ret = 1. - (p_arr**2).sum() return ret def giniSplit(arr1, arr2): sampleNum1 = float(arr1.shape[0]) sampleNum2 = float(arr...
true
aa78021f1042aea4ae8c061977018626a0fcf96f
BitGuerra/Sistemas_Embebidos
/Semana_12/Firmata_Arduino/Firmata_Analogo.py
UTF-8
466
3.21875
3
[]
no_license
from pyfirmata import Arduino,util # Crea un objeto de tipo Arduino especificando el puerto de conexion tarjeta = Arduino('/dev/ttyACM0') #Inicia el iterador para evitar el overflow en el puerto serial it = util.Iterator(tarjeta) it.start() #Crea un referencia para leer el pin analogo A0 analogo_0 = tarjeta.get_pin(...
true
50fa64f11852c1292f4d5c9e46e807b57196b89d
MatanyaToren/heart-rate
/QLabeledSpinBox.py
UTF-8
1,310
2.796875
3
[]
no_license
import sys from PyQt5 import QtWidgets from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QSpinBox, QLabel, QVBoxLayout from PyQt5.QtCore import Qt class QLabeledSpinBox(QWidget): def __init__(self, label='label for slider', range=(1,30), initValue:int = 20): super().__init__() ...
true
16172ea15ba107b15c88dabef075feeab7708100
xiangjie818/scripts
/python/snapshot.py
UTF-8
3,383
3.046875
3
[]
no_license
#!/usr/bin/python # coding=utf-8 from __future__ import division __metaclass__ = type import commands,sys,os class Color: def black(self, para): print "\033[30m%s\033[0m" % para def red(self, para): print "\033[31m%s\033[0m" % para def green(self, para): print "\033[32m%s\033[0m" % ...
true
7fa142521303756113df8adf4e868db256ba9fd5
nicodr97/MacroPy
/Macro/PDB_tools.py
UTF-8
5,383
2.578125
3
[]
no_license
import os import logging as log from Bio.Align import PairwiseAligner from Bio.PDB import Superimposer, MMCIFIO, PDBIO def get_chain_full_id(chain): return ":".join(chain.get_full_id()[0::2]) def align(chain, seq): """Align the sequence of a chain object with a sequence string""" # Get chain...
true
57cdb2c2e3a31115bbe131005fd5a742a0e5ecfe
ivan-ge677/algorithm-and-data-structure
/code/hanoi.py
UTF-8
562
3.109375
3
[]
no_license
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : hanoi.py @Contact : ivan.ge@nio.com @License : (C)Copyright 2015-2021, NIO @Modify Time @Author @Version @Desciption ------------ ------- -------- ----------- 2021/2/8 8:22 下午 Ivan.GE 1.0 None ''' def hanoi(...
true
0faefba7e4359f67278770c82732ab8e577c0b2e
humorbeing/python_github
/kaggle_song_git/code_box/fake_V1001/total_counter_fake_genre_V1001.py
UTF-8
3,049
2.515625
3
[]
no_license
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import time import numpy as np import pickle since = time.time() data_dir = '../data/' save_dir = '../saves/' # save_dir = '../fake/' if 'fake' in save_dir: print('-' * 45) print() print(' !' * 22) print() print(' this is...
true
23a21f42a00781b44b466abf353b98b1ba3be994
sean-puzzlor-solutions/puzzlor_2008_02_Doctor_Decision_Tree
/doctor_decision_tree.py
UTF-8
6,585
3.71875
4
[]
no_license
def doctor_decision_tree(): # The cost to go to the doctor and have the test is $200 and the cost of a penicillin prescription is $50. c_doctor = 200 c_penicillin = 50 # The chance of the illness being a cold is 50%, flu is 20%, and bacterial is 30%. # The test results also match these ratios. ...
true
026a14444d284370246ba31dc25097e50b7e3b35
geometer/sandbox
/python/sandbox/property.py
UTF-8
28,193
2.90625
3
[ "Apache-2.0" ]
permissive
from enum import Enum, auto import itertools from .figure import Figure, Circle from .scene import Scene from .util import Comment, divide, normalize_number, keys_for_triangle class Property: def __init__(self, property_key, point_set): self.implications = [] self.property_key = property_key ...
true
92631fd3ff549c102a3ab43bf08d17b4141c2e59
beausea/python3-pentest
/Chapter14/14-02.py
UTF-8
415
3.03125
3
[]
no_license
#!/usr/bin/env python3 import sys from scapy.all import * target = str("127.0.0.1") port = int(4321) print("Attacking target " + target + " on port " + str(port)) i = IP() i.dst = target i.src = target t = TCP() t.dport = port t.sport = port for x in range(1, 100): send(i/t) print("IP/...
true
db44af16a466bf34092bcd0d88d0a5b60a8ca219
leejin21/algProbSolve-PY
/swexpertAc/05_graphBasic/calculate2.py
UTF-8
2,193
3.84375
4
[]
no_license
# calculate.py # 5247. [파이썬 S/W 문제해결 구현] 6일차 - 연산 # 미완 ''' 자연수 N에 몇 번의 연산을 통해 다른 자연수 M을 만들려고 한다. 사용할 수 있는 연산이 +1, -1, *2, -10 네 가지라고 할 때 최소 몇 번의 연산을 거쳐야 하는지 알아내는 프로그램을 만드시오. 단, 연산의 중간 결과도 항상 백만 이하의 자연수여야 한다. 예를 들어 N=2, M=7인 경우, (2+1) *2 +1 = 7이므로 최소 3번의 연산이 필요한다. [입력] 첫 줄에 테스트 케이스의 개수가 주어지고, 다음 줄부터 테스트 케이스 별로 첫 ...
true
51fb030fe8dd032bff76564d8fc17a4236cd2425
erjan/coding_exercises
/number_of_distinct_binary_strings_after_applying_operations.py
UTF-8
1,121
3.875
4
[ "Apache-2.0" ]
permissive
''' You are given a binary string s and a positive integer k. You can apply the following operation on the string any number of times: Choose any substring of size k from s and flip all its characters, that is, turn all 1's into 0's, and all 0's into 1's. Return the number of distinct strings you can obtain. Since th...
true
fa43fd70df690140ac5db56bb6b7d8fb76cd46b2
LucasPickering/mbta
/api/core/management/commands/insertstations.py
UTF-8
895
2.65625
3
[]
no_license
import json from django.core.management.base import BaseCommand from core import models class Command(BaseCommand): help = "Insert stations from JSON into the DB" def add_arguments(self, parser): parser.add_argument("--data", "-d", default="data/stations.json") parser.add_argument( ...
true
0d3daeaa2f85a409d9444526d2a055bf32947330
xenron/sandbox-github-clone
/bmw9t/nltk/ch_three/23.py
UTF-8
537
3.796875
4
[]
no_license
# ◑ Are you able to write a regular expression to tokenize text in such a way that the word don't is tokenized into do and n't? Explain why this regular expression won't work: «n't|\w+». import nltk from nltk import word_tokenize import re # reads in a text f = open('corpus.txt') raw = f.read() matches = re.findall...
true
cb64aa497005bed34866dcde2c2119a8dbf58657
indicwiki-iiit/Football-players
/FOOTBALL MALE PLAYERS/readData.py
UTF-8
880
2.859375
3
[]
no_license
import pickle import pandas as pd import sweetviz as sv def analyse(df,title): #generating sweetviz report report =sv.analyze([df,title]) report.show_html() def main(): playerFile = './players.csv' playerDF = pd.read_csv(playerFile) #filling null values with nan string playerDF=playerDF.fillna('nan') #conv...
true
75c225fb8468521f3954e5e92ac3dc893e610310
cfelton/HDMI-Source-Sink-Modules
/hdmi/interfaces/hdmi_interface.py
UTF-8
2,610
2.75
3
[ "MIT" ]
permissive
from myhdl import Signal class HDMIInterface: def __init__(self, clock): """ This interface is the external interface modeled after the xapp495 external HDMI interface Args: :param clock: A reference clock used to transmit signals, It is usually 10 times the pixel...
true
8a3dea61c636160d13010b5cc82ed8c168e18195
rpmullig/IU_DATA_STRUCTURES_AND_ALGORITHMS
/Python_Class_Files/HeapCompression/heap.py
UTF-8
2,407
3.609375
4
[]
no_license
from swap import swap #from aifc import data def less(x, y): return x < y def less_key(x, y): return x.key < y.key def left(i): return 2 * i + 1 def right(i): return 2 * (i + 1) def parent(i): return (i-1) / 2 # Student code -- fill in all the methods that have pass as the only statement class...
true
f594b2039a59fcb1c596d3625eaef0fbb4700656
jewettaij/dlpdb
/dlpdb/has_sheets.py
UTF-8
903
3.640625
4
[ "MIT" ]
permissive
#!/usr/bin/env python """ This program currently does not do anything which grep could not do. This returns prints nothing, but it returns (using an exit code) whether or not a PDB file contains a "SHEET" record. If it doesn't it could either be because the original authors of the PDB file neglected to indicate where...
true
d50410002bc076311da1f576b55e232ebb5e750a
LuisTV13/uploadSellin
/dataframe.py
UTF-8
1,189
2.71875
3
[]
no_license
from typing import NewType import pandas as pd import json path= 'input/Sell_In.xlsx' def getDataframe(): df=pd.read_excel(path, sheet_name='Standard_WB',skiprows=6, header=None) P1_NART=df[1] PRODUCT_NAME=df[2] CALENDAR_DAY=df[3] N_S=df[4].fillna(0) NET_SALES=[] QTY=df[5].fillna(0)...
true
f9d3f2b6022c457614836de90f6c59518890d391
AneiMakovec/IEPS-19-crawler
/implementation-extraction/run-extraction.py
UTF-8
19,899
2.546875
3
[]
no_license
import sys import re import json import pylcs import math from lxml import html ########################################################### ############ REGULAR EXPRESSION IMPLEMENTATION ############ ########################################################### def do_reg_ex(): print("STARTING REGULAR EXPRESSION I...
true
aafa8fffb31c2b6be65635b555b912b57d51dae2
MilanaShhanukova/2020-2-level-ctlr
/config/reference_text_preprocess_score_four_test.py
UTF-8
1,630
2.8125
3
[]
no_license
import re import os import json import unittest from constants import ASSETS_PATH from pipeline import CorpusManager, TextProcessingPipeline, validate_dataset from config.test_params import TEST_FILES_FOLDER class ReferenceTextPreprocessTest(unittest.TestCase): @classmethod def setUpClass(cls) -> None: ...
true
14bd0865e6a3e953bc15ca9d4dd5ef5a235899fa
jftuga/universe
/Misc/misc/fix_crappy_characters.py
UTF-8
1,521
3.375
3
[]
no_license
""" fix_crappy_characters.py -John Taylor May-6-2011 Python 2.6 or 2.7 Sometimes copying & pasting from a web page can screw up punctuation characters. This script fixes that! You may need to add more values to the 'fix' table. The key in the 'fix' dictionary is the ascii decimal value of the bad character. """ ...
true
45023187bd67488bfcea566b686eef48951c4fe0
coreemu/core
/daemon/core/emane/modelmanager.py
UTF-8
2,460
2.609375
3
[ "BSD-2-Clause" ]
permissive
import logging import pkgutil from pathlib import Path from core import utils from core.emane import models as emane_models from core.emane.emanemodel import EmaneModel from core.errors import CoreError logger = logging.getLogger(__name__) class EmaneModelManager: models: dict[str, type[EmaneModel]] = {} @...
true
e19384c051d28253f89674336af5b541a5a129a5
GustavoR0dr1gu3z/Clasificador_Objetos_Python
/Goma/ClasificadorGOMA.py
UTF-8
1,560
2.6875
3
[]
no_license
import cv2 import matplotlib as plt import numpy as np import os from PIL import Image #Imagen original goma0 = cv2.imread('goma0.png', 0) #lectura en escala de grises goma1 = cv2.imread('goma1.png', 0) #lectura en escala de grises goma2 = cv2.imread('goma2.png', 0) #lectura en escala de grises goma3 = cv2.imread('goma...
true
19ea0e13aa8721fe97531eaccddd63c97f0e9cb2
Ainur13/py-method-lessons
/Lyrics.py
UTF-8
2,212
2.796875
3
[]
no_license
import requests import telebot from telebot import types token="write_here_your_token" bot = telebot.TeleBot(token) apikey="a5f0fc8611a415ab2f3dddca814f4516" @bot.message_handler(commands=["start"]) def HandleStart(msg): chatId=msg.chat.id name=msg.from_user.first_name reply = "Hello,"+name+"!\n" ...
true
aa208cd874845a89a887ad28cc6b4ff767a9cdda
elor-arieli/poissonHMM_for_neural_data
/auxilary_functions.py
UTF-8
966
3.0625
3
[]
no_license
import numpy as np # import numpy.math.factorial as factorial from scipy.misc import factorial def poisson_prob_population_vec(firing_rate_vec, spike_count_matrix): # spike_count_matrix axis are: 0 - trials, 1 - neurons # gets a matrix of trials and neurons and an array of firing rates and calculates the pois...
true
c29e065d59c3d5cece85a98b63d64bb51be29c5e
pacman2020/API-with-restful-flask
/app/controllers/user.py
UTF-8
2,498
2.59375
3
[]
no_license
from app import ( app, Resource, reqparse, jwt_required, create_access_token, get_jwt_identity) from app.models.user import User class UserResource(Resource): parser = reqparse.RequestParser() parser.add_argument('username',type=str, required=False, help="username field cannot be ...
true
72fa77ace026cc302f9003fddd707ec49c85de3b
xuguangmin/Programming-for-study
/python_study_code/gui/listBox.py
UTF-8
952
3.140625
3
[]
no_license
#!/usr/bin/python #_*_ coding:utf-8 _*_ #列表框控件和带复选框的列表控件 import wx class ListBoxFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, u'列表框', size = (600, 350)) panel = wx.Panel(self, -1) colorList = [u'红', u'蓝', u'绿', u'黄', u'黑', u'紫', u'白'] #关联 colorList和控件listBox self.listBox = wx.ListB...
true
b6644ea10ee3c208138f6a65a1d7b513aa0dbdf4
tikistuna/Project-Euler
/Euler26.py
UTF-8
1,353
3.953125
4
[]
no_license
# If q is rational we may write it as an irreducible fraction a/b where a,b ∈ ℤ. Consider the Euclidean division of a by b: # At each step, there are only finitely many possible remainders r(0≤r<b). # Hence, at some point, we must hit a remainder which has previously appeared in the algorithm: # the decimals cycle from...
true
f16197f55a3e2b2646a8e6e593c4764f870ed4f0
sofieseilnacht/multi-image-upload
/app/astrometry/progressBar.py
UTF-8
340
3.515625
4
[]
no_license
import time class ProgressBar: def __init__(self,label): self.label = label print(label+": ", end='') def incrementAndPause(self, secs): self.increment() time.sleep(secs) def increment(self): print('.', end='', flush=True) def done(self): print('', end...
true
9b5f25689505c4734641fba04237914cf426b76e
pflun/advancedAlgorithms
/canCross.py
UTF-8
702
3.25
3
[]
no_license
# https://www.youtube.com/watch?v=-FBfrVz841k class Solution(object): def canCross2(self, stones): if len(stones) <= 1: return True dic = {} # stone index => [lastSteps] for i in range(len(stones)): dic[i] = set([]) dic[0].add(0) for i in rang...
true
c9554acb77329e6bc984a7559f8527a3ae2b87e8
alldatacenter/alldata
/dts/airbyte/airbyte-integrations/connectors/source-rss/source_rss/source.py
UTF-8
4,871
2.65625
3
[ "Apache-2.0", "BSD-3-Clause", "MIT", "Elastic-2.0" ]
permissive
# # Copyright (c) 2023 Airbyte, Inc., all rights reserved. # from abc import ABC from calendar import timegm from datetime import datetime from typing import Any, Iterable, List, Mapping, MutableMapping, Optional, Tuple import feedparser import pytz import requests from airbyte_cdk.sources import AbstractSource from...
true
94b35b7c5edb7b21876bb29b21c9bf36115282d8
devm1023/GeekTalentDB
/src/converttime.py
UTF-8
753
3.078125
3
[]
no_license
import sys from datetime import datetime, timedelta timestamp0 = datetime(year=1970, month=1, day=1) def usageAbort(): print('usage: python3 converttime.py (-s | -m) (YYYY-MM-DD | <timestamp>)') exit(1) if len(sys.argv) < 3 or sys.argv[1] not in ['-s', '-m']: usageAbort() if sys.argv[1] == '-s': ...
true
101d3a90ed401374ea2e95a773b01f4f636ee6e6
lcsm29/project-euler
/py/py_0307_chip_defects.py
UTF-8
737
3.09375
3
[ "MIT" ]
permissive
# Solution of; # Project Euler Problem 307: Chip Defects # https://projecteuler.net/problem=307 # # k defects are randomly distributed amongst n integrated-circuit chips # produced by a factory (any number of defects may be found on a chip and each # defect is independent of the other defects). Let p(k,n) represent ...
true
1e8d9b86f8e5f19eea97870f955771dbda7db454
IvanProtsenko/BioInf
/suffering.py
UTF-8
2,274
2.609375
3
[]
no_license
flagok_n=0 left_n=0 right_n=0 flagok_h=0 left_h=0 right_h=0 name_gene=[] stplus = [] stminus = [] with open (r"C:\Users\Иванg\Desktop\gene_counts\genome_annotation.gtf") as imp: for line in imp: gene_info=line.strip().split('\t') name_gene.append(line.strip().split('"')[5]) if gene_info[6]...
true
4843f006c0797822e2ec16555e493490bb30a1e7
byaminov/advent-of-code-2018
/aoc/day20.py
UTF-8
3,384
2.953125
3
[]
no_license
from collections import defaultdict from typing import List import networkx as nx def solve1(text: str): distances = populate_grid_and_get_distances(text) return max(distances.values()) def solve2(text: str): distances = populate_grid_and_get_distances(text) return len([d for d in distances.values(...
true
0cdb674456f6b4a8727121afd7121699ffdabe54
lalimite123/Groupe4L2IN2019-2020-
/Client.py
UTF-8
793
3.140625
3
[]
no_license
FOYOU ELIAN FAREL 18A892FS L2IN classe Client: def __init __ (self, numero): self.numero = numero self.solde = 10000 def InfoSolde(self): print("votre solde est:\n", self.solde) def versement(self): som = input("combien vouliez vous verser ?\n") som = int(som) self.solde...
true
e5eb5998e397e63b1095ad8c6912e38699941364
lxxue/s2cnn
/examples/shrec17/baseline/readacc.py
UTF-8
305
2.578125
3
[ "MIT" ]
permissive
import numpy as np accs = [] for i in range(10): with open("log_few10/{}/log.txt".format(i)) as f: for line in f: if 'Test Acc' in line: acc = float(line.split()[-1]) accs.append(acc) accs = np.array(accs) print(accs) print(np.std(accs)) print(np.mean(accs))
true
2ddb9b24ae690a877f5b4ad0fa48b429651fc97c
fpspokane/data_sharing_backend
/data-sharing-api/app.py
UTF-8
4,372
2.640625
3
[ "MIT" ]
permissive
import os import json import pandas as pd import psycopg2 from chalice import Chalice, BadRequestError, ChaliceViewError, Response from chalicelib import helpers # initialize Chalice app app = Chalice(app_name='data-sharing-api') debug=True # assign environment variables DB_HOST = os.environ['DB_HOST'] DB_USER = os.e...
true
3800dc2268771a615c11be00429556bd0434acc0
jedzej/tietopythontraining-basic
/students/slawinski_amadeusz/lesson_06_dicts_tuples_sets_args_kwargs/11_access_rights.py
UTF-8
434
3.265625
3
[]
no_license
#!/usr/bin/env python3 how_many_files = int(input()) files = {} for i in range(how_many_files): name, *files[name] = input().split() how_many_accesses = int(input()) operation_definition = {"read": "R", "write": "W", "execute": "X"} for i in range(how_many_accesses): readline = input().split() if oper...
true
2d7358ad0c8ff3df834aab4d5e5717c7396ba998
yangtingting123456/python_jichu_lianxi
/course_exercises/20210131/上课代码/day02_04.py
UTF-8
2,496
4.03125
4
[]
no_license
''' @File : day02_04.py @Time : 2021/1/31 14:12 @Author: luoman ''' # import lib # 循环: ''' 当代码中有重复操作语句的时候 语法形式: while 表达式: [缩进]语句块 [else: [缩进]语句块] ''' # 举例:要求一行输出5个*符号 # print('*', end='\t') # print('*', end='\t') # print('*', end='\t') # print('*', end='\t') # print('*', end='\t') count = 1 # 起始条件 while count ...
true
a9397106dba69a192b9921fc50ba85669739c50c
corihuela05/TurtleRace
/MyTurtleRace.py
UTF-8
11,882
3.296875
3
[]
no_license
import time import turtle from turtle import Turtle from random import randint #WINDOW SETUP window=turtle.Screen() window.title("My TURTLE RACE") turt=turtle.bgcolor("forestgreen") turtle.color("white") turtle.speed(0) turtle.penup() turtle.setpos(-250,200) turtle.write(" Turtle Race Championships",font=...
true
c6571f0c929fb8e752bf6a980a39e1972e5318dd
SamanthaEgge/Sprint-Challenge--Hash
/hashtables/ex3/ex3.py
UTF-8
1,002
3.5625
4
[]
no_license
def intersection(arrays): result = [] ## get numbah of arrays print(len(arrays)) numbArrays = len(arrays) #init array dictionary arrayDict = {} ## create dictionary based upon array input ## if key is found, increment value by 1 ## if key = len(arrays), add to result ## profit? # print('we in...
true
4ecca6ca102e390ca52661e52262e01a465ebda2
dustinpfister/examples-python
/for-post/python-standard-library-json/s1-basic/dumps.py
UTF-8
78
2.90625
3
[]
no_license
import json t=json.dumps(['foo', {'bar': 42}]) print(t) # ["foo", {"bar": 42}]
true
af4cdcd57cf8b9ba5a4a5d39fd97895c23694dcf
elemley/PSM5113_ch9
/mod93_exp.py
UTF-8
1,071
3.0625
3
[]
no_license
from math import * import numpy as np import matplotlib.pyplot as plt from psm_plot import * from random import * def exp1(x,r): tmp = abs(r)*exp(r*x) return tmp #test of exponential sampling r = -2.0 n = 300 #number of plot points for function xstart = 0.0 xend = 3.0 x = [xstart] dx = (xend-xstart)/n for i ...
true
b7c4052d6e1151d2696afc210104b70b7de9a2ba
xuzhenmaosoft/cms
/Loss_weight/Linear_test.py
UTF-8
600
2.90625
3
[]
no_license
#coding:utf-8 from sklearn.metrics import mean_squared_error, mean_absolute_error import pandas as pd y_ture = pd.read_csv('../data/20180128.csv')['y'] y_pred = pd.read_csv('../result/pred_linear.csv')['y_pred'] # MSE可以评价数据的变化程度,MSE的值越小,说明预测模型描述实验数据具有更好的精确度。 # MAE:平均绝对误差是绝对误差的平均值 # 平均绝对误差能更好地反映预测值误差的实际情况. print('线性模型ms...
true
081ecb1264cb8781f0c184fb003dfaa0f3847926
Zackno23/hello_cli
/atp.py
UTF-8
63
3
3
[]
no_license
user_name = input("what's your name.") print('Hi', user_name)
true
1c41de095a4c2d034887a2c5e0ac38cb3af23308
sumomoneko/letsencrypt-dozens
/scripts/dozens.py
UTF-8
2,196
2.65625
3
[]
no_license
#!/usr/bin/env python3 import requests import os import sys class Dozens: def __init__(self, user, key): headers = {'X-Auth-User': user, "X-Auth-Key": key} r = requests.get(url="http://dozens.jp/api/authorize.json", headers=headers) r.raise_for_status() self._auth_token = r.json()...
true
96f99f81424a16992d4cba8b11db1c54aace87d7
ThomasJRyan/Daily-Coding-Problem
/Day_1/main.py
UTF-8
1,136
4.3125
4
[]
no_license
# Given a list of numbers and a number k, # return whether any two numbers from the list add up to k. # For example, given [10, 15, 3, 7] and k of 17, # return true since 10 + 7 is 17. # Bonus: Can you do this in one pass? def is_two_num_equal(num, list): def mapper(n, pos): return [n+i for num, i in e...
true
de3f71c3da3de6f950d3993de85072b7188b95f2
chadwalt/bucketlist2
/app/models.py
UTF-8
5,924
3.1875
3
[]
no_license
""" This is going to contain the models for the application. Creating users, buckets and bucketitems""" # Import the datetime. import datetime ## Import the database. from app import db ## Import the JSON Web Token for authentication. import jwt import os from flask_bcrypt import Bcrypt ## Import the encryption mod...
true
1ca653e753b05de8e4e99ac09921f85dbc973c4e
abdul8117/igcse-cs
/Algorithms/Shift/main.py
UTF-8
1,116
3.640625
4
[]
no_license
import string def increment_index(key, index): if key > 0: for i in range(key): if index == 25: index = 0 index += 1 if key < 0: for i in range(abs(key)): if index == 0: index = 25 ...
true
d426a542c154c1d3105a1135e3a3eaff504f2467
yanxurui/keepcoding
/python/algorithm/leetcode/210.py
UTF-8
1,515
3.15625
3
[]
no_license
# https://leetcode.com/problems/course-schedule-ii/discuss/59317/Two-AC-solution-in-Java-using-BFS-and-DFS-with-explanation from collections import defaultdict class Solution(object): def findOrder(self, numCourses, prerequisites): """ :type numCourses: int :type prerequisites: List[List[i...
true
8f74d113c8d2d038e0d655ea895d15a45519138b
hwadhwani77/python_lab
/twopointer.py
UTF-8
4,600
3.71875
4
[]
no_license
import math from collections import deque def search_triplets(arr): arr.sort() triplets = [] for i in range(len(arr)): if i > 0 and arr[i] == arr[i-1]: # skip same element to avoid duplicate triplets continue search_pair(arr, -arr[i], i+1, triplets) return triplets def search_pair(arr, target...
true
bac13cbd89c07e62b7c2608706ab9b7b6b7d28d7
eltonrp/curso_python3_curso_em_video
/03_estruturas_compostas/ex115/lib/arquivo/__init__.py
UTF-8
2,096
3.28125
3
[ "MIT" ]
permissive
from curso_em_video.ex115.lib.interface import * def arquivoexiste(nome): try: a = open(nome, 'rt') a.close() except FileNotFoundError: return False else: return True def criararquivo(nome): try: a = open(nome, 'wt+') except: print('Houve um ERRO n...
true
75b9366e42dd07c9fa09ec0272fc68515f9ff5f1
TernenceWind/jianzhiOffer
/chapter 4/32_1_printtreeu2d.py
UTF-8
695
3.96875
4
[]
no_license
# -*- coding:utf-8 -*- # 从上到下打印二叉树 # 即为二叉树的广度优先遍历 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 返回从上到下每个节点值列表,例:[1,2,3] def PrintFromTopToBottom(self, root): # write code here result = [] if root =...
true
c948c4deb5b578d06c0978532ad1bcd7795cee93
holmes1313/data_structure_and_algorithms_in_python
/4_maps_and_hashing.py
UTF-8
4,038
4.3125
4
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sun Sep 29 16:12:02 2019 @author: z.chen7 """ # Sets and Maps """ A list has ordering for its elements A set doesn't have that but instead doesn't allow for repeated elements """ locations = {'North America': {'USA': ['Mountain View']}} locations['North America']['USA'].append(...
true
5e1b784a2219a649adc8319f0caf3e8b036aa3cd
ankit9968/Hacktober_Fest
/Python/commonSubsequence.py
UTF-8
809
3.171875
3
[]
no_license
def longestCommonSubsequenceLength(s1, s2): # Helper function for recursion def lcs(n,m,cache): if n == 0 or m == 0: return 0 if cache[n-1][m-1] != -1: return cache[n-1][m-1] s1FinalCharacter = s1[n-1] s2FinalCharacter = s2[m-1] ...
true
bbc75231266b288a2c8e3579f428c423da79b28b
datacite/mds
/client/python/post_doi.py
UTF-8
624
2.515625
3
[ "Apache-2.0" ]
permissive
import requests, sys, codecs #endpoint = 'https://mds.datacite.org/doi' endpoint = 'https://mds.test.datacite.org/doi' if (len(sys.argv) < 4): raise Exception('Please provide username, password, location of doi-url file') username, password, filename = sys.argv[1:] file = codecs.open(sys.argv[3], 'r', encodin...
true
2cb09eb25f23b8d5ba077a41540055530ff9d3f6
HypoChloremic/EBM
/EBM/Workbook_freq.py
UTF-8
1,640
3.6875
4
[ "MIT" ]
permissive
# In order to create a decorator, we first need to write the function # that will decorate the functions of interest. # we start therefore with the sort function. # as a parameter we catch the method of interest itself, # inside the decorator function we will construct a wrapper function # which will be...
true
202176b1a0cd758cbc5a42651245f3fbb6ff688a
rosered90/wisdom_backend
/apps/gps/consumers.py
UTF-8
1,442
2.59375
3
[]
no_license
# _*_ coding:utf-8 _*_ """ gps消息推送的consumers功能 """ from channels.generic.websocket import AsyncWebsocketConsumer import json import channels.layers from asgiref.sync import async_to_sync class GpsConsumer(AsyncWebsocketConsumer): async def connect(self): self.group_name = 'push_gps_info' # Join r...
true