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
2291746376
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Author: HuHao <huhao1@cmcm.com> Date: '2018/8/25' Info: """ # 获取系统环境 import os # 创建app实例和数据库实例 from app import create_app,db # 获取数据据类模板 from app.models import User,Role,Post,Permission # 使用 Manage 丰富启动参数支持,和 Shell 环境支持 from flask_script import Manager,Shell # ...
happy-place/flasky
manage.py
manage.py
py
3,574
python
zh
code
0
github-code
36
72466882663
""" WSGI config for mintemplate project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/ """ import os import sys import site prev_sys_path = list(sys.path) root = os.path.normpath(os.p...
kfarr2/Minimal-Template
mintemplate/wsgi.py
wsgi.py
py
1,128
python
en
code
0
github-code
36
15231900014
import sys import io import urllib.request print('hi') print('한글') sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8') sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8') imgUrl = "http://blogfiles.naver.net/20130502_54/dbsgusrl77_136748336507323OOv_JPEG/%BF%B5%C8%AD_%C0%BA%B9%D...
leyuri/Crawling
Chapter2/download2-1.py
download2-1.py
py
1,112
python
en
code
0
github-code
36
35797953381
# method 1 target = int(input()) Fibs = [1, 1] i = 2 while i < target: Fibs.append(Fibs[i - 1] + Fibs[i - 2]) i += 1 print(Fibs[target-1]) # method 2 target = int(input()) res = 0 a, b = 1, 1 for i in range(target-1): a,b=b,a+b print(a) # method 3 递归实现 def Fib(n): return 1 if n<=2 else Fib(n-1)+Fib(n...
StevenCReal/PythonCode
PRACTICE/#6F斐波那契数列.py
#6F斐波那契数列.py
py
356
python
en
code
1
github-code
36
17894243960
import os import time from absl import app from absl import flags from absl import logging import robustness_metrics as rm import tensorflow as tf import tensorflow_datasets as tfds import uncertainty_baselines as ub import ood_utils # local file import from baselines.cifar import utils # local file import from basel...
google/uncertainty-baselines
baselines/cifar/mimo.py
mimo.py
py
19,130
python
en
code
1,305
github-code
36
28875886668
from __future__ import absolute_import, unicode_literals from draftjs_exporter.dom import DOM from draftjs_exporter.error import ExporterException from draftjs_exporter.options import Options class EntityException(ExporterException): pass class EntityState: def __init__(self, entity_decorators, entity_map)...
mohit-n-rajput/BT-Real-Estate
venv/lib/python3.6/site-packages/draftjs_exporter/entity_state.py
entity_state.py
py
2,098
python
en
code
1
github-code
36
37416138856
import argparse import sys import traceback from logging import error, warning from typing import Dict, List, Text from urllib.parse import urlparse import act.api import requests import urllib3 from act.api.libs import cli import act from act.workers.libs import worker urllib3.disable_warnings(urllib3.exceptions.In...
mnemonic-no/act-workers
act/workers/url_shorter_unpack.py
url_shorter_unpack.py
py
4,131
python
en
code
6
github-code
36
17233781871
import argparse rows = 128 ### sliced spectrogram height cols = 1024 ### sliced spectrogram width channels = 2 max_width = 10337 ### maximum raw spectrogram width split_count = 10 ### number of slices per song epochs = 100 batch_size = 32 spectrogram_features = ['h', 'p'] ### Percussive & harmonic componen...
taprosoft/music-genre-classification
src/config.py
config.py
py
1,525
python
en
code
24
github-code
36
20410429609
import torch from torch import Tensor, nn from dataclasses import dataclass, field from typing import List, Tuple from prediction.model import PredictionModel, PredictionModelConfig from prediction.types import Trajectories from prediction.utils.transform import transform_using_actor_frame_gauss from prediction.utils...
dhararya/Predicting-Car-Trajectories
prediction/modules/probabilistic_model.py
probabilistic_model.py
py
2,483
python
en
code
0
github-code
36
31309911488
import numpy as np from sigmoid import sigmoid def predict(Theta1, Theta2, X): #PREDICT Predict the label of an input given a trained neural network # p = PREDICT(Theta1, Theta2, X) outputs the predicted label of X given the # trained weights of a neural network (Theta1, Theta2) # Useful values m = n...
EliottSimon17/NeuralNetwork
src/predict.py
predict.py
py
1,502
python
en
code
0
github-code
36
34198323203
import pytest from loguru import logger from pytest_mock import MockerFixture from fastapi_cloud_logging.fastapi_cloud_logging_handler import FastAPILoggingHandler @pytest.fixture def logging_handler(mocker: MockerFixture) -> FastAPILoggingHandler: return FastAPILoggingHandler( mocker.Mock(), transport=m...
quoth/fastapi-cloud-logging
tests/test_loguru.py
test_loguru.py
py
1,376
python
en
code
5
github-code
36
18624673274
# Subsequence of products less than K def subseq_product(arr, k): n = len(arr) product = 1 start = end = 0 result = 0 while(end < n): product = product * arr[end] while(start < end and product >= k): product = product/arr[start] start = start + 1 ...
indrajitrdas/Simple-Programs
ContiguousSubArrayProductLessThanK.py
ContiguousSubArrayProductLessThanK.py
py
593
python
en
code
0
github-code
36
41630548406
import os import torch import numpy as np from torch.utils.data import Dataset, DataLoader, sampler from PIL import Image import random from scipy import signal import wave import struct import random class wave_spec(Dataset): def __init__(self,root_dir,trans = None): self.root_dir = root_dir self.trans = tra...
devansh20la/Speech_Recognition
data_loader_spec.py
data_loader_spec.py
py
1,324
python
en
code
0
github-code
36
5738397642
"""Database debug and diagnostics functions.""" import json from typing import Any, Generator, Dict from . import db from . import user as usermod from . import request as requestmod def sprint_users(*criterions) -> Generator[str, None, None]: """Yields a generator whose elements are strings representing a user...
ProfessorLinstar/Gymbuddies
gymbuddies/database/debug.py
debug.py
py
1,545
python
en
code
0
github-code
36
14145225992
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 25 20:03:31 2020 @author: b """ import numpy as np values = [1, 2.4, 234, 112, 345] array = np.array(values) A = np.arange(1, 10, 1).reshape(3,3) b = np.ones((3,6)) # indexing A[0, 1] # Slicing # A[debut:fin:pas, debut:fin:pas] A[:, 0] # Subsett...
b846/Data
1b Numpy Indexing Slicing Masking.py
1b Numpy Indexing Slicing Masking.py
py
3,332
python
fr
code
0
github-code
36
23665407617
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None from collections import deque class Solution: def isSymmetrical(self, pRoot): if pRoot == None: return True queue = deque() ...
Lucky4/coding-interview
53.py
53.py
py
1,758
python
en
code
0
github-code
36
16178101967
#Korean vowel combination con_dict = [ ['ㅏㅣ','ㅐ'], ['ㅑㅣ','ㅒ'], ['ㅓㅣ','ㅔ'], ['ㅕㅣ','ㅖ'], ['ㅗㅣ','ㅚ'], ['ㅗㅐ','ㅙ'], ['ㅜㅓ','ㅝ'], ['ㅜㅔ','ㅞ'], ['ㅡㅣ','ㅢ'], ['ㅣㅏ','ㅑ'], ['ㅣㅓ','ㅕ'], ['ㅣㅗ','ㅛ'], ['ㅣㅜ','ㅠ'], ['ㅡㅓ','ㅓ'], ['ㅗㅏ','ㅘ'], ] #jongsung_list = [ 'ㄱ', 'ㄲ', 'ㄳ', 'ㄴ', 'ㄵ', 'ㄶ', 'ㄷ', 'ㄹ', 'ㄺ', 'ㄻ'...
joowhan/Translation_Project
api/src/low/dictionary.py
dictionary.py
py
5,445
python
ko
code
2
github-code
36
27374508738
# Python XML DOM Minidom # xml.dom.minidom — Minimal DOM implementation. # xml.dom.minidom is a minimal implementation of the Document Object Model interface, with an API similar to that in other languages. # It is intended to be simpler than the full DOM and also significantly smaller. # Users who are not already ...
VakinduPhilliam/Python_XML_Processing
Python_XML_DOM_Minidom_DOM_Flexibility_Example.py
Python_XML_DOM_Minidom_DOM_Flexibility_Example.py
py
2,468
python
en
code
2
github-code
36
7142523944
from llama_index import ServiceContext, VectorStoreIndex, StorageContext from llama_index.node_parser import SentenceWindowNodeParser from llama_index.indices.postprocessor import MetadataReplacementPostProcessor from llama_index.indices.postprocessor import SentenceTransformerRerank from llama_index import load_index_...
kilianovski/study
rag/utils.py
utils.py
py
2,068
python
en
code
1
github-code
36
34458782519
import numpy as np import findiff def curl_2d (x,y,u,v): d_dy = findiff.FinDiff(0, y, acc=10) d_dx = findiff.FinDiff(1, x, acc=10) dv_dx = d_dx(v) du_dy = d_dy(u) curl_2d = dv_dx - du_dy # (nul, nul, D) = Derivative_Calc.cheb_derivative(velocity) # curl_2d = np.matmul(-v , D.transpose()) - np.matmul(D, u...
HarleyHanes/aerofusion-HarleyFork
Python/aerofusion/numerics/curl_calc.py
curl_calc.py
py
341
python
en
code
0
github-code
36
15281460473
class Solution: def toGoatLatin(self, sentence: str) -> str: sentence = sentence.split() vowels = "aeiou" final = "" for i, word in enumerate(sentence): if word[0].lower() not in vowels: word = word[1:] + word[0] + "ma" print(word) ...
type0-1/LeetCode
goat-latin.py
goat-latin.py
py
482
python
en
code
0
github-code
36
29155312950
def createTreeItem(key, value): """ Maakt een nieuwe BST item aan met self.key=key en self.Root=value :param key: De zoeksleutel van het item. :param value: De waarde van het item. :return: Geeft de gemaakte BST terug. """ Tree = BST() Tree.key = key Tree.Root = value return Tree...
MenuaSoftware/CinepolisSystem
Project/Denis/BST.py
BST.py
py
12,220
python
nl
code
0
github-code
36
29640551287
#https://open.kattis.com/problems/detaileddifferences #setting test case variable testCase = input() #creating for loop in range of test case for i in range(int(testCase)): #get line 1 from user and then print line1 = input() print(line1) #get line 2 from user and then print line2 = input() ...
teddcp2/Tensorflow-Deep-Learning-notes
python/detailed_differences_1.4.py
detailed_differences_1.4.py
py
961
python
en
code
0
github-code
36
28692875111
# 2023.09.19 # 빅데이터개론 # userListHeader.py # zip, enumerate 함수를 구현 """ myZip function parameter: *args 가변인자, 매개변수의 수가 변할 수 있음 여러 데이터가 합쳐진 형태를 튜플로 리턴 // list가 아니어도 묶을 수 있다 이때 가장 짧은 길이의 데이터에 맞춤 """ def myZip(*args): min_length = min(len(arg) for arg in args) # len()은 이전에 구현했으니, 메소드를 바로 사용 result...
ffvv0123/2023-R2-Big-Data
List/List_02/userListHeader.py
userListHeader.py
py
903
python
ko
code
0
github-code
36
18914351143
class Solution: def taskSchedulerII(self, tasks: list[int], space: int) -> int: day = 0 history: dict[int, int] = {} for task_i, task in enumerate(tasks): if task in history and day - history[task] <= space: day += space - (day - history[task]) + 1 hi...
lancelote/leetcode
src/task_scheduler_ii.py
task_scheduler_ii.py
py
379
python
en
code
3
github-code
36
70536838504
''' Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null. ''' # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next =...
ChrisStewart132/LeetCode
160. Intersection of Two Linked Lists.py
160. Intersection of Two Linked Lists.py
py
975
python
en
code
0
github-code
36
13632762170
# -*- coding: utf-8 -*- """ Created on Thu Oct 25 15:04:22 2018 @author: Nagano Masatoshi """ import cv2 import os #import ffmpeg as fp def main(): #動画を読み込む filename = './movie/output.mp4' video = cv2.VideoCapture(filename) path = 'movie2' if not os.path.exists(path): ...
nagano28/img2mp4-mp42img
movie2img.py
movie2img.py
py
723
python
en
code
1
github-code
36
30289586485
class Solution(object): def maxArea(self, height): """ :type height: List[int] :rtype: int """ # start at both ends L = 0 R = len(height)-1 res = 0 # consider conditions that can never have a maximum ## bottom length continues ...
hanjisu49/LeetCode-for-BigTech
0011_containerMostWater.py
0011_containerMostWater.py
py
743
python
en
code
0
github-code
36
22635756480
# from django.http import HttpResponse from django.shortcuts import render # from random import randint # Create your views here. from . models import Article # 같은 폴더 안의 models에서 Article을 사용할거야 def index(request): # random_number = randint(1,18) # return HttpResponse("Hello, word {}".format(random_number)) ...
jungeunlee95/python-practice
Django/src/blog/views.py
views.py
py
696
python
en
code
0
github-code
36
22777255698
# -*- coding:utf-8 -*- import os from os import path import random def check_file(path='./',ext=''): _filelist = os.listdir(path) ch_e = [] for _file in _filelist: _root, _ext = os.path.splitext(_file) if _ext == ext: ch_e.append(_file) else: pass return...
Swall0w/Yolo-Fomat
gen_label.py
gen_label.py
py
915
python
en
code
0
github-code
36
11359144671
def snail(arr): global N newX, newY = 0, 0 dx = [1, 0, -1, 0] dy = [0, 1, 0, -1] dr_s = 0 num = 1 for i in range(N*N): X, Y = newX, newY arr[Y][X] = num newX = dx + dx[dr_s] newY = dy + dy[dr_s] if newX >= N or newX < 0 or newY >= N or newY < 0 or ar...
Jade-KR/TIL
04_algo/sw문제/d12/prac.py
prac.py
py
684
python
en
code
0
github-code
36
71534550504
import cv2 import os import torch import torch.nn as nn import torchvision import argparse import numpy as np import copy from torch.autograd import Variable pa = argparse.ArgumentParser() pa.add_argument("--input_row", type=int, default=0) pa.add_argument("--input_col", type=int, default=0) pa.add_argument("--input_c...
DrWiki/Alliance_Sentry_CNN_Tensorflow_Pytorch
Robomaster_CNN.py
Robomaster_CNN.py
py
6,374
python
en
code
2
github-code
36
13354653919
def reverse_string_1(s): return ' '.join(reversed(s.split())) def reverse_string(s): length = len(s) words = list() spaces = [' '] i = 0 while i < length: if s[i] not in spaces: word_start = i while i < length and i not in spaces: i += 1 ...
XingzheZhao/Coding_Docs
problems/reverseString.py
reverseString.py
py
924
python
en
code
0
github-code
36
4500647945
""" This unit test tests the uri resolver. It is often the case, that a taxonomy schema imports another taxonomy using a relative path. i.e: <link:linkbaseRef [..] xlink:href="./../example_lab.xml" [..]/> The job of the uri resolver is to resolve those relative paths and urls and return an absolute path or url """ impo...
manusimidt/py-xbrl
tests/test_transformation.py
test_transformation.py
py
15,723
python
en
code
78
github-code
36
34772355909
#! //Users/tyt15771/miniconda3/envs/pymol/bin/python from pymol import cmd import json import os import argparse parser = argparse.ArgumentParser() parser.add_argument( "-l", "--lig_path", required=True, ) parser.add_argument( "-p", "--prot_path", required=True, ) parser.add_argument( "-t...
xchem/PLEC
generate_complexes.py
generate_complexes.py
py
1,280
python
en
code
0
github-code
36
19448716950
import cv2 import os import re import mediapipe as mp import pandas as pd # Initialize mediapipe lib mpPose = mp.solutions.pose pose = mpPose.Pose() mpDraw = mp.solutions.drawing_utils lm_list = [] label = "FALLBACK" no_of_frames = 200 def make_landmark_timestep(results): c_lm = [] for id, lm in enumerate(re...
nt-myduyen/demo-human-detection
read-data.py
read-data.py
py
2,663
python
en
code
0
github-code
36
27078162265
#!/usr/bin/python # -*- coding: utf-8 -*- from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector from score.items import ScoreItem from sunburnt import SolrInterface class ScoreSpider(CrawlSpider): name = 'score' ...
h4k1m0u/matchendirect-crawl
score/score/spiders/score_spider.py
score_spider.py
py
6,947
python
en
code
0
github-code
36
29871880593
from fastapi import APIRouter, HTTPException, status, Body from fastapi.param_functions import Depends from fastapi.security.oauth2 import OAuth2PasswordRequestForm from sqlalchemy.orm.session import Session from db.database import get_db from auth import oauth2 from utils.hash import Hash from jose import jwt from jos...
DaXuaBa/mobirace_be
auth/authentication.py
authentication.py
py
3,009
python
en
code
0
github-code
36
21624620290
import re import duckduckgo def duckduck_regex(message): regex = "^\/duckduck\s+(?P<data>[a-zA-Z0-9\s]+)" m = re.match(regex, message) if not m: return None else: return m.groupdict()["data"] def ddg(query): """ DuckDuckGo search """ return duckduckgo.get_zci(query)
0x00-0x00/gadreel-bot
src/duckduckgo.py
duckduckgo.py
py
317
python
en
code
2
github-code
36
74072355624
import moviepy.editor as mp from assembly_api import * def convert(name): video = mp.VideoFileClip(name) video.audio.write_audiofile("converted.wav") print("Please enter the name of video file you want to summarize along with its type...... eg: test.mp4") name = input() convert(name) def start(): filename ...
SiddheshJawadi/NLP_Webinar_Summarization
NLP/main.py
main.py
py
487
python
en
code
0
github-code
36
43697079041
from libqtile.lazy import lazy from libqtile.config import Key mod = "mod4" terminal = "kitty" filemanager = "thunar" browser = "brave" keys = [ # window controls Key([mod], "j", lazy.layout.down(), desc="Move focus down"), Key([mod], "k", lazy.layout.up(), desc="Move focus up"), Key([mod, "shift"], "...
daddyhacker18/dotfiles-laptop
.config/qtile/modules/keys.py
keys.py
py
3,211
python
en
code
0
github-code
36
8170098557
import pickle import numpy as np import matplotlib.pyplot as plt import os #global a,b,c,aami data_sys = './diadata/' filelist=['data1.txt','data2.txt','data3.txt','data4.txt','data5.txt','data6.txt','data7.txt','data8.txt','data9.txt','data10.txt' ,'data11.txt','data12.txt','data13.txt','data14.txt','data15....
WangboML/BP_estimation
sys_process.py
sys_process.py
py
1,484
python
en
code
2
github-code
36
38394545817
import pandas as pd #%% #1a opción Rutas de importación y exportación synergy_dataframe = pd.read_csv('synergy_logistics_database.csv', index_col=0, encoding='utf-8', parse_dates=[4, 5]) #Definir apartados combinaciones1 = synergy_dataframe.groupby(by=['direction', 'origin', ...
ingridhuezo7/01-HUEZO-INGRID
ANALISIS_02_ HUEZO VAPNIK_INGRID/ANALISIS_02_ HUEZO VAPNIK_INGRID.py
ANALISIS_02_ HUEZO VAPNIK_INGRID.py
py
3,198
python
es
code
0
github-code
36
4723479414
# -*- coding: utf-8 -*- """ Custom scripts to plot DISCO profiles to a passed plot axis. """ import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import os import numpy as np from utils.plotting_helpers import annotate_sig_buildup_points from utils.wrangle_data import flatten_multicolumns, calcula...
Frank-Gu-Lab/disco-figures-template
notebooks/utils/plotting.py
plotting.py
py
15,812
python
en
code
2
github-code
36
15778610136
import os import sys from typing import Callable from utils.inputs import int_input from utils.prints import Color, print_line, print_result def get_exercices_count() -> int: """ Retourne le nombre d'exercices. :return: Le nombre d'exercices. :rtype: int """ # count the number of files with pattern "ex[number]...
Ayfri/Python-TP3
menu/menu.py
menu.py
py
2,550
python
fr
code
0
github-code
36
15827646142
from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() from builtins import * import itertools import logging import pymongo import arrow import pandas as ...
e-mission/e-mission-server
emission/storage/decorations/trip_queries.py
trip_queries.py
py
22,026
python
en
code
22
github-code
36
14156669347
import json import ptvsd import sys import requests import boto3 ptvsd.enable_attach(address=('0.0.0.0', 5678), redirect_output=True) print("waiting for debugger to attach...") sys.stdout.flush() ptvsd.wait_for_attach() print("attached") # import requests def create_dynamo_table(event, context, table_name_value,...
tclarkston/debug-lambda
dynamo_db/app.py
app.py
py
1,888
python
en
code
0
github-code
36
39623165565
# # Day 3: Rucksack Reorganization # https://adventofcode.com/2022/day/3 # import string def calculate(lines: list[str]): SCORE_KEY = list(string.ascii_lowercase) + list(string.ascii_uppercase) score = 0 for i in range(0, len(lines), 3): sack1 = set(lines[i].strip()) sack2 = set(lines[i + ...
jeffharrington/advent-of-code-2022
day03/day3b.py
day3b.py
py
564
python
en
code
0
github-code
36
37454105581
"""Console script for bgcflow.""" import subprocess import sys from pathlib import Path import click import bgcflow from bgcflow.bgcflow import cloner, deployer, get_all_rules, snakemake_wrapper from bgcflow.mkdocs import generate_mkdocs_report from bgcflow.projects_util import copy_final_output, projects_util CONTE...
matinnuhamunada/bgcflow_wrapper
src/bgcflow/cli.py
cli.py
py
7,639
python
en
code
2
github-code
36
40572434380
import setuptools import version with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="uncertainty-wizard", version=version.RELEASE, author="Michael Weiss", author_email="code@mweiss.ch", description="Quick access to uncertainty and confidence of Keras networ...
testingautomated-usi/uncertainty-wizard
setup.py
setup.py
py
838
python
en
code
41
github-code
36
11113762870
# -*-coding:utf-8-*- """ File Name: mouse_response_and_type_conversion.py Program IDE: PyCharm Date: 10:04 Create File By Author: Hong """ import cv2 as cv import numpy as np # 在图像上画矩形框 x1 = -1 y1 = -1 x2 = -1 y2 = -1 # canvas = np.zeros((300, 300, 3), dtype=np.uint8) canvas = cv.imread('images/2.png...
YouthJourney/Computer-Vision-OpenCV
mouse_response_and_type_conversion.py
mouse_response_and_type_conversion.py
py
2,441
python
en
code
21
github-code
36
39829558439
import numpy as np import copy import json import imageio import math import os import functools import torch from torch import nn from torch.utils.data import Dataset # Code based on: # https://github.com/openai/baselines/blob/master/baselines/deepq/replay_buffer.py # Expects tuples of (state, next_sta...
willwhitney/dynamics-aware-embeddings
rl/utils.py
utils.py
py
14,213
python
en
code
42
github-code
36
37862197413
import pandas as pd from sentence_transformers import SentenceTransformer from sklearn.metrics.pairwise import cosine_similarity from transformers import AutoTokenizer, AutoModel import torch from typing import List from patent_phrase_similarity.data.analysis.visualize_datasets import plot_score_vs_test_score from p...
vquilon/kaggle-competitions
patent-phrase-to-phrase-matching/models/transformers_similarity.py
transformers_similarity.py
py
6,450
python
en
code
0
github-code
36
2722280973
class Solution(object): def buildTree(self, preorder, inorder): if not preorder or not inorder: return None # firt elementin preorder is root, found the index in preorder and separate them root = TreeNode(preorder[0]) index = inorder.index(preorder[0]) ...
ZhengLiangliang1996/Leetcode_ML_Daily
Tree/105_ConstructBinaryTreeFromPreorderandInorder.py
105_ConstructBinaryTreeFromPreorderandInorder.py
py
571
python
en
code
1
github-code
36
71304388263
#Desafio 31 #Débora Janini #Este desafio fiz com base em de duas colegas, #aonde pude ver ferraemntas novas do python e entender N = int(input()) array = list(map(int, input().split())) menor = min(array) #min retorna o menor posicao = array.index(menor) #index retorna o indice, então #index do menor valor no array...
deborajanini/desafios-python
desafio31versao2.py
desafio31versao2.py
py
382
python
pt
code
0
github-code
36
29465284343
## This module aims to analyze the effect of angle distribuiton import numpy as np import math as mt import matplotlib.pyplot as plt import Kinematics import scipy.integrate as integrate import scipy.optimize as opt #Particle Property #kpc kpc_in_cm = 3.08567758e21 #light speed vc = 3e10 #Neutrino M_nu = 0.32 # Unit...
CrazyAncestor/DM_Neutrino_Flux
old_codes/Angle_Effect.py
Angle_Effect.py
py
10,190
python
en
code
0
github-code
36
16379803548
# %% preliminaries import sys, os from pylab import * from treefarm import * from treefarm.minimizers.flatgp import FlatGPMinimizer, expected_improvement from treefarm.core.utils import get_minium_states from treefarm.core.space_utils import get_subspace, to_space from time import sleep import GPy kernel_dict = { ...
Mome/baumschule
examples/test_different_kernels.py
test_different_kernels.py
py
2,382
python
en
code
0
github-code
36
16655733054
from hypothesis import given, assume, strategies as st from quadratic import quadratic import cmath @given(a = st.floats(min_value=-10000, max_value=10000), b = st.floats(min_value=-10000, max_value=10000), c = st.floats(min_value=-10000, max_value=10000)) def test_quad(a, b, c): assume(abs(a) >= 0.0...
rhettinger/modernpython
test_quadratic.py
test_quadratic.py
py
535
python
en
code
438
github-code
36
10453935366
# Copyright (C) 2020-2021 Burak Martin (see 'AUTHOR' for full notice) """ Enable/disable parallelism, caching and nogil. The program needs to be restarted to take effect since these options only effect numba functions which need to be recompiled. """ parallel = True cache = True nogil = True
pymatting/pymatting-interactive-tool
config/config.py
config.py
py
308
python
en
code
5
github-code
36
16662671
load("@obazl_rules_ocaml//ocaml:providers.bzl", "BuildConfig", "OpamConfig") opam_pkgs = { "ocaml": ">= 4.04.0", "dune": ">= 1.2.0", "ounit": "with-test & >= 1.0.2", "ppx_sexp_conv": "with-test & >= v0.9.0", "stringext": ["1.4.0"], "angstrom": ["0.14.0"], } opam = OpamConfig( version = ...
tweag/ocaml-uri-bazel
bzl/opam.bzl
opam.bzl
bzl
541
python
en
code
0
github-code
36
6197795850
def gcd(n1,n2): while n2 >0: n1,n2 = n2 , n1%n2 return n1 def solution(denum1, num1, denum2, num2): # 1. 두 분수의 합 계산 boonmo = num1 * num2 boonja = denum1 * num2 + denum2 * num1 # 2. 최대공약수 계산 gcd_value = gcd(boonmo, boonja) # 3. gcd 로 나눈 값을 answer에 담기 answer = [boonja / ...
byeong-chang/Baekjoon-programmers
프로그래머스/lv0/120808. 분수의 덧셈/분수의 덧셈.py
분수의 덧셈.py
py
414
python
ko
code
2
github-code
36
19691521791
import torch from torch import nn import torch.nn.functional as F from utils import gelu, LayerNorm from transformer import TransformerLayer, Embedding, LearnedPositionalEmbedding, SelfAttentionMask from label_smoothing import LabelSmoothing class BIGLM(nn.Module): def __init__(self, local_rank, vocab, embed_dim...
lipiji/SongNet
biglm.py
biglm.py
py
7,558
python
en
code
227
github-code
36
29791048785
import requests from lxml import etree import json from pyecharts import Map # 0.1.9.4 class nCoV_2019: def __init__(self): self.headers = { "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 S...
Ramelon/Python-
疫情图.py
疫情图.py
py
3,469
python
zh
code
7
github-code
36
34246961090
""" The directories module: Provides paths to all directories used in the package. This module helps with the relative paths of the directories in this package. It helps with overcoming the hassle of re-writing & hardcoding paths used for reference. At a glance, the structure of the module is following: - ai_dir{}: ...
ganyavhad/charlotte
utils/paths/directories.py
directories.py
py
2,597
python
en
code
0
github-code
36
37222098464
#!/usr/bin/env python # coding: utf-8 # In[143]: #Natural Language Processing with the DIJA and Reddit Headlines #Classification Predictions on Stock Market from Headlines #Classification includes Overall Up or Down, Market Volitality, and Measure of Strong and Poor Days import numpy as np import pandas as pd from...
rbarrow2727/stockheadlines
Visualization_and_Modeling_for_Stock_Market_News_Headline_Classification_v5.py
Visualization_and_Modeling_for_Stock_Market_News_Headline_Classification_v5.py
py
27,699
python
en
code
0
github-code
36
6372282633
from fastapi import Security, HTTPException, status from fastapi.security.api_key import APIKeyHeader from app.db.session import SessionLocal from app.core.settings import API_KEY_NAME, API_KEY api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False) def get_db(): db = SessionLocal() try: ...
GrupoX-FIUBA/users-service
app/endpoints/base.py
base.py
py
1,007
python
en
code
0
github-code
36
19294329942
# server.py - Main server file # Imports import paho.mqtt.client as mqtt import requests import recommender import json import threading import queue import config # Constants for MQTT TEST_FEED = "charliemm/feeds/test-feed" RECOMMENDATIONS_FEED = "charliemm/feeds/project.recommendations" UPDATES_FEED = "charliemm/fe...
maguic11/WhereNext
server/server.py
server.py
py
5,092
python
en
code
0
github-code
36
22782805173
#! /usr/bin/env python3 import boto3 import logging from botocore.exceptions import ClientError from regionslist import regions session = boto3.Session(profile_name='temp') def deployStack(region): temp_cfnclient = session.client('cloudformation', region_name=region) response = temp_cfnclient.create_...
desiby/stelligent-u
01-cloudformation/1.3.2/deploys3.py
deploys3.py
py
695
python
en
code
0
github-code
36
26067827949
import torch.utils.data as data import numpy as np import os import torch import time import data_reader from PIL import Image def collate_fn(batch): inputs = batch[0][0]; gt = batch[0][1]; noise_std = batch[0][2] for index in range(1,len(batch)): inputs = torch.cat((inputs,batch[index][0]),0)...
eedalong/ISP_Demosaic
demosaicnet_src/datasets.py
datasets.py
py
3,126
python
en
code
1
github-code
36
22403507258
from SudokuBoard import SudokuBoard, INDEXES_PAIRS, get_random_indexes # CONSTANTS NUMBER_OF_ROWS = 9 NUMBER_OF_COLUMNS = 9 class SudokuGame: def __init__(self): self.board = SudokuBoard() self.playing_board = SudokuBoard() # testing self.board.fill_board() pass def ...
ofirmeir/Sela_Sudoku
SudokuGame.py
SudokuGame.py
py
1,069
python
en
code
0
github-code
36
5061905616
from skimage import io, transform import torch import os import cv2 from torchvision import transforms, datasets, utils as vutils from torch.utils.data import Dataset, DataLoader import torch.nn as nn import torch.nn.functional as F class WormClassifier(nn.Module): def __init__(self, dim=64): super(Worm...
paolobif/wormifier
models.py
models.py
py
2,595
python
en
code
0
github-code
36
5424410088
import frappe from frappe import _ from frappe.model.document import Document class UpgradationAndStatusChange(Document): def validate(self): pass #if self.transfer_date > frappe.utils.nowdate(): # frappe.throw("Future date not allowed") def on_submit(self): new_school = frappe.get_doc("School", self.school...
hamza0342/semis
semis/semis/doctype/upgradation_and_status_change/upgradation_and_status_change.py
upgradation_and_status_change.py
py
730
python
en
code
0
github-code
36
34323690653
#scan port using nmap import nmap import sys import argparse def port_scanner(network): print("Nmap scanning on " + network + " ...\n") scan_nmap = nmap.PortScanner() res = scan_nmap.scan(hosts=network, arguments='-sn') print(res["nmap"]) print("there was " + res["nmap"]["scanstats"]["totalhosts"] + " hosts sc...
bonnettheo/python_hacking_tools
ip_scanner.py
ip_scanner.py
py
1,482
python
en
code
0
github-code
36
29466847233
#@author: Neil #2018-09-26 import sys, pygame from pygame.locals import * from random import randrange class Weight(pygame.sprite.Sprite): def __init__(self, speed): pygame.sprite.Sprite.__init__(self) self.speed = speed # 绘制Sprite对象时要用到的图像和矩形: self.image = weight_image...
Crazyalltnt/Beginning-Python-3-Projects
10-Do-It-Yourself Arcade Game/weights.py
weights.py
py
1,998
python
zh
code
5
github-code
36
70234738344
from sshtunnel import SSHTunnelForwarder from concurrent.futures import ProcessPoolExecutor import pymysql import pandas as pd import datetime import numpy as np from visits import Visits def read_from_db(query): tunnel = SSHTunnelForwarder( ('192.168.2.85', 22), ssh_username='ubuntu', ...
AlexMuliar/counter
count_visits.py
count_visits.py
py
2,624
python
en
code
0
github-code
36
6890156052
import requests import json from libs.html_parser import html_to_nodes def createPage(access_token, image_sources): """Create a page on https://telegra.ph/ Accepts a list of image sources and creates a page containing those images. Returns the url of the page in case of success, False otherwise """ ...
xareyli/telegraph-uploader
libs/telegraph/create_page.py
create_page.py
py
1,501
python
en
code
0
github-code
36
11311733424
import npyscreen import curses def simpletest(screen): SA = npyscreen.Form() w = npyscreen.Textfield(SA, ) w.value = u'\u00c5 U+00C5 LATIN CAPITAL LETTER A WITH RING ABOVE\n'.encode('utf-8') w.edit() w.update() if __name__ == "__main__": curses.wrapper(simpletest)
npcole/npyscreen
utf8-pycurses.py
utf8-pycurses.py
py
277
python
en
code
436
github-code
36
8640560733
#!/usr/bin/python # -*- coding: utf-8 -*- """ Created on Thu Jul 18 04:52:01 2019. @author: jamiesom """ import pandas as pd from electricitylci.globals import data_dir, output_dir import numpy as np from electricitylci.eia860_facilities import eia860_generator_info import re def generate_power_plant_construction(ye...
USEPA/ElectricityLCI
electricitylci/power_plant_construction.py
power_plant_construction.py
py
5,934
python
en
code
23
github-code
36
31712806303
# price and discount is float price=9.99 discount=0.2 result=price*(1-discount) print(result) # String name="Krishna" name1="Sai" print(name) print(name*2) print(name+" "+name1) # excercise of creating variables var1="hola" var2="hola" print(var1+" "+var2) num1=8 num2=2 print(num1*num2) # using f-string n...
KrishnaSaiVadlamani/Demo-Application
FlaskWithPython/module2/basicCode.py
basicCode.py
py
536
python
en
code
0
github-code
36
24184036928
''' Created on Jul 16, 2011 @author: Giulio ''' import logging from system.network.ServerProxy import ServerProxy class DummyProxy(ServerProxy): ''' classdocs ''' recognizedFuncs = ['shell','send','receive','close'] def __init__(self): ServerProxy.__init__(self) self._logger = l...
gbottari/ESSenCe
src/system/network/DummyProxy.py
DummyProxy.py
py
914
python
en
code
0
github-code
36
74611240104
#!/usr/bin/env python import altair_saver from map_maker_lib import create_topo_data, read_file, validate_data, \ create_plot, DATA_TYPES, DELIMITERS, COLOR_SCHEMES import streamlit as st BE_GEO_URL = 'https://gist.githubusercontent.com/jandot/ba7eff2e15a38c6f809ba5e8bd8b6977/raw/eb49ce8dd2604e558e10e15d9a38...
gjbex/Python-for-data-science
source-code/streamlit/map_maker/map_maker_app.py
map_maker_app.py
py
2,085
python
en
code
12
github-code
36
19310364873
import os import functools dir_path = os.path.dirname(os.path.realpath(__file__)) with open(dir_path+'/input.txt') as f: lines = [line.rstrip("\n") for line in f] print(os.path.basename(dir_path)) def diff(str1, str2): res = "" for char in str1: if char not in str2: res += char f...
recrtl/aoc21
day8-2/main.py
main.py
py
2,736
python
en
code
1
github-code
36
14822140289
# # @lc app=leetcode.cn id=257 lang=python3 # # [257] 二叉树的所有路径 # # https://leetcode-cn.com/problems/binary-tree-paths/description/ # # algorithms # Easy (56.91%) # Total Accepted: 5.9K # Total Submissions: 10.4K # Testcase Example: '[1,2,3,null,5]' # # 给定一个二叉树,返回所有从根节点到叶子节点的路径。 # # 说明: 叶子节点是指没有子节点的节点。 # # 示例: # ...
ZodiacSyndicate/leet-code-solutions
easy/257.二叉树的所有路径/257.二叉树的所有路径.py
257.二叉树的所有路径.py
py
1,342
python
en
code
45
github-code
36
14248925493
#입력 n, c = map(int, input().split()) arr = [] for _ in range(n): arr.append(int(input())) #과정 #[1, 2, 8, 4, 9]가 있을 때 인접한 영역을 기준으로 이진탐색을 수행 # 먼저 최소 gap과 최대 gap을 지정한 다음 그 중간값을 기준으로 공유기를 #설치할 수 있는 개수를 구한 다음 c보다 크거나 같은 경우 #즉, c보다 더 많은 공유기 설치가 가능한 경우 gap을 더 늘려야 하므로 시작점 #즉, gap의 최소를 업데이트 # 반면 공유기를 c보다 더 적게 설치할 수 밖에 없...
vmfaldwntjd/Algorithm
BaekjoonAlgorithm/파이썬/이진 탐색/Baekjoon_2110.py
Baekjoon_2110.py
py
1,975
python
ko
code
0
github-code
36
37568831331
D = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five',6: 'six',7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten',11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen',15: 'fifteen', 16: 'sixteen', 17: 'seventeen',18: 'eighteen', 19: 'nineteen', 20: 'twenty', 30: 'thirty',40: 'forty', 50: 'fifty', 60: 'sixty', 70: '...
jorul/ITGK
ITGK øvinger/Eksamen 2016/4.py
4.py
py
2,908
python
en
code
0
github-code
36
17106811081
import os inputPath = os.path.join(os.path.dirname(__file__), "input") with open(inputPath, "r") as inputFile: initialLines = [line.strip() for line in inputFile.readlines() if line] def getLineAtCursor(lines, cursor): command, value = lines[cursor].split(" ") value = int(value) return command, valu...
mmmaxou/advent-of-code
2020/day-8/answer.py
answer.py
py
1,816
python
en
code
0
github-code
36
6758424060
import pygame import random pygame.init() dis_width = 800 # указываем высоту и ширину экрана dis_height = 600 win = pygame.display.set_mode((dis_width, dis_height)) pygame.display.set_caption("snake") # пишем название экрана x = 0 # начальные координаты змейки y = 0 speed = 10 # скорость з...
artem6033/snake
snake.py
snake.py
py
3,345
python
ru
code
0
github-code
36
37726664454
import threading import time from traceback import print_tb import numpy as np import serial.tools.list_ports import serial import queue import PySimpleGUI as sg import matplotlib.figure as figure import matplotlib.pyplot as plt number_of_network_nodes = 3 monitor_serial = 'All' # 'Single' or 'All' class Artist: ...
PedroTaborda/DistributedIlluminationSystem
serial_com_async.py
serial_com_async.py
py
12,472
python
en
code
0
github-code
36
34111347494
import argparse ''' Given a file with both genders, creates 2 CSVs, one for male and one for female. Uses 'gender' column; '0'=female, '1'=male. ''' def split_genders(file, dest_file, gender_idx): lines = open(file, 'r').readlines() with open(dest_file + '_male.csv','w') as file: for line_idx in range(len(li...
carisatinie/emotion_bias
programs/split_genders.py
split_genders.py
py
2,471
python
en
code
0
github-code
36
7784669889
import requests import json def versiontuple(v): return tuple(map(int, (v.split(".")))) if __name__ == '__main__': # Load the .json file containing the remote version url = 'https://raw.githubusercontent.com/matteocali/DEILabs/main/data/version.json' f = requests.get(url) # The .json() method au...
matteocali/DEILabs
data/version_checker.py
version_checker.py
py
763
python
en
code
4
github-code
36
32625776262
import re class Solution: def myAtoi(self, string): """ :type string: str :rtype: int """ string = string.strip() pattern = re.compile('[+-]?\d+') try: result = int(pattern.match(string).group()) if result > 2147483647: ...
7forz/leetcode_algo_data_structure
008-String to Integer (atoi).py
008-String to Integer (atoi).py
py
527
python
en
code
0
github-code
36
5049733369
import argparse import json import os import time # isort: off import torch import torch.multiprocessing as mp import tensorrt as trt # isort: on from safetensors import safe_open from transformers import AutoModelForCausalLM, GPTNeoXConfig from weight import load_from_hf_gpt_neox import tensorrt_llm from tensorrt_ll...
NVIDIA/TensorRT-LLM
examples/gptneox/build.py
build.py
py
17,487
python
en
code
3,328
github-code
36
70864089065
import multiprocessing import os class Logger: info_enabled = 1 debug_enabled = 1 output_enabled = 1 @staticmethod def output(prefix, s): if Logger.output_enabled: print(multiprocessing.current_process().name, prefix, s) @staticmethod def info(s): if Logger.i...
b49nd1n/IPS
ips/logger.py
logger.py
py
495
python
en
code
0
github-code
36
11904566223
from collections import defaultdict class DigitSignals: def __init__(self, signals): self.signals = ["".join(sorted(s)) for s in signals] self.signalsByLength = defaultdict(list) self.wires = ["?"] * 7 self.numberMap = {} self.signalsToNumbers = {} self.solve() ...
ianlayzer/adventofcode2021
code/08.py
08.py
py
3,775
python
en
code
0
github-code
36
18046091832
# daf_test_start.py - DAF connection test based on ppo_aoa_random_start.py import logging import numpy as np from stable_baselines3 import PPO from backend.rl_base_classes.aoa_base_class import AoABaseClass from backend.rl_environments.discrete_environment import DiscreteEnv from backend.utils.analysis import plot_av...
hmdmia/HighSpeedRL
rl_runners/daf_test_start.py
daf_test_start.py
py
3,524
python
en
code
0
github-code
36
5050338619
import tempfile import unittest from collections import OrderedDict from itertools import product import numpy as np import parameterized # isort: off import torch import tensorrt as trt # isort: on from parameterized import parameterized from transformers import BertConfig, BertForQuestionAnswering, BertModel impor...
NVIDIA/TensorRT-LLM
tests/model/test_bert.py
test_bert.py
py
15,445
python
en
code
3,328
github-code
36
13100989511
from time import time import six import json from chameleon import PageTemplate BIGTABLE_ZPT = """\ <table xmlns="http://www.w3.org/1999/xhtml" xmlns:tal="http://xml.zope.org/namespaces/tal"> <tr tal:repeat="row python: options['table']"> <td tal:repeat="c python: row.values()"> <span tal:define="d python: c + 1" tal...
ddps-lab/serverless-faas-workbench
openwhisk/cpu-memory/chameleon/function.py
function.py
py
1,104
python
en
code
96
github-code
36
3106445086
# coding: utf-8 import unittest from unittest.mock import MagicMock, patch from car_rewrite_model.model import CarRewriteBaseKeywords, CarRewriteSynonymsReplace class TestDemo(unittest.TestCase): def test_car_rewrite_base_keywords(self): CarRewriteBaseKeywords.get_tf_results = MagicMock(return_value=['改...
flyliu2017/car_rewrite_model
tests/test_demo.py
test_demo.py
py
3,205
python
en
code
0
github-code
36
72152970985
import numpy as np import torch from torch import nn crop_size = 256 cfa_pattern = 1 idx_R = np.tile( np.concatenate((np.concatenate((np.zeros((cfa_pattern, cfa_pattern)), np.ones((cfa_pattern, cfa_pattern))), axis=1), np.concatenate((np.zeros((cfa_pattern, cfa_pattern)), n...
samsungexpert/snu
myloss.py
myloss.py
py
4,782
python
en
code
1
github-code
36
7961895091
import RPi.GPIO as GPIO import time import datetime import math from ISStreamer.Streamer import Streamer streamer = Streamer(bucket_name="Hamster Fitness Tracker", access_key="PUT YOUR CLIENT KEY HERE") streamer.log("ZooZoo Says","") # Setup Pins pinNumLaserBreak = 18 pinNumLED = 4 GPIO.setmode(GPIO.BCM) # numbering s...
initialstate/blog
hamster_fitness.py
hamster_fitness.py
py
1,974
python
en
code
2
github-code
36