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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
19573688332 | import os
import pathlib
import struct
import click
import tqdm
from collections import defaultdict
class ResException(Exception):
pass
class Res(object):
def __init__(self, file):
# Every resource file begins with the string 'ITERES'
self._file = file
self._file.seek(0, os.SEEK_EN... | ali1234/iteres | iteres/res.py | res.py | py | 2,250 | python | en | code | 1 | github-code | 1 |
28437959160 | import os
import sys
import time
import json
import asyncio
import logging
import re
from opencensus.ext.azure.log_exporter import AzureLogHandler
from azure.iot.device import Message
from azure.iot.device.aio import IoTHubModuleClient
from datetime import datetime, timedelta
TWIN_CALLBACKS = 0
OBJECT_TAGS = ['truck'... | liupeirong/MLOpsManufacturing | samples/edge-object-detection/edge/modules/objectDetectionBusinessLogic/main.py | main.py | py | 9,013 | python | en | code | 21 | github-code | 1 |
11216264433 | import os
import numpy as np
import pandas as pd
import time
def measure_elapsed_time(function):
def wrapper(*args, **kwargs):
start_time = time.time()
result = function(*args, **kwargs)
end_time = time.time()
elapsed_time = end_time - start_time
print(f"Elapsed time: {elaps... | kayesokua/gestures | src/data/augmentation.py | augmentation.py | py | 3,145 | python | en | code | 0 | github-code | 1 |
5876622591 | import numpy as np
import math
import random
import sys
import itertools
from pathlib import Path
home = str(Path.home())
import sys
rankability_path = "%s/rankability_toolbox_dev"%home
if rankability_path not in sys.path:
sys.path.insert(0,rankability_path)
import pyrankability
from pyrankability.rank import solve... | IGARDS/sensitivity_study | src/sensitivity_tests.py | sensitivity_tests.py | py | 28,780 | python | en | code | 2 | github-code | 1 |
24476355814 | while True:
print("Options")
print("1.Addition")
print("2.Subtraction")
print("3.Division")
print("4.Multiply")
commandtxt=input("Choose command: ")
num1=float(input("First Number: "))
num2=float(input("Second Number: "))
if(commandtxt=="Addition"):
rslt=num1+num2
pri... | OrhunGNC/Learning-Python | Improved Calculator/Improved Calculator/Improved Calculator.py | Improved Calculator.py | py | 1,532 | python | en | code | 0 | github-code | 1 |
10186949378 | T = int(input())
for tc in range(1, T+1):
s = input().strip()
dic = {
'p': 'q',
'q': 'p',
'b': 'd',
'd': 'b',
}
result = ''
for i in range(len(s)-1, -1, -1):
result += dic[s[i]]
print('#{} {}'.format(tc, result)) | daeungdaeung/SWEA | D03/10804.py | 10804.py | py | 279 | python | en | code | 0 | github-code | 1 |
31208091569 | import xlrd
import xlwt
from xlutils.copy import copy
import os
def get_file_and_rewrite(startpath):
for root, dirs, files in os.walk(startpath):
for dir in dirs:
for root, dirs, files in os.walk(startpath + "\\" + dir):
for file in files:
file_loc = root ... | comewithme1200/pythonMaibeo | test.py | test.py | py | 2,323 | python | en | code | 0 | github-code | 1 |
12999156252 |
class zhang(object):
pass
s = zhang()
s.name = 'zhang'
print(s.name)
# 可以给实例绑定一个方法 MethodType 这个方法可以给类或者实例绑定一个方法
def set_age(self, age):
self.age = age
from types import MethodType
s.set_age = MethodType(set_age, s)
s.set_age(24)
# __slots__ 使用方法
# print(dir(zhang)) 查看了一下 里面并没有包括 __slots__ .. 不知道为什么
# 限制... | qiang437587687/pythonBrother | Borther/FirstLearn/ObjectOrientedProgramming.py | ObjectOrientedProgramming.py | py | 5,321 | python | zh | code | 1 | github-code | 1 |
33710378084 | import base64
import os
def img_to_base64(image_bytes):
"""
:param image_bytes: 文件路径
:return: base64字符串
"""
with open(image_bytes, "rb") as fb:
img = fb.read()
base64_bytes = base64.b64encode(img)
img_suffix = os.path.splitext(image_bytes)[1].replace('.', '')
if im... | GavinHaydy/ruffian_test | ruffianTest/common/picture/picture_to_base64.py | picture_to_base64.py | py | 1,007 | python | en | code | 0 | github-code | 1 |
40419888974 | from pathlib import Path
import re
from collections import deque
data_folder = Path(".").resolve()
reg = re.compile(r"(\d+) <-> (.+)")
def find_groups(comms):
groups = []
for i in range(len(comms)):
in_groups = []
for j in range(len(groups)):
for k in range(len(comms[i])):
... | eirikhoe/advent-of-code | 2017/12/sol.py | sol.py | py | 1,549 | python | en | code | 0 | github-code | 1 |
26426506277 | from collections import defaultdict,deque
def convert(n,k):
ret = ''
while n:
ret += str(n%k)
n//=k
return ret[::-1]
def isPrime(num):
if num==2 or num==3: return True
if num%2 == 0 or num%3==0 or num<2 : return False
for i in range(3, int(num**.5)+1, 2):
if num%i == 0: ... | dohui-son/Python-Algorithms | programmers/x_k진수에서소수개수구하기.py | x_k진수에서소수개수구하기.py | py | 517 | python | en | code | 0 | github-code | 1 |
73938022115 | '''
Created on 25 abr. 2020
@author: jesus.fernandez
'''
import urllib3
import pandas as pd
class WorldCovidDataCrawler(object):
'''
classdocs
'''
#Declaración de constantes
URL_BASE = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_... | jfernandezrodriguez01234/TFM_jfernandezrodriguez01234 | src/crawlers/medical/WorldCovidDataCrawler.py | WorldCovidDataCrawler.py | py | 3,058 | python | pt | code | 0 | github-code | 1 |
12505645993 | def min_num():
lis=[2,3,4,5]
min = lis[0]
for x in lis:
if x < min:
min = x
print("minimum number in list",min)
if __name__ == '__main__':
min_num() | kuldeepsinghn/python- | minimum_element.py | minimum_element.py | py | 204 | python | en | code | 0 | github-code | 1 |
41927760490 | import pymem
import pymem.process
import psutil
import os
import time
class PymongUS:
def __init__(self):
self.dwspeed = 0x00DA3C30
self.imposter =0x00DA5A84
self.pm = pymem.Pymem('Among Us.exe')
def makemeImposter(self):
try:
client = pymem.process.module_from_name(... | xsphereboi/Pymong-US | app.py | app.py | py | 3,463 | python | en | code | 0 | github-code | 1 |
73111772195 | # -*- coding: utf-8 -*-
# __author__ = 'XingHuan'
# 4/15/2018
import logging
import inspect
import functools
import time
log_level = logging.DEBUG
log_formats = [
'%(levelname)s:%(name)s: %(asctime)s %(pathname)s[line:%(lineno)d] %(funcName)s %(message)s',
'%(levelname)s:%(name)s: %(asctime)s %(message)s',
]
... | ZackBinHill/Sins | sins/utils/log.py | log.py | py | 1,436 | python | en | code | 0 | github-code | 1 |
36537091858 | import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
from keras.models import Sequential
from keras.layers import Dense
X = np.array([[185.32, 12.69],
[259.92, 11.87],
[231.01, 14.41],
[175.37, 11.72],
[187.12, 14.13]])
Y = np.array([[1.],
[0.],... | dunkerbunker/Python-ML-AI | manual models/tensorflowTest.py | tensorflowTest.py | py | 2,413 | python | en | code | 0 | github-code | 1 |
19585411357 |
# https://leetcode.com/problems/plus-one/
# 66. Plus One
# You are given a large integer represented as an integer array digits,
# where each digits[i] is the ith digit of the integer.
# The digits are ordered from most significant to least significant in left-to-right order.
# The large integer does not contain any l... | kj-grogu/COEN-279-DAA | src/PlusOne.py | PlusOne.py | py | 1,741 | python | en | code | 0 | github-code | 1 |
40664894260 | import sys
sys.stdin = open("B3_input.txt")
# def process_solution(a, k, sum):
# global nmin
# if sum > nmin : return
#
# def make_candidates(a, k, input, c):
# in_perm = [0] * NMAX
#
# for i in range(1, k):
# in_perm[a[i]] = 1
#
# ncands = 0
# for i in range(1, input+1):
# if i... | manuck/Algorithm | codexpert(AD)/B3-최소의 합.py | B3-최소의 합.py | py | 2,384 | python | en | code | 0 | github-code | 1 |
23884480580 | import function_rat_num as fr
import sys
def x():
global first_num
first_num = float(input('Введите первое число: ').replace(',', '.'))
return first_num
def y():
global second_num
second_num = float(input('Введите второе число: ').replace(',', '.'))
return second_num
def select_operation():... | Fenixzavad/HomeWorkP10 | function_rat_num.py | function_rat_num.py | py | 2,179 | python | ru | code | 0 | github-code | 1 |
42332194005 | import pandas as pd
import numpy as np
import os
import random
import pywt
import pickle
from tqdm import tqdm
import torch
from random import sample
from dataloaders.utils import Normalizer,components_selection_one_signal,mag_3_signals,PrepareWavelets,FiltersExtention
from sklearn.utils import class_weight
from skimag... | teco-kit/ISWC22-HAR | dataloaders/dataloader_base.py | dataloader_base.py | py | 28,398 | python | en | code | 11 | github-code | 1 |
10693944537 | # iterative
# n = number of nodes
# Time: O(n)
# Space: O(n)
from collections import deque
def tree_includes(root, target):
if not root:
return False
queue = deque([root])
while queue:
current = queue.popleft()
if current.val == target:
return True
if current.left:
queue.append(c... | mjfung1/structy | Python/27tree_includes.py | 27tree_includes.py | py | 679 | python | en | code | 1 | github-code | 1 |
8120556036 | #!/usr/bin/env python
# coding: utf-8
# # FINAL PROJECT
#
# ### Pooja Agrawal
#
#
# In[1]:
get_ipython().run_line_magic('reset', '-f')
# In[2]:
# To supress warnings
import warnings
warnings.filterwarnings("ignore")
# In[4]:
from pandas import ExcelWriter
from pandas import ExcelFile
from pandas import Series
from p... | Poojaagwork/Bankruptcy-Data-Analysis-And-Prediction | Pooja_FINAL PROJECT320.py | Pooja_FINAL PROJECT320.py | py | 41,482 | python | en | code | 0 | github-code | 1 |
32163590327 | import os
import ast
import argparse
import functools
import subprocess
import collections
from .visitor import Visitor
PREAMBLE = r"""
\documentclass[a4paper,oneside,article]{memoir}
\usepackage[T1]{fontenc}
\usepackage[noend]{algorithmic}
\usepackage{algorithm}
\usepackage{amsmath,amssymb}
\begin{document}
""".stri... | Mortal/algorithmicpy | algorithmic/main.py | main.py | py | 2,935 | python | en | code | 0 | github-code | 1 |
39412489351 | from django.contrib import admin
from .models import NewsItem, Comment
class CommentAdmin(admin.ModelAdmin):
list_display = ['name_author', 'news', 'text', 'check_admin', 'show_piece_text']
list_filter = ['name_author']
search_fields = ['name_author']
actions = ['switch_to_status_deleted']
def s... | glebserg/portfolio | Test/DjangoNewsItems/news/app_news/admin.py | admin.py | py | 1,666 | python | en | code | 0 | github-code | 1 |
70749701793 | # replace Channel.save_measurement_locally:
from save_all_s4p.vna_monkeypatch import monkeypatch
monkeypatch()
# imports
from pathlib import Path
from save_all_s4p import get_timestamp
from rohdeschwarz.instruments.vna import Vna
# constants
PORTS = [1, 2, 3, 4]
TEN_SECONDS_MS = 10 * 1000
# data pat... | Terrabits/save_all_s4p | __main__.py | __main__.py | py | 1,454 | python | en | code | 0 | github-code | 1 |
33443196607 |
from os.path import basename, splitext
import tkinter as tk
from tkinter import HORIZONTAL, Scale
class Application(tk.Tk):
name = "Prasátko"
def __init__(self):
super().__init__(className=self.name)
self.title(self.name)
# self.geometry('800x600')
self.bind("<Escape>", self.q... | vac39328/uvod | Prasátko.py | Prasátko.py | py | 3,986 | python | en | code | 0 | github-code | 1 |
26219034741 | import coverage
import test_sut
cov = coverage.Coverage()
cov.set_option("run:branch", True)
cov.start()
test_sut.test_handle_event()
cov.stop()
cov.save()
cov.report(show_missing=True) | mikepatrick/coverage-test | collect_coverage.py | collect_coverage.py | py | 188 | python | en | code | 0 | github-code | 1 |
3839894470 | from django.shortcuts import render
import csv
import random
from .models import Cliente, Producto, Ventas
from django.core.mail import EmailMessage
from barcode.codex import Code128
from barcode.writer import ImageWriter
from reportlab.platypus import (SimpleDocTemplate, Image, Spacer,Table)
from reportlab.lib.pagesiz... | hrdax/Juan_MellaEV4 | JMNJEV4/views.py | views.py | py | 28,128 | python | es | code | 0 | github-code | 1 |
4603867834 | import pygame
import math
car_img = pygame.image.load('pic/car_img.png')
class Window:
def __init__(self, win_w, win_h):
self.win_w = win_w
self.win_h = win_h
self.win = pygame.display.set_mode((win_w, win_h))
self.clock = pygame.time.Clock()
self.speed = 30
def ... | march-o/neat-car-ai | window.py | window.py | py | 3,122 | python | en | code | 0 | github-code | 1 |
4822443874 | import fastr
import argparse
def fastr_apply_network():
network = fastr.create_network(id="applynetwork")
source_t1 = network.create_source('NiftiImageFileCompressed', id='T1')
source_t2 = network.create_source('NiftiImageFileCompressed', id='T2')
source_t1Gd = network.create_source('NiftiImageFileCom... | karinvangarderen/glassimaging | glassimaging/preprocessing/applynetwork.py | applynetwork.py | py | 2,160 | python | en | code | 3 | github-code | 1 |
39894682781 | import numpy as np
class MultinomialNaiveBayes:
__theta_y1: float
__theta_y0: float
__theta_j_y1: dict
__theta_j_y0: dict
__vocab: np.ndarray
@staticmethod
def calculate_theta_y1(y: np.ndarray) -> float:
return np.mean(y)
@staticmethod
def calculate_theta_j_y(X_specific_c... | jansowa/ml-numpy-algorithms | multinomial_naive_bayes.py | multinomial_naive_bayes.py | py | 4,077 | python | en | code | 0 | github-code | 1 |
41284570814 | from keras.preprocessing.text import Tokenizer
from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout, Merge, Input, concatenate, Lambda
from keras.layers.embeddings import Embedding
from keras.models import Model
from keras.preprocessing import sequence
from keras.utils import np_utils
from ... | renhaocui/activityExtractor | trainFullModel.py | trainFullModel.py | py | 22,297 | python | en | code | 1 | github-code | 1 |
5118680206 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import logistic
def classifyVector(inX, weights):
"""
分类
"""
prob = logistic.sigmoid(sum(inX * weights))
if prob > 0.5:
return 1.0
else:
return 0.0
def colicTest():
"""
训练和测试模型
"""... | yingzk/MyML | 1-Logistic Regession/horse.py | horse.py | py | 1,724 | python | en | code | 65 | github-code | 1 |
41032471906 | import yaml
from aws_cdk import Aws, CfnOutput, Duration, Size, Stack
from aws_cdk import aws_events as events
from aws_cdk import aws_events_targets as targets
from aws_cdk import aws_iam as iam
from aws_cdk import aws_s3 as s3
from aws_cdk import aws_sns as sns
from constructs import Construct
class ProducerStack(S... | awsdocs/aws-doc-sdk-examples | .tools/test/eventbridge_rule_with_sns_fanout/producer_stack/producer_stack.py | producer_stack.py | py | 4,722 | python | en | code | 8,378 | github-code | 1 |
71413888673 | # @Author : kane.zhu
# @Time : 2022/12/2 16:21
# @Software: PyCharm
# @Description:
from celery.schedules import crontab
beat_schedule = {
'add-every-30-seconds': {
'task': 'celery.reverse_schedule',
'schedule': crontab(minute="*"),
},
}
| canpowerzhu/flask-demo | utils/kane_celery/cele_schedule.py | cele_schedule.py | py | 268 | python | en | code | 1 | github-code | 1 |
36366419603 | users = [
# name is_superuser quota username systems-they-can-access
('alice', True, 10_000, 'alice', ['sierra', 'vulcan', 'quartz']),
('bob', True, 20_000, 'bob0', ['vulcan', 'quartz']),
]
# name, is_superuser, quota, username, systems = users[0]
# print(f'{name} can use {syste... | decarlof/dutc | example_11.py | example_11.py | py | 445 | python | en | code | 0 | github-code | 1 |
29388150642 | #!/usr/bin/python
import random
dayofweek = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
header = "first,last,email,day,08:00:00-10:00:00,10:00:00-12:00:00,12:00:00-14:00:00,14:00:00-16:00:00,16:00:00-18:00:00,18:00:00-20:00:00"
first = ['Travis', 'Mirian', 'Marshall', 'Marcia', 'Denisha'... | myrjone/SMP | SMP/data/tarostering/import/taFiles/taGenerator.py | taGenerator.py | py | 1,892 | python | en | code | 0 | github-code | 1 |
727185089 | import numpy as np
from autoencoder import Autoencoder
from sklearn import datasets
P=Autoencoder(4,2)
X, Y = datasets.make_classification(
n_features=4,
n_classes=4,
n_samples=100,
n_redundant=0,
n_clusters_per_class=1
)
P.Train(X,2000)
| dani2442/DeepLearning | ShallowNN/Autoencoder/autodencoder_test.py | autodencoder_test.py | py | 264 | python | en | code | 2 | github-code | 1 |
7283812606 | import dolfin as df
from coordinate_systems import SphericalCoordinateSystem
N = 100
r_max = 2
mesh = df.IntervalMesh(N, 0, r_max)
V = df.FunctionSpace(mesh, 'P', 2)
r = df.SpatialCoordinate(mesh)
u = df.TrialFunction(V)
v = df.TestFunction(V)
coordinates = SphericalCoordinateSystem(mesh)
spherical_laplace = coo... | wagnandr/immunotherapy-lung-cancer | reduced_models/test_laplace_spherical.py | test_laplace_spherical.py | py | 880 | python | en | code | 0 | github-code | 1 |
23097599098 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('academy', '0005_aluno_pessoa'),
]
operations = [
migrations.CreateModel(
name='Professor',
fields=[
... | rodrigolucianocosta/Relationship- | relationship/academy/migrations/0006_professor.py | 0006_professor.py | py | 818 | python | en | code | 0 | github-code | 1 |
10331518142 | # Escribir un programa que pida al usuario dos números y muestre por pantalla
# su división. Si el divisor es cero el programa debe mostrar un error.
num_1 = input("Escribe un numero: ")
num_2 = input("Escribe otro numero: ")
if num_2 == "0":
print("Error, no se puede dividir entre 0")
else:
print(round(floa... | Isabel-Calcano/Repo-Isabel-Calca-o | Alf Ejercicios/Condicionales 3.py | Condicionales 3.py | py | 351 | python | es | code | 0 | github-code | 1 |
26632544137 | from docx import Document
from docx.shared import Pt
from openpyxl import load_workbook
import os
nome_arquivo = "Alunos.xlsx"
planilhaAlunos = load_workbook(nome_arquivo)
sheet = planilhaAlunos['Nomes']
for L in range(2, len(sheet['A']) + 1):
arquivo = Document('Certificado1.docx')
estilo = arquivo.styles[... | marques-matheus/Python | Word/Gerando_certificado_em_massa.py | Gerando_certificado_em_massa.py | py | 706 | python | pt | code | 0 | github-code | 1 |
32066594400 | from flask import Flask
from twilio.twiml.voice_response import VoiceResponse
app = Flask(__name__)
@app.route("/answer", methods=['GET', 'POST'])
def answer_call():
"""Respond to incoming phone calls with a brief message."""
# Start our TwiML response
resp = VoiceResponse()
# Read a mes... | marzookh/twilio | answer_phone.py | answer_phone.py | py | 562 | python | en | code | 0 | github-code | 1 |
24285392707 | import sys
import logging
sys.path.append('../../../../')
from flask import current_app, request
from flask_restful import Resource, reqparse
from spiders.selenium_spider import bloomberg
parser = reqparse.RequestParser()
parser.add_argument('spider')
parser.add_argument('action')
def test():
print('testing')
... | kingking888/news_plus | web/backend/news/apps/jobs.py | jobs.py | py | 2,136 | python | en | code | 0 | github-code | 1 |
8149836765 | import random
name = input("What is your name? ")
print("Hello", name, "! Time to play Mystery Word")
def run():
with open("words.txt") as f:
word_list = f.read().splitlines()
game_difficulty = None
while True:
try:
game_difficulty = int(input("What difficulty w... | Momentum-Team-8/python-mystery-word-bhall20 | game.py | game.py | py | 2,416 | python | en | code | 0 | github-code | 1 |
18455753919 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 21 13:14:50 2017
@author: B
"""
import sys
sys.path.append('/root/asar2018psc/training/Models/')
import numpy as np
np.random.seed(123)
import argparse
import Models , PageLoadBatches
from keras.callbacks import ModelCheckpoint
from keras import optimizers
i... | beratkurar/asar2018-page-segmentation-competition | training/lightpagetrainf8.py | lightpagetrainf8.py | py | 3,903 | python | en | code | 3 | github-code | 1 |
19646054791 | # Determine the date of the class
def classdate(number):
return (datetime.date.today() + datetime.timedelta(days=(number-datetime.date.today().weekday()))).strftime("%m/%d")
nextmon, nexttue, nextwed, nextthu, nextfri = classdate(7), classdate(8), classdate(9), classdate(10), classdate(11)
# Get coaches for eac... | impatmcb/report-automation | training_resource_management/extravars.py | extravars.py | py | 2,632 | python | en | code | 0 | github-code | 1 |
10959366830 | '''
This module is used to split tags in a HED string .
Created on Nov 15, 2017
@author: Jeremy Cockfield
'''
import copy;
class HedStringDelimiter:
DELIMITER = ',';
DOUBLE_QUOTE_CHARACTER = '"';
OPENING_GROUP_CHARACTER = '(';
CLOSING_GROUP_CHARACTER = ')';
TILDE = '~';
def __init__(self... | VisLab/HEDToolsArchived | python/hedvalidation/hedvalidation/hed_string_delimiter.py | hed_string_delimiter.py | py | 11,103 | python | en | code | 6 | github-code | 1 |
10382864943 | from socket import socket, AF_INET, SOCK_DGRAM
import CommTypes_pb2 as pb
import time
import datetime
import numpy as np
def recvSSLMessage(udp_sock):
msg = pb.protoMotorsDataSSL()
# multiple messages are received and accumulated on buffer during vision processing
# so read until buffer socket ... | jgocm/proto-motors-data-collect | src/runMotorsCollectFromSSLSpeeds.py | runMotorsCollectFromSSLSpeeds.py | py | 3,530 | python | en | code | 0 | github-code | 1 |
125319284 | import constants
import time
import datetime
import os
import pandas as pd
import py_parser
import numpy as np
import label_perturbation_main
def giveTimeStamp():
tsObj = time.time()
strToret = datetime.datetime.fromtimestamp(tsObj).strftime(constants.TIME_FORMAT)
return strToret
def generateUnitTest(a... | jem0101/BigSwag-SQA2022-AUBURN | TestOrchestrator4ML-main/resources/Code/generation/main.py | main.py | py | 3,660 | python | en | code | 2 | github-code | 1 |
75060035874 | # 1-
def is_row_equal(matrix, row_num):
""" Function is_row_equal gets a matrix and number
and returns if the sum of all number in that row
is equal to the received num.
"""
sum_of_row = 0
# running number of cols of that row
# [number of elements in list].
for i in range(len(mat... | avihay30/PythonProjects | Python_practices/Gidon_lab/12_practice.py | 12_practice.py | py | 5,028 | python | en | code | 0 | github-code | 1 |
5890809734 | n = int(input())
s = input()
s = ""
ans = ""
for i in range(n):
s = input().split()
s = s[1 :]
f = True
if s.isdigit():
ans = c + 1
else :
ans = count + 1
print(ans)
| ds4an/CoDas4CG | GeneratedPrograms/CoasetoFine/pre/131.py | 131.py | py | 175 | python | en | code | 13 | github-code | 1 |
73832383713 | import os
import shutil
class Builder:
def __init__(self, file_name, noconsole = True, flags = ""):
self.file_name = file_name
self.flags = flags
self.default_flags = ""
space = 0
if noconsole:
if space != 0:
self.default_flags += "... | Aermoss/AerForge | aerforge/build.py | build.py | py | 1,325 | python | en | code | 4 | github-code | 1 |
35121463315 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import cherrypy
import Installation
import Equipement
import Activite
import database as bd
class WebManager(object):
@cherrypy.expose
def index(self):
return '''
<html><body>
<h1> Installations sportives des Pays de la loire </h1>
<input type="button" name=... | wlegendre5/TDPython | CherryMain.py | CherryMain.py | py | 1,765 | python | en | code | 0 | github-code | 1 |
20495946674 | from parakeet import jit, config, c_backend
def covariance(x,y):
return ((x-x.mean()) * (y-y.mean())).mean()
def fit_simple_regression(x,y):
slope = covariance(x,y) / covariance(x,x)
offset = y.mean() - slope * x.mean()
return slope, offset
import numpy as np
N = 2*10**7
x = np.random.randn(N).astype(... | iskandr/parakeet | benchmarks/simple_regression.py | simple_regression.py | py | 481 | python | en | code | 232 | github-code | 1 |
74876653154 | from talon import ctrl
from talon.voice import Context, Key, press, Str
from user.utils import repeat_function, optional_numerals, numerals, text_to_number
context = Context('VSCode', bundle='com.microsoft.VSCodeInsiders')
contextDS = Context('DataStudios', bundle='com.azuredatastudio.oss')
def jump_to_line(m):
... | christianhultin/Talon-Scripts | applications/vscode.py | vscode.py | py | 5,095 | python | en | code | 0 | github-code | 1 |
39279834787 | # _*_ coding: utf-8 _*_
counter = 0
def move(disk_number, piller_1, piller_2):
global counter
counter += 1
print('第%d次移动:把%d号盘子从柱子%s移动到柱子%s' %
(counter, disk_number, piller_1, piller_2))
def hanoi_tower(N, A, B, C):
if isinstance(N, (int, float)):
if N == 1:
move(1, A, C)
else:
# move N-1 disks to p... | pengqianggs/Python3 | liaoxuefeng/02.function/02.practice.py | 02.practice.py | py | 735 | python | en | code | 0 | github-code | 1 |
9417593237 | from django.urls import path
from api.views import (
TaskAPIView,
AlgorithmTestAPIView,
TestAPIView,
WantedPageDataAPIView,
KreditJobAPIView,
GoogleTrendsAPIView,
)
urlpatterns = [
path('test/', TestAPIView.as_view(), name='test'),
path('algo_test/', AlgorithmTestAPIView.as_view(), nam... | veggieavocado/Gobble-v.1 | api/urls.py | urls.py | py | 647 | python | en | code | 1 | github-code | 1 |
19817687474 | # -*- coding: utf-8 -*-
import json
from classytags.core import Tag, Options
from cms.utils.encoder import SafeJSONEncoder
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter('json')
def json_filter(value):
"""
Returns the JSON representat... | farhan711/DjangoCMS | cms/templatetags/cms_js_tags.py | cms_js_tags.py | py | 1,039 | python | en | code | 7 | github-code | 1 |
44396101883 | #
# @lc app=leetcode id=23 lang=python3
#
# [23] Merge k Sorted Lists
#
from typing import List, Optional
# @lc code=start
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeKLists(self, lists: Li... | lamdalamda/.leetcode | 23.merge-k-sorted-lists.py | 23.merge-k-sorted-lists.py | py | 4,377 | python | en | code | 0 | github-code | 1 |
3141982124 | import math
import numpy as np
import pandas as pd
from tqdm import tqdm
from scipy import sparse
from sklearn.decomposition import TruncatedSVD
from tools.utils import normalize_adjacency
from tools.Config import Config
class GraRep(object):
"""
GraRep Model Object.
A sparsity aware implementation of GraRe... | PiggyGaGa/FBNE-PU | Baselines/GraRep.py | GraRep.py | py | 3,500 | python | en | code | 2 | github-code | 1 |
70979189794 | from pymongo import MongoClient
from celery import Celery
import redis
from task_config import CACHE_REDIS_HOST
from task_config import CELERY_BROKER_URL
from task_config import CELERY_RESULT_BACKEND
from task_config import MONGODB_URL
#------- redis---------#
class RedisWrapper:
def __init__(self):
self.... | ThatMrWayne/Macros-Eat | tasks/task.py | task.py | py | 5,512 | python | zh | code | 1 | github-code | 1 |
9276188014 | t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = [a[i] - b[i] for i in range(n)]
#print(c)
m = 0
ans = 1
for v in c:
if v < 0:
#print("encountered negative difference, setting to NO")
... | FlashWhite/codeforces | 1690b.py | 1690b.py | py | 645 | python | en | code | 0 | github-code | 1 |
38257185552 | import unittest
import HtmlTestRunner
from WebDriver.webdriver import WebDriver
class EnvironmentSetUp(unittest.TestCase, WebDriver):
@classmethod
def setUpClass(cls):
cls.driver.get("http://automationpractice.com/index.php")
cls.driver.maximize_window()
@classmethod
def tearDownClas... | vadymulianov/PythonPageObjectModel | EnvironmentSetUp/environment.py | environment.py | py | 403 | python | en | code | 0 | github-code | 1 |
10450147143 | """ Simple youtube downloader best resolution video by URL """
from pytube import YouTube
def print_progress_bar(file_size: int, bytes_remaining: int) -> None:
""" Visualizes the download progress """
# rows, columns = os.popen('stty size', 'r').read().split()
fill_empty = ' '
fill_full = '#'
fill... | darkus007/youtube_downloader | you_tu_be_best_res.py | you_tu_be_best_res.py | py | 2,054 | python | en | code | 0 | github-code | 1 |
29250258555 | class Node:
def __init__(self, data):
self.val = data
self.next = None
class Queue:
def __init__(self):
self.head = None
self.tail = None
def enqueue(self, data):
newNode = Node(data)
if self.is_empty():
self.head = newNode
self.tail... | ho991217/Python | PAlgorithm/Day11/Test02.py | Test02.py | py | 1,138 | python | en | code | 0 | github-code | 1 |
8691121259 | class TicTacToe:
def __init__(self, n: int):
"""
Initialize your data structure here.
"""
self.n = n
self.rows = [[0] * n, [0] * n]
self.cols = [[0] * n, [0] * n]
self.diags = [[0, 0], [0, 0]]
def move(self, row: int, col: int, player: int) -> int:
... | songkuixi/LeetCode | Python/Design Tic-Tac-Toe.py | Design Tic-Tac-Toe.py | py | 1,303 | python | en | code | 1 | github-code | 1 |
36039086783 | def maximalSquare(matrix):
"""
:type matrix: List[List[str]]
:rtype: int
"""
for line in matrix:
print(line)
if len(matrix) == 0:
return 0
m = len(matrix)
n = len(matrix[0])
dp = [[0] * n for _ in range(m)]
for i in range(m):
if matrix[i][0] == '1':
... | zhaoxy92/leetcode | dynamic-programing/221_maximal_square.py | 221_maximal_square.py | py | 888 | python | en | code | 0 | github-code | 1 |
23180854671 | class Solution(object):
def restoreString(self, s, indices):
"""
:type s: str
:type indices: List[int]
:rtype: str
"""
arr = [0] * len(indices)
l = ''
for i in range(len(indices)):
arr[indices[i]] = s[i]
for i in range(len(indices))... | 7Aishwarya/Data-Structures-and-Algorithms | Sorting/Shuffle-string.py | Shuffle-string.py | py | 366 | python | en | code | 0 | github-code | 1 |
24603216306 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 29 17:52:45 2019
@author: qinzhen
"""
import numpy as np
import matplotlib.pyplot as plt
def readData(images_file, labels_file):
x = np.loadtxt(images_file, delimiter=',')
y = np.loadtxt(labels_file, delimiter=',')
return x, y
def softmax(x):
"""
Co... | Doraemonzzz/CS229 | 17autumn/ps4/q1/my_nn_starter.py | my_nn_starter.py | py | 5,288 | python | en | code | 14 | github-code | 1 |
35886830090 | from __future__ import annotations
from copy import deepcopy
from sys import stdout
from os import get_terminal_size
from typing import Generator, overload
from contui.style import Style
__all__ = ["Buffer"]
def _write(content: str):
stdout.write(content)
stdout.flush()
class Pixel:
"""A unicode symbol... | Tired-Fox/contui | contui/buffer.py | buffer.py | py | 6,823 | python | en | code | 0 | github-code | 1 |
25297763622 | #!/usr/bin/env python
# coding=utf-8
from __future__ import print_function
import json
import os
import re
import sys
import time
import requests
try:
import config
except ImportError:
print(('Please see config.py.example, update the '
'values and rename it to config.py'))
sys.exit(1)
APIURL ... | linaspurinis/trakt.plex.scripts | lib/trakt.py | trakt.py | py | 5,971 | python | en | code | 31 | github-code | 1 |
42015858077 |
from pathlib import Path
HOME_DIR = Path.home()
BASE_DIR = HOME_DIR / 'covid_phylo_data'
BASE_DIR.mkdir(exist_ok=True)
CACHE_DIR = BASE_DIR / 'cache'
RAW_SEQUENCE_SHELVE_FNAME = 'raw_seqs.shelve'
| JoseBlanca/covid_phylo | src/config.py | config.py | py | 201 | python | en | code | 1 | github-code | 1 |
7168933467 | #!/usr/bin/env python
# coding: utf-8
# In[64]:
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from nltk.stem import PorterStemmer
from nltk.tokenize import sent_tokenize, word_tokenize
from sklearn.pipeline import FeatureUnion
from nltk.corpus import stopwords
im... | AdroitProgrammer/TechFestival-Hackathon | main.py | main.py | py | 3,167 | python | en | code | 1 | github-code | 1 |
17440181992 | from time import process_time
from collections import defaultdict
from functools import lru_cache
def solve(data):
positions = [int(data[0].split()[-1]), int(data[1].split()[-1])]
score = [0, 0]
die = 1
player = 0
total_rolls = 0
while max(score) < 1000:
roll = 0
for i in range... | Florik3ks/AOC2021 | 21/21.py | 21.py | py | 3,479 | python | en | code | 1 | github-code | 1 |
27150385369 | import sklearn.datasets
import pandas as pd
from sklearn.model_selection import train_test_split
import numpy as np
from sklearn.metrics import accuracy_score
breast_cancer = sklearn.datasets.load_breast_cancer()
breast_cancer_DF = pd.DataFrame( breast_cancer.data, columns = breast_cancer.feature_names)
breast_cancer_... | abhishekv362/Neural-Networks | MP Neuron/Implementation.py | Implementation.py | py | 1,180 | python | en | code | 0 | github-code | 1 |
18403269330 | from flask import Flask, render_template, request, redirect, session,flash
from pymongo import MongoClient
from bson.objectid import ObjectId
from user_database import user_coll , post_coll
import datetime
app = Flask(__name__)
app.secret_key = "3423"
@app.route('/')
def browser():
return render_template('login.ht... | longvd336/First-project | app.py | app.py | py | 9,196 | python | en | code | 1 | github-code | 1 |
1963557510 | def dfs(deep, s) :
if deep == n :
print(' '.join(s))
return
for i in range(1, n+1) :
if not str(i) in s :
s.append(str(i))
dfs(deep+1, s)
s.pop()
n = int(input())
dfs(0, []) | totwjfakd/-algorithm | DFS,BFS/백준10974_모든 순열.py | 백준10974_모든 순열.py | py | 245 | python | en | code | 0 | github-code | 1 |
26950031561 | import os
import json
import mikochiku_alarm
from PyQt5.QtWidgets import QWidget, QMainWindow
from PyQt5.QtWidgets import QComboBox, QLabel, QFrame, QLineEdit, QPushButton, QCheckBox
from PyQt5.QtGui import QFont
from PyQt5.QtCore import Qt
import settings
class ConfigTab(QMainWindow):
def __init__(self, pare... | pusaitou/mikochiku_alarm | config_tab.py | config_tab.py | py | 4,043 | python | en | code | 17 | github-code | 1 |
26459808577 | import scipy as sp
import numpy as np
from typing import Literal, Tuple
def cossin(Q: np.ndarray, shape: Tuple[int, int], ret: Literal['full', 'blocks', 'minimal'] = 'full'):
p, q = shape
m, _ = Q.shape
m1, m2 = m - p, m - q
(U_1, U_2), theta, (V_1t, V_2t) = sp.linalg.cossin(Q, p=p, q=q, separate=... | sfcaracciolo/cossin_wrapper | src/cossin_wrapper/core.py | core.py | py | 2,991 | python | en | code | 0 | github-code | 1 |
6564899352 | import argparse
import time, datetime
import os
import os.path as osp
import logging
from baselines import logger, bench
from baselines.common.misc_util import (
set_global_seeds,
boolean_flag,
)
import baselines.torcs_ddpg.training as training
from baselines.torcs_ddpg.models import Actor, Critic
from baseline... | dosssman/TorcsRLILHybrid | baselines/torcs_ddpg/main.py | main.py | py | 7,196 | python | en | code | 4 | github-code | 1 |
163086800 | import cv2
import dlib
import numpy as np
from mtcnn import MTCNN
# Inicialización de MTCNN y dlib
detector = MTCNN()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
with open("coco.names", "r") as f:
classes = [line.strip() for line in f.readlines()]
colors = np.random.uniform(0, 255, s... | SergioAyalaHernandez/detectorRostros | detectorObjetos2.py | detectorObjetos2.py | py | 2,924 | python | en | code | 0 | github-code | 1 |
11588017226 | #!/usr/bin/env python3
"""
Export item content
"""
import pandas as pd
fname = "dat/response.csv"
df = pd.read_csv(fname)
items = df.columns.tolist()
out = pd.DataFrame()
out["long-form"] = items
out.to_csv("dat/items.csv")
| knielbo/survey_visualization | item_content.py | item_content.py | py | 224 | python | en | code | 1 | github-code | 1 |
21430433938 | import os
def part_1(x_coords, y_coords):
highest_position = 0
hitting_positions = set()
for x_start in range(1, x_coords[1] + 1):
for y_start in range(1000, y_coords[0] - 1, -1):
x_speed, y_speed = x_start, y_start
x, y = 0, 0
highest_try_position = 0
... | borisbarath/advent-of-code-21 | 17/trickshot.py | trickshot.py | py | 2,128 | python | en | code | 0 | github-code | 1 |
20190419338 | from mrjob.job import MRJob
from mrjob.step import MRStep
from datetime import datetime
from datetime import timedelta
# We extend the MRJob class
# This includes our definition of map and reduce functions
class MRAvgTripTime(MRJob):
def mapper(self, _, line):
row = line.split(',')
if len(row) >... | Vishal4295/Map-Reduce-Case-Study | mrtask_d.py | mrtask_d.py | py | 1,327 | python | en | code | 0 | github-code | 1 |
18690098738 | """Contains classes and utilities related to FICA taxes."""
from ...earnings import EarningsTaxPolicy, EarningsType, TaxCategory
from ...money import Money
from ..composite import CompositeTax
from ..bracket import Bracket, BracketTax
from ..flat import FlatTax
from .data import (
ADDITIONAL_MEDICARE_TAX_RATE,
... | thomasebsmith/finances | src/finances/tax/federal/fica.py | fica.py | py | 2,571 | python | en | code | 0 | github-code | 1 |
34280625886 | # Title: Face detection using Python and OpenCV.
# Author: @CodeProgrammer "On Telegram" || @PythonSy "On Instagram".
"""
you need to install OpenCV by using this command in the terminal:
pip install opencv-python
for more codes you can visit our channel on Telegram: @CodeProgrammer
"""
import cv2
"""
load t... | hack-parthsharma/Useless-Python-Codes | Face Detection.py | Face Detection.py | py | 914 | python | en | code | 5 | github-code | 1 |
13355328222 | # 1 Vamos a medir el tiempo en que tarda un algoritmo
import time
# Factorial ITERATIVO
def factorial(n):
respuesta = 1
while n > 1:
respuesta *= n
n -= 1
return respuesta
# Factorial RECURSIVO
def factorial_r(n):
if n == 1:
return 1
return n * factorial (n - 1)
# Pun... | Meister-hub/POO | complegidad_algoritmica.py | complegidad_algoritmica.py | py | 679 | python | es | code | 0 | github-code | 1 |
8556970875 | from rest_framework.views import APIView
from rest_framework.response import Response
import math
class PostProcView(APIView):
def largest_remainder(self, options, q, points, zero_votes):
out = []
e = []
r = []
if not zero_votes:
if len(options) == 0:
... | josvilgar1/decide-defensa | decide/postproc/views.py | views.py | py | 5,820 | python | en | code | 0 | github-code | 1 |
30815615363 | from flask import abort
from sqlalchemy.exc import SQLAlchemyError
from app_client.app_client.models import Client, db
from app_client.app_client.handle_excep import valid_none
def list_client():
try:
cliente_list = Client.query.all()
except SQLAlchemyError as error:
abort(500, str(error.__d... | dilermando-lima/api-python-flask | app_client/app_client/cliente_views.py | cliente_views.py | py | 1,940 | python | en | code | 0 | github-code | 1 |
27736665489 | from typing import List, Tuple, Optional, Union
from pathlib import Path
import pandas as pd
import numpy as np
import fire
import ta
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.pipeline import make_pipeline, Pipeline
from sklearn.preprocessing import FunctionTransformer
from src.paths impor... | Paulescu/hands-on-train-and-deploy-ml | src/preprocessing.py | preprocessing.py | py | 5,277 | python | en | code | 505 | github-code | 1 |
70506253475 | #!/usr/bin/env python
from api_types import DEFAULT_DATASET
from flask import Flask, render_template, request, redirect, url_for
import api
import dataset
import filters
app = Flask(__name__, static_folder="public", template_folder="views")
app.jinja_env.filters["diff_classname"] = filters.diff_classname_filter
... | OrcaCollective/1-312-hows-my-driving | src/app.py | app.py | py | 5,101 | python | en | code | 3 | github-code | 1 |
36196462632 | from .models import Carrito
def carrito_total(id_carrito):
carrito = Carrito.objects.get(id_carrito=int(id_carrito.id_carrito))
items = carrito.items.all()
total = sum([item.cantidad * item.producto.precio for item in items])
carrito.total = total
carrito.save()
def calcular_precio_total(items... | Pipe930/Api-Rest-Farmacia | apps/ventas/total_carrito.py | total_carrito.py | py | 1,500 | python | es | code | 1 | github-code | 1 |
37449295163 | import sys
import json
from datetime import datetime
# Import the necessary methods from "twitter" library
from twitter import Twitter, OAuth, TwitterHTTPError, TwitterStream
if sys.version_info[0] < 3:
raise Exception("Python 3 is required to run this script")
try:
with open('config_json.txt') as config_fil... | prairiewest/simple-tweet-scraping | tweets.py | tweets.py | py | 5,774 | python | en | code | 0 | github-code | 1 |
4883070999 | # BAP 2019
# Author: Axel Claeijs
# This script uses the trained network to make predictions
#-----------------------------------------------------------
# IMPORTS
#-----------------------------------------------------------
import sys
import cv2
import math
import pptk
import numpy as np
import matplotlib.pyplot as ... | axelclaeijs/PointCloud_Costmap_NN | Use_WM.py | Use_WM.py | py | 5,144 | python | en | code | 0 | github-code | 1 |
8015046067 | # freecodecamp Algorithmic Trading - Equal-Weight S&P 500
import numpy as np # one or two dimensional arrays/tensors
import pandas as pd # spreadsheets, tabular
import requests # html
import xlsxwriter
import math
stocks = pd.read_csv('sp_500_stocks.csv')
type(stocks) # print? tells what type
# store in s... | chrissmith10/projects-freecodecamp | algtradeqweightsp500.py | algtradeqweightsp500.py | py | 4,848 | python | en | code | 0 | github-code | 1 |
73264299875 | from sys import exit
from random import randint
from textwrap import dedent
class Scene(object) :
def enter(self) :
print("You are exiting the game")
exit(1)
class Engine(object) :
def __init__(self, scene_map) :
self.scene_map = scene_map
def play(self) :
current_scene ... | Leeoku/LearnPythonHardWay | ex43.py | ex43.py | py | 4,079 | python | en | code | 0 | github-code | 1 |
20256660501 | def crayonColors():
'''
crayonColors=checks the file with the 1990 crayon colors, removes the ones
listed in the file that were discontinued, and adds the ones listed in
the file that were added to production
@param original=file with the list of colors in 1990
@param removed=file with list of colors discontinued
@... | haoknowah/OldPythonAssignments | Gaston_Noah_NKN328_Hwk12/033_crayonColors.py | 033_crayonColors.py | py | 2,087 | python | en | code | 0 | github-code | 1 |
15224383350 | # coding=utf-8
from __future__ import absolute_import
import logging.config
from os.path import join, realpath, abspath, dirname as up
from django.utils.text import slugify
class LoggingSettings(object):
"""
Drop in replacement of Django's Logging Configuration:
Sends INFO level or higher to the console ... | techoutlooks/django-quickconfigs | quickconfigs/config/logging.py | logging.py | py | 3,509 | python | en | code | 0 | github-code | 1 |
28134075243 | import tensorflow as tf
import numpy as np
import facenet
import math
import pickle
from scipy import misc
import sklearn.metrics as ms
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import classificatio... | rjx678/facenet_demo | src/align/test_svc.py | test_svc.py | py | 25,114 | python | en | code | 1 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.