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
32869975011
from fastapi import APIRouter from api.schemes import relations, responses from database import redis def add_relation(rel: relations.Relation, rel_name: str) -> responses.RelationOperations: if redis.add_relation(rel_name, rel.user_id, rel.item_id): return responses.RelationOperations(status="successful...
Muti-Kara/sylvest_recommender
api/routers/relations.py
relations.py
py
1,755
python
en
code
2
github-code
6
38043006452
import cloudinary.uploader import requests # define your S3 bucket name here. S3_BUCKET_NAME = "akshayranganath" def get_file_name(url, transformation): # transformation will be of the format "t_text_removed/jpg". # remove the "/jpg" part and the "t_" part transformation = transformation.rsplit('/',1)...
akshay-ranganath/create-and-upload
demo_upload_and_download.py
demo_upload_and_download.py
py
2,558
python
en
code
0
github-code
6
33488962773
''' Given an array A, we can perform a pancake flip: We choose some positive integer k <= A.length, then reverse the order of the first k elements of A. We want to perform zero or more pancake flips (doing them one after another in succession) to sort the array A. Return the k-values corresponding to a sequence of p...
sxu11/Algorithm_Design
Contests/C118_PancakeSorting.py
C118_PancakeSorting.py
py
1,915
python
en
code
0
github-code
6
30517336024
from .errors import * class Asset: """Generic class representing a file asset URL.""" def __init__(self, client, url, filename): self.client = client self._url = url self.filename = filename self._response = None def __str__(self): return f"{self.__class__.__name_...
nwunderly/aionasa
aionasa/asset.py
asset.py
py
2,644
python
en
code
7
github-code
6
36021767355
import numpy as np import sys #file_name = "space_pulse_illumination_0.000000V.dat"; file_name = sys.argv[-1] fname = open(file_name); column_number = 5; tmp_title = []; tmp_value = []; tmp_data = 0; tmp_time = 0; tmp_data_number = 0; J = []; time = []; value = []; value_space_pos = []; i = 0; position_number = 1; f...
dglowienka/drift-diffusion_mini-modules
Dynamic/time_J.py
time_J.py
py
1,400
python
en
code
0
github-code
6
21211345581
import sys import heapq input = sys.stdin.readline INF = float('inf') V, E = map(int, input().split()) graph = [[] for _ in range(V + 1)] for _ in range(E): a, b, w = map(int, input().split()) graph[a].append((w, b)) graph[b].append((w, a)) v1, v2 = map(int, input().split()) def dijakstra(start): min_...
kimkimj/Algorithm
python/Dijkstra/specificRoute.py
specificRoute.py
py
984
python
en
code
0
github-code
6
25097354504
# -*- coding: utf-8 -*- """ Created on Thu Jul 21 13:56:29 2022 @author: maria """ import numpy as np import pandas as pd from numpy import zeros, newaxis import matplotlib.pyplot as plt import scipy as sp from scipy.signal import butter,filtfilt,medfilt import csv import re import functions2022_07_15 as fun #gettin...
mariacozan/Analysis_and_Processing
code_archive/2022-07-21-neuronal_classification.py
2022-07-21-neuronal_classification.py
py
5,001
python
en
code
0
github-code
6
35574568262
# This module contains the set of functions that work with the IPCA inflation index. # IPCA is the most used inflation index in Brazil. It is calculated and published by IBGE. It is published between the 8th and 11th of the following month. # IPCA is published both as a monthly percentage rate and a index number. We up...
ReiNog/CurryInv
ipca.py
ipca.py
py
6,923
python
en
code
0
github-code
6
74182080829
#!/usr/bin/env python from __future__ import print_function import boto3 from botocore.exceptions import ClientError import json import argparse import time import random import uuid ALL_POLICY = '''{ "Version": "2012-10-17", "Statement": [ { "Sid": "Stmt''' + str(random.randint(100000, 999999)) +'''", ...
dagrz/aws_pwn
elevation/add_iam_policy.py
add_iam_policy.py
py
2,724
python
en
code
1,106
github-code
6
14698252975
from flask import Flask, request, jsonify from SSAPI import app, api, db, guard from flask_restplus import Resource, reqparse, inputs import flask_praetorian from SSAPI.models import * @api.route('/Scrimmages') class ScrimmageList(Resource): @flask_praetorian.auth_required def get(self): """ Returns a...
ktelep/SSAPI
SSAPI/scrimmage_views.py
scrimmage_views.py
py
7,157
python
en
code
0
github-code
6
71588771707
import pytest from pytest import approx from brownie import chain from brownie.test import given, strategy from decimal import Decimal from .utils import RiskParameter, transform_snapshot @pytest.fixture(autouse=True) def isolation(fn_isolation): pass @given( initial_fraction=strategy('decimal', min_value=...
overlay-market/v1-periphery
tests/state/test_volume.py
test_volume.py
py
5,680
python
en
code
3
github-code
6
27673024131
import torch from torch import nn def init_weights_(m: nn.Module, val: float = 3e-3): if isinstance(m, nn.Linear): m.weight.data.uniform_(-val, val) m.bias.data.uniform_(-val, val) class Actor(nn.Module): def __init__(self, state_dim: int, ...
zzmtsvv/rl_task
spot/modules.py
modules.py
py
2,231
python
en
code
8
github-code
6
40124065659
from pymongo.mongo_client import MongoClient from pymongo.server_api import ServerApi import certifi from pprint import pprint class database: def __init__(self): uri = "mongodb+srv://user:user@harvest-hero.zdaj74u.mongodb.net/?retryWrites=true&w=majority" # Create a new client and connec...
SteveHuy/Harvest-Hero
Database+APIs/database.py
database.py
py
721
python
en
code
0
github-code
6
43984207586
# gdpyt-analysis: test.test_fit_3dsphere """ Notes """ # imports from os.path import join import math import numpy as np import pandas as pd import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from correction import correct from utils import fit, plotting, functions # read dataframe fp = '/Users...
sean-mackenzie/gdpyt-analysis
test/test_fit_3dsphere.py
test_fit_3dsphere.py
py
6,764
python
en
code
0
github-code
6
29788980815
from collections import Counter import numpy as np import pandas as pd import pickle from sklearn import svm, model_selection, neighbors from sklearn.ensemble import VotingClassifier, RandomForestClassifier from sklearn.model_selection import cross_validate, train_test_split # processing data for Machine Learning # ...
mihir13/python_for_finance
PythonForFinance9.py
PythonForFinance9.py
py
3,409
python
en
code
0
github-code
6
9651796880
import utils from utils import * # Arguments available def parse_args(): parser = argparse.ArgumentParser(description='Task1') parser.add_argument('--image_path', type=str, default=None, help='Path to an image on which to apply Task1 (absolute or relative path)') parser.add_argument('--save_pat...
SebastianCojocariu/Curling-OpenCV
task_1.py
task_1.py
py
3,759
python
en
code
1
github-code
6
23088053555
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Code by: Magnus Øye, Dated: 12.11-2018 Contact: magnus.oye@gmail.com Website: https://github.com/magnusoy/Balancing-Platform """ # Importing packages import numpy as np from numpy import sqrt, sin, cos, pi, arccos import matplotlib.pylab as plt # Plot style plt.style...
magnusoy/Balancing-Platform
src/balancing_platform/util/graphs.py
graphs.py
py
2,702
python
en
code
7
github-code
6
15306305960
""" WENO Lax-Friedrichs Author: Pierre-Yves Taunay Date: November 2018 """ import numpy as np import matplotlib.pyplot as plt ############### #### SETUP #### ############### # Grid npt = 200 L = 2 dz = L/npt zvec = np.linspace(-L/2 + dz/2,L/2-dz/2,npt) EPS = 1e-16 # Time dt = dz / 1 * 0.4 tmax = 2000 tc = 0 # Sche...
pytaunay/weno-tests
python/advection_1d/weno-advection.py
weno-advection.py
py
5,051
python
en
code
1
github-code
6
71579186747
""" Optimizes GPST model hyperparameters via Optuna. """ import os import time import json import shutil import logging import argparse import tempfile import datetime import optuna from train import train from lumber import get_log from arguments import get_args def main() -> None: """ Run an Optuna study. ""...
langfield/spred
spred/gpst/optimize.py
optimize.py
py
4,018
python
en
code
3
github-code
6
37164877474
import torch import numpy import pandas import sys import os import copy import torch.nn as nn import torch.nn.functional as F import torch.optim as optim #Global option defaults that can be changed later by command line gcm_folder_path : str = "gcms" target_folder_path : str = "targets" class_index = "...
tigerwxu/gcm-cnn
gcm-cnn.py
gcm-cnn.py
py
10,296
python
en
code
0
github-code
6
3145047297
#!/usr/bin/env python #!/users/legarreta/opt/miniconda3/envs/sims/bin/python #!/usr/bin/python3 # Get RMSDs from multiple files # INPUTS: input dir and pattern string USAGE="rmsds-trajectory-ALL.py <input dir>" import os, sys def main (): # Check command line arguments args = sys.argv if (len(args) < 2): p...
luisgarreta/dockingBCL2
scripts/rmsds-trajectory-ALL.py
rmsds-trajectory-ALL.py
py
3,642
python
en
code
0
github-code
6
1306545281
import os, datetime def call_msra(): terr = input('код территории: ') if terr == "": print() call_msra() comp = input('номер АРМа: ') if comp == "": print() call_msra() else: os.system(r'C:\Windows\System32\msra.exe /offerra kmr-' + terr + '-' +...
Aarghe/some_scripts
msra/msra.py
msra.py
py
2,782
python
ru
code
0
github-code
6
20921293526
import numpy as np import matplotlib.pyplot as plt def plot_results(results, range_param, label='', color='r', marker='o'): mean_results = np.mean(results, axis=1) min_results = np.mean(results, axis=1) - np.std(results, axis=1) max_results = np.mean(results, axis=1) + np.std(results, axis=1) plt.plot...
sharpenb/Multi-Scale-Modularity-Graph-Clustering
Scripts/experiments/results_manager.py
results_manager.py
py
1,613
python
en
code
2
github-code
6
70929697148
from tasks import Task from workWithFiles import * class WorkWithUser: def __init__(self): self.task: Task = Task.NONE self.idNote: int = None self.title: str = None self.item: str = None self.datetime_min: datetime = None self.datetime_ma...
galkinnikolay/HomeworkPython
workWithUser.py
workWithUser.py
py
8,880
python
ru
code
0
github-code
6
13305672302
import cv2 #image read """ img = cv2.imread("Resources/lena.png") cv2.imshow("Output",img) cv2.waitKey(0) """ #video read """ cap = cv2.VideoCapture("Resources/test_video.mp4") while True: success, img = cap.read() cv2.imshow("Video",img) if cv2.waitKey(1) & 0xFF ==ord('q'): break ...
Umang-Seth/General_OpenCV_Fn
Load_Webcam.py
Load_Webcam.py
py
543
python
en
code
0
github-code
6
8499616042
import os import sys user_path = os.environ.get("USER_PATH") sys.path.append(user_path) from data_structures.min_heap import MinHeap def k_largest_elements(arr, k): temp = [] heap = MinHeap(temp) for elmnt in arr: if len(heap) < k: heap.insert(elmnt) else: if elmn...
mathivanansoft/algorithms_and_data_structures
data_structures/k_largest_elements.py
k_largest_elements.py
py
654
python
en
code
0
github-code
6
5405379024
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import random # imports relevant libraries import operator import matplotlib.pyplot import agentframework import csv import matplotlib.animation num_of_agents = 10 num_of_iterations = 100 neighbourhood = 20 f = open('datain.txt') # open...
cman2000/Portfolioabm
model.py
model.py
py
1,832
python
en
code
0
github-code
6
4537498830
from DEFINITIONS import * from Structures import ERTree from AF import make_create_condition, AFD, AFND, State class ER: def __init__(self, erid, regex): self.id = erid self.regex = regex def parse_generic(self, ps): try: i = ps.index("-") replace_string = ""...
bruno-borges-2001/Analisador
ER/ER.py
ER.py
py
6,254
python
en
code
0
github-code
6
71010185787
#!/usr/bin/python import sys, copy from scanner import scanner from parser import parser from lex_rules import build_patterns from bookmarks import create_bookmark from symbol_table import build_productions, build_subproductions, Symbol, Production from scope import build_scopes, Scope, ScopeSymbol, handleScope from...
lukedupin/C2
main.py
main.py
py
4,412
python
en
code
0
github-code
6
42132347145
import math import numpy as np from scipy.stats import bernoulli simlen = 1000000 pmf = np.full(10,0.1) def cdf(k): if(k>10): return 1 elif(k<=0): return 0 else: return k*0.1 print("Value equal to 7:") p1 = pmf[7] data_bern1 = bernoulli.rvs(size=simlen,p=p1) err_ind1 = np.nonzero...
gadepall/digital-communication
exemplar/10/13/3/30/codes/code.py
code.py
py
984
python
en
code
7
github-code
6
16325138014
from abc import abstractmethod import threading from types import MethodType from typing import Any, Dict, Generic, NoReturn from jsonIO.Serializable import SerializableType from protocol.interface import ( AbstractRequestClient, AbstractRequestServer, AbstractSerializableHandler, AbstractSerializableR...
MysteriousChallenger/nat-holepunch
server/PackageSocketRequestServer.py
PackageSocketRequestServer.py
py
2,929
python
en
code
0
github-code
6
2502699508
# To manage matrices correctly # At deployment, check if new matrices have been added to old batch sizes import grid import orjson import sys # VERSION_FILE VERSION_FILE = "versioning.json" def readable_string(batch, num_infected, infection_rate): m,n = grid.parse_batch(batch) return f'{n} Samples (with {m} ...
Aakriti28/tapestry-server
old-server/matrix_manager.py
matrix_manager.py
py
4,223
python
en
code
0
github-code
6
6756372344
#====================== # Author: Susmita Datta # Title: insertionSort # # Time Complexity of Solution: # O(n^2) # # Sample input = [3, 2, 1, 4, 5, 6, 9, 8, 7] # Sample output = [1, 2, 3, 4, 5, 6, 7, 8, 9] # #-------------------------------------------- def insertionSort(unsorted): for index in range(1, len(un...
ssmtdatta/Sorting
insertionSort.py
insertionSort.py
py
763
python
en
code
0
github-code
6
2026773879
import json import os import pathlib import time from selenium import webdriver from selenium.webdriver import ActionChains driver = webdriver.Chrome() targetUrl = 'https://www.douban.com/' username = "" psw = "" def login_zhi_hu(): loginurl = targetUrl # 登录页面 # 加载webdriver驱动,用于获取登录页面标签属性 # driver = we...
Nienter/mypy
personal/douban.py
douban.py
py
3,789
python
en
code
0
github-code
6
75163149306
# -*- coding: utf-8 -*- """ Flask Skeleton """ from flask import Blueprint, request, redirect, url_for, render_template, flash, session from pymongo import errors as mongo_errors from bson.objectid import ObjectId from flask_login import login_required import datetime from app import mongo, login_manager from app.usu...
e-ruiz/big-data
01-NoSQL/atividade-04/src/app/blog/posts.py
posts.py
py
2,268
python
en
code
1
github-code
6
1925325981
from odoo import models, fields, api class LP_Crm(models.Model): _inherit = 'crm.lead' lp_company_id = fields.Many2one('res.partner', 'company' , compute = '_compute_company') lp_individual_id = fields.Many2many('res.partner') lp_OneDrive_url = fields.Char('OneDrive folder URL') lp_client_size = fields.Char...
MoathAlrefai2/lp-erp-dev001
lp_crm/model/lp_crm.py
lp_crm.py
py
8,538
python
en
code
0
github-code
6
19400090459
from typing import List class Solution: def minFallingPathSum(self, A: List[List[int]]) -> int: h = len(A) w = len(A[0]) for i in range(1,h): for j in range(w): if j == 0: A[i][j] = min(A[i-1][j] + A[i][j],A[i-1][j+1] + A[i][j]) ...
Yigang0622/LeetCode
minFallingPathSum.py
minFallingPathSum.py
py
653
python
en
code
1
github-code
6
38740337725
import pytest import numpy as np from uncoverml import patch @pytest.mark.parametrize('make_multi_patch', ['make_patch_31', 'make_patch_11'], indirect=True) def test_grid_patch(make_multi_patch): timg, pwidth, tpatch, tx, ty = make_multi_patch patches = pa...
GeoscienceAustralia/uncover-ml
tests/test_patch.py
test_patch.py
py
593
python
en
code
32
github-code
6
36066284113
#%% from PIL import Image import numpy as np import onnxruntime import torch import cv2 def preprocess_image(image_path, height, width, channels=3): image = Image.open(image_path) image = image.resize((width, height), Image.LANCZOS) image_data = np.asarray(image).astype(np.float32) image_data = image_d...
cassiebreviu/onnxruntime-raspberrypi
inference_mobilenet.py
inference_mobilenet.py
py
2,000
python
en
code
4
github-code
6
7159944925
# 由于反/防爬虫策略,以及防止封ip的风险 # 我们选择动态切换user-agent import urllib.request import ssl import random # 创建未证实的ssl上下文 context = ssl._create_unverified_context() def load_baidu(): url = "https://www.baidu.com" header = { '' } # 创建代理列表 user_agent_list = [ 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKi...
hengxuZ/python-crawler-lesson
lesson-01/随机设置代理爬取页面.py
随机设置代理爬取页面.py
py
1,194
python
en
code
1
github-code
6
8063903284
import logging import subprocess from subprocess import Popen, PIPE def run(command: str) -> None: """ :param command: shell statement :return: """ logging.debug(command) subprocess.call(command, shell=True, universal_newlines=True) def call(command: str) -> str: """ :param command:...
leaderli/li_py
li/li_bash.py
li_bash.py
py
1,123
python
en
code
0
github-code
6
4828707472
from fastapi.security import OAuth2PasswordBearer from sqlalchemy.orm import Session from models import Quote, Title, Year from schemas import QuoteBase, QuoteCreate, TitleBase, TitleCreate, YearBase, YearCreate import random import auth import models import schemas oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token...
rubenpinxten/herexamen_API
myProject/crud.py
crud.py
py
3,543
python
en
code
0
github-code
6
2216069250
class Macro: def render(self, inv): ctx = akat.prepare(inv, required_args = ["cond"], keywords = ["likely", "unlikely"], required_enclosing_macros = ["COROUTINE"]) if ctx.likely and ctx.unlikely: akat.fatal_error("It can't be both likely and unlikely!") label, state = ctx.COROU...
akshaal/akatlib4
akatpp/akat_wait_until.py
akat_wait_until.py
py
561
python
en
code
0
github-code
6
30117142033
import numpy as np from PIL import Image class predict_day_night_algos: def __init__(self,img_path,algorithm_choice): self.img_path = img_path self.algorithm_choice = algorithm_choice def select_algorithm(self): """ the function selects which algorithm, based on the ...
shivargha98/shivargha_bandopadhyay
predict_day_night.py
predict_day_night.py
py
2,888
python
en
code
0
github-code
6
30669751378
import os import cv2 dir = "/Users/sunxiaofei/PycharmProjects/remote-server-projects/unlabeled_dataset/data" for i, eachVid in enumerate(os.listdir(dir)): vPath = os.path.join(dir, eachVid) vname = vPath.split("/")[-1][:-4] print(vname) print(vPath) vidcap = cv2.VideoCapture(vPath) success,image = vidcap....
sxfduter/python_utils
video_frame_extraction.py
video_frame_extraction.py
py
709
python
en
code
0
github-code
6
73510591867
class Solution: def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]: countWord = [] countQuery = [] ans = [] for word in words: w = sorted(word) countWord.append(w.count(w[0])) countWord.sort() for query in queri...
yonaSisay/a2sv-competitive-programming
compare-strings-by-frequency-of-the-smallest-character.py
compare-strings-by-frequency-of-the-smallest-character.py
py
771
python
en
code
0
github-code
6
22002934531
""" Interfaces for Deep Q-Network. """ import random import numpy as np import tensorflow as tf from collections import deque from scipy.misc import imresize from qnet import QNet class DeepQLearner(object): """ Provides wrapper around TensorFlow for Deep Q-Network. """ def __init__(self, ac...
TianyiWu96/DQN
src/qlearn.py
qlearn.py
py
11,988
python
en
code
0
github-code
6
18100363274
""" 1143. Longest Common Subsequence https://leetcode.com/problems/longest-common-subsequence/ """ from typing import Dict, List, Tuple from unittest import TestCase, main class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: """ This is a classic DP problem te...
hirotake111/leetcode_diary
leetcode/1143/solution.py
solution.py
py
1,955
python
en
code
0
github-code
6
29099504157
import xml.etree.ElementTree as ET from datetime import date from pathlib import Path def _convert_dict(temp_dict): """ Convert one dict to a new one :param temp_dict: A temporary dict :type temp_dict: dict :return: The same dict in a new formate that fits with the database :rtype: dict "...
ZexiDilling/structure_search
xml_handler.py
xml_handler.py
py
7,386
python
en
code
0
github-code
6
17044150914
# ESCOLHA DA PALAVRA # import random palavrasaleatorias = ['GIRAFA', 'GATO', 'ESMALTE', 'MIOJO', 'MORANGO', 'CHOCOLATE', 'VERDE', 'CINZA', 'PYTHON', 'ABELHA', 'PUCPR', 'ALEGRIA','ESTUDAR', 'PROGRAMA', 'PIMENTA'] # escolha de maneira randômica escolhida = palavrasaleatorias[random.randint(0,14)] # conta o número de le...
micheleotta/Jogo-da-forca
forca.py
forca.py
py
2,079
python
pt
code
0
github-code
6
36637137136
import tkinter as tk from tkinter import ttk from tkinter import * import numpy as np from PIL import ImageTk, Image from os import listdir from os.path import isfile, join from PIL.Image import Resampling from hopfield_clouds import HopfieldClouds # root.columnconfigure(0, weight=1) # root.columnconfigure(1, weigh...
behenate/hopfield-reconstruction
gui.py
gui.py
py
5,007
python
en
code
0
github-code
6
15512669243
import pygame #Impordime pygame'i #Defineerime funktsiooni, mis joonistab ruudustiku def draw_grid(screen, ruudu_suurus, read, veerud, joone_värv): for i in range(read): #Esimene tsükel, mis käib läbi kõik read for j in range(veerud): #Teine tsükel, mis käib läbi kõik veerud rect = pygame.Rect(...
KermoV/Ulesanne_3
Ülesanne_3.py
Ülesanne_3.py
py
1,403
python
et
code
0
github-code
6
27679859460
# Things to show # Name, Orbital Radius, Gravity, Mass, Distance, Planet Type, Goldilock, Discovery Date, Mass of hoststar from flask import Flask, jsonify, make_response from pandas import read_csv app = Flask(__name__) data = read_csv("csv/display.csv") @app.get("/") def index(): to_send = [] i = 1 while Tru...
CometConnect/python
api.py
api.py
py
1,549
python
en
code
0
github-code
6
15598819292
import sys sys.path.append('..') import torch from torch import nn from torch.nn import functional as F from ssd import config as cfg from basenet.vgg import vgg_feat from basenet.resnet import resnet101_feat from ssd.utils_ssd.priorbox import PriorBox from ssd.utils_ssd.L2Norm import L2Norm from ssd.utils_ssd.detect...
AceCoooool/detection-pytorch
ssd/ssd300.py
ssd300.py
py
4,567
python
en
code
24
github-code
6
42896164462
import jax import numpy as np import pytest import hilbert_sort.jax as jax_backend import hilbert_sort.numba as np_backend @pytest.fixture(scope="module", autouse=True) def config_pytest(): jax.config.update("jax_enable_x64", True) @pytest.mark.parametrize("dim_x", [2, 3, 4]) @pytest.mark.parametrize("N", [150...
AdrienCorenflos/parallel-Hilbert
tests/test_agree.py
test_agree.py
py
1,622
python
en
code
1
github-code
6
36942742650
class Erecord: def __init__(self, eId, eName, eAddress, eRate, eHour): self.id = eId self.name = eName self.address = eAddress self.rate = eRate self.hour = eHour def __str__(self): return "ID: " + str(self.id) + " Name: " + self.name def calc_salary(sel...
Sir-Lance/CS1400
EmployeeClass.py
EmployeeClass.py
py
615
python
en
code
0
github-code
6
7873679939
import numpy as np from multiprocessing import Pool h, w = 1080, 1920 def draw_pixel(): pixel = np.zeros(24, dtype=np.uint8) for i in range(24): pixel[i] = np.random.randint(0, 2) return pixel def draw_row(p): row = np.zeros((24, w), dtype=np.uint8) row[:, 0] = draw_pixel() for j in r...
e841018/ERLE
rand_img.py
rand_img.py
py
888
python
en
code
2
github-code
6
160637604
import numpy as np import pandas as pd #Setting the recent season match yrBefore = np.arange(1900,2023) yrAfter = np.arange(1901,2024) yrBefore_list = [] yrAfter_list = [] for s in yrBefore: a = str(s) yrBefore_list.append(a) for j in yrAfter: b = str(j) yrAfter_list.append(b) seaso...
Taofeek26/Taofeek26
btttt.py
btttt.py
py
2,577
python
en
code
0
github-code
6
42134577155
import numpy as np # Define the number of simulations num_simulations = 100000 # Initialize a counter for successful outcomes successful_outcomes = 0 for _ in range(num_simulations): # Initialize the bag with 5 red and 3 blue balls bag = np.array(['red', 'red', 'red', 'red', 'red', 'blue', 'blue', 'blue']) ...
gadepall/digital-communication
exemplar/12/13/3/75/codes/main.py
main.py
py
822
python
en
code
7
github-code
6
71186923
import boto3 import uuid import json from jwcrypto import jwt, jwk DDB_CLIENT = boto3.client('dynamodb') ddb_table = "iowt-devices" def create_new_device(): id = str(uuid.uuid4()) key = jwk.JWK(generate="oct", size=256) key_data = json.loads(key.export())['k'] token = jwt.JWT(header={"alg": "A256KW...
wilsonc101/iowt
www/create_device.py
create_device.py
py
886
python
en
code
0
github-code
6
12064414796
from sys import argv def next_nb(ls, visited, iterator, element): for i in range(len(ls[iterator])): print(f"{visited} {ls[iterator][i]}") if visited[ls[iterator][i] - 1] == 0: visited[ls[iterator][i] - 1] = element next_nb(ls, visited, ls[iterator][i] - 1, element) i...
patyen/GiIZ
Set2/Task3/kopia.py
kopia.py
py
1,145
python
en
code
1
github-code
6
33613649647
''' --- Day 2: Dive! --- Now, you need to figure out how to pilot this thing. It seems like the submarine can take a series of commands like forward 1, down 2, or up 3: forward X increases the horizontal position by X units. down X increases the depth by X units. up X decreases the depth by X units. Note that since y...
Patbmcdonald/Advent-Of-Code-2021
aoc/day2/day2.py
day2.py
py
3,032
python
en
code
0
github-code
6
39001711691
import csv import MySQLdb mydb= MySQLdb.connect(host='localhost', user='root', db='celebal') cursor=mydb.cursor() with open('dataset1.csv', 'r') as csvfile: csv_data1 = csv.reader(csvfile, delimiter=',') next(csv_data1) cursor.execute("TRUNCATE TABLE data1") for row in csv_data1: cursor.execute("INSERT ...
shauryaa/CelebalAssignment1
try.py
try.py
py
910
python
en
code
0
github-code
6
1360530890
import Utils.Data as data from Utils.Data.DatasetUtils import is_test_or_val_set, get_train_set_id_from_test_or_val_set, \ get_test_or_val_set_id_from_train from Utils.Data.Features.Feature import Feature from Utils.Data.Features.Generated.EnsemblingFeature.MatrixEnsembling import ItemCBFMatrixEnsembling from Utils...
MaurizioFD/recsys-challenge-2020-twitter
Utils/Data/Features/Generated/EnsemblingFeature/SimilarityFoldEnsembling.py
SimilarityFoldEnsembling.py
py
7,398
python
en
code
39
github-code
6
75136926587
import pytest import tgalice from dialog_manager import QuizDialogManager @pytest.fixture def default_dialog_manager(): return QuizDialogManager.from_yaml('texts/quiz.yaml') def make_context(text='', prev_response=None, new_session=False): if prev_response is not None: user_object = prev_response.u...
avidale/musiquiz
test_scenarios.py
test_scenarios.py
py
1,432
python
en
code
0
github-code
6
811146806
'''Minimum characters that are to be inserted such that no three consecutive characters are same Given a string str and the task is to modify the string such that no three consecutive characters are same. In a single operation, any character can be inserted at any position in the string. Find the minimum number of suc...
Saima-Chaity/Leetcode
Interviews/NoThreeConsecutiveCharacter.py
NoThreeConsecutiveCharacter.py
py
791
python
en
code
0
github-code
6
2542812722
import os import json import logging from infy_bordered_table_extractor import bordered_table_extractor from infy_bordered_table_extractor.bordered_table_extractor import OutputFileFormat from infy_bordered_table_extractor.providers.tesseract_data_service_provider import TesseractDataServiceProvider from infy_bordered_...
Infosys/Document-Extraction-Libraries
infy_bordered_table_extractor/tests/test_border_table_img.py
test_border_table_img.py
py
3,357
python
en
code
6
github-code
6
40319534507
from ansible.module_utils.basic import AnsibleModule from ansible_collections.ansibleguy.opnsense.plugins.module_utils.base.api import \ Session from ansible_collections.ansibleguy.opnsense.plugins.module_utils.base.cls import GeneralModule class General(GeneralModule): CMDS = { 'set': 'set', ...
ansibleguy/collection_opnsense
plugins/module_utils/main/webproxy_forward.py
webproxy_forward.py
py
2,388
python
en
code
158
github-code
6
72255300348
from __future__ import annotations import json import re from typing import TYPE_CHECKING import asyncpg import discord import pandas as pd from tweepy.asynchronous import AsyncClient from ..helpers import add_prefix if TYPE_CHECKING: from bot import Bot async def setup_cache(bot: Bot): prefixes = await b...
LeoCx1000/fish
src/utils/core/startup.py
startup.py
py
4,587
python
en
code
0
github-code
6
31957026711
from __future__ import annotations import asyncio from typing import TYPE_CHECKING, Any, Union, Optional, TypedDict, final from datetime import datetime import attr import ujson from tomodachi.utils import helpers from tomodachi.core.enums import ActionType if TYPE_CHECKING: from tomodachi.core.bot import Tomod...
httpolar/tomodachi
tomodachi/core/actions.py
actions.py
py
4,732
python
en
code
4
github-code
6
35406045180
import json import os from elasticsearch import Elasticsearch, helpers, exceptions client = Elasticsearch(os.getenv("ELASTICSEARCH_URL")) f = open("dump", "r") def main(): while True: line = f.readline() if len(line) == 0: break data = json.loads(line) yield { ...
polianax/regex
upload.py
upload.py
py
506
python
en
code
0
github-code
6
3653572970
import numpy as np import pandas as pd import matplotlib.pyplot as plt from skimage.color import rgb2lab from skimage.color import lab2rgb from sklearn.model_selection import train_test_split from sklearn.naive_bayes import GaussianNB from sklearn.pipeline import make_pipeline from sklearn.preprocessing import Function...
injoon2019/SFU_CMPT353
Exercise/e7/colour_bayes.py
colour_bayes.py
py
4,009
python
en
code
1
github-code
6
14200847696
import discord import asyncio from discord.ext import commands class Channels(commands.Cog): def __init__(self, bot): self.bot = bot self.role_bot_id = int(self.bot.config['Zone']['role_bot_id']) self.channel_private_id = int(self.bot.config['Zone']['channel_private_id']) self.cate...
yutarou12/bot-zone
cogs/channels.py
channels.py
py
3,982
python
en
code
0
github-code
6
40347602041
class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def serialize(root): queue = [root] string = "" while queue: curr = queue.pop(0) if curr is not None: queue.append(curr.left) qu...
dunningkrugerkid/programming-problems
tree_problems.py
tree_problems.py
py
1,116
python
en
code
0
github-code
6
23247293601
class Person: def __init__(self, language): self.language = language def hello(self): if self.language == "ko": print("안녕") elif self.language == "en": print("hey") def hello(language): if language == "ko": print("안녕") elif language == "en": ...
yoonej111/translation-practice-program
person.py
person.py
py
494
python
en
code
0
github-code
6
17435023939
# coding: utf-8 """ Simple multithread task manager __author_ = 'naubull2 (naubull2@gmail.com)' """ import logging import random import json import time import atexit from queue import Queue from threading import Thread logger = logging.getLogger("dialog-tool") class Worker(Thread): """ Thread executing task...
naubull2/codingtests
frequent_subjects/task_manager.py
task_manager.py
py
3,836
python
en
code
0
github-code
6
73743939389
import os from os import walk, getcwd from PIL import Image """ Class label (BDD) """ # same order with yolo format class annotation classes = [ "bike" , "bus" , "car", "motor", "person", "rider", "traffic light", "traffic sign", "train", "truck"] """ Inverse convert function """ def i_convert(size, box): ...
jwchoi384/Gaussian_YOLOv3
bdd_evaluation/convert_txt_to_bdd_eval_json.py
convert_txt_to_bdd_eval_json.py
py
2,038
python
en
code
660
github-code
6
35489755246
# file to work with polls import db_interface import random num_to_part = { 0: "noun", 1: "verb", 2: "adj", 3: "adv", 4: "other" } class Poll: def __init__(self, options, correct_option_id, question, is_anonymous): self.options = options self.correct_option_id = correct_optio...
Bliznetc/tg_bot_
polls.py
polls.py
py
2,160
python
en
code
1
github-code
6
18091289859
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('account', '0045_auto_20150130_0558'), ] operations = [ migrations.AlterField( model_name='basicmemberinformation...
hongdangodori/slehome
slehome/account/migrations/0046_auto_20150130_0600.py
0046_auto_20150130_0600.py
py
531
python
en
code
0
github-code
6
39713348458
from os.path import join, dirname, realpath, exists from PIL import Image, ImageDraw, ImageFont import numpy import base64 from io import BytesIO # info: image (PNG, JPG) to base64 conversion (string), learn about base64 on wikipedia https://en.wikipedia.org/wiki/Base64 def image_base64(img, img_type): with Bytes...
katiehickman/m224_seals
image.py
image.py
py
6,588
python
en
code
1
github-code
6
16409168230
import random import time ''' 数据库,未来数据库会向实体数据库迁移。 这些将作为初始化用数据。 并给出展示数据的一类解决方案 ''' ''' ================================================================tools================================================= ''' ''' 对只有str的list用 ''' def geting_str(lists): lis = '' for items in lists: lis += items return lis ''' 将str...
masterfzb/AIreader
data_base.py
data_base.py
py
10,760
python
en
code
1
github-code
6
35257204680
import minerl from minerl.data import BufferedBatchIter import numpy as np import random from itertools import combinations from actions import action_names import cv2 import numpy as np import torch ''' The mineRL framework models actions as dictionaries of individual actions. Player recorded demonstrat...
anishhdiwan/DQfD_Minecraft
demo_sampling.py
demo_sampling.py
py
8,704
python
en
code
0
github-code
6
71877607227
#pyautogui 라이브러리 추가 #pip install pyautogui import pyautogui #듀얼모니터는 인식 안됨 #마우스 현재 좌표 출력 #pyautogui.position() #해당 좌표로 마우스 이동 #pyautogui.moveTo(40, 154) #이미지 추출 라이브러리 추가 #pip install opencv-python #해당하는 이미지와 유사한 화면이 존재하는 위치로 이동(출력결과 : x축 값, y축 값 , 가로 길이, 세로 길이) #pyautogui.locateOnScreen('') #좌표, 저장될 이미지 길이(x축 값, y축...
BrokenMental/Python-Study
pyautogui.py
pyautogui.py
py
1,032
python
ko
code
0
github-code
6
31678929018
# import and necessary libraries import dask.distributed import dask.utils import numpy as np import planetary_computer as pc import xarray as xr from IPython.display import display from pystac_client import Client import matplotlib.pyplot as plt import folium from odc.stac import configure_rio, stac_load # Function ...
Christobaltobbin/OpenDataCube
Scripts/odc_utils.py
odc_utils.py
py
3,287
python
en
code
0
github-code
6
36818284421
import pytest from database import Model, ModelAttribute pytestmark = pytest.mark.asyncio class A(Model): a = ModelAttribute() b = ModelAttribute() c = ModelAttribute() @pytest.mark.parametrize('count', (10, 15)) async def test_insert_find(db, count): c_true_count = 0 for i in range(count): ...
AzaubaevViktor/vk_grabber
src/database/tests/test_no_uid.py
test_no_uid.py
py
1,000
python
en
code
1
github-code
6
4424193456
import sys from utils.MyStats import * if __name__=="__main__": if len(sys.argv) != 2: print("Error: number arguments") exit() classes_ = ["Ravenclaw", "Slytherin", "Gryffindor", "Hufflepuff"] path = sys.argv[1] classes_label = "Hogwarts House" drop_columns = ["First Name", "Last Na...
artainmo/dslr
scatter_plot.py
scatter_plot.py
py
637
python
en
code
0
github-code
6
35540502029
a, b = map(int, input().split()) if a > b: temp: int = a a, b = b, temp arr = list([i for i in range(a+1, b)]) print(len(arr)) for i in arr: print(i, end=" ")
BlueScreenMaker/Yeummy_Algorithm
BOJ/BOJ 10093 숫자.py
BOJ 10093 숫자.py
py
173
python
en
code
0
github-code
6
21018004406
#!/usr/bin/env python # -*- coding: utf -8 -*- """ Collection of functions for TLE propagation and estimation =========================================================== """ __author__ = "Mirco Calura" __maintainer__ = "Matteo Aquilano" __copyright__ = "Copyright 2020 by SES ENGINEERING S.A. All Rights Reserve...
maxmartinezruts/satellite-collision-avoidance-GUI
DataProcess/sgp4/tle_lib.py
tle_lib.py
py
4,482
python
en
code
3
github-code
6
43372057736
from Node import Node #if greater we go right, if lower we go left class BST: def __init__(self, head_node_value): self.head_node = Node(head_node_value) #this is an instance of the Node self.sorted_node_values = [] def add_node(self, value, node=None): new_node = Node(value) ...
simachami/Week4-Day3
BST.py
BST.py
py
3,125
python
en
code
0
github-code
6
1957129894
# import the modules to access their methods import random import time import emoji # Defined this user defined function def ran(): inp = int(input("Guess the number Between 1 and 10\n")) Guess = None Guess = random.randrange(1,10) if inp > 0 and inp < 11: if inp == Guess: # g...
RajeshKumar-1998/Guess-No-Game
Guess Num Game.py
Guess Num Game.py
py
1,258
python
en
code
0
github-code
6
44427355496
import os from test_framework.test_framework import BitcoinTestFramework from test_framework.util import (assert_equal, assert_raises_rpc_error) def read_dump(file_name, addrs, hd_master_addr_old): """ Read the given dump, count the addrs that match, count change and reserve. Also check that the old hd_m...
bitcoin-sv/bitcoin-sv
test/functional/wallet-dump.py
wallet-dump.py
py
4,774
python
en
code
597
github-code
6
6144518391
def number_stops(m,n,stops): current = 0 nb =0 last = -1 while(current<=n): last = current while(current<=n) and (stops[current+1]-stops[last]<=m): current += 1 if current == last: return -1 elif(current<=n): nb +=1 return nb if ...
OualhaSlim/Algorithmic-Toolbox
greedy_algorithms/3_car_fueling.py
3_car_fueling.py
py
525
python
en
code
0
github-code
6
156567587
#-*- coding: utf-8 -*- import numpy as np from sklearn.cluster import AgglomerativeClustering as sk_AgglomerativeClustering from sklearn.externals.joblib import Memory from .clustering import Clustering class AgglomerativeClustering(Clustering): """docstring for AgglomerativeClustering.""" def __init__(self, d...
netoaraujjo/hal
clustering/agglomerative_clustering.py
agglomerative_clustering.py
py
1,946
python
en
code
0
github-code
6
42284509571
class Stack: stack = "" def __init___(self): pass def push(self, element): self.stack += element def pop(self): element = None if not self.is_empty(): element = self.stack[-1] self.stack = self.stack[:-1] return element def __str__(self): return self.stack def is_empty(self): if len(...
rijumone/compete_code
g4g/parantheses_checker.py
parantheses_checker.py
py
2,221
python
en
code
0
github-code
6
29552040169
import numpy as np import unittest def canonize_labels(x, support=None): ''' 1. construct a dict - if not support, construct using np.unique - if support, check validation, then iterate to get the dict 2. use map to transform the data ''' if type(x) == list: x = np.array(x) ...
rafaelxiao/infinity
tools/process_canonize_labels.py
process_canonize_labels.py
py
985
python
en
code
0
github-code
6
12722977840
#!/usr/bin/python3 import numpy as np import random """ w/ decision tree we want to choose features based on greatest information gain (smallest entropy) p_dot = P/(P+N) Entropy: Imp(p_dot) = -p_dot*log_2(p_dot) - (1-p_dot)log_2(1-p_dot) Combine entropy of branches with weights for total entropy after split Lowest E...
Mgla96/DiabeticRetinopathy
diabeticret.py
diabeticret.py
py
17,450
python
en
code
0
github-code
6
39371296170
pcts = ("10", "12", "15") # Tuple pcts_types = " or ".join(pcts) print("Welcome to the tip calculator!") bill = float(input("What was the total bill? $")) tip = int(input(f"What percentage tip would you like to give? {pcts_types}? ")) people = int(input(f"How many people to split the bill? ")) amount = round(((bill * ...
carlohcs/100-days-of-code-python-pro-bootcamp-for-2022
days/03/tip_calculator.py
tip_calculator.py
py
430
python
en
code
0
github-code
6
7769213718
import numpy as np import torch import random from PIL import Image #---------------------------------------------------------# # 将图像转换成RGB图像,防止灰度图在预测时报错。 # 代码仅仅支持RGB图像的预测,所有其它类型的图像都会转化成RGB #---------------------------------------------------------# def cvtColor(image): if len(np.shape(image)) == 3 and np.shap...
yangshunzhi1994/SCD
object verification/utils/utils.py
utils.py
py
3,489
python
en
code
0
github-code
6
40687305933
import argparse import json from typing import List from google.protobuf import json_format from load_tests.common import ( benchmark_grpc_request, make_full_request_type, make_output_file_path, ) from magma.common.service_registry import ServiceRegistry from orc8r.protos.common_pb2 import Void from orc8r....
magma/magma
lte/gateway/python/load_tests/loadtest_directoryd.py
loadtest_directoryd.py
py
7,544
python
en
code
1,605
github-code
6
35317487695
from flask_socketio import send, emit, join_room from flaskapp.blueprints.web.models.chat import ChatModel def getChat(socketio): # @socketio.on('connect') # def connect(): # print('connect: ') @socketio.on('joinPrivateGroup') def joinPrivateGroup(data): print('joinPrivateGroup', data)...
Igorok/flaskapp
flaskapp/blueprints/web/chat.py
chat.py
py
861
python
en
code
0
github-code
6