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
12752730558
""" Convert the CSV file with the information of transfers into a directed graph that can be used for debugging. """ import pandas as pd import networkx as nx import matplotlib.pyplot as plt # Read CSV file csv_file = "../data/n_100_cifar10/transfers.csv" df = pd.read_csv(csv_file) # Create a directed graph G = nx.Di...
devos50/decentralized-learning
scripts/convert_transfers_to_graph.py
convert_transfers_to_graph.py
py
1,825
python
en
code
2
github-code
1
20162168775
import pygame import random from object import Object class Enemy(Object): def __init__(self, pos): super().__init__("cursor.png", pos) self.image = pygame.transform.scale(self.image, (70, 90)) self.accel = pygame.math.Vector2(0, 0) self.accelspeed = 0.1 def update(self): ...
mojd1234/ouch
enemy.py
enemy.py
py
1,216
python
en
code
0
github-code
1
11646312135
from gtts import gTTS import wikipedia as wiki import sys bad_sections = ['See also', 'References', 'External links', 'Gallery'] # removes the sections which wouldn't be useful in these formats def remove_extra(page): new_sections = page.sections for x in bad_sections: if x in new_sections...
ajsebastian/audioWiki
main.py
main.py
py
2,238
python
en
code
0
github-code
1
22671788315
##http://codeforces.com/contest/976/problem/E class Pet(object): def __init__(self, hp, dmg): self.hp = hp self.dmg = dmg def hp_sort(self): return (self.hp) def dmg_gain(self): return ((self.hp*2) - self.dmg) def WellPlayed(): n_pets, n_sp1, n_sp2 = map(int, input().strip().split()) ...
ece-mohammad/CodeForces
WellPlayed.py
WellPlayed.py
py
1,020
python
en
code
0
github-code
1
15685220785
from aiogram.dispatcher import Dispatcher, FSMContext from aiogram.types import CallbackQuery, Message from tgbot.misc import AddChannel from tgbot.models import Channels async def start_add_chanel(callback: CallbackQuery) -> None: await callback.message.edit_text('Отправте нам сылку на канал') await AddCha...
sardor86/something_telegram_bot
tgbot/handlers/admin/add_chanel.py
add_chanel.py
py
1,050
python
en
code
0
github-code
1
32996852891
from setuptools import find_packages, setup third_party_dependencies = ( "Flask", "flask-GraphQL", "graphene_sqlalchemy", "psycopg2", "SQLAlchemy", "requests", ) tests_require = ( "nose", ) setup( name="slack-server-python", version="0.1.0", author="Richard Shen", author_e...
ariia-git/slack-server-python
setup.py
setup.py
py
744
python
en
code
0
github-code
1
33427742555
from setuptools import setup, find_packages ######################################################################################################################## with open("README.rst", "r") as handler: LONG_DESC = handler.read() setup( author="Shapelets.io", author_email="dev@shapelets.io", name=...
shapelets/khiva-python
setup.py
setup.py
py
533
python
de
code
46
github-code
1
40531959843
"""序列化""" import json """JSON 如果我们要在不同的编程语言之间传递对象,就必须把对象序列化为标准格式,比如XML, 但更好的方法是序列化为JSON,因为JSON表示出来就是一个字符串,可以被所有语言读取, 也可以方便地存储到磁盘或者通过网络传输。 JSON不仅是标准格式,并且比XML更快,而且可以直接在Web页面中读取,非常方便。 JSON表示的对象就是标准的JavaScript语言的对象,JSON和Python内置的数据类型对应如下:""" """JSON类型 Python类型 {} dict [] list "string" str 1234.56 ...
zongrh/untitled_python3
python_io/python_serialize.py
python_serialize.py
py
2,229
python
zh
code
1
github-code
1
13894006197
import numpy as np import time import random import inspyred import cans.genetic_kwargs as kwargs from cans.plate import Plate from cans.cans_funcs import frexp_10, pickleable from cans.guesser import fit_imag_neigh from cans.model import CompModel, CompModelBC from cans.fitter import Fitter # Generator functions...
boo62/cans
cans/genetic.py
genetic.py
py
17,701
python
en
code
0
github-code
1
74136555873
import numpy as np import copy import cv2 import operator from scipy.ndimage import zoom from skimage import measure import pydensecrf.densecrf as dcrf from pydensecrf.utils import unary_from_labels, create_pairwise_bilateral, create_pairwise_gaussian def CRF(img,anno,gt_prob): gt, labels = np.unique(ann...
DQDH/Semantic_Image_Segmentation
make_localization_cues/generate_cues/tools/sod.py
sod.py
py
3,447
python
en
code
0
github-code
1
34804274654
""" Option menu for plant electrophysiological data analysis GUI """ # standard libraries import tkinter as tk __author__ = 'Kyle Vitatuas Lopin' class OptionMenu(tk.Menu): def __init__(self, master): tk.Menu.__init__(self, master=master) # Make the main menu to put all the submenus on ...
Zanith/Plant_analysis
option_menu_gui.py
option_menu_gui.py
py
1,548
python
en
code
0
github-code
1
2426105697
from odoo import models, api, fields def production_request_state_to_emoji(state): res = state if res == 'draft': res = '🏳️' elif res == 'to_approve': res = '⏳' elif res == 'approved': res = '🚧' elif res == 'done': res = '✅' elif res == 'cancel': res =...
decgroupe/odoo-addons-dec
stock_mrp_traceability/models/mrp_production_request.py
mrp_production_request.py
py
932
python
en
code
2
github-code
1
11636969673
import numpy as np class Perceptron: def __init__(self, N, alpha = 0.1): # N as number of columns of input matrix # alpha as learning rate # initialize the weight self.weight = np.random.randn(N + 1) / np.sqrt(N) self.alpha = alpha def activation(self, x): # Sig...
gabrielkunz/ai-projects
02_perceptron/perceptron.py
perceptron.py
py
1,414
python
en
code
0
github-code
1
27037413528
#!/usr/bin/env python3 import os from jmapc import Client, MailboxQueryFilterCondition, Ref from jmapc.methods import MailboxGet, MailboxGetResponse, MailboxQuery # Create and configure client client = Client.create_with_api_token( host=os.environ["JMAP_HOST"], api_token=os.environ["JMAP_API_TOKEN"] ) # Prepare...
smkent/jmapc
examples/mailbox.py
mailbox.py
py
1,809
python
en
code
19
github-code
1
7639807209
import pandas as pd import os import numpy as np import re import time import sys from fuzzywuzzy import fuzz import logging from static import * # To calculate: TF-IDF & Cosine Similarity from sklearn.feature_extraction.text import TfidfVectorizer from scipy.sparse import csr_matrix import sparse_dot_topn.sparse_do...
oportusgonzalo/product-deduplication
bivariate_comparison.py
bivariate_comparison.py
py
14,706
python
en
code
0
github-code
1
37820308114
import os import sys import time import shutil import random import socket import winreg from multiprocessing.spawn import freeze_support import psutil import logging import hashlib from contextlib import closing from http_server import start_web from configparser import ConfigParser from concurrent.futures import Pro...
nyacat/gms_auto
gms_patcher/main.py
main.py
py
7,199
python
en
code
0
github-code
1
41163200701
# house.py # a House contains Rooms from room import Room from roomnode import RoomNode class House: ''' a House contains multiple Room objects ''' def __init__(self): ''' create the house ''' start = Room("The Void", "You should never see this room...") kitchen = Room("Kitchen",...
biglerd7304/CSC221
Adventure/house.py
house.py
py
1,798
python
en
code
0
github-code
1
8658763067
""":cvar pip3 uninstall telebot pip3 uninstall PyTelegramBotAPI pip3 install pyTelegramBotAPI pip3 install --upgrade pyTelegramBotAPI """ try: import cv2 import PIL.Image as Image import io import base64 #from byte_array import byte_data import telebot import config import random fr...
Hammoudmsh/Information-security-Bot
main.py
main.py
py
21,191
python
en
code
0
github-code
1
26807453323
#!/usr/bin/env python3 import os import shutil import yt_dlp import requests from utils import logger from downloaders import DL_DIRECTORY log = logger.get_log(__name__) class Downloader(): def __init__(self): self._createTempDir() def cleanUp(self): for filename in os.listdir(DL_DIRECTORY)...
jsaddiction/TrailerTech
downloaders/downloader.py
downloader.py
py
4,543
python
en
code
10
github-code
1
25362261753
import pyclipper import math of = pyclipper.PyclipperOffset() def anyValidPath(paths): ''' checks the list of paths to find any non empty path ''' for pth in paths: if len(pth) > 0: return True return False def closePath(path): ''' closes the path if open by adding the point, des...
kreso-t/FreeCAD_Mod_Adaptive_Path
Adaptive/GeomUtils.py
GeomUtils.py
py
8,377
python
en
code
5
github-code
1
42183818903
""" Module for entities implemented using the switch platform (https://www.home-assistant.io/integrations/switch/). """ from __future__ import annotations import logging from typing import Any from hahomematic.const import TYPE_ACTION, HmPlatform import hahomematic.device as hm_device from hahomematic.entity import G...
Lemocin/hahomematic
hahomematic/platforms/switch.py
switch.py
py
1,379
python
en
code
null
github-code
1
18934781052
import argparse from typing import Any, Dict, List, Optional, Tuple, Union from nerf_turret_utils.number_utils import map_range def assert_in_int_range(value: int, min_val: int, max_val: int) -> int: """ Check whether an input integer value is within a certain range. Parameters: value: The input ...
anjrew/Autonomous-Nerf-Turret
components/ai_controller/ai_controller_utils.py
ai_controller_utils.py
py
5,722
python
en
code
3
github-code
1
22091972180
cont = 0 media = 0 while cont != 2: num = float(input()) if num >= 0 and num <= 10: cont += 1 media += num else: print('nota invalida') print(f'media = {media/2:.2f}')
JoaoAssalim/Beecrowd-Solution
Python/1117.py
1117.py
py
209
python
en
code
5
github-code
1
21246271231
''' Faça um programa que calcule o menor número divisível por cada um dos números de 1 a 20. ''' inicio = 1 fim = 20 # Substituir por 20. No enunciado, ele fala que pra 10, retorna 2520. valor = 1 num = fim cont = 0 while valor == 1: for i in range(inicio, fim+1): if num%i != 0: cont ...
higor-gomes93/curso_programacao_python_udemy
Sessão 6 - Exercícios/ex34.py
ex34.py
py
440
python
pt
code
0
github-code
1
15856858846
from ckiptagger import data_utils, construct_dictionary, WS, POS, NER def main(): ws = WS("./data") # word segmentation pos = POS("./data") # pos tagging # example sentences raw_sentences = [ '别只能想自己,想你周围的人。还有你,如果你是一个家庭的爸爸,你多想自己的孩子;如果你是青少年你多想自己的未来;那你可以禁烟了。', '别只想自己,要想...
tlamlert/chin-grammar-detection
code/ckipTagger_demo.py
ckipTagger_demo.py
py
1,001
python
en
code
1
github-code
1
36105481363
import gzip from tempfile import mkdtemp import os import numpy as np from astropy.io import fits def _make_file_for_testing(file_name='', **kwd): img = np.uint16(np.arange(100)) hdu = fits.PrimaryHDU(img) for k, v in kwd.items(): hdu.header[k] = v hdu.writeto(file_name) def directory_f...
astropy/ccdproc
ccdproc/utils/sample_directory.py
sample_directory.py
py
2,932
python
en
code
86
github-code
1
40420201014
from pathlib import Path import re from math import ceil import copy data_folder = Path(__file__).parent.resolve() file = data_folder / "input.txt" find_ingredients = re.compile(r"(\d+ \w+)+") class Ingredient: def __init__(self, name, quantity): self.name = name self.quantity = int(quantity) cl...
eirikhoe/advent-of-code
2019/14/sol.py
sol.py
py
4,470
python
en
code
0
github-code
1
45493379784
# -*- coding: utf-8 -*- """ DockWidget ----------------- begin: 2016-08-26 last: 2019-11 """ from pathlib import Path import sys from datetime import datetime from qgis.PyQt import QtGui, QtWidgets, uic from qgis.PyQt.QtCore import pyqtSignal #from qgis.PyQt.QtWidgets import QFileDialog # QWidget, QList...
Weathermann/radolan2map
classes/gui.py
gui.py
py
10,897
python
en
code
7
github-code
1
10182172033
# 1. Из колоды в 52 карты извлекаются случайным образом 4 карты. # a) Найти вероятность того, что все карты – крести. # б) Найти вероятность, что среди 4-х карт окажется хотя бы один туз. import main num_card = 52 num_clubs = 13 card = 4 all_clubs_probability = 1 for i in range(card): all_clubs_probability *= ...
DianaMaroz/Probability_homework_Moroz
home_work01/task01.py
task01.py
py
1,809
python
ru
code
0
github-code
1
10040110350
#The necessary imports import copy import functools import random import numpy as np import numba as nb class data: """ contains: __init__(self, positions, series) fill_in(self,position,values) """ def __init__(self, positions, series, positive_tests, ancestor, gender): """ ...
luca-scharr/IQ-Number-Test-Solver
classes.py
classes.py
py
2,252
python
en
code
0
github-code
1
27394255300
import numpy as np from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures from sklearn.metrics import mean_squared_error # 输入数据 X = np.array([[2022], [2021], [2020]]) # 年份 Y = np.array([442, 440, 458]) # 录取分数 best_degree = 1 # 最佳多项式次数 best_mse = float('inf') # 初始化最佳...
lyscf/gaokao-analytics
predict/predict_demo.py
predict_demo.py
py
1,771
python
en
code
6
github-code
1
15674221296
import sys import googlemaps from datetime import datetime,date from datetime import timedelta try: from config import config except: print("No existe el archivo config, stop") sys.exit() from helpers import helpers H=helpers() def groute(start,end,timet,mode="walking"): gmaps = googlemaps.Client(key...
carlitoselmago/streetPred
googledirections.py
googledirections.py
py
2,186
python
en
code
0
github-code
1
39276789702
############################################################ # Maya Dunlap # MENG 5930 - Modern Robotics # Prerequisite 2: Introduction to Python Programming # with Emphasis on Robotics Applications ############################################################ #################### CREATING DICTIONARIES ...
mfdunlap/meng5930_modern_robotics
Lab3_Prereq2/dictionaries.py
dictionaries.py
py
2,268
python
en
code
1
github-code
1
25009433106
# load HCP acqusition scheme from dmipy.data import saved_acquisition_schemes # ball stick and spherical mean ball-stick model from dmipy.signal_models import cylinder_models, gaussian_models from dmipy.core import modeling_framework from dmipy.core.modeling_framework import MultiCompartmentSphericalMeanModel, MultiCo...
PaddySlator/dmipy-bayesian
setup_models.py
setup_models.py
py
3,531
python
en
code
5
github-code
1
30906550732
import numpy as np import time import pandas from keras_retinanet.models import load_model from keras_retinanet.utils.image import preprocess_image, resize_image from osgeo import gdal from helpers import sliding_window from helpers import pixel2coord from helpers import non_max_suppression_fast (winW, winH, stepSi...
muhanur/detect-from-google
process.py
process.py
py
2,635
python
en
code
2
github-code
1
35430194614
import sys sys.stdin = open('input_11047.txt', 'r') N, M = map(int, input().split()) candy = [list(map(int, input().split())) for _ in range(N)] DP = [[0] * M for __ in range(N)] # 1 행 base case 설정 for c in range(M): if c == 0: DP[0][c] = candy[0][0] else: DP[0][c] = DP[0][c - 1] + candy[0][c] ...
wally-wally/TIL
02_algorithm/baekjoon/problem/10000~19999/11048.이동하기/11048.py
11048.py
py
599
python
en
code
32
github-code
1
43027922069
from django.urls import path from . import views urlpatterns = [ path('',views.index,name='index'), path('transactions',views.transactions,name='transactions'), path('updatePage',views.updatePage,name='updatePage'), path('update',views.update,name='update'), path('delete', views.delete, name="delet...
mathurtanmay02/Expensez
dashboard/urls.py
urls.py
py
436
python
en
code
0
github-code
1
70960308513
# 题意需要注意一个规则: # 每次只能移动两端的cow,且只能把cow放到另外两头cows中间 # min 比较简单,只能是0次,1次,2次(无论在何位置,最多两次就能放好) # max 滚刀肉 # 测试用例:1 7 9 # 1 6 7 # 1 5 6 # 1 4 5 # 1 3 4 # 1 2 3 # ans:5 import sys sys.stdin = open('herding.in', 'r') sys.stdout = open('herding.out', 'w') a,b,c = sorted(map(int, input().split())) if a+1==b and b+1==c: min_...
cola0405/usaco
bronze/19-2/1.py
1.py
py
612
python
zh
code
0
github-code
1
27287255173
import os import pandas as pd import pytest from pandas.testing import assert_frame_equal, assert_series_equal import cleanvision # To ensure backwards compatibility from cleanvision.imagelab import Imagelab class TestImagelabSaveLoad: def test_save(self, generate_local_dataset, tmp_path): imagelab = I...
cleanlab/cleanvision
tests/test_save_load.py
test_save_load.py
py
3,168
python
en
code
725
github-code
1
3288527771
from tkinter import Tk, RIGHT, BOTTOM, BOTH, TOP, StringVar, font, Text, DISABLED, Scrollbar, Y from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg import frameCreator def CreateWindow(window): #Main window and setting props wind...
gianlacasella/ScientificGraphingCalculator
windowCreator.py
windowCreator.py
py
4,583
python
en
code
4
github-code
1
37873244448
import os from flask import Flask from flask import render_template app = Flask(__name__) locations = [] @app.route('/') def home(): origin = '37.866197,+-122.252968' destination = '37.876031,+-122.258791' waypoints = 'International+House+Berkeley|Greek+Theater+Berkeley|GSPP+Berkeley' return render_tem...
ashirahattia/prov02website
__init__.py
__init__.py
py
659
python
en
code
0
github-code
1
33420603124
from django.conf import settings from django.conf.urls.defaults import patterns, include, url from cloudmailin.views import MailHandler # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() from mailpost.views import create_post, FakeEmailView from django.contrib.auth...
sharnett/BookerE
bookere/urls.py
urls.py
py
1,949
python
en
code
1
github-code
1
75065185953
__all__ = [ "process_epoch", ] import logging import sys from typing import NoReturn, Optional import torch import tqdm from torch import LongTensor, Tensor from . import _settings as settings from . import results from . import utils from .. import _config as config from .. import influence_utils from ..influen...
ZaydH/target_identification
fig01_cifar_vs_mnist/poison/tracin_utils/main.py
main.py
py
8,735
python
en
code
5
github-code
1
36300920616
import mysql import mysql.connector def insert_activity(activity): activity_name = activity["activity"] type = activity["type"] participants = activity["participants"] price = activity["price"] link = activity["link"] key = activity["key"] accessibility = activity["accessibility"] inse...
ayden521/src
db_service.py
db_service.py
py
1,447
python
en
code
0
github-code
1
10186879438
T = int(input()) for test_case in range(1, T + 1): N = int(input()) all_set = {str(i) for i in range(0, 10)} my_set = set() cnt = 0 idx = 1 while all_set != my_set: # 숫자를 문자로 바꿔서 비교 my_set = my_set | set(str(N*idx)) idx += 1 cnt += 1 print('#{} {}'.format(tes...
daeungdaeung/SWEA
D02/1288.py
1288.py
py
358
python
ko
code
0
github-code
1
4805265619
import torch.nn as nn import torch from src.losses.loss_functions import ( DJSLoss, ClassifLoss, DiscriminatorLoss, GeneratorLoss, ) from src.utils.custom_typing import ( DiscriminatorOutputs, ClassifierOutputs, EDIMOutputs, GenLosses, DiscrLosses, ClassifLosses, ) class EDIMLo...
MehdiZouitine/Learning-Disentangled-Representations-via-Mutual-Information-Estimation
src/losses/EDIM_loss.py
EDIM_loss.py
py
6,090
python
en
code
56
github-code
1
34842760480
# Evaluate Division: https://leetcode.com/problems/evaluate-division/ # You are given an array of variable pairs equations and an array of real numbers values, where equations[i] = [Ai, Bi] and values[i] represent the equation Ai / Bi = values[i]. Each Ai or Bi is a string that represents a single variable. # You are ...
KevinKnott/Coding-Review
Month 03/Week 04/Day 02/d.py
d.py
py
2,683
python
en
code
0
github-code
1
32601342276
#!/usr/bin/python3 from typing import List import json class Solution: def wordsTyping(self, sentence: List[str], rows: int, cols: int) -> int: nums = [len(d) for d in sentence] n = len(sentence) ans, row, col, j = 0, 0, 0, 0 while row < rows: col = 0 while...
negibokken/sandbox
leetcode/418_sentence_screen_fitting/main.py
main.py
py
1,007
python
en
code
0
github-code
1
10450580233
""" Модуль содержит настройки игры. """ FPS = 60 SCREEN_SIZE = 700, 800 BACKGROUND_COLOR = 0, 0, 0 # RGB SHOW_GAME_LEVEL_COUNTER_MAX_VALUE = 60 # начальные настройки PLAYER_LIVES = 3 PLAYER_SPEED = 4 ALIEN_SPEED = 0.4 ALIEN_SPEED_INCREMENT = 0.02 BULLET_SPEED = 8
darkus007/SpaceDefender
SpaceDefender/settings.py
settings.py
py
312
python
en
code
0
github-code
1
19294746004
#!/usr/bin/env python # coding: utf-8 # In[76]: import pyspark from pyspark import SparkContext from pyspark.sql import SQLContext from pyspark.conf import SparkConf from pyspark.sql.session import SparkSession # Need to make declaration in SparkContext() when submit pyspark job sc = SparkContext() spark = SQLConte...
rauldatascience/semi-structured-dwh
series_spark_job.py
series_spark_job.py
py
1,490
python
en
code
0
github-code
1
28413515227
import re import string from Transition import Transition class ProblemParser: states = {} transitions_by_current = {} transitions_by_next = {} initial_state = None goal_state = None actions_available = [] def __init__(self, file_path): file = open(file_path) text = file....
WonK67/mdp-planning
ProblemParser.py
ProblemParser.py
py
3,187
python
en
code
0
github-code
1
43849622923
from django import forms from apps.inicio.models import Actor class ActorForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ActorForm, self).__init__(*args, **kwargs) for i, (fname, field) in enumerate(self.fields.iteritems()): field.widget.attrs["class"] = field.widget...
JhonnySA/Videoteca
proyectos/videoteca/apps/inicio/formstotal/actor.py
actor.py
py
443
python
en
code
0
github-code
1
57138372
""" please place a file gmail_settings.py with two varialbes: GMAIL_ACCOUNT = "" GMAIL_PASSWORD = "" or set the environment variables GMAIL_ACCOUNT = "" GMAIL_PASSWORD = "" """ from settings import GMAIL_ACCOUNT, GMAIL_PASSWORD import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEBase impo...
c3h3/gmaildotpy
gmail/gmail.py
gmail.py
py
2,382
python
en
code
1
github-code
1
20980695431
#!/usr/bin/env python #coding:utf-8 """ task.py ~~~~~~~~~~~~~ :license: BSD, see LICENSE for more details. """ from flask import Blueprint,render_template,g,request from application.models import * from application.decorators import admin_required import json,logging,urllib from google.appengine.api import memcach...
itopidea/leepress
application/views/task.py
task.py
py
2,198
python
en
code
1
github-code
1
29055176966
import discord import asyncio from discord.ext import commands from datetime import datetime import math from config import * bot = commands.Bot(command_prefix=PREFIX, intents= discord.Intents.all()) bot.remove_command('help') @bot.event async def on_ready(): await bot.change_presence(status=discord.S...
respuNN/Discord-Presence-Tracker
log-bot.py
log-bot.py
py
2,758
python
en
code
0
github-code
1
71571421794
from typing import Iterable, Optional def main(data: Iterable[str]): nums = [int(line) for line in data] num_set = set(nums) def search(num: int) -> Optional[int]: target = 2020 - num if target in num_set: return target return None while nums: num1 = nums....
Lexicality/advent-of-code
src/aoc/y2020/day1.py
day1.py
py
620
python
en
code
0
github-code
1
35463765809
class FootInch: def __init__(self, foot, inch): self.foot = foot self.inch = inch self.inches = self.foot * 12 +self.inch def __str__(self): return "{}' {}''".format(self.foot, self.inch) def __add__(self, other): # Overload + x = self.inches + other.inches ...
ApexTone/Learn-Python
OOP/19OperatorOverloading.py
19OperatorOverloading.py
py
786
python
en
code
0
github-code
1
27089416527
import heapq N = int(input()) grid = [] edges = [[-1 for _ in range(N)] for _ in range(N)] for i in range(N): v = list(map(int, input().split())) grid.append(v) for i in range(N): for j in range(N): if i == j: continue a, b, c = grid[i] p, q, r = grid[j] edges[...
Intel-out-side/AtCoder
ABC180/e.py
e.py
py
1,156
python
en
code
0
github-code
1
34521671321
#!/usr/bin/python3 import os, tempfile, subprocess try: data = input(">").strip() if len(data) > 12: raise Exception("too large") with tempfile.TemporaryDirectory() as dirname: name = os.path.join(dirname, "user") with open(name, "w") as f: f.write(data) os.chmod(name, 0o500) ...
p4-team/ctf
2018-12-08-hxp/misc_elves/tiny_elves_fake.py
tiny_elves_fake.py
py
418
python
en
code
1,716
github-code
1
32261344928
import requests from bs4 import BeautifulSoup def get_article_body(url): # Send a GET request to the URL response = requests.get(url) # Check if the request was successful (status code 200) if response.status_code == 200: # Parse the HTML content of the page soup = BeautifulSoup(respon...
AlexOutis/NewsBot
soup.py
soup.py
py
1,242
python
en
code
0
github-code
1
34520883151
#!/usr/bin/env python3 import sys import random from cryptography.hazmat.primitives import serialization from cryptography.hazmat.backends import default_backend def ReadPrivateKey(filename): return serialization.load_pem_private_key( open(filename, 'rb').read(), password=None, backend=default_backend()) d...
p4-team/ctf
2018-06-23-google-ctf/crypto_secrecy/challenge.py
challenge.py
py
1,222
python
en
code
1,716
github-code
1
73934624355
"""General-purpose test script for image-to-image translation. Once you have trained your model with train.py, you can use this script to test the model. It will load a saved model from --checkpoints_dir and save the results to --results_dir. It first creates model and dataset given the option. It will hard-cod...
deltahue/DL-Project-2020
contrastive-unpaired-translation-master/test.py
test.py
py
6,810
python
en
code
0
github-code
1
22737252153
from os import link from bs4 import BeautifulSoup from command import Command import requests import discord # Every module has to have a command list commandList = [] commandList.append(Command("!score", "score", "Used to see the score of live games or the betting odds of an upcoming game.\nNote: if trying to use t...
ndamalas/Wild-Card-Bot
modules/sports.py
sports.py
py
8,361
python
en
code
4
github-code
1
72316129314
class Parent(): def __init__(self, last_name, eye_color): print ("Parent Constructor is called") self.last_name = last_name self.eye_color = eye_color class Child(Parent): def __init__(self, last_name, eye_color, number_of_toys): print("Child Constructor is called") ...
zsivany/udacity_python
inheritance.py
inheritance.py
py
603
python
en
code
0
github-code
1
71103471073
""" This is a custom pylinter. It will take the active git branch and compare it to our development branch, getting a list of files changed. It will then pylint the original files and compare it to the new files. Files must maintain a high pylint rating (9+ by default), and not introduce new problems. ver 0.1: - Us...
astraw38/lint
lint/linters/pylinter.py
pylinter.py
py
3,344
python
en
code
2
github-code
1
71934734434
# coding: utf-8 from zfits import FactFits from astropy.io import fits import matplotlib.pyplot as plt f = FactFits( "zfits/test_data/20160817_016.fits.fz", "zfits/test_data/20160817_030.drs.fits.gz" ) facttools = fits.open("zfits/test_data/20160817_016_calibrated.fits") e = f.get_data_calibrated(0) ft_e = factto...
fact-project/zfits
plot_comparison.py
plot_comparison.py
py
645
python
en
code
1
github-code
1
12967072447
import torch from termcolor import colored import torch.nn as nn import torch.nn.functional as F import torchvision import os def visual_representation(ckpt_path=None, use_3d=False): """ 2D encoder of pretrained 3D Visual representation """ if ckpt_path is None: ckpt_path = "checkpoints/videoae...
YanjieZe/rl3d
load_3d.py
load_3d.py
py
2,036
python
en
code
63
github-code
1
26253222037
import os from pathlib import Path from mne_bids import BIDSPath from seek_localize import read_dig_bids from seek_localize.bids import write_dig_bids # BIDS entities subject = 'la02' session = 'presurgery' acquisition = 'seeg' datatype = 'ieeg' space = 'fs' # paths to test files cwd = os.getcwd() bids_root = Path(...
adam2392/seek_localize
tests/test_bids.py
test_bids.py
py
2,516
python
en
code
2
github-code
1
24598567986
import hashlib from collections import OrderedDict class Perceiver: def __init__(self, perceptor): self.last_state = None self.perceptor = perceptor self.current_state = None self.keys = None self.sorted_keys(perceptor.get_state()) self.perceive(perceptor.get_state(...
DorAm1010/ReinforcementLearning_Q-Table
perceiver.py
perceiver.py
py
857
python
en
code
0
github-code
1
29926890398
import numpy as np import astropy.units as u from eventio import EventIOFile from eventio.simtel import MCShower from astropy.coordinates import SkyCoord, AltAz from astropy.time import Time __all__ = [ "find_nearest_bin", "create_angular_area_scaling", "poisson_likelihood_gaussian", "tensor_poisson_li...
ParsonsRD/template_builder
template_builder/utilities.py
utilities.py
py
5,442
python
en
code
5
github-code
1
71073872995
import func user, game, kepemilikan, history = func.load() logged = False user_id = '' role = '' func.clear() print('Selamat datang di antarmuka "Binomo"') while True : inpt = input('>>> ') func.clear() if logged == True: if role == 'user': if inpt == 'buy_game': ...
justinjya/TubesBNMO4
bnmo.py
bnmo.py
py
3,110
python
id
code
0
github-code
1
7425957587
import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('assets/CFPB Housing Data.csv') CENSUS = df['Census Tract'] LOAN = df['Loan Amount'] plt.scatter(CENSUS, LOAN) plt.xlabel("Census Tract") plt.ylabel("Loan Amount") plt.show() #print(df.head)
shacktemp/data_1_checks
kc_2.py
kc_2.py
py
266
python
en
code
0
github-code
1
73551679072
from io import BytesIO from io import TextIOWrapper from pathlib import Path from trimesh import load from trimesh.exchange.gltf import export_glb from trimesh.resolvers import FilePathResolver from viktor import File from viktor import UserException from viktor.core import Storage from viktor.core import ViktorContro...
y-macken/sample-grasshopper
app/grasshopper/controller.py
controller.py
py
4,515
python
en
code
0
github-code
1
8415907355
from django.db import models from django.contrib.auth.models import User class Project(models.Model): name = models.CharField(max_length=256, unique=True) description = models.TextField() class Dataset(models.Model): name = models.CharField(max_length=256) description = models.TextField() class Pa...
tcouch/dataset-app-django
data_classifier/projects/models.py
models.py
py
2,111
python
en
code
0
github-code
1
74075896353
class Cake: def __init__(self, name, price, ingredient): self.name = name self.price = price self.ingredient = ingredient class Shop: def __init__(self): self.ingredient = {} self.product = {} def buy_ingredient(self, buy_dict): for key, value in buy_dict.i...
deinm/heven_2021_coding_test
Q1_sample.py
Q1_sample.py
py
4,035
python
en
code
0
github-code
1
70882084515
''' This script works by constantly PINGing an IP address with a fake MAC address thereby spoofing the switch into thinking that you are the rightful owner of this MAC address. Therefore, (in theory) all the traffic coming from or to the MAC address will be sent to you. ''' from scapy.all import * import time ip = ...
ChopperCP/BlackHatPython
MAC Spoof/macspoof.py
macspoof.py
py
733
python
en
code
0
github-code
1
12942980985
# This simple script will save the current space center to a PDF in your current font folder. from mojo.UI import CurrentSpaceCenter, SpaceCenterToPDF import time import os font = CurrentFont() if font and CurrentSpaceCenter(): ufoPath = font.path ufoDirectory = os.path.dirname(ufoPath) fileName, fi...
asaumierdemers/cabRoboFontScripts
SpaceCenter/spaceCenterToPDF.py
spaceCenterToPDF.py
py
564
python
en
code
8
github-code
1
9061757350
minloc = np.argmin(np.abs(lyapmean_clv)) angle_un_s = np.zeros(t.shape[0]) corr_un_s = np.zeros(t.shape[0]) angle_1 = np.zeros((t.shape[0],M-1)) corr_1 = np.zeros((t.shape[0],M-1)) for tn,ti in enumerate(t): q1, _ = np.linalg.qr(CLV[tn,:,0:minloc,0], mode='reduced') q2, _ = np.linalg.qr(CLV[tn,:,minloc+1:,0], ...
seschu/lorenz96_python
lorenz96_anglesclvs.py
lorenz96_anglesclvs.py
py
792
python
en
code
1
github-code
1
40147795568
# -*- coding: utf-8 -*- # #Date: 2023-05-27 15:03:45 #Author: unknowwhite@outlook.com #WeChat: Ben_Xiaobai #LastEditTime: 2023-05-28 15:15:49 #FilePath: \ghost_sa_github_cgq\tools\update_shortcut.py # import sys sys.path.append('./') from component.db_op import do_tidb_exe,do_tidb_select from component.url_t...
white-shiro-bai/ghost_sa
tools/update_shortcut.py
update_shortcut.py
py
4,821
python
en
code
256
github-code
1
41827178704
import torch from torch import nn, einsum import numpy as np from einops import rearrange, repeat from einops.layers.torch import Rearrange def pair(t): return t if isinstance(t, tuple) else (t, t) class AddPositionEmbs(nn.Module): """向输入中添加可学习的位置嵌入模块 """ def __init__(self,inputs_positions=None): ...
Lp-wu/ViT-by-pytorch
ViT.py
ViT.py
py
12,536
python
en
code
0
github-code
1
18432972215
import pandas as pd import numpy as np records1 = pd.Series({'Name':'Claude', 'Class':'Biology','Age':35}) records2 = pd.Series({'Name':'Richard', 'Class':'Computer','Age':33}) records3 = pd.Series({'Name':'Runa', 'Class':'Economy','Age':34}) df = pd.DataFrame([records1,records2,records3],index=["school1","school2",...
Muhinyuzi/data_science
tests.py
tests.py
py
944
python
en
code
0
github-code
1
24220348512
# írd ki egy szám abszolút értékét n = int(input("szám?")) if n > 0: print(n) elif n < 0: print(-n) # válaszd ki a kisebb számot i = 10 j = 6 if i > j: print(j) elif j > i: print(i)
sylar1119/python-training
selection_advanced.py
selection_advanced.py
py
209
python
hu
code
0
github-code
1
1502163330
import unittest from pyapp import rotate_clockwise class RotateClockwise(unittest.TestCase): def setUp(self): self.rotate_clockwise = rotate_clockwise.rotate_clockwise def test_rotate_clockwise(self): m3 = [[1,2,3],[4,5,6],[7,8,9]] m4 = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] ...
ucsd-ets/python-docker-example
tests/rotate_clockwise_test.py
rotate_clockwise_test.py
py
941
python
en
code
0
github-code
1
73033920353
# -*- coding: utf-8 -*- ''' Simple returner for Couchbase. Optional configuration settings are listed below, along with sane defaults. couchbase.host: 'salt' couchbase.port: 8091 couchbase.bucket: 'salt' couchbase.skip_verify_views: False To use the couchbase returner, append '--return couchbase' to the salt co...
shineforever/ops
salt/salt/returners/couchbase_return.py
couchbase_return.py
py
7,730
python
en
code
9
github-code
1
71446573473
# 257. Binary Tree Paths # Easy # # 2497 # # 129 # # Add to List # # Share # Given the root of a binary tree, return all root-to-leaf paths in any order. # # A leaf is a node with no children. # # # # Example 1: # # # Input: root = [1,2,3,null,5] # Output: ["1->2->5","1->3"] # Example 2: # # Input: root = [1] # Output:...
laiqjafri/LeetCode
problems/00257_binary_tree_paths.py
00257_binary_tree_paths.py
py
1,200
python
en
code
0
github-code
1
43140850865
import os ### AWS AWS_REGION=os.environ.get("AWS_REGION", "ap-northeast-1") AWS_S3_ENDPOINT_URL=os.environ.get("AWS_S3_ENDPOINT_URL", None) AWS_S3_BUCKET_NAME=os.environ.get("AWS_S3_BUCKET_NAME", "nstpc") AWS_SQS_ENDPOINT_URL=os.environ.get("AWS_SQS_ENDPOINT_URL", None) AWS_SQS_TRANSFER_QUEUE_NAME=os.environ.get("AWS_...
horietakehiro/NstPlaycloud
backend/src/transfer/common/config.py
config.py
py
841
python
en
code
0
github-code
1
25333352243
def Insert(qArr): item = input("Enter element to be inserted") qArr.append(item) def Display(qArr): if(len(qArr)== 0): print("List is empty") else: print(qArr) def Delete(qArr): if(len(qArr)== 0): print("List is empty") else: qArr.remove(qArr[0]) def m...
sixthcodebrewer/GIT-IV-SEM
Python/TW1b.py
TW1b.py
py
684
python
en
code
0
github-code
1
42440455663
import telebot import sql_functions import urllib.request import json import alice_vars from alice_vars import bot import bot_functions def cat(message): chat_id = message.chat.id if sql_functions.check_user(alice_vars.db_name, 'Admins', chat_id): keyboard = alice_vars.keyboard_admin else: ...
adtya/the-alice-bot
easter_eggs.py
easter_eggs.py
py
1,655
python
en
code
2
github-code
1
25084814981
''' This class loads data from log files into data dictionaries that can be queried ''' import pandas as pd import time import pymongo import numpy as np import os import sys module_path = os.path.abspath(os.path.join('..')) if module_path not in sys.path: sys.path.append(module_path) from db.database ...
Husseinjd/DroneCrashDetection
dtloader/dataloader.py
dataloader.py
py
8,170
python
en
code
0
github-code
1
75114762274
from Query import * from FileReader import * from Select import * from Metadata import * from Data import * from LexerParser import * class Main: database={} md=Metadata() statement='' while statement!='quit': statement=input("SQL>") statement=statement.lower() #statement=statement.replace(","," ") if s...
klorenmtan/CS227Database
updatedb/Main.py
Main.py
py
599
python
en
code
0
github-code
1
31234711983
from itertools import permutations def solution(k, dungeons): answer = -1 dun_list = list(permutations(dungeons, len(dungeons))) for dun in dun_list: tired = k cnt = 0 for d in dun: if tired < d[0]: break else: tired -= d[...
earthssu/Programmers-Algorithm
Level2/피로도.py
피로도.py
py
401
python
en
code
0
github-code
1
24021067933
from cgitb import reset from http import HTTPStatus from flask import Flask, jsonify, request from flask_restful import Api, Resource, abort from flask_cors import CORS from util.math import math app = Flask(__name__) CORS(app) api = Api(app) # Create resource class Operation(Resource): ''' Perform operation...
seanfinnessy/SimpleCalculator
server/app.py
app.py
py
859
python
en
code
0
github-code
1
70205742114
''' 문제 그래프가 주어졌을 때, 그 그래프의 최소 스패닝 트리를 구하는 프로그램을 작성하시오. 최소 스패닝 트리는, 주어진 그래프의 모든 정점들을 연결하는 부분 그래프 중에서 그 가중치의 합이 최소인 트리를 말한다. 입력 첫째 줄에 정점의 개수 V(1 ≤ V ≤ 10,000)와 간선의 개수 E(1 ≤ E ≤ 100,000)가 주어진다. 다음 E개의 줄에는 각 간선에 대한 정보를 나타내는 세 정수 A, B, C가 주어진다. 이는 A번 정점과 B번 정점이 가중치 C인 간선으로 연결되어 있다는 의미이다. C는 음수일 수도 있으며, 절댓값이 1,000,000을 넘지 ...
hanseul-jeong/Coding_test
Backjoon/단계별로풀어보기/1197.py
1197.py
py
1,896
python
ko
code
0
github-code
1
5645433231
#maxiumb sum sub array or largest continuos sum def large_sum_cont(arr): if len(arr) == 0: return 0 max_sum = current_sum = arr[0] for num in arr[1:]: #skip first elemnt as it is alrady set current_sum = max(current_sum + num,num) max_sum = max(current_sum,max_sum) return ma...
ankitash18/Python_Practice
src/DataStructure/ArraysProblem/LargestContinueousSum.py
LargestContinueousSum.py
py
394
python
en
code
0
github-code
1
29111524576
from datetime import datetime from app.main.constants import (PLOT_SAVE_DIRECTORY, TIME_STAMP_FORMAT, PlotStyle) from app.main.models.wall import Wall from matplotlib import pyplot as plt ''' Description: This method contains helper functions for plotting and reporting. ''' class Rep...
nchalimba/building-plan-processor
app/main/reporting/reporting_helper.py
reporting_helper.py
py
2,197
python
en
code
0
github-code
1
10989295854
import unittest from towhee import pipe, ops from towhee.tools.graph_visualizer import GraphVisualizer # pylint: disable=protected-access class TestVisualizer(unittest.TestCase): """ Unit test for Visualizer. """ p0 = ( pipe.input('path') ) p1 = ( p0.map('path', 'path', lambda ...
towhee-io/towhee
tests/unittests/tools/test_graph_visualizer.py
test_graph_visualizer.py
py
740
python
en
code
2,843
github-code
1
20548988187
polydata = inputs[0] # version 0.1 ALL = 0b0 # This is not a bitmask BARYON = 0b10 DARK_MATTER = 0b1000000000 # This is not a bitmask BARYON_STAR = 0b100000 BARYON_WIND = 0b1000000 BARYON_STAR_FORMING = 0b10000000 DARK_AGN = 0b100000000 SE...
dbernhard-0x7CD/CosVis
paraview_scripts/particle_type_filter.py
particle_type_filter.py
py
1,440
python
en
code
0
github-code
1
17213380192
import argparse from math import pi, sin, asin import time from time import sleep import pvaccess as pva class UnionTest: def __init__(self, **kwargs): """ """ self.dataStruct = {'ArrayId': pva.UINT, 'Time': [pva.DOUBLE], 'value': pva....
epics-extensions/c2dataviewer
example/union.py
union.py
py
2,375
python
en
code
4
github-code
1
42944462130
import os, sys import re import fnmatch try: from teststatus import RESULTS_KEYWORDS except ImportError: from .teststatus import RESULTS_KEYWORDS class WordExpression: """ Takes a string consisting of words, parentheses, and the operators "and", "or", and "not". A word is any sequence of characters ...
rrdrake/vvtools
vvt/libvvtest/FilterExpressions.py
FilterExpressions.py
py
17,823
python
en
code
4
github-code
1
2599586486
import numpy as np import pandas as pd import matplotlib.pyplot as plt veriler = pd.read_csv('Ads_CTR_Optimisation.csv') import random N = 10000 d = 10 toplam = 0 secilenler = [] for n in range(0,N): ad = random.randrange(d) secilenler.append(ad) odul = veriler.values[n,ad] # verilerdeki n. satır = 1 is...
AyseErdanisman/MakineOgrenmesiKurs
7- Takviyeli Öğrenme (Reinforced Learning)/1- UCB (Üst Güven Sınırı)/Rasgele Örnekleme Yaklaşımı/random.py
random.py
py
398
python
tr
code
6
github-code
1