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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
36259278100 | import requests
from bs4 import BeautifulSoup
import json
import secrets
from requests_oauthlib import OAuth1
from operator import itemgetter
import sqlite3
import csv
import base64
import itertools
import plotly.plotly as py
import plotly.graph_objs as go
import webbrowser
spotifybase = "https://accounts.spotify.com/... | jntoma/finalproj206 | final_food.py | final_food.py | py | 33,382 | python | en | code | 0 | github-code | 6 |
4470012110 | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 10 23:13:16 2015
@author: maxshashoua
"""
file = list(open("Standing_Ovation_Large.in"))
for i in range(len(file)):
file[i] = file[i].strip("\n").strip()
T = int(file[0])
Total = T
data = file[1:]
""""
for l in data:
t = l[0]
s = 1
friends = 0
raw... | emsha/Code-Jam | standingovation.d/Standing_Ovation_Solver.py | Standing_Ovation_Solver.py | py | 1,142 | python | en | code | 0 | github-code | 6 |
5259664413 | import re
#import CMUTweetTagger
#import cPickle
from collections import defaultdict
import pickle
from nltk.corpus import wordnet as wn
from itertools import product
import spacy
from spacy.symbols import *
from nltk import Tree
import nltk
nlp=spacy.load('en')
np_labels=set(['nsubj','dobj','pobj','iobj','conj','nsu... | varun-manjunath/disaster-mitigation | matching/common_nouns.py | common_nouns.py | py | 7,549 | python | en | code | 2 | github-code | 6 |
24706158570 | #!/usr/bin/python2.4
import base64
import hmac
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import hashlib
class PlacesHandler(webapp.RequestHandler):
"""Handles requests to /places."""
def post(self):
"""Handle... | bilal-karim/gmaps-samples-v3 | devfest-2010/whereiscoffee/places.py | places.py | py | 1,627 | python | en | code | 6 | github-code | 6 |
1370583347 | """Finds the differences between two dictionaries and writes them to a csv."""
import csv
def diff_dictionaries(DCT1, DCT2):
"""Output a dictionary of the differences between two dictionaries."""
return {player: DCT1[player] for player in set(DCT1) - set(DCT2)}
def write_to_csv(dct):
"""Write dictionar... | craighillelson/diff_dicts | diff_dicts.py | diff_dicts.py | py | 910 | python | en | code | 0 | github-code | 6 |
4769812727 | '''Partition a set into two subsets such that the difference of subset sums is minimum.
Given a set of integers, the task is to divide it into two sets S1 and S2 such that the absolute difference between their sums is minimum.'''
#This function returns the list of all the sum of all subset possible
def subsetSum... | subhajitsinha1998/DynamicPrograming | minSubsetSumDifference.py | minSubsetSumDifference.py | py | 1,707 | python | en | code | 0 | github-code | 6 |
13902158282 | mA = [[ 1, 2, 3],[ 4, 5, 6]]
t = [[ 1, 4],
[ 2, 5],
[ 3, 6]]
matriz = [[1,2,3],[4,5,6]]
def transpuesta(mA):
t = []
for i in range(len(mA[0])):
t.append([])
for j in range(len(mA)):
t[i].append(mA[j][i])
return t
matrizTranspuesta = transpuesta(matriz)
for linea in mat... | Nayherly/INFORME02 | Matrices/4.Transpuesta.py | 4.Transpuesta.py | py | 514 | python | en | code | 0 | github-code | 6 |
4328206070 | """
The game is played on a square board divided into 20 rows and 20 columns, for
a total of 400 squares. There are a total of 84 game tiles, organized into 21
shapes in each of four colors: blue, yellow, red and green. The 21 shapes are
based on free polyominoes of from one to five squares (one monomino, one
domino,... | wnojopra/obstructus | game.py | game.py | py | 4,419 | python | en | code | 0 | github-code | 6 |
31958051556 | import sys
import csv
def main():
# get command line arguments
inputdatabase = sys.argv[1]
inputsequence = sys.argv[2]
# open database file
csvfile = open(inputdatabase, newline='')
databaseobj = csv.reader(csvfile)
# load database into array
database = []
for row in databaseobj:... | Verano-20/CS50-PSET6-DNA | dna.py | dna.py | py | 2,420 | python | en | code | 1 | github-code | 6 |
29832128346 | import cv2
#Reading Image
img = cv2.imread('img46_gray_noise.png')
#Aplying filter
median = cv2.medianBlur(img,3)
#Showing image
cv2.imshow("Noised Image", img)
cv2.imshow("median", median)
cv2.waitKey()
cv2.destroyAllWindows()
#Save result
cv2.imwrite("denoised_image.png", median) | Digu62/computer_vision_challenges | Questao1/main.py | main.py | py | 286 | python | en | code | 0 | github-code | 6 |
75118275066 | import sqlite3
with open("C:\\Users\Asmaa Samir\Desktop\Project\data.txt", "w") as myFile:
my_tuple1 = ('google.com ', '198.188.3.2 ', '255.255.255.0', '11:01 ')
my_tuple2 = ('youtube.com', '199.588.35.22', '255.255.255.0', '1:01')
my_tuple3 = ('google.com', '198.155.66.1', '255.255.255.0', '7:55')
... | AsmaaGHSamir/GProject | DB.py | DB.py | py | 926 | python | en | code | 1 | github-code | 6 |
27645529568 | ''' COMPSCI 235 (2021) - University of Auckland
ASSIGNMENT PHASE TWO
Simon Shan 441147157
Flask app entry point
'''
from library import create_app
app = create_app()
if __name__ == '__main__':
app.run(
host='localhost',
port=5000,
threaded=False,
)
| mightbesimon/library-flask-website | wsgi.py | wsgi.py | py | 299 | python | en | code | 1 | github-code | 6 |
25755936450 | import unittest
from constants import (
LAST_NAME_1,
LAST_NAME_2,
LAST_NAME_3,
LAST_NAME_4,
LAST_NAME_UPDATED,
LAST_NAME_TEST,
FIRST_NAME_1,
FIRST_NAME_2,
FIRST_NAME_3,
FIRST_NAME_4,
FIRST_NAME_JOHN,
FIRST_NAME_UPDATED,
MIDDLE_NAME_1,
MIDDLE_NAME_2,
MIDDLE_NA... | dan9Protasenia/task-management | tests/test_employee_service.py | test_employee_service.py | py | 5,175 | python | en | code | 0 | github-code | 6 |
6729300182 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
"""
@file: oracle_cls.py
@author: ImKe at 2022/2/23
@email: tuisaac163@gmail.com
@feature: #Enter features here
"""
import torch.nn as nn
import torch
import datetime, os, copy, math, time, collections, argparse, nltk, json, sys
sys.path.append('../')
import numpy as np
from... | ImKeTT/AdaVAE | controlgen/oracle_cls.py | oracle_cls.py | py | 9,368 | python | en | code | 32 | github-code | 6 |
10418352733 | from __future__ import annotations
import dataclasses
import typing
from randovania.game_description.db.resource_node import ResourceNode
from randovania.game_description.requirements.requirement_and import RequirementAnd
from randovania.game_description.requirements.resource_requirement import ResourceRequirement
fr... | randovania/randovania | randovania/game_description/db/teleporter_network_node.py | teleporter_network_node.py | py | 3,434 | python | en | code | 165 | github-code | 6 |
39269318225 | import logging
import os
import random
import sys
from functools import wraps
from pprint import pformat
from subprocess import Popen, PIPE
from threading import Thread
from dim import db
from dim.models.dns import OutputUpdate
from dim.rpc import TRPC
from tests.pdns_test import PDNSTest
from tests.pdns_util import c... | 1and1/dim | dim-testsuite/tests/pdns_changes.py | pdns_changes.py | py | 4,950 | python | en | code | 39 | github-code | 6 |
8169757480 | """
Exercício 4
Nome na vertical em escada. Modifique o programa anterior de forma a mostrar o nome em formato de escada.
F
FU
FUL
FULA
FULAN
FULANO
"""
nome = input('Digite seu nome: ').strip().upper()
# OPÇÃO 1
n = ''
for c in nome:
n += c
print(n)
# OPÇÃO 2
# for c in range(len(nome)+1):
# p... | fabriciovale20/ListaExerciciosPythonBrasil | 6. String/ex004.py | ex004.py | py | 341 | python | pt | code | 0 | github-code | 6 |
39261296650 | import os
import shutil
import zipfile
from base64 import b64decode
from utils.config import config
import requests
root_path = os.getcwd()
gat = (
"Z2l0aHViX3BhdF8xMUJBQkhHNkEwa1JRZEM1dFByczhVXzU0cERCS21URXRGYm"
"FYRElUWE5KVUk4VkUxVTdjb0dHbElMSWdhVnI2Qkc3QzVCN0lCWlhWdDJMOUo2"
)
def download_and_extract_zip(... | CHNZYX/Auto_Simulated_Universe | utils/update_map.py | update_map.py | py | 4,483 | python | en | code | 2,771 | github-code | 6 |
5308998970 | # ababcdcdababcdcd ->2ab2cd2ab2cd ->2 ababcdcd
# abcabcdede -> abcabc2de ->2abcdede
# 1씩 증가하면서 묶기 -> 같은거 있으면 합치기 -> 길이 구하기
# 하나가 에러남 -> 길이가 1,2,3 일 때 예외처리하면 안남
def solution(s):
def merge_len(var):
cnt = 1
temp = ''
# 마지막인 경우 케이스 생각해야함
for i in range(len(var)-1):
if var[i... | louisuss/Algorithms-Code-Upload | Python/Programmers/Level2/문자열압축.py | 문자열압축.py | py | 2,022 | python | ko | code | 0 | github-code | 6 |
15503714340 | import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([5, 6, 7, 8])
c = np.add(a, b)
print(c)
# creating a custom ufunc - universal functions
def add_2_str(v, k):
y = v + k
return y
add_2_str = np.frompyfunc(add_2_str, nin=2, nout=1)
print(add_2_str([1, 2, 3, 4, 5], [6, 7, 8, 9, 10]))
print(add_2_str... | BLACKANGEL-1807/Python-Scripts | Numpy(basics)/numpy_ufunc.py | numpy_ufunc.py | py | 406 | python | en | code | 0 | github-code | 6 |
27070905288 | import datetime as dt
import random
import pytest
from scheduler import Scheduler, SchedulerError
from scheduler.base.definition import JobType
from scheduler.threading.job import Job
from ...helpers import DELETE_NOT_SCHEDULED_ERROR, foo
@pytest.mark.parametrize(
"n_jobs",
[
1,
2,
... | DigonIO/scheduler | tests/threading/scheduler/test_sch_delete_jobs.py | test_sch_delete_jobs.py | py | 2,653 | python | en | code | 51 | github-code | 6 |
6814879797 | import pika, json
def upload(f, fs, channel, access):
# put file into mongodb database
try:
# get file if success
fid = fs.put(f)
except Exception as err:
return "internal server error", 500
# create message
message = {
"video_fid": str(fid),
"mp3_fid": None,
# who owns the file
"username": acc... | dawmro/testing_microservice_architectures | python/src/gateway/storage/util.py | util.py | py | 807 | python | en | code | 0 | github-code | 6 |
29800711842 | import mraa
import time
RedPin = 3
BluePin = 4
# humidity_seneor = mraa.Gpio(sensorPin)
# humidity_seneor.dir(mraa.DIR_IN)
i = 0
redLED = mraa.Gpio(RedPin)
blueLED = mraa.Gpio(BluePin)
redLED.dir(mraa.DIR_OUT)
blueLED.dir(mraa.DIR_OUT)
try:
while (1):
redLED.write(True)
blueLED.write(False)
... | RichardZSJ/IoT-Project | test sensor.py | test sensor.py | py | 481 | python | en | code | 0 | github-code | 6 |
8097011811 | import pathlib
import PIL.Image
import PIL.ImageChops
import pyscreenshot
from sigsolve import imageutil, geometry
import numpy
def rehydrate(array):
# return PIL.Image.frombytes('RGB', array.shape[:2], array.astype(numpy.uint8).tobytes())
return PIL.Image.fromarray(array, 'RGB')
class Vision:
# How m... | dewiniaid/sigsolve | sigsolve/vision.py | vision.py | py | 3,821 | python | en | code | 3 | github-code | 6 |
31951175852 | #TESTING EXCERCISES
from random import choice
import string
class Boggle:
def __init__(self):
self.words = self.read_dict("words.txt")
def read_dict(self, dict_path):
with open(dict_path) as dict_file:
return [word.strip() for word in dict_file]
def make_board(self):
... | ortolanotyler/flaskproblemsets | 24.5/boggle.py | boggle.py | py | 1,651 | python | en | code | 0 | github-code | 6 |
21355088375 | class Solution:
def networkDelayTime(self, times, n: int, k: int) -> int:
graph = dict()
for i in range(1, n+1):
graph[i] = dict()
for edge in times:
graph[edge[0]][edge[1]] = edge[2]
all_node = {i for i in range(1, n+1)}
t_node = {k}
... | Alex-Beng/ojs | FuckLeetcode/743. 网络延迟时间.py | 743. 网络延迟时间.py | py | 1,153 | python | en | code | 0 | github-code | 6 |
12026854258 | import sys
from PyQt4 import QtGui, QtCore
import pyfits
import os
from gui import Ui_mainwindow as MW
from analysis import *
class ModeloTablaEjes(QtCore.QAbstractListModel):
def __init__(self, ejes = [], parent = None):
QtCore.QAbstractListModel.__init__(self,parent)
self._ejes = ejes
def... | ChivoAttic/StructureDetection | Gui/app.py | app.py | py | 2,574 | python | en | code | 2 | github-code | 6 |
14594653005 | import tensorflow as tf
import pathlib
import os
import cv2
import numpy as np
import tqdm
import argparse
class TFRecordsSeg:
def __init__(self,
image_dir="/datasets/custom/cityscapes",
label_dir="/datasets/custom/cityscapes",
tfrecord_path="data.tfrecords",
... | AhmedBadar512/Badr_AI_Repo | utils/create_seg_tfrecords.py | create_seg_tfrecords.py | py | 6,714 | python | en | code | 2 | github-code | 6 |
26234013938 | #!/usr/bin/python3
"""Starts a basic flask web application"""
from flask import Flask, render_template
from markupsafe import escape
from models import storage
from models.state import State
from models.city import City
app = Flask(__name__)
@app.teardown_appcontext
def teardown(self):
"""procedure to run after... | AndyMSP/holbertonschool-AirBnB_clone_v2 | web_flask/8-cities_by_states.py | 8-cities_by_states.py | py | 1,008 | python | en | code | 0 | github-code | 6 |
35515894022 | import sys
sys.path.append('..')
from common.wrapped_input import wrapped_input
from common.clean_screen import clean_screen
__TERMINATE_MARKS__ = ['***', '****']
class Reader:
def __init__(self, args):
self.loop = True
def run(self, parser):
print("""
_ __ __, ... | ezPsycho/brainSpy-cli | src/readers/interactive.py | interactive.py | py | 881 | python | en | code | 6 | github-code | 6 |
277770918 | import os, sys
import subprocess
# os.environ['DISPLAY'] = ':99.0'
# os.environ['PYVISTA_OFF_SCREEN'] = 'true'
# os.environ['PYVISTA_USE_IPYVTK'] = 'true'
# bashCommand ="Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & sleep 3"
# process = subprocess.Popen(bashCommand, stdout=subprocess.PIPE, shell=True)
# process.w... | uncbiag/shapmagn | shapmagn/experiments/datasets/lung/lung_data_analysis.py | lung_data_analysis.py | py | 28,299 | python | en | code | 94 | github-code | 6 |
6460552932 | import sys
import click
import logging
from pprint import pprint
from ftmstore import get_dataset
from servicelayer.cache import get_redis, get_fakeredis
from servicelayer.logs import configure_logging
from servicelayer.jobs import Job, Dataset
from servicelayer import settings as sl_settings
from servicelayer.archive.... | alephdata/ingest-file | ingestors/cli.py | cli.py | py | 3,714 | python | en | code | 45 | github-code | 6 |
5119440044 | from netaddr import IPNetwork, IPAddress
import logging
from pymongo import MongoClient
logger = logging.getLogger( "ucn_logger" )
class VPNResolve(object):
def __init__( self, cidr, dbcfg):
self.logscollection = dbcfg['logscollection']
self.devicecollection = dbcfg['devicecollection']
self.db = dbcfg['db']
... | ucn-eu/ucnviz | vpnresolve.py | vpnresolve.py | py | 1,620 | python | en | code | 0 | github-code | 6 |
39629119175 | import numpy as np
import glob
import os
import pandas as pd
from tqdm import tqdm
import nltk
import string
from nltk.tokenize import word_tokenize
import random
import pickle
from nltk.corpus import stopwords
from autocorrect import Speller
import re
from nltk.corpus import wordnet
from nltk.stem.wordnet import Wor... | kalyankumarp/Abstractive-Text-Summarization-using-Transformers | Models/preprocess.py | preprocess.py | py | 4,310 | python | en | code | 3 | github-code | 6 |
42479631473 | """Unsupervised Model scheleton."""
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from yadlt.core.model import Model
from yadlt.utils import tf_utils
class UnsupervisedModel(Model):
"""Unsupervised Model scheleton class.
The interface of the class is sklearn... | gabrieleangeletti/Deep-Learning-TensorFlow | yadlt/core/unsupervised_model.py | unsupervised_model.py | py | 4,251 | python | en | code | 965 | github-code | 6 |
11545903852 |
import modules.processing_turn as m_turn
import modules.data_base as m_data
def click_cell(x,y):
# Умова першого рядка таблиці
if y < 100 and y > 0:
# Умова першої комірки по х
if x > -100 and x < 0 and m_data.list_cells[0] == 0:
m_turn.who_turn(-100, 100, 0)
# Умова друг... | BoiarkinaOryna/cross_zero_game | modules/checking_square_coordinates.py | checking_square_coordinates.py | py | 1,655 | python | uk | code | 0 | github-code | 6 |
10701337998 | import tensorflow as tf
import re
import time, datetime
import os
import data_helper
TOWER_NAME = 'tower'
class CNNClassify(object):
"""CNN图像分类
"""
def __init__(self, batch_size, num_classes, num_train_examples, initial_lr=0.1, lr_decay_factor=0.1,
moving_average_decay=0.9999, num_epochs_p... | mikuh/tf_code | cnn/cnn_model.py | cnn_model.py | py | 19,630 | python | en | code | 3 | github-code | 6 |
26807586503 | from src.utils.all_utils import read_yaml, create_directory
import argparse
import os
import shutil
from tqdm import tqdm
import logging
log_string = "[%(asctime)s: %(levelname)s: %(module)s]: %(message)s"
logs_dir = "Logs"
os.makedirs(logs_dir,exist_ok=True)
logging.basicConfig(filename=os.path.join(logs_dir,"Running... | vicharapubhargav/dvc_tensorflow_demo | src/stage_01_load_save.py | stage_01_load_save.py | py | 1,595 | python | en | code | 0 | github-code | 6 |
715415024 | import pandas as pd
import pickle
def buildDataSet():
#Import Ingredients DF
print('Loaded Products...')
ewg_ing_df = pd.read_json('ingredients_products_keys_fixed/ewg_ingredients.json', orient = 'index')
#Build mapping between Ingredient ID and ingredient Name
ing_map = {}
for i in range(len(ewg_in... | SombiriX/w210_capstone | buildModel.py | buildModel.py | py | 8,443 | python | en | code | 1 | github-code | 6 |
655729367 | import os
from glob import glob
import torch_em
from . import util
URL = "https://zenodo.org/record/6546550/files/MouseEmbryos.zip?download=1"
CHECKSUM = "bf24df25e5f919489ce9e674876ff27e06af84445c48cf2900f1ab590a042622"
def _require_embryo_data(path, download):
if os.path.exists(path):
return
os.ma... | constantinpape/torch-em | torch_em/data/datasets/mouse_embryo.py | mouse_embryo.py | py | 2,459 | python | en | code | 42 | github-code | 6 |
72699334907 | import pandas as pd
from sklearn.model_selection import train_test_split
from transformers import BertTokenizer, BertModel, AutoTokenizer, AutoModelForMaskedLM
from torch import nn
import numpy as np
from sklearn.model_selection import train_test_split, KFold, StratifiedKFold
from torch.optim import Adam
from tqdm impo... | zzhaire/dig-dig-books | code/train.py | train.py | py | 7,354 | python | en | code | 1 | github-code | 6 |
36151078302 | import sqlite3 as lite
import sys
from bs4 import BeautifulSoup
import requests
import re
def site_parsing():
max_page = 10
pages = []
id_n = 0
id_n_price = 0
for x in range(1, max_page + 1):
pages.append(requests.get('https://moto.drom.ru/sale/+/Harley-Davidson+Softail/'))
for n in... | TatyanaKuleshova/lesson19-project- | db.py | db.py | py | 1,878 | python | en | code | 0 | github-code | 6 |
21545803934 | # num = 100
#
# while num > 0:
# print(num)
# num = num + 1
# num = 1
# while num <= 100:
# if num % 2 == 0:
# print(num)
# num += 1
#
# num = 1
# son = 0
# while num <= 100:
# if num % 4 == 0:
# son += 1
# num += 1
#
# print(son)
import random
num = 1
nums = []
while num <= ... | Sanjarbek-AI/Python-688 | Lesson-10/dars.py | dars.py | py | 462 | python | en | code | 0 | github-code | 6 |
23948038488 | import torch.nn as nn
import torch_geometric.nn as pyg_nn
class iVGAE_Encoder(nn.Module):
def __init__(self, in_channels, hidden_channels, out_channels):
super().__init__()
self.conv0 = pyg_nn.GCNConv(in_channels, hidden_channels)
self.conv1 = pyg_nn.GCNConv(hidden_channels, hidden_channels... | DavidCarlyn/iVGAE | models.py | models.py | py | 1,705 | python | en | code | 0 | github-code | 6 |
25147617203 | import errno
import logging as _logging
import socket
import socketserver
import threading
import time
from napalm import utils
# Log
logging = _logging.getLogger("SERVER")
# Temp
# utils.default_logging_setup()
try:
from twisted.internet import reactor
from twisted.internet.protocol import connectionDone, P... | markelov-alex/py-sockets | napalm/socket/server.py | server.py | py | 18,945 | python | en | code | 0 | github-code | 6 |
17283528585 | from solver import Solver
from config import Config
if __name__ == '__main__':
cfg = Config()
cfg.data_dir = "/data/face/parsing/dataset/ibugmask_release"
cfg.model_args.backbone = "STDCNet1446"
cfg.model_args.pretrain_model = "snapshot/STDCNet1446_76.47.tar"
solver = Solver(cfg)
solver.sample... | killf/U2Net4FaceParsing | test.py | test.py | py | 409 | python | en | code | 0 | github-code | 6 |
39046925212 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 11 10:48:58 2018
@author: Diogo
"""
from SQL_obj_new.DB_interaction_DDI_sql_new import _DB_interaction_DDI_SQL
class DB_interaction_DDI(object):
"""
This class treat the source that give the information about the DDI object has it exists in DB_interaction_DDI ta... | diogo1790/inphinity | objects_new/DB_interaction_DDI_new.py | DB_interaction_DDI_new.py | py | 2,715 | python | en | code | 0 | github-code | 6 |
33155203825 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-from telegram.ext import Updater, CommandHandler
from telegram.ext import Updater, CommandHandler
updater = Updater('TOKEN')
def start_method(bot, update):
bot.sendMessage(update.message.chat_id, "سلام")
start_command = CommandHandler('start', start_method)
updater.di... | rasoolhp/free-telegram-bot | bot.py | bot.py | py | 412 | python | en | code | 5 | github-code | 6 |
17913448581 | """Made email unique
Revision ID: ff6f0a832e3a
Revises: 876813ef988d
Create Date: 2022-08-09 16:32:43.590993
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'ff6f0a832e3a'
down_revision = '876813ef988d'
branch_labels = None
depends_on = None
def upgrade() -> ... | djangbahevans/wallet-clone | backend/alembic/versions/ff6f0a832e3a_made_email_unique.py | ff6f0a832e3a_made_email_unique.py | py | 667 | python | en | code | 0 | github-code | 6 |
3148189147 | # devuelve un string donde los caracteres consecutivos de S no se repitan más que R veces
def sin_repetidos(str,number):
cantidad = 0
final = ""
anterior = ""
for caracter in str:
cantidad = cantidad+1
if(caracter != anterior):
cantidad=1
anterior=caracter
... | jazz-bee/sin_repetidos | ejercicio.py | ejercicio.py | py | 403 | python | es | code | 0 | github-code | 6 |
7002507231 | import json
from .db_utils import conn as db_conn
from enum import Enum
class NotificationType(Enum):
questionEndorse = 'question_endorsed'
answerEndorse = 'answer_endorsed'
answerUser = 'answer_user'
answerSaved = 'answer_saved'
NOTIFICATION_TEXT_BY_TYPE = {
NotificationType.questionEndorse: "end... | minupalaniappan/gradfire | daviscoursesearch/flaskapp/utils/notif_utils.py | notif_utils.py | py | 1,239 | python | en | code | 12 | github-code | 6 |
35757262298 | from clases import Automovil
# Obtener datos, mostrando los textos del ejemplo
def obtener_datos():
msg = [
'Inserte la marca del automóvil: ',
'Inserte el modelo: ',
'Inserte el número de ruedas: ',
'Inserte la velocidad en km/h: ',
'Inserte e... | tiango-git/full-stack-mod4-eval | parte1/main.py | main.py | py | 1,783 | python | es | code | 0 | github-code | 6 |
32174246789 | from android.droidagent import DroidAdapter, DroidElement
from rpa import InputMethod
import time
'''
A sample can open contact book and search the phone number by specific name
'''
agent = DroidAdapter()
DroidElement.setAgent(agent)
person = 'Bart'
DroidElement().start('contacts')
time.sleep(1)
DroidElement('txt_con... | bartmao/pyRPA | samples/sample-andriod.py | sample-andriod.py | py | 524 | python | en | code | 20 | github-code | 6 |
37682586689 | """
Challenge 18: Print the first 100 prime numbers
"""
import math
def isPrime(n) -> bool:
if n < 2:
return False
if n == 2:
return True
maxDiv = math.sqrt(n)
i = 2
while i <= maxDiv:
if n % i == 0:
return False
i += 1
return True
def printPrime(n... | mofirojean/50-Coding-Challenge | 50 Coding Challenge Part I/Python/Challenge18.py | Challenge18.py | py | 562 | python | en | code | 2 | github-code | 6 |
32672071641 | """Search: 'python filter one list based on another' to solve"""
import string
import unittest
if not hasattr(unittest.TestCase, 'assertCountEqual'):
unittest.TestCase.assertCountEqual = unittest.TestCase.assertItemsEqual #kinda like method_override in npm
def test_blah():
txt = ['I', 'like', 'to', 'eat', 'un... | ckim42/Core-Data-Structures | Lessons/source/redact_problem.py | redact_problem.py | py | 1,547 | python | en | code | 0 | github-code | 6 |
71270407548 | """
This question is asked by Apple. Given two binary strings
(strings containing only 1s and 0s) return their sum (also as a binary string).
Note: neither binary string will contain leading 0s unless the string itself is 0
Ex: Given the following binary strings...
"100" + "1", return "101"
"11" + "1", return "100"
... | lucasbivar/coding-interviews | the-daily-byte/week_01/day_05_add_binary.py | day_05_add_binary.py | py | 1,314 | python | en | code | 0 | github-code | 6 |
45641177766 | import streamlit as st
import pandas as pd
import numpy as np
import umap
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from scipy.cluster.hierarchy import dendrogram, linkage, fcluster
from sklearn.decomposition import PCA
import webbrowser
# Set width mode to wide to display plots better
st.se... | furmanlukasz/clusteringSchizphrenia | app.py | app.py | py | 9,731 | python | en | code | 0 | github-code | 6 |
25570985502 | from View.View import *
from Calculator.Types.Rational import Rational
from Calculator.Types.Complex import Complex
def Start():
while True:
type_choice = input(f"{choice_type_values} > ")
if type_choice == "1":
num1 = Rational("Первое число")
num2 = Rational("Вто... | kdmitry0688/JAVA_OOP | HW7/Control.py | Control.py | py | 1,114 | python | en | code | 0 | github-code | 6 |
12731744615 | #!/usr/bin/env python3
# create a GUI in Python
from tkinter import *
'''class App(tk.Frame):
def __init__(self,master=None):
super().__init__(master)
self.master=master
self.pack()
self.create_widgets()
def create_widgets(self):
'''
#create root window
root =Tk()
#d... | ndlopez/learn_python | learn_tk/tk_gui.py | tk_gui.py | py | 1,832 | python | en | code | 0 | github-code | 6 |
27535780328 | import time
from functools import wraps
from typing import Dict
import requests
from constants import GITHUB_ROOT, RENDER_ROOT
from logging_config import logger
from render_api.utils import get_headers, get_github_status
session = requests.Session()
# Decorator for logging and error handling
def log_and_handle_err... | Fyleek/render-api | render_api/services/deployment_status_service.py | deployment_status_service.py | py | 4,593 | python | en | code | 0 | github-code | 6 |
73574084347 | import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "Deuces Poker Client",
version = "1.0",
author = "Daniel Fonseca Yarochewsky",
description = ("A client to simulate a Texa Holdem Poker Table"),
license = "F... | yarochewsky/poker-client | setup.py | setup.py | py | 409 | python | en | code | 1 | github-code | 6 |
23609310998 | import selenium
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from bs4 import BeautifulSoup
import pymysql
from db_setting import db
# 페이지 로딩을 기다리는데 사용할 time 모듈 import
impo... | Ticket-Cinema/real-time-crawling | first_chart_crawling/actor_crawling.py | actor_crawling.py | py | 3,333 | python | en | code | 0 | github-code | 6 |
29818611165 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : get_content_data.py
# @Description: 获取去标签后的文本数据
# @Time : 2020-5-30 上午 11:09
# @Author : Hou
import os
import pandas as pd
import pymysql.cursors
def get_id_list():
original_data = pd.read_excel(os.path.join(os.path.abspath('../..'), 'data'... | Kidron-Hou/category_division | src/data/get_content_data.py | get_content_data.py | py | 1,684 | python | en | code | 0 | github-code | 6 |
3929047732 | from .wav import write_sine_wave_wav_file
def test_sine():
import io
import time
buffer_size = io.DEFAULT_BUFFER_SIZE
filename = "test-5min-512hz-sr48khz-s24le-pcmdatagen.wav"
frequency = 512
sample_rate = 48000
duration = 5 * 60 * sample_rate # 5 minutes
bit_depth = 24
start_ti... | louie-github/morsel | morsel/test_sine.py | test_sine.py | py | 772 | python | en | code | 0 | github-code | 6 |
14489406692 | #1)
import numpy as np
def polyfit_file(file, d):
data = np.loadtxt(file, float)
x = data[:,0]
y = data[:,1]
return np.polyfit(x, y, d)
#2)
import numpy as np
import random as rd
def flip_coin(N):
h=0.0
t=0.0
while h+t<N:
x=rd.randint(1,2)
if x==1:
h+=1
e... | cameronfantham/PX150-Physics-Programming-Workshop | Task 4.py | Task 4.py | py | 1,142 | python | en | code | 0 | github-code | 6 |
7784070706 | """MYAPP Core application logic."""
from json import (
JSONDecoder,
JSONEncoder,
loads as _json_loads,
)
from logging import getLogger
from pathlib import PosixPath
from http import HTTPStatus
from flask import Blueprint, current_app, request, Response
from flask.views import MethodView
from webargs.flaskp... | jjj4x/flask_api_example | src/myapp/core.py | core.py | py | 7,547 | python | en | code | 0 | github-code | 6 |
35614869771 | """
This will fetch database data from database
"""
from typing import List
from copy import deepcopy
from codegen.table.python_free_connex_table import PythonFreeConnexTable
from codegen.database import DatabaseDriver
from os import path
class DataFetcher:
def __init__(self, db_driver: DatabaseDriver):
"... | secyan/secyan_gen | codegen/utils/DataFetcher.py | DataFetcher.py | py | 1,945 | python | en | code | 2 | github-code | 6 |
29446328549 | # -*- coding: utf-8 -*-
import sys
import cv2
import mediapipe as mp
import re
import time
import threading
from PySide2 import QtCore, QtGui, QtWidgets
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
from selenium import webdriver
from lib.handsign.gesture import define_gest... | cheeseBG/EmergencyResponseSystem | main.py | main.py | py | 17,061 | python | en | code | 1 | github-code | 6 |
39635306222 | from datetime import datetime
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.template import loader
from django.urls import reverse
from .models import BusinessIdea
# Create your views here.
def list(request):
ideas_list = BusinessIdea.objects.... | Gael-Bernard/business_ideas_upm | business_ideas_upm/ideas/views.py | views.py | py | 1,571 | python | en | code | 0 | github-code | 6 |
38093763953 | from book import Book
class Library:
def __init__(self, books_list, readers_list):
self.books_list = books_list
self.readers_list = readers_list
def add_book_to_library(self):
book_id, book_name, book_author, book_date = input("Please enter book id, title, author name, year of edition... | alisa-moto/python-adnanced | HW_02/library.py | library.py | py | 4,100 | python | en | code | 0 | github-code | 6 |
33937872661 | """
Returns a dictionary of the keyboard
mapped to its ord() value.
string DATA
ascii_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
digits = '0123456789'
hexdigits = '0123456789abcdefABCDEF'
letters = 'abcdefghijklmnopqrstuvwxyzABCD... | cameronbriar/curses | examples/key.py | key.py | py | 934 | python | en | code | 0 | github-code | 6 |
71066840189 | import numpy as np
from examples.example_imports import *
scene = EagerModeScene()
scene.save_default_config()
number = DecimalNumber(0).scale(2)
scene.add(number)
scene.wait()
print(np.linspace(0, 10, 4))
scene.play(ChangingDecimal(number, lambda x: x*10), run_time=4)
scene.hold_on()
| beidongjiedeguang/manim-express | examples/animate/demo_numbers.py | demo_numbers.py | py | 291 | python | en | code | 13 | github-code | 6 |
43555685205 |
class Robot:
"""
+Y
90
N
^
-X 180 W < * > E 0 +X
v
S
270
-Y
"""
# dirname => (dx, dy)
directions_to_deltas = {
'E': (1, 0),
'N': (0, 1),
'W': (-1, 0),
'S': (0, -1)... | ruke47/advent-of-code-2020 | 12/2.py | 2.py | py | 2,071 | python | en | code | 0 | github-code | 6 |
11403898752 | from torch.utils.data import Dataset
from transformers import Trainer
from transformers import TrainingArguments
from trainer.callbacks.printer import PrinterCallback
from data_manager.batch_sampler import Batch_Sampler
from model.model_parameters import Model_Parameters
from trainer.tne_config import TNE_Config
import... | ranraboh/TNE_TASK | trainer/tne_trainer.py | tne_trainer.py | py | 4,430 | python | en | code | 0 | github-code | 6 |
43431205524 | import datetime
import uuid
import logging
from concurrent.futures import ThreadPoolExecutor
from functools import partial
import pandas as pd
import sys
import pprint
import traceback
from core.scraper.scraper import Scraper
from core.db.db_helper import DbHelper
from common.constants import THREAD_NO, LARGE_CHUNK, B... | CMUChimpsLab/playstore-scraper | core/scraper/updater.py | updater.py | py | 5,745 | python | en | code | 1 | github-code | 6 |
2088894049 | ## \example pmi/symmetry.py
"""Clone molecules and use a symmetry constraint
"""
import IMP
import IMP.atom
import IMP.rmf
import IMP.pmi
import IMP.pmi.topology
import IMP.pmi.dof
import IMP.pmi.macros
import IMP.pmi.restraints.stereochemistry
import math
import sys
IMP.setup_from_argv(sys.argv, "Symmetry constraint... | salilab/pmi | examples/symmetry.py | symmetry.py | py | 2,257 | python | en | code | 12 | github-code | 6 |
16838024238 | from typing import List
from csvcubed.models.cube import (
Cube,
QbDimension,
ExistingQbDimension,
QbColumn,
CsvColumnUriTemplateMissingError,
QbAttributeLiteral,
CsvColumnLiteralWithUriTemplate,
QbAttribute,
NoDimensionsDefinedError,
)
from csvcubed.models.validationerror import Va... | GDonRanasinghe/csvcubed-models-test-5 | csvcubed/csvcubed/utils/qb/validation/cube.py | cube.py | py | 2,817 | python | en | code | 0 | github-code | 6 |
26304099314 | from django.conf import settings
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import ObjectDoesNotExist
from django.shortcuts import get_object_or_404, redirect, render, reverse
from django.utils import timezone
from django.views import generi... | ifty123/ecomm_fix | ecomm/toko/views.py | views.py | py | 14,172 | python | en | code | 0 | github-code | 6 |
71087029308 | """Simple wrapper for app"""
import json
from rich.console import Console
from typing import List
import requests
from src.utils import Oracles
class FlaskAppClient:
ERROR_KEY = "error"
TRACEBACK_KEY = "traceback"
def __init__(self, base_url="http://127.0.0.1:5000"):
self.base_url = base_url
... | molecule-one/mlinpl-23-workshops | src/server_wrapper.py | server_wrapper.py | py | 2,462 | python | en | code | 1 | github-code | 6 |
10906525746 | import argparse
import time
import pika
from pika.exceptions import (
ChannelClosed,
ConnectionClosed,
AMQPConnectionError,
AMQPHeartbeatTimeout,
)
class Logger:
LOG_EXCHANGE = "logs"
LOG_EXCHANGE_TYPE = "topic"
def __init__(self, url, routing_keys):
connection = pika.BlockingCo... | allo-media/eventail | scripts/logger.py | logger.py | py | 2,599 | python | en | code | 2 | github-code | 6 |
29209651660 | import os
from pathlib import Path
def correct_content(req):
with open(req, "rb") as fp:
content = fp.read()
try:
if b"\x00" in content:
raise ValueError()
content = content.decode("utf-8")
except (UnicodeDecodeError, ValueError):
content = (
content... | smythi93/Tests4Py | requirements.py | requirements.py | py | 2,015 | python | en | code | 8 | github-code | 6 |
29465067093 | # Return the number (count) of vowels in the given string.
# We will consider a, e, i, o, u as vowels for this Kata (but not y).
# The input string will only consist of lower case letters and/or spaces.
def get_count(sentence):
# create a count variable for the vowels in the sentence
num_vowels = 0
... | tuyojr/code_wars-hacker_rank-leetcode | code_wars/get_count.py | get_count.py | py | 1,679 | python | en | code | 0 | github-code | 6 |
21247797774 | import os
import pandas as pd
from sklearn.model_selection import train_test_split
import click
FILENAME_DATA = "data.csv"
FILENAME_TARGET = "target.csv"
FILENAME_TRAIN_X = "X_train.csv"
FILENAME_TRAIN_Y = "y_train.csv"
FILENAME_TEST_X = "X_test.csv"
FILENAME_TEST_Y = "y_test.csv"
@click.command("split_data")
@cli... | made-mlops-2022/alexey_sklyannyy | airflow_ml_dags/images/airflow-split/split_data.py | split_data.py | py | 1,308 | python | en | code | 0 | github-code | 6 |
13092352572 | # encoding = utf-8
class Trie(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = {}
self.end = -1
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: void
"""
... | somenzz/geekbang | algorthms/trie.py | trie.py | py | 4,115 | python | en | code | 5 | github-code | 6 |
23800674981 |
from pynput.keyboard import Key,Listener
keys=[]
def on_press(key):
try:
key=str(key)
if(key=='Key.enter'):
key='\n'
elif(key=='Key.space'):
key=' '
elif(key=='Key.alt'):
key=' alt '
elif(key=='Key.ctrl'):
key=' ctrl '
... | prajwalcbk/tools | keylogger/3.py | 3.py | py | 791 | python | en | code | 0 | github-code | 6 |
30247773703 | import random
# Split string method
names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
number_of_names = len(names)
random_name = random.randint(0, number_of_names - 1)
buyer = name... | ramirors1/Random-name | main.py | main.py | py | 470 | python | en | code | 0 | github-code | 6 |
18658019054 | '''
Created on Dec 13, 2022
@author: balut
'''
from erorrs.Errors import RepositoryException
from domain.entities import Bicicleta
class InFileRepositoryBiciclete(object):
'''
classdocs
'''
def __init__(self, fileName):
'''
Constructor
'''
self.__produse = []
... | Baluta-Lucian/FP | Projects/MagazinBicicleteSimulare/repository/InFileRepositoryBiciclete.py | InFileRepositoryBiciclete.py | py | 2,069 | python | en | code | 0 | github-code | 6 |
71271494589 | dna = input()
new = ""
for i in dna:
if i not in 'ATGC':
new = "Invalid Input"
break
if i == 'A':
new += 'U'
elif i == 'C':
new += 'G'
elif i == 'T':
new += 'A'
else:
new += 'C'
print(new)
#or you can use this
b=input()
a="GCTA";c="CGAU"
try:print('... | anubhavsrivastava10/Leetcode-HackerEarth-Solution | HackerEarth/Jadoo and DNA Transcription.py | Jadoo and DNA Transcription.py | py | 385 | python | en | code | 9 | github-code | 6 |
36417191928 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
l = head
r = head
while r != None and... | eyosiasbitsu/Competitive-programming-A2SV | Project Phase Camp/0876-middle-of-the-linked-list/0876-middle-of-the-linked-list.py | 0876-middle-of-the-linked-list.py | py | 443 | python | en | code | 3 | github-code | 6 |
33869960923 | import fasttext
import pickle
model = fasttext.load_model('/data/disk1/private/yx/model200v2_8.bin', encoding='utf-8')
(wordnum,vec_size) = (len(model.words),model.dim)
word2id = {}
vecList = []
for idx,word in enumerate(model.words):
word2id[word] = idx
vecList.append(model[word])
with open("/data/disk1/privat... | xcjthu/TopTextClassification | utils/powerlawtools/fastmodeltrans.py | fastmodeltrans.py | py | 533 | python | en | code | 3 | github-code | 6 |
24742947009 | from asyncirc import irc
import asyncirc.plugins.sasl
import asyncio, configparser, time, sys
config = configparser.ConfigParser(interpolation=None)
config.read('config.ini')
network = config["DEFAULT"]["network"]
server = config[network]["server"]
port = config[network]["port"]
nick = config[network]['nick']
passwor... | kyrias/reclaimer | reclaimer.py | reclaimer.py | py | 2,611 | python | en | code | 2 | github-code | 6 |
32161722151 | import sys
from pathlib import Path
from colorama import Fore
sys.path.append(str(Path(__file__).parent.parent))
from g4f import BaseProvider, models, Provider
logging = False
class Styles:
ENDC = "\033[0m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
def main():
providers = get_providers()
failed_pr... | dovgan-developer/discord-bot-g4f | testing/test_providers.py | test_providers.py | py | 2,239 | python | en | code | 1 | github-code | 6 |
14069562246 | ''''
Microbial growth model for A. Niger
including inhibition dynamics based on Haldane's equation
'''
##############################################################################
mic_name = 'A. niger'
print( '\n'*2, 'Summary of params used for species ', mic_name)
# Imports
from inhibition import lo... | TheoBatik/microbial_models | 5b_A_niger.py | 5b_A_niger.py | py | 9,887 | python | en | code | 0 | github-code | 6 |
14335019516 | import numpy as np
import matplotlib.pyplot as plt
from mpi4py import MPI
from process_coordination import width_height, bool_boundaries, number_of_blocks
from streaming_functions import streaming, recalculate_functions
from plotting_functions import plot_velocity, plot_velocity_slice
# Initialize parallelization
com... | Dunitrie/HPC | main.py | main.py | py | 3,550 | python | en | code | 1 | github-code | 6 |
27554887332 | # Given an array of integers nums and an integer target, return indices of the two numbers such
# that they add up to target. You may assume that each input would have exactly one solution, and you
# may not use the same element twice. You can return the answer in any order.
# Example1
# Input: nums = [2, 7, 11, 15], ... | emurali08/Python_Revised_notes | Interview_tests/Interview_tests_2022/find_arr_items_to_target_sum.py | find_arr_items_to_target_sum.py | py | 868 | python | en | code | null | github-code | 6 |
21998501456 | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
ans = 0
i = 0
n = len(s)
sub_str = dict()
for j in range(n):
if s[j] in sub_str:
i = max(i, sub_str[s[j]])
ans = max(ans, j - i + 1)
sub_str[s[j]] = j + 1
... | hangwudy/leetcode | 1-99/3_最长无重复字串.py | 3_最长无重复字串.py | py | 402 | python | en | code | 0 | github-code | 6 |
11301162272 | from rest_framework.response import Response
from rest_framework.decorators import api_view
from datetime import datetime
from coupon.models import Coupon
from coupon.serializers import CouponSerializer
@api_view(['GET'])
def get_coupons(request):
user_id = request.GET.get('user_id')
expired = request.GET.get... | jpswing/assmovie | coupon/views.py | views.py | py | 1,042 | python | en | code | 0 | github-code | 6 |
6600903749 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from datetime import date
import sys
if __name__ == '__main__':
# список работников
workers = []
# организация бесконечного цикла запроса команд
while True:
# запросить команду из терминала
command = input(">>>").lower()
# выполн... | Valentina1502/LABA_1 | zd4.py | zd4.py | py | 3,987 | python | ru | code | 0 | github-code | 6 |
36148958510 | class UTE:
"""
Modelo de uma usina termelétrica em um estudo de
planejamento energético.
"""
def __init__(self,
ute_id: int,
nome: str,
capacidade: float,
custo: float):
self.id = ute_id
self.nome = nome
self... | rjmalves/lpoe | modelos/ute.py | ute.py | py | 950 | python | pt | code | 0 | github-code | 6 |
6032334630 | from AutoTensor.q_learning.config_scheme import *
class ConfigBuilder:
def __build_item(self, node, name):
if isinstance(node, ValueNode):
return node.default
elif isinstance(node, OptionsNode):
return node.options[node.default]
elif isinstance(node, ClassN... | epeters3/AutoTensor | AutoTensor/q_learning/config_builder.py | config_builder.py | py | 1,086 | python | en | code | 1 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.