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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
75002646183 | from concurrent.futures import ThreadPoolExecutor,wait,as_completed
from socket import timeout
from turtle import done
from unittest.result import failfast
import requests
import re
import warnings
import os
import traceback
import importlib
warnings.filterwarnings('ignore')
url='https://e-hentai.org'
slist... | CrystalRays/pytools | ehentaidownloader.py | ehentaidownloader.py | py | 4,505 | python | en | code | 0 | github-code | 36 |
9856058749 | import re
import csv
import os
import sys
import pickle
from pprint import pprint
from enum import Enum
sys.path.insert(0, '../heatmap')
sys.path.insert(0, '../tests')
from stat_type_lookups import *
from tester import *
# Types of files:
# Fundamental files
# - PlayByPlay.csv, GameIDs.csv, BoxscoreStats.csv
#... | AdamCharron/CanadaBasketballStats | enrich/parse_to_yaml.py | parse_to_yaml.py | py | 11,609 | python | en | code | 0 | github-code | 36 |
38164556201 | import glob
import importlib
import io
import logging
import os
import shlex
import subprocess
import time
import cornet
import numpy as np
import pandas
import torch
import torch.nn as nn
import torch.utils.model_zoo
import torchvision
import tqdm
from PIL import Image
from torch.nn import Module
Image.warnings.simp... | franzigeiger/training_reductions | base_models/trainer_performance.py | trainer_performance.py | py | 12,170 | python | en | code | 3 | github-code | 36 |
13262505124 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy,roslib
from std_msgs.msg import Bool
from ardrone_autonomy.msg import Navdata
from drone_controller import droneStatus
from ardrone_project.msg import ImageCalc
controlStatus = {
0:None,
1:"Take_Off_Unit",
2:"Land_Unit",
3:"Follow_controller",... | alexoshri/ardrone_project_work | scripts/central_control_unit.py | central_control_unit.py | py | 4,015 | python | en | code | 0 | github-code | 36 |
74582104744 | from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from .models import File
from .models import Folder
from .serializers import FileSerializer
from .s... | balibabu/backend | fileapi/views.py | views.py | py | 4,763 | python | en | code | 0 | github-code | 36 |
7870435087 | from bs4 import BeautifulSoup
from uk_bin_collection.uk_bin_collection.common import *
from uk_bin_collection.uk_bin_collection.get_bin_data import \
AbstractGetBinDataClass
# import the wonderful Beautiful Soup and the URL grabber
class CouncilClass(AbstractGetBinDataClass):
"""
Concrete classes have to ... | robbrad/UKBinCollectionData | uk_bin_collection/uk_bin_collection/councils/ValeofGlamorganCouncil.py | ValeofGlamorganCouncil.py | py | 4,863 | python | en | code | 51 | github-code | 36 |
37208016314 | from datetime import datetime, timedelta
birthdate = input("Tell us your bidrthay in DD.MM.YYYY format ")
print(birthdate)
date_obj = datetime.strptime(birthdate, '%d.%m.%Y').date()
print(date_obj)
time_difference = datetime.now().date() - date_obj
time_now = datetime.now()
if (time_now.year < date_obj.year):
pr... | KyleKiske/DI-Bootcamp | Week2/Day2/ChallengeGold.py | ChallengeGold.py | py | 1,248 | python | en | code | 0 | github-code | 36 |
10828719550 | import math
def solution(w,h):
total = w * h
if w == h: # 정사각형인 경우
return total - w
else: # 직사각형인 경우
# 가로질러가는 가로의 개수 + 세로의 개수에서 - 최대공약수 빼주기
# ex) 가로가 2, 세로가 3일 때
# 가로질러가는 가로: 3개 , 가로질러가는 세로: 2개, 최대공약수는 1
return total - (w+h-math.gcd(w,h))
| choijaehoon1/programmers_level | src/test07.py | test07.py | py | 447 | python | ko | code | 0 | github-code | 36 |
28067670792 | # 2021-03-12
# 출처 : https://www.acmicpc.net/problem/1009
# 분산처리
# 재용이는 최신 컴퓨터 10대를 가지고 있다. 어느 날 재용이는 많은 데이터를 처리해야 될 일이 생겨서 각 컴퓨터에 1번부터 10번까지의 번호를 부여하고, 10대의 컴퓨터가 다음과 같은 방법으로 데이터들을 처리하기로 하였다.
# 1번 데이터는 1번 컴퓨터, 2번 데이터는 2번 컴퓨터, 3번 데이터는 3번 컴퓨터, ... ,
#
# 10번 데이터는 10번 컴퓨터, 11번 데이터는 1번 컴퓨터, 12번 데이터는 2번 컴퓨터, ...
#
# 총 데이터의... | hwanginbeom/algorithm_study | 1.algorithm_question/2.implemented/88.Implemented_kyounglin.py | 88.Implemented_kyounglin.py | py | 1,361 | python | ko | code | 3 | github-code | 36 |
38916812011 | import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import time
import random
from discord import Game
Client = discord.client
client = commands.Bot(command_prefix = '-')
Clientdiscord = discord.Client()
TOKEN = ("NTczNDkxODgzOTc2ODE4Njk4.XMroNg.Pzwl-RFn... | ANATLANTIDA/BOT | Bot.py | Bot.py | py | 2,165 | python | en | code | 0 | github-code | 36 |
36829740540 | import pytest
from launch_jenkins import launch_jenkins
from launch_jenkins import log
from launch_jenkins import errlog
from launch_jenkins import CaseInsensitiveDict
def test_log(monkeypatch, capsys):
monkeypatch.setitem(launch_jenkins.CONFIG, 'quiet', False)
log('hello', 'world')
out, err = capsys.rea... | ocaballeror/jenkins-launch | tests/test_misc.py | test_misc.py | py | 1,681 | python | en | code | 0 | github-code | 36 |
14041677139 | def coach_data(file_name):
try:
with open(file_name) as f:
data = f.readline()
return (data.strip().split(','))
except IOError as err:
print('File error:', str(err))
return None
def sanitize(time_string):
if '-' in time_string:
splitter = '-'
elif ':... | duheng18/python-study | headfirst/example/example15.py | example15.py | py | 722 | python | en | code | 0 | github-code | 36 |
44095045713 | from test_framework import generic_test
def closest_int_same_bit_count(x: int) -> int:
# what we want to do here is basically swap the first different bits to get the same weight but closest abs val
# to do this, we loop from 0 to 63
for i in range(63):
shift1 = x >> i
shift2 = x >> i+1
... | kchen1025/Python-EPI | epi_judge_python/closest_int_same_weight.py | closest_int_same_weight.py | py | 1,001 | python | en | code | 0 | github-code | 36 |
21594616095 | import spacy
import plac
import numpy as np
import time
import re
import os
import sys
import argparse
from sklearn.metrics import accuracy_score
from conllToSpacy import main
# Parsing argument for command-line.
parser = argparse.ArgumentParser(description="Testing an NER model with SpaCy.")
parser.add_argument("-tp"... | Djia09/Named-Entity-Recognition-spaCy | test_ner_spacy.py | test_ner_spacy.py | py | 3,496 | python | en | code | 3 | github-code | 36 |
42576581221 | """ Exercício para mostras as faces encontradas com variação de parâmetro """
import cv2
classificador = cv2.CascadeClassifier('cascades\\haarcascade_frontalface_default.xml')
imagem = cv2.imread('pessoas\\pessoas3.jpg')
imagemcinza = cv2.cvtColor(imagem, cv2.COLOR_BGR2GRAY)
facesdetectadas = classificador.detectMu... | alans96/PythonProject | Computer Vision/1 Detecção de Faces com Python e OpenCV/3 exe.py | 3 exe.py | py | 583 | python | pt | code | 0 | github-code | 36 |
42603056105 | import os
import json
import shutil
import time
import traceback
__author__ = 'Michael Ryan Harlich'
def update_paths(paths):
paths['partial_prediction'] = paths['output'] + 'partial_predication.ent'
paths['partial_ground_truth'] = paths['output'] + 'partial_ground_truth.ent'
paths['aligned_prediction'] ... | RyanHarlich/Ca-Prediction-Automated-Testing-Quick-Tools | segments_rmsd/partial_protein/partial_protein.py | partial_protein.py | py | 2,534 | python | en | code | 0 | github-code | 36 |
7143422402 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'wangzhefeng'
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
# data
cmb = pd.read_excel("/home/wangzhefeng/project/python/projects/zhaohanglicai/CMB_Finance.xlsx")
... | wangzhefeng/DataSpider | projects/zhaohanglicai/zhlc_analysis.py | zhlc_analysis.py | py | 1,439 | python | en | code | 0 | github-code | 36 |
17300324237 | from django.conf.urls import url
from django.views.generic import TemplateView
from .views import (
klasses_list_view,
klasses_detail_view,
klasses_create_view,
klasses_delete_view,
klasses_update_view,
)
urlpatterns =[
# This is Klasses pages
url(r'^list/$', klasses_list_view, name='klasse... | SaramCodes/School-Management-System | klass/urls.py | urls.py | py | 683 | python | en | code | 1 | github-code | 36 |
15637256017 | import os
import csv
import sys
import fnmatch
import shutil
import time
import re
import config as cfg
import numpy as np
import pandas as pd
import mysql.connector as mysql
import sqlalchemy
from datetime import datetime
from dateutil.parser import parse
from selenium import webdriver
from selenium.webdriver.common.k... | xxwikkixx/ChadBot | barchart/barchartDl.py | barchartDl.py | py | 6,546 | python | en | code | 16 | github-code | 36 |
4640657000 | from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status, permissions
from .models import CustomUser
from .serializers import CustomUserSerializer
# Create your views here.
class CustomUserList(APIView):
permission_cl... | SheCodesAus/heading_for_success_backend_bris_2023 | SheFunds_backend/users/views.py | views.py | py | 1,915 | python | en | code | 1 | github-code | 36 |
44145316591 | import json
import logging
import typing
class JSONDumpReader(typing.Iterator[dict]):
def __init__(self, dump_path: str):
self.__dump_path = dump_path
def __iter__(self):
with open(self.__dump_path) as f:
for l in f:
l = JSONDumpReader.__clean_line(l)
... | AlexandraBaier/bachelorthesis | data_analysis/dumpio.py | dumpio.py | py | 1,344 | python | en | code | 0 | github-code | 36 |
28930913211 | #!/usr/bin/python3
# -*- coding: utf8 -*-
# Code from here:
# https://stackoverflow.com/a/26289475
import psutil
import subprocess
import time
import os
class SSHTunnel(object):
"""
A context manager implementation of an ssh tunnel opened from python
"""
def __init__(self, tunnel_command):
a... | Vasilesk/quotes-posting | sshtunnel.py | sshtunnel.py | py | 2,205 | python | en | code | 0 | github-code | 36 |
37955494687 | from flask import Flask, request, jsonify
import util
app = Flask(__name__)
# @app.route decorator exposes the http enedpoint
@app.route("/hello")
def test():
return "hello world"
@app.route("/get-locations")
def get_locations():
response = jsonify(
{
"locations": util.get_locations()
... | Chiemerie1/house_prices_ML_model_deployment | server/server.py | server.py | py | 963 | python | en | code | 0 | github-code | 36 |
44310767729 | import pygame, colors, random, time, sideclass, draw, timer
from random import randint
def collision(player, enemy, player1, screen, WIDTH, HEIGHT):
if (pygame.sprite.groupcollide(player, enemy, False, True)):
draw.drawlose(enemy, screen, WIDTH, HEIGHT)
player1.score = 0
def side(screen, WIDTH, ... | RamboTheGreat/Minigame-Race | sidescroll.py | sidescroll.py | py | 2,909 | python | en | code | 0 | github-code | 36 |
21136786262 | # 动态规划
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
# 数组的长度
n = len(nums)
if not n: return 0
# 初始化状态
pre = nums[0]
ans = pre
# 状态转移
for i in range(1, n):
pre = pre + nums[i] if pre>0 else nums[i]
ans = max(p... | SkyChaseHsu/leetcode_cookboook | solutions/53_maximum-subarray/53_maximum-subarray.py | 53_maximum-subarray.py | py | 384 | python | en | code | 1 | github-code | 36 |
42754051183 | from datetime import datetime
from elasticsearch import Elasticsearch
from elasticsearch import helpers
import json
import time
es = Elasticsearch()
f = open("yt_data.rst")
lines = f.readlines()
cnt = 1
data_cnt = 0
actions = []
s = time.time()
for line in lines:
data = json.loads(line)
action = {
"_ind... | timothyliu0912/db_project | db/c.py | c.py | py | 641 | python | en | code | 0 | github-code | 36 |
12338769948 | ################011011100110010101101111####
### neo Command Line #######################
############################################
def getcmdlist():
cmds = {
"os" :"Open active Schedule View in Excel.",
"ov" :"Open selected views in Project Browser."
}
return c... | 0neo/pyRevit.neoCL | neoCL.extension/neocl_o.py | neocl_o.py | py | 700 | python | en | code | 7 | github-code | 36 |
40554209630 | """
Stack-In-A-Box: Stack Management
"""
import logging
import re
import threading
import uuid
import six
logger = logging.getLogger(__name__)
class ServiceAlreadyRegisteredError(Exception):
"""StackInABoxService with the same name already registered."""
pass
class StackInABox(object):
"""Stack-In-A-... | TestInABox/stackInABox | stackinabox/stack.py | stack.py | py | 11,760 | python | en | code | 7 | github-code | 36 |
36570577773 | from haystack.forms import SearchForm
from django import forms
from haystack.query import SearchQuerySet
from haystack.query import SQ
from peeldb.models import City
valid_time_formats = ["%Y-%m-%d 00:00:00"]
class job_searchForm(SearchForm):
q = forms.CharField(max_length=200, required=False)
location = for... | MicroPyramid/opensource-job-portal | search/forms.py | forms.py | py | 7,863 | python | en | code | 336 | github-code | 36 |
22234739193 | from pykinect2 import PyKinectV2
from pykinect2.PyKinectV2 import *
from pykinect2 import PyKinectRuntime
import numpy as np
import cv2
import time
# kinect = PyKinectRuntime.PyKinectRuntime(PyKinectV2.FrameSourceTypes_Color)
# while True:
# if kinect.has_new_color_frame():
# frame = kinect.get_last_color_fram... | zachvin/KinectImaging | tests.py | tests.py | py | 996 | python | en | code | 0 | github-code | 36 |
5577508746 | import json
with open('firm.txt', 'r', encoding='utf-8') as f:
data = []
for line in f:
line = line.replace("\n", "")
string = line.split(" ")
data.append(string)
average = 0
avg_firms = 0
diction = {}
for el in data:
profit = int(el[2]) - int(el[3])
diction.update({el[0]:profi... | Ilyagradoboev/geekproject | lesson_5.7.py | lesson_5.7.py | py | 580 | python | en | code | 0 | github-code | 36 |
26285333278 | import os, requests, colorama
from colorama import Fore
green = Fore.GREEN
red = Fore.RED
yellow = Fore.YELLOW
reset = Fore.RESET
#banner
banner = """
__ __ __
/ / / /___ _____/ /_
/ /_/ / __ \/ ___/ __/
/ __ / /_/ (__ ) /_ ... | Nadeesha-Prasad/Zero-Balance-Host-Scanner-For-Linux | hscan.py | hscan.py | py | 2,271 | python | en | code | 1 | github-code | 36 |
20466647981 | """
왕실의 나이트
1) x, y축 범위 벗어나는지 체크
2) 2가지 경우의 수로 이동해보기
3) 이동 가능한 count 출력
"""
import sys
location = sys.stdin.readline()
x, y = (ord(location[0]) - 96), int(location[1])
count = 0
def search(current_x, current_y, dx, dy):
global count
for i in range(4):
nx = current_x + dx[i]
ny = current_y + ... | roum02/algorithm | implementation/practice4-2.py | practice4-2.py | py | 580 | python | ko | code | 0 | github-code | 36 |
30351631272 |
def load_and_get_stats(filename):
"""Reads .wav file and returns data, sampling frequency, and length (time) of audio clip."""
import scipy.io.wavfile as siow
sampling_rate, amplitude_vector = siow.read(filename)
wav_length = amplitude_vector.shape[0] / sampling_rate
return sampling_rate, amplit... | Sychee/Piano-Audio-Classifier | audio_to_spectogram.py | audio_to_spectogram.py | py | 1,820 | python | en | code | 0 | github-code | 36 |
41203564707 | import cv2
import numpy as np
from PIL import Image
facedetect = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')#create a cascade classifier using haar cascade
cam = cv2.VideoCapture(0)#creates avideo capture object
rec=cv2.createLBPHFaceRecognizer()#create a recognizer object
rec.load("test_traini... | UPASANANAG/Face-Recognizer | facedetector.py | facedetector.py | py | 1,437 | python | en | code | 0 | github-code | 36 |
22868444012 | import pandas as pd
import numpy as np
from nltk.corpus import stopwords
nltk_stopwords = stopwords.words('english')
# Sklearn TF-IDF Libraries
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity... | chois11/7071CEM-R | resources/backend/search_engine.py | search_engine.py | py | 1,376 | python | en | code | 0 | github-code | 36 |
26009651155 | import argparse
import os
import random
import re
import subprocess
import time
parser = argparse.ArgumentParser()
parser.add_argument(
"-n", "--number", help="max number of problems to attempt", type=int
)
parser.add_argument(
"-r", "--random", help="attempt problems in random order", action="store_true"
)
pa... | russellw/ayane | script/e.py | e.py | py | 2,820 | python | en | code | 0 | github-code | 36 |
4005001933 | #!/usr/local/bin/python
from config import *
class Primer:
"""
Primer is an object representing a primer either left or right.
Two primers are equal if their sequence are the same and their TFGP are equal.
:param target: the target instance where the primer come from.
:param sequence: sequence o... | gloubsi/oncodna_primers_design | code/primer.py | primer.py | py | 4,684 | python | en | code | 0 | github-code | 36 |
36060957275 | # list of registered users - pdf - full format
# list of users who availed book - name, ISBN, borrowDate and returnDate
# list of users with fine amount - name and fee pending
# send notification about the due submit and late fee - sends notification
from db_read import database
from fpdf import FPDF
from tkinter... | sridamul/BBMS | userManagement.py | userManagement.py | py | 11,961 | python | en | code | 0 | github-code | 36 |
40746622543 | import numpy as np
import gzip
from ase import Atom, Atoms
import gzip
import io
import os
from ase.io import write, read
import pyscal3.formats.ase as ptase
import warnings
def read_snap(infile, compressed = False):
"""
Function to read a POSCAR format.
Parameters
----------
infile : string
... | pyscal/pyscal3 | src/pyscal3/formats/vasp.py | vasp.py | py | 3,869 | python | en | code | 2 | github-code | 36 |
33052012137 | from sqlalchemy.orm import Session
import curd, cloud, orm
def policy_with_projects(yun, projects):
if not projects or len(projects) == 0:
return None
tagvals = ','.join(['"'+p.project.name+'"' for p in projects])
return yun.CloudIAM.policy_gen_write_with_tag("Project", tagvals)
def policy_with_te... | kealiu/codecommitter | app/iam.py | iam.py | py | 2,267 | python | en | code | 0 | github-code | 36 |
2109558152 | import numpy as np
import pandas as pd
from math import factorial, pi
import scipy.optimize
import scipy.misc
import os
import re
import argparse
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF,ConstantKernel
# for tests
#import matplotlib.pyplot... | pierre-moreau/EoS_HRG | EoS_HRG/fit_lattice.py | fit_lattice.py | py | 20,400 | python | en | code | 0 | github-code | 36 |
36929730434 | import exdir
import quantities as pq
import numpy as np
def convert_from_list(data):
if isinstance(data, dict):
try:
for key, value in data.items():
data[key] = convert_from_list(value)
except AttributeError:
pass
elif isinstance(data, list):
ret... | CINPLA/exdir | exdir/plugins/numpy_attributes.py | numpy_attributes.py | py | 1,435 | python | en | code | 69 | github-code | 36 |
24644699429 | import io
import itertools
def part_one():
file = open('inputs\\day_1_part_1.txt', 'r')
total = 0
for line in file:
total = total + int(line)
print(f'Part 1 Total {total}')
def part_two():
file = open('inputs\\day_1_part_1.txt', 'r')
observed_frequencies = {0}
total = 0
for lin... | mruston0/AdventOfCode2018 | day_1_chronal_calibration.py | day_1_chronal_calibration.py | py | 639 | python | en | code | 0 | github-code | 36 |
31515158551 | """Basic state machine implementation."""
# pylint: disable=unnecessary-pass, too-many-instance-attributes
from typing import Iterable, Union
from rclpy import logging
from rclpy.node import Node
from rclpy.time import Time, Duration
LOGGER = logging.get_logger("behavior")
class Resource:
"""The resource class i... | LARG/spl-release | src/behavior/behavior/state_machine.py | state_machine.py | py | 22,719 | python | en | code | 1 | github-code | 36 |
12171164046 | # 어린 왕자
import sys
t = int(input()) # 테스트 케이스
for i in range(t):
x1, y1, x2, y2 = map(int, sys.stdin.readline().split()) # 출발점, 도착점 좌표
n = int(input()) # 행성의 개수
stars = []
for i in range(n): # 행성의 중심과 반지름
cx, cy, r = map(int, sys.stdin.readline().split())
stars.append([cx, cy, r])
... | hi-rev/TIL | Baekjoon/기하1/little_prince.py | little_prince.py | py | 862 | python | ko | code | 0 | github-code | 36 |
35056080810 | import cantera as ct
import numpy as np
from typing import List, Tuple
from scipy import integrate
from copy import copy
"""
Present a simple implementation of IDT reactors and the
cantera implementation of a LFS reactor.
Each model can be called as:
IDT, all_conditions = idt_reactor.solve(gas, flag='T', temp_rise=... | fingeraugusto/red_app | src/reactors.py | reactors.py | py | 11,199 | python | en | code | 0 | github-code | 36 |
13412389294 | import pandas as pd
import numpy as np
from training_utils import train_eval_model, store_model
### 1. Load data from data.csv file
data_train = pd.read_csv("data_train.csv", sep=';', header=0, dtype={'Gender': int, 'Age': int, 'Competitionage': int,
... | MiriUll/Swim-result-prediction | machine_learning/train_tf_model.py | train_tf_model.py | py | 2,277 | python | en | code | 0 | github-code | 36 |
42259381708 | import numpy as np
from ochre.datagen import DataGenerator
def dgen():
ocr_seqs = ['abc', 'ab', 'ca8']
gs_seqs = ['abc', 'bb', 'ca']
p_char = 'P'
oov_char = '@'
n = 3
ci = {'a': 0, 'b': 1, 'c': 2, p_char: 3, oov_char: 4}
dg = DataGenerator(xData=ocr_seqs, yData=gs_seqs, char_to_int=ci,
... | KBNLresearch/ochre | tests/test_datagen.py | test_datagen.py | py | 1,111 | python | en | code | 119 | github-code | 36 |
15539017308 | from functools import reduce
from decimal import Decimal
# From stdin:
# num_of_elem=int(input())
# elements=list(map(int,input().split()))
# From a file:
num_of_elem=0
elements=""
with open('input/input03.txt','r') as file_in:
file_lines=file_in.readlines()
num_of_elem=int(file_lines[0])
elements=file_li... | gianv9/HackerRanksSubmissions | 10 Days of Statistics/Day 0/Mean Median and Mode/solution.py | solution.py | py | 1,156 | python | en | code | 0 | github-code | 36 |
28230488326 | from requests import Request, Session
import config
import json
__all__=['SendBookClass', 'SendFindClass']
config_FindClass = config.FindClass()
config_BookClass = config.BookClass()
http_proxy = "http://localhost:8888"
https_proxy = "https://localhost:8888"
ftp_proxy = "ftp://10.10.1.10:3128"
#cafile = 'FiddlerR... | akhildevelops/cult-fitness-auto-book | cult_network.py | cult_network.py | py | 2,133 | python | en | code | 1 | github-code | 36 |
35515239669 | import argparse
from datetime import datetime
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data
from model import Model
from dataset import Dataset
from tqdm import tqdm
from sklearn.metrics import confusion_matrix, roc_curve, auc
import numpy as np
import matplotli... | onermustafaumit/MLNM | gland_classification/four_resolutions_model/test.py | test.py | py | 9,294 | python | en | code | 4 | github-code | 36 |
37770543831 | import sys
def search_next_router(start, end):
mid_distance = (end - start) // 2
count = 1
for idx, a_house in enumerate(houses[1:]):
if (a_house - houses[idx]) > mid_distance:
count += 1
return count
N, C = map(int, input().split())
houses = [int(sys.stdin.readline()) for _ in ... | TB2715/python-for-coding-test | BaekJoon/2110.py | 2110.py | py | 374 | python | en | code | 0 | github-code | 36 |
72694778664 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def deepestLeavesSum(self, root: TreeNode) -> int:
queue, result = [root, None], 0
while len(queue) != 1:
node = queue... | githubli97/leetcode-python | 202012/20201211/q1302.py | q1302.py | py | 637 | python | en | code | 0 | github-code | 36 |
41510394343 | # -*- coding: utf-8 -*-
# project 1
import pandas as pd
import numpy as np
import matplotlib
import warnings
import matplotlib.pyplot as plt
import os
import seaborn as sns
from scipy import stats as st
from scipy.linalg import svd
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklear... | tirohweder/into_ml_dm_project_1 | main.py | main.py | py | 11,707 | python | en | code | 3 | github-code | 36 |
38028426057 | """
Dmytro Mishagli, UCD
04 Dec 2019 -- the script was created.
"""
import numpy as np
def basis(x,n,L):
'''
The basis function.
'''
return np.sqrt(2/L) * np.sin( x * n * np.pi / L )
def integ(n,m,lower_limit,upper_limit,L):
"""
Returns values of the integrals in a Hamiltonian of a square potential well,
c... | mishagli/qsol | qsol.py | qsol.py | py | 2,359 | python | en | code | 1 | github-code | 36 |
12316087861 | import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
import os
import glob
import cv2
import math
import csv
import re
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from tensorflow.keras.applications.imagenet_utils import preprocess_input, decode_predictions
... | NoahSCode/EDUSIM | app_train.py | app_train.py | py | 10,305 | python | en | code | 0 | github-code | 36 |
34100493282 | # Practice python, assignment 3
# linked list
# bring codes for the single linked list and stack from the lab and lecture slides.
class LList:
class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
def __init__(self):
self.head = None... | angie0bb/python-practice | practice_python_p3.py | practice_python_p3.py | py | 5,153 | python | en | code | 0 | github-code | 36 |
43103024978 | from celery import shared_task
from celery.utils.log import get_task_logger
from decouple import config
logger = get_task_logger("tasks")
expiration_time = config("EXPIRATION_TIME", default=1800, cast=int)
@shared_task(
bind=True,
default_retry_delay=3,
eta=expiration_time,
retry_kwargs={... | guilhermehgbrito/qrcode-api | qrcode_api/apps/api/tasks.py | tasks.py | py | 721 | python | en | code | 0 | github-code | 36 |
74339948582 | # Module importieren
from machine import Pin
import time
# Pins für die LEDs aktivieren
rot = Pin(14, Pin.OUT)
gelb = Pin(12, Pin.OUT)
gruen = Pin(13, Pin.OUT)
# Funtion für die Ampelschaltung
def ampel(led):
#for i in range(5):
led(1)
time.sleep_ms(3000)
led(0)
time.sleep_ms(1)
#... | kvogl/MicroPython | MicroPython_Ampel/extern_led.py | extern_led.py | py | 444 | python | de | code | 0 | github-code | 36 |
17880038233 | from tkinter import *
window = Tk()
window.title("Grid Geometry")
lblNumYears = Label(window, text = "Number of Years:")
lblNumYears.grid(row = 0, column = 0, pady = 20) #top left
entNumYears = Entry(window, width =5)
entNumYears.grid(row = 0, column = 1, sticky = S)
btnCalculate = Button(window, text = ... | ES21215/my_awesome_repository | Python/GUI/Gui4.py | Gui4.py | py | 448 | python | en | code | 0 | github-code | 36 |
1063868906 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from PIL import Image
from matplotlib import pyplot as plt
import numpy as np
import pytesseract
import cv2
import tkinter as tk
import logging
import time
import re
import threading
# Dimensioning values
# We are defining global variables based on match data in order t... | BrunoSader/An-emotional-sports-highlight-generator | ocr/final_ocr.py | final_ocr.py | py | 18,525 | python | en | code | 4 | github-code | 36 |
41865132711 | from __future__ import absolute_import, print_function
import os
import numpy as np
import pyopencl as cl
os.environ['PYOPENCL_COMPILER_OUTPUT']='1'
modulepath=os.path.dirname(os.path.abspath(__file__))
class Particles(object):
def __init__(self,nparticles=1,ndim=10):
self.nparticles=nparticles
... | rdemaria/sixtracklib_gsoc18 | studies/study1/sixtracklib.py | sixtracklib.py | py | 2,937 | python | en | code | 0 | github-code | 36 |
72806130663 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 2 17:51:41 2018
@author: USER
"""
import sys
sys.path.append('..')
import os
import torch
import torch.nn as nn
import numpy as np
import utils.general as utils
import utils.adversarial_ae as ae_utils
from adverse_AE import Adversarial_AE, Discriminator
... | bchao1/Fun-with-MNIST | Adversarial_Autoencoder/train.py | train.py | py | 3,559 | python | en | code | 23 | github-code | 36 |
70712255464 |
with open('input.txt', 'r') as f:
input = f.readlines()
def findmax():
max = []
total = 0
for x in input:
if x.strip() != '':
total += int(x.strip())
else:
max.append(total)
total = 0
max.sort()
print(sum(max[-3:]))
findmax() | bg-gif/Advent-of-Code-2022 | day_one_a.py | day_one_a.py | py | 304 | python | en | code | 0 | github-code | 36 |
4969851196 | import math
import itertools
def klauber(x):
return x*x-x+41
def isPrime(x):
for i in range(2,1+int(math.sqrt(x))):
if x%i == 0:
return False
return True
def klauberNotPrime(r):
result = []
for i in range(1,r):
if not isPrime(klauber(i)):
result.append(i)
... | AlJinni/Genetic-Primes | Recovery.py | Recovery.py | py | 6,166 | python | en | code | 0 | github-code | 36 |
18626454048 | #
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be u... | ssOleg/pywbem | pywbem/_recorder.py | _recorder.py | py | 36,379 | python | en | code | null | github-code | 36 |
12852390478 | # An implementation of the three-body problem by Logan Schmalz
# https://github.com/LoganSchmalz/threebody/
# MIT License
import numpy as np
import scipy as sci
import scipy.integrate
import scipy.linalg
import matplotlib.pyplot as plt
# As astronomers, we like to normalize values to scales that make sense
# So that'... | LoganSchmalz/threebody | threebody.py | threebody.py | py | 5,543 | python | en | code | 0 | github-code | 36 |
23229025125 | import tensorflow as tf
from tools.tools import count
from tools.tools import indicator
class Loss(object):
def __init__(self):
pass
@staticmethod
def loss_l2(estimated, target):
"""estimated and target are dense tensors"""
with tf.name_scope('l2_loss'):
# with tf.cont... | MehdiAbbanaBennani/Neural-Networks-for-Collaborative-Filtering | autoencoder/Loss.py | Loss.py | py | 1,406 | python | en | code | 35 | github-code | 36 |
23314260402 | import logging
import os
from malware_extractor import MalwareExtractor
logger = logging.getLogger(__name__)
class VXVaultExtractor(MalwareExtractor):
def process_input(self):
# files are just zip files, so can simply copy those across
self.copy_files()
if __name__ == "__main__":
logger.i... | g-clef/malware_extractor | VXVaultExtractor.py | VXVaultExtractor.py | py | 708 | python | en | code | 0 | github-code | 36 |
7689734407 | def method1(arr, n, k):
arr.sort()
return arr[k - 1]
def method2(arr, k):
import heapq
smallest = []
for value in arr:
if len(smallest) < k:
heapq.heappush(smallest, -value)
else:
heapq.heappushpop(smallest, -value)
if len(smallest) < k:
return ... | thisisshub/DSA | F_sorting/problems/D_kth_smallest_element.py | D_kth_smallest_element.py | py | 645 | python | en | code | 71 | github-code | 36 |
20238646277 | from numpy import *
import operator
import matplotlib
import matplotlib.pyplot as plt
from os import listdir
def classify0(inX, dataSet, labels, k):
dataSetSize=dataSet.shape[0]#返回dataset的第一维的长度
print(dataSetSize)
diffMat = tile(inX, (dataSetSize,1)) - dataSet
#计算出各点离原点的距离
#表示diffMat的平方
sqDiffM... | geroge-gao/MachineLeaning | kNN/kNN.py | kNN.py | py | 4,622 | python | en | code | 4 | github-code | 36 |
22264732686 | from excepciones_estrellas import RutaPeligrosa
# No modificar esta función
def verificar_condiciones_estrella(estrella):
if estrella.luminosidad > 15500:
raise RutaPeligrosa("luz", estrella.nombre)
elif estrella.magnitud > 4:
raise RutaPeligrosa("tamaño", estrella.nombre)
elif estrella.te... | Alzvil/IIC2233-Progra-Avanzada-Tareas-2021-1 | Actividades/AF2/calcular_ruta.py | calcular_ruta.py | py | 842 | python | es | code | 0 | github-code | 36 |
35386932044 | #!/usr/bin/env python3
from sys import stderr, exit
import random
from multilanguage import Env, Lang, TALcolors
from TALinputs import TALinput
from TALfiles import TALfilesHelper
import triangle_lib as tl
# METADATA OF THIS TAL_SERVICE:
args_list = [
('source',str),
('instance_id',int),
('instance_forma... | romeorizzi/TALight | example_problems/tutorial/triangle/services/check_and_reward_one_sol_driver.py | check_and_reward_one_sol_driver.py | py | 5,352 | python | en | code | 11 | github-code | 36 |
42412749367 | from flask import Flask, Response, jsonify
from Flask_PoolMysql import func
# 实例化flask对象
app = Flask(__name__)
app.config.from_pyfile('config.py')
class JsonResponse(Response):
@classmethod
def force_type(cls, response, environ=None):
"""这个方法只有视图函数返回非字符、非元祖、非Response对象才会调用
:param response:
... | loingjuzy/learn-flask | Flask_T1.py | Flask_T1.py | py | 1,397 | python | en | code | 0 | github-code | 36 |
25667125459 | import os
import sys
import math
import socket
import random
import threading
from cv2 import aruco
from threading import Thread
from collections import namedtuple
from gps.Address import *
from gps.ServerThreadManager import *
from gps.SimulatorClient import... | AlexPirciu/BFMC | BFMC_GPS/gps/SimulatedGps.py | SimulatedGps.py | py | 4,156 | python | en | code | 0 | github-code | 36 |
72809319784 | from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union
import attr
from ..models.reference_type import ReferenceType
from ..types import UNSET, Unset
if TYPE_CHECKING:
from ..models.key import Key
T = TypeVar("T", bound="Reference")
@attr.s(auto_attribs=True)
class Reference:
"""
Att... | sdm4fzi/aas2openapi | ba-syx-submodel-repository-client/ba_syx_submodel_repository_client/models/reference.py | reference.py | py | 3,280 | python | en | code | 7 | github-code | 36 |
72515328423 |
import glob, os, sys
#sim_list = glob.glob('../*-*-*/Simulation/*/MD_R*.out')
lig_set = [x for x in os.listdir('../') if 'script' not in x]
print(f'\n\nThere are {len(lig_set)} IFD cases.\n\n')
#lig_set = list(set([x.split('/')[1] for x in sim_list]))
#print(lig_set)
total_sim = 0
total_failed_sim = 0
total_succ... | darrenjhsu/tiny_IFD | 01_Workflow/utilities/check_sims.py | check_sims.py | py | 1,869 | python | en | code | 12 | github-code | 36 |
16272104179 | import torch
import torch.nn.functional as F
# Focal Loss with alpha=0.25 and gamma=2 (standard)
class FocalLoss(torch.nn.Module):
def __init__(self, alpha=0.25, gamma=2):
super(FocalLoss, self).__init__()
self.alpha = alpha
self.gamma = gamma
def forward(self, pred, targets):
... | martinigoyanes/drugVQA | loss.py | loss.py | py | 2,477 | python | en | code | 0 | github-code | 36 |
35675762725 | """
*Kind*
Second kind.
In HTML, instances include element, class, ident, pseudo-class, pseudo-element.
Importantly, this allows the instantiation of custom XML types.
"""
from abc import ABCMeta
__all__ = ["Kind"]
class Kind:
__metaclass__ = ABCMeta
| jedhsu/text | text/_form/cascade/_kind/_kind.py | _kind.py | py | 274 | python | en | code | 0 | github-code | 36 |
4513078370 | import json
import random
words = []
unavailableWordIndices = set()
rejectedWordIndices = set()
with open("words.js", "r") as f:
s = f.read()
s = s[s.find("["):s.rfind(",")] + "]"
words = json.loads(s)
with open("history.json", "r") as f:
history = json.load(f)
for item in history:
index ... | mkacz91/slowle | picker.py | picker.py | py | 2,289 | python | en | code | 1 | github-code | 36 |
21417420352 | import pandas as pd
import numpy as np
import requests
from textblob import TextBlob as tb
from bs4 import BeautifulSoup as bs
from matplotlib import pyplot as plt
import time
import nltk
import re
from IPython.display import clear_output
import matplotlib.pyplot as plt
import seaborn as sns
stopwords = nltk.corpus.... | Ruksana-Kauser/NLP_Final_Project | reviews.py | reviews.py | py | 6,211 | python | en | code | 0 | github-code | 36 |
4578606765 | n,k = [int(x) for x in input().split()]
work = {} #work เก็บงานของอุปกรณ์
price = {} #price เก็บราคาของอุปกรณ์
sumprice = 0
for i in range(n):
data = [int(x) for x in input().split()]
work[i] =set([j-1 for j in range(1,k+1) if data[j] == 1])
price[i] = data[0]
sumprice += data[0]
check = set([i for i in... | naphattar/Betaprogramming | Chapter 1/1036.ver1.py | 1036.ver1.py | py | 934 | python | en | code | 0 | github-code | 36 |
34203757063 | import torch
import torch.nn as nn
from math import sin, cos
import models
from models.base import BaseModel
from models.utils import chunk_batch
from systems.utils import update_module_step
from nerfacc import ContractionType, OccupancyGrid, ray_marching
from nerfacc.vol_rendering import render_transmittance_from_alph... | 3dlg-hcvc/paris | models/se3.py | se3.py | py | 10,421 | python | en | code | 31 | github-code | 36 |
42632745572 | from setuptools import setup, find_packages
version = '0.1'
long_description = (
open('README.rst').read()
+ '\n' +
'Contributors\n'
'============\n'
+ '\n' +
open('CONTRIBUTORS.rst').read()
+ '\n' +
open('CHANGES.rst').read()
+ '\n')
setup(
name='imio.dms.ws',
version=ver... | IMIO/imio.dms.ws | setup.py | setup.py | py | 1,189 | python | en | code | 0 | github-code | 36 |
31059838395 | import ampalibe
from views import app_view
from ampalibe import Payload
from .base import chat, query
from response import BackAndMenuButton
from applicative.contre_vote import ContreVote
from applicative import Participant, Vote, Voter
@ampalibe.command("/vote")
def vote(sender_id, participant_id, **ext):
voter ... | iTeam-S/hiu-vote-bot | controllers/voting.py | voting.py | py | 8,636 | python | en | code | 7 | github-code | 36 |
18206090350 | from scrapy.selector import HtmlXPathSelector
from scrapy.contrib.spiders import CrawlSpider # Rule
from scrapy.http.request import Request
import html2text
import time
import re
import dateutil.parser
import datetime
import urlparse
from buzz_crawler.items import BuzzCrawlerItem
from markdown import markdown
class ... | claudehenchoz/z4 | buzz_crawler/buzz_crawler/spiders/woz_spider.py | woz_spider.py | py | 1,600 | python | en | code | 0 | github-code | 36 |
71845863784 | from django.http import HttpResponse
from django.template import loader
def index(request):
template = loader.get_template('pages/page_index.html')
context = {}
return HttpResponse(template.render(context, request))
def page(request):
template = loader.get_template('pages/page_display.html')
con... | craig-glass/epic_django | pages/views.py | views.py | py | 466 | python | en | code | 0 | github-code | 36 |
70434845545 | #coding = utf-8
#选择信息增益最大的10维特征
import numpy as np
from InfoGain import choose_best_feature
data_path = "C:\\Users\\TJM\\OneDrive\\graduated\\研①\\人工智能算法与实践\\homework\\分享\\Test\\1-kddcup.data_10_percent_corrected"
test_path = "C:\\Users\\TJM\\OneDrive\\graduated\\研①\\人工智能算法与实践\\homework\\分享\\Test\\3-corrected.txt... | JimmyTang178/ArtificialIntelligenceProject | data_process.py | data_process.py | py | 5,843 | python | en | code | 1 | github-code | 36 |
31805232109 | # /usr/bin/python3.6
# -*- coding:utf-8 -*-
# 超时
class Solution(object):
def minKBitFlips(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: int
"""
try:
old_index = A.index(0)
except:
return 0
length = len(A)
re... | bobcaoge/my-code | python/leetcode_bak/995_Minimum_Number_of_K_Consecutive_Bit_Flips.py | 995_Minimum_Number_of_K_Consecutive_Bit_Flips.py | py | 901 | python | en | code | 0 | github-code | 36 |
42194340126 | import datetime
import math
from sqlalchemy import desc, asc
from app.main import db
from app.main.model.unit import Unit
from app.main.service.language_helper import LanguageHelper
def save_unit(data, args):
errors = {}
language_data = LanguageHelper(args)
# Check unique field is null or not
if da... | viettiennguyen029/recommendation-system-api | app/main/service/unit_service.py | unit_service.py | py | 9,022 | python | en | code | 0 | github-code | 36 |
35153410551 | import torch
import torch.nn as nn
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(784, 256, bias = False)
self.bn1 = nn.BatchNorm1d(256)
self.relu1 = nn.ReLU()
self.fc2 = nn.Linear(256, 128)
self.bn2 = nn.BatchNorm1d... | Sachi-27/WiDS--Image-Captioning | Week 2/model.py | model.py | py | 649 | python | en | code | 0 | github-code | 36 |
18913307423 | class Solution:
def maxArea(self, height: list[int]) -> int:
left = 0
right = len(height) - 1
biggest_area = 0
while left < right:
left_bar = height[left]
right_bar = height[right]
current_area = min(left_bar, right_bar) * (right - left)
... | lancelote/leetcode | src/container_with_most_water.py | container_with_most_water.py | py | 508 | python | en | code | 3 | github-code | 36 |
40285478633 | # %%
import logging
import os.path
import shutil
import sys
from typing import Optional
import matplotlib.pyplot as plt
import pandas as pd
import pytorch_lightning as pl
import torch
import torch.nn.functional as F
import torchaudio
from icecream import ic
from torch.utils.data import Dataset, DataLoader
import matpl... | Stanvla/Thesis | hubert/clustering/torch_mffc_extract.py | torch_mffc_extract.py | py | 17,709 | python | en | code | 0 | github-code | 36 |
42493659115 | """
Helper function to safely convert an array to a new data type.
"""
from __future__ import absolute_import, print_function, division
import numpy as np
import theano
__docformat__ = "restructuredtext en"
def _asarray(a, dtype, order=None):
"""Convert the input to a Numpy array.
This function is almost ... | Theano/Theano | theano/misc/safe_asarray.py | safe_asarray.py | py | 2,384 | python | en | code | 9,807 | github-code | 36 |
11686617200 | import psutil
import time
import sys
# Nav : gzserver, move_base, amcl, robo state pub, rosout, mapsrv
# ObjTrack : gzserver, subscribr, objdetector, objtracker, controller
# Nav2D : stage, navigator, operator, mapper, rviz, joy, controller
cpu_util = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
mem_util = [0.0, 0.0, 0.0,... | aditi741997/robotics_project | measure_cpu.py | measure_cpu.py | py | 2,264 | python | en | code | 1 | github-code | 36 |
17643428428 | import argparse
import os
import torch
import torch.nn as nn
import torch.optim as optim
from tqdm import tqdm
from torchvision.utils import save_image
from torch.utils.data import Dataset, DataLoader
import albumentations
from albumentations.pytorch import ToTensorV2
from PIL import Image
import numpy as np
torch.bac... | ishon19/CSE676-FinalProject | Pix2Pix.py | Pix2Pix.py | py | 14,819 | python | en | code | 1 | github-code | 36 |
17849611547 | from ..config import np, Vector, DataName, MetaboliteConfig, ParameterName, LegendConfig
from ..metabolic_network_contents.metabolite import Metabolite
from ..metabolic_network_contents.reaction import Reaction
metabolite_width = MetaboliteConfig.width
class NormalLegendConfig(object):
metabolite_content_dict ... | LocasaleLab/Automated-MFA-2023 | figures/figure_plotting/figure_elements/metabolic_network/layout_generator_functions/legend_layout_generator.py | legend_layout_generator.py | py | 11,543 | python | en | code | 0 | github-code | 36 |
30326237829 | import sys
import time
from threading import Thread
class ProgressThread(Thread):
def __init__(self):
super(ProgressThread, self).__init__()
self.is_stop = False
self.cursor_index = 0
self.cursor_str = '|/-\\'
self.now = None
self.info = ""
def set_progress_inf... | Whale-lyi/simple-predict | progress.py | progress.py | py | 2,068 | python | en | code | 0 | github-code | 36 |
24938213556 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# filename: const.py
# modified: 2019-03-30
"""
常数表
"""
__all__ = [
"PROJECT_DIR",
"PACKAGE_DIR",
"CACHE_DIR",
"CONFIG_DIR",
"STATIC_DIR",
"LOG_DIR",
"INPUT_DIR",
"OUTPUT_DIR",
"OUTPUT_SRC_DIR",
"STYLE_CSS",
"CLIENT_DEFAULT_T... | pkuyouth/pkuyouth-html-coder | htmlcoder/core/const.py | const.py | py | 1,832 | python | en | code | 5 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.