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
37080023999
def solution(n): answer = 0 n_3 = '' while n >= 3: n_3 += str(n % 3) n = n // 3 n_3 += str(n) a = 1 for i in n_3[::-1]: answer += int(i) * a a *= 3 return answer
JeonggonCho/algorithm
프로그래머스/lv1/68935. 3진법 뒤집기/3진법 뒤집기.py
3진법 뒤집기.py
py
222
python
en
code
0
github-code
6
38776144324
import os import webbrowser from shutil import copyfile import random import cv2 import pickle from moviepy.editor import * from flask import Flask, render_template, redirect, url_for, request from flaskwebgui import FlaskUI pickle_base = "C:\\Users\\AI\\AIVideo_Player\\data\\" image_directory = 'C:\\Users\...
olusegvn/VideoPlayer
engine/AIVideoPlayerBackend.py
AIVideoPlayerBackend.py
py
7,987
python
en
code
0
github-code
6
44042814684
import pandas as pd import re import graphlab as gl from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.decomposition import NMF from nltk.stem.wordnet import WordNetLemmatizer from helper import * class Registries(object): def __init__(self, filepath): self.filepath = filepath ...
vynguyent/Expecting-the-unexpected
Model/registries.py
registries.py
py
4,677
python
en
code
0
github-code
6
40254170266
# Configuration file for jupyterHub...there's probably a better way of doing this # Define the custom authentication class JupyterHub attempts to use c.JupyterHub.authenticator_class = 'oauthenticator.LocalODROAuthenticator' # Define the ODR server location odr_base_url = '[[ ENTER ODR SERVER BASEURL HERE ]]' c.ODROA...
OpenDataRepository/data-publisher
external/jupyterhub/jupyterhub_config.py
jupyterhub_config.py
py
2,732
python
en
code
14
github-code
6
36079540438
import atexit import json import logging import os # needs install import websocket from log.timeutil import * logger = logging.getLogger() logger.setLevel(logging.DEBUG) handler = logging.StreamHandler() handler.setLevel(logging.DEBUG) logger.addHandler(handler) import log.encoder try: import thread except I...
yasstake/mmf
log/bitws.py
bitws.py
py
6,831
python
en
code
1
github-code
6
35863858862
n = int(input()) s = input() ans = 0 ans_list = [] R_index = [] G_index = [] B_index = [] for i in range(n): if s[i] == 'R': R_index.append(i) elif s[i] == 'G': G_index.append(i) elif s[i] == 'B': B_index.append(i) ans = len(R_index) * len(G_index) * len(B_index) for j in range(1...
bokutotu/atcoder
ABC/162/d_.py
d_.py
py
589
python
en
code
0
github-code
6
39688600504
# 55. Jump Game # Time: O(len(nums)) # Space: O(1) class Solution: def canJump(self, nums: List[int]) -> bool: if len(nums)<=1: return True max_pos = nums[0] for index in range(len(nums)): max_pos = max(max_pos, index+nums[index]) if index>=max_pos: ...
cmattey/leetcode_problems
Python/lc_55_jump_game.py
lc_55_jump_game.py
py
435
python
en
code
4
github-code
6
73675802426
# This script fills the newly created point geofield # coding=utf-8 import os, sys proj_path = "/home/webuser/webapps/tigaserver/" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tigaserver_project.settings") sys.path.append(proj_path) os.chdir(proj_path) from django.core.wsgi import get_wsgi_application applicati...
Mosquito-Alert/mosquito_alert
util_scripts/create_aimsurv_experts.py
create_aimsurv_experts.py
py
5,288
python
en
code
6
github-code
6
24923567054
# -*- coding: utf-8 -*- """ Created on Mon Apr 1 18:19:38 2013 @author: matz """ import math import sys import cvtype import datatype import document import generator import package import test # abbreviations DT = test.Default() # calcHistWrapper dcl = document.Document() dclIncludes = ["<opencv2/core/core.hpp>"...
uboot/stromx-opencv
opencv/cvimgproc.py
cvimgproc.py
py
50,787
python
en
code
0
github-code
6
34711984830
# Coding Math Episode 2 # Display a sine wave import pygame import math import numpy as np pygame.init() RED = pygame.color.THECOLORS['red'] screen = pygame.display.set_mode((800, 600)) screen_rect = screen.get_rect() print(f"Size of the screen ({screen_rect.width}, {screen_rect.height})") screen_fonts = pygame.font...
piquesel/coding-math
ep2.py
ep2.py
py
1,397
python
en
code
0
github-code
6
5671705163
import random import uuid import pytest from aws.src.database.domain.dynamo_domain_objects import Tenure, HouseholdMember, TenuredAsset, Asset, AssetTenure, \ Patch, Person, PersonTenure def test_generates_tenure(tenure_dict: dict): tenure = Tenure.from_data(tenure_dict) assert isinstance(tenure, Tenur...
LBHackney-IT/mtfh-scripts
aws/tests/domain/test_dynamo_domain_objects.py
test_dynamo_domain_objects.py
py
8,127
python
en
code
0
github-code
6
22561698639
import os from bazelrio_gentool.utils import ( TEMPLATE_BASE_DIR, render_templates, ) from bazelrio_gentool.dependency_helpers import BaseDependencyWriterHelper def write_shared_root_files( module_directory, group, include_raspi_compiler=False, test_macos=True, include_windows_arm_compiler...
bzlmodRio/gentool
bazelrio_gentool/generate_shared_files.py
generate_shared_files.py
py
4,947
python
en
code
0
github-code
6
70281053308
from typing import Dict, Any, Union, Optional, List import torch import numpy as np from overrides import overrides from transformers import ViltProcessor from PIL import Image from allennlp.data.fields.field import DataArray from allennlp.data.fields.metadata_field import MetadataField class ViltField(MetadataFiel...
esteng/ambiguous_vqa
models/allennlp/data/fields/vilt_field.py
vilt_field.py
py
1,820
python
en
code
5
github-code
6
72014782588
class Graph: def __init__(self): self.dict = {} def addVertex(self, vertex): if vertex not in self.dict.keys(): self.dict[vertex] = [] return True return False def BFS(self, vertex): queue = [vertex] visited = [vertex] while queue: ...
jetunp/Practice
graph.py
graph.py
py
2,374
python
en
code
0
github-code
6
19700262291
''' NOTAS ":.0f" continua sendo valor float, apesar de mostrar um valor inteiro. A funcionalidade do int() e do trunc() é a mesma. Para arredondamento preciso de acordo com as regras matemáticas, usar round(). ''' def Inteiro(): n=float(input('Digite um número quebrado: ')) print('O valor transformado em inteir...
PR1905/Estudos-Python
desafio016 - Arredondamento e Menus.py
desafio016 - Arredondamento e Menus.py
py
1,380
python
pt
code
0
github-code
6
26095879865
import os import sys import torch import torch.nn.functional as F from torch.utils.tensorboard import SummaryWriter import Optimizer writer = SummaryWriter('./runs') grad_clip = 1.0 # clip gradients at an absolute value of save_prefix='' def clip_gradient(optimizer, grad_clip): # """ # 剪辑反向传播期间计算的梯度,以避免梯度爆炸。 # # p...
dubochao/CNN-sentiment-analysis
train.py
train.py
py
5,496
python
en
code
0
github-code
6
9369376357
import pyodbc cnxn = pyodbc.connect("DRIVER={ODBC Driver 17 for SQL Server};" "Server=DESKTOP-0A2HT13;" "Database=Databricks;" "UID=prajwal;" "PWD=Prajwal082;" "Trusted_Connection=yes;") cursor = cnxn.cursor...
Prajwal082/Main
postgres.py
postgres.py
py
814
python
en
code
0
github-code
6
11415062176
""" [ [ [ "M: How long have you been teaching in this middle school?", "W: For ten years. To be frank, I'm tired of teaching the same textbook for so long though I do enjoy being a teacher. I'm considering trying something new." ], [ { "questio...
nli-for-qa/conversion
qa2nli/qa_readers/dream.py
dream.py
py
4,251
python
en
code
1
github-code
6
22241072161
import torch import math import torch.nn as nn import torch.nn.functional as F from typing import List class Convolution(nn.Module): def __init__(self, in_ch, out_ch): super(Convolution, self).__init__() self.conv = nn.Sequential( nn.Conv2d(in_ch, out_ch, 3, 1, 1), nn.Batch...
yezi-66/IFE
unet_github/lib/Network.py
Network.py
py
7,331
python
en
code
26
github-code
6
19340985778
class EvenTree(object): def __init__(self, graph={}): self.graph = graph self.visited_node = [] self.total_forest = 0 def calculate_forest(self): for k,v in self.graph.items(): if k not in self.visited_node: key1 = k key_list = [k...
sunilchauhan/EvenTree
EvenTree.py
EvenTree.py
py
3,088
python
en
code
0
github-code
6
31272615348
# -*- coding: utf-8 -*- """Image transformation test meant to be run with pytest.""" import sys import pytest from confmap import ImageTransform from confmap import HyperbolicTiling sys.path.append("tests") def test_tilesAndTransform(): im=ImageTransform('./examples/sample1.png',0,data=None ...
FCoulombeau/confmap
tests/test_tilesAndTransforms.py
test_tilesAndTransforms.py
py
1,016
python
en
code
8
github-code
6
21666698024
#https://leetcode.com/problems/valid-sudoku/ class Solution: #Traverse the entire board once, and check each cell to see if there's another cell with the same value #in the same row, column, and square. Immediately return False if such a cell is found def isValidSudoku(self, board: list[list[str]]) -> bool...
Adam-1776/Practice
DSA/validSodoku/solution.py
solution.py
py
2,643
python
en
code
0
github-code
6
19575911667
def bissextile(): try: n = int(date.get()) if n%4==0 and (n//100)%4==0: tmp = "Is Bissextile" else: tmp = "Is Not Bissextile" txt.set(tmp) except: txt.set("The value isn't an integer") from tkinter import * from keyboard import * ...
OJddJO/NSI
bissextile.py
bissextile.py
py
934
python
en
code
0
github-code
6
28654892890
import re def day3_2(): with open("day3 - input.txt") as input: # with open("day3 - input1.txt") as input: # with open("day3 - input2.txt") as input: wires = [num.strip() for num in input.read().split()] wire_0 = wires[0].split(",") wire_1 = wires[1].split(",") wire_0_hor = [] wire_...
mellumfluous/AdventOfCode-2019
day3_2.py
day3_2.py
py
3,391
python
en
code
0
github-code
6
74142898108
from django.http import JsonResponse from django.shortcuts import render # Create your views here. from django.views.generic import View from django_redis import get_redis_connection from redis import StrictRedis from apps.goods.models import GoodsSKU from utils.common import LoginRequiredViewMixin, BaseCartView cl...
xmstu/dailyfresh2
dailyfresh/apps/cart/views.py
views.py
py
4,266
python
en
code
0
github-code
6
13042124891
# -*- coding: utf-8 -*- """ Created on Wed Dec 5 16:42:07 2018 @author: lud """ import matplotlib #import matplotlib.pyplot as plt matplotlib.use('TkAgg') from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg # implement the default mpl key bindings from matplotlib.backend_bases im...
stevenluda/cuboidPlotter
PlotCuboids.py
PlotCuboids.py
py
4,848
python
en
code
0
github-code
6
75177510266
import os import string import json from collections import namedtuple from sys import stdout from lex.oed.languagetaxonomy import LanguageTaxonomy from apps.tm.models import Lemma, Wordform, Definition, Language, ProperName from apps.tm.build import buildconfig LEMMA_FIELDS = buildconfig.LEMMA_FIELDS BlockData = nam...
necrop/wordrobot
apps/tm/build/lexicon/populatedb.py
populatedb.py
py
6,316
python
en
code
0
github-code
6
72623372987
#!/usr/bin/python # -*- coding: utf-8 -*- import mock import unittest from cloudshell.networking.brocade.cli.brocade_cli_handler import BrocadeCliHandler from cloudshell.networking.brocade.runners.brocade_state_runner import BrocadeStateRunner class TestBrocadeStateRunner(unittest.TestCase): def setUp(self): ...
QualiSystems/cloudshell-networking-brocade
tests/networking/brocade/runners/test_brocade_state_runner.py
test_brocade_state_runner.py
py
1,123
python
en
code
0
github-code
6
35153932961
age = input("What is your current age?") #4680 weeks in 90 years daysold = int(age) * 365 weeksold = int(age) * 52 monthsold = int(age) * 12 days = (365*90) - daysold weeks = 4680 - weeksold months = (12*90) - monthsold print("You have " + str(days) + " days, " + str(weeks) + " weeks, and " + str(months) + " month...
georgewood749/life_in_weeks_calculator
main.py
main.py
py
329
python
en
code
0
github-code
6
3277704581
import os from playwright.sync_api import sync_playwright key = "2731" os.makedirs(f"res/{key}", exist_ok=True) def main(): with sync_playwright() as p: browser = p.chromium.launch(headless=False, slow_mo= 5000) page = browser.new_page() page.goto("https://mri.cts-mrp.eu/portal/details?pro...
ReCodeRa/MRI_02
MRI/pw_down_sync_single_pdf.py
pw_down_sync_single_pdf.py
py
1,397
python
en
code
0
github-code
6
9736948830
import pickle import numpy as np import tensorflow as tf from sklearn.model_selection import train_test_split from sklearn.metrics import f1_score, accuracy_score from tensorflow import keras import matplotlib.pyplot as plt import tensorflow_addons as tfa import health_doc import matplotlib.pyplot as plt impo...
Szu-Chi/NLP_Final_Hierarchical_Transfer_Learning
BERT_multi_student.py
BERT_multi_student.py
py
4,067
python
en
code
0
github-code
6
25018394942
import datetime import hashlib import json from urllib.parse import urlparse import requests from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import padding import config import crypto class Blockchain: def __init__(self, key_path=None): # I...
ivana-dodik/Blockchain
EP -- zadatak 03/bez master key/blockchain.py
blockchain.py
py
6,409
python
en
code
0
github-code
6
70170907387
import numpy as np #%% def continuous_angle(x): last = 0 out = [] for angle in x: while angle < last-np.pi: angle += 2*np.pi while angle > last+np.pi: angle -= 2*np.pi last = angle out.append(angle) return np.array(out) #%% def dist2agent(da...
aliseyfi75/Autonomous-Driving
Codes/add_features.py
add_features.py
py
3,966
python
en
code
0
github-code
6
8381595021
from os import system import matplotlib import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib.collections import PolyCollection from mpl_toolkits.axes_grid import make_axes_locatable ############################################################################## # matplotlib configur...
ngctnnnn/DRL_Traffic-Signal-Control
sumo-rl/sumo/tools/contributed/sumopy/agilepy/lib_misc/matplotlibtools.py
matplotlibtools.py
py
1,749
python
en
code
17
github-code
6
4495169101
# -*- coding: utf-8 -*- """ Tests for CSV Normalizer """ import csv from io import StringIO from _pytest.capture import CaptureFixture from pytest_mock import MockFixture from src.csv_normalizer import main def test_outputs_normalized_csv(mocker: MockFixture, capsys: CaptureFixture[str]) -> None: with open("tes...
felipe-lee/csv_normalization
tests/test_csv_normalizer.py
test_csv_normalizer.py
py
2,253
python
en
code
0
github-code
6
33595739631
from flask import Flask, render_template, request, redirect, url_for from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import Base, Movie app = Flask(__name__) engine = create_engine('sqlite:///books-collection.db?check_same_thread=False') Base.metadata.bind = engine DB...
mrSlavik22mpeitop/stepik_selenium
flask_app_mpei.py
flask_app_mpei.py
py
2,261
python
en
code
0
github-code
6
29104292358
import numpy as np import pandas as pd np.random.seed(123) data = pd.DataFrame({'A': np.random.normal(0, 1, 50), 'B': np.random.normal(0, 1, 50), 'C': np.random.normal(0, 1, 50)}) # extract a single column from the DataFrame col = data['C'] threshold = 0.5 # filter out the ...
shifa309/-Deep-Learning-BWF-Shifa-Imran
Task15/Shifa_6.py
Shifa_6.py
py
653
python
en
code
0
github-code
6
16439987677
import math from datetime import datetime, timedelta from decimal import Decimal from financial.input import ( FinancialDataInput, FinancialStatisticsInput, NullFinancialDataInput, NullFinancialStatisticsInput, ) from financial.model import FinancialData, db class FinancialDataInputValidationService:...
pevenc12/python_assignment
financial/services.py
services.py
py
8,468
python
en
code
null
github-code
6
21480418170
from collections import namedtuple from functools import partial from itertools import count, groupby, zip_longest import bpy import numpy as np import re from .log import log, logd from .helpers import ( ensure_iterable, get_context, get_data_collection, get_layers_recursive, load_pro...
greisane/gret
operator.py
operator.py
py
21,651
python
en
code
298
github-code
6
12984152626
#7. Dadas dos listas enlazadas simples ya creadas (PTR1 y PTR2) ordenadas #ascendentemente, hacer un algoritmo que cree una tercera lista PTR3 #ordenada descendentemente con los elementos comunes de las dos listas. from List import List,Node PTR1 = List(list=[1,3,5,7,9,10]) PTR2 = List(list=[1,2,4,5,6,6,7,8,9,11]) ...
WaffleLovesCherries/ActividadListasEnlazadas
ClassList/Ejercicio7.py
Ejercicio7.py
py
466
python
es
code
0
github-code
6
10422164463
from __future__ import annotations import traceback from PySide6 import QtWidgets from randovania.games.prime2.patcher.claris_randomizer import ClarisRandomizerExportError def create_box_for_exception(val: Exception) -> QtWidgets.QMessageBox: box = QtWidgets.QMessageBox( QtWidgets.QMessageBox.Critical,...
randovania/randovania
randovania/gui/lib/error_message_box.py
error_message_box.py
py
1,513
python
en
code
165
github-code
6
32713874308
import scrapy class KistaSpider(scrapy.Spider): name = "kista" def start_requests(self): urls = ['https://www.hemnet.se/bostader?location_ids%5B%5D=473377&item_types%5B%5D=bostadsratt', ] for url in urls: yield scrapy.Request(url=url, callback=self.parse) def parse(se...
theone4ever/hemnet
hemnet/spiders/kista_bostadsratt_spider.py
kista_bostadsratt_spider.py
py
547
python
en
code
0
github-code
6
1482920507
# 从爬虫生成的Excel表格中读取数据并生成词云图 import os import sys import PIL import jieba import openpyxl import wordcloud import configparser import numpy as np import pandas as pd import matplotlib.pyplot as plt from collections import Counter from multiprocessing import Pool # 定义一些参数,参数的详细介绍见GitHub上的readme.md config_f...
AyaGuang/bilibili-Danmu-Crawler
102101430/generate_Cloud.py
generate_Cloud.py
py
5,425
python
zh
code
0
github-code
6
37731445163
import math from visual import* import Image dx=-50 dy=15 #Green comment block was originally user input for drop position, etc., #but was commented out, just not deleted. """ dx=-20 dy=input("please input the drop y position....recommand 10 or higher") w=input("if you know the bounce height press '1', if...
emayer2/Projects
Python Simulation/Ball Bounce.py
Ball Bounce.py
py
3,190
python
en
code
0
github-code
6
72474001467
import random import numpy as np from math import sqrt, log import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D x1_list = [] x2_list = [] y_list = [] counter = 0 def drawFunc(minX, minY, maxX, maxY, ax = None): #fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) #ax.set_xlabel('x1') ...
AlexSmirno/Learning
6 Семестр/Оптимизация/Lab_6_grad.py
Lab_6_grad.py
py
7,739
python
en
code
0
github-code
6
5838127346
from datetime import datetime from maico.sensor.stream import Confluence from maico.sensor.targets.human import Human from maico.sensor.targets.human_feature import MoveStatistics from maico.sensor.targets.first_action import FirstActionFeature import maico.sensor.streams.human_stream as hs class OneToManyStream(Conf...
tech-sketch/maico
maico/sensor/streams/one_to_many_stream.py
one_to_many_stream.py
py
2,289
python
en
code
0
github-code
6
74432928827
""" This file is part of Candela. Candela is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Candela is distributed in the hope that it will b...
emmettbutler/candela
candela/shell.py
shell.py
py
21,960
python
en
code
71
github-code
6
44782282173
import os import LuckyDraw import Quiz import hangman import time def main(): def title(): clear() print("\t\t_______Game Vault______\n\n") def clear(): os.system('cls') def delay(): time.sleep(1) status = True while(status!=False): ...
aswinachu02/Python-Projects
GameVault.py
GameVault.py
py
961
python
en
code
0
github-code
6
20723844837
# Exercise 1 : Family # 1. Create a class called Family and implement the following attributes: # - members: list of dictionaries with the following keys : name, age, gender and is_child (boolean). # - last_name : (string) # Initial members data: # [ # {'name':'Michael','age':35,'gender'...
Alex-Rabaev/DI-Bootcamp
week 3/Day 2/ExercisesXP/W3D2_ExerciseXP_plus.py
W3D2_ExerciseXP_plus.py
py
6,662
python
en
code
1
github-code
6
34836695873
#!/usr/bin/env python3 """Tools to define Templates. Templates are very similar to plugins, but use jinja to transform `.enbt` template files upon installation. """ __author__ = "Miguel Hernández-Cabronero" __since__ = "2021/08/01" import sys import argparse import inspect import os import glob import shutil import t...
miguelinux314/experiment-notebook
enb/plugins/template.py
template.py
py
9,816
python
en
code
3
github-code
6
71484280508
N, A, B, C, D = map(int, input().split()) S = "#{}#".format(input()) def reachable(start, end): now = start while now <= end: nex = now while nex <= end and S[now] == S[nex]: nex += 1 if S[now] == '#' and nex - now >= 2: return False now = nex return...
knuu/competitive-programming
atcoder/agc/agc034_a.py
agc034_a.py
py
604
python
en
code
1
github-code
6
1090949893
from keras.applications import resnet50 from keras.applications import mobilenetv2 from keras.applications import mobilenet from keras.applications import vgg19 # from keras_squeezenet import SqueezeNet import conv.networks.get_vgg16_cifar10 as gvc import conv.networks.gen_conv_net as gcn # import conv.networks.Mobile...
nitthilan/ml_tutorials
conv/networks/get_all_imagenet.py
get_all_imagenet.py
py
11,760
python
en
code
0
github-code
6
22618188640
# encoding: utf-8 # pylint: disable=redefined-outer-name,missing-docstring import pytest from tests import utils from app import create_app @pytest.yield_fixture(scope='session') def flask_app(): app = create_app(flask_config='testing') from app.extensions import db with app.app_context(): db.c...
DurandA/pokemon-battle-api
tests/conftest.py
conftest.py
py
2,085
python
en
code
3
github-code
6
30793951295
'''Instead of giving some hard coded values and changing it later in the entire code which will be very time consuming and troublesome we are going to create a class which will manage all the settings parameter so even if we have to change later we only need to make changes in this file ''' class settings:...
shreyashkhurud123/Alien_Invasion_Python
Alien_Invasion/Alien_Invasion/settings.py
settings.py
py
1,628
python
en
code
0
github-code
6
29534323943
from scipy.interpolate import Rbf # radial basis functions import matplotlib.pyplot as plt import numpy as np x = [1555,1203,568,1098,397,564,1445,337,1658,1517,948] y = [860,206,1097,425,594,614,553,917,693,469,306] x = [0.9, 0.6, 0.1, 0.5, 0.04, 0.1, 0.82, 0.0, 1.0, 0.89, 0.46] y = [0.73, 0.0, 1.0, 0.24, 0.43, 0.45...
twilly27/DatacomProject
Project/HeatMapping.py
HeatMapping.py
py
795
python
en
code
0
github-code
6
12611135709
import pytest from utils import * from fireplace.exceptions import GameOver LORD_JARAXXUS = "EX1_323" LORD_JARAXXUS_HERO = "EX1_323h" LORD_JARAXXUS_WEAPON = "EX1_323w" INFERNO = "EX1_tk33" INFERNO_TOKEN = "EX1_tk34" def test_jaraxxus(): game = prepare_game(CardClass.WARRIOR, CardClass.WARRIOR) game.player1.hero....
jleclanche/fireplace
tests/test_jaraxxus.py
test_jaraxxus.py
py
3,302
python
en
code
645
github-code
6
44855982856
def stringToInt(s): multiply = 1 if s[0] == '-': multiply = -1 s = s[1:] mul = len(s)-1 num = 0 for ch in s: num = num + (10 ** mul) * (ord(ch)-48) mul = mul - 1 num = num * multiply return num print(stringToInt("-0000045637560003330003"))
sandeepjoshi1910/Algorithms-and-Data-Structures
stoi.py
stoi.py
py
319
python
en
code
0
github-code
6
10862974654
""" Run the model end to end """ import argparse import sys import torch from pathlib import Path import pytorch_lightning as pl from pytorch_lightning.callbacks.early_stopping import EarlyStopping from pytorch_lightning.callbacks.model_checkpoint import ModelCheckpoint from smallteacher.data import DataModule, train...
SmallRobotCompany/smallteacher
smallssd/end_to_end.py
end_to_end.py
py
4,407
python
en
code
5
github-code
6
71060757628
import turtle from math import sin, cos, pi r = 200 inc = 2*pi/100 t = 0 n = 1.5 for i in range (100): x1 = r * sin(t) y1 = r * cos(t) x2 = r * sin(t+n) y2 = r * cos(t+n) turtle.penup() turtle.goto(x1, y1) turtle.pendown() turtle.goto(x2, y2) t += inc
Camilotk/python-pooii
tutoriais/desenho.py
desenho.py
py
290
python
en
code
0
github-code
6
69809912829
import threading from datetime import datetime from time import sleep from random import randint from queue import Queue # loops = [4,2] # def loop(nloop,nsec): # print('start loop',nloop,'at:',datetime.now()) # sleep(nsec) # print('loop',nloop,'done at:',datetime.now()) # def main(): # print('starting at:',...
algebrachan/pythonStudy
py_by_myself/study_test/thread_test.py
thread_test.py
py
2,433
python
en
code
0
github-code
6
2254678822
import urllib from xml.dom import minidom import re def buildResponse(node_list): return_string = "" for i in node_list: return_string = return_string + i + "\n" return return_string.strip() def buildURL(key, word): return "http://www.dictionaryapi.com/api/v1/references/collegiate/xml/" + word + "?key=" + key ...
sarthfrey/Texty
dictionaryDef.py
dictionaryDef.py
py
819
python
en
code
9
github-code
6
35031034974
from app.models.player import * import random player1 = Player("PLayer 1") player2 = Player("Player 2") players = [player1, player2] def one_player(name1): player1.name = name1 player2.name = "Computer" def add_players(name1, name2): player1.name = name1 player2.name = name2 def random_move(self): ...
linseycurrie/Wk2-HW-RockPaperScissors-Flask
app/models/play_game.py
play_game.py
py
953
python
en
code
0
github-code
6
6397362139
import sys from math import sqrt from itertools import compress # 利用byte求质数 def get_primes_3(n): """ Returns a list of primes < n for n > 2 """ sieve = bytearray([True]) * (n // 2) for i in range(3, int(n ** 0.5) + 1, 2): if sieve[i // 2]: sieve[i * i // 2::i] = bytearray((n - i * i -...
YuanG1944/COMP9021_19T3_ALL
9021 Python/review/mid-examples/2017S1_Sol/5.py
5.py
py
1,735
python
en
code
1
github-code
6
20495057760
import sys, iptc, re, socket single_options = False predesigned_rules = ['BlockIncomingSSH', 'BlockOutgoingSSH', 'BlockAllSSH', 'BlockIncomingHTTP', 'BlockIncomingHTTPS',\ 'BlockIncomingPing', 'BlockInvalidPackets', 'BlockSYNFlooding', 'BlockXMASAttack', 'ForceSYNPackets'] accepted_protocols = ['ah','egp','esp'...
syerbes/myFirewall
myFirewall.py
myFirewall.py
py
21,668
python
en
code
0
github-code
6
28153479584
import src.fileIO as io import src.chris as chris import src.filepaths as fp import src.analysis as anal import src.plotting as plot from pathlib import Path def batch_calculate_peak_wavelength(parent_directory, batch_name, file_paths, ...
jm1261/PeakFinder
batch_peakfinder.py
batch_peakfinder.py
py
4,669
python
en
code
0
github-code
6
15206966945
# -*- coding: utf-8 -*- """ Ventricular tachycardia, ventricular bigeminy, Atrial fibrillation, Atrial fibrillation, Ventricular trigeminy, Ventricular escape , Normal sinus rhythm, Sinus arrhythmia, Ventricular couplet """ import tkinter as tk import scipy.io as sio from PIL import Image, ImageTk class App(...
Sandovaljuan99/INMEDUMG
Cardiac arrhythmia simulator/IGPY.py
IGPY.py
py
4,934
python
es
code
1
github-code
6
73652351869
# 给你一个字符串 s 和一个整数 k 。你可以选择字符串中的任一字符,并将其更改为任何其他大写英文字符。该操作最多可执行 k 次。 # 在执行上述操作后,返回包含相同字母的最长子字符串的长度。 class Solution(object): def characterReplacement(self, s, k): """ :type s: str :type k: int :rtype: int """ num = [0] * 26 left = right = maxn = 0 n = l...
xxxxlc/leetcode
array/characterReplacement.py
characterReplacement.py
py
876
python
zh
code
0
github-code
6
7946323385
from flaskr.db import get_db no_of_existing_accounts = 3 def test_create_account(client, app): expected_account = { "account_number": "4", "account_name": "Brukskonto", "account_nickname": "Min Brukskonto", "account_owner_name": "Ola Nordmann", "account_type": "DEPOSIT", ...
eilidht/Accounts
tests/test_account.py
test_account.py
py
4,629
python
en
code
0
github-code
6
8764441086
class animal: leg=4 @staticmethod def sum(x,y): sum=x+y print(sum) @staticmethod def mul(x,y): mul=x*y print(mul) @classmethod def walk(cls,name): print(f"{name} has {animal.leg} leg") @classmethod def evenodd(cls,num): if num%2==0: print(f"{num} is even number") else: print("f{num} is odd ...
divyansh251/basic-oops-concepts
oops4.py
oops4.py
py
409
python
en
code
0
github-code
6
1040065850
import numpy as np import pandas as pd import operator from sklearn import preprocessing data = pd.read_csv("data.csv",header=None) min_max_scaler = preprocessing.MinMaxScaler(feature_range=(0,1)) def classify(v,k,distance): target_values = data.iloc[:,-1] nearest_neighbors = knn(data,k,v,distance) classificat...
egjimenezg/DataAnalysis
knn/knn.py
knn.py
py
2,364
python
en
code
0
github-code
6
16404587226
from ksz.src import plot import matplotlib.pyplot as plt data_path_list = [ '/data/ycli/dr12/galaxy_DR12v5_LOWZ_North_TOT_wMASS.dat', '/data/ycli/dr12/galaxy_DR12v5_LOWZ_South_TOT_wMASS.dat', '/data/ycli/dr12/galaxy_DR12v5_CMASS_North_TOT_wMASS.dat', '/data/ycli/dr12/galaxy_DR12v5_CMASS...
YichaoLi/pksz
plot_pipe/plot_stellar_mass.py
plot_stellar_mass.py
py
1,401
python
en
code
0
github-code
6
28610424615
from __future__ import annotations import json import subprocess import collections import concurrent.futures from os import path, system from datetime import datetime root_path = path.abspath("src/test_cases/UI") report_path = path.abspath("src/reports/concurrent_test_logs") def generate_pytest_commands(): conf...
huymapmap40/pytest_automation
src/config/parallel_test/run_parallel_test.py
run_parallel_test.py
py
2,068
python
en
code
1
github-code
6
13749339342
import ROOT #from root_numpy import root2array, root2rec, tree2rec import pylab,numpy,pickle import matplotlib pylab.rcParams['font.size'] = 14.0 pylab.rcParams['axes.labelsize']=18.0 pylab.rcParams['axes.titlesize']=20.0 pylab.rcParams['ytick.labelsize']='large' pylab.rcParams['xtick.labelsize']='large' pylab.rcParam...
daughjd/bashscripts
PaperPlotter.py
PaperPlotter.py
py
11,938
python
en
code
0
github-code
6
6671408695
from netpyne import specs def set_netParams(Nin, Pops, Exc_ThtoAll, Exc_AlltoAll, Inh_AlltoAll): netParams = specs.NetParams() # object of class NetParams to store the network parameters netParams.defaultThreshold = 0.0 ## Cell parameters/rules GenericCell = {'secs': {}} GenericCell['secs']['som...
DepartmentofNeurophysiology/Cortical-representation-of-touch-in-silico-NetPyne
netParams.py
netParams.py
py
3,439
python
en
code
1
github-code
6
10528777232
import pygame from pygame.sprite import Sprite class Tiro(Sprite): """Class para manipular os tiros disparados pela nave""" def __init__(self, ik_game): """Cria um disparo na posição atual da nave""" super().__init__() self.screen = ik_game.screen self.configuracoes =...
ruansmachado/Invasao_Klingon
tiro.py
tiro.py
py
1,130
python
pt
code
0
github-code
6
26345275028
dct = {} while True: inp = input() if inp == "drop the media": break command = inp.split(" ")[0] post_name = inp.split(" ")[1] if command == "post": dct[post_name] = {"Likes": 0, "Dislikes": 0, "Comments": {}} elif command == "like": dct[post_name]["Likes"] += 1 ...
YovchoGandjurov/Python-Fundamentals
02. Lists and Dictionaries/Dictionaries/05.Social_Media_Posts.py
05.Social_Media_Posts.py
py
856
python
en
code
1
github-code
6
71548544188
import math import torch import numpy as np import torch.nn as nn import torch.nn.functional as F from torch.nn import init from collections import OrderedDict from modules import CompactBasicBlock, BasicBlock, Bottleneck, DAPPM, segmenthead, GhostBottleneck bn_mom = 0.1 BatchNorm2d = nn.BatchNorm2d class CompactDu...
himlen1990/cddrnet
utils/speed_test/cddrnet_eval_speed.py
cddrnet_eval_speed.py
py
8,667
python
en
code
1
github-code
6
9637017975
from selenium import webdriver from selenium.webdriver.edge.service import Service from selenium.webdriver.common.by import By from time import sleep class InternetSpeed: def __init__(self, edge_driver_path): self.driver = webdriver.Edge(service=Service(edge_driver_path)) self.down = 0 ...
na-lin/100-days-of-Python
Day51_Internet-Speed-Twitter-Complaint-Bot/internet_speed.py
internet_speed.py
py
1,309
python
en
code
0
github-code
6
74658795066
from lindertree.lsystem import * from lindertree.turtle_interprate import * axiom = string_to_symbols('!(1)F(5)X') constants = {'w':1.4, 'e':1.6, 'a':1.1} width_rule = Rule.from_string('!(x)', '!(x*w)', constants) elongation_rule = Rule.from_string('F(x)', 'F(x*e)', constants) angle_rule1 = Rule.from_string('+(x)', '+...
valentinlageard/lindertree
example_parametric.py
example_parametric.py
py
807
python
en
code
1
github-code
6
28039146623
#! /usr/bin/env python3 __author__ = 'Amirhossein Kargaran 9429523 ' import os import sys import socket import pickle import select import signal import threading import time from threading import Thread from datetime import datetime # Local modules from APIs.logging import Log from APIs.logging import Color from AP...
kargaranamir/Operating-Systems
Project II/Code/chatServer.py
chatServer.py
py
14,141
python
en
code
0
github-code
6
9754918030
import click import unittest from click.testing import CliRunner from doodledashboard.notifications import TextNotification from parameterized import parameterized from sketchingdev.console import ConsoleDisplay from tests.sketchingdev.terminal.ascii_terminal import AsciiTerminal class TestConsoleDisplayWithText(uni...
SketchingDev/Doodle-Dashboard-Display-Console
tests/sketchingdev/test_text_notification.py
test_text_notification.py
py
1,699
python
en
code
0
github-code
6
29050546230
from etl import ETL import os DATASET_PATH = "/home/login/datasets" DATASET_NAME = "CIMA" DATASET_SIZE = 377 validation_size = 0.2 validation_size = int(DATASET_SIZE * validation_size) validation_etl = ETL("/home/login/datasets", [], size=validation_size) validation_etl.load(DATASET_NAME) validation_path = os.path....
eskarpnes/anomove
etl/validation_split.py
validation_split.py
py
765
python
en
code
0
github-code
6
28558999835
from helper import is_prime, find_prime_factors, int_list_product def smallest_multiple(n): ls = list() for i in range(2,n): pf = find_prime_factors(i) for l in ls: for f in pf: if(l == f): pf.remove(f) break for f in ...
thejefftrent/ProjectEuler.py
5.py
5.py
py
436
python
en
code
0
github-code
6
27070910668
import datetime as dt import random import pytest from scheduler import Scheduler, SchedulerError from scheduler.base.definition import JobType from scheduler.threading.job import Job from ...helpers import foo @pytest.mark.parametrize( "empty_set", [ False, True, ], ) @pytest.mark.para...
DigonIO/scheduler
tests/threading/scheduler/test_sch_get_jobs.py
test_sch_get_jobs.py
py
2,720
python
en
code
51
github-code
6
25476219530
import random suits = ("Hearts", "Spades", "Diamonds", "Clubs") tarotSuits = ("Swords", "Cups", "Wands", "Coins") names = ("Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King") tarotNames = ("Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",...
Malbrett/Nettlebot
cards.py
cards.py
py
3,490
python
en
code
0
github-code
6
35035790893
import csv import json import numpy as np from tabulate import tabulate import matplotlib.pyplot as plt from math import ceil from wand.image import Image as WImage from subprocess import Popen def make_json(csvFilePath,keyName,alldata): # create a dictionary data = {} # Open a csv re...
miccec/ExomePipeline
interactPlots.py
interactPlots.py
py
4,422
python
en
code
0
github-code
6
968977222
import pyodbc import pandas as pd # Connection steps to the server from OnlineBankingPortalCSV2_code import Accounts, Customer server = 'LAPTOP-SELQSNPH' database = 'sai' username = 'maram' password = 'dima2k21' cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID=...
divyamaram/Database-Managment-systems
OnlineBankingPortalCSV3_code.py
OnlineBankingPortalCSV3_code.py
py
4,255
python
en
code
0
github-code
6
10480951725
accounts = [[1,2,3],[2,3,4],[10,12]] c = [] n = 0 for i in accounts: n = 0 for j in i: n = j + n c.append(n) print(c) c.sort(reverse=True) a = c print(a) print(a[0])
SmolinIvan/Ivan_Project
Training/leetcode/sample2.py
sample2.py
py
202
python
en
code
0
github-code
6
31932908131
from pyspark.ml.classification import NaiveBayes from pyspark.ml.evaluation import MulticlassClassificationEvaluator from pyspark.sql import SparkSession spark = SparkSession.builder.getOrCreate() spark.sparkContext.setLogLevel("ERROR") data = spark.read.format("libsvm").load("file:///usr/lib/spark/data/mllib/sample_...
geoffreylink/Projects
07 Machine Learning/SparkML/sparkML_CL_naivebayes.py
sparkML_CL_naivebayes.py
py
789
python
en
code
9
github-code
6
41466182049
num=int(input('Enter a Number : ')) copy=num count=len(str(num)) add=0 while(num!=0): rem=num%10 add+=rem**count num//=10 if(copy==add): print('Armstrong number') else: print('Not armstrong number')
Kanchana5/armstrong-number
Armstrong1.py
Armstrong1.py
py
219
python
en
code
0
github-code
6
11948273979
#!/usr/bin/python3.8 # -*- coding: utf-8 -*- # # SuperDrive # a live processing capable, clean(-ish) implementation of lane & # path detection based on comma.ai's SuperCombo neural network model # # @NamoDev # # ============================================================================ # # Parse arguments import os...
kaishijeng/SuperDrive
drive.py
drive.py
py
8,715
python
en
code
3
github-code
6
71361629947
from turtle import Turtle FONT = ("Courier", 24, "normal") class Scoreboard(Turtle): def __init__(self): super(Scoreboard, self).__init__() self.hideturtle() self.color('black') self.penup() self.level = 0 with open('data.txt') as high_score: self.high_...
Benji918/turtle-crossing-game
scoreboard.py
scoreboard.py
py
923
python
en
code
0
github-code
6
4583110582
from __future__ import division from copy import deepcopy import torch from torch.autograd import Variable import torch.nn.functional as F device = torch.device("cuda" if torch.cuda.is_available() else "cpu") import numpy as np import torch def average_rule(keys, Temp_state_dict, neighbors): aggr_state_dict = {...
cbhowmic/resilient-adaptive-RL
aggregateMethods.py
aggregateMethods.py
py
9,022
python
en
code
0
github-code
6
28160427846
import asyncio from time import time from httpx import RequestError from loguru import logger from src.client import IteriosApiClient from src.exceptions import FailedResponseError from src.helpers import ( get_random_country, get_random_dep_city, get_search_start_payload, get_timing_results, setup_logger, ) ...
qwanysh/iterios-stress
start_search.py
start_search.py
py
2,281
python
en
code
0
github-code
6
27537219474
import objreader def hexDig2hexStr(hexDig, length): hexDig = hexDig.upper() hexStr = hexDig[2:] # 0xFFFFF6 => FFFFF6 for i in range(0, length - len(hexStr)): # 位數不足補零 hexStr = '0' + hexStr return hexStr # Hex String => Dec Int Digit def hexStr2decDig(hexStr, bit...
Yellow-Shadow/SICXE
LinkingLoader2021/LinkingLoader/pass2.py
pass2.py
py
4,795
python
en
code
0
github-code
6
53879462
from zohocrmsdk.src.com.zoho.api.authenticator import OAuthToken from zohocrmsdk.src.com.zoho.crm.api import Initializer from zohocrmsdk.src.com.zoho.crm.api.business_hours import BusinessHoursOperations, BodyWrapper, BusinessHours, \ BreakHoursCustomTiming, ActionWrapper, BusinessHoursCreated, APIException from zo...
zoho/zohocrm-python-sdk-5.0
versions/1.0.0/samples/business_hours/UpdateBusinessHours.py
UpdateBusinessHours.py
py
4,189
python
en
code
0
github-code
6
25538067967
import streamlit as st import pandas as pd import plotly.express as px import matplotlib.pyplot as plt import seaborn as sns sns.set_style("darkgrid") hide_st_style = """ <style> footer {visibility: hidden;} #MainMenu {visibility: hidden;} header {visi...
Somnathpaul/Olympic-data-analysis
main.py
main.py
py
6,253
python
en
code
0
github-code
6
31238312514
# 조건을 활용한 리스트 내포 # 리스트를 선언 array = ["사과", "자두", "초콜릿", "바나나", "체리"] output = [fruit for fruit in array if fruit != "초콜릿"] """ array의 요소를 fruit이라고 할 때 초콜릿이 아닌 fruit으로 리스트를 재조합 실행함년 초콜릿을 제외한 요소만 모인 리스트를 만든다 if구문을 포함한 리스트 내포는 다음과 같은 형태로 사용 리스트 이름 = [표현식 for 반복자 in 반복할 수 있는 것 if 조건문] """ # 출력 print(output)
DreamisSleep/pySelf
chap4/array_comprehensions.py
array_comprehensions.py
py
555
python
ko
code
0
github-code
6
37213848810
from collections import Counter, defaultdict import pandas as pd import os import csv import json # get phoneme features from PHOIBLE # note the path is resolved-phoible.csv that is corrected for mismatches between phonemes in PHOIBLE and the XPF Corpus phoneme_features = pd.read_csv("Data/resolved-phoible.csv") phone...
daniela-wiepert/XPF-soft-constraints
FD/Code/ngram_model_fd.py
ngram_model_fd.py
py
9,512
python
en
code
0
github-code
6
5355823795
R=[-1,1,0,0] C=[0,0,-1,1] from heapq import heappush,heappop def dijkstra(): x=[(0,0)] dis[0][0]=mat[0][0] while(True): boo=False h=[] for i in x: a=i[0];b=i[1] for j in range(4): r=a+R[j] c=b+C[j] if(0<=r<n and ...
avikram553/Basics-of-Python
Graph Algo/Dijkstra_on_matrix.py
Dijkstra_on_matrix.py
py
1,018
python
en
code
0
github-code
6