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
14345356618
A = {} def readd(name_file): with open(name_file, encoding='utf-8') as f: lines = f.readlines() len_lin = len([l for l in lines if l.strip(' \n') != '']) A[name_file] = len_lin readd("1.txt") readd("2.txt") readd("3.txt") #print(A) sorted_tuple = sorted(A.items(), key=lambda x: x[1]) sorted_tu...
fearlesshawk/homework-text
texts.py
texts.py
py
788
python
ru
code
0
github-code
36
70427123945
def outer_function(): num = 20 def inner_function(): global num num = 30 print("Before calling inner_function(): ", num) inner_function() print("After calling inner_function(): ", num) outer_function() print("Outside both function: ", num) import random print(random.randra...
asu2sh/dev
Python/main.py
main.py
py
22,131
python
en
code
3
github-code
36
3102977676
import json import os from flask import Flask, render_template, request import tensorflow as tf from tensorflow.contrib import predictor os.environ['CUDA_VISIBLE_DEVICES']='0' app = Flask(__name__) print("# Load lm model...") config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False) config.gpu_opt...
flyliu2017/mask_comments
data_process/lm.py
lm.py
py
766
python
en
code
0
github-code
36
73435227303
"""setup.py file.""" import uuid from setuptools import setup, find_packages try: # pip >=20 from pip._internal.network.session import PipSession from pip._internal.req import parse_requirements except ImportError: try: # 10.0.0 <= pip <= 19.3.1 from pip._internal.download import PipSes...
ixs/napalm-procurve
setup.py
setup.py
py
1,391
python
en
code
21
github-code
36
17744150099
import sys import argparse import pdb import os import time import getpass import yaml import random import string from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler from parse_rest.connection import register from parse_rest.datatypes import Object from parse_rest.query im...
mkhairul/codeMonitor
src/agent.py
agent.py
py
4,886
python
en
code
1
github-code
36
36919269029
from __future__ import unicode_literals, division, absolute_import, print_function import logging import base64 import inspect import re import enum import sys import textwrap import time from datetime import datetime, timezone, timedelta from typing import Callable, Tuple, Optional from asn1crypto import x509, keys,...
mongodb/mongo
src/third_party/mock_ocsp_responder/mock_ocsp_responder.py
mock_ocsp_responder.py
py
23,898
python
en
code
24,670
github-code
36
15369619842
from contextlib import contextmanager from typing import Union from apiens.error import exc from .base import ConvertsToBaseApiExceptionInterface @contextmanager def converting_unexpected_errors(*, exc=exc): """ Convert unexpected Python exceptions into a human-friendly F_UNEXPECTED_ERROR Application Error ...
kolypto/py-apiens
apiens/error/converting/exception.py
exception.py
py
1,528
python
en
code
1
github-code
36
41824110115
from pandas.io.parsers import read_csv from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter import numpy as np def carga_csv(file_name): """carga""" valores = read_csv(file_name, header=None).values ...
nesi73/AA
Practica 1/Practica1.2.py
Practica1.2.py
py
1,873
python
en
code
0
github-code
36
8445202168
"""Module for RBF interpolation.""" import math import warnings from itertools import combinations_with_replacement import cupy as cp # Define the kernel functions. kernel_definitions = """ static __device__ double linear(double r) { return -r; } static __device__ float linear_f(float r) { return -r; } ...
cupy/cupy
cupyx/scipy/interpolate/_rbfinterp.py
_rbfinterp.py
py
23,197
python
en
code
7,341
github-code
36
42090081109
from pathlib import Path import logging import shlex import subprocess import sys # Returns the URIs of all the files inside 'path'. def get_uri_list(path: Path) -> list: uri_list = [] for file in path.iterdir(): if file.is_file(): uri_list.append(file.as_uri()) if uri_list == []: ...
Dante-010/change_wallpaper.py
helper_functions.py
helper_functions.py
py
1,642
python
en
code
0
github-code
36
9456997248
""" 34. Find First and Last Position of Element in Sorted Array Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1]. Follow up: Could you write an algorithm with O(log n) runtime complexity? Ex...
juliazakharik/ML_algorithms
algorithms/WEEK1/positions_in_sorted_array.py
positions_in_sorted_array.py
py
1,779
python
en
code
1
github-code
36
7226796164
# read tabdelimited data from Ocean Optics HR2000 and convert to csv import os from textwrap import indent import datamod3 import re import sys path = os.path.join(os.getcwd(),'testdataJCAMP','LABCALC.DX') reflectionwavelengths = [] reflectionvalues = [] darkwavelengths = [] darkvalues = [] refwavelengths = [] refval...
giacomomarchioro/SpectraInteroperabilityFramework
spectraformat/convertJCAMPDXinfraredspectrum.py
convertJCAMPDXinfraredspectrum.py
py
1,821
python
en
code
0
github-code
36
3585776354
# Local Imports from utils import BertBatchInput, BertSingleDatasetOutput, BertBatchOutput # Standard Imports # Third Party Imports import torch from torch import nn from torch.nn import MSELoss from transformers import BertPreTrainedModel, BertModel class ArgStrModel(BertPreTrainedModel): """Handles weights and...
The-obsrvr/ArgStrength
Hyper-parameter-optimization/src/modeling.py
modeling.py
py
8,100
python
en
code
0
github-code
36
32143174021
import os import SimpleITK as sitk import slicer from math import pi import numpy as np # read input volumes fixedImageFilename = '/Users/peterbehringer/MyImageData/ProstateRegistrationValidation/Images/Case1-t2ax-intraop.nrrd' movingImageFilename= '/Users/peterbehringer/MyImageData/ProstateRegistrationValidation/Im...
PeterBehringer/BRAINSFit_to_SimpleITK
_old/simpleITK_EulerRotation.py
simpleITK_EulerRotation.py
py
5,841
python
en
code
2
github-code
36
42768410408
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.converter import TextConverter, HTMLConverter from pdfminer.layout import LAParams from pdfminer.pdfpage import PDFPage from collections import defaultdict from io import BytesIO import PyPDF2 import re import json from PDF_Keywords_Ext...
CSIRO-enviro-informatics/modsim-keywords
PDF_Keywords_Extractor/PdfExtractor.py
PdfExtractor.py
py
7,785
python
en
code
1
github-code
36
74653263464
def gcd(a, b): if a < b: return gcd(b, a) while b: a, b = b, a % b return a def triplet(perimeter): a, b, c = 0, 0, 0 m, k, n, d = 0, 0, 0, 0 isfound = False mlimit = int(perimeter ** 0.5) for m in range(2, mlimit): if perimeter / 2 % m == 0: if m % 2 == 0: k = m + 1 els...
EricRovell/project-euler
deprecated/009/python/009.euclid.py
009.euclid.py
py
747
python
en
code
0
github-code
36
21362127557
# step1_unpack.py """Read the GEMS output directly from .tar archives, compile it into a single data set of size (num_variables * domain_size)x(num_snapshots), and save it in HDF5 format. The GEMS data for this project collects snapshots of the following variables. * Pressure * x-velocity * y-velocity * Temperature *...
a04051127/ROM-OpInf-Test
step1_unpack.py
step1_unpack.py
py
8,380
python
en
code
null
github-code
36
73193573864
#!/usr/bin/python # -*- coding: utf8 -*- from RGBStrip.renderers.base import BaseSingleTimedRenderer class ConeSpinLineRenderer(BaseSingleTimedRenderer): def __init__( self, loader, name=None, interval_seconds=0.2, section=None, palette=None, active=True, # Custom ...
csudcy/rgb_strip
RGBStrip/renderers/cone_spin_line.py
cone_spin_line.py
py
1,151
python
en
code
0
github-code
36
18645146697
from pyttsx3 import init from speech_recognition import Recognizer,Microphone from webbrowser import open import wikipedia from datetime import date,datetime # pip install pyttsx3 speech_recognition,wikipedia ''' speaking methord''' def speak(output): engine =init() engine.setProperty('rate',120) ...
MohitKumar-stack/personal-computer-assistance
jarvis.py
jarvis.py
py
2,308
python
en
code
1
github-code
36
70447210985
import os import typer from src.core.config import settings from src.collection.building import collect_building from src.collection.poi import collect_poi from src.collection.landuse import collect_landuse from src.collection.network import collect_network from src.collection.network_pt import collect_network_pt from ...
goat-community/data_preparation
manage.py
manage.py
py
4,391
python
en
code
0
github-code
36
74143239463
def marathonTaskScore(marathonLength, maxScore, submissions, successfulSubmissionTime): lost1=0 if submissions>1: lost1=10*(submissions-1) d=maxScore -lost1 - successfulSubmissionTime*(maxScore/2)*(1/marathonLength) print(d) if successfulSubmissionTime==-1: return 0 if d<maxScore...
jahirulislammolla/CodeFights
BotChallenges/Codefigtsbot/marathonTaskScore.py
marathonTaskScore.py
py
363
python
en
code
2
github-code
36
26796000187
import requests from bs4 import BeautifulSoup import pprint def stocks_gainers(): res = requests.get('https://www.google.com/finance/markets/gainers?hl=en') soup = BeautifulSoup(res.text, 'html.parser') stocks_container_gainers = soup.find('div', {'class': 'Sy70mc'}) stocks_listing_gainers = st...
Prasadk1234/Project
Stock_monitoring.py
Stock_monitoring.py
py
1,420
python
en
code
1
github-code
36
22565082017
class Solution: def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]: graph = defaultdict(list) output = [i for i in range(len(quiet))] cnt = [0 for _ in range(len(quiet))] que = deque() for a, b in richer: graph[a].append(b) ...
miedan/competetive-programming
loud-and-rich.py
loud-and-rich.py
py
796
python
en
code
0
github-code
36
12507825781
# 정렬 # 실패율 def solution(N, stages): arrived = [0] * (N+2) # 도달한 사람 수 now = [0] * (N+2) # 클리어 못한 사람 수 (플레이어들의 현위치) for s in stages: now[s] += 1 for i in range(1, s+1): arrived[i] += 1 rate = dict() # 실패율을 저장하는 딕셔너리 (레벨: 실패율) for i in range(1, N+1): ...
Hong-Jinseo/Algorithm
이코테/04_sorting/25_실패율.py
25_실패율.py
py
725
python
ko
code
0
github-code
36
73478421545
import pygame import random from pygame.math import Vector2 from triangle import Triangle from settings import * from colors import * class Sierpinski: def __init__(self): self.width = WIDTH self.height = HEIGHT self.xoff = X_OFF self.yoff = Y_OFF self.gameWinWidth = GA...
Deadshot96/sierpinski-triangle
main.py
main.py
py
3,079
python
en
code
0
github-code
36
18924228815
from selenium import webdriver from selenium.webdriver.common.by import By import time class SwitchToFrame(): def test1(self): baseUrl = "https://letskodeit.teachable.com/pages/practice" driver = webdriver.Firefox() driver.maximize_window() driver.get(baseUrl) driver.find...
PacktPublishing/-Selenium-WebDriver-With-Python-3.x---Novice-To-Ninja-v-
CODES/S23 - Selenium WebDriver -_ Switch Window And IFrames/5_switch-to-alert.py
5_switch-to-alert.py
py
764
python
en
code
11
github-code
36
30371792823
import streamlit as st from EmailSender import EmailSender from models.client.client import CreateClient from models.client.message import CreateMessage from models.client.template import CreateTemplate from pages.group_send import run_group_send from pages.single_send import run_single_send from pages.manage_client...
helmi75/SendMegaEmailsOVH
App/main.py
main.py
py
1,610
python
en
code
0
github-code
36
86452991700
import pandas as pd import numpy as np import scanpy as sc import decoupler as dc import anndata as ad import matplotlib.pyplot as plt import matplotlib.backends.backend_pdf import argparse # Init args parser = argparse.ArgumentParser() parser.add_argument('-m','--meta_path', required=True) parser.add_argument('-p','...
saezlab/VisiumMS
workflow/scripts/figures/fig1/niches_markers.py
niches_markers.py
py
2,695
python
en
code
1
github-code
36
31604178727
import json ores = [ 'iron', 'coal', 'gold', 'copper', 'silver', 'redstone', 'diamond', 'lapis', 'emerald', 'quartz', 'tin', 'lead', 'nickel', 'zinc', 'aluminum', 'cobalt', 'osmium', 'iridium', 'uranium', 'ruby', 'sapphire', 'sulfu...
N-Wither/omniores
src/main/python_data_generate/tag/ores.py
ores.py
py
2,012
python
en
code
1
github-code
36
506067890
""" SQLITE Column Types """ def pnd_map_sqtypes(type_): __types = { 'int32' : 'integer', 'int64' : 'integer', 'float32' : 'numeric', 'float64' : 'numeric', 'object' : 'text' } return __types[type_] def sqtypes_from_df(df): """ Get PGTypes from pan...
jasp382/glass
glass/cons/sqlite.py
sqlite.py
py
476
python
en
code
2
github-code
36
39156552883
import re from math import log from time import sleep import subprocess from io import StringIO from pathlib import Path from operator import itemgetter from Bio import SearchIO, SeqIO from Bio.Blast import NCBIXML, NCBIWWW from RecBlast import print, merge_ranges from RecBlast.WarningsExceptions import * class Searc...
docmanny/RecSearch
RecBlast/Search.py
Search.py
py
43,643
python
en
code
4
github-code
36
69886416746
import requests import os CHAT_ID = os.getenv('CHAT_ID') TOKEN = os.getenv('TG_TOKEN') print(f"TOKEN is {TOKEN}, CHAT_ID is {CHAT_ID}") if not CHAT_ID or not TOKEN: raise ValueError("Char ID or TOKEN was not specified") TOKEN = TOKEN.replace("\n", "") async def send_message(data: str): """ Send data t...
dievskiy/devops-kubernetes-course
part-5/502/broadcaster/send.py
send.py
py
666
python
en
code
1
github-code
36
28297108867
#!/usr/bin/env python3 from collections import namedtuple from datetime import datetime import os, sys, time import xml.etree.ElementTree as ET import logging import yaml import requests import re import twitter import nltk import argparse parser = argparse.ArgumentParser() parser.add_argument('--offset', type=int...
zouharvi/arxiv-twitter
run.py
run.py
py
5,360
python
en
code
0
github-code
36
15768186318
"""Test cases for the kallisto methods.""" import numpy as np import pytest from kallisto.units import Bohr from rdkit import Chem from rdkit.Chem.rdMolDescriptors import CalcNumAtoms from tests.store import pyridine from jazzy.core import get_charges_from_kallisto_molecule from jazzy.core import kallisto_molecule_fro...
AstraZeneca/jazzy
tests/test_kallisto.py
test_kallisto.py
py
3,257
python
en
code
63
github-code
36
2548310
import pytest from comicgeeks import Comic_Geeks from dotenv import dotenv_values from pathlib import Path dotenv_path = Path(".devdata.env") env = dotenv_values(dotenv_path=dotenv_path) if "LCG_CI_SESSION" not in env: import os env = { "LCG_CI_SESSION": os.environ.get("LCG_CI_SESSION"), "LCG_...
pruizlezcano/comicgeeks
tests/test_Issue.py
test_Issue.py
py
6,575
python
en
code
2
github-code
36
42893966152
import json import boto3 print('creating client') client = boto3.client( 'dynamodb', # endpoint_url="http://9.9.9.9:8000", endpoint_url="http://localhost:8000", aws_access_key_id='dummyid', aws_secret_access_key='dummykey', aws_session_token='dummytoken', region_name='us-west-2' ) def...
tthoraldson/PetMatch
src/pet_match_stack/lambdas/dynamo_test/app.py
app.py
py
878
python
en
code
0
github-code
36
28583822519
#! /usr/bin/env python3 import csv with open("tsv/categories_taxonomy.tsv") as tree_file: reader = csv.reader(tree_file, delimiter='\t') b = True _child = [] _parent = [] for row in reader: if b: b = False #Skip the first line continue if not (row[0] in _par...
prof4321/open-food-fact
read_categories.py
read_categories.py
py
899
python
en
code
0
github-code
36
70360189864
#!/usr/bin/python3 from math import cos, sin, atan2, radians from numpy import array, dot import rospy from std_msgs.msg import Float64, Bool from time import sleep class PathPlanner: pos_x = 0.0 pos_y = 0.0 yaw = 0.0 prev_x = 0.0 prev_y = 0.0 prev_real_x = 0.0 prev_real_y = 0.0 del_...
amer-adam/pathplan_ros
PP.py
PP.py
py
7,211
python
en
code
0
github-code
36
31877057798
import numpy as np import cv2 as cv from pathlib import Path def get_image(): Class = 'BACKWARD' Path('DATASET1/'+Class).mkdir(parents=True, exist_ok=True) width=1200 height=720 cam=cv.VideoCapture(0,cv.CAP_DSHOW) cam.set(cv.CAP_PROP_FRAME_WIDTH, width) cam.set(cv.CAP_PROP_FRAME_HEIGHT,hei...
Ewon12/Hand-Gesture-Recogniton-Control-for-a-Cylindrical-Manipulator
get_image.py
get_image.py
py
1,043
python
en
code
0
github-code
36
28091587486
from flask import Flask, render_template, redirect from flask_restful import abort, Api import news_resources import projects_resources import library_recources import reports_resources from __all_forms import LoginForm, RegistrationForm, CreateNewsForm, CreateProjectForm, ChangePasswordForm, \ FindErrorForm from d...
InfiRRiar/YL_proj_web
run.py
run.py
py
16,572
python
ru
code
0
github-code
36
30481483106
from pathlib import Path import pyotp from Model import login, order_book, stats, trades from time import sleep import pandas as pd import json import datetime from threading import Thread import pickle import os.path class Controller: TOKEN = "" symbols = None order_list = [] trade_list = [] stat...
amirhosseinttt/nobitexAutoTrader
dataCollector/Controller.py
Controller.py
py
11,133
python
en
code
0
github-code
36
27514897214
''' GRID WALK (https://www.codeeval.com/open_challenges/60/) CHALLENGE DESCRIPTION: There is a monkey which can walk around on a planar grid. The monkey can move one space at a time left, right, up or down. That is, from (x, y) the monkey can go to (x+1, y), (x-1, y), (x, y+1), and (x, y-1). Points where the sum of th...
stroud109/challenges
grid_walk/grid_walk.py
grid_walk.py
py
2,226
python
en
code
3
github-code
36
41220371897
# https://en.wikipedia.org/wiki/Trilateration # https://electronics.stackexchange.com/questions/83354/calculate-distance-from-rssi # https://stackoverflow.com/questions/4357799/convert-rssi-to-distance # https://iotandelectronics.wordpress.com/2016/10/07/how-to-calculate-distance-from-the-rssi-value-of-the-ble-beacon/ ...
mirrorcoloured/picobeacon
analysis/analysis.py
analysis.py
py
4,235
python
en
code
0
github-code
36
6049157141
nama_PTN = "Politeknik Negeri Pontianak"; nama_mhs = "Oliver Dillon"; print(nama_PTN); print(nama_mhs); umur = 18; print(umur); type(umur); umur = "delapan belas"; print(umur); type(umur); umur = (("delapan belas")); print(umur); type(umur); umur = tuple(("delapan belas")); print(umur); type(umur);...
Oliv-e/tugaskuliah
Struktur Data S2/Pertemuan #2/jobsheet01.py
jobsheet01.py
py
1,396
python
id
code
0
github-code
36
7737167108
import os.path as osp import warnings from collections import OrderedDict import mmcv import numpy as np from mmcv.utils import print_log from prettytable import PrettyTable from torch.utils.data import Dataset from mmseg.core import eval_metrics, intersect_and_union, pre_eval_to_metrics from mmseg.utils import get_r...
uijinee/segmentation
mmsegmentation/mmseg/datasets/TrashDataset.py
TrashDataset.py
py
3,022
python
en
code
0
github-code
36
28885592092
#!/usr/bin/env python import sys import os, fnmatch import re import sys, getopt def main(argv): inputpath = '' outputfile = '' typefiles = '' try: myopts, args = getopt.getopt(sys.argv[1:],"i:o:t:") except getopt.GetoptError as e: print (str(e)) print ("Usage %s -t [imas_a | imas_b] -i <inputp...
aferreroc/ansible-checkinf
parseresults_mtools.py
parseresults_mtools.py
py
2,318
python
en
code
0
github-code
36
32161323459
#Patrick Douglas #Robot Strategy/AI import rg """ -check if in spawn zone. if yes, find open space and go there. if no, continue -check surrounding area. if 1 enemy: if myhealth > enemyhealth: attack if myhealth < enemyhealth: if they have less than 15, suicide else b...
castlez/robogame
pd-strat.py
pd-strat.py
py
3,485
python
en
code
1
github-code
36
30972445679
import pandas as pd import numpy as np data = pd.read_csv("./data/day3.txt", header=None) #Part 1 letters = [] for rucksac in data[0]: for letter in rucksac[0:int((len(rucksac)/2))]: if letter in rucksac[int((len(rucksac)/2)):len(rucksac)]: letters.append(letter) ...
Hopeguy/Advent-of-code-2022
day-3.py
day-3.py
py
1,119
python
en
code
0
github-code
36
36156110649
# WAP to solve quadratic equation import math import cmath a = float(input("Enter co-ef of x^2: ")) b = float(input("Enter co-ed of x: ")) c = float(input("Enter constant: ")) d = (b * b) - (4 * a * c) if d == 1: print("Single Root Exists!") Root = ((-b) / (2 * a)) print(Root) elif d > 0: ...
Penguin5681/Practicals
PYTHON/6.py
6.py
py
661
python
en
code
2
github-code
36
37069874151
#!/usr/bin/python3 """ function that queries the Reddit API and prints the titles of the first 10 hot posts listed for a given subreddit. """ import requests def top_ten(subreddit): """ function that queries subredit hot topics """ params = {'limit': 10} url = f"https://www.reddit.com/r/{subreddi...
wughangar/alx-system_engineering-devops
0x16-api_advanced/1-top_ten.py
1-top_ten.py
py
1,000
python
en
code
0
github-code
36
36369809558
from ast import literal_eval import os, sys import customtkinter as ctk from PIL import Image ctk.set_appearance_mode("dark") ctk.set_default_color_theme("blue") from numpy import number sys.path.insert(0, os.path.dirname("algorithms")) import random import copy import tkinter as tk from tkinter import ttk fro...
Jakcrimson/pjeb_twitter_sentiment_analysis
gui/xsa.py
xsa.py
py
26,096
python
en
code
1
github-code
36
19249979909
from functools import reduce from typing import NamedTuple Coord = tuple[int, int] """X and Y coordinates""" Views = list[list[int]] """ The views from the tree looking outwards. Each outer list is a direction. The inner list contains tree heights. The start of the list is closest to the tree. """ class Tree(NamedT...
dan-osull/python_aoc2022
day08/code.py
code.py
py
2,988
python
en
code
1
github-code
36
16097700723
from player import Player from typing import List class LineUp: def __init__(self): self.players:List[Player] = [] def addPlayer(self, player: Player): self.players.append(player) def print(self, otherLineup): if(otherLineup == 0): for player in self.players: ...
JHarding86/SoccerSubs
lineup.py
lineup.py
py
3,616
python
en
code
0
github-code
36
10524711951
#!/usr/bin/python import os from os.path import expanduser from dotenv import load_dotenv import mysql.connector def se_db_run_cmd(query,values): home = expanduser("~") config_path = home + "/.app_config/.env_db" load_dotenv(dotenv_path=config_path) try: mydb = mysql.connector.connect( host=os.ge...
jsanchezdevelopment/se_project
se_test/se_db/se_db_run_cmd.py
se_db_run_cmd.py
py
926
python
en
code
0
github-code
36
4254200904
""" Problem Statement # Given an array of ‘K’ sorted LinkedLists, merge them into one sorted list. Example 1: Input: L1=[2, 6, 8], L2=[3, 6, 7], L3=[1, 3, 4] Output: [1, 2, 3, 3, 4, 6, 6, 7, 8] Example 2: Input: L1=[5, 8, 9], L2=[1, 7] Output: [1, 5, 7, 8, 9] """ from heapq import * def merge_lists(lists): mi...
blhwong/algos_py
grokking/k_way_merge/merge_k_sorted_lists/main.py
main.py
py
833
python
en
code
0
github-code
36
29696788586
import utils def read_input(path): return [(l[0], int(l[1])) for l in [l.split() for l in utils.read_lines(path)]] def part1(path): input = read_input(path) h = 0 v = 0 for m in input: if m[0] == "forward": h += m[1] elif m[0] == "up": v -= m...
dialogbox/adventofcode
py/2021/day2.py
day2.py
py
666
python
en
code
0
github-code
36
73850392743
from django.urls import path from . import views # /articles/ ___ app_name = 'articles' urlpatterns = [ # 입력 페이지 제공 path('', views.index, name='index'), # /articles/10/ 이런식으로 몇번 게시글 보여주세요 라는 의미이다. path('<int:article_pk>/', views.detail, name='detail'), # detail # path('new/', views.new, name='new')...
blueboy1593/Django
Django_crud/articles/urls.py
urls.py
py
923
python
en
code
0
github-code
36
29659709532
#Import modules from bs4 import BeautifulSoup from urllib.request import urlopen import math import pandas as pd import numpy as np from sklearn.linear_model import LinearRegression #Lottery ticket expectation value calculator class lottery_expectation_calculator: def __init__(self): self.current_jackpot ...
StanleyKubricker/Lottery-Expectation-Value
lottery_expectation_value.py
lottery_expectation_value.py
py
4,744
python
en
code
0
github-code
36
1270205424
import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() setuptools.setup( name="PyPolkaSideCar-mickstar", # Replace with your own username version="0.0.1", author="Michael Johnston", author_email="michael.johnston29@gmail.com", description="A Simple ...
mickstar/PyPolkaSideCar
setup.py
setup.py
py
823
python
en
code
1
github-code
36
2030921281
import sys sys.path.append("../") from Heap.heap import minHeap def heapSort(L: list) -> list: if len(L) == 0: return [] heap = minHeap() for num in L: heap.addElement(num) heapSorted = [] while heap.length > 0: heapSorted += [heap.removeElement()] return heapSorted ...
youngseok-seo/cs-fundamentals
Sorting/heapSort.py
heapSort.py
py
386
python
en
code
0
github-code
36
23620498135
import math import json import argparse import cv2 import numpy as np from shapely.geometry import Point from PIL import Image, ImageDraw, ImageFont SIZE = 60, 60 INNER_CIRCLE_DIAM = 28 HOLE_SPACING = 0 HOLE_SIZE = 0.800 # only used for debug out...
volzotan/LensLeech
fabrication/stencil/cncwrite.py
cncwrite.py
py
13,041
python
en
code
5
github-code
36
18793575519
import hmac import hashlib import binascii import urlparse import urllib class Parameters(object): def __init__(self, sources, skip=None): self.sources = sources self.skip = set(skip or []) @property def composed(self): """ Composes multiple parameter sources in a single object. I...
pbs/piston-api-auth
api_auth/authentication2.py
authentication2.py
py
4,499
python
en
code
0
github-code
36
31727663113
""" This module should contain helper functionality that assists for Jira. """ import logging from collections import namedtuple from typing import Dict, List, Union import jira SSLOptions = namedtuple("SSLOptions", "check_cert truststore") class JiraUtils: """ This class contains the shared functions that ...
openSUSE/sle-prjmgr-tools
sle_prjmgr_tools/utils/jira.py
jira.py
py
5,957
python
en
code
4
github-code
36
36011399342
#!/bin/python # -*- coding: utf-8 -*- # Created by 顾洋溢 import unittest import HTMLTestRunner from test_interfacecase.public.users_uId_user_push import Users_uId_user_push from test_interfacecase.bussiness import global_value from test_interfacecase.public.login_logout import Login_logout class Users_uId_user_pushT...
xuxiuke/Android_test
SmartHomeV6Code_TestTeam-InterfaceTest/test_interfacecase/unite/test_users_uId_user_push.py
test_users_uId_user_push.py
py
1,028
python
en
code
1
github-code
36
36779144168
import sys from UserString import MutableString from string import ascii_uppercase from numpy import random from bits.convert_base import BaseConverter class SpreadsheetEncodingDecoder(BaseConverter): alphabet_number_map = {a: p + 1 for p, a in enumerate(ascii_uppercase)} number_to_alphabet_map = {v: k for ...
mshekhar/random-algs
bits/spreadsheet_encoding_decoder.py
spreadsheet_encoding_decoder.py
py
939
python
en
code
4
github-code
36
74552235623
import os import json import sqlite3 import datetime, time import itertools from common import util import queue import threading from threading import Thread import logging import sqlite3 import datetime, time import itertools from common import util class IDEBenchDriver: def init(self, options, schema, driver...
leibatt/crossfilter-benchmark-public
drivers/sqlite.py
sqlite.py
py
3,498
python
en
code
3
github-code
36
7689882357
class Node: def __init__(self): self.data = 0 self.next = None def getIntersectionNode(head1, head2): curr1 = head1 curr2 = head2 while curr1 != curr2: if curr1 == None: curr1 = head2 else: curr1 = curr1.next if curr2 == None: ...
thisisshub/DSA
J_linked_list/problems/H_the_intersection_of_two_linked_list.py
H_the_intersection_of_two_linked_list.py
py
1,019
python
en
code
71
github-code
36
18873086609
from django.shortcuts import redirect, render from . import models def index(req): return render(req, 'home.html') def listKategori(req): if req.method == 'POST': kategori_id = req.POST.get('kategori_id') data = models.KategoriModel.objects.get(id=kategori_id) data.delete() return redirect('/kateg...
zakiyul/2022django
bookstore/views.py
views.py
py
4,596
python
en
code
0
github-code
36
39908905434
# Imports from FindRoots from FindRoots import fixPoint from FindRoots import bisection from FindRoots import falsPos from FindRoots import newRap from FindRoots import secant from FindRoots import multipleRoot from FindRoots import intervals from FindRoots import derivatives # Imports from Integrals from Integral...
Ngonzalez693/MetodosNumericos
ProgramMetods/main.py
main.py
py
9,646
python
en
code
0
github-code
36
35865671344
import time from school import clear class Gym: def __init__(self, user): class_prompt = input("Enter Gym (Y/N): ") if class_prompt.lower() == "y": in_gym(user) elif class_prompt.lower() == "n": out_gym(user) def in_gym(user): clear() choice = input("Do you ...
AlamTahmidul/adVent
gym.py
gym.py
py
1,888
python
en
code
0
github-code
36
74612450025
#有序字典 from collections import OrderedDict from pyexcel_xls import get_data def readXlsAndXlsxFile(path): #创建一个有序的字典,excel中的数据都是有顺序的,所以用有序字典 dic = OrderedDict() #抓取数据 xdata = get_data(path) #OrderedDict([('Sheet1', [['年度', '总人口(万人)', '出生人口(万人)', '死亡人口(万人)'..... for sheet in xdata: dic[shee...
hanyb-sudo/hanyb
自动化办公/4、excel自动化办公/3、返回xls和xlsx文件内容.py
3、返回xls和xlsx文件内容.py
py
666
python
en
code
0
github-code
36
27433522121
import random import numpy as np import math # =============================================== HELPER FUNCTIONS ===================================================== def split_set(x, y, val_size): """ Split the given training set into a validation and training set. """ val_indices = random.sample(range(len(y...
2067015b/ML_ex01
Regression/Bayes.py
Bayes.py
py
4,245
python
en
code
0
github-code
36
73200842984
#! python3 import os import pandas as pd import numpy as np tsv, prefix, threshold = os.sys.args[1], os.sys.args[2], float(os.sys.args[3]) expr = pd.read_csv(tsv, sep='\t', index_col=0) #### top = [] for i in expr.columns: x = expr.loc[:, i].nlargest(10) top.append (list (x.index.values)) top.append (x...
d2jvkpn/BioinformaticsAnalysis
Gene_expression/Expression_summary.py
Expression_summary.py
py
969
python
en
code
1
github-code
36
40877684818
import argparse import sys import datetime from lib.data_holder import * from lib.models import * from lib.extremums import * ### ### GLOBALS ### CACHE_DIR = 'cache' data_holder = None def lazy_data_holder(): global data_holder if data_holder is None: data_holder = DataHolder() return data_hol...
Intelligent-Systems-Phystech/ProbabilisticMetricSpaces
code/main.py
main.py
py
6,488
python
en
code
0
github-code
36
7522166332
import cv2 from mtcnn import MTCNN capture = cv2.VideoCapture(0) detector = MTCNN() while True: ret, frame = capture.read() faces = detector.detect_faces(frame) for single_faces in faces: x, y, width, height = single_faces["box"] left_eyeX, left_eyeY = single_faces["keyp...
iamSobhan/deep_learning
face_detection/face_video_detect.py
face_video_detect.py
py
1,466
python
en
code
0
github-code
36
5495864560
import pickle from flask import Flask, request, app, jsonify,url_for, render_template import numpy as np import pandas as pd from sklearn.preprocessing import StandardScaler app=Flask(__name__) ## load the model regmodel=pickle.load(open('regmodel.pkl','rb')) scalar=pickle.load(open('scaling.pkl','rb')) @app.route('/...
MithunMiranda/bostonhousepricing
app.py
app.py
py
997
python
en
code
0
github-code
36
6601688520
from flask import render_template,request,redirect from models import * from forms import CardForm, StoryForm, NewsForm from upload import save_file from app import app from extensions import db import requests import xml.etree.ElementTree as ET @app.route('/') def index(): story = Story.query.all() card = Car...
Emrahgs/Yelo-Bank-Flask
controllers.py
controllers.py
py
3,427
python
en
code
1
github-code
36
20508999439
""" 50% - recursiva """ def saque(mapa): return saqueaux(mapa,(0,0),0) def saqueaux(mapa,coords,valor): if mapa[coords[1]][coords[0]].isdigit(): valor+= int(mapa[coords[1]][coords[0]]) if coords[0] == len(mapa[0])-1 and coords[1] == len(mapa)-1: return valor if mapa[coords[1]][coords[0...
Andre-N-Costa/Laboratorios-Algoritmia-II
Treino3/saque.py
saque.py
py
1,712
python
es
code
0
github-code
36
2116048955
from mirl.agents.td3_agent import TD3Agent import mirl.torch_modules.utils as ptu import torch.nn.functional as F import copy from mirl.utils.logger import logger class TD3BCAgent(TD3Agent): def __init__( self, env, policy, qf, qf_target, pool=None, normali...
QiZhou1997/MIRL
mirl/agents/td3bc_agent.py
td3bc_agent.py
py
4,104
python
en
code
0
github-code
36
12840958073
''' Yangbot #2 - elo ~ 1800 - 2000 FEATURE LIST: - UCI interface [INCOMPLETE] - opening book [OK] - negamax [OK] - quiscence search [OK] - killer moves [TESTING] - move ordering ...
yangman946/yanchess-ai
chessAI/test.py
test.py
py
24,405
python
en
code
0
github-code
36
29550562784
from pymongo import MongoClient import json #import numpy as np puerto = 27017 #puerto = 50375 hostname = 'localhost' def ConectToMongoDB(puerto, Hostname): # Conexión a la base de datos mongoClient = MongoClient(Hostname, puerto) # Creamos la base de datos Pulseras db = mongoClient.Pulseras # ...
palomadominguez/TFG-pulseras
src/MongoConection.py
MongoConection.py
py
1,109
python
es
code
0
github-code
36
42194323986
import datetime import math from sqlalchemy import desc, asc from app.main import db from app.main.model.product_price_history import ProductPriceHistory from app.main.model.product import Product def save_product_price_history(data): errors = {} # Check null if data['effective_date'] == "": err...
viettiennguyen029/recommendation-system-api
app/main/service/product_price_history_service.py
product_price_history_service.py
py
14,012
python
en
code
0
github-code
36
12267770021
# coding=utf8 from youtubesearchpython import Search import pandas as pd import numpy as np search_query_test = 'Кончится Лето Kino' def find_first_vid(search_query): allSearch = Search(search_query, limit = 1) result_dict = allSearch.result() result_dict2 = list(result_dict.values())[-1] ...
WildLegolas/spotify_csv_to_mp3
youtube_vid_finder.py
youtube_vid_finder.py
py
2,573
python
en
code
0
github-code
36
42990004536
import unittest import mysql.connector class TestMySQL(unittest.TestCase): def test_connect(self): connection = mysql.connector.connect(host='127.0.0.1', user='root', passwd='') try: cursor = connection.cursor()...
src-d/go-mysql-server
_integration/python-mysql/test.py
test.py
py
837
python
en
code
1,035
github-code
36
70596813543
import string #get alphabet using the string module so we don't have to type it out by ourselves alphabet = list(string.ascii_lowercase) direction = '' def encrypt(plain_text, shift_amt): encr_text = "" for letter in plain_text: #if the plain text in a specific location contains a space, ...
enzofalone/caesar-cipher
__main__.py
__main__.py
py
2,042
python
en
code
0
github-code
36
42750610767
# Generators def generator_func(num): for i in range(num): # after yielding i, it pauses and remembers the last yield yield i g = generator_func(10) # when next(g) is called, the generator_func will pick up from last yield and yields next value until it reaches the last index of range # when t...
1kvsn/python-cheat-sheet
notes/generator.py
generator.py
py
1,513
python
en
code
0
github-code
36
20579907742
import numpy as np import matplotlib.pyplot as plt from tkinter import * from tkinter import messagebox # Own Fuctions from harmGen import * from transformLibrary import * from visualization import * from preSettings import preSet # Optional: copy another PreSet.py file with new default values...
josediazb/alpha-beta-harmonics
clarkeos.py
clarkeos.py
py
4,883
python
en
code
1
github-code
36
15511156980
project='dcpots' version='0.1.1' debug = 1 defs = [] verbose = 'on' extra_c_flags = '-wno-unused-parameter' extra_cxx_flags = '--std=c++11 -lpthread -lrt -ldl' env={ 'protoc':'protoc', } units = [{ 'name':'dcbase', 'subdir':'base', }, { 'name':'dcnode', '...
jj4jj/cmaketools
examples/dcpots.py
dcpots.py
py
7,336
python
en
code
1
github-code
36
22612711093
import urllib3 from kivy.clock import Clock from functools import partial class Ping(): # Выводим статус подключения к сети на главной странице и странице Настроек def getPing(self, ti): try: http=urllib3.PoolManager() response = http.request('GET', 'http://google.com') self.screens[0].ids.net_l...
IPIvliev/Pro_2
Moduls/ping.py
ping.py
py
655
python
ru
code
0
github-code
36
8669136509
from cterasdk.core import cli from tests.ut import base_core class TestCoreCLI(base_core.BaseCoreTest): def setUp(self): super().setUp() self._cli_command = 'show /settings' def test_run_cli_command(self): execute_response = 'Success' self._init_global_admin(execute_response=...
ctera/ctera-python-sdk
tests/ut/test_core_cli.py
test_core_cli.py
py
553
python
en
code
6
github-code
36
10492814030
import matplotlib.pyplot as plt import pyk4a from pyk4a import Config, PyK4A import open3d as o3d import time import numpy as np import copy import cv2 from modern_robotics import * if __name__ == "__main__": k4a = PyK4A( Config( color_resolution=pyk4a.ColorResolution.RES_720P, de...
chansoopark98/3D-Scanning
test_code/capture_by_button.py
capture_by_button.py
py
2,887
python
en
code
0
github-code
36
8860145335
import numpy as np import pandas as pd import matplotlib.pyplot as plt import os seeds = [6969, 4242, 6942, 123, 420, 5318008, 23, 22, 99, 10] delta_vals = [0.1, 0.2, 0.3, 0.4, 0.6, 0.7, 0.8, 0.9, 0.001, 0.005, 0.01, 0.05, 0.5, 1, 2, 3, 5] delta_vals = [1, 2, 3, 5] root_folder = 'sumo/test_results' test_results = 'n...
TheGoldenChicken/robust-rl
examineloss.py
examineloss.py
py
1,060
python
en
code
0
github-code
36
32512355098
"""this module contains methods for working with a web server """ from http.server import BaseHTTPRequestHandler, HTTPServer import cgi from search_engine import SearchEngine, Context_Window import time class RequestHandler(BaseHTTPRequestHandler): def do_GET(self): """create an html page with a...
mathlingv-siv/tokenizer
web_server.py
web_server.py
py
8,672
python
en
code
0
github-code
36
2036893082
import click_log import logging class MyFormatter(click_log.ColorFormatter): def format(self, record): msg = click_log.ColorFormatter.format(self, record) if record.levelname in ("DEBUG", "INFO"): new_msg = "> " + msg elif record.levelname in ("WARNING"): new_msg = ...
nuvolos-cloud/resolos
resolos/logging.py
logging.py
py
647
python
en
code
3
github-code
36
74004605223
import os from openai import OpenAI from sentence_transformers import SentenceTransformer from typing import Protocol import numpy.typing as npt import numpy as np import config class EmbeddingMaker(Protocol): def encode(self, text: str) -> npt.NDArray[np.float32]: ... class AI: def __init__(self) ...
capgoai/doc_search
api/ai.py
ai.py
py
1,070
python
en
code
0
github-code
36
12366302032
"""Module containing a framework for unittesting of AMPLE modules""" __author__ = "Felix Simkovic" __date__ = "22 Mar 2016" __version__ = "1.0" import glob import logging import os import sys from ample.constants import AMPLE_DIR from unittest import TestLoader, TextTestRunner, TestSuite # Available packages. Hard-...
rigdenlab/ample
ample/testing/unittest_util.py
unittest_util.py
py
2,557
python
en
code
6
github-code
36
29867512033
import os import json import shelve from jsonobject import JsonObject from constants import * class TranslationDB(): def __init__(self): if CLEAN: self.db = shelve.open(TRANSLATION_CACHE_NAME, flag='n') self.db = shelve.open(TRANSLATION_CACHE_NAME) if len(self.db) == 0...
Jugbot/FEH-Automation
database/translationdb.py
translationdb.py
py
782
python
en
code
2
github-code
36
38707691318
#!/usr/bin/env python import scenario import AStarAlgo from math import * import numpy as np class experiment: lookup_table = {} lakes = {} fires = {} drone = {} def __init__(self): self.scene = scenario.scenario_cityfire() self.scene.generate_scenario() def create_lookup_tab...
NithyaMA/Artificial-Intelligence
ai-cs540-team-e-proj-master/experiment.py
experiment.py
py
7,355
python
en
code
0
github-code
36
16403973201
class Caneta: def __init__(self, cor): self._cor = cor # atributos que começam com underline são privados daquela classe e não devem ser usados fora dela @property def cor(self): print('Property usada.') return self._cor @cor.setter def cor(self, valor): print('Set...
Pimegonho/Python-Udemy
Aulas/A132_setter.py
A132_setter.py
py
440
python
pt
code
0
github-code
36
33642822124
# A program that prints a descriptive text to show if each character in a string is a vowel or consonant # prints not a letter if the character is a special letter # prints empty string if the string is empty word = "Hello,planet" if not word: print("Empty string") else: for letter in word.lower(): ...
Willmuseve/simple-python
Conditionals/task2.py
task2.py
py
544
python
en
code
0
github-code
36