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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
42110400732 | import cv2
# using USB webcam number 1
cam = cv2.VideoCapture(0)
# You can save your video according to the same size as your webcam stream or hardcode the size you like
# frame_width = int(cam.get(3))
# frame_height = int(cam.get(4))
# recorder = cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc('M','J','P','G'),... | abuelgasimsaadeldin/opencv-starter-pack | python/basic/video_writer.py | video_writer.py | py | 979 | python | en | code | null | github-code | 1 |
35632566087 | import sys
def main(lines):
class info:
def __init__(self, number, string):
self.number = number
self.string = string
def calc(self):
if num % self.number == 0:
ans.append(self.string)
def print_ans(self, answer):
if len(ans) == 1:
... | YujinMiyoshi/0202 | track_test/cording_test1.py | cording_test1.py | py | 988 | python | en | code | 0 | github-code | 1 |
16284369692 | """
validate and maniopulate genbank files.
"""
from setuptools import find_packages, setup
dependencies = ['click']
setup(
name='faketool',
version='0.1.4',
url='https://github.com/sgordon007/fake-tool',
license='BSD',
author='Sean Gordon',
author_email='seangordon07@gmail.com',
descripti... | sgordon007/fake-tool | setup.py | setup.py | py | 1,617 | python | en | code | 0 | github-code | 1 |
33346652507 | N,M=map(int,input().split())
location=list(map(int,input().split()))
location.append(0)
list_plus=[]
list_minus=[]
location.sort()
index=location.index(0)
if index==N:
list_plus.append(0)
else :
list_plus=location[index+1:N+1]
list_minus=location[0:index]
minus_count=len(list_minus)
plus_count=len(list_plus)
if... | atg0831/algo | prev-problems/1461.py | 1461.py | py | 2,989 | python | en | code | 0 | github-code | 1 |
26632783548 | class Solution:
def spiralOrder(self, matrix: [[int]]) -> [int]:
if matrix == []:
return []
top = 0
bottom = len(matrix) - 1
left = 0
right = len(matrix[0]) - 1
res = []
while top < bottom and left < right:
res += matrix[top][left:r... | RafaelHuang87/Leet-Code-Practice | 54.py | 54.py | py | 864 | python | en | code | 0 | github-code | 1 |
35076962554 | """
DW NVM implementation
"""
from pyedbglib.protocols.jtagice3protocol import Jtagice3ResponseError
from .nvm import NvmAccessProviderCmsisDapAvr
from .avr8target import TinyAvrTarget
class NvmAccessProviderCmsisDapDebugwire(NvmAccessProviderCmsisDapAvr):
"""
NVM Access the DW way
"""
def __init__(s... | SpenceKonde/megaTinyCore | megaavr/tools/libs/pymcuprog/nvmdebugwire.py | nvmdebugwire.py | py | 2,214 | python | en | code | 471 | github-code | 1 |
1917816925 | from trackingsimpy.simulation.revisit_interval import BaseRISimulation
from trackingsimpy.tracking import TrackingComputer
from trackingsimpy.radar import PositionRadar
import filterpy.common
from filterpy.kalman import IMMEstimator, KalmanFilter
from trackingsimpy.common.motion_model import constant_turn_rate_matrix, ... | PetteriPulkkinen/TrackingSimPy | trackingsimpy/simulation/revisit_interval/defined_imm.py | defined_imm.py | py | 4,167 | python | en | code | 2 | github-code | 1 |
32808604003 | import random
dict_options = {1: "Rock", 2: "Paper", 3: "Scissors"}
winner = "Me"
me_i = 0
you_i = 0
error_count = 0
def did_you_win(m, y):
if (m == 1) and (y == 2):
return "You"
elif (m == 1) and (y == 3):
return "Me"
elif (m == 2) and (y == 3):
return "You"
elif (m == 2) and... | StephenH69/Python-Scripts | rock_paper_scissors.py | rock_paper_scissors.py | py | 1,713 | python | en | code | 1 | github-code | 1 |
11131287505 | from urllib.request import Request, urlopen
from fake_useragent import UserAgent
import json
import csv
headers = {"user-agent": UserAgent().chrome, "referer": "https://finance.daum.net/"}
path = "./RPAbasic/crawl/download/"
data = []
try:
url = "https://finance.daum.net/api/search/ranks?limit=10"
res = urlope... | hayeong25/Python_Soldesk | rpa/crawl/urllib/5_daum_kosdaq.py | 5_daum_kosdaq.py | py | 2,167 | python | ko | code | 0 | github-code | 1 |
29317960475 |
import sys
import time
import os
import gc
import json
import argparse
from pathlib import Path
os.environ["JAX_PLATFORMS"] = "cpu"
import jax
import flax
import numpy as np
import jax.numpy as jnp
import orbax
import orbax.checkpoint
from optax import MaskedNode
from etils import epath
from praxis import base_hyper... | Lisennlp/paxml_praxis | paxml/my_scripts/converts/qwen_hf_to_paxml.py | qwen_hf_to_paxml.py | py | 10,005 | python | en | code | 0 | github-code | 1 |
42627997082 | import random
import os
os.system('title Flip A Coin')
coin = ["heads", "tails"]
heads = 0
tails = 0
while 1:
heads = 0
tails = 0
p = input("Enter times to flip the coin : ")
for _ in range(int(p)):
x = "".join(random.choices(coin))
if 'tails' in x:
tails+=1
... | Younesdev12/some-simple-projects | src/coinflip.py | coinflip.py | py | 554 | python | en | code | 0 | github-code | 1 |
30523416801 | import sys
import random
import re
from functools import partial
from tqdm import tqdm
from junkdrawer import generator_looper
def lindenate(liRules, sInput="", lIterations=1):
"""This function iteratively processes a set of find-and-replace rules, liRules, on a given string, sInput.
By defaul... | Thelnar/Lindenmayer-Fractals-Web-App | lindenmayer.py | lindenmayer.py | py | 10,433 | python | en | code | 0 | github-code | 1 |
71346990433 | # Add a filter to a palette
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-i', default="Palette.dmp", help='Input tileset palette file. default is Palette.dmp')
parser.add_argument('-o', default="Palette2.dmp", help='Output tileset palette file. default is Palette2.dmp')
parser.add_argument('... | Huichelaar/HuichFE | Graphics/RGBFilter.py | RGBFilter.py | py | 1,442 | python | en | code | 2 | github-code | 1 |
72921628835 | import urllib.request, json
from libbottles.utils import connection
from libbottles.exceptions import NoConnection
class Request:
_headers = {}
def __init__(self, headers: dict = None):
self._headers["User-Agent"] = "libbottles client (usebottles.com)"
if headers is not None:
s... | bottlesdevs/libbottles | libbottles/utils/request.py | request.py | py | 730 | python | en | code | 4 | github-code | 1 |
43073974779 | import logging
from typing import Dict
import grpc
from needlestack.apis import collections_pb2
from needlestack.apis import servicers_pb2
from needlestack.apis import servicers_pb2_grpc
from needlestack.apis import serializers
from needlestack.collections.collection import Collection
from needlestack.collections.sha... | needlehaystack/needlestack | needlestack/servicers/searcher.py | searcher.py | py | 6,488 | python | en | code | 3 | github-code | 1 |
2775733167 | """
https://leetcode.com/problems/backspace-string-compare/
"""
class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
clean_s, clean_t = list(), list()
for i, c in enumerate(S):
if c != '#':
clean_s.append(c)
elif c == '#' and clean_s:
... | alexparunov/leetcode_solutions | src/800-900/_844_backspace-string-compare.py | _844_backspace-string-compare.py | py | 560 | python | en | code | 1 | github-code | 1 |
26885414895 | import json
from datetime import timedelta
from db.redis import init_redis_pool
async def add_test_result_to_redis(result_id: int, user_id: int, id_company: int, id_quiz: int, data: dict):
redis = await init_redis_pool()
key = f"result_test:{result_id:}:id_user:{user_id}:id_company:{id_company}:id_quiz:{id_... | saindi/internship | app/db/redis_actions.py | redis_actions.py | py | 905 | python | en | code | 0 | github-code | 1 |
22594227372 | ####################################################
##### This is focal loss class for multi class #####
##### University of Tokyo Doi Kento #####
####################################################
import torch
import torch.nn as nn
import torch.nn.functional as F
# I refered https://github.com/c0nn3r/Re... | ISCAS007/torchseg | torchseg/utils/loss/focalloss2d.py | focalloss2d.py | py | 2,324 | python | en | code | 7 | github-code | 1 |
32790785348 | import requests
from bs4 import BeautifulSoup
import json
# URL of the web page to scrape
url = 'https://nookipedia.com/wiki/Category:New_Horizons_fish_icons'
# Send an HTTP request to the web page
response = requests.get(url)
# Check if the request was successful
if response.status_code == 200:
# Parse the HTML... | JohnMcSwiney/acnh_encyclopedia | server/img_scraping.py | img_scraping.py | py | 1,012 | python | en | code | 1 | github-code | 1 |
11460338892 | from django.db import models
from django.utils.translation import gettext_lazy as _
class VCard(models.Model):
"""
Vcard model.
"""
title = models.CharField(
_("Title"),
blank=True,
max_length=150,
default="",
)
def __str__(self):
return self.title
... | 7saikat7/django-qr-vcard | qr_vcard/models/vcard.py | vcard.py | py | 409 | python | en | code | 0 | github-code | 1 |
2299030097 | import json
import subprocess
import os
import zmq
class CommandLineBarcodeReader():
def __init__(self, config_path="scandit_commandline",port=5556):
self.context = zmq.Context()
self.process = None
self.config_path = config_path
self.port = port
self.start_comman... | xulihang/Barcode-Reading-Performance-Test | barcode_reader/commandline.py | commandline.py | py | 2,416 | python | en | code | 11 | github-code | 1 |
8933078688 | """
大多数(nobody)女主喜好
"""
BaiJiaHui = {
'like': {'服饰搭配', '古典乐', '古装片', '滑雪', '美容', '民谣', '萨克斯', '桑拿', '时尚', '天文', '西餐', '演唱会', '游戏', '瑜伽', '桌游', '温泉', '吉他',
'游泳', '度假村', '网球', '美容'},
'dislike': {'美食', '高抬腿'}
}
GaoShanShan = {
'like': {'高山', '有氧跑', '海边休闲', '剪纸', '民宿', '拼图', '桑拿', '派对', '爱情片',... | LuShengcan/lywt | lywt/nobody.py | nobody.py | py | 1,723 | python | zh | code | 0 | github-code | 1 |
43154185198 | from tkinter import PhotoImage
import tkinter as tk
from ingresar import*
from generar import*
from general import*
from funciones import *
from archivo import *
from validaciones import *
matriz= []
matriz = leerDatos('datos')
print(matriz)
# diccionario de colores
color = {"fondo":"#F0F0F0", "sidebar":"#052744... | Chacalerks/Tarea-Programada-2 | mainFrontend.py | mainFrontend.py | py | 2,275 | python | es | code | 1 | github-code | 1 |
2122135874 | from src.examples.program.traccar.config.config import Config
from src.examples.program.traccar.config.configKey import ConfigKey
from src.examples.program.traccar.model.extendedModel import ExtendedModel
class PropertiesProvider:
def _initialize_instance_fields(self):
self._config = None
self._e... | sofialucca/thesisResearch | src/examples/program/traccar/notification/propertiesProvider.py | propertiesProvider.py | py | 1,699 | python | en | code | 0 | github-code | 1 |
21246023751 | '''
Escreva um programa que leia a profissão e o tempo de serviço (em anos) de cada um dos 5
funcionários de uma empresa e armazene-os no arquivo "emp.txt". Cada linha do arquivo
corresponde aos dados de um funcionário.
'''
raiz = 'c:/Users/Higor H/Documents/Estudos/Python'
pasta = raiz + '/Curso de Programação em Pyt... | higor-gomes93/curso_programacao_python_udemy | Sessão 13 - Exercícios/ex23.py | ex23.py | py | 671 | python | pt | code | 0 | github-code | 1 |
69878608033 | import sys
from collections import deque
N, M, V = map(int, sys.stdin.readline().split())
graph = [[0]*(N+1) for i in range(N+1)]
#인접행렬생성
for i in range(M):
a, b = map(int, sys.stdin.readline().split())
graph[a][b] = graph[b][a] = 1
visited = [False] * (N + 1)
def dfs(V):
visited[V] = True
print(V, ... | jjongram/demo-repository | self_study/src/baekjoon/bfsdfspractice.py | bfsdfspractice.py | py | 778 | python | en | code | 1 | github-code | 1 |
40759520304 | import json
import pickle
import random
from os.path import join, dirname
import nltk
from nltk.corpus import treebank
from nltk.tag.sequential import ClassifierBasedPOSTagger
MODEL_META = {
"corpus": "treebank",
"lang": "en",
"model_id": "nltk_treebank_clftagger",
"tagset": "Penn Treebank",
"algo... | OpenJarbas/ModelZoo | train/postag/nltk_treebank_clf_postag.py | nltk_treebank_clf_postag.py | py | 1,106 | python | en | code | 1 | github-code | 1 |
3259438205 | import sys
input = lambda: sys.stdin.readline().strip()
cnt_fib = 0
def fib(n):
global cnt_fib
cnt_fib += 1
if n == 1 or n == 2:
return 1
return fib(n - 1) + fib(n - 2)
def fibonacci(n):
f = [0] * (n + 1)
f[1] = f[2] = 1
cnt = 0
for i in range(3, n + 1):
f[1] = f[i - 1... | zinnnn37/BaekJoon | 백준/Bronze/24416. 알고리즘 수업 - 피보나치 수 1/알고리즘 수업 - 피보나치 수 1.py | 알고리즘 수업 - 피보나치 수 1.py | py | 472 | python | en | code | 0 | github-code | 1 |
5606689245 | from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import *
import wizzat.testutil
import wizzat.pghelper
class DBTestCase(wizzat.testutil.TestCase):
db_info = {
'host' : 'localhost',
'port' : 5432,
'user' : 'wizzat',
... | wizzat/wizzat.py | tests/testcase.py | testcase.py | py | 630 | python | en | code | 6 | github-code | 1 |
34214137069 | """
Exp 00 - Tests Data preprocessing and trains a basic linear regression
Model for abalone age prediction
"""
from datetime import datetime
from sklearn.linear_model import LinearRegression
import numpy as np
class Exp00:
""" Experiment Class to test and run abalone data processing
... | zaccross/Linear-Regression-Project-0.5 | exp00.py | exp00.py | py | 5,389 | python | en | code | 0 | github-code | 1 |
5970089244 | n = int(input())
longest_intersection = set()
best_length = 0
for _ in range(n):
ranges = input().split("-")
first_range_start, first_range_end = map(int, ranges[0].split(","))
second_range_start, second_range_end = map(int, ranges[1].split(","))
first_set = set([x for x in range(first_range_start, f... | LachezarKostov/SoftUni | 02_Python-Advanced/02_Table-and-Sets/02-Exercise/06-Longest Intersection.py | 06-Longest Intersection.py | py | 721 | python | en | code | 1 | github-code | 1 |
27286453553 | from __future__ import annotations
import warnings
from typing import TYPE_CHECKING, Any, Dict, Optional, Union
import numpy as np
import pandas as pd
if TYPE_CHECKING: # pragma: no cover
from cleanlab.datalab.internal.data import Data
from cleanlab.datalab.internal.issue_manager import IssueManager
fro... | cleanlab/cleanlab | cleanlab/datalab/internal/data_issues.py | data_issues.py | py | 10,122 | python | en | code | 7,004 | github-code | 1 |
26844478578 | import pytest
import hashtags as ht
@pytest.fixture
def tweets():
return [
{
'id_str': '1',
'text': " Doesn't matter what the text is. ",
'entities': {
'hashtags': [
{'text': 'fOO'},
{'text': 'Bar'}
... | marklar/massiu | test/test_hashtags.py | test_hashtags.py | py | 1,311 | python | en | code | 0 | github-code | 1 |
33761576764 | from fst import EPSILON
simulation_number = 1
configurations_dict = \
{
"MUTATE_RULE_SET": 1,
"MUTATE_HMM": 1,
"EVOLVE_RULES": True,
"EVOLVE_HMM": True,
"COMBINE_EMISSIONS": 1,
"MERGE_EMISSIONS": 0,
"ADVANCE_EMISSION": 1,
"CLONE_STATE": 0,
"CLONE_EMISSION": 1,
"SPLIT_EMISSION": 0,
"MOVE_EMISSION": 1,
"ADD_STATE": 1,... | taucompling/morphophonology_spe | source/simulations/dag_zook_noise_voicing.py | dag_zook_noise_voicing.py | py | 4,163 | python | en | code | 5 | github-code | 1 |
30654758574 | import os
import numpy as np
import zarr
from pyproj import Proj, transform
from rasterio import Affine
from rasterio.crs import CRS
from rasterio.transform import rowcol, xy
from scipy.stats import binom
def albers_conus_extent():
return "-2493045.0 177285.0 2342655.0 3310005.0"
def albers_conus_crs():
re... | carbonplan/forest-risks | carbonplan_forest_risks/utils.py | utils.py | py | 4,259 | python | en | code | 29 | github-code | 1 |
13463218914 | import argparse
import sys
import os
from random import randint as rand
#this will store lists of all the predictions needed for the labels
preds = {}
def dataReader(data_file):
f = open(data_file)
data = []
i = 0
for line in f.readlines():
line = [float(x) for x in line.split()]
d... | FrancisDcruz/ML_Algorithms | Bagged_Decission_Stump/Bagged_Decission_Stump.py | Bagged_Decission_Stump.py | py | 5,659 | python | en | code | 0 | github-code | 1 |
41564702032 | from bs4 import BeautifulSoup
import xlsxwriter
workbook = xlsxwriter.Workbook('aliexpress.xlsx')
worksheet = workbook.add_worksheet()
orders = []
fileN = 14
def readDataHTML():
global days
global weekdayBuckets
global mptc
global tptc
global targetdir
global fileN
for i in range(... | DawidPietrykowski/AliReader | AliReader/AliReader.py | AliReader.py | py | 4,155 | python | en | code | 0 | github-code | 1 |
71606823075 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/10/11 14:31
# @Author : Tao.Xu
# @Email : tao.xu2008@outlook.com
import sys
import json
import superelasticsearch
from superelasticsearch import SuperElasticsearch
from elasticsearch import serializer, exceptions
from tlib import log
from tlib.retry... | txu2k8/libs-py | tlib/es/elasticsearch_super.py | elasticsearch_super.py | py | 17,979 | python | en | code | 1 | github-code | 1 |
20658199400 |
def repeticoes_quadrantes_pista(quad, matriz_pistas):
for percorrer in matriz_pistas: # Percorro todos os quadrantes
i, j, valor = percorrer # Desempacoto as listas iteradas
if i in 'ABC' and j in '123': # Primeiro quadrante 3x3 e assim sucessivamente...
quad.append(valor)
if len... | DegeneratorX/sudoku | checagem_repeticoes_pista.py | checagem_repeticoes_pista.py | py | 5,277 | python | pt | code | 0 | github-code | 1 |
12809185680 | def main():
temps = input("Enter number of days and the high temperatures:")
templist = temps.split(' ')
tlist2 = [int(i) for i in templist]
tlist3 = tlist2[1:]
prev = tlist3[0]
day = 1
cdays = 0
for i in tlist3[1:]:
diff = prev - i
day += 1
if diff >= 15:
print("Temperature drop (" + ... | granja-c/Programming-1-7 | itscoldout.py | itscoldout.py | py | 481 | python | en | code | 0 | github-code | 1 |
3085545928 | # -*- coding: GBK -*-
import conf
class Player(object):
FireMoney = 60
NeedleMoney = 80
def __init__(self, hid):
super(Player, self).__init__()
self.room = None
self.hid = hid
self.isOver = False
def getDamage(self, fireType):
if fireType == conf.FIRE_LEFT:
return self.fireDamage
else:
return sel... | zhanghuanzj/PythonTrifles | TPS2017/TPS/server/common/player.py | player.py | py | 1,140 | python | en | code | 2 | github-code | 1 |
73116502755 | import json
from dataclasses import dataclass
from datetime import datetime
from functools import partial
from typing import Optional
import arrow
# import pytest
from arrow import Arrow
from lyubishchev.clockify_fetcher.fetcher import (
generate_time_interval_from_time_series,
) # generate_event_from_time_seri... | eliteGoblin/lyubishchev | tests/unit/clockify_fetcher/test_generate_time_interval_from_time_series.py | test_generate_time_interval_from_time_series.py | py | 4,992 | python | en | code | 0 | github-code | 1 |
26434848146 | """create item table
Revision ID: ff9dac589eea
Revises: 8c1c7409f4e5
Create Date: 2022-07-10 08:58:37.265281
"""
from alembic import op
import sqlalchemy as sa
from datetime import datetime
# revision identifiers, used by Alembic.
revision = 'ff9dac589eea'
down_revision = '8c1c7409f4e5'
branch_labels = None
depends_... | guneybilen/fastAPI_justlikenew | alembic/versions/ff9dac589eea_create_item_table.py | ff9dac589eea_create_item_table.py | py | 1,168 | python | en | code | 0 | github-code | 1 |
10753417824 | # author:JinMing time:2020-05-17
# -*- coding: utf-8 -*-
import socket
name = "Nathaniel"
def handleData(data):
"""
将消息处理为特定格式
:param data: 消息原文
:return: 处理后的消息
"""
# 先处理消息第二部分
if data == "Nathaniel":
dataType = "1"
else:
dataType = "2"
# 处理消息的第一部分
strLen = le... | chenjinming580/PycharmProjects | untitled/python2file/day4/job/客户端.py | 客户端.py | py | 900 | python | en | code | 0 | github-code | 1 |
8294469824 | from easyjsonparser.document import JSONObjectDocument
import easyjsonparser as ejp
import unittest
class TestObjectWithObject(JSONObjectDocument):
class ObjectProperty(ejp.Object):
attr1 = ejp.String()
attr2 = ejp.Integer()
prop = ObjectProperty()
class TestObjInObj(unittest.TestCase):
... | xatavian/easyjsonparser | test/test_objinobj.py | test_objinobj.py | py | 1,370 | python | en | code | 3 | github-code | 1 |
69971042913 | # import modules
import pygame
import time
import random
#initialize pygame
pygame.init()
#########################################################
# our game variables
#get colors
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
blue = (20, 136, 234)
display_width = 800 #game width
display_height = 600 #... | evanswanjau/slither | slither.py | slither.py | py | 7,241 | python | en | code | 1 | github-code | 1 |
26717443328 | from mem_solver import *
import math
COV = 1024
class HMC( object ):
def __init__( self, config, bit_unit, mode = 1 ):
self.config = config
self.bit_unit = bit_unit
self.mode = mode
# spec short cut
self.total_size = self.config[ "config" ][ "size" ]
self.num_ba... | YingjingLu/Near-Mem-DL | src/simulator/hmc.py | hmc.py | py | 11,783 | python | en | code | 3 | github-code | 1 |
34308854571 | # [si]rc - Asynchronous source RCON tool.
from decorators import *
import functools
from textwrap import dedent
import logging
import model
import sqlalchemy
import time
__all__ = [
"list", "select",
"add", "set", "delete",
"stats", "status", "rcon",
"error", "help"
]
def list( ... | koenbollen/sirc | src/commands.py | commands.py | py | 6,447 | python | en | code | 0 | github-code | 1 |
16001559321 |
import unittest
# Modules needed to support tests
import os
import os.path
import tempfile
# Module under test
import dedupe.detector.detector as detector
class TestProcessFilename(unittest.TestCase):
def _make_standard_file_at(self, filename):
fout = open(filename, 'w+b')
fout.write(self.... | pcurry/DeDupe | test/python2.7/dedupe/detector/detector_test.py | detector_test.py | py | 1,694 | python | en | code | 0 | github-code | 1 |
33953298529 | from torch.utils.data import Dataset
from PIL import Image
from glob import glob
from tqdm import tqdm
import os
#SubClass of Dataset that takes the IN9L dataset stored in the folder
#indicated by the parameter "root" and perform operation on it
class IN9L_dataset(Dataset):
def __init__(
self,
... | Giordano-Cicchetti/MaskTune_NN | IN9L/IN9L.py | IN9L.py | py | 1,910 | python | en | code | 0 | github-code | 1 |
21603769373 | from typing import List, Callable, Tuple
SUPER_MODULO = 5*17*7*13*19*11*3*2
def basic_monkey_throw(value: int, divider: int, success_monkey: int, fail_monkey: int) -> Tuple[int, int]:
# new_value = int(value / 3) # PART 1
new_value = value % SUPER_MODULO # PART 2
if new_value % divider == 0:
# new... | jochemvanweelde/adventofcode | aoc2022/Day 11/monkey_in_the_middle.py | monkey_in_the_middle.py | py | 4,374 | python | en | code | 0 | github-code | 1 |
16139182495 | import torch
from torch import nn
import torchvision.datasets as datasets
from torch.utils.data import Subset, DataLoader, TensorDataset
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
from typing import Tuple
import os
import cv2
def get_cv_datasets(
dataset: torch.Tensor,
epoch_nr:... | m-ulmestrand/ego-generator | face/train.py | train.py | py | 7,497 | python | en | code | 0 | github-code | 1 |
71015664355 | # Title: 터렛
# Link: https://www.acmicpc.net/problem/1002
import sys
sys.setrecursionlimit(10 ** 6)
read_single_int = lambda: int(sys.stdin.readline().strip())
read_list_int = lambda: list(map(int, sys.stdin.readline().strip().split(' ')))
def dist2(x: int, y: int, xx: int, yy: int):
return (x-xx)... | yskang/AlgorithmPractice | baekjoon/python/turret_1002.py | turret_1002.py | py | 955 | python | en | code | 1 | github-code | 1 |
27271932926 | n, k = map(int, input().split())
coins = []
dp = [0 for i in range(k + 1)]
dp[0] = 1
for i in range(n):
coins.append(int(input()))
for coin in coins:
for index in range(1, k + 1):
if index - coin >= 0:
dp[index] += dp[index - coin]
print(dp[k]) | honggom/TIL | problem-solving/baekjoon/dp/2293.py | 2293.py | py | 275 | python | en | code | 0 | github-code | 1 |
37555770747 | import requests
import lxml.html
headers = {"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0"}
def Japanese_translation(english):
results = set()
url = 'https://jisho.org/search/'
response = requests.get(url + english, headers=headers)
html = lxml.html.froms... | HiroRittsu/DevelopingEnglish | lib/JISHO_ORG.py | JISHO_ORG.py | py | 1,078 | python | en | code | 0 | github-code | 1 |
5699937924 | from django.conf import settings
from django.contrib.auth.base_user import BaseUserManager
from django.contrib.auth.models import AbstractUser
from django.contrib.postgres.fields import ArrayField
from django.db import models, transaction
from django.db.models import F
from lottery.models import Draw, get_number_of_ti... | conyappa/backend | conyappa/accounts/models.py | models.py | py | 7,960 | python | en | code | 0 | github-code | 1 |
24172843200 | import torch
def init_weights(m) -> None:
if isinstance(m, torch.nn.Linear):
torch.nn.init.xavier_uniform_(m.weight)
m.bias.data.fill_(0.01)
if isinstance(m, torch.nn.Embedding):
torch.nn.init.xavier_uniform_(m.weight)
class CategoryClassification(torch.nn.Module):
def __init__(
... | alexflorensa/product-category-classification | models/categoryclassification.py | categoryclassification.py | py | 1,216 | python | en | code | 0 | github-code | 1 |
15087752784 | import base64
from Crypto.Cipher import AES as aes
from Crypto.Util.Padding import pad
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
key = get_random_bytes(16)
iv = b''
if iv == b'':
iv = get_random_bytes(16)
print(iv)
# cipher = aes.new(key, aes.MODE_CBC, iv)
# ... | alitcy/fyp-21-s1-02 | enc-dec.py | enc-dec.py | py | 2,111 | python | en | code | 0 | github-code | 1 |
72427446434 | from django.shortcuts import get_object_or_404,render, HttpResponseRedirect
from django.shortcuts import render
from django.contrib import messages
from .forms import todoform,dateform
from django.shortcuts import redirect
from django.conf import settings
# Create your views here.
# import datetime
from datetime impor... | ashtiv/django-diary | accounts/views.py | views.py | py | 7,635 | python | en | code | 0 | github-code | 1 |
1502144500 | from typing import List
def rotate_clockwise(matrix: List[List[int]]) -> None:
"""
Rotate a nxn 2D int matrix 90 degrees clockwise in place
Args:
matrix: A nxn 2D int matrix
Returns:
matrix being roated 90 degree clockwise in place
Raises:
TypeError: If the matrix is ... | ucsd-ets/python-docker-example | pyapp/rotate_clockwise.py | rotate_clockwise.py | py | 1,014 | python | en | code | 0 | github-code | 1 |
12951104701 | from typing import Any
from datetime import datetime
from datasets import load_dataset
import meilisearch
# https://huggingface.co/datasets/mc4
dataset = load_dataset("mc4", "ja", split="train", streaming=True)
documents: list[dict[str, Any]] = list(dataset.take(30000))
# add primary key and convert datetime string in... | Wattyyy/ms-error-reproduction | mc4_index.py | mc4_index.py | py | 824 | python | en | code | 0 | github-code | 1 |
40296713959 | '''
Rotina para gabarito da estratégia de busca de geolocalização do sensor SEARCH1
Programa de Autoria de Henrique Guimarães Coutinho. Domínio público.
Última atualização: 09/09/2021.
Como citar: endereço github.
'''
import numpy as np
#import matplotlib
import matplotlib.pyplot as plt
import math as m
... | henriquecoutin/search1 | Explore_and_Analyse_Data.py | Explore_and_Analyse_Data.py | py | 3,585 | python | pt | code | 1 | github-code | 1 |
21182580023 | import csv
import GGlib
liste_coord = []
coordinates = []
with open('data_for_example/Baiedeschaleurs.csv') as csvfile:
data = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in data:
# print(row[0])
coord = row[0].split(",")
latitude = float(coord[0])
longitude = float(coord[1])
coordinates += [... | CIDCO-dev/PecheFantome | src/GIS/example_csv_to_shp.py | example_csv_to_shp.py | py | 443 | python | en | code | 1 | github-code | 1 |
25433492869 | import heapq, sys
input = sys.stdin.readline
h = []
for i in range(int(input())):
n = int(input())
if n == 0:
if len(h) == 0:
print(0)
else:
print(heapq.heappop(h))
else:
heapq.heappush(h, n) | reddevilmidzy/baekjoonsolve | 백준/Silver/1927. 최소 힙/최소 힙.py | 최소 힙.py | py | 262 | python | en | code | 3 | github-code | 1 |
41579158009 | from flask import Flask, render_template, request, redirect, url_for, flash, abort, session, jsonify
import json
import os.path
# from werkzeug.utils import secure_filename
import datetime
import os
app = Flask(__name__)
app.permanent_session_lifetime = datetime.timedelta(days=30)
# Set up this secret_key to be genera... | StellarApp/dl-image-recognition | app.py | app.py | py | 2,634 | python | en | code | 0 | github-code | 1 |
31533506345 | # 1. Connect to database
from pymongo import MongoClient
# from bson.objectid import ObjectId
uri = "mongodb://admin:Hanoi1@ds029224.mlab.com:29224/c4e21"
client = MongoClient(uri)
db = client.get_database()
# 2. Select collection
posts = db['posts']
# 3. Create document
post = {
"title": "Hôm nay là thứ 3",
... | unpreghini/htanh-lab-c4e21 | Lab1/db_blog.py | db_blog.py | py | 623 | python | vi | code | 0 | github-code | 1 |
39560810668 | import copy
from BU.NTS.dataCheck.dataCheck import getNowAccount,warning_rate,isOpen,t_risk_limit_leverage
from param.dict import SuccessMessage,FailMessage
from common import mysqlClient
from common.other import httpCheck as e
from UnitTest.com import LogName
from common.util import truncate, printc, printl, d, Count,... | wuzhiding1989/newqkex | BU/NTS/dataCheck/Formula.py | Formula.py | py | 31,378 | python | en | code | 1 | github-code | 1 |
10558607947 | class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# hashmap 이용
dic_nums = {}
for i, num in enumerate(nums):
check_num = target - num
if check_num in dic_nu... | SeungUkLee/LeetCode | Easy/1. Two Sum/Two Sum.py | Two Sum.py | py | 425 | python | en | code | 0 | github-code | 1 |
17609033288 | from weconnect.models.reviews import Review
from flask import current_app as app
class ReviewController():
"""
Controls all CRUD operations of the Review object.
"""
def create_review(self, content, business_id, user_id):
"""
Creates and adds a review to the app database.
... | JoshuaOndieki/weconnect | weconnect/review_controller.py | review_controller.py | py | 1,641 | python | en | code | 2 | github-code | 1 |
31839036452 | class CoefficientMatrix:
#Static variables defined at this indentation.
def __init__ (self, list_2d):
#Instance variables defined as `self.var_name`.
self.coeff_matrix = list_2d
self.rows = len(list_2d)
self.columns = len(list_2d[0])
return None
def add(self, ma... | SS-Runen/Learning-Mathematics-for-Machine-Learning | Python/CoefficientMatrix.py | CoefficientMatrix.py | py | 3,166 | python | en | code | 0 | github-code | 1 |
5118190626 | import copy
import logging
from random import sample, uniform
import unittest
import numpy as np
import pandas as pd
import time
from sklearn.ensemble import RandomForestClassifier
from make_data import make_data
import mr
N_SAMPLES = [100, 1000, 10000]
N_CLASSES = [(3, 1), (5, 1), (7, 1)]
N_FEATURES = [12]
N_INFO =... | bradgwest/mtrf | debug_mr.py | debug_mr.py | py | 3,880 | python | en | code | 0 | github-code | 1 |
7305644829 | import json
from src import plugin_loader
from unittest import TestCase
from src.attribute_methods import attribute_runner
root_directory = 'unit-tests/attribute_methods/sources/'
class TestAttributeRunner(TestCase):
def test_equal(self):
max_allowed = 0.4
with open(root_directory + 'settings.jso... | akhtyamovrr/plagchecker | unit-tests/attribute_methods/test_attribute_runner.py | test_attribute_runner.py | py | 732 | python | en | code | 0 | github-code | 1 |
36458767221 | import cv2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
def iterative_algorithm(img):
img_array = np.array(img).astype(np.float32)
I=img_array
Ti=50 #Set initial arbitrary value as threshold value
b=1
m,n=I.shape
diff = 255
count = 1
while diff!=0:
... | ravi-kr-singh/Image_Processing_nd_Computer_Vision_Programs | 07_iterative_algorithm.py | 07_iterative_algorithm.py | py | 1,614 | python | en | code | 0 | github-code | 1 |
74240361954 | def convert(nota_str):
nota = int(nota_str)
if nota == 0:
return 'E'
elif nota > 0 and nota < 36:
return 'D'
elif nota > 35 and nota < 61:
return 'C'
elif nota > 60 and nota < 85:
return 'B'
else:
return 'A'
entrada = input ()
print(convert(entrada))
| Turtienski/URI_JUDGE_PYTHON | Problema_2344/Notas_da_Prova.py | Notas_da_Prova.py | py | 317 | python | es | code | 0 | github-code | 1 |
8499194960 | #!/usr/bin/env python3
"""
libminutaria-cli
================
:Authors:
Locynaeh
:Version:
1.0
Command Line Interface (CLI)) based on the libminutaria library.
This script is directly usable in a terminal. Use -h/--help arguments for more
information on how to use the CLI provided.
"""
from datetime import ... | Locynaeh/minutaria | minutaria-cli.py | minutaria-cli.py | py | 1,930 | python | en | code | 1 | github-code | 1 |
17398468249 | responses = {}
# Set the flag to continue the survey.
polling_active = True
while polling_active:
# Request name and user response.
name = input("\nWhat is your name? ")
response = input("Which mountain would you like to climb someday? ")
# The answer is stored in the dictionary.
responses[name] ... | pavel-malin/python_work | mountain_poll.py | mountain_poll.py | py | 688 | python | en | code | 1 | github-code | 1 |
13056722078 | from django.core.management.base import BaseCommand, CommandError
from bhojanalayas.models import Address, Details
import csv
# from float import float
class Command(BaseCommand):
def add_arguments(self, parser):
pass
def handle(self, *args, **options):
with open('../../../../restaurantsa912... | megharana/Fortinet-Challenge | WorldBhojanalaya/bhojanalayas/management/commands/moveCSVToDb.py | moveCSVToDb.py | py | 1,929 | python | en | code | 0 | github-code | 1 |
36090971500 | class Table_matk:
def __init__(self, ids = "", sinhvien = None, hs1 = 0.0,hs2 = 0.0,hs3 = 0.0):
self.ids = ids
self.sinhvien = sinhvien
self.hs1 = hs1
self.hs2 = hs2
self.hs3 = hs3
self.calculate_gpa()
self.calculate_capacity()
def calculate_gpa(self):
... | anhduc1234567/PythonChap5 | lesson52_class/Table_mark.py | Table_mark.py | py | 862 | python | en | code | 0 | github-code | 1 |
10285812257 | from selenium import webdriver
from selenium.common.exceptions import TimeoutException
import xlsxwriter as xw
workbook = xw.Workbook("scrap2.xlsx")
worksheet = workbook.add_worksheet("Noticias")
# worksheet_error_page = workbook.add_worksheet("Erros de página")
# worksheet_error_content = workbook.add_worksheet("Erro... | HugoPfeffer/web-scrap-casb | noticias v2.py | noticias v2.py | py | 2,675 | python | en | code | 0 | github-code | 1 |
26401545941 | from flask import Flask, request, redirect, render_template, flash
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://build-a-blog:buildablog@localhost:8889/build-a-blog'
app.config['SQLALCHEMY_ECHO'] = True
db = SQLAlchemy(... | noragharris/build-a-blog | main.py | main.py | py | 1,740 | python | en | code | 0 | github-code | 1 |
24759725791 | import random
livend=[]
livenda=[]
comi=[]
for i in range(5):
vend=str(input("Digite o nome de um vendedor"))
venda=random.randint(300,30000)
comissao = venda * 0.1
livend.append(vend)
livenda.append(venda)
comi.append(comissao)
medvenda=sum(livenda)/len(livenda)
mais=0
for k in range(5):
... | GaBenfika/ExPython | 2°SEMESTRE/AU.160921/EX.02.160921.py | EX.02.160921.py | py | 775 | python | pt | code | 0 | github-code | 1 |
40172056753 | '''This module contains the implementation of recommending algorithms based on
the latent factor model.And the sample function to get the negative sample randomly.
Also some evaluation functions are included.
'''
import math
import random
def get_item_pool(path):
'''get_item_pool(filepath) -> list
This... | cyrusin/pyresys | rec/latent_factor_model.py | latent_factor_model.py | py | 4,785 | python | en | code | 1 | github-code | 1 |
29219958398 | from PyQt5.QtWidgets import QApplication, QSystemTrayIcon,QMenu
from PyQt5.QtGui import QIcon
import sys
from PyQt5.QtWidgets import QApplication, QSystemTrayIcon,QMenu
from PyQt5.QtGui import QIcon
from firebase_admin import credentials
from firebase_admin import db
import os
import speech_recognition as sr
import win... | BryanTG1221/IDA | IDA/scripts/icon.py | icon.py | py | 3,113 | python | en | code | 0 | github-code | 1 |
29453296966 | #
from typing import List
import numpy as np
from verypy.classic_heuristics.parallel_savings import clarke_wright_savings_function
from verypy.classic_heuristics.gaskell_savings import gaskell_lambda_savings_function, gaskell_pi_savings_function
from verypy.classic_heuristics.sweep import bisect_angle
SAVINGS_FN = {
... | jokofa/NRR | lib/nrr/utils.py | utils.py | py | 6,997 | python | en | code | 2 | github-code | 1 |
70497481953 | from functools import cmp_to_key
class Player(object):
def __init__(self, name, score):
self.name = name
self.score = score
def __repr__(self):
return f'{self.name} {self.score}'
def comparator(a, b):
if a.score > b.score:
return -1
elif a.score < b.sc... | NathanFee/InterviewQuestions | sort_complex.py | sort_complex.py | py | 950 | python | en | code | 0 | github-code | 1 |
12234502058 | # Merge sort algorithm:
# 1. Divide the unsorted list into sublists, each containing one element (a list of one element is considered sorted).
# 2. Repeatedly merge sorted sublist to produce new sorted sublists until there is only one sublist remaining - this will be the sorted list.
# Pseudocode of merge sort algorit... | SaidRem/algorithms | merge_sort.py | merge_sort.py | py | 3,136 | python | en | code | 0 | github-code | 1 |
30935072808 | num = int(input("Input a four digit numbers: "))
x = num //1000
x1 = (num - x*1000)//100
x2 = (num - x*1000 - x1*100)//10
x3 = num - x*1000 - x1*100 - x2*10
print("The sum of digits in the number is", x+x1+x2+x3)
#Solution by Gopal
n = input("Input a four digit numbers: ")
n1 = int(n[0])
n2 = int(n[1])
n3 = int(n[2]... | prasannagiri2072/python-practice | spreedsheet work1/task-12.py | task-12.py | py | 397 | python | en | code | 0 | github-code | 1 |
4597239667 | from __future__ import unicode_literals
from configyaml.config import DictNode
from configyaml.config import AbstractNode
class DummyFoo(AbstractNode):
def __init__(self, *args, **kwargs):
self._type = str
super(DummyFoo, self).__init__(*args, **kwargs)
class DummyConfig(DictNode):
def __in... | dropseed/configyaml | tests/test_dict.py | test_dict.py | py | 4,029 | python | en | code | 3 | github-code | 1 |
15760045645 | import tkinter as tk
import fxmeter as m
import random
from threading import Thread
import time
import random_logger as te
class Mainframe(tk.Frame):
def __init__(self,master,*args,**kwargs):
tk.Frame.__init__(self,master,*args,**kwargs)
print("initializing")
#gauge setup
self.tempframe1 = m.Me... | eerogue/Datalogger | gauges.py | gauges.py | py | 3,246 | python | en | code | 0 | github-code | 1 |
12863077047 | """
This code is same from https://github.com/siddk/npi
npi.py
Core model definition script for the Neural Programmer-Interpreter.
"""
import tensorflow as tf
import tflearn
class NPI():
def __init__(self, core, config, npi_core_dim=256, npi_core_layers=2, verbose=0):
"""
Instantiate a... | nsitaula/Neural-Program-Learning-Project | npi.py | npi.py | py | 6,530 | python | en | code | 2 | github-code | 1 |
5025490453 | # coding=utf-8
from pickle import FALSE
from sys import flags, version_info
from tkinter import filedialog
from STCore.Component import StarElement
from logging import root
from operator import contains
from os import scandir
from tkinter.constants import W
import matplotlib
from matplotlib import axes
imp... | JotaRata/StarTrak | STCore/ImageView.py | ImageView.py | py | 20,497 | python | en | code | 2 | github-code | 1 |
44425282922 | import configparser
import os
class ProjectConfig:
_cf = None
def __init__(self):
if ProjectConfig._cf is None:
try:
# 拼接获得config.ini路径
__CONFIG_FILE_PATH = os.path.dirname(os.path.abspath(__file__))
__CONFIG_FILE_NAME = 'config.ini'
... | cxb1004/emotion | config.py | config.py | py | 1,288 | python | en | code | 0 | github-code | 1 |
13786581127 | import cv2
img = cv2.imread('araba.png')
print(type(img))
# <class 'numpy.ndarray'>
print(img.shape)
cv2.imshow('orgin', img)
img_rotate_90_clockwise = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
cv2.imshow('cv_rotate_90_clockwise.jpg', img_rotate_90_clockwise)
# True
img_rotate_90_counterclockwise = cv2.... | MetehanYildiz25/ImageProcessing | Görüntü İşleme/aynalma_yöntem_2.py | aynalma_yöntem_2.py | py | 621 | python | en | code | 0 | github-code | 1 |
22462377193 | from sklearn.feature_extraction.text import TfidfVectorizer
from preprocess import *
from db_controller import *
from konlpy.tag import Okt, Kkma, Mecab
from numpy.linalg import norm
from numpy import dot
import numpy as np
import os
import sys
def text_slice(documents:list): # db에서 꺼낸 기사 데이터 정제 -> [' 기사본문 ', ' 기사본문 '... | Mayberry2021/tf_idf | DTM.py | DTM.py | py | 1,528 | python | en | code | 0 | github-code | 1 |
6311646706 | import os
from constants_private import *
TICKERS_LARGE = ["BA", "TSLA", "SCI", "WM", "ACB", "NVDA", "BABA","MSFT","ACN","AAL","T","BAC","HRL","HST","HWM","HPQ","HUM","HBAN","HII","IT","IEX","IDXX","INFO"]
TICKERS_SMALL = ["AFRM",]
TICKERS_BEST = ["AFRM", "UBER", "PLTR", "BA", "BABA", "TSLA", "WM", "ACB", "NVDA", "GME... | oostben/trading_bot | constants.py | constants.py | py | 540 | python | en | code | 0 | github-code | 1 |
70735106274 | import os
from Prop3D.parsers.psize import Psize
from Prop3D.parsers.container import Container
from Prop3D.parsers.pdb2pqr import Pdb2pqr
from Prop3D.util.pdb import get_first_chain, replace_chains
class APBS(Container):
IMAGE = 'docker://edraizen/apbs:latest'
LOCAL = ["apbs"]
PARAMETERS = [("in_file", "... | bouralab/Prop3D | Prop3D/parsers/apbs.py | apbs.py | py | 7,686 | python | en | code | 16 | github-code | 1 |
42043912000 |
#-*- utf-8 -*-
# age = 3
# if age >= 18:
# print('your age is', age)
# print('adult')
# else:
# print('your age is', age)
# print('teenager')
# s = input('birth: ')
# birth = int(s)
# if birth < 2000:
# print('00前')
# else:
# print('00后')
s1 = input('height: ')
s2 = input('weight: ')
height ... | zhcjie/python-learn | 条件判断.py | 条件判断.py | py | 510 | python | en | code | 0 | github-code | 1 |
33654275353 | from random import random
matrix = []
rows = int(input("Rows: "))
cols = int(input("Cols: "))
for i in range(rows):
matrix.append([int(random() * 100) for i in range(cols)])
print('\n'.join([''.join(['{:4}'.format(item) for item in row]) for row in matrix]))
print("=================")
summ = [sum(i) for i in matr... | mrTvixx/python_labs | lab18/index.py | index.py | py | 346 | python | en | code | 0 | github-code | 1 |
8785524037 | from __future__ import absolute_import, division, print_function
import tempfile
import pytest
import paayes
TEST_RESOURCE_ID = "file_123"
class TestFileUpload(object):
@pytest.fixture(scope="function")
def setup_upload_api_base(self):
paayes.upload_api_base = paayes.api_base
paayes.api_b... | paayes/paayes-python | tests/api_resources/test_file_upload.py | test_file_upload.py | py | 2,061 | python | en | code | 1 | github-code | 1 |
26070430980 | import pytest
from django.core.files.base import ContentFile
try:
from wagtail.core.models import Page
except ImportError:
from wagtail.wagtailcore.models import Page
from wagtail_svgmap.models import ImageMap
from wagtail_svgmap.tests.utils import EXAMPLE2_SVG_DATA, IDS_IN_EXAMPLE2_SVG, IDS_IN_EXAMPLE_SVG
... | City-of-Helsinki/wagtail-svgmap | wagtail_svgmap/tests/test_model.py | test_model.py | py | 2,694 | python | en | code | 13 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.