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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
23239896973 | from sys import stdin, stdout
def getAnswer(w: int, m: int) -> float:
sum_m: int = m * 10
if sum_m >= 5000:
sum_m -= 500
return w * 10 / sum_m
def solution():
w, m = map(int, stdin.readline().rstrip().split())
curMax: float = getAnswer(m, w)
answer: str = 'S'
for i in range(2):
... | anothel/CodeKata | 백준/Bronze/17450. 과자 사기/과자 사기.py | 과자 사기.py | py | 589 | python | en | code | 1 | github-code | 90 |
70591348778 | import ast
import discord
import config
import traceback
import datetime
import random
import asyncio
import uuid
from discord.ext import commands
from discord_slash import cog_ext, SlashContext
from discord_slash.utils.manage_commands import create_option, create_choice
class LootBoxes(commands.Cog):
def __init... | KAJdev/Melonpan | Cogs/LootBoxes.py | LootBoxes.py | py | 3,203 | python | en | code | 5 | github-code | 90 |
36780431544 | from distutils.util import execute
import pyttsx3
def setup(rate=170, volume=1):
engine = pyttsx3.init()
try:
voice_id ='HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_ZIRA_11.0'
engine.setProperty('voice', voice_id)
except:
voices = engine.getProperty('voic... | Vanshika02/Object-Detection-for-visually-impaired | speak_object.py | speak_object.py | py | 856 | python | en | code | 0 | github-code | 90 |
3209597386 | from collections import defaultdict
import csv
import json
import sys
def process_column_names(names):
out = names[:]
assert (out[0] == 'Percentile')
assert (out[1] == 'Year')
for i, n in enumerate(out):
out[i] = n.split('\n')[-1]
return out
def get_year_country_data(colnames, csvreader):
"""Consume... | ted-dokos/inequality-bar | src/data-wrangling/csv_to_json.py | csv_to_json.py | py | 4,708 | python | en | code | 0 | github-code | 90 |
71794788777 | # -*- coding: utf-8 -*-
import scrapy
from teacher.items import TeacherItem
class AtguiguSpider(scrapy.Spider):
name = 'Atguigu'
allowed_domains = ['guigu.com']
start_urls = ['http://www.atguigu.com/teacher.shtml']
def parse(self, response):
teacher_list = response.xpath('//div[@class="teacher... | LIMr1209/Internet-worm | day07/作业/teacher/teacher/spiders/Atguigu.py | Atguigu.py | py | 763 | python | en | code | 0 | github-code | 90 |
4799882496 | from helpers import clean_content
from discord import Embed
import hunspell
class HelpResponder:
def __init__(self, message):
self.original_message = message
self.query = clean_content(self.original_message.content, "!help")
def getReply(self):
help_embed = Embed(title="Bot Help", des... | hideaway-social/discord-divinity-bot | responders/help_responder.py | help_responder.py | py | 1,333 | python | en | code | 2 | github-code | 90 |
36914554945 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
from text.detector.nms import nms,rotate_nms
from apphelper.image import get_boxes
from text.detector.text_proposal_connector import TextProposalConnector
def normalize(data):
if data.shape[0]==0:
return data
max_=data.max()
min_=da... | chineseocr/chineseocr | text/detector/detectors.py | detectors.py | py | 2,378 | python | en | code | 5,610 | github-code | 90 |
40072098464 | import logging
import os
from torchvision import datasets
from torchvision.datasets import VisionDataset
_log = logging.getLogger(__name__)
class DigitFolder(VisionDataset):
"""DIGIT data loader where the images are arranged in this way: ::
root/class0/serial_number/xxx.png
root/class0/serial_nu... | facebookresearch/PyTouch | pytouch/datasets/digit.py | digit.py | py | 2,774 | python | en | code | 213 | github-code | 90 |
9550968413 | """
PyConvert module.
Converts QS projects into Python packages that can be parsed with MyPy
"""
import sys
import os
import os.path
import codecs
import xml.etree.ElementTree as ET
from multiprocessing import Pool
from typing import List, Tuple, TypeVar, cast, Dict, Optional
from pineboolib.core.utils import logging
... | deavid/pineboo | pineboolib/application/parsers/qsaparser/pyconvert.py | pyconvert.py | py | 8,173 | python | en | code | 4 | github-code | 90 |
18460391139 | from collections import deque
def BFS():
color=[["white" for _ in range(w)] for _ in range(h)]
queue=deque([])
ans=0
for i in range(h):
for j in range(w):
if color[i][j]=="white" and S[i][j]=="#":
queue.append([i,j])
color[i][j]="gray"
... | Aasthaengg/IBMdataset | Python_codes/p03157/s891779373.py | s891779373.py | py | 1,037 | python | en | code | 0 | github-code | 90 |
14286624799 | import os
import random
import datetime
from string import ascii_lowercase
from time import sleep
DEFAULT_SESSION_LENGTH = 25
DEFAULT_NUM_ACTIVITIES = 1
DEFAULT_RANDOM_ACTIVITY_AMOUNT = 5
session_length = DEFAULT_SESSION_LENGTH
num_activities = DEFAULT_NUM_ACTIVITIES
shortlist = []
queue = []
def create_files():
... | nafeu/activity-roulette | main.py | main.py | py | 8,593 | python | en | code | 0 | github-code | 90 |
23971407586 | """ 1. Write an app for a cafe. Decide on the items in the cafe, stock of each item in the morning,
stock in the evening, sales amount at the end of the day and profit for each item. You need to restock an item
if the supply reaches 20% of the stock. Print the 3 items with highest sales, and top 3 highest profit."""
... | Maheshwaran6380/Sayur_Mahesh | List_Problems/cafe.py | cafe.py | py | 3,148 | python | en | code | 0 | github-code | 90 |
71232437736 | import random
import gevent
from gevent import Greenlet
from gevent.queue import Queue
from pytest import mark, raises
from honeybadgerbft.core.reliablebroadcast import reliablebroadcast, reliablebroadcast_change, encode, decode
from honeybadgerbft.core.reliablebroadcast import hash, merkleTree, getMerkleBranch, merkle... | buptis073114/FAV-BFT | test/test_vofsq_rbc.py | test_vofsq_rbc.py | py | 2,690 | python | en | code | 0 | github-code | 90 |
73427594538 | """A word processing software is expected to calculate the frequency of each word in given
file. Write the python function “Find_all()” that accepts the file name and returns a
dictionary with word frequency"""
def findall():
F=open("happy.txt","r")
value=F.readlines()
for i in value:
for j... | Biancaa-R/simple-python-programs-for-absolute-beginers- | 1practice/freq.py | freq.py | py | 359 | python | en | code | 0 | github-code | 90 |
25292689779 | import argparse
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
import json
import time
import os.path
import csv
import re
import youtube_comment_crawl as ycc
with open('youtube_key.json') as json_file:
API_INFO = json.load(json_file)
DEVELOPER_KEY = API_INFO['DEVELOP... | limyj0708/Comment_Crawling | youtube_video_crawl.py | youtube_video_crawl.py | py | 5,730 | python | en | code | 0 | github-code | 90 |
74602559015 | #!/usr/bin/env python3
import math
from enum import Enum
import RPi.GPIO as GPIO
import time
import atexit
from datetime import datetime
#import matplotlib.pyplot as plt
#STATUS_LED = 10
#BTN_RUN_STOP = 11
#BTN_DIRECTION = 12
#BTN_SPEED_INCREASE = 13
#BTN_SPEED_DECREASE = 15
#MotorPin_A = 1... | brakedust/raspberry_pi_stuff | one_button.py | one_button.py | py | 10,668 | python | en | code | 0 | github-code | 90 |
18814941057 | import re
import datetime
import scrapelib
import requests
import pytz
from collections import defaultdict
from .actions import Categorizer
from .utils import xpath
from openstates.scrape import Scraper, Bill, VoteEvent as Vote
from utils import LXMLMixin
import lxml.etree
import lxml.html
class WABillScraper(Scrap... | openstates/openstates-scrapers | scrapers/wa/bills.py | bills.py | py | 24,450 | python | en | code | 820 | github-code | 90 |
23810268435 | def get_psnr(img, largest_pixel_list, smallest_pixel_list, co_largest_pixel_list, co_smallest_pixel_list, max_neighbor, min_neighbor, threshold, chunk_size=2):
ep = []
embed_index_max = []
embed_index_min = []
contexts = []
for mn, clpl in zip(max_neighbor, co_largest_pixel_list):
contexts.... | WeightedComplexity/WeightedComplexity | main.py | main.py | py | 4,899 | python | en | code | 0 | github-code | 90 |
31734599556 | """
The BinaryTree class for Lab 7.
"""
from typing import Any
class BinaryTree:
"""
A class representing a BinaryTree.
value - The value of the BinaryTree's root
left - The root node of this BinaryTree's left subtree.
right - The root node of this BinaryTree's right subtree.
"""
value: A... | CSMYang/CSC148 | csc148/lab_binary_tree.py | lab_binary_tree.py | py | 4,630 | python | en | code | 0 | github-code | 90 |
25412927327 | import os
import torch
import numpy as np
import imageio
import cv2
import pdb
def recursive_glob(rootdir=".", suffix=""):
return [
os.path.join(looproot, filename)
for looproot, _, filenames in os.walk(rootdir)
for filename in filenames
if filename.endswith(suffix)]
class citysc... | feinanshan/TDNet | Testing/dataloader.py | dataloader.py | py | 2,424 | python | en | code | 198 | github-code | 90 |
20649704045 | import numpy as np
#Input parameters.........................................
survey_name = "DES-VVDS "
author = "Pol Marti Sanahuja"
cat_file = "/Users/polstein/Dropbox/PhD_pmarti/Data/Photoz/DES-SV/vvds02hr/des_vvds02hr_detmodel_petro_JHK_spec_prior.bpz"
plot_folder = "./plot"
code = "BPZ"
qual_para = "odds"
#Fie... | polmartisanahuja/Photoz-Analysis | other/parameters.py | parameters.py | py | 1,920 | python | en | code | 0 | github-code | 90 |
29974973797 | from django.urls import path
from . import views
urlpatterns = [
path('todo-list/', views.TodoListAV.as_view(), name='todo-list'),
path('todo-list/<int:pk>', views.TodoDetailAV.as_view(), name='todo-detail'),
path('delete-all-todo/', views.delete_all, name='delete-all-todo'),
path('complete-all-todo/'... | Intigam-M/React-Todo-App | backend/todo/urls.py | urls.py | py | 455 | python | en | code | 0 | github-code | 90 |
8992672361 | # -*- coding: utf-8 -*-
# try something like
def index():
games = db(db.games.id > 0).select()
return locals()
def edit():
try:
request.args[0]
except IndexError:
redirect(URL('index'))
#form=crud.update(db.games, request.args(0))
db.games.id.readable = False
record = db.games(request.args[0])
form = SQLFO... | redris96/IceScheduler | controllers/game.py | game.py | py | 721 | python | en | code | 0 | github-code | 90 |
13411955077 | import os
from ImageData import ImageObject
from RepositoryManager import RepositoryManagerClass
FOLDER_DIR = 'natural_images/fruit/'
FOLDER_TO_PROCESS = 'new/'
if __name__ == '__main__':
repo = RepositoryManagerClass()
count = 0
for file in os.listdir(FOLDER_DIR):
print("Count {}".format(count)... | sonnguyen9800/ResearchOpenCV | main.py | main.py | py | 742 | python | en | code | 1 | github-code | 90 |
12976739904 | import os
## input
pvalue_file = "ctgov_data/nctid_with_pvalue"
pub_file = "nctid_publication_abstract/nctid2puburl.txt"
pub_folder = 'nctid_publication_abstract'
## output
pvalue_and_pub_file = "ctgov_data/nctid_with_pvalue_and_pub.txt"
with open(pvalue_file, 'r') as fin:
lines = fin.readlines()
nctid_with_pva... | futianfan/HINT | src/intersection_pvalue_and_publication.py | intersection_pvalue_and_publication.py | py | 1,817 | python | en | code | 0 | github-code | 90 |
27065426674 | from advent2pt1 import open_file
def elven_pairs(all_elves: list) -> list:
'''Break elves into pairs\n
Returns a list of paired elves'''
paired_elves = []
for line in all_elves:
index = line.index(",")
paired_elves.append([line[0:index], line[index + 1:len(line)].strip()])
re... | Shades4355/Advent-of-Code | 2022/advent4pt1.py | advent4pt1.py | py | 1,366 | python | en | code | 0 | github-code | 90 |
18252693549 | #B - Bishop △(TLE,WA)
H,W = map(int,input().split())
count = 0
if H == 1 or W == 1:#コーナーケース(H,Wが1の時どこにも動けない)
count = 1
elif H % 2 == 0:
count = (H // 2)*W
else :
count = (H // 2)*W + ((W + 2 - 1) // 2)#x/yの切り上げ:(x+y-1)//y
print(count) | Aasthaengg/IBMdataset | Python_codes/p02742/s574904914.py | s574904914.py | py | 295 | python | ja | code | 0 | github-code | 90 |
19297823105 | import json
import razorpay
from math import ceil
from django.contrib.auth import logout
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.conf import settings
from django.h... | ingenious-dev325/EcommerceWebsite | myweb/myproject/views.py | views.py | py | 12,562 | python | en | code | 0 | github-code | 90 |
42249656305 | def biggest(aDict):
'''
aDict: A dictionary, where all the values are lists.
returns: The key with the largest number of values associated with it
'''
big = 0
biggest = None
if aDict == {}:
return None
for key in aDict:
if len(aDict[key]) > big:
biggest = key... | coraallensavietta/pythonExercises | biggest.py | biggest.py | py | 420 | python | en | code | 0 | github-code | 90 |
4654797349 | # # -*- coding: utf-8 -*-
import jsonpickle
import os.path
from model.group import Group
import random
import string
import getopt # для чтения командной строки
import sys # чтобы получить доступ к этим опциям
#файл генерирует тестовые данные в формате json для создания/редактирования групп
#изменять длину генерируемых... | mtopchiev/address-book | generator/group.py | group.py | py | 2,878 | python | ru | code | 0 | github-code | 90 |
38990863878 | import numpy as np
import seaborn as sns
import itertools
import matplotlib.pyplot as plt
from pandas import read_csv
from sklearn.ensemble import AdaBoostClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsClassifier
from skl... | De-Gald/SoccerCorners | main.py | main.py | py | 11,201 | python | en | code | 0 | github-code | 90 |
18112071109 | def main():
input()
a = set(input().split())
input()
b = set(input().split())
print(len(a.intersection(b)))
if __name__ == "__main__":
import os
import sys
if len(sys.argv) > 1:
if sys.argv[1] == "-d":
fd = os.open("input.txt", os.O_RDONLY)
os.dup2(fd, s... | Aasthaengg/IBMdataset | Python_codes/p02267/s287281625.py | s287281625.py | py | 382 | python | en | code | 0 | github-code | 90 |
11438856218 | import rasterio
from affine import Affine
def array_to_raster(data, outfilename=None, format='GTiff', affine=Affine.identity(), projection=None):
"""
Only GTiff driver supported at present.
Will implicitly overwrite existing output.
prj must be a pyproj.Proj object
"""
if format != 'GTiff':
... | consbio/trefoil | trefoil/utilities/conversion.py | conversion.py | py | 764 | python | en | code | 13 | github-code | 90 |
18254474329 | N = int(input())
ans = []
def get_range(s):
start = ord("a")
end = ord(max(s))
return [chr(c) for c in range(start, end + 2)]
def pana(s):
if len(s) == N:
ans.append(s)
return
for t in get_range(s):
pana(s + t)
return
pana("a")
ans.sort()
print(*ans, sep="\n") | Aasthaengg/IBMdataset | Python_codes/p02744/s772569511.py | s772569511.py | py | 314 | python | en | code | 0 | github-code | 90 |
27239477672 | import numpy
import pandas
import sklearn
from sklearn.ensemble import RandomForestClassifier
from sprout.SPROUTObject import SPROUTObject
from sprout.utils import sprout_utils
from sprout.utils.dataset_utils import load_MNIST
from sprout.utils.general_utils import current_ms
from sprout.utils.sprout_utils import corr... | tommyippoz/SPROUT | examples/sklearn_example.py | sklearn_example.py | py | 2,781 | python | en | code | 3 | github-code | 90 |
35092709558 | '''
Given the head of a singly linked list, return true if it is a palindrome.
Input: head = [1,2,2,1]
Output: true
Input: head = [1,2]
Output: false
'''
# Definition for singly-linked list.
import collections
from typing import Deque
class ListNode:
def __init__(self, val=0, next=None):
self.val = va... | freeDevdh/python_algorithm | leetcode/linked_list/palindrome-linked-list.py | palindrome-linked-list.py | py | 1,220 | python | en | code | 0 | github-code | 90 |
20145988175 | #!/bin/env python
from typing import List
from collections import defaultdict
class Solution:
def majorityElement(self, nums: List[int]) -> int:
nums.sort()
return nums[len(nums)//2]
def majorityElement_vote(self, nums: List[int]) -> int:
"""
Go through the list:
majori... | theodoresi/leetcode_solutions | python_version/169_majority_element/majority_element.py | majority_element.py | py | 1,242 | python | en | code | 0 | github-code | 90 |
74305914535 | '''
For each level, add value for each node, and expand the son nodes for the next level
1. Use deque to build a queue, right in, left out
Time: Loop through n nodes, therefore O(n)
Space: Store n nodes in queue, therefore O(n)
'''
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self... | fudigit/Basic_Algorithm | 4.BFS&Topological_Sort/69.Binary_Tree_Level_Order_Traversal.py | 69.Binary_Tree_Level_Order_Traversal.py | py | 1,417 | python | en | code | 0 | github-code | 90 |
40400969950 | #!/usr/bin/env python3
import tokenize
from io import StringIO
from textwrap import dedent
from token import STRING, NL
import sys
def concat_check_files_messages(file_names):
for file_name, line_number in concat_check_files(file_names):
yield f"{file_name}, line {line_number}: implicit concatenation"
... | TecKnow/learning | pythonmorsels/concat_check/concat_check.py | concat_check.py | py | 1,234 | python | en | code | 0 | github-code | 90 |
22491356140 | import os
import shutil
import logging
from functools import partial
import qtawesome as qta
from Qt import QtWidgets, QtCore
from rez.config import config
from rez.package_copy import copy_package
from .utils import catch_exception
def get_local_repo_index():
packages_path = config.get('packages_path', [])
... | cuckon/rez-manager | src/rez_manager/views.py | views.py | py | 5,939 | python | en | code | 22 | github-code | 90 |
43583342164 | from omero.gateway import BlitzGateway
from omero.rtypes import rlong, rstring
import omero.scripts as scripts
# Deletes all rois in a list of Image Ids
def deleteROIs(conn, ids):
print("Checking Images: " + str(ids))
rois_removed = []
for id in ids :
try :
result = conn.getObjects("ro... | LavLabInfrastructure/omeroScriptsLLAB | histoqc/util_scripts/Delete_ROIs.py | Delete_ROIs.py | py | 2,695 | python | en | code | 0 | github-code | 90 |
3487681591 | """fully taken from ignite example"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchtext.vocab import GloVe
from ignite.engine import Engine, Events
from ignite.metrics import Accuracy, Loss, RunningAverage
from ignite.handlers import ModelCheckpoint, EarlyStopping
from ignite.contrib.ha... | pollomarzo/learNN | teo/brevtorch_fakenews/src/TextCNN.py | TextCNN.py | py | 4,328 | python | en | code | 1 | github-code | 90 |
34479755241 | import pandas as pd
from datetime import date as dt
import xlsxwriter as xlw
#Functions
def Add_to_Worksheet(worksheet, sheet, i, count):
myVals = [
str(pd.to_datetime(sheet['Date'][i])),
str(sheet['Close'][i])
]
worksheet.write(('A' + str(count)), i)... | BreakTCode/Downturn-Analysis | Downturn-Analysis V1.py | Downturn-Analysis V1.py | py | 3,530 | python | en | code | 0 | github-code | 90 |
41799368984 | class Hero:
'Description the superhero!'
def __len__(self):
return len(self.__dict__)
def __str__(self):
res = ''
for i,j in sorted(self.__dict__.items()):
res += f'{str(i)}: {str(j)}\n'
return res.rstrip('\n')
hero = Hero()
assert len(hero) == 0
hero.health = ... | gotcrab/oop_training | magic_str_repr/Hero_len.py | Hero_len.py | py | 826 | python | en | code | 0 | github-code | 90 |
18410491639 | n=int(input())
t1=2
comb=set()
while t1*t1<=n:
if n%t1==0:
t2=n//t1
m=t1-1
if t2==n%m:
comb.add(m)
m=t2-1
if t1==n%m:
comb.add(m)
t1+=1
if n>2:
print(sum(comb)+n-1)
else:
print(sum(comb)) | Aasthaengg/IBMdataset | Python_codes/p03050/s069476612.py | s069476612.py | py | 270 | python | en | code | 0 | github-code | 90 |
16414576201 | from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
class TrainMetricRecorder:
#train loss
#val loss
#train accuracy
#val accuracy
METRICS = {'accuracy': accuracy_score, 'precision': precision_score, 'recall': recall_score, 'f1_score': f1_score}
def __init__(sel... | sunnynevarekar/image-classification-recipe | callbacks.py | callbacks.py | py | 2,520 | python | en | code | 0 | github-code | 90 |
18165203989 |
N = int(input())
As = list(map(int, input().split()))
ans = 0
tall = int(As[0])
for A in As:
if(tall > A):
ans += tall - A
else:
tall = A
print(ans) | Aasthaengg/IBMdataset | Python_codes/p02578/s088404675.py | s088404675.py | py | 158 | python | en | code | 0 | github-code | 90 |
14391225291 | import sqlite3
import requests
from sqlite3 import Error
from flask import abort
from flask import Flask
from flask import jsonify
from flask import request
from bs4 import BeautifulSoup
from flask import make_response
from flask_httpauth import HTTPBasicAuth
app = Flask(__name__)
#====================================... | NazimNaeem/python_learn | task12/main.py | main.py | py | 2,650 | python | en | code | 0 | github-code | 90 |
6746490159 | from typing import List, Union
from enum import Enum, auto
class OrderState(Enum):
INCONCLUSIVE = auto()
CORRECT = auto()
WRONG = auto()
PuzzleInput = List[str]
SignalPacket = List[Union[List[str], str]]
def load_puzzle_input(case: str) -> PuzzleInput:
if case == "puzzle":
file_name = "Day... | VictorOnink/Advent-of-Code-2022 | Day_13_Distress_Signal/day_13_file.py | day_13_file.py | py | 3,451 | python | en | code | 0 | github-code | 90 |
18110279569 | # -*- coding:utf-8 -*-
from collections import deque
result = deque()
def operation(command):
if command[0] == "insert":
result.appendleft(command[1])
elif command[0] == "delete":
if command[1] in result:
result.remove(command[1])
elif command[0] == "deleteFirst":
resu... | Aasthaengg/IBMdataset | Python_codes/p02265/s072224219.py | s072224219.py | py | 495 | python | en | code | 0 | github-code | 90 |
23046375691 | '''
567. Permutation in String
Medium
Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string.
Example 1:
Input: s1 = "ab" s2 = "eidbaooo"
Output: True
Explanation: s2 contains o... | aditya-doshatti/Leetcode | permutation_in_string_567.py | permutation_in_string_567.py | py | 984 | python | en | code | 0 | github-code | 90 |
26479383281 | import cv2
from os import path, mkdir, walk
from numpy import ndarray
from typing import Union
class CapturaImagens:
def __init__(self,
nome_do_sinal: str,
quantidade_de_capturas: int,
captura_de_video: Union[int, str]):
self.__nome_do_sinal = nome_do_sin... | HiagoAdao/PedraPapelTesoura | pedra_papel_tesoura/conjunto_de_dados/captura_imagens.py | captura_imagens.py | py | 3,968 | python | pt | code | 1 | github-code | 90 |
2677808751 | import copy
import itertools
from utils import *
rows = 'ABCDEFGHI'
cols = '123456789'
def cross(a, b):
return [s+t for s in a for t in b]
boxes = cross(rows, cols)
row_units = [cross(r, cols) for r in rows]
column_units = [cross(rows, c) for c in cols]
square_units = [cross(rs, cs) for rs in ('ABC','DEF','GHI'... | AakankshaDC/aind_sudoku_solver | solution.py | solution.py | py | 7,134 | python | en | code | 0 | github-code | 90 |
9786590898 | #palindromos
frase = input("Digite uma frase ou palavra: ")
frase = frase.strip()
frase = frase.upper()
fraseAnalise = frase.replace(" ", "")
palindromo = True
tamanho = len(fraseAnalise)
for a in range(0,tamanho):
if fraseAnalise[a] != fraseAnalise[tamanho-1-a]:
palindromo = False
break
if palind... | Nubreu/TerraLab | sprint02/53.py | 53.py | py | 452 | python | pt | code | 0 | github-code | 90 |
18166608169 | h, w, m = map(int, input().split())
h_cnt = [0 for _ in range(h)]
w_cnt = [0 for _ in range(w)]
xs = []
ys = []
for _ in range(m):
y, x = map(int, input().split())
y -= 1
x -= 1
h_cnt[y] += 1
w_cnt[x] += 1
xs.append(x)
ys.append(y)
h_max = max(h_cnt)
w_max = max(w_cnt)
h_max_induce = {i: v f... | Aasthaengg/IBMdataset | Python_codes/p02580/s878938783.py | s878938783.py | py | 666 | python | en | code | 0 | github-code | 90 |
18162621589 | n, m = list(map(int, input().split()))
relations = {}
for _ in range(m):
a, b = list(map(int, input().split()))
a -= 1
b -= 1
if relations.get(a):
relations[a].append(b)
else:
relations[a] = [b]
if relations.get(b):
relations[b].append(a)
else:
relations[b] = [a]
from collections import... | Aasthaengg/IBMdataset | Python_codes/p02573/s886640334.py | s886640334.py | py | 837 | python | en | code | 0 | github-code | 90 |
73211677098 | #
# @lc app=leetcode id=1047 lang=python
#
# [1047] Remove All Adjacent Duplicates In String
#
# @lc code=start
class Solution(object):
def removeDuplicates(self, s):
"""
:type s: str
:rtype: str
"""
# Stack solution is the simplest in this case
stack = []
... | ashshekhar/leetcode-problems-solutions | 1047.remove-all-adjacent-duplicates-in-string.py | 1047.remove-all-adjacent-duplicates-in-string.py | py | 641 | python | en | code | 0 | github-code | 90 |
26555755151 | import os
import win32gui
import time
import sys
import subprocess
#png or PNG makes a difference it is CASE sensative !
BOT_LEFT_IMG = 'BBDefense_BTN.png'
TOP_LEFT_IMG = 'Gale3BetBTNDef.png'
BOT_RIGHT_IMG = 'GaleRFI - Copy - Copy.PNG'
TOP_RIGHT_IMG = '3BetIPPotBluffs.PNG'
BOT_LEFT_PATH = 'F:\\CrushPoker\\OverNightM... | galethegreat/Poker_ALL_Open | Poker_Charts_Open.py | Poker_Charts_Open.py | py | 2,184 | python | en | code | 0 | github-code | 90 |
14221521341 | from classes import VkUser
from config import token
user1 = VkUser(token)
user2 = VkUser(token, owner_id=171681064)
user1.get_friends()
user2.get_friends()
user2.friends.append(21444050)
user_mutual = user1 & user2
for friend in user_mutual:
print(friend.last_name, friend.first_name)
print(friend)
| EmilTK/python_netology | lesson11/main.py | main.py | py | 310 | python | en | code | 0 | github-code | 90 |
31376525584 |
import sys
def test(actual, expected):
""" Compare the actual to the expected value,
and print a suitable message.
"""
linenum = sys._getframe(1).f_lineno # Get the caller's line number.
if (expected == actual):
msg = "Test on line {0} passed.".format(linenum)
else:
... | Ronald-Gutierrez/Fundamentos-de-la-Programacion | ejercicios de string/ejercicio8.py | ejercicio8.py | py | 869 | python | en | code | 0 | github-code | 90 |
18515441989 | n=int(input())
a=list(map(int,input().split()))
ans=0
now=0
for i in range(n):
if now != a[i]:
now=a[i]
else:
now=0
ans+=1
print(ans) | Aasthaengg/IBMdataset | Python_codes/p03296/s097499362.py | s097499362.py | py | 149 | python | en | code | 0 | github-code | 90 |
4952125742 | from django.urls import path
from recipeapp.views import (
index,
RegisterView,
LoginView,
LogoutView,
CommentCreateView,
recipe_list,
recipe_detail,
recipe_delete,
RecipeCreateView,
category_detail,
CategoryCreateView,
TagCreateView,
CommentEditView,
CommentDelet... | AWP2019-2020/topchef | recipeapp/urls.py | urls.py | py | 1,604 | python | en | code | 0 | github-code | 90 |
40171192684 | #coding=utf8
import json
import django
import os
'''
此文件未完成。
'''
os.environ['DJANGO_SETTINGS_MODULE']='backend.settings'
django.setup()
os.system("python makedata.py")
from django.test import TestCase
from django.contrib.auth.models import User
from sua.views import *
from sua.AdminViews import *
# Crea... | GYS-team/GYS-backend | tests.py | tests.py | py | 4,906 | python | en | code | 0 | github-code | 90 |
28733915246 | import argparse
import time
import os
from rot13 import rot13
from header import make_head, r_body, read_head
from bytes_decoder import tobits, listtobytes
from concurrent.futures import ThreadPoolExecutor
# Trabajo de hilos
def worker(byte, bit):
if (byte % 2 == 0) and (bit == 1):
byte += 1
# Sum... | naldeco98/lab | alumnos/58032-Nicolas-Aldeco/r-tp2/main.py | main.py | py | 4,758 | python | es | code | null | github-code | 90 |
18017248611 | from functools import partial
from torch.nn.modules.loss import _Loss
from .functional import focal_loss_with_logits
__all__ = ["BinaryFocalLoss", "FocalLoss"]
class BinaryFocalLoss(_Loss):
def __init__(
self,
alpha=0.5,
gamma=2,
ignore_index=None,
reduction="mean",
... | SysCV/transfiner | pytorch_toolbelt/losses/focal.py | focal.py | py | 2,783 | python | en | code | 501 | github-code | 90 |
13608779689 | #
# abc096 b
#
import sys
from io import StringIO
import unittest
class TestClass(unittest.TestCase):
def assertIO(self, input, output):
stdout, stdin = sys.stdout, sys.stdin
sys.stdout, sys.stdin = StringIO(), StringIO(input)
resolve()
sys.stdout.seek(0)
out = sys.stdout.r... | mskt4440/AtCoder | abc096/b.py | b.py | py | 915 | python | en | code | 0 | github-code | 90 |
42497859759 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import rospy
from geometry_msgs.msg import Twist
NODE_NAME = "turtle_mover"
TOPIC_NAME = "cmd_vel"
MSG_TYPE = Twist
PUBLISH_HZ = 10.0
class topic_publisher():
def __init__(self):
rospy.init_node(NODE_NAME)
self.publisher1 = rospy.Publisher(TOPIC_NAME, MSG_TYPE, queue... | macho-yoo/ROS_WS | src/scout_sim_launch/scripts/twist_pub.py | twist_pub.py | py | 1,411 | python | ko | code | 0 | github-code | 90 |
18504614739 | s = input()
k = int(input())
cnt = 0
for i in range(len(s)):
if s[i]=="1":
cnt += 1
else:
break
if cnt < k:
print(s[cnt])
else:
print(1) | Aasthaengg/IBMdataset | Python_codes/p03282/s699331464.py | s699331464.py | py | 170 | python | en | code | 0 | github-code | 90 |
29988445241 | # QPushButton
# 父类QAbstractButton
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
class QPushButtonDemo(QDialog):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('QPushButton控件演示')
... | gaoleifx/Python_project | QT/QPushButton.py | QPushButton.py | py | 1,700 | python | en | code | 0 | github-code | 90 |
24175408964 | import cv2
import numpy as np
import pandas as pb
import math
from fastseg import MobileV3Large, MobileV3Small
from fastseg.image import colorize, blend
import cv2
model = MobileV3Small.from_pretrained().cuda()
model.eval()
import numpy as np
import time
# Open a local image as input
from PIL import Image
import pickle... | CagedRage/ProjectIris | downloadalllabels.py | downloadalllabels.py | py | 1,811 | python | en | code | 0 | github-code | 90 |
5817434096 |
X = [l.strip() for l in open('Labs/input.txt').readlines()]
Q = []
for elf in ('\n'.join(X)).split('\n\n'):
q = 0
for x in elf.split('\n'):
q += int(x)
Q.append(q)
Q.sort()
print(Q[-1] + Q[-2] + Q[-3]) | KarstenLansing/MarkdownNotes | notes/Labs/1.py | 1.py | py | 224 | python | en | code | 0 | github-code | 90 |
25713112652 | '''
Inversions
'''
c = 0
def inversion_cnt(a, n):
# O(n^2), Exceeds time limit
cnt = 0
for i in range(n):
for j in range(i, n - 1):
if a[i] > a[j + 1]:
cnt += 1
return cnt
def merge_invers_count(a:list, b:list):
# n(logn). Had to use the global var for the recursive ap... | HornbillFromMinsk/EPIC | Algos/Homework/hw_sorting_inversions_count.py | hw_sorting_inversions_count.py | py | 1,121 | python | en | code | 0 | github-code | 90 |
7574375400 | from .ticket_auth import TktAuthentication
COOKIE_AUTH_KEY = 'aiohttp_auth.auth.CookieTktAuthentication'
class CookieTktAuthentication(TktAuthentication):
"""Ticket authentication mechanism based on the ticket_auth library, with
ticket data being stored as a cookie in the response.
"""
async def re... | gnarlychicken/aiohttp_auth | aiohttp_auth/auth/cookie_ticket_auth.py | cookie_ticket_auth.py | py | 2,519 | python | en | code | 12 | github-code | 90 |
72910600616 | from yogi import *
from math import *
from turtle import *
def dibuixar_rellotge(h: int, m: int) -> None:
"""Dibuixa un rellotge il·lustrant el temps d'entrada."""
# Es dibuixa el cercle.
penup()
goto(0, -200)
pendown()
circle(200)
penup()
goto(0, 0)
# Es dibuixen les... | lluc-palou/ap1-jutge | functions, actions and types/P48022.py | P48022.py | py | 1,768 | python | ca | code | 0 | github-code | 90 |
72291249898 | from django.urls import path
from . import views
urlpatterns = [
path('', views.api_root, name='root'),
path('requests/', views.RequestsList.as_view(), name='requests-list'),
path('customers/', views.CustomersList.as_view(), name='customers-list'),
path('customers/<str:username>/', views.CustomerDetai... | EvgenyOcean/2020-d2tree5 | django-back/market/urls.py | urls.py | py | 949 | python | en | code | 1 | github-code | 90 |
30723210744 | import click
import fuse
from logbook.handlers import StderrHandler
from logbook.compat import redirect_logging
from logbook import Logger, DEBUG, INFO
from .fs import LegitFS
log = Logger('cli')
@click.command(help='Mount a git repository with history at MOUNTPOINT')
@click.argument(
'mountpoint',
type=cl... | mbr/legitfs | legitfs/cli.py | cli.py | py | 1,251 | python | en | code | 6 | github-code | 90 |
8663467547 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.metrics import *
import matplotlib
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# 读入数据
# score矩阵存放数据
score = np.zeros((1000,... | zhangwei19980131/Python-course | 使用Python自动化/Method_1.py | Method_1.py | py | 916 | python | en | code | 0 | github-code | 90 |
7004937213 | from rest_framework import generics
from rest_framework.response import Response
from post.models import PostModel
from post.api.serializer import PostSerializer, PostDetailSerializer, PostLikeSerializer
class PostList(generics.ListCreateAPIView):
serializer_class = PostSerializer
def get_queryset(self):
... | shevchykH/social_network_src | post/api/views.py | views.py | py | 1,358 | python | en | code | 0 | github-code | 90 |
20115838502 | '''
Given the root of a binary tree, return the vertical order traversal of its nodes' values. (i.e., from top to bottom, column by column).
If two nodes are in the same row and column, the order should be from left to right.
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, le... | XihangJ/leetcode | BFS/314. Binary Tree Vertical Order Traversal.py | 314. Binary Tree Vertical Order Traversal.py | py | 1,431 | python | en | code | 1 | github-code | 90 |
15446254209 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import logging
import os
import argparse
import config.loader
import background.endpoint
import time
def run(cycle=True, interval=3):
while True:
if background.endpoint.work(): continue
if not cycle: break
time.sleep(interval*60)
def test_run(... | pblin/soshio | analysis/worker.py | worker.py | py | 829 | python | en | code | 0 | github-code | 90 |
21360426254 | #!/usr/bin/python
#
# Perform optical character recognition, usage:
# python3 ./image2text.py train-image-file.png train-text.txt test-image-file.png
#
# Authors: (insert names here)
# (based on skeleton code by D. Crandall, Oct 2020)
#
from PIL import Image, ImageDraw, ImageFont
import sys
import numpy as np
imp... | saathvik13/Optical-Character-Recognition_HMM | image2text.py | image2text.py | py | 9,754 | python | en | code | 0 | github-code | 90 |
18141862859 | # coding: utf-8
row, col = map(int, input().split())
spreadsheet = []
for i in range(row):
val = list(map(int, input().split()))
val.append(sum(val))
spreadsheet.append(val)
for r in spreadsheet:
print(' '.join(map(str, r)))
last_row = []
for j in range(len(spreadsheet[0])):
col_sum = 0
for ... | Aasthaengg/IBMdataset | Python_codes/p02413/s218731841.py | s218731841.py | py | 454 | python | en | code | 0 | github-code | 90 |
12008711120 | import tensorflow as tf
import numpy as np
float_type = tf.float64
from npde import NPODE, NPSDE, BrownianMotion
from kernels import OperatorKernel
from utils import plot_model
def npde_fit(sess,t,Y,model='sde',sf0=1.0,ell0=[2,2],sfg0=1.0,ellg0=[1e5],
W=6,ktype="id",whiten=True,Nw=50,
fix_e... | velait/OUP | NPDE/npde-master/npde_helper.py | npde_helper.py | py | 7,413 | python | en | code | 1 | github-code | 90 |
23785221771 | import csv
import datetime
from datetime import timedelta
from dateutil.relativedelta import relativedelta
import argparse
import bbgClient
import os
import pandas as pd
MONTHLY_FILE_NAME = "C:/DataBatch_ETF_NewProject/Output/US_IDX_IMP_M_update.csv"
DAILY_FILE_NAME = "C:/DataBatch_ETF_NewProject/Output/dpricing_chang... | nsawant55ip/DataBatch_ETF3 | Code/bbgIndices.py | bbgIndices.py | py | 9,557 | python | en | code | 0 | github-code | 90 |
10995953021 | import os
import re
import io
from setuptools import setup, find_packages
BITTYTAX_PATH = os.path.expanduser('~/.bittytax')
VERSION_FILE = 'bittytax/version.py'
GITHUB_REPO = 'https://github.com/BittyTax/BittyTax'
def get_version():
line = open(VERSION_FILE, 'rt').read()
version = re.search(r'^__version__ = ... | 737147948/BittyTax | setup.py | setup.py | py | 2,151 | python | en | code | null | github-code | 90 |
30748628473 | import numpy
from sys import path
path.append("D:/Github/astrophy-research/mylib")
path.append("D:/Github/astrophy-research/multi_shear_detect")
import h5py
from plot_tool import Image_Plot
chisa_name = "chisq_diff_expo"
data_path = "E:/works/correlation/CFHT/cut_2.5/smooth/zbin_111111"
h5f = h5py.File("%s/%s.hdf5"... | hekunlie/astrophy-research | CFHTLenS/Fourier_Quad/correlation/correlation_exposure_wise/MCMC/plot_brutal_search.py | plot_brutal_search.py | py | 1,443 | python | en | code | 2 | github-code | 90 |
10223447047 | import numpy as np
import scipy
import matplotlib.pyplot as plt
def determinant_calc():
# create set of random 4x4 arrays with values from 0 to 1
setArray = np.array(
[np.random.rand(4, 4), np.random.rand(4, 4), np.random.rand(4, 4), np.random.rand(4, 4), np.random.rand(4, 4)])
# calculate determi... | SoencerKelly/Physics3926ASS | Lab7/Kelly_Spencer_Lab7.py | Kelly_Spencer_Lab7.py | py | 4,307 | python | en | code | 2 | github-code | 90 |
31995946435 | """Source code for distributed attentional actor architecture after another attention (DA6) model.
Author: Yoshinari Motokawa <yoshinari.moto@fuji.waseda.jp>
"""
from typing import List
import numpy as np
import torch
from core.handlers.observations.observation_handler import ObservationHandler
from core.utils.loggin... | Yoshi-0921/MAEXP | core/agents/models/customs/da6_iqn_cond.py | da6_iqn_cond.py | py | 7,157 | python | en | code | 1 | github-code | 90 |
28104431107 | iN1 = int(input("Ingrese el numero para saber si es perfecto o no: "))
iCont = 1
iNum = 0
while iCont != iN1:
if (iN1 % iCont) == 0:
iNum = iNum + iCont
iCont = iCont + 1
print("-" * 50)
if iNum == iN1:
print(f"El numero {iN1} es perfecto")
else:
print(f"El numero {iN1} no es perfecto") | AlejandroP75/CampusAP75 | Python/Clases/Python/C5-Ciclo while/Ejercicio saber si un numero es perfecto o no.py | Ejercicio saber si un numero es perfecto o no.py | py | 317 | python | ro | code | 0 | github-code | 90 |
36498845107 | import torch
from torch import nn
import torch.nn.functional as F
device = torch.device('cuda:1')
class EmbedVector(nn.Module):
def __init__(self, config):
super(EmbedVector, self).__init__()
self.config = config
# 目标维度
target_size = config.label
# 实体查找表(14951,100)
... | liushizhong123/RPJE | embedding.py | embedding.py | py | 3,417 | python | en | code | 3 | github-code | 90 |
36270714207 | """comments
Revision ID: 78bc7345edfb
Revises: 2a8d08a2c5ad
Create Date: 2021-04-06 13:36:20.585985
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '78bc7345edfb'
down_revision = '2a8d08a2c5ad'
branch_labels = None
depends_on = None
def upgrade():
op.crea... | guldfisk/fml | migrations/versions/78bc7345edfb_comments.py | 78bc7345edfb_comments.py | py | 732 | python | en | code | 1 | github-code | 90 |
42273979137 | import cv2
import numpy as np
import dlib
from math import hypot
from scipy.spatial import distance as dist
from imutils import face_utils
import argparse
import world
import math
from keras.preprocessing import image
from keras.models import Model, Sequential
from keras.layers import Conv2D, MaxPooling2D, A... | michaelcandra/face_pose_dev | Facial Landmark/main3.py | main3.py | py | 3,010 | python | en | code | 0 | github-code | 90 |
39891290117 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 15 09:48:02 2018
@author: up201706860
"""
def translate(astring, table):
for i in range (len(table)):
(caract,subs)=table[i]
astring=astring.replace(caract, str(subs))
return astring
| TitanicThompson1/FPRO | Práticas/translate.py | translate.py | py | 301 | python | en | code | 0 | github-code | 90 |
42289002937 | import functools
import logging
import urllib.parse
from pprint import pformat
from typing import Any, Callable, List
import requests # type: ignore
from .. import config, exceptions, logging_messages
from . import failed_response_handler
LOGGER = logging.getLogger(__name__)
def wrap(check_on_prem: bool = False) ... | comet-ml/comet-llm | src/comet_llm/experiment_api/request_exception_wrapper.py | request_exception_wrapper.py | py | 2,073 | python | en | code | 287 | github-code | 90 |
41639031691 | import sys
def conversorBinarioDecimal(binario):
binario = list(binario)
decimal = 0
for i in range(len(binario)):
decimal += int(binario[i])*2**(len(binario) - i - 1)
return decimal
def conversorBinarioDecimalSM(binario):
if binario[0] == '0':
sinal = 1
else:
sinal = ... | RafaelNeiva2/Trabalho-Arquitetura_de_Computadores | ConversorDeBases.py | ConversorDeBases.py | py | 3,176 | python | pt | code | 0 | github-code | 90 |
71766495978 | # Python3 program to Convert characters
# of a string to opposite case
# Function to convert characters
# of a string to opposite case
def convertOpposite(str):
ln = len(str)
# Conversion according to ASCII values
for i in range(ln):
if str[i] >= 'a' and str[i] <= 'z':
# Convert lowercase to upperca... | gauravk268/Competitive_Coding | Python Competitive Program/convert_capital to small.py | convert_capital to small.py | py | 698 | python | en | code | 19 | github-code | 90 |
1250317052 | import scrapy
import re
import dateparser
from tpdb.BaseSceneScraper import BaseSceneScraper
class siteSapphixSpider(BaseSceneScraper):
name = 'Sapphix'
network = 'Sapphix'
parent = 'Sapphix'
start_urls = [
'https://www.sapphix.com',
]
selector_map = {
'title': '//h2/text()'... | SFTEAM/scrapers | scenes/siteSapphix.py | siteSapphix.py | py | 1,984 | python | en | code | null | github-code | 90 |
71008987176 |
n = float(input("ingrese los segundos: "))
if n >= 0:
hrs = int(n/3600)
tiempo = n % 3600
min = int(tiempo/60)
seg = tiempo % 60
print("la convercion es: ", hrs, ":", min, ":", seg)
else:
print("error el numero no debe ser cero")
| Kazansky98/iceman | ejercicio 10.py | ejercicio 10.py | py | 267 | python | es | code | 0 | github-code | 90 |
38133679160 | from View.GameStateENUM import GridObjects as go
from copy import deepcopy
class AbstractStrategy():
def __init__(self, viewManager, gameWindow):
self.viewManager = viewManager
self.gameWindow = gameWindow
def Solve(self):
print("wip")
def Sort(self, currentGrid):
#set mazewalls to a list of ... | Miko3o/maze_solver | part_3_b/Controller/Strategies/AbstractStrategy.py | AbstractStrategy.py | py | 786 | python | en | code | 0 | github-code | 90 |
4543286086 | from django.urls import path, include
from . import views
app_name = "Transactions"
urlpatterns = [
path('', views.index, name='index'),
path('place/', views.Place, name='Place'),
path('mytrades/', views.MyTrades, name='MyTrades'),
path('trades/', views.Trades, name='Trades'),
path('buy/<int:AdId>... | OdenigboGodfrey/currency_trade | Transactions/urls.py | urls.py | py | 997 | 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.