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
4127015597
def move_backward(backwardAmount: number): DFRobotMaqueenPlus.clear_distance(Motors.ALL) DFRobotMaqueenPlus.motot_run(Motors.M1, Dir.CCW, basespeed) DFRobotMaqueenPlus.motot_run(Motors.M2, Dir.CCW, basespeed) while abs(parse_float(DFRobotMaqueenPlus.reade_distance(Motors1.M2))) < moveAmount[backwardAmou...
RoboRuckus/micromayhem-maqueen-receiver
main.py
main.py
py
6,723
python
en
code
1
github-code
54
13126649946
""" A series of speed tests on pytorch LSTMs. - LSTM is fastest (no surprise) - When you have to go timestep-by-timestep, LSTMCell is faster than LSTM - Iterating using chunks is slightly faster than __iter__ or indexing depending on setup """ import argparse import os import sys import time import timeit import torc...
BenjaminWinter/MultiGpuTests
tests/lstmtest.py
lstmtest.py
py
6,637
python
en
code
3
github-code
54
34025337955
from poker.card import Card from poker.deck import Deck from poker.hand import Hand from poker.player import Player from poker.game_round import GameRound deck = Deck() cards = Card.create_standard_52_cards() deck.add_cards(cards) # from main import deck, cards, game_round, hand1, hand2, player1, player2 # python -m ...
sehrish30/Texas-Hold-em-Poker
main.py
main.py
py
1,171
python
en
code
0
github-code
54
10374150419
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( int_or_none, parse_duration, qualities, unified_strdate, ) class CCCIE(InfoExtractor): IE_NAME = 'media.ccc.de' _VALID_URL = r'https?://(?:www\.)?media\.ccc\.de/v/(?P<id>[^/?#&]+)' ...
AntidoteLabs/Antidote-DM
Antidotes DM/youtube_dl/extractor/ccc.py
ccc.py
py
4,566
python
en
code
3
github-code
54
13876140498
#! /usr/bin/env python # -*- coding: utf-8 -*- """ @version: 1.0 @author: li @file: code1.py @time: 2020/4/23 3:44 下午 """ import json from tqdm import tqdm import os, re import numpy as np import pandas as pd from keras_bert import load_trained_model_from_checkpoint, Tokenizer import codecs import gc from keras.layer...
STHSF/ccks_compete
ccks2020/test/code1.py
code1.py
py
14,390
python
en
code
0
github-code
54
73006282720
import torch from CCN_operator import MConv, DConv if __name__ == '__main__': data = torch.rand((2,2,32,32),dtype=torch.float32).to('cuda:0') mc = MConv(2,1,2,5).to('cuda:0') dc = DConv(2,1,2,5).to('cuda:0') mc.bias.data.fill_(0.1) y1 = mc(data) dc.weight = mc.weight dc.bias = mc.bias f...
limuhit/CCN
pytorch/CCN/test/test_conv_mask.py
test_conv_mask.py
py
407
python
en
code
14
github-code
54
18293542767
import os import csv partisanship = r"C:\Users\838sa\Downloads\phrase_partisanship" x = os.listdir(partisanship) y = [] for f in x: if 'partisan_phrases_' in f: y.append(f) phrases = [] for file in y: join = os.path.join(partisanship, file) with open(join, 'r') as datafile: next(datafile) ...
cubicmight/SplittingSets
read_data.py
read_data.py
py
604
python
en
code
0
github-code
54
70170929761
from dataclasses import dataclass import pytest from voir.argparse_ext import ExtendedArgumentParser @dataclass class Muffin: __help__ = "Lovely muffinness" class RedHerring: def hello(x): # wow! z = x * x return z moistness: int = 10 has_chocolate: bool...
breuleux/voir
tests/test_argparse_ext.py
test_argparse_ext.py
py
2,692
python
en
code
0
github-code
54
73893352161
import os import argparse import data_loader import localization def path_check(*path_list): ''' 检查目标路径是否存在,若不存在则自动创建 ''' for path in path_list: if not os.path.exists(path): os.makedirs(path) def save_file(path,data): f = open(path, 'w', encoding='utf-8') ...
Barreleyes/Excel-Tools
main.py
main.py
py
2,559
python
zh
code
4
github-code
54
9950666413
import logging import threading from pesos.vendor.mesos import mesos_pb2 from pesos.vendor.mesos.internal import messages_pb2 as internal from compactor.context import Context from compactor.process import ProtobufProcess logging.basicConfig(level=logging.DEBUG) class SimpleReceiver(ProtobufProcess): def __init_...
wickman/pesos
tests/test_protobuf_passing.py
test_protobuf_passing.py
py
1,299
python
en
code
47
github-code
54
20677743496
n = eval(input("Enter the limit for the fibonacci series to be printed: ")) first = 0 second = 1 print(first,second,end=" ") while n-2>0: temp = first+second print(temp, end = ' ') first = second second = temp n -= 1 #if not this print() line, a '%' will be printed at the end print()
gayathrichelluri/python
Fibonacci.py
Fibonacci.py
py
305
python
en
code
0
github-code
54
71586777441
from typing import Any, Optional, TypedDict from django.db.models import Prefetch from drf_spectacular.utils import extend_schema_field, extend_schema_serializer from rest_framework import serializers from rest_framework.exceptions import PermissionDenied, ValidationError import custom_view from acl.models import ACL...
dmm-com/airone
entry/api_v2/serializers.py
serializers.py
py
42,547
python
en
code
24
github-code
54
6138613609
hs = [5e-7, 1e-6, 1e-5, 1e-4, 1e-3] iters = [2000000, 1000000, 100000, 10000, 1000] methods = ["rk4", "rk8pd", "rkf", "evan-rk4", "evan-rk38", "evan-rkf"] for method in methods: for i in xrange(len(hs)): filename = 'inputs/pr2_input_{1:s}_{0:d}.ini'.format(i, method) f = open(filename, 'w') ...
eaott/CSE380
project/pr2_create_input.py
pr2_create_input.py
py
656
python
en
code
0
github-code
54
28794086883
def mergeSort(alist): if len(alist)>1: mid = len(alist)//2 lefthalf = alist[:mid] righthalf = alist[mid:] mergeSort(lefthalf) mergeSort(righthalf) i=0 j=0 k=0 while i < len(lefthalf) and j < len(righthalf): if lefthalf[i] < righth...
Diegod064/Fundamentos-de-Problemas-Computacionais-1
ordenacao-biblioteca.py
ordenacao-biblioteca.py
py
4,353
python
pt
code
0
github-code
54
2965618790
import json import logging from urllib.parse import urljoin from scrapy import Request, Spider from scrapy.http import Response from ...scrapy_utils.items import RecipeURLItem from ...utils.storage import Storage logger = logging.getLogger(__name__) ADVANCED_SEARCH_PAGE = 'https://foodnetwork.co.uk/recipe-search/' ...
john-hu/untitled
peeler/foodnetwork/spiders/recipe_list.py
recipe_list.py
py
2,712
python
en
code
0
github-code
54
25884410660
from fastapi import FastAPI from routers import pneumothorax_router app = FastAPI() app.include_router(pneumothorax_router.router, prefix='/pneumothorax') # noqa @app.get('/healthcheck', status_code=200) async def healthcheck(): return 'Good to go'
LifeLex/NIH_ChestXraysModels
app.py
app.py
py
256
python
en
code
0
github-code
54
73357339040
""" Version2: - simple bfs traversal implementation with queue - implementation with adjacency list Implementation steps: - Step1: initializing - add the source node to the 'next_to_process' queue. Also add source node to 'seen' list - Step2: pop a 'processing_node' from the 'next_to_process' queue. And add the 'pro...
fhrazib/coding-exercises
standard-ds-and-algorithm/graph/bfs-v2.py
bfs-v2.py
py
4,532
python
en
code
0
github-code
54
6788068385
import math import os import random import unittest from collections import deque from contextlib import contextmanager from random import randint from os import urandom import re import bitcoin from ethereum import abi, tester, utils from ethereum.config import default_config from ethereum.tester import TransactionFa...
paulperegud/swap_contract
tests/test_swap.py
test_swap.py
py
6,452
python
en
code
0
github-code
54
11436431551
import requests from bs4 import BeautifulSoup one_ses = requests.session() def phonetic(name_phonetic): url = "https://crptransfer.moe.gov.tw/index.jsp" params = { "SN":name_phonetic, "sound":"1" } chinese_list = [] # 根據長度取值 len_sn = len(params["SN"]) re = one_ses.get(ur...
stevenklc/phonetic
API_chinese_t.py
API_chinese_t.py
py
1,143
python
en
code
0
github-code
54
5715928656
# -*- coding: utf-8 -*- """ step06.word_count.py 뉴스 기사 -> word count -> 시각화 """ # 1. file load import pickle path = 'C:\\work\\Crystal\\DataAnalysis\\[ITWILL]BigDataAnalysis_ExpertTraining\\04. Python Basic\\workspace\\chap10_Crawling\\data' file=open(path+'/news_data.pkl',mode='rb') news_data_load=pickle.load(file)...
srabbit01/2022_ITWILL
04_Python_Basic/chap10_Crawling/step06_word_count.py
step06_word_count.py
py
2,288
python
ko
code
0
github-code
54
21483145645
def get_page(url): try: import urllib3 http = urllib3.PoolManager() r = http.request('GET', url) return r.data except: return "" def get_next_target(page): start_link = page.find('<a href=') if start_link == -1: return None, 0 start_quote = page.fin...
gerardo8a/python-crawler
search_engine.py
search_engine.py
py
3,733
python
en
code
1
github-code
54
10394427770
import numpy as np import cv2 from typing import Tuple fx = 520.9 #f/rho_w fy = 521.0 #f/rho_h cx = 325.1 #u0 cy = 249.7 #v0 def project_points(ids: np.ndarray, points: np.ndarray, depth_img: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """ Projects the 2D points to 3D using the depth image and the cam...
computer-vision-project-task-7/Visual-Odometry
pyVO-master/pointProjection.py
pointProjection.py
py
1,705
python
en
code
0
github-code
54
18471410884
import unittest from qddynamics.inference.model import Posterior from qddynamics.io import get_data_file_path, load_data import pandas as pd import numpy as np class TestPosterior_v2(unittest.TestCase): ''' Class for testing functionality of the likelihood function Loads the real data of x, y, sigma_y, a...
phys201/qd_laser_dynamics
qddynamics/tests/test_posterior_v2.py
test_posterior_v2.py
py
2,373
python
en
code
2
github-code
54
7937034630
import discord import sqlite3 import time import os import sys client = discord.Client() async def build_db_for_channel(list_of_channels): await client.wait_until_ready() start = time.time() print("connecting to db") con = sqlite3.connect('messages.db') cur = con.cursor() print("creating ta...
michaelmdresser/discord-markov
build_msg_db.py
build_msg_db.py
py
2,007
python
en
code
4
github-code
54
72312849120
import os from qisys import ui import qisys import qisys.parsers from qitoolchain.convert import convert_package def configure_parser(parser): """Configure parser for this action """ qisys.parsers.default_parser(parser) parser.add_argument("--name", required=True, help="The name of...
trb116/pythonanalyzer
data/input/aldebaran/qibuild/python/qitoolchain/actions/convert_package.py
convert_package.py
py
1,202
python
en
code
1
github-code
54
36710786407
#!/usr/bin/env 全部 # -*- coding: utf-8 -*- # @Time : 2021/9/13 5:49 下午 # @Author : linksdl # @ProjectName : futuretec-project-algorithm_leetcode # @File : 116-深度 or 深度优先搜索(填充每个节点的下一个右侧节点指针)middle.py ''' 116. 填充每个节点的下一个右侧节点指针 给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下: struct Node { int val; N...
linksdl/meta-project-learning_programming_algorithms
力扣-练习/全部/116-深度 or 广度优先搜索(填充每个节点的下一个右侧节点指针)middle.py
116-深度 or 广度优先搜索(填充每个节点的下一个右侧节点指针)middle.py
py
1,507
python
en
code
2
github-code
54
24254491372
""" #app/tests/test_questions Handles question-related tests """ import json from flask_testing import TestCase from api import create_app from api.questions.views import QUESTION_LIST from api.answers.views import ANSWER_LIST class Base(TestCase): """Base class to be inherited""" def create_app(self): ...
Tony-Ndichu/Heroku
tests/test_questions.py
test_questions.py
py
5,673
python
en
code
0
github-code
54
74348704481
import math def egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) i = 0 def modinv(a, m): # Нахождение инверсии по модулю g, x, y = egcd(a, m) if g != 1: raise Exception('modular inverse does not exist') else...
beksmaster/RSA
main.py
main.py
py
2,937
python
ru
code
0
github-code
54
28097815416
VERSION = 'v0.0.2' APPNAME = 'ZoomChatter' import re # Flask and Flask-RESTful from flask import Flask, request from flask_restful import reqparse, abort, Api, Resource # get_links() from urlextract import URLExtract app = Flask(__name__) api = Api(app) def get_participants(input): # doesn't work for chat form...
KeysAndValues/zoomchatter
api.py
api.py
py
1,334
python
en
code
0
github-code
54
16054602025
def marge(A:list, B:list): """ Слияние отсортированных массивов в один """ C = [0] * (len(A) + len(B)) # создание списка соответсвующей длины i = k = n = 0 # три индекса для A, B и С соответственно while i < len(A) and k < len(B): # пока один из массивов не закончится if A[i] <= B[k]: # ср...
nbox363/lections_mipt_khirianov
sorting/quicly sort/sort_merger.py
sort_merger.py
py
1,946
python
ru
code
0
github-code
54
30513881832
# Ejemplo 1 # Una sala de juegos cobra $5000 sie el cliente es menor de edad y # $10000 su supera los 18 años. # Además, si es un niño menor de 4 años, su entrada es gratis. # Elabore un programa que solicite la edad del cliente y arroje el # valor de su entrada. edad = float(input("\nDigite la edad del cliente: "))...
djotalorab/MisionTIC2022
MisionTIC_Ciclo1_python/Sesion7/7_1.py
7_1.py
py
563
python
es
code
1
github-code
54
5716294496
# -*- coding: utf-8 -*- """ step01_cosine_similarity.py 코사인 유사도 이용 -> 유사 문서 찾기 <작업절차> 1. 자연어 -> 문서단어행렬 변경 2. 코사인 유사도 적용 # Encoding: 단어 -> 숫자 """ # 희소행렬(sparse matrix) from sklearn.feature_extraction.text import TfidfVectorizer # 단어생성기 # 코사인 유사도 from sklearn.metrics.pairwise import cosine_similarity # ...
srabbit01/2022_ITWILL
05_Python_ML/workspace/chap10_Text_Mining/lecture04_Similarity/step01_cosine_similarity.py
step01_cosine_similarity.py
py
3,098
python
ko
code
0
github-code
54
39707212382
import pandas as pd import numpy as np import os from bs4 import BeautifulSoup from urllib.request import urlopen # 観測所名が半角の方がいいのでENGLISH版ページを採用 sonde_sites_url = 'https://www.jma.go.jp/jma/en/Activities/upper/upper.html' this_file_path = os.path.abspath(os.path.dirname(__file__)) sonde_sites_csv_path = os.path.join...
PLANET-Q/StatwindTool
tools/sonde_sites.py
sonde_sites.py
py
2,576
python
en
code
0
github-code
54
12259536575
import json from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.contrib.auth.decorators import login_required from django.http import HttpResponse, HttpResponseRedirect from django.http import JsonResponse from django.shortcuts import render from django.urls impo...
lukekasper/Personal-Projects
CS50/Project4/network/views.py
views.py
py
8,836
python
en
code
0
github-code
54
14992439386
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the ESE database resources.""" import unittest from esedbrc import resources from tests import test_lib class EseColumnDefinitionTest(test_lib.BaseTestCase): """Tests for the ESE database column definition.""" def testInitialize(self): """Tests th...
libyal/esedb-kb
tests/resources.py
resources.py
py
2,844
python
en
code
38
github-code
54
33622585713
""" FinDB task backend """ from json import dumps from twitter_utils import get_sentiment def lift_off(event: dict, _: dict) -> dict: """ Start processing """ try: try: symbol = str(event["queryStringParameters"]["symbol"]).upper().strip() if symbol not in [ ...
abhified/findb
main.py
main.py
py
1,645
python
en
code
0
github-code
54
72871247842
from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.db import models from django.utils.translation import gettext_lazy as _ from .managers import AccountManager # Create your models here. class Account(AbstractBaseUser, PermissionsMixin): ...
iyanuashiri/exchange-api
app/accounts/models.py
models.py
py
1,260
python
en
code
1
github-code
54
42525086972
from lxml import etree from parser.xml.position_helper import PositionHelper # purpose of this class is to identify separators (pictures, adds, horizontal # lines etc.) and rename blockTypes to "separator" ERROR = 3 gap = 5 class SeparatorId(object): # main method for identifing separators @classmethod ...
jhagara/TP-DeepSearch
parser/xml/discriminator/separatorsid.py
separatorsid.py
py
4,464
python
en
code
0
github-code
54
14768149748
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('topic', '0008_auto_20150627_2350'), ] operations = [ migrations.AddField( model_name='subtopicitem', ...
kylewu/todaqui
todaqui/topic/migrations/0009_auto_20150702_1952.py
0009_auto_20150702_1952.py
py
592
python
en
code
0
github-code
54
21563746236
from enum import Enum from loguru import logger from ..data.schema import Item class Priority(Enum): newest = "newest" local = "local" remote = "remote" error = "error" class DB: def __init__(self): self.nodes = dict() def add(self, node): id = node.id if id in sel...
memri/pymemri
pymemri/pod/db.py
db.py
py
3,492
python
en
code
3
github-code
54
25377211164
def solution(rows, columns, queries): answer = [] board = [[0 for _ in range(columns+1)] for _ in range(rows+1)] for n in range(1,rows+1): for m in range(1,columns+1): board[n][m] = (n-1) * columns + m # 당연히 rows가 아니고 (n-1) * columns 생각해보면 됨 for x1,y1,x2,y2 in queries: ...
noxknow/Python-Coding_test
(04) 2021 카카오 블라인드, 인턴쉽/2021 카카오 웹 백엔드 행렬 테두리 회전.py
2021 카카오 웹 백엔드 행렬 테두리 회전.py
py
1,647
python
ko
code
1
github-code
54
5100168705
""" Reads NFC tags from the Grove NFC module, connected to RPISER on a grove shield example usage: # wait for up to 5 seconds and display the ID of an NFC tag that is # put in front of the reader print grovenfcreader.waitForTag(5) """ import nfc import time import nfc.ndef import nfc.tag impo...
joemarshall/g54ubi-useful-code
grovepi-base/grovenfcreader.py
grovenfcreader.py
py
1,125
python
en
code
2
github-code
54
42479187442
from math import perm import pickle from re import A from tabnanny import check import os from ray.rllib.models import ModelCatalog from ray.rllib.agents.ppo.ppo import PPOTrainer from ray.rllib.agents.ppo.ppo import DEFAULT_CONFIG as ppo_config from ray.tune.registry import register_env from ray.rllib.env.wrappers.pet...
JoarVarpe/pet_for_sale
generate_winning_games_db.py
generate_winning_games_db.py
py
11,002
python
en
code
0
github-code
54
15852472609
import tensorflow as tf import numpy as np import cv2 import json from tflite_model import * def _get_triangle(self, kp0, kp2, dist=1): """get a triangle used to calculate Affine transformation matrix""" dir_v = kp2 - kp0 dir_v /= np.linalg.norm(dir_v) R90 = np.r_[[[0,1],[-1,0]]] dir_v_r = dir_v @...
gitjjh/mec-hand-tracking
tflite_hand_det.py
tflite_hand_det.py
py
5,240
python
en
code
0
github-code
54
23147141979
# -*- coding: utf-8 -*- """Agilent34970A communication. Created on 10/02/2015 @author: James Citadini """ import sys as _sys import time as _time import traceback as _traceback from . import utils as _utils class Agilent34970ACommands(): """Commands of Agilent 34970 Data Acquisition/Switch Unit.""" def __...
lnls-ima/ima-utils
imautils/devices/Agilent34970ALib.py
Agilent34970ALib.py
py
4,551
python
en
code
0
github-code
54
72511393440
import sys sys.path.insert(0, '../ghtesting') import pickle import os import re from collections import Counter from git import Repo from ghdatabase import GHDatabase from ghrepo import GHRepo from datetime import datetime with open('../data/final_reports.pickle', 'rb') as f: final_reports = pickle.load(f) servi...
brkhrdt/testing-on-github
notebooks/util.py
util.py
py
3,381
python
en
code
0
github-code
54
3572515070
import dash import dash_bootstrap_components as dbc from dash.dependencies import Input, Output, State import dash_core_components as dcc import dash_html_components as html # For encoding local images import base64 # declaring the layout and server etc from main import app, server # import all pages in the app from...
Duckchoy/alphadash
index.py
index.py
py
3,108
python
en
code
0
github-code
54
34836835635
import paddle from paddle.io import DataLoader, DistributedBatchSampler from ppad.datasets.registry import DATASETS, PIPELINES from ppad.utils.build_utils import build from ppad.datasets.pipelines.transforms import Compose def build_transform(cfg): """Build pipeline. Args: cfg (dict): root config dict...
paddle-lwfx/AnomalyDetection
ppad/datasets/builder.py
builder.py
py
1,626
python
en
code
1
github-code
54
3652082524
#!/usr/bin/python # -*- coding: utf-8 -*- import urllib.request import requests #import urllib from bs4 import BeautifulSoup import os if os.path.exists('image') == True: # 如果目录不存在则创建 print("image dir is exsit") else: os.mkdir('image') header = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) \ ...
hitlx/python-crawler-bing
Code/crawler_bing.py
crawler_bing.py
py
1,360
python
en
code
1
github-code
54
15562947970
''' PROBLEM STATEMENT: UPSIDE DOWN Given a binary tree where all the right nodes are leaf nodes, flip it upside down and turn it into a tree with left leaf nodes. Keep in mind: ALL RIGHT NODES IN ORIGINAL TREE ARE LEAF NODE. For example, turn these: 1 / \ 2 3 / \ 4 5 / \ 6 7 1 / \ 2 3 ...
chumkiroy/Problems
trees/upside_down.py
upside_down.py
py
2,064
python
en
code
0
github-code
54
1616739748
''' 205. 同构字符串 给定两个字符串 s 和 t,判断它们是否是同构的。 如果 s 中的字符可以被替换得到 t ,那么这两个字符串是同构的。 所有出现的字符都必须用另一个字符替换,同时保留字符的顺序。两个字符不能映射到同一个字符上,但字符可以映射自己本身。 示例 1: 输入: s = "egg", t = "add" 输出: true 示例 2: 输入: s = "foo", t = "bar" 输出: false 示例 3: 输入: s = "paper", t = "title" 输出: true 说明: 你可以假设 s 和 t 具有相同的长度。 ''' ## 使用两个映射表表示正反唯一的映射关系,同290...
WQAQs/study-notes
algorithm/leetcode/205_isIsomorphic.py
205_isIsomorphic.py
py
1,132
python
zh
code
1
github-code
54
43839905170
# You are going to write a program that tests the compatibility between two people. # # To work out the love score between two people: # # Take both people's names and check for the number of times the letters in the word TRUE occurs. # # Then check for the number of times the letters in the word LOVE occurs. # ...
niravcenation/Python_Tutorial
Day 3/Love_calculator(5).py
Love_calculator(5).py
py
1,519
python
en
code
1
github-code
54
18377998070
import tkinter as tk, os from PIL import Image, ImageTk def resize( w_box, h_box, pil_image): #参数是:要适应的窗口宽、高、Image.open后的图片 w, h = pil_image.size #获取图像的原始大小 f1 = 1.0*w_box/w f2 = 1.0*h_box/h factor = min([f1, f2]) width = int(w*factor) height = int(h*factor) return pil_image.resize((width, heig...
NewmanNya/nHentai
gui.py
gui.py
py
2,474
python
en
code
0
github-code
54
37166730654
from copy import deepcopy from typing import Dict, Any import numpy import pytest import yaml from tests.utility import get_data_directory from transformer_alignment.config import Config from transformer_alignment.dataset import create_and_split_dataset @pytest.fixture() def config_dict(): light_train_config_pa...
Hiroshiba/transformer-alignment
tests/test_dataset.py
test_dataset.py
py
3,207
python
en
code
0
github-code
54
70990208802
from django import forms from .models import Prestamo from applications.libro.models import Libro class PrestamoFormulario(forms.ModelForm): class Meta: # Conectamos el formulario con un modelo model = Prestamo # Especifica que campos se administraran desde el formulario fields = ...
gustavo9601/django_biblioteca
biblioteca/applications/lector/forms.py
forms.py
py
1,071
python
es
code
0
github-code
54
74229550240
# -*- coding: utf-8 -*- """ Script largely based on the boxofficemojo_parse.py script written and published by mrphilroth. The orginal script can be found at https://github.com/mrphilroth/website-movieratings """ import urllib2 from bs4 import BeautifulSoup import MySQLdb as mdb # set up the connection to the mysql ...
iacobus42/movies
collection/getMojoTitles.py
getMojoTitles.py
py
2,917
python
en
code
0
github-code
54
37670742568
import cv2 import mediapipe import handTracker as ht cap = cv2.VideoCapture(0) tracker = ht.handDetector() while True: ret, frame = cap.read() cv2.rectangle(frame, (10,10), (250,30), (255,255,255), cv2.FILLED) cv2.putText(frame, 'Project Hand Tracking', (15,25), cv2.FONT_HERSHEY_COMPLEX, 0.5, (255,0,0), 1...
Raihan-009/openCV_HandDetection
examples/handTrackingExample.py
handTrackingExample.py
py
532
python
en
code
0
github-code
54
40543662564
import argparse import os import shutil if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', required=True, help='input folder with images to process') args = parser.parse_args() input_folder = args.input if not os.path.isdir(input_folder): e...
przemo2174/CNNTools
CNNTools/clear_test_train_folders.py
clear_test_train_folders.py
py
552
python
en
code
0
github-code
54
35201855116
# -*- coding: utf-8 -*- """ Created on Tue Dec 26 23:59:46 2017 @author: wlunareve """ import tensorflow as tf import numpy as np ''' create data ''' x_data = np.random.rand(100).astype(np.float32) y_data = x_data*0.1+0.3 ''' create tensorflow structure #weights 相當於 x_data*0.1 中的0.1 1維 初始值 -1 ~ 1 #biases 相當於 x_da...
ToDSung/python_survey
tensorflow/tensorflow_example1.py
tensorflow_example1.py
py
956
python
en
code
0
github-code
54
71023977441
#!/usr/bin/env python # Example use # sudo python minesweeper.py -t http://www.mejortorrent.org/ -tm 15 import subprocess import signal import sys import threading import validators import os import time import json import datetime class Command(object): def __init__(self, cmd, url): self.cmd = cmd ...
apollolo/CryptoJacking
minesweeper/run.py
run.py
py
2,984
python
en
code
0
github-code
54
72376995042
from tkinter import * import tkinter.ttk as ttk import os import calendar import io import json import datetime # Employee at the top class Employee(ttk.LabelFrame): def __init__(self, parent, controller, *args, **kwargs): ttk.LabelFrame.__init__(self, parent, *args, **kwargs) # styles ...
ciszko/ECP
employee.py
employee.py
py
14,386
python
en
code
0
github-code
54
30011459772
from api.publications.models import Publication from api.ratings.models import Ratings from api.reports.models import Report, ReportReasons def create_rating_report(rating_id,data, user_id): if Report.objects.filter(rating_id=rating_id, user_id=user_id).exists(): raise Exception("You have already reported...
Green-Wheel/Backend
api/reports/services.py
services.py
py
2,173
python
en
code
2
github-code
54
72951628003
""" Helpers for interactive traversal/inspection of the pkgexploration graph """ import json import logging logger = logging.getLogger(__name__) def load_graph(path): with open(path) as f: return json.load(f) def find_node(g, path): parts = path.split('.') index = g['shards'][parts[0]] cur ...
kiteco/kiteco-public
kite-python/kite_pkgexploration/kite/pkgexploration/viewgraph.py
viewgraph.py
py
664
python
en
code
678
github-code
54
3558182692
from azure.identity import DefaultAzureCredential from azure.mgmt.hdinsightcontainers import HDInsightContainersMgmtClient """ # PREREQUISITES pip install azure-identity pip install azure-mgmt-hdinsightcontainers # USAGE python create_autoscale_cluster.py Before run the sample, please set the values o...
Azure/azure-sdk-for-python
sdk/hdinsight/azure-mgmt-hdinsightcontainers/generated_samples/create_autoscale_cluster.py
create_autoscale_cluster.py
py
3,932
python
en
code
3,916
github-code
54
11307230781
from math import sqrt from random import choice from pathlib import Path from shutil import rmtree import tqdm from beartype import beartype import nibabel as nib import torch from torch import nn from torch.utils.data import Dataset, DataLoader, random_split import torchvision.transforms as T from torchvision.dataset...
ibrahimethemhamamci/GenerateCT
transformer_maskgit/transformer_maskgit/ctvit_inference.py
ctvit_inference.py
py
9,884
python
en
code
43
github-code
54
41887869081
with open("input.txt", "r", encoding="utf-8") as f: commands = [line.strip().split() for line in f.readlines()] directions_map = { "U": [0, 1], "D": [0, -1], "L": [-1, 0], "R": [1, 0] } def calculate_move(head, tail): move = [0, 0] x_diff, y_diff = abs(head[0] - tail[0]), abs(head[1] - ta...
paciadawid/advent-of-code-2022
09/day_9.py
day_9.py
py
1,457
python
en
code
0
github-code
54
33043141008
from glob import glob import logging as log import os.path as osp from datumaro.components.extractor import Importer class YoloImporter(Importer): @classmethod def detect(cls, path): return len(cls.find_configs(path)) != 0 def __call__(self, path, **extra_params): from datumaro.componen...
TaSeeMba/cvat
datumaro/datumaro/plugins/yolo_format/importer.py
importer.py
py
1,268
python
en
code
7
github-code
54
31135449366
import pandas as pd import pulp as p def pre_process_data(filename="player_data_22-23.csv", opt_target="Total Points"): # Read the CSV file into a DataFrame player_attributes = pd.read_csv(filename) # Convert the position numbers to names player_attributes["Position"] = player_attributes["Positio...
JordanConnolly/Fantasy-Premier-League-optimisation
milp_initial_team_selection.py
milp_initial_team_selection.py
py
4,533
python
en
code
1
github-code
54
35346119882
''' Reads matrices in CSV format and applies transformation operations on them ''' import argparse import operator import sys import numpy as np import os.path parser = argparse.ArgumentParser(description='Converts an alignment matrix to Pharaoh format.') parser.add_argument('-r','--range', help='For using %d placehol...
fstahlberg/ucam-scripts
gnmt/csv2align.py
csv2align.py
py
1,213
python
en
code
1
github-code
54
31596531571
import pytest from upstash_redis import Redis @pytest.fixture(autouse=True) def flush_hash(redis: Redis): hash_name = "myhash" redis.delete(hash_name) yield redis.delete(hash_name) def test_hdel(redis: Redis): hash_name = "myhash" field1 = "field1" field2 = "field2" field3 = "field3...
upstash/redis-python
tests/commands/hash/test_hdel.py
test_hdel.py
py
1,133
python
en
code
11
github-code
54
71920545761
import configparser import numpy as np import pymysql import time import threading import os import logging # Facilitate implicit casting between numyp.float types and MySQL floats. pymysql.converters.encoders[np.float64] = pymysql.converters.escape_float pymysql.converters.conversions = pymysql.converters.encoders.co...
maestro73/bitmex-trading
MySqlDataStore.py
MySqlDataStore.py
py
3,259
python
en
code
0
github-code
54
28429255566
##Clip Raster Dataset by known extent - Left Bottom Right Top import arcpy import glob arcpy.env.workspace = r"Q:\france\sar_subset" fps = glob.glob(r'Q:\france\sar_project\*.tif') count=0 ls = [1,10,11,12,2,3,4,5,6,7,8,9] for fp in fps: print(fp) arcpy.Clip_management( fp,"399960 53...
sjliu68/ArcPy-Function
batch_clip.py
batch_clip.py
py
417
python
en
code
2
github-code
54
20927808586
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Create and pickle a topics_roles dict structure: {'topic ID' : {'SPEAKER ROLE' : [role-specific sentences in topic]}} Created on Sat Dec 16 16:16:22 2017 @author: hanamollerkalpak """ import cPickle as pickle from swda_time import *...
idiosynkratisch/CoSP2017Project
topics_roles_pickle.py
topics_roles_pickle.py
py
2,833
python
en
code
1
github-code
54
2355532175
# This Python 3 environment comes with many helpful analytics libraries installed ''' Airbnb compition for interview - I am able to discuss every line of code with good details Author 85% Ahmed Shehata 15% looking at some functionality to extract extra feature from ses ''' #Importing The Nescessary Libraries im...
sajedjalil/Data-Science-Pipeline-Detector
dataset/airbnb-recruiting-new-user-bookings/Ahmed Shehata/airbnb-new-user-booking-vodafone.py
airbnb-new-user-booking-vodafone.py
py
17,809
python
en
code
8
github-code
54
35541766340
""" Runtime: 3.4 seconds Starting with the naive brute force solution, calculating the chain for every number, it ran in 44 seconds. If my solution falls under the 1 min rule, I generally don't look up ways for a better solution. However in this case I had an idea right after finishing the first solution. After looki...
atheri/project-euler
014.py
014.py
py
1,747
python
en
code
0
github-code
54
3166957227
def find_two_sum(numbers, target_sum): """ :param numbers: (list of ints) The list of numbers. :param target_sum: (int) The required target sum. :returns: (a tuple of 2 ints) The indices of the two elements whose sum is equal to target_sum """ for i in range(len(numbers)): for j in range...
douglaszickuhr/python-code
find-two-sum.py
find-two-sum.py
py
476
python
en
code
0
github-code
54
74229883682
""" A simple cache for hit boxes calculated from texture. Hit box calculations are normally done at load time by inspecting the contents of a loaded image. Depending on the hit box algorithm a hit box is calculated: * None : Simply a box around the whole texture. No caching needed. * Simple : Scanning the corner...
pythonarcade/arcade
arcade/cache/hit_box.py
hit_box.py
py
4,731
python
en
code
1,537
github-code
54
8184431369
import torch.nn as nn import torch class Bluestack(nn.Module):#resblock_add, must in_ch = out_ch def __init__(self, in_ch, out_ch): super(Bluestack, self).__init__() self.conv = nn.Sequential( nn.Conv2d(in_ch, out_ch, 3, padding=1), nn.BatchNorm2d(out_ch), ...
ddyss/Res-Unet
my_code_for_PAT/resnet_fc.py
resnet_fc.py
py
3,439
python
en
code
1
github-code
54
16540467136
from wso import * from wsosamples import * o = win32com.client.Dispatch("Scripting.WindowSystemObject") f = o.CreateForm(0,0,650,400) f.CenterControl() def MouseMove(sender,x,y,flags): sender.Form.StatusBar[0].Text = str(x)+" x "+str(y) def MouseExit(sender): sender.Form.StatusBar[0].Text = "No Mouse In Control" ...
VeretennikovAlexander/WindowSystemObject
Demo/Python/test.py
test.py
py
2,897
python
en
code
7
github-code
54
63950826
import numpy as np with open('d21.txt', 'rt') as f: input = f.read().strip() inp = """ ../.# => ##./#../... .#./..#/### => #..#/..../..../#..# """.strip() initial = """ .#. ..# ### """.strip() def parse(input): lines = input.split('\n') rules = {} for line in lines: pat, out = line.split(' ...
bj0/aoc
aoc/2017/d21.py
d21.py
py
2,761
python
en
code
0
github-code
54
4660916040
from pyspark import SparkContext, SparkConf from datetime import datetime from pyspark.mllib.stat import Statistics from pyspark.mllib.linalg import Vectors conf = SparkConf().setAppName("Chicago Crime Data Analysis") sc = SparkContext(conf=conf) sc.setLogLevel("ERROR") # Load the data from HDFS crimeData = sc.textF...
samswain2/MSiA-SQ
MSiA 431/03_hw/02_question/swain_02_p2_script.py
swain_02_p2_script.py
py
2,855
python
en
code
0
github-code
54
34374930286
WIN = 'WIN' LOSE = 'LOSE' COL = 15 ROW = 8 GOLD_QUANTITY = 8 SWORDS_QUANTITY = 10 WUMPUS_QUANTITY = 8 HOLES_QUANTITY = 8 GOLD = "G" WUMPUS = "W" HOLES = "O" PLAYER = "J" SIGNAL_WUMPUS = "+" SIGNAL_HOLE = "~" PLAYER = "J" ALL_ELEMENTS = "GWOJ+~J" ITEMS_DICTIONARY = {"O": "~", "W": "+"} SCORE_GAME = {"move": -10, "gold...
evbeda/games
wumpus/constants.py
constants.py
py
825
python
en
code
1
github-code
54
2315464692
class Solution(object): def restoreString(self, s, indices): """ :type s: str :type indices: List[int] :rtype: str """ arr = ["" for i in range(len(s))] for i,x in enumerate(s): arr[indices[i]] = x return "".join(arr)
iamabhishek98/leetcode_solutions
shuffle-string/shuffle-string.py
shuffle-string.py
py
297
python
en
code
0
github-code
54
2756328727
import random def my_message(): return "HELLO" # only if this script is executed from teh command-line if __name__ == "__main__": print("Rock, Paper, Scissors, Shoot!") # CAPTURE INPUTS # 1. Create variables # 2. Make it user friendly by repeating the choice. user_choice = input("Plea...
amoy007/rps-exercise-inclass
game.py
game.py
py
3,124
python
en
code
0
github-code
54
15866046478
import numpy as np def slice_sample(logp, x0, width=1.0, positive=False, eps=1e-10): ''' Slice sampler for 1-dimensional densities Parameters ---------- logp : Log density function x0 : Initial point width: slice width positive: True if the density has positive support eps: Left en...
cmcrae/MTH3000
SliceSample/slice_sample.py
slice_sample.py
py
1,229
python
en
code
0
github-code
54
12920668635
from django.http import HttpResponse, HttpResponseNotFound, Http404 from django.shortcuts import render, redirect from myapp.models import * menu = ["О сайте", "Добавить статью", "Обратная связь", "Войти"] menu = { 'about': "О сайте", 'addpage': "Добавить статью", 'feedback': "Обратная связь", 'login'...
romver0/DjangoTutorial
backend/myapp/views.py
views.py
py
3,558
python
ru
code
0
github-code
54
30514973972
from WConio2 import textcolor, clrscr, getch, setcursortype import ctypes ctypes.windll.kernel32.SetConsoleTitleW("n Numbers HCF") def hcf(n): a, b, r = n[0], n[1], 0 for x in range(0, len(n) - 1): while a != 0: r = b % a b = a a = r a = b if x + 2 ...
shubhattin/mama_purAnyAni
Python/n Numbers HCf Project/hcf.py
hcf.py
py
1,215
python
en
code
1
github-code
54
74146280160
from packgen.models import draft_picks, draft_record, all_cards, KTK_Reg_Coef from django.db.models import Sum import math ###### define functions #take prev_picks and current_pack as a queryset of draft_picks. This contains all cards previously drafted as well as cards in the pack #return list of tuples of multivers...
errorbean/magicdraftai
draft_algos.py
draft_algos.py
py
7,105
python
en
code
0
github-code
54
69911968801
from flask import Response, abort, jsonify, request import flask from flask_restful_swagger_3 import Resource, swagger, Schema from flask_restful import reqparse from app_models.order_model import OrderModel, OrderPaginated from app_models.user_model import UserModel from app_models.tea_model import TeaModel from app_m...
blazej700/ibd
teashop_server/app_resources/photo_res.py
photo_res.py
py
2,881
python
en
code
0
github-code
54
23053505833
import json import socket import sys import threading import queue import time import requests from Cryptodome.Cipher import PKCS1_OAEP from Cryptodome.PublicKey import RSA HOST = "127.0.0.1" PORT = 9876 def generate_keys(): key_pair = RSA.generate(3072) public_key = key_pair.public_key() ...
GostaCarlstrand/chat_server_group_2
socket_server.py
socket_server.py
py
4,357
python
en
code
0
github-code
54
2596432435
import json from sklearn import svm from sklearn.svm import SVC def main(train): #open training set with open(train) as data_file: data = json.load(data_file) #initialize list for ingredients cmposing of all ingredients ingrList = [] for i in range(len(data)): ingredients = data[i]['ingredients...
sajedjalil/Data-Science-Pipeline-Detector
dataset/whats-cooking/jass/jjhjh-jh.py
jjhjh-jh.py
py
1,858
python
en
code
8
github-code
54
42331237
class Solution: def fourSum(self, nums: list[int], target: int) -> list[list[int]]: nums.sort() result = [] n = len(nums) for i in range(n-3) : for j in range(i + 1, n - 2): left ,right = j+1 ,n -1 while left<right: ...
GGCPP89S51/leetcode
leetcode_array/leetcode_array_4Sum.py
leetcode_array_4Sum.py
py
908
python
en
code
0
github-code
54
7994651744
""" Random number generation using linear congruent method Lev Kaplan 2019 """ # rand1.py: experimenting with random numbers from pylab import * def drand48(): global rnd rnd = (0o273673163155 * rnd + 11) % 2**48 # 0o means octal notation return rnd/2**48 # return number between 0 and ...
zpopovych/CompPhys
04/04_02.py
04_02.py
py
804
python
en
code
0
github-code
54
72160001123
from yambopy import * from netCDF4 import Dataset from yambopy.lattice import rec_lat, car_red class YamboStaticScreeningDB(object): """ Class to handle static screening databases from Yambo This reads the databases ``ndb.em1s*`` There :math:`√v(q,g1) \chi_{g1,g2} (q,\omega=0) √v(q,g2)` is stored....
alexmoratalla/yambopy
yambopy/dbs/em1sdb.py
em1sdb.py
py
8,014
python
en
code
1
github-code
54
37385040419
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jan 30 08:26:41 2022 @author: tanvimohan """ import threading import time def NumGen(): for a in range(30): if event.is_set(): break else: print(a) time.sleep(1) event = threading.Event() thr...
risrivas/python_for_finance
interactive_brokers/events.py
events.py
py
518
python
en
code
0
github-code
54
27638188505
import sys import setup def read_file(name): file = open(name) setup.MEM = file.read().split("\n") setup.maximum = len(setup.MEM) def get_next_instruction(setup): # print("*******",setup.registers[15]//4) to_return = setup.MEM[setup.registers[15]//4] setup.registers[15] += 4 return to_r...
trinity97/ARMSimulator
ARMSimulator/src/python/helper.py
helper.py
py
3,297
python
en
code
0
github-code
54
17347488590
# pitch # roll # yaw # pivot from PyQt5.QtWidgets import ( QWidget, QGridLayout, QVBoxLayout, QHBoxLayout, QPushButton, QGroupBox, QLabel, QFormLayout, QFrame, QScrollArea, QSizePolicy ) from vedo import Line, Point from PyQt5.QtCore import Qt, QSize from constant.enums im...
s-triar/tooth-aligner
view/toolbar_right/panel_korkhaus.py
panel_korkhaus.py
py
3,528
python
en
code
0
github-code
54
10820948725
# node and its network + weight Network = [] # store new value to node success_dic = {} # all node Node = [] # weight list_of_weight = [] # receive node Receive_node = 5 # # For part D, have the user input each pipe's flow data. # receive = "" def add_edge(node1, node2): global receive if node1 == 0: ...
kosalvireak/Network_model
Apsara_Oil_Khoeun_Kosalvireak.py
Apsara_Oil_Khoeun_Kosalvireak.py
py
4,380
python
en
code
0
github-code
54
16391311888
"""empty message Revision ID: 33193052f21 Revises: 423081911c8e Create Date: 2016-03-08 23:07:20.193665 """ # revision identifiers, used by Alembic. revision = '33193052f21' down_revision = '423081911c8e' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - pl...
tsnaomi/finnsyll-dev
migrations/versions/33193052f21_.py
33193052f21_.py
py
722
python
en
code
3
github-code
54
21910925643
from unittest import mock from unittest.mock import MagicMock import pytest from molgenis.bbmri_eric.errors import EricError from molgenis.bbmri_eric.pid_service import ( DummyPidService, NoOpPidService, PidService, Status, ) @pytest.fixture def handle_client() -> MagicMock: return MagicMock() ...
molgenis/molgenis-py-bbmri-eric
tests/test_pid_service.py
test_pid_service.py
py
2,902
python
en
code
0
github-code
54