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
33385097559
import threading import uuid import json import webbrowser import requests from api_clients import thangs_login_client from time import sleep from login_token_cache import set_token, get_bearer_json_file_location, get_api_token class ThangsLoginService: __GRANT_CHECK_INTERVAL_SECONDS = 0.5 # 500 milliseconds ...
physna/thangs-blender-addon
services/thangs_login_service.py
thangs_login_service.py
py
1,762
python
en
code
30
github-code
90
31085359910
import numpy as np import h5py import os from sklearn.metrics import roc_auc_score, roc_curve, auc, precision_recall_curve, average_precision_score from sklearn.metrics import mean_squared_error from sklearn.metrics import accuracy_score import torch from utils import * from model_convtrans import * torch.cuda.empty_c...
RunzeSu/DeepCAT
results.py
results.py
py
2,189
python
en
code
0
github-code
90
71866708777
Import('env', 'lib') env = env.Clone( LIBS=['corrective', lib.name], LIBPATH=['..', '.'], RPATH=lib.dir.abspath ) File([ 'Candidates.h', 'Complex.h', 'Conjunction.h', 'Disjunction.h', 'Foci.h', 'Outcome.h', 'Predicate.h', 'Predicates.h', ...
liblit/cbiexp
src/corrective-ranking/SConscript
SConscript
775
python
en
code
5
github-code
90
18259353989
import collections import sys S=collections.deque(input()) Q=int(input()) r=0 for _ in range(Q): fs=next(sys.stdin).split() T=int(fs[0]) if T==1: r^=1 else: F,C=int(fs[1])-1,fs[2] if F==r: S.appendleft(C) else: S.append(C) ans=''.join(reversed(S...
Aasthaengg/IBMdataset
Python_codes/p02756/s798998770.py
s798998770.py
py
346
python
en
code
0
github-code
90
18314593139
import sys from collections import defaultdict #+++++ def main(): n, k = map(int, input().split()) aal = list(map(int, input().split())) sss = [0]*(n+1) si=0 for i, a in enumerate(aal): si+=a-1 sss[i+1]=si%k count=0 mkl_dict=defaultdict(lambda :0) for j in range(n+1): sj=sss[j] if j-k >= 0: m...
Aasthaengg/IBMdataset
Python_codes/p02851/s277692939.py
s277692939.py
py
659
python
en
code
0
github-code
90
24178575167
import logging import tensorflow as tf import sys from graphs.builder import create_models, load_models from statistical.ae_losses import expected_loglikelihood_with_lower_bound from utils.reporting.logging import log_message def create_graph(name, variables_params, restore=None): variables_names =...
kkahloots/Generative_Models
graphs/basics/AE_graph.py
AE_graph.py
py
2,758
python
en
code
1
github-code
90
27613968784
import turtle screen = turtle.Screen() screen.setup(500,500) screen.tracer(0) screen.addshape("heart 02.gif") # register the image with the screen as a shape don = turtle.Turtle() screen1=turtle.clone() screen2=turtle.clone() screen3=turtle.clone() don.speed(200) turtle.bgcolor("black") don.shape("heart 02.gif") sc...
Farhan-Malik/python-turtle-moving-heart
main.py
main.py
py
826
python
en
code
0
github-code
90
7733001929
from cmath import log from pycardano import * import json import sys from dataclasses import dataclass, field from typing import Dict, List t = True f = False dev = f class Methods: def l(self, l, d, s): # pretty and informative logging if not dev: return dtype = type(d) try:...
34r7h/cardano-python-js
python/tx.py
tx.py
py
7,227
python
en
code
0
github-code
90
34130574570
"""Open directory of current file in explorer Usage: 1. Store in $sublime/Packages/User 2. Map to hotkey (e.g. F11) 3. Press hotkey to open explorer Tested under Windows 7, 8 and Ubuntu 12.01. """ import os import platform import subprocess import sublime_plugin mapping = {'Windows': 'explorer', ...
mottosso/sublime
plugins/open_in_explorer.py
open_in_explorer.py
py
685
python
en
code
0
github-code
90
18233965769
def to_fizzbuzz(number): if number % 15 == 0: return 'FizzBuzz' if number % 3 == 0: return 'Fizz' if number % 5 == 0: return 'Buzz' else: return str(number) # return i def main(): N = int(input()) # this list concludes "FizzBuzz", "Fizz" or "Buzz" ...
Aasthaengg/IBMdataset
Python_codes/p02712/s328907691.py
s328907691.py
py
679
python
en
code
0
github-code
90
32275633958
from random import randint from time import sleep from os import system def Upup(Up): if Up == 'X': return 0 elif Up == 'K': return 6 elif Up == 'Q': return 5 elif Up == 'J': return 4 elif Up == '10': return 3 elif Up == '9': return 2 elif Up == '8': return 1 def Downdown(Do...
Castlestar4/Sevens
theGame.py
theGame.py
py
23,464
python
en
code
0
github-code
90
18106995079
N = int(input()) A = [int(A) for A in input().split()] cnt = 0 for i in range(N): A_min = i for j in range(i, N): if A[A_min] > A[j]: A_min = j if i != A_min: t = A[i] A[i] = A[A_min] A[A_min] = t cnt += 1 for i in range(N): if i == N - 1: pri...
Aasthaengg/IBMdataset
Python_codes/p02260/s990677395.py
s990677395.py
py
392
python
en
code
0
github-code
90
43548579142
import pygame from pygame.locals import * import os import sys from RadioButton import RadioGroup from CheckBox import CheckBox from startMenu import Start class Options(object): def __init__(self, screen, infoScreen, font_op, y_offset): self.screen = screen self.infoScreen = infoScreen se...
pmcoxson/CSC450GROUP1
optionsMenu.py
optionsMenu.py
py
9,666
python
en
code
null
github-code
90
43005035055
from discord.ext import commands from discord.ext.commands.errors import CommandNotFound class CommandsEvents(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener("on_command") async def on_command_event(self, ctx): self.bot.logger.info(f'{ctx.author} used command...
Sly0511/MineMineNoMiBot
modules/events/commands.py
commands.py
py
715
python
en
code
0
github-code
90
7808760394
# -*- coding: utf-8 -*- __author__ = 'Anders Mølmen Høst' __email__ = 'anderhos@nmbu.no' """ From Book: A Primer on Scientific Programming with Python Author: Hans Petter Langtangen Editition: 5th Edition Year: 2016 Exercise 2.20: Explore what zero can be on a computer """ """ 1: Storing 1.0 as a value for eps...
anderhos/Python-exercises
src/machine_zero.py
machine_zero.py
py
749
python
en
code
0
github-code
90
20616259355
import logging import os import sqlite3 from datetime import date, datetime logger = logging.getLogger("xivstrategy.data_store") class DataStore: def __init__(self): databaseFilepath = os.path.dirname(os.path.realpath(__file__)) + '/' + 'data/mydb' self.db = sqlite3.connect(databaseFilepath, detec...
ShadoFlameX/XIV-Strategy
data_store.py
data_store.py
py
2,193
python
en
code
0
github-code
90
4717377427
n, m = map(int, input().split()) nums = [0] * (n + m + 1) ans = [] for i in range(1, n + 1): for j in range(1, m + 1): nums[i + j] += 1 max_val = max(nums) for i, v in enumerate(nums): if v == max_val: ans.append(str(i)) print(' '.join(ans))
ambosing/PlayGround
Python/Problem Solving/ETC_algorithm_problem/2-5-2 polygon.py
2-5-2 polygon.py
py
267
python
en
code
0
github-code
90
69799471016
"""Generic functions for projects in google colab. This file contains functions to load/write files in various formats. Covered formats: - json - jsonl - txt """ from typing import List, Dict, Any, Union import matplotlib.pyplot as plt import json import os def load_json_file( filepath: str ) -> List...
LucaDeGrandis/utils
scripts/generic_functions.py
generic_functions.py
py
4,159
python
en
code
0
github-code
90
35729983925
from pymongo import MongoClient import datetime client = MongoClient() db = client.test posts = db.posts post = {"author": "Mike", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"], "date": datetime.datetime.now()} return_post = posts.insert_one(post) print(return_post....
Jacob-xyb/Web_Note
02_Web数据库/001_MongoDB/003_PyMongo/01_Tutorial/005_Inserting_a_Document.py
005_Inserting_a_Document.py
py
367
python
en
code
0
github-code
90
19838591038
import torch def encode(t: torch.Tensor, dim: int = 10): """Encode a tensor with a sinusoidal positional encoding. Args: t: tensor to encode dim: dimension of the encoding Returns: encoded tensor """ # if dim % 2 != 0: # raise ValueError("dim must be even") t_di...
ShreyanshDarshan/NeuralPixels
positional_encoding.py
positional_encoding.py
py
709
python
en
code
0
github-code
90
22258733012
def solution(files, loss): answer = [] files_dict = {} temp = {} for i, v in enumerate(files): files_dict[i + 1] = v temp[i + 1] = 0 filecnt = 0 index = 1 cnt = -1 keyindex = 0 tempkeys = list(temp.keys()) while temp: cnt = cnt + 1 filecnt = filec...
JisungKim94/CodingTest
Programmers/SW인증시험.py
SW인증시험.py
py
1,511
python
en
code
0
github-code
90
34776187866
from dataclasses import dataclass from datetime import date from typing import Dict, Generator, List, Tuple from or_shifty.person import Person from or_shifty.shift import Shift Idx = Tuple[int, int, int, int] PersonShift = int @dataclass(frozen=True) class IndexEntry: idx: Idx person: Person person_shi...
Dalamar42/or-shifty
or_shifty/indexer.py
indexer.py
py
3,757
python
en
code
11
github-code
90
24623030501
import os import time import asyncio from typing import Dict, Mapping, Iterable, Optional, Any, Union, cast import aioredis import aioredis.util import redis from dragonchain import logger _log = logger.get_logger() REDIS_ENDPOINT = os.environ["REDIS_ENDPOINT"] LRU_REDIS_ENDPOINT = os.environ["LRU_REDIS_ENDPOINT"] ...
dragonchain/dragonchain
dragonchain/lib/database/redis.py
redis.py
py
14,227
python
en
code
701
github-code
90
9587444970
import torch import torch.nn as nn import numpy as np from utils.utils import AverageMeter, ProgressMeter from torch.utils.tensorboard import SummaryWriter writer = SummaryWriter() xent = nn.CrossEntropyLoss() def simclr_train(train_loader, model, criterion, optimizer, epoch, pos_dataloader): """ Train accordi...
tianyu0207/CCD
colon_local/utils/train_utils.py
train_utils.py
py
2,707
python
en
code
41
github-code
90
71832941096
from tkinter import * from pathlib import Path from tkinter import Tk, Canvas, Entry, Text, Button, PhotoImage OUTPUT_PATH = Path(__file__).parent ASSETS_PATH = OUTPUT_PATH / Path("./assets") def relative_to_assets(path: str) -> Path: return ASSETS_PATH / Path(path) window = Tk() window.geometry("568x382") w...
guneetsura/converterapppy
index.py
index.py
py
2,781
python
en
code
0
github-code
90
27704172558
import flask import time import socket import subprocess h_name = socket.gethostname() IP_address = socket.gethostbyname(h_name) app = flask.Flask(__name__) @app.route('/') def index(): Time = time.strftime("%H:%M:%S") client_port = str(flask.request.environ.get('REMOTE_PORT')) hostname = h_name host...
Parth-Works/Automation-with-Ansible
application2.py
application2.py
py
764
python
en
code
0
github-code
90
73501447657
import sys input = sys.stdin.readline n, m = map(int, input().rstrip().split()) graph = [[] for _ in range(n)] for i in range(n) : instr = input().rstrip() for c in instr: graph[i].append(int(c)) dx = [1, 0, -1, 0] dy = [0, 1, 0 ,-1] def dfs(n, m, graph, stack) : while stack : x, y = stack.pop() graph[y][...
Err0rCode7/algorithm
baekjoon/bfs_dfs/음료수얼려먹기.py
음료수얼려먹기.py
py
792
python
en
code
0
github-code
90
74330171176
import pandas as pd def preprocess(data_file, labels_file=None): features = ['reanalysis_specific_humidity_g_per_kg', 'reanalysis_dew_point_temp_k', 'station_avg_temp_c', 'precipitation_amt_mm', 'week_start_date'] df = pd.read_csv(data_file, index_col=[0, 1, 2]) df['statio...
HimashiNethinikaRodrigo/DengiAI
code/model_2_preprocess.py
model_2_preprocess.py
py
1,444
python
en
code
0
github-code
90
41921443877
import win32com.client import datetime as dt import tkinter as tk from tkinter import filedialog, simpledialog, messagebox import os import sys app_window = tk.Tk() app_window.withdraw() senders_count = 1 senders = {} if os.path.isfile("DBYD_asset_owners.csv"): with open("DBYD_asset_owners.csv") as f...
luke-twigg/scripts
DBYD Email sorter/Code/DBYD_email_sorter.py
DBYD_email_sorter.py
py
2,633
python
en
code
0
github-code
90
27365748961
def parser(result): result = result.split('\n') output = [] for line in result: line = line.split(' ') interval ='' transfer = 0 bandwith = 0 for n in range(len(line)): if(line[n] == 'sec'): interval = line[n-2][...
Anton-G-11/QA-Testing
lab7/pars.py
pars.py
py
731
python
en
code
0
github-code
90
24823725865
import re import time import urllib2 from lxml import etree from database import PrognosDB from conditions import Locations class CubanWeather(object): def __init__(self): self.weather_data = {} self.location = Locations() self.db = PrognosDB() self.db.create_connection() ...
codeshard/prognos
prognos/weather.py
weather.py
py
2,808
python
en
code
14
github-code
90
19511643056
import sys # exit() import time # sleep() import pygame from ball import Ball from paddle import Paddle from wall import Wall width = 640 height = 480 white_color = (255, 255, 255) pygame.init() def game_over(): font = pygame.font.SysFont('Arial', 72) text = font.render('Game over :(', True, white_color)...
gertoska/breakout
game.py
game.py
py
3,040
python
en
code
0
github-code
90
26045932822
from functools import wraps import json def json_io(func): @wraps(func) def dec(self, url, payload=None): if payload is not None and isinstance(payload, str): payload = json.loads(payload) return json.dumps(func(self, url, payload), indent=2) return dec class User(object): de...
JCArya/Exercism-in-Python
rest_api.py
rest_api.py
py
2,388
python
en
code
1
github-code
90
6576390697
from typing import List ''' def fourSumCount(nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int: count = 0 for i in range(len(nums1)): for j in range(len(nums2)): for k in range(len(nums3)): for l in range(len(nums4)): if nums1...
MuskanMall/leetcode
HashMaps/4sum.py
4sum.py
py
913
python
en
code
0
github-code
90
3350830610
# Creating an automated Parking lott import warnings import datetime import math import dateparser warnings.filterwarnings(action="ignore") class Two_wheeler: def __init__(self, plate): """ :rtype: object """ self.enterTime = datetime.datetime.now() self.plate = plate ...
kumar-rohan-412/Valet-Parking
Valet_Parking_Final.py
Valet_Parking_Final.py
py
6,361
python
en
code
0
github-code
90
17999120540
from kivy.app import App from kivy.config import Config from kivy.core.audio import SoundLoader from widgets import Pong from telas import TelaJogo, TelaMenu, TelaVencedor1, TelaVencedor2 from kivy.uix.screenmanager import ScreenManager # Carrega nosso arquivo de configurações Config.read("Tutoriais_Kivy_KivyMD/Jogo_p...
LivioAlvarenga/Tutoriais_Kivy_KivyMD
Jogo_pong/main.py
main.py
py
1,295
python
pt
code
1
github-code
90
4668986942
# Name: Huan-Yun Chen # soundex.py template # CSCI 4140 import sys import nltk import re # Define any global helper strings at this point # Define tuple list and mapping code to create dictionary for consonant # transformations at this point # function that takes token, transforms it into its new form, and returns ...
oliver0616/my_work2
Natural Language Processing/NLTK/Assignment/Assignment3/hw3_Chen.py
hw3_Chen.py
py
2,282
python
en
code
1
github-code
90
74025857578
import json import os from django.core.files.uploadedfile import SimpleUploadedFile from django.urls import reverse, path, include from rest_framework.test import APITestCase, URLPatternsTestCase from apps.order_app.models import Order from core import settings class OrderTests(APITestCase, URLPatternsTestCase): ...
kaidenvlr/onedev-tz
apps/order_app/tests.py
tests.py
py
3,311
python
en
code
0
github-code
90
27693240474
from basic.collection.queue_ import Queue from basic.collection.tree import Node def preorder_serialize(head=None): if not head: return '#' return str(head.val) + ',' + str(preorder_serialize(head.left)) + \ ',' + str(preorder_serialize(head.right)) def inorder_serialize(head=None, res...
xyzacademic/LeetCode
basic/BinaryTree/preorder_serialize.py
preorder_serialize.py
py
1,619
python
en
code
0
github-code
90
22242138316
import json import time from classes.functions import Functions class Trudy: def __init__(self, neo): self.neo = neo self.functions = Functions() def Trudy(self, username): self.functions.createTaskData('Trudy', username) if time.time() - float(self.functions.lastRun('Trudy', u...
MajinClraik/Multi-Tool
classes/trudy.py
trudy.py
py
1,384
python
en
code
0
github-code
90
32658800096
# -*— coding:utf-8 -*- import asyncio import json import aioamqp from anquant.tasks import LoopTask, SingleTask from anquant.utils import logger from anquant.utils.locker import async_method_locker class Event: def __init__(self, name=None, exchange=None, queue=None, routing_key=None, pre_fetch_count=1, data=No...
Ansore/anquant
anquant/event_engine.py
event_engine.py
py
8,462
python
en
code
0
github-code
90
33168638638
""" @author: yigit.yildirim@boun.edu.tr """ from tkinter import * from world import World # Window-related stuff begins # initializing root root = Tk() root.title("Contagion") root.resizable(False, False) # initializing canvas canvas = Canvas(root, width=1000, height=500) canvas.pack() root.update_idletasks() # W...
yildirimyigit/ds-p4ai
oop/contagion/contagion.py
contagion.py
py
468
python
en
code
0
github-code
90
18297632689
n,m=map(int,input().split()) a=list(map(int,input().split())) for i in range(n):a[i]*=-1 a.sort() from bisect import bisect_left,bisect_right def check(mid): mm=0 for i in range(n): if -(a[i]+a[0])<mid:break mm+=bisect_right(a,-(mid+a[i])) return mm ok=0 ng=10**10+7 while ng!=ok+1: mid=(ok+ng)//2 if c...
Aasthaengg/IBMdataset
Python_codes/p02821/s208865293.py
s208865293.py
py
534
python
en
code
0
github-code
90
35612990530
import sys from time import sleep import pygame from settings import Settings from game_stats import GameStats from ship import Ship from bullet import Bullet from alien import Alien from button import Button from scoreboard import Scoreboard class AlienInvasion: """Overall class to manage game assets and behavi...
quantenmagier/Carls_studies-electric_boogalo
main.py
main.py
py
10,016
python
en
code
2
github-code
90
17874371797
from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth.decorators import login_required import datetime from.models import Product, Sell, Order from .forms import FormInventoryAdd, FormSellCustomer, FormSellOrder from django.contrib.auth import logout # Create you...
Rono-Koushique/Inventory-records-manager
techdorbesh/database/views.py
views.py
py
7,001
python
en
code
1
github-code
90
18224647606
from twisted.internet.defer import Deferred from crow2.events.hook import Hook from crow2.events.yielding import yielding from crow2.util import AttrDict def test_simple(): """ "Simple" test of yielding """ hook1 = Hook() hook2 = Hook() @hook1 @yielding def handler(event): "yi...
lahwran/crow2
crow2/events/test/test_yielding.py
test_yielding.py
py
2,479
python
en
code
1
github-code
90
17521032380
import sys import os sys.path.append(os.path.abspath('.')) from hotword_detection import mfcc import numpy as np def test_mfcc_first_coefficient(): temp = mfcc.MFCC() no_of_test = 100 input_matrix = np.random.random_sample((no_of_test,200)) def first_coeff_greater_than_0(x): ...
sakethgsharma/HotWordDetection
hotword_detection/test/test_mfcc.py
test_mfcc.py
py
995
python
en
code
27
github-code
90
34872508690
import gzip import io import os from pathlib import Path import subprocess import sys import tarfile import textwrap import time import zipfile import numpy as np import pytest from pandas.compat import is_platform_windows import pandas as pd import pandas._testing as tm import pandas.io.common as icom @pytest.ma...
pandas-dev/pandas
pandas/tests/io/test_compression.py
test_compression.py
py
12,343
python
en
code
40,398
github-code
90
25209840398
from io import StringIO import sys import streamlit as st from krr_system import ( TimeDomainDescription, Fluent, Scenario, ) # to be deleted when TimeDomainDescription.description() will return value instead of print class Capturing(list): def __enter__(self): self._stdout = sys.stdout ...
GiveMeMoreData/krr_system
app.py
app.py
py
24,950
python
en
code
0
github-code
90
7563359696
import sys import os folder = sys.argv[1] extension_count = {} longest = "" shortest = "" second_c = "" # use os.walk to get all files in the folder for _, _, files in os.walk(folder): print(files) # get longest name, shortes, first file with seond letter c longest = files[0] shortest ...
nicolaee2/python-lab
main/4.py
4.py
py
1,275
python
en
code
0
github-code
90
37658848504
from pycipher import Caesar #!pip install pycipher def cipher(message, offset): encrypted_message = Caesar(key=offset).encipher(message) print(f"{message} encrypted with the Caesar cipher with an offset of {offset}: ") print(encrypted_message) my_message = input("Enter message to encrypt: ") my_offset =...
mit-dci/Oct-19-members-week
cipher.py
cipher.py
py
384
python
en
code
0
github-code
90
18344452139
# LRRRRRRL, LRL は同じ(不幸な人は3人) # L, R で分割してやると一回の操作でLRL -> LLL -> で不幸な人が2人へる LR の時は LLで1人減る n, k = list(map(int, input().split(' '))) s = input() # LLRRRLL -> 1,1,1に変換して合体させていく old = '' converted = [] for c in s: if old != c: converted.append(1) old = c temp = max(len(converted) - 2*k, 1) # 必ず一人は犠牲に...
Aasthaengg/IBMdataset
Python_codes/p02918/s244071513.py
s244071513.py
py
460
python
ja
code
0
github-code
90
10885959002
import streamlit as st import pandas as pd import numpy as np from streamlit_folium import folium_static from utils import ( get_folium_map, add_dc_markers, get_nearsest_dc, get_initial_map, get_initial_map_opt, ) from config import dc_lat_lng, dc_colors, capacity_grid_options, dc_capacity from st_a...
chakra1166/s2p-route-opt
main.py
main.py
py
5,542
python
en
code
0
github-code
90
42985852816
from math import * t=int(input()) def solve(n): sum=0.0 if n %2==1: for i in range(1,n+1,2): sum += (1.0/i) else: for i in range(2,n+1,2): sum += (1.0/i) # lamf tròn đến 6 chữ số phần thập phân print('{:.6f}'.format(sum)) while t >0: n=int(input()) ...
nguyenkien0703/python_ptit
PY01036.py
PY01036.py
py
350
python
vi
code
0
github-code
90
2438899006
import json import handler.TransformClickHouseData as TCH class AppLambdaDelegate: def __init__(self, **kwargs): for key, val in kwargs.items(): setattr(self, key, val) def exec(self): event = self.event event = json.loads(event.get("Records")[0].get("body")) reco...
PharbersDeveloper/phlambda
deprecated/phtransformschema/src/delegate/AppLambdaDelegate.py
AppLambdaDelegate.py
py
804
python
en
code
0
github-code
90
19646907102
from aiokafka import AIOKafkaConsumer import asyncio from pydantic import BaseSettings try: from dotenv import load_dotenv except ImportError: pass else: load_dotenv() class Settings(BaseSettings): KAFKA_HOST: str KAFKA_PORT: int settings = Settings() async def consume(): consumer = AIOK...
Vitaliy3000/python_advanced_tutorial
Asynchrony/consumer.py
consumer.py
py
900
python
en
code
0
github-code
90
9037630408
import serial def validHeartRateValue(heart_rate): if heart_rate < 90 or heart_rate > 150: return True return False def validSpo2Value(spo2): if spo2 < 100 and spo2 > 40: return True return False def getMaxValues(heart_rate_values, spo2_values): max_heart_rate = max(heart_rate_...
GabrielRodriguesDeveloper/Pulse-Oximeter-Telegram-Bot-Python
values.py
values.py
py
1,647
python
en
code
0
github-code
90
25908702552
# File: lab7.py # Author: Edward Hanson # Date: 10/13/2015 # Section: 18 # E-mail: ehanson1@umbc.edu # Description: def main(): items = ["shoes", "socks", "hat", "belt", "blouse", "dress", "tie"] prices = [ 54.99, 7.11, 6.49, 22.58, 21.73, 38.99, 14.83] LISTLENGTH = 7 cash...
Rudedaisy/CMSC-201
Labs/lab7/lab7.py
lab7.py
py
1,158
python
en
code
0
github-code
90
18476081909
n=int(input()) lim_keta=len(str(n)) def dfs(keta,num): if int(num)<=n and len(set(num))==3: global cnt cnt+=1 if keta==lim_keta: return for i in '753': dfs(keta+1,num+i) cnt=0 for i in '753': dfs(1,i) print(cnt)
Aasthaengg/IBMdataset
Python_codes/p03212/s316989574.py
s316989574.py
py
241
python
en
code
0
github-code
90
18151059969
from collections import deque N, M = [int(x) for x in input().split()] route = {int(x): [] for x in range(N)} for _ in range(M): a, b = [int(x) - 1 for x in input().split()] route[a].append(b) route[b].append(a) queue = deque() queue.append(0) all_town = set([int(x) for x in range(N)]) result = 0 while...
Aasthaengg/IBMdataset
Python_codes/p02536/s564784660.py
s564784660.py
py
601
python
en
code
0
github-code
90
23641088961
from django.urls import reverse from django.views.generic import FormView from barriers.forms.statuses import BarrierChangeStatusForm from .mixins import BarrierMixin class BarrierChangeStatus(BarrierMixin, FormView): template_name = "barriers/edit/status/change.html" form_class = BarrierChangeStatusForm ...
uktrade/market-access-python-frontend
barriers/views/statuses.py
statuses.py
py
1,191
python
en
code
5
github-code
90
6045320215
from gillespie_simple import * from pathlib import Path # Concentrations conc_init_prey = 4 # M conc_init_hunter = 10 # M # Fake volume vol = 10**(-21) # L # Initial counts no_init_prey = int(conc_init_prey * vol * AVOGADRO) no_init_hunter = int(conc_init_hunter * vol * AVOGADRO) print("Initial no prey: %d" % no_in...
smrfeld/gillespie-simple-python
examples/lotka_volterra/main.py
main.py
py
991
python
en
code
0
github-code
90
33235269858
# %% import os import numpy as np import pandas as pd from sklearn.datasets import make_classification from sklearn.datasets import make_regression from sklearn.preprocessing import StandardScaler from sklearn.decomposition import KernelPCA from sklearn.neighbors import KNeighborsClassifier from sklearn.neighbors impor...
gmcmacran/semi_supervised
code/run sim.py
run sim.py
py
7,350
python
en
code
0
github-code
90
29066735651
""" from src.glcm_old import horizontal_glcm, vertical_glcm, diagonal_glcm g = horizontal_glcm("cropped/lighthouse/lighthouse_crop14.png") h = vertical_glcm("cropped/lighthouse/lighthouse_crop14.png") m = diagonal_glcm("cropped/lighthouse/lighthouse_crop14.png") for i in range(10): s = "" for j in range(10):...
Black3800/chasjp
src/test_glcm.py
test_glcm.py
py
1,064
python
en
code
0
github-code
90
27925944311
from .plugin import Plugin class Monitor(Plugin): def __init__(self, running_average=True, epoch_average=True, smoothing=0.7, precision=None, number_format=None, unit=''): if precision is None: precision = 4 if number_format is None: number_format = '.{}f'...
sibozhang/Text2Video
venv_vid2vid/lib/python3.7/site-packages/torch/utils/trainer/plugins/monitor.py
monitor.py
py
2,292
python
en
code
381
github-code
90
21815216487
from dataclasses import dataclass @dataclass(order=True, frozen=True) class Size: width: int = 800 height: int = 680 max_content_width = width - 20 @dataclass(order=True, frozen=True) class Position: screen_x: int = int(Size().width / 2) screen_y: int = int(Size().height / 2 - 41) screen_hid...
vagabondHustler/subsearch
src/subsearch/gui/resources/config.py
config.py
py
1,612
python
en
code
27
github-code
90
42618431013
from typing import Dict, Any #The strip() method removes any leading (spaces at the beginning) and trailing (spaces at the end) characters (space is the default leading character to remove) biografy: https://www.w3schools.com/python/ref_string_strip.asp #Por eso lo usaremos para eliminar los espacios :) class Analizado...
Dlassoc/Ejercicio_Eventos
Ejercicio.py
Ejercicio.py
py
1,312
python
pt
code
0
github-code
90
1018302015
class Conversion: def convertntegertoromannumeral(self, integerinput): numerals = { 1: "I", 2: "II", 3: "III", 4: "IV", 5: "V", 6: "VI", 7: "VII", 8: "VIII", 9: "IX", 10: "X" } ...
MorphX2/convertIntegerToRomanNumeral
convertIntegerToRomanNumeral.py
convertIntegerToRomanNumeral.py
py
657
python
en
code
0
github-code
90
25263707802
from common import * from functools import reduce def draw(t=0, **kwargs): s=np.array((2048,2048)) y,x=meshgrid_euclidean(s) pts=[] for (r,n,o) in ((0,1,0),(0.2+0.12*math.sin(t*0.03),3,0.001*t+math.pi/6),(0.4+0.3*math.sin(0.34+0.0174*t),6,math.sin(0.4+0.0042*t)*math.pi)): for a in range(n): ...
fferri/geometric_patterns
video2.py
video2.py
py
741
python
en
code
9
github-code
90
17960876969
from collections import defaultdict a = input() len_a = len(a) ans = 1 + len_a*(len_a-1)//2 d = defaultdict(int) for ai in a: d[ai] += 1 for key,val in d.items(): ans -= val*(val-1)//2 print(ans)
Aasthaengg/IBMdataset
Python_codes/p03618/s100969303.py
s100969303.py
py
207
python
en
code
0
github-code
90
14393998840
# Libs import machine import utime import neopixel import gc # region Color ''' Color Aufabe: Save RGB Color Func GetRGB | None | list[R:int, G:int, B:int] Func SetRGB | Write RGB | None ''' class Color(): def __init__(self, r, g, b): self.R = r self.G = g self.B = b def GetRGB(sel...
chaosmac1/projektsoundvisual
main.py
main.py
py
36,493
python
en
code
0
github-code
90
18038709429
s = input() n = len(s) i = n while i > 0: if i >= 7 and s[i-7:i] == 'dreamer': i -= 7 elif i >= 5 and s[i-5:i] == 'dream': i -= 5 elif i >= 6 and s[i-6:i] == 'eraser': i -= 6 elif i >= 5 and s[i-5:i] == 'erase': i -= 5 else: print('NO') exit() print('...
Aasthaengg/IBMdataset
Python_codes/p03854/s459456800.py
s459456800.py
py
325
python
en
code
0
github-code
90
39227476197
# -*- coding: utf-8 -*- """ Created on Mon Feb 23 09:02:21 2015 @author: adelpret q.shape""" import matplotlib.pyplot as plt import numpy as np import plot_utils as plut from hrp2_motors_parameters import k_d, k_p, k_tau, k_v FOLDER_ID = 5 EST_DELAY = 40 """ delay introduced by the estimation in number of samples "...
stack-of-tasks/sot-torque-control
python/dynamic_graph/sot/torque_control/identification/pos_ctrl/compress_stairs_data.py
compress_stairs_data.py
py
8,970
python
en
code
8
github-code
90
72208054378
""" 编写一个算法来判断一个数 n 是不是快乐数。 “快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。如果 可以变为  1,那么这个数就是快乐数。 如果 n 是快乐数就返回 True ;不是,则返回 False 。   示例: 输入:19 输出:true 解释: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1 """ class Solution: def isHappy(self, n: int) -> bool: def ...
Asunqingwen/LeetCode
每日一题/快乐数.py
快乐数.py
py
1,231
python
zh
code
0
github-code
90
73873941417
# Standard Library import random import traceback # 3rd Party import docker import pybreaker import requests from flask import current_app # Fastlane from fastlane.worker.errors import NoAvailableHostsError class DockerPool: def __init__(self, docker_hosts): self.docker_hosts = docker_hosts sel...
fastlane-queue/fastlane
fastlane/worker/docker/pool.py
pool.py
py
3,559
python
en
code
49
github-code
90
18289081179
from collections import deque H, W = map(int, input().split()) maze = [list(input()) for i in range(H)] XY = [(-1, 0), (1, 0), (0, 1), (0, -1)] t_max = 0 for i in range(H): for j in range(W): step = [[0]*W for _ in range(H)] visited = [[False]*W for _ in range(H)] queue = deque([(i, j)]) ...
Aasthaengg/IBMdataset
Python_codes/p02803/s610727198.py
s610727198.py
py
827
python
en
code
0
github-code
90
9974014026
# -*- coding: utf-8 -*- # Auther : jianlong from animal.cat import cat from animal.dog.dog import dog import time from test1 import test1 from test.second import second_test from test.alist import alit def upper(str): result = '' try: result = str.upper() except Exception as e: print("程序出错...
jianlongIT/python_test
pythonlearn/test2.py
test2.py
py
499
python
en
code
0
github-code
90
73521622697
from django.contrib.auth import get_user_model from djoser.views import UserViewSet from rest_framework import mixins, status, viewsets from rest_framework.generics import get_object_or_404 from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response from users.models import ...
OlegZhigulin/foodgram-project-react
backend/foodgram/users/views.py
views.py
py
2,426
python
en
code
0
github-code
90
32661312631
import json import pickle import logging from collections import defaultdict from typing import Any, Dict, List, Iterable, Text from overrides import overrides import torch from allennlp.data.fields import ( MetadataField, TextField, IndexField, ListField, ) from allennlp.data.dataset_readers.dataset...
allenai/data-efficient-finetuning
attribution/p3_jsonl_reader.py
p3_jsonl_reader.py
py
4,866
python
en
code
27
github-code
90
28839287921
#!/usr/bin/env python3 import sys import urllib.parse infn = sys.argv[1] data = open(infn).readlines() grep_v_in_l = [ 'Copyright owners', 'Ad revenue', 'Content found during', 'some territories', 'cannot be monetized', 'Copyright owner', 'On behalf', 'GmbH', 'LLC', 'Content ...
npinto/dotfiles
utils/.utils/yt-tracklist-clean.py
yt-tracklist-clean.py
py
1,370
python
en
code
10
github-code
90
8583862455
## @package app.wh_freq_app from app.app import App from ui.wh_freq_app.main_window import MainWindow ## Handles startup for the WH Question app. class WhFreqApp(App): ## Constructor # @param self def __init__(self): super(WhFreqApp, self).__init__( 'wh_freq_app', App.APP_T...
babylanguagelab/bll_app
wayne/app/wh_freq_app.py
wh_freq_app.py
py
509
python
en
code
0
github-code
90
36318187395
import sys import optparse from optparse import Option, BadOptionError from trigger.cli import cmdoptions from trigger.cli.cmdparser import ConfigOptionParser, UpdatingDefaultsHelpFormatter, parse_opts from trigger.cli.utils import get_prog, get_userinput_boolean,is_true from trigger.log import Logger from trigger.tri...
weiwongfaye/python_cli_template
trigger/cli/commands.py
commands.py
py
6,453
python
en
code
0
github-code
90
1699089750
""" high level Api """ import asyncio import datetime as dt import logging from itertools import product from typing import Dict from typing import List from typing import Optional from typing import Tuple import pandas as pd from .enums import ErrorBehaviour from .enums import SecurityIdType from .errors import Bloo...
rockscie/async_blp
async_blp/async_blp.py
async_blp.py
py
11,272
python
en
code
13
github-code
90
42039518730
""" Given a directed acyclic graph, with n vertices numbered from 0 to n-1, and an array edges where edges[i] = [fromi, toi] represents a directed edge from node fromi to node toi. Find the smallest set of vertices from which all nodes in the graph are reachable. It's guaranteed that a unique solution exists. Notice ...
nilay-gpt/LeetCode-Solutions
graphs/min_nodes_to_visit_all.py
min_nodes_to_visit_all.py
py
1,064
python
en
code
2
github-code
90
13680901281
import numpy as np import csv def get_train_data_for_class(train_X,train_Y,class_label): class_X = np.copy(train_X) class_Y = np.copy(train_Y) class_Y = np.where(class_Y == class_label,1,0) return class_X,class_Y def import_data(): X = np.genfromtxt("train_X_lg_v2.csv",dtype=np.float128,delimiter ...
shubh-cmd/ML-algorithm
logistic_regression/train.py
train.py
py
2,539
python
en
code
0
github-code
90
28890045538
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue May 15 13:38:27 2018 @author: eo """ import cv2 import numpy as np from functools import partial class FrameLab: def __init__(self, name="Unnamed Frame Processor"): # Name this object to use for plotting/feedback sel...
EricPacefactory/eolib
legacy/framelab_legacy.py
framelab_legacy.py
py
81,129
python
en
code
0
github-code
90
21396394329
# -*- coding: utf-8 -*- #2017/10/27 CRP_assignment.py : CRPにおけるテーブル数と着席客数をグラフで表す import random as rm import matplotlib.pyplot as plt from collections import Counter def chinese_restaurant_process(num_customers, alpha): if num_customers <= 0: return [] table_assignments = [1] # first customer sits at table 1 ...
KanaOzaki/Nonparametric
CRP_assignment.py
CRP_assignment.py
py
1,651
python
en
code
0
github-code
90
25525407138
from flask import request from app import app from app.db import postgre from app.utils import wrappers, logger logger = logger.Logger(__name__) def sendFeedback(): logger.info("API Handler feedback/send") try: message = request.json['message'] except Exception: return { ...
codingjerk/ztd.blunders-web
app/api/feedback/send.py
send.py
py
567
python
en
code
0
github-code
90
17950103520
import requests import json from codes import * def geoCodeLocation(inputString): location = inputString.replace(" ","+") url = ('https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=%s'% (location, google_api_key)) content = requests.get(url) result = content.json() if (result['status...
ivandodo/lesson2
geocode.py
geocode.py
py
1,710
python
en
code
0
github-code
90
73501449577
import sys input = sys.stdin.readline # 다익스트라는 바로 연결되어 있는 값 중에서 최단 경로를 선택하는 알고리즘이였다면, # 플로이드 워셜 알고리즘은 현재의 노드를 통해서 갈 수 있는 최단 경로를 업데이트 하는 방식이다. # a 에서 b로 가는 값을 선택할 때, a에서 b로 바로 갈 수 있는 값과 k노드를 통해 a에서 k와 k에서 b를 통해 가는 방식 중 최소 값을 선택한다. # 점화식을 통해 모든 경로를 해보기 때문에 O(n^3)의 시간복잡도를 갖는다. # 2차원 배열을 선언하여 a에서 b로 가는 INFINITE 값으로 초기화하고...
Err0rCode7/algorithm
baekjoon/dijkstra_graph/floyd-warshall.py
floyd-warshall.py
py
1,565
python
ko
code
0
github-code
90
14289069923
#!/usr/bin/env python3 import subprocess import logging # Configure logging logging.basicConfig(level=logging.INFO, filename='railway_logs.txt', filemode='w', format='%(asctime)s - %(levelname)s - %(message)s') # Create a logger instance logger = logging.getLogger('RailwayLogger') # Stream logs ...
eastcoreesolis/railwaystreamlogs
test.py
test.py
py
948
python
en
code
0
github-code
90
11173899370
from django.conf import settings from mongoengine import MultipleObjectsReturned, DoesNotExist from dms.models import UserProfile __author__ = 'asseym' def get_profile(phone): return _mobile_user(phone) def _mobile_user(phone): char_index = settings.NUMBER_OF_CHARS_IN_PHONE_NUMBER try: if len(ph...
unicefuganda/necoc
dms/utils/user_profile_utils.py
user_profile_utils.py
py
1,903
python
en
code
1
github-code
90
72017890857
# -*- coding: utf-8 -*- """Server for the Raspi Webapp """ import sys import os import signal import json as j import time from sanic import Sanic from sanic.response import json from sanic.response import file import src.raspi.webapp.mw_adapter_server as mw_adapter_server from src.raspi.lib import zmq_ack from src.ra...
Inux/pren
src/raspi/webapp/server.py
server.py
py
6,047
python
en
code
1
github-code
90
17853233852
#Escriba un programa que pida un número de jugadores y tire un dado para cada jugador. import random #importamos la librería random cant_jugadores = int(input("Ingrese la cantidad de jugadores: ")) if (cant_jugadores <= 0) : print ("Cantidad de jugadores errónea") else : for i in range(cant_jugadores) : ...
EmiSchonhals1/Mi-ruta-de-aprendizaje-de-Python
xx MiniJuegos xx/1_dado_x_jugador.py
1_dado_x_jugador.py
py
432
python
es
code
0
github-code
90
19199194178
import matplotlib.pyplot as plt ## Ploting Rotas and Polo def plot_polo_rotas(rotas_geo, polo_geo, title=''): ax = rotas_geo.plot(color='red', alpha=1, edgecolor='k') polo_geo.plot(ax=ax, color='green', alpha=0.5) plt.title(title) plt.show() def plot_only_rotas(rotas_geo, title=''): ...
rodrigoelemesmo/posicionador
posicionador/utils.py
utils.py
py
414
python
en
code
0
github-code
90
3311454235
import numpy as np import matplotlib.pyplot as plt # Behaviour of kron # >>> np.kron([1,10,100], [5,6,7]) # array([ 5, 6, 7, 50, 60, 70, 500, 600, 700]) # >>> np.kron([5,6,7], [1,10,100]) # array([ 5, 50, 500, 6, 60, 600, 7, 70, 700]) def codeSignal(inVal, chipLen): # make ten copies of the signal...
e2choy/dsp
code_signal.py
code_signal.py
py
942
python
en
code
0
github-code
90
14497391676
import numpy as np from neuron import h class ArtificialCell: def __init__(self, event_times): # Convert event times into nrn vector self.nrn_eventvec = h.Vector() self.nrn_eventvec.from_python(event_times) # load eventvec into VecStim object self.nrn_vecstim = h.VecStim()...
jasmainak/netcon_bug
debug.py
debug.py
py
2,195
python
en
code
0
github-code
90
40946614929
""" Machine shop example Covers: - Interrupts - Resources: PreemptiveResource Scenario: A workshop has *n* identical machines. A stream of jobs (enough to keep the machines busy) arrives. Each machine breaks down periodically. Repairs are carried out by one repairman. The repairman has other, less important ...
adarshanand67/CS415-Modelling-and-Simulations
simpy docs/machine_shop copy.py
machine_shop copy.py
py
4,477
python
en
code
0
github-code
90
18463640659
import numpy as np s = np.array(list(input())) t = np.array(list(input())) dp = np.zeros((len(s)+1, len(t)+1), dtype=int) equal = s[:, None] == t[None, :] for i in range(len(s)): dp[i+1, 1:] = np.maximum(dp[i, :-1]+equal[i], dp[i, 1:]) dp[i+1] = np.maximum.accumulate(dp[i+1]) i = len(s) j = len(t) ans = [] ...
Aasthaengg/IBMdataset
Python_codes/p03165/s940347275.py
s940347275.py
py
522
python
en
code
0
github-code
90
1849049256
import sys input = sys.stdin.readline dp = [[0 for i in range(30)] for j in range(30)] def binomial(n,k): if n==k or k==0: return 1 if dp[n][k] != 0: return dp[n][k] dp[n][k] = binomial(n-1,k-1)+binomial(n-1,k) return dp[n][k] T = int(input()) for _ in range(T): N,M = map(int, in...
GANGESHOTTEOK/yaman-algorithm
07_DP/AN/BOJ1010.py
BOJ1010.py
py
359
python
en
code
2
github-code
90