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
32961592369
import base64 import json import re from datetime import datetime, timezone, timedelta from typing import Optional, Any from .log import Log def lowercase(string): return str(string).lower() def uppercase(string): return str(string).upper() def snakecase(string): string = re.sub(r"[\-\.\s]", '_', str(string)...
ServiceStack/servicestack-python
servicestack/utils.py
utils.py
py
7,623
python
en
code
3
github-code
1
9269156525
import os import json import requests class app_info_mode(): def __init__(self): self.path = os.path.abspath(os.path.dirname(__file__)) self.mode = "translate" self.print_format = "t_mode" self.version = "v2.0" self.fromlang = 'en' self.tolang = 'zh' #get th...
ZZP-DMU/tub
init.py
init.py
py
3,115
python
en
code
1
github-code
1
2440120696
# Polinomial Linear Regression # 1) Importing Libraries import numpy as np # Mathematics fucntopns import matplotlib.pyplot as plt # Plot and Charts import pandas as pd #Data Set management and import them import seaborn as sns # Covariance Matrix # 2) importing Datas...
awaisajaz1/Machine-Learning-Learning-Path
Machine Learning A-Z/Part 2 - Regression/Section 6 - Polynomial Regression/POLINOMIAL_LINEAR_REGRESSION.py
POLINOMIAL_LINEAR_REGRESSION.py
py
4,396
python
en
code
0
github-code
1
11190749780
from __future__ import annotations import contextlib import difflib import hashlib import os import pathlib import random import string from typing import Callable, Protocol from xml.dom import minidom from xml.etree import ElementTree import numpy as np import pytest from click.testing import CliRunner from PIL impo...
abey79/vpype
tests/conftest.py
conftest.py
py
8,656
python
en
code
618
github-code
1
41543948505
from flask import Blueprint, request, jsonify, json from db import db, app, ma from flask import Flask, redirect, request, jsonify, json, session, render_template from model.turnos import turnos, turnosSchema routes_turnos = Blueprint("routes_turnos", __name__) turno_schema = turnosSchema() turnos_schema = turnosSc...
winsignares/lavadocarro
CARW/api/turno.py
turno.py
py
1,332
python
en
code
0
github-code
1
72153324834
"""Tests for pydent.base.py.""" import copy import pytest from pydent import AqSession from pydent import ModelBase from pydent import ModelRegistry from pydent.exceptions import NoSessionError from pydent.marshaller import add_schema from pydent.marshaller import exceptions from pydent.marshaller import fields from ...
aquariumbio/pydent
tests/test_pydent/test_base.py
test_base.py
py
8,013
python
en
code
6
github-code
1
10451723483
import os import maya.cmds as cmds from functools import partial import Core reload(Core) class UIContainer(): frozen = False def build(parent, imagesPath, iconSize=25, height=20, marginSize=5): """ build widget @param parent : parent layout in maya @image...
darkuress/animBuddy
animBuddy/ViewportRefresh/Widget.py
Widget.py
py
1,205
python
en
code
1
github-code
1
14990079057
from datetime import datetime import cv2 as cv import matplotlib.pyplot as plt def perform_sift_performant(query, train): start = datetime.now() img1 = cv.imread(query, cv.IMREAD_GRAYSCALE) # queryImage img2 = cv.imread(train, cv.IMREAD_GRAYSCALE) # trainImage # Initiate SIFT detector sift = c...
Mini-Sylar/Fingerprint-Matching-System
Algorithms/SIFT/Performant_SIFT.py
Performant_SIFT.py
py
1,399
python
en
code
7
github-code
1
14386114791
''' 47. 이진 트리 직렬화 & 역직렬화 이진트리를 배열로 직렬화하고, 반대로 역직렬화하는 기능을 구현하라. https://leetcode.com/problems/serialize-and-deserialize-binary-tree/ ''' from collections import deque # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right ...
hyo-eun-kim/algorithm-study
ch14/hyoeun/ch14_6_hyoeun.py
ch14_6_hyoeun.py
py
1,870
python
en
code
0
github-code
1
34523987410
from Utils import * from webbrowser import open as open_url def _main(): from main import main GithubPanel().panel(main) class GithubPanel(): def __init__(self) -> None: from main import VALIDATING_CHAINS self.VALIDATING_CHAINS = VALIDATING_CHAINS def panel(self, main_panel_...
notional-labs/chain-chores
Panel_Github.py
Panel_Github.py
py
5,667
python
en
code
4
github-code
1
4622716657
import os from shutil import copyfile from typing import List, TYPE_CHECKING import jinja2 from ..checks.issues import Issues from ..checks.file_size import FileSizeCheck from .utils import create_parent_directory from ..checks.base import Check if TYPE_CHECKING: from combine.core import ContentDirectory class ...
dropseed/combine
combine/files/core.py
core.py
py
2,317
python
en
code
10
github-code
1
26714113006
import os import sys import math import argparse os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import matplotlib matplotlib.use('Agg') import numpy as np from models import * import datasets as dsets from datasets import PairwiseDataset models = { 'cyclegan': CycleGAN, 'unit': UNIT } def load_data(data_type): ...
tatsy/keras-generative
train_im2im.py
train_im2im.py
py
2,392
python
en
code
123
github-code
1
25346439097
from sys import exit from kojak import cli from kojak.exceptions import KojakException from kojak.models import Analyze from kojak.reports import Report from pbr.version import VersionInfo def main(): args = cli.argparser().parse_args() version = VersionInfo("kojak") if args.version: print("koja...
openuado/kojak
kojak/__main__.py
__main__.py
py
845
python
en
code
1
github-code
1
27358429875
from views import ViewsInterface from .checkers import check_menu from .simulations import Simulations def main_menu(view: ViewsInterface): options = [ ( 'Effectuer une simulation', Simulations.run, { 'view': view } ), ( ...
Nemesix493/Projet-7-AlgoInvest-Trade
controllers/__init__.py
__init__.py
py
620
python
en
code
0
github-code
1
10428105366
import errno import linecache import mimetypes import os import signal import sys from datetime import datetime from functools import wraps from urllib.parse import urlparse import pandas as pd import requests from bs4 import BeautifulSoup from validator_collection import checkers EN_KEY_WORDS = ["debt", "statistical...
dmatekenya/UNSIAP-Python-Oct-2019
src/python-for-data-science/case_study_web_scraping.py
case_study_web_scraping.py
py
11,265
python
en
code
0
github-code
1
4970143606
def game_core_v3(number) -> int: """Угадываем число с наименьшим количеством попыток, на каждой итерации делим диапазон значений на 2. Args: number (int, optional): Загаданное число. Returns: int: Число попыток """ min = 0 max = 100 count = 0 while True: predict = round((min...
Alexey-919/guess-the-number-game
project_1/game.py
game.py
py
689
python
ru
code
0
github-code
1
29847234118
import server from pico2d import * class FixedBackground: def __init__(self): self.image = load_image('SAYBAB_background.png') self.canvas_width = get_canvas_width() self.canvas_height = get_canvas_height() self.w = self.image.w self.h = self.image.h self.bgm = l...
TaeRimUm/SAYBAB_PROJECT_1
background.py
background.py
py
1,192
python
en
code
1
github-code
1
191431414
import numpy from chainer import cuda from chainer import function from chainer.utils import type_check class BatchNormalization(function.Function): """Batch normalization on outputs of linear or convolution functions. Args: size (int or tuple of ints): Size (or shape) of channel dimens...
jem0101/BigSwag-SQA2022-AUBURN
TestOrchestrator4ML-main/resources/Data/supervised/GITLAB_REPOS/jamieoglindsey0@chainer/chainer/functions/batch_normalization.py
batch_normalization.py
py
5,086
python
en
code
2
github-code
1
5558903910
import os, re, json import xml.etree.ElementTree as ET FACULTIES = {"Факультет інформатики", "Факультет економічних наук"} # these are hardcoded, but idk how to figure them out from the file DOCSPECS = {"Факультет економічних наук": { "ек": "Економіка", "мар": "Маркетинг", "мен": "Менеджмент", "фін": ...
Doodlinka/FidoTask
scheduleParser.py
scheduleParser.py
py
8,036
python
en
code
0
github-code
1
17517600280
class Solution: def splitString(self, s: str) -> bool: n = len(s) def backtrack(cur_idx, prev_idx): if cur_idx == n: return True for j in range(cur_idx, n): val = int(s[cur_idx:j+1]) if val + 1 == prev_idx and back...
Eben-Success/A2SVOnboarding
A2SV_Education/Backtracking/1849. Splitting a String Into Descending Consecutive Values.py
1849. Splitting a String Into Descending Consecutive Values.py
py
542
python
en
code
0
github-code
1
31982254831
from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .models import ( Persona, CallesIndependencia, ) from .forms import ( PersonaForm, PersonaVerificacionForm ) # AUTOCOMPLETADO CALLES from django.http import ...
independencia-datalake/datalake
datalake/core/views.py
views.py
py
3,396
python
es
code
0
github-code
1
13342642180
import sys import os from basic.constant import ROOT_PATH from basic.common import checkToSkip, printStatus INFO = __file__ def process(options, collection): rootpath = options.rootpath tpp = options.tpp tagfile = os.path.join(rootpath, collection, "TextData", "id.userid.%stags.txt" % tpp) resultfi...
li-xirong/jingwei
preprocess/count_tags.py
count_tags.py
py
2,257
python
en
code
48
github-code
1
40898316325
# 백준 13단계 집합과 맵 # 10815번 숫자 카드 import sys sys.stdin = open('input.txt') input = sys.stdin.readline # 여기부터 제출해야 한다. N = int(input()) list_N = list(map(int, input().split())) M = int(input()) list_M = list(map(int, input().split())) list_N.sort() # 이진탐색 def binary_search(array, target, start, end): while start ...
boogleboogle/baekjoon
step/13/1_10872.py
1_10872.py
py
1,024
python
en
code
0
github-code
1
4199197855
N = int(input()) peopleList = list(map(int, input().split())) resultList = [0 for _ in range(len(peopleList))] for i in range(N): count = 0 tall = i + 1 leftNum = peopleList[i] for j in range(N): if resultList[j] == 0 and count == leftNum: resultList[j] = tall break ...
hyeonwook98/Algorithm
Baekjoon/1138.py
1138.py
py
394
python
en
code
0
github-code
1
27281990840
""" """ from __future__ import annotations import sys import xml.etree.ElementTree as ET # iter - any depth # find - just direct children def main(args: list[str]): """""" path = "eagle-files/CAN-Test-Board" schPath = path + ".sch" brdPath = path + "brd" print(brdPath) if(__name__ == "__main...
grantg012/EagleEyeSight
tests/test1.py
test1.py
py
349
python
en
code
0
github-code
1
21030594928
import time import random import datetime import sys import numpy as np from utils.parameters import parse_command_line from utils.bayesian_optimization import * from utils.default_params import * np.set_printoptions(precision = 4, suppress = True) np.set_printoptions(threshold=sys.maxsize) ###### TRAIN PARAMETERS #...
simonetibaldi/BATQuO
src/main_pulser.py
main_pulser.py
py
1,272
python
en
code
0
github-code
1
73034166753
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Jayesh Kariya <jayeshk@saltstack.com>` ''' # Import Python Libs from __future__ import absolute_import # Import Salt Testing Libs from salttesting import TestCase, skipIf from salttesting.mock import ( NO_MOCK, NO_MOCK_REASON ) from salttesting.helpers imp...
shineforever/ops
salt/tests/unit/modules/win_disk_test.py
win_disk_test.py
py
1,683
python
en
code
9
github-code
1
18918186348
''' LEGB Local Enclosed Global Built-in ''' x = 'global X' def outer(): #global x x = 'outer X' def inner(): #nonlocal x x = 'inner X' print(x) inner() print(x) outer() print(x)
srawla3010/py-training
_practice/MS_corey/LEGB.py
LEGB.py
py
194
python
en
code
0
github-code
1
8804112016
############################################ # MATHEMATICS # ############################################ # # # COUTRET-ROZET Corentin # # # # Project : 302separation # # ...
sheiiva/302separation
sources/ArgumentManager.py
ArgumentManager.py
py
1,643
python
en
code
0
github-code
1
34139484273
class Solution: def minSetSize(self, arr: List[int]) -> int: len_arr = len(arr) dic = {} res = 0 for num in arr: dic[num] = dic.get(num, 0) + 1 sorted_values = sorted(dic.values()) while len_arr > len(arr)/2: len_arr -= sorted_values.pop() ...
rawanelbanaa/ProblemSolving_LeetCode
1338-reduce-array-size-to-the-half/1338-reduce-array-size-to-the-half.py
1338-reduce-array-size-to-the-half.py
py
354
python
en
code
0
github-code
1
26723797186
import EventOperation import unittest from unittest.mock import Mock, patch import CallbackHandler class TestEventOperation(unittest.TestCase): @patch("ResponseCreator.createJsonResponse") def testThatChallengeInRequestIsReturnedInResponseIfSet(self, createJsonResponseMock): challengeRequest = moc...
MarkusTillman/ScanishTranslator
EventOperation_Test.py
EventOperation_Test.py
py
1,993
python
en
code
1
github-code
1
275881198
from git import Repo import datetime import time from datetime import date, timedelta import json import requests now = datetime.datetime.now() clean_now = now.strftime("%Y-%b-%d, %A %I:%M:%S") message = "Commit made on: " full = message + clean_now working_tree_dir = '/home/ec2-user/crontGit/ltserge.github.io' file...
LtSerge/ltserge.github.io
ltserge.py
ltserge.py
py
2,098
python
en
code
0
github-code
1
44848288194
import tkinter as tk import sys class Aplicacion: def __init__(self): self.ventana1=tk.Tk() self.ventana1.title("titulo de la ventana") self.label1=tk.Label(self.ventana1, text="etiqueta n 1") self.label1.grid(column=0, row=0) self.label2=tk.Label(self.ventana1, text="etique...
Drako01/Trabajo-Practico---Python
Marcelo/0000 ejercicios/tkinkerpoo/00003tklabelyboton.py
00003tklabelyboton.py
py
657
python
es
code
2
github-code
1
32794252932
class Publication: def __init__(self, title, price): self.title = title self.price = price class Periodical(Publication): def __init__(self, title, price, period, publisher): super().__init__(title, price) self.period = period self.publisher = publisher class Book(Pu...
MichalJagielo/Python_examples
python_oop/04_python_oop.py
04_python_oop.py
py
1,339
python
en
code
0
github-code
1
70735088674
import os import traceback from functools import partial from typing import Union, Any import h5pyd from Prop3D.common.featurizer import ProteinFeaturizer from Prop3D.util import safe_remove from Prop3D.generate_data.data_stores import data_stores from toil.job import Job from toil.realtimeLogger import RealtimeLogg...
bouralab/Prop3D
Prop3D/generate_data/calculate_features_hsds.py
calculate_features_hsds.py
py
8,865
python
en
code
16
github-code
1
18169707301
file = open("input.txt", "r") input = [int(line) for line in file] def part1(): maximum = max(input) + 3 sorted_input = sorted(input + [0, maximum]) diffs = [ sorted_input[i + 1] - sorted_input[i] for i in range(len(sorted_input) - 1) ] return diffs.count(1) * diffs.count(3) def part2(): def coun...
pedroclobo/advent-of-code
2020/10/solution.py
solution.py
py
774
python
en
code
0
github-code
1
70352172194
from lii3ra.ordertype import OrderType from lii3ra.exit_strategy.exit_strategy import ExitStrategyFactory from lii3ra.exit_strategy.exit_strategy import ExitStrategy class ProfitProtectorFactory(ExitStrategyFactory): params = { # long_profit_floor, long_pp_ratio, short_profit_floor, short_pp_ratio ...
tranducquy/lii3ra
lii3ra/exit_strategy/profit_protector.py
profit_protector.py
py
6,736
python
en
code
0
github-code
1
27439167711
from __future__ import absolute_import from threading import Thread, Lock, Event, Condition import ctypes import os import sys import traceback import shutil from time import time import hashlib from tempfile import mkstemp from functools import wraps, partial from six.moves import xrange from past.builtins import exec...
thiagoralves/OpenPLC_Editor
editor/runtime/PLCObject.py
PLCObject.py
py
28,013
python
en
code
307
github-code
1
28144934766
from ignite.metrics import Metric from ignite.metrics.metric import sync_all_reduce, reinit__is_reduced import torch EPSILON_FP16 = 1e-5 class MultiClassAccuracy(Metric): def __init__(self, threshold=0.5, num_classes=1000, output_transform=lambda x: x): self.correct = None self.total = None ...
ryanwongsa/ECCV22_Chalearn-MSSL
metrics/multiclassaccuracy.py
multiclassaccuracy.py
py
1,276
python
en
code
4
github-code
1
32029297558
from PIL import Image import numpy as np from tqdm import tqdm import pickle def load_data(file): try: with open(file, 'rb') as fo: data = pickle.load(fo) return data except: with open(file, 'rb') as f: u = pickle._Unpickler(f) u.encoding = 'latin1' ...
OscarcarLi/meta-analysis-classification
datasets/filelists/FC100/process.py
process.py
py
974
python
en
code
1
github-code
1
43679695528
initial_file = open('numbers.txt', 'r') result_list = [result.rstrip() for result in initial_file] summ = 0 for result in result_list: summ += int(result) print(summ) final_file = open('results.txt', 'w') final_file.write(str(summ)) initial_file.close() final_file.close()
Dober616/work
22/22.4/1. Сумма чисел.py
1. Сумма чисел.py
py
276
python
en
code
0
github-code
1
27155993930
import ast import json from http.server import BaseHTTPRequestHandler from it.inspector import Inspector from it.session import Session from it.utils import Group, logger class InspectorServer(BaseHTTPRequestHandler): def do_GET(self, *args, **kwargs): self.respond(200, message="use post method") de...
three-headed-giant/it
it/server/handler.py
handler.py
py
2,035
python
en
code
79
github-code
1
72153323874
from uuid import uuid4 import pytest from pydent.marshaller.base import add_schema from pydent.marshaller.base import ModelRegistry from pydent.marshaller.fields import Alias from pydent.marshaller.fields import Callback from pydent.marshaller.fields import Field from pydent.marshaller.fields import Nested from pyden...
aquariumbio/pydent
tests/test_marshaller/test_fields/test_marshalling.py
test_marshalling.py
py
19,065
python
en
code
6
github-code
1
32918003515
import glob import io import logging import re import textwrap import traceback from contextlib import redirect_stdout import discord from discord.ext import commands from discord.ext.commands import Cog, Bot, Context from cogs.commands import settings from utils import embeds from utils.record import record_usage #...
richtan/chiya
cogs/commands/moderation/administration.py
administration.py
py
13,552
python
en
code
null
github-code
1
31518888968
import os import gzip import shutil from inspect import isawaitable from typing import Optional, Union, Dict, Tuple, Iterable, Iterator, List, Coroutine, NamedTuple, Callable, Generator from logging import Logger from pandas import read_csv, DataFrame, isna, Series, concat import numpy as np from pathlib import Path fr...
NatureGeorge/pdb-profiling
pdb_profiling/utils.py
utils.py
py
34,681
python
en
code
9
github-code
1
25597986377
# coding: utf-8 # In[2]: import argparse import pandas as pd import numpy as np def main(): # Parse arguments from command line parser = argparse.ArgumentParser() # Set up required arguments this script parser.add_argument('function', type=str, help='function to call') parser.add_argument('start...
jayacl5/bigdatafed
getCommodityPrice.py
getCommodityPrice.py
py
1,201
python
en
code
0
github-code
1
14935617233
#!/usr/bin/env python3 import sys import curses import argparse import debugoutput import keyinput import mapgenfuncs from gameworld import GameWorld, GameMap from screenpanels import MessagePanel, ListMenu def draw_screen(stdscr, gameworld, gamewindow, panellist, show_debug_text=False): """Display the current g...
DeepwaterCreations/rockslike
rockslike.py
rockslike.py
py
3,731
python
en
code
0
github-code
1
37306582499
# -*- coding: utf-8 -*- # ### PATHS DATASETS # PATH_DATA = 'data/' PATH_DATA_RAW = PATH_DATA+'raw/' # cognitive PATH_DATA_COGNITIVE = PATH_DATA+'cognitive/' PATH_DATA_FEATURES01_COGNITIVE = PATH_DATA+'features01_cognitive/' PATH_FEATURES01_COGNITIVE_CSV = PATH_DATA_FEATURES01_COGNITIVE+'features.csv' # dlib PATH_DL...
next-samuelmunoz/hci-eye_tracking
eye_tracking/config.py
config.py
py
1,256
python
en
code
1
github-code
1
33159388072
# -*- coding: utf-8 -*- # 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 import os import fitz import img2pdf class WqxtPipeline(object): def process_item(self, item, spider): return ...
ithomia/wenquan_scrapy
wqxt/pipelines.py
pipelines.py
py
1,713
python
en
code
3
github-code
1
3505597412
import os import socket import json import requests import datetime import threading from urllib import parse from flask import Flask,request,redirect,url_for,render_template from Core import Request from Classifier import Classifier from Configuration import Configuration from Log import LogController class Transpare...
Scentedtea0210/Web-Application-Firewall
WAF/TransparentProxy.py
TransparentProxy.py
py
8,066
python
en
code
0
github-code
1
5407069729
# coding: utf-8 """ This module contains all data objects getted from forum and wiki API. These API provides JSON data, and this module enhances data model by mirroring data attributes to data model. Here is an exemple : .. code-block:: python from campbot import CampBot bot = CampBot(use_demo=True) ...
c2corg/CampBot
campbot/objects.py
objects.py
py
11,732
python
en
code
2
github-code
1
5603964278
#!/usr/bin/env python3 from itertools import product, permutations, combinations, combinations_with_replacement import heapq from collections import deque, defaultdict, Counter from bisect import bisect import sys def input(): return sys.stdin.readline().rstrip() def list_int(): return list(map(int, input().split())...
yuu246/Atcoder_ABC
practice/recommendation/ABC218_D.py
ABC218_D.py
py
1,194
python
en
code
0
github-code
1
35042213128
from django.contrib import admin from .forms import CustomUserCreationForm, AdminUserChangeForm from .models import CustomUser from django.contrib.auth.admin import UserAdmin # Register your models here. class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = AdminUserChangeForm model ...
kjaymiller/diversity-orgs-django
accounts/admin.py
admin.py
py
716
python
en
code
7
github-code
1
6874365117
nombre = "Carlos" apellido = "Juan Perez" edad = 37 direccionDeCorreo = "CarlosJuanPerez@hotmail.com" telefono = 342105832 casado = False hijos = True listaAmigos = ["Marco", "Daniel", "Hernesto"] peliculasFav = {"1": "Pulp Fiction", "2": "Anaconda", "3": "El Club De La Pelea"} datosDeCarlos = [nombre, apellido, edad,...
Guido564/open-bootcamp-fullstack
Python/Modulo 3/Tarea1.py
Tarea1.py
py
413
python
es
code
0
github-code
1
33630670598
# -*- coding: utf-8 -*- ''' Created on 13th may 2016 @author: Daniel Durrenberger daniel.durrenberger@amaris.com Python 2.7.12 Pandas 0.18.1 Numpy 1.11.1 Scipy 0.18.0 ''' import numpy as np import preprocessing as pp def window_idx(time_ref, seconds_before, seconds_after, fs): start = int(time_ref - seconds_befo...
hugueschips/taf
processing.py
processing.py
py
3,263
python
en
code
0
github-code
1
28420576380
# -*- coding: utf-8 -*- ''' 作业2 ''' # @Time : 2021/4/5 18:40 # @Author : LINYANZHEN # @File : pytorch2_2.py import numpy as np import pandas as pd import random import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import datetime import time #...
AWSDJIKL/Artificial-Intelligence-and-Neural-Network
pytorch2/pytorch2_2.py
pytorch2_2.py
py
3,039
python
en
code
0
github-code
1
20426891679
from typing import Iterable, Any def is_present(substring: str, iterable: Iterable[str]): for string in iterable: if string is not None and substring in string: return True return False def set_to_empty(iterable: list[Any]) -> list[Any]: if iterable == ['']: iterable = [] ...
BilakshanP/SketchX
Main/core/helpers/misc_helper.py
misc_helper.py
py
340
python
en
code
0
github-code
1
7960570876
#1929 concatenation of arrays """ ---given an array of ints nums, of length n, create an array ans ---of length 2n, where ans[i]=nums[i] and ans[i+n]=nums[i] ---ans is the concatenation of 2 nums arrays """ class Solution(object): def getConcatenation(self,nums): ans=[] for i in range(2):...
npicciano79/leetcode_problems
python/lc_1929concatArray.py
lc_1929concatArray.py
py
477
python
en
code
0
github-code
1
8364525664
""" :Author: Daniel Mohr :Email: daniel.mohr@dlr.de :Date: 2021-02-19 :License: GNU GENERAL PUBLIC LICENSE, Version 3, 29 June 2007. tests the script: pydabu check_nasa_ames_format """ import subprocess try: from .data_path_class import DataPathClass except (ModuleNotFoundError, ImportError): from data_path_...
dlr-pa/pydabu
tests/mixin_check_nasa_ames_format.py
mixin_check_nasa_ames_format.py
py
1,366
python
en
code
4
github-code
1
23724759222
import pathlib import pygubu PROJECT_PATH = pathlib.Path(__file__).parent PROJECT_UI = PROJECT_PATH / "snakegame.ui" import tkinter as tk from tkinter import * from PIL import ImageTk, Image import random, os import numpy as np from operator import itemgetter import pickle # - GAMEPLAN DATA SETUP GAMEPLAN_SIZE =...
mwsse/raw_nn
snakeAI.py
snakeAI.py
py
12,755
python
en
code
0
github-code
1
72895055393
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
CiscoSystems/avos
openstack_dashboard/dashboards/project/data_processing/data_plugins/tests.py
tests.py
py
1,916
python
en
code
47
github-code
1
74732864354
import tkinter as tk from tkinter import ttk import datetime as dt import mysql.connector from tkinter import messagebox import configparser class NuovoLottoCucina(tk.Toplevel): def __init__(self): super(NuovoLottoCucina, self).__init__() self.title("Nuovo Lotto Cucina") self.geometry("+0+...
AleLuzzi/GestioneLaboratorio
Laboratorio/nuovo_lotto_cucina.py
nuovo_lotto_cucina.py
py
12,794
python
it
code
1
github-code
1
25858534397
import numpy as np from scrrpy import Cusp def test_g(tol=1e-3): j = np.logspace(-2, 0, 1000)[:-1] # gamma = 2 cusp = Cusp(gamma=2) g = cusp._g(j) g2 = j / (1 + j) assert abs(1 - g / g2).max() < tol # gamma = 1 cusp = Cusp(gamma=1) g = cusp._g(j) g2 = j assert abs(1 - g ...
benbaror/scrrpy
tests/test_cusp.py
test_cusp.py
py
1,144
python
en
code
0
github-code
1
34916818954
class node: def __init__(self, name, x = None, y = None): self.name = name self.edges = [] self.x = x self.y = y def connect(self, node): key = (self.name, node.name) self.edges.append(key) class edge: def __init__(self, left, right, weight = 1): se...
HenokMekuanint/KNAPSACK_AND_TSP
graph.py
graph.py
py
5,793
python
en
code
1
github-code
1
70723099874
import os import shutil def organizer(): # os.chdir("/Users/Jay/Desktop/Dogs/DogsBreedClassifier/") original_dataset_dir = 'static' base_dir = 'train/data' os.mkdir(base_dir) train_dir = os.path.join(base_dir, 'train') validation_dir = os.path.join(base_dir, 'validation') test_dir = os...
jay-babu/dogs-breed-classifier
app/dogs_file_organizer.py
dogs_file_organizer.py
py
7,166
python
en
code
0
github-code
1
2328687448
''' Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using extra space? Approach: Space - O(1) and Time: O(n) Check inline comments. Link: https://leetcode.com/problems/linked-list-cycle/ ''' # Definition for singly-linked list. # class ListNode(object): # def __init__...
yagamiram/Leetcode_problems_in_python
linked_list_cycle.py
linked_list_cycle.py
py
1,965
python
en
code
0
github-code
1
8650838427
import nltk import numpy as np import pandas as pd df = pd.DataFrame(columns=['Original_Name','Fixed_Name','UniqueID','SourceID', 'Type','Text','SentimentScore','EffectScore','SourceType','Text','Stemmed_Text', 'Lowercased','WithoutStopwords', 'WordNgrams','trigram...
OmarMeriwani/Fake-Financial-News-Detection
Sentiments/preproc.py
preproc.py
py
936
python
en
code
4
github-code
1
5498440877
from struct import unpack import json import hid from math import cos, atan USB_VID = 0x04d8 USB_PID = 0xef7e def hid_multiread(dev): data = dev.read(128, timeout_ms=10) res = data while len(data) > 0: data = dev.read(128, timeout_ms=10) res.extend(data) return res def hid_query(d...
murez/looking_glass_py
get_cal.py
get_cal.py
py
2,837
python
en
code
2
github-code
1
24877168673
"""Submit proposal content.""" import os from typing import Optional import httpx from starlette.datastructures import UploadFile from saltapi.auth.token import create_token from saltapi.repository.user_repository import User import logging logger = logging.getLogger(__name__) proposal_submission_url = f"{os.enviro...
saltastroops/salt-api-old
saltapi/submission/submit.py
submit.py
py
2,842
python
en
code
0
github-code
1
20126426839
# P : A수도, 1리터당 요금 # Q : B수도, 기본 요금 # R : B수도, 기본 요금 한계(<=R) # S : B수도, 1리터 당 초과 요금(>R) # W : 종민이 사용 수도 양 T = int(input()) for test_case in range(1, T+1): p,q,r,s,w = map(int, input().split()) wTaxA = p * w wTaxB = 0 if w <= r: wTaxB = q else: wTaxB = q + s*(w-r) if wTaxA < wTaxB: prin...
hso8706/Algorithm
SWEA/D2/1284. 수도 요금 경쟁 D2 Attack/수도 요금 경쟁 D2 Attack.py
수도 요금 경쟁 D2 Attack.py
py
470
python
ko
code
0
github-code
1
8785486459
import csv import sys from backend.KoalbyHumanoid.Kinematics.TrajectoryPlanning import TrajPlanner from backend.KoalbyHumanoid.Robot import SimRobot, RealRobot from backend.Primitives.MovementManager import play_motion_kinematics from backend.Simulation import sim as vrep class Walker: def __init__(self): ...
KoalbyMQP22-23/flask-project
backend/Testing/runToTestWalk.py
runToTestWalk.py
py
4,371
python
en
code
0
github-code
1
24543006030
import h5py import json import numpy as np from os.path import splitext, basename, join as pjoin from pipeline_utils import print_and_call from pipeline_config import MAPPING_PATH from graphslam_config import GRAPHSLAM_EVAL_DIR, GRAPHSLAM_MAPS_DIR, MATCH_JSON_DATA from sklearn.neighbors import NearestNeighbors import m...
sameeptandon/sail-car-log
mapping/sandbox/graphslam/scripts/eval_maps.py
eval_maps.py
py
4,146
python
en
code
2
github-code
1
74771536672
from typing import List from RLEnv.EnvLayer.PCBRoutingEnv import PCBRoutingEnv from scipy.spatial.distance import cityblock import numpy as np class rl_env(PCBRoutingEnv): def __init__( self, resolution: float, pcb_folder: str, pcb_names: List[str], connect_coef: float=2...
PCBench/PCBench
Baselines/RL/rl_env.py
rl_env.py
py
871
python
en
code
1
github-code
1
38105066131
import numpy as np import matplotlib.pyplot as plt np.random.seed(0) def marginal_distribution(mu, sigma2, indeces): mu_U = mu[indeces] sigma2_U = sigma2[indeces][:,indeces].reshape(-1,len(indeces)) return mu_U, sigma2_U def conditional_distribution(X, mu, sigma2, indeces): mu_U, sigma2_U = marginal_d...
hongxin-y/EECS545-Homeworks
HW4/prob5.py
prob5.py
py
2,419
python
en
code
2
github-code
1
72143448995
import datetime from typing import Any, Dict, List, Type, TypeVar, Union import attr from dateutil.parser import isoparse from ..types import UNSET, Unset T = TypeVar("T", bound="PatchedPipelineInvocation") @attr.s(auto_attribs=True) class PatchedPipelineInvocation: """Dynamically removes fields from serialize...
caltechads/brigid-api-client
brigid_api_client/models/patched_pipeline_invocation.py
patched_pipeline_invocation.py
py
2,948
python
en
code
0
github-code
1
4474715554
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jan 2 13:44:25 2021 @author: Scott T. Small This module demonstrates documentation as specified by the `NumPy Documentation HOWTO`_. Docstrings may extend over multiple lines. Sections are created with a section header followed by an underline of equal...
stsmall/abc_scripts2
project/stat_modules/popstats.py
popstats.py
py
6,127
python
en
code
3
github-code
1
74415935072
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sponsorships', '0003_sponsorship_event'), ] operations = [ migrations.CreateModel( name='SponsorshipLevel', ...
dco5/tendenci-sponsorships
sponsorships/migrations/0004_auto_20180110_2357.py
0004_auto_20180110_2357.py
py
1,169
python
en
code
1
github-code
1
36043447445
import threading from queue import Queue def jop1(): global lock a=0 lock.acquire() for i in range(10): a+=i print('a=',a) lock.release() def jop2(): b=0 lock.acquire() for i in range(100): b+=i print('b=',b) lock.release() if __name__ == '__main__': ...
ByronGe/Python-base-Learning
PythonLearning/LearningThread/TestThread4.py
TestThread4.py
py
470
python
en
code
0
github-code
1
1211038178
import socket import threading import struct ip_addr = "0.0.0.0" tcp_port = 7777 def process_client_stats(client_socket,address): print(f'Accepted connection from {address[0]}:{address[1]}') logFile = open(f"{address[0]}_{address[1]}.txt", 'w') try: while True: request =...
joaojomoura/UA
3_ano/RC1/Projeto-RC1/Sockets/server.py
server.py
py
1,073
python
en
code
0
github-code
1
73767637792
from __future__ import print_function import logging import sys from argh import * from vcloudtools.api import VCloudAPIClient log = logging.getLogger(__name__) parser = ArghParser() @arg('path', help='Path to fetch', default='/') def browse(args): """ Browse the vCloud API using the built-in hypermedia lin...
alphagov/vcloudtools
vcloudtools/command/browse.py
browse.py
py
648
python
en
code
4
github-code
1
30693236327
import json with open ("city.json") as file: data = json.load(file) list_data = [] for i in data: #print (i['name']) list_data.append({"id":i['id'], "text":i["name"]}) data = {"results":list_data} with open("city_name.json", "w") as f: json.dump(list_data, f)
pbrlionocde/mini_weather_portal
app/static/json/j.py
j.py
py
271
python
en
code
0
github-code
1
39497017221
#DFS를 이용한 bipartite matching #Kuhn's Algorithm def bpm(s): #방문 체크한 s번에서 또 연결을 체크한다면... if visited[s] == 1: return False #최초로 s번에서 연결을 시도한다면.. 방문체크를 해주고 visited[s] = 1 #s와 연결된 모든 v에 대하여... for v in graph[s]: #v가 매칭되어 있지 않거나 #v가 매칭되어 있다면, 해당...
yundaehyuck/Python_Algorithm_Note
theory_source_code/bipartite/bipartite_matching(+random_opt).py
bipartite_matching(+random_opt).py
py
2,003
python
ko
code
0
github-code
1
18276850000
from datetime import datetime import schedule from telebot import types from rf_bank_api import get_banks_currency from keyboards import kb_banks, kb_currencies, kb_configure from database_work import add_banks, add_currencies, get_currencies, get_banks, form_gist from data import banks, currencies, rus_to_en_banks, ...
SuDarina/currency_bot
controller.py
controller.py
py
6,195
python
ru
code
0
github-code
1
75045505952
import time import os, json import wiotp.sdk.application client = None def commandCallback(event): if event.eventId == "doorStatus": # Received event 'doorStatus' payload = json.loads(event.payload) # Get the status and time status = payload['status'] time = payload['time'...
iSagnik/Intro-to-IOT
hw4/laptop/laptop.py
laptop.py
py
975
python
en
code
0
github-code
1
22129992552
import discord, asyncio, requests, datetime # -- INIT -- POST_TIME_H = 6 POST_TIME_M = 0 POST_TIME_S = 0 BOT_EMAIL = '' BOT_PASS = '' KEY = '' CHAN_ID = '' # Connect to client client = discord.Client() def apiGet(url): response = requests.get(url) return response.json() def randomWord(): url = "ht...
resloved/word-of-the-day-discord
wotd.py
wotd.py
py
2,554
python
en
code
0
github-code
1
37969632625
info_student = [ "João", "Wagner", "Andre", "Victor", "Odilon", "Maycon", "Marlon", "Alan", "Patrick", "Guilherme Reis", "Brecailo", "Eduarda", "Eduardo", "Erick", "Fabricio", "Giselle", "Gui Felicio", "Júlio", "Kauany", "Kazulle", "Lucas", "Rafael", "Rhuan", "Sasah" ] user_logat = input("Digite Seu Usuario: ") us...
Vavatrewq/FAP_SI
works/python-practice/files/fapStudent.py
fapStudent.py
py
500
python
is
code
1
github-code
1
71704829473
from __future__ import print_function import sys import re import argparse p = argparse.ArgumentParser( description="Read ascii index " "and output a list of registers and descriptions." ) p.add_argument("-i",required=True, help="input file",dest='inxfile') p.add_argument("-o", help="output file name", dest='outf'...
ashima/embedded-STM32F-lib
readDocs/scripts/regsOfindex.py
regsOfindex.py
py
1,939
python
en
code
13
github-code
1
8647085877
# -*- encoding:utf-8 -*- import numpy as np from basic.specturm import _spectrogram from basic.pitch import estimate_tuning import util.utils as utils import filters def chroma_stft(y=None, sr=22050, S=None, norm=np.inf, n_fft=2048, hop_length=512, tuning=None, **kwargs): S, n_fft = _spectrogram...
rumourcy/MIR
feature/spectral.py
spectral.py
py
785
python
en
code
0
github-code
1
39690492775
# 4.2 바이트에 대한 기본 지식 # bytes 와 bytearray # bytes는 불변형이고, bytearray는 가변형 cafe = bytes('café',encoding='utf_8') print(cafe) print(cafe[0]) print(cafe[:1]) cafe_arr = bytearray(cafe) print(cafe_arr) print(cafe_arr[:-1]) import array numbers = array.array('h',[-2,-1,0,1,2]) #h명령어는 short int 형의 배열을 생성한다. print(numbers) oc...
wiesunggue/python_study
ch04_textbyte/chapter04_02.py
chapter04_02.py
py
1,085
python
ko
code
0
github-code
1
13356202645
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def recoverTree(self, root: Optional[TreeNode]) -> None: """ Do not return anything, modify ...
Biruk-Tassew/Competitive_programming
99_Recover_Binary_Search_Tree/99_Recover_Binary_Search_Tree.py
99_Recover_Binary_Search_Tree.py
py
966
python
en
code
0
github-code
1
39184132558
from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator from users.models import User class BaseModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True cl...
MrBerserk/semestrovka
web/models.py
models.py
py
3,801
python
en
code
0
github-code
1
6386175748
from statistics import median_low as mdl, median_high as mdh, median as md from copy import deepcopy as dc num = int(input()) floors = list(map(int, input().split())) newfloor = dc(floors) newfloor.sort() if len(floors)%2==0: medl = mdl(newfloor) medh = mdh(newfloor) midmed = md(newfloor) ind = min([fl...
oneku16/CompetitiveProgramming
ICPC/ICPC2021/warmup/k.py
k.py
py
544
python
en
code
0
github-code
1
9391357764
import os def readname(): # filePath = './div2k' # filePath = './pristine_images' # filePath = './BSD432_color' filePath = './flower_2000' name = os.listdir(filePath) return name, filePath if __name__ == "__main__": name, filePath = readname() print(name) txt = ope...
FightingSrain/ColorfulRL
read_file.py
read_file.py
py
456
python
en
code
5
github-code
1
34636894694
from enum import Enum class Level(Enum): SMALL = 0 MEDIUM = 1 LARGE = 2 class Fuzz(): def __init__(self): pass class Fuzzifier(): @staticmethod def to_level(s, m, l): return Level([s, m, l].index(max([s, m, l]))) @staticmethod def fl(input_): f = Fuzzifier(...
ysam12345/ci_hw1
src/fuzz.py
fuzz.py
py
2,344
python
en
code
0
github-code
1
8946929415
# -*- coding: utf-8 -*- import numpy as np from scipy.stats import linregress def _area_of_triangles(this_bin, pre_point, next_point): """Area of a triangle from duples of vertex coordinates Uses implicit numpy boradcasting along first axis of this_bin""" bin_pre = this_bin - pre_point pre_bin = pre_p...
FarisYang/LTTB-LTD-py
down_sample/ltd.py
ltd.py
py
5,287
python
en
code
3
github-code
1
31336183986
import sys import bilby import pandas as pd from bilby.core.prior import PriorDict, Uniform from gwpopulation.hyperpe import HyperparameterLikelihood from gwpopulation.models.spin import agn_spin from agn_utils.data_formetter import dl_to_ld from agn_utils.pe_postprocessing.jsons_to_numpy import load_posteriors_and_t...
avivajpeyi/agn_phenomenological_model
agn_utils/pop_inf/spin_orientation_pop_inf.py
spin_orientation_pop_inf.py
py
2,925
python
en
code
0
github-code
1
9943778853
import argparse import torchvision.transforms as transforms import torchvision import torch import torch.nn as nn import torch.optim as optim from torchvision import datasets from cutout import Cutout from models.resnet import * from models.resnet import Bottleneck from utils import CrossEntropy device = torch.device...
leejeongho3214/KD
train.py
train.py
py
6,804
python
en
code
0
github-code
1
20059168851
""" Gridsearch implementation """ from hops import hdfs, tensorboard, devices from hops.experiment_impl.util import experiment_utils from hops.experiment import Direction import threading import six import time import os def _run(sc, train_fn, run_id, args_dict, direction=Direction.MAX, local_logdir=False, name="no...
logicalclocks/hops-util-py
hops/experiment_impl/parallel/grid_search.py
grid_search.py
py
4,463
python
en
code
26
github-code
1
42557553956
from fastapi import FastAPI, HTTPException from pydantic import BaseModel class Line(BaseModel): matter: str teacher: str coef: float ects: float cc1: float cc2: float exam: float app = FastAPI() @app.get("/grades") def grades(): with open("exportFIles/note.txt", "r", encoding="utf...
Alex061998/ScrapperPython
api.py
api.py
py
2,717
python
en
code
0
github-code
1
75201405152
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # Created on 2017/12/1 __author__ = "Sky Jin " """ Description: 练习 1 : 去掉页面动态窗: 这里举一个新世界教育官网首页的例子 由于alert弹窗不美观,现在大多数网站都会使用自定义弹窗, 使用Selenium自带的方法就驾驭不了了,此时就要搬出JS大法 driver.execute_script(js_monitor """ from selenium import webdriver...
skyaiolos/SeleniumWithPython
demomore/training_JS_find/training1_dis_alertdlg.py
training1_dis_alertdlg.py
py
977
python
zh
code
1
github-code
1