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
42592803391
import pandas as pd import doctest as dt def ler_arquivo_csv(nome_arquivo: str) -> pd.DataFrame: """ Função para ler arquivos do tipo CSV e transformar em DataFrame Pandas. Parameters ---------- nome_arquivo : string Nome do arquivo .csv, que deve estar na mesma pasta. Também é possível fo...
gferraricarvalho/TRAB-A1-LP
ler_arquivo.py
ler_arquivo.py
py
921
python
pt
code
0
github-code
90
29371566294
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 28 16:34:24 2019 @author: walter """ import os import numpy as np from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.models import load_model import re def load_data(path): path = o...
walterBSG/Manga-Translator-With-Deep-Learning
translator_module.py
translator_module.py
py
2,869
python
en
code
36
github-code
90
17984836799
s=input() m=10**9+1 for alpha in set(s): temp=alpha+s+alpha M=0 now=0 for i,key in enumerate(temp): if key==alpha: if M<i-now-1: M=i-now-1 now=i if m>M: m=M print(m)
Aasthaengg/IBMdataset
Python_codes/p03687/s789690024.py
s789690024.py
py
218
python
en
code
0
github-code
90
14267826928
""" The Code is under Tencent Youtu Public Rule builder for transforms transforms from torch or home-made """ import copy from torchvision import transforms from .randaug_ccssl.randaugment import RandAugmentCCSSL from .randaug_comatch.randaugment import RandomAugmentComatch from .randaug_fixmatch.randaugment import...
pingqingsheng/pivotmatch
semilearn/datasets/augmentation/transform/builder.py
builder.py
py
3,362
python
en
code
0
github-code
90
48479731200
# News Recommender version 2. Given a URL for a news article, recommend TV news # clips similar to article contents from collections import Counter import logging import math import json import urllib3 from sklearn.feature_extraction.text import TfidfVectorizer from scipy.spatial.distance import cosine import en_core_w...
internetarchive/tvnews
tvnews/NewsRecommender.py
NewsRecommender.py
py
3,059
python
en
code
2
github-code
90
70305401897
from runrex.algo.pattern import Pattern from runrex.text import Document from runrex.algo.result import Status, Result from runrex.terms import hypothetical, negation instructions = r'(remember|recall|do not)' side_effects = r'(side effects?)' negation_group = (negation, hypothetical, instructions, side_effects) cl...
kpwhri/pcos-runrex
src/pcos_runrex/algo/hyperandrogenism.py
hyperandrogenism.py
py
2,966
python
en
code
0
github-code
90
73935035818
from pika import BlockingConnection, ConnectionParameters from json import dumps import sys # Primeiro argumento é o nome da queue que receberá a mensagem # Segundo argumento é o nome do algoritmo # Dali em diante são os nome dos argumento seguidos do valor dos argumento # Por exemplo, para iniciar Dijkstra no nó q1...
chsponciano/aws-container-manager
ServerApp/scripts/python/start_algorithm.py
start_algorithm.py
py
952
python
pt
code
0
github-code
90
70403401256
from cs50 import get_float # Ask how many cents the customer is owed # function that prompt the user the change is owed while True: try: cents = get_float("Change owed: ") if cents > 0: break except ValueError: pass cents = cents * 100 coins = 0 while cents >= 25: ce...
tthierry64/CS50
Week6/sentimental-cash/cash.py
cash.py
py
595
python
en
code
0
github-code
90
8827923312
from classifying.terror.data_maker import au, fi, fu, ftu, tk, prefix_textarr, split_train_test, test_train_pos_neg_portion label_t, label_f = ftu.label_t, ftu.label_f value_t, value_f = ftu.value_t, ftu.value_f neg_pattern = "/home/nfs/cdong/tw/seeding/NEGATIVE/{}" k_data_pattern = "/home/nfs/cdong/tw/seedin...
leeyanghaha/my_merge
classifying/k/k_data_maker.py
k_data_maker.py
py
2,616
python
en
code
0
github-code
90
18709054587
from rest_framework import serializers from apps.contact.models import FormEmail from apps.contact.tasks import send_info class FormEmailSerializer(serializers.ModelSerializer): class Meta: model = FormEmail fields = "__all__" def create(self, validated_data): form_email = super().c...
edzen12/fast
backend/apps/contact/serializers.py
serializers.py
py
487
python
en
code
0
github-code
90
71789647338
#!/usr/bin/env python3 from collections import OrderedDict from enum import Enum from day8_part1 import make_layers class Colors(Enum): BLACK = "0" WHITE = "1" TRANSPARENT = "2" def __get__(self, *args): return self.value def main(): with open("./inputs/day8.txt") as file: ...
alu-/advent-of-code-2019
day8_part2.py
day8_part2.py
py
1,212
python
en
code
0
github-code
90
40003839715
from string import ascii_lowercase from gallows import HANGMAN_GALLOWS from word import get_random_word RANDOM_WORD = get_random_word() def display_board(wrong_answers, idxs): print(HANGMAN_GALLOWS[len(wrong_answers)], end='\t') curr_ans = ''.join([' ' +letter+ ' ' if idxs[i] else '__ ' for i, letter in enu...
frank-quoc/forty_two_python_projects
beginners/hangman/hangman.py
hangman.py
py
2,085
python
en
code
0
github-code
90
18456388419
import sys input = sys.stdin.readline from operator import itemgetter import heapq n, k = map(int, input().split()) TD = sorted([list(map(int, input().split())) for _ in range(n)], reverse=True, key=itemgetter(1)) L = [[] for _ in range(n+1)] P = [] a = 0 cnt = 0 F = [-float("inf")]*(n+1) B = 0 for t, d in TD[:k]: if...
Aasthaengg/IBMdataset
Python_codes/p03148/s956095118.py
s956095118.py
py
671
python
en
code
0
github-code
90
73620506857
""" 只要按照二叉搜索树的规则去遍历,遇到空节点就插入节点就可以了。不需要调整树 """ class Solution(object): def insertIntoBST(self, root, val): """ :type root: TreeNode :type val: int :rtype: TreeNode """ if not root: return TreeNode(val) if val > root.val: root.right =...
xiangzuo2022/leetcode_python
python/701.insert_into_binary_search_tree.py
701.insert_into_binary_search_tree.py
py
551
python
en
code
0
github-code
90
9188851377
import _pickle from feynman.etc import Try_sync_access from feynman.etc.util import get_logger class Pickle_serializer(): def __init__(self): self.logger = get_logger() def load(self, fname): with Try_sync_access(fname + '.lock'): with open(fname, "rb") as f: data...
kangheeyong/LIB-Feynman
feynman/serialize/pickle_serializer.py
pickle_serializer.py
py
653
python
en
code
0
github-code
90
70591533737
from flask import Flask, render_template, Response ,request from model import CovidTest import cv2 import numpy as np app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') # @app.route('/r') # def r(): # return render_template('result.html',res="Covid Negative") @app.route('/...
Das-Abhi/X-Ray-Covid-19-Detection-Infoweb
main.py
main.py
py
907
python
en
code
1
github-code
90
18184028609
N = int(input()) A = sorted(list(map(int, input().split())), reverse=True) ans = A[0] cnt = 1 for a in A[1:]: if cnt + 1 < N: ans += a cnt += 1 if cnt+ 1 < N: ans += a cnt += 1 print(ans)
Aasthaengg/IBMdataset
Python_codes/p02615/s467443459.py
s467443459.py
py
230
python
en
code
0
github-code
90
23373326440
import os import shutil import maya.cmds as cmds import maya.mel as mel from psd_tools import PSDImage # SETTINGS ROOT_PATH = "/Users/minuj/Documents/UbisoftTest_2/UnityProject/Shader" SOURCE_PATH = "{}/Raw".format(ROOT_PATH) ASSET_PATH = "{}/Assets/Sources".format(ROOT_PATH) def confirmDir(dirname): if not ...
minuJeong/ShaderTest
Maya/exporter.py
exporter.py
py
2,581
python
en
code
0
github-code
90
33705753551
import logging from django.apps import AppConfig from django.conf import settings from judoscale.core.config import config as judoconfig from judoscale.core.reporter import reporter logger = logging.getLogger(__name__) class JudoscaleDjangoConfig(AppConfig): name = "judoscale.django" label = "judoscale_dja...
judoscale/judoscale-python
judoscale/django/apps.py
apps.py
py
1,320
python
en
code
4
github-code
90
29864619083
import pyspeckit from pyspeckit.spectrum import models from pyspeckit.wrappers import fith2co from astropy.io import fits import numpy as np import pyregion import paths from paths import (datapath, dpath, rpath, mpath, h2co11subfn, h2co22subfn, cont2cm, cont6cm) from common_constants import TCMB, et...
keflavich/w51_singledish_h2co_maps
analysis_scripts/load_pyspeckit_cubes.py
load_pyspeckit_cubes.py
py
7,012
python
en
code
0
github-code
90
18288580839
# -*- coding: utf-8 -*- """ Created on Tue Sep 8 18:25:14 2020 @author: liang """ H, W = map(int, input().split()) field = [input() for i in range(H)] def Init(): return [[-1]*W for _ in range(H)] ans = -1 from collections import deque q = deque() adj = ((1,0), (-1,0), (0,1), (0,-1)) def BFS(y,x): def is...
Aasthaengg/IBMdataset
Python_codes/p02803/s000033188.py
s000033188.py
py
1,138
python
en
code
0
github-code
90
18154123879
N, K = map(int, input().split()) MOD = 998244353 S = [] for _ in range(K): S.append(tuple(map(int, input().split()))) dp = [0] * (N + 1) dp[1] = 1 sum_list = [0] * (N + 1) sum_list[1] = 1 for i in range(2, N+1): for L, R in S: RR = i - L if RR <= 0: continue LL = max(1, i-R...
Aasthaengg/IBMdataset
Python_codes/p02549/s406661027.py
s406661027.py
py
499
python
en
code
0
github-code
90
27103266909
import Songs from tkinter import * import webbrowser def home(): root4.destroy() def listen(): pos = Songs.song.index(str(song.var1.get())) webbrowser.open(Songs.link[pos]) def song(): label4 = Label(root4,text="Select the song of the artist",font=("times 12 bold")) label4.place(x=27...
Aiden-Frost/Beat-Finder-TkinterGUI
Play_song.py
Play_song.py
py
1,593
python
en
code
0
github-code
90
43212762304
""" 《邢不行-2020新版|Python数字货币量化投资课程》 无需编程基础,助教答疑服务,专属策略网站,一旦加入,永续更新。 课程详细介绍:https://quantclass.cn/crypto/class 邢不行微信: xbx9025 本程序作者: 邢不行 # 课程内容 通过获取历史K线数据,进一步讲解ccxt的用法 """ import pandas as pd import ccxt import time import os from datetime import timedelta pd.set_option('expand_frame_repr', False) # 当列太多时不换行 # =====设定...
siegjan6/coin2021
program/2_牛刀小试/3_构建自己的数字货币数据库/6_获取历史K线数据.py
6_获取历史K线数据.py
py
3,274
python
zh
code
3
github-code
90
26496505128
from sys import stdin from collections import deque deq = deque([]) n = int(input()) for _ in range(n) : c = stdin.readline().strip().split() if c[0] == "push_front" : deq.appendleft(int(c[1])) elif c[0] == "push_back" : deq.append(int(c[1])) elif c[0] == "pop_front" : prin...
hamin2065/PS
스택,큐,덱/10866_2.py
10866_2.py
py
649
python
en
code
0
github-code
90
3781311305
import os import random import discord DOG_LIST = ["わん!", "わおーーん", "わんわん!", "わん!!!", "わん><", "わん......", "いっそうは動物を好きになるニャン", "わおん!", "いぬです。よろしくおねがいします", "いっぬ", "わんわん!", "わんわんわん!", ...
approvers/ponyo
src/DOG.py
DOG.py
py
997
python
en
code
0
github-code
90
13002808848
# remove는 원본 변형 T = int(input()) for i in range(T): test = list(map(int,input().split())) test.remove(max(test)) test.remove(min(test)) result = round(sum(test) / len(test)) print('#{} {}'.format(i+1, result))
hyeinkim1305/Algorithm
SWEA/D2/1984번/1984.py
1984.py
py
234
python
ko
code
0
github-code
90
12888349346
import argparse from common.detector_result import StatusMsg, Status from .constant_accuracy_overall import load_and_merge def parse_args(): parser = argparse.ArgumentParser() parser.add_argument( "-d", dest="detector", help="Detector result(s)", required=True, nargs=...
alan-turing-institute/CSV_Wrangling
scripts/analysis/constant_failure.py
constant_failure.py
py
1,555
python
en
code
26
github-code
90
33660924777
from typing import List class Solution: def maxProfit(self, prices: List[int]) -> int: profit = 0 for i in range(1, len(prices)): tmp = prices[i] - prices[i-1] if tmp > 0: profit += tmp return profit if __name__ == '__main__': solution = Solution...
algorithm004-04/algorithm004-04
Week 03/id_489/LeetCode_122_489.py
LeetCode_122_489.py
py
372
python
en
code
66
github-code
90
24803066739
bufferinput = open("input.txt", "r") position = 0 bufferlist = [] for line in bufferinput: for character in line: bufferlist.append(character) fours = [] for character in bufferlist: position = position + 1 if len(fours) == 4: placeholder = [] for cc in fours: if cc not i...
kormorant/aoc2022
day6part1.py
day6part1.py
py
525
python
en
code
0
github-code
90
72984803175
class Solution: def partitionLabels(self, s: str) -> List[int]: pos, start, end, ans = {}, 0, 0, [] for i in range(len(s)): if s[i] in pos: pos[s[i]].append(i) else: pos[s[i]] = [i] for key in pos: if pos[key][0] > end: ...
DayeemParkar/LeetCode-GFG-Submissions
763-partition-labels/763-partition-labels.py
763-partition-labels.py
py
607
python
en
code
0
github-code
90
18901058715
from item_list import CRAFTABLE_LIST import requests import json import pandas as pd from multiprocessing import Pool from multiprocessing.dummy import Pool def get_item_info(ITEM): URL = 'https://gameinfo.albiononline.com/api/gameinfo/items/' + ITEM + '/data' RESPONSE = requests.get(URL).content ITEM_FULL...
gkdekker/Albion_Trader_and_Crafter
get_recipe.py
get_recipe.py
py
3,437
python
en
code
0
github-code
90
37255768067
from fastapi import FastAPI from fastapi import Request from fastapi.templating import Jinja2Templates # from starlette.requests import Request # from starlette.templating import Jinja2Templates app = FastAPI() templates = Jinja2Templates(directory="templates") @app.get("/") async def main(request: Request): re...
zhenghaizhang/fastapi_first_part
lesson3/template_and_url.py
template_and_url.py
py
663
python
en
code
0
github-code
90
14320034522
from django.shortcuts import render, redirect, get_object_or_404 # Create your views here. from webapp.forms import GuestForm from webapp.models import Guest def index_view(request): guests = Guest.objects.order_by('-updated_at') return render(request, 'index.html', {'guests': guests}) def add_note(request...
mtashtanovski/Exam_6_py_group9_MT
source/webapp/views.py
views.py
py
1,949
python
en
code
0
github-code
90
32876493875
from befunge.caret import Vec def test_vec_init(): try: vec = Vec() except Exception as e: raise e else: assert vec is not None def test_vec_sum(): a = Vec(2, 3) b = Vec(3, 2) assert a + b == Vec(5, 5)
FacelessLord/Befunge
tests/test_vec.py
test_vec.py
py
254
python
en
code
0
github-code
90
22504943175
import numpy as np import torch import torch.nn as nn from torch.optim import Adam from torch.optim.lr_scheduler import ReduceLROnPlateau import sys import os import matplotlib.pyplot as pt import h5py from unet import UNet import time from calc_cl_func_newbin import calc_cond,calc_rl use_cuda = True device = torch.de...
chitingchiang/unet_21cm_dust
pytorch/run_train.py
run_train.py
py
7,200
python
en
code
0
github-code
90
26482710890
from tqdm.auto import tqdm import numpy as np import pandas as pd import torch import torch.nn.functional as F from torch.utils.data import DataLoader from transformers import AutoTokenizer, RobertaModel from datasets import load_dataset def get_dataLoader(name_dataset='dyda_da', batch_size=64): dataset = load_datas...
yunhao-tech/NLP_ENSAE_2023
Intent Classification Project/scripts/fine_tuning_RoBERTa.py
fine_tuning_RoBERTa.py
py
7,050
python
en
code
0
github-code
90
20360192798
MENU = { "espresso": { "ingredients": { "water": 50, "coffee": 18, }, "cost": 1.5, }, "latte": { "ingredients": { "water": 200, "milk": 150, "coffee": 24, }, "cost": 2.5, }, "cappuccino": { ...
divx89/100DaysOfCode-Python
Day015-21225-Coffee_Machine/main.py
main.py
py
3,854
python
en
code
1
github-code
90
35645886536
class Solution(object): def floodFill(self, image, sr, sc, newColor): """ :type image: List[List[int]] :type sr: int :type sc: int :type newColor: int :rtype: List[List[int]] """ visited = [ [0 for x in range(len(image[0]))] for y in range(len...
cloi1994/session1
Uber/733.py
733.py
py
971
python
en
code
0
github-code
90
12084655360
import os import setuptools with open("tunga/README.md", "r") as fh: long_description = fh.read() with open("requirements.txt") as fd: reqs = [item.strip() for item in fd.readlines()] try: build_version = str(os.environ["BUILD_VERSION"]).split(".")[-1] except: build_version = "local2" def install_de...
tunga-ml/tunga
setup.py
setup.py
py
2,182
python
en
code
4
github-code
90
8755987412
from django.conf import settings from django.db import models from django.utils import timezone from m2m_history.fields import ManyToManyHistoryField from vkontakte_api.decorators import atomic from vkontakte_api.utils import get_improperly_configured_field class UserableModelMixin(models.Model): class Meta: ...
ramusus/django-vkontakte-groups
vkontakte_groups/mixins.py
mixins.py
py
4,321
python
en
code
2
github-code
90
10370366781
import argparse from smart_queue.db.database import get_all_conditions parser = argparse.ArgumentParser( description="Get priority of conditions with given time" ) parser.add_argument( "-t", "--time", dest="wait_time", required=True, help="Wait time in minutes", ) args = parser.parse_args() ...
1orange/queue-system-api
priority_checker.py
priority_checker.py
py
960
python
en
code
0
github-code
90
42220631209
import tkinter as tk class tableService(object): def __init__(self, container, data, scrollable = True): self.data = data self.frame = container self.header_bg = '#3d3d3d' self.header_color = '#ffffff' self.body_bg = '#ffffff' self.body_color = '#141414' if(...
onisueka/python-tkinter-table-scrollbar
tableService.py
tableService.py
py
3,568
python
en
code
0
github-code
90
34241031193
#!/usr/bin/env python3 """ Module to test exercise2.py """ __author__ = 'Shuai Wang' __email__ = "info.shuai@gmail.com" __copyright__ = "2014 Shuai Wang" __license__ = "MIT License" __status__ = "Prototype" import pytest from exercise2 import checksum def test_checksum(): """ Inputs that are the correct...
jayinai/inf1340
inf1340_ass1/test_exercise2.py
test_exercise2.py
py
1,107
python
en
code
0
github-code
90
39573509649
# Знайти ідентифікатор групи, де знаходиться найбільша кількість жінок, народжених після 1977 року. # Як відповідь необхідно вказати через пробыл ідентифікатор знайденої групи і скільки в ній було жінок, # народжених після 1977 року. Файл group_people.json import json def find_max_people(rel_path: str) -> [tuple]: ...
dmytroPPK/qaauto-course
lesson9/homework/task_1.py
task_1.py
py
1,119
python
uk
code
0
github-code
90
30297671423
#!/usr/bin/python import time import RPi.GPIO as GPIO # GPIO Pins festlegen (anpassen) LCD_RS = 25 LCD_E = 24 LCD_DATA4 = 23 LCD_DATA5 = 17 LCD_DATA6 = 20 LCD_DATA7 = 21 LCD_WIDTH = 16 # Zeichen je Zeile LCD_LINE_1 = 0x80 # Adresse LCD Zeile 1 LCD_LINE_2 = 0xC0 # Adresse LCD Zeile 2 LCD_CHR = GPIO.HIGH LCD_CMD = ...
Carpocalypse/Spielwiese
hd44780.py
hd44780.py
py
2,768
python
en
code
0
github-code
90
8456219266
''' vid:https://www.youtube.com/watch?v=zjo9yFHoUl8 scrap: http://econpy.pythonanywhere.com/ex/001.html setting up env $ pip3 install selenium download : https://github.com/mozilla/geckodriver/releases sudo cp geckodriver /usr/bin/geckodriver ''' from selenium import webdriver #1.open up a firefox browser and na...
ArchitW/Scrapping-Selenium-Python
selanium_master.py
selanium_master.py
py
813
python
en
code
0
github-code
90
4433329651
import socket import threading nome = input("Digite seu nome: ") cliente = socket.socket(socket.AF_INET, socket.SOCK_STREAM) HOST = '127.0.0.1' PORT = 9999 try: cliente.connect((HOST, PORT)) except: print('Erro de conexão') exit() def receive(): while True: try: ...
Carolissis/Exercicios
Segundo_periodo/Ciber/projeto_final/cliente.py
cliente.py
py
867
python
en
code
0
github-code
90
32617532877
#给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。 #给你一个整数 n ,返回和为 n 的完全平方数的 最少数量 。 #完全平方数 是一个整数,其值等于另一个整数的平方;换句话说,其值等于一个整数自乘的积。例如,1、4、9 和 16 都是完全平方数,而 3 和 11 不是。 class Solution: def numSquares(self, n: int) -> int: squareNums = [i**2 for i in range(0,int(math.sqrt(n))+1)] ...
ysuyll1597425570/leetcode-training
DP/279-numSquares.py
279-numSquares.py
py
826
python
zh
code
0
github-code
90
74068743017
# SolidPython で建物を作成するサンプル import sys from solid import * from solid.utils import * import viewscad building_size = (15,5,10.5) window_size = (2,0.2,1.5) window_offset = (0.25,-0.1,0.5) window_mergin = (2, 0, 1.5) window_front_count = (6,5) window_left_count = (2,5) def windows(props): (cw , ch ) = props a = unio...
yamagame/python-3d-modeling
src/building.py
building.py
py
976
python
en
code
0
github-code
90
43812656598
from dataclasses import dataclass from typing import Optional from sintetizador.model.operation.variable import Variable from sintetizador.model.operation.spatialresolution import SpatialResolution from sintetizador.model.operation.temporalresolution import TemporalResolution @dataclass class OperationSynthesis: ...
rjmalves/sintetizador-dessem
sintetizador/model/operation/operationsynthesis.py
operationsynthesis.py
py
1,029
python
en
code
2
github-code
90
33965836193
import logging from math import ceil from typing import Dict, Optional, Union import torch from omegaconf import DictConfig, OmegaConf from pytorch_lightning import Trainer from nemo.collections.asr.data import audio_to_text_dataset from nemo.collections.asr.losses.similarityloss import NegativeCosineSimilarityLoss f...
huawei-noah/Speech-Backbones
SPIRAL/nemo/collections/asr/models/st2vec/st2vec_pretrain.py
st2vec_pretrain.py
py
9,172
python
en
code
466
github-code
90
34290680597
## written by xiongbiao ## date 2020-6-4 from Tree.node import TreeNode ''' 给定一个二叉树,它的每个结点都存放一个 0-9 的数字,每条从根到叶子节点的路径都代表一个数字。 例如,从根到叶子节点路径 1->2->3 代表数字 123。 计算从根到叶子节点生成的所有数字之和。 ''' class Solution(object): def sumNumbers(self, root): """ :type root: TreeNode :rtype: int """ if...
xb2342996/Algorithm-and-Data-Structure
LeetCode_vII/Tree/129. 求根到叶子节点数字之和.py
129. 求根到叶子节点数字之和.py
py
874
python
zh
code
0
github-code
90
10425132409
#!/usr/bin/env python # -*- encoding: utf-8 -*- import heapq from collections import defaultdict,OrderedDict # 查找序列内最大和最小的N个数 portfolio = [ {'name': 'IBM', 'shares': 100, 'price': 91.1}, {'name': 'AAPL', 'shares': 50, 'price': 543.22}, {'name': 'FB', 'shares': 200, 'price': 21.09}, {'name': 'HPQ', '...
anstones/py-collection
Py-cookbook/数据结构与算法.py
数据结构与算法.py
py
5,058
python
en
code
3
github-code
90
71658391656
#!/bin/python3 import math import os import random import re import sys # Complete the solve function below. def solve(s): lst = s.split() cap_name = s for name in lst: cap_name = cap_name.replace(name, name.capitalize()) return cap_name if __name__ == '__main__': fptr = open(os.envi...
kishlayjeet/HackerRank-Solutions
Python/Strings/Capitalize.py
Capitalize.py
py
434
python
en
code
1
github-code
90
18194393179
MOD = 10**9+7 k = int(input()) s = input() n = len(s) U = n+k fact = [0]*(U+1) fact[0] = 1 for i in range(1, U+1): fact[i] = fact[i-1]*i % MOD invfact = [0]*(U+1) invfact[U] = pow(fact[U], MOD-2, MOD) for i in reversed(range(U)): invfact[i] = invfact[i+1]*(i+1) % MOD def nCr(n, r): if r < 0 or n...
Aasthaengg/IBMdataset
Python_codes/p02632/s285657288.py
s285657288.py
py
507
python
en
code
0
github-code
90
30622238830
#FizzBuzz program, prints Fizz if the mod operator returns 0 for 3, Buzz if the mod operator returns 0, and FizzBuzz #if both of them return 0 #================================= #Function for FizzBuzz iteration #================================= def fizzbuzz(number): output = "" divis = False if (number % ...
sleddog/methods
projects/fizzbuzz/python/b-cornett/fizzBuzz.py
fizzBuzz.py
py
1,371
python
en
code
7
github-code
90
23816127337
from __future__ import annotations import os import sys import typing as t import globus_sdk from .client_login import get_client_login, is_client_login from .scopes import CURRENT_SCOPE_CONTRACT_VERSION if sys.version_info >= (3, 8): from typing import Literal else: from typing_extensions import Literal i...
globus/globus-cli
src/globus_cli/login_manager/tokenstore.py
tokenstore.py
py
9,488
python
en
code
67
github-code
90
28998498421
import turtle as t import random as r def turn_right(): t.setheading(0) def turn_left(): t.setheading(180) def turn_up(): t.setheading(90) def turn_down(): t.setheading(270) def play(): t.fd(10) ang = te.towards(t.pos()) te.setheading(ang) te.fd(9) if t.distance(ts) < 12: ...
graysunday/python
17A-trun.py
17A-trun.py
py
953
python
en
code
0
github-code
90
40723307191
# Write documentation for this file ''' Write documentation for this module here. ''' # Part 1.1 def readBallot(filename): '''This function reads a cvs file and returns a list of lists where each interior list is a single ballot containing candidate names ordered from most prefered to least ...
bern1ard0/Python_Projects
lab04/voting.py
voting.py
py
7,317
python
en
code
0
github-code
90
42169959528
# -*- coding: utf-8 -*- #!/usr/bin/python import falcon from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine, Column, Integer, String, Date, DateTime from sqlalchemy.sql import select, insert import config from controllers.users import UserLogin from models.customers import Custo...
ngnamuit/ngnamuit-sample-python-api-falcon-
controllers/customers.py
customers.py
py
4,786
python
en
code
0
github-code
90
18656163962
from rest_framework import routers from django.urls import path from .api import AuthenticationViewSet, FileViewSet, ListSignatureRequestByUserViewSet, ListSignatureRequestUserByRequestViewSet, ListSignatureRequestUserByUserViewSet, SignatureRequestUserViewSet, SignatureRequestViewSet, UserViewSet, GetGenerateFileSigne...
Arquitectura-de-Software-UFPS-2022-I/sign-documents-api
api_base_app/apps/base_app/api/urls.py
urls.py
py
1,383
python
en
code
0
github-code
90
33562075189
import datetime import sys from PyQt5 import QtWidgets from PyQt5.QtCore import QThread from PyQt5.QtWidgets import QDesktopWidget from model.model import Phase from view.view import Gui from .worker import PhaseUpdate, StatusUpdate class Controller: def __init__(self): self._app = QtWidgets.QApplicati...
mr-davtyan/dnModeling
controller/controller.py
controller.py
py
5,995
python
en
code
0
github-code
90
8293226788
import streamlit as st from streamlit_extras.switch_page_button import switch_page import time if "user_info" not in st.session_state or not st.session_state["user_info"]: switch_page("Landing") st.set_page_config(layout="wide") user_data = st.session_state["user_info"] st.title("Welcome to Hack-o-Taco 🌮") st.s...
nekocandy/hackotaco
pages/bento.py
bento.py
py
1,663
python
en
code
0
github-code
90
74144254376
from skimage import filters # Define um nested gaussian filter para ser aplicado nas imagens individuais (2D) # A entrada eh um ndarray 2D def NestedFilter2D(ImgArray,GaussMatrix2DVar,filter2DNestNumber=None,index=1): if filter2DNestNumber==None: return(ImgArray) else: def Ga...
amaurijp/BioSPA
Modules/MODimageGaussFilter.py
MODimageGaussFilter.py
py
1,512
python
en
code
3
github-code
90
13609850309
# # abc208 b # import sys from io import StringIO import unittest class TestClass(unittest.TestCase): def assertIO(self, input, output): stdout, stdin = sys.stdout, sys.stdin sys.stdout, sys.stdin = StringIO(), StringIO(input) resolve() sys.stdout.seek(0) out = sys.stdout.r...
mskt4440/AtCoder
abc208/b.py
b.py
py
1,160
python
en
code
0
github-code
90
31193939073
from engine.engine import TRTEngine from core.process import BackBoneProcessor from core.process import HeadProcessor # base.py에서 구현한 Tracker 모델을 구체화 함 # base.py의 BaseTracker와 SiameseTracker는 정확히는 트래킹을 위한 헬퍼 함수를 가지고 있는 상태임. # 실제 추론은 Engine에서 이뤄지며 Model은 Engine과 Tracker를 묶어주는 역할 class Model(object): """ TensorRT ...
SSSSSSL/NanoTrack_TensorRT
tracker/model.py
model.py
py
2,065
python
ko
code
2
github-code
90
70761323816
import pandas as pd # Sample dataset (you can replace this with your own data or load from a file) data = { "Heights": [165, 170, 175, 160, 180, 172, 168, 163, 158, 182], "Weights": [70, 75, 80, 65, 85, 77, 73, 68, 63, 88] } # Create a DataFrame from the data df = pd.DataFrame(data) # View basic statistical ...
abujarshaikh/Python
Sleep3q2.py
Sleep3q2.py
py
414
python
en
code
0
github-code
90
4967663176
######## PLOTTING USING 39000+ TILES DICTIONAIRY ############################################# import rasterio as rio import plotly.graph_objects as go from rasterio.mask import mask import requests import re ################################################################################################ # f...
Steven-Verkest-AI/3D_House_Project_Deployment
Project2/APP_CODE.py
APP_CODE.py
py
2,938
python
en
code
0
github-code
90
22222181135
# -*- coding: utf-8 -*- import re from lxml import etree import requests import time import pandas as pd ''' 使用前, cookies需要更新 ''' start_site = 'https://weibo.cn/search/mblog?hideSearchFrame=&keyword={}&page={}' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Ge...
Sososososo12/weibo_scrapy
weibo-scrapy/search.py
search.py
py
7,407
python
en
code
1
github-code
90
15078988510
"""WRITE ALGORITHM TO FIND THE Kth TO LAST ELEMENT OF A SINGLY LINKED LIST""" class Node(object): """docstring for Node.""" def __init__(self, data): super(Node, self).__init__() self.data = data self.nextNode = None class LinkedList(object): """docstring for LinkedList.""" def...
PeterChencha/python_data_structures
Linkedlists/fromlast.py
fromlast.py
py
1,650
python
en
code
0
github-code
90
17243018190
#BAEKJOON 1316범 N = int(input()) answer = 0 for n in range(N): word = list(input()) word_set = list(set(word)) group = [] isGroup = True for w in word: if w not in group: group.append(w) else: if group[-1] != w: isGroup = False if isGr...
luboolu/BAEKJOON
7_문자열/그룹단어체커/solution.py
solution.py
py
372
python
en
code
2
github-code
90
18396342239
N=int(input()) d={} k=[] for x in range(N): S,P=input().split() if S not in k: k.append(S) d[S]=[] d[S].append([int(P),x+1]) k.sort() for y in k: d[y].sort(reverse=True) for z in range(len(d[y])): print(d[y][z][1])
Aasthaengg/IBMdataset
Python_codes/p03030/s502258946.py
s502258946.py
py
236
python
en
code
0
github-code
90
40028980605
class Date: def __init__(self, year, month, day): self.year = year self.month = month self.day = day def tomorrow(self): self.day += 1 @staticmethod def parse_from_string(date_str): year, month, day = tuple(date_str.split("-")) return Date(int(year), int...
zackhsw/myTest_flask
advance_apply/chapter04/class_method.py
class_method.py
py
1,495
python
en
code
0
github-code
90
24625499835
import argparse import os import numpy as np import torch import torch.nn as nn from facenet_pytorch import fixed_image_standardization from torch.utils.tensorboard import SummaryWriter from torchvision import transforms from tqdm import tqdm from data_loader import get_loader, read_dataset, CompositeDataset from mod...
Megatvini/DeepFaceForgeryDetection
src/train.py
train.py
py
10,340
python
en
code
64
github-code
90
7336552422
#!/usr/bin/env python #-*- coding:utf-8 -*- __author__ = 'luotianshuai' import random import time def handler(array): for i in range(len(array)): smallest_index = i #假设默认第一个值最小 for j in range(i,len(array)): if array[smallest_index] > array[j]: smallest_index = j #如果找...
luotianshuai/notes-doemos
python/Guide_27/teach/new_choice.py
new_choice.py
py
904
python
en
code
1
github-code
90
18122053699
class Dice: def __init__(self, dice): self.dice = dice self.rule={'N':(1,5,2,3,0,4),'S':(4,0,2,3,5,1),'E':(3,1,0,5,4,2),'W':(2,1,5,0,4,3)} def output(self): return self.dice def move(self, direction): for _ in direction: self.dice = [self.dice[y] for y in self.rul...
Aasthaengg/IBMdataset
Python_codes/p02384/s645570014.py
s645570014.py
py
774
python
en
code
0
github-code
90
4461469659
import numpy as np import torch from GL_Policy import GCN,MLP #State Variable Initialization vtol_edge = np.matrix([ [0,1,1,1,1], [1,0,1,1,1], [1,1,0,1,1], [1,1,1,0,1], [1,1,1,1,0]]) pad_edge = np.matrix([ [0,1,1], [1,0,1], [1,1,0]]) vtol_features = np.matrix([ [0.3,0,3,4,5], #[B...
JhoelWit/GLUAM
.vs/Github Repo/v17/GL_Test.py
GL_Test.py
py
3,327
python
en
code
0
github-code
90
37856055015
#!/usr/bin/env python3 import numpy as np from os import getenv, makedirs import os.path as ptt import sys from astropy.table import Table, vstack import argparse from splog import Splog from collections import OrderedDict from pydl.pydlutils import yanny from subprocess import getoutput from datetime import date impo...
sdss/idlspec2d
bin/manage_coadd_Schema.py
manage_coadd_Schema.py
py
9,676
python
en
code
1
github-code
90
70869260138
common = ['C','C#','D','Eb','E','F','F#','G','Ab','A','Bb','B'] class Note: def __init__(self, noteName, octave=None): self.octave = octave if type(noteName) is int: offset, idx = divmod(noteName, 12) self.name = common[idx] self.octave = offset - 1 else: self.name = noteName ...
jshanley/pymotive
note.py
note.py
py
401
python
en
code
0
github-code
90
15728397398
import unittest import data import numpy as np class DataProcessTest(unittest.TestCase): @unittest.skip('') def test_image_name_dict(self): d = data.get_images_name() self.assertTrue(len(d['yome'])==56) @unittest.skip('') def test_read_tvt_imgs(self): pass #img_dict = data.get_characters_ttv_imgs(['yome','...
uabharuhi/kmk
utest.py
utest.py
py
1,959
python
en
code
0
github-code
90
524861717
from tkinter import messagebox, simpledialog, Tk import random # Create an if-main code block, *hint, type main then ctrl+space to auto-complete if __name__ == '__main__': # Make a new window variable, window = Tk() window = Tk() # Hide the window using the window's .withdraw() method window.withdraw()...
123456789degrees/Summer-Camp
Level0-Module0/_03_print_and_popups/_e_awesome_or_not.py
_e_awesome_or_not.py
py
1,428
python
en
code
0
github-code
90
18101932499
from collections import deque q = deque([]) n = int(input()) G = [] for i in range(n): u, k, *vvv = list(map(int, input().split())) G.append([v-1 for v in vvv]) visited = [False for _ in range(n)] q.append(0) dist = [-1 for _ in range(n)] dist[0] = 0 while q: u = q.popleft() visited[u] = True for v in G[u]: ...
Aasthaengg/IBMdataset
Python_codes/p02239/s663294298.py
s663294298.py
py
490
python
en
code
0
github-code
90
18386937999
import sys input = sys.stdin.readline sys.setrecursionlimit(10000000) from collections import defaultdict mod = 10**9+7 N = int(input()) xy = [list(map(int, input().split())) for i in range(N)] xy.sort() Ans = N for i in range(N): for j in range(i+1, N): a, b = xy[j][0]-xy[i][0], xy[j][1]-xy[i][1] ...
Aasthaengg/IBMdataset
Python_codes/p03006/s868605651.py
s868605651.py
py
529
python
en
code
0
github-code
90
75056370855
class Jar: def __init__(self, capacity): if not isinstance(capacity, int) or capacity < 0: raise ValueError("Capacity must be a non-negative integer") self.capacity = capacity self.cookies = 0 def __str__(self): return "�" * self.cookies def deposit(self, n):...
SiddheshKotwal/CS50x_2023
jar/jar.py
jar.py
py
1,506
python
en
code
1
github-code
90
18288691129
import queue h,w = map(int,input().split()) v = [(1, 0), (0, 1), (-1, 0), (0, -1)] s = [input() for i in range(h)] ans = 0 que = queue.Queue() for i in range(h * w): c = 0 d = [[h*w] * w for i in range(h)] p = (i//w, i%w) if s[p[0]][p[1]] == '#': continue d[p[0]][p[1]] = 0 que.put(p) ...
Aasthaengg/IBMdataset
Python_codes/p02803/s153859641.py
s153859641.py
py
749
python
en
code
0
github-code
90
17637764847
import xbmc import xbmcaddon addon = xbmcaddon.Addon('script.mrknow.urlresolver') name = addon.getAddonInfo('name') LOGDEBUG = xbmc.LOGDEBUG LOGERROR = xbmc.LOGERROR LOGFATAL = xbmc.LOGFATAL LOGINFO = xbmc.LOGINFO LOGNONE = xbmc.LOGNONE LOGNOTICE = xbmc.LOGNOTICE LOGSEVERE = xbmc.LOGSEVERE LOGWARNING = xbmc.LOGWARNIN...
mrknow/filmkodi
script.mrknow.urlresolver/lib/urlresolver9/lib/log_utils.py
log_utils.py
py
1,007
python
en
code
66
github-code
90
22282343058
__version__ = "0.2" import sys import re import colour import numpy # Observers # - Classic default was 2° (from 1931) # - Newer addition of 10° (from 1964) # # Das 2°-Gesichtsfeld entspricht der Größe der Netzhautregion mit der dichtesten Packung von # Zapfen (Farbrezeptoren) im menschlichen Auge. Das normale Sichtf...
sebastian-software/colorpro
colorpro.py
colorpro.py
py
7,728
python
en
code
1
github-code
90
18102422079
import sys def insertionSort(A, N): for n in range(N-1): print (A[n], end=" ") print(A[N-1]) for i in range(1, N): v = A[i] j = i - 1 while j >= 0 and A[j] > v: A[j + 1] = A[j] j = j - 1 A[j + 1] = v for n in range(N-1): ...
Aasthaengg/IBMdataset
Python_codes/p02255/s327297004.py
s327297004.py
py
496
python
en
code
0
github-code
90
17164515837
from apps.account import models as account_models from apps.store import models as store_models from rest_framework import serializers class ClientSerializer(serializers.ModelSerializer): first_name = serializers.SerializerMethodField() last_name = serializers.SerializerMethodField() phone = serializers.S...
IslomK/TestTask
apps/restful/serializers.py
serializers.py
py
5,529
python
en
code
1
github-code
90
18744333935
import os import time from PyQt5 import QtWidgets, QtCore, QtGui from PyQt5.QtCore import QSize from PyQt5.QtCore import Qt from PyQt5.QtCore import pyqtSignal from PyQt5.QtGui import QCursor from PyQt5.QtGui import QPixmap from PyQt5.QtWidgets import QApplication from PyQt5.QtWidgets import QMenu, QAbstractItemView, ...
kaoxing/seg
projectFiles/UI/Widgets/imageWidget.py
imageWidget.py
py
5,984
python
en
code
2
github-code
90
14560905191
import unittest from hdlite import Simulation as sim from hdlite import Signal as sig from hdlite.Component import * class DFlipFlop(Component): def __init__(self, name, clock, resetn, d, q, qn): super().__init__(name) self.d = d self.q = q self.qn = qn self.clock = clock...
msiddalingaiah/EE
HDLite/hdltest/TestSignals.py
TestSignals.py
py
4,558
python
en
code
0
github-code
90
72024539496
"""Тестирование построения многоугольников зон влияния""" from __future__ import annotations from pathlib import Path import unittest from geometry import Point from model import Grid from processing import BoundaryBuilder, Xgml from tests.mocks import ConfigMock, get_test_grid from tests.utils import clean_directory,...
lastick1/rexpert
tests/unit/test_boundary_builder.py
test_boundary_builder.py
py
6,609
python
en
code
1
github-code
90
70087172136
# -*- coding: utf-8 -*- from odoo import models, fields, api, _ from odoo.exceptions import ValidationError import base64 import xlrd import logging _logger = logging.getLogger(__name__) class GraduationWizard(models.TransientModel): _name = 'graduation.wizard' _description = 'Graduation wizard' new_gr...
dionisiotorres/dxm_varios
mobile_device_reception/wizard/graduation_wizard.py
graduation_wizard.py
py
2,925
python
en
code
0
github-code
90
37289226284
import random from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.shortcuts import render, get_object_or_404 from django.views.generic import ListView from mainapp.models import Product, ProductCategory def get_hot_product(): return random.sample(list(Product.objects.all()), 1)[...
vlgreb/shop
geekshop/mainapp/views.py
views.py
py
4,000
python
en
code
0
github-code
90
14098502341
import pygame import os import math import random # Bubble sprite class class Bubble(pygame.sprite.Sprite): def __init__(self, color, image, animation = None, position=(0,0), row_idx=-1, col_idx=-1): super().__init__() self.image = image self.color = color self.position = position...
1201ysy/Pygame
BubbleBubble/bubblebubble.py
bubblebubble.py
py
19,139
python
en
code
0
github-code
90
28335763118
import sys if __name__ == '__main__': skip = int(sys.argv[1]) counter = {} for line in sys.stdin: count, *words = line.strip().split() words = ' '.join(words[::skip+1]) if words not in counter: counter[words] = count else: counter[words] += count ...
Neverous/ii-nlp15
genskipgrams.py
genskipgrams.py
py
408
python
en
code
0
github-code
90
18515754029
import sys readline = sys.stdin.buffer.readline def even(n): return 1 if n%2==0 else 0 n = int(readline()) lst1 = list(map(int,readline().split())) ans = 0 flag = 0 for i in range(n-1): if flag: flag = 0 continue if lst1[i] == lst1[i+1]: ans += 1 flag = 1 print(ans)
Aasthaengg/IBMdataset
Python_codes/p03296/s522050536.py
s522050536.py
py
308
python
en
code
0
github-code
90
18230328886
#! /usr/bin/env python3 import sqlalchemy as sa import pytest from ws.client.api import API from ws.db.database import Database import ws.db.schema as schema from fixtures.postgresql import * from fixtures.mediawiki import * from fixtures.title_context import * # disable rate-limiting for tests def pytest_configure...
lahwaacz/wiki-scripts
tests/conftest.py
conftest.py
py
1,713
python
en
code
27
github-code
90
18228838629
s=[int(x) for x in reversed(list(input()))] n=len(s) x=[0]*2019 dp = 0 dim = 1 for si in s: dp = (dp + si*dim) % 2019 x[dp] += 1 dim = dim * 10 % 2019 ans = x[0] for i in range(2019): ans += x[i]*(x[i]-1)//2 print(ans)
Aasthaengg/IBMdataset
Python_codes/p02702/s976723822.py
s976723822.py
py
226
python
en
code
0
github-code
90