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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
4269069182 | # Statement for enabling the development environment
DEBUG = True
# Define the application directory
import os
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
# Application threads
# A common general assumption is using 2 per available cores
# to handle incoming requests using one
# perform backgorund operations... | swapnil085/web_portal | src/config.py | config.py | py | 586 | python | en | code | 0 | github-code | 6 |
20489742276 | import scipy
from scipy.special import logsumexp
from sklearn.cluster import KMeans
from sklearn.cluster import SpectralClustering
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC, SVR
from ucsl.sinkhornknopp_utils import *
def one_hot_encode(y, n_classes=None):
''' utils function ... | rlouiset/py_ucsl | ucsl/utils.py | utils.py | py | 6,772 | python | en | code | 1 | github-code | 6 |
18361449182 | from rest_framework import serializers
from .models import *
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
def create(self, validated_data):
user = User.objects.create(
username=validated_data['username'],
email=validated... | raulfanc/gradebook_backend | gradebook_app/serializers.py | serializers.py | py | 2,626 | python | en | code | 0 | github-code | 6 |
14127553386 | import tkinter as tk
import datetime
class App:
def __init__(self,parent):
self.parent = parent
self.hour_label = tk.Label(self.parent,text="H",background='plum1',font=('verdana',12,'bold'))
self.tick1 = tk.Label(self.parent,text=':',background='plum1',font=('verdana',1... | vishalnain-10/Digital-Watch-using-tkinter | digi_clock.py | digi_clock.py | py | 2,437 | python | en | code | 0 | github-code | 6 |
70281057148 | from typing import List, Iterable
from torch.utils import data
from allennlp.common.registrable import Registrable
from allennlp.data.samplers.bucket_batch_sampler import BucketBatchSampler
from allennlp.data.samplers.max_tokens_batch_sampler import MaxTokensBatchSampler
"""
Duplicates of the pytorch Sampler classes.... | esteng/ambiguous_vqa | models/allennlp/data/samplers/pytorch_samplers.py | pytorch_samplers.py | py | 7,387 | python | en | code | 5 | github-code | 6 |
37079042149 | import sys
group_num = 1
while True:
n = int(sys.stdin.readline())
if n == 0:
break
name_list = []
pn_list = [[] for i in range(n)]
for j in range(n):
name_pn = sys.stdin.readline().split()
name_list.append(name_pn[0])
pn_list[j] = name_pn[1:]
... | JeonggonCho/algorithm | 백준/Silver/1384. 메시지/메시지.py | 메시지.py | py | 752 | python | en | code | 0 | github-code | 6 |
10422855793 | import dataclasses
import io
import logging
import math
import shutil
import tempfile
from pathlib import Path
import discord
import graphviz
import PIL.Image
from discord import Embed
from discord.ext.commands import Context, Converter
from PIL import ImageDraw
from randovania.game_description import default_databas... | randovania/randovania | randovania/server/discord/database_command.py | database_command.py | py | 16,089 | python | en | code | 165 | github-code | 6 |
8276036736 | import subprocess
import sys
import os
from ronto import verbose
from ronto.model.builder import InteractiveBuilder, TargetBuilder
from ronto.model.docker import docker_context
from .fetch import process as fetch_process
from .init import init_process
@docker_context()
def build_process(args):
verbose("Process ... | almedso/ronto | src/ronto/cli/build.py | build.py | py | 1,736 | python | en | code | 1 | github-code | 6 |
72330666747 | # TEE RATKAISUSI TÄHÄN:
import pygame
pygame.init()
naytto = pygame.display.set_mode((640, 480))
robo = pygame.image.load("robo.png")
leveys, korkeus = 640, 480
x = 0
y = 0
suunta = 1
kello = pygame.time.Clock()
while True:
for tapahtuma in pygame.event.get():
if tapahtuma.type == pygame.QUIT:
... | jevgenix/Python_OOP | osa13-06_reunan_kierto/src/main.py | main.py | py | 796 | python | fi | code | 4 | github-code | 6 |
40734405251 | from tkinter import Tk, Label, Button, HORIZONTAL
from tkinter import ttk
import time
from tkinter import messagebox
import sys
def main(name):
'''main function for studying'''
# instantiating a class object for the tkinter GUI
study_window = Tk()
study_window.title("Studying App")
study... | tinotenda-alfaneti/pomodoro-study-app | studying.py | studying.py | py | 3,374 | python | en | code | 0 | github-code | 6 |
17315144162 | #!/usr/bin/env python
# encoding: utf-8
"""
@author: zk
@contact: kun.zhang@nuance.com
@file: data_format.py
@time: 4/19/2019 10:08 AM
@desc:
"""
def add_label(data, topic, sep='\t'):
"""
add label for data
:param data:
:param topic:
:param sep:
:return:
"""
res = []
for item in da... | zhiyou720/tools | data_format.py | data_format.py | py | 537 | python | en | code | 0 | github-code | 6 |
21568994484 |
import torch
import torchvision.datasets
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
# 相对路径为相对于当前工程的
dataset = torchvision.datasets.CIFAR10("./PyTorch/data", train=True, transform=torchvision.transforms.ToTensor(), download=True, )
dataloader = DataLoader(dataset, 64)
# 打... | puzhiyuan/AutonomousDriving | PyTorch/src/TensorBoard.py | TensorBoard.py | py | 761 | python | en | code | 1 | github-code | 6 |
72833441787 | import numpy as np
import matplotlib.pyplot as plt
# Set size of squares and circles.
d = 31#61
r = int(d/2)
# Set linear dimension of square canvas.
res = 64 #128
pad = 2 # boundary number of pixels
# Set number of data examples to be generated.
num_examples = 1000
def gen():
# Create square s... | alexgilbert747/thesis | generate_data.py | generate_data.py | py | 2,290 | python | en | code | 0 | github-code | 6 |
2083516856 | import csv
import json
from collections import OrderedDict
from pathlib import Path
from typing import Any, List, Optional, Union
import torch
from pytorch_lightning import LightningModule, Trainer
from src.utils import pylogger
log = pylogger.get_pylogger(__name__)
def process_state_dict(
state_dict: Union[Or... | gorodnitskiy/yet-another-lightning-hydra-template | src/utils/saving_utils.py | saving_utils.py | py | 7,154 | python | en | code | 128 | github-code | 6 |
38857299042 | from django.db.utils import IntegrityError
from spyne.error import ResourceNotFoundError, ResourceAlreadyExistsError
from spyne.model.complex import Iterable
from spyne.model.primitive import Integer
from spyne.protocol.soap import Soap11
from spyne.application import Application
from spyne.decorator import rpc
from s... | Vixx-X/SOAP-REST-MICROSERVICES | SOAP/soap/soap/apps/soap/views.py | views.py | py | 1,975 | python | en | code | 0 | github-code | 6 |
22077450147 | n = int(input())
while n > 0:
n = n - 1
l = []
s = 0
m = int(input())
i = 1
while i <= m:
if s + i <= m:
s += i
l.append(i)
i *= 2
if s < m:
l.append(m - s)
l1 = sorted(l)
print(len(l1) - 1)
for j in range(1, len(l1)):
prin... | yunusergul/codeforcesExamples | Codeforces Round #638 (Div. 2)/D. Phoenix and Science.py | D. Phoenix and Science.py | py | 361 | python | en | code | 0 | github-code | 6 |
4680383558 | from fabric.api import *
# reconsider changing the execution model
env.user = 'root'
env.colorize_errors = True
[env.hosts.append(i.replace('\n', '')) for i in open('servers_list', 'r')]
def install_key():
"""copy ssh public key"""
run('rm -rf ~/.ssh ; mkdir -p ~/.ssh')
put('fabric/concat.pub', '~/.ssh/au... | dolohow/torrents-shell-utilities | fabfile.py | fabfile.py | py | 6,558 | python | en | code | 0 | github-code | 6 |
24325824848 |
import cv2
import numpy as np
from scipy.ndimage.measurements import label
from code.features import FeatureExtractor
from collections import deque
HEAT_INCREMENT = 10
class VehicleDetector:
def __init__(self, svc, scaler, n_rows, n_cols, config, buffer_size = 8):
self.svc = svc
... | olasson/SDCND-T1-P5-VehicleDetection | code/detect.py | detect.py | py | 5,703 | python | en | code | 0 | github-code | 6 |
13279743396 | import datetime
import matplotlib.pyplot as plt
import matplotlib.dates
import pandas as pd
import numpy as np
import os.path
class Graphs:
def __init__(self, data_base):
self.data_base = data_base
def overall_results_per(self):
correct = self.data_base["correct"].sum() / len(self.data_bas... | jlcoto/der_die_das | grapher_gen_results.py | grapher_gen_results.py | py | 10,304 | python | en | code | 0 | github-code | 6 |
8103653348 | #
# @lc app=leetcode id=88 lang=python3
#
# [88] Merge Sorted Array
#
# @lc code=start
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
'''
for j in range(n):
... | HongyuZhu999/LeetCode | 88.merge-sorted-array.py | 88.merge-sorted-array.py | py | 683 | python | en | code | 0 | github-code | 6 |
41389643477 | from ciscoconfparse import CiscoConfParse
import hashlib
import difflib
class audit:
def configuration_must_have(self,input_parent,input_config,show_command_output,show_command):
audit = False
actual_child_config = "No Configuration Found: {}".format(input_config)
parent_config = ""
... | johnanthonyraluta/Port_Mapping | Resources/cisco/ios_xr/audit.py | audit.py | py | 2,484 | python | en | code | 0 | github-code | 6 |
11964989637 | from django.urls import path
from .views import *
app_name = 'blog'
urlpatterns = [
path('', posts_list, name='post_list'),
path('tag/<slug:tag_slug>', posts_list, name='post_list_by_tag'),
# path('', PostsList.as_view(), name='post_list'),
path('p/<slug:slug>/<int:year>/<int:month>/<i... | black15/django-blog-v2 | blog/urls.py | urls.py | py | 500 | python | en | code | 2 | github-code | 6 |
10713095984 | from typing import Set
from pychu.tlogic.tcards import Card
from pychu.tpattern.multiples import TMultiFinder
from pychu.tpattern.tpatternfinder import TPatternFinder
def find_bombs(cards):
buffer = []
out = []
first = True
for card in cards:
if first:
first = False
b... | akkurat/tichu | python/src/pychu/tpattern/bombs.py | bombs.py | py | 830 | python | en | code | 0 | github-code | 6 |
4333793200 | # ruff: noqa: FBT001
# note: only used items are defined here, with used typing
import sys
from typing import Iterator, Optional, Sequence, TypeVar
from xml.etree.ElementTree import Element, ParseError
if sys.version_info < (3, 8): # pragma: no cover
from typing_extensions import Protocol
else: # pragma: no cov... | Rogdham/bigxml | stubs/defusedxml/ElementTree.pyi | ElementTree.pyi | pyi | 858 | python | en | code | 17 | github-code | 6 |
26040212886 | from __future__ import annotations
import dataclasses
import logging
import os
from abc import ABCMeta
from dataclasses import dataclass
from typing import Any, ClassVar, Generic, Iterable, Mapping, Type, TypeVar
import yaml
from typing_extensions import final
from pants.backend.helm.subsystems.helm import HelmSubsy... | pantsbuild/pants | src/python/pants/backend/helm/util_rules/tool.py | tool.py | py | 16,274 | python | en | code | 2,896 | github-code | 6 |
41957058631 | import unittest
from unittest.mock import Mock
from fhirbug.config import utils
from .resources import sample_settings
utils.default_settings = sample_settings
class TestLazySettings(unittest.TestCase):
def test_config_from_defaults(self):
lazy_setting = utils.LazySettings()
settings = lazy_setti... | zensoup/fhirbug | tests/test_config.py | test_config.py | py | 1,284 | python | en | code | 14 | github-code | 6 |
22177410667 | import numpy as np
import pandas as pd
from .weight_base import WeightBase
class WeiAge(WeightBase):
"""
Calculates weights which will make
the age distribution uniform
"""
name = 'wei_age'
def __init__(self,
data: pd.DataFrame):
super(WeiAge, self).__init__(
... | michal-racko/medical-cost | src/data_processing/weights/wei_age.py | wei_age.py | py | 809 | python | en | code | 0 | github-code | 6 |
74538689467 | "Sample code to get hardware information."
from ctypes import (
c_short,
c_char_p,
byref,
)
from thorlabs_kinesis import benchtop_stepper_motor as bsm
if __name__ == "__main__":
serial_no = c_char_p(bytes("40875459", "utf-8"))
channel = c_short(1)
if bsm.SBC_Open(serial_no) == ... | ekarademir/thorlabs-kinesis | examples/ex4_hwinfo_bsc.py | ex4_hwinfo_bsc.py | py | 987 | python | en | code | 31 | github-code | 6 |
70322594108 | """remove_product_rating_score
Revision ID: 177cf327b079
Revises: acf2fa2bcf67
Create Date: 2023-05-26 14:43:55.049871
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "177cf327b079"
down_revision = "acf2fa2bcf67"
branch_labels = None
depends_on = None
def upg... | ttq186/DressUp | alembic/versions/2023-05-26_remove_product_rating_score.py | 2023-05-26_remove_product_rating_score.py | py | 741 | python | en | code | 0 | github-code | 6 |
43625098034 | class Solution(object):
# O(n**2)
def shortestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
i, j = 0, len(s)-1
while j >= 0:
if s[i] == s[j]:
i += 1
j -= 1
if i == len(s):
return s
mid = s... | MichaelTQ/LeetcodePythonProject | solutions/leetcode_0201_0250/LeetCode214_ShortestPalindrome.py | LeetCode214_ShortestPalindrome.py | py | 1,464 | python | en | code | 0 | github-code | 6 |
6993423096 | from __future__ import annotations
import math
from typing import TYPE_CHECKING
from adapter.path_adapter import PathAdapter, PathAttributeID
from adapter.straight_adapter import StraightAdapter
from common.image_manager import ImageID
from entity_base.image.image_state import ImageState
from models.path_models.path_se... | AnselChang/Pathogen4 | models/path_models/path_segment_model.py | path_segment_model.py | py | 12,457 | python | en | code | 11 | github-code | 6 |
21686337671 | import argparse
import mmread_utils as mmu
import pickle as pkl
def parse_annots(fn):
"""
Columns are:
* 0 - run_barcode
* 1 - cell_ontology_class
* 17 - tissue
"""
annots_dict = {}
for i, line in enumerate(open(fn)):
if i == 0: continue
line = line.split(',')
... | dobinlab/STARsoloManuscript | splicing/make_mmu_pkl.py | make_mmu_pkl.py | py | 3,304 | python | en | code | 8 | github-code | 6 |
71843767229 | class Produto:
def __init__(self, nome, valor):
self.nome = nome
self.valor = valor
class CarrinhoCompras:
def __init__(self, ):
self.produtos = []
def inserir_produto(self, produto):
self.produtos.append(produto)
def lista_produtos(self):
for produto in self.p... | gittil/SoulOn-Python2 | Modulo_1/agregacao.py | agregacao.py | py | 794 | python | pt | code | 1 | github-code | 6 |
27009828768 | from sklearn.linear_model import LassoCV
def run(x_train, y_train, x_test, y_test, eps, n_alphas, alphas, fit_intercept, normalize, precompute, max_iter, tol, copy_X, cv, verbose, n_jobs,
positive, random_state, selection):
reg = LassoCV(eps=eps,
n_alphas=n_alphas,
alph... | lisunshine1234/mlp-algorithm-python | machine_learning/regression/linear_models/lassoCV/run.py | run.py | py | 1,314 | python | en | code | 0 | github-code | 6 |
74626753147 | #%%
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
import matplotlib.ticker as ticker
from matplotlib import rcParams
import numpy as np
from highlight_text import fig_text
import pandas as pd
from PIL import Image
import urllib
import os
df = pd.read_csv("success_rate_2022_2023.csv", index_col ... | array-carpenter/14thstreetanalytics | success_rate_comparison/success_rate_comparison.py | success_rate_comparison.py | py | 4,223 | python | en | code | 0 | github-code | 6 |
24333749632 | #!/bin/python3
import os
import sys
#
# Complete the gradingStudents function below.
#
def gradingStudents(grades):
l=[]
for i in grades:
if i<38:
l.append(i)
elif i%5==1 or i%5==2 or i%5==0:
l.append(i)
elif i%5==3:
l.append(i+2)
elif i%5==4... | nami-h/Python | multiple conditions in if else.py | multiple conditions in if else.py | py | 680 | python | en | code | 0 | github-code | 6 |
37020505173 | # 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
# dist... | TateWalker/Galactic-Data | irsa.py | irsa.py | py | 14,152 | python | en | code | 0 | github-code | 6 |
4072532441 | from __future__ import division
import os
import sys
import subprocess
import threading
import json
import numpy as np
import ast
import tempfile
# Assumes spice.jar is in the same directory as spice.py. Change as needed.
SPICE_JAR = 'SPICE-1.0/spice-1.0.jar'
TEMP_DIR = 'tmp'
CACHE_DIR = 'cache'
class Spice:
"""... | SamarthGVasist/Image-Captioning-using-Deep-Learning-Models-CDSAML- | SPICE.py | SPICE.py | py | 5,716 | python | en | code | 0 | github-code | 6 |
12195520060 | # 875. Koko Eating Bananas
# source: https://leetcode.com/problems/koko-eating-bananas/
class Solution(object):
def minEatingSpeed(self, piles, H):
left, right = 0, max(piles)
while left < right: # O(lgn) for binary search, totally O(NlgN)
mid = (left + right) / 2
# print(le... | ClaytonStudent/leetcode- | LeetCodePython/875_Koko_Eating_Bananas.py | 875_Koko_Eating_Bananas.py | py | 651 | python | en | code | 0 | github-code | 6 |
8952803072 | # Create your views here.
from bet_data_fetcher.models import *
from django.conf import settings
from django.core.cache import cache
from exceptions import *
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
def _fetch_data_from_sites():
""" Fetches data from site classes in bet_s... | rahul342/betapp | bet_data_fetcher/views.py | views.py | py | 4,634 | python | en | code | 0 | github-code | 6 |
25416563401 | #Задача 2. Напишите программу, которая найдёт произведение пар чисел списка. Парой считаем первый и последний элемент, второй и предпоследний и т.д.
#************************
def fillList(n,l,r):
import random
resultList = []
for i in range(n):
resultList.append(random.randint(l, r))
return r... | PavlovaAlena/Python3 | Seminar3_#2/Program.py | Program.py | py | 1,522 | python | ru | code | 0 | github-code | 6 |
27734565992 | import RPi.GPIO as GPIO
import time
buttonPin = 26
# Set buttonPin to INPUT mode with pull-up resistor
def setup():
GPIO.setmode(GPIO.BCM)
GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# If button pressed return 1, else return 0
def detect():
return 1 if GPIO.input(buttonPin) == GPIO.... | kendrick010/ece140a-lab6 | hardware/button.py | button.py | py | 700 | python | en | code | 0 | github-code | 6 |
70128173308 | """ Main Qt widget and file as well. """
import sys
from PySide6.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout
from PySide6.QtCore import QTimer
import globals
from main_gl_widget import MainGlWidget
# Important:
# You need to run the following command to generate the ui_form.py file
# pyside... | Iosiv42/GoL | src/widget.py | widget.py | py | 1,938 | python | en | code | 0 | github-code | 6 |
18003891687 | from unittest.mock import patch
from django.urls import reverse
from rest_framework import status
from django.contrib import messages
from comment.conf import settings
from comment.models import Comment
from comment.tests.base import BaseCommentTest, BaseCommentFlagTest, BaseCommentViewTest
from comment.tests.test_ut... | Shirhussain/RTL-Blog-with-multiple-user | comment/tests/test_views.py | test_views.py | py | 22,289 | python | en | code | 2 | github-code | 6 |
7937970870 | from PIL import Image, ImageDraw, ImageFont, ImageColor, ImageEnhance
import requests
import io
import json
from rembg import remove, new_session
import uvicorn
from fastapi import FastAPI, Request
from fastapi.responses import FileResponse, Response
app = FastAPI()
def ReduceOpacity(im, opacity):
"""
Return... | kimtrietvan/Image-text-template | main.py | main.py | py | 10,449 | python | en | code | 0 | github-code | 6 |
36294713470 | # 2016년 1월 1일은 금요일입니다. 2016년 a월 b일은 무슨 요일일까요? 두 수 a ,b를 입력받아 2016년 a월 b일이 무슨 요일인지 리턴하는 함수, solution을 완성하세요. 요일의 이름은 일요일부터 토요일까지 각각 SUN,MON,TUE,WED,THU,FRI,SAT
# 입니다. 예를 들어 a=5, b=24라면 5월 24일은 화요일이므로 문자열 "TUE"를 반환하세요.
# 제한 조건
# 2016년은 윤년입니다.
# 2016년 a월 b일은 실제로 있는 날입니다. (13월 26일이나 2월 45일같은 날짜는 주어지지 않습니다)
# jan = 31
# ... | minkimhere/algorithm_python | 13_2016.py | 13_2016.py | py | 1,324 | python | ko | code | 0 | github-code | 6 |
6634251613 | def vaild(strs):
length = len(strs)
if strs == None or len(strs) == 0:
return 1
hstack = []
sArr = list(strs)
hstack.append(sArr.pop(0))
while hstack and sArr:
next_item = sArr.pop(0)
if next_item in ["(", "[", "{"]:
hstack.append(next_item)
elif next_... | rh01/gofiles | lcode1-99/ex65/main.py | main.py | py | 727 | python | en | code | 0 | github-code | 6 |
11472746542 | import json
from typing import List, Dict, Any
def extract_json(string: str) -> List[Dict[str, Any]]:
json_strings = []
json_objects = []
open_brackets = 0
start_index = None
for index, char in enumerate(string):
if char == '{':
open_brackets += 1
if open_brackets =... | hsyhhssyy/amiyabot-arknights-hsyhhssyy-maa | utils/string_operation.py | string_operation.py | py | 1,033 | python | en | code | 3 | github-code | 6 |
35141470185 | #!/usr/bin/env python
"""The setup script."""
from setuptools import setup, find_packages
with open("README.rst") as readme_file:
readme = readme_file.read()
with open("HISTORY.rst") as history_file:
history = history_file.read()
with open("requirements.txt") as requirements_file:
requirements = requir... | hXtreme/flask-easyapi | setup.py | setup.py | py | 1,725 | python | en | code | 2 | github-code | 6 |
3288249384 | import tkinter as tk
from PIL import Image, ImageTk
from .constants import *
from utility.statistics import StatisticsKeys
class LoadStep:
def __init__(self, gui):
self.gui = gui
self.loading_steps_frame = tk.Frame(self.gui.root, bg='#d9ddff')
self.next_state_button = tk.Button(self.loadi... | kn2282/TIAG_Project_Python | src/gui/load_step.py | load_step.py | py | 1,742 | python | en | code | 0 | github-code | 6 |
4759197935 | """Test the gambit.sigs.convert module."""
import pytest
import numpy as np
from gambit.sigs.convert import dense_to_sparse, sparse_to_dense, can_convert, \
check_can_convert, convert_dense, convert_sparse
from gambit.kmers import KmerSpec
from gambit.test import random_seq
def test_dense_sparse_conversion():
"""... | jlumpe/gambit | tests/sigs/test_sigs_convert.py | test_sigs_convert.py | py | 2,427 | python | en | code | 16 | github-code | 6 |
5469193778 | import os
import glob
import re
primary=[
r"path1",
r"path2",
r"path3",
r"path4",
r"path5"
]
secondary=[
r"path6",
r"path7"
]
pl=len(primary)
sl=len(secondary)
for q in range(pl):
primary[q]+="\\"
#print(primary[q])
for q in range(sl):
secondary[... | kobayu0902art/work_snippets | find.py | find.py | py | 2,051 | python | en | code | 0 | github-code | 6 |
75188751546 | import sys
sys.stdin = open("inputs/문자열비교.txt", "r")
def match(p, t):
i = 0 # 전체 문자열 t의 인덱스
j = 0 # 안에 속할 문자열 p의 인덱스
while j < len(p) and i < len(t):
if t[i] != p[j]: # 만약 일치에 실패한다면
i = i-j # i는 j와 비교를 시작한 부분에서 한 칸 더 오른쪽으로 시작점을 옮김
j = -1 # j는 처음부터 (인덱스 0부터) 비교 시작
i =... | zacinthepark/Problem-Solving-Notes | swea/0816_문자열비교.py | 0816_문자열비교.py | py | 917 | python | ko | code | 0 | github-code | 6 |
36767879089 | '''
Author : knight_byte
File : A_Patrick_and_Shopping.py
Created on : 2021-04-19 14:15:35
'''
def main():
d = sorted(list(map(int, input().split())))
mi = min(2*(d[0]+d[1]), sum(d))
print(mi)
if __name__ == '__main__':
main()
| arbkm22/Codeforces-Problemset-Solution | Python/A_Patrick_and_Shopping.py | A_Patrick_and_Shopping.py | py | 257 | python | en | code | 0 | github-code | 6 |
74977722427 | import logging
from ontobio.io.gafparser import GafParser
from dipper.sources.Source import Source
from dipper.models.assoc.Association import Assoc
from dipper.models.Model import Model
from dipper.models.Reference import Reference
__author__ = 'timputman'
LOG = logging.getLogger(__name__)
class RGD(Source):
... | monarch-initiative/dipper | dipper/sources/RGD.py | RGD.py | py | 4,818 | python | en | code | 53 | github-code | 6 |
4246502703 | from Model.Animal import animalModel
from Controller.Animal import animalController
from fastapi import APIRouter, Depends, HTTPException
router = APIRouter(
prefix="/animals",
tags=["animals"],
responses={404: {"description": "Not found"}},
)
_animalCon = animalController.animalController()
@router.get... | aziznaufal/Mainan | Python/PercobaanFastAPI/Route/Animal/AnimalApi.py | AnimalApi.py | py | 596 | python | en | code | 0 | github-code | 6 |
14489820952 | import numpy as np
import pandas as pd
import string
def csv():
#Verify .csv files in folder
possible_csvs = ["ByTeacher_DetailData.csv"]
for i in range(1,10):
possible_csvs.append("ByTeacher_DetailData ({}).csv".format(i))
csvs = possible_csvs.copy()
for i in possible_csvs:
try:
... | cameronfantham/EF-KPI-Data-Pre-processing | KPI Report Generator/kpi_all (old).py | kpi_all (old).py | py | 3,971 | python | en | code | 0 | github-code | 6 |
42084381756 | import logging
import json
import re
from typing import Any
from concurrent.futures import ThreadPoolExecutor
from pymongo import MongoClient, database
from bson.json_util import dumps, loads
from bson.objectid import ObjectId
from backend.conf.confload import config
from backend.models.system import ResponseBasic
f... | tbotnz/cmdboss | backend/cmdboss_db/cmdboss_db.py | cmdboss_db.py | py | 7,900 | python | en | code | 22 | github-code | 6 |
30783796663 | """
https://adventofcode.com/2019/day/8
"""
from typing import List, Tuple, NamedTuple, Iterator
import itertools
import math
Layer = Tuple[Tuple[int]]
class LayerMetrics(NamedTuple):
name: str
count: int
layer_nums: Layer
def grouper(iterable: List[int], size:int) -> Iterator[Tuple[int]]:
iterable ... | giordafrancis/adventofcode2019 | day08_image.py | day08_image.py | py | 2,140 | python | en | code | 0 | github-code | 6 |
23178241186 | '''
Created by Jianyuan Su
Date: Jan 4, 2019
'''
from tkinter import *
from tkinter import filedialog, messagebox
from GUI import main_page
class StartPage(Frame):
def __init__(self, master, controller):
super().__init__(master)
self.master = master
self.controller = controller
co... | haohao1331/InverseBach | GUI/start_page.py | start_page.py | py | 5,589 | python | en | code | 0 | github-code | 6 |
74788996347 | # Task 1
# my_string = str(input("Enter the string:\n"))
# change_character = my_string[0].lower()
# new_string = my_string[0] + my_string[1:].lower().replace(change_character, "$")
# print(new_string)
# Task 2
"""
2) Add 'ing' at the end of a given string (length should be at least 3).
If the given string already e... | imigivanov/hillel-python-course | practice/practice_day_3/main.py | main.py | py | 648 | python | en | code | 0 | github-code | 6 |
37182141846 | from PyQt5.QtWidgets import QLabel, QWidget
class DescriptionLabel(QLabel):
def __init__(self, text: str, parent: QWidget):
super().__init__(text, parent)
self.setMaximumWidth(300)
self.setWordWrap(True)
self.setStyleSheet("QLabel{"
"font-size: 8pt;}")
| brankomilovanovic/Database-Handler | handlers/rel/mysql/Connection/UI/DescriptionLabel.py | DescriptionLabel.py | py | 318 | python | en | code | 0 | github-code | 6 |
19265213860 | from kubernetes import client, config
from datetime import datetime
import threading
import time
from settings import CPU_THRESHOLD ,SUSPEND_AFTER_DRAIN
def time_now():
return datetime.now().strftime("%H:%M:%S")
class Drainy:
"""
This Drainy class is to auto-drain a faulty node as self-healing solution
... | netmanyys/drainy | main.py | main.py | py | 5,104 | python | en | code | 0 | github-code | 6 |
74147628668 | # coding: utf-8
"""
Pydici billing views. Http request are processed here.
@author: Sébastien Renard (sebastien.renard@digitalfox.org)
@license: AGPL v3 or newer (http://www.gnu.org/licenses/agpl-3.0.html)
"""
from datetime import date, timedelta
import mimetypes
import json
from io import BytesIO
import os
import sub... | digitalfox/pydici | billing/views.py | views.py | py | 39,484 | python | en | code | 122 | github-code | 6 |
6442868869 | import torch
import torch.nn as nn
from constants import IMG_SIZE
class LinearVAE(nn.Module):
def __init__(self, num_features):
super(LinearVAE, self).__init__()
self.num_features = num_features
self.encoder = nn.Sequential(
nn.Linear(in_features=IMG_SIZE ** 2, out_features=51... | antoineeudes/MLFlowPlayground | src/model.py | model.py | py | 1,564 | python | en | code | 0 | github-code | 6 |
42964990913 | # def draw_line(px_context, x1: int, y1: int, x2: int, y2: int, color = (0, 0, 0)) -> None:
# """Brezenhem - algorithm drawing line"""
# lx = abs(x1 - x2) # define lengths
# ly = abs(y1 - y2)
#
# dy = 1 if y1 < y2 else -1 # define direct line
# dx = 1 if x1 < x2 else -1
#
# def cal... | DnineO/Computer-Graphics | lab 14/algorithms_drawing_with_pillow.py | algorithms_drawing_with_pillow.py | py | 5,772 | python | en | code | 0 | github-code | 6 |
30528663499 | from PIL import Image, ImageDraw
def board(num, size):
col = (255, 255, 255)
picture = Image.new("RGB", (num * size, num * size), col)
x = size * num
y = x
draw = ImageDraw.Draw(picture)
for i in range(0, x, size):
if i % (size * 2) == 0:
for j in range(0, y, size):
... | OrAnge-Lime/Python-Practice-3 | 26.2.py | 26.2.py | py | 704 | python | en | code | 0 | github-code | 6 |
1989910236 | import os
from os import system, name
from time import sleep
from var import *
from verifpiece import *
from time import sleep
from verifmove import *
#from chess import *
def clear():
os.system('cls' if os.name == 'nt' else 'clear')
def platePrint(plate):
clear()
# for i in range(8):
# print("|", 8 - i... | MaximCosta/PythonChess | verif.py | verif.py | py | 3,995 | python | en | code | 1 | github-code | 6 |
1336928761 | # Найдите три ключа с самыми высокими значениями в словаре
# my_dict = {'a':500, 'b':5874, 'c': 560,'d':400, 'e':5874, 'f': 20}.
my_dict = {'a':500, 'b':5874, 'c': 560,'d':400, 'e':5874, 'f': 20}
#Решение зацени говнокодище, без использования операторов сортировки!!!)
list_1=tuple(my_dict.items()) # здесь трансформи... | capeman1/Examples | example#5.py | example#5.py | py | 1,400 | python | ru | code | 0 | github-code | 6 |
70396795707 | import chex
import jax
import jax.numpy as jnp
import shinrl as srl
dS = 10
dA = 5
obs_shape = (2,)
act_shape = (3,)
init_probs = jnp.array([0.2, 0.8, 0, 0, 0, 0, 0, 0, 0, 0])
discount = 0.99
def tran_fn(state, action):
next_state = jnp.array([state, (state + action) % 10], dtype=int)
prob = jnp.array([0.2,... | omron-sinicx/ShinRL | tests/envs/base/mdp_test.py | mdp_test.py | py | 1,458 | python | en | code | 42 | github-code | 6 |
37273225181 |
from cc3d.core.PySteppables import *
from cc3d.CompuCellSetup import persistent_globals as pg
class ConstraintInitializerSteppable(SteppableBasePy):
def __init__(self,frequency=1):
SteppableBasePy.__init__(self,frequency)
def start(self):
for cell in self.cell_list:
cell.targ... | SouKot/cc3d-scipyOptimize | Simulation/nutrient_stress_mitosisSteppables.py | nutrient_stress_mitosisSteppables.py | py | 9,639 | python | en | code | 0 | github-code | 6 |
26625314906 | from django.contrib.auth.decorators import user_passes_test
from django.core import urlresolvers
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext as _
from product.forms import VariationM... | dokterbob/satchmo | satchmo/apps/product/views/adminviews.py | adminviews.py | py | 5,586 | python | en | code | 30 | github-code | 6 |
25785346221 | import numpy as np
import matplotlib.pyplot as plt
import xlrd
from config import SHEET_INDEX, ROW_START, ROW_END, COLUMN_START, COLUMN_END,FILE_NAME
from model import Unit
plt.rcParams['font.family']='Calibri'
def read_data():
workbook = xlrd.open_workbook(FILE_NAME)
sheet = workbook.sheets()[0]
result = ... | gaufung/CodeBase | PDA/Figures/app.py | app.py | py | 2,205 | python | en | code | 0 | github-code | 6 |
1414104927 | import logging
import coloredlogs
import sys
import os
import yaml
import argparse
log = logging.getLogger(__name__)
class Workspace:
BACK_CONFIG_VERSION = "0.03"
CONFIG_VERSION = "0.05"
DEFAULT_WORKSPACE_DIR = os.path.join(os.path.expanduser("~"),
".tng-workspac... | sonata-nfv/tng-sdk-project | src/tngsdk/project/workspace.py | workspace.py | py | 14,885 | python | en | code | 5 | github-code | 6 |
4729016187 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 13 00:32:57 2018
@author: pablosanchez
"""
import tensorflow as tf
import utils.constants as const
from networks.dense_net import DenseNet
class ConvNet(object):
def __init__(self, hidden_dim, output_dim, reuse, transfer_fct=tf.nn.relu,
... | psanch21/VAE-GMVAE | networks/conv_net.py | conv_net.py | py | 7,684 | python | en | code | 197 | github-code | 6 |
3695969994 | """Split-Attention"""
import torch
from torch import nn
import torch.nn.functional as F
from torch.nn.modules.utils import _pair
from .dropblock import DropBlock2D
__all__ = ['SplAtConv2d']
class SplAtConv2d(nn.Module):
"""Split-Attention Conv2d
"""
def __init__(self, in_channels, out_channels, kernel_... | welkin-feng/ComputerVision | cvmodels/models/layers/splat.py | splat.py | py | 3,449 | python | en | code | 2 | github-code | 6 |
13138139061 | from tkinter import *
def miles_to_km():
miles = float(miles_input.get())
km = miles * 1.609
kilometer_result_label.config(text=f"{km}")
mero_app = Tk()
mero_app.title("Miles to Kilometer Converter")
mero_app.config(padx=20, pady=20)
miles_input = Entry(width=7)
miles_input.grid(column=1, row=0)
miles... | callmebhawesh/100-Days-Of-Code | Day 27/project/main.py | main.py | py | 753 | python | en | code | 3 | github-code | 6 |
69997908667 | import requests
try:
import BeautifulSoup #python2
version = 2
except ImportError:
import bs4 as BeautifulSoup #python3
version = 3
def get_people_by_url(url, recurse=False):
response = requests.get(url)
html = response.content
if version == 2:
soup = BeautifulSoup.BeautifulSoup(ht... | barryam3/MITpeople | MITpeople.py | MITpeople.py | py | 2,696 | python | en | code | 0 | github-code | 6 |
27812524833 | from collections import deque
class Queue:
def __init__(self):
self.queue = deque()
def enqueue(self, item):
self.queue.append(item)
def dequeue(self):
if self.is_empty():
raise IndexError("Queue is empty")
return self.queue.popleft()
def is_empty(self):
... | aaryam-dev/Python_DSA | Data Structures/2_Queue/Queue.py | Queue.py | py | 897 | python | en | code | 0 | github-code | 6 |
27537060768 | import requests
import json
BASE_URL = 'http://localhost:9000'
def test_health():
response = requests.get(BASE_URL)
assert response.status_code == 200
assert response.text == "Welcome to our Spring-Boot Application!"
def test_get_logs():
response = requests.get(BASE_URL + "/logs")
logs = respon... | GalDavid6/GaMosh.DevOps | tests/test_http.py | test_http.py | py | 696 | python | en | code | 0 | github-code | 6 |
71859300669 | '''
Plotting Histograms and Scatter Plots for analysis
Also makes and prints dataframes sorted by various
statistics (see per_million)
Makes a final csv file with relevant contribution stats
'''
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm
import w... | fzyang1227/ds2000proj | graphs.py | graphs.py | py | 5,649 | python | en | code | 0 | github-code | 6 |
16593446793 | from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import gpg
import support
support.init_gpgme(gpg.constants.protocol.OpenPGP)
c = gpg.Context()
def dump_item(item):
print("l={} k={} t={} o={} v={} u={}".format(
item.level, item... | Discreete-Linux/gpgme | lang/python/tests/t-trustlist.py | t-trustlist.py | py | 608 | python | en | code | 1 | github-code | 6 |
24623314639 | import tkinter as tk
import webbrowser
def open_pdf(event):
webbrowser.open_new("Os.pdf")
def open_pdf2(event):
webbrowser.open_new("idea.pdf")
root = tk.Tk()
# Creating four frames for the top row
frame1 = tk.Frame(root, width=400, height=300, bg="white")
frame1.grid(row=0, column=0, padx=... | TanishDahiya/WebPort | guibox.py | guibox.py | py | 3,288 | python | en | code | 0 | github-code | 6 |
24199878977 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 11 20:11:22 2019
@author: Administrator
"""
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
m = len(grid)
if not m:
return
n = len(grid[0])
memo = [[None for _ in range(n)] for _ in range(m)]
... | AiZhanghan/Leetcode | code/64. Minimum Path Sum.py | 64. Minimum Path Sum.py | py | 851 | python | en | code | 0 | github-code | 6 |
32909453379 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import m3u8
import os
import sys
from Crypto.Cipher import AES
from multiprocessing import Pool
import multiprocessing
import requests
import logging
import threading
import queue
import aiohttp
import asyncio
import time
from functools import wraps
from concurrent.futures... | id10tttt/tools | m3u8_donwload.py | m3u8_donwload.py | py | 9,424 | python | en | code | 1 | github-code | 6 |
137753727 | ###############################################################################
# Pareto-Optimal Cuts for Benders Decomposition #
# Article: Accelerating Benders Decomposition: Algorithmic Enhancement and #
# Model Selection Criteria ... | isaac0821/BendersDecomposition | benders.py | benders.py | py | 10,604 | python | en | code | 15 | github-code | 6 |
5634782182 | #encoding:utf-8
# 导入matplotlib.pyplot, numpy 包
import numpy as np
import matplotlib.pyplot as plt
# 添加主题样式
# plt.style.use('mystyle')
# 设置图的大小,添加子图
fig = plt.figure(figsize=(5,5))
ax = fig.add_subplot(111)
#绘制sin, cos
x = np.arange(-np.pi, np.pi, np.pi / 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3=np.tan(x)
s... | peipei1109/P_04_CodeCategory | visualize/pltmultiLegend.py | pltmultiLegend.py | py | 1,227 | python | en | code | 0 | github-code | 6 |
39253570970 | from datetime import datetime
from urllib.parse import urljoin
import os
import responses
from django.conf import settings
from django.test import TestCase
from mangaki.models import (Work, WorkTitle, RelatedWork, Category, Genre,
Language, ExtLanguage, Artist, Staff, Studio)
from mangaki.... | mangaki/mangaki | mangaki/mangaki/tests/test_anilist.py | test_anilist.py | py | 11,533 | python | en | code | 137 | github-code | 6 |
5309111950 | import bisect
def search(nums, target, start, end):
while start <= end:
mid = (start+end) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
start = mid
else:
end = mid
return -1
def search2(nums, target, start, end):
if ... | louisuss/Algorithms-Code-Upload | Python/Tips/BinarySearch/binary_search.py | binary_search.py | py | 1,022 | python | en | code | 0 | github-code | 6 |
72780266429 | import onnx
import numpy as np
import onnxruntime as ort
import tvm
from tvm.contrib import graph_executor
import tvm.auto_scheduler as auto_scheduler
from tvm import relay, autotvm
import tvm.relay.testing
from tvm.autotvm.tuner import XGBTuner, GATuner, RandomTuner, GridSearchTuner
model_encoder = "/home/xinyuwang/... | angry-crab/tvm_example | python/ansor.py | ansor.py | py | 2,954 | python | en | code | 0 | github-code | 6 |
15757203807 | from django.http import HttpRequest
from django.test import TestCase
from snippets.views import top
from django.urls import resolve
from snippets.views import top, snippet_new, snippet_edit, snippet_detail
# Create your tests here.
class CreateSnippetTest(TestCase):
def test_should_resolve_snippet_new(self):
... | KentaKamikokuryo/DjangoWebApplication | djangosnippets/snippets/tests.py | tests.py | py | 771 | python | en | code | 0 | github-code | 6 |
386804619 | """
Created on Tue Nov 10
This program finds the solution to the system Ax = b and the LU factorization of A
using the Doolittle method.
Parameters
----------
A : Invertible matrix
b : Constant vector
Returns
-------
x : Solution
L : Factorization matrix L
U : Factorization matriz U
@author: Cesar Andres Garcia ... | jsperezsalazar2001/SADA_ANALYTICS | SADA_ANALYTICS/public/python/stepped.py | stepped.py | py | 3,549 | python | en | code | 1 | github-code | 6 |
35776081465 | from django.urls import path
from . import consumers
websocket_urlpatterns = [
path('ws/machine/<int:pk>/last/', consumers.MachineLastRunConsumer),
path('ws/machine/<int:pk>/runs/', consumers.MachineRunsStatusConsumer),
path('ws/machine/status/', consumers.MachinesStatusConsumer),
]
| TobKed/system_test_progress_tracking | system_test_progress_tracking/progress_tracking/routing.py | routing.py | py | 299 | python | en | code | 0 | github-code | 6 |
23520366148 | import pygame
from animation_folder import import_folder
class Door(pygame.sprite.Sprite):
def __init__(self, pos):
super().__init__()
# Door attributes
self.frames = 0
self.animation_speed = 0.15
self.animations = import_folder('./graphics/pain_character/door')
self... | lekan2410/Naruto-Platformer-V2 | Code/door.py | door.py | py | 825 | python | en | code | 0 | github-code | 6 |
9174273420 | load(":common/python/semantics.bzl", "TOOLS_REPO")
_CcInfo = _builtins.toplevel.CcInfo
# NOTE: This is copied to PyRuntimeInfo.java
DEFAULT_STUB_SHEBANG = "#!/usr/bin/env python3"
# NOTE: This is copied to PyRuntimeInfo.java
DEFAULT_BOOTSTRAP_TEMPLATE = "@" + TOOLS_REPO + "//tools/python:python_bootstrap_template.tx... | bazelbuild/bazel | src/main/starlark/builtins_bzl/common/python/providers.bzl | providers.bzl | bzl | 7,822 | python | en | code | 21,632 | github-code | 6 |
9309515906 | from sklearn import svm
import numpy as np
import cv2
from autoCanny import auto_canny
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
train =[]
label =[]
for i in range(0,10):
for j in range(1,3795):
path = "hog/" + str(i) + "/" + "img (" + str(j) + ").jpg"
... | mervedadas/Optical-Character-Recognition | model.py | model.py | py | 1,275 | python | en | code | 0 | github-code | 6 |
42166292211 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
import numpy as np
import cv2
import sys
# In[ ]:
def view_img(filepath):
img = cv2.imread(filepath)
window = cv2.namedWindow("Image Viewer", cv2.WINDOW_NORMAL)
img = cv2.resize(img, (1080, 720))
cv2.imshow(window, img)
cv2.waitKey()
print("i... | ANSHAY/OpenCV | practice/scripts/view_img.py | view_img.py | py | 605 | python | en | code | 0 | github-code | 6 |
3475871616 | #!/bin/env python3
import requests
import time
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
IP = "127.0.0.1"
PORT = ":12345"
url = "http://" + IP + PORT + "/cpu"
response = requests.get(url)
if response.ok:
print ("%s" % (response.content))
else:
response.raise_... | Antonito/cpp_gkrellm | scripts/cpu_load.py | cpu_load.py | py | 829 | python | en | code | 0 | github-code | 6 |
22904964205 | import argparse
from os.path import join
from pathlib import Path
import cv2
import numpy as np
parser = argparse.ArgumentParser(description='This script creates points.txt and clusters.txt files for a given image.')
parser.add_argument('--src_img', type=str, help='Path to the source image.')
parser.add_argument('--... | markomih/kmeans_mapreduce | data_prep_scripts/data_prep.py | data_prep.py | py | 1,652 | python | en | code | 41 | github-code | 6 |
38452601952 | mod = int(1e9)
L = [0,1]
n = int(input())
for i in range(abs(n)-1):
L.append((L[i]+L[i+1])%mod)
if n<0 and n%2 == 0:
print(-1)
elif n == 0:
print(0)
else:
print(1)
print(L[abs(n)]) | LightPotato99/baekjoon | dynamic/fibonacci/fiboExpansion.py | fiboExpansion.py | py | 197 | python | en | code | 0 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.