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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
12117516603 | """
有道翻译
"""
from selenium.webdriver import Chrome, ChromeOptions
from selenium.webdriver.common.by import By
import time
option = ChromeOptions()
option.add_argument("--headless")
with Chrome(options=option) as driver:
driver.get("https://fanyi.youdao.com/")
input_txt = driver.find_element(By.XPATH,'//div... | 15149295552/Code | Month07/day17_python/exercise04.py | exercise04.py | py | 676 | python | en | code | 1 | github-code | 13 |
30604937036 | import random
from pcom.commands.base_command import BaseCommand
from pcom.errors import PComError
from typing import List
class EthernetCommandWrapper(BaseCommand):
def __init__(self, base_command: BaseCommand):
super().__init__(plc_id=base_command._plc_id, protocol=base_command.protocol)
self.b... | metalsartigan/pypcom | src/pcom/plc/ethernet_command_wrapper.py | ethernet_command_wrapper.py | py | 1,663 | python | en | code | 1 | github-code | 13 |
5871993071 | import numpy as np
def solve(grid : np.array) -> None:
def handle_col(r,c):
nonlocal last_value
value = grid[r, c]
if value != '?':
last_value = value
return
if last_value != '?' and value == '?':
grid[r, c] = last_value
n_rows, n_cols = ... | eric7237cire/CodeJam | 2017/1A/A.py | A.py | py | 1,721 | python | en | code | 7 | github-code | 13 |
709643745 | from Engine import *
mouseX = 0;
mouseY = 0;
def CloseFunc():
print("Closing...");
def MousePos(pos):
print(pos);
mouseX = pos[0];
mouseY = pos[1];
def KeyDown(key, mods):
pass;
mainWindow = Window();
mainWindow.OpenWindow(480,480,"Hello PyGame!");
renderer.OpenSurface(480, 480, mainWindow);
splash = Loa... | NPEX42/GamePy | Game.py | Game.py | py | 833 | python | en | code | 0 | github-code | 13 |
11276636159 | import scrapy
import csv
class routeSpider(scrapy.Spider):
name = "areaScrape"
allowed_domains = ['www.mountainproject.com']
def start_requests(self):
with open('data2.csv', 'rt') as allLinks:
allLinks = csv.reader(allLinks)
for link in allLinks:
url = str(*link)
yield scrapy.Request(url, self.pars... | swanjson/mountainSpider | area2routeNameLink.py | area2routeNameLink.py | py | 863 | python | en | code | 0 | github-code | 13 |
15639216283 | #! /usr/bin/env python
import os
# don't use gpu
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
import numpy as np
import numpy as np
import matplotlib.pyplot as plt
from scaledgp import ScaledGP
from scipy import signal
from progress.bar import Bar
import random
from utils import *
BASE_PATH = os.path.expanduser('~/Doc... | YimingShu-teay/balsa-reproduction | balsa_reproduction/model_service.py | model_service.py | py | 5,532 | python | en | code | 2 | github-code | 13 |
13366176946 | from django.http.response import HttpResponse
from django.shortcuts import redirect, render
from .forms import *
from django.views import View
# Create your views here.
def index(request):
return render(request,'index.html')
def inventoryHome(request):
if request.method=='POST':
form=InventoryForm(req... | jithinvv4u/DRF2 | inventory/views.py | views.py | py | 2,410 | python | en | code | 0 | github-code | 13 |
8869511265 | import random
class wordjumblegame(object):
def __init__(self, name, level) -> None:
self.name = name
self.points = 0
self.level = level
self.words = self.loadwords(self.level)
def __str__(self):
return self.name
def __repr__(self):
return se... | mindful-ai/oracle-python-feb2023 | 15_example_03/15_example_03/wordjumblegame_oop.py | wordjumblegame_oop.py | py | 2,998 | python | en | code | 0 | github-code | 13 |
9440095039 |
import json, time
from sys import argv
import bs4
from tqdm import tqdm
from utils import save_obj
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.commo... | piyushjaingoda/National-Flag-Recognition-using-Machine-Learning-Techniques | web_scraping/google_images_scraper.py | google_images_scraper.py | py | 2,128 | python | en | code | 3 | github-code | 13 |
74879554577 | # coding=utf-8
import logging
from collections import defaultdict
from django.core.management import BaseCommand
from django.db.models import Count
from benchmark.models import ResultAuthor, Result
class Command(BaseCommand):
def handle(self, *args, **options):
try:
return self._process(*arg... | thejoeejoee/VUT-FIT-IFJ-2017-server | benchmark/management/commands/merge_authors.py | merge_authors.py | py | 976 | python | en | code | 0 | github-code | 13 |
72259460818 | #! /usr/bin/env python
# -*- coding: utf-8
import time
import cv2
import numpy as np
from math import pi, sin, cos, asin, acos
import csv
from perception.wedge.gelsight.util.Vis3D import ClassVis3D
from perception.wedge.gelsight.gelsight_driver import GelSight
from controller.gripper.gripper_control import Gripper_Co... | nehasunil/deformable_following | following.py | following.py | py | 4,892 | python | en | code | 0 | github-code | 13 |
20809119299 | import pytest
import redis
import time
from crypto_tulips.dal.services.contract_service import ContractService, ContractFilter
from crypto_tulips.dal.objects.contract import Contract
now = int(time.time())
c1 = Contract('tcs_hash1', 'tcs_sig1', 'tc_matt', 100, 0.5, 1, 1000, now, now + 900)
c2 = Contract('tcs_hash2', ... | StevenJohnston/py-crypto-tulips | crypto_tulips/dal/services/tests/test_contract_service.py | test_contract_service.py | py | 3,349 | python | en | code | 1 | github-code | 13 |
40840615783 | # -*- coding: utf-8 -*-
#
# This software is licensed under
# CeCILL FREE SOFTWARE LICENSE AGREEMENT
# This software comes in hope that it will be useful but
# without any warranty to the extent permitted by applicable law.
# (C) M. Couprie <coupriem@esiee.fr>, 2011
# Université Paris-Est, Laboratoire d'Informatiqu... | technolapin/sable | pink/tutorial/python/MC-TP6/solution/test_arrays.py | test_arrays.py | py | 2,336 | python | en | code | 2 | github-code | 13 |
37159835074 | from customtkinter import *
import tkinter
from tkinter import messagebox
import sqlite3
from PIL import Image,ImageTk
import time
loginP = CTk()
loginP.title("patient registration page")
loginP.resizable(0, 0)
loginP.state('zoomed')
loginP.iconbitmap("istock.ico")
set_default_color_theme('green')
#####creating datab... | NirajanMahato/Pharmacy-Management-System-Gen-IV- | phar_login.py | phar_login.py | py | 16,366 | python | en | code | 0 | github-code | 13 |
15071349300 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Mapping fastq to reference genome
1. rRNA, spikein, optional
2. genome
"""
import os
import sys
import re
import io
import glob
import json
import tempfile
import shlex
import subprocess
import logging
import pandas as pd
import pysam
import pybedtools
from utils_par... | bakerwm/goldclip | goldclip/log_parser/alignment.py | alignment.py | py | 26,410 | python | en | code | 0 | github-code | 13 |
268989372 | import numpy as np
import vidProc
import cellSum
import grid_map
import videoRecord
import math
import cv2
def printCalibrationShape():
#chamar função que permite enviar o GCode que imprime a forma de calibração
#Subir a Cabeça de impressão
return None
def movePrintCore(time, name, celLen):
#D... | DuarteCPereira/tese | camNozzle.py | camNozzle.py | py | 9,067 | python | en | code | 0 | github-code | 13 |
1386991125 | import requests
from datetime import datetime
def getData(city) -> str:
try:
api_key = "eb5ef05a1f20ab85b9ff23ff53bd617f"
URL = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}"
r = requests.get(URL)
return r.json()
except:
r = r.json(... | ayirolg/ShapeAI-Project | weather.py | weather.py | py | 1,918 | python | en | code | 0 | github-code | 13 |
41837400754 | import argparse
from tsm.lexicon import Lexicon
from tsm.util import read_file_to_lines, write_lines_to_file
from tsm.sentence import Sentence
parser = argparse.ArgumentParser()
parser.add_argument('lexicon_path')
parser.add_argument('src_path')
parser.add_argument('dest_path')
parser.add_argument('--with-prob', acti... | Chung-I/ChhoeTaigiDatabase | lexicon_g2p.py | lexicon_g2p.py | py | 1,137 | python | en | code | null | github-code | 13 |
37616809579 | import tweepy
import time
from sportsipy.mlb.roster import Player
import datetime
x = datetime.datetime.now()
print('Twitter bot active', flush=True)
#API keys from twitter
#Add your own here
CONSUMER_KEY = ""
CONSUMER_SECRET = ""
ACCESS_KEY = ""
ACCESS_SECRET = ""
auth = tweepy.OAuthHandler(CONSUMER_KEY,CONSUMER_SE... | mihan-b/jaysstarter-bot | bot.py | bot.py | py | 12,390 | python | en | code | 0 | github-code | 13 |
21830953372 | import numpy as np
from math import cos, sin, atan2, pi
import math
class RobotModel:
def __init__(self, max_v, min_v, max_w, max_acc_v, max_acc_w,
init_x, init_y, init_yaw, init_v=0.0, init_w=0.0, robot_radius=0.3,
laser_min_angle=-pi/2, laser_max_angle=pi/2, laser_increment_angl... | sldai/RL_pursuit_evasion | robot_model.py | robot_model.py | py | 4,448 | python | en | code | 10 | github-code | 13 |
20220590257 | #!/usr/bin/env python3
from jinja2 import Template
import sys, json, yaml
json_file = open(sys.argv[2])
json_file.close
variables = json.load(json_file)
with open(sys.argv[1]) as file_:
t = Template(file_.read())
output = t.render(variables)
with open(sys.argv[3], 'w') as f:
f.write(output) | tacobayle/nestedEsxiVcenter | python/template.py | template.py | py | 299 | python | en | code | 1 | github-code | 13 |
19388818042 | import numpy as np
from scipy.io import loadmat # this is the SciPy module that loads mat-files
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from datetime import datetime, date, time
import pandas as pd
# mat is a dict that contains this_resp
# this_resp is a 3x7x9 cell (3 blocks, 7 muscle ... | samlaf/GP-BCI | data_singe/load_matlab.py | load_matlab.py | py | 5,232 | python | en | code | 1 | github-code | 13 |
7897248420 | import re
import pandas as pd
import os
movie_data = pd.read_csv(os.path.join("data",'movies_awards.csv'))
lenght_movies = movie_data['Title'].count()
dummy=[0 for i in xrange(lenght_movies)]
d={}
columns = ['Awards_won','Awards_nominated','Primetime_awards_won','Primetime_awards_nominated',
'Oscar_awards_... | Uppalapa/Dataanalysis-using-Python-Projects | Assignment 3/Q4_PART_1.py | Q4_PART_1.py | py | 3,433 | python | en | code | 0 | github-code | 13 |
358111766 | # -*- coding: utf-8 -*-
import json
from PIL import Image,ImageDraw,ImageFont
from datetime import datetime
baseUi = 'display/ui/resources/UI.png'
currentlyIconPath = 'display/ui/resources/icons/currently/'
dailyIconPath = 'display/ui/resources/icons/daily/'
hourlyIconPath = 'display/ui/resources/icons/hourly/'
class... | namarino41/weatherbox | weatherbox_display/display/ui/ui_builder.py | ui_builder.py | py | 8,294 | python | en | code | 1 | github-code | 13 |
26383856387 | from leetcode.string.longest_repeating_character import Solution
import pytest
@pytest.mark.parametrize(
"string,k,expected",
[
("ABAB", 2, 4),
("AABABBA", 1, 4),
("BAAAABBA", 1, 5),
("BAAAABBA", 3, 8),
("BAAAABBBBBA", 1, 6),
("CBAAAABBBBBA", 2, 7),
("CB... | martinabeleda/leetcode | leetcode/string/test/test_longest_repeating_character.py | test_longest_repeating_character.py | py | 576 | python | en | code | 1 | github-code | 13 |
1653427365 | import logging
from datetime import datetime
from sqlalchemy import func
from flask import Blueprint, jsonify, request
from ledger import db
from ledger.models import Transaction
from .decorators import auth_required
logger = logging.getLogger(__name__)
index_blueprint = Blueprint('index', __name__)
@index_blueprin... | fizzy123/ledger | ledger/views/index.py | index.py | py | 1,049 | python | en | code | 0 | github-code | 13 |
28942761930 | import requests
import json
class initfmp :
"""
FMP Api driver to get data with attached apikeys and main endpoint
"""
def __init__(self) :
self.config = self.get_config()
self.endpoint = self.config['fmp']['endpoint']
self.api_key = self.config['fmp']['api_key']
def get_co... | gonggse/dime-data-engineer-exam | utils/fmp_driver.py | fmp_driver.py | py | 1,031 | python | en | code | 2 | github-code | 13 |
14966961078 | from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
import debug_toolbar
urlpatterns = [
path('admin/', admin.site.urls),
path('review/', include("review.urls", namespace="review")),
path('account/', include("a... | Oseni03/ecomstore | core/urls.py | urls.py | py | 817 | python | en | code | 1 | github-code | 13 |
21928266713 | # CodeChef - LAPIN - Lapindromes
# https://www.codechef.com/LP1TO201/problems/LAPIN
import sys
input = sys.stdin.readline
from collections import Counter
T = int(input())
for _ in range(T):
S = input().rstrip()
middle = len(S) // 2
if len(S) % 2 != 0:
S = S[:middle] + S[middle+1:]
first_ha... | dyabk/competitive-programming | Codechef/self_learning/level_up/strings/Lapindromes.py | Lapindromes.py | py | 454 | python | en | code | 0 | github-code | 13 |
24349269402 | from configparser import ConfigParser
import os
from freddi import Freddi, FreddiNeutronStar
DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
DAY = 86400
# Should contain all dimensional qu
_UNITS = dict(
Mx=1.98892e33,
Mopt=1.98892e33,
period=DAY,
distance=1000 * 3.08567758135e18,
ti... | hombit/freddi | python/test/test_util.py | test_util.py | py | 1,201 | python | en | code | 6 | github-code | 13 |
1935925886 |
class Difficulties:
"""A class that initializes the chosen difficulty
Attributes:
difficulty: The chosen game difficulty
"""
def __init__(self, difficulty):
"""The classes constructor which sets the difficulties values
Args:
Listed above
"""
self.... | Savones/ot-harjoitustyo | memory_game/src/objects/difficulties.py | difficulties.py | py | 1,096 | python | en | code | 1 | github-code | 13 |
12218437330 | import socket
import sys
import subprocess as sp
from timestamp import timestamp
from datetime import datetime
extProc = sp.Popen(['python','node2.py']) # runs myPyScript.py
status = sp.Popen.poll(extProc) # status should be 'None'
IP = '0x2A'
MAC = 'N2'
LOCAL_ARP_TABLE = {
"0x21": "R2",
"0x2A": "N2",
... | wellsonah2019/cs441_t6 | node2-listener copy.py | node2-listener copy.py | py | 6,559 | python | en | code | 0 | github-code | 13 |
6002482278 | '''
Example code of simulating a liquid fountain in a simple box.
The simulation is based on PBF (https://mmacklin.com/pbf_sig_preprint.pdf)
Note: the same functions used for this PBF are used for liquid reconstruction
'''
import torch
import open3d as o3d
from differentiableFluidSim import FluidGravityForce, uniformS... | ucsdarclab/liquid_reconstruction | simulateBox.py | simulateBox.py | py | 4,021 | python | en | code | 1 | github-code | 13 |
36636885428 | # properties ...
class Car:
def __init__(self, speed):
self.speed=speed
c1 = Car("high")
c2 = Car("mid")
c3 = Car("low")
def get_speed(car):
speeds = {
"high":300,
"mid":200,
"low":100
}
speed = speeds.get(car.speed , None)
if not speed:
r... | Sina-Gharloghi/HeyvaAI-exercise | 102prj16.py | 102prj16.py | py | 462 | python | en | code | 0 | github-code | 13 |
24653586600 | import base64
import xml.etree.ElementTree as element_tree
import string
import os
import boto3
from util import Util
from hls_aes import HLSAesLib
from key_generator import KeyGenerator
s3_client = boto3.client("s3")
KEY_STORE_BUCKET = os.environ["KEY_STORE_BUCKET"]
HLS_AES_128_SYSTEM_ID = '81376844-f976-481e-a84e-c... | OdaDaisuke/aws-speke | src/server_response_builder.py | server_response_builder.py | py | 4,716 | python | en | code | 5 | github-code | 13 |
33704174995 | # coding=UTF-8
import random
import requests
from requests import Timeout, RequestException
from bs4 import BeautifulSoup
proxies_pool = [
{},
{'http': '172.19.0.11:8118','https': '172.19.0.11:8118'}
]
headers_ = {'user_agent': "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/113.0",
... | DarkGoldBar/spiders_lair | drug_solubility/main.py | main.py | py | 1,708 | python | en | code | 0 | github-code | 13 |
30138843612 | from flask_jwt_extended import jwt_required
from flask_restful import Resource
from zou.app.mixin import ArgsMixin
from zou.app.models.project import Project, PROJECT_STYLES
from zou.app.models.project_status import ProjectStatus
from zou.app.services import (
deletion_service,
projects_service,
shots_se... | cgwire/zou | zou/app/blueprints/crud/project.py | project.py | py | 7,319 | python | en | code | 152 | github-code | 13 |
35386369181 | import PyGeom2
def viz(g):
a=g.point(0,0,color=(1,0,0))
b=g.point(100,0,moveable=True)
c=g.point(0,100,moveable=True)
g.text(base=c, string = "asdf", size=-18, color = (0,1,0))
g.line(a,b)
g.rect(c, (5, 6))
g.polygon(vertices = (a, b, c), fill = (1,2,3))
g.text(base=b, string = str(b), size=-18, color = (0,1,0... | victorliu/PyGeom2 | test.py | test.py | py | 374 | python | en | code | 1 | github-code | 13 |
39423093284 | class Parrot:
species = "bird"
def __init__(self,name,age):
self.name = name
self.age = age
def __str__(self):
return"{}(name:{} age :{})".format(__class__.species,self.name,self.age)
blu = Parrot("Blu",10)
woo = Parrot("woo",21)
print(blu)
print(woo)
| dharmeshvyas/BCA-SEM-6 | python/UNIT -2/practical-1.py | practical-1.py | py | 305 | python | en | code | 0 | github-code | 13 |
21411108938 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def verticalOrder(self, root: TreeNode) -> List[List[int]]:
"""
[MEMO] If there is order req... | stevenjst0121/leetcode | 314_binrary_tree_vertical_order_traversal.py | 314_binrary_tree_vertical_order_traversal.py | py | 1,294 | python | en | code | 0 | github-code | 13 |
31272834440 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""收集由RabbitMQ回传的微博数据."""
import logging
import asyncio
import json
from core.mq_connection import get_channel
from spider import TweetP
from db import RawDataDAO
from db import TweetDAO
class DataCollecter(object):
"""收集由RabbitMQ回传的微博数据."""
def __init__(self):
... | njnubobo/WeiboSpider | weibo_spider/scheduler/datacollecter.py | datacollecter.py | py | 2,020 | python | en | code | 0 | github-code | 13 |
24632157870 | import os
import re
from setuptools import setup, find_packages
def long_description():
try:
return open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
except IOError:
return None
def read_version():
with open(os.path.join(os.path.dirname(__file__), 'pyplanet', '__init__.py')) as handler:
re... | 15009199/PyPlanet-F8-F9-rebind | setup.py | setup.py | py | 2,404 | python | en | code | null | github-code | 13 |
17297281267 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth import authenticate, login,logout
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from rest_framework import viewsets
from .models import *
from .serializers import *
from dj... | sayok88/magical_task | apps/app1/views.py | views.py | py | 3,918 | python | en | code | 0 | github-code | 13 |
10945448738 | import pytest
from pynamodb.pagination import RateLimiter
class MockTime():
def __init__(self):
self.current_time = 0.0
def sleep(self, amount):
self.current_time += amount
def time(self):
return self.current_time
def increment_time(self, amount):
self.current_time +... | pynamodb/PynamoDB | tests/test_pagination.py | test_pagination.py | py | 2,078 | python | en | code | 2,311 | github-code | 13 |
16788061574 |
import weakref
import math
import numpy as np
import py_trees
import shapely
import carla
from srunner.scenariomanager.carla_data_provider import CarlaDataProvider
from srunner.scenariomanager.timer import GameTime
from srunner.scenariomanager.traffic_events import TrafficEvent, TrafficEventType
from srunner.scena... | liuyuqi123/ComplexUrbanScenarios | test/scenario_runner/srunner/drl_code/scenario_utils/atomic_criteria_fixed.py | atomic_criteria_fixed.py | py | 10,927 | python | en | code | 37 | github-code | 13 |
17587494512 | from tkinter import *
#Configuracion de la raiz
root = Tk()
"""
# variables dinamicas
texto = StringVar()
texto.set("Un nuevo texto")
#Configuracion de un marco
#frame = Frame(root, width=480, height=320)
#frame.pack()
#label = Label(root, text="Hola Mundo")
#label.place(x=500, y=500) # x=0 y = 0
#label.pack()
Lab... | irwinet/app_python3 | Fase 4 - Temas avanzados/Tema 13 - Interfaces graficas con tkinter/label.py | label.py | py | 729 | python | es | code | 0 | github-code | 13 |
37984908992 | import dataclasses
import time
import rospy
from droneresponse_mathtools import Lla
from mavros_msgs.msg import RCIn
from .Drone import FlightMode
from .sensor import SensorData
def is_data_available(data: SensorData) -> bool:
a = dataclasses.asdict(data)
# Geofence not needed to run tests
del a["geof... | DroneResponse/hardware-tests | src/dr_hardware_tests/flight_predicate.py | flight_predicate.py | py | 5,341 | python | en | code | 0 | github-code | 13 |
12811267793 | # File : word_frequency.py
# Author : 임현 (hyunzion@gmail.com)
# Since : 2018 - 06 - 06
import string # 스트링
import re # 정규 표현식
# 단어 빈도수를 저장할 파이썬 딕셔너리 변수
frequency = {}
# sms spam data txt 파일을 염
spam_data = open('spam_sms.txt', 'r')
# data를 읽어서 문자를 모두 소문자로 바꿔줌 (정규 표현식을 쉽게 쓰기 위함)
data_string = spam_data.read().lower(... | HyunIm/Sangmyung_University | 2018년도 1학기/통계, 유훈 교수님/기말고사_대체 과제/스팸 필터링/임현/1_Materials/3_Python/word_frequency.py | word_frequency.py | py | 975 | python | ko | code | 4 | github-code | 13 |
71006328977 | import numpy as np
import random
import math
import agents.evaluator.subsquares as subsquares
def showVector(v, dec):
fmt = "%." + str(dec) + "f" # like %.4f
for i in range(len(v)):
x = v[i]
if x >= 0.0: print(' ', end='')
print(fmt % x + ' ', end='')
class NeuralNetwork:
def __init__(self, layer_... | thien/slowpoke | library/agents/evaluator/neural.py | neural.py | py | 6,288 | python | en | code | 1 | github-code | 13 |
43770684836 | import copy
input = 'input'
with open(input) as f:
rules, messages_received = f.read().split('\n\n')
rulemap = {}
for rule in rules.split("\n"):
nr, value =rule.split(':')
rulemap[nr] = value.strip().strip('"')
all = []
def gen(message, messages):
for i, item in enumerate(message):
if item n... | stehal/aoc2020 | day19/solution.py | solution.py | py | 2,016 | python | en | code | 0 | github-code | 13 |
5099903891 | from concurrent.futures import ThreadPoolExecutor
from pipeline.pipeline_processes.pipeline_process_interface import PipelineProcessInterface
from pipeline.pipeline_processes.load_file import LoadFile
from pipeline.global_params import GlobalParams
class EncodeData(PipelineProcessInterface):
FIRST_COLUMN_TO_ENCO... | mortalswat/hashcode-2021 | pipeline/pipeline_processes/encode_data.py | encode_data.py | py | 1,933 | python | en | code | 0 | github-code | 13 |
3769567163 | import pyttsx3
import datetime
import speech_recognition as sr
import wikipedia
import webbrowser
from selenium import webdriver
import os
import smtplib
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voices',voices[1].id)
#print(voices[1].id)
def speak(audio):
... | akashchakraborty/Thanos---Voice-Assistant | ThanosAssistant.py | ThanosAssistant.py | py | 3,008 | python | en | code | 0 | github-code | 13 |
20758396578 | import psycopg2
from telegram import Update, Bot
from telegram.ext import CallbackContext
import logging
from aiogram import Bot, Dispatcher, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.state import State, StatesGroup
from ... | chyngyz475/telebot_041 | bot/handlers/checkout_handler.py | checkout_handler.py | py | 9,088 | python | ru | code | 0 | github-code | 13 |
42702789891 | # Programa de configuração para o cx_Freeze poder "Buildar"
import sys
from cx_Freeze import setup, Executable
build_exe_options = {"packages": ["os"], "includes": ["tkinter"], "include_files": ["fundo.png", "lapis.ico"]}
base = None
if sys.platform == "win32":
base = "Win32GUI"
setup(
name="Edito... | luizsouza1993/Data_Science_Python | # Programa de configuração para o cx_Fre.py | # Programa de configuração para o cx_Fre.py | py | 576 | python | en | code | 0 | github-code | 13 |
28566799351 | import ccxt
import ta
import pandas as pd
import time
import talib
#This bot fetches the last 1000 1-day candles for the BTC/USDT symbol on the Bybit exchange, converts them to Heikin-Ashi candles, and calculates the 20-day and 50-day exponential moving averages (EMAs) and the 14-day relative strength index (RSI). If... | osasere1m/tradingbotccxt | testbot/Heikin-Ashi.py | Heikin-Ashi.py | py | 2,922 | python | en | code | 0 | github-code | 13 |
32761733402 | import networkx as nx
import numpy as np
import random
import util
import sys
class graphSolver:
def __init__(self, node_names, house_names, start, adj_mat):
# Genetic Algo Hyperparameters
self.default_iterations = 100
self.population_size = 100
self.elite_size = int(self.populati... | NickL77/CS170-TSP | geneticAlg/geneticAlg.py | geneticAlg.py | py | 11,889 | python | en | code | 0 | github-code | 13 |
9640497351 | class QueryContext:
def __init__(self, stream_id, model, input_list,scale=None):
# input 是tensor list
self.has_deadline=False
self.stream_id=stream_id
self.model=model
self.input_list=input_list
# shape是属性 size是方法
# print(len(input_list),"输入长度")
sel... | sunnie-star/DRL_Bilevel | scheduler/query.py | query.py | py | 594 | python | zh | code | 0 | github-code | 13 |
73159848339 | import json
import requests
def tag_data_using_clarinAPI(tagger, input_file_path, output_file_path):
clarinpl_url = "http://ws.clarin-pl.eu/nlprest2/base"
user_mail = ""
url = clarinpl_url + "/process"
lpmn = tagger
text = open(input_file_path, "r", encoding="utf8").read()
payload = {'text... | AgataSkibinska/NLP-taggers-analysis | clarin_API_tagger.py | clarin_API_tagger.py | py | 855 | python | en | code | 0 | github-code | 13 |
29863013617 | import json
import unittest
from os.path import dirname, join
from pytest import raises
import intelmq.tests.bots.experts.domain_suffix.test_expert as domain_suffix_expert_test
from intelmq.bots.experts.domain_suffix.expert import DomainSuffixExpertBot
from intelmq.bots.experts.taxonomy.expert import TaxonomyExpertBot... | certtools/intelmq | intelmq/tests/lib/test_bot_library_mode.py | test_bot_library_mode.py | py | 5,333 | python | en | code | 856 | github-code | 13 |
13228013161 | import os
import copy
import logging
from pathlib import Path
from functools import reduce, partial
from operator import getitem
from datetime import datetime
from logger import setup_logging
from utils import read_json, write_json
class ConfigParser:
def __init__(self, config, testing=False, resume=None, modific... | yjlolo/ismir20-unsupervised-disentanglement | parse_config.py | parse_config.py | py | 9,698 | python | en | code | 1 | github-code | 13 |
3481070043 | import requests
# Define the URL you want to request
class carCapas:
def __init__(self, url):
url = "http://192.168.1.147:8080/api/sparkle/"
self.url = url
def consumeGet(self,endPoint):
try:
response = requests.get(self.url+endPoint)
if response.status_code... | gnro/PyPinino | ApiRequests.py | ApiRequests.py | py | 1,055 | python | en | code | 0 | github-code | 13 |
12635411644 | import os.path
import rasterio
import numpy as np
import matplotlib.pyplot as plt
import torch
from torchvision.models import ViT_L_16_Weights, vit_l_16
from torchvision.models import swin_v2_b, Swin_V2_B_Weights
from h3.utils.directories import get_xbd_hurricane_dir
def load_image() -> np.ndarray:
hurricane_dir =... | ai4er-cdt/hurricane-harm-herald | h3/models/pre_train.py | pre_train.py | py | 1,191 | python | en | code | 1 | github-code | 13 |
21585948261 | # Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, '../README.md'), encoding='utf-8') as f... | corenel/ip-camera-ehome-server | python/setup.py | setup.py | py | 1,259 | python | en | code | 2 | github-code | 13 |
7041365744 | #!/usr/bin/env python3
#
# CovidDataMain.py
#
# Prepare the data from Github and produce the csv files for other apps
#
from datetime import datetime
from dateutil.relativedelta import relativedelta
from dateutil import parser
from geopy.geocoders import Nominatim
import os
import logging
import numpy as np
import pan... | SavedRepos/CovidProjects | Apps/C19CollectData/C19CollectDataMain.py | C19CollectDataMain.py | py | 2,750 | python | en | code | 0 | github-code | 13 |
36882800039 | from data import question_data
from question_model import Question
from quiz_brain import QuizBrain
question_bank=[]
for i in question_data:
new_que=Question(i["text"],i["answer"])
question_bank.append(new_que)
quiz=QuizBrain(question_bank)
while(quiz.still_have_question()):
quiz.next_question()
print(f"Yo... | 23navi/Python-Codes | 100DaysOfCode/Day17/quiz-game/main.py | main.py | py | 373 | python | en | code | 4 | github-code | 13 |
15457391207 | # USBHub.py
#
# Contains class definitions to implement a USB hub.
from USB import *
from USBDevice import *
from USBConfiguration import *
from USBInterface import *
from USBEndpoint import *
class USBHubClass(USBClass):
name = "USB hub class"
def __init__(self, maxusb_app):
self.maxusb_app = maxus... | nccgroup/umap | devices/USBHub.py | USBHub.py | py | 5,949 | python | en | code | 265 | github-code | 13 |
19107656456 | #!/usr/bin/env python3
import sys
import time
isRemaining = 0
K = int(sys.argv[2])
currentWord = ""
byteStringLeftover = ""
frequencyTable = {}
treeInLine = []
fileInLine = []
trailingZeros = 0
codes = []
dictionary = {}
reqBits = 0
class Node():
def __init__(self, character, freq, left, right):
self.character = ... | Rugshtyne/HuffmanCoder | python/encoder.py | encoder.py | py | 6,070 | python | en | code | 0 | github-code | 13 |
24580181691 | from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QTextEdit, QLabel, QLineEdit, QFileDialog
from linkTree import build_link_tree_and_scrape
import json
import sys
class WebScraperApp(QWidget):
def __init__(self, parent=None):
super(WebScraperApp, self).__init__(parent)
se... | trv893/py-web-scrape | ui.py | ui.py | py | 2,106 | python | en | code | 0 | github-code | 13 |
39443440443 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Main file of Altai. Execute it to use the application. """
# System imports
import sys
from os.path import expanduser
import PySide2.QtGui as QtGui
import PySide2.QtCore as QtCore
import PySide2.QtWidgets as QtWidgets
# Altai imports
from . import config
from .vented_b... | Psirus/altai | altai/gui/main.py | main.py | py | 4,344 | python | en | code | 0 | github-code | 13 |
9382542497 | import sys
import re
# copies two conllu files, but it removes sentid's if one of the files
# had a conversion error for that sentid
def add_keys(f):
keys = set()
reg_id = re.compile('# sent_id = (.*)$')
reg_error = re.compile('# error')
for line in f:
line = line.rstrip()
m = reg_id.m... | rug-compling/Alpino | EvalUD/goodkeys.py | goodkeys.py | py | 1,337 | python | en | code | 19 | github-code | 13 |
18081905648 | # 导入os模块
import os
# 定义全局变量 BASE_DIR 通过VASE_DIR定位到项目根目录
BASE_PATH = os.path.dirname(os.path.abspath(__file__))
# 定义请求头
HEADERS = None
# 定义员工ID
EMP_ID = None | varrtgust0621/testIHRMProject | app.py | app.py | py | 216 | python | zh | code | 0 | github-code | 13 |
30993854546 | #! /usr/bin/env python
import os, sys
import pygame, random
try:
import android
except ImportError:
android = None
FPS = 30
TIMEREVENT = pygame.USEREVENT
skier_images = ["skier_left2.png",
"skier_left1.png",
"skier_down.png",
"skier_right1.png",
... | noahdhwest/Breakout | .backup-break.py | .backup-break.py | py | 9,637 | python | en | code | 1 | github-code | 13 |
16840314637 | from selenium import webdriver
from time import sleep
import sys
import json
#####
url = 'https://www.youtube.com'
file = 'cookies.dat'
driver_path = r"D:\ProgramData\Python add-ons\geckodriver.exe"
how_to_use = '''***** How to Use *****
signin2cookies.py
--> this uses default driver_path "D:\ProgramDa... | akshaysmin/youtube_reply_bot | signin2cookies.py | signin2cookies.py | py | 2,249 | python | en | code | 1 | github-code | 13 |
27878463324 | '''
Testing the Measurement class
================================================================
Unit tests for running test sequences and related functions.
This is the first sanity check to run when testing any changes.
'''
#================================================================
#%% Imports
#========... | redlegjed/test_measure_process_lib | unit_test/test_example_sequence.py | test_example_sequence.py | py | 9,031 | python | en | code | 0 | github-code | 13 |
23343505298 | from editor import *
import typer
from typing import Optional
import allpyCon
app = typer.Typer(add_completion=False)
app.add_typer(allpyCon.app, name="all")
__version__ = "0.1.0"
def version_callback(value: bool):
if value:
typer.echo(f"pyCon CLI Version: {__version__}")
raise typer.Exit()
@a... | Bonnary/pyCon | pyCon.py | pyCon.py | py | 4,422 | python | en | code | 0 | github-code | 13 |
34835026694 | """
Find a valid itinerary from the tickets, in lexographical order if multiple poss
Uses DFS: follows possible path until reaches end point (only one possible)
These will all be accessed in lexographical order, and added to the itinerary
in reverse order (postvisit)
Essentially there is a main line from the start to... | BenLeong0/leetcode_etc | leetcode_problems/leetcode332.py | leetcode332.py | py | 1,234 | python | en | code | 0 | github-code | 13 |
3345840963 | '''
Multipoint communication service protocol (T.125)
'''
import logging, ptypes, protocol.gcc as gcc, protocol.ber as ber, protocol.per as per
from ptypes import *
ptypes.setbyteorder(ptypes.config.byteorder.bigendian)
### MCS protocol data (BER Encoding)
class Protocol(ber.Protocol.copy(recurse=True)):
pass
cla... | arizvisa/syringe | template/protocol/mcs.py | mcs.py | py | 16,313 | python | en | code | 35 | github-code | 13 |
9923084643 | import plotly
from plotly.graph_objs import Scatter, Layout
x = []
y = []
with open('/tmp/mem_dump.txt',"r") as memDump:
for line in memDump:
yx = line.split(" ")
if yx[0] == '#':
continue
else:
x.append(yx[1])
y.append(yx[0])
with open('/tmp/cpu_dump.t... | fd-rey/TFG | python/plot.py | plot.py | py | 896 | python | en | code | 0 | github-code | 13 |
44407838131 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 28 17:29:11 2017
@author: subhy
Functions to help define ABCs (abstract base classes) from a template.
"""
__all__ = [
'typename', 'ABCauto',
'get_abstracts', 'subclass_hook', 'subclass_hook_nosub',
'check_methods', 'check_attributes', 'check_properties',
]
... | subhylahiri/sl_py_tools | abc_tricks.py | abc_tricks.py | py | 4,994 | python | en | code | 1 | github-code | 13 |
664484024 | # Manny Pagan
# Sept 24th Python Course
# Assignment 5
# Due: Oct 10th
user_input = input("What calculation would you like to do? (add, sub, mult, div)")
prompt_one = int(input("What is number 1?"))
prompt_two = int(input("What is number 2?"))
def problem_4_calculator():
if "add" in user_input:
print(prom... | manuelpagan/assignment4 | problem4.py | problem4.py | py | 673 | python | en | code | 0 | github-code | 13 |
26384313770 | from __future__ import division, print_function, absolute_import
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("./data/", one_hot=True)
# Training Parameters
learning_rate = 0.001
num_steps = 200
batch_size = 128
display_step = 10
# Network Para... | AdrianHsu/tensorflow-basic-models | convolutional_network_raw.py | convolutional_network_raw.py | py | 4,917 | python | en | code | 0 | github-code | 13 |
13522692096 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys, time, json
import gym
import numpy as np
import tensorflow as tf
from easy_rl.agents import agents
from easy_rl.models import DQNModel
from easy_rl.utils.window_stat import WindowStat
FLAGS = tf.f... | alibaba/EasyReinforcementLearning | demo/run_apex_agent_on_cartpole.py | run_apex_agent_on_cartpole.py | py | 4,571 | python | en | code | 188 | github-code | 13 |
72093792659 | import calculate_scores
import objects
import get_grand_prix_names
import load_config
def calculate_running_totals(current_year, display_breakdown = True):
grand_prix_names = get_grand_prix_names.get_grand_prix_names(active_year = current_year)
predictor_totals = objects.predictor_totals.PredictorTotals... | JamesScanlan/f1ftw | f1ftw/calculate_running_totals.py | calculate_running_totals.py | py | 1,323 | python | en | code | 0 | github-code | 13 |
10816186254 | # type hints
# specify the data type to be fixed (avoid dynamic typing)
age: int
name: str
height: float
is_human: bool
# : fixed the input data type
# -> fixed the output data type
def police_check(age: int) -> bool:
if age > 18:
can_drive = True
else:
can_drive = False
return can_drive
... | WOOAK/udemy-100-days-of-code-Python | Day 34/main.py | main.py | py | 484 | python | en | code | 0 | github-code | 13 |
21501081369 | import inspect
import os
import vcr
def path_generator(function):
func_dir = os.path.dirname(inspect.getfile(function))
file_name = '{}.yml'.format(function.__name__)
return os.path.join(func_dir, 'mocks', file_name)
replay = vcr.VCR(func_path_generator=path_generator)
dir_path = os.path.dirname(os.pat... | new69/mtls | test/test_setup.py | test_setup.py | py | 546 | python | en | code | 0 | github-code | 13 |
9087016503 | # standard python modules
import numpy as np
# plotting utilities
import matplotlib.pyplot as plt;import matplotlib as mpl;import matplotlib.cm as cm;import matplotlib.colors as colors;from matplotlib import rc
majortickwidth,minortickwidth,fontsize = 1.5,0.75,10
majortickwidth,minortickwidth,fontsize = 1.0,0.5,10
c... | michael-petersen/LinearResponse-paper | scripts/P23Figure4.py | P23Figure4.py | py | 8,147 | python | en | code | 0 | github-code | 13 |
35041419639 | ## Primary Author: Mayank Mohindra <github.com/mayankmtg>
##
## Description: Main file. Contains logic to handle all commands and start the bot
##
import discord
from discord.ext import commands
from search import perform_search
from config import Config
from cache import save_search_query, find_search_history
from... | mayankmtg/sample-discord-bot | bot.py | bot.py | py | 1,798 | python | en | code | 0 | github-code | 13 |
29575167563 | # pylint: disable=R0901, W0613, R0201
import logging.config
from django.conf import settings
from django.db import transaction
from drf_yasg2 import openapi
from drf_yasg2.utils import swagger_auto_schema
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.response import... | MikelTopKek/topnews | backend/rest_api/views/posts.py | posts.py | py | 3,839 | python | en | code | 0 | github-code | 13 |
18091116314 | import glob
import os
from time import time
from preprocessing import file_preprocessing
from utils import folders, initializing
# Ejecutar en Terminal la siguiente línea ANTES de ejecutar por primera vez:
# sudo chmod 777 /etc/ImageMagick-6/policy.xml
# Actualizar opciones de seguridad
initializing.initialize()
# C... | cdcaballeroa2/pdf_info | LAST_VERSION/main_first.py | main_first.py | py | 1,110 | python | es | code | 0 | github-code | 13 |
33566202009 | import json # yahoo.
import re # unicode replace.
import math # for millify.
try: # for google stockquote.
import xml.etree.cElementTree as ElementTree
except ImportError:
import xml.etree.ElementTree as ElementTree
import datetime # futures math.
import pytz # tzconv for relativetime.
# extra supybot lib... | andrewtryder/Stock | plugin.py | plugin.py | py | 29,652 | python | en | code | 1 | github-code | 13 |
43551390739 | from application import app
import database
from flask import request, jsonify
from urllib.parse import urlencode
def fetch_products_query(search_q, page, count, store=None):
if page.isnumeric() and page != "0":
page = int(page)
else:
raise ValueError("Invalid value for param page!")
if c... | gianani/ecom_api | routes.py | routes.py | py | 4,621 | python | en | code | 0 | github-code | 13 |
73645013137 |
import string
from string import punctuation
import tweepy
from tweepy import OAuthHandler
from tweepy import Stream
import json
import matplotlib.pyplot as plt
consumer_key = 'i2Eego1GgNga1ND3Oxpq2wwxm'
consumer_secret = '2bNZvOqlg7MvqQeCsqP7Ma64Gh77xCvdmlNI5Th6SmfxLELQQu'
access_token = '1373172530-UqKl5faRYzTWuYnC... | haoweichen/Web-Scraping-2 | Assignment3.py | Assignment3.py | py | 3,940 | python | en | code | 0 | github-code | 13 |
28171702911 | # Create your views here.
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from django.utils import timezone
from django.http import Http404
from polls.models import Choice, Poll
class Index... | lydiaxmm/Module5 | mysite/polls/views.py | views.py | py | 4,082 | python | en | code | 0 | github-code | 13 |
20294713204 | from coincurve import PublicKey, PrivateKey
from raiden_libs import utils
import binascii
import time
import json
trip_along_ringbahn_raw = [
{'timestamp': int(time.time()) - 10000, 'lat': {'val1': 52, 'val2': 536131},
'lon': {'val1': 13, 'val2': 447444}, 'temperature': {"val1": 19, "val2": 0}},
{'timesta... | Anylsite/anyledger-backend | signtest.py | signtest.py | py | 1,846 | python | en | code | 1 | github-code | 13 |
37314918864 | """Config module."""
import logging
from pathlib import Path
logging.basicConfig(
filename="execution_logs.log",
level=logging.INFO,
format="%(asctime)s - %(message)s",
)
DATE = "20231203"
ROOT_DIR = Path(__file__).parents[1]
DATA_DIR = ROOT_DIR / "data"
DATE_DIR = ROOT_DIR / "data" / DATE
HTML_DIR = DAT... | aingelmo/spanish-crossfit-data | src/config.py | config.py | py | 563 | python | en | code | 0 | github-code | 13 |
4547620077 | import os
import copy
import glob
import pickle
import sys
import tensorflow as tf
import numpy as np
from ray import tune
from softlearning.environments.utils import get_goal_example_environment_from_variant
from softlearning.algorithms.utils import get_algorithm_from_variant
from softlearning.policies.utils import ... | avisingh599/reward-learning-rl | examples/classifier_rl/main.py | main.py | py | 6,982 | python | en | code | 361 | github-code | 13 |
8971211903 | import os
if not os.path.isfile("config.json"):
print("config.json not found, please create one")
exit()
import json
with open("config.json", "r") as f:
IMAGE_ROOT_PATH = json.load(f)["image-path"]
import sqlite3
connection = sqlite3.connect("database.db")
cursor = connection.cursor()
cursor.row_factory =... | ManInDark/EasyDiffusionSearch | search.py | search.py | py | 1,920 | python | en | code | 0 | github-code | 13 |
18101526615 | import sys
import warnings
import torch
import torch.nn as nn
from torch.optim.lr_scheduler import ReduceLROnPlateau
from data.data import prepare_folds
from loops import train, evaluate
from utils.checkpoint import save
from utils.setup import setup_network, setup_hparams
warnings.filterwarnings("ignore")
device = ... | usef-kh/Cassava-Leaf-Disease-Classification | cv_train.py | cv_train.py | py | 2,182 | python | en | code | 0 | github-code | 13 |
22845696785 | '''
Created on Aug 9, 2012
@author: PENNETTI
'''
'''
A perfect number is a number for which
the sum of its proper divisors is
exactly equal to the number. For
example, the sum of the proper divisors
of 28 would be 1 + 2 + 4 + 7 + 14 = 28,
which means that 28 is a perfect number.
A number n is called... | pennetti/project-euler | python/Problem_023.py | Problem_023.py | py | 1,981 | python | en | code | 0 | github-code | 13 |
73254230416 | import supybot.conf as conf
import supybot.registry as registry
def configure(advanced):
# This will be called by supybot to configure this module. advanced is
# a bool that specifies whether the user identified himself as an advanced
# user or not. You should effect your configuration by manipulating th... | amirdt22/supybot-jira | JIRA/config.py | config.py | py | 1,595 | python | en | code | 1 | github-code | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.