seq_id stringlengths 7 11 | text stringlengths 156 1.7M | repo_name stringlengths 7 125 | sub_path stringlengths 4 132 | file_name stringlengths 4 77 | file_ext stringclasses 6
values | file_size_in_byte int64 156 1.7M | program_lang stringclasses 1
value | lang stringclasses 38
values | doc_type stringclasses 1
value | stars int64 0 24.2k ⌀ | dataset stringclasses 1
value | pt stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
9001276762 | from time import time
from gurobipy import Model
class MDSP:
def __init__(self, d: list, filename: str, optimize=False, time_limit=3600):
self.D = d
self.B = sum(d)
self.k = len(self.D)
self.D_ = self.get_unique_distances()
self.M = self.get_mult()
self.P = list(ra... | cleberoli/mdsp | model/mdsp.py | mdsp.py | py | 1,706 | python | en | code | 0 | github-code | 6 |
23565353773 | # -*- coding: utf-8 -*-
'''Polynomial basis linear model data generator'''
import numpy as np
import hw3_1a
def polynomial(basis,var,weights,n=1):
noise = hw3_1a.normal_generating(0, var)
x = np.random.uniform(-1, 1, n)
X=[]
for power in range(basis):
X.append( x[:] ** power)
... | n860404/Machine_learning_2019 | HW3/hw3_1b.py | hw3_1b.py | py | 736 | python | en | code | 0 | github-code | 6 |
41211514297 | import rabacus as ra
import pylab as plt
import numpy as np
z = 3.0
Nnu = 100
q_min = 1.0e-2
q_max = 1.0e6
uvb = ra.BackgroundSource( q_min, q_max, 'hm12', z=z, Nnu=Nnu )
NT=100
T = np.logspace( 4.0, 5.0, NT ) * ra.u.K
nH = np.ones( NT ) * 1.0e-2 / ra.u.cm**3
nHe = nH * 10**(-1.0701)
H1i = np.ones(T.size) * uvb.th... | galtay/rabacus | cloudy/cooling/rabacus_confirm.py | rabacus_confirm.py | py | 1,097 | python | en | code | 4 | github-code | 6 |
13879303932 | #!/usr/local/bin/python3.7
# -*- coding: utf-8 -*-
# @Time : 2020-06-20 16:15
# @Author : 小凌
# @Email : 296054210@qq.com
# @File : test_06_audit.py
# @Software: PyCharm
import json
import unittest
import ddt
from common.excel_handler import ExcelHandler
from common.http_handler import visit
from middlerware.h... | galaxyling/api-framework | testcases/test_06_audit.py | test_06_audit.py | py | 3,807 | python | en | code | 1 | github-code | 6 |
20209358126 | n , k = [int(s) for s in input().split()]
s = set([str(s) for s in range(n + 1)])
mm = set()
for i in range(k):
a_i, b_i = [int(s) for s in input().split()]
j = 0
while a_i + j * b_i <= n:
m = a_i + j * b_i
mm.update(str(m))
s.remove(m)
j += 1
print(len(s)) | Nayassyl/22B050835 | pt/sets/100.py | 100.py | py | 301 | python | en | code | 0 | github-code | 6 |
73025036669 | from enum import Enum
from typing import List
import sqlalchemy as sa
from sqlalchemy import orm as so
from .base import BaseMixin, db, IdentityMixin, TimestampMixin
__all__ = ['Chat', 'ChatEntry']
class Chat(BaseMixin, IdentityMixin, TimestampMixin, db.Model):
"""Chat Model.
Represents a chat conversatio... | sergeyklay/promptly | backend/promptly/models/chat.py | chat.py | py | 2,313 | python | en | code | 1 | github-code | 6 |
70506428347 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
... | yangh9596/Algo-Leetcode | Leetcode/230_Kth Smallest Element in a BST.py | 230_Kth Smallest Element in a BST.py | py | 1,178 | python | en | code | 0 | github-code | 6 |
22019313936 | # -*- coding: utf-8 -*-
import numpy as np
from progbar import progress
import sys
def findBchange(initialPDB, multiDoseList, Bmetric, relative=True):
# function to determine the Bfactor/Bdamage (specified by Bmetric)
# change between the initial and later datasets --> becomes an
# object attribute for th... | GarmanGroup/RIDL | lib/findMetricChange.py | findMetricChange.py | py | 1,686 | python | en | code | 3 | github-code | 6 |
40759032093 | from utilities.Constants import Constants
from indicators.Indicator import Indicator
import pandas as pd
class MACD(Indicator):
# price is DataFrame, = adj_close
def __init__(self, df=None, fast_period=12, slow_period=26, signal_period=9):
super().__init__()
self.fast_period = fast_period
... | alejandropriv/stocksAnalysis | indicators/MACD.py | MACD.py | py | 2,625 | python | en | code | 0 | github-code | 6 |
41584638888 | """Celery를 사용하는 예제"""
import random
import time
from os import path
from urllib import parse
import requests
from celery import Celery
from pydub import AudioSegment
from my_logging import get_my_logger
logger = get_my_logger(__name__)
# 크롤링 요청 간격 리스트 정의
RANDOM_SLEEP_TIMES = [x * 0.1 for x in range(10, 4... | JSJeong-me/2021-K-Digital-Training | Web_Crawling/python-crawler/chapter_5/crawler_with_celery_sample.py | crawler_with_celery_sample.py | py | 5,058 | python | ko | code | 7 | github-code | 6 |
72492708988 | import pytest
from pytest_persistence import plugin
plg = plugin.Plugin()
@pytest.mark.parametrize("scope", ["session", "package", "module", "class", "function"])
@pytest.mark.parametrize("result", ["result", 42])
def test_store_fixture(result, scope):
fixture_id = ('fixture1', scope, 'tests/test_mock.py')
... | JaurbanRH/pytest-persistence | tests/test_unit.py | test_unit.py | py | 1,367 | python | en | code | 0 | github-code | 6 |
2246643792 | testname = 'TestCase apwds_1.2.1'
avoiderror(testname)
printTimer(testname,'Start','Check Ac basic wds configuration in open mode')
###############################################################################
#Step 1
#操作
# AC上show wireless network 2
#预期
# 显示WDS Mode....................................... Disable
##... | guotaosun/waffirm | autoTests/module/apwds/apwds_1.2.1.py | apwds_1.2.1.py | py | 5,416 | python | de | code | 0 | github-code | 6 |
12702052399 | """
To render html web pages
"""
import random
from django.http import HttpResponse
from django.template.loader import render_to_string
from articles.models import Article
def home_view(request, id=None, *args, **kwargs):
"""
Take in a request (Django send request)
return HTML as a response
(We pic... | L1verly/djproject-private | djproject/views.py | views.py | py | 832 | python | en | code | 0 | github-code | 6 |
34313307894 | import os
import subprocess
import time
import sys
import tracemalloc
import concurrent.futures
import threading
stopProcessing = False
def get_all_pids():
ps_cmd = ['ps', '-e', '-o', 'pid']
out = subprocess.Popen(ps_cmd, stdout = subprocess.PIPE).communicate()[0]
out = ''.join(map(chr,out))
out = ou... | noman-bashir/CarbonTop | code/power_model/powerTrial.py | powerTrial.py | py | 3,096 | python | en | code | 0 | github-code | 6 |
19239217812 | # tree ! 트리 나라 관광 가이드
# 부모 도시 없다면 만들어주기
K = int(input())
A = list(map(int, input().split()))
N = max(A)
parent = [-2] * (N+1) # 루트 도시의 부모는 -1이니 존재하지 않는 값인 -2로 통일
parent[A[0]] = -1 # 루트 도시가 0번이 아닌 경우도 있다!
for i in range(K-1): # 만약 아직 부모가 없는 도시라면 바로 전 도시를 부모로 하기
if parent[A[i+1]] == -2:
parent[A[i+1]] = A[i... | sdh98429/dj2_alg_study | BAEKJOON/tree/b15805.py | b15805.py | py | 508 | python | ko | code | 0 | github-code | 6 |
34097968081 | #!/usr/bin/python
import curses
import sys
import RPi.GPIO as GPIO
def main(stdscr):
# do not wait for input when calling getch
stdscr.nodelay(1)
initGPIO()
while True:
# get keyboard input, returns -1 if none available
c = stdscr.getch()
if c != -1:
# print numer... | tophsic/gpio | one_led_controled_by_s.py | one_led_controled_by_s.py | py | 914 | python | en | code | 0 | github-code | 6 |
36733301943 | import re
import json
from collections import defaultdict
def file_paths(file_path= 'logs_2/postcts.log1'):
with open(file_path, 'r') as file:
file_data = file.read()
return file_data
def parse_log_file():
file_contents = file_paths()
# Compile regex patterns for improved ... | DavidJose2000/Log_parse | Zpharse.py | Zpharse.py | py | 6,755 | python | en | code | 0 | github-code | 6 |
5153764381 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import sklearn
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, classification_report
import xlsxwriter
#Reading the file into the system
file1 = ... | Royston2708/Loan_Defaulter_Project | Models/Decision Trees and Random Forrest.py | Decision Trees and Random Forrest.py | py | 2,138 | python | en | code | 0 | github-code | 6 |
13446768071 | """ Отсортируйте по убыванию методом пузырька одномерный целочисленный массив,
заданный случайными числами на промежутке [-100; 100). Выведите на экран исходный
и отсортированный массивы.
"""
import random, math
def bubble_sort(array):
n = 1
while n < len(array):
change = 0
for i in ra... | byTariel/Algoritms | dz_7_task_1.py | dz_7_task_1.py | py | 860 | python | ru | code | 0 | github-code | 6 |
36651552794 | #!/usr/bin/python3
# Codeforces - Educational Round #90
# Author: frostD
# Problem B - 01 Game
def read_int():
n = int(input())
return n
def read_ints():
ints = [int(x) for x in input().split(" ")]
return ints
#---
def solve(s):
moves = 0
ms1 = s.split('10') # move set 1
ms2 = s.split('01') # move set 2... | thaReal/MasterChef | codeforces/ed_round_90/game.py | game.py | py | 709 | python | en | code | 1 | github-code | 6 |
19570224957 |
def read_cook_book(file, cook_book_):
list_temp = []
line1 = str(file.readline().strip())
num2 = int(file.readline())
i = 0
while i < num2:
line = file.readline()
list_line = line.split(' | ')
dict_ingr = {'ingredient_name': list_line[0],
'quantity': int... | IlAnSi/DZ_2_8 | Cook_Book.py | Cook_Book.py | py | 1,706 | python | en | code | 0 | github-code | 6 |
32756126137 | # !/usr/bin/python
import os
import sys
# Logging configuration
import logging
class logger(logging.Logger):
def __init__(self):
"""Initializer."""
super().__init__()
logging.basicConfig(filename="errlog.log",
filemode="a",
format="(%(asctime)s)... | MohdFarag/Musical-Instruments-Equalizer | src/logger.py | logger.py | py | 478 | python | en | code | 0 | github-code | 6 |
26023698980 | import matplotlib.pyplot as plt
import numpy as np
#plot 1
x=np.arange(-8,8,0.1)
y=x**3
plt.subplot(2,2,1)
plt.plot(x,y)
plt.title("plot 1")
#plot 2
x=np.linspace(0,3*np.pi,400)
y=x/(1+(x**4)*(np.sin(x))**2)
plt.subplot(2,2,2)
plt.plot(x,y)
plt.title("plot 2")
#plot 3
x=np.linspace(1,10,400)
y=np.sin(1/(x**(1/2)))
p... | suanhaitech/pythonstudy2023 | Wangwenbin/Matplotlib4.py | Matplotlib4.py | py | 492 | python | uk | code | 2 | github-code | 6 |
6794457250 | from __future__ import annotations
import typing
from dataclasses import dataclass
from anchorpy.borsh_extension import EnumForCodegen
import borsh_construct as borsh
class UninitializedJSON(typing.TypedDict):
kind: typing.Literal["Uninitialized"]
class ActiveJSON(typing.TypedDict):
kind: typing.Literal["Ac... | Ellipsis-Labs/phoenixpy | phoenix/types/market_status.py | market_status.py | py | 4,121 | python | en | code | 5 | github-code | 6 |
24883752413 | from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^$', 'informes.views.home', name='i_home'),
url(r'^pendientes/$', 'informes.views.informes_pendientes', name='i_pend'),
url(r'^arreglados/$', 'informes.views.informes_arreglados', name='i_fixed'),
url(r'^noarreglados/... | efylan/ccreservas | informes/urls.py | urls.py | py | 592 | python | es | code | 0 | github-code | 6 |
31559622204 | num = input()
#First Method for python
print(num[::-1])
#Second Method for c
num,a = int(num),0
while num > 0:
a = a*10 + num%10
num = num//10
print(a) | Shobhit0109/programing | EveryOther/python/Codes/New codes/Rev num in 2 ays.py | Rev num in 2 ays.py | py | 166 | python | en | code | 0 | github-code | 6 |
38336203002 | #!/usr/bin/python
from websocket import create_connection
import unittest
from common import read_info
from common import read_message
from common import check_action as c
import time
import json
class websocket_request(unittest.TestCase):
"""32. 安装脚本"""
def setUp(self):
rt=read_info.ReadInfo()
... | leen0910/websocket_api | websocket_api/test_case/test10_InstallScript.py | test10_InstallScript.py | py | 2,199 | python | en | code | 0 | github-code | 6 |
5897258860 | import pickle
import numpy as np
from flask import Flask, request, jsonify
# Load the pickled model
with open('model.pkl', 'rb') as file:
model = pickle.load(file)
app = Flask(__name__)
# Endpoint for making predictions
@app.route('/predict', methods=['POST'])
def predict():
try:
data = request.get_j... | mdalamin706688/copd-ml-model | app.py | app.py | py | 1,327 | python | en | code | 0 | github-code | 6 |
75114039226 | from timeit import default_timer as timer
import re
start = timer()
file = open('input.txt')
# exponential growth, every 7 days, after 0
# unsynchronized
# +2 day before first cycle
memo = {} # global const
def solve_babies(days, initial_clock, spawn_clock, cycle):
if initial_clock > days:
return 0
key = (days,... | kmckenna525/advent-of-code | 2021/day06/part2.py | part2.py | py | 1,044 | python | en | code | 2 | github-code | 6 |
10691788495 | import logging
from sentry.client.handlers import SentryHandler
logger = logging.getLogger()
# ensure we havent already registered the handler
if SentryHandler not in map(lambda x: x.__class__, logger.handlers):
logger.addHandler(SentryHandler(logging.WARNING))
# Add StreamHandler to sentry's default so y... | 8planes/langolab | django/web/sentry_logger.py | sentry_logger.py | py | 475 | python | en | code | 3 | github-code | 6 |
73080806907 | from NaiveTruthReader import NaiveTruthReader
from headbytes import HeadBytes
import numpy as np
feature_maker = HeadBytes(10)
reader = NaiveTruthReader(feature_maker, "test.csv")
reader.run()
data = [line for line in reader.data]
split_index = int(0.5 * len(data))
train_data = data[:split_index] # split% of data.
... | xtracthub/XtractPredictor | features/reader_test.py | reader_test.py | py | 967 | python | en | code | 0 | github-code | 6 |
72743745468 | from app.shared.common.recaptcha import CaptchaValidation
from app.shared.database.dynamodb_client import DynamodbClient
from app.shared.models import CustomerReviewModel
def main(object_id: str) -> dict:
dynamodb = DynamodbClient()
try:
dynamodb.contact_us.delete(object_id)
except Exception as err... | ishwar2303/graphidot-serverless-backend | app/functions/contact_us/delete_customer_message.py | delete_customer_message.py | py | 428 | python | en | code | 0 | github-code | 6 |
12483191239 | # reference: J. P. Tignol
# "Galois Thoery of Algebraic Equations" chapter 12
import numpy as np
from sympy import factorint,root,expand
class Period:# Gaussian periods
@classmethod
def init(cls,p):# p must be prime
n = p-1
g = 2 # generator mod p
f = factorint(n)
... | tt-nakamura/cyclo | cyclo.py | cyclo.py | py | 5,447 | python | en | code | 0 | github-code | 6 |
20216419382 | from model.flyweight import Flyweight
from model.static.database import database
class Operation(Flyweight):
def __init__(self,activity_id):
#prevents reinitializing
if "_inited" in self.__dict__:
return
self._inited = None
#prevents reinitializing
self.activity... | Iconik/eve-suite | src/model/static/sta/operation.py | operation.py | py | 1,189 | python | en | code | 0 | github-code | 6 |
18002323535 | from hydra import compose, initialize
import logging
import torch
from torch.utils.tensorboard import SummaryWriter
from data.dataset import get_dex_dataloader
from trainer import Trainer
from utils.global_utils import log_loss_summary, add_dict
from omegaconf import OmegaConf
from omegaconf.omegaconf import open_dict... | PKU-EPIC/UniDexGrasp | dexgrasp_generation/network/train.py | train.py | py | 4,171 | python | en | code | 63 | github-code | 6 |
1999311786 | import os
from enum import Enum, auto
from random import randint
import pygame
class Main:
@staticmethod
def start():
pygame.font.init()
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (400, 100)
surface = pygame.display.set_mode((1200, 900))
pygame.display.set_caption('Mineswe... | MaximCosta/messy-pypi | messy_pypi/done/main_minesweeper.py | main_minesweeper.py | py | 7,807 | python | en | code | 2 | github-code | 6 |
3885504768 | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.html import mark_safe
from rooms.models import Room
from .models import User
# admin.ModelAdmin을 상속받는 경우
# @admin.register(User)
# class CustomUserAdmin(admin.ModelAdmin):
# """ Custom User Admin """
# list_di... | Odreystella/Pinkbnb | users/admin.py | admin.py | py | 1,838 | python | en | code | 0 | github-code | 6 |
42660213870 | # read the sequence file to python
n = 0
for line in open("ampR.fastq"):
line = line.strip()
if not line:
continue
n += 1
# starts with '@'
if line.startswith("@") and n != 4:
name = line[1:].split(" ", maxsplit=1)[0]
seq = score = ""
n = 1
elif n == 2:
s... | FlyPythons/Python-and-Biology | data/1/read_fastq.py | read_fastq.py | py | 647 | python | en | code | 2 | github-code | 6 |
11844211331 | from flask import Flask, render_template, request
from mbta_helper import find_stop_near
app = Flask(__name__, template_folder="templates")
@app.route("/")
def index():
"""
This function asks for the user's location
"""
return render_template("index.html")
@app.route("/POST/nearest", methods=["POST... | nandini363/Assignment-3 | app.py | app.py | py | 917 | python | en | code | 0 | github-code | 6 |
17372597106 | # LinearlyVariableInfill
"""
Linearly Variable Infill for 3D prints.
Author: Barnabas Nemeth
Version: 1.5
"""
from ..Script import Script
from UM.Logger import Logger
from UM.Application import Application
import re #To perform the search
from cura.Settings.ExtruderManager import ExtruderManager
from collections imp... | vaxbarn/LinearlyVariableInfill | LinearlyVariableInfill.py | LinearlyVariableInfill.py | py | 21,725 | python | en | code | 0 | github-code | 6 |
20040130347 | from random import choice
def get_binary():
output = []
for i in range(8):
output.append(choice([0,1]))
return output
def get_binary_sum():
output = []
for i in range(8):
output.append(choice([0,1]))
return sum(output)
samps = []
counts = 0
while 0 not in samps:
samps.app... | mwboiss/DSI-Prep | intro_py/binary_sum.py | binary_sum.py | py | 385 | python | en | code | 0 | github-code | 6 |
35160550288 | from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.db.models import Q
from .models import Employee
from .forms import AddEmployeeForm
@login_required(login_url='authapp:login')
def index(request):
context = dict(... | somukhan9/django-employee-management-system | employee/views.py | views.py | py | 3,206 | python | en | code | 0 | github-code | 6 |
7848372415 | import time
import numpy as np
import json
from simplex_algorithm.Interaction import Interaction
class SimplexSolver():
'''
Class is responsable to solve maximization Linear Programming Problems.
@author: Matheus Phelipe
'''
def __init__(self, matrix_a, matrix_b, matrix_c, max_iteractions, has_... | matheusphalves/simplex-algorithm | simplex_algorithm/SimplexSolver.py | SimplexSolver.py | py | 4,877 | python | en | code | 0 | github-code | 6 |
35560642063 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from mayavi import mlab
from scipy.ndimage import map_coordinates
from scipy import signal, interpolate
from PIL import Image, ImageDraw
from matplotlib.colors import ListedColormap
from tqdm import tqdm, trange
def create_block_diagram(strat, prop, ... | zsylvester/stratigraph | stratigraph/stratigraph.py | stratigraph.py | py | 50,938 | python | en | code | 8 | github-code | 6 |
582921826 | import numpy as np
import argparse
# parser = argparse.ArgumentParser(description='Keypoints distance computing script')
# parser.add_argument(
# '--origin_image_file', type=str, required=False,
# help='path to a file containing the keypoints and descriptors of the first image'
# )
# parser.add_argument(
#... | vqlion/PTIR-Image-Processing | test_keypoints_distance.py | test_keypoints_distance.py | py | 2,595 | python | en | code | 0 | github-code | 6 |
5308746110 | from copy import deepcopy
arr = [[None]*4 for _ in range(4)]
for i in range(4):
row = list(map(int, input().split()))
for j in range(4):
# (번호, 방향)
arr[i][j] = [row[j*2], row[j*2+1]-1]
dirs = [(-1, 0), (-1, -1), (0, -1),
(1, -1), (1, 0), (1, 1), (0, 1), (-1, 1)]
# 현재 위치에서 왼쪽으로 회전된 결과... | louisuss/Algorithms-Code-Upload | Python/DongbinBook/simulation/kid_shark_solution.py | kid_shark_solution.py | py | 2,490 | python | ko | code | 0 | github-code | 6 |
37076357644 | """
Find the LCA of Binary Tree.
https://www.youtube.com/watch?v=13m9ZCB8gjw
"""
def lca(root, n1, n2):
if root is None:
return None
if root.data == n1 or root.data == n2:
return root
node_left = lca(root.left, n1, n2)
node_right = lca(root.right, n1, n2)
if node_left is not Non... | piyush9194/data_structures_with_python | data_structures/trees/lowest_common_ancestor_bt.py | lowest_common_ancestor_bt.py | py | 502 | python | en | code | 0 | github-code | 6 |
41039585752 | import logging
import random
import string
import time
import sys
from decimal import Decimal
from typing import Any, Callable, Optional, TypeVar, Union
import requests
from vega_sim.grpc.client import VegaCoreClient, VegaTradingDataClientV2
from vega_sim.proto.data_node.api.v2.trading_data_pb2 import GetVegaTimeReque... | vegaprotocol/vega-market-sim | vega_sim/api/helpers.py | helpers.py | py | 6,261 | python | en | code | 19 | github-code | 6 |
34465917082 | import torch
from torch.utils.data import DataLoader
from .coco_dataset import build_dataset
def batch_collator(batch):
images, boxmgrs = list(zip(*batch))
images = torch.stack(images, dim=0)
return images, boxmgrs
def build_dataloader(cfg, is_train=True):
dataset = build_dataset(cfg, is_train=is_t... | lmyybh/computer-vision | yolo/yolo/data/dataloader.py | dataloader.py | py | 558 | python | en | code | 0 | github-code | 6 |
15018597005 | from utils.utils import OS
import sys
if OS.Linux:
import matplotlib
matplotlib.use("agg")
import json
import math
import multiprocessing
import random
from multiprocessing import Pool
from threading import Thread
from typing import Union, Callable
from uuid import UUID
import networkx
from Model.Computatio... | Moni5656/npba | Model/ModelFacade.py | ModelFacade.py | py | 30,489 | python | en | code | 0 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.