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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
72711274578 | import csv
import sys
import os
import tkinter as tk
# user input - input the order file and cartons file (with correct filepaths) into the quotations below:
csv_items = csv.reader(open('C:\\Users\\Desktop\\order.csv'))
csv_cartons = csv.reader(open('C:\\Users\\Desktop\\carton.csv'))
# region import data
... | geersenthil/Packaging-Carton-Optimization | Script-Final.py | Script-Final.py | py | 10,239 | python | en | code | 0 | github-code | 13 |
16132250333 | import base64
import io
import qrcode
def lambda_handler(event, context):
url = event["url"]
img = qrcode.make(url)
img_bytes = io.BytesIO()
img.save(img_bytes, format="PNG")
return {
"statusCode": 200,
"body": base64.b64encode(img_bytes.getvalue()).decode("utf-8"),
"isBas... | udhayprakash/PythonMaterial | python3/18_aws_cloud/a_AWS_Lambdas/d_practical_utility_functions/d_generate_QR_code.py | d_generate_QR_code.py | py | 457 | python | en | code | 7 | github-code | 13 |
4307290093 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 29 10:06:29 2018
@author: newness
"""
#LINKEDIN PROJECT SAMPLE
#WE WANT TO ANSWER QUESTION: WHICH GEOGRAPHY IS MOST ENGR JOB LISTING\
#HOW BANKS ARE SHIFTING STRATEGIES
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import glob
#... | insighty/old_projects | proposal_n.py | proposal_n.py | py | 1,885 | python | en | code | 0 | github-code | 13 |
40208226275 | import arcpy
import string
from arcpy import env
from arcpy.sa import *
def zstat(flderName):
wkSpace = "C:/Workspace/spk/"+flderName+"/"
arcpy.env.workspace = wkSpace
maskDir = wkSpace
fcs = arcpy.ListFeatureClasses()
rasters = arcpy.ListRasters()
for fc in fcs:
for raster in rasters... | sakdahomhuan/da-ArcPy | _zstatisic.py | _zstatisic.py | py | 988 | python | en | code | 1 | github-code | 13 |
41805709673 | class Solution(object):
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
ans = []
def dfs(lst, dep):
if not (k - dep):
ans.append(lst[:])
start = lst[dep - 1] + 1 if dep else ... | superwhd/LeetCode | 77 Combinations.py | 77 Combinations.py | py | 499 | python | en | code | 1 | github-code | 13 |
35900866569 | # Proje 1
l = [[1,'a',['cat'],2],[[[3]],'dog'],4,5]
l1 = []
def flatten(n):
for i in n :
if isinstance(i,list):
flatten(i)
else:
l1.append(i)
flatten(l)
print(l1)
# Proje 2
lst = [[1, 2], [3, 4], [5, 6, 7]]
l2 = []
def Reverse(lst):
for j in lst:
if isinstanc... | muhammed-gumus/Python-Case | Patika/Patika-final-case.py | Patika-final-case.py | py | 459 | python | en | code | 0 | github-code | 13 |
74406567696 | #!/usr/bin/env python
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
# Imports
import numpy
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
#---------------------------------... | LorenFiorini/Competitive-Programming | kickStart (Google)/2021/Round A 2021/2021AB.py | 2021AB.py | py | 3,896 | python | en | code | 2 | github-code | 13 |
32276930743 | # exercise 135: The Sieve of Eratosthenes
limit = int(input('enter a limit: '))
nums = []
for i in range(0, limit + 1):
nums.append(i)
nums[1] = 0
#print(nums)
p = 2
while p < limit:
# making all multiple of p except p equal to zero, because I already know they are not prime numbers
# using p itself as ... | sara-kassani/1000_Python_example | books/Python Workbook/lists/ex135.py | ex135.py | py | 717 | python | en | code | 1 | github-code | 13 |
7500470737 | """User View tests"""
import os
from unittest import TestCase
from models import db, connect_db, Message, User, Likes, Follows
os.environ['DATABASE_URL'] = "postgresql:///warbler-test"
from app import app, CURR_USER_KEY
app.config['TESTING'] = True
app.config['DEBUG_TB_HOSTS'] = ['dont-show-debug-toolbar']
app.con... | AlpineCurt/warbler | test_user_views.py | test_user_views.py | py | 9,044 | python | en | code | 0 | github-code | 13 |
1768952105 | import socket
# Crear socket TCP/IP
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Conectar el socket al puerto
server_address = ('localhost', 10000)
sock.bind(server_address)
print('Servidor iniciado, host {} puerto {}'.format(*server_address))
# A escucha de conexiones
sock.listen(1)
while True:
#... | leomm20/CursoPython | src/cp09_extras/cp70_cliente_servidor_servidor.py | cp70_cliente_servidor_servidor.py | py | 1,150 | python | es | code | 0 | github-code | 13 |
2014750961 | from gensim.models import Doc2Vec
import sys, os, time, subprocess
from sklearn.cluster import KMeans, AgglomerativeClustering#, SpectralClustering, DBSCAN
from sklearn.metrics import classification_report,confusion_matrix,roc_curve,auc, silhouette_score
from sklearn.ensemble import GradientBoostingClassifier
from skl... | jordanplanders/Thinkful | Bootcamp/Capstone/cluster_analysis2.py | cluster_analysis2.py | py | 8,762 | python | en | code | 1 | github-code | 13 |
17050417274 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class ContractSignRsp(object):
def __init__(self):
self._open_id = None
self._sign_url = None
self._user_id = None
self._user_name = None
@property
def open_id(... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/ContractSignRsp.py | ContractSignRsp.py | py | 2,249 | python | en | code | 241 | github-code | 13 |
28974632946 | """Synchronous API for external server-side processes
The *messaging server* should never use these interfaces,
they are intended for Django and similar processes which
want to write a message to a channel and/or add/remove
sessions to/from a channel.
"""
import os, sys
import argparse
from . import base
class Chan... | mcfletch/ssws | ssws/sync.py | sync.py | py | 4,647 | python | en | code | 0 | github-code | 13 |
35723646672 | # -*- coding: utf-8 -*-
import requests
import pygame
from CameraControl import CameraControl
from CarControl import CarControl
class Client:
target_host = ''
target_port = ''
def __init__(self, target_host, target_port):
self.target_host = target_host
self.target_port = target_port
#... | Capstone-Projects-2021-Fall/project-steve | RPi/client.py | client.py | py | 4,127 | python | en | code | 0 | github-code | 13 |
24547148496 | from bs4 import BeautifulSoup
import requests
import re
from urllib.parse import urlparse
from html.parser import HTMLParser
class UrlDAO:
# def __init__(self):
# self.s = set()
def getUrls(self, url: str):
r = requests.get(url, timeout = 1)
soup = BeautifulSoup(r.content)
s... | saramnt/prova_venv | innolva_spider/dao/UrlDAO.py | UrlDAO.py | py | 1,072 | python | en | code | 0 | github-code | 13 |
24049969436 | from __future__ import print_function
import os.path
from flask import render_template, session, redirect
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from . import... | Joshgonzalez246/SmartDoorbell-FUN09a | routes.py | routes.py | py | 2,618 | python | en | code | 1 | github-code | 13 |
34788078020 | from ROOT import *
from utils import *
ftemplates = TFile('usefulthings/llhd-prior-coarse-1p2width.root')
ftemplates.cd('splines')
ftemplates.ls()
c1 = mkcanvas('c1')
histnames = ['hRTemplate(gPt20.0-25.0, gEta0.0-0.4)', 'hRTemplate(gPt20.0-25.0, gEta2.5-6.0)','hRTemplate(gPt200.0-300.0, gEta0.0-0.4)']
histnames... | sbein/BayesQcd | tools/DrawResponsesAndPrior.py | DrawResponsesAndPrior.py | py | 1,804 | python | en | code | 0 | github-code | 13 |
11658694251 | # RealSeriesEvaluationRun.build_corpora()
# RealSeriesEvaluationRun.train_vecs()
import json
import os
from collections import defaultdict
import pandas as pd
from joblib import Parallel, delayed
from tqdm import tqdm
import numpy as np
from lib2vec.corpus_structure import Corpus, DataHandler, ConfigLoader, Preprocesse... | LasLitz/ma-doc-embeddings | experiments/common_words_experiment.py | common_words_experiment.py | py | 15,669 | python | en | code | 3 | github-code | 13 |
5309021695 | t = int(input())
for i in range(t):
a, b, c = map(int, input().split())
mi = min(a, b)
mi = min(mi, c)
if mi==a:
print("Draw")
elif mi==b:
print("Bob")
else:
print("Alice") | shruti01052002/Mission-Data-Structures | Array/HardestProblem.py | HardestProblem.py | py | 220 | python | en | code | 0 | github-code | 13 |
5400078192 | import argparse
import json
import catalogue.bin
from catalogue.bibtex import decode
def main(args):
entries = []
for entry in args.path:
with open(entry) as f:
entries.extend(json.load(f))
catalogue.bin.pbcopy(decode(entries))
if __name__ == "__main__":
parser = argparse.Argume... | wesselb/catalogue | copy_bibtex.py | copy_bibtex.py | py | 438 | python | en | code | 0 | github-code | 13 |
9746661084 | import pandas as pd
class HqCsv:
def __init__(self, _ticker, csvFile):
self._ticker = _ticker
csv = pd.read_csv(csvFile, index_col=[0], parse_dates=False)
csv['PrevClose'] = csv.Close.shift(1)
csv['PrevVolume'] = csv.Volume.shift(1)
csv['VolChange'] = (csv.Volume - csv.PrevV... | jbtwitt/pipy | hq/HqCsv.py | HqCsv.py | py | 1,650 | python | en | code | 0 | github-code | 13 |
43860256545 | from sys import stdin
par = []
set_size = 0
def initialize(size):
global set_size
set_size = size
return [i for i in range(size)]
def find(i):
return i if par[i] == i else find(par[i])
def union(a, b):
if find(a) != find(b):
par[find(a)] = find(b)
global set_size
set_s... | rezakrimi/ACM | UVaProblems/UVa459.py | UVa459.py | py | 605 | python | en | code | 0 | github-code | 13 |
16027410084 | # 길찾기
# SWEA 난이도 D4
# 0에서 99로 길 존재하는지
# stack dfs 로 구현해보자
def dfs(start, end, graph, visited):
stack = [start]
# visited[start] = True
while stack:
w = stack.pop()
if w == end:
return 1
if visited[w] == False:
visited[w] = True
for i in graph[w]:... | joonann/ProblemSolving | python/202308/11/길찾기.py | 길찾기.py | py | 800 | python | en | code | 0 | github-code | 13 |
8536454102 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
Created on Oct 30, 2017
@author: hadoop
'''
from utils.emails import send_email
from drawing.drawing_utils import draw_stock_with_multi_periods
import os
if __name__ == '__main__':
file_lst = []
code_id = "399300"
fname = "/home/hadoop/" + code_id... | liujinguang/stockquantpro | stock-quant-pro/uts/test_email.py | test_email.py | py | 900 | python | en | code | 0 | github-code | 13 |
13210705802 | score = {'001':96,'002':98,'003':92,'004':93,'005':94}
score['006'] = 100
score['002'] = 99
del score['001']
print(score['004'])
max = score['002']
min = score['002']
count =0
for key,value in score.items():
if(max < value):
max = value
if(min > value):
min = value
count+=value
print("最大值:"... | lemon5227/CodeField | Python/实验三其他组合数据类型/9.py | 9.py | py | 384 | python | en | code | 0 | github-code | 13 |
30599696915 | """This is a exercise from https://exercism.io/my/tracks/python"""
from enum import Enum
from textwrap import indent
class Vector(list):
"""Adds a 2D-orientation to a list. This is usefull when dealing with matrices."""
def __init__(self, *args, axis=None):
if axis not in Matrix2D.Axes:
ra... | cglacet/exercism-python | saddle-points/complete_saddle_points.py | complete_saddle_points.py | py | 11,518 | python | en | code | 5 | github-code | 13 |
34059061313 | import cv2
import numpy as np
from PIL import Image
from io import BytesIO
import base64
# Read the image
img = cv2.imread('image.jpeg')
img = cv2.resize(img, (640, 480))
# Define the points
points = [(150, 50),(150,200,),(190,200),(150, 200), (200, 150), (850, 350)]
# Draw a line through all the points
color = (0, ... | sriprada346/Route-planner | tes.py | tes.py | py | 915 | python | en | code | 0 | github-code | 13 |
10976074278 | from output.base import Output
from output.console import ConsoleOutput, TableConsoleOutput
from output.file import CSVFileOutput, JSONFileOutput, YAMLFileOutput
_outputs = {
"console": ConsoleOutput,
"tableconsole": TableConsoleOutput,
"jsonfile": JSONFileOutput,
"yamlfile": YAMLFileOutput,
"csvfi... | pedrolp85/python_basics | nba_cli_project/output/defaults.py | defaults.py | py | 430 | python | en | code | 0 | github-code | 13 |
5748094252 | #!/usr/bin/python3
''' base.py module file. '''
class Base:
''' base class that have init methode. '''
__nb_objects = 0
def __init__(self, id=None):
''' initialize the id. '''
if (id is not None):
self.id = id
else:
Base.__nb_objects += 1
self.i... | Dragonkuro2/alx-higher_level_programming | 0x0C-python-almost_a_circle/models/base.py | base.py | py | 342 | python | en | code | 1 | github-code | 13 |
31013973053 | import pandas as pd
import numpy as np
import string
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import time
import xgboost as xgb
from sklearn.metrics import mean_squared_error #RMSE
from math import sqrt
from sklearn.metrics import roc_curve
from sklearn.metrics import auc
fro... | shanggangli/kaggle-Predict-Future-Sales | Predict-Future-Sales.py | Predict-Future-Sales.py | py | 8,565 | python | en | code | 1 | github-code | 13 |
40210658220 | from src.graphics import run_example
import pygame, sys
from pygame.locals import *
from math import copysign
from typing import List
import random
epsilon = .00000000001
class Entity:
def __init__(self, xi, mass=1, v=0, id=None):
"""
:param x: The initial x position. This variable will not eve... | samsonjj/1d-physics-python | src/main.py | main.py | py | 6,074 | python | en | code | 0 | github-code | 13 |
21473527589 | visitors = int(input())
counter_back = 0
counter_chest = 0
counter_legs = 0
counter_abs = 0
counter_protein_shake = 0
counter_protein_bar = 0
counter_train = 0
counter_buy = 0
for i in range(0, visitors):
acts = input()
if acts == 'Back':
counter_back += 1
counter_train += 1
... | patsonev/Python_Basics_Exam_Preparation | fitness_center.py | fitness_center.py | py | 1,098 | python | en | code | 0 | github-code | 13 |
10024223163 | from __future__ import print_function
# Import comet_ml in the top
from comet_ml import Experiment
import argparse
import os
import sys
import torch
from torch.optim import Adam
from given_code.classify_svhn import get_data_loader
from q3.vae.models.conv_vae import ConvVAE
from q3.vae.vae_trainer import VAETrainer
fr... | Lap1n/ift6135 | tp3/src/q3/vae/run_train_vae.py | run_train_vae.py | py | 3,022 | python | en | code | 0 | github-code | 13 |
12322642741 | # http://demo.spiderpy.cn/get/ 代理接口
import requests
"""
代理形式
proxies = {
"http": "http://10.10.1.10:3128",
"https": "http://10.10.1.10:1080",
}
"""
def get_proxy():
"""获取代理函数"""
json_data = requests.get(url='http://demo.spiderpy.cn/get/').json()
# print(json_data)
proxy = json_da... | lll13508510371/Scrapping | 03 requests入门/code/09 proxy关键字参数.py | 09 proxy关键字参数.py | py | 956 | python | zh | code | 0 | github-code | 13 |
20224937382 | #import sqlanydb
import os
import pyodbc
from clases.cls_Bdd import BaseDD
os.environ["SQLANY_API_DLL"]='/opt/sqlanywhere17/lib64/libdbcapi_r.so'
servidor='193.168.1.175:5000'
usuario='sa'
clave='Emilita01'
db='master'
puerto=5000
drver='SYBASE'
print("Hola ")
Conn = BaseDD(servidor,usuario,clave,db,puerto,drver... | wbarrazaj/Monitor-Sybase-Python | Prueba.py | Prueba.py | py | 541 | python | es | code | 0 | github-code | 13 |
28594164910 | # -*- coding: utf-8 -*-
"""
Updated 16 Dec 2017
10 sheep eat away at their environments
Greedy sheep are sick after 100 units
@author: amandaf
"""
import matplotlib.pyplot
import matplotlib.animation
import csv
import agentframework
import random
#setup variables
num_of_agents = 10
num_of_iterations = 100
agents = [... | gisworld/ABM | src/unpackaged/abm/practicals/Animation/Sheep/model.py | model.py | py | 2,411 | python | en | code | 0 | github-code | 13 |
32307981415 | def longest_streak(head):
if head is None:
return 0
current = head
current_val = head.val
count = 0
lst = []
while current:
if current.val == current_val:
count += 1
current = current.next
else:
lst.append(count)
current_val = current.val
count = 1
current ... | kabszac/dsandalgo | linkedlist/longstreak.py | longstreak.py | py | 1,041 | python | en | code | 0 | github-code | 13 |
74937180176 | import numpy as np
import random
import re
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn import datasets
import random
import time
def time_me(fn):
def _wrapper(*args, **kwargs):
start = time.clock()
fn(*args, **kwargs)
print("%s cost %s second" % (fn... | YOUNGBChen/MachineLearningCourse | Secomd/K-means.py | K-means.py | py | 4,409 | python | en | code | 3 | github-code | 13 |
24899288514 | from .redditManager import get_instance
from flask import (Blueprint, render_template, request)
import markdown
import urllib
import json
from html_diff import diff as df
from urllib.parse import quote
diff = Blueprint('diff', __name__)
class Submission:
def __init__(self, author, id, selftext, title, url, subreddi... | adhesivecheese/modpanel | project/diff.py | diff.py | py | 1,487 | python | en | code | 1 | github-code | 13 |
69846570258 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 22 11:20:38 2020
@author: christopher_sampah
"""
import pandas as pd
import numpy as np
import seaborn as sbn
import matplotlib.pyplot as plt
from scipy.stats import norm
from scipy import stats
import sklearn
from sklearn import linear_model as lm
from sklearn.model_se... | ChrisMattSam/cuanto_cuesta_casa | data_analysis.py | data_analysis.py | py | 11,634 | python | en | code | 0 | github-code | 13 |
6917501917 | from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from .models import *
import random
from json import dumps
from django.views.decorators.cache import cache_control
from django.db import connection
def test(request):
with connection.cursor() as ... | syuan2000/colorWebTool | main/views.py | views.py | py | 3,305 | python | en | code | 0 | github-code | 13 |
30238715243 | ''' Reverso do número. Faça uma função que retorne o reverso de um número inteiro
informado.
'''
numeroDigitado = (input('Digite um número: '))
def reverso(numero):
inverte = str(numero)
print(inverte[::-1])
reverso(numeroDigitado)
| nataliakdiniz/estrutura_dados_uniesp | primeira_unidade/reversoNumero.py | reversoNumero.py | py | 251 | python | pt | code | 0 | github-code | 13 |
6609558679 | from pyspark import SparkContext, SparkConf
from pyspark.sql import SparkSession, HiveContext, Row
from pyspark.sql.types import *
from pyspark.sql.functions import col
import pyspark.sql.functions as F
import time
from pyspark.sql.functions import lit
spark = (SparkSession
.builder
.a... | muharandy/Identity-Matching | matching_prep.py | matching_prep.py | py | 3,751 | python | en | code | 0 | github-code | 13 |
3199765789 | from unicodedata import name
from django.urls import path
from Kitab import views
from django.contrib.auth import views as auth_views
from django.contrib import admin
from django.contrib import admin
from django.contrib.auth.views import LoginView
urlpatterns = [
path('', views.home, name='home'),
path... | Samitalimbu/OnlineMusicalInstruments | Kitab/urls.py | urls.py | py | 2,090 | python | en | code | 0 | github-code | 13 |
1189690192 |
from __future__ import unicode_literals
from wxpy import *
from wechat_sender import listen
bot = Bot()
my = bot.friends()
'''
my1 = bot.friends().search('吴震')[0]
my2 = bot.friends().search('吴明')[0]
my3 = bot.friends().search('朱依心')[0]
'''
@bot.register(Friend)
def reply_test(msg):
msg.reply('欢迎关注,更多内容请关注公众号--SQ... | WUZHEN1991/sigma_dati | wechat.py | wechat.py | py | 611 | python | en | code | 0 | github-code | 13 |
34573015212 | population = [int(x) for x in input().split(", ")]
min_wealth = int(input())
while True:
count = len(population)
# първо проверяваме дали е възможно разпределянето на богатството
if sum(population) < min_wealth * count:
print("No equal distribution possible")
break
if all(i >= min_wealth f... | TinaZhelyazova/02.-Python-Fundamentals | 18. Lists Advanced - More Exercises/01. Social Distribution.py | 01. Social Distribution.py | py | 1,176 | python | bg | code | 0 | github-code | 13 |
16156277413 | import re
# doc='''Dave Martin
# 615-555-7164
# 173 Main St., Springfield RI 55924
# davemartin@bogusemail.com
# Charles Harris
# 800-555-5669
# 969 High St., Atlantis VA 34075
# charlesharris@bogusemail.com
# Eric Williams
# 560-555-5153
# 806 1st St., Faketown AK 86847
# laurawilliams@bogusemail.com
# Corey Jeffer... | saisrihari/Programs | python_class/last/rexp.py | rexp.py | py | 591 | python | en | code | 0 | github-code | 13 |
74772215378 | import os
import pickle
import time
import gym
import gym_grid
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.distributions.categorical import Categorical
from torch.utils.tensorboard import SummaryWriter
from sympy.utilities.iterables import multiset_permutations
import sy... | SagarParekh97/Decision-Making-under-Uncertainty | P2/PPO.py | PPO.py | py | 12,813 | python | en | code | 0 | github-code | 13 |
1385325825 | import math
import torch
def adv_perturbation(x, opB, opR, c_B, eta, lr, num_iters, device):
"""
Computes an adversarial perturbation e = [e1;e2] (assuming e1 = e2) for
a (subdifferentiable) reconstruction method for recovering a vector x given
measurements y1 = B @ x + e1, y2 = B @ x + e2. Expressed ... | mneyrane/MSc-thesis-NESTAnets | nestanet/stability.py | stability.py | py | 3,568 | python | en | code | 0 | github-code | 13 |
32871493562 | from typing import List, Optional
from pydantic import BaseModel
from enum import Enum
class Field(BaseModel):
name_field: str
type: str
length: int = None
value: str = None
primary_key: bool = False
not_null: bool = False
unique: bool = False
default: str = None
auto_increment: b... | vuminhhieucareer172/SparkPushNotification | backend/schemas/table.py | table.py | py | 683 | python | en | code | 0 | github-code | 13 |
23172846319 | from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name = 'home'),
path('login', views.login, name = 'login'),
path('logout', views.logout_view, name = 'logout'),
path('signup', views.sigunup, name = 'signup'),
path('puzzle1/<int:ans>', views.puzzle1, name = 'puzz... | KShanmukhaSrinivas/Treasure_Hunt | Treasure/main/urls.py | urls.py | py | 456 | python | en | code | 0 | github-code | 13 |
956814392 | # https://projecteuler.net/problem=10
import math
import unittest
from multiprocessing import Pool, Process
def sieve_of_eratosthenes(n):
multiples = []
for i in range(2, n+1):
if i not in multiples:
print (i)
for j in range(i*i, n+1, i):
multiples.append(j)
d... | aj07mm/project_euler | problem_010.py | problem_010.py | py | 1,286 | python | en | code | 0 | github-code | 13 |
2061677900 | """
Cleans raw ELEXON data that was scraped using scrape_data.py
Each report requires a slightly different approach for cleaning
"""
import numpy as np
import pandas as pd
from forecast import check_dataframe
def print_duplicates(df):
dupes = df[df.index.duplicated()]
num = dupes.shape[0]
print('{} dupl... | ADGEfficiency/forecast | projects/elexon/cleaning_data.py | cleaning_data.py | py | 2,397 | python | en | code | 19 | github-code | 13 |
29956660589 | from functools import wraps
from typing import Any, Callable, TypeVar
T = TypeVar('T', bound=Any)
def gameover(game: Callable[..., T]) -> Callable[..., T | None]:
@wraps(game)
def wrapper(*args, **kwargs) -> T | None:
try:
return game(*args, **kwargs)
except KeyboardInterrupt:
... | Lingxuan-Ye/games | lib/decorators/lifecycle.py | lifecycle.py | py | 494 | python | en | code | 0 | github-code | 13 |
31740533985 | # -*- coding: utf-8 -*-
# @Time : 2023/10/15 下午3:38
# @Author : nanji
# @Site :
# @File : adaboost_c.py
# @Software: PyCharm
# @Comment :
import numpy as np
from machinelearn.decision_tree_04.decision_tree_C \
import DecisionTreeClassifier
import copy
class SAMMERClassifier:
'''
SAMME.R算法是将SAM... | lixixi89055465/py_stu | machinelearn/ensemble_learning_08/adaboost/adaboost_discrete_c.py | adaboost_discrete_c.py | py | 4,204 | python | en | code | 1 | github-code | 13 |
2265902891 | import tkinter as tk
fileSizeList = [
"Bytes",
"Kilobytes",
"Megabytes",
"Gigabytes"
]
app = tk.Tk()
fileSize = ''
app.geometry('100x200')
sizeMenuVal = tk.StringVar(app)
sizeMenuVal.set(fileSizeList[0])
sizeMenu = tk.OptionMenu(app, sizeMenuVal, *fileSizeList)
sizeMenu.config(width=90, font=('Helvetica', 12))
s... | Mobenator/FileShift | dropdowntest.py | dropdowntest.py | py | 562 | python | en | code | 0 | github-code | 13 |
43003558709 | import pandas as pd
import numpy as np
'''inputs to func look something like this:
filename = 'test_dataset.csv'
list_nans = [np.nan, 'na', 88, 999]
new_df = missing_coder(filename=filename, list_nans=list_nans'''
def missing_coder(filename, list_nans):
df = pd.read_csv(filename, na_values=list_nans)
cols = ... | matthewvowels1/missingness_dummy_coder | missing_coder.py | missing_coder.py | py | 717 | python | en | code | 0 | github-code | 13 |
13478514140 | from decimal import Decimal
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect, render
from django.views.generic import (
ListView,
DetailView,
CreateView,
UpdateView,
DeleteView,
)
from accounting.models import Invoice
from accounting.views import gener... | jfoltan/VetSimplify | records/views.py | views.py | py | 14,316 | python | en | code | 0 | github-code | 13 |
42482686021 | # -*- coding: utf-8 -*-
from pathlib import Path
from typing import List, Optional, Dict, Any
import re
import json
from tqdm import tqdm
import copy
RAWDATA_PATH = Path("./data/train.txt")
TARGET_DIR = Path("./data/cgec")
class DataProcessor:
leading_dash_pattern = re.compile(r"^——(.*)")
def get_gec_samples_f... | Peter-Chou/cgec-initialized-with-plm | preprocess_data.py | preprocess_data.py | py | 2,478 | python | en | code | 3 | github-code | 13 |
23943165479 | import numpy as np
import pandas as pd
import re
def check_last_day(curr_year: int, curr_month: int, curr_day: int) -> bool:
"""
Checks if the specified day is the last day in the specified month.
Checks for 29 days during leap year (only years 1992 - 2020), otherwise 28 days for Feb.
:param curr_year... | changsteph/CITRUS-June2022 | aggregate_data.py | aggregate_data.py | py | 4,378 | python | en | code | 0 | github-code | 13 |
31428537020 | import sqlite3
def create_database(db_connection: sqlite3.Connection):
sql_list = [
"""
CREATE TABLE IF NOT EXISTS photo (
id STRING PRIMARY KEY,
file_path STRING
);
""",
"""
CREATE TABLE IF NOT EXISTS face (
... | Doka-NT/python-face-gallery | src/infrastructure/database.py | database.py | py | 1,177 | python | en | code | 0 | github-code | 13 |
41910816039 | import bpy
from mathutils import Vector, Euler, Matrix
from math import radians, degrees, sin, cos, atan2, sqrt, pi
def delete_meshes():
candidate_list = [item.name for item in bpy.data.objects if item.type == "MESH"]
# select mesh objects and remove them
for object_name in candidate_list:
bpy.dat... | dkobozev/quadropod | ik/ik.py | ik.py | py | 5,552 | python | en | code | 1 | github-code | 13 |
6998887758 | # encoding: utf-8
import http
import requests
from ...config import CxConfig
from ...auth import AuthenticationAPI
from ...exceptions.CxError import BadRequestError, NotFoundError, CxError
from .dto.customTasks import CxCustomTask
from .dto import CxLink
class CustomTasksAPI(object):
"""
REST API: custom ta... | lxj616/checkmarx-python-sdk | CheckmarxPythonSDK/CxRestAPISDK/sast/projects/CustomTasksAPI.py | CustomTasksAPI.py | py | 4,203 | python | en | code | null | github-code | 13 |
15527134748 | from .models import *
def get_classroom_list_summary(user_id, date, class_id):
user_profile = User.objects.get(id=user_id)
classroom_profile = classroom.objects.get(id=class_id)
single_classroom = classroomLists.objects.filter(lesson_classroom=classroom_profile, year=date).first()
class_name = class... | Class-Planit/class-planit | planit/get_students.py | get_students.py | py | 5,790 | python | en | code | 0 | github-code | 13 |
33001926091 | # editor.py: shader editor
#
# author: Antony Ducommun dit Boudry (nitro.tm@gmail.com)
# license: GPL
#
import io, re
from pathlib import Path
from PySide2.QtCore import Qt, Signal, Slot, QPoint, QSize
from PySide2.QtGui import QColor, QSyntaxHighlighter, QTextOption, QWindow
from PySide2.QtWidgets import (
QActio... | nitrotm/3dtagger | editor.py | editor.py | py | 8,240 | python | en | code | 1 | github-code | 13 |
19388764242 | """
We fit GPs to the full dataset, testing different models and kernels
"""
# Idea:
# Query new points twice + fit heteroskedastic noise to empirical data
import matplotlib as mpl
mpl.rcParams['pdf.fonttype'] = 42
from load_matlab import *
import numpy as np
import GPy
import matplotlib.pyplot as plt
import matplotli... | samlaf/GP-BCI | data_10ch/gp_full_1d.py | gp_full_1d.py | py | 16,245 | python | en | code | 1 | github-code | 13 |
6230866052 | import csv
from numpy import *
import scipy.cluster.vq as kmean
from nexus import Cluster, Geopoint
class Clump:
'''Plot centroid locations on a static Google Map.'''
def __init__(self):
self.clusters = []
self.header = []
def plot_centers(self, centroid_list):
print('\nThe c... | wegry/geocluster | clump.py | clump.py | py | 6,292 | python | en | code | 0 | github-code | 13 |
30102256735 | #!/usr/bin/python
from subprocess import Popen, PIPE, check_output
import argparse
import calendar
import os
import re
import time
import xml.etree.ElementTree as ET
parser = argparse.ArgumentParser(
description='Get OCSP production time for X-Road certificates.',
formatter_class=argparse.RawDescriptionHelpFo... | 1AndyCh/ria-eek | misc/ocsp_produced.py | ocsp_produced.py | py | 3,112 | python | en | code | 0 | github-code | 13 |
41161374164 | def age_assignment(*args, **kwargs):
people = {}
people_string = ''
for name in args:
people[name] = kwargs[name[0]]
people = dict(sorted(people.items(), key= lambda kvp: kvp[0]))
for name, age in people.items():
people_string += f"{name} is {age} years old.\n"
return people_stri... | lefcho/SoftUni | Python/SoftUni - Python Advanced/Functions Advanced/age_assignment.py | age_assignment.py | py | 441 | python | en | code | 0 | github-code | 13 |
37972287616 | import sys
from datetime import datetime
from PyQt6.QtWidgets import (
QApplication,QWidget,
QFormLayout,QPushButton,
QLineEdit,QMenuBar,
QMainWindow,QLabel,
QComboBox
)
from PyQt6.QtGui import QAction
from PyQt6.QtCore import Qt
# class for window
class MainWindow(QWidget):
def __i... | AbdulRehmanjr/python | APL/mid/q2.py | q2.py | py | 3,496 | python | en | code | 1 | github-code | 13 |
42117749772 |
import json
from types import new_class
from datetime import datetime
import re
import csv
from numpy import empty, number
import operator
import itertools
import reverse_geocoder as rg
import os
import pandas as pd
from geopy.geocoders import Nominatim
file_path=str(input("Please provide the path to the JSON file:... | spokenwebsites/ADP_Front | webapp/src/assets/js/viz3.geolocations.py | viz3.geolocations.py | py | 4,339 | python | en | code | 3 | github-code | 13 |
30176990310 | import numpy as np
import numpy.linalg as LA
import scipy
def logsig(x):
""" Compute the log-sigmoid function component-wise.
See http://fa.bianp.net/blog/2019/evaluate_logistic/ for more details.
logsig(x) = log(1/[1 + exp(-t)])
"""
out = np.zeros_like(x)
idx0 = x < ... | ABMOPT/ABM | src/workers/utils.py | utils.py | py | 2,437 | python | en | code | 0 | github-code | 13 |
17041413844 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayFundWalletOperationQueryModel(object):
def __init__(self):
self._biz_scene = None
self._biz_types = None
self._current_page = None
self._end_biz_dt = None
... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/AlipayFundWalletOperationQueryModel.py | AlipayFundWalletOperationQueryModel.py | py | 4,917 | python | en | code | 241 | github-code | 13 |
13514135206 | from ebcli.core.abstractcontroller import AbstractBaseController
from ebcli.resources.strings import strings
from ebcli.core import io
from ebcli.lib import elasticbeanstalk, aws
from botocore.compat import six
urllib = six.moves.urllib
class QuicklinkController(AbstractBaseController):
class Meta:
label ... | aws/aws-elastic-beanstalk-cli | ebcli/labs/quicklink.py | quicklink.py | py | 3,555 | python | en | code | 150 | github-code | 13 |
32014771409 | # -*- coding: utf-8 -*-
# @Author : dhawal1939
# @File : utils.py
import cv2
import math
import torch
import numpy as np
from numpy.random import uniform
def map_range(x, low=0, high=1):
return np.interp(x, [x.min(), x.max()], [low, high]).astype(x.dtype)
def get_antilog_01_vals(val):
# Color space conve... | dhawal1939/rot_equi | utils.py | utils.py | py | 1,048 | python | en | code | 0 | github-code | 13 |
11159279527 | from board.board import Board
def solve(board):
print("Solving.....")
return backtrack(board, 0, 0)
# procedure backtrack(c) is
# if reject(P, c) then return
# if accept(P, c) then output(P, c)
# s ← first(P, c)
# while s ≠ NULL do
# backtrack(s)
# s ← next(P, s)
def backtrack(board, curr_ro... | brendanbeck62/sudoku_solver | server/logic/solve.py | solve.py | py | 1,302 | python | en | code | 0 | github-code | 13 |
1152783397 | __version__ = '0.1.0'
import sys
import json
import time
# gridappsd-python module
from gridappsd import GridAPPSD, topics, DifferenceBuilder
from gridappsd.topics import simulation_input_topic
# global variables
gapps = None
sim_id = None
def _main():
global sim_id, gapps
if len(sys.argv)<3 or '-help' in... | GRIDAPPSD/gridappsd-state-estimator | state-estimator/sim_starter/sim_updater.py | sim_updater.py | py | 1,448 | python | en | code | 1 | github-code | 13 |
22732498701 | # 足立くんによるお馬さん予測シミュレーション
import math
import datetime
import re
import time
import locale
import tkinter as tk # for making Desktop Application
import numpy as np # for array calculation
import sympy as sp # for mathematical operation
import openpyxl # to use Excel from python
import django ... | KotaroHimeji/keiba | horsePrediction.py | horsePrediction.py | py | 3,198 | python | en | code | 0 | github-code | 13 |
73332219217 | """empty message
Revision ID: f8b90c51e27b
Revises: b499bd9608a5
Create Date: 2023-04-14 14:47:13.412965
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'f8b90c51e27b'
down_revision = 'b499bd9608a5'
branch_labels = None
depends_on = None
def upgrade():
# ... | apurv101/parcelini_backend | migrations/versions/f8b90c51e27b_.py | f8b90c51e27b_.py | py | 1,452 | python | en | code | 0 | github-code | 13 |
16747856638 |
from _setup import results_path
from tabulate import tabulate
import gridsearch
def format_tabel(mean, stddev, row_names, row_header, col_names, col_header, caption):
header = [
['', '', '\\multicolumn{%d}{c}{\\texttt{%s}}' % (len(col_names), col_header)],
['', ''] + list(map(str, col_names))
... | AndreasMadsen/course-42137 | code/plot/best_tables.py | best_tables.py | py | 2,474 | python | en | code | 7 | github-code | 13 |
25579140282 | # coding: utf-8
"""
For testing theBoolean-level reasoning engines in the parallel CDCL(T) SMT solving engine
"""
from arlib.tests import TestCase, main
# from ..theory import SMTLibTheorySolver, SMTLibPortfolioTheorySolver
from arlib.tests.grammar_gene import gen_cnf_numeric_clauses
from arlib.bool.pysat_solver impor... | ZJU-Automated-Reasoning-Group/arlib | arlib/tests/test_bool_engines.py | test_bool_engines.py | py | 957 | python | en | code | 6 | github-code | 13 |
1960092744 | from django.urls import path
from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
path('registration/', views.register, name='registration'),
path('logout/', views.logout_user, name='logout'),
path('login/', auth_views.LoginView.as_view(template_name='accounts/login.html... | kubix283/Blog_Public | blog/accounts/urls.py | urls.py | py | 508 | python | en | code | 0 | github-code | 13 |
8902603640 | import pandas as pd
data = pd.read_csv(r"E:\YD\git\learn\pandas_01\nato_phonetic_alphabet.csv")
NATO_ALPHABET = {row.letter : row.code for (index, row) in data.iterrows()}
# while True:
# word = input("Word for translate: ")
# # result = []
# # for i in word:
# # if i.upper() in NATO_ALPHABET:
# ... | foxtailer/learn | 100day_of_code/pandas_01/NATO_alphabet.py | NATO_alphabet.py | py | 870 | python | en | code | 0 | github-code | 13 |
3318575026 | from mode import Mode
class Operation:
"""
this class present an operation that need to be done to finish a job.
for every operation we will save its name(number), modes, ann all resource that all modes need.
"""
def __init__(self, number):
self.number = number
self.modes = []
... | danielifshitz/RSSP | code/job_operation.py | job_operation.py | py | 2,100 | python | en | code | 1 | github-code | 13 |
5473232936 | def merge_list(list1, list2):
merged_data="" #' '
j = len(list1)-1 # 8 -1 = 7
for i in range(len(list1)): #1 2 3
str1 = str2 = '' #
if list1[i]: #
str1 =list1[i] # app' list[5]
if list2[j]:
str2 = list2[j] #'le
... | SnehaShet22/TCET-B2 | DAY-7.py | DAY-7.py | py | 14,644 | python | en | code | 1 | github-code | 13 |
33168618590 | """Setuid backdoor handler
SYNOPSIS:
suidroot --create <SUIDROOT_BACKDOOR>
suidroot "<COMMAND>"
DESCRIPTION:
Provide a simple way to install persistent setuid(2)
backdoor from previously obtained root access.
SUIDROOT_BACKDOOR file should be carefully chosen to not
look suspicious. Our goal i... | nil0x42/phpsploit | plugins/system/suidroot/plugin.py | plugin.py | py | 4,838 | python | en | code | 2,044 | github-code | 50 |
39273401386 |
class Person:
def __init__(self, name):
self.name = name
class Bike:
def __init__(self, speeds, owner):
self.speed = speeds
self.owner = owner
self.color = "grey"
self._layers = 1
def set_color(self, new_color):
self._layers += 1
self.color = new... | Rick-and-morty/tic-tac-toe | day4_oop.py | day4_oop.py | py | 821 | python | en | code | 0 | github-code | 50 |
25125456678 | import pika
import json
import ssl
import os
import requests
from log.logger import Logger
from abc import ABC, abstractmethod
from db.db_operation import DBOperation
from common.password import get_password, get_password_by_auth_token
class BasePublisher(ABC):
def __init__(self, meta={}, logger=None):
... | kenshinsee/common | lib/mq/publisher.py | publisher.py | py | 5,695 | python | en | code | 0 | github-code | 50 |
41512481994 | # -*- coding: utf-8 -*-
"""
@author:XuMing(xuming624@qq.com)
@description:
This basic example loads a pre-trained model from the web and uses it get entities.
"""
import sys
sys.path.append('..')
from nerpy import NERModel
if __name__ == '__main__':
# BertSoftmax中文实体识别模型: NERModel("bert", "shibing624/bert4ner-ba... | shibing624/nerpy | examples/base_zh_demo.py | base_zh_demo.py | py | 1,259 | python | en | code | 84 | github-code | 50 |
27906932859 | """
Programme d'alignement de sequence par paires a partir d'embedding obtenus par des methodes basees sur des transformers
"""
#import-------------------------------------------------------------------------------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt... | Kainizim/alignement_transformers | alignement_transformers.py | alignement_transformers.py | py | 10,028 | python | fr | code | 0 | github-code | 50 |
73396392475 | import pytorch_lightning as pl
#import wandb #import if tracking is desired
from pytorch_lightning.loggers import WandbLogger
from pytorch_lightning import Trainer
from pytorch_lightning.callbacks import TQDMProgressBar
# Import custom modules
from data.cifar100 import CIFAR100DataModule
from vision_transformer.models... | curt-tigges/vit | train.py | train.py | py | 2,270 | python | en | code | 2 | github-code | 50 |
70301397595 | import datetime
import logging
import numbers
import time
from creme import (compose, feature_extraction, linear_model, metrics, optim,
preprocessing, stats, time_series)
from src.features.build_features import build_train_predict_features
def get_hour(x):
x['hour'] = x['date'].hour
retur... | LuisBlanche/StreamBikes | src/models/online_model.py | online_model.py | py | 3,466 | python | en | code | 2 | github-code | 50 |
11948645009 | import datetime
import enum
from dataclasses import dataclass
from dataclasses_json import dataclass_json
from option import Option, Underlying
class SwaptionType(enum.Enum):
Payer = 'Payer'
Receiver = 'Receiver'
class SettlementType(enum.Enum):
Cash = 'Cash'
Physical = 'Physical'
@dataclass
cla... | metahris/pypws | pypws/swaption.py | swaption.py | py | 751 | python | en | code | 2 | github-code | 50 |
11863735160 | """Словарь очень похож на список, но порядок элементов в нем не имеет значения и они
не выбираются смещением, таким как 0 и 1. Вместо этого для каждого значения вы
указываете связанный с ним уникальный ключ"""
d1 = { "Iphone": '13', 'Samsung': 'A15', 'Nokia': '3310'}
d2 = dict(name="Jack", lname="London", course = 3)... | abdumalikyaqub/python-practice | intro-py/dict.py | dict.py | py | 692 | python | ru | code | 0 | github-code | 50 |
38770201916 | from torchvision import datasets, transforms
from torch.utils.data import DataLoader
#
# class Cifar10_DataLoader(DataLoader):
# """
# MNIST data loading demo using BaseDataLoader
# """
# def __init__(self, data_dir, batch_size, shuffle=True, validation_split=0.0, num_workers=1, training=True):
#
# ... | hannie0615/paper-implement | CNN/data_loaders.py | data_loaders.py | py | 1,474 | python | en | code | 0 | github-code | 50 |
2331765924 | class BreadthFirstPaths:
def __init__(self, G, s):
self.marked = []
self.edgeTo = []
self.s = s
for i in range(G.v()):
self.marked.append(False)
self.edgeTo.append(-1)
self.bfs(G, s)
def bfs(self, G, s):
queue = []
self.marked[s] = True
queue.insert(0, s)
while len(queue) != 0:
v = queue.... | SenaSerefoglu/Algorithms | BreadthFirstSearch/bfp.py | bfp.py | py | 726 | python | en | code | 3 | github-code | 50 |
23654731462 | import numpy as np
import unittest
from load import *
from process_test_corpus import *
from utils import *
from viterbi import Viterbi
from hmm import HMM
import pickle
class TestViterbi(unittest.TestCase):
def setUp(self):
self.vocab = vocab
self.tag_counts = tag_counts
self.transi... | LTPhat/HMM-Viterbi-POS-Tagger | test_viterbi.py | test_viterbi.py | py | 11,346 | python | en | code | 0 | github-code | 50 |
73051478555 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
from collections imp... | AbramovAV/ml_engineer_interview_prep | coding_interview/leetcode_medium/path-sum-ii.py | path-sum-ii.py | py | 1,241 | python | en | code | 0 | github-code | 50 |
29256597281 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import itertools
import os
from lab.environments import LocalEnvironment, MaiaEnvironment
from downward.reports.compare import ComparativeReport
import common_setup
from common_setup import IssueConfig, IssueExperiment, RelativeScatterPlotReport
DIR = os.path.dirname... | aig-upf/automated-programming-framework | PLANNERS/fast-downward/experiments/issue693/v6-blind.py | v6-blind.py | py | 2,443 | python | en | code | 13 | github-code | 50 |
9901936916 | import time
starta = time.time()
import torch
import sys
import torch.distributions as tdist
print(time.time() - starta)
#start = torch.cuda.Event(enable_timing=True)
#end = torch.cuda.Event(enable_timing=True)
#start.record()
#end.record()
MS_TO_S = 1/1000
ma_eps = 1.0E-9
aqua_device = torch.device("cpu")
posterior_b... | uiuc-arc/aquasense | python_models/radar_query_dice.py | radar_query_dice.py | py | 3,686 | python | en | code | 0 | github-code | 50 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.