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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
43594129465 | import getopt
import os
import random
import re
import string
import sys
import jsonpickle
from model.contact import Contact
try:
opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of groups", "file"])
except getopt.GetoptError as err:
getopt.usage()
sys.exit(2)
n = 5
f = "data/contacts.json"
f... | xd2006/python_st | generator/contact.py | contact.py | py | 2,534 | python | en | code | 0 | github-code | 13 |
3889320392 | from models.voucher_type import VoucherType, db
# Get all VoucherTypes
def find_all():
return VoucherType.query.all()
# Get VoucherTypes by filtering
# By id
def find_by_id(id):
return VoucherType.query.filter_by(id=id).first()
# Insert data
def insert(json_data):
try:
voucherType = VoucherType.f... | NXTung1102000/InformationSystemIntegration | backend/repository/voucher_type_repo.py | voucher_type_repo.py | py | 866 | python | en | code | 0 | github-code | 13 |
24550411459 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 18 17:06:24 2020
Experiment code - temporal masking, blocked-design
intact, negated and scrambled faces with their phase scrambled mask.
4 durations
@author: jschuurmans
"""
#%% =====================================================================... | jpschuurmans/CtF_7T_experiment | exampleCodes/experimentCode.py | experimentCode.py | py | 23,519 | python | en | code | 1 | github-code | 13 |
678235219 | import cProfile, pstats
from BVP import BVP_solver
from PDEs import Grid, BoundaryCondition
def profile_BVP_solver(grid,bc_left,bc_right,q,D,u_guess=None):
# Create a cProfile.Profile object
pr = cProfile.Profile()
# Start profiling
pr.enable()
# Call the BVP_solver function
result = BVP_so... | MikeJohnson424/emat30008 | profile_BVP_solver.py | profile_BVP_solver.py | py | 833 | python | en | code | 0 | github-code | 13 |
17057271394 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class OpenPromoCamp(object):
def __init__(self):
self._camp_alias = None
self._camp_desc = None
self._camp_end_time = None
self._camp_name = None
self._camp_star... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/OpenPromoCamp.py | OpenPromoCamp.py | py | 3,453 | python | ro | code | 241 | github-code | 13 |
38924816615 | from typing import Optional, Dict, List
import pandas as pd
import pyarrow
from common.pandas.df_utils import concat, downsample_uniform
from featurizer.actors.cache_actor import get_cache_actor, create_cache_actor
from featurizer.calculator.calculator import build_feature_label_set_task_graph
from featurizer.calcula... | dirtyValera/svoe | featurizer/runner.py | runner.py | py | 5,865 | python | en | code | 12 | github-code | 13 |
43266985024 | from api.models import TaskList
from api.serializers import TaskListSerializer, TaskSerializer
from rest_framework.response import Response
from rest_framework.decorators import api_view
from django.shortcuts import get_object_or_404
@api_view(['GET', 'POST'])
def task_lists_view(request):
if request.method == 'G... | saltanatnareshova/webdev2019-1 | Week13/todo_back/api/views/fbv.py | fbv.py | py | 1,909 | python | en | code | 0 | github-code | 13 |
4714375773 | import random
import heapq
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
from matplotlib import animation
def party_dijkstra(G, source, target=None, cutoff=None, weight='weight'):
"""Compute shortest paths and lengths in a weighted graph G of multiple parties
Uses aa modification o... | ruffsl/CS6601P1 | Code/Python/ccrpTools.py | ccrpTools.py | py | 14,893 | python | en | code | 5 | github-code | 13 |
22842280397 | import numpy as np
import torch
import rawpy
from torch.utils.data import Dataset
import random
from PIL import Image
from scipy import ndimage
from os.path import join
patch_size = 512
class LSID(Dataset):
def __init__(self, data_path, subset, patch_size=512, max_nr_images_per_gt_and_shutter=100):
self.... | NoorZia/LSID | dataset.py | dataset.py | py | 4,642 | python | en | code | 1 | github-code | 13 |
29839414242 | import sys
import encodings
import encodings.aliases
import re
import collections
from builtins import str as _builtin_str
import functools
CHAR_MAX = 127
LC_ALL = 6
LC_COLLATE = 3
LC_CTYPE = 0
LC_MESSAGES = 5
LC_MONETARY = 4
LC_NUMERIC = 1
LC_TIME = 2
def getUserLocale():
# get system localeconv and reset system... | gplehmann/Arelle | arelle/Locale.py | Locale.py | py | 7,428 | python | en | code | null | github-code | 13 |
4224376224 | import json
import time
import random
from instagrapi import Client
cl = Client()
cl.login('USERNAME','PASSWORD')
json.dump(
cl.get_settings(),
open('session.json', 'w')
)
# cl = Client(json.load(open('settings.json')))
print('Login Successfully...')
media = cl.hashtag_medias_recent('python', amount=10) # ... | EsmaeiliSina/instabot | app.py | app.py | py | 794 | python | en | code | 2 | github-code | 13 |
14415174725 | import pygame
import math
from pygame.math import Vector2 as vec
from settings import *
from main_test import *
from ghost import *
# Ghost 클래스 상속
class PinkGhost(Ghost):
def __init__(self, Game, pos, speed):
self.Game = Game
self.grid_pos = pos
self.pos = [pos.x, pos.y]
self.pix_po... | KKIMIs/AI-Pacman | GamePacman/pink_ghost.py | pink_ghost.py | py | 4,036 | python | en | code | 0 | github-code | 13 |
35905259419 | import numpy as np
import pandas as pd
import requests
import json
from datetime import date, timedelta, datetime
import time
import sqlite3
from sqlite3 import Error
today = date.today()
tdelta = timedelta(days=7)
one_week_date = today + tdelta
# day_time = datetime.today().strftime('%A')
conn = sqlite3.connect('dat... | ashabooga/robodojo | get_matches.py | get_matches.py | py | 11,640 | python | en | code | 0 | github-code | 13 |
73648316177 | import config
import mysql.connector
yhteys = mysql.connector.connect(
host='127.0.0.1',
port=3306,
database='flight_game',
user=config.user,
password=config.password,
autocommit=True
)
def hae_maa_koodilla(iso):
sql = f"SELECT TYPE, COUNT(*) FROM airpor... | Xanp0/NoelS_Ohjelmisto1 | moduuli_08/teht2_Maakoodi.py | teht2_Maakoodi.py | py | 772 | python | fi | code | 0 | github-code | 13 |
2312676422 | #! python3
# mclip.py - Dependendo da palavra chave dada, é copiada uma mensagem para o clipboard
TEXT = {'agree': """Yes, I agree. That sounds fine to me.""",
'busy': """Sorry, can we do this later this week or next week?""",
'upsell': """Would you consider making this a monthly donation?"""}
... | claudioLamelas/projects | python/mclip.py | mclip.py | py | 989 | python | pt | code | 0 | github-code | 13 |
9077690360 | # 수도코드
# 1. 총합 가격부터 개수와 각 물건의 가격과 개수를 입력받는다.
# 2. 조건문을 사용해 물건의 개수*가격을 합한 금액이 총합과 일치하는지 판단한다.
total = int(input())
# 영수증의 총 금액
tc = int(input())
# 물건의 종류의 수
sum = 0
# 각 물건들을 총 합한 금액
for i in range(tc):
a, b = map(int, input().split())
sum += a*b
# 물건 종류의 수만큼 각각 금액과 수량을 입력받고 sum에 더해준다.
if total == ... | Mins00oo/PythonStudy_CT | BACKJOON/Python/B5/B5_25304_영수증.py | B5_25304_영수증.py | py | 664 | python | ko | code | 0 | github-code | 13 |
73917236819 | from globs import *
"""
The first two consecutive numbers to have two distinct prime factors are:
14 = 2 × 7
15 = 3 × 5
The first three consecutive numbers to have three distinct prime factors are:
644 = 2² × 7 × 23
645 = 3 × 5 × 43
646 = 2 × 17 × 19.
Find the first four... | gavinmcguigan/gav_euler_challenge_100 | Problem_47/DistinctPrimesFactors.py | DistinctPrimesFactors.py | py | 917 | python | en | code | 1 | github-code | 13 |
16178961995 | from __future__ import print_function, division
import os
import numpy as np
from mdtraj.core.topology import Topology
from mdtraj.utils import cast_indices, in_units_of, open_maybe_zipped
from mdtraj.formats.registry import FormatRegistry
from mdtraj.utils.unitcell import lengths_and_angles_to_box_vectors, box_vectors... | mdtraj/mdtraj | mdtraj/formats/pdbx.py | pdbx.py | py | 10,601 | python | en | code | 505 | github-code | 13 |
34389914982 | # Python program for two pointers technique
# Find if there is a pair [A0..N-1] with given sum
def isPairSum(A, N, X):
# First pointer
i = 0
# Second pointer
j = N - 1
while (i < j):
# If there is a match
if (A[i] + A[j] == X):
return True
... | NijazK/Two_Pointers_LeetCode | isPairSum.py | isPairSum.py | py | 801 | python | en | code | 0 | github-code | 13 |
10747206392 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import numpy as np
import matplotlib.pyplot as pl
from matplotlib.gridspec import GridSpec, GridSpecFromSubplotSpec
from forcepho.postprocess import Samples, Residuals
from prospect.plotting.corner import allcorner, scatter, marginal, corner, get_spans, pr... | bd-j/forcepho | demo/demo_snr/single_plot.py | single_plot.py | py | 4,429 | python | en | code | 13 | github-code | 13 |
23235773597 | class Cake:
def __init__(self,name,kind,taste,additives,filling):
self.name = name
self.kind = kind
self.taste = taste
self.additives = additives
self.filling = filling
cake1 = Cake('apple pie','cake','apple',['apple'],'')
cake2 = Cake('strawberry pie','cake','strawberry',['... | rzemien94/Python_courses | PythonSrednioZaawansowany/lesson82classess.py | lesson82classess.py | py | 522 | python | en | code | 0 | github-code | 13 |
5718606576 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
__author__ = 'geecode@outlook.com'
__version__ = '1.0'
import sys
import math
from io import StringIO
import token
import tokenize
import argparse
import json
class CosineDiff(object):
@staticmethod
def __token_frequency(source):
"""
get valid to... | qiuxfeng1985/geecode-sublime-plugin | geecode_similar.py | geecode_similar.py | py | 5,034 | python | en | code | 0 | github-code | 13 |
70838629459 | import tensorflow as tf
class IOU(tf.keras.metrics.Metric):
def __init__(self, **kwargs):
super(IOU, self).__init__(**kwargs)
self.iou = self.add_weight(name="iou", initializer="zeros")
self.total_iou = self.add_weight(name="total_iou", initializer="zeros")
self.num_ex = self.add_w... | DeepanChakravarthiPadmanabhan/object_localization_pets | localize_pets/loss_metric/iou.py | iou.py | py | 1,640 | python | en | code | 0 | github-code | 13 |
37170479213 | from itertools import takewhile
cCLnv=len
cCLnV=float
cCLnQ=int
cCLni=range
cCLnK=enumerate
cCLnR=list
cCLnr=max
cCLnF=min
from typing import NamedTuple
from p2.src.algorithm_api import Algorithm
from p2.src.data_api import Instance,Solution,Schedule,Task
cCLnG=1
cCLnA=0
def cCLne(cCLnu,cCLnE,cCLnP,cCLnb,cCLnJ,enumerat... | KamilPiechowiak/ptsz | p2/src/id136715/algorithm.py | algorithm.py | py | 1,913 | python | en | code | 0 | github-code | 13 |
14739268805 | #Uses python3
import sys
def dfs(adj, used, order, x):
#write your code here
used[x] = True
for w in adj[x]:
if not used[w]:
dfs(adj, used, order, w)
return v
def toposort(adj):
used = [False] * len(adj) #[0] * len(adj)
order = []
for x in adj:
w = dfs(adj, us... | price-dj/Algorithms_On_Graphs | Week2/workspace/pset2/toposortv5.py | toposortv5.py | py | 853 | python | en | code | 0 | github-code | 13 |
23249081116 | #!/usr/bin/env python3
# encoding: utf-8
import random
from typing import List
class Solution:
def _pivot(self, nums: List[int], start: int, end: int) -> int:
# Put nums[start] to its right place. Keep the smaller (or equal) numbers
# on its left and the bigger numbers on the right. Return its in... | misaka-10032/leetcode | coding/00215-kth-largest-element-in-array/solution.py | solution.py | py | 1,529 | python | en | code | 1 | github-code | 13 |
2487537375 | import spaco as spaco
import importlib
importlib.reload(spaco)
import numpy as np
import pandas as pd
import copy
def dataGen(I, T, J, q, rate, s=3, K0 = 3, SNR1 = 1.0, SNR2 = 3.0):
Phi0 = np.zeros((T, K0))
Phi0[:,0] = 1.0
Phi0[:,1] = np.arange(T)/T
Phi0[:, 1] = np.sqrt(1-Phi0[:,1]**2)
Phi0[:,2] = (... | LeyingGuan/SPACO | tests/example_spaco_RankSelection.py | example_spaco_RankSelection.py | py | 2,557 | python | en | code | 0 | github-code | 13 |
4534334079 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 11 13:26:13 2021
@author: asus
"""
import numpy as np
import matplotlib.pyplot as plt
N = 256
Re = 400
title_u = "Re=" + str(Re) + "_N=" + str(N) + "_u.txt"
title_v = "Re=" + str(Re) + "_N=" + str(N) + "_v.txt"
u = np.loadtxt(title_u)
v = np.loadtxt(title... | sbakkerm/Lid-Driven-Cavity | LBM/part_b_lineplots.py | part_b_lineplots.py | py | 1,375 | python | en | code | 3 | github-code | 13 |
14802809103 | import tkinter
from tkinter import filedialog, CENTER, NW
from PIL import ImageTk, Image
from gender_recognition_ai import gendernn
root = tkinter.Tk()
root.geometry("600x400+0+0")
root.title("Gender Recognition AI v1.0")
root.iconbitmap("gender.ico")
def open_picture(path="bg.png"):
width = 600
img = Imag... | AnakinTrotter/gender-recognition-ai | gender_recognition_ai/GUI.py | GUI.py | py | 1,650 | python | en | code | 4 | github-code | 13 |
3597331657 | import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize
# Определение функции Матиоша
def matyas(x):
return 0.26 * (x[0] ** 2 + x[1] ** 2) - 0.48 * x[0] * x[1]
# Функция для отслеживания значений функции в каждой итерации
def track_convergence(result):
values = []
for iterat... | tigersing/dmytro.kocherzhenko | practice03.py | practice03.py | py | 4,046 | python | ru | code | 0 | github-code | 13 |
22478705465 | import os
import shutil
import random
from PIL import Image
from collections import Counter
def statistic_images(path):
'''
统计图片size
'''
trainset = os.listdir(path)
result = []
for filename in trainset:
image = Image.open(path+"/"+filename)
result.append(image.size)
imag... | NICE-FUTURE/predict-gender-and-age-from-camera | data/utils.py | utils.py | py | 4,306 | python | en | code | 33 | github-code | 13 |
16808508174 | import sys
from collections import namedtuple
from hypothesis.strategies import (
binary,
booleans,
builds,
complex_numbers,
decimals,
dictionaries,
fixed_dictionaries,
floats,
fractions,
frozensets,
integers,
just,
lists,
none,
one_of,
randoms,
recur... | HypothesisWorks/hypothesis | hypothesis-python/tests/common/__init__.py | __init__.py | py | 2,369 | python | en | code | 7,035 | github-code | 13 |
17922281055 | import os
import pandas as pd
from pyMetricBenchmark.matplot import boxplot, liniendiagramm
from pyMetricBenchmark.matplot import balkenplot
from pyMetricBenchmark.datei import download
from pyMetricBenchmark.fatjar import subfatjar
# Funktionen um die Daten der Performace csv in eigenständige Dataframm zu ändern
# I... | skyfly18/pyMetricBenchmark | src/pyMetricBenchmark/benchmarkGroup5.py | benchmarkGroup5.py | py | 14,815 | python | de | code | 0 | github-code | 13 |
1902900652 | import cocos
from math import sin,cos,radians, atan2, pi, degrees
import pyglet
from cocos.actions import *
from time import sleep
from time import sleep
import threading
from classchar import Char
import cocos.collision_model as cm
import cocos.euclid as eu
from cocos.scenes.transitions import *
from random import ran... | silago/gametest | classman.py | classman.py | py | 3,136 | python | en | code | 1 | github-code | 13 |
6584767835 | # Input data split indexes.
IP_ADDR = 0
REMOTE_USER = 1
TIME_LOCAL = 2
HTTP_METHOD = 3
RESOURCE_URL = 4
HTTP_VERSION = 5
STATUS = 6
BYTES_SENT = 7
HTTP_REFERER = 8
USER_AGENT = 9
def parse_line(line):
"""
Parses the raw log string. Return a tuple with ordered
indexes. Use above indexes to access them.
... | yasinmiran/big-data-gcw | utils/common.py | common.py | py | 781 | python | en | code | 1 | github-code | 13 |
42095167313 | import os
import spotipy
import json
import calendar
import datetime
from dotenv import load_dotenv
import pytz
def spotipy_token(scope, username):
env_path = r'D:/Users/john/Documents/python_files/SpotifyAPI/.env'
project_folder = os.path.expanduser(env_path) # adjust as appropriate
load_dotenv(os.path.... | bonjohh/SpotifyAPI | create_new_music_playlist/create_new_music_playlist.py | create_new_music_playlist.py | py | 6,597 | python | en | code | 0 | github-code | 13 |
559436834 | #!/bin/python3
import math
import os
import random
import re
import sys
def primality(n):
if n==1:
return "Not prime"
elif n==2:
return "Prime"
elif n%2==0:
return "Not prime"
else:
f=math.ceil(math.sqrt(n))
for i in range(3,f+1,2):
if n%i==0:
... | Quasar0007/Competitive_Programming | Primality.py | Primality.py | py | 637 | python | en | code | 0 | github-code | 13 |
35920431023 | """
Project:
This program is use to read table data from a pdf file.The create_folder function will create a folder name called'csv'
in the current working directory.
Author: <Hashimabdulla> <hashimabdulla69@gmail.com> , April 18 2020
Version: 0.1
Module: Pdf table data extractor.
"""
import os
import shutil
import ca... | sandyiswell/covid19Kerala | pdf_tabledata_into_csv.py | pdf_tabledata_into_csv.py | py | 1,215 | python | en | code | 5 | github-code | 13 |
21690505687 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('mandats', '__first__'),
]
operations = [
migrations.CreateModel(
name='VueFederation',
fields=[
... | Brachamul/elan-democrate | datascope/migrations/0001_initial.py | 0001_initial.py | py | 979 | python | fr | code | 2 | github-code | 13 |
21264105816 | from collections import defaultdict
import heapq
from typing import List
class Solution:
def build_adjList(self, edges, succProb):
# undirect graph
adjList = defaultdict(list)
for i in range(len(edges)):
u, v, prob = edges[i][0], edges[i][1], succProb[i]
adjList[u].a... | sundaycat/Leetcode-Practice | solution/1514. path-with-maximum-probability.py | 1514. path-with-maximum-probability.py | py | 1,347 | python | en | code | 0 | github-code | 13 |
37995738928 | def addHSG2VertexReconstruction( d3pdalg,
quadruplet_key = "QuadrupletCandidates",
vertex_key = "QuadrupletVertexCandidates",
electron_target = "el_",
muid_target = "mu_muid_",
... | rushioda/PIXELVALID_athena | athena/PhysicsAnalysis/D3PDMaker/HiggsD3PDMaker/python/HSG2VertexReconstruction.py | HSG2VertexReconstruction.py | py | 1,482 | python | en | code | 1 | github-code | 13 |
39814383480 | """Mass-balance models"""
# Built ins
# External libs
import numpy as np
import pandas as pd
import netCDF4
from scipy.interpolate import interp1d
from scipy import optimize as optimization
# Locals
import oggm.cfg as cfg
from oggm.cfg import SEC_IN_YEAR, SEC_IN_MONTH
from oggm.utils import (SuperclassMeta, lazy_proper... | Chris35Wills/oggm | oggm/core/massbalance.py | massbalance.py | py | 19,317 | python | en | code | null | github-code | 13 |
39984916026 | from django.http import HttpResponse
import json
# pylint: disable=attribute-defined-outside-init
class JSONMixin(object):
def dispatch(self, request, *args, **kwargs):
# Try to dispatch to the right method; if a method doesn't exist,
# defer to the error handler. Also defer to the error handler ... | TelemarkAlpint/slingsby | slingsby/general/mixins.py | mixins.py | py | 1,200 | python | en | code | 3 | github-code | 13 |
23442005224 | import torch
import transforms as T
from pollination_model import get_model_instance_segmentation
from PIL import Image
def get_transform(train):
transforms = []
transforms.append(T.ToTensor())
if train:
transforms.append(T.RandomHorizontalFlip(0.5))
return T.Compose(transforms)
def main(pat... | a7med12345/Pollination_project | test.py | test.py | py | 1,315 | python | en | code | 1 | github-code | 13 |
786844052 | # To Plot and analyze different results obtained by the model
import os
import matplotlib.pyplot as plt
import pickle
import numpy as np
from utils import provide_shuffle_idx
from io_args import args
pkl_filename = args.gt_pkl_filename
gt_labels = np.squeeze(pickle.load(open(pkl_filename, 'rb')))
pred_labels = np.squ... | ashar6194/velo_from_video | rough_plots.py | rough_plots.py | py | 1,629 | python | en | code | 0 | github-code | 13 |
13317913063 | from typing import Callable, Union
import operator
Operand = Union[str, int]
Register = str
Position = int
Registers = dict[Register, int]
Modification = Callable[[Registers, Position, Operand, Operand], Position]
def modify_register(modification: Callable[[int, int], int]) -> Modification:
def apply_modificatio... | takemyoxygen/advent-of-code | 2017/common/registers.py | registers.py | py | 1,609 | python | en | code | 1 | github-code | 13 |
4923125156 | import numpy
#Global Variables
ciphertext = ""
keymatrix = []
plaintextmatrix = []
ciphertextmatrix = []
#Function to calculate multiplicative inverse
def multiplicativemodinverse(base):
for x in range(1, 26):
if (((base%26) * (x%26)) % 26 == 1):
return x
return -1
def getkeymatrix (... | snutesh/Cryptography_and_Computer_Security | Assignment_1/HillCipher_Decryption2.py | HillCipher_Decryption2.py | py | 3,452 | python | en | code | 0 | github-code | 13 |
44000658211 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 10 16:49:09 2016
@author: Zhian Wang
GWID: G33419803
Analyzing sereal data files by puting them into a dataframe,
compute the total births, seclect top 5 names, plot a graph, etc.
"""
import time
import pandas as pd
def getData():
"""
Reads multiple files and ... | zhianwang/DNSC-6211-Programming_for_Business_Analytics | Assignment1/A01_G33419803.py | A01_G33419803.py | py | 7,934 | python | en | code | 0 | github-code | 13 |
43006383296 | from copy import copy
def merge_sort(numbers):
copy_numbers = copy(numbers)
swap_count = m_sort(copy_numbers, [None] * len(numbers), 0, len(numbers)-1)
print (swap_count)
return copy_numbers
def m_sort(numbers, temp, left, right):
if left >= right:
temp[left] = numbers[left] ... | atiq1589/algorithms | python/merge_sort.py | merge_sort.py | py | 1,991 | python | en | code | 0 | github-code | 13 |
20101425942 | import os
import shutil
from PIL import Image, ImageStat
import PIL
import glob
import hashlib
def validate_images(input_dir: str, output_dir: str, log_file: str, formatter: str = "07d"):
log_file = log_file+".txt"
input_dir = os.path.abspath(input_dir)
if not os.path.isdir(input_dir):
raise Value... | FloGr1234/Python_II | Unit_1/a1_ex2.py | a1_ex2.py | py | 3,535 | python | en | code | 0 | github-code | 13 |
16013147700 | from PyOpenGL.line import LineDDA, LineBres
# from PyOpenGL.curve import Circle, Ellipse
if __name__ == '__main__':
xa, ya, xb, yb = tuple(map(int, input('Enter 2 end points: ').strip().split()))
# lineDDA = LineDDA(xa, ya, xb, yb)
# lineDDA.draw()
lineBres = LineBres(xa, ya, xb, yb)
lineBres.draw... | sagar-spkt/Learning | main.py | main.py | py | 680 | python | en | code | 0 | github-code | 13 |
31154391159 | from rest_framework import viewsets, response, status
from trackangle.place.api.v1.serializers import PlaceSerializer, CommentSerializer, BudgetSerializer, RatingSerializer
from trackangle.route.api.v1.serializers import RouteSerializer
from trackangle.route.models import RouteHasPlaces
from trackangle.place.models im... | trackangle/trackangle-angular | trackangle/place/api/v1/views.py | views.py | py | 3,687 | python | en | code | 0 | github-code | 13 |
26062065223 | from typing import Dict, Tuple
import pytest
import torch
from torch import nn
import merlin.models.torch as mm
from merlin.models.torch import link
from merlin.models.torch.batch import Batch
from merlin.models.torch.block import Block, ParallelBlock, get_pre, set_pre
from merlin.models.torch.container import BlockC... | EJHortala/models-1 | tests/unit/torch/test_block.py | test_block.py | py | 8,439 | python | en | code | null | github-code | 13 |
6791800798 | # ======================================================================================================================
# =========================== Définit et stocke les informations des environnements
class Biome:
def __init__(
self,
biome_id: int,
name: str,
mobs... | Dinoxel/tobias_game | old_code/game_data.py | game_data.py | py | 1,487 | python | fr | code | 0 | github-code | 13 |
35806175962 | from Point2D import *
from math import sin, cos
from bazier import vec2d
class Missile:
def __init__(self,x ,y, rad, player):
self.position = vec2d(x, y)
self.rad = rad
self.player = player
def move(self, x, y):
self.position.y += y
self.position.x += x
de... | AlexVestin/GameJam | Missile.py | Missile.py | py | 426 | python | en | code | 0 | github-code | 13 |
7828564566 | '''
===============================================================================
-- Author: Hamid Doostmohammadi, Azadeh Nazemi
-- Create date: 28/10/2020
-- Description: This code is for skewing or deskewing using perspective
transform based on having 4 coordinate values to address them. ... | HamidDoost/basic-image-processing-concepts | skewOrDeskewTransform.py | skewOrDeskewTransform.py | py | 2,720 | python | en | code | 0 | github-code | 13 |
72106319699 | ## return two primes a and b whose sum is equal to given even number
def get_primes(num):
lp = [0]*(num+1) ## to store least prime divisors
primes = []
for val in range(2,num+1):
if not lp[val]:
lp[val] = val ## least divisor of prime is the number itself (ignoring 1)
prime... | JARVVVIS/ds_algo_practice | gfg/goldbach.py | goldbach.py | py | 787 | python | en | code | 0 | github-code | 13 |
74638433296 | #Importing
from selenium import webdriver
from selenium.webdriver.common.by import By
from bs4 import BeautifulSoup
import time
import pandas as pd
import requests
import csv
#Assigning the value of the constant
START_URL = "https://en.wikipedia.org/wiki/List_of_brightest_stars_and_other_record_stars"
brows... | CodingAkshita/webscraping2 | scraper.py | scraper.py | py | 3,168 | python | en | code | 0 | github-code | 13 |
1338942154 | from socket import *
import findDog as FD
import dog_bowl as bowl
import user_setting as usr
from gpiozero import LED
from time import sleep
flag = False
_led = LED(17)
while True:
#안드로이드 앱과 통신
clientSocket = socket(AF_INET, SOCK_STREAM)
ADDR = (usr.Mobile,5050)
clientSocket.connect(ADDR)
print("conne... | god102104/oh_spaghetti | client_socket.py | client_socket.py | py | 1,055 | python | en | code | 0 | github-code | 13 |
65778793 | import numpy as np
import math
"""
以三硬币模型作为最简单的模拟
"""
class EM:
def __init__(self, prob):
self.pro_A, self.pro_B, self.pro_C = prob
# e_step
def pmf(self, i,data):
pro_1 = self.pro_A * math.pow(self.pro_B, data[i]) * math.pow((1 - self.pro_B), 1 - data[i])
pro_2 = (1 - self.pro_A) ... | HitAgain/Machine-Learning-practice | EM/EM.py | EM.py | py | 1,487 | python | en | code | 2 | github-code | 13 |
2791633720 | #!/usr/bin/python3
import gi
from pathlib import Path
gi.require_version('Gtk', '3.0')
from gi.repository import GLib, Gtk
ROOT = Path( __file__ ).parent.absolute()
try:
gi.require_version('AyatanaAppIndicator3', '0.1')
from gi.repository import AyatanaAppIndicator3 as AppIndicator
except (ImportError, Value... | nE0sIghT/appindicator-testcase | testcase.py | testcase.py | py | 1,745 | python | en | code | 0 | github-code | 13 |
28252066853 | from django.shortcuts import render,redirect
from django.views import View
from .forms import RegisterForm , LoginForm , ImageForm
from django.contrib.auth import authenticate,login,logout
from .models import CategoryModel,ImageModel
from django.contrib import messages
from django.core.files.storage import FileSyste... | Apeksha2311/LeafDetective | PlantDiseaseApp/views.py | views.py | py | 5,358 | python | en | code | 0 | github-code | 13 |
37410142069 | from functools import reduce
from itertools import product
from random import random
import cv2 as cv
import numpy as np
from scipy import ndimage
from data import uint
class Augmentor:
def __init__(self,
rotation_rng=(-20, 20),
g_shift_x_rng=(-10, 10),
g_shift... | pmikolajczyk41/retina-matcher | data/augmentor.py | augmentor.py | py | 3,317 | python | en | code | 0 | github-code | 13 |
42659464564 | str = input('Give the string to encrypt\n')
key = int(input('Give the key for encryption\n'))
def enc(c, key) :
if c.islower() :
return chr((ord(c) - 97 + key)%26 + 97)
return chr((ord(c) - 65 + key)%26 + 65)
def dec(c, key) :
if c.islower() :
return chr((ord(c) - 97 - key + 26)%26 + 97)
... | AatirNadim/Socket-Programming | substitution_cipher/no_socket.py | no_socket.py | py | 727 | python | en | code | 0 | github-code | 13 |
11721024053 | import telebot
from telebot import types
from data import langs, menu, translations # noqa
from settings import DEBUG, managers, token # noqa
# todo
# /тейкэвей добавить ссылку на мозогао
# При выборе доставки спросить локацию
# При выборе PhonePe вернуть ссылку для оплаты (с суммой?)
# При заказе - повторить спис... | kamucho-ru/rest_bot | bot.py | bot.py | py | 23,237 | python | en | code | 0 | github-code | 13 |
24844423188 | from typing import List, Tuple
from abcurve import AugmentedBondingCurve
from collections import namedtuple
from utils import attrs
import config
def vesting_curve(day: int, cliff_days: int, halflife_days: float) -> float:
"""
The vesting curve includes the flat cliff, and the halflife curve where tokens are ... | commons-stack/commons-simulator | simulation/hatch.py | hatch.py | py | 7,835 | python | en | code | 32 | github-code | 13 |
4531859367 | import csv
import sys
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
TEST_SIZE = 0.4
def main():
# Check command-line arguments
if len(sys.argv) != 2:
sys.exit("Usage: python shopping.py data")
# Load data from spreadsheet and split int... | yadavjp75/shoppingCS50 | shopping.py | shopping.py | py | 5,913 | python | en | code | 0 | github-code | 13 |
21326088885 | from requests_html import HTMLSession
import csv
import datetime
import sqlite3
#connect to/create database
conn = sqlite3.connect('amztracker.db')
c = conn.cursor()
#only create the table once, then comment out or delete the line
#c.execute('''CREATE TABLE prices(date DATE, asin TEXT, price FLOAT, title TEXT)''')
#... | jhnwr/amazon-price-tracker | amzpricers.py | amzpricers.py | py | 1,154 | python | en | code | 11 | github-code | 13 |
74847606417 | def falling(n, k):
"""Compute the falling factorial of n to depth k.
>>> falling(6, 3) # 6 * 5 * 4
120
>>> falling(4, 3) # 4 * 3 * 2
24
>>> falling(4, 1) # 4
4
>>> falling(4, 0)
1
"""
sum = 1
while(k>0):
sum *= n
k -= 1
n -= 1
return sum
... | kiroitorat/CS61A | lab/lab01/lab01.py | lab01.py | py | 1,383 | python | en | code | 0 | github-code | 13 |
23052557590 | from lift import Elevator
elevator_1 = Elevator("OTIS")
elevator_2 = Elevator("PHILLIPS")
# Везем человека в лифте под именем OTIS
elevator_1.lift()
# Везем двоих человек в лифте под именем PHILLIPS
elevator_2.lift()
elevator_2.lift()
# Получаем информацию по лифту под именем OTIS
elevator_1.info()
# Получаем информа... | nvovk/python | OOP/0 - Lift (example)/index.py | index.py | py | 498 | python | ru | code | 0 | github-code | 13 |
17881982262 | import sys
import clipboard
import json
SAVED_DATA = "clipboard.json"
def save_items(filepath, data):
with open(filepath, "w") as f:
json.dump(data, f)
#save_items("clipboard.json", {"Data" : "value"})
def load_items(filepath):
try:
with open(filepath, "r") as f:
data = json.load... | Mithiran-coder/My_Python_programs | multiclipboard.py | multiclipboard.py | py | 1,096 | python | en | code | 0 | github-code | 13 |
72070992339 | # -*- coding: utf-8 -*-
"""
Created on Fri Dec 11 12:12:13 2020
@author: dakar
"""
#%%
import warnings
import random
from copy import copy, deepcopy
import matplotlib.pyplot as plt
import networkx as nx
from tsp_heuristics.io.read_data import make_tsp
from tsp_heuristics.sol_generators import random_tour_list, order... | cookesd/tsp_heuristics | tsp_heuristics/classes/tsp.py | tsp.py | py | 29,476 | python | en | code | 0 | github-code | 13 |
13325017357 | import os
import sys
from setuptools import setup, find_packages
os.chdir(os.path.dirname(os.path.realpath(__file__)))
VERSION_PATH = os.path.join("mudlink", "VERSION.txt")
OS_WINDOWS = os.name == "nt"
def get_requirements():
"""
To update the requirements for Shinma, edit the requirements.txt file.
"""... | volundmush/mudlink-python | setup.py | setup.py | py | 2,108 | python | en | code | 1 | github-code | 13 |
23632804232 | import re
from collections import deque
# operands, operators = [], []
print('Reverse Polish Notation\n')
expression = input("Enter a mathematical expression :\n").split()
print(expression)
# operands = [re.findall(r'\d+', expression)]
# operators = [re.findall(r'\D+', expression)]
#function to evalute the first ope... | MicroClub-USTHB/python-language | Math_level3/reverse_polish_notation/rpn.py | rpn.py | py | 837 | python | en | code | 2 | github-code | 13 |
327359771 | import math
def compute_coords(index):
next_sqrt = 2 * math.ceil(0.5 * (index**0.5 - 1)) + 1
next_bottom_right = (next_sqrt - 1) // 2
coords = [next_bottom_right, next_bottom_right]
diff = next_sqrt**2 - index
for sign in [-1, 1]:
for j in [0, 1]:
delta = min(diff, next_sqrt-1... | grey-area/advent-of-code-2017 | day03/part1.py | part1.py | py | 473 | python | en | code | 0 | github-code | 13 |
14412202460 | # This file is part of Korman.
#
# Korman is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Korman is distributed i... | H-uru/korman | korman/plasma_launcher.py | plasma_launcher.py | py | 8,579 | python | en | code | 31 | github-code | 13 |
30360281637 | from django.db import models
from django.contrib.auth.models import AbstractUser
USER = 'user'
ADMIN = 'admin'
MODERATOR = 'moderator'
ROLES_CHOICES = {
(USER, 'Пользователь'),
(ADMIN, 'Администратор'),
(MODERATOR, 'Модератор'),
}
class User(AbstractUser):
username = models.CharField(
max_l... | denchur/GroupProj | api_yamdb/users/models.py | models.py | py | 1,241 | python | en | code | 0 | github-code | 13 |
74514483858 | '''
SẮP XẾP THEO TỔNG CHỮ SỐ
Cho dãy số A[] có N phần tử đều là các số nguyên dương, không quá 6 chữ số.
Hãy sắp xếp dãy số theo tổng chữ số tăng dần. Nếu tổng chữ số bằng nhau thì số nào nhỏ hơn sẽ viết trước.
Input
Dòng đầu ghi số bộ test (không quá 10)
Mỗi bộ test gồm 2 dòng:
Dòng đầu là số N (N < 100)
Dòng thứ 2 ... | cuongdh1603/Python-Basic | PY02023.py | PY02023.py | py | 978 | python | vi | code | 0 | github-code | 13 |
4790806748 | from bin.scraper import Omni
if __name__ == '__main__':
scraper = Omni(
base_url='https://www.dallascounty.org/jaillookup/searchByName',
specs={
'pagination': True,
'pages_element': '',
'error_message': 'No records were found using the search criteria provided',... | isome01/intelbroker | main.py | main.py | py | 573 | python | en | code | 0 | github-code | 13 |
10348863123 | import multiprocessing
from decimal import Decimal
from slacker import Slacker
from pymarketcap import Pymarketcap
from tinymongo import TinyMongoClient
import cryCompare
class ArbitrageBot:
def __init__(self):
# getcontext().prec = 15
# api_key = 'EcBv9wqxfdWNMhtOI8WbkGb9XwOuITAPxBdljcxv8RYX1H7u2... | Nfinger/crypto-analytics-api | arbitrage.py | arbitrage.py | py | 3,531 | python | en | code | 0 | github-code | 13 |
12984635602 | import numpy as np
import pandas as pd
import csv
import yfinance as yf
import matplotlib as plt
import tensorflow as tf
#Paramter:
details = 6
stocks = 27
days = 762
start = '2016-01-01'
end = '2019-01-01'
dataSet = np.zeros((days,details,1))
print(dataSet.shape)
stocklist = [] ... | TheGamlion/Stock_RNN | main.py | main.py | py | 898 | python | en | code | 0 | github-code | 13 |
9712290865 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch_geometric.nn as gnn
import torch_geometric.nn.models as M
class GCNGATVGAE(nn.Module):
def __init__(self, input_feat_dim, hidden_dim1, hidden_dim2, num_heads = 3):
super(GCNGATVGAE, self).__init__()
self.gcn = gnn.G... | Anindyadeep/MultiHeadVGAEs | Models/gcn_gat_cat.py | gcn_gat_cat.py | py | 1,911 | python | en | code | 4 | github-code | 13 |
17051875254 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class ExtendFieldInfo(object):
def __init__(self):
self._field_name = None
self._field_value = None
@property
def field_name(self):
return self._field_name
@field_... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/ExtendFieldInfo.py | ExtendFieldInfo.py | py | 1,401 | python | en | code | 241 | github-code | 13 |
40445234202 | def is_pangram(sentence):
if sentence == "":
return False
alphabet = 'abcdefghijklmnopqrstuvwxyz'
sen_lowercase = sentence.lower()
sen_list = list(sen_lowercase)
alpha_list = list(alphabet)
#test
#I had to define the flag here because test for empty sentange was failling when f... | CatalinPetre/Exercism | python/pangram/pangram_raw.py | pangram_raw.py | py | 1,678 | python | en | code | 0 | github-code | 13 |
28663913736 | import sqlite3
import time
class DbStore():
def __init__(self, name):
self.name = name
def create_db(self):
con = sqlite3.connect(str(self.name) + '.db')
cur = con.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS history_message(time TEXT,'
'sen... | amakovey/messenger | dbclient.py | dbclient.py | py | 2,578 | python | ru | code | 0 | github-code | 13 |
10999165238 | from utilities import get_random_list
from utilities import timeit
@timeit
def solve_ranked_pythonic(ranked, player):
player_rank = []
unique_sorted_rank = list(set(ranked))
unique_sorted_rank.sort()
i = 0
current_position = len(unique_sorted_rank) + 1
for score in player:
if current_... | pedrolp85/python_pair_programming | climbing_the_leaderboard.py | climbing_the_leaderboard.py | py | 1,833 | python | en | code | 1 | github-code | 13 |
34795809269 | #!/usr/bin/env/python
# File name : server.py
# Production : PiCar-C
# Website : www.adeept.com
# Author : William
# Date : 2019/11/21
import servo
servo.servo_init()
import socket
import time
import threading
import GUImove as move
import Adafruit_PCA9685
import os
import FPV
import info
import LED
import GUIf... | adeept/adeept_picar-b | server/server.py | server.py | py | 16,211 | python | en | code | 21 | github-code | 13 |
17045551064 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.FliggyPoiInfo import FliggyPoiInfo
class AlipayOverseasTravelFliggyPoiCreateModel(object):
def __init__(self):
self._data_version = None
self._ext_info = None... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/AlipayOverseasTravelFliggyPoiCreateModel.py | AlipayOverseasTravelFliggyPoiCreateModel.py | py | 3,684 | python | en | code | 241 | github-code | 13 |
73907473938 | """final
Revision ID: 31fff8168895
Revises:
Create Date: 2023-10-07 23:14:02.633868
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '31fff8168895'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by... | Renardo1985/BookShop | server/migrations/versions/31fff8168895_final.py | 31fff8168895_final.py | py | 3,272 | python | en | code | 0 | github-code | 13 |
71497083219 | # 언어 : Python
# 날짜 : 2022.1.20
# 문제 : BOJ > 가장 먼 노드 (https://programmers.co.kr/learn/courses/30/lessons/49189)
# 레벨 : level 3
# =====================================================================================
from collections import deque, defaultdict, Counter
def solution(n, edge):
distance = [float("inf")... | eunseo-kim/Algorithm | programmers/코딩테스트 고득점 Kit/그래프/01_가장 먼 노드.py | 01_가장 먼 노드.py | py | 1,072 | python | en | code | 1 | github-code | 13 |
20619606030 | from utils import *
data1 = pd.read_excel('附件表/附件1-商家历史出货量表.xlsx', engine = 'openpyxl')
data2 = pd.read_excel('附件表/附件2-商品信息表.xlsx', engine = 'openpyxl')
data3 = pd.read_excel('附件表/附件3-商家信息表.xlsx', engine = 'openpyxl')
data4 = pd.read_excel('附件表/附件4-仓库信息表.xlsx', engine = 'openpyxl')
data = pd.merge(data1,data2)
data = ... | Andd54/Mathor_Cup_Project | Question1(2).py | Question1(2).py | py | 2,985 | python | en | code | 0 | github-code | 13 |
12740657893 | from torch.optim import SGD, Adam
from torch.optim.lr_scheduler import MultiStepLR
import torch
import torchvision.datasets as dset
import torchvision.transforms as transforms
import gpytorch
from deep_gp.models.deep_kernel_model import DKLModel, DenseNetFeatureExtractor
normalize = transforms.Normalize(mean=[0.5071,... | AlbertoCastelo/bayesian-dl-medical-diagnosis | tests/test_gpytorch.py | test_gpytorch.py | py | 3,855 | python | en | code | 0 | github-code | 13 |
43231703074 |
import sys
import random
import numpy as np
import pygame as pg
import vars
sys.path.append('./')
try:
from Graph_package.MovableVertex import MovableVertex2D, interact_manager
from Graph_package.Graph2D import Graph2D, InteractiveGraph2D
from GUI_package.Pygame_package import Graph_drawer
from RSA.... | VY354/my_repository | Python/projects/swarm_intelligence/road_search_algorithm/main.py | main.py | py | 1,876 | python | en | code | 0 | github-code | 13 |
4883186627 | from sqlalchemy import create_engine, text
# Database engine
engine = create_engine("sqlite:///rocketpool.db")
# Query the database directly with raw SQL
with engine.connect() as connection:
result = connection.execute(text("SELECT id, slug FROM protocol_topics"))
# Construct URLs and store them in a list
... | PaulApivat/data_engineer | practice/discourse/rocketpool/pipeline/post_model.py | post_model.py | py | 3,951 | python | en | code | 0 | github-code | 13 |
36681894515 | from typing import List
import numpy as np
from reward_shaping.core.reward import RewardFunction
from reward_shaping.core.utils import clip_and_norm
from reward_shaping.envs.lunar_lander.specs import get_all_specs
gamma = 1.0
def safety_collision_potential(state, info):
assert "collision" in state
return i... | EdAlexAguilar/reward_shaping | reward_shaping/envs/lunar_lander/rewards/potential.py | potential.py | py | 6,192 | python | en | code | 0 | github-code | 13 |
74128043539 | import cv2
import os
import numpy as np
import face_recognition as fr
import time
from facerec import face_data_encodings
from vars import *
dataset = os.listdir(folder_name)
dataset = dataset[1:]
checked = [False]*len(dataset)
test_images = os.listdir(test_set)
def isthere(ret):
for i in range(len(ret)):... | Charan2k/rec-face | prediction.py | prediction.py | py | 1,020 | python | en | code | 0 | github-code | 13 |
74388856017 | # Tetris en Python
# Desarrollado por Santiago Menendez, pero no llegue a los 40 minutos permitidos por lo que no quede
import os
import random
import time
import keyboard
# Blocks
class Block:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
self.shape = []
self.x_shape = 0
... | SantiMenendez19/tetris_game | tetris.py | tetris.py | py | 13,926 | python | en | code | 1 | github-code | 13 |
73996330258 | import socket
import time
import cv2
import numpy as np
from pred_net import YoloTest
import json
def start():
address = ('0.0.0.0', 6606)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(address)
s.listen(1)
yolo=YoloTest()
def recvpack(sock, count):
buf = b''
_... | hry8310/ai | dl/tf-yolo3/sv.py | sv.py | py | 1,957 | python | en | code | 2 | github-code | 13 |
9746674534 | import pandas as pd
import numpy as np
CsvFileNameFormat="/gitrepo/robotRepo/hq{}/{}.y.csv"
VOLUME_REDUCER=1000.0
def readRawData(ticker, day):
csvFile=CsvFileNameFormat.format(day, ticker)
df = pd.read_csv(csvFile, index_col=[0], parse_dates=False)
csvShape=df.shape
df['PrevClose'] = df.Close.shift(1)... | jbtwitt/pipy | hq/HqReader.py | HqReader.py | py | 3,381 | python | en | code | 0 | github-code | 13 |
72651545619 | __authors__ = [
# alphabetical order by last name
'Thomas Chiroux', ]
import unittest
import datetime
# dependencies imports
from dateutil import rrule
# import here the module / classes to be tested
from srules import Session, SRules
class TestSRules(unittest.TestCase):
def setUp(self):
self.s... | LinkCareServices/python-schedule-rules | tests/srules_test.py | srules_test.py | py | 1,950 | python | en | code | 1 | github-code | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.