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
20611100192
# coding: utf-8 import asyncio import requests from retrying_async import retry def request_api_sync(): print('正在获取') response = requests.get(url="https://www.google.com") print(response.status_code, response.content) raise Exception("异常") @retry(attempts=3, delay=3) async def request_api_async()...
Quarticai/retrying-async
test_retring_async.py
test_retring_async.py
py
614
python
en
code
null
github-code
1
1538782476
import logging import time as tm import numpy as np __author__ = 'frank.ma' logger = logging.getLogger(__name__) class Maze(object): def print_maze(self): logger.info('size: [%i, %i]' % self.size) logger.info('start: [%i, %i]' % self.start) logger.info('end: [%i, %i]' % self.end) ...
frankma/Finance
src/MiniProjects/Maze/maze.py
maze.py
py
993
python
en
code
0
github-code
1
72696729313
# Competative Programming Question 169 = A. Div. 7 (From CodeForces) """ A. Div. 7 | Get the Problem Statement on CodeForces : https://codeforces.com/problemset/problem/1633/A And get the solution here, solved in python by me :} """ # Author = Abhinav # Date = 7 February 2022 # Pourpose = Just for practise and imp...
Brodevil/Competative-Programming
Python/Solved Questions/practise_set_169.py
practise_set_169.py
py
714
python
en
code
3
github-code
1
36564736991
import os #import cv2 import math import time import csv import random import numpy as np import scipy.io as scio import PIL.Image as Image #from sklearn.metrics import confusion_matrix, roc_curve, average_precision_score, auc, f1_score import argparse parse = argparse.ArgumentParser('Train_Unimodal') parse.add_argum...
qiulu-sjtu/MultimodalFusion
Train_Unimodal_Coatt.py
Train_Unimodal_Coatt.py
py
15,323
python
en
code
0
github-code
1
6028045464
import numpy as np import math from nn import NeuralNet from typing import List, Dict, Tuple class AimAssistant: """ Wrapper around the neural net for data preprocessing / postprocessing """ sides_crop = 0.3 top_crop = 0.35 def __init__(self, crop: bool = False): self.to_crop = crop ...
EvgeniiTitov/aim_assistance_v2
aim_assistant.py
aim_assistant.py
py
6,437
python
en
code
0
github-code
1
24850037333
from typing import Dict from rlcard3.games.mocsar.action import Action from rlcard3.model_agents.agent import Agent from rlcard3.games.mocsar.utils import get_action_ids, action_to_ret, decode_obs import numpy as np class MocsarRandomAgent(Agent): """ Mocsar Rule agent version 1, take a random action """ ...
cogitoergoread/rlcard3
rlcard3/model_agents/mocsar_random_agent.py
mocsar_random_agent.py
py
2,236
python
en
code
1
github-code
1
17959440858
# 약어 생성(create abbreviation) # 사람 이름이 영어로 나열되면서 콤마(,)로 구분되어 있을 때, 약어를 자동으로 # 생성하는 프로그램을 만드시오. 사람 이름의 첫글자는 반드시 대문자로 입력. # 예를 들어, Changwon,Science,High,School 이 입력되면 CSHS 를 출력한다. # 입력은 한 줄로 이루어져 있고, 최대 100글자의 영어 알파벳 대문자, 소문자, # 그리고 콤마(,)로만 이루어져 있다. 첫 글자는 반드시 대문자이고, 콤마 뒤에도 # 반드시 대문자이다. 그 외의 모든 문자는 소문자이다. 입력에 공백은 존재하지 # 않는...
junes7/python_algorithm
CodeUp/deep_problem/2762.py
2762.py
py
836
python
ko
code
1
github-code
1
4711295669
import numpy as np import pandas as pd # Get top GDX component stock based on greatest market value but excluding exclude_stock def get_top_gdx(gdx_components, quote_manager, exclude_stock=None, count=10): # Grab date from exclude_stock for checking quote data exists date = exclude_stock.name # Remove ...
jner14/gold_backtester
gbutils.py
gbutils.py
py
3,704
python
en
code
0
github-code
1
22671610775
# http://codeforces.com/group/P8UZg7UOT5/contest/225111/problem/E def AmrAndMusic(): n, k = map(int, input().strip().split()) learned = [] inst = [ *map(int, input().strip().split()) ] if min(inst) > k: return 0 else: inst = [ (...
ece-mohammad/CodeForces
AmrAndMusic.py
AmrAndMusic.py
py
544
python
en
code
0
github-code
1
38975891687
from django.urls import path from . import views urlpatterns = [ path("", views.dashboard, name='dashboard'), path("cotacao/", views.cotacao, name='cotacao'), path("entregas/", views.lista_entregas, name='entregas' ), path("formulario/", views.formulario, name='formulario') # Outras URLs relaciona...
Brunobh51/sistema
app_CotacaoEntregas/urls.py
urls.py
py
378
python
pt
code
0
github-code
1
27508252115
# Once contacts are imported, we will create relationships # Since Meetings are hierarchical along with Wagtail Pages, # we need to move the existing pages to the correct parent. # https://stackoverflow.com/a/57057466/1191545 import re from django.core.exceptions import ObjectDoesNotExist from contact.models import Me...
WesternFriend/WF-website
content_migration/management/import_civicrm_clerk_relationships_handler.py
import_civicrm_clerk_relationships_handler.py
py
3,571
python
en
code
46
github-code
1
31034374235
nums = [10, 15, 3, 7, 9, 16] def nums_that_equal(num, k): if [True for i in num for j in num if i + j == k]: return True else: return False test_k = [5, 8, 9, 12, 50, 20, 25] for test_num in test_k: value = nums_that_equal(nums, test_num) print(f"k = {test_num} and test is {value}")...
hackwithcameron/daily-problems
Problem-1/problem-1.py
problem-1.py
py
321
python
en
code
0
github-code
1
1490343469
out_base_folder = "/home/dany/Dropbox/Projects/deskydoo/desky/deskydoo/fe/articles"; # Languages for text, must be set up in format ("ISO2CODE", "FULL") LAN_LIST = [ # ('it','italian'), ('en','english'), ('es','spanish'), ] # ************************* # TEXT GENERATION -- Chose between: (as 202310, the 3.5 works...
danruggi/icontent_ai
settings.py
settings.py
py
930
python
en
code
0
github-code
1
37574210596
import requests from flask import render_template, Flask, request, url_for from flask_bootstrap import Bootstrap from flask_wtf import FlaskForm from werkzeug.utils import redirect from wtforms import StringField, SelectField, SubmitField from wtforms.validators import DataRequired, URL from cafeApiManager import Api...
yassineberradi/cafe_wifi
main.py
main.py
py
5,389
python
en
code
1
github-code
1
23949433233
import requests from utility.conversions import number_to_ranks class LobbySetup: ''' Retrieve lobby details. Must be in game. ''' def __init__(self, headers): self.headers = headers def get_latest_season_id(self, region): try: response = requests.get( ...
seanfinnessy/Val_UI
server/setup/LobbySetup.py
LobbySetup.py
py
5,451
python
en
code
0
github-code
1
38311900062
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Apr 10 17:43:35 2019 @author: stef This script is to analyse and produce some summary statistics for (a subset of) all the NOS dictionaries extracted using the function scrape_nos.py. Which dictionaries to analyse can be set using the ``which_files'' l...
nestauk/openjobs-SDS-NOS-2019
check_extracted_NOS.py
check_extracted_NOS.py
py
8,663
python
en
code
2
github-code
1
44429839864
from src.simulator import Simulator from sys import argv def main(): woman = 500 man = 500 years = 20 if len(argv) == 4: woman = int(argv[1]) man = int(argv[2]) years = int(argv[3]) s = Simulator() s.build(woman, man, 12*years) collector = s.sim() if argv.count('graph'): from app import app app.dat...
sandorml/populated_evol
main.py
main.py
py
423
python
en
code
1
github-code
1
74541723232
from setuptools import find_packages, setup with open("README.md", encoding="utf8") as f: readme = f.read() setup( name="jupyterhub-tmpauthenticator", version="1.0.0", description="JupyterHub authenticator that hands out temporary accounts for everyone", url="https://github.com/jupyterhub/tmpauthe...
jupyterhub/tmpauthenticator
setup.py
setup.py
py
1,285
python
en
code
20
github-code
1
2673784857
import unittest import training from convertToYOLOcsv import convertToYOLO import torch import utils from metrics import PredictionStats, AveragePrecision, TRUE_POSITIVE, FALSE_POSITIVE class TestMethods(unittest.TestCase): def test_loss(self): outputs = torch.rand((64, 7*7*(5+4))) truth = torch....
edinitu/ObjectDetection
tests.py
tests.py
py
4,764
python
en
code
0
github-code
1
34275611553
import requests import os url = 'http://ubmcmm.baidustatic.com/media/v1/0f000ZjaV0Hbb1uWirPKsf.jpg' root = 'D://pics//' path = root + url.split('/')[-1]#保留原来文件名 try: if not os.path.exists(root): os.mkdir(root) if not os.path.exists(path): r = requests.get(url) with open(path,'wb') as f:...
wxzoro1/MyPractise
python/spidercode/beatifulsoup/网络图片的爬取.py
网络图片的爬取.py
py
465
python
en
code
0
github-code
1
70343107554
from canvasapi import Canvas def get_assignments(course_id): ''' Return a list of all the assignments in a Canvas course, with an id equals to the id specified as parameter. ''' url = 'https://canvas.instructure.com/' key = 'vQF6J15Kuh3Y6ut1Vh247dlVEIpTEbMnWq7lRKjDBaWuWll3VHtEHosToRrelBpMBf5Di...
s2e-lab/SecurityEval
Testcases_Insecure_Code/CWE-321/author_1.py
author_1.py
py
593
python
en
code
31
github-code
1
29293537961
"""Tutor shared region nav bar.""" import re from time import sleep from pypom import Region from selenium.common.exceptions import WebDriverException from selenium.webdriver.common.by import By from utils.tutor import TutorException from utils.utilities import Utility, go_to_, go_to_external_ class Menu(Region): ...
openstax/os-automation
regions/tutor/nav.py
nav.py
py
16,999
python
en
code
2
github-code
1
7593388743
import unittest from xml.etree import ElementTree as ET from xmlcomparer import transformer import logging #logging.basicConfig(level=logging.DEBUG) class TestTransformer(unittest.TestCase): def test_can_ignore_order(self): xml_incorrect_order = ET.parse("../../demo/sort_only2.xml") t = transform...
withrocks/xmlcomparer
test/integration/test_transformer.py
test_transformer.py
py
851
python
en
code
0
github-code
1
37743374034
# snail coordinate function def snail_coordinate(num): # required numbers up to x and y req_num_up_x = num // 2 req_num_up_y = (num-1) // 2 # coordinate function def coord(n): # output coord = (((2*n)+1) * ((n%2)-((n-1)%2)) + 1) // 4 # return return coord # output...
AmirhossienDH124/SnailCoordinate
coordinate_snail.py
coordinate_snail.py
py
564
python
en
code
0
github-code
1
26461253101
import pandas as pd import json import time import os import re import random import requests from urllib import parse class DuckSearch: def __init__(self, settings): self.domain = 'https://duckduckgo.com' self.language = settings.get('DDGlanguage', 'en-us') self.headers = { 'U...
SNStatComp/urlfinding
urlfinding/duckduckgo.py
duckduckgo.py
py
2,911
python
en
code
3
github-code
1
7108370811
#!/usr/bin/python3 """ Module gérant l'interface graphique des fenêtres liées à la gestion des devoirs. """ ## imports import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk from autocompletion import * from traitements.traitements import * from dbManagement.dbManagement import BaseDeDonnées ## Cla...
AdrienLicari/competences
fenetresDevoir.py
fenetresDevoir.py
py
19,696
python
fr
code
0
github-code
1
28107460378
import random for i in range(3): print(random.random()) for i in range(3): print(random.randint(10,20)) members = ['John','Mary','Bob','Josh'] leader = random.choice(members) print(leader) class Dice: def roll(self): tupl = [] first = random.randint(1,6) second = random.randint...
surajchoubey/Python3Noobies
randomJ.py
randomJ.py
py
399
python
en
code
0
github-code
1
71830237474
""" Defines the robot class and some actions the robot can perform and the main real-time control loop. """ import time import threading import logging import math import numpy as np import sm_kinematics log = logging.getLogger(__name__) from enum import Enum import config # import joints import pca9685_psd import ...
chrisalbertson/Spek1
Software/quad_controller/robot.py
robot.py
py
21,773
python
en
code
3
github-code
1
70662817315
from material import Material import numpy as np from texture import Texture class Mesh: """ Simple class to hold a mesh data. Focuses on vertices, faces (indices of vertices for each face) and normals. """ def __init__(self, vertices=None, faces=None, normals=None, textureCoords=None, material=...
ashrichter/3dstreetscene
mesh.py
mesh.py
py
4,855
python
en
code
1
github-code
1
21990160974
#https://www.baeldung.com/java-least-common-multiple#:~:text=Using%20the%20Euclidean%20Algorithm,-There's%20an%20interesting&text=As%20stated%2C%20gcd(a%2C,gcd(a%2Cb). #https://site.ada.edu.az/~medv/acm/Docs%20e-olimp/Volume%2012/1155_English.htm import math def gcde(a, b, d, x, y): if (b == 0): d = a ...
gadnlino/tep20231
src/aula6/euclid_problem/main.py
main.py
py
733
python
en
code
0
github-code
1
28911552493
#UTAT - Orbital Subsystem #Jai Willems, 1006342165 #University of Toronto Faculty of Applied Science and Engineering #Division of Engineeing Science #Completed 18-08-2020 #The purpose of this script is to create a orbital simulation program. #--------------------------------------------------------------------------...
utat-ss/FINCH-Orbit
Jai_Code/Orbit Determination.py
Orbit Determination.py
py
2,086
python
en
code
0
github-code
1
15279130231
# Binary Search from collections import List class Solution: def maxLength(self, ribbons: List[int], k: int) -> int: low, high = 1, max(ribbons) while low <= high: mid = low + (high - low) // 2 # add number of ribons that can be ...
onyxolu/DSA
Facebook/Top 100/CuttingRibbons.py
CuttingRibbons.py
py
716
python
en
code
0
github-code
1
25727907989
import operator from typing import Union, Tuple, Callable, TypeVar from numbers import Number from decimal import Decimal, ROUND_DOWN from functools import total_ordering from tensortrade.core.exceptions import ( InvalidNegativeQuantity, IncompatibleInstrumentOperation, InvalidNonNumericQuantity, Quan...
tensortrade-org/tensortrade
tensortrade/oms/instruments/quantity.py
quantity.py
py
10,188
python
en
code
4,270
github-code
1
18960408588
import cv2 import numpy as np import rect image = cv2.imread('test-images/page.jpg') # Resizing will make results better. Why????? image = cv2.resize(image, (1500, 880)) orig = image.copy() gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray, (5, 5), 0) kernel = np.ones((3, 3), np.uint8) ...
billstark/receipt-scanner
ReceiptGenerator/archive/scanner_archived.py
scanner_archived.py
py
2,794
python
en
code
86
github-code
1
5328726166
# ****************************************************************************** ## GLOBIO - https://www.globio.info ## PBL Netherlands Environmental Assessment Agency - https://www.pbl.nl. ## Reuse permitted under Gnu Public License, GPL v3. # ***************************************************************************...
GLOBIO4/GlobioModelPublic
Calculations/GLOBIO_CalcAquaticWetlandFloodplainFRHLUMSA.py
GLOBIO_CalcAquaticWetlandFloodplainFRHLUMSA.py
py
6,777
python
en
code
17
github-code
1
19116388243
# -*- mode: python -*- # vi: set ft=python : """ Downloads a precompiled version of buildifier and makes it available to the WORKSPACE. Example: WORKSPACE: load("@drake//tools/workspace:mirrors.bzl", "DEFAULT_MIRRORS") load("@drake//tools/workspace/buildifier:repository.bzl", "buildifier_repositor...
GTLIDAR/safe-nav-locomotion
motion_planner/drake/tools/workspace/buildifier/repository.bzl
repository.bzl
bzl
1,780
python
en
code
21
github-code
1
41054820426
import time import pytest from botocore.exceptions import ClientError from botocore.stub import ANY import service_linked_roles @pytest.mark.parametrize( "error_code, stop_on_method", [ (None, None), ("TestException", "stub_create_service_linked_role"), ("TestException", "stub_list_a...
awsdocs/aws-doc-sdk-examples
python/example_code/iam/test/test_service_linked_roles.py
test_service_linked_roles.py
py
2,202
python
en
code
8,378
github-code
1
41581380035
import pygame,sys from esTxt import textt def options(): altura = 600 largura = 1230 mainClock = pygame.time.Clock() screen = pygame.display.set_mode((largura,altura), 0, 32) es=textt("opt",(225,225,225),screen,40,400) running = True while running: screen.fill((0,0,0)) ...
EmanuelUrbano/oJogo02
opt.py
opt.py
py
679
python
en
code
0
github-code
1
70611386915
import urllib.request import shutil import requests import xlsxwriter import random import re from pymongo import MongoClient client = MongoClient() db = client.chrome collect = db.polyA mcursor = collect.find({'organism':'Homo sapiens'}) TotalConsmRNA = {} RegionConsmRNA = {} ConsGene = {} RegionConsGene = {} T...
freezer333/biotools
analysis/URichMRNADist.py
URichMRNADist.py
py
1,901
python
en
code
2
github-code
1
2582002054
# Your code goes here # Tracy Cook; Assignment 1; March 5, 2016 import csv # Open our input and output files csvfile = open('cleanme.csv', 'r') outfile = open('cleanme-clean.csv', 'w') # Now a DictReader and DictWriter # DictReader and DictWriter are imported libraries reader = csv.DictReader(csvfile) writer = csv.D...
tmcook23/adj-assignments
cleaner1.py
cleaner1.py
py
853
python
en
code
0
github-code
1
23007355058
""" A module for calculating pharmacies' current respond time. """ import datetime import numpy as np import pandas as pd from scipy.interpolate import interp1d from scipy.signal import medfilt from scipy.signal import savgol_filter import ext_connections as ext_con import requests import os import json class Respon...
john-djorason/respond_time
respond_time/respond_time.py
respond_time.py
py
19,620
python
en
code
0
github-code
1
11457307264
from fastapi import APIRouter, HTTPException from models.post import Post from services.post_service import * posts = APIRouter() @posts.get("/posts/") def get_all_post(): try: return get_all() except Exception as e: return HTTPException(status_code= 400, detail= str(e)) @posts.get("/posts/{...
ilyas-macit/PostApi
routers/post_router.py
post_router.py
py
1,041
python
en
code
0
github-code
1
25221058278
#!/usr/bin/env python3 import os import json import backoff import requests import pandas as pd from io import StringIO from datetime import datetime, timedelta import singer from singer import utils, metadata from singer.catalog import Catalog, CatalogEntry from singer.schema import Schema from singer.transform impo...
SageData-OOD/tap-indeed
tap_indeed/__init__.py
__init__.py
py
14,550
python
en
code
0
github-code
1
3540734192
"""============================================================================ Ex2: PCA - sklearn --> mở rộng thêm phân tích phương sai để xác định k a) Đọc tập tin dữ liệu Student_12f.xls vào dataframe. b) Áp dụng phương pháp PCA để giảm xuống k chiều (2 < k < 12). Giải thích nguyên nhân hay c...
lualua0909/Math-4-ML-lds3
B3. PCA/Ex2 - PCA voi sklearn (Phan tich phuong sai).py
Ex2 - PCA voi sklearn (Phan tich phuong sai).py
py
5,375
python
vi
code
10
github-code
1
70507014433
#!/usr/bin/env python3 import os, signal, subprocess import psutil class ProcessT: def __init__(self, proc_arg): print(proc_arg) self._process = subprocess.Popen(proc_arg['cmd'], shell=True) self._name = proc_arg['name'] def kill(self): self._process.kill() def name(self):...
Jay87682/auto_unittest_flask
flask_app/controller.py
controller.py
py
1,927
python
en
code
0
github-code
1
27976554317
import numpy as np import matplotlib.pyplot as plt import functions # functions parameters N = 8 # Number of particles timesteps = 1000 # Number of functions time steps dt = 1e-1 # Timestep alpha = 0.5 # cubic coupling beta = 0.1 # quartic coupling # for dt, timesteps in zip([1, 5*1e-1, 1e-1, 5*1e-2, 1e-2, 5*1e-3...
zRko29/Physics-masters
deprecated/energies.py
energies.py
py
1,111
python
en
code
0
github-code
1
37413111880
import torch.nn as nn import model.octconv as oct import model.venconv as ven from model.median_pooling import median_pool_2d class PrePocess(nn.Module): def __init__(self, config): super(PrePocess, self).__init__() # parameters low_channel_num = [config["in_channels"], 16, 32, c...
StephenYang190/SpeckleNoisePytorch
model/FDDnet.py
FDDnet.py
py
6,883
python
en
code
0
github-code
1
73085125154
import web import random import serialsend urls = ( '/', 'index', ) render = web.template.render('templates/', base='layout') ''' used to display a simple form using HTML5 x-webkit-speech. post data is then sent to serialsend.py which acts as a middleman between python and the micro-controller. ''' c...
beng/arduino_speech
talk.py
talk.py
py
625
python
en
code
1
github-code
1
41480233265
import json import os from pkg_resources import resource_filename DEFAULT_UA_LIST = resource_filename( 'VHostScan', 'lib/ua-random-list.txt') class file_helper(object): """description of class""" def __init__(self, output_file): self.output_file = output_file def check_directory(self): ...
codingo/VHostScan
VHostScan/lib/helpers/file_helper.py
file_helper.py
py
1,498
python
en
code
1,113
github-code
1
3420991534
from sklearn.model_selection import StratifiedShuffleSplit def cross_validation(clf, features, labels): cv = StratifiedShuffleSplit(random_state=106) true_negatives = 0 true_positives = 0 false_negatives = 0 false_positives = 0 for train_idx, test_idx in cv.split(features, labels): fe...
mukerong/Data-Science-Project
Titanic-Survival-Exploration/cross_validation.py
cross_validation.py
py
1,651
python
en
code
1
github-code
1
14939283703
# load the dataset ''' data = open('dataset.csv').read() labels=[] texts= [] for i, line in enumerate(data.split("\n")): print line content = line.split() print content[0] labels.append(content[0]) texts.append(content[1:]) # create a dataframe using texts and lables traindataframe = pandas.DataFra...
vikash18086/News_Classification-Data_Mining_Project-
Final_project/Naive.py
Naive.py
py
3,259
python
en
code
0
github-code
1
4450960332
import json import datetime class Utility: zones = ['1', '2'] @staticmethod def load_config(): try: with open('fare_config.json', mode='r') as config_file: return json.loads(config_file.read()) except FileNotFoundError: return False @staticmeth...
mani1604/travelcard
utility.py
utility.py
py
707
python
en
code
0
github-code
1
36220973818
import pygame from itertools import product class Board: def __init__(self, w, scr): self.world=w self.screen=scr def paint(self): org=self.world.get_organism() width=self.world.get_n() height=self.world.get_m() sizex = 500 / width sizey =...
epaw02/Python-World-Simulation-OOP
phytonn/Board.py
Board.py
py
782
python
en
code
0
github-code
1
37850694353
from pyspark.sql.functions import col from pyspark.sql.types import ( DoubleType, IntegerType, LongType, StringType, StructField, TimestampType, ) from . import AbstractSchema class AnswersSchema(AbstractSchema): def get_columnid(self): return ["activityId", "userId"] def get...
himewel/engage
spark/src/schemas/answers_schema.py
answers_schema.py
py
1,459
python
en
code
2
github-code
1
4848631023
from collections import defaultdict import tator if __name__ == '__main__': parser = tator.get_parser() args = parser.parse_args() api = tator.get_api(host=args.host, token=args.token) projects = api.get_project_list() total_size = 0 total_duration = 0 size_by_org = defaultdict(int) du...
cvisionai/tator-py
examples/platform_stats.py
platform_stats.py
py
1,177
python
en
code
4
github-code
1
31319950017
#!/usr/local/bin/python """ Capture pictures from webcamera to create stop motion video Examples Output to 'out' directory, capture every 60 seconds: python camcapture.py Output to 'mydir', capture every 30 seconds python camcapture.py -o mydir -r 30 """ import argparse import cv2 import time import datetime import...
julenka/stopmotionselfie
camcapture.py
camcapture.py
py
1,382
python
en
code
4
github-code
1
17287911939
# Shows different formula for time decay for use in a game # The first uses a linear decay which results in a fast decay # The Improved version uses a formula giving a decay that slows down over time # This is based on the formula f(x) = x / x + h # To run first install plotly using: # pip3 install plotly import plotl...
Apress/beginning-game-programming-with-pygame-zero
Chapter 4/timedecaygraph.py
timedecaygraph.py
py
1,167
python
en
code
11
github-code
1
43527352932
#!/usr/bin/python2 # This script parses the Naughty and Nice List (CSV). # For each person on the list, query the NPPD # infractions database and gather an infractions list. # Written for the SANS Holiday Hack Challenge 2017 # by Jason Testart # December 2017 import csv import urllib2 import json # Function: Given ...
jasontestart/CTF
SANSHolidayHackChallenge/2017/nppd/getAllInfractions.py
getAllInfractions.py
py
1,136
python
en
code
0
github-code
1
25820153472
from __future__ import absolute_import, division, print_function, unicode_literals import requests from requests.api import request from oauthlib import oauth1 import json import os import re try: # python2 from urlparse import parse_qsl except ImportError: # python3 from urllib.parse import parse_qsl ...
discogs/discogs_client
discogs_client/fetchers.py
fetchers.py
py
6,555
python
en
code
481
github-code
1
2768924683
import urllib.request as req from bs4 import BeautifulSoup import openpyxl #엑셀에 넣기 위해 import os from openpyxl.drawing.image import Image #앨범을 넣기 위해 부러와 #엑셀파일 존재하는지 확인 위해 OS 블러옴 if not os.path.exists("./멜론음원차트_오늘.xlsx"): book = openpyxl.Workbook() book.save("./멜론음원차트_오늘.xlsx") headers = req.Request(...
Aki-hwang/Python_lvl_1
30_멜론크롤링.py
30_멜론크롤링.py
py
2,026
python
ko
code
0
github-code
1
27232796115
""" Various helper methods """ from django.core.signing import Signer, BadSignature from django.conf import settings import os import base64 import binascii def get_size(path): """ Returns the size of a directory using Python 3.5 PEP 471 os.scandir() MUCH faster than os.walk as scandir return...
bwebsterhv/transpack
src/transpack/helpers.py
helpers.py
py
1,340
python
en
code
0
github-code
1
5502015887
""" YouTube: https://youtu.be/GdNA6AFk0Mg Terminal display commands: .header on .mode columns WHERE Clause Reference: https://www.tutorialspoint.com/sqlite/sqlite_where_clause.htm """ import sqlite3 from sqlite3 import OperationalError, IntegrityError import os import sys class DB_Manager: conn = None def ...
tacomonster/Database_Manager
DB_Manager.py
DB_Manager.py
py
3,745
python
en
code
2
github-code
1
4025684782
import pyotp import re import time import os from kaushaltools.qrmanager import qrmanager class totp: """ A class for generating and managing Time-Based One-Time Passwords (TOTP). This class provides methods to generate TOTP keys, generate OTPs, create 2FA URLs, show and save QR codes, scan QR codes, and ...
KaushalBhatol/kaushaltools
kaushaltools/totp.py
totp.py
py
7,799
python
en
code
0
github-code
1
40731159802
import numpy as np import warnings import os import statsmodels.formula.api as smf import pandas as pd import functools import re warnings.filterwarnings('ignore') class stepwise: def __init__(self,step,fit_intercept): self.step = step self.fit_intercept = fit_intercept def reduce_concat(sel...
avinashbarnwal/stepwisereg
stepwisereg/.ipynb_checkpoints/stepwisereg-checkpoint.py
stepwisereg-checkpoint.py
py
2,780
python
en
code
27
github-code
1
23768057380
from dataclasses import dataclass, field from typing import List from entity import MovingEntity from entity.ship_components import ( AvailableComponents, ShipComponent, container, defense, ) from processor import logging @dataclass class Ship(MovingEntity): """尚未初始化数值和组件的飞船 初始化属性和默认值已给出,可以根...
RuofengX/PyCosmic
entity/ships.py
ships.py
py
1,911
python
en
code
0
github-code
1
21860841913
import shutil import os ## # @Author: Ed Ardolino # @Version 1.0 # @Creation Date: 3-26-2021 ## ## # # Python program to move files from one specified location to another specified location # ## # User enters the source directory source_dir = input("What is your source directory?: ") # User enters the target direct...
EdArdolino/FileMover
FileMove.py
FileMove.py
py
1,446
python
en
code
0
github-code
1
26577958655
#!/usr/bin/env python3 import toml import sys def err(msg, *args): print('error:', msg % args, file = sys.stderr) def enforce_key_not_in_configs(dict, key, type, action): if key in dict: err('%s %s should not %s in configs.toml', type, key, action) sys.exit(1) def main(): sec...
contain-rs/admin
homu/generate-cfg.py
generate-cfg.py
py
1,308
python
en
code
0
github-code
1
24993597076
import sys """ forward 3 down 4 forward 3 up 4 down 4 """ def part1(input): position = { 'horizontal': 0, 'vertical': 0 } for line in input: direction, distance = line.split(' ') if direction == 'up': position['vertical'] -= int(distance) if direction ==...
marc-gav/advent-of-code-2021
problem2.py
problem2.py
py
1,347
python
en
code
0
github-code
1
70328223393
import speech_recognition as sr import tkinter as tk import algorithm sentences = [] text_display = None def update_text(): global recognized_text text_display.config(state=tk.NORMAL) text_display.insert(tk.END, recognized_text + '\n') text_display.config(state=tk.DISABLED) text_display.see(tk.EN...
vmdo2/speech-tag-identifier
speech.py
speech.py
py
2,578
python
en
code
0
github-code
1
30800311878
from . import UnzBaseModule, EventHandlerStatus class UnzMessageModule(UnzBaseModule): name = "unz-message" default_config = { "command": "unz-message", "arguement-error": "Too few arguements. Use unz-message (channel-name) (message)", "channel-error": "Unknown channel" } de...
KiRtAp2/univerzal
unz_modules/unz_message.py
unz_message.py
py
1,384
python
en
code
0
github-code
1
35350021858
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('group_discussion', '0003_comment_parent')...
jscott1989/newscircle
group_discussion/migrations/0004_topicuser.py
0004_topicuser.py
py
799
python
en
code
0
github-code
1
42917174855
import logging from six import add_metaclass from abc import ABCMeta, abstractmethod from agentml.parser import Element from agentml.common import attribute from agentml.parser.trigger.response import Response @add_metaclass(ABCMeta) class BaseCondition(object): """ AgentML Base Condition class """ de...
rainyDayDevs/AgentML
agentml/parser/trigger/condition/__init__.py
__init__.py
py
8,088
python
en
code
4
github-code
1
16130620140
class Solution: def letterCombinations(self, digits: str) -> List[str]: if not digits: return [] mapping = { '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', ...
heymamba824/Leetcode
day23/17.py
17.py
py
776
python
en
code
0
github-code
1
35318589108
import json import logging import random import time import copy from argparse import ArgumentParser from itertools import chain from pprint import pformat import copy import numpy as np import torch import torch.nn.functional as F from transformers import * from VideoGPT2 import * from train import SPECIAL_TOKENS, S...
ictnlp/DSTC8-AVSD
generate.py
generate.py
py
13,878
python
en
code
54
github-code
1
36976777837
# Author: Gael Varoquaux <gael dot varoquaux at normalesup dot org> # License: BSD 3 clause # mods to use webcam: A.Mazel # source controlled under electronoos.scripts import time # Standard scientific Python imports import matplotlib.pyplot as plt # Import datasets, classifiers and performance metrics from sklearn ...
alexandre-mazel/electronoos
scripts/sklearn_digits.py
sklearn_digits.py
py
5,178
python
en
code
2
github-code
1
34139298663
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: hashMap = {} for index , value in enumerate(nums): num_needed = target - value if num_needed in hashMap: return [hashMap[num_needed], index] hashMap [value] =...
rawanelbanaa/ProblemSolving_LeetCode
0001-two-sum/0001-two-sum.py
0001-two-sum.py
py
341
python
en
code
0
github-code
1
5139062156
from threading import * import time import cv2 import socket import io import pickle import struct global connection global address cam=cv2.VideoCapture(0) #stream = io.BytesIO() client_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM) client_socket.connect(('192.168.1.5', 9000))#192.168.43.205 ...
32shivang/Blind-Eye
piValcode.py
piValcode.py
py
907
python
en
code
0
github-code
1
34275552373
'''class Student(object):#类名开头通常大写 pass bart = Student() bart.name ='Green' print(bart.name)''' '''class Student (object): def __init__(self,name,score): self.name = name self.score = score bart = Student('Green',100) print(bart.name,bart.score) def print_score(std): print('%s:%s' %(std.nam...
wxzoro1/MyPractise
python/liaoscode/类和事例.py
类和事例.py
py
796
python
en
code
0
github-code
1
23088721998
__author__ = "maggie.sun@intel.com, ryan.lei@intel.com" from shutil import copyfile import fileinput import os import re from Utils import GetShortContentName, ExecuteCmd from Config import BinPath, LogCmdOnly, LoggerName, HDRTool import logging subloggername = "HDRToolsRun" loggername = LoggerName + '.' + '%s' % sub...
WuJoel2020/aom
tools/convexhull_framework/src/CalcQtyWithHdrTools.py
CalcQtyWithHdrTools.py
py
2,956
python
en
code
0
github-code
1
75256442273
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def __init__(self): self.res = list() def maxDepth(self, root): """ :type root: TreeNode :rtype: int ...
HawkinYap/Leetcode
leetcode104.py
leetcode104.py
py
730
python
en
code
0
github-code
1
13010341198
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest from clime import Command from clime.util import * class TestClime(unittest.TestCase): def test_util_autotype(self): cases = ('string', '100', '100.0', None) answers = ('string', 100 , 100.0 , None) for case, answer in zip(...
moskytw/clime
tests/test.py
test.py
py
1,786
python
en
code
152
github-code
1
26687931335
import torch from tqdm import tqdm from transformers import AutoModelForCausalLM, AutoTokenizer, logging as tf_logging from model_utils import predict from utils import ( HitsMetric, adjust_top_k, get_args, get_filename, load_data, prepare_input, update_history, update_metric, write...
usc-isi-i2/isi-tkg-icl
run_hf.py
run_hf.py
py
1,852
python
en
code
10
github-code
1
8626025770
#!/usr/bin/python3 # -*-coding:utf-8 -*- from handler import * from v1 import * """AdminHandler(관리자) """ class AdminHandler: def __init__(self): pass def get_score(self, data): """경기일 점수정보""" if not data: return jsonify({"data": {"games": []}}) scores = adm.get...
volt772/prooya
BE (Python)/v1/admin.py
admin.py
py
2,508
python
en
code
0
github-code
1
58932599
import pandas as pd from sklearn.model_selection import train_test_split, cross_val_predict from sklearn.metrics import classification_report, accuracy_score from sklearn.utils.validation import column_or_1d from sklearn.metrics import roc_auc_score, roc_curve from sklearn import tree from sklearn.ensemble import Rando...
lionliu/GrammaticalFacialExpressionsDataMining
Guilherme/RandomForestPreParam.py
RandomForestPreParam.py
py
3,015
python
en
code
0
github-code
1
585688575
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def minDepth(self, root): """ :type root: TreeNode :rtype: int """ if root == Non...
JSantosha/LeetCode-Python
Breadth-first Search/111 - Minimum Depth of Binary Tree.py
111 - Minimum Depth of Binary Tree.py
py
1,188
python
en
code
0
github-code
1
1034404782
import os import logging import ycm_core from collections import defaultdict from ycmd.completers.general_completer import GeneralCompleter from ycmd import identifier_utils from ycmd import utils from ycmd.utils import ToUtf8IfNeeded from ycmd import responses SYNTAX_FILENAME = 'YCM_PLACEHOLDER_FOR_SYNTAX' class Id...
TonyRobotics/RoboWare-Studio
extensions/RichardHe.you-complete-me-1.0.36/ycmd/ycmd/completers/all/identifier_completer.py
identifier_completer.py
py
7,399
python
en
code
234
github-code
1
24670436795
from decimal import Decimal from math import floor from itertools import chain import json from datetime import datetime, timedelta from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404, render from django.utils import timezone from django.http import HttpResponse, Ht...
hashirharis/DjangoERP
pos/views.py
views.py
py
25,396
python
en
code
1
github-code
1
8868844094
import boto3 import numpy as np from tempfile import NamedTemporaryFile from librosa.feature import melspectrogram import librosa boto_session = boto3.session.Session(region_name='eu-west-3') s3 = boto_session.resource('s3') sukikana_bucket = 'sukikana' def get_logmels(song_id): with NamedTemporaryFile('wb+') a...
pluttgens/sukikana
tasks/audio/get_log_mel_spectrum.py
get_log_mel_spectrum.py
py
806
python
en
code
0
github-code
1
36299131948
from . import DataProduct class CTDAS(DataProduct): """ CTDAS CH4 data """ # List of all possible fields we expect from the data # (original_name, standard_name, units) field_list = ( ('bio_flux_opt', 'CH4_natural_flux', 'Tg(CH4) year-1'), ('anth_flux_opt', 'CH4_fossil_flux', 'Tg(CH4) year-1'), ...
neishm/EC-CAS-diags
eccas_diags/interfaces/ctdas-ch4.py
ctdas-ch4.py
py
5,818
python
en
code
0
github-code
1
33371717840
import re import docutils.core import docutils.io import markdown import textwrap from rst2html5 import HTML5Writer import wiki #=============================================================================== # MARKUP BASE #=============================================================================== class Marku...
mgaitan/waliki_flask
waliki/markup.py
markup.py
py
6,530
python
en
code
17
github-code
1
6999417837
#!/usr/bin/env python # coding: utf-8 # # Introduction # <div class="alert alert-warning"> # <font color=black> # # **What?** self and __init__ # # </font> # </div> # # Create a class # <div class="alert alert-info"> # <font color=black> # # - So in python everything is an object, but classess and objects are no...
kyaiooiayk/Awesome-Python-Programming-Notes
tutorials/From_notebook_to_python/self and __init__.py
self and __init__.py
py
3,460
python
en
code
0
github-code
1
4052054857
import xml.etree.ElementTree as ET from subprocess import check_output import logging logger = logging.getLogger(__name__) class AEMetric(object): # command to run official eval.jar to get f1 score commands = { "rest": "./java -cp reviewlab/eval/A.jar absa16.Do Eval -prd data/ft/ae/16/rest/re...
FuyuTang-rinnki/AspectExtraction
a3/BERT-PT/reviewlab/metric.py
metric.py
py
4,250
python
en
code
0
github-code
1
30800279598
import discord import logging import asyncio import settings as stg import db_handler from module_registry import get_default_registry from unz_modules import UnzBaseModule, EventHandlerStatus logging.basicConfig( level=stg.LOG_LEVEL, format=stg.LOG_FORMAT, datefmt=stg.LOG_DATEFMT, handlers=[ ...
KiRtAp2/univerzal
main.py
main.py
py
2,831
python
en
code
0
github-code
1
13271284726
from __future__ import annotations import logging from pathlib import Path from typing import TYPE_CHECKING import pytest from pyk.kcfg.show import KCFGShow from pyk.proof import APRProof, APRProver, ProofStatus from pyk.proof.show import APRProofNodePrinter from pyk.testing import KCFGExploreTest, KProveTest from p...
runtimeverification/pyk
src/tests/integration/proof/test_mini_kevm.py
test_mini_kevm.py
py
3,364
python
en
code
12
github-code
1
72689378914
from rest_framework import viewsets from rest_framework.generics import get_object_or_404 from rest_framework.permissions import IsAuthenticated from api.permissions import OnlyAuthorChangeContent from api.serializers import PostSerializer, GroupSerializer, CommentSerializer from posts.models import Post, Group clas...
LariosDeen/api_yatube
yatube_api/api/views.py
views.py
py
1,223
python
en
code
0
github-code
1
19384581235
import unittest import random class Mean: def __init__(self, message): self.message = message def __enter__(self): return self def __exit__(self, a, b, c): print("exit a=" + str(a) + ", b=" + str(b) + ", c=" + str(c) ) self.message = None def getString(self): ...
danidemi/tutorial-python-tdd
idioms.py
idioms.py
py
2,522
python
en
code
0
github-code
1
74732733154
import sys import random while True: line = input() n = int(line.split()[0]) for i in range(n): line = input() m = int(input()) for i in range(m): line = input() # use file=sys.stderr to print for debugging print("debug code", file=sys.stderr, flush=True) # this wi...
alem-io/cup-code-examples
python/main.py
main.py
py
393
python
en
code
0
github-code
1
74930752674
import random from sys import modules from typing import Union import discord from redbot.core import commands from leveler.abc import MixinMeta from .basecmd import LevelSetBaseCMD class Profile(MixinMeta): """Profile commands""" lvlset = getattr(LevelSetBaseCMD, "lvlset") @lvlset.group(name="profil...
fixator10/Fixator10-Cogs
leveler/commands/lvlset/profile.py
profile.py
py
8,270
python
en
code
68
github-code
1
659214172
import nltk from nltk.corpus import wordnet s=input('enter a negtive sentence : ') #I am not happy s=s.lower() tmp='' words=[] for w in nltk.word_tokenize(s): word=w if tmp=='not': antonyms=[] for syn in wordnet.synsets(word): for s in syn.lemmas(): for a in s.anton...
one-last-time/python
NLTk/sentenceNegetion.py
sentenceNegetion.py
py
648
python
en
code
0
github-code
1
24597026520
# -*- coding: utf-8 -*- """ cron: 30 7 * * * new Env('每日新闻'); """ import requests, time, re, json, sys, traceback from io import StringIO from KDconfig import getYmlConfig, send class News: def __init__(self, cookie): self.sio = StringIO() self.Cookies = cookie def SignIn(self): print...
KD-happy/KDCheckin
News.py
News.py
py
2,400
python
en
code
227
github-code
1