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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
7401140866 | import cv2
import pyautogui
import time
import numpy as np
import keyboard
from sentdex import PressKey, ReleaseKey, W, A, S, D
import imutils
import threading
CHARACTER_POSITION = [190, 301]
CAPTURE_AREA = ((433, 400), (950, 893))
QUIT = False # We loop in-game until this is set to True.
ALLOWED_KEYS ... | automatingisfun/SnSSword | main.py | main.py | py | 4,620 | python | en | code | 0 | github-code | 50 |
19735161972 | import os
import pandas as pd
import numpy as np
import matplotlib
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42
matplotlib.rcParams['font.family'] = 'Arial'
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
from scipy.stats.stats import _ttest_finish
imp... | huruifeng/PD-MAP | EV/clustering/11_clusters_center_DTW.py | 11_clusters_center_DTW.py | py | 9,755 | python | en | code | 0 | github-code | 50 |
42409715469 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 19 14:00:47 2021
@author: LENOVO
"""
import pygame
import numpy as np
import random
import time
from enum import Enum
pygame.init()
class Direction(Enum):
RIGHT = 1
LEFT = 2
NONE = 3
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
font = pygame.font.SysFont('ai... | sagarkalburgi/Games | python_games/Car_game/Cargame.py | Cargame.py | py | 6,794 | python | en | code | 0 | github-code | 50 |
70865877594 | #!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import pandas as pd
import os
import sys
fileDir = sys.argv[1]
x = sys.argv[2]
y = sys.argv[3]
z = sys.argv[4]
data = pd.read_csv(fileDir, engine = 'c', float_precision = 'round_trip', dtype=np.float64)
... | jackbergus/NCL_CSC3232 | python/02_markov/plot3d_average_hitting_time.py | plot3d_average_hitting_time.py | py | 1,078 | python | en | code | 0 | github-code | 50 |
32968574047 | """
# Regular Expression:
find the pattern(string or numbers) in raw string
Methods:
- match: it will match first pattern in starts of the string
- search: it will search return single matched pattern in entire string
- findall: it will return all matched patterns in the string
- sub: whenever matches... | tiru777/pythonbatch2 | class21.py | class21.py | py | 2,370 | python | en | code | 1 | github-code | 50 |
23576460451 | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'name': 'python-mal',
'description': 'Provides programmatic access to MyAnimeList resources.',
'author': 'Shal Dengeki',
'license': 'LICENSE.txt',
'url': 'https://github.com/shaldengeki/python-mal',
'downl... | shaldengeki/python-mal | setup.py | setup.py | py | 606 | python | en | code | 16 | github-code | 50 |
2923237636 | import torch
from clustering.utils import Confusion
from sklearn.cluster import KMeans
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity as cosine
from sklearn.metrics import silhouette_score
from sklearn import preprocessing
def get_kmeans(all_features, all_labels, num_classes):
all_featu... | JiachengLi1995/UCTopic | clustering/kmeans.py | kmeans.py | py | 4,342 | python | en | code | 40 | github-code | 50 |
9435429156 | #nome do vendedor (string), salário (float) e montante total vendas (float)
"""nome = str(input())
salario = float(input())
total_vendas = float(input())
total = total_vendas*0,15
salario1 = float(total + salario)
print(f"TOTAL = R$ {salario1:.2f}")"""
nome = input()
salario = float(input())
vendas = float(input()... | irisjulia/desafios-python | desafio10.py | desafio10.py | py | 413 | python | pt | code | 0 | github-code | 50 |
5662279018 | import os
import glob
import shutil
from tqdm import tqdm
# Défini chemin des images
image_folder_path = "../../public/random_avatar/"
# Sélectionne ‘*.png’
files = glob.glob(image_folder_path + '/*.png')
# Ajoute le chemin du fichier user à la liste des fichiers à supprimer
user_file_path = "../../app/api/user/"
fi... | chambrin/random-user-generator-api | script/Generator-user/purge.py | purge.py | py | 936 | python | fr | code | 0 | github-code | 50 |
31834991871 | import random
from PIL import Image
import requests
import sys
import vlc
import time
sound_file = vlc.MediaPlayer("file:///Users/terribroughton/Desktop/pokemonmusic.mp3")
sound_file.play()
time.sleep(5)
# Delay printing
def delay_print(s):
# print one character at a time
# https://stackoverflow.com/q... | Terrib96/Pokemon-game | Projectpoke.py | Projectpoke.py | py | 2,168 | python | en | code | 0 | github-code | 50 |
41699431692 | import pygame
import os
from pygame.locals import *
import STATE
import sys
image = pygame.image.load(os.path.join('assets','hero1.png'))
image = pygame.transform.scale(image, (32, 32))
x = 0
y = 0
def take_turn():
global x, y
# check for key presses
# This is where we determine what the player does
... | gavinraym/alphaPygame | dev_temp/lab/player.py | player.py | py | 1,151 | python | en | code | 0 | github-code | 50 |
13910155274 | from pyautocad import Autocad,APoint,ACAD
import numpy as np
import pyptlist
import random
import time
acad=Autocad(create_if_not_exists=True)
def getpoint():#从cad中获得点
acad.doc.SetVariable('pdmode', 2)
n = acad.doc.Utility.GetInteger('请输入点的个数(至少3个):')
if n < 3:
acad.prompt('输入点数量有误,程序终止')
... | YU6326/YU6326.github.io | code/curvenew.py | curvenew.py | py | 2,196 | python | en | code | 6 | github-code | 50 |
26217989458 | import streamlit as st
import openai
st.set_page_config(page_title="Chat GPT", page_icon=":crown:", layout="wide")
# ---- Header ----
def main():
st.session_state.setdefault("logs", [])
if __name__ == "__main__":
main()
st.header("Chat GPT")
st.subheader("""
HI :wave:,
... | kpister/prompt-linter | data/scraping/repos/MohamedArafath205~Chat-GPT/app.py | app.py | py | 1,848 | python | en | code | 0 | github-code | 50 |
34978948199 | import socket
from fdp import ForzaDataPacket
from matplotlib import pyplot
import time
# Create a UDP socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Bind the socket to the port
server_address = ("127.0.0.1", 1010)
s.bind(server_address)
print("Do Ctrl+c to exit the program !!")
props = []
arr = []
t_m... | drosoCode/drosocode.github.io | content/posts/upgrading-your-rgb-with-wled-aurora-and-openrgb/test.py | test.py | py | 881 | python | en | code | 0 | github-code | 50 |
20974794669 | #WAP to input a number & print the reverse of a number & also print it's ones digit.
num = int(input("Enter a number: "))
rev = 0
while(num>0):
rem = num % 10
rev = (rev * 10) + rem
num = num//10
a = rev%10
print("The reverse number is : ",rev)
print("It's ones digit is : ",a)
| reyagarg13/Reya-Python-for-beginners | reverse of a number & also print it's ones digit..py | reverse of a number & also print it's ones digit..py | py | 296 | python | en | code | 0 | github-code | 50 |
18566249446 | # This function is written to get list of EC2 instances as Dictionary Object in Python
import boto3
ec2 = boto3.client('ec2',region_name="us-east-1")
ec2_dict=ec2.describe_instances()
print("ec2_dict type is",type(ec2_dict))
print("ec2_dict is",ec2_dict)
# https://boto3.amazonaws.com/v1/documentation/api/late... | pravin2610/myfirstrepo | 1a_list_ec2.py | 1a_list_ec2.py | py | 6,183 | python | en | code | 0 | github-code | 50 |
8642522026 | import bs4 as bs
import urllib.request as req
import down as manhas
length = int(input('Enter your How many video of playlist u want to downlode :'))
link = input('Enter the url of 1st video : ')#'https://www.youtube.com/watch?v=P6YJy2fmJ1o&list=RDP6YJy2fmJ1o'
name = ''
main_list = []
main_list.append(link)
list1 = ... | Monkeydluffy3/youtube-playlist-downloder | try.py | try.py | py | 1,204 | python | en | code | 2 | github-code | 50 |
2203159720 | from gui.docking import *
from gui.layout_manger import *
from gui.state_manager import *
from gui.window_manager import *
from project.project_manager import *
def entry_point():
layout_manager = LayoutManager()
settings = Settings()
app_settings = AppSettings()
project = Project()
hello_imgui.s... | AmirmohammadZarif/Artel | Engine/ArtelSlicer/main.py | main.py | py | 3,418 | python | en | code | 0 | github-code | 50 |
41642694128 | import matplotlib.pyplot as plt
import streamlit as st
import pandas as pd
from streamlit_lottie import st_lottie
import requests
import numpy as np
from sklearn import preprocessing
from sklearn.svm import SVR
import pickle
st.set_page_config(layout="wide")
def load_lottieurl(url: str):
r = requests.get(url)
... | issaiass/BDev---Abalone-Ring-Prediction | streamlit.py | streamlit.py | py | 4,307 | python | en | code | 0 | github-code | 50 |
34961777963 | from manimlib.imports import *
class lesson_1(Scene):
def construct(self):
title = TextMobject("An overview on Trigonometry")
title.scale(1)
self.play(Write(title))
self.wait(3)
self.play(FadeOut(title))
'''insert unit circle diagram'''
trig... | AjayArvind2207/YT | OverviewTrig/trig1.py | trig1.py | py | 5,651 | python | en | code | 0 | github-code | 50 |
12602492470 | import hashlib
import json
import time
import uuid
from enum import IntEnum
from typing import List, Tuple, Union
from zhixuewang.models import (BasicSubject, ExtendedList, Exam, Homework, HwAnsPubData, HwResource, HwType, Mark, StuHomework, Subject, SubjectScore,
StuClass, School, Sex, G... | SkinCrab/zhixuewang-python | zhixuewang/student/student.py | student.py | py | 25,269 | python | en | code | null | github-code | 50 |
73643328794 | import random
import sys
def game_play():
#the first choice input made by player
your_choice = input("Pick a hand form(Rock,Paper or Scissors): ")
#Possible options in the form of a list
possibilities = ["rock", "paper","scissors"]
#the computers random choice instruction
... | Bophelo11/RockPaperScissors | RockPaperScissor/main.py | main.py | py | 1,232 | python | en | code | 0 | github-code | 50 |
40121542286 | import sys
if sys.version_info < (3, 9):
import importlib_resources
else:
import importlib.resources as importlib_resources
from asdf.extension import ManifestExtension
from asdf.resource import DirectoryResourceMapping
import asdf_zarr
from .converter import ChunkedNdarrayConverter
def get_resource_mappi... | eslavich/asdf-zarr | src/asdf_zarr/integration.py | integration.py | py | 1,040 | python | en | code | 0 | github-code | 50 |
18575529987 | """EndpointStore Unit Tests."""
from __future__ import annotations
import uuid
from unittest import mock
import pytest
import requests
from proxystore.store.endpoint import EndpointStore
from proxystore.store.endpoint import EndpointStoreError
def test_no_endpoints_provided() -> None:
with pytest.raises(ValueE... | SJTU-Serverless/proxystore | tests/store/endpoint_test.py | endpoint_test.py | py | 2,438 | python | en | code | null | github-code | 50 |
43169018962 | import numpy as np
import csv
import os
import math
from collections import defaultdict
import time
import matplotlib.pyplot as plt
starttime = time.time_ns()
def Distance(Xa, Ya, Xb, Yb):#calculates the distance between 2 points with pythagoras
D = (math.sqrt((Xa-Xb)**2+(Ya-Yb)**2))
return D
pointarray = [... | youpie/AMA_2023_Group_assignment | GA2/GA2_A_kruskal.py | GA2_A_kruskal.py | py | 3,621 | python | en | code | 0 | github-code | 50 |
16440065305 | import csv
import glob
import math
import os
import pathlib
import pickle
import random
import cv2
import numpy as np
import pandas as pd
import torch
import project_utils
from cnn_transformer import build_feature_extractor, FeatureExtractorSpec, FeatureExtractorFeatures
from tag_lut import tag_count, freq_tag_lut, d... | Munroe-Meyer-Institute-VR-Laboratory/Aggression-Detection | dataloader_utils.py | dataloader_utils.py | py | 25,420 | python | en | code | 0 | github-code | 50 |
8542873671 | from tkinter import *
from PIL import Image, ImageTk
import random as rd
import copy
class PlacedImage():
def __init__(self, path, x, y, deg, height=128, width=128):
self.path = path
self.x = x
self.y = y
self.deg = deg
self.height = height
self.width = width
de... | leogummersbach/micropolis-autoplace | image_array.py | image_array.py | py | 20,410 | python | en | code | 0 | github-code | 50 |
72984219036 | from python_tsl2591 import tsl2591
import os
import subprocess
import time
import influxdb_client
from influxdb_client.client.write_api import SYNCHRONOUS
bucket = "main"
org = "Main"
token = os.environ['INFLUX_DB_TOKEN']
url = "http://34.122.138.205:8086"
client = influxdb_client.InfluxDBClient(
url=url,
to... | kmazur/plants | python/reporting/light_sensor.py | light_sensor.py | py | 1,353 | python | en | code | 0 | github-code | 50 |
72598569436 | from math import ceil
from typing import Union
from .backends import NumpyBackend, TorchBackend
from .truncator import SvdTruncator, QrTruncator, EigTruncator, QrTruncatorWithCBE
class iTEBD:
"""
Conventions:
MPS tensors, e.g. B have legs [vL, p, vR], i.e. left virtual, physical, right virtual
S matri... | Jakob-Unfried/Fast-Time-Evolution-of-MPS-using-QR | code/tebd.py | tebd.py | py | 6,404 | python | en | code | 0 | github-code | 50 |
39610267400 | import requests
import json
def api1_call():
url = "https://apigateway-econtract-staging.vnptit3.vn/auth-service/oauth/token"
payload = json.dumps({
"grant_type": "client_credentials",
"client_id": "test.client@econtract.vnpt.vn",
"client_secret": "U30nrmdko76057dz5aQvV9ug0mTsqAQy"
})
headers = {
... | huynhbaokhanh/khanhhb-vttagg | api1.py | api1.py | py | 456 | python | en | code | 0 | github-code | 50 |
4948936869 | from direct.showbase.DirectObject import DirectObject
from direct.actor.Actor import Actor
class Player(DirectObject):
def __init__(self, parent, resetMouse):
"""
It's assumed parent is render
"""
self.resetMouse = resetMouse
self.actor = Actor("panda", {"walk": "pa... | ryancollingwood/panda3d-test | player.py | player.py | py | 2,411 | python | en | code | 0 | github-code | 50 |
73821526874 | import pickle
from DataProcessing import ModuleStormReader as Msr
from DataProcessing import ModuleReanalysisData as Mre
from DataProcessing import MyModuleFileFolder as MMff
def load_data_storm_interim(types, size_crop=7, levtype='sfc', pkl_inputfile='./data/tracks.pkl', folder_data='./data/',
... | sophiegif/FusionCNN_hurricanes | DataProcessing/ModuleFeatures.py | ModuleFeatures.py | py | 4,057 | python | en | code | 20 | github-code | 50 |
16848030702 | import sys
import copy
f = open("input.txt", "r")
lines = f.readlines()
f.close()
#1 @ 912,277: 27x20
class Region:
i = 0
x = 0
y = 0
w = 0
h = 0
regions = []
for line in lines:
parts1 = [p.replace("#", "").strip() for p in line.split("@")]
r = Region()
r.i = parts1[0]
parts2 =... | torkeldanielsson/AoC_2018 | 03/program.py | program.py | py | 1,270 | python | en | code | 0 | github-code | 50 |
41800750578 | import csv
import matplotlib
import numpy as np
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from statistics import stdev
legend = []
values = []
markers = ["o", "*", "^", "h", "s", "D"]
colors = ["b", "g", "r", "c", "m", "k"]
for i in range(6):
values.append(([], []))
# Read BFI values from csv f... | WMostert1/cos700researchproject | StatisticalTests/scatter_plot.py | scatter_plot.py | py | 2,439 | python | en | code | 0 | github-code | 50 |
25564357080 | from typing import List
class Solution:
def maxProduct(self, nums: List[int]) -> int:
N = len(nums)
if N == 0:
return 0
dp_max = [0] * (N + 1)
dp_min = [0] * (N + 1)
import sys
res = 0 - sys.maxsize
dp_max[0] = 1
dp_min[0] = 1
f... | Symbolk/AlgInPy | DP/152maximum-product-subarray.py | 152maximum-product-subarray.py | py | 1,151 | python | en | code | 3 | github-code | 50 |
27339011988 | from flask import render_template, url_for
from . import main_page_bp
@main_page_bp.route("/")
def index():
template_values = {
"login_url": url_for("admin_auth.login"),
}
return render_template("admin_main_page/index.html", **template_values)
| nydkc/dkc-application | src/admin/main_page/index.py | index.py | py | 266 | python | en | code | 0 | github-code | 50 |
9874025472 | import os # importing env vars
from twitchio.ext import commands
bot = commands.Bot(
irc_token=os.environ['TMI_TOKEN'],
client_id=os.environ['CLIENT_ID'],
nick=os.environ['BOT_NICK'],
prefix=os.environ['BOT_PREFIX'],
initial_channels=[os.environ['CHANNEL']]
)
@bot.event
async def event_ready():
print(f"{os.e... | kristin1502/TheSeedling | bot.py | bot.py | py | 699 | python | en | code | 0 | github-code | 50 |
74164593754 | #!/usr/bin/env python3
import click
import tame
from tame.recipes.utils import load_traj_seg
@click.command(name='persist',
options_metavar='[options]',
short_help='persistent time')
@load_traj_seg # general input handler
@click.option('--max-dt', metavar='', default=30.0, sh... | yqshao/tame | tame/recipes/persist.py | persist.py | py | 1,301 | python | en | code | 0 | github-code | 50 |
6724325988 | import os
from flask import Flask, make_response
app = Flask(__name__)
app.config["SECRET_KEY"] = os.environ.get(
"SECRET_KEY", "secret_l801#+#a&^1mz)_p&qyq51j51@20_74c-xi%&i)b*u_dt^2=2key"
)
@app.route("/")
def boilerplate_script():
script = "git clone --quiet https://github.com/CheesecakeLabs/django-drf-bo... | fredericojordan/boilerplate-script | boilerplate.py | boilerplate.py | py | 616 | python | en | code | 0 | github-code | 50 |
10926638608 | import os
import pytest
from chess_analysis import download_pgn
from data.pgn_text import LASKER_GAME
TEST_LIVE = os.getenv("TEST_LIVE", False)
def test_get_download_url():
# Normal behavior
game_id = "112358"
filename = "johnson_lasker_1926.pgn"
expected = "https://www.chessgames.com/pgn/johnson_... | mdashx/chess-analysis | tests/test_download_pgn.py | test_download_pgn.py | py | 1,016 | python | en | code | 0 | github-code | 50 |
42547803889 |
import os.path
import yaml
# f = open(os.path.dirname(__file__) + '/../brownie-config.yml')
# print(f)
current_directory = os.path.dirname(__file__)
parent_directory = os.path.split(current_directory)[0] # Repeat as needed
parent_parent_directory = os.path.split(parent_directory)[0] # Repeat as needed
file_pat... | tonisives/ti-python-crypto-codecamp | lesson-thirteen/brownie/scripts/test.py | test.py | py | 417 | python | en | code | 0 | github-code | 50 |
34655300854 | _author_ = 'jake'
_project_ = 'leetcode'
# https://leetcode.com/problems/remove-duplicates-from-sorted-array/
# Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
# Do not allocate extra space for another array, you must do this in place with constan... | jakehoare/leetcode | python_1_to_1000/026_Remove_Duplicates_from_Sorted_Array.py | 026_Remove_Duplicates_from_Sorted_Array.py | py | 933 | python | en | code | 49 | github-code | 50 |
29543510024 | from selenium import webdriver
from selenium.webdriver.chrome.options import Options
# from bs4 import BeautifulSoup
# from extractors.wwr import extract_wwr_jobs
# base_url = "https://kr.indeed.com/jobs?q="
# search_term = "python"
# response = get(f"{base_url}{search_term}")
# if response != 200:
# print("Can't ... | kanujoa/Python_scrapper | 5. Job Scrapper/5-12 Indeed/fix403.py | fix403.py | py | 644 | python | en | code | 0 | github-code | 50 |
37960506579 | print( 'Павловська Катерина. КМ-93. Варіант №14.' )
print("Task: Make a program that determines the result of divination on the camomile - love-does not love, taking the original given number of petals n (enter from the keyboard)." )
print()
print('You are welcomed by the guessing program')
import re
re_intege... | KatePavlovska/python-laboratory | laboratory1&2update/Lab1_Task2_the_guessing_pavlovska_km_93.py | Lab1_Task2_the_guessing_pavlovska_km_93.py | py | 1,719 | python | en | code | 0 | github-code | 50 |
32173442293 | import redis
# r = redis.Redis(host='localhost', port=6379, db=1)
class Base(object):
def __init__(self):
self.r = redis.Redis(host='localhost', port=6379, db=1)
class TestZset(Base):
def test_zadd(self):
"""ZADD命令将一个或多个 member 元素及其 score 值加入到有序集 key 当中
redis.zadd('my-key', 'name1',... | huazhicai/shengxun | database/redis/test_zset_redis.py | test_zset_redis.py | py | 2,142 | python | en | code | 0 | github-code | 50 |
312517426 | #-*- python -*-
""" Syslog log observer """
from __future__ import absolute_import, division, print_function
import syslog
from zope.interface import implementer
from twisted.logger import ILogObserver
from twisted.logger import LogLevel
from twisted.logger import formatEvent
# These defaults come from the Python s... | sveinse/lumina | lumina/syslog.py | syslog.py | py | 2,053 | python | en | code | 1 | github-code | 50 |
18018347486 | from .core import Core, Settings
class Download(Core):
host = 'https://artifacts.elastic.co/downloads/beats/elastic-agent/{endpoint}'
endpoint = Settings.download_endpoint
kwargs = {
'stream': True
}
def parse_response(self, response):
self.__logger.debug('Saving file to download... | MSAdministrator/elastic-agent-setup | elastic_agent_setup/download.py | download.py | py | 608 | python | en | code | 3 | github-code | 50 |
39208639638 | #function "max()" accepts two nums & returns max of them
# function is a part of Python syntax
def max(a, b):
if a > b:
return a
else:
return b
print(max(3, 5))
print(max(5, 3))
print(max(int(input("Enter First Number: ")), int(input("Enter Second Number: "))))
| izzyward02/IFSC1202 | 06.00.10 Max.py | 06.00.10 Max.py | py | 290 | python | en | code | 0 | github-code | 50 |
23571007904 | from re import fullmatch
from copy import deepcopy
from itertools import product, chain, repeat, islice
import heapq
from math import inf
import multiprocessing
from timeit import default_timer
from board import Board
class Player:
def __init__(self, player, walls, game):
self.player = player
sel... | JovanMarkovic99/blockade-board-game | players.py | players.py | py | 31,405 | python | en | code | 0 | github-code | 50 |
26012548738 | #!/usr/bin/env python
'''Testing the server by sending logs'''
from pysyslogclient import SyslogClientRFC5424, SyslogClientRFC3164
def test_tcp_rfc3164():
client1 = SyslogClientRFC3164('127.0.0.1', 1514, proto='TCP')
client1.log('My message', program='myapp')
client1.close()
def test_tcp_rfc5424():
c... | snoozeweb/snooze_plugins | input/syslog/examples/client.py | client.py | py | 522 | python | en | code | 0 | github-code | 50 |
73741877595 | from day18 import Day18
import unittest
class TestDay18(unittest.TestCase):
def test_part1(self) -> None:
input = Day18().read_file("tests/test_day18.1.txt")
output = 4
actual = Day18.solve_part1(input)
self.assertEqual(actual, output, f"input={input}, expected={output}, actual={ac... | jimmynguyen/advent-of-code | 2017/tests/test_day18.py | test_day18.py | py | 579 | python | en | code | 0 | github-code | 50 |
31557975708 | # coding: utf-8
import sys
sys.path.append('..')
from common import config
# 在用GPU运行时,请打开下面的注释(需要cupy)
# ===============================================
# config.GPU = True
# ===============================================
from common.np import *
import pickle
from common.trainer import Trainer
from common.optimizer im... | UserXiaohu/Natrual-Language-Processing | code/ch04/train.py | train.py | py | 1,481 | python | en | code | 25 | github-code | 50 |
2483177839 | from datetime import time as d_time, timedelta as d_timedelta, timezone as d_timezone
import logging
from modules.json import Json
from modules.threading import Thread
from os.path import getmtime, isfile
from time import sleep
from typing import Union
from threading import current_thread
logger = logging.getLogger("m... | AloneAlongLife/ARK-Server-Manager-Plus_2.0 | modules/config.py | config.py | py | 7,287 | python | en | code | 2 | github-code | 50 |
70822559517 | import instance_manager as ec2_util
import boto3
sqs_client = boto3.client('sqs', region_name="us-east-1")
def get_sqs_url(client):
sqs_queue = client.get_queue_url(QueueName="Request-Queue")
return sqs_queue["QueueUrl"]
INPUT_QUEUE = get_sqs_url(sqs_client)
WEB_TIER = "i-0711d441e1e48e5b5"
#APP_TIER = "i... | akhi-uday/CSE546 | auto-scale/controller.py | controller.py | py | 2,644 | python | en | code | 0 | github-code | 50 |
9303118777 | from sys import stdin
for i in range(2, int(stdin.readline())):
flag = False
for j in range(2, i):
if (i % j) == 0:
flag = True
break
if flag is False:
print(i, end=" ")
| niranjrajasekaran/efficient-solution | prime_number.py | prime_number.py | py | 223 | python | en | code | 0 | github-code | 50 |
73383830876 | """
##############################################
Clustering analysis module
##############################################
All functions related to the clustering of poles for automatic OMA.
"""
import numpy as np
import hdbscan
from . import modal
def crossdiff(arr, relative=False, allow_negatives=False):
"""... | knutankv/koma | koma/clustering.py | clustering.py | py | 12,994 | python | en | code | 21 | github-code | 50 |
272915248 | import warnings
import os
import numpy as np
import types
from .dng import Tag, dngIFD, dngTag, DNG, DNGTags
from .defs import Compression, DNGVersion, SampleFormat
from .packing import *
from .camdefs import BaseCameraModel
class DNGBASE:
def __init__(self) -> None:
self.compress = None
self.path ... | schoolpost/PiDNG | src/pidng/core.py | core.py | py | 7,645 | python | en | code | 172 | github-code | 50 |
3768099499 | import random
import time
# Helper functions
def hit(who, times):
for _ in range(times):
card = random.choice(deck)
deck.remove(card)
who.append(card)
def total(who):
total = 0
for x in who:
if isinstance(x, int):
total += x
elif x in "JQK":
... | Roberto-Yudi/Blackjack | blackjack.py | blackjack.py | py | 5,458 | python | en | code | 0 | github-code | 50 |
23351154201 | from django.shortcuts import render
from django.contrib.auth.decorators import login_required, permission_required
from .models import EmployeeInstance, Employee
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
from django.urls import reverse
import datetime
from .forms import... | rarblack/intranet | PeopleOnBoard/views.py | views.py | py | 4,831 | python | en | code | 0 | github-code | 50 |
20613847786 | import numpy as np
import cv2
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
Image_Height=28
Image_Width=28
def get_image(name):
image= np.fromfile(str(name), dtype='uint8', sep="")
image=image.reshape([28, 28])
img_resized=cv2.resize(image,(56,56))
return img_resized
zero1=get_... | slr248/EE569 | SIFT and Bag of Words/bag_of_words.py | bag_of_words.py | py | 1,803 | python | en | code | 0 | github-code | 50 |
12907939397 | from jesse.services.db import database
from playhouse.migrate import *
from jesse.enums import migration_actions
import click
def run():
"""
Runs migrations per each table and adds new fields in case they have not been added yet.
Accepted action types: add, drop, rename, modify_type, allow_null, deny_nul... | jesse-ai/jesse | jesse/services/migrator.py | migrator.py | py | 7,706 | python | en | code | 4,933 | github-code | 50 |
16360419858 | import os
import shutil
import datetime
import torch as t
from typing import Any
from tqdm.auto import tqdm
from dataclasses import dataclass
from torch.utils.tensorboard import SummaryWriter
from Trainer import MetricsManager
@dataclass
class BaseTrainer:
optimizer: Any
model: Any
train_iter: Any
de... | zqs01/ASR_chinese_e2e | Trainer/base_trainer.py | base_trainer.py | py | 5,028 | python | en | code | 0 | github-code | 50 |
14510063048 | import random
import emoji
# def level(level , attempt):
def check_guess(user_guess , random_number , attempts , level):
run_out_guesses = False
if level == "easy":
attempts = 6
if user_guess == random_number:
print(f"You have won the game")
else:
attempts -... | tonylloyd2/coding-room | python_workspace/guessgame/guessgame_advanced.py | guessgame_advanced.py | py | 2,076 | python | en | code | 4 | github-code | 50 |
33399347917 | from PyQt4 import QtGui, uic
from windows.controllers.organization_interface.orders_adder import OrderAdder
from windows.widgets.path import ORGANiZATION_ORDERS
from models.organizations import Organizations
class OrdersView(QtGui.QWidget):
_path = ORGANiZATION_ORDERS
def __init__(self, stacked_widget, *ar... | Belyashi/LogisticTask | windows/controllers/organization_interface/orders_view.py | orders_view.py | py | 2,018 | python | en | code | 0 | github-code | 50 |
7016078014 | import time
import psycopg2
import requests
from src.utils import config
class Parser:
"""Класс для парсинга"""
def __init__(self, url: str, employer: str):
self.employer_url = None
self.url = url
self.employer = employer
def get_employers(self):
"""Метод для получения спи... | MaksimPakhomov22/Parse_Vacancies_HH.ru__SQL | src/classes.py | classes.py | py | 8,953 | python | ru | code | 1 | github-code | 50 |
23308369789 | #!/usr/bin/env python
# coding: utf-8
# In[36]:
class Queue:
inner_list = [] #que is made out of a list
top = 0 #top will point to position that next item gets inserted (back of the que)
#(initiated as zero becuz front = back = 0)
def enqueue(self, value):
... | ZachOhl/HW-6 | 2/hw6_02.py | hw6_02.py | py | 2,001 | python | en | code | 0 | github-code | 50 |
9118724663 | from kivy.app import App
from kivy.clock import Clock
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from functools import partial
class LongPress(App):
def create_clock(self, widget, touch, *args):
callback = partial(self.menu, touc... | InfinityCliff/F-150_Console | Samples/longbutpress.py | longbutpress.py | py | 1,207 | python | en | code | 7 | github-code | 50 |
69848990874 | from PIL import Image
import os
# Ruta de la carpeta que contiene las imágenes PNG y donde se guardarán las imágenes JPG
ruta_carpeta = ""
# Obtener la lista de archivos en la carpeta
archivos = os.listdir(ruta_carpeta)
# Iterar sobre los archivos en la carpeta
for archivo in archivos:
# Comprobar si el archivo ... | sitocristobal/granito | Changeextension.py | Changeextension.py | py | 920 | python | es | code | 0 | github-code | 50 |
18777169664 | from Functions import Q_table, StateRep, Reward, Qvalue, maxQ
import pandas
maxBuffer = 4
StationsNumber = 2
UtilizationDisc = 100 // 25
gamma = 0.9
alpha = 0.3
#OrderTypes = 3 # fixing the number of OrderTypes
Qdf = Q_table(maxBuffer, UtilizationDisc, StationsNumber) # initializing Q-table to our param... | neprev/DTSimioRL | Step0.py | Step0.py | py | 405 | python | en | code | 2 | github-code | 50 |
26264978378 | import os, logging
from langchain.vectorstores import SupabaseVectorStore
from langchain.embeddings import OpenAIEmbeddings
from langchain.llms import OpenAI
#https://python.langchain.com/en/latest/modules/chains/index_examples/chat_vector_db.html
from langchain.chains import ConversationalRetrievalChain
import opena... | kpister/prompt-linter | data/scraping/repos/kumar045~langchain-github/qna~question_service.py | qna~question_service.py | py | 2,033 | python | en | code | 0 | github-code | 50 |
37350414540 | # CP template Version 1.006
import os
import sys
#import string
#from functools import cmp_to_key, reduce, partial
#import itertools
#from itertools import product
#import collections
#from collections import deque
#from collections import Counter, defaultdict as dd
#import math
#from math import log, log2, ceil, floor... | TaemHam/Baekjoon_Submission | 10866/main.py | main.py | py | 2,628 | python | en | code | 0 | github-code | 50 |
9542843433 |
import smtplib
from email.utils import formataddr
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import json
def send_mail(message):
with open('vars.json') as f:
vars = json.loads(f.read())
server = smtplib.SMTP_SSL(vars['SMTPSERVER'], vars['SMTPPORT'])
... | bondyr135/legendary-octo-spork | mail_sender.py | mail_sender.py | py | 658 | python | en | code | 0 | github-code | 50 |
8958728841 | from django.shortcuts import render, redirect
from shopping.signupform import CustomUserCreationForm
#
# def signup(request):
# if request.method == 'POST':
# form = CustomUserCreationForm(request.POST)
#
# if form.is_valid():
# form.save()
# return redirect('/login/')
# ... | locallhosts/Retailshopping | shopping/signup_view.py | signup_view.py | py | 1,565 | python | en | code | 0 | github-code | 50 |
71467994716 | # -*- coding: utf-8 -*-
import re
if __name__ == "__main__":
input_str = input()
ans_str = "No"
reg_str = r"^methoo*d$"
searched_result = re.search(reg_str, input_str)
if searched_result:
ans_str = "Yes"
print(ans_str)
| ksato-dev/algo_method | 6_re/re1_2.py | re1_2.py | py | 251 | python | en | code | 0 | github-code | 50 |
27063410608 | import pandas as pd
import os
def dataframe_concat(n):
dataframe = None
for i in range(1, n + 1):
filePath = f"./label {i}.csv"
dataframe = pd.concat([dataframe, pd.read_csv(filePath, index_col=0)], ignore_index=True)
dataframe.to_csv("./final.csv")
if __name__ == "__main__":
n = len... | mmmmmcree/Project | 手势识别/Hand Landmarks data/dataframe_concat.py | dataframe_concat.py | py | 367 | python | en | code | 0 | github-code | 50 |
35713145962 | import os
import subprocess
import sys
from distutils.core import setup
from typing import List
_minimum_version = (3, 7)
if sys.version_info < _minimum_version:
raise RuntimeError('Required Python {}'.format(
'.'.join([str(i) for i in _minimum_version])
))
version = '0.1.0'
proto_pkgs = ['keymaster_... | shiroyuki/keymaster | setup.py | setup.py | py | 2,226 | python | en | code | 0 | github-code | 50 |
19723215684 | import numpy as np #version 1.9.2
import pandas as pd
#import seaborn as sns
pd.options.display.width = 0
def read_data():
data = pd.read_csv("data/admission/Admission_Predict.csv")
data.columns = data.columns.str.strip()
data.columns = data.columns.str.replace(" ", "_")
print("\n\n... | al1357/py_ml_algorithms | logistic_regression/data_admissions.py | data_admissions.py | py | 686 | python | en | code | 0 | github-code | 50 |
2415260724 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# draw_figure.py
# author: Kentaro Wada <www.kentaro.wada@gmail.com>
import sys
import pygame
screen_size = (640, 480)
pygame.init()
screen = pygame.display.set_mode(screen_size)
pygame.display.set_caption("図形の描画")
while True:
screen.fill((0,0,0))
# 図形を描画
... | wkentaro/inbox-arhive | python/game/code/draw_figure.py | draw_figure.py | py | 790 | python | en | code | 1 | github-code | 50 |
13878773848 | import traceback
from challenges.models import ChallengePhase
challenge_phases = ChallengePhase.objects.all()
try:
for phase in challenge_phases:
phase.max_submissions_per_month = phase.max_submissions
phase.save()
except Exception as e:
print(e)
print(traceback.print_exc())
| Cloud-CV/EvalAI | scripts/migration/set_monthly_submission_limit.py | set_monthly_submission_limit.py | py | 307 | python | en | code | 1,583 | github-code | 50 |
22931008479 | #_*_ coding: utf-8 _*_
#https://sshuhei.com
import json
import logging
import logging.handlers
import time
import itertools
from src import channel
from hyperopt import fmin, tpe, hp
def describe(params):
i, j, k, l, m, cost, mlMode, fileName = params
channelBreakOut = channel.ChannelBreakOut()
channelBr... | Connie-Wild/ChannelBreakoutBot | machineLearning.py | machineLearning.py | py | 6,723 | python | en | code | 199 | github-code | 50 |
12323243647 | def main():
elfCalories = []
currentSum = 0
with open("elf_calorie_list.txt", "r") as file:
for line in file:
if line != "\n":
currentSum += int(line)
else:
elfCalories.append(currentSum)
currentSum = 0
... | EwanWilliams/advent-of-code-2022 | day1/day1_puzzle2.py | day1_puzzle2.py | py | 517 | python | en | code | 0 | github-code | 50 |
27179941409 | def double_char(s):
i = 0
value = ""
while i < len(s):
value += s[i] + s[i]
i += 1
return value
def count_hi(s):
i = 0
value = 0
while i < len(s) - 1:
if "hi" == s[i] + s[i + 1]:
value += 1
i += 1
return value
def cat_dog(s):
i = 0
cv... | CreativePenguin/stuy-cs | intro-comp-sci2/python/Homework#11String-2.py | Homework#11String-2.py | py | 1,117 | python | en | code | 0 | github-code | 50 |
17575619324 | """ MTFB-CNN model from Hongli Li et al 2023.
See details at https://doi.org/10.1016/j.bspc.2022.104066
Notes
-----
The initial values in this model are based on the values identified by the authors
References
----------
Li H, Chen H, Jia Z, et al.
A parallel multi-scale time-frequency bl... | LiangXiaohan506/EISATC-Fusion | models/MTFB_CNN.py | MTFB_CNN.py | py | 10,547 | python | en | code | 2 | github-code | 50 |
21393235048 | import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
data = np.load("MUG-varyM_AllImitate_Z100_N12_n1000_beta10.npz")
P_pq_t = data["strategies"]
pay_pq_t = data["payoffs"]
M_arr = data["GroupCutoff_arr"]
print(np.shape(P_pq_t))
Pmean_pq_t = np.mean(np.mean(np.mean(
P_pq_t[:,:,-250:,:,:], axi... | anuanupapa/MUG | Z100_N12/data_plot.py | data_plot.py | py | 721 | python | en | code | 0 | github-code | 50 |
27806385996 | #!/usr/bin/env python3
import patt
import logging
import os
import tempfile
from pathlib import Path
import shutil
from string import Template
import time
logger = logging.getLogger('patt_postgres')
def log_results(result, hide_stdout=False):
patt.log_results(logger='patt_postgres', result=result, hide_stdout=hi... | unipartdigital/puppet-patt | files/patt/patt_postgres.py | patt_postgres.py | py | 12,660 | python | en | code | 1 | github-code | 50 |
30213462563 | import copy
from typing import Dict, Any, List, Tuple
import collections
from tqdm import tqdm
import torch
import torch.nn
import torch.utils.data.dataloader
from tabluence.deep_learning.data.tensorizer.single_slice.base import SingleSliceTensorizerBase
class CustomTensorizer(SingleSliceTensorizerBase):
"""
... | shayanfazeli/tabluence | tabluence/deep_learning/data/tensorizer/single_slice/custom_tensorizer.py | custom_tensorizer.py | py | 8,511 | python | en | code | 4 | github-code | 50 |
11488052446 | from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller import dpset
from ryu.controller import ofp_event
from ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER
from ryu.app.wsgi import ControllerBase, WSGIApplication, route
from ryu.controller.handler import set_ev_cls
... | ataeiamirhosein/SoftwareDefinedNet | sar_application_SDN.py | sar_application_SDN.py | py | 13,982 | python | en | code | 1 | github-code | 50 |
21852447518 | # -*- coding: utf-8 -*-
import pytest
from homology.abrams_y import the_complex
from homology.elementary_collapses import collapse_all
from homology.benchmarks.memoize import memoize
from sage.interfaces.chomp import have_chomp
assert have_chomp() is True
NS = [2, 3]
@memoize
def the_complex_(n, collapsed):
com... | langston-barrett/computational-homology | homology/benchmarks/test_elementary_collapses.py | test_elementary_collapses.py | py | 1,129 | python | en | code | 1 | github-code | 50 |
36225975709 | import os
import errno
import logging
import logging.config
import threading
import serial
import json
import time
import queue
from entities.entity import Session, engine, Base
from entities.btn import Btn
from entities.btnaction import BtnAction
from entities.action import Action
from entities.command import Command... | thatcrazygame/tiny_btn_hub | backend/src/hub.py | hub.py | py | 7,107 | python | en | code | 0 | github-code | 50 |
26636133784 | #!/usr/bin/python3.5
def find_uniq(arr):
count = {}
arr_len = len(arr)
count[arr[0]] = 0
for item in arr:
if item != arr[0]:
count[item] = 0
i = 0
while i < arr_len:
j = 0
if count[arr[i]] == 0:
while j < arr_len:
if arr[i] == ar... | PeterZhangxing/codewars | find_uniq.py | find_uniq.py | py | 658 | python | en | code | 0 | github-code | 50 |
26992725477 | # pip install pyttsx3 ; this works offline
import pyttsx3
def text_to_Speech(audio):
engine.say(audio)
engine.runAndWait()
engine = pyttsx3.init() # ----------->> object for pyttsx3 class
for voice in engine.getProperty("voices"): # ------->> To check the number of voices in system
print(voice)
... | Mansish-101M99/Python-Projects | Text-toSpeech Generator/txttospeech1.py | txttospeech1.py | py | 504 | python | en | code | 1 | github-code | 50 |
71649771356 | class Node:
def __init__(self, val=None):
self.val = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self,data):
new_node = Node(data)
new_node.next=self.head
self.head = new_node
def printList(self):
tem... | devlmhieu7521/Interview_Answering | code python/Q6.py | Q6.py | py | 893 | python | en | code | 0 | github-code | 50 |
24076609465 | import logging
from typing import List, Dict, Union
import pandas as pd
import openomics
from .clinical import (
ClinicalData,
HISTOLOGIC_SUBTYPE_COL,
PATHOLOGIC_STAGE_COL,
TUMOR_NORMAL_COL,
PREDICTED_SUBTYPE_COL,
)
from .genomics import SomaticMutation, CopyNumberVariation, DNAMethylation
from .i... | FernandoMarcon/bench | omics/open-omics/env/lib/python3.10/site-packages/openomics/multiomics.py | multiomics.py | py | 11,398 | python | en | code | 0 | github-code | 50 |
8496933853 | # web_app/routes/home_routes.py
from flask import Blueprint, render_template
from web_app.models import User
home_routes = Blueprint("home_routes", __name__)
@home_routes.route("/")
def index():
screen_names = User.query.with_entities(User.screen_name).distinct()
for screen_name in screen_names:
print... | jasimrashid/twitoff | web_app/routes/home_routes.py | home_routes.py | py | 573 | python | en | code | 0 | github-code | 50 |
24333899889 | import time
from typing import List
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
max_sum = nums[0]
curr_sum = 0
for n in nums:
if curr_sum < 0:
curr_sum = 0
curr_sum += n
max_sum = max(max_sum, curr_sum)
return... | zluo16/python-data-structures-and-algorithms | blind_75/arrays/max_sub_array.py | max_sub_array.py | py | 633 | python | en | code | 0 | github-code | 50 |
40185943580 | import FWCore.ParameterSet.Config as cms
process = cms.Process('TEST')
process.options.wantSummary = True
process.load('FWCore.MessageService.MessageLogger_cfi')
process.MessageLogger.cerr.FwkReport.reportEvery = 100 # only report every 100th event start
process.MessageLogger.cerr.enableStatistics = False # enable "... | cms-sw/cmssw | HLTrigger/HLTfilters/test/testTriggerResultsFilter_by_TriggerResults_cfg.py | testTriggerResultsFilter_by_TriggerResults_cfg.py | py | 7,494 | python | en | code | 985 | github-code | 50 |
39260960064 | # Assorted functions
import pickle
import os.path
from googleapiclient.discovery import build
def initialize_sheets():
# Get Credentials
token_path = os.path.join(os.path.dirname(
os.path.relpath(__file__)), "token.pickle")
with open(token_path, 'rb') as token:
creds = pickle.load(token)
... | jsowder/personal-django | sheets/funs.py | funs.py | py | 446 | python | en | code | 0 | github-code | 50 |
8876543996 | from flask_restx import fields, Namespace
from flask_restx.reqparse import RequestParser
from flask import request
from http import HTTPStatus
from marshmallow_sqlalchemy.fields import Nested
from datetime import datetime, timedelta
from dateutil import parser as dparser
from openapi_genclient.models import (
Oper... | jackalissimo/pipkoff | app/routes/api_v0/operations.py | operations.py | py | 3,064 | python | en | code | 0 | github-code | 50 |
11401326887 | import socket
target_host = '144.202.120.116'
target_port = 6999
for i in range(0, 1000):
# 建立一个socket对象,参数AF说明我们将使用标准ipv4地址或host,SOCK说明这将是一个TCP客户端
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接客户端
client.connect((target_host, target_port))
# 发送一些数据,发送一条信息,python3只接收btye流
prin... | Zealper/MyStudyMaterials | PythonBlackHatLearning/TCPclient.py | TCPclient.py | py | 728 | python | zh | code | 0 | github-code | 50 |
37953111765 | from typing import Dict, List, Tuple
import json
import logging
from overrides import overrides
from allennlp.common.file_utils import cached_path
from allennlp.data.dataset_readers.dataset_reader import DatasetReader
from allennlp.data.fields import Field, TextField, LabelField, SpanField
from allennlp.data.tokenize... | DFKI-NLP/DISTRE | tre/dataset_readers/semeval_2010_task_8_reader.py | semeval_2010_task_8_reader.py | py | 2,710 | python | en | code | 82 | github-code | 50 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.