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
75051539708
# -*- coding: utf-8 -*- r""" tests.test_state ~~~~~~~~~~~~~~~~ Tests for the \p State class including movement mechanics and enumeration of the \p MoveSet class. :copyright: (c) 2019 by Zayd Hammoudeh. :license: MIT, see LICENSE for more details. """ from typing import Tuple import pytest fr...
ZaydH/stratego
src/tests/test_state.py
test_state.py
py
14,130
python
en
code
0
github-code
6
22844256236
nstations = int(input()) nlines = int(input()) station_lines = {} # station -> lines for i in range(nlines): _, *stations = map(int, input().split()) for st in stations: station_lines.setdefault(st, []).append(i) start, end = map(int, input().split()) #=== from itertools import combinations fr...
sergey-ryzhikov/yandex-alogotrain-3.0B
t40.py
t40.py
py
1,563
python
en
code
0
github-code
6
30434077830
#%% # 신호 기록 가져오기 with open('sample_20200601_pointfinger.txt', 'r') as openfile : samples = openfile.readlines() tmp_timests = [ samples[i][:-1] for i in range(len(samples)) if i%3==0 ] tmp_samples = [ samples[i][:-1] for i in range(len(samples)) if i%3==1 ] #%% # 중복된 시간 기록 제거 timests, samples = list(), list() del...
oimq/DoTheEHands
SignalAnalyzer.py
SignalAnalyzer.py
py
6,880
python
en
code
0
github-code
6
17968730699
# Databricks notebook source # MAGIC %md # MAGIC # Train Machine Learning Model # MAGIC # MAGIC This notebook aims to develop and register an MLFlow Model for deployment consisting of: # MAGIC - a machine learning model to predict the liklihood of employee attrition. # MAGIC # MAGIC This example uses an adapted versio...
nfmoore/azure-databricks-mlops-example-scenarios
core/notebooks/train_model.py
train_model.py
py
7,954
python
en
code
2
github-code
6
3360586236
""" 백준 1012 : 유기농 배추 """ """ BFS - Breath first Search 한번 방문한 지점은 절대로 다시 방문하지 않는다. """ from collections import deque import sys input=sys.stdin.readline dx=[-1,1,0,0] dy=[0,0,-1,1] # ( -1, 0) ( 1,0) ( 0,-1) (0,1) def BFS(graph,visit , x, y): deq=deque() deq.append([x,y]) visit[x]...
030831/2023-Winter_Vacation_GroupStudy
1012.py
1012.py
py
1,301
python
ko
code
0
github-code
6
43469204471
from __future__ import annotations import yaml import os import errno __all__ = ["save_setup", "read_setup"] def save_setup(setup: dict, path: str): """ Save Model initialization setup dictionary. Parameters ---------- setup : dict The setup dictionary to be saved to `YAML <https://yaml...
DassHydro-dev/smash
smash/io/setup_io.py
setup_io.py
py
2,170
python
en
code
2
github-code
6
13289274017
import os import platform import sys try: from pip._internal.operations import freeze except ImportError: # pip < 10.0 from pip.operations import freeze py_version = sys.version.replace("\n", " ") py_platform = platform.platform() pkgs = freeze.freeze() pip_pkgs = "\n".join( pkg for pkg in pkgs ...
kalaracey/runhouse
collect_env.py
collect_env.py
py
1,178
python
en
code
null
github-code
6
74175163389
# -*- coding:utf-8 -*- """ 题目描述:大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0) """ class Solution: def Fibonacci(self, n): # write code here dp = [0,1] if n>=2: for i in range(2,n+1): dp.append(dp[i-1]+dp[i-2]) return dp[n]
xxxsssyyy/offer-Goal
07斐波那契数列.py
07斐波那契数列.py
py
392
python
zh
code
7
github-code
6
10420754903
from __future__ import annotations import asyncio import os import platform import re from asyncio import IncompleteReadError, StreamReader, StreamWriter from pathlib import Path from typing import TYPE_CHECKING from randovania.patching.patchers.exceptions import UnableToExportError if TYPE_CHECKING: from collec...
randovania/randovania
randovania/games/prime2/patcher/csharp_subprocess.py
csharp_subprocess.py
py
3,321
python
en
code
165
github-code
6
21764328772
# Approach 1 - Breadth-First Search # Time: O(N) # Space: O(N) from collections import deque class Solution: def orangesRotting(self, grid: List[List[int]]) -> int: queue = deque() # build the initial set of rotten oranges fresh_oranges = 0 ROWS, COLS = len(grid), len(gri...
jimit105/leetcode-submissions
problems/rotting_oranges/solution.py
solution.py
py
1,876
python
en
code
0
github-code
6
72613074749
#Importing the Morse code Letters from letter_morse import ENGLISH_TO_MORSE #Looping through the letters MC_TO_ENGLISH = {} for key, value in ENGLISH_TO_MORSE.items(): MC_TO_ENGLISH[value] = key #Function for converting Eng to Morse def english_to_mc(message): morse = [] for char in message: ...
Bophelo11/Morse-Code-convertor
MorseCodeConverterPortfolio/main.py
main.py
py
1,375
python
en
code
0
github-code
6
25363489701
import psycopg2 from users import * from moderators import * def menu(): # Menu voor het kiezen van de verschillende opties. while True: print("Welcome to our program.") menu_choice = int(input("1. Would you like to leave a message?\n" "2. Would you like to log in as a m...
DamianPlomp/stationszuil
main.py
main.py
py
850
python
en
code
0
github-code
6
42857124490
import pytest from django.conf import settings from django.test import override_settings from .compat import nullcontext def pytest_configure(): settings.configure( **dict( SECRET_KEY="abcd", INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.s...
thaitl235/djangorestframework-api-key
tests/conftest.py
conftest.py
py
2,739
python
en
code
null
github-code
6
2338682136
import pandas as pd import numpy as np import json from collections import defaultdict from play_by_play import PlayByPlay #define front end variables DATE = '2015-12-25' SEASON = '2015-16' SEASON_TYPE = 'Regular+Season' # 'Regular+Season' or 'Playoffs' HOME_TEAM = 'LAL' def build_df(json): rows = [] for fr...
nalin1096/DS5500_Player_Tracking_and_Identification_NBA
helpers/play_by_play/pbp_ocr.py
pbp_ocr.py
py
4,444
python
en
code
6
github-code
6
37961270756
import dash_html_components as html import dash from dash.dependencies import Input, Output import dash_table import pandas as pd import dash_core_components as dcc df = pd.read_csv('GraphVisualizationLearning\/data.csv') # print(df['seed'][2]) # print(df['seed']) del df['seed'] # df = df.dropna() dff = df[["Config",...
shashank793/DataVisualisation
venv/simple_graph/create_tabl.py
create_tabl.py
py
6,981
python
en
code
0
github-code
6
22666651676
def main(): # Upper limit is the highest 1_2_3_4_5_6_7_8_9_0 number # while the lower limit is the lowest. # # Returns the first (only) number that matches # the given pattern mathematically. # # The variable i has to end in 0, for the square to also # end with the number 0, therefore...
kakuttaja/project-euler
206.py
206.py
py
934
python
en
code
0
github-code
6
438092224
from django.http import HttpResponse from django.shortcuts import redirect, reverse, render from cart.models import Cart, Item, OrderItem, Basket from product_listing.models import Product import cart.forms import datetime from django.contrib.auth import authenticate # Create your views here. def index(request): cont...
ftaoussi/COMP307---Marketplace
cart/views.py
views.py
py
4,769
python
en
code
0
github-code
6
39702394709
from flask import Blueprint from flask import render_template, url_for, request from flask import make_response, send_from_directory from werkzeug.utils import secure_filename import os from apps.xmind2caseapp import write2excel, xmind2case x2c = Blueprint('x2c',__name__) # workpath = os.getcwd() workpath=os.path.di...
siqyka/QtestTool
x2c.py
x2c.py
py
1,860
python
en
code
0
github-code
6
29127983258
from django.test import TestCase from django.utils.translation import ugettext_lazy as _ from social_links import forms class LinksFormTests(TestCase): def taset_clean_url(self): valid_urls = [['https://www.example.com','https://www.example.com'] ['http://www.example.com','http://w...
TimBest/ComposersCouch
social_links/tests/tests_forms.py
tests_forms.py
py
5,893
python
en
code
1
github-code
6
5384553044
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals import os __DIR__ = os.path.abspath(os.path.dirname(__file__)) from ply import lex, yacc from .data import Domain, MsgId, MsgStr, MsgStrPlural, MsgStrList, Message class ParserException(Exception): pass DEB...
takada-at/ponda
ponda/parser.py
parser.py
py
5,662
python
en
code
0
github-code
6
37269948830
def unboundedKnapsack(n, w, items, weights): if n == 0 or w == 0: return 0 if dp[n][w] != -1: return dp[n][w] if weights[n-1] <= w: dp[n][w] = max(items[n-1]+unboundedKnapsack(n, w-weights[n-1], items, weights), unboundedKnapsack(n-1, w, items, weights)) ...
richiabhi/Self---Dp
unboundedKnapsack memoized.py
unboundedKnapsack memoized.py
py
593
python
en
code
0
github-code
6
34371656679
############################################################################################################ from colorama import * import os import requests import re ############################################################################################################ def search_words_in_file(file_path,...
OMGmultitools/Anti-Grabber
Anti Grabbee.py
Anti Grabbee.py
py
3,123
python
en
code
0
github-code
6
2052137958
# Program to try and work out the power spectrum import numpy as np import matplotlib.pyplot as plt from scipy.fftpack import fft, fftfreq, ifft n = 1024 Lx = 100 omg = 2.0*np.pi/Lx x = np.linspace(0, Lx, n) y1 = 1.0*np.cos( 5.0*omg*x) y2 = 1.0*np.sin(10.0*omg*x) y3 = 0.5*np.sin(20.0*omg*x) y = y1 + y2 + y3 act = y1...
arunprasaad2711/Python_IISC_SIAM_2017
Programs_Session3/06_FFT_IFFT_example.py
06_FFT_IFFT_example.py
py
2,057
python
en
code
8
github-code
6
37555045718
# Low-Dose CT with a Residual Encoder-Decoder Convolutional Neural Network (RED-CNN) # https://arxiv.org/ftp/arxiv/papers/1702/1702.00288.pdf # reference https://github.com/SSinyu/RED-CNN import os import numpy as np import torch.nn as nn from model import common def make_model(args, parent=False): return REDCNN(...
stefenmax/pytorch-template-medical-image-restoration
src-v3/model/redcnn.py
redcnn.py
py
2,084
python
en
code
6
github-code
6
39868308641
from django.db import models from main.model.playlist import Playlist from main.model.track import Track class PlaylistTracks(models.Model): playlist = models.ForeignKey( Playlist, on_delete=models.CASCADE ) # при удалении плейлиста чистится кросс-таблица track = models.ForeignKey( ...
artemgv/spacemusic
app/main/model/playlisttracks.py
playlisttracks.py
py
992
python
en
code
0
github-code
6
39697377859
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits import mplot3d # index boundaries for time 3D plot nStart = 140000 nEnd = 160000 with open("time_series_stochastic_old.txt", "r") as file: lines = file.readlines() time = [] intensity = [] E_real = [] E_imag = [] for line in lines:...
sir-aak/microscopically-derived-rate-equations
plotscripts/mdre_plotscript_spiking_detail.py
mdre_plotscript_spiking_detail.py
py
1,701
python
en
code
1
github-code
6
72357813309
# ============================================================================== # Main runner entry point for the project # Implemented using SAGE math library # # Author: Malo RANZETTI # Date: Spring 2023 # ============================================================================== import os import msidh import ...
mrztti/M-SIDH
run.py
run.py
py
5,043
python
en
code
1
github-code
6
25602972286
def sums(items): luvut = {0: 1} x = 0 for i in items: new = {} for j in luvut: summa = i + j new.update({j: 1}) if summa not in luvut: new.update({summa: 1}) x += 1 luvut = new return x # Juho Heiskasen ratkais...
Noppacase22/DSA-2022
sums.py
sums.py
py
1,076
python
en
code
0
github-code
6
43168508245
import asyncio import json import logging import typing from pathlib import Path import discord from discord.ext import commands from fuzzywuzzy import process from roycemorebot.constants import ( Categories, Channels, Emoji, Guild, MOD_ROLES, StaffRoles, ) log = logging.getLogger(__name__) ...
egelja/roycemorebot
roycemorebot/exts/subscriptions.py
subscriptions.py
py
15,209
python
en
code
1
github-code
6
24522571380
import torch import torch.nn as nn import torch.optim as optim from torchvision import datasets, transforms # 定义客户端类 class Client: def __init__(self, model, train_loader, test_loader, lr=0.1): self.model = model self.train_loader = train_loader self.test_loader = test_loader self.op...
huguangs/NIID-Bench-main-master
top-k/main.py
main.py
py
4,358
python
en
code
0
github-code
6
22868199973
from global_function import data_exist, rindex import pickle def Filter_Redundancy(type, query, replace_space, replace_percentage, replace_apostrophe, replace_plus): with open('Resources/redundancy/media search redundancy filter.pck', 'rb') as file: media_search_redundancy = pickle.load(file) for...
TroySigX/smartbot
mediaSearch.py
mediaSearch.py
py
2,195
python
en
code
2
github-code
6
36813380552
"""empty message Revision ID: 073719702e2e Revises: 23ecd00cae18 Create Date: 2020-03-29 13:31:19.799319 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '073719702e2e' down_revision = '23ecd00cae18' branch_labels = None depends_on = None def upgrade(): # ...
koiic/project-tracker
migrations/versions/073719702e2e_.py
073719702e2e_.py
py
1,333
python
en
code
0
github-code
6
15412087448
from django.shortcuts import render from django.http import HttpResponse from django.utils.translation import get_language from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.decorators import login_required from django.conf import settings from . import Checksum from paytm.models import Pa...
harishbisht/paytm-django
payments/paytm/views.py
views.py
py
2,130
python
en
code
31
github-code
6
75066284348
import torch import logging import pickle from core.utils import scale_image, save_layer_image from data import image_corruption def evaluate(model, loader, args, perturbation=False, pSize=0, **kwargs): objective_function= kwargs.get('objective_function', None) device = kwargs['device'] if 'epoch' in kwar...
SMRhadou/UnrolledGlow
core/evaluation.py
evaluation.py
py
1,612
python
en
code
0
github-code
6
31512974964
import json import requests import constants import tokens def make_api_call(access_token, url, method, **kwargs): response = method( url=url, headers={ "Accept": "application/json", "Content-Type": "application/json", "Authorization": f"Bearer {access_token}",...
rjshearme/spotify_recently_added_playlist
api.py
api.py
py
1,168
python
en
code
0
github-code
6
35608959841
#!/usr/bin/env python try: import orz except ImportError: import os import sys curr_path = os.path.abspath(os.path.dirname(__file__)) sys.path.append(os.path.join(curr_path, "D:\Working\OpenRoleZoo\OpenRoleZoo\python")) import orz import os def timestamp(filename): if not os.path.exists(f...
SeetaFace6Open/OpenRoleZoo
python/model2model2.py
model2model2.py
py
1,296
python
en
code
1
github-code
6
70680835069
from flask import Flask from flask import render_template import ffmpeg_streaming from ffmpeg_streaming import Formats import sys app = Flask(__name__) @app.route("/") def streaming(): return render_template('streaming.html') @app.route('/video') def video_server(): video = ffmpeg_streaming.input('pexels_video....
ifcassianasl/python_test_rtsp
main.py
main.py
py
764
python
en
code
1
github-code
6
21629194042
import tensorflow as tf from data_structures import UNK_label, PAD_label def TEEmbeddingLayer(size_TE_label_vocab, size_TE_label_embed, TE_label_set): if TE_label_set == 'none': raise NotImplementedError('Can\'t embed TE labels if there are no TE labels') return tf.keras.layers.Embedding(size_TE_lab...
bnmin/tdp_ranking
frozen_bert/te_embedding.py
te_embedding.py
py
1,927
python
en
code
1
github-code
6
779248836
from dataclasses import dataclass from typing import Annotated, List from fastapi import Depends from fastapi_pagination import Page from fastapi_pagination.ext.sqlalchemy import paginate from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from config.db import get_db_session from readconnec...
YeisonKirax/readconnect-back
src/readconnect/books/infrastructure/db/repository/books_repository.py
books_repository.py
py
2,625
python
en
code
0
github-code
6
11232494681
from collections import defaultdict ENTER = "Enter" LEAVE = "Leave" CHANGE = "Change" ENTER_MESSAGE = "님이 들어왔습니다." LEAVE_MESSAGE = "님이 나갔습니다." class ChatRoom: def __init__(self): super().__init__() def operation(result, command, chatRoom, nicknames, uid="", name=""): if command == ENTER: ...
gatherheart/Solved_PS
KAKAO/2019_KAKAO_1.py
2019_KAKAO_1.py
py
1,378
python
en
code
0
github-code
6
70276262907
import torch import time import argparse from importlib import import_module import numpy as np import utils import train parser = argparse.ArgumentParser(description='BertClassifier') # parser.add_argument('--model', type=str, default='BertFc', help='choose a model') # parser.add_argument('--model', type=str, defaul...
Jacquelin803/Transformers
BertClassifier/main.py
main.py
py
2,007
python
en
code
1
github-code
6
5489764282
""" Module that provides different readers for trajectory files. It also provides a common interface layer between the file IO packages, namely pygmx and mdanalysis, and mdevaluate. """ from .checksum import checksum from .logging import logger from . import atoms from functools import lru_cache from collections impo...
mdevaluate/mdevaluate
mdevaluate/reader.py
reader.py
py
12,347
python
en
code
5
github-code
6
73492056828
#Name: Ishika Soni #Email: ishika.soni97@myhunter.cuny.edu #Date: October 4, 2021 #This program asks the user for a 6-digit hex number and uses it as the hex code #to stamp 4 turtles of that color into a square. import turtle mess = input("Please enter a 6-digit Hexadecimal number: ") wn = turtle.Screen() alex = tur...
issoni/Short-Turtle-Graphics
14colored-square.py
14colored-square.py
py
454
python
en
code
0
github-code
6
5446974377
import numpy as np import scipy as sp import matplotlib import matplotlib.pyplot as plt from matplotlib import cm def func2(x): return np.round(np.random.random()) def func(x,y,z,r): l = np.linalg.norm(np.array([x,y,z])) if(l < r): return 1.0 else: return 0.0 def normalize_signal_1d(...
mcastrorib/bergman_periodic_solution
python/fft_test.py
fft_test.py
py
9,440
python
en
code
0
github-code
6
74796406586
from torch.utils.tensorboard import SummaryWriter from torchvision import transforms import cv2 from PIL import Image # 1、transform使用Totensor img_path = "../dataset/train/ants/0013035.jpg" img_PIL = Image.open(img_path) tensor_trans = transforms.ToTensor() img_tensor = tensor_trans(img_PIL) # 2、tensor数据类型 writer = S...
ccbit1997/pytorch_learning
src/learn_transform.py
learn_transform.py
py
1,344
python
en
code
0
github-code
6
37562147384
"""helper ============= Helper functions for inventory scripts. """ __author__ = "Balz Aschwanden" __email__ = "balz.aschwanden@unibas.ch" __copyright__ = "Copyright 2017, University of Basel" __credits__ = ["Balz Aschwanden"] __license__ = "GPL" import json import os import socket def get_hostname(): """Ret...
ANTS-Framework/ants
antslib/inventory/helper.py
helper.py
py
1,278
python
en
code
42
github-code
6
24981950749
fishlist = list(map(int, open('2021\D6\input.txt','r').read().split(',') )) print(fishlist) days = 256 numfish = [] numfish.append([0]*7) # old fish 0 -> 6 numfish.append([0]*2) # new fish 0 -> 1 out = 0 for fish in fishlist: numfish[0][fish] += 1 for day in range(days): temp = [0]*7 ...
elliotcoy/AdventOfCode2021
2021/D6/P2.py
P2.py
py
677
python
en
code
0
github-code
6
35413595898
# -*- coding:utf-8 -*- import random import pygame class BoardManager: WALL = 0 FOOD = 1 NONE = 2 HEAD = 3 BODY = 4 def __init__(self, x_blocks, y_blocks, block_width, origin_x, origin_y, caption): self.x_blocks = x_blocks self.y_blocks = y_blocks # NONE的方块 sel...
coderwf/pygames
glutsnake/board.py
board.py
py
4,748
python
en
code
0
github-code
6
6606127726
dx = [0, 0, 1, -1] dy = [-1, 1, 0, 0] def solution(game_board, table): def rotate(): tmp = [] for elm in block_piece: start_x, start_y = elm[0] space = [(0, 0)] for x, y in elm[1:]: space.append((start_y-y, x-start_x)) space.sort(key=...
JeongGod/Algo-study
hyeonjun/18week/p84021.py
p84021.py
py
2,031
python
en
code
7
github-code
6
34787406936
from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity from wordcloud_process import wordcloud_img from article_loader import ArticleLoader article_loader = ArticleLoader('english_corpora.yaml') articles = article_loader.load() def feature_and_matrix(arti...
is3ka1/NLP-Practice
week1/english_news_analyse.py
english_news_analyse.py
py
1,252
python
en
code
0
github-code
6
21836192189
import sys from pprint import pprint sys.stdin = open('../input.txt', 'r') N = int(input()) dp = [[0] * 10 for _ in range(N)] dp[0] = [1] * 10 for i in range(1, N): # 행 for j in range(10): # 열 for k in range(j, 10): dp[i][k] += dp[i-1][j] print(sum(dp[N-1]) % 10007)
liza0525/algorithm-study
BOJ/boj_11057_increasing_number.py
boj_11057_increasing_number.py
py
298
python
en
code
0
github-code
6
25172905892
#%% import pandas as pd import altair as alt import numpy as np from sklearn.neighbors import NearestNeighbors alt.data_transformers.disable_max_rows() #%% RADICL_file="/home/vipink/Documents/FANTOM6/HDBSCAN_RADICL_peak/data/processed/chr16_filter_df.csv" #%% radicl_df = pd.read_csv(RADICL_file,delimiter="\t") # Obser...
princeps091-binf/HDBSCAN_RADICL_peak
scripts/RADICL_read_neighbourhood.py
RADICL_read_neighbourhood.py
py
2,053
python
en
code
0
github-code
6
6597568149
from numpy.polynomial import Polynomial as P from numpy import polynomial print("Interpolação de Newton") pontos = [] k = 0 while True: k += 1 while True: print("Digite as coordenadas do ", k, "º ponto separados por espaço:", end="\nf para finalizar \n") l = input() if l == "f".lower...
fernandoajn/calculo-numerico
metodos/newton.py
newton.py
py
2,151
python
pt
code
1
github-code
6
70622403067
class Car : addr = '서울' #static 변수 역할 __slots__ = ['name', 'price', 'company'] # 슬롯 . 이 클래스가 가질 수 있는 멤버변수명을 미리 지정해 줄 수 있다. def __init__(self, **args): if 'name' in args: # self.add(value) #이런식으로 넣을 수 없음 의미가없다. self.name = args['name'] if 'price' in args: ...
Yang-Seungjae/Python
test.py
test.py
py
1,048
python
ko
code
0
github-code
6
3721769844
import io import time from openpyxl import Workbook import openpyxl as O import speedtest import re import sys import psycopg2 from psycopg2 import Error from datetime import datetime import hashlib from .connection import Connection cn=Connection() class SpeedPage(): def asking_name(self): print("Введите ваше ИМЯ...
Astarota/SpeedTestCLI
pages/speed_page.py
speed_page.py
py
3,737
python
en
code
0
github-code
6
29192430322
# Hack 1: InfoDB lists. Build your own/personalized InfoDb with a list length > 3, create list within a list as illustrated with Owns_Cars InfoDb = [] # List with dictionary records placed in a list InfoDb.append({ "FirstName": "Joan", "LastName": "Mir", "Number":...
kkwan0/Tri-3-Kurtis-Kwan
week1/infoDB.py
infoDB.py
py
2,157
python
en
code
0
github-code
6
8909257357
import numpy as np import cv2 import os from PIL import Image X = 10 # 0 Y = 105 # 95 WIDTH = 215 # 356 HEIGHT = 440 # 440 def process_img(original_img): processed_img = cv2.cvtColor(original_img, cv2.COLOR_BGR2GRAY) processed_img = cv2.resize(processed_img, (10, 20)) return processed_img def grab_screen...
sebastianandreasson/tetris_tensorflow
grab_screen.py
grab_screen.py
py
671
python
en
code
0
github-code
6
6748902164
import cv2 import numpy as np import face_recognition import os from datetime import datetime import keyboard import os import pandas as pd train_data_path = os.path.join('artifacts', "attendance.csv") os.makedirs(os.path.dirname(train_data_path), exist_ok=True) columns =['Name','Time'] test = [] train = pd.DataFrame(...
aruneer007/attendance
face.py
face.py
py
2,859
python
en
code
0
github-code
6
9580721700
""" Tomasulo main module. """ import argparse import logger from machine import Machine def main(): """ Main entry point. Parses command line argument and begins execution. :return: None """ parser = argparse.ArgumentParser(description='Simulate execution of DLX code on a Tomasulo processor....
kaledj/TomasuloSim
tomasulo.py
tomasulo.py
py
751
python
en
code
0
github-code
6
7946627355
from cs50 import get_float # The coins quarter = 25 dime = 10 nickel = 5 penny = 1 # Counter for change owed counter = 0 # To get the number from user while True: dollars = get_float("Change owed: ") if dollars >= 0: break # Converting to cents cents = int(round(dollars * 100)) ...
eiliaJafari/CS50X-2021
ProblemSets/6/cash.py
cash.py
py
774
python
en
code
0
github-code
6
73951878269
""" faster """ class Solution: def countArrangement(self, N: int) -> int: li=list(range(0,N+1)) # 1-indexing # 0 is useless self.ans=0 def backtrack(right): # swap from RHS # from RHS is better since larger numbers are less likely to be Beautiful # if we start from left to right there will ...
y56/leetcode
526. Beautiful Arrangement/solns.py
solns.py
py
1,643
python
en
code
0
github-code
6
24436690438
from __future__ import annotations import idaapi import pyphrank.utils as utils from pyphrank.ast_analyzer import CTreeAnalyzer, TFG from pyphrank.cfunction_factory import CFunctionFactory from pyphrank.type_flow_graph_parts import Node, UNKNOWN_SEXPR def get_funcname(func_ea: int) -> str: return idaapi.get_name(f...
Mizari/phrank
pyphrank/function_manager.py
function_manager.py
py
5,588
python
en
code
51
github-code
6
35492004084
from ninja import Router from ninja import NinjaAPI, File from ninja.files import UploadedFile from django.http import HttpResponse from RECOGNIZE.text_reader import OCR_Reader import io import PIL.Image as Image import cv2 import os import time import json import uuid import requests router = Router() path = __file__...
fakhrilak/image_recognize
RECOGNIZE/index.py
index.py
py
2,687
python
en
code
0
github-code
6
35010781963
from grafo.Grafo import * from collections import deque class EdmondsKarp: def __init__(self, grafo: Grafo) -> None: self.grafo = grafo self.fluxo = {arco: 0 for arco in self.grafo.arcos.values()} self.fluxo = {} for arco in self.grafo.arcos.values(): self.fluxo[(arco.v...
jdanprad0/INE5413-Grafos
Atividade-03-Grafos/algoritmos_t3/edmondsKarp/EdmondsKarp.py
EdmondsKarp.py
py
2,190
python
en
code
0
github-code
6
6159961636
import json a = { "name": "ivo", "age": "22" } def serialize_to(path, data): json_string = json.dumps(a, indent=4) with open(file, "w") as f: f.write(json_string) def unserialize_from(path): with open(path, "r") as f: contents = f.read() return json.loads(contents)
Vencislav-Dzhukelov/101-3
week3/3-Panda-Social-Network/panda_json.py
panda_json.py
py
316
python
en
code
0
github-code
6
18101264424
from typing import List, Tuple from unittest import TestCase, main class Solution: def longestPalindrome(self, s: str) -> str: def func(left: int, right: int, longest: str) -> str: """returns the longest palindromic substring using left and right index""" longest_length = len(longe...
hirotake111/leetcode_diary
leetcode/longest_palindromic_substring/solution.py
solution.py
py
1,187
python
en
code
0
github-code
6
25408409971
from FemFrameTool import read_fun, read_vel from RPData import RPData # from IntegratorST import integrate_by_st_vert, integrate_by_st_vem import numpy as np import pandas as pd def calc_area_field(relative_path): area = read_fun(relative_path + 'field_1.fun') return area def calc_height_field(relative_path): he...
brilliantik/Color_ST_Integrate
CalcParam.py
CalcParam.py
py
7,887
python
en
code
0
github-code
6
13974817829
from pydantic import BaseModel, Field from typing import List, Union import pydantic from .validators import validate_polygon, validate_is_plane_orthogonal_to_polygon, validate_plane_normal_is_not_zero class Point3DModel(BaseModel): __root__: List[float] = Field(..., min_items=3, max_items=3) class PlaneModel...
mikheev-dev/polygon_splitter
src/data_model.py
data_model.py
py
2,164
python
en
code
1
github-code
6
33551925024
import requests as rq from dotenv import load_dotenv import os import smtplib import sys class FPL: URL = 'https://fantasy.premierleague.com/api/bootstrap-static/' def __init__(self): self.response_raw = rq.get(FPL.URL) load_dotenv() self.email_sent = os.getenv('EMAIL_SENT') ...
FilleDille/fpl_reg_chaser
main.py
main.py
py
1,966
python
en
code
0
github-code
6
35416632908
import logging import battle.main import memory.main import screen import xbox FFXC = xbox.controller_handle() logger = logging.getLogger(__name__) def yojimbo(gil_value: int = 263000): logger.info("Yojimbo overdrive") screen.await_turn() memory.main.wait_frames(6) if not screen.turn_aeon(): ...
coderwilson/FFX_TAS_Python
battle/overdrive.py
overdrive.py
py
723
python
en
code
14
github-code
6
5480419217
import os import requests from bs4 import BeautifulSoup import re import time import sys user_agent = 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36' def get_music_data(url): """ 用于获取歌曲列表中的歌曲信息 """ headers = {'User-Agent':user_agent} ...
haochen1204/Reptile_WYYmusic
网易云爬虫.py
网易云爬虫.py
py
3,336
python
en
code
1
github-code
6
35177658753
import numpy as np from sklearn.model_selection import train_test_split class ToyDataset: def __init__(self, min_len, max_len): self.SOS = "<s>" self.EOS = "/<s>" self.characters = list("abcd") self.int2char = self.characters # 1 for SOS, 1 for EOS, 1 for padding ...
xuzhiyuan1528/tf2basic
Seq2Seq/Utils.py
Utils.py
py
2,080
python
en
code
0
github-code
6
25205799104
# -*- coding: utf-8 -*- """ Abstract class for detectors """ import abc class Embedder(abc.ABC): @abc.abstractmethod def embed(self): 'Return embed features' return NotImplemented @abc.abstractmethod def get_input_shape(self): 'Return input shape' return NotI...
chunhanl/ElanGuard_Public
src/face_reid/embedders.py
embedders.py
py
10,556
python
en
code
13
github-code
6
17176402024
import datetime import h5py import librosa import numpy as np import os import pandas as pd import soundfile as sf import sys import time import localmodule # Define constants. data_dir = localmodule.get_data_dir() dataset_name = localmodule.get_dataset_name() orig_sr = localmodule.get_sample_rate() negative_labels ...
BirdVox/bv_context_adaptation
src/001_generate-audio-clips.py
001_generate-audio-clips.py
py
6,126
python
en
code
8
github-code
6
31854187897
# 歌词解析程序 # 歌词管理器 <> 词句 import time import os # 建立数据模型,储存一句歌词的相关信息 class LrcItem: time = 0.0 # 以秒为单位的时间 seg = "" # 一句歌词 def __init__(self, time, seg): self.time = time self.seg = seg # 歌词管理器,负责通过时间获取歌词 class LrcManager: lrcList = [] # 设置歌词路径 def set_lrc_path(self, pat...
920630yzx/python_course
pycharm学习-进阶篇/面向对象的程序设计/4.1歌词(项目).py
4.1歌词(项目).py
py
2,916
python
zh
code
0
github-code
6
8385108161
from __future__ import absolute_import from __future__ import print_function import argparse from lxml import etree parser = argparse.ArgumentParser( description='Create tls links from sumo net as needed by tls_csv2SUMO.py. You have to edit the link number ' + 'field (preset with g). The comment gives the lin...
ngctnnnn/DRL_Traffic-Signal-Control
sumo-rl/sumo/tools/tls/createTlsCsv.py
createTlsCsv.py
py
1,181
python
en
code
17
github-code
6
35279730803
from flask import Flask, url_for, render_template, request, flash, redirect, session, abort, jsonify import RPi.GPIO as GPIO import subprocess, os, logging import ipdb from config import Config from time import sleep '''initial VAR''' # Light GPIO RELAIS_4_GPIO = 2 # Water GPIO RELAIS_WATER_GPIO = 22 logging.basicCo...
oldgiova/python-api-webservice-lightscontrol
main.py
main.py
py
3,747
python
en
code
0
github-code
6
31211285971
''' TAREA5 Determina el tamaño de muestra requerido por cada lugar decimal de precisión del estimado obtenido para el integral, comparando con Wolfram Alpha para por lo menos desde uno hasta siete decimales; representa el resultado como una sola gráfica o de tipo caja-bigote o un diagrama de...
Elitemaster97/Simulacion
Tarea5/Tarea5.1.py
Tarea5.1.py
py
3,447
python
es
code
0
github-code
6
40140601153
import streamlit as st import pandas as pd st.set_page_config(layout="wide") col1, col2 = st.columns([3, 1]) option = None df = pd.read_csv('reuters_summaries.csv') with col2: st.write("") st.write("") st.write("") st.write("") st.write("") option = st.selectbox('', ['Crude Oil', 'Biofuel'])...
Jayanth-Shanmugam/news-articles-summarization
pages/Reuters.py
Reuters.py
py
1,302
python
en
code
0
github-code
6
21107944564
from classification.image_to_array import imageTonpv from classification.cnn_class import cnn_class import csv from os import listdir from os.path import isfile, join import cv2 import numpy as np def finalReport(label_ids = [], cids_test = [], class_count=[], class_viability =[], path = '', model='' ): v...
chenxun511happy/Cartilage-Net
classification/ClassifyMain.py
ClassifyMain.py
py
5,545
python
en
code
1
github-code
6
73573186747
import requests addresses = { "TXA2WjFc5f86deJcZZCdbdpkpUTKTA3VDM": "energyRateModelContract", "TSe1pcCnU1tLdg69JvbFmQirjKwTbxbPrG": "sTRXImpl", "TU3kjFuhtEo42tsCBtfYUAZxoqQ4yuSLQ5": "sTRXProxy", "TNoHbPuBQrVanVf9qxUsSvHdB2eDkeDAKD": "marketImpl", "TU2MJ5Veik1LRAgjeSzEdvmDYx7mefJZvd": "marketProxy", } json_ori =...
dpneko/pyutil
contract_whitelist.py
contract_whitelist.py
py
733
python
en
code
0
github-code
6
74306420987
from dataclasses import dataclass from sqlalchemy import (Boolean, Column, DateTime, ForeignKey, Integer, MetaData, Numeric, String, Table, create_engine) metadata = MetaData() @dataclass class IOLModel: sql_path: str def __post_init__(self): self.metadata = MetaData() ...
fscorrales/apys
src/apys/models/iol_model.py
iol_model.py
py
7,935
python
en
code
0
github-code
6
39386351985
from board import Board from piece import Grid_Point #variable controlling board size size = 8 current_player = 'O' def main(): #create board and current player string selection = 0 global size global current_player #loop until player starts game while(selection != '1'): ...
dank-dan-k/Reversi
main.py
main.py
py
6,101
python
en
code
0
github-code
6
30039234138
from django.views.decorators.http import require_http_methods from django.http import JsonResponse from django.http import HttpResponse from .service.login import Login from .service.report import uploadData from .service.getdata import getRoadMap import json # Create your views here. @require_http_methods(["GET",...
luzy99/road_smoothness_detection
road_detect_server/my_server/wx/views.py
views.py
py
1,542
python
en
code
0
github-code
6
70102817469
from RedditClient import RedditClient class RedditGold(RedditClient): def __init__(self): super().__init__() self.full_name = None self.months = None self.username = None def generate_body(self): body = {} if self.full_name != None: body['fullname'...
cthacker-udel/Python-Reddit-API
RedditGold.py
RedditGold.py
py
625
python
en
code
1
github-code
6
14279541024
from collections import defaultdict from intcode.intcode import read_program, VM import matplotlib.pyplot as plt DIRECTION_LEFT = (-1, 0) DIRECTION_RIGHT = (1, 0) DIRECTION_UP = (0, -1) DIRECTION_DOWN = (0, 1) TURN_LEFT = 0 TURN_RIGHT = 1 COLOR_BLACK = 0 COLOR_WHITE = 1 next_direction_left = { DIRECTION_UP: DI...
bwdvolde/advent-of-code-2019
day11/solution.py
solution.py
py
2,178
python
en
code
0
github-code
6
36942823350
import turtle window = turtle.Screen() window.bgcolor("black") shapeA = turtle.Turtle() shapeB = turtle.Turtle() shapeC = turtle.Turtle() shapeD = turtle.Turtle() shapeA.sety(100) shapeA.pencolor("red") for i in range(3): shapeA.pensize(3) shapeA.fd(50) shapeA.left(120) shapeB.setx(-100) shapeB.pencolor(...
Sir-Lance/CS1400
shit.py
shit.py
py
590
python
en
code
0
github-code
6
26969763906
import os from utils.util import make_dir_under_root, read_dirnames_under_root OUTPUT_ROOT_DIR_NAMES = [ 'masked_frames', 'result_frames', 'optical_flows' ] class RootInputDirectories: def __init__( self, root_videos_dir, root_masks_dir, video_names_filename=None ...
amjltc295/Free-Form-Video-Inpainting
src/utils/directory_IO.py
directory_IO.py
py
2,029
python
en
code
323
github-code
6
70779220668
import math import os import re from ast import literal_eval from dataclasses import dataclass import numpy as np import pandas as pd import torch import torch.nn as nn from accelerate.logging import get_logger from accelerate.utils import is_tpu_available from sklearn.metrics import accuracy_score, average_precision_...
starmpcc/REMed
src/utils/trainer_utils.py
trainer_utils.py
py
11,900
python
en
code
8
github-code
6
3337680824
def multiply(num1: str, num2: str) -> str: print(int(num1)*int(num2)) if num1 == '0' or num2 == '0': return '0' jin_nums = 0 nums_list = [] # 存放所有想加的结果 # nn1=list(num1) # nn1.reverse() # nn2=list(num2) # nn2.reverse() for i in range(len(num1)-1,0,-1): print('-------'...
zml1996/learn_record
leet_code/字符串相乘.py
字符串相乘.py
py
1,594
python
en
code
2
github-code
6
29272947400
import pymongo import json from pymongo import MongoClient from bson import json_util def StatImages(): client = MongoClient('mongodb://0.0.0.0:27017/') db = client['diplom_mongo_1'] posts = db.posts data = posts.find({"type": "image"}) count = 0 weight = 0 copies = 0 copiesId = {} copiesIdList = [] imgForma...
dethdiez/viditory_analyzer
api/stat.py
stat.py
py
964
python
en
code
0
github-code
6
39763237198
s1=input() s2=input() s1=s1.lower() s2=s2.lower() b=[] for i in s1: if i in s2: if i==' ': continue if ord(i) not in b: b.append(ord(i)) print(len(b))
gokinahemalatha/codemind-python
common_characters_-II.py
common_characters_-II.py
py
193
python
en
code
0
github-code
6
5435410186
import turtle import time import random abstand = time.sleep(0.1) fenster = turtle.Screen() fenster.title("Israa @snake spiel") fenster.setup(width=500, height=500) fenster.bgcolor("black") Kopf = turtle.Turtle() Kopf.color("red") Kopf.penup() Kopf.goto(0,0) Kopf.shape("square") Kopf.direction="stop"...
Israti/MeineProjekte
Snack.py
Snack.py
py
1,816
python
de
code
0
github-code
6
42432941077
import pandas as pd import numpy as np import math class Node: def __init__(self, fkey=None, fval=None, output=None, children=None): self.fkey = fkey # 特征名 self.fval = fval # 特征值 self.output = output # 当前节点的输出值 self.children = {} if children is None else children # 子节点 c...
mygithub-gyq/gyq2023.github.io
聚类算法/ID3.py
ID3.py
py
4,300
python
en
code
0
github-code
6
34892249806
import IsPrime def str_to_int(l): k = [] for i in l: i = int(i) k.append(i) return k def IsPrimeUserList(): user_input = input("Enter a list of numbers: ") l = user_input.split(" ") l = str_to_int(l) k = [] for i in l: if IsPrime.IsPrime(i): k.append...
ekloberdanz/python
isPrimeUserList.py
isPrimeUserList.py
py
395
python
en
code
0
github-code
6
12015658480
import numpy as np import collections # it is optional to use collections from operator import itemgetter, attrgetter # prediction function is to predict label of one sample using k-NN def predict(X_train, y_train, one_sample, k, lambda_value = 1): one_sample = np.array(one_sample) X_train = np.array(X_train)...
arkincognito/EEE3314-02Assignments
P04_2.py
P04_2.py
py
3,080
python
en
code
0
github-code
6
72612614909
"""trt_face_detection.py This script demonstrates how to do real-time face detection with TensorRT optimized retinaface engine. """ import os import cv2 import time import argparse import pycuda.autoinit # This is needed for initializing CUDA driver from utils.camera import add_camera_args, Camera from utils.displa...
d246810g2000/tensorrt
face_recognition/trt_face_detection.py
trt_face_detection.py
py
3,588
python
en
code
35
github-code
6
24670591384
from AcceptNumbers import * def main(): num = int(input("Enter number of elements: ")) if(num <= 0): print("Enter positive number") return numList = acceptNNumbers(num) print("Maximum of given numbers is:", max(numList)) if(__name__ == "__main__"): main()
SnehalKaranje/python
list/MaxFromList.py
MaxFromList.py
py
297
python
en
code
0
github-code
6
7239186990
import cv2 as cv import numpy as np import imutils path = "/home/pks/Downloads/Assignment/IVP/mini project/" def orientation(image): ''' Rotate the image before any operation based on the pos. of roll no. box w.r.t number table ''' row, col = image.shape[:2] thresh = cv.Canny(image, 40, 90) ...
pritamksahoo/III-IV-YEAR-Assignments
IVP/extract_ROI.py
extract_ROI.py
py
8,042
python
en
code
2
github-code
6
21071664643
from dataclasses import dataclass from typing import Union import numpy as np from matplotlib import pyplot as plt @dataclass class SpeakerSegment: start: int = 0 end: Union[int, None] = None @dataclass class SplitStuff4Tw: threshold_value: float split_index: int class CustomSegmentationStrategy:...
centre-for-humanities-computing/Gjallarhorn
data_processing/custom_segmentation.py
custom_segmentation.py
py
5,069
python
en
code
1
github-code
6