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
4034762044
""" Utilities for point clouds. Code modified from Jiayuan Gu. """ import numpy as np def pad_or_clip(array: np.array, n: int, fill_value=0): """Pad or clip an array with constant values. It is usually used for sampling a fixed number of points. """ if array.shape[0] >= n: return array[:n] ...
hansongfang/CompNet
common_3d/utils/pc_utils.py
pc_utils.py
py
1,881
python
en
code
33
github-code
6
25050908902
import threading from threading import* import time #dictionary for storing key value data dict={} def create(key,value,timeout=0): if key in dict: print("error: this key already exists") else: if(key.isalpha()): #checking the size of file and JSON object ...
Akhileshpm/file-based-key-value-store
main.py
main.py
py
2,618
python
en
code
2
github-code
6
10423084443
from __future__ import annotations import dataclasses from typing import TYPE_CHECKING from unittest.mock import MagicMock, PropertyMock import pytest from randovania.exporter import pickup_exporter from randovania.game_description import default_database from randovania.game_description.assignment import PickupTarg...
randovania/randovania
test/games/dread/exporter/test_dread_patch_data_factory.py
test_dread_patch_data_factory.py
py
12,949
python
en
code
165
github-code
6
11816055102
import os import sys from threading import Thread case = [] for item in os.listdir(sys.argv[1]): if os.path.isdir(sys.argv[1] + '//' + item) and item != "banira_files": case.append(item) num = 0 if len(case) > 3: if len(case) % 3 == 0: num = len(case) // 3 else: num = len(case) // ...
cchenyixuan/Banira
utils/interpolation_runner.pyw
interpolation_runner.pyw
pyw
1,685
python
en
code
0
github-code
6
37616517604
from time import sleep from signal import pause from gpiozero import LED from gpiozero import Button from pygame import mixer mixer.init() placeholder = mixer.Sound('placeholder.wav') ph_len = placeholder.get_length() led = LED(25) btn = Button(4) while True: btn.wait_for_press() print("Initialized") b...
Aahil52/animatronics2022
testscripts/soundandlightstest.py
soundandlightstest.py
py
516
python
en
code
0
github-code
6
30023024204
import os import glob import numpy as np from scipy.stats import norm import json class WarpedSpace: # takes a prior as a dict and returns a scipy normal distribution @staticmethod def create_distribution(prior): means = [] stds = [] ranges = [] for key in sorted(prior...
piboauthors/PiBO-Spearmint
spearmint/warping.py
warping.py
py
3,633
python
en
code
0
github-code
6
50818241
# # @lc app=leetcode.cn id=754 lang=python3 # # [754] 到达终点数字 # # @lc code=start class Solution: def reachNumber(self, target: int) -> int: # due to symmetry target = abs(target) x = count = 0 def dfs(x, target, count): # base case if x > target: ...
code-cp/leetcode
solutions/754/754.到达终点数字.py
754.到达终点数字.py
py
623
python
en
code
0
github-code
6
13160016876
from django.shortcuts import render from subscribers.models import subscriberForm from subscribe.settings import EMAIL_HOST_USER from django.core.mail import send_mail,BadHeaderError # Create your views here. def index(request): form=subscriberForm() return render(request,"index.html",{"form":form}) ...
pawankushwah850/Emailsubscriber
subscribers/views.py
views.py
py
1,862
python
en
code
1
github-code
6
40369313075
while True: try: # 1. Преобразование введённой последовательности в список spisok = [int(c) for c in input('Введите последовательность чисел через пробел: ').split()] except ValueError: print("Это неправильный ввод! Введите данные согласно условий ввода!") else: break while T...
sigmaclap/PythonTasks
17.9.1/17.9.py
17.9.py
py
2,120
python
ru
code
0
github-code
6
13750197452
from abc import ABC, abstractmethod class Notification(ABC): def __init__(self, msg) -> None: self.msg = msg @abstractmethod def send(self) -> bool: ... class EmailNotification(Notification): def send(self) -> bool: print(f'Enviando e-mail de notificação... {self.msg}') retu...
daugbit/Cursos
Python_3_Udemy/ex029_polimorfismo.py
ex029_polimorfismo.py
py
859
python
pt
code
0
github-code
6
23156107935
from flask import Flask from main import main from mypage import mypage from challengedetail import challengedetail from flask import Flask, render_template, jsonify, request, session, redirect, url_for from db import db app = Flask(__name__) # JWT 토큰을 만들 때 필요한 비밀문자열입니다. 아무거나 입력해도 괜찮습니다. # 이 문자열은 서버만 알고있기 때문에, 내 서버에서...
cchloe0927/Mallenge
app.py
app.py
py
6,984
python
ko
code
2
github-code
6
25969778046
import requests from bs4 import BeautifulSoup import pandas as pd #程式欢迎语 print("**欢迎来到UCAR爬虫程式**") print("\n") #将资料存入建立好的list titles = [] date = [] url_list = [] clicks =[] replys = [] #自定义查询关键字及日期区间 x = str(input("请输入想爬取的关键字:")) print("日期格式输入范例(YYYYMMDD):20200715") print("\n") start_date = int(input("请输入想爬取的起始日期:"...
weiweibro87777/UCAR_web-crawler
ucar.py
ucar.py
py
3,533
python
zh
code
1
github-code
6
9002196810
from ast import parse import pathlib import configparser import shutil import enum from sre_constants import CATEGORY output = pathlib.Path("./.out") shutil.rmtree(output, ignore_errors=True) output.mkdir(exist_ok=True) book_counter = 0 cfg = configparser.ConfigParser() cfg.read(".input.ini", encoding="utf-8") wit...
diraven/zomegen
books/__main__.py
__main__.py
py
1,440
python
en
code
0
github-code
6
9658653690
import matplotlib.pyplot as plt import scipy.signal as ss import numpy as np import math window_size = 55 '------------------------------------------------------------------------------' # opis: oblicza i zwraca pochodna sygnalu. # nazwa funkcji: FUNC_diff # parametry: # ecg_filtered - numpy 1D array #...
sebastianczuma/r_peaks
R_PEAKS_old.py
R_PEAKS_old.py
py
9,657
python
en
code
1
github-code
6
71082529147
from classes.rayon import * from processing.analysis import intersect def rayon_direct(start_point,end_point, murs): #renvoie le rayon direct (dans une liste) list_rayon = [] nouveau_rayon = Rayon(start_point) nouveau_rayon.add_point_principal(end_point) nouveau_rayon.find...
bjoukovs/PHYSRayTracing2017
processing/direct.py
direct.py
py
445
python
en
code
0
github-code
6
13415300522
# -*- coding: utf-8 -*- """ @author: Taoting 将用coco格式的json转化成labeime标注格式的json """ import json import cv2 import numpy as np import os #用一个labelme格式的json作为参考,因为很多信息都是相同的,不需要修改。 def reference_labelme_json(): ref_json_path = './bin/25.json' data=json.load(open(ref_json_path)) return data def labe...
Tommy-Bie/Logistics-Package-Separation-Software
DatasetUtils/coco2labelme.py
coco2labelme.py
py
2,887
python
en
code
1
github-code
6
5782054342
from django.contrib import admin from .models import Listing # change Register your models data's list views attribite. class ListingAdmin(admin.ModelAdmin): list_display = ('id', 'title', 'is_published', 'price', 'list_date', 'realtor') # display items list_display_links = ('id', 'title', 'realtor') #clic...
MonadWizard/django_HouseSellRealEstate_project
listings/admin.py
admin.py
py
671
python
en
code
3
github-code
6
5073225844
import urllib, urllib.request from datetime import datetime def get_data(province_id): # Отримання тестових даних із WEB-сторінки url = 'https://www.star.nesdis.noaa.gov/smcd/emb/vci/VH/get_TS_admin.php?country=UKR&provinceID={}&year1=1981&year2=2020&type=Mean'.format(province_id) # Відкриття WEB-сторінки м...
DJeik7/lab2
Ad1.py
Ad1.py
py
1,504
python
uk
code
0
github-code
6
70879486268
from enum import Enum class Color(Enum): WHITE = True BLACK = False class Direction(Enum): EAST = "e" SOUTH_EAST = "se" SOUTH_WEST = "sw" WEST = "w" NORTH_WEST = "nw" NORTH_EAST = "ne" class Coordinate: # Using axial coordinates # https://www.redblobgames.com/grids/hexagons...
cj81499/advent-of-code
src/aoc_cj/aoc2020/day24.py
day24.py
py
4,291
python
en
code
2
github-code
6
20651798683
import math import random import numpy as np from itertools import combinations from copy import deepcopy class Node: def __init__(self): self.parent = None self.state = [] self.children = [] self.fully_expanded = False self.Q = 0 self.N = 0 def...
shaido987/riskloc
algorithms/hotspot.py
hotspot.py
py
8,100
python
en
code
93
github-code
6
37175527133
from jd.api.base import RestApi class ComJdStockShopGlobalWebOpenWarehouseFacadeAddStoreRequest(RestApi): def __init__(self,domain,port=80): """ """ RestApi.__init__(self,domain, port) self.storeName = None self.remark = None self.venderId = None self.storeId = None def getapiname(self): r...
PsKs/jd-sdk
jd/api/rest/ComJdStockShopGlobalWebOpenWarehouseFacadeAddStoreRequest.py
ComJdStockShopGlobalWebOpenWarehouseFacadeAddStoreRequest.py
py
405
python
en
code
1
github-code
6
22093759735
import pandas as pd from sklearn import svm import statistics data = pd.read_csv('cleaned_LaptopDataset.csv') t = statistics.median(data['latest_price']) h = [] from sklearn import preprocessing le = preprocessing.LabelEncoder() for x in data.latest_price: if (x >= t): h.append(1...
mohamedezzeldeenhassanmohamed/Data-Mining-Project
svm.py
svm.py
py
1,007
python
en
code
0
github-code
6
720316267
# BFD - Bidirectional Forwarding Detection - RFC 5880, 5881 # scapy.contrib.description = BFD # scapy.contrib.status = loads from scapy.packet import * from scapy.fields import * from scapy.all import * # Otherwise failing at the UDP reference below class BFD(Packet): name = "BFD" fields_desc = [ ...
p4lang/scapy-vxlan
scapy/contrib/bfd.py
bfd.py
py
1,129
python
en
code
33
github-code
6
31472363916
# Code adapted from https://www.codeproject.com/Articles/5297227/Deep-Learning-for-Fashion-Classification # import tensorflow.keras as keras import os import matplotlib.pyplot as plt import matplotlib.image as img import tensorflow as tf import keras import numpy as np from keras.preprocessing.image import ImageDataGe...
nnanna217/msc-image-search
func/my_samples/cp_fashion-classifier.py
cp_fashion-classifier.py
py
4,162
python
en
code
0
github-code
6
10713768489
from scipy import stats, signal from collections import defaultdict import numpy as np from tqdm.notebook import tqdm import pandas as pd from src import config from src.FFT import FFTAnalysis as FFT def _extractTimeDomainFeatures(sig): ''' Extracts time domain features from one vibration signal''' # Get ti...
Miltos-90/Bearing_Fault_Classification
src/feature_extraction.py
feature_extraction.py
py
4,432
python
en
code
0
github-code
6
34668621923
from django.urls import path from django.conf.urls import url from . import views app_name = 'choistick' urlpatterns = [ path('', views.index, name='index'), path('map/', views.map, name='map'), path('join/', views.signup, name='join'), path('pick/', views.pick, name='pick'), path('warn/', views.warn, name='warn...
jaemin8852/Search_Location
choistick/urls.py
urls.py
py
421
python
en
code
0
github-code
6
13300386404
#!/usr/bin/python3 import _thread import re, time, cv2, serial ''' ServoController interfaces with the arduino board to control the servo motor over USB serial coms ''' class ServoController: def __init__(self): self.ser = serial.Serial('com3', 9600, timeout=0.5) def __enter__(s...
bradys/cat-cam
Cat_Cam.py
Cat_Cam.py
py
6,213
python
en
code
0
github-code
6
21806540252
from jetracer.nvidia_racecar import NvidiaRacecar import time import sys from multiprocessing import Process, Value import zmq import Jetson.GPIO as GPIO pinrun = 'DAP4_SCLK' #12 pinbouton = 'SPI2_SCK' #13 pinau = 'SPI2_CS1' #16 autrepin = 'SPI2_CS0' #18 GPIO.setmode(GPIO.TEGRA_SOC) GPIO.setup(pinrun, GPIO.OUT) GPIO...
SpaceLabsfr/BlockApp
serveur-blockapp.py
serveur-blockapp.py
py
2,553
python
en
code
0
github-code
6
40678810913
import argparse import json import os import platform import subprocess from typing import List HOST_MAGMA_ROOT = '../../../.' def main() -> None: """ Run main""" args = _parse_args() if args.mount: _run(['up', '-d', 'test']) _run(['exec', 'test', 'bash']) _down(args) elif a...
magma/magma
feg/gateway/docker/build.py
build.py
py
4,696
python
en
code
1,605
github-code
6
27213803395
def solution(n, words): word_set = {words[0]} n_cnt = [0] * (n + 1) n_cnt[1] += 1 for i in range(1, len(words)): num = i % n + 1 if words[i][0] != words[i - 1][-1] or words[i] in word_set: return [num, n_cnt[num] + 1] else: word_set.add(words[i]) ...
hammii/Algorithm
Programmers_python/영어_끝말잇기.py
영어_끝말잇기.py
py
360
python
en
code
2
github-code
6
34861772057
from statuspage.forms import StatusPageModelForm from utilities.forms import StaticSelect from ..models import UptimeRobotMonitor __all__ = ( 'UptimeRobotMonitorForm', ) class UptimeRobotMonitorForm(StatusPageModelForm): fieldsets = ( ('UptimeRobot Monitor', ( 'component', 'metric', 'paus...
Status-Page/Status-Page
statuspage/sp_uptimerobot/forms/models.py
models.py
py
578
python
en
code
45
github-code
6
5308571260
n, c = map(int, input().split()) location = [] for _ in range(n): location.append(int(input())) location.sort() # gap 최소값 start = location[1]-location[0] # gap 최대값 end = location[-1] - location[0] result = 0 while (start <= end): # gap의 중간 값 mid = (start + end) // 2 value = location[0] cnt = 1 ...
louisuss/Algorithms-Code-Upload
Python/DongbinBook/binary_search/find_router.py
find_router.py
py
810
python
ko
code
0
github-code
6
36076011155
# -*- coding: utf-8 -*- from flask import Flask, render_template, request,jsonify, redirect,url_for from json import dumps import celery , sys from celeryconfig import appcelery from Buscador import tasks import time, json app = Flask(__name__) @app.route('/datos', methods=['GET', 'POST']) def recibirInformacion(): ...
AntonioAlcM/tfg_ugr
backend/tratamientoDatos.py
tratamientoDatos.py
py
2,620
python
pt
code
1
github-code
6
44633342253
from typing import List from torch import optim from torch.optim.optimizer import Optimizer from torch_geometric.data.data import Data from src.dataset import citeSeer from src.model import GAT import torch import torch.nn.functional as F from torch_geometric.data import Dataset EPOCH = 200 # --- da...
February24-Lee/gnn_research
test_gat_exmaple.py
test_gat_exmaple.py
py
1,645
python
en
code
0
github-code
6
18732949012
import json import numpy as np import util class AudfprintAligner: matches = {} def __init__(self, matchfile): with open(matchfile) as f: for x, ys in json.load(f).iteritems(): for y, m in ys.iteritems(): m = m[0] if "Matched" in m: ...
grateful-dead-live/meta-alignment
audfprint_aligner.py
audfprint_aligner.py
py
1,407
python
en
code
0
github-code
6
24150609056
import requests import random from utils.others import get_atitle, get_genre, get_t_from_u, get_urls from utils.anilist import Anilist from utils.techzapi import TechZApi def get_genre_html(li): x = """<a>{}</a>""" html = "" for i in li: html += x.format(i.strip()) return html def get_eps_...
TechShreyash/AnimeDex
utils/html_gen.py
html_gen.py
py
10,463
python
en
code
186
github-code
6
5991002670
from collections import OrderedDict from itertools import chain from .types import Vsn, MatrixID, PacketClass from .patches import patch from .cache import from_page, get_page from .sources import version_urls from .parsers import pre_versions, pre_packets, rel_version, rel_packets from .parsers import first_heading ...
joodicator/mc-dev-data
mcdevdata/matrix.py
matrix.py
py
7,498
python
en
code
1
github-code
6
34161150799
from ninjaopenfoam import Case, Gnuplot, GmtPlot, GmtPlotCopyCase, PDFLaTeXFigure import os class SchaerWaves: def __init__(self): self.linearUpwindW() self.cubicFitW() self.charneyPhillipsW() def linearUpwindW(self): self.btf300dzLinearUpwind = GmtPlotCopyCase( ...
hertzsprung/thesis
generators/schaerWaves.py
schaerWaves.py
py
3,873
python
en
code
0
github-code
6
73526486907
import os.path import pandas as pd def loadEgPed(): '''Load example pedigree data. ''' basepath = os.path.abspath(__file__) folder = os.path.dirname(basepath) data_path = os.path.join(folder, 'data/ped.txt') text = pd.read_table(data_path,header=0) return text def loadEgGeno(): '''Load...
zhaow-01/PyAGH
PyAGH/loaddata.py
loaddata.py
py
512
python
en
code
4
github-code
6
74281107067
from typing import Any, List from fastapi import APIRouter, HTTPException, Depends from apps.auth.model import User from apps.bank.cruds import invoice from apps.bank.schemas.invoice import InvoiceUpdate, InvoiceView, InvoiceCreate, InvoiceViewFull from core.security import current_user_is_banker, get_current_user r...
MojsaKirill/CRUD
app/api/api_v1/endpoints/invoices.py
invoices.py
py
2,101
python
en
code
0
github-code
6
73084758907
import pandas as pd # import requests import sys import collections # import urllib.request import json # url = 'http://loterias.caixa.gov.br/wps/portal/loterias/landing/lotofacil/!ut/p/a1/04_Sj9CPykssy0xPLMnMz0vMAfGjzOLNDH0MPAzcDbz8vTxNDRy9_Y2NQ13CDA0sTIEKIoEKnN0dPUzMfQwMDEwsjAw8XZw8XMwtfQ0MPM2I02-AAzgaENIfrh-FqsQ9w...
daklima/bootcamp-engdados-oct22
A001/main.py
main.py
py
3,954
python
en
code
0
github-code
6
26596833071
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ # Import libraries import matplotlib.pyplot as plt import matplotlib.animation as animate import matplotlib.lines as mlines import agentframework import csv # Request input from user for number of heroes and enemies print("Welcome to the h...
emilyjcoups/Agent_Based_Model
model.py
model.py
py
5,535
python
en
code
0
github-code
6
16986332004
import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator from numpy.lib.shape_base import split import math import cmath def get_MSI (matrix, f, tau, iterCnt): #method of simple iterations n = np.size(f) B = np.diagflat([1] * n) - tau * matrix ...
Nevtod/Labs
ComputingMath/lab1/Computing_math.py
Computing_math.py
py
3,874
python
en
code
0
github-code
6
650459657
#! /bin/python import os import sys import json import luigi import nifty.tools as nt import elf.skeleton.io as skelio from elf.skeleton import skeletonize as skel_impl, get_method_names import cluster_tools.utils.volume_utils as vu import cluster_tools.utils.function_utils as fu from cluster_tools.cluster_tasks im...
constantinpape/cluster_tools
cluster_tools/skeletons/skeletonize.py
skeletonize.py
py
7,301
python
en
code
32
github-code
6
35632930544
""" ID: detrime1 LANG: PYTHON3 TASK: friday """ import sys,os.path from collections import * if os.path.exists('friday.in'): sys.stdin = open('friday.in', 'r') sys.stdout = open('friday.out', 'w') def detri(): n = int(input()) weekDays = [0]*7 monthDays = [31,28,31,30,31,30,31,31,30,31,30,31] day = 2 for...
llxSKyWALKeRxll/USACO_Training
Chapter 1/Friday The Thirteenth/friday.py
friday.py
py
1,458
python
en
code
0
github-code
6
37169471952
from flask import request from flask_restx import Resource from ..service.auth_service import Auth from ..util.decorator import admin_token_required from ..service.user_service import save_new_user, get_a_user from ..util.dto import AuthDto api = AuthDto.api user_auth = AuthDto.user_auth user_token = AuthDto.user_tok...
miteshnath/flask-admin-jwt
app/main/controller/auth_controller.py
auth_controller.py
py
2,367
python
en
code
1
github-code
6
70835853948
import csv import argparse import os import sys import numpy as np import torch import torch.cuda from PIL import Image from torch.autograd import Variable from torchvision.transforms import transforms from my.yolov3.easy.net.load_net import load_net from PIL import Image image_size = (96, 96) test_transformations...
NJUCoders/commodity-classification-hard
easy/predict.py
predict.py
py
1,931
python
en
code
0
github-code
6
20044628025
houses = [[3,7],[1,9],[2,0],[5,15],[4,30]] # houses = [[1,2],[2,3],[3,1],[4,20]] d = {} for i in houses: d[i[0]] = i[1] SortedDict = {k: v for k, v in sorted(d.items(), key=lambda item: item[1])} print(SortedDict) fList = [] finalList = [] for j in SortedDict: fList.append(j) print(fList) finalList = fList[-2:...
Elevenv/Placement-Stuff
house.py
house.py
py
418
python
en
code
1
github-code
6
811036516
'''Process Restricted Friend Requests https://leetcode.com/problems/process-restricted-friend-requests/ You are given an integer n indicating the number of people in a network. Each person is labeled from 0 to n - 1. You are also given a 0-indexed 2D integer array restrictions, where restrictions[i] = [xi, yi] means ...
Saima-Chaity/Leetcode
Graph/Process Restricted Friend Requests.py
Process Restricted Friend Requests.py
py
2,945
python
en
code
0
github-code
6
36255805376
import boto3 import json import os dynamodb = boto3.resource('dynamodb') client = boto3.client('dynamodb') USERS_TABLE = dynamodb.Table(os.environ['USERS_TABLE']) def delete_user_service(event, context): try: response = USERS_TABLE.update_item( Key={ 'userId': event['pathParam...
Glendid/glendid-app-users
src/services/DeleteUser.py
DeleteUser.py
py
875
python
en
code
0
github-code
6
4388139380
# -*- coding: utf-8 -*- #------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Conector para blip.tv # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ import re import urllib try: from core import scrapertoo...
TuxRneR/pelisalacarta-personal-fork
tags/xbmc-addons/plugin.video.pelisalacarta/servers/bliptv.py
bliptv.py
py
1,763
python
en
code
0
github-code
6
17007776735
import requests import bs4 import urllib def spider(max_pages): for page in range(1, max_pages + 1): query = urllib.parse.urlencode({'query':u'대선후보'}) url = 'http://news.naver.com/main/search/search.nhn?query=' + '%B4%EB%BC%B1%C8%C4%BA%B8' source_code = requests.get(url) plain_text ...
masonHong/INU-Study
C Team(Hong, Heo)/Crowaling/Practice 1.py
Practice 1.py
py
668
python
en
code
0
github-code
6
72112922749
import numpy as np import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.nn.functional as F # import snntorch import pandas as pd import tqdm import argparse from . import p_snu_layer class SNN_Net(torch.nn.Module): def __init__(self, inputs_num = 4, hidden_num = 4, outputs_num = 3 ,l_tau...
GTAKAGI/PSNN
snn_model/network.py
network.py
py
3,693
python
en
code
0
github-code
6
71271557629
class Solution: def findMaxForm(self, strs: List[str], m: int, n: int) -> int: dp = [[0] * (n+1) for _ in range(m+1)] counter=[[s.count("0"), s.count("1")] for s in strs] for zeroes, ones in counter: for i in range(m, zeroes-1, -1): for j in range(n, ones...
anubhavsrivastava10/Leetcode-HackerEarth-Solution
Leetcode/May 2022/23)474. Ones and Zeroes.py
23)474. Ones and Zeroes.py
py
451
python
en
code
9
github-code
6
27390116761
# 2SUM # http://rosalind.info/problems/2sum/ from utilities import get_file, get_answer_file def two_sum(num_array): minus_set = set(-i for i in num_array) for i, value in enumerate(num_array): if value in minus_set: try: j = num_array.index(-value, i+1) except ...
Delta-Life/Bioinformatics
Rosalind/Algorithmic Heights/code/2SUM.py
2SUM.py
py
761
python
en
code
0
github-code
6
11547913275
# This file is part of RADAR. # Copyright (C) 2019 Cole Daubenspeck # # RADAR is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later versio...
Sevaarcen/RADAR
cyber_radar/helpers/target_prioritizer.py
target_prioritizer.py
py
4,715
python
en
code
2
github-code
6
23468677797
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('tapp', '0005_comment_end_i'), ] operations = [ migrations.AlterModelOptions( name='essay', options={...
rihakd/textAnalyticsDjango
TA/tapp/migrations/0006_auto_20151119_1941.py
0006_auto_20151119_1941.py
py
386
python
en
code
0
github-code
6
26225231093
s = open('Day14.txt').read() def twist(a, n): return a[:n][::-1] + a[n:] def skip(a, k): return a[k:] + a[:k] def knot(a, x): p = k = 0 for i in x: a = skip(twist(skip(a, p), i), -p) p = (p + i + k) % len(a) k += 1 return a def densehash(a): return list(map( ...
pirsquared/Advent-of-Code
2017/Day14.py
Day14.py
py
1,621
python
en
code
1
github-code
6
73549612348
import pandas as pd import numpy as np import io import requests from sklearn.tree import DecisionTreeClassifier from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier from sklearn.neural_network import MLPClassifier from sklearn.preprocessing...
aslakey/CBM_Encoding
lead_scoring_computation_time.py
lead_scoring_computation_time.py
py
3,159
python
en
code
18
github-code
6
75132007548
from sklearn.datasets import load_boston from sklearn.model_selection import train_test_split # model_selection模型选择过程中各种数据分割的类与函数 from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LinearRegression, SGDRegressor, LogisticRegression # 线性回归 # externals是外部的、外部扩展的意思 fr...
hahahei957/NewProject_Opencv2
机器学习/19_线性回归.py
19_线性回归.py
py
5,679
python
zh
code
0
github-code
6
8694936867
from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("newListing", views.newForm, name="new"), ...
SHorne41/Project-2-Commerce
auctions/urls.py
urls.py
py
1,046
python
en
code
0
github-code
6
35379120975
import math import boto3 from aws_cdk import ( core, aws_ec2 as ec2, aws_ecs as ecs, aws_cloudwatch as cw ) from cdklocust.locust_container import locustContainer class CdklocustStack(core.Stack): def __init__(self, scope: core.Construct, id: str, vpc, **kwargs) -> None: super().__ini...
tynooo/cdklocust
cdklocust/cdklocust_stack.py
cdklocust_stack.py
py
3,687
python
en
code
3
github-code
6
26345256198
n = map(float, input().split(' ')) counts = {} for x in n: if x in counts: counts[x] += 1 else: counts[x] = 1 for x in sorted(counts): print("{} -> {} times".format(x, counts[x]))
YovchoGandjurov/Python-Fundamentals
02. Lists and Dictionaries/Dictionaries/02.Count_Real_Numbers.py
02.Count_Real_Numbers.py
py
211
python
en
code
1
github-code
6
9487674486
# -*- coding: utf-8 -*- import nengo import numpy as np from nengo_ssp.vector_generation import HexagonalBasis, GridCellEncoders #from nengo_ssp.utils import ssp_vectorized class PathIntegrator(nengo.Network): def __init__(self, n_neurons, n_gridcells, scale_fac=1.0, basis=None,xy_rad=10, **kwargs): kw...
nsdumont/nengo_ssp
nengo_ssp/networks.py
networks.py
py
5,032
python
en
code
0
github-code
6
10422637903
from __future__ import annotations import dataclasses from typing import TYPE_CHECKING from randovania.bitpacking import bitpacking from randovania.bitpacking.bitpacking import BitPackDecoder, BitPackValue from randovania.game_description import default_database if TYPE_CHECKING: from collections.abc import Iter...
randovania/randovania
randovania/layout/base/ammo_pickup_state.py
ammo_pickup_state.py
py
3,973
python
en
code
165
github-code
6
10294402912
#-*-python-*- from warn import * from Rnaseq import * from Rnaseq.command import * from sqlalchemy import * from sqlalchemy.orm import mapper, sessionmaker # usage: provenance load <readset pipeline> # This is sort of a test command, probably won't be used in production class Load(Command): def description(self)...
phonybone/Rnaseq
lib/Rnaseq/cmds/rnaseq/load.py
load.py
py
1,138
python
en
code
3
github-code
6
8352755533
from __future__ import absolute_import, unicode_literals import base64 import json import random import warnings import websocket from c8 import constants from c8.api import APIWrapper from c8.apikeys import APIKeys from c8.c8ql import C8QL from c8.collection import StandardCollection from c8.exceptions import ( ...
Macrometacorp/pyC8
c8/fabric.py
fabric.py
py
56,104
python
en
code
6
github-code
6
33215300998
# # @lc app=leetcode.cn id=15 lang=python3 # # [15] 三数之和 # # @lc code=start class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: result = [] n = len(nums) nums.sort() for i, first in enumerate(nums): if i > 0 and first == nums[i - 1]: ...
P4Peemo/Leetcode
15.三数之和.py
15.三数之和.py
py
807
python
en
code
0
github-code
6
8600407692
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from .routers import post, user, auth, vote ############################################ #models.Base.metadata.create_all(bind=engine) app = FastAPI() origins = ["*"] app.add_middleware( CORSMiddleware, allow_origins=origins, ...
Mattia921/example-fastapi
app/main.py
main.py
py
1,524
python
en
code
0
github-code
6
18849850963
import os import random import math import seaborn import matplotlib.pyplot as plt num_train_samples = 1 threshold = 0.25 dtw_window = 50 # thresholds: 0.15, 0.2, ... def read_gesture(path): with open(path, "r") as file: lines = [line.rstrip() for line in file] gesture = [[float(value) for value...
xrgman/ColorMatchingBracelet
arduino/GestureRecorder/evaluate.py
evaluate.py
py
5,392
python
en
code
2
github-code
6
2055718392
# USAGE # python knn.py --dataset ../../SolutionDL4CV/SB_code/datasets/animals from sklearn.neighbors import KNeighborsClassifier from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report from pyimagesearch.preprocessing import ...
lykhahaha/Mine
StarterBundle/chapter07-first_image_classifier/knn.py
knn.py
py
1,583
python
en
code
0
github-code
6
4709876834
import numpy as np import matplotlib.pyplot as plt import activation_functions as acfunc inp_a = np.arange(-1.0, 1.0, 0.2) inp_b = np.arange(-1.0, 1.0, 0.2) outputs = np.zeros((10, 10)) weight_a = 2.5 weight_b = 3 bias = 0.1 for i in range(10): for j in range(10): u_single = inp_a[i] * weight_a + inp_b...
tsubamon55/pyailesson
single_neuron.py
single_neuron.py
py
471
python
en
code
0
github-code
6
14478011852
''' Loss functions. ''' import copy import torch import torch.nn as nn from torch.autograd import Variable import numpy as np import utils class NLLLoss(nn.Module): """Self-Defined NLLLoss Function Args: weight: Tensor (num_class, ) """ def __init__(self, weight): super(NLLLoss, se...
TalkToTheGAN/REGAN
loss.py
loss.py
py
5,235
python
en
code
42
github-code
6
8310998664
def makeForms(verb): character = ('o', 'ch', 's', 'sh', 'x', 'z') if verb.endswith("y"): new = verb[:-1] + "ies" elif verb.endswith(character): new = verb + "es" else: new = verb + "s" return new def main(): verb = input("Enter your word: ") print("The ...
angelinekaren/Programming-Exercises
Exercise 4/answer12/main.py
main.py
py
378
python
en
code
0
github-code
6
71994815868
"""Control implementation for assignment 1. The controller used the simulation in file `aer1216_fall2020_hw1_sim.py`. Example ------- To run the simulation, type in a terminal: $ python aer1216_fall2020_hw1_sim.py Notes ----- Tune the PD coefficients in `HW1Control.__init__()`. """ import numpy as np from gym_...
kaustubhsridhar/Constrained_Models
Drones/gym-pybullet-drones/assignments/aer1216_fall2020_hw1_ctrl.py
aer1216_fall2020_hw1_ctrl.py
py
5,709
python
de
code
15
github-code
6
71570292029
from django import forms from django.core.exceptions import ValidationError from semester.models import Semester, CourseOffered, CourseDistribution, DistributedSectionDetail from tempus_dominus.widgets import TimePicker, DatePicker from django.contrib import messages from django.shortcuts import redirect class Semest...
Emad-ahmed/luRoutine
semester/forms.py
forms.py
py
4,085
python
en
code
0
github-code
6
40182196672
from anomaly_detection import Amean from multiprocessing import Process, Queue from database import DataBase from datetime import datetime, timedelta import time import traceback class AnomalyDomain (Process): # initilize data def __init__(self, name, host) : super(AnomalyDomain, self).__init__(...
DUCQUAN7850/warning_service_master
warning_service-master/anomaly_domain.py
anomaly_domain.py
py
4,642
python
en
code
0
github-code
6
42174278814
# import transformers # import datasets # from pprint import pprint # # with pipeline # model = transformers.AutoModelForSequenceClassification.from_pretrained("") # load model from local directory # tokenizer = transformers.AutoTokenizer.from_pretrained("TurkuNLP/bert-base-finnish-cased-v1") # test_pipe = transfo...
TurkuNLP/register-qa
predict.py
predict.py
py
4,037
python
en
code
0
github-code
6
36920706174
#------------------------------------------------------------------------- # Script en python que se encarga de conectarse a un recurso Event Hub de # Microsoft Azure y leer todos los mensajes disponibles, al mismo tiempo # que deja un checkpoint de lo que ha leído para no repetir mensajes # la siguiente vez que ...
NoeCampos22/Ejercicio_Azure_Databricks
Mini-Ejercicios/1_Enviar_Recibir_Eventos_EventHub/EPH.py
EPH.py
py
5,351
python
es
code
0
github-code
6
2500816506
from bokeh.layouts import column from bokeh.models.widgets import RadioButtonGroup,Select, Div, Button,PreText from bokeh.models import TextInput, RadioGroup from bokeh.plotting import curdoc button_group = RadioButtonGroup(labels=["Physical parameters", "Geometric parameters", "Initial conditions"], active=1) ## A...
sduarte09/Module5
Exercise/Group5/BWC.py
BWC.py
py
2,455
python
en
code
0
github-code
6
39688374544
# Time: O(n) # Space: O(1) class Solution: def rob(self, nums: List[int]) -> int: """ """ if not nums: return 0 if len(nums)==1: return nums[0] return max(self.util(nums[:-1]), self.util(nums[1:])) def util(self, nums): # Linear Space ...
cmattey/leetcode_problems
Python/lc_213_house_robber_ii.py
lc_213_house_robber_ii.py
py
704
python
en
code
4
github-code
6
38453788242
import sys input = sys.stdin.readline T = int(input()) for tc in range(1,T+1): L = list(map(int,input().split())) L.sort() a,b,c = L ans = "NO" if a**2 + b**2 == c**2: ans = "YES" print(f"Case #{tc}: {ans}")
LightPotato99/baekjoon
math/geometry/triangle/pythagoras/rightTri.py
rightTri.py
py
240
python
en
code
0
github-code
6
17137130653
import requests import re from bs4 import BeautifulSoup from openpyxl import load_workbook DIRECTORY_URL = "https://directory.tufts.edu/searchresults.cgi" WORKBOOK_NAME = "DirectoryResults_2017-2018.xlsx" NAME_SHEET = "DirectoryResults" # This script works on Excel Sheets with a single column in the A column of # a ...
jGowgiel/fec-donation-aggregator
scripts/DirectoryScrape.py
DirectoryScrape.py
py
1,261
python
en
code
0
github-code
6
24502646621
from utils import * from fastapi import FastAPI, Query, Path, Body, Cookie, Header from pydantic import BaseModel, Required, Field, HttpUrl app = FastAPI() @app.get('/') def read_root(): return {'Hello': 'World'} # Examplos com path params class ModelName(str, Enum): name1 = 'Phelipe' name2 = 'Marcos...
williamelias/Fast-Api-Quiz
code/app/main.py
main.py
py
5,446
python
pt
code
0
github-code
6
27456097150
from pathlib import Path from sphinx.directives import SphinxDirective from docutils.parsers.rst import directives from docutils import nodes from sphinx.util.logging import getLogger import yaml import json logger = getLogger(__name__) class PyConfig(SphinxDirective): has_content = True def run(self): ...
yoblee/docs
sphext/sphinx_pyscript/pys_directives/__init__.py
__init__.py
py
2,360
python
en
code
0
github-code
6
41774127803
import hearts.model.game as m from hearts.game_master import GameMaster import logging class GameBackend(object): def __init__(self, player_svc): self._next_game_id = 1 self._game_masters = {} self._players = {} self._player_mapping = {} self._player_svc = player_svc ...
MHeasell/hearts-server
hearts/game_backend.py
game_backend.py
py
1,880
python
en
code
0
github-code
6
31329871933
#%% import pandas as pd import numpy as np import datetime as dt import xarray as xr import cftime import dask from glob import glob #%% '''SUBSET RH DATA''' data = pd.read_csv("preprocessing/inputdata/AMF_US-MBP_BASE_HH_2-5.csv", skiprows = 2, na_values = -9999) data['TIMESTAMP_START'] = ...
mwdjones/clm_frost
preprocessing/forcings/Add_RH_to_Forcings.py
Add_RH_to_Forcings.py
py
3,217
python
en
code
0
github-code
6
8898957294
import telebot import config from ibm_watson import LanguageTranslatorV3 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator import json from telebot import types import pyowm owm = pyowm.OWM('c8548689b28b1916f78403fb9c92e4f3', language='ru') bot = telebot.TeleBot(config.TOKEN) authenticator =...
IgorSopronyuk/translate_IBM_bot
translater_IBM_bot.py
translater_IBM_bot.py
py
17,771
python
ru
code
0
github-code
6
21682006700
from tkinter import * from sudoku_api import get_grid,solve from sudoku_solver import solver,if_poss import tkinter.messagebox root=Tk() entries=user_inps=[[0 for i in range(9)] for j in range(9)] canvas=Canvas(root,height=500,width=450) canvas.pack() board=[[0 for i in range(9)] for j in range(9)] def get(event): re...
m-mukund/Sudoko_Solver
sudoku_inter.py
sudoku_inter.py
py
3,397
python
en
code
0
github-code
6
69869460347
def Mark( x=None, text='', color='', bold=True, underline=False): """ This function prints an object x and adds a description text. It is useful for for debugging. """ start = '' end = '' if color != '' or bold or underline: end='\033[0m' colorDict = { '': '', None: '', 'p...
google/expt-analysis
python/data_analysis.py
data_analysis.py
py
82,173
python
en
code
6
github-code
6
1805360050
#! /usr/bin/env python3 count = {} def char_count(str): for char in str: c = count.get(char) if c is None: count[char] = 1 else: count[char] += 1 print(count) if __name__ == '__main__': s = input('Enter a string') char_count(s)
wffh/project
count_str_fast.py
count_str_fast.py
py
297
python
en
code
0
github-code
6
23435779102
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import QMessageBox import sys import json import mainwindow, mystock, recepe, compute class MyMainWindow(mainwindow.Ui_MainWindow): def setupUi(self, mw, database): super().setupUi(mw) self.tabWidget = QtWidgets.QTabWidget() mw...
bernard169/open-breware
mymainwindow.py
mymainwindow.py
py
1,084
python
en
code
0
github-code
6
14872333572
import torch from torch import nn import torch.nn.functional as F from torch import optim from torchvision import datasets, transforms, models from workspace_utils import active_session from collections import OrderedDict import numpy as np from PIL import Image import argparse import json parser = argparse.Argument...
OmarMohy/Image-Classifier-with-Deep-Learning
predict.py
predict.py
py
3,922
python
en
code
0
github-code
6
33293378254
'''Simple Script to Label Item Description''' #import libraries packages import pandas as pd import numpy as np import matplotlib.pyplot as plt import string import re import json #read from csv data = pd.read_csv('./item.csv') item = data['Item Description'] #data cleaning (lowercase, remove whitespace, re...
aqillakhamis/Text-Matching-Label
textMatching.py
textMatching.py
py
1,824
python
en
code
1
github-code
6
4729018877
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 13 00:32:57 2018 @author: pablosanchez """ import tensorflow as tf import utils.constants as const from networks.dense_net import DenseNet class DeconvNet(object): def __init__(self, width, height, nchannels, reuse, transfer_fct=tf.nn.relu, ...
psanch21/VAE-GMVAE
networks/deconv_net.py
deconv_net.py
py
3,987
python
en
code
197
github-code
6
5223556496
import os import time import requests import functools from concurrent.futures import ThreadPoolExecutor import click import yaml def _get_connection_urls(workload_yaml): with open(workload_yaml) as f: workload = yaml.safe_load(f) uris = workload.get("EnvironmentDetails", {}).get("MongosyncConnectionU...
mongodb/genny
src/cast_python/src/mongosync_actor.py
mongosync_actor.py
py
4,300
python
en
code
42
github-code
6
30367868751
from numpy import linspace, sin from chaco.api import ArrayPlotData, Plot from chaco.tools.api import PanTool, ZoomTool from enable.api import ComponentEditor from traits.api import Enum, HasTraits, Instance from traitsui.api import Item, Group, View class PlotEditor(HasTraits): plot = Instance(Plot) plot_t...
enthought/chaco
examples/tutorials/scipy2008/ploteditor.py
ploteditor.py
py
2,299
python
en
code
286
github-code
6
36584033730
# -*- coding: utf-8 -*- """ Created on Wed Aug 19 14:36:47 2020 @author: allison """ def readATS(filename): infile = open(filename) ats = [] for line in infile: ats.append(line.replace("\n","")) infile.close() return ats def readCouplingMatrix(filename): infile = open(filename) Cs...
allie-walker/SCA4RNA_results
coupling_matrix_tools.py
coupling_matrix_tools.py
py
1,583
python
en
code
0
github-code
6
20918248522
import pandas as pd import numpy as np from scipy.sparse import csr_matrix from sklearn.neighbors import NearestNeighbors from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity, linear_kernel def GetMoviesByDescription(movieName): movie_...
InsiyaKanjee/Project4
initdb.py
initdb.py
py
7,073
python
en
code
0
github-code
6
18677212205
import argparse import logging import random import sys import time from copy import deepcopy import numpy as np import torch from scipy.stats import kendalltau from datasets.dataloader import get_dataloader from models.cell_operations import NAS_BENCH_201 from models.supernet import Supernet201 from utils import obt...
ShunLu91/PA-DA
nasbench201/train_baselines_201.py
train_baselines_201.py
py
14,254
python
en
code
29
github-code
6