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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
5942225814 |
def input_number():
try:
number1 =int(input("Please enter a number from 1 - 20: "))
except:
print("Not and integer")
return -1
while number1 < 1 or number1 > 20:
print("value out of range")
input_number()
def input_numberx():
try:
number2 =int(input("Ple... | DenizzG/Python-WSTask | itteration mult task .py | itteration mult task .py | py | 796 | python | en | code | 0 | github-code | 90 |
27001684522 | #!/usr/bin/env python3
from argparse import ArgumentParser
import copy
from elftools.elf.elffile import ELFFile
import itanium_demangler
import sys
parser = ArgumentParser()
parser.add_argument('in_elf_path')
parser.add_argument('in_symbols_path')
parser.add_argument('out_symbols_path')
parser.add_argument('out_rep... | mkw-sp/mkw-sp | postprocess.py | postprocess.py | py | 3,698 | python | en | code | 73 | github-code | 90 |
23944063735 | '''operasi buat data pertama'''
from . import Database
from . import Util
import time
import os
def delete(no_buku):
'''delt'''
try:
with open(Database.DB_NAME,"r") as file:
counter = 0
while(True):
content = file.readline()
if len(content) == 0:
... | Mfadlyp/Python_Basic | 58. PROJECT/CRUD/Operasi.py | Operasi.py | py | 3,839 | python | id | code | 0 | github-code | 90 |
28564187160 | import heapq
import sys
input = sys.stdin.readline
V,E=map(int,input().split())
graph=[[] for _ in range(V+1)]
visited=[False]*(V+1)
result=[]
for i in range(E):
A,B,C=map(int,input().split())
graph[A].append((B,C))
graph[B].append((A,C))
def mst(start):
queue=[(0,start)]
while queue:
... | ehdtndla123/Algorithm | Baekjoon/1197.py | 1197.py | py | 607 | python | en | code | 0 | github-code | 90 |
17964807059 | n = int(input())
s1 = list(input())
s2 = list(input())
mod = int(1e9+7)
def ranl(lst):
ans = []
cnt = 1
ini = lst[0]
for i in range(1, len(lst)):
if ini == lst[i]:
cnt += 1
else:
ans.append((ini, cnt))
cnt = 1
ini = lst[i]
ans.append((... | Aasthaengg/IBMdataset | Python_codes/p03626/s932621417.py | s932621417.py | py | 736 | python | fr | code | 0 | github-code | 90 |
14412643070 | import datetime
from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union
import attr
from dateutil.parser import isoparse
from ..types import UNSET, Unset
if TYPE_CHECKING:
from ..models.post_return_order_customer_order import PostReturnOrderCustomerOrder
from ..models.post_return_order_line i... | Undefined-Stories-AB/ongoing_wms_rest_api_client | ongoing_wms_rest_api_client/models/post_return_order_model.py | post_return_order_model.py | py | 5,499 | python | en | code | 1 | github-code | 90 |
34514663377 | from io import StringIO
from collections import OrderedDict
from django.core.management import call_command
from django.contrib.auth.models import User
from django.db import connection
from django.db.transaction import atomic
from django.test import TestCase
from oauth2_provider.models import Application
class Clie... | ministryofjustice/cla_backend | cla_backend/apps/cla_auth/tests/management/commands/test_copy_client_data_to_new_table.py | test_copy_client_data_to_new_table.py | py | 3,344 | python | en | code | 5 | github-code | 90 |
42351031566 | import os
import sys
import cv2
import logging
from multiprocessing import freeze_support
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5 import uic, QtGui, QtCore
from PyQt5.QtGui import *
from PyQt5.QtMultimedia import *
from PyQt5.QtMultimediaWidgets impor... | DD-DuDa/LabelTrack | main.py | main.py | py | 17,119 | python | en | code | 54 | github-code | 90 |
34525173200 | from socketserver import TCPServer,StreamRequestHandler
import socket
host=socket.gethostname()
class Handler(StreamRequestHandler):
def handler(self):
addr=self.request.getpeername()
print('Got connection from',addr)
self.wfile.write('Thank you for connecting')
server=TCPServer((ho... | shiqingyan/learn-Python | Sockserver.py | Sockserver.py | py | 375 | python | en | code | 0 | github-code | 90 |
27848281316 | def calculate_bill(name, cleaning, cavity_filling, x_ray):
cleaning_rate = 60
cavity_filling_rate = 200
x_ray_rate = 100
tax_rate = 0.15
#given rates
subtotal = 0
if cleaning == 'y':
subtotal += cleaning_rate
if cavity_filling == 'y':
subtotal += cav... | aditithapa1/labpython | part1.py | part1.py | py | 1,096 | python | en | code | 0 | github-code | 90 |
21306233518 | from typing import Any
import pandas as pd
from fastapi.logger import logger
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.models.bank import Bank, BankType
from app.query import bank as query
from app.utils import get_dataframe
class BaseParser:
logger = logger
bank_type: BankType
U... | Samoed/EthicsAnalysis | api/app/dataloader/base_parser.py | base_parser.py | py | 1,347 | python | en | code | 0 | github-code | 90 |
13737821607 | import torch
import numpy as np
import wandb
from model import DQN, ReplayMemory
def get_epsilon(it, p=0.05, when_to_end=1000):
if it >= when_to_end:
return p
else:
return 1 - it / (when_to_end * (1 + p))
def select_action(model, state, epsilon, device="cpu"):
state = torch.tensor(state)... | Vansil/ReinforceRepoLab | code/train.py | train.py | py | 5,512 | python | en | code | 0 | github-code | 90 |
19200824318 | import unittest
from unittest.mock import MagicMock
class TestAction(unittest.TestCase):
def test_hash(self):
from muzero.environment.action import Action
import random
for _ in range(100):
action_id = random.randint(0, 10000)
action = Action(action_id)
... | radiachkik/MuZero | test_muzero/test_environment.py | test_environment.py | py | 11,617 | python | en | code | 2 | github-code | 90 |
29406571263 | from __future__ import absolute_import, division, print_function
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import importlib
import os, glob
from resnet_models import BaseNetwork
from torch.utils.data import Dataset, DataLoader
import torchsummary
from skimage import io, trans... | m4nh/epirobot | ano_test.py | ano_test.py | py | 13,312 | python | en | code | 0 | github-code | 90 |
42268332894 | import sys
sys.stdin = open('hws/algorithm/0922/input.txt', 'r')
## greedy 재귀 탐색으로 최대 화물 적재 횟수 구하는 함수
def greedy(s): # s : 시작 시간
for i in sorted(schedule, key=lambda x:schedule[x]): # i : 끝나는 시간이 가장 빠른 시작 시간
if i >= s: # 시작 시간(i)이 s 이상일 경우
global cnt
cnt += 1 # 횟수 + 1
g... | junhong625/TIL | Algorithm/SWEA/D3/5202_화물 도크.py | 5202_화물 도크.py | py | 960 | python | ko | code | 2 | github-code | 90 |
44995796609 | from time import time
a = [3,4,9,7,2,6,0,5]
n = len(a)
def sorts(a, n):
for i in range(n):
smallest = i
for j in range(i+1, n):
if int(a[j])<int(a[smallest]):
smallest = j
temp = a[i]
a[i] = a[smallest]
a[smallest] = temp
return a
if __name_... | Ethic41/codes | python/Algorithms/selection_sort.py | selection_sort.py | py | 359 | python | en | code | 1 | github-code | 90 |
15502523628 | from flask import Flask, render_template,request
from random import randint
import math
import time
import json
app = Flask(__name__)
class Animal:
def __init__(self,positionX, positionY, type) :
self.positionX = positionX
self.positionY = positionY
self.type = type
def __repr__(self):... | jeremgiral/RenardLapin | server.py | server.py | py | 9,336 | python | en | code | 0 | github-code | 90 |
18159137955 | import warnings
from typing import Optional, Dict, List, Type, Any
import pytorch_lightning as pl
import torch
from torch import nn as nn
from torchmetrics import Metric
from schnetpack.model.base import AtomisticModel
__all__ = ["ModelOutput", "AtomisticTask"]
class ModelOutput(nn.Module):
"""
Defines an ... | 1Bigsunflower/schnetpack | src/schnetpack/task.py | task.py | py | 18,933 | python | en | code | null | github-code | 90 |
43627826541 | # Author : Choi Donghyeon
import os
import pandas as pd
import numpy as np
from gensim.models import FastText
from konlpy.tag import Okt
from tokenizer import tokenize
from preprocess import preprocess_data
from keras.utils.np_utils import to_categorical
from keras.models import Sequential
from keras.layers import ... | fake6an/gbj | gbj/test/intent_train2.py | intent_train2.py | py | 6,141 | python | en | code | 0 | github-code | 90 |
18148749259 | x=0
y=0
n=int(input())
for i in range(n):
s,t=map(str,input().split())
if s==t :
x+=1
y+=1
elif s>t : x+=3
else : y+=3
print(x,y)
| Aasthaengg/IBMdataset | Python_codes/p02421/s772769605.py | s772769605.py | py | 164 | python | en | code | 0 | github-code | 90 |
71694992617 | import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # NOQA
from ..error.error import CoordinateError
class ScattererBuilder:
'''
This class constructs the Hamiltonian matrix from the geometrical information in the Lattice class.
Returns a hermitian Hamiltonian arra... | ccmt-regensburg/tbtranss | tbtranss/hamiltonian/scatterer.py | scatterer.py | py | 16,999 | python | en | code | 1 | github-code | 90 |
27306644435 | def forecast(*args):
cloudy_dict = {}
rainy_dict = {}
sunny_dict = {}
for arg in args:
city = arg[0]
weather = arg[1]
d = {city: weather}
if weather == "Sunny":
sunny_dict.update(d)
elif weather == "Cloudy":
cloudy_dict.update(d)
... | MEngMihailTodorov/Softuni_courses | Softuni_Advanced_2022/Advanced/Python_Advanced/_Final_Exam/03_Hourly_Forecast.py | 03_Hourly_Forecast.py | py | 1,268 | python | en | code | 0 | github-code | 90 |
39254580718 | from django.test import TestCase
from app_Compras.models import *
class TestModels(TestCase):
def testcreate(self):
self.Clienteprueba = tblClientes.objects.create(
id_cliente=1253,
nombre="mel",
apellido="mendo",
factura="prueba"
) | Melvin565484/Proyecto-Parcial | app_Compras/tests/tests_models.py | tests_models.py | py | 302 | python | es | code | 0 | github-code | 90 |
11623021686 | from collections import defaultdict
class Solution:
def groupAnagrams(self, strs: list[str]) -> list[list[str]]:
"""
https://leetcode.com/problems/group-anagrams/description/
TC: O(mn) SC: O(n) m = avg. len(strs[i]), n = len(strs)
"""
anagram_groups = defaultdict(list)
... | dbring/leetcode | Python/49-group-anagrams.py | 49-group-anagrams.py | py | 710 | python | en | code | 0 | github-code | 90 |
44868906618 | import pygame
import pygame.display as display
from pygame.constants import *
from lifeforms import Lifeforms
from random import randint
from time import sleep
def main():
pygame.init()
display.set_caption('Game of Life')
width, height = 800, 800
L = Lifeforms()
screen = display.set_mode((width,... | quintant/Game-of-Life | main.py | main.py | py | 1,159 | python | en | code | 0 | github-code | 90 |
30330075233 | import matplotlib.pyplot as plt
import numpy as np
def unit_step(a, n):
unit =[]
for sample in n:
if sample<a:
unit.append(0)
else:
unit.append(1)
return(unit)
a_u = 2
UL_u = 5
LL_u = 0
unit_i = np.arange(LL_u, UL_u, 1)
def unit_impulse(a, n):
delta ... | diegojespana/Practica2-Comunicaciones4 | Practica2.2.py | Practica2.2.py | py | 897 | python | en | code | 0 | github-code | 90 |
17977692159 | n = int(input())
a = list(map(int,input().split()))
s = 0
for i in a:
s += i
ans = float('inf')
tmp = 0
for i in range(n-1):
tmp += a[i]
ans = min(ans,abs(s-tmp-tmp))
print(ans)
| Aasthaengg/IBMdataset | Python_codes/p03659/s920605160.py | s920605160.py | py | 194 | python | en | code | 0 | github-code | 90 |
2827014828 | from tkinter import *
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import Tk,Label, Button,Entry, messagebox
from sklearn.preprocessing import StandardScaler
import joblib
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.line... | Amira-Shinnawi/DSS | Loan Status Prediction/LogisticRegression.py | LogisticRegression.py | py | 9,477 | python | en | code | 0 | github-code | 90 |
23410130939 | import gym
from gym import spaces
import numpy as np
import math
from Tank_real_2D_cont.Tank_2D_cont.env_2D_cont import Open_Ai, WIDTH, HEIGHT
class customENV_tank(gym.Env):
#metadata = {'render.modes' : ['human']}
def __init__(self):
self.pygame = Open_Ai()
self.action_space = spaces... | anavartpandya/Training-2D-pixel-Tank-using-Reinforcement-Learning | TANK2D_RL_PROJECT/_2D MOTION (CONTINUOUS ACTION SPACE)/Tank_real_2D_cont/Tank_2D_cont/open_AI_env_2D_cont.py | open_AI_env_2D_cont.py | py | 1,379 | python | en | code | 0 | github-code | 90 |
37690146658 | import aioredis
from loguru import logger
from aiogram import Bot, Dispatcher, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from data import config
from libs import ServiceNow
snow_bat_session: ServiceNow
bot = Bot(token=config.BOT_TOKEN, parse_mode=types.ParseMode.HTML)
storage = MemoryStorag... | dganic/24x7TeamTgBot | bot_loader.py | bot_loader.py | py | 651 | python | en | code | 1 | github-code | 90 |
18302568839 | import math
N = int(input())
if N%2 == 1:
print(0)
exit()
ans = 0
i = 1
while 1:
a = 2*5**i
if N//a == 0:
break
ans += (N//a)
i += 1
print(ans) | Aasthaengg/IBMdataset | Python_codes/p02833/s321128236.py | s321128236.py | py | 178 | python | en | code | 0 | github-code | 90 |
18908112048 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Very simple HTTP server in python for logging requests
Usage:
./run.py [<port>]
"""
from http.server import BaseHTTPRequestHandler, HTTPServer
import logging
class Server(BaseHTTPRequestHandler):
"""
Server class
"""
def _set_response(self):
... | mpepping/request-logger | run.py | run.py | py | 1,835 | python | en | code | 0 | github-code | 90 |
17945414849 | import sys
import math
import collections
import bisect
import itertools
# import numpy as np
sys.setrecursionlimit(10 ** 7)
INF = 10 ** 20
MOD = 10 ** 9 + 7
# MOD = 998244353
ni = lambda: int(sys.stdin.readline().rstrip())
ns = lambda: map(int, sys.stdin.readline().rstrip().split())
na = lambda: list(map(int, sys.s... | Aasthaengg/IBMdataset | Python_codes/p03576/s866889724.py | s866889724.py | py | 1,071 | python | en | code | 0 | github-code | 90 |
37715150210 | import argparse
import cv2
from sys import platform
from inference import Network
INPUT_STREAM = 'pets.mp4'
def arg_parse():
parser = argparse.ArgumentParser("Run inference on input video")
i_desc = "location of input file"
m_desc = "location of the model XML file"
d_desc = "CPU"
parser._action_gro... | msrepo/opencv-practice | opencv-python/process_model_output/app.py | app.py | py | 1,922 | python | en | code | 1 | github-code | 90 |
24664020715 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 8 09:00:17 2018
@author: dkochar
Write a program which calculates a student’s letter grade based on their score.
Default score should be 100. Use the following logic. if ...
score is greater than or equal to 90, then it is an A
score is greater than or equal to 80, the... | david-kochar/PythonScripts | ClarityPythonTrainingLabs/ClarityPythonTrainingLab2.py | ClarityPythonTrainingLab2.py | py | 752 | python | en | code | 0 | github-code | 90 |
25857538744 | import ee
class Landsat(object):
""""""
def __init__(self, toa_image):
"""Initialize a Landsat Collection 1 image
Parameters
----------
toa_image : ee.Image
Landsat 5/7/8 Collection 1 TOA image
(i.e. from the "LANDSAT/X/C01/T1_TOA" collection)
... | hgbzzw/openet-disalexi-beta | openet/disalexi/landsat.py | landsat.py | py | 9,142 | python | en | code | 8 | github-code | 90 |
31279978794 | import matplotlib.pyplot as plt
import numpy as np
cafe = np.array([5, 5, 7, 6, 7, 4])
te = np.array([1, 2, 0, 2, 1, 3])
agua = np.array([10, 0, 14, 12, 15, 13])
nombres = ['María', 'Pablo', 'Ema', 'Franco', 'Estefanía', 'Pedro']
x = np.arange(len(nombres)) # Cantidad de lugares para las labels
width = 0.35 ... | madescoces/python | matematicas_3/src/3_class/Matplotlib/5_matplotlib_stack_bar_3.py | 5_matplotlib_stack_bar_3.py | py | 991 | python | es | code | 0 | github-code | 90 |
72157871018 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Project: DevelopBasic
# Software: PyCharm
# DateTime: 2018-10-16 17:47
# File: 24-16进制.py
# __author__: 天晴天朗
# Email: tqtl@tqtl.org
a = bin(110)
b = oct(110)
c = hex(110)
d = chr(110)
print(a,b,c,d)
| cuixiaozhao/DevelopBasic | Chapter-02/24-16进制.py | 24-16进制.py | py | 261 | python | en | code | 0 | github-code | 90 |
2271220545 | import math
from Bitarray import Bitarray
#import GeneralHashFunctions
def BKDRHash(key, j):
base = [31, 131, 1313, 13131, 131313, 1313131, 13131313, 131313131]
seed = base[j]# 31 131 1313 13131 131313 etc..
hash = 0
for i in range(len(key)):
hash = (hash * seed) + ord(key[i])
return hash
#b... | AnkorTn/EE208_Lab | lab2-Crawler/partC/BloomFilter.py | BloomFilter.py | py | 1,100 | python | en | code | 0 | github-code | 90 |
22824854184 | import pytest
import pandas as pd
from collections import defaultdict,Counter
from TicketToRideGame import Deck, Board ,TicketToRideGame
deck_input = {'a':1,'b':2,'c':3}
@pytest.fixture()
def deck():
return Deck(deck_input)
def test_init(deck):
assert deck.next_deck == []
input_from_current_deck = dict... | untergunter/reinforcement_learning_ticket_to_ride | testTicketToRideGame.py | testTicketToRideGame.py | py | 4,012 | python | en | code | 0 | github-code | 90 |
37777612010 | # -*- coding: utf-8 -*-
from djangorestframework_camel_case.render import CamelCaseJSONRenderer
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.renderers import BrowsableAPIRenderer
from rest_framework.response import Response
from astrobin.api2.serializers.gear_se... | astrobin/astrobin | astrobin/api2/views/gear_view_set.py | gear_view_set.py | py | 1,883 | python | en | code | 100 | github-code | 90 |
29552022257 | for _ in range(int(input())):
nums = list(range(0, 10))
num = int(input())
state = list(map(int, input().split()))
result = []
for i in state:
cnt, work = input().split()
for w in work:
if w == 'D':
i += 1
else:
i -= 1
result.append(str(nums[i % 10]))
print(' '.join(r... | mooyeon-choi/TIL | problemSolving/codeforces/round_806/c_cypher.py | c_cypher.py | py | 327 | python | en | code | 2 | github-code | 90 |
29341494861 | import tkinter as tk
from tkinter.ttk import *
from tkinter import *
from PIL import Image, ImageTk
from customtkinter import *
import numpy as np
import tensorflow as tf
from tensorflow import keras
class MainWindow(tk.Tk):
def __init__(self):
super().__init__()
# Load trained model
self.... | sabynana/Paddy_Disease | apikkGUI.py | apikkGUI.py | py | 5,482 | python | en | code | 0 | github-code | 90 |
5511387347 | from action import action_
import CLI
import os
import pandas as pd
import warnings
print("AWS RDS connecting...")
warnings.filterwarnings("ignore")
###
color = pd.read_csv('Data/color.csv')
color = color['color']
manufacture = pd.read_csv('Data/manufacture.csv')
manufacture = manufacture['manufacture']
clothesType = {... | chc-tw/Inventory-system-implementation | main.py | main.py | py | 5,102 | python | en | code | 0 | github-code | 90 |
12692799647 | import ssl
import urllib.request
import xml.etree.ElementTree as ET
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
URL_STRING = "http://py4e-data.dr-chuck.net/comments_1895398.xml"
uh = urllib.request.urlopen(URL_STRING, context=ctx)
data =... | liaoyichen123/Learning-Python | Cousera Using Python to Access Web Data/Week 5 Web Service and XML/main.py | main.py | py | 466 | python | en | code | 0 | github-code | 90 |
31429206477 | import subprocess
import sys
from pathlib import Path
import loguru
from PySide6.QtCore import QThread, Signal
from src.conf import config, config_path
class Download(QThread):
isFinished = Signal(bool)
"""
Methods:
download(url:str) -> Path: absoult Path
"""
def download(self, url: str... | 271374667/NuitkaGUI | src/common/download.py | download.py | py | 1,133 | python | en | code | 12 | github-code | 90 |
18154032419 | # 解説を見て解き直し
N, K = [int(x) for x in input().split()]
ranges = [tuple(int(x) for x in input().split()) for _ in range(K)]
ranges.sort()
p = 998244353
dp = [0] * (N + 1)
dpsum = [0] * (N + 1)
dp[1] = 1
dpsum[1] = 1
for i in range(2, N + 1):
for l, r in ranges:
rj = i - l
lj = max(1, i - r) # 1以上
... | Aasthaengg/IBMdataset | Python_codes/p02549/s298437641.py | s298437641.py | py | 500 | python | en | code | 0 | github-code | 90 |
13739935948 | import tornado.ioloop
import os
from Controller.IndexController import IndexController
from Controller.AliPayController import AliPayController
# from Controller.AliPayNotifyUrlController import AliPayNotifyUrlController
from Controller.WXPayController import WXPayController
from tornado.options import define, optio... | VictorZhang2014/wechat_alipay_api | main.py | main.py | py | 1,172 | python | en | code | 0 | github-code | 90 |
2575394916 | # views.py
#
# Authors:
# - Coumes Quentin <coumes.quentin@gmail.com>
import json
import logging
import os
import threading
import time
from io import SEEK_END
import docker
from django.conf import settings
from django.http import (HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed,
... | PremierLangage/sandbox | sandbox/views.py | views.py | py | 4,628 | python | en | code | 7 | github-code | 90 |
8829731066 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Foo(object):
# 静态方法
@staticmethod
def add(x, y):
return x + y
x = Foo.add(3, 4)
class Date(object):
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
# 静态方法
@staticmeth... | lanzhiwang/python-patterns | Object_Oriented/05.py | 05.py | py | 864 | python | en | code | 1 | github-code | 90 |
11690575580 | import logging
import select
import socket
import struct
import threading
import time
from .constants import PYADS_ENCODING
from .adscommands import DeviceInfoCommand
from .adscommands import ReadCommand
from .adscommands import ReadStateCommand
from .adscommands import ReadWriteCommand
from .adscommands i... | rako233/TC2ADSProtocol | ads/adsclient.py | adsclient.py | py | 19,310 | python | en | code | 0 | github-code | 90 |
17437437780 | """
You will be given a number and you will need to return it as a string in Expanded Form.
For example:
expanded_form(12) # Should return '10 + 2'
expanded_form(42) # Should return '40 + 2'
expanded_form(70304) # Should return '70000 + 300 + 4'
NOTE: All numbers will be whole numbers greater than 0... | Ristani/Codewars-Katas | kyu-06/write-number-in-expanded-form.py | write-number-in-expanded-form.py | py | 981 | python | en | code | 0 | github-code | 90 |
26073422009 | import cv2
import numpy as np
cap = cv2.VideoCapture(r"path")
success,image = cap.read()
fps = cap.get(cv2.CAP_PROP_FPS)
video_length = 62800
fr = video_length * fps
n = 15
desired_frames = n * np.arange(fr)
for i in desired_frames:
cap.set(1,i-1)
success,image = cap.read(... | KastoneX/binary-image-classification | 15frames.py | 15frames.py | py | 549 | python | en | code | 0 | github-code | 90 |
23845881431 | import pygame
##from math import copysign
##import car
##import static_objects
##import os
##from random import randint
##import world_map
import startmenu
import gameloop
if __name__ == '__main__':
pygame.init()
pygame.display.set_caption('Game')
W, H = 800, 600 #camera width and height in pixels
scr... | sanyicz/a-day-in-the-drive | main.py | main.py | py | 779 | python | en | code | 0 | github-code | 90 |
14285322753 | # _*_ coding : UTF-8 _*_
# 开发人员 : ChangYw
# 开发时间 : 2019/8/2 16:32
# 文件名称 : citys_info.PY
# 开发工具 : PyCharm
class Citys:
def __init__(self, citys = {}):
self.__citys = citys
@property
def citys(self):
return self.__citys
@citys.setter
def citys(self, citys):
... | wenzhe980406/PythonLearning | day15/citys_info.py | citys_info.py | py | 1,397 | python | en | code | 0 | github-code | 90 |
18391354979 | n=int(input())
num=len(str(n))-1
l=[]
ans=1
mod=10**9+7
for i in range(num):
ans=(ans*3)%mod
l.append(ans)
w=str(n)
now=2
for i in range(1,num):
if w[i]=="0":
pass
else:
ans=(ans+now*l[-i-1])%mod
now=(now*2)%mod
if w[-1]=="0":
ans=(ans+now)%mod
else:
ans=(ans+3*now)%mod
if n==1:
print(3)
else:... | Aasthaengg/IBMdataset | Python_codes/p03015/s370813280.py | s370813280.py | py | 333 | python | de | code | 0 | github-code | 90 |
12916890091 |
import datetime
import numpy as np
#Get current time and round down the hours
dt = datetime.datetime.now()
dt = dt - datetime.timedelta(hours=dt.hour)
#list of all forcast times
forecastlist = []
# add hour offset and append to list
for i in range(0,48) :
dt = dt + datetime.timedelta(hours = i)
forecast... | MinusKeys/GribPy | createlist.py | createlist.py | py | 798 | python | en | code | 0 | github-code | 90 |
11586483343 | import logging
import re
import os
import hazm
import nltk
import functools
import operator
from zeep import Client
from requests.auth import HTTPBasicAuth
from requests import Session
from zeep.transports import Transport
import re
from hazm import *
import os
import gdown
from parstdex import Parstdex
from parsi_io.m... | language-ml/parsi.io | parsi_io/modules/question_generator.py | question_generator.py | py | 21,029 | python | en | code | 13 | github-code | 90 |
72873307498 | """ Implemente un programa que lea el contenido del fichero y realice los
siguientes cálculos:
● ¿Qué mes se ha gastado más?
● ¿Qué mes se ha ahorrado más?
● ¿Cuál es la media de gastos al año?
● ¿Cuál ha sido el gasto total a lo largo del año?
● ¿Cuáles han sido los ingresos totales a lo largo del año?
● Opcional:... | cfontcuberta/Buenas | actividad1/cfontcuberta_act1_copia.py | cfontcuberta_act1_copia.py | py | 1,159 | python | es | code | 0 | github-code | 90 |
12187964654 | #!/usr/bin/env python
import arvados
import arvados.collection
import sys
from arvados.arvfile import ArvadosFile
def main():
# Find (or create) collections to contain the sorted BAM and VCF files
newnameVCF = "PGP_vcf_collection"
destVCF = findCollection(newnameVCF)
newnameBAM = "PGP_bam_collection"
... | PGPHarvard/tools | datatools/collectVCFBAM_Veritas.py | collectVCFBAM_Veritas.py | py | 2,208 | python | en | code | 2 | github-code | 90 |
3407207544 | import numpy as np
from shapreg import utils
class StochasticCooperativeGame:
'''Base class for stochastic cooperative games with exogenous variable U.'''
def __init__(self):
pass
def __call__(self, S, U):
raise NotImplementedError
def sample(self, samples):
'''Sample exogeno... | andrewherren/shapley-regression | shapreg/stochastic_games.py | stochastic_games.py | py | 3,051 | python | en | code | null | github-code | 90 |
73674134057 | from django.test import TestCase
from django.core.exceptions import ValidationError
from unittest.mock import patch
from squad.core.models import Group, PatchSource
from squad.plugins import gerrit
plugins_settings = """
plugins:
gerrit:
build_finished:
success:
My-Custom-Label: "+1"
error:... | Linaro/squad | test/plugins/test_gerrit.py | test_gerrit.py | py | 11,922 | python | en | code | 54 | github-code | 90 |
11945660365 | import csv
import os
from palivocab import config
from palivocab.words.word import Word
class DataManager:
gender_mapper = {
'm': 'masculine',
'f': 'feminine',
'nt': 'neuter',
}
def generate_path(self, source=None, lesson_number=None, word_class=None):
path = os.path.join... | eBLDR/Pali-Vocab | palivocab/data_manager.py | data_manager.py | py | 3,925 | python | en | code | 0 | github-code | 90 |
17452744042 | import argparse
import json
import numpy as np
import os
import time
from tqdm import tqdm
from PIL import Image
from torchvision import transforms
from flowmatch.datasets.utils import id_to_str, str_to_id, center_crop, xywh2xyxy
from flowmatch.networks.flownet import FlowNet
from flowmatch.utils import load_config
... | siddancha/FlowVerify | flowmatch/datasets/obj_det.py | obj_det.py | py | 10,272 | python | en | code | 2 | github-code | 90 |
30768607190 | # coding: utf-8
import numpy as np
import time
def random_weight():
a = np.random.randint(1,101,size=5)
return np.sort(a)[::-1]
def weighting(data):
a = random_weight()
data_weighted = [[0] * 8] * 16
for i in range(16):
for j in range(8):
if data[i][j] == "A":
... | h13o/matching | method3.py | method3.py | py | 4,195 | python | en | code | 0 | github-code | 90 |
18195095113 | #!/usr/bin/python3
""" Module to operate on a text file """
def write_file(filename="", text=""):
""" Function to write a string to a text file
Args:
filename (str): name of the file
text (str): text to be written to file
Returns:
number of characters written to the file
"""... | n1klaus/alx-higher_level_programming | 0x0B-python-input_output/1-write_file.py | 1-write_file.py | py | 498 | python | en | code | 0 | github-code | 90 |
27676430670 | import numpy as np
import networkx as nx
from matplotlib import pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from .config import figstyle
from .statistics import dd, jdd
def plot_dd_and_jdd(A, title, save_to=None):
d = dd(A)
nbins = np.amax(d) + 1
# Degree Distribution
f, x =... | cwindolf/capstone | src/lib/plotting.py | plotting.py | py | 2,553 | python | en | code | 0 | github-code | 90 |
19756933327 | def twoNumberSum(array, targetSum):
# Create an empty set to store numbers we've seen so far
nums_seen = set()
for num in array:
# Calculate the complement of the current number with respect to the target sum
complement = targetSum - num
# If the complement is i... | AKSHAY20022/CodingChallenge | Two_Number_Sum_BetterTimeComplexity.py | Two_Number_Sum_BetterTimeComplexity.py | py | 729 | python | en | code | 0 | github-code | 90 |
7322615451 | try:
import os, sys, yaml
import ConfigParser
except ImportError:
pass
if __name__ == '__main__':
ymlfile = sys.argv[1]
with open(ymlfile, "r") as f:
content = yaml.load(f)
cf = ConfigParser.ConfigParser()
cf.add_section("pattern")
cf.add_section("no_pattern")
cf.add_section("others")
for n in xrange(len... | Hoohaha/ComDebugger | WpfApplication2/bin/Comdebugger_V3.8/interface/YamlPaser.py | YamlPaser.py | py | 658 | python | en | code | 1 | github-code | 90 |
18130363110 | # workaround to select Agg as backend consistenly
import os
from typing import Any, Dict, List, Union
import matplotlib as mpl # type: ignore
import matplotlib.pyplot as plt # type: ignore
import numpy as np
import pandas as pd
import seaborn as sns # type: ignore
mpl.use("Agg")
mpl.rcParams["text.latex.preamble"]... | Mic92/vmsh | tests/plot.py | plot.py | py | 5,038 | python | en | code | 100 | github-code | 90 |
25609273111 | import numpy as np
x = np.ones((5, 1))
w = np.random.uniform(0,1,(10, 5))
alpha = 0.01
Ytrue = np.ones((10, 5)).dot(x) / 10 # Function to be learned
print("Actual function")
print(Ytrue)
def sigmoid(x):
return 1/(1+np.exp(-x))
for i in range(10000):
Ypred = sigmoid(w.dot(x))
grad = ((Ypred - Ytrue) * Yt... | ZeyadYasser/Stanford-CS231n-Projects | numpy-neural-network/nn.py | nn.py | py | 488 | python | en | code | 1 | github-code | 90 |
35608301860 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
Script to convert to fixed file format to csv
'''
import os
import sys
import getopt
from datetime import datetime
from exceptions import NumericFormatException
from exceptions import DateFormatException
from exceptions import StringFormatException
from exceptions import ... | zhshun/csv-converter | converter.py | converter.py | py | 5,228 | python | en | code | 0 | github-code | 90 |
18380804799 | n = int(input())
ab = [list(map(int,input().split())) for _ in range(n)]
ab = sorted(ab,key=lambda x: x[1])
ans = 'No'
t = 0
for i in ab:
t += i[0]
if i[1] < t:
break
else:
ans = 'Yes'
print(ans) | Aasthaengg/IBMdataset | Python_codes/p02996/s293951525.py | s293951525.py | py | 217 | python | en | code | 0 | github-code | 90 |
41839802450 | # 부분구간합
# 2차원에서 구간합을 구하는 문제
import sys
n, m = map(int, sys.stdin.readline().split())
a = []
for i in range(n):
a.append(list(map(int, sys.stdin.readline().split())))
# a = [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7]]
b = []
for i in range(m):
b.append(list(map(int, sys.stdin.readline().split())))
#... | 96Jerry/BaekJun-problem | partial_sum/11660.py | 11660.py | py | 908 | python | en | code | 0 | github-code | 90 |
15635684012 | import streamlit as st
import preprocessor, helper
import matplotlib.pyplot as plt
import logging
def fetch_stats(selected_user, df):
"""
Fetches stats for the selected user or overall chat.
Args:
selected_user (str): The user to fetch stats for. If None, stats for overall chat will be fetched.
... | Abhijit1102/whatsapp_chat_analyser | app.py | app.py | py | 3,145 | python | en | code | 0 | github-code | 90 |
44772080071 | from tensorflow.keras.layers import Conv2D, Dropout, Flatten, Dense, Reshape, Conv2DTranspose, ReLU, BatchNormalization, LeakyReLU
from tensorflow import keras
import tensorflow as tf
def mnist_uni_gen_cnn(input_shape):
return keras.Sequential([
# [n, latent] -> [n, 7 * 7 * 128] -> [n, 7, 7, 128]
... | qiank128/mnistGANs | gan_cnn.py | gan_cnn.py | py | 3,296 | python | en | code | null | github-code | 90 |
13218439170 | import shutil
import sys
from pathlib import Path
import cv2 as cv
suffix_set = set(".avi,.mp4,.MOV,.mkv".split(","))
def find_videos(input_dir):
video_paths = []
for f in sorted(Path(input_dir).glob("**/*")):
if f.suffix in suffix_set:
video_paths.append(f.as_posix())
return video... | flystarhe/hello | hello/video/resize.py | resize.py | py | 3,502 | python | en | code | 2 | github-code | 90 |
70194442216 | import os
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column, String, Integer
from sqlalchemy_utils import database_exists, create_database
Base = declarative_base()
class DB:
def __init__(self):
... | mahmoudhossam/task-queue | db.py | db.py | py | 1,348 | python | en | code | 4 | github-code | 90 |
20297905844 | from random import randint
maximum=int(input("Enter the max value of dice:"))
print('The person who reaches {} wins.And if any player exits before the game ends ,a random number from (10-30) will be subtraced from thier score. '.format(str(10*maximum)))
player1=0
player2=0
while player1 < 10*maximum and player2 < 10*... | shiva341/python-projects | dice.py | dice.py | py | 963 | python | en | code | 0 | github-code | 90 |
18309721549 | '''
Created on 2020/09/04
@author: harurun
'''
def main():
import sys
pin=sys.stdin.readline
pout=sys.stdout.write
perr=sys.stderr.write
N=int(pin())
S=pin()[:-1]
cnt=0
l=["0","1","2","3","4","5","6","7","8","9"]
for i in l:
for j in l:
for k in l:
c=[i,j,k]
n=0
fo... | Aasthaengg/IBMdataset | Python_codes/p02844/s270753881.py | s270753881.py | py | 489 | python | en | code | 0 | github-code | 90 |
18493174169 | S = input()
T = input()
ans = 'Yes'
dic1,dic2 = {},{}
for i,j in zip(S,T):
if i in dic1:
if dic1[i] != j:
ans = 'No'
else:
dic1[i] = j
if j in dic2:
if dic2[j] != i:
ans = 'No'
else:
dic2[j] = i
#print(dic1)
#print(dic2)
print(ans) | Aasthaengg/IBMdataset | Python_codes/p03252/s493309710.py | s493309710.py | py | 314 | python | en | code | 0 | github-code | 90 |
18249616189 | import collections
n = int(input())
arr = list(map(int,input().split()))
cnt = collections.Counter(arr)
total = 0
for key in cnt.keys():
total += cnt[key] * (cnt[key] - 1)//2
for i in range(n):
tmp = total
tmp -= cnt[arr[i]]*(cnt[arr[i]] - 1)//2
tmp += (cnt[arr[i]] - 1)*(cnt[arr[i]] - 2)//2
print(tmp)
| Aasthaengg/IBMdataset | Python_codes/p02732/s749434989.py | s749434989.py | py | 318 | python | en | code | 0 | github-code | 90 |
17058279746 | # ----------------------------------------------------------------------------
#
# \file GetAtlasMacro.py
# \author pierre
# \date 2017-12-14
#
# get atlas for filename and week
# ----------------------------------------------------------------------------
from mevis import MLAB, MLABFileManager, MLABFil... | meribach/mevislabFetalMRI | Modules/Macros/CHUVFetalMRI/GetAtlasMacro.py | GetAtlasMacro.py | py | 2,348 | python | en | code | 0 | github-code | 90 |
2623817760 | import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from matplotlib.lines import Line2D
from sklearn.decomposition import PCA
import pandas as pd
from sklearn.manifold import TSNE
def plot_treatment(path, new_df, n, batch):
X = new_df.iloc[:, :-2].copy()
col = [mcolors.CSS4_COLORS['brown'], mc... | arivasm/Treatment_response_results | code/visualize_triples.py | visualize_triples.py | py | 1,867 | python | en | code | 0 | github-code | 90 |
18431164289 | from collections import Counter
mod = 10 ** 9 + 7
n = int(input())
s = input()
d = Counter(s)
res = 1
for v in d.values():
res = res * (v + 1) % mod
print(res - 1)
| Aasthaengg/IBMdataset | Python_codes/p03095/s667298030.py | s667298030.py | py | 170 | python | en | code | 0 | github-code | 90 |
23624900465 | import json
from mininet.net import Mininet
from mininet.topo import Topo
class customTopo(Topo):
""" create a custom topology"""
def __init__(self, **opts):
listenPort = 6653
Topo.__init__(self, **opts)
fl = open('network.json')
graph = json.load(fl)
fl.clo... | Irfan-Ahmad-byte/net_setup | network.py | network.py | py | 1,408 | python | en | code | 0 | github-code | 90 |
14552036184 | import paho.mqtt.client as mqtt
import random
import time
# broker_address = "b1386744d1594b29a88d72d9bab70fbe.s1.eu.hivemq.cloud"
broker_address = "broker.hivemq.com"
username = "cg4002_b15"
password = "CG4002_B15"
topic = "Sensor/Temperature/TMP1"
def on_connect(client, userdata, flags, rc):
if rc == 0:
... | shyamgj1900/CG4002_B15 | external_comms/client.py | client.py | py | 892 | python | en | code | 0 | github-code | 90 |
9849816724 | import Models.InterpolationLayer
import Utils
from Utils import LeakyReLU
import numpy as np
import tensorflow as tf
class UnetAudioEnhancer:
'''
U-Net network for audio enhancement.
Uses valid convolutions, so it predicts for the centre part of the input - only certain input and output shapes are theref... | jdavibedoya/SE_Wave-U-Net | Models/UnetAudioEnhancer.py | UnetAudioEnhancer.py | py | 7,600 | python | en | code | 3 | github-code | 90 |
24384830847 | """
+---------------------------+----------------------------------------------------------------------+
| Display Name | Somatic VC |
+---------------------------+----------------------------------------------------------------------+
| Short Name ... | MagdalenaZZ/Python_ditties | run_strelka_mertha.py | run_strelka_mertha.py | py | 8,331 | python | en | code | 0 | github-code | 90 |
3008807716 | from django.db.models import OuterRef, Subquery
from django.views.generic import FormView
from . import forms, models
class CurrencyFormView(FormView):
form_class = forms.CurrencyForm
template_name = "currencies/currency_form.html"
success_url = "/"
def form_valid(self, form):
start_date = f... | martynawitkowska/nbp_currency_browser | backend/currencies/views.py | views.py | py | 1,766 | python | en | code | 0 | github-code | 90 |
41678666069 | """Script containing the abstract policy class."""
import numpy as np
import tensorflow as tf
import tensorflow.contrib.slim as slim
from hbaselines.utils.tf_util import get_trainable_vars
from hbaselines.utils.tf_util import get_target_updates
class ActorCriticPolicy(object):
"""Base Actor Critic Policy.
A... | EC2EZ4RD/I2HRL | hbaselines/fcnet/base.py | base.py | py | 12,416 | python | en | code | 3 | github-code | 90 |
43970610704 | from inv_net.inv_net import InvNet
from visualization.vis import InvNetVisualization
root_file_dir = 'data/case1'
inv_net = InvNet()
inv_net.get_all_from_file(root_file_dir)
vis = InvNetVisualization(inv_net)
vis.draw() | durianh96/InvNet-inv-graph | graph_building_ex.py | graph_building_ex.py | py | 222 | python | en | code | 0 | github-code | 90 |
9468503850 | """Custom dataset mapper for semantic segmentation task.
This code is based on MaskFormerSemanticDatasetMapper.
"""
import copy
import logging
import torch
import torchvision
from detectron2.config import configurable
from detectron2.data import MetadataCatalog
from detectron2.data import detection_utils as utils
fr... | nab-126/adv-part-based-models | part_model/dataloader/detectron2/sem_seg_mapper.py | sem_seg_mapper.py | py | 9,595 | python | en | code | 0 | github-code | 90 |
20876756185 | def find_cycle(pos):
if visited[pos] == 2:
return False
if visited[pos] == 1:
return True
visited[pos] = 1
for el in matrix[pos]:
if find_cycle(el):
return True
visited[pos] = 2
return False
n, count = map(int, input().split())
matrix = [[] for _ in range(n ... | YFatMR/Algorithms | SanDiego/course_3/week2/acyclicity.py | acyclicity.py | py | 570 | python | en | code | 1 | github-code | 90 |
18422203899 | import itertools
def actual(a, b, c, d, e):
all_permutations = list(itertools.permutations([a, b, c, d, e], 5))
order_time_list = []
for orders in all_permutations:
elapsed_time = 0
for i in range(5):
elapsed_time += orders[i]
if i == 4:
# 最後の注文は... | Aasthaengg/IBMdataset | Python_codes/p03076/s560908046.py | s560908046.py | py | 843 | python | ja | code | 0 | github-code | 90 |
18543396469 | # coding: utf-8
A,B,C,X,Y = map(int, input().split())
minprice = 10**10
for i in range(max(X,Y)+1):
tmp = 0
tmp += C * i*2
tmp += A * max(0,X-i)
tmp += B * max(0,Y-i)
minprice = min(minprice, tmp)
print(minprice) | Aasthaengg/IBMdataset | Python_codes/p03371/s801800914.py | s801800914.py | py | 232 | python | en | code | 0 | github-code | 90 |
32548830199 | import os #importing library os
import colorama # importing library colorama
print("""
# # ##### ##### ## ##### ## ##### # ######
# # # # # # # # # # # # # # #
# # # # # # # ... | RoxCoderSA/Updatable | updatable.py | updatable.py | py | 5,458 | python | en | code | 2 | github-code | 90 |
18302168029 | import sys
n = int(input())
a = list(map(int, sys.stdin.readline().split()))
m = 1
for i in a:
if i == m:
m += 1
if m == 1:
print(-1)
exit(0)
print(1+n-m) | Aasthaengg/IBMdataset | Python_codes/p02832/s831301520.py | s831301520.py | py | 174 | python | en | code | 0 | github-code | 90 |
74872992935 | from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.http import require_POST
from cowshare.models import Product, Category
from .cart import Cart
from .forms import CartAddProductForm
from django.db.models import Sum
from orders.models import Order, OrderItem
from django.contri... | emmakodes/cowshare | cart/views.py | views.py | py | 2,620 | python | en | code | 0 | github-code | 90 |
18191910309 | N = int(input()) - 1
keta = 1
cumsum = 0
oldcumsum = 0
while True:
cumsum += 26 ** keta
if cumsum > N:
break
else:
oldcumsum = cumsum
keta += 1
N -= oldcumsum
#N -= 1
#print(keta)
name = ''
for k in range(1,keta+1):
ch_n = N // (26 ** (keta - k))
ch = chr(ord('a') + ch_n)
name += ch
N -= ch_n ... | Aasthaengg/IBMdataset | Python_codes/p02629/s209017783.py | s209017783.py | py | 352 | python | en | code | 0 | github-code | 90 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.