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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
15718283398 | # import eventlet
# eventlet.monkey_patch()
from flask import Flask, request, jsonify, render_template
from flask_socketio import SocketIO, emit
from flask_cors import CORS
import time
import pandas as pd
import numpy as np
from math import sqrt
import heapq
from copy import deepcopy
import json
app = Flask(__name__... | GunjanAS/RepeatedAStar-algo-visualizer | app.py | app.py | py | 13,501 | python | en | code | 0 | github-code | 1 |
10581112484 | import csv
with open('dataset.csv','r') as f:
reader = csv.reader(f)
header_row = next(reader)
ip=[]
tp=[]
for row in reader:
# print(row[0])
ip.append(row[0])
tp.append(row[1])
f.close()
nip=[]
ntp=[]
for i in ip:
if i not in nip:
nip.append(i)
count =ip.index(i)
ntp.append(tp[count... | MieMieWangWang/SNS | dataset.py | dataset.py | py | 572 | python | en | code | 0 | github-code | 1 |
11286756056 | import argparse
import cv2
import minerl
import numpy as np
import plotly.express as px
import random
import streamlit as st
from pathlib import Path
import time
@st.cache(suppress_st_warning=True, allow_output_mutation=True, max_entries=1)
def get_timeseries_actions_fig(actions_wide, action_labels, rewards):
st.... | JunShern/minerl-trajectory-viewer | main.py | main.py | py | 6,347 | python | en | code | 0 | github-code | 1 |
71015536355 | # Title: 감소하는 수
# Link: https://www.acmicpc.net/problem/1038
import itertools
import sys
sys.setrecursionlimit(10 ** 6)
def read_list_int():
return list(map(int, sys.stdin.readline().strip().split(' ')))
def read_single_int():
return int(sys.stdin.readline().strip())
def add_to_one(d_numb... | yskang/AlgorithmPractice | baekjoon/python/decreasing_number_1038.py | decreasing_number_1038.py | py | 1,814 | python | en | code | 1 | github-code | 1 |
10786967423 | #Number guessing program on the command line.
#Guess the number (between 1 and 10) and see if you are right!
#Written by Caleb Phillips (LebbyFoxx).
#Monday 28th September 2020.
import random
#Function that randomises number.
def numGuess():
#Variable 'tries' is set to 5 (and will be reduced if the ans... | Lebyfochs/RandomPython | NumberGuessCLI.py | NumberGuessCLI.py | py | 1,942 | python | en | code | 0 | github-code | 1 |
32351368644 | #!/usr/bin/env python
"""
This script creates an injection and a .ini file to run LALInference
(C) Archisman Ghosh, Abhirup Ghosh, 2015-09-20
"""
import sys, lal, os, commands, numpy as np
sys.path.insert(1, os.path.join(os.path.expanduser('~'), 'src/lalsuite/lalinference/python'))
import imrtestgr as tgr
import nr_... | abhirup-ghosh/testGR_IR | scripts/create_recovery_abhi.py | create_recovery_abhi.py | py | 6,320 | python | en | code | 0 | github-code | 1 |
3157406584 | from user_access import data_read, data_write
class User:
def __init__(self, *args, **kwargs):
self.__dict__.update(kwargs)
@classmethod
def create_user(cls, *args, **kwargs):
user = cls(*args, **kwargs)
user.save()
return user
def save(self):
users_data = da... | Samuel-Koomson/MVP-Complete | Alx_portfolio_project/users/user.py | user.py | py | 854 | python | en | code | 0 | github-code | 1 |
3214676513 | #!/usr/bin/env python3
#-*- coding: utf-8 -*-
def plantilla_ahorcado( palabra, lista_letras, lista_errores):
""" plantilla que crea a partir de una palabra y dos listas con aciertos y errores
la figura del juego del ahorcado """
persona = ("O", "|", "/", "\\","/", "\\")
horca = [" ", " ", " ", " ", " ... | lucianomartinez27/console-games | ahorcado/funciones.py | funciones.py | py | 782 | python | es | code | 0 | github-code | 1 |
34462986189 | def checkMagazine(magazine, note):
mag = {}
match = 'Yes'
for word in magazine:
if word in mag:
mag[word] += 1
else:
mag[word] = 1
for word2 in note:
if word2 in mag:
mag[word2] -= 1
if mag[word2] < 0:
ma... | Kakurouta/Python_Problem_Solving | HashTables_RansomNote.py | HashTables_RansomNote.py | py | 389 | python | en | code | 0 | github-code | 1 |
23150118653 | import pymol
from pymol import cmd
class PymolRun:
@staticmethod
def main(queue):
print('### LAUCH PYMOL')
pymol.finish_launching()
cmd.fetch('1d86')
while True:
# {'cmd': [0, 1, 3]}
# If the queue is empty, queue.get() will block until the q... | capotandrei/natural-interaction-with-molecular-graphics-programs | pymol_class.py | pymol_class.py | py | 1,071 | python | en | code | 1 | github-code | 1 |
32105962555 | #!/usr/bin/env python3
"""Contains function sum_list"""
from typing import Union, List
def sum_mixed_list(mxd_list: List[Union[int, float]]) -> float:
"""Calculates the sum of floats in the given list"""
sum: float = 0.00
for num in mxd_list:
sum += num
return sum
| Caesar-12/alx-backend-python | 0x00-python_variable_annotations/6-sum_mixed_list.py | 6-sum_mixed_list.py | py | 292 | python | en | code | 0 | github-code | 1 |
21843690643 | class Solution:
def findMin(self, nums: List[int]) -> int:
if len(nums) == 1 or nums[0] < nums[-1]:
return nums[0]
l, r = 0, len(nums) - 1
while l <= r:
mid = l + ((r - l) >> 1)
if nums[mid - 1] > nums[mid]:
r... | uditmanav17/leetcode | 153-find-minimum-in-rotated-sorted-array/153-find-minimum-in-rotated-sorted-array.py | 153-find-minimum-in-rotated-sorted-array.py | py | 601 | python | en | code | 0 | github-code | 1 |
73696765472 | import os, sys
import gym
import torch
import cv2
import numpy as np
import random
import time
import schedule
sys.path.append("./")
from network.backbone import BasicNet
from policy_optimizer import Optimizer
from network.dqn import DQN
from utils.dataloader import tnx2batch, batch4net
from utils.atari_wrapper import ... | fangyuedong/rainbow-with-ray | agent.py | agent.py | py | 8,661 | python | en | code | 6 | github-code | 1 |
23844910762 | from collections import deque
from contextlib import contextmanager
from string import Template
from textwrap import dedent
import dominate
from dominate.tags import *
from dominate.util import text
import arcade.examples
import pathlib
import math
import demos.lib02
import demos.movement
def main():
with open('... | cjrh/pyconau2018-arcade2Dmultiplayer | generate_slides.py | generate_slides.py | py | 22,383 | python | en | code | 6 | github-code | 1 |
42956395054 | __all__ = ["load", "save", "load_single_particle_model", "load_multi_particle_model"]
import os
import numpy as np
import tensorflow as tf
import deeptrack as dt
from tqdm import tqdm
import glob
import pandas as pd
def load(filename: str):
*_, ext = filename.split(os.path.extsep)
if os.path.isdir(filename):... | BenjaminMidtvedt/AutoTracking | autotracker/fs.py | fs.py | py | 2,200 | python | en | code | 1 | github-code | 1 |
22777502445 | import numpy as np
from pbcore.io import BamReader, IndexedBamReader, IndexedFastaReader, AlignmentSet
import pickle
import sys
import itertools
import pandas as pd
import gzip
import pysam
from array import array
from tqdm import tqdm, trange
# Kinetics tools can be found https://github.com/PacificBiosciences/kineti... | amaslan/dimelo-seq | ctcf_and_h3k9me3/PerMoleculeIPDRatio.py | PerMoleculeIPDRatio.py | py | 5,676 | python | en | code | 3 | github-code | 1 |
674861904 | import sys
if sys.version_info.major == 2:
import httplib
from base64 import decodestring as base64_decode
from StringIO import StringIO as StringLikeIO
else:
from http import client as httplib
from base64 import decodebytes as base64_decode
from io import BytesIO as StringLikeIO
import base64... | maibrahim2016/background_removal | src/tests/test_microservice_response.py | test_microservice_response.py | py | 10,637 | python | en | code | 0 | github-code | 1 |
24913233421 | import requests
from get_access_token_by_refresh_token import get_access_token
def get_modules():
url = 'https://www.zohoapis.in/crm/v2/settings/modules'
access_token = get_access_token()
headers = {
'Authorization': 'Zoho-oauthtoken {}'.format(access_token)
}
response = requests.get(url=... | kirankigi5/remote_pregnancy_monitor | Remote-pregnancy-monitor-main/zoho_apis/fetch_modules.py | fetch_modules.py | py | 484 | python | en | code | 0 | github-code | 1 |
21150388793 | import flet as ft
import views as views_handle
def main(page: ft.Page):
#defining the fonts
page.fonts = {
"SF Pro": "https://raw.githubusercontent.com/google/fonts/master/ofl/sfprodisplay/SFProDisplay-Bold.ttf",
}
#defining the window size
page.window_min_width = 425
page.win... | Sirapobchon/CPE334Project | fletapp/main.py | main.py | py | 997 | python | en | code | 0 | github-code | 1 |
18720834678 | #길이제한 해주는 프로그램 GPT3 최대 2048개의 토큰 처리 가능
import pandas as pd
from transformers import GPT2Tokenizer
def trim_to_combined_token_limit(csv_file, max_tokens=2048):
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
df = pd.read_csv(csv_file)
for idx, row in df.iterrows():
# convert 'nan' or empty inputs... | Dumul-KJH/everytime_ai | everytime_length.py | everytime_length.py | py | 1,693 | python | en | code | 0 | github-code | 1 |
26166079305 | #问题011:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子。假如兔子都不死。问每个月的兔子总数为多少?
#【思路分析】这其实就是斐波拉契数列的由来,可以思考斐波拉契数列的打印过程
'''
实际解决这题时,按照事实的逻辑顺序来解题即可,即:
第一个月有一对小兔子,
第二个月一对小兔子长成了一对大兔子
第三个月,一对大兔子生出了一对小兔子,原本的一对大兔子都不死
每个月的过程是:
大兔子每月生小兔子
原先的小兔子长成2月兔(下月生育)
大兔子不死
'''
smallrabi=1
grownrabi=0
oldrabi=0
for month in range(1,... | JohnWang7802/python-100- | 100_11.py | 100_11.py | py | 1,014 | python | zh | code | 0 | github-code | 1 |
6180786354 | from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from datetime import datetime
##
## begin util functies
##
def nvl(value,default_value) :
return default_value if value is None else value
##
## einde util functies
##
cla... | nosinga/parool | djp/dj_breev/breev/models.py | models.py | py | 5,799 | python | en | code | 1 | github-code | 1 |
39307547167 | import numpy as np
# gradient descent는 tensorflow에 이미 구현이 되어있다.
# 확률적 선형 뉴런 분석기는 각 훈련 샘플에 대해서 조금씩 가중치를 업데이트 한다.
class LogisticRegressionGD(object):
"""경사 하강법을 이용한 Logistic regression 분류기
매개변수
------------
eta : float
학습률 (0.0과 1.0 사이)
n_iter : int
훈련 데이터셋 반복 횟수
rando... | Wookhwang/Machine-Learning | Sciket_logistic_regression/src/LogisticRegressionGD.py | LogisticRegressionGD.py | py | 2,711 | python | ko | code | 0 | github-code | 1 |
73782221473 | # coding: utf-8
from pycparser import c_parser, c_ast
from cflags_loader import read_compiler_dflags_lib, get_cpp_dflags
from c_preprocessing import preprocess
def parse_text(text):
parser = c_parser.CParser()
ast = parser.parse(text, filename="<none>")
return ast
def get_ast(grouprep, filename, includ... | sa2c/shoplifter | files_and_functions/ast_parsing.py | ast_parsing.py | py | 1,801 | python | en | code | 0 | github-code | 1 |
31891577704 | # test_dbmanager.py
import unittest
import os
from binance import enums as k_binance
from src.pp_order import Order, OrderStatus
from polaris_old.pp_dbmanager import DBManager
TEST_DATABASE = 'test.db'
class TestDBManager(unittest.TestCase):
def setUp(self) -> None:
try:
os.remove(TEST_DATA... | xavibenavent/polaris_plus | tests/test_dbmanager.py | test_dbmanager.py | py | 1,945 | python | en | code | 0 | github-code | 1 |
36367821093 | # -*- coding: utf-8 -*-
"""
This module containes a set of thin wrappers to
hook the methods in postprocess package to X-ray
absorption tomography data object.
"""
# Import main TomoPy object.
from syncpy.tomopy.xtomo.xtomo_dataset import XTomoDataset
# Import available functons in the package.
from syncpy.tomopy.a... | decarlof/syncpy | syncpy/tomopy/xtomo/xtomo_postprocess.py | xtomo_postprocess.py | py | 4,608 | python | en | code | 0 | github-code | 1 |
34139411643 | class Solution:
def validPalindrome(self, s: str) -> bool:
i = 0
j = len(s)-1
while i<j:
if s[i]!=s[j]:
leftPointer=s[i+1:j+1]
rightPointer=s[i:j]
return leftPointer == leftPointer[-1::-1] or rightPointer == rightPointer[-1::-1]
... | rawanelbanaa/ProblemSolving_LeetCode | 0680-valid-palindrome-ii/0680-valid-palindrome-ii.py | 0680-valid-palindrome-ii.py | py | 396 | python | en | code | 0 | github-code | 1 |
25142773814 | import unittest
from ..app.player import Player
from ..app.board import Board
class TestPlayer(unittest.TestCase):
"""docstring for TestPlayer."""
def test_player_name_on_object_creation(self):
self.player = Player("Tester Testersen")
player_name = self.player.get_name()
self.assertEq... | thomakj/battleship | tests/test_player.py | test_player.py | py | 880 | python | en | code | 0 | github-code | 1 |
10913932737 | import logging
from tvm import topi, te
from tvm.target import Target
from .. import tag
def schedule_pool(outs, layout):
"""Create schedule for avgpool/maxpool"""
if layout != "NHWC":
logger = logging.getLogger("topi")
logger.warning(
"""We currently only support NHWC target spec... | LiRWZ/tvm | python/tvm/topi/arm_cpu/pooling.py | pooling.py | py | 4,116 | python | en | code | null | github-code | 1 |
18105290044 | def get_inputs(filename: str):
with open(filename, "r") as file:
lines = file.read().splitlines()
first = lines[0].split(" ")
N = int(first[0])
M = int(first[1])
n = lines[1].split(" ")
numbers = []
for v in n:
numbers.append(int(v))
return (N, M, numbers)
for i in... | akornfellner/PROO_2DHIF | CCC/Parkgarage/python/level2.py | level2.py | py | 909 | python | en | code | 4 | github-code | 1 |
20199877377 | import random
from astral import Astral
from datetime import datetime, timedelta, time
from timedevent import TimedEvent
from scenes import VACATION_SCENES
import logging
logger = logging.getLogger(__name__)
#
# This event builds the script of events for vacation mode for a single day. Once it executes, it will... | RalphLipe/homecontrol | vacationmode.py | vacationmode.py | py | 4,044 | python | en | code | 0 | github-code | 1 |
2962763568 | import torch
def eval_model(model, loader, device):
with torch.no_grad():
test_accuracy = []
for input, target in loader:
input, target = input.to(device), target.to(device)
output = model(input)
batch_accuracy = (output.argmax(dim=1) == target).float()
... | kefirski/pruning | utils.py | utils.py | py | 421 | python | en | code | 0 | github-code | 1 |
136133084 | """
PCBA dataset loader.
"""
import os
import logging
import deepchem
import gzip
logger = logging.getLogger(__name__)
DEFAULT_DIR = deepchem.utils.data_utils.get_data_dir()
def load_pcba(featurizer='ECFP',
split='random',
reload=True,
data_dir=None,
save_dir=... | jem0101/BigSwag-SQA2022-AUBURN | TestOrchestrator4ML-main/resources/Data/supervised/GITHUB_REPOS/deepchem@deepchem/deepchem/molnet/load_function/pcba_datasets.py | pcba_datasets.py | py | 5,859 | python | en | code | 2 | github-code | 1 |
32893793613 | import tensorflow as tf
# Our warm-up example turned into single-process "cluster".
server = tf.train.Server.create_local_server()
greeting = tf.constant('Hello, distributed Prague!')
with tf.Session(server.target) as sess:
result = sess.run(greeting)
print(result)
# We can also use the same cluster configur... | valohai/ml-prague-2019-workshop | src/02-distributed/basics.py | basics.py | py | 654 | python | en | code | 5 | github-code | 1 |
40172072893 | '''This module contains the collaborative filtering algorithms based on user similarity.
'''
import math
from operator import itemgetter
def user_sim_matrix(train):
'''user_sim_matrix(dict) -> dict
This will return the user similarity matrix. Use it when the train set is not very large.
'''
sim_matr... | cyrusin/pyresys | rec/user_cf.py | user_cf.py | py | 4,183 | python | en | code | 1 | github-code | 1 |
23765184542 | import os
import glob
import shutil
def main():
with open("files.txt") as f:
lines = f.read().splitlines()
lines = [l.strip() for l in lines]
for l in lines:
print(l)
for fl in glob.glob(os.path.expanduser(l)):
if not os.path.isf... | Funami580/dotfiles-s6-sway | update.py | update.py | py | 1,073 | python | en | code | 2 | github-code | 1 |
4220134129 | sentence = "I am the very model of a modern major general. something something"
fixed = ""
for index in range(len(sentence)):
if index >= 2 \
and fixed[index-2] == '.' \
and fixed[index-1] == " ":
fixed += sentence[index].upper()
else:
fixed += sentence[index]
print(fi... | CleverAndWitty/CIS1501-Fall2018 | Lab5/strings.py | strings.py | py | 325 | python | en | code | 0 | github-code | 1 |
75021518114 | import numpy as np
def constructAdjM(input_file):
'''
Constructs adjacency matrix
'''
with open(input_file, "r") as inFile:
S = inFile.readline().split()
V, E = int(S[0]), int(S[1])
adjM = []
for i in range(V):
adjM.append(V * [0])
for _ in range... | Siddhesh-Shukla/Information-Retrieval | A2. Page Ranking/A/graph.py | graph.py | py | 2,376 | python | en | code | 0 | github-code | 1 |
4016584342 | import os
import numpy as np
import rasterio as rio
import rasterio.features
import geopandas as gpd
import rasterstats
def find_underlying_vector_value(starting_objects, starting_objects_identifying_column, objects_to_select,
objects_to_select_attribute_column):
"""
Find the ... | DaisyMeadow/EGM722_Assessment | Site_characteristics.py | Site_characteristics.py | py | 25,072 | python | en | code | 0 | github-code | 1 |
3267556703 | from __future__ import absolute_import, division, print_function
import os
import sys
import glob
import argparse
import numpy as np
import PIL.Image as pil
import PIL.ImageOps
import matplotlib as mpl
import matplotlib.cm as cm
import matplotlib.pyplot as plt
from skimage.segmentation import mark_boundaries
from sc... | LeungTsang/Depth-W-Net | seg_eval.py | seg_eval.py | py | 9,369 | python | en | code | 0 | github-code | 1 |
41057271021 | import tkinter as tk
from tkinter import filedialog
from module.logger import write_log
def select_folder() -> str:
"""エクスプローラー画面でフォルダ選択"""
root = tk.Tk()
root.withdraw()
folder_path = filedialog.askdirectory()
write_log('select_folder path:' + folder_path)
return folder_path
def select_json_file() -> str:
"... | pinfu-jp/MergeFilesByPython | module/select_folder.py | select_folder.py | py | 678 | python | en | code | 2 | github-code | 1 |
3781723308 | from Button import Button
from Globals import Steering
class AIButton(Button):
isPlayingwithAI = False
text1 = "AI"
text2 = "1v1"
def __init__(self,text,x,y,width,height, paddle):
Button.__init__(self,text,x,y,width,height)
self.paddle = paddle
def AI(self):
s... | igabiernat/Pong | AIButton.py | AIButton.py | py | 697 | python | en | code | 0 | github-code | 1 |
70960375393 | '''
Universidad del Valle de Guatemala
Redes - 2021
DVR.py
Roberto Figueroa 18306
Luis Quezada 18028
Esteban del Valle 18221
'''
from slixmpp.basexmpp import BaseXMPP
from node import Node
from asyncio import sleep
from aioconsole import aprint
from time import time
from xml.etree import ElementTree as ET
import jso... | Crismaria11/lab3-redes | DVR.py | DVR.py | py | 7,570 | python | en | code | 0 | github-code | 1 |
17019893795 | import pickle
from constants import Constants
from quotes import fetch_quotes, get_the_quote
from music import music_classify, get_songs
from movies import movies_classify, get_movies
from images import ImageDatasetProcessing, get_images
from books import books_classify, get_books
class Recommendations:
def ... | radhakumaran/MoodSeek | recommendations.py | recommendations.py | py | 2,964 | python | en | code | 1 | github-code | 1 |
20635589950 | import pysam, sys, getopt
argv = sys.argv[1:]
opts, args = getopt.getopt(argv, 'i:o:t:f:')
input_file = None
output_directory = None
tag = None
names = None
for opt, arg in opts:
if opt == '-i':
input_file = arg
elif opt == '-o':
output_directory = arg
elif opt == '-t':
tag = arg
... | vdblm/SinglePolyA | codes/bam_splitter.py | bam_splitter.py | py | 1,310 | python | en | code | 0 | github-code | 1 |
23870105129 | from PyQt5 import QtWidgets
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QSize, Qt
from .widgets import ControlButton, ScrollableButton, Seekbar, PlaybackModeControlButton
from .uilib.util import mask_image_circ, shadowify, setElide
class PlayerInfoFrame(QtWidgets.QFrame):
def __init__(self, p):
... | blitpxl/phonoid | src/app/ui/playerpanel.py | playerpanel.py | py | 6,635 | python | en | code | 15 | github-code | 1 |
24603697811 | from flask import Flask, request, jsonify
import json
# 将当前程序作为web app应用
# 配置static模式
# static_folder静态文件的路径
app = Flask(__name__,static_folder='static',static_url_path='/')
@app.route(rule='/sales', methods=['GET'])
def post_test():
# 附加题: 从excel表中读取这些数据
sales_data = [20, 20, 30, 10, 10, 15]
... | miaozilong/ruantong-xinagjianguniversity | 上课演示/2023-07-06/上午/4.py | 4.py | py | 489 | python | en | code | 0 | github-code | 1 |
73944547232 | import training.dataset
import unittest
import model.rigid_body_model as rbm
import model.param as model_param
import numpy as np
from scipy.spatial.transform import Rotation as R
class TestDexGraspDataset(unittest.TestCase):
def setUp(self) -> None:
self.hand_plant = rbm.AllegroHandPlantDrake(meshcat_open... | Ericcsr/synthesize_pregrasp | neurals/test/test_dataset.py | test_dataset.py | py | 6,574 | python | en | code | 8 | github-code | 1 |
36924729027 | import requests
from bs4 import BeautifulSoup
def music_Leaderboard(input_country):
country = {"西洋": "3",
"日韓": "2",
"華語": "1"}
req = requests.get(
'https://www.kiss.com.tw/music/billboard.php?a=%s' % (country[input_country]))
soup = BeautifulSoup(req.text, 'html.pars... | Yicheng-1218/line_bot | music.py | music.py | py | 773 | python | en | code | 0 | github-code | 1 |
33974716392 | # pragma: no cover
"""
This module defines a bounding box type and implements a constraint solver
that can position multiple bounding boxes s/t they do not overlap
(in addition to other constraints).
main() function used for testing purposes. Primary function made available to outside callers
is run_model()
"""
from i... | Tubbz-alt/adam | adam/visualization/positioning.py | positioning.py | py | 48,738 | python | en | code | null | github-code | 1 |
1095510646 | from pylab import *
from matplotlib.patches import FancyArrow
# Foreman-Mackey's taste in figures
rc("font", size=20, family="serif", serif="Computer Sans")
rc("text", usetex=True)
import word
import parameters
t = linspace(-10., 10., 10001)
plot(t, word.TwoExp(t).model(parameters.TwoExpParameters(1.0, 0.5, 1., 3., ... | dhuppenkothen/magnetron_old | figs.py | figs.py | py | 1,025 | python | en | code | 0 | github-code | 1 |
42882290933 | from Calc import calc
if __name__ == '__main__':
number_operation = input("Введіть кількість операцій: \t")
try:
number_operation = int(number_operation)
except ValueError:
print("Ви ввели не вірне значеня!")
else:
if number_operation > 0:
i = 2
firs... | imbull/HW_Gaponenko | Main.py | Main.py | py | 1,733 | python | uk | code | 0 | github-code | 1 |
27170748674 | # Aaron Yerke, HW 2 for ML 2019
# 1. (50 points) Implement gradient descent-based logistic regression in Python. Use
# ∆J = 0.00001 as the stopping criterion.
# 2. (50 points total distributed as below) Apply your code from question 2 to the iris virginica and virsicolor flowers.
# Specifically, randomly select 99 of t... | palomnyk/machineLearningFall2019 | assignment2/assignment2.py | assignment2.py | py | 8,129 | python | en | code | 0 | github-code | 1 |
74043067873 | import bluetooth
import time
import serial # 导入模块
import zxing
import numpy as np
import time
import cv2 as cv
reader = zxing.BarCodeReader()
log_counter = 0
start_time = time.time()
IMG_PATH='/home/pi/Documents/gx/0003.jpg'
# set blue thresh 设置HSV中蓝色、天蓝色范围
lower_red = np.array([0,43,46])
upper_red = np.array([15,255... | darrrt/EngineeringInnovationComp2023 | deprecated/multi-communication/deprecated/all-1.py | all-1.py | py | 5,732 | python | en | code | 12 | github-code | 1 |
419217840 | #!/usr/bin/env python
import os
import json
import argparse
from pprint import pprint
from pathlib import Path
import requests
from requests.auth import HTTPBasicAuth
import jwt
from dotenv import find_dotenv, load_dotenv
DOTENV_PATH = find_dotenv()
if DOTENV_PATH:
load_dotenv(DOTENV_PATH)
KEYCLOAK_HOST = os.en... | kids-first/kf-api-fhir-service | web_app/auth.py | auth.py | py | 3,396 | python | en | code | 5 | github-code | 1 |
7283766876 | import time
import numpy as np
import dolfin as df
import petsc4py as p4py
import reduced_models.vasculature_io as vio
from integrate_2d_surface import integrate_2d_surface, integrate_2d_surface_mat
class NutrientSolver:
def __init__(self, mesh, kappa) -> None:
self.function_space = V = df.FunctionSpace(m... | wagnandr/immunotherapy-lung-cancer | reduced_models/nutrients_robin.py | nutrients_robin.py | py | 4,530 | python | en | code | 0 | github-code | 1 |
38810876405 | import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
####################################################################################################
#####################################... | SilvesterYu/CMU-AdvancedComputerVision | lifany_hw4/python/nnq6.py | nnq6.py | py | 7,704 | python | en | code | 1 | github-code | 1 |
10192095448 | from copy import deepcopy
fn = "input.txt"
# fn = "test.txt"
def part1(data):
pass
def part2(data):
pass
class Grid:
def __init__(self):
self.g = {}
self.min_x = 100000
self.max_x = -100000
self.min_y = 100000
self.max_y = -100000
self.min_z = 100000
... | ahenshaw/aoc2020 | aoc17/solver2.py | solver2.py | py | 2,974 | python | en | code | 0 | github-code | 1 |
23150403791 | import sys
import pathlib
import json
def get_settings_dir(name) -> pathlib.Path:
"""
Returns a parent directory path
where persistent application data can be stored.
# linux: ~/.local/share
# macOS: ~/Library/Application Support
# windows: C:/Users/<USER>/AppData/Roaming
"""
home = ... | djaney/arcassistant | arcassistant/shared/settings.py | settings.py | py | 1,710 | python | en | code | 1 | github-code | 1 |
41330510557 | from databases import Database
from sqlalchemy import select, func
from typing import Dict
from db import models
from schemas import companies_members as schema_cm
from utils.exceptions import MyExceptions
class GenericDatabase:
def __init__(self, db: Database):
self.db = db
self... | zxc322/fast_api_app | repositories/services/generic_database.py | generic_database.py | py | 1,363 | python | en | code | 0 | github-code | 1 |
1309363052 | from flask import current_app
from sqlalchemy import asc, desc
from sqlalchemy.exc import SQLAlchemyError
from app import db
from app.businesses.exceptions import EntityNotFoundException
from app.businesses.models import Business, Category, Tag, BusinessUpload
CONTAINS = '%{}%'
class BaseRepository(object):
mod... | Baobab-team/baobab-api | app/businesses/repositories.py | repositories.py | py | 4,612 | python | en | code | 0 | github-code | 1 |
24879635403 | from sqlalchemy.engine import Connection
from saltapi.repository.finder_chart_repository import FinderChartRepository
from saltapi.service.finder_chart_service import FinderChartService
def test_get_finder_chart(db_connection: Connection) -> None:
finding_chart_id = 55345
expected_proposal_code = "2015-2-SCI... | saltastroops/salt-api | tests/service/test_finder_chart_service.py | test_finder_chart_service.py | py | 769 | python | en | code | 0 | github-code | 1 |
24814790092 | import numpy as np
import pandas as pd
class AdalineSGD(object):
def __init__(self, eta, n_iter, shuffle=True, random_state=1):
self.eta = eta
self.n_iter = n_iter
self.shuffle = shuffle
self.is_initialized = False
self.random_state = random_state
def fit... | EmilWalewski/Machine-learning | LogisticRegression.py | LogisticRegression.py | py | 1,499 | python | en | code | 0 | github-code | 1 |
26816965336 | def search():
w = input("请输入要查询的单词:")
fr = open("test.txt", 'r')
dic = {}
for line in fr.readlines():
line = line.replace("\n", "")
line = list(line.split(","))
key = line[0]
coment = line[1:]
dic[key] = coment #
if w in dic.keys():
print(dic[w])
... | jianjiachenghub/PythonClass | Class8/5120173407_周杰_second191022153024.py | 5120173407_周杰_second191022153024.py | py | 1,455 | python | en | code | 0 | github-code | 1 |
26082568433 | # pylint: disable=protected-access
from asyncio import create_task
from unittest.mock import AsyncMock, Mock, call, patch
from unittest.async_case import IsolatedAsyncioTestCase
from faker import Faker
from fetcher import Fetcher
class TestFetcher(IsolatedAsyncioTestCase):
def test_parse_url(self):
test... | ilya0100/DeepPythonHW | 08/tests.py | tests.py | py | 2,501 | python | en | code | 0 | github-code | 1 |
19942664956 | """
Parse text from PDF file.
Approach: Read PDF into list, then search list for certain terms. Append lines
where terms are found to new file or list, then parse those lines for the info
394.22
26572588200001
1503541657
"""
def getTotDue(x):
return float(''.join(num for num in x if num.isdigit() or num == '.'))
... | thoweath/PythonScripts | PythonScripts/PDFReader2.py | PDFReader2.py | py | 3,023 | python | en | code | 0 | github-code | 1 |
4469206526 | from pants.base.exceptions import TargetDefinitionException
from pants.base.payload import Payload
from pants.base.payload_field import PrimitiveField
from pants.fs import archive as archive_lib
from pants.contrib.node.targets.node_package import NodePackage
class NodeBundle(NodePackage):
"""A bundle of node modul... | manonja/smart-portfolio | contrib/node/src/python/pants/contrib/node/targets/node_bundle.py | node_bundle.py | py | 1,763 | python | en | code | 1 | github-code | 1 |
37598665486 | from django.shortcuts import render
from article.models import Article
def HomePage(request):
articles = Article.objects.all().order_by('-created_date')[:3]
first_article = None
second_article = None
third_article = None
if len(articles) >= 1:
first_article = articles[0]
if len(a... | kimjonginil/Womens-Diary-Diploma | backend/app/main/views.py | views.py | py | 634 | python | en | code | 0 | github-code | 1 |
12336878258 | # !/usr/bin/env python3
# -*- coding: utf-8 -*-
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for data in [b'Bob', b'Mich', b'Sar']:
# 发送数据
s.sendto(data, ('127.0.0.1', 9999))
# 接收数据
print(s.recv(1024).decode('utf-8'))
s.close()
| linkecoding/Python-Learning | day19/py_udp_client.py | py_udp_client.py | py | 282 | python | en | code | 1 | github-code | 1 |
43399303375 | import itertools
def check_gap(mat, mingap=0, maxgap=0):
for i, mat_i in enumerate(mat):
if i == 0:
pre = mat_i
continue
if mat_i <= pre + mingap or mat_i > pre + 1 + maxgap:
return False
pre = mat_i
return True
def sequenceMatching(edgeM... | yahuan-chen/PRED-ontologies | Helpers/spm_core_functions.py | spm_core_functions.py | py | 2,278 | python | en | code | 0 | github-code | 1 |
6803771447 | import cv2
from djitellopy import Tello
def initialize():
drone = Tello()
drone.connect()
drone.for_back_velocity = 0
drone.left_right_velocity = 0
drone.up_down_velocity = 0
drone.yaw_velocity = 0
drone.speed = 0
print(drone.get_battery())
drone.streamon()
re... | ollin23/dsc609 | detector.py | detector.py | py | 1,390 | python | en | code | 0 | github-code | 1 |
11510348772 | # Released under the MIT License. See LICENSE for details.
#
"""Various functionality related to achievements."""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
import babase
import bascenev1
import bauiv1
if TYPE_CHECKING:
from typing import Any, Sequence
import baclassi... | efroemling/ballistica | src/assets/ba_data/python/baclassic/_achievement.py | _achievement.py | py | 50,903 | python | en | code | 468 | github-code | 1 |
17463168218 | """Modulo principal.
Le os argumentos do input do usuario.
"""
import Matrix
import Print
import DigitClassifier
import numpy as np
import time
import os
import ctypes
def parte1():
print("\nParte 1\n----------------------\nRot-givens\n")
print("item a)")
n = m = 64
W = np.zeros((n, m))
b = np.zer... | gabrielhirata/GT-EP1-numerico | digit-classifier-master/main.py | main.py | py | 7,658 | python | en | code | 0 | github-code | 1 |
14282361490 | #!/usr/bin/python3
"""defines a class Square that inherits from Rectangle"""
Rectangle = __import__('9-rectangle').Rectangle
class Square(Rectangle):
"""represents a class Square"""
def __init__(self, size):
"""instantiate Square with private attribute size"""
self.integer_validator(... | Suzzy-cs/higher_level_prog | 0x0A-python-inheritance/10-square.py | 10-square.py | py | 398 | python | en | code | 0 | github-code | 1 |
74944576993 | import sys
import pandas as pd
import sqlite3
import z_service
def make_fedtbl(sq_conn):
dtfReg=pd.read_csv(r'C:\Documents and Settings\ggolyshev\PycharmProjects\Cities\Base\regionsF.csv',
sep=';', encoding='cp1251')
dtfFO=dtfReg[['FederalDistrictName', 'FederalDistrictID']].drop... | GeorgyGol/ReadWIKI_cities | make_db.py | make_db.py | py | 4,087 | python | en | code | 0 | github-code | 1 |
44612275491 | import unittest
from poly.edge import Edge
from poly.point import Point
from poly.polygon import Polygon
import random
class TestPolygon(unittest.TestCase):
def test_weakSimple(self):
"""See Wikipedia for entry on weakly simple polygon."""
m = Point(0, 0)
a = Point(0, 4)
... | heineman/python-polygon-intersection | Polygon/test/test_polygon.py | test_polygon.py | py | 1,389 | python | en | code | 15 | github-code | 1 |
6230064290 | import traceback
from aiogram import Router, F
from aiogram import types
from aiogram.fsm.context import FSMContext
from datetime import datetime, timedelta
from config_reader import myvars, DEBUG
from filters.permission import check_permission
from handlers.superuser_menu import InputData
from keyboards.for_doctor i... | kuromaster/mednotebot | handlers/docotor_menu.py | docotor_menu.py | py | 11,983 | python | en | code | 0 | github-code | 1 |
11866935175 | import os
from bcitp.utils.standards import PATH_TO_SESSION
from kivy.uix.screenmanager import Screen
from kivy.properties import ObjectProperty, StringProperty
class StartScreen(Screen):
# layout
session_name = ObjectProperty(None)
label_msg = StringProperty('')
def __init__(self, session_header, ... | rafaelmendes/BCItp | bcitp/screens/start_screen.py | start_screen.py | py | 1,710 | python | en | code | 4 | github-code | 1 |
35470321422 | class Solution:
def repeatedNTimes(self, A: List[int]) -> int:
d={}
max=0
maxKey=0
for i in A:
if i not in d:
d[i]=1
else:
d[i]+=1
for i in d:
if d[i]>max:
max=d[i]
maxKey=i
... | vshkodin/problem-solving-with-algorithms-and-data-structures-using-python | repeatedNTimes.py | repeatedNTimes.py | py | 419 | python | en | code | 0 | github-code | 1 |
30645335501 | from snappy.snap import t3mlite as t3m
from snappy.snap.mcomplex_base import *
from snappy.SnapPy import matrix
from .hyperboloid_utilities import *
__all__ = ['RaytracingData']
class RaytracingData(McomplexEngine):
def add_weights(self, weights):
for tet in self.mcomplex.Tetrahedra:
tet.Weig... | ekim1919/SnapPy | python/raytracing/raytracing_data.py | raytracing_data.py | py | 3,659 | python | en | code | null | github-code | 1 |
19323790025 | import json
from unittest import mock
import pytest
from intergov.repos.message_lake.minio.miniorepo import MessageLakeMinioRepo
from tests.unit.domain.wire_protocols.test_generic_message import _generate_msg_object
CONNECTION_DATA = {
'host': 'minio.host',
'port': 1000,
'access_key': 'access_key',
'... | bizcubed/intergov | tests/unit/repos/message_lake/test.py | test.py | py | 3,510 | python | en | code | 0 | github-code | 1 |
72318871074 | DEBUG = False
with open("input.txt") as f:
lines = f.read().splitlines()
commands = iter(lines)
X = 1
cooldown = 1
signals = []
current = "INIT"
CRT_screen = ""
suspend = 0
cycle = 0
while True:
cooldown -= 1
cycle += 1
if cooldown == 0:
X += suspend
suspend = 0
current ... | TrongTheAlpaca/AdventOfCode | 2022/day_10/day_10.py | day_10.py | py | 1,238 | python | en | code | 2 | github-code | 1 |
41649853983 | import sys
import librosa
from mir_eval.onset import f_measure
import numpy as np
import matplotlib.pyplot as plt
import math
from tensor_hero.preprocessing.audio import compute_mel_spectrogram_from_audio, filter_spec_by_amplitude
if not sys.warnoptions:
import warnings
warnings.simplefilter("ignore")
def nino... | elliottwaissbluth/tensor-hero | tensor_hero/onset.py | onset.py | py | 12,326 | python | en | code | 1 | github-code | 1 |
71112283234 | from AIPUBuilder.Optimizer.utils import *
from AIPUBuilder.Optimizer.framework import *
@op_register(OpType.UpsampleByIndex)
def upsamplebyindex(self, *args):
values = self.inputs[0].betensor
argmax = self.inputs[1].betensor.long()
current_batch = values.shape[0]
_, bottom_height, bottom_width, botto... | Arm-China/Compass_Optimizer | AIPUBuilder/Optimizer/ops/upsamplebyindex.py | upsamplebyindex.py | py | 2,986 | python | en | code | 18 | github-code | 1 |
71377850914 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import numpy as np
import pygimli as pg
from pygimli import plt
import pygimli.meshtools as mt
def testShowVariants():
# Create geometry definition for the modelling domain
world = mt.createWorld(start=[-10, 0], end=[10, -16],
... | gimli-org/gimli | pygimli/testing/test_show.py | test_show.py | py | 11,902 | python | en | code | 312 | github-code | 1 |
25376932933 | from argparse import ArgumentParser
from .sensing_reader import SensingReader
from .common import SUPPORT_CAMERA_INFO_DICT
def parse_args(argv):
parser = ArgumentParser()
parser.add_argument(
"--camera",
type=str,
help="camera model",
)
parser.add_argument(
"--i2c_bus"... | windzu/apk | apk/calibration/read_sensing/main.py | main.py | py | 1,061 | python | en | code | 2 | github-code | 1 |
31941896761 | from flask import jsonify, request
from pydash import omit
from .. import routes
from middleware import db, auth
from models import User
@routes.route('/api/auth/register', methods=['POST'])
def register():
body = request.get_json()
user = User(
username = body['username'],
hashed_password = auth.hash_p... | joem2019a/devops-assignment | api/routes/auth/register.py | register.py | py | 768 | python | en | code | 0 | github-code | 1 |
29551847807 | import notabene as nb
i = nb.to('i')
with nb.files.defs('001-008-algo.tex') as defs:
nb.config.push('display style', True)
defs.prefix = 'ex'
defs['Affect'] = nb.algo.affect(i, i+1)
defs.cheatsheet()
| HerveFrezza-Buet/notabene | examples/example-001-008-algo.py | example-001-008-algo.py | py | 225 | python | en | code | 0 | github-code | 1 |
19136982972 | import cv2
import numpy as np
import matplotlib.pyplot as plt
def 垂直边缘提取():
#差分求图像梯度,应用特殊卷积求差分.
img = cv2.imread("opencv\\files\sudoku.jpg", 0)
#卷积核
kernel = np.array([[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]], dtype=np.float32)
#这样的核可以提取竖直边缘,转置后可提取水... | AH-NAN/opencv | 算子和金字塔.py | 算子和金字塔.py | py | 5,144 | python | zh | code | 0 | github-code | 1 |
19546355153 | #!/usr/bin/python
# This prints chromosome strand "left" or "right", depending on the argument.
# Usage: select-strand.py {0 | 1} < chromosome > single-strand
# Prints Nucleotide tab In-gene-mark
# where Nucleotide is one of [ACGT] or X for other input letters
# and In-gene-mark is 0 or 1
import sys
import re
from ... | pompomon/nfpl104-genes | select-strand.py | select-strand.py | py | 3,913 | python | en | code | 0 | github-code | 1 |
19503054314 | from openerp.exceptions import except_orm, ValidationError
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
from openerp.exceptions import Warning as UserError
from openerp import models, fields, api, _
from openerp import workflow
import time
import datetime
from datetime import date
from openerp.tools.transla... | hosterp/BUREAU_GREEN_20_06_23 | hiworth_cashbook/models/cash_book.py | cash_book.py | py | 11,025 | python | en | code | 0 | github-code | 1 |
5300887273 | import os
import random
import tensorflow as tf
import numpy as np
from prep import coco_gen, save_image, bert
from model import Holly
import hyperparameters as hp
def load_recent_priority_model():
for root, dirs, _ in os.walk("./priority/"):
dirs = sorted(dirs, reverse=True)
print(dirs)
... | KoyenaPal/CS1430-FinalProj | code/eval.py | eval.py | py | 1,982 | python | en | code | 0 | github-code | 1 |
74660377312 | """
Search module for searching the web based on user queries.
"""
import asyncio
from search_engine_parser.core.engines.yahoo import Search as YahooSearch
def searcher(query, n_results, n_pages, only_description):
"""
Search the web using Yahoo Search engine and retrieve search results.
Parameters:... | nthng-quan/FlixRS | modules/search.py | search.py | py | 1,431 | python | en | code | 0 | github-code | 1 |
18042314284 | # coding: utf-8
from tastypie.resources import ModelResource
from tastypie.authorization import Authorization
from tastypie import fields
from tastypie.constants import ALL, ALL_WITH_RELATIONS
from ...models import Programacao
from django.utils import timezone
class ProgramacaoResource(ModelResource):
programa = f... | rbiassusi/grade_programacao | grade_programacao/radio/api/resources/programacaoresource.py | programacaoresource.py | py | 1,631 | python | en | code | 0 | github-code | 1 |
42049926844 | import argparse
import datetime
import json
import logging
import apache_beam as beam
from apache_beam.options.pipeline_options import PipelineOptions
import apache_beam.transforms.window as window
import ast
from google.auth.transport.requests import Request
from google.oauth2.service_account import Credentials
from... | anandj123/gcptest | gmail-attachment/gmailattachment.py | gmailattachment.py | py | 6,832 | python | en | code | 2 | github-code | 1 |
40709061375 |
"""
Disclaimer
This software was developed by employees of the National Institute of Standards and Technology (NIST), an agency of the Federal Government and is being made available as a public service. Pursuant to title 17 United States Code Section 105, works of NIST employees are not subject to copyright protect... | usnistgov/trojai-baseline-pruning | extended_dataset_ner.py | extended_dataset_ner.py | py | 10,286 | python | en | code | 5 | github-code | 1 |
23550856102 | import os,sys
import argparse
import random
from collections import defaultdict, deque
import signal
from multiprocessing import Pool
from time import time
'''
Below awesome fast[a/q] reader function taken
from https://github.com/lh3/readfq/blob/master/readfq.py
'''
def readfq(fp): # this is a generator ... | ksahlin/alignment_evaluation | scripts/compute_seed_E_hits.py | compute_seed_E_hits.py | py | 7,348 | python | en | code | 2 | github-code | 1 |
23720578792 | #Michael Holloway SID: 001215316
import csv
import datetime
# entry point for the entire program to begin running
def start():
#import distance and location data
global distances, locations
distances, locations = importDistanceList();
#intial load of trucks
#manually set to balance loads and grou... | m-holloway-cw/PackageRouting | main.py | main.py | py | 18,549 | python | en | code | 0 | github-code | 1 |
29262417436 | def happy_number(num):
visit = set()
while num not in visit:
visit.add(num)
num = square(num)
if num == 1:
return True
return False
def square(num):
output = 0
while num:
digit = num%10
digit = digit ** 2
output+=digit
num = num /... | Mayankjha997/Neetcode_python_solution | math and geo/happy_number.py | happy_number.py | py | 415 | python | en | code | 0 | github-code | 1 |
30189967092 |
import pandas as pd
from catboost import CatBoostRegressor as cbr
from catboost import CatBoostClassifier as cbc
from sklearn.preprocessing import LabelEncoder as LE
from sklearn.preprocessing import OneHotEncoder
import random
from sklearn.metrics import f1_score
training_dataset = pd.read_csv( r'train.csv')
tes... | DataScienceWorks/AV-WNS-2018-September-JobPromotionPrediction | others_solutions/pre-final/084r_S0umya_409_578825_cf_final_5ag0EsU.py | 084r_S0umya_409_578825_cf_final_5ag0EsU.py | py | 4,918 | python | en | code | 0 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.