seq_id stringlengths 4 11 | text stringlengths 113 2.92M | repo_name stringlengths 4 125 ⌀ | sub_path stringlengths 3 214 | file_name stringlengths 3 160 | file_ext stringclasses 18
values | file_size_in_byte int64 113 2.92M | program_lang stringclasses 1
value | lang stringclasses 93
values | doc_type stringclasses 1
value | stars int64 0 179k ⌀ | dataset stringclasses 3
values | pt stringclasses 78
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
72582688035 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Monitor:
"""
Monitor Model
"""
def __init__(self, dpm_proxy):
self.__dpm_proxy = dpm_proxy
def getAllClientMac(self):
"""
get all appeared client macs
:return: get all appeared client macs
"""
... | edward9210/wifi_perceive | WCM/models/Monitor.py | Monitor.py | py | 1,023 | python | en | code | 0 | github-code | 1 |
27640855765 | lista = []
def criarLista():
tamanho = int(input("Informe o tamanho da lista: "))
for valor in range(tamanho):
lista.append(0)
return lista
print(criarLista())
for i in lista:
valorInteiro = int(input("Coloque um valor inteiro para preencher a lista: "))
lista.insert(i, valorInteiro)
... | stephbertolo/provaPratica | Questao 01.py | Questao 01.py | py | 416 | python | pt | code | 0 | github-code | 1 |
2888562607 | import sys
snput = lambda: sys.stdin.readline()
m_snput = lambda: map(int, snput().split())
if __name__ == "__main__":
n, m, t = m_snput()
max_n = n
time_list = [True] * t
for i in range(m):
a, b = m_snput()
for i in range(a, b):
time_list[i] = False
for i in time_list... | Kumamoto-Hamachi/atcoder_pr | abc_contest/abc185/b/b_false.py | b_false.py | py | 1,164 | python | en | code | 1 | github-code | 1 |
33286894157 | import sys
sys.path.insert(0, "../SymJAX")
from scipy.stats import kde, multivariate_normal
import cdd
import numpy as np
import itertools
from scipy.spatial import ConvexHull, Delaunay
from scipy.special import softmax
from numpy.linalg import lstsq
from tqdm import tqdm
import symjax as sj
import symjax.tensor as T
f... | RandallBalestriero/EMDGN | utils_old.py | utils_old.py | py | 15,737 | python | en | code | 1 | github-code | 1 |
74543466592 | import unittest
from pathlib import Path
import lindenmayer_system as ls
from PIL import Image, ImageDraw
class TurtleInterpreterTestCase(unittest.TestCase):
def setUp(self):
self.image = Image.new("RGB", (1280, 1280), "white")
self.draw = ImageDraw.Draw(self.image)
self.pos = (1280 / 2, 1... | lucas-escobar/botany-lab | tests/test_turtle_interpreter.py | test_turtle_interpreter.py | py | 3,503 | python | en | code | 0 | github-code | 1 |
28557952081 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('docs', '0002_drop_doccomments'),
]
operations = [
migrations.CreateModel(
name='DocPageAlias',
field... | postgres/pgweb | pgweb/docs/migrations/0003_docs_alias.py | 0003_docs_alias.py | py | 880 | python | en | code | 66 | github-code | 1 |
15252913493 | import sys
sys.path.insert(0, '../..')
import generatorUtils as gu
import random
from base import Decision, ReusableDecision
class SingleShape(ReusableDecision):
def registerChoices(self):
self.addChoice(self.getKey(), {
'correct' : 100,
'missingRepeat' : 10,
'moveNest... | malik-ali/generative-grading | src/rubricsampling/grammars/codeorg9/singleShape.py | singleShape.py | py | 7,250 | python | en | code | 5 | github-code | 1 |
18810182845 | """
Orthogonal Distance Regression using Monte Carlo to estimate errors
i.e. 1 fit using ODR with 10000 MC samples
Isaac Cheng - January 2021
"""
import sys
from pathlib import Path
import sqlite3
from contextlib import closing
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
impo... | tvwenger/coop2021 | rot_curve/odr_MC_errors.py | odr_MC_errors.py | py | 7,351 | python | en | code | 0 | github-code | 1 |
25108675279 | #!/usr/bin/env python
# xml parsing help from https://www.geeksforgeeks.org/reading-and-writing-xml-files-in-python/?ref=lbp
# to run you need to do
# `pip3 install beautifulsoup4`
# `pip3 install lxml`
import argparse
import datetime
from bs4 import BeautifulSoup
class Card(object):
"""
a ca... | brooks42/pkto | scripts/set_editor_script.py | set_editor_script.py | py | 9,191 | python | en | code | 5 | github-code | 1 |
70543510754 | from operator import add, sub
from _utils import *
inp = get_input(2020, 8)
tape = inp.strip().split("\n")
def step(i, acc):
op = {"+": add, "-": sub}
instr, arg = tape[i].split()
sign, num = arg[:1], arg[1:]
if instr == "nop":
i += 1
elif instr == "acc":
i += 1
acc = op[... | eferm/aoc-2020 | aoc_2020/day_08.py | day_08.py | py | 1,145 | python | en | code | 0 | github-code | 1 |
75162791714 | # -*- coding: utf-8 -*-
# Automatic provisioning of wireguard keypair resources.
import nixops.util
import nixops.resources
import logging
from typing import Mapping, Optional, Sequence
logger = logging.getLogger(__name__)
class WgKeypairOptions(nixops.resources.ResourceOptions):
"""Definition of wireguard key... | input-output-hk/nixops-wg-links | nixops_wg_links/resources/wg_keypair.py | wg_keypair.py | py | 5,381 | python | en | code | 2 | github-code | 1 |
25516931292 | import numpy as np
import numpy.typing as npt
import pandas as pd
from scipy import special
from typing import Any
from linearlab.lik.base import Likelihood
from linearlab.link import Link, LogitLink, logit
class _BinomialBase(Likelihood[npt.NDArray[np.int_]]):
def params(self) -> list[str]:
return ["p"]
... | dschulman/linearlab | linearlab/lik/_binomial.py | _binomial.py | py | 2,597 | python | en | code | 0 | github-code | 1 |
38543312863 | import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
from keras.models import load_model
import time
total_starttime = time.time()
generator = load_model(r'C:\Licenta\GAN_IMAGES\model_16_batch\generator_model_99.h5')
damaged_directory = r"C:\Licenta\GAN_I... | acuiram/DCGAN-with-U-Net | load_model.py | load_model.py | py | 1,410 | python | en | code | 1 | github-code | 1 |
10965723303 | import tensorflow as tf
import numpy as np
M = 2
K = 1
H = 2
Epoch_num = 1000
X = np.array([[0,0], [0,1], [1,0], [1,1]])
Y = np.array([[0],[1],[1],[0]])
x = tf.placeholder(tf.float32, shape=[None, M])
t = tf.placeholder(tf.float32, shape=[None, K])
W = tf.Variable(tf.random.truncated_normal([M, H]))
b = tf.Variab... | kitwub/prjLearnAI2018 | myEx/myEx06.py | myEx06.py | py | 901 | python | en | code | 0 | github-code | 1 |
20383117487 | from django import forms
from .models import Post
from urllib import request
from django.core.files.base import ContentFile
from django.utils.text import slugify
class PostCreateForm(forms.ModelForm):
def save(self, force_insert=False, force_update=False, commit=True):
posts = super().save(commit=False)
... | OtuokereTobechukwu/trill | activity/forms.py | forms.py | py | 619 | python | en | code | 0 | github-code | 1 |
71547218275 | start=ord(input("Enter start character:"))
stop=ord(input("Enter stop range of charcter :"))
for i in range(start,stop+1):
print(chr(i),end=" ")
print()
while start<=stop:
print(chr(start),end=" ")
start=start+1
| ssiedu/Python-Programming-070823-06PM | alphabetseries.py | alphabetseries.py | py | 228 | python | en | code | 0 | github-code | 1 |
7217036142 | import pendulum
from airflow import models
from airflow.operators.bash_operator import BashOperator
from datetime import datetime, timedelta
KST = pendulum.timezone("Asia/Seoul")
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime(2021, 8, 9, tzinfo=KST),
'email': ['... | J-TKim/airflow_tutorial | main.py | main.py | py | 1,065 | python | en | code | 1 | github-code | 1 |
30435717428 | class Node:
def __init__ (self, data):
self.data = data
self.prev = None
self.next = None
def __str__(self):
return str(self.data)
class List:
def __init__(self):
self.head = None
self.tail = None
def __str__(self):
if (self.head == None):... | ssai-snu/PythonProgramming | 11.Double_LinkedList.py | 11.Double_LinkedList.py | py | 1,253 | python | en | code | 0 | github-code | 1 |
71621333475 | from ast import Try
from dataclasses import replace
from os import rename
import sys
import time
from unicodedata import decimal
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from seleniu... | luanlara/CasosDeTeste4Sem | Caso3/codigoTestado3.py | codigoTestado3.py | py | 5,806 | python | pt | code | 0 | github-code | 1 |
161448674 |
import os
import pytest
from path import Path
from . import initialize_git_repo_and_commit, prepare_project
DIST_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '../dist'))
# Test if package can be imported to allow testing on
# conda-forge where ``pytest-virtualenv`` is not available.
try:
impor... | jem0101/BigSwag-SQA2022-AUBURN | TestOrchestrator4ML-main/resources/Data/supervised/GITHUB_REPOS/scikit-build@scikit-build/tests/test_distribution.py | test_distribution.py | py | 1,736 | python | en | code | 2 | github-code | 1 |
38933376235 | class FileManager:
def load_file(self, filename):
file_data = None
while file_data is None:
try:
file_handle = open(filename, 'r')
except FileNotFoundError:
print("{} not found.".format(filename))
print("please try an alternati... | Crossroadsman/treehouse-techdegree-python-project3 | file_manager.py | file_manager.py | py | 1,104 | python | en | code | 0 | github-code | 1 |
73026238115 |
class MyArray():
def __init__(self, size):
self.size = size
self.items = [None] * size
self.index = 0
def insert(self, item):
if (self.size == self.index):
newItems = [None] * self.size * 2
for i in range(self.size):
newItems[i] = self.it... | zalogarciam/data-structures-and-algorithms | Stacks/TwoStacks.py | TwoStacks.py | py | 4,866 | python | en | code | 0 | github-code | 1 |
16525458252 | import sys
import os
from shutil import copyfile
import subprocess
def check_dir(path):
directory = os.path.dirname(path)
if not os.path.exists(path):
return False
return True
def check_and_create(path):
if (check_dir(path) == False):
os.makedirs(path)
if __name__=='__main__':
#Need to error check
#W... | Benta63/Binary-Image-Segmentation | Ideas/MakeSlurm/MakeSlurm.py | MakeSlurm.py | py | 3,323 | python | en | code | 1 | github-code | 1 |
36224024372 | from pathlib import Path
import shelve
class PID():
P = Path('C:\\','Users','leouh', 'Documents', 'Rb_Controller')
def __init__(self):
with shelve.open('config') as config:
self.cfg = dict(config)
self.Ts = 1/self.cfg['freq']
if self.cfg['ki']:
self.taui = self.c... | leouhre/Rb_Controller | classes/pid.py | pid.py | py | 2,831 | python | en | code | 0 | github-code | 1 |
2360329917 | # Write a script that takes a string of words and a letter from the user.
# Find the index of first occurrence of the letter in the string. For example:
#
# String input: hello world
# Letter input: o
# Result: 4
result = ""
entry = input("please enter a string of words:\n\n words: ")
print("thanks!")
letter = inp... | SamuelMiller413/Python-101- | 12_user-input-string-formatting/12_01_input_occurrence.py | 12_01_input_occurrence.py | py | 749 | python | en | code | 0 | github-code | 1 |
43502378799 | # -*- coding: utf-8 -*-
__author__ = 'apsmi'
import asynchat, socket, struct, pickle
IN_BUF_SIZE = 128 * (2**10) # размер входящего буфера сокета
OUT_BUF_SIZE = 128 * (2**10) # размер исходящего буфера сокета
LEN_TERM = 4
# сокет, принимающий соединение от клиентов
class Client(asynchat.async_chat):
def __in... | apsmi/PyTanks | client_player.py | client_player.py | py | 2,210 | python | ru | code | 0 | github-code | 1 |
25463104297 | import argparse
import os
import os.path
import pandas
def main():
parser = argparse.ArgumentParser(description='Quick helper for getting model accuracies', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('inputs', nargs = '+', help='input CSVs')
parser.add_argument('--nrows', ... | CSSLab/maia-individual | 3-analysis/get_accuracy.py | get_accuracy.py | py | 727 | python | en | code | 18 | github-code | 1 |
37067667552 | from tkinter import *
from date.SQL import executeSQL
class FFCview:
def __init__(self):
self.root=Tk()
self.root.title="四角码转换器"
self.l_character = Label(self.root, text="汉字")
l.grid(row=1, column=0, sticky=W)
self.root.mainloop()
if __name__ == '__main... | Luoxin/Morse_Chinsese | user/FCCview.py | FCCview.py | py | 357 | python | en | code | 0 | github-code | 1 |
15237244149 | ## For example, if you pass '12345' the function returns all the sum of single digit
## in this case, the function will return 1+2+3+4+5 = 15
def sum_func(n):
## Base case when number is single digit by itself, when a number only contains 1 digit.
if len(str(n)) == 1:
return n
else:
## n %... | francedance/Python-Randomness | recursion/sum of single digit/sum_of_single_digit.py | sum_of_single_digit.py | py | 821 | python | en | code | 0 | github-code | 1 |
41094600245 | # savers
from sqlalchemy import exc
from src import db_manager
def save_page_to_db(page):
try:
db_manager.session.add(page)
db_manager.session.commit()
except exc.SQLAlchemyError as e:
db_manager.handel_exception(e, True, 'save_page', page.url)
return True
def save_site_to_db(si... | lavrinec/GOV-Crawler | crawler/src/savers.py | savers.py | py | 1,893 | python | en | code | 0 | github-code | 1 |
43806012643 | import sys
sys.stdin = open("양팔저울.txt")
def comp_kg(k, left, right, kgs):
global cnt
if sum(left) < sum(right):
return
if k == N:
# print(left, right)
cnt += 1
return
else:
comp_kg(k+1, left+[kgs[k]], right, kgs)
comp_kg(k+1, left, right+[kgs[k]], kgs)
... | 01090841589/ATM | 그외/08 4주/양팔저울.py | 양팔저울.py | py | 1,020 | python | ko | code | 0 | github-code | 1 |
11426662777 | # SOFTEX-RECIFE
# Aluno: Fábio de Tássio
# Atividade 02 do módulo 02 (Dominar as diferentes estruturas condicionais lógicas)
# Desenvolva um código que utilize as seguintes características de um veículo:
# - Quantidade de rodas;
# - Peso bruto em quilogramas;
# - Quantidade de pessoas no veículo.
# Com essas informaç... | fabiodtassio/Logica-e-Orientacao-a-Objetos | Modulo.02/atividade02.py | atividade02.py | py | 1,442 | python | pt | code | 0 | github-code | 1 |
42351005175 | import socket
import threading
import re
def thread_client(client_socket):
try:
while True:
data = client_socket.recv(1024).decode()
if not data:
break
match = re.match(r'^([0-9]+)([+\-*/])([0-9]+)$', data)
if match:
num1, op... | haticeadiguzel/TCP_CALCULATION_PROJECT | server/server.py | server.py | py | 1,916 | python | en | code | 0 | github-code | 1 |
9967391677 |
try:
nombre = str(input("\nIngrese su nombre: "))
edad = int(input("Ingrese su edad: "))
identificacion = int(input("Ingrese su identificacion: "))
if edad >= 18:
print("\nTu, {}, identificado con numero {} eres mayor de edad".format(nombre,identificacion))
else:
print("\nTu, {}, i... | BENC2024/ejerciciosdeclase | Ejercicio_otros/mostrar.py | mostrar.py | py | 460 | python | es | code | 0 | github-code | 1 |
30807069231 | #!/usr/bin/env python
#
# A class to control mu-del converters
#
# Incomplete
# 7DEC11 - Kyle Eberhart
import telnetlib
import logging
from multiprocessing import Process
from multiprocessing import Queue as Q
import queue
import time
class ConvProcess(object):
'''
A converter controller that runs in ... | keberhart/mu_del_converters | MuDelconverter.py | MuDelconverter.py | py | 13,500 | python | en | code | 0 | github-code | 1 |
22925175380 | import sys
import xbmc, xbmcplugin, xbmcgui, xbmcaddon
# -- Constants ----------------------------------------------
ADDON_ID = 'plugin.video.entertain'
FANART = xbmcaddon.Addon(id=ADDON_ID).getAddonInfo('path') + '/fanart.jpg'
# -- Settings -----------------------------------------------
settings = xbmcaddon.Addon(i... | tuxpoldo/entertain-xbmc | addon.py | addon.py | py | 10,745 | python | en | code | 7 | github-code | 1 |
73100419554 | print("Hello, world!")
name = input("Name: ")
print("Hello, " + name)
print(f"Hello, {name}")
n = input("Number: ")
if n.isdigit():
n = int(n)
if n > 0:
print(f"{n} is positive")
elif n < 0:
print(f"{n} is negative")
else:
print("Number is zero")
else:
print("No es un n... | soliakt/cs50-projects | hello.py | hello.py | py | 953 | python | en | code | 0 | github-code | 1 |
70173697953 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import argparse, codecs, sys
# Parseur de ligne de commande
parser = argparse.ArgumentParser(description="Sorts or inverts lines or characters from a file.")
parser.add_argument('-f', help="input file")
# seul -l ou -c est permis
lorc = parser.add_mutuall... | ndaoust/Z | scramble.py | scramble.py | py | 1,693 | python | fr | code | 0 | github-code | 1 |
21448529472 | import datetime as dt
from dateutil import parser
import os
import pandas as pd
import numpy as np
from scipy import interpolate
from matplotlib import mlab
from selenium import webdriver
import bs4
from timeout import timeout
class DECStation:
def __init__(self, number, name, lon, lat):
self.number = ... | patrick-miller/forecastaer | main.py | main.py | py | 11,649 | python | en | code | 1 | github-code | 1 |
72827283555 | n,m,x,y,k = map(int,input().split())
arr = []
dx = [0,0,-1,1]
dy = [1,-1,0,0]
for _ in range(n):
arr.append(list(map(int,input().split())))
command = list(map(int,input().split()))
dice = [0]*6
def diceMove(x):
if x == 1:
tmp = dice[4]
dice[4] = dice[1]
dice[1] = dice[5]
dice... | clapans/Algorithm_Study | 박수근/all_code/14499.py | 14499.py | py | 1,071 | python | en | code | 0 | github-code | 1 |
30375203012 | from fractions import Fraction
from wick.index import Idx
from wick.operator import FOperator, Tensor
from wick.expression import Term, Expression, AExpression
from wick.wick import apply_wick
from wick.convenience import E1, E2, commute
i = Idx(0, "occ")
a = Idx(0, "vir")
j = Idx(1, "occ")
b = Idx(1, "vir")
T1 = E1(... | awhite862/wick | examples/ccsd_1rdm.py | ccsd_1rdm.py | py | 1,831 | python | en | code | 14 | github-code | 1 |
13537059335 | #!/usr/bin/env python3
"""
author: huchiwen
language :python3
"""
def main():
A = [1,2,3]
B = [1,89,3]
res =0
result = (len(A) == len(B))
if result:
for i in range(0,len(A)):
res+=A[i]*B[i]
print(res)
else:
print("list not equal")
if __name__ == "__main__":
... | huchiwen/learningpy3 | ai.py | ai.py | py | 327 | python | en | code | 0 | github-code | 1 |
4878328533 | # -*- coding: utf-8 -*-
# © 2017 Eficent Business and IT Consulting Services S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from openerp.osv import fields, orm
from openerp.tools import float_compare, float_round, DEFAULT_SERVER_DATETIME_FORMAT
class StockLocation(orm.Model):
_inherit ... | one2pret/eficent-odoo-addons | stock_location_analytic/models/stock_location.py | stock_location.py | py | 9,165 | python | en | code | null | github-code | 1 |
39998982074 | import unittest
import shutil
import tempfile
import os
import logging
logging.getLogger().setLevel(logging.ERROR)
import heppy.framework.context as context
if context.name != 'bare':
from simple_example_noindexing_cfg import config
from heppy.utils.debug_tree import create_tree, remove_tree
from heppy.fr... | cbernet/heppy | heppy/test/test_noindexing.py | test_noindexing.py | py | 2,161 | python | en | code | 9 | github-code | 1 |
4516929724 | # Проанализировать зарплаты КМДА csv файлы за 2019 год найти средние минимальные максимальные построить график
import matplotlib.pyplot as plt
def get_data(filename):
with open(filename, 'r', encoding='utf8') as file:
data = {}
file.readline()
for row in file:
row_array = row... | su1gen/python-homework | lesson05HW/kmda/__main__.py | __main__.py | py | 1,344 | python | ru | code | 0 | github-code | 1 |
906788412 | import keras
from keras.layers import LSTM, Dense, Activation, Bidirectional, Dropout
from keras.optimizers import RMSprop, Adam, Adagrad, SGD
import datautils as dt
from keras.models import Sequential
from keras import regularizers
import os
import numpy as np
import pickle
from itertools import islice
from keras.mode... | skreddy99/NLP-Question-and-Answering-using-Mahabharatha | lstm_predict.py | lstm_predict.py | py | 5,770 | python | en | code | 1 | github-code | 1 |
28840367023 | # this class is meant to create a menu floater that moves across the screen vertically and in random positions
#importing librairies
import copy
import random
import pygame
import TestTubeGame
class Menu_Floater:
def __init__(self,img, direction):
self.image = img
self.current_image = copy.cop... | MiracleSheep/Python_Pygame_TestTubeGame | menu_floater.py | menu_floater.py | py | 1,851 | python | en | code | 0 | github-code | 1 |
41408100912 |
# 1305. All Elements in Two Binary Search Trees
# https://leetcode.com/problems/all-elements-in-two-binary-search-trees/
# https://leetcode.com/problems/all-elements-in-two-binary-search-trees/solution/
# https://leetcode.com/problems/all-elements-in-two-binary-search-trees/discuss/464368/Short-O(n)-Python
# Defini... | aszx4510/LeetCode | python/1305-all_elements_in_two_binary_search_trees.py | 1305-all_elements_in_two_binary_search_trees.py | py | 1,670 | python | en | code | 0 | github-code | 1 |
30209496323 | # LMGP Visualization
#
#
#
import numpy as np
import matplotlib.pyplot as plt
import torch
def plot_ls(model, constraints_flag = True):
#
# plot latent values
zeta = torch.tensor(model.zeta, dtype = torch.float64)
#A = model.nn_model.weight.detach()
perm = model.perm
levels = model.num_leve... | yiping514/LMGP | lmgp_pytorch/visual/plot_latenth_position.py | plot_latenth_position.py | py | 2,515 | python | en | code | 0 | github-code | 1 |
74069745633 | ### FUNCTIONS
import skimage
import numpy as np
from math import sqrt
from skimage.feature import blob_dog, blob_log
from PIL import Image
import torch
from torchvision import transforms
import matplotlib.pyplot as plt
import matplotlib
import cv2
import os
### 1 GET DISTANCE
def crop_x(image, x1=100,x2=250, y1=38... | AlmudenaBravoC/CAD-ultrasound-renal-diagnosis | TestImage/allProcess.py | allProcess.py | py | 6,977 | python | en | code | 2 | github-code | 1 |
35846348458 | import subprocess
import time
import csv
RangeToDo = 38
NumToIterate = 3
filesToBench = ["LoopCache","Origonal","WithOverhead"]
for fileName in filesToBench:
print(subprocess.check_output("./"+str(fileName)+" ../example.txt "+str(42)))
csvFileName = "benchOuput_"+fileName+".csv"
timesAll = []
timesAvg ... | Fallstop/bf-in-rosetta | rust/Benchmarks/benchAll.py | benchAll.py | py | 1,140 | python | en | code | 2 | github-code | 1 |
17890730091 | import sys
import os
from rich.pretty import pprint
from urllib.parse import quote_plus
from rich.table import Table
from rich.console import Console
from rich.prompt import IntPrompt, Prompt, Confirm
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/../..")
from lib.submissions import get_submissions,... | willthbill/cfscripts | src/scripts/UnsolvedContestProblems/main.py | main.py | py | 4,947 | python | en | code | 2 | github-code | 1 |
16616999122 | import random
"""
Implement a program that tells the user the probability of getting heads when tossing a coin
"""
def main():
#specific range
min = 0
max = 0.7
#generate a random floating point number
heads = min + (max-min)*random.random()
print(f'The probability of h... | gxgarciat/Playground-CiP-py | 4_Worked_Examples/3_WeightedCoin.py | 3_WeightedCoin.py | py | 381 | python | en | code | 0 | github-code | 1 |
20109466392 | import string
import numpy as np
import pandas as pd
from kartothek.io.eager import store_dataframes_as_dataset
def create_dataset(dataset_uuid, store_factory, metadata_version):
df = pd.DataFrame(
{"P": np.arange(0, 10), "L": np.arange(0, 10), "TARGET": np.arange(10, 20)}
)
df_helper = pd.Data... | hoffmann/kartothek | kartothek/io/testing/utils.py | utils.py | py | 1,030 | python | en | code | null | github-code | 1 |
1333573052 | """
Filename : rabinKarp.py
Author : Archit Joshi
Description : Implementation of the Rabin Karp algorithm to find pattern
occurrences in a string.
Complexity : O(n)
Language : python3
"""
def hashVal(string):
"""
Simple has function that returns the hash value as sum of ordinal va... | JoshiArchit/Algorithm-Implementations | Rabin Karp Algorithm/rabinKarp.py | rabinKarp.py | py | 1,792 | python | en | code | 1 | github-code | 1 |
20491607874 | import torch
from torch import nn
import torch.nn.functional as F
class FastText(nn.Module):
def __init__(self, num_tags, vocab_size, embed_size, input_dropout_rate,
embed_type='rand', use_bigram=False, bigram_vocab_size=0, bigram_embed_size=0):
super(FastText, self).__init__()
se... | zerozzl/nlp_text_cla | fasttext/model.py | model.py | py | 2,103 | python | en | code | 0 | github-code | 1 |
5393022370 | import PySimpleGUI as sg
from Utility import PathDefs
NAME_SIZE = 20
def name(name):
dots = NAME_SIZE - len(name) - 2
return sg.Text(name + ' ' + '•' * dots, size=(NAME_SIZE, 1), justification='r', pad=(0, 0), font='Courier 10')
def create_rows(max_cost, max_mass, max_disp, max_time, cost_coef, mass_coef, ... | anikimmel/LMCOgui | Utility/row_utilities.py | row_utilities.py | py | 5,099 | python | en | code | 0 | github-code | 1 |
32200653326 | #! /usr/bin/env python
import sys
import argparse
import csv
def main():
parser = argparse.ArgumentParser()
parser.add_argument('input', metavar='INPUT', type=argparse.FileType('rb'), help="csv file")
parser.add_argument('output', metavar='OUTPUT', type=argparse.FileType('wb'), help="yml file")
args... | pk-hack/CoilSnake | coilsnake/tools/csv2yml.py | csv2yml.py | py | 818 | python | en | code | 153 | github-code | 1 |
30874114710 | import requests
ship = "10/"
resp = requests.get("https://swapi.co/api/starships/"+ship)
print(resp.status_code)
data = resp.json()
print(str(data['name']))
print("Peliculas:")
for var in data['films']:
url = str(var)
pelis = requests.get(url)
pelis = pelis.json()
print(str(pelis['title'... | Pxncxke/millenium | api.py | api.py | py | 323 | python | en | code | 0 | github-code | 1 |
14680309244 | budget = float(input())
statist_count = float(input())
price_clothes = float(input())
decour = budget * 0.1
clothes_all = statist_count * price_clothes
if statist_count > 150:
clothes_all *= 0.9
expenses = decour + clothes_all
if (expenses) > budget:
print(f'Not enough money! \n Wingard needs {(expenses - b... | Grigorov999/SoftUni-Python | Python_basics/Godzilla_vs_Kong.py | Godzilla_vs_Kong.py | py | 439 | python | en | code | 0 | github-code | 1 |
935555272 | import functools
import logging
import time
def validate_command(command):
def actual_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if len(args) < 2:
logging.debug(f"{func.__name__} Error: not enough arguments")
return
... | CS4224-Claps/project | cockroachdb/utils/decorators.py | decorators.py | py | 1,236 | python | en | code | 1 | github-code | 1 |
25282917434 | from tkinter import *
import time
#new seperate window functions. These code is just a front end for the deposit, withdraw, and balance functions
def deposit_window():
time.sleep(1)
dwindow = Toplevel(root)
dwindow.title('Deposit')
dwindow.geometry("470x300")
dwindow.resizable(0,0)
dlabel=L... | EthicalDeveloper/python-banking-system | utopiabank.py | utopiabank.py | py | 2,488 | python | en | code | 0 | github-code | 1 |
21193345308 | class Solution(object):
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
totalper = 0
island, rightedg, downedg = 0, 0, 0
rows, cols = len(grid), len(grid[0])
for r, row in enumerate(grid):
for c, val in enum... | excaliburnan/SolutionsOnLeetcodeForZZW | 463_IslandPerimeter/islandPerimeter.py | islandPerimeter.py | py | 643 | python | en | code | 0 | github-code | 1 |
24758047234 | import boto3
import logging
import os
import json
dynamodb_client = boto3.client('dynamodb', region_name="us-east-1")
sns_client = boto3.client('sns', region_name="us-east-1")
CUSTOMERS_TABLE_NAME = os.getenv('CUSTOMERS_TABLE', "functions_table")
SNS_TOPIC_ARN_FUNCTION_MODIFIED = "function_modified"
with_sns_msg = T... | dome9/protego-examples | proact/inputs/python_new_file_handler/python_new_file_handler.py | python_new_file_handler.py | py | 1,058 | python | en | code | 4 | github-code | 1 |
29245319623 | import math
def firstBadVersion(n):
"""
:type n: int
:rtype: int
"""
start = 0
end = n
mid = int(math.ceil((start + end)/2))
lastGood = 0
print("start: " + str(start))
print("mid: " + str(mid))
print("end: " + str(end))
while start<=end:
print("this is loop")
... | jinlee487/Algorithm | src/leetcode/l278.py | l278.py | py | 874 | python | en | code | 0 | github-code | 1 |
39117095073 | """
CS235 Homework 3
Aleksander Skjoelsvik
"""
from math import floor
from fractions import gcd
#Task 1:
"""
a:
4x = 2 (mod 11)
4x = 24 (mod 11)
x = 6 + 11Z
b:
x = 3 (mod 7)
x = 1 (mod 5)
x = 31 + 35Z
c:
x = 2 (mod p)
x = 4... | alekplay/schoolwork | CS235/hw3.py | hw3.py | py | 1,964 | python | en | code | 0 | github-code | 1 |
26593044181 | """Backend functions for exporting data."""
import os
import boto3
import fsspec
import shutil
import logging
import warnings
import datetime
import xarray as xr
import pandas as pd
from importlib.metadata import version as _version
from botocore.exceptions import ClientError
from climakitae.util.utils import read_csv... | cal-adapt/climakitae | climakitae/core/data_export.py | data_export.py | py | 26,702 | python | en | code | 11 | github-code | 1 |
70205308194 | from dp import *
import pickle
from collections import defaultdict
from most_probable_sequence import most_probable_sequence
from utils import get_data
from rich import print
def load_weights(run_name, weights_root):
if run_name != None:
w = np.load(f"outputs/{run_name}/w.npy")
b = np.load(f"outpu... | yermandy/most-probable-sequence | inference.py | inference.py | py | 7,238 | python | en | code | 0 | github-code | 1 |
74918538912 | from slsim.Sources.SourceVariability.variability import (
Variability,
)
class Source(object):
"""This class provides source dictionary and variable magnitude of a individual
source."""
def __init__(self, source_dict, variability_model=None, kwargs_variab=None):
"""
:param source_dict... | LSST-strong-lensing/slsim | slsim/Sources/source.py | source.py | py | 4,037 | python | en | code | 7 | github-code | 1 |
30558238775 | import psycopg2
import json
from kafka import KafkaConsumer
class Consumer:
kafka_server = None
consumer = None
kafka_topic = None
db_config = None
db_conn = None
def __init__(self):
config = self.load_config()
self.kafka_server = config['credentials']['kafka']['uri']
s... | vladimir-kirillovskiy/website-monitoring | consumer.py | consumer.py | py | 2,947 | python | en | code | 0 | github-code | 1 |
30915139901 | import pytest as pytest
from selenium import webdriver
driver = None
@pytest.fixture()
def setup_and_teardown(request):
global driver
driver = webdriver.Chrome()
driver.maximize_window()
request.cls.driver = driver
yield
driver.quit()
| VardhiniMohan/SeleniumPythonHybridFramework2 | tests/conftest.py | conftest.py | py | 262 | python | en | code | 0 | github-code | 1 |
42448765073 | import argparse
import glob
import json
import os
import sys
MIN_PYTHON = (3, 0)
if sys.version_info < MIN_PYTHON:
sys.exit("Python {}.{} or later is required.\n".format(*MIN_PYTHON))
parser = argparse.ArgumentParser()
parser.add_argument("input", help="input directory with files to annotate")
parser.add_argument... | iscoe/dragonfly | scripts/pack.py | pack.py | py | 1,916 | python | en | code | 9 | github-code | 1 |
35947581054 | # -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
"""
This script is for plotting G1/G2/G4 data of calculated Symm-Func for
train and predict of Lammps-MD 1000K LC7
"""
def plotG(symdt, plttitle, plotfile, xlb, clr):
fig = plt.figure()
ax = fig.add_subplot(111)
plt.title(plttitle... | s-okugawa/HDNNP-tools | tools/Lmps-MD/plotSymF-TP2.py | plotSymF-TP2.py | py | 3,233 | python | en | code | 0 | github-code | 1 |
38597169357 | #!/usr/bin/python3
import datetime, glob, os, subprocess, unittest
from slippi import Game, parse
from slippi.id import CSSCharacter, InGameCharacter, Item, Stage
from slippi.log import log
from slippi.metadata import Metadata
from slippi.event import Buttons, Direction, End, Frame, Position, Start, Triggers, Velocit... | hohav/py-slippi | test/replays.py | replays.py | py | 11,337 | python | en | code | 54 | github-code | 1 |
32157164091 | class GroupRule:
def __init__(self, group, tag_requires, tag_conflicts, group_requires, group_conflicts):
self.group = group
self.tag_requires = set(tag_requires)
self.tag_conflicts = tag_conflicts
self.group_requires = group_requires
self.group_conflicts = group_conflicts
def meets_requireme... | protoclex/TagGuard | tag_guard/group_rule.py | group_rule.py | py | 1,128 | python | en | code | 0 | github-code | 1 |
43514093925 | import unittest
from delivery import *
from pedidos import *
from loja import *
from motoboy import *
moto1 = Motoboy('João', 2, None, None)
moto2 = Motoboy('Carlos', 2, None, None)
moto3 = Motoboy('Alberto', 2, None, None)
moto4 = Motoboy('Bruna', 2, 'Magazine', None)
moto5 = Motoboy('Luiza', 3, None, None)
pedido1_... | estevo72/teste_zax | test.py | test.py | py | 2,533 | python | pt | code | 0 | github-code | 1 |
1127182714 | class Solution:
def reverseWords(self, s: str) -> str:
s =s.strip() #删除首尾空格
#双指针,从右向左寻找空格
i = j =len(s) -1
new =[]
while i>=0:
while i>=0 and s[i] != ' ': i-=1 #寻找第一个空格
new.append(s[i+1: j+1]) #添加进数组
while i>=0 and s[i] == ' ': i-=1 #跳过空格
... | MeiXue16/Algorithmus- | s58_1.py | s58_1.py | py | 467 | python | en | code | 0 | github-code | 1 |
17407487909 | import gtk
import thermo
class SteamSolver:
def __init__(self):
'''Initial window which has a combo box from which the user can choose either of temperature and pressure'''
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.set_size_request(500 , 500)
self.win... | MechCoder/Steam-Solver | Steamsolver.py | Steamsolver.py | py | 9,908 | python | en | code | 0 | github-code | 1 |
26219537771 | from tvm.relay.expr_functor import ExprMutator
#from collage.utils import *
import tvm.relay as relay
"""
This class annotates relay expression with compiler_begin and compiler_end
for each operator from target backend.
This will be merged by merge and partition pass following this.
"""
class ExtCompilerOpAnnotator(Ex... | mikepapadim/collage-non-tvm-fork | python/collage/optimizer/ext_compiler_op_annotator.py | ext_compiler_op_annotator.py | py | 2,406 | python | en | code | 1 | github-code | 1 |
9249662097 | import gym
# Set learning parameters
LEARNING_RATE = .8
DISCOUNT_FACTOR = .95
NUM_EPISODES = 2000
def state_to_scalar(state):
state_scalar = state.reshape(state.shape[0] * state.shape[1] * state.shape[2], 1)
return state_scalar
env = gym.make('SpaceInvaders-v0')
env.reset()
print('env.observation_space.n... | raphaelgodro/open-ai-trains | space_invaders.py | space_invaders.py | py | 1,080 | python | en | code | 0 | github-code | 1 |
24284873718 | # 複雑なソート
# 数値や文字列のようにそのものでソートできないものをソートする
class Tool:
def __init__(self, name, weight):
self.name = name
self.weight = weight
def __repr__(self):
return f'Tool({self.name!r}, {self.weight})'
tools = [
Tool('level', 3.5),
Tool('hammer', 1.25),
Tool('screwdriver', 0.5),
Tool('chiel', 0.25),
]
p... | todayisanotherday/effective-python | chapter02/14.py | 14.py | py | 1,571 | python | en | code | 0 | github-code | 1 |
15497539483 | '''
283. Move Zeroes
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
1.You must do this in-place without making a copy of the array.
2.Minimize ... | swave2015/swave-LeetCode | Python/move_zeroes.py | move_zeroes.py | py | 999 | python | en | code | 0 | github-code | 1 |
23163444909 | import pyaudio
import math
import struct
# Wut is diz??
Threshold = 10
SHORT_NORMALIZE = (1.0/32768.0)
swidth = 2
chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000
f_name_directory = r'audiofiles'
class Listener:
@staticmethod
def rms(frame):
count = len(frame) / swidth
format... | astuvan/av_generator | sound/react_to_sound/react_threshold.py | react_threshold.py | py | 1,392 | python | en | code | 0 | github-code | 1 |
72503316195 | import cv2
import numpy as np
from keras.models import load_model
model = load_model('CNNmodel.h5')
def prediction(pred):
return chr(pred + 65)
def keras_predict(model1, image):
data = np.asarray(image, dtype="int32")
pred_probab = model1.predict(data)[0]
pred_class = list(pred_probab).index(max(pr... | CharizmaticWizard/Sign-Language-Detection | capture.py | capture.py | py | 1,644 | python | en | code | 1 | github-code | 1 |
38975372598 | import shell_content
import os
import time
import signal
import subprocess
import numpy as np
import pydoop.hdfs as hdfs
import json
spark_conf_names = ['spark.default.parallelism', 'spark.driver.cores', 'spark.driver.memory',
'spark.driver.maxResultSize',
'spark.executor.instan... | TsinghuaDatabaseGroup/AI4DBCode | Spark-Tuning/prediction_nn/run_action.py | run_action.py | py | 8,108 | python | en | code | 56 | github-code | 1 |
74789092834 | import random
import time
def RandomSearch(A,k):
n = len(A)
checked = [0 for i in range(n)]
while sum(checked)!=n:
i = random.randint(0,n-1)
if (A[i]==k):
return i
checked[i] = 1
return -1
def LinearSearch(A,k):
n = len(A)
for i in range(n):
... | charleschang213/VE477 | Labs/l8/l8.py | l8.py | py | 937 | python | en | code | 0 | github-code | 1 |
35162208747 | import sys
import atexit
import subprocess
import typing
class AutoPager:
def __init__(self, no_pager: bool = False, always: bool = False):
self.original_stdout = sys.stdout
self.always = always
self.no_pager = no_pager
if self.original_stdout.isatty():
self.process: t... | informationsea/cromwell-helpers | cromwellhelper/pager.py | pager.py | py | 751 | python | en | code | 0 | github-code | 1 |
4700100069 | # system imports
import logging
import sys
import os
import io
import concurrent.futures
import shutil
from time import sleep
#import keyring
# google and http imports
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledApp... | k3tchup/google_drive_sync | libgdrive/gDrive.py | gDrive.py | py | 48,013 | python | en | code | 0 | github-code | 1 |
40829037969 | from base64 import b64encode
from django import template
CSS_CLASS = 'dj-special-block'
KEY_PREFIX = 'dj-special-{}'
block_count = 0
register = template.Library()
class ShideNode(template.Node):
template = "<div class=\"%s\" id=\"{key_name}\"></div>"\
"<script>localStorage.setItem('{key_name}', ... | xfenix/django-search-hide | searchhide/templatetags/searchhide.py | searchhide.py | py | 1,199 | python | en | code | 0 | github-code | 1 |
12015108525 |
import os
from dragonEyes.align_dlib import AlignDlib
import csv
import glob
import cv2
from PIL import Image, ImageDraw
import pandas as pd
from random import shuffle
align_dlib = AlignDlib(os.path.join(os.path.dirname(__file__), 'transferredSkills/dlib_models/shape_predictor_68_face_landmarks.dat'))
def draw_on_im... | rtbins/MishMash-Dumbo | facial_recog_service/dragonEyes/modify_image.py | modify_image.py | py | 4,937 | python | en | code | 0 | github-code | 1 |
26787388699 | from queue import Queue
import task2
import solver
class HigherLevelSokoban:
def __init__(self, lower_level_sokoban):
self.lower_level_sokoban = lower_level_sokoban
def gen_new_states_with_priority(self, state_with_priority):
_, state = state_with_priority
# print('here')
fo... | sgorawski/InformatykaUWr | Sztuczna_inteligencja/lab2/task3.py | task3.py | py | 2,406 | python | en | code | 0 | github-code | 1 |
15859503196 | from crypt import methods
from flask import Flask , render_template, request, make_response
from werkzeug.wrappers import Response
import os
from .healpers.CsvHealper import allowed_file, parse_user_file, generate_file
def create_app():
app = Flask(__name__)
app.secret_key = os.environ["Secret"]
return a... | Maminebouzid/flask_upload_csv | app/__init__.py | __init__.py | py | 2,028 | python | en | code | 0 | github-code | 1 |
32065924500 | """
Graph structure with basic methods built in
"""
from personal_information import (Address, Person, COVID_Status)
from basic_data_structures import (Stack, Queue)
import csv
import random
class Node:
"""
A single entity in the graph
"""
pass
class Graph:
"""
A graph representation of the... | yonathanF/UVA-CDE-Corona-Project | ProjectTemplate/graph.py | graph.py | py | 3,351 | python | en | code | 1 | github-code | 1 |
18900639652 | from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext
from .forms import Mp3DetailsForm
from gtts import gTTS
import os
import time
def index(request):
if request.method == 'POST':
context = RequestContext(request)
aform = Mp3Details... | me12722/text-to-speech | Text_to_Speech/tts/views.py | views.py | py | 1,449 | python | en | code | 0 | github-code | 1 |
72617146914 | #!/usr/bin/env python3
import re
import csv
import collections
def get_error_message_type(log):
if re.search(r"ERROR", log):
return "ERROR"
if re.search(r"INFO", log):
return "INFO"
def find_errors():
error_dict = {}
with open("syslog.log", "r") as logfile:
for ... | annie21409/google-python-professional | final_project/tickylog.py | tickylog.py | py | 2,178 | python | en | code | 0 | github-code | 1 |
72133950755 | #!/usr/bin/python3
# 9-model_state_filter_a.py
"""Script that lists all State that contains the letter a
from the database hbtn_0e_6_usa
"""
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from model_state import Base, State
from sys import argv
def firstState():
"""Prints first state... | jonseb974/holbertonschool-higher_level_programming | python-object_relational_mapping/9-model_state_filter_a.py | 9-model_state_filter_a.py | py | 804 | python | en | code | 0 | github-code | 1 |
75060048994 | def check_square(matrix, r, c):
square_list = [matrix[r - 1][c - 1],
matrix[r - 1][c],
matrix[r - 1][c + 1],
matrix[r][c - 1],
matrix[r][c + 1],
matrix[r + 1][c - 1],
matrix[r + 1][c],
... | avihay30/PythonProjects | Python_practices/HW_Malam/HW04/q1_hard_way.py | q1_hard_way.py | py | 3,275 | python | en | code | 0 | github-code | 1 |
28646143818 | #Faça um programa que leia um número inteiro e diga quantas vezes ele foi dividido - utilizar cores
n = int(input('Digite um número: '))
tot = 0
for i in range(1, n + 1):
if n%i == 0:
print('\033[33m', end='')
tot += 1
else:
print('\033[31m', end='')
print('{} '.format(i), end='')
p... | jaquemff/exercicio-aprendizagem-python | ExercicioNumeroPrimo.py | ExercicioNumeroPrimo.py | py | 390 | python | pt | code | 0 | github-code | 1 |
6517886216 | #Tool check active subdomain from amass result
from concurrent.futures import ThreadPoolExecutor
import requests
from requests.exceptions import ConnectionError
import argparse
parser = argparse.ArgumentParser(description='Example argument parser')
parser.add_argument('--input_file','-i', help='path to input file')
p... | quangdaik2362001/simple_tool | is_live.py | is_live.py | py | 1,171 | python | en | code | 0 | github-code | 1 |
704734527 | __docformat__ = 'restructuredtext'
import sys
from zope import component
from zope.interface import implements
from zope.component.interfaces import ComponentLookupError
from zope.traversing.interfaces import IPathAdapter, ITraversable
from zope.traversing.interfaces import TraversalError
from zope.traversing.adapter... | displacedaussie/gae-zpt | zope/pagetemplate/engine.py | engine.py | py | 14,488 | python | en | code | 3 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.