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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
38431802866 |
import os
import random
train_precent=0.8
#base_root = r"C:\Users\29533\Desktop\szs_xc_0406-0408\rain_day_aug"
base_root = os.path.dirname(os.path.abspath(__file__))
print(base_root)
xml= base_root + "/Annotations/"#Annotations文件夹的路径
total_xml=os.listdir(xml)
num=len(total_xml)
tr=int(num*train_precent)
train=ra... | HelloSZS/Common-tools_FOR_Object-detection | 1VOC划分训练集测试集.py | 1VOC划分训练集测试集.py | py | 728 | python | en | code | 1 | github-code | 6 |
11004600528 | from typing import List
class Solution:
def largestSumOfAverages(self, A: List[int], K: int) -> float:
n = len(A)
p = [0.0] * (n + 1)
for i in range(n):
p[i+1] = p[i]+A[i]
dp = [0.0] * n
for i in range(n):
dp[i] = (p[n] - p[i])/(n-i)
for k ... | xixihaha1995/CS61B_SP19_SP20 | temp/toy/python/813. Largest Sum of Averages.py | 813. Largest Sum of Averages.py | py | 555 | python | en | code | 0 | github-code | 6 |
9910655539 | from flask import Flask, render_template
import requests, json
NYTimes_API_KEY = 'ca470e1e91b15a82cc0d4350b08a3c0b:14:70189328'
app = Flask(__name__, static_folder='static', static_url_path='/static')
NYTimes_Search_URL = 'http://api.nytimes.com/svc/search/v2/articlesearch.json?q={0}+&api-key=' + NYTimes_API_KEY
def... | NYUHackDays/NYTimes-Python-Done | nytimes.py | nytimes.py | py | 614 | python | en | code | 0 | github-code | 6 |
354470885 | from math import log
import numpy as np
from util.PreprocessUtil import PreprocessUtil
from algos.BaseMM import BaseMM
class HMM(BaseMM):
prior_prob = None # dict, [n_state,]
transition_prob = None # dict of dict, [n_state, n_state]
emission_prob = None # dict of dict, [n_state, n_ob... | hedwigi/statisticalSeqModels | algos/HMM.py | HMM.py | py | 7,148 | python | en | code | 0 | github-code | 6 |
73928041148 | from pyvi import window
from pyvi.modes import normal
class Editor(object):
_command = None
active_tab = None
def __init__(self, tabs=None, config=None, normal=normal):
self.config = config
self.mode = self.normal = normal
self.count = None
if tabs is None:
t... | Julian/PyVi | pyvi/editor.py | editor.py | py | 635 | python | en | code | 11 | github-code | 6 |
730586622 | from selenium import webdriver
from selenium.webdriver.common.by import By
chrome_driver_path = r"C:\Users\Tobiloba\development\chromedriver.exe"
driver = webdriver.Chrome(executable_path=chrome_driver_path)
#driver.get('https://www.amazon.com/dp/B0963P9QTM/ref=sbl_dpx_kitchen-electric-cookware_B08GC6PL3D_0')
#pri... | adecool/python100days | day-48/main.py | main.py | py | 1,180 | python | en | code | 0 | github-code | 6 |
21705466300 | from os.path import basename
from glob import glob
from tqdm import tqdm
def main():
"""
フルラベルファイルのp16に歌唱者名を仕込む。
"""
# フルラベルファイルが入ってるフォルダを指定
label_dir = input('label_dir: ').strip('"')
# フルラベル全ファイル取得
l = glob(f'{label_dir}/**/*.lab', recursive=True)
# ラベルファイルのp16部分に歌唱者名を埋め込む
for pa... | oatsu-gh/nnsvs_mixed_db | recipe/00-svs-world/utils/set_singername_p16.py | set_singername_p16.py | py | 763 | python | ja | code | 0 | github-code | 6 |
44248037473 | import cv2
import numpy as np
import glob
import uuid
import caffe
import skimage.io
from util import histogram_equalization
from scipy.ndimage import zoom
from skimage.transform import resize
import random
#from project_face import project_face
import cv2
import numpy as np
from matplotlib import pyplot as plt
import ... | juanzdev/TeethClassifierCNN | src/mouth_detector_dlib.py | mouth_detector_dlib.py | py | 4,369 | python | en | code | 3 | github-code | 6 |
36917846701 | import logging
import os
import sys
from queue import Empty
from threading import Thread
import argparse
import jsonpickle
from polarity_server import globals
from polarity_server.rest import RestApi
class App:
thread_run = True
@classmethod
def run(cls):
parser = argparse.ArgumentParser()
... | willmfftt/polarityserver | polarity_server/app/app.py | app.py | py | 4,759 | python | en | code | 0 | github-code | 6 |
44055444234 | print("Hello Adafruit!!!")
import sys
import random
import time
from Adafruit_IO import MQTTClient
import cv2
from read_serial import *
from simple_ai import *
AIO_FEED_ID = ["iot-hk222.light", "iot-hk222.pump"]
AIO_USERNAME = "vynguyen08122002"
AIO_KEY = "aio_jTpa00iRWo7ACInoo8sMTJ1I7Pr8"
def connected(client):
... | vynguyenkn0812/HK222_IoT | Gateway/main.py | main.py | py | 2,285 | python | en | code | 0 | github-code | 6 |
43691629803 | #!/usr/bin/python3
""" Method that determines if all the boxes can be opened. """
def canUnlockAll(boxes):
if not boxes:
return False
boxLen = len(boxes)
boxOpen = [0]
for k in boxOpen:
for box in boxes[k]:
if box not in boxOpen and box < boxLen:
boxOpen.ap... | vagava/holbertonschool-interview | 0x00-lockboxes/0-lockboxes.py | 0-lockboxes.py | py | 400 | python | en | code | 0 | github-code | 6 |
42367773251 | # -*- coding: utf-8 -*-
from tornado.web import RequestHandler
from ..Apps import Apps
from ..Exceptions import AsyncyError
from ..Sentry import Sentry
class BaseHandler(RequestHandler):
logger = None
# noinspection PyMethodOverriding
def initialize(self, logger):
self.logger = logger
def ... | rashmi43/platform-engine | asyncy/http_handlers/BaseHandler.py | BaseHandler.py | py | 1,138 | python | en | code | 0 | github-code | 6 |
29703199407 | import bpy
import types
import sys
from select import select
import socket
import errno
import mathutils
import traceback
from math import radians
from bpy.props import *
from ast import literal_eval as make_tuple
from .callbacks import *
from ..nodes.nodes import *
def make_osc_messages(myOscKeys, myOscMsg):
env... | maybites/blender.NodeOSC | server/_base.py | _base.py | py | 16,277 | python | en | code | 100 | github-code | 6 |
825675496 | # -*- coding: utf-8 -*-
"""
Created on Tue May 10 04:27:29 2022
@author: ThinkPad
"""
from __future__ import print_function
import argparse
import os
import numpy as np
import random
import torch
import torch.nn.parallel
import torch.optim as optim
import torch.utils.data
from PartialScan import PartialScans,unpickle,... | FreddieRao/TextCondRobotFetch | pointnet/inference.py | inference.py | py | 13,605 | python | en | code | 2 | github-code | 6 |
23055528773 | """
Creation:
Author: Martin Grunnill
Date: 13/09/2022
Description: Classes for Multnomial random draw seeding of infections.
Classes
-------
MultnomialSeeder
Makes multinomial draws selecting an infectious hosts branch and then state.
"""
from numbers import Number
import numpy as np
import math
cla... | LIAM-COVID-19-Forecasting/Modelling-Disease-Mitigation-at-Mass-Gatherings-A-Case-Study-of-COVID-19-at-the-2022-FIFA-World-Cup | seeding_infections/multinomail_seeding.py | multinomail_seeding.py | py | 8,269 | python | en | code | 0 | github-code | 6 |
12771403336 | import tensorflow as tf
from yolo import YOLO, detect_video
from PIL import Image
import os
os.environ['CUDA_VISIBLE_DEVICES'] = "1"
def detect_img(yolo):
img = '10.jpg'
try:
image = Image.open(img)
except Exception as e:
print('Open Error! Try again!')
print(e)
else:
r_... | Jerry-Z464/yolo | keras-yolo3/test.py | test.py | py | 490 | python | en | code | 0 | github-code | 6 |
7357482434 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This is an example script that uses DIC data from Carrol et al
as input for SIF to find K field and cracktip data
The output is written to a CSV file
@author: Swati Gupta
"""
import SIF_final as SIF
import numpy as np
from os import walk
import pdb
from datetime imp... | sg759/separability | DICexample.py | DICexample.py | py | 2,731 | python | en | code | 0 | github-code | 6 |
7919794607 | from random import randint
from time import sleep
def more_five(x):
if x > 5:
return True
new = [2, 5, 10 ,12, 15, 1 ,2]
res_map = map(more_five, new)
print(list(res_map))
list_cmp = [randint(0, 10) for i in range(10) if i % 2 == 0]
#print(list_cmp)
set_cmp = [randint(0, 10) for i in range(10)]
#prin... | Savitskiyov/Python | Seminar 6/Seminar_1.py | Seminar_1.py | py | 723 | python | en | code | 0 | github-code | 6 |
9633391789 | # W.A.P in Python to count the occurance of each character in your name and display each character of the string. #
str = input("Enter the name : ")
L = []
for i in str.lower() :
if i not in L :
L.append(i)
print("The total number of occurances of",i,"is",str.count(i))
L1 = lis... | sunny-ghosh/Python-projects | Practical_24.py | Practical_24.py | py | 336 | python | en | code | 0 | github-code | 6 |
42598863082 | #Project euler problem 10
#Problem link https://projecteuler.net/problem=10
def sumPrimes(n):
sum, sieve = 0, [True] * n
for p in range(2, n):
if sieve[p]:
sum += p
for i in range(p * p, n, p):
sieve[i] = False
return sum
print(sumPrimes(2000000)) | mahimonga/Project-Euler | Problem5_10/summation_of_primes.py | summation_of_primes.py | py | 310 | python | en | code | 2 | github-code | 6 |
14822509390 | from sqlalchemy.orm import Session
from database_models import Task, TaskStatuses
from schemas import CreateTaskModel, UpdateTaskModel, DeleteTaskModel
from datetime import datetime
def create_task(db:Session, task: CreateTaskModel):
db_task = Task(
name = task.name,
description = task.description... | maximzec/ToDoApp | crud.py | crud.py | py | 993 | python | en | code | 0 | github-code | 6 |
32257470125 | # Ben Readman
# While loop Calculator
x = 0
go = 'y'
num = int(input("Please enter the first number: "))
minnum = num
maxnum = num
while go == 'y':
num2 = int(input("Please enter the next number: "))
avrg = num + num2
num = num2
if minnum > num2:
minnum = num2
else:
min... | ThatGuyBreadman1567/WhileLoopCalculator | WhileLoopCalculator.py | WhileLoopCalculator.py | py | 717 | python | en | code | 0 | github-code | 6 |
28028911172 | #!/usr/bin/python3
import random
import sys
import os
#from turtle import clear
#from typing_extensions import TypeVarTuple
#from tkinter import N
from time import sleep
from functions import k_d_function, fselection, current_score, addTo, averageSolution
# what to keep track of? Ability to add more
# Features
... | miturn/stat_tracker | stat_tracker.py | stat_tracker.py | py | 15,046 | python | en | code | 0 | github-code | 6 |
6484090494 | from rest_framework import serializers
from django.contrib.auth import get_user_model
from session.serializers.recent_sessions import RecentSessionSerializer
User = get_user_model()
class ClientListSerializer(serializers.ModelSerializer):
number_of_sessions = serializers.SerializerMethodField()
latest_sessi... | roberttullycarr/cyclingsimulator | backend/user/serializers/coach/list_clients.py | list_clients.py | py | 909 | python | en | code | 0 | github-code | 6 |
11110715644 | # coding:utf-8
import pygame
class Main(object):
def __init__(self, title, height, width, Fps=60):
self.height = height
self.width = width
self.title = title
self.Fps = Fps
self.main()
self.vars()
self.events()
def main(self):
pygame.init() ... | PatrickShun/pygameDemo | pygamedemo_run.py | pygamedemo_run.py | py | 1,650 | python | zh | code | 0 | github-code | 6 |
25316393069 | from typing import List, Set, Callable, Optional, Iterator
import math
class Tile:
def __init__(self, tile: List[str], tile_id: int = 0):
self.tile = tile
self.id = tile_id
self.edge_len = len(tile)
def right_edge(self) -> str:
return "".join(t[-1] for t in self.tile)
def... | stx73/aoc2020 | day20/p1.py | p1.py | py | 3,211 | python | en | code | 0 | github-code | 6 |
40887076205 | # Тестирование компонентов задач
import unittest
from pyodbc import Connection as PyodbcConnection
from connections import Connection1
from task_classes.db.mssqldb import MSSqlTarget
from task_classes.csv_task_classes import PrepareCsvBulkPackages
class TestMSSqlTarget(unittest.TestCase):
"""Класс тестирования M... | Foresco/luigivar | tests.py | tests.py | py | 2,370 | python | ru | code | 0 | github-code | 6 |
39803355853 | import pickle
from pathlib import Path
script_location = Path(__file__).absolute().parent
data_loc = script_location / "name_gen_model"
from bangla_linga.BN_countvectorizer import CountVectorizer
import bangla_linga.BN_ngram as ng
class BN_gen_pred(object):
def __init__(self,model_name=data_loc):
self.model_... | Kowsher/Bangla-NLP | Bangla Linga/bangla_linga/gender_prediction.py | gender_prediction.py | py | 846 | python | en | code | 11 | github-code | 6 |
26336217910 | import streamlit as st
import extra_streamlit_components as stx
from datetime import datetime, timedelta
import Scripts.constants as constants
@st.experimental_singleton(suppress_st_warning=True)
def get_manager():
return stx.CookieManager()
# def get_user_cookies():
# COOKIES = constants.COOKIES.get(constan... | PeaPals/docnets | Scripts/cookie_manager.py | cookie_manager.py | py | 1,550 | python | en | code | 0 | github-code | 6 |
37407227644 | from matplotlib import pyplot as plt
from findiff import FinDiff
import pandas as pd
import numpy as np
from tqdm import tqdm
id_col = 'ID'
date_col = 'DATE'
px_close = 'px_last'
px_high = 'px_high'
px_low = 'px_low'
px_open = 'px_open'
def find_derivative(series): #1 day interval
'''
Compute the first and se... | etq-quant/etqbankloan | Lib/etiqalib/ta/turning_points.py | turning_points.py | py | 24,726 | python | en | code | 0 | github-code | 6 |
11896445749 | from django.http import HttpRequest
from google_optimize.context_processors import google_experiment
def test_experiment_processor():
request = HttpRequest()
request.COOKIES["_gaexp"] = "GAX1.2.utSuKi3PRbmxeG08en8VNw.18147.1"
experiment = google_experiment(request)
assert experiment == dict(google_op... | danihodovic/django-google-optimize | tests/test_context_processors.py | test_context_processors.py | py | 585 | python | en | code | null | github-code | 6 |
44617869434 | import numpy as np
import pandas as pd
class DataPreparationAirQuality(object):
def __init__(self, conf, utils, raw_repo, processed_repo) -> None:
self.target_col = "CO(GT)"
self.study_label = "Air Quality"
self.utils = utils
self.processed_data = pd.DataFrame()
self.is_se... | luis00rod/capgemini_tecnical_test | src/main/interactors/forecast/data_preparation_air_quality.py | data_preparation_air_quality.py | py | 1,950 | python | en | code | 0 | github-code | 6 |
32676437510 |
qtndPrimos = somaMultiplosTres = 0
qtndParesMaioresVinte = somaParesMaioresVinte = 0
for i in range(10):
div = 0
number = int(input("Número: "))
if number % 3 == 0:
somaMultiplosTres += number
if (number % 2 == 0 ) and (number > 20):
somaParesMaioresVinte += number
qtndParesMaioresVinte += 1
... | JLramosSoares/linguagem-de-programacao-exercicios | Lista_2021_1/exerc_4.py | exerc_4.py | py | 737 | python | pt | code | 0 | github-code | 6 |
11417571951 | # -*- coding: utf-8 -*-
"""
(C) 2014-2019 Roman Sirokov and contributors
Licensed under BSD license
http://github.com/r0x0r/pywebview/
"""
import os
import sys
import logging
import json
import shutil
import tempfile
import webbrowser
from threading import Event, Semaphore
from ctypes import windll
from platform imp... | hanzzhu/chadle | venv/Lib/site-packages/webview/platforms/edgechromium.py | edgechromium.py | py | 6,044 | python | en | code | 1 | github-code | 6 |
7986369348 | import basc_py4chan as chanapi
import requests
import argparse
import sys
import os
class FourchanDownloader:
def __init__(self):
self.boards_list = chanapi.get_all_boards()
def run(self):
self.verify_boards()
if len(self.board) == 0:
print("No existing boards selected, yo... | SteelPh0enix/4chanDownloader | 4chan.py | 4chan.py | py | 4,179 | python | en | code | 0 | github-code | 6 |
24990513085 | # -*- coding: utf-8 -*-
import numpy as np
import time
import os
if __name__ == '__main__':
save_dir = '/home/shengby/Datasets/csv_generator/h750_w270_num100000/'
file_nums = 100000
for i in range(file_nums):
file_path = save_dir + str(i) + '.csv'
data = np.random.rand(750, 270)
np.... | Finallap/WiFi_Sensing_Python | data_loader/concurrent_study/csv_generator.py | csv_generator.py | py | 391 | python | en | code | 5 | github-code | 6 |
10068857131 | import cv2
import numpy as np
from time import sleep
import os
# global variables
bg = None
def run_avg(image, aWeight):
global bg
# initialize the background
if bg is None:
bg = image.copy().astype("float")
return
# compute weighted average, accumulate it and update the background
... | RemonIbrahimNashed/HandGestureUseingCNN | live.py | live.py | py | 2,732 | python | en | code | 0 | github-code | 6 |
36733100195 | import os
import sys
import logging
import MySQLdb
#import datetime
logger = logging.getLogger(__name__)
locz = []
locz_file = ''
# 'locz' table fields: chat_id, chat_title, user_id, user_name, date_time, latitude, longitude
def add_loc(mess):
locstr = 'chat.id:' + str(mess.chat.id) + ',chat.title:' + str(mess... | nikodim500/pyIkuraTeleBot | locationstore.py | locationstore.py | py | 3,142 | python | en | code | 0 | github-code | 6 |
72646625788 | # some functions from discovery/scripts/cdisco/cdisco.py
import numpy as np
import torch
import torchvision
import PIL.Image as Image
from my_datasets import transform
from my_datasets import transform_normalize
def get_model_state(model, paths, y, dim_c, dim_w, dim_h, SAVEFOLD=''):
batch_size = 32
tot_acc =... | lomahony/sw-interpretability | scripts/get_embeddings.py | get_embeddings.py | py | 3,411 | python | en | code | 4 | github-code | 6 |
43493696921 | # GCDMOD in python
# shivamgor498
# https://www.codechef.com/AUG18A/problems/GCDMOD/
def power(x, y, m) :
if (y == 0) :
return 1
p = power(x, y // 2, m) % m
p = (p * p) % m
if(y % 2 == 0) :
return p
else :
return ((x * p) % m)
def modInverse(a, m) :
return power(a, m -... | shivamgor498/Codechef | GCDMOD.py | GCDMOD.py | py | 877 | python | en | code | 0 | github-code | 6 |
24293856933 | def reshape_matrix(mat, x, y):
number_of_elements = len(mat) * len(mat[0])
if x * y != number_of_elements:
return None
result = [[None for _ in range(x)] for _ in range(y)]
current_row = 0
current_col = 0
for i in range(len(mat)):
for j in range(len(mat[0])):
if curre... | ckallum/Daily-Interview-Pro | solutions/reshaping_matrix.py | reshaping_matrix.py | py | 730 | python | en | code | 16 | github-code | 6 |
73919543869 | from django.shortcuts import render
from resources.models import Resource
def resources(request):
resources = Resource.objects.all().order_by('order').filter(hidden=False)
context = {
'resources': resources
}
return render(request, 'resources.html', context)
| ctiller15/Humanity-first-tracker | resources/views.py | views.py | py | 288 | python | en | code | 0 | github-code | 6 |
29099740995 | from torch.utils.data import Dataset
from typing import List
import torch
import pandas as pd
class InferenceDataset(Dataset):
def __init__(self, texts: List[list], tokenizer, max_length: int):
self.texts = texts
self.tokenizer = tokenizer
self.max_length = max_length
def __len__(self... | MaryNJ1995/Sarcasm_Detection | src/inference/dataset.py | dataset.py | py | 3,398 | python | en | code | 1 | github-code | 6 |
5257520483 | import boto3
from secretss import accessKey, secretKey
# upload files to AWS S3 bucket
s3 = boto3.client('s3')
bucket_name = "mmc-video-bucket"
file_path = 'E:\Programming files\Home-Surveillance\\basicvideo.mp4'
object_key = 'basicvideo.mp4'
s3.upload_file(file_path, bucket_name, object_key)
| Varun-Naik/Home-Surveillance | upload_to_s3.py | upload_to_s3.py | py | 297 | python | en | code | 1 | github-code | 6 |
39359091601 | import time
from openpyxl import Workbook
from selenium import webdriver
import openpyxl
# from selenium.webdriver.common import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exc... | Paviterence/Selenium-Python-BasicCodes | webScrapping.py | webScrapping.py | py | 1,886 | python | en | code | 1 | github-code | 6 |
6511550014 | point1 = []
point2 = []
with open('day5-input.txt','r') as f:
for line in f.readlines():
p1, p2 = line.split(' -> ')
p1 = [int(i) for i in p1.strip('\n').split(',')]
p2 = [int(i) for i in p2.strip('\n').split(',')]
if p1[0] == p2[0] or p1[1] == p2[1]:
point1.append(p1)
point2.append(p2)
points = {}... | kebab01/advent-of-code-2021 | day5_part1-2.py | day5_part1-2.py | py | 896 | python | en | code | 0 | github-code | 6 |
20519423740 | """!
@brief Examples of usage and demonstration of abilities of K-Medoids algorithm in cluster analysis.
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2020
@copyright BSD-3-Clause
"""
from pyclustering.samples.definitions import SIMPLE_SAMPLES, FCPS_SAMPLES
from pyclustering.cluster impor... | annoviko/pyclustering | pyclustering/cluster/examples/kmedoids_examples.py | kmedoids_examples.py | py | 5,155 | python | en | code | 1,113 | github-code | 6 |
8495271737 | import bpy
from bpy_extras.object_utils import world_to_camera_view
import numpy as np
from util import poissonDiscSampling
import math
import random
from mathutils import Euler, Vector
import os
import glob
import sys
class ForegroundObjectPlacementRandomizer:
"""
A randomizer class which randomly spawns vir... | MichaelLiLee/Synthetic-Data-Generator-for-Human-Detection | HumanSDG/HumanSDG_020_ForegroundObjectPalcementRandomizer.py | HumanSDG_020_ForegroundObjectPalcementRandomizer.py | py | 11,870 | python | en | code | 0 | github-code | 6 |
35463051615 | import math
from cmath import exp
import kwant
def hopping(sitei, sitej, phi, salt):
xi, yi = sitei.pos
xj, yj = sitej.pos
return -exp(-0.5j * phi * (xi - xj) * (yi + yj))
def onsite(site, phi, salt):
return 0.3 * kwant.digest.gauss(repr(site), salt) + 4
def test_qhe(W=16, L=8):
def central_re... | kwant-project/kwant | kwant/tests/test_comprehensive.py | test_comprehensive.py | py | 1,848 | python | en | code | 76 | github-code | 6 |
21594560177 | from django.shortcuts import render, redirect
import csv
from django.http import HttpResponse
from django.template.loader import render_to_string
# from weasyprint import HTML
# Create your views here.
from .models import Members, Loans, Deposits
from django.db.models import Avg, Sum
from .forms import MemberForm
d... | laloluka/sol | information_system/views.py | views.py | py | 2,960 | python | en | code | 0 | github-code | 6 |
14035574166 | from ADMIN import *
from VIP_csv import *
from USER import *
if __name__ == '__main__':
sign = 0
user = 0
# loop program, can exit with "end"
while True:
if sign == 0:
print("Sign in as:")
who = ""
# not able to sign in as long as name is admin vip_user o... | ChitzAK/Curs_Python | TODOES.py | TODOES.py | py | 4,249 | python | en | code | 0 | github-code | 6 |
37512481914 | import os
import pytest
from contextlib import contextmanager
from tempfile import TemporaryDirectory, NamedTemporaryFile
from unittest.mock import patch
from zipfile import ZipFile
from repo2docker.contentproviders import Hydroshare
from repo2docker.contentproviders.base import ContentProviderException
def test_co... | igorkatinas/jupyter | tests/unit/contentproviders/test_hydroshare.py | test_hydroshare.py | py | 7,638 | python | en | code | 0 | github-code | 6 |
12902368672 | #!/usr/bin/python3
import sqlite3
import gspread
from oauth2client.service_account import ServiceAccountCredentials
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
dbfile = 'TimeTrack4237.db'
dbconn = sqlite3.connect(dbfile)
student_hours = None
with dbconn:
... | washide/TimeTrack4237 | UploadTotalHours.py | UploadTotalHours.py | py | 1,173 | python | en | code | 0 | github-code | 6 |
28041597167 | import unittest
import os
from conans.test.utils.test_files import temp_folder
from conans.util.files import save
from time import sleep
class SaveTestCase(unittest.TestCase):
def setUp(self):
folder = temp_folder()
self.filepath = os.path.join(folder, "file.txt")
# Save some content an... | pianoslum/conan | conans/test/util/files_test.py | files_test.py | py | 1,276 | python | en | code | null | github-code | 6 |
73652360829 | # 给你一个长度固定的整数数组 arr,请你将该数组中出现的每个零都复写一遍,并将其余的元素向右平移。
# 注意:请不要在超过该数组长度的位置写入元素。
# 要求:请对输入的数组 就地 进行上述修改,不要从函数返回任何东西。
class Solution(object):
def duplicateZeros(self, arr):
"""
:type arr: List[int]
:rtype: None Do not return anything, modify arr in-place instead.
"""
i = 0
... | xxxxlc/leetcode | array/duplicateZeros.py | duplicateZeros.py | py | 912 | python | zh | code | 0 | github-code | 6 |
14374651405 | """Bridgy App Engine config.
"""
import logging
class StubsFilter(logging.Filter):
"""Suppress these INFO logs:
Sandbox prevented access to file "/usr/local/Caskroom/google-cloud-sdk"
If it is a static file, check that `application_readable: true` is set in your app.yaml
"""
def filter(self, recor... | snarfed/bridgy-fed | appengine_config.py | appengine_config.py | py | 580 | python | en | code | 219 | github-code | 6 |
17707768416 | from tensorflow.keras.layers import Conv2D, Conv2DTranspose, concatenate, Dropout
from model.create_layers import create_conv_layers
class Decoder:
def __init__(self, inputs, conv_layers, output_channels, dropout=0.3, name="Decoder"):
self.inputs = inputs
self.dropout = dropout
self.name =... | amahiner7/UNet_oxford_iiit_pet-Tensorflow | model/decoder.py | decoder.py | py | 1,643 | python | en | code | 0 | github-code | 6 |
650276737 | #! /bin/python
# IMPORTANT do threadctl import first (before numpy imports)
from threadpoolctl import threadpool_limits
import os
import sys
import json
import luigi
import nifty.tools as nt
import cluster_tools.utils.volume_utils as vu
import cluster_tools.utils.function_utils as fu
from cluster_tools.cluster_task... | constantinpape/cluster_tools | cluster_tools/label_multisets/create_multiset.py | create_multiset.py | py | 5,506 | python | en | code | 32 | github-code | 6 |
3026246186 | # -*- coding: utf-8
from woo import utils,pack,export,qt
import gts,os
def Plane(v1,v2,v3,v4):
pts = [ [Vector3(v1),Vector3(v2),Vector3(v3),Vector3(v4)] ]
return pack.sweptPolylines2gtsSurface(pts,capStart=True,capEnd=True)
# Parameters
tc=0.001# collision time
en=0.3 # normal restitution coefficient
es=0.3 # t... | Azeko2xo/woodem | scripts/test-OLD/ResetRandomPosition.py | ResetRandomPosition.py | py | 2,200 | python | en | code | 2 | github-code | 6 |
19678508262 | from os import path
import os
from .core import ZephyrBinaryRunner, get_env_or_bail
DEFAULT_PYOCD_GDB_PORT = 3333
class PyOcdBinaryRunner(ZephyrBinaryRunner):
'''Runner front-end for pyocd-flashtool.'''
def __init__(self, target, flashtool='pyocd-flashtool',
gdb=None, gdbserver='pyocd-gdbs... | rogerioprando/zephyr | scripts/support/runner/pyocd.py | pyocd.py | py | 5,225 | python | en | code | 0 | github-code | 6 |
19400189989 | from typing import List
import random
# 398. 随机数索引
# https://leetcode-cn.com/problems/random-pick-index/
# 蓄水池抽样
class Solution:
def __init__(self, nums: List[int]):
self.nums = nums
def pick(self, target: int) -> int:
ans = -1
k = 1
for i, each in enumerate(self.nums):
... | Yigang0622/LeetCode | randomNumIndexing.py | randomNumIndexing.py | py | 693 | python | en | code | 1 | github-code | 6 |
25353649574 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 19 12:30:02 2021
@author: Nassim
"""
import os
from tkinter import *
from tkinter import filedialog, ttk
import numpy as np
import esat
def main():
root = Tk()
root.title("ESAT")
root.configure(bg="lightsteelblue")
root.geometry("800x400")
main_fol... | NassimOumessoud/esat | scripts/main.py | main.py | py | 6,588 | python | en | code | 0 | github-code | 6 |
24826877634 | import numpy as np
from timeit import default_timer as timer
import utils
from utils import *
from PyCuNN import *
from scipy.spatial.distance import euclidean as euc
import pickle
class rnn(object):
def __init__(self, layers):
super(rnn, self).__init__()
self.layers = layers
self.w1 = init_weights([self.layer... | tylerpayne/PyCuNN | nn/rnn.py | rnn.py | py | 5,216 | python | en | code | 0 | github-code | 6 |
5479249067 | """
Proximal Policy Optimization Algorithms (PPO):
https://arxiv.org/pdf/1707.06347.pdf
Related Tricks(May not be useful):
Mastering Complex Control in MOBA Games with Deep Reinforcement Learning (Dual Clip)
https://arxiv.org/pdf/1912.09729.pdf
A Closer Look at Deep Policy Gradients (Value clip, Re... | haosulab/ManiSkill2-Learn | maniskill2_learn/methods/mfrl/ppo.py | ppo.py | py | 21,464 | python | en | code | 53 | github-code | 6 |
43724719541 | from PyQt5.QtCore import QThread, QMutex, pyqtSignal
from binance.client import Client
import pyupbit
import pybithumb
import requests
from bs4 import BeautifulSoup
from debug import debuginfo
class binanceThread(QThread):
binance_data = pyqtSignal(dict)
def __init__(self):
QThread.__init__(self)
... | JunTae90/coin_viewer | thread.py | thread.py | py | 9,535 | python | en | code | 0 | github-code | 6 |
8201566770 | from typing import Dict
import os
import shutil
from hexlib.db import Table, PersistentState
import pickle
from tesseract import get_tesseract_langs
import sqlite3
from config import LOG_FOLDER, logger
from sist2 import SearchBackendType, Sist2SearchBackend
RUNNING_FRONTENDS: Dict[str, int] = {}
TESSERACT_LANGS = g... | simon987/sist2 | sist2-admin/sist2_admin/state.py | state.py | py | 3,537 | python | en | code | 652 | github-code | 6 |
6806255656 | """
Пожалуйста, приступайте к этой задаче после того, как вы сделали и получили ревью ко всем остальным задачам
в этом репозитории. Она значительно сложнее.
Есть набор сообщений из чата в следующем формате:
```
messages = [
{
"id": "efadb781-9b04-4aad-9afe-e79faef8cffb",
"sent_at": datetime.datet... | hodakoov/basic_exercises | for_dict_challenges_bonus.py | for_dict_challenges_bonus.py | py | 7,598 | python | ru | code | null | github-code | 6 |
8412088860 | from rest_framework import serializers
from .models import (
Product,
ProductImage,
Size,
Category
)
class CategoryListSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(
view_name='products:category-detail-view',
lookup_field='slug'
... | fanimashaun-r7/Nf_Kicks_Api | app/products/serializers.py | serializers.py | py | 2,365 | python | en | code | 0 | github-code | 6 |
39131633270 | import random
from itertools import zip_longest
from typing import List
from config import MuZeroConfig
from game.game import AbstractGame
import _pickle as cPickle
import os
import numpy as np
class ReplayBuffer(object):
def __init__(self, config: MuZeroConfig, fighter):
self.window_size = config.windo... | Nebraskinator/StreetFighter2AI | muzero/training/replay_buffer.py | replay_buffer.py | py | 6,951 | python | en | code | 1 | github-code | 6 |
27009678128 | import numpy as np
import run as r
from sklearn.gaussian_process.kernels import ABCMeta, Matern, ConstantKernel, Exponentiation, ExpSineSquared, Hyperparameter, KernelOperator, \
NormalizedKernelMixin, PairwiseKernel, RationalQuadratic, StationaryKernelMixin, RBF, CompoundKernel, DotProduct, Product, GenericKernel... | lisunshine1234/mlp-algorithm-python | machine_learning/regression/gaussian_processes/GaussianProcessRegressor/main.py | main.py | py | 6,034 | python | zh | code | 0 | github-code | 6 |
21402453945 | import torch
import math
from torch import nn
import torch.nn.functional as F
from transformers.activations import get_activation
from .utils import init_weights
def _mask(logits, mask):
return mask * logits - 1e3 * (1 - mask)
# VarMisuse -----------------------------------------------------------------
class... | cedricrupb/ctxmutants | ctxmutants/modelling/meta_models.py | meta_models.py | py | 14,434 | python | en | code | 0 | github-code | 6 |
39048517647 | import re
import logging
from datetime import datetime, timezone
__all__ = ('datetime_to_ns',)
logger = logging.getLogger('aionationstates')
class DataClassWithId:
def __eq__(self, other):
# Ids in NS are pretty much always not globally unique.
if type(self) is not type(other):
ret... | micha030201/aionationstates | aionationstates/utils.py | utils.py | py | 6,383 | python | en | code | 0 | github-code | 6 |
37635242690 | from videos_freeze_analyzer import VideosFreezeAnalyzer
from video_valid_points_list_generator import dowload_url
from video_valid_points_list_generator import VideoValidPointsListGeneratorFfmpeg
from video_freeze_analyzer import VideoFreezeAnalyzer
import json
def main(urls):
files = []
for url in urls:
... | EderRobins/video_freeze_analyzer | main.py | main.py | py | 1,064 | python | en | code | 0 | github-code | 6 |
72638922747 | import pandas as pd
from dotenv import load_dotenv
import os
# load env
load_dotenv()
# load dataset
url = "https://raw.githubusercontent.com/erijmo/3690/main/healthcare_dataset.csv"
df = pd.read_csv(url)
# set api key
api_key = os.getenv("OPENAI_API_KEY")
def get_healthcare_response(user_input, user_... | erijmo/3690 | chatbot.py | chatbot.py | py | 1,661 | python | en | code | 0 | github-code | 6 |
43242935161 | from thumbor.utils import logger
try:
import cv2 # noqa
import numpy as np # noqa
CV_AVAILABLE = True
except ImportError:
CV_AVAILABLE = False
class BaseDetector:
def __init__(self, context, index, detectors):
self.context = context
self.index = index
self.detectors = d... | thumbor/thumbor | thumbor/detectors/__init__.py | __init__.py | py | 983 | python | en | code | 9,707 | github-code | 6 |
34429645121 | class Node:
def __init__(self, data):
self.data = data
self.nref = None
self.pref = None
class Queue:
def __init__(self):
self.start = None
self.end = None
def is_empty(self):
return self.start is None
def pop(self):
if self.is_empty():
... | scary327/python_skillbox | mod5/task2.py | task2.py | py | 1,687 | python | en | code | 0 | github-code | 6 |
38666481157 | import sys
def qtm(seq):
result = 0
for move in seq:
if move.startswith("("):
result += 0 # this line does nothing, but I added it for clarity that we weight AUF as 0
elif "2" in move:
result += 2
else:
result += 1
return result
def htm(seq):
... | kuba97531/kubesolver | src/py/sort_algs.py | sort_algs.py | py | 1,942 | python | en | code | 4 | github-code | 6 |
70063293948 | import socket
import tkinter as tk
from tkinter import *
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to the server
host = '10.0.65.12'
port = 5556
s.connect((host, port))
print('Connected to the server')
name = input("What's your name: ")
print(name)
s.send(str.encode(name))
flag = s.recv(1042... | CrazyKanav/21_Dares | DKINTER/client.py | client.py | py | 2,924 | python | en | code | 0 | github-code | 6 |
21341173003 | import torch
from torch.optim import SGD
import torch.nn.functional as F
from sklearn.metrics import accuracy_score
from models_torch.FFM import FFM_Layer
from utils.load_data import load_criteo_data
if __name__ == '__main__':
(X_train, y_train), (X_test, y_test), feature_info = load_criteo_data('dataset... | KrianJ/CtrEstimate | predict_ffm_torch.py | predict_ffm_torch.py | py | 1,739 | python | en | code | 0 | github-code | 6 |
10695567948 | import subprocess
from multiprocessing import Pool
import os
import numpy as np
import sys
def Thread(arg):
print(arg)
file = open('output/' + str(0) + '.log', 'w')
subprocess.call(arg, shell=True, stdout=file)
def main():
seed = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
batch = np.array([10, 50,... | mikufan/NCRFAE_DepParsing | noderun_pl_model.py | noderun_pl_model.py | py | 1,323 | python | en | code | 3 | github-code | 6 |
43193622036 | #!/usr/bin/env python
import rospy
import smach
from mavros_msgs.msg import WaypointList
from std_msgs.msg import Bool,String
from PrintColours import *
#from aerialcore_common.srv import ConfigMission, ConfigMissionResponse
#
# def mission_callback(req):
# rospy.loginfo(" /mission/new service was called")
# ... | miggilcas/muav_state_machine | scripts/AgentStates/gcs_connection.py | gcs_connection.py | py | 2,658 | python | en | code | 0 | github-code | 6 |
3121294529 | import os
import sys
import time
from functools import partial
from multiprocessing import Pool
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chro... | davi1972/greener-app | greener-scraper/greener-scraper-cli.py | greener-scraper-cli.py | py | 9,583 | python | en | code | 1 | github-code | 6 |
18216861751 | #Fall2019W7
#C-Elevator Trouble
def failMsg():
print("use the stairs")
def main():
params = input().split()
f = int(params[0])
s = int(params[1])
g = int(params[2])
u = int(params[3])
d = int(params[4])
floorDif = g - s
curr = s
buttonPresses = 0
if (floorDif % 2 == 1 a... | andrew-qu2000/Programming-Club | Poly Programming Club/Fall2019W7C.py | Fall2019W7C.py | py | 450 | python | en | code | 0 | github-code | 6 |
41146228063 | from flask import Flask, g, render_template, request, send_from_directory, url_for
import sqlite3, os, datetime
from werkzeug.utils import redirect, secure_filename
SITENAME = 'SaLeeMas - PicShare'
# Définir le dossier dans lequel les photos
# vont petre uploadés
UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'png',... | Sabrina-MORSLI/PicShare | picshare/run.py | run.py | py | 7,210 | python | en | code | 0 | github-code | 6 |
17522204148 | import json
import sqlite3
from urllib import response
from fastapi.testclient import TestClient
import time
import pytest
from main import app, conn, c
from models import AtualizarFilme, AtualizarPlaneta, Filme, Planeta, Excluido, InserirPlaneta
client = TestClient(app)
# def test_create_schema():
# c.executesc... | MarceloTerra0/FastAPI_TesteTuring | test_main.py | test_main.py | py | 5,453 | python | en | code | 0 | github-code | 6 |
27465756937 | import keras.backend as K
import tensorflow as tf
import cv2
import imageio
import numpy as np
def square_sum(x):
return K.sum(K.square(x), axis=-1, keepdims=True)
def euclSq(x):
x, y = x
x = K.batch_flatten(x)
y = K.batch_flatten(y)
return square_sum(x - y)
def l2_normalize(x):
inv_sqrt = ... | ebatuhankaynak/DeepPotato | src/util.py | util.py | py | 1,405 | python | en | code | 0 | github-code | 6 |
39939937920 | from mpl_toolkits.mplot3d import axes3d
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import csv
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
from mpl_toolkits.mplot3d import Axes3D
import plotly.graph_objects as go
import plotly.express as px
... | urbancomp/fogarch | FogLayer/visualization/chart3_old.py | chart3_old.py | py | 7,553 | python | en | code | 1 | github-code | 6 |
34213861281 | import math
n = int(input())
for _ in range(n):
line = input()
k = int(math.sqrt(len(line)))
chunks = [line[i:i+k] for i in range(0, len(line), k)]
s = ""
for j in reversed(range(k)):
for chunk in chunks:
s += chunk[j]
print(s) | david-vinje/kattis-problems | Solutions/EncodedMessage.py | EncodedMessage.py | py | 250 | python | en | code | 0 | github-code | 6 |
3755394850 | import asyncio
import traceback
from neptune_py.skeleton.skeleton import NeptuneServiceSkeleton
from neptune_py.skeleton.messager import (
NeptuneWriterBaseAbstract, NeptuneMessageType
)
import struct
import collections
class TLV:
_format = '!HI'
meta_size = struct.calcsize(_format)
tlv = collections... | kstardust/neptune | neptune_py/skeleton/transporter/neptune_tlv.py | neptune_tlv.py | py | 3,598 | python | en | code | 0 | github-code | 6 |
18805702748 | # 9 - Crie uma lista contendo 5 nomes e adicione esta lista dentro da lista gerada no exercício 4
import random
lista1 = ['Maria', 'João', 'Marcio', 'Marta', 'Ana']
lista2 = []
contador = 0
while contador < 10:
n = random.randint(10, 1580)
lista2.append(n)
contador += 1
lista2.append(lista1)
print(list... | chrystian-souza/exercicios_em_python | exerciciosAula4/exercicio09.py | exercicio09.py | py | 326 | python | pt | code | 0 | github-code | 6 |
44833012944 | import socket
from time import sleep
TCP_IP = '192.168.1.103'
TCP_PORT = 5005
BUFFER_SIZE = 40 # Normally 1024, but we want fast response
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
c1 = ""
c2 = ""
print("INICIA SERVER")
conn, addr = s.accept()
print('Connection a... | juanmanuelramallo/Monster-Pi | Pruebas/server.py | server.py | py | 924 | python | en | code | 0 | github-code | 6 |
3286995844 | from utility import classifier as cls
import numpy as np
import random
# action space 中的最后一个动作为终止
# 自己构建的环境
class MyEnv:
def __init__(self, state_size, max, data, classifier):
self.state_size = state_size
self.action_size = state_size + 1 # 包含一个终止动作
self.max = max # 最多选取max个特征,超出直接终止
... | jsllby/select-features | utility/env.py | env.py | py | 2,162 | python | en | code | 0 | github-code | 6 |
26531296671 | from pyhpecfm import fabric
from lib.actions import HpecfmBaseAction
class fabricIpLookup(HpecfmBaseAction):
def run(self):
cfm_fabrics = fabric.get_fabric_ip_networks(self.client)
if isinstance(cfm_fabrics, list):
fabric_data = []
# Loop through cfm_fabrics and process IPZ
... | HewlettPackard/stackstorm-hpe-cfm | actions/get_fabric_ips.py | get_fabric_ips.py | py | 979 | python | en | code | 1 | github-code | 6 |
35777431960 | from pydoc import tempfilepager
from PIL import Image
import numpy
import cv2
slot_1_box = (905, 215, 930, 235)
slot_2_box = (933, 215, 958, 235)
slot_3_box = (961, 215, 986, 235)
slots_poss = (slot_1_box, slot_2_box, slot_3_box)
def get_crop(_source, _box):
return Image.open(_source).convert('RGB').crop(_box) ... | BruceCheng1995/cyber_hunter | src/analyze_slot.py | analyze_slot.py | py | 2,531 | python | en | code | 0 | github-code | 6 |
36403480999 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# 技术支持:dwz.cn/qkEfX1u0 项目实战讨论QQ群6089740 144081101
# CreateDate: 2019-12-29
def fib2(n):
if n < 2: # base case
return n
return fib2(n - 2) + fib2(n - 1) # recursive case
if __name__ == "__main__":
print(fib2(5))
print(fib2(10)) | china-testing/python-testing-examples | interview/fib2.py | fib2.py | py | 325 | python | en | code | 35 | github-code | 6 |
26041579406 | from __future__ import annotations
import itertools
import re
from collections import defaultdict
from typing import Iterable, Iterator, Sequence, Tuple, TypeVar
from pkg_resources import Requirement
from typing_extensions import Protocol
from pants.backend.python.subsystems.setup import PythonSetup
from pants.backe... | pantsbuild/pants | src/python/pants/backend/python/util_rules/interpreter_constraints.py | interpreter_constraints.py | py | 21,381 | python | en | code | 2,896 | github-code | 6 |
16916661051 | import subprocess
import sys
import json
import platform
import os
from crmetrics import CRBase
class CRLogs(CRBase):
def _get_container_logs(self, pod, namespace, containers, kubeconfig):
for c in containers:
container = c['name']
cmd = 'kubectl logs ' + pod + ' -n ' + namespace + ' -c ' + container + ' ' +... | cloud-ark/kubeplus | plugins/crlogs.py | crlogs.py | py | 3,366 | python | en | code | 555 | github-code | 6 |
31089813709 | #!/bin/python3
# Prune only reasonable lexical mappings using both lex.e2f & lex.f2e
import pickle
def is_char_in_lang_range(c):
'''hindi unicode range is 0900 - 097F
or 2304 - 2431 in integers'''
lb = 2304
ub = 2431
ic = ord(c)
return ic >= lb and ic <= ub
def is_lang(word):
'''... | bnjasim/phraseOut | get_lex_dict.py | get_lex_dict.py | py | 2,175 | python | en | code | 0 | github-code | 6 |
3919536002 | # standard python libs
import os
import re
import html
import json
import random
import hashlib
import lxml.html
import lxml.etree
import unicodedata
import urllib.request
from datetime import datetime
from urllib.parse import urlparse
from urllib.parse import urlsplit
# non-standard libs which must be installed
from ... | thezedwards/webXray | webxray/OutputStore.py | OutputStore.py | py | 43,016 | python | en | code | 1 | github-code | 6 |
72715840829 | from django.db import models
from django import forms
from django.contrib.auth import get_user_model
# Create your models here.
class Challenge(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey ( # author info will be retrieved from the user model
get_user_model(),
... | hackathon-team-1/ReadingChallenge | readingchallenge/challenges/models.py | models.py | py | 1,024 | 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.