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
5198901937
#!/usr/bin/env python # -*- coding: utf-8 -*- from datetime import datetime import unittest import yalix.repl as repl import yalix.utils as utils def send_inputs(*args): # count always starts from 1 def invoke(count): try: cmd = args[count - 1] if isinstance(cmd, str): ...
rm-hull/yalix
python/tests/repl_test.py
repl_test.py
py
1,934
python
en
code
5
github-code
36
39370596177
def fibonacci(n): if n == 1 or n == 2: return 1 prev, curr = 1, 1 for i in range(2, n): tmp = prev prev = curr curr = prev + tmp return curr x = int(input()) print(fibonacci(x))
bbpythoncourse/python
4/4.4.py
4.4.py
py
238
python
en
code
0
github-code
36
41585308053
from flask.ext.mongokit import MongoKit, Document from datetime import datetime from sensorapp import db, app @db.register class Device(Document): __database__ = app.config["DB_NAME"] __collection__ = "device" structure = { 'name': unicode, 'digit_pin_num': int, 'analog_pin_num': in...
janetyc/SensorIoT
sensorapp/models.py
models.py
py
2,885
python
en
code
0
github-code
36
24969027415
from typing import List class Solution: def dailyTemperatures(self, temperatures: List[int]) -> List[int]: ans = [0] * len(temperatures) stack = [] for i, v in enumerate(temperatures): while stack and stack[-1][1] < v: index, value = stack.pop() ...
inverseTrig/leet_code
739_daily_temperatures.py
739_daily_temperatures.py
py
530
python
en
code
0
github-code
36
42712331906
def solution_long(start, length, debug=False): """ Known Working Solution :param start: :param length: :param debug: :return: """ if start < 0 or start > 2000000000 or length < 1 or start + length > 2000000000: return 0 skip_start = length run_checksum = 0 worker = s...
drewtuley/LAMBCHOP
SecurityQueue/queue_to_do.py
queue_to_do.py
py
2,128
python
en
code
0
github-code
36
72045571623
puzzle = open('puzzle', 'r').read().strip() puzzle = list(map(int, puzzle.split())) def get_nodes(x): child_nodes = x[0] metadata_entries = x[1] ret = [] ret_sum = 0 steps = 0 for i in range(child_nodes): sub = get_nodes(x[2+steps:]) ret.append(sub[0]) steps += sub[1] if child_nodes == 0: ret_sum ...
filipmlynarski/Advent-of-Code-2018
day_08/day_8_part_2.py
day_8_part_2.py
py
549
python
en
code
0
github-code
36
25955407466
import time class Profiler: ''' A small profiler class for measuring how long a block of code runs. This should be used like: ``` with Profiler('label'): # code to run here ``` and will automatically print runtime information. Additionally, if multiple `with` blocks are neste...
nicknytko/numml
numml/profiler.py
profiler.py
py
1,389
python
en
code
9
github-code
36
11685619050
from django.shortcuts import render from django.shortcuts import render,redirect from django.contrib.auth.forms import UserCreationForm,AuthenticationForm # from .models import Device from django.contrib.auth import authenticate from django.contrib.auth import login #from .forms import SignUpForm from django.core.mail ...
sanjolisogani/new_ops
newops/views.py
views.py
py
14,804
python
en
code
0
github-code
36
13419956267
import pygame,sys from Room import Room,Overworld class Game: def __init__(self) -> None: self.overworld = Overworld(screen,self.start_game) self.status = 'overworld' self.current_room = 0 def start_game(self): self.room = Room(self.current_room, self.create_overworld) ...
NishantK30/projects
text based game/main.py
main.py
py
960
python
en
code
0
github-code
36
15150261198
#Healthy programmer # 9am - 5pm # Water = water.mp3 (3.5 liters)every 40min - Drank - log # Eyes = eyes.mp3 (Every 30 min) - EyesDone - log # Pysical Activity = pysical.mp3 (every 45 min)- ExDone - log # # Rules - pygame module to play audio from pygame import mixer from datetime import datetime from time import time ...
entbappy/My-python-projects
Ex7 Healty programmer50.py
Ex7 Healty programmer50.py
py
1,582
python
en
code
2
github-code
36
28069150292
# 2021-10-15 # 출처 : https://programmers.co.kr/learn/courses/30/lessons/86491 # 위클리 챌린지 - 8주차_최소직사각형 #sizes=[[60, 50], [30, 70], [60, 30], [80, 40]] sizes=[[10, 7], [12, 3], [8, 15], [14, 7], [5, 15]] def solution(sizes): long=[] short=[] for i in sizes: if i[0]<i[1]: long.append(i[1...
hwanginbeom/algorithm_study
WeeklyChallenge/WeeklyChallenge08_kyounglin.py
WeeklyChallenge08_kyounglin.py
py
517
python
en
code
3
github-code
36
21953618118
""" Process the VCF file to compute observed values of statistics and estimate misorientation rate """ import egglib ##### PARAMETERS AND CONFIGURATION ##################################### fname = '/home/flavia/flavia_data2/2023/demography/egglib/filtered_genotyped_combined_outgroup_208samples_pass_filter5_renamed....
flaviarogerio/demographic
cp_stats4.py
cp_stats4.py
py
7,729
python
en
code
0
github-code
36
35076398379
"""This file contains the signature validator abstraction""" import base64 import json from cose.headers import KID from cose.keys.keyops import VerifyOp from cose.messages import Sign1Message from cose.keys import CoseKey from cose.algorithms import Es256, Ps256 from cose.keys.keytype import KtyEC2, KtyRSA from cose...
ryanbnl/eu-dcc-diagnostics
classes/SignatureValidator.py
SignatureValidator.py
py
3,969
python
en
code
9
github-code
36
36754576461
# Binary Search def solution(A, value): if (len(A) == 1) & (A[0] == value): print(f'found it: {A[0]}') return A[0] elif (len(A) == 1) & (A[0] != value): print('Not found it') elif len(A) == 0: print('Not found it') elif len(A) > 1: mid = len(A) // 2 print...
Quantanalyst/SoftwareEngineeringNotes
Data Structure and Algorithms/Popular Questions/BinarySearch.py
BinarySearch.py
py
649
python
en
code
0
github-code
36
38488870579
#!/usr/bin/env python3 # # Bonus. GPE auto-training + GSA using external (from publication) dataset loaded from json file # import os from gpytorch.likelihoods import GaussianLikelihood from gpytorch.means import LinearMean from gpytorch.kernels import MaternKernel, ScaleKernel from GPErks.gp.data.dataset import Data...
stelong/GPErks
examples/example_bonus.py
example_bonus.py
py
3,888
python
en
code
3
github-code
36
30807564816
import copy import os import sys # define our clear function def clear(): # for windows if os.name == 'nt': _ = os.system('cls') # for mac and linux(here, os.name is 'posix') else: _ = os.system('clear') def systemStrip(input): return input.strip("").replace("&", "").re...
Treelovah/dev-null
console.py
console.py
py
12,973
python
en
code
0
github-code
36
9959099201
import random import itertools import math import json from functions.counting import counting from functions.multi_arithematic import multiple_operations_two_ops from functions.single_arithematic import single_arithematic from functions.avg_val import average_point_value from functions.permutation_combination import ...
GVS-007/MLLM_Reasoning
final_data_creation.py
final_data_creation.py
py
7,225
python
en
code
0
github-code
36
3419259967
from spectractor import parameters from spectractor.simulation.simulator import AtmosphereGrid, SpectrumSimulatorSimGrid from spectractor.config import load_config from spectractor.simulation.image_simulation import ImageSim from spectractor.logbook import LogBook from spectractor.extractor.extractor import Spectractor...
LSSTDESC/Spectractor
runSimulator.py
runSimulator.py
py
2,608
python
en
code
13
github-code
36
14380560581
from typing import * class Solution: def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]: rows = len(image) cols = len(image[0]) source = image[sr][sc] if color == source: return image def helper(sr, sc): ...
jithindmathew/LeetCode
flood-fill.py
flood-fill.py
py
735
python
en
code
0
github-code
36
18056687843
from one_layer_net_base import OneLayerNetBase class OneLayerNet(OneLayerNetBase): def calc_corrections(self, vector, learning_rate): for j in range(len(self.neurons)): error = vector.get_desired_outputs()[j] - self.neurons[j].get_out() weights_deltas = [0] * len(self.neurons[j].ge...
StanislavMakhrov/OneLayerPerceptron
pure_python/one_layer_net_delta_rule.py
one_layer_net_delta_rule.py
py
873
python
en
code
0
github-code
36
72734862185
from qblockchain import QBlockchain import hashlib def main(): qbc = QBlockchain() qbc.mine_block("First block 1") print(qbc.is_chain_valid()) #qbc.break_up_4bit_values([0000]) #qbc.xor(["23ab0","12ab0"],4) xor_bin = qbc.xor(str("1234"), str("abc0"), 4) hashOut = hashlib.sha3_256(xor_...
asiaat/python_qblockchain
main.py
main.py
py
1,487
python
en
code
0
github-code
36
16620383859
# @Author: Billy Li <billyli> # @Date: 06-05-2022 # @Email: li000400@umn.edu # @Last modified by: billyli # @Last modified time: 06-06-2022 import sys from pathlib import Path import shutil import numpy as np from scipy.stats import uniform data_dir = Path.cwd().parent.joinpath("data") sys.path.insert(1, str(...
billy000400/CircNN
src/features/make_data_single_track.py
make_data_single_track.py
py
2,828
python
en
code
0
github-code
36
13990400448
from collections import defaultdict from sys import maxint class Solution(object): def getClosest(self, S, t): closest = None minDiff = maxint for k, x in S: diff = abs(t - x) if diff < minDiff: minDiff = diff closest = k, x r...
dariomx/topcoder-srm
leetcode/zero-pass/google/optimal-account-balancing/Solution3.py
Solution3.py
py
1,460
python
en
code
0
github-code
36
25163396057
import os from unittest import mock from easul import util from easul.driver import MemoryDriver from easul.visual import Visual from easul.tests.example import diabetes_progression_algorithm, prog_input_data, no_prog_input_data import logging from easul.visual.element import Prediction from easul.visual.element.pr...
rcfgroup/easul
easul/tests/visual/test_prediction.py
test_prediction.py
py
2,967
python
en
code
1
github-code
36
32487421332
#-*-coding:utf-8 -*- import sys import hmac import hashlib import time import requests import json import urllib import top class ewsServiceApi: ''' Aliyun EWS service api ''' def __init__(self,accesskey,secretkey): self.accesskey = accesskey self.secrekey = secretkey self.tim...
opnms/opnms
base/ewsService.py
ewsService.py
py
2,267
python
en
code
0
github-code
36
13958593890
class URL_helper: def __init__(self): self.__HOUSE_TYPES_LIST = ['rodinne-domy', 'vily', 'chalupy', 'chaty', 'projekty-na-klic', 'zemedelske-usedlosti', 'pamatky-jine', 'vicegeneracni-domy'] self.__HOUSE_LOCATIONS_DICT = {'Karlovarsky': ['cheb', 'karlovy-vary'...
eugenganenco/SRealty
webScraper/URL_helper.py
URL_helper.py
py
5,434
python
cs
code
0
github-code
36
34353676149
import requests from bs4 import BeautifulSoup from time import sleep import json from sqlalchemy import create_engine,Column,Integer,String,ForeignKey,table, column, select, update, insert from sqlalchemy.ext.declarative import declarative_base from urlparse import urlparse from sqlalchemy.orm import sessionmaker from ...
VladislavSpassov/HackBulgariaTasks
Week13/CrawnBGWebsites.py
CrawnBGWebsites.py
py
3,072
python
en
code
0
github-code
36
34642170576
#!/usr/bin/python3 from network import Model from Experiences import Experiences import numpy as np model = Model() experiences = Experiences() print('experiences ', len(experiences.get()[0])) for i in range(10): model_loss = model.model_train(experiences, False) print('model', model_loss) model.save() ...
uberthought/DQN
offline_train.py
offline_train.py
py
435
python
en
code
0
github-code
36
18306688211
from PIL import Image img=Image.open(r"C:\Users\rohan\Downloads\Pictures\IMG_5093.jpg") height=img.height width=img.width print(f"Height:{height} Width:{width}") r,g,b=img.getpixel((100,100)) print(f"R:{r} G:{g} B:{b}") img2=img.convert("L") img2.show() img2=img2.save(r"C:\Users\rohan\Downloads\Pictures\test2.jpeg") i...
rohanxd1/Codes
Python/TEST.py
TEST.py
py
416
python
en
code
0
github-code
36
11519320722
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function import logging from types import FunctionType from fdm import central_fdm from lab import B from plum import Dispatcher, Self, Referentiable, type_parameter, Union from .util import uprank from .input import Input, At, MultiInp...
pb593/stheno
stheno/graph.py
graph.py
py
27,441
python
en
code
null
github-code
36
70231595624
''' Name: Main file for HW2 of FE 595 Intro: This file should load the cleaned data from theyfightcrime.org, sort the data, and return the required info. Author: William Long Date : 09/22/2019 ''' import pandas as pd import numpy as np from textblob import TextBlob import nltk #First, Let's load the data m_raw = pd....
bluefinch83/FE_595_HW2
Main.py
Main.py
py
2,099
python
en
code
0
github-code
36
3269577614
def main(): print("Result-> "+str(quicksort([2, 7, 9, 3, 1, 6, 5, 4]))) def quicksort(arr): pivot = arr[len(arr)-1] wall = 0 for i in range(len(arr)): if arr[i] < pivot: swap_elements(arr, wall, i) wall += 1 # switch the pivot with the first element on the right si...
VAR-solutions/Algorithms
Sorting/quickSort/python/quick_sort.py
quick_sort.py
py
811
python
en
code
733
github-code
36
4394037963
# 스티커 모으기(2) # r1 x # https://programmers.co.kr/learn/courses/30/lessons/12971 # https://inspirit941.tistory.com/158 def solution(sticker): answer = 0 if len(sticker) == 1: return sticker[0] dp = [0 for _ in range(len(sticker))] dp[0] = sticker[0] dp[1] = dp[0] for i in ran...
sjjam/Algorithm-Python
programmers/level/L3/12971.py
12971.py
py
645
python
en
code
0
github-code
36
23188615876
import visualization import ROOT as root from detector import Detector tracking_file_name = "../../build/output/pgun/klong/stat0.root" tracking_file = root.TFile.Open(tracking_file_name) tree = tracking_file.Get("integral_tree") LAYERS_Y=[[6001.0, 6004.0], [6104.0, 6107.0]] det = Detector() count ...
seg188/MATHUSLA-MLTracker
scripts/draw_energy.py
draw_energy.py
py
1,722
python
en
code
1
github-code
36
19702023558
from flask import Flask, request, send_from_directory, send_file from contracts import DCCInterface from web3 import Web3, HTTPProvider import json import _thread import time import traceback app = Flask(__name__) jobs = [] jobs_details = [] web3 = Web3([HTTPProvider("http://10.8.3.1:8545")]) def thread_prune_entrie...
jimgao1/dcc
src/server.py
server.py
py
1,747
python
en
code
0
github-code
36
4828550972
from concurrent.futures import process from matplotlib.pyplot import cla import numpy as np, pandas as pd import re from scipy import rand dataset = pd.read_csv("../../resources/Part 7 - Natural Language Processing/Section 36 - Natural Language Processing/Python/Restaurant_Reviews.tsv",delimiter="\t", quoting=3) ## ...
ManishLapasi/MLstuff
models/NLP/nlpselect.py
nlpselect.py
py
4,084
python
en
code
0
github-code
36
12029446848
#!/usr/bin/env python3.8 how_many_prime = int(input("How many prime numbers would you like to see? ")) def natural_num(num: int)-> int: yield num yield from natural_num(num+1) def sieve(s: int)-> int: n = next(s) yield n yield from sieve(i for i in s if i%n!=0) p = sieve(natural_num(2)) for _ i...
NateDreier/Learn_Python
independent_learning/random_proj/lazy_prime.py
lazy_prime.py
py
364
python
en
code
0
github-code
36
14873664547
import cv2 import yaml from application.main.onnx_model.base_model import BaseModel from typing import Tuple from application.main.onnx_model.util import * class YoloOnnxModel(BaseModel): def __init__(self, cfg_file): super(YoloOnnxModel, self).__init__(cfg_file) self.input_nodes = ["images"] ...
YoungHyuenKim/onnx_fastAPI_example
application/main/onnx_model/yolo_model.py
yolo_model.py
py
2,184
python
en
code
0
github-code
36
21645118091
from datetime import date, datetime, timezone, timedelta import threading import git import os from repoorgui.commands import commandfn # see https://stackoverflow.com/a/39956572 # made changes to return repo object if exits def is_git_repo(path): try: r = git.Repo(path) _ = r.git_dir ret...
abhishekmishra/repoorgui
src/repoorgui/gitworkspace.py
gitworkspace.py
py
4,397
python
en
code
0
github-code
36
21520280572
""" VATSIM Status Proxy Copyright (C) 2017 - 2019 Pedro Rodrigues <prodrigues1990@gmail.com> This file is part of VATSIM Status Proxy. VATSIM Status Proxy 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,...
pedro2555/vatsim-status-proxy
settings.py
settings.py
py
2,875
python
en
code
2
github-code
36
72054157543
# Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html # useful for handling different item types with a single interface from datetime import datetime from urllib.parse import urljoin import pymongo imp...
mudssky/myScrapySpiders
getchu/getchu/pipelines.py
pipelines.py
py
3,959
python
en
code
0
github-code
36
38044872719
input_file = open("../inputs/day11input.txt", "r") input_array = [] f = list(input_file.readline()) while f: f.remove("\n") input_array.append(f) f = list(input_file.readline()) for i in range(len(input_array)): for j in range(len(input_array[i])): input_array[i][j] = int(input_array[i][j]) ...
pvtrov/advent-of-code-2021
day11/1.py
1.py
py
3,349
python
en
code
0
github-code
36
30370929393
import sys sys.stdin = open('input.txt') def DFS(start_node, end_node): to_visits = [start_node] while to_visits: current = to_visits.pop() visited[current] = True for node in graph[current]: if visited[node] is False: visited[node] = True to_...
pugcute/TIL
algorithm/2644_촌수계산/2644.py
2644.py
py
775
python
en
code
0
github-code
36
24201123813
# 백준 부분수열의 합 import sys N, S = map(int, sys.stdin.readline().split(' ')) arr = list(map(int, sys.stdin.readline().split(' '))) cnt = 0 visited = [False] * N def backtracking(size, now_sum): global cnt if size == N: if now_sum == S: cnt += 1 return backtracking(size+1, now_sum + arr[si...
superyodi/burning-algorithm
dfs/boj_1182.py
boj_1182.py
py
430
python
en
code
1
github-code
36
71244709543
"""watch for changes in tiles.yml""" import hashlib import os from src.config_parser import ConfigFile from src.template import create_all_tiles from src.tilefy_redis import TilefyRedis class Watcher: """watch for changes""" FILE_PATH = "/data/tiles.yml" def __init__(self): self.modified = Fal...
bbilly1/tilefy
tilefy/src/watcher.py
watcher.py
py
2,072
python
en
code
16
github-code
36
34996914416
import numpy as np import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt from numpy import pi inputName = "21cylindrov" fileName = inputName + "-Tphi-all" plotName = fileName + "-smery" data = np.load("./Results/"+fileName+".npz") inputData = np.load("./Inputs/" + inputName + ".npz") n = inputData...
KlaraFickova/Diplomovka
Draw/smery-f.py
smery-f.py
py
919
python
en
code
0
github-code
36
38799414939
import discord import bdg import gamelist import random class SurpriseGameCommand(bdg.BdgCommand): header = { 'name': "sortear_jogo", 'description': "Lista de Jogos - Sorteie um jogo aleatório baseado no filtro especificado", } async def on_command(self, i: discord.Interaction, filtro: gamelist.GameFilter): ...
DanielKMach/BotDusGuri
src/commands/gamelist/surprise.py
surprise.py
py
814
python
pt
code
1
github-code
36
44396010983
import tensorflow as tf import os import cProfile def variable_turn_off_gradient(): step_counter = tf.Variable(1, trainable=False) print(step_counter) def variable_placing(): with tf.device('CPU:0'): # Create some tensors a = tf.Variable([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) b = tf...
jk983294/morph
book/tensorflow/core/variables.py
variables.py
py
1,966
python
en
code
0
github-code
36
70553071464
import time, datetime import numpy as np import os import os.path as osp import torch import torchvision import matplotlib.pyplot as plt import torchvision.utils as vutils import torch.nn.functional as F import cv2 import glob import random from lib.utils.eval_utils import ( batch_compute_similarity_transform_tor...
JunukCha/SSPSE
utils/trainer_utils.py
trainer_utils.py
py
26,289
python
en
code
6
github-code
36
2051327559
##https://towardsdatascience.com/develop-a-nlp-model-in-python-deploy-it-with-flask-step-by-step-744f3bdd7776 from flask import Flask, request, jsonify,render_template,redirect,flash import pandas as pd import matplotlib.pyplot as plt #from flask_cors import CORS from data_Preprocessing import DataPreprocessing from ve...
Pooja-AI/Email-Classification
file.py
file.py
py
10,841
python
en
code
0
github-code
36
37348251487
from my_radial_grid import * beta = 0.4 N = 150*(2 + 1) ae_grid = MyAERadialGridDescriptor(beta/N, 1.0/N, N) # Grid points in this case is # a g # r(g) = -------, g = 0, 1, ..., N - 1 # 1 - b g print("Grid parameters:") print("a = ", ae_grid.a) print("b = ", ae_grid....
f-fathurrahman/ffr-learns-gpaw
ae_generator/test_radial_grid_02.py
test_radial_grid_02.py
py
567
python
en
code
0
github-code
36
41166932292
# pip install requests bs4 lxml # pip install jieba import requests import bs4 import jieba import csv stocks = set() def prepare_stocks(): with open('week3/Stock.csv', encoding='utf-8') as csv_file: csv_reader = csv.reader(csv_file) stock_list = list(csv_reader) for stock in stoc...
andrewintw/learning-python-web-crawler
week3/lab00_ptt_from_teacher.py
lab00_ptt_from_teacher.py
py
2,001
python
en
code
0
github-code
36
37502377637
# https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV4suNtaXFEDFAUf """ 단순한 구현 문제 사용된 코어와 사용할 코어의 개수가 최대로 사용했던 코어의 개수보다 적으면 더이상 탐색하지 않는다. """ dire = [[-1, 0], [1, 0], [0, -1], [0, 1]] def DRAW(x, y, d, graph): tx, ty = x + dire[d][0], y + dire[d][1] while 0 <= tx < len(graph) and 0 ...
junsgi/Algorithm
BackTracking/[SW Test 샘플문제] 프로세서 연결하기.py
[SW Test 샘플문제] 프로세서 연결하기.py
py
2,239
python
ko
code
0
github-code
36
8591398196
import torch import torch.nn as nn import torch.nn.functional as F import copy import numpy as np from itertools import chain class SurgicalFineTuningBert(nn.Module): def __init__( self, bert_model, ) -> None: super().__init__() self.get_extended_attention_mask = bert_model.get...
AntoineBigeard/NLPSurgicalFineTuning
src/pimped_bert.py
pimped_bert.py
py
4,780
python
en
code
2
github-code
36
70345439783
import os import sys import pdb import torch import numpy as np import pickle as pkl from PIL import Image from random import shuffle from torchvision import datasets, transforms """ Template Dataset with Labels """ class XYDataset(torch.utils.data.Dataset): def __init__(self, x, y, **kwargs): self.x, se...
joey-wang123/DRO-Task-free
data.py
data.py
py
11,866
python
en
code
11
github-code
36
43319179836
#!/usr/bin/env python from geometry_msgs.msg import ( PoseStamped, Pose, Point, Quaternion, ) def house_coordinates(x, y, z, width, height): ''' This function takes in coordinates x, y, z to determine where the structure will be built from. It also takes in the width and height of th...
ansonthalia/DE_robotics1
Final_Submission/House_Builder.py
House_Builder.py
py
7,047
python
en
code
0
github-code
36
18488873840
from utility import log, timeit, Timer import CONSTANT from concurrent.futures import ProcessPoolExecutor import datetime import numpy as np import os import pandas as pd import CONSTANT import gc from CONSTANT import LABEL,NUMERICAL_PREFIX,LABEL_CNT_SUFFIX @timeit def cat_Lable_Cnt_Fun(train_data, y, test_data, co...
HantaoShu/KDD2019-Challenge
Lib_preprocess/catFeatureLabelCnt.py
catFeatureLabelCnt.py
py
5,098
python
en
code
5
github-code
36
16667044604
import os import pydicom import numpy as np import dicom_numpy from utils import hidden_errors from tf_utils import * from pathlib import Path def read_dicom_folder(dicom_folder, rescale=None): ''' Reads all .dcm files in `dicom_folder` and merges them to one volume Returns: The volume and the affine...
xeTaiz/dvao
volume_loader.py
volume_loader.py
py
2,556
python
en
code
6
github-code
36
35382251444
#!/usr/bin/env python3 from re import M from sys import stderr, exit from multilanguage import Env, Lang, TALcolors from TALinputs import TALinput import random import graph_connectivity_lib as gcl from time import monotonic # METADATA OF THIS TAL_SERVICE: problem="graph_connectivity" service="eval_bot_deciding_con...
romeorizzi/TALight
example_problems/tutorial/graph_connectivity/services/eval_bot_deciding_connectivity_driver.py
eval_bot_deciding_connectivity_driver.py
py
6,055
python
en
code
11
github-code
36
74120599144
from django.db.models import Q from django.shortcuts import render from apps.news.models import News, HeadlineNews, BottomInfo # Views function for home page of site def index(request): # news part latest_news = News.objects.order_by('-published_date')[:3] headlines = HeadlineNews.objects.filter(is_publis...
libomun/crhs
apps/home/views.py
views.py
py
1,287
python
en
code
0
github-code
36
6796248308
import pandas ''' features of papers used including: 1.main title 2.abstract contents 3.author 4.keywords for both main title and abstract contents, dictionary and word counts need to be attained expected result: a dict containing text, word count, and a dictionary for authors, authors of each pa...
another1s/ontology_learning
program/analyse.py
analyse.py
py
4,163
python
en
code
2
github-code
36
72167483303
""" This file holds the interaction sites class used in simulation.py. """ import warnings from random import random from copy import deepcopy from itertools import combinations from math import comb import numpy as np class InteractionSites: """A class designed to host interactions between persons within specif...
Queens-Physics/quaboom
cv19/interaction_sites.py
interaction_sites.py
py
33,973
python
en
code
4
github-code
36
7755009879
import numpy as np import json import copy import functools from tensorpack.utils import logger from petridish.info.layer_info import LayerInfo, LayerInfoList, LayerTypes class CellNetworkInfo(dict): def __init__(self, master=None, normal=None, reduction=None): super(CellNetworkInfo, self).__init__(loca...
microsoft/petridishnn
petridish/info/net_info.py
net_info.py
py
27,723
python
en
code
111
github-code
36
5850629924
#coding: utf-8 import pygame from block import Block import constants #insert this class in ship method gen_shoot() class Bullet(Block): def __init__(self,x,y, sign, speed, targets_nopoints= None, targets_points=None, point_receptor=None): super(Bullet, self).__init__(x,y,10,10,constants.YELLOW) self.dir_x = 0 ...
RafaelPAndrade/Pixel_Martians
bullet.py
bullet.py
py
1,487
python
en
code
0
github-code
36
12546585829
""" ospopen.py This programs lists your outdated Python packages and the latest version available. """ import sys import os infile = os.popen("/Library/Frameworks/Python.framework/Versions/3.6/bin" "/pip3 list -o") #Create a child process and a pipe. ...
zeeboo26/Python-INFO1-CE9990
ospopen.py
ospopen.py
py
822
python
en
code
0
github-code
36
13070086793
def boardScore(A): A = [a.split() for a in A] res = 0 m, n = len(A), len(A[0]) def dfs(i, j, flag): nonlocal score, area if i >= m or j >= n or i < 0 or j < 0 or not A[i][j] or A[i][j][0] != flag or A[i][j] == '#': return score += int(A[i][j][1:]) area += 1 ...
Jason003/Interview_Code_Python
Airbnb/board score.py
board score.py
py
787
python
en
code
3
github-code
36
43494226202
from PyQt4 import QtGui, QtCore # # # class RubberbandEnhancedLabel(QtGui.QLabel): # # def __init__(self, parent=None): # QtGui.QLabel.__init__(self, parent) # self.selection = QtGui.QRubberBand(QtGui.QRubberBand.Rectangle, self) # # def mousePressEvent(self, event): # ''' # ...
lkosh/abandoned_objects
select2.py
select2.py
py
10,387
python
en
code
1
github-code
36
23331748159
import matplotlib.pyplot as plt from utility_functions import * depth = 120 layers = 100 segments = 1 size_classes = 2 lam = 300 simulate = False verbose = True l2 = False min_attack_rate = 10**(-3) mass_vector = np.array([0.05, 20, 6000]) # np.array([1, 30, 300, 400, 800, 16000]) obj = spectral_method(depth, layer...
jemff/food_web
old_sims/other_initial_conditions.py
other_initial_conditions.py
py
1,717
python
en
code
0
github-code
36
8225047192
#3 more decision problems #FizzBuzz values #use % to find multiples of a numner equaled to zero number = int(input('Enter a positive integer: ')) if number % 3 == 0: print('Fizz') elif number % 5 == 0: print('Buzz') elif number % 3 == 0 and number % 5 == 0: print('FizzBuzz') else: print(n...
JordanRabold/Python-3.10
fizz_buzz.py
fizz_buzz.py
py
588
python
en
code
0
github-code
36
16010531173
''' api_test.py Jeff Ondich, 11 April 2016 Ethan Somes, 13 April, 2017 Revised from Jeff's example for CS 257 Software Design. How to retrieve results from an HTTP-based API, parse the results (JSON in this case), and manage the potential errors. ''' import sys import argparse import...
NylaWorker/TrebuchetPhysicsSimulation
CS257/API.py
API.py
py
5,087
python
en
code
0
github-code
36
27254946312
""" --------------------------------------------------------------- Authors: A. Ramirez-Morales (andres.ramirez.morales@cern.ch) H. Garcia-Tecocoatzi --------------------------------------------------------------- """ from decays.decay_wrapper import decay import decays.decay_utils_em as du import numpy as...
Ailierrivero/bottom-baryonsFW-copy
decays/electro_width.py
electro_width.py
py
10,332
python
en
code
0
github-code
36
11831438569
import discord from discord.ext import commands from discord.commands import Option from commands.funcs.yatta_gif import yatta_gif # List of commands here: # /yattagif class Gif(commands.Cog, description='Gif maker'): def __init__(self, bot): self.bot = bot self.footer = "Developed by jej#6495 for...
jej-v/snowcodes2022
commands/yatta.py
yatta.py
py
1,201
python
en
code
0
github-code
36
22663485001
def jugar_suma_modular(modulo, numero_inicial, numero_objetivo): resultado = numero_inicial while resultado != numero_objetivo: numero = int(input("Ingresa un número para sumar: ")) resultado = (resultado + numero) % modulo print(f"Resultado parcial: {resultado}") print("¡Ganaste!")...
Jacobo24/Trabajo_profundizacion
Juego_de_suma_modular.py
Juego_de_suma_modular.py
py
470
python
es
code
0
github-code
36
38793714824
condition=[] count=[] def Count(end,totalmass): if totalmass==0: return 1 if totalmass<0: return 0 if [end,totalmass] in condition: return count[condition.index([end,totalmass])] else: value=0 for i in range(len(masslist)): value+=Count(masslist[i],to...
XueningHe/Rosalind_Genome_Sequencing
PeptideNumberGivenMass.py
PeptideNumberGivenMass.py
py
752
python
en
code
0
github-code
36
18852099221
from os import environ from time import time, sleep import requests import requests.auth from requests_oauthlib import OAuth1 from .exceptions import * class API: def __init__(self, session=None): self.log_function = print self.retry_rate = 5 self.num_retries = 5 s...
kavyamandaliya/SentimentAnalysis
scraper/scrap/apis.py
apis.py
py
13,220
python
en
code
0
github-code
36
19786182992
from keras import Model import numpy as np from scam.exceptions import InvalidState from scam.utils import resize_activations, normalize_activations class ScoreCAM: def __init__(self, model_input, last_conv_output, softmax_output, input_shape, cam_batch_size=None): """ Prepares class activation m...
andreysorokin/scam-net
scam/keras.py
keras.py
py
3,075
python
en
code
9
github-code
36
74331703784
''' https://codeforces.com/problemset/problem/126/B Solution: Compute array z as Z function of the string. Then we just need to find an element z[i] such that z[i]=n-i and z[i]<max(z) or z[i]==max(z) and count(z[i])>=2 ''' def Z(s): n=len(s) z=[0 for i in range(n)] l,r=0,0 for i in range(1,n): ...
codeblooded1729/Competitive-programming-Problems
codeforces/passsword.py
passsword.py
py
995
python
en
code
0
github-code
36
23971685802
from __future__ import unicode_literals import os import re import json from contextlib import contextmanager from collections import defaultdict from functools import wraps, partial import psycopg2 from PyQt4.QtCore import Qt, QSettings, QRect from PyQt4.QtGui import ( QIcon, QMessageBox, QDialog, QStandardItem,...
Oslandia/qgis-menu-builder
menu_builder_dialog.py
menu_builder_dialog.py
py
32,979
python
en
code
2
github-code
36
26523812537
#!/usr/bin/env python # -*- coding: utf8 -*- import os import pyhaproxy.pegnode as pegnode import pyhaproxy.config as config class Parser(object): """Do parsing the peg-tree and build the objects in config module Attributes: filepath (str): the absolute path of haproxy config file filestrin...
imjoey/pyhaproxy
pyhaproxy/parse.py
parse.py
py
10,541
python
en
code
53
github-code
36
5820967293
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Mar 6 18:28:13 2022 @author: ldd775 """ import socket, sys, re, os import params def recBytes(): sys.path.append("../lib") # for params switchesVarDefaults = ( (('-l', '--listenPort') ,'listenPort', 50001), (('-?',...
utep-cs-systems-courses/os-project3-framing-lddavila
lib/framingServer.py
framingServer.py
py
5,153
python
en
code
0
github-code
36
43660570358
import arcpy import os import csv def aggregate_by_route_by_injury_type(route_fc, crash_fc, gdb, distance): """Iterates through the bus route data and aggregates the number and type of injuries within the search distance""" arcpy.env.workspace = gdb route_dictionary = {} for row in arcpy.da.S...
ttlin1/Bus
determine_number_crashes_for_each_route.py
determine_number_crashes_for_each_route.py
py
4,071
python
en
code
0
github-code
36
43696108113
import os from math import ceil from keras import backend from keras import optimizers from keras.applications.vgg19 import VGG19 from keras.applications.resnet50 import ResNet50 from keras.layers import Dense, Flatten, BatchNormalization, Dropout from keras.models import Sequential, Model from keras.callbacks import...
anson627/kaggle
planet/lib/classifier.py
classifier.py
py
5,485
python
en
code
0
github-code
36
25634514682
import claripy import code from hashlib import sha512 import json import sys b = [claripy.BVS('b_%d' % i, 1) for i in range(33896)] s = claripy.Solver() with open("map3.txt", 'r') as f: cipher, chalbox = json.loads(f.read()) length, gates, check = chalbox for i in range(33767,33896): name, args = gates[i-...
posgnu/ctfs
pctf2018/3iscABC/sol.py
sol.py
py
907
python
en
code
1
github-code
36
990448118
import requests import random import time from threading import Thread # Import modules for HTTP flood import tools.randomData as randomData import tools.ipTools as ipTools def HTTP_ATTACK(threads, attack_time, target): # Finish global FINISH FINISH = False if ipTools.isCloudFlare(target): if not ...
Marshmello1912/Git
Impulse/tools/L7/http.py
http.py
py
1,653
python
en
code
0
github-code
36
38552357203
''' # the Space Complexity is O(1) and the Time Complexity is O(N) def caesar_enc(str, key): alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', ' j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' ] # or say alpha=list("abcdefjhijklmnopqrstuwuxyz") HashTable = {} ...
pro-ghanem/MY-DSA-Problem-Solving
String Manipulation/Caeser Encrypter.py
Caeser Encrypter.py
py
1,006
python
en
code
0
github-code
36
75121574505
import unittest import requests URL = 'http://127.0.0.1:8000/segment' IMAGE_PATH = './data/test_image/' IMAGE_NAME = '0bf631128.jpg' IMAGE_FORMAT = 'image/jpeg' class ImageSegmentationTest(unittest.TestCase): def test_image_segmentation(self): with open(IMAGE_PATH+IMAGE_NAME, 'rb') as image_file: ...
MykytaKyt/airbus-ship-detection
tests/test_app.py
test_app.py
py
994
python
en
code
0
github-code
36
25842561969
from sqlalchemy import ForeignKey, Table, Column from sqlalchemy.sql.sqltypes import Integer, String, Float, Boolean, Date from config.db import meta, engine castings = Table("castings", meta, Column("id", Integer, primary_key=True), Column("castingDate", Date), Column("name", String(255)), Column("ca...
Lorea13/Profesionales-del-Arte
backend/models/casting.py
casting.py
py
554
python
en
code
0
github-code
36
2112950145
import json class SettingFile(object): def __init__(self, path, defaults): self._defaults = defaults self._path = path self._data = dict() self._callbacks = dict() for setting in defaults: self._callbacks[setting] = callback_assist() self.load() def...
sdfgeoff/newsscroller
setting_file.py
setting_file.py
py
2,100
python
en
code
0
github-code
36
22541773169
# RA, 2020-10-13 import contextlib import io @contextlib.contextmanager def open_maybe_gz(file, *, mode='r'): """ Open `file` for reading that could be a - file descriptor - path to file - path to gzipped file `mode` is either 'r' or 'rb', and has to be specified. Usage: with...
Luca-Blum/Computational_Biomedicine
project1/solution/humdum/io/gz.py
gz.py
py
891
python
en
code
0
github-code
36
37980420317
import random from enum import Enum fifth_ed_bad_reactions = ["cringe.jpg", "mike.jpg", "nat1.gif", "nat1.jpg", "jazz.jpg"] fifth_ed_good_reactions = ["heisenberg.gif", "joji.jpg", "mcmahon.gif", "nat20.jpg"] sw_bad_reactions = ["bad1.gif", "bad2.gif", "bad3.gif", "bad4.gif", "bad5.gif", "bad6.jpg...
SPIGS/DiceBot
gamemode.py
gamemode.py
py
1,148
python
en
code
1
github-code
36
30810878899
import serial import KeyConfig as kc import struct import socket IP = '192.168.1.200' PORT = 12345 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) s.setblocking(False) def read_data(): d: bytes = ser.readline() if len(d) > 0: res = d.decode().replace('\r\n', '') r...
AssoAndrea/UE-ArduinoLightController
PythonMiddleware/main.py
main.py
py
1,249
python
en
code
1
github-code
36
37877826411
import os import re import shutil from glob import glob from osrf_pycommon.process_utils import AsyncSubprocessProtocol from catkin_tools.common import mkdir_p from catkin_tools.terminal_color import fmt from .events import ExecutionEvent MAX_LOGFILE_HISTORY = 10 class IOBufferContainer(object): """A simple ...
catkin/catkin_tools
catkin_tools/execution/io.py
io.py
py
9,125
python
en
code
153
github-code
36
6171191684
def find_Team(t, n, l): if n > l : return l if n == l : t.append(l) if (2*n + 1) < l: t.append(2*n + 1) find_Team(t, 2*n + 1, l) if (2*n + 2) < l: t.append(2*n + 2) find_Team(t, 2*n + 2, l) return t def compare(n, m): power1 = 0 power2 = 0 for i in n:...
PPZeen/OODS_Exersice
Tree/tree2_4.py
tree2_4.py
py
805
python
en
code
0
github-code
36
23155147064
import logging import os from datetime import datetime file_name=f"{datetime.now().strftime('%d_%m_%Y_%H_%M_%S')}.log" logs_path=os.path.join(os.getcwd(),"logs",file_name) os.makedirs(logs_path,exist_ok=True) logs_file_path=os.path.join(logs_path,file_name) logging.basicConfig(filename=logs_file_path, ...
Hema9121/second-hema-ml-repo
src/logger.py
logger.py
py
500
python
en
code
0
github-code
36
27930609748
# Sum of even-valued fibonacci numbers less than or equal to 4 million def fibonacci(n): if n <= 1: return n else: return (fibonacci(n-1) + fibonacci(n-2)) total = 0 for i in range(34): f = fibonacci(i) if f % 2 == 0: total = total + f print...
vandervel/Project-Euler-Problems
solutions/problem2.py
problem2.py
py
328
python
en
code
0
github-code
36
13979863718
def read_inputs(input_file): with open(input_file, 'r') as f: lines = f.read().splitlines() data = [] for line in lines: l = line.split(" ") data.append([l[0], int(l[1])]) return data def pilot(input): horiz_pos = 0 depth = 0 aim = 0 for cmd in input: ...
brad-trantham/adventofcode2021
src/pilot.py
pilot.py
py
820
python
en
code
0
github-code
36
73971404584
from scripts.util.joystick import Joystick from carla_env import CarlaEnv from wrapped_carla_env import BiasedAction import time import carla import pygame import numpy as np class ManualInterface: def __init__(self, env: CarlaEnv): # create env self.env = env self.obs = None se...
imoneoi/carla_env
scripts/manual_control.py
manual_control.py
py
4,642
python
en
code
3
github-code
36
8785489698
import gymnasium as gym from IPython import display import matplotlib.pyplot as plt from utils.visualize import visualize_policy, visualize_q, visualize_model, visualize_v class JupyterRender(gym.Wrapper): def __init__(self, env): super().__init__(env) self.env = env def render(self, title='En...
moripiri/Reinforcement-Learning-on-FrozenLake
utils/wrapper.py
wrapper.py
py
2,250
python
en
code
4
github-code
36
34092269946
# To be filled by students import unittest import pandas as pd import sys import os from pandas._libs.missing import NA from pandas.util.testing import assert_frame_equal if os.path.abspath(".") not in sys.path: sys.path.append(os.path.abspath(".")) from src.data import Dataset class TestDataset(unittest.TestCase): ...
amy-panda/EDAWebApp
src/test/test_data.py
test_data.py
py
1,309
python
en
code
0
github-code
36
26579543800
''' Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character ...
msencer/leetcode-solutions
easy/python/Isomorphic.py
Isomorphic.py
py
1,159
python
en
code
5
github-code
36