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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
14806245075 | import timeit
def t1():
li = []
for i in range(10000):
li.append(i)
def t2():
li = []
for i in range(10000):
li = li +[i]
def t3():
li = [i for i in range(10000)]
def t4():
li = list(range(10000))
def t5():
li = []
for i in range(10000):
li.insert(0, i)
... | penguinsss/Project | 基础语法/列表类型性能测试.py | 列表类型性能测试.py | py | 978 | python | en | code | 0 | github-code | 36 |
34212063715 | # https://www.acmicpc.net/problem/14500
# solution
# 1) 초기 좌표 (i,j)를 정한다
# 2) 인접한 좌표에 대해 dfs 하며 4개 블럭으로 가능한 합의 최대값을 갱신한다
# 3) dfs 불가능한 'ㅗ' 모양 블럭으로 가능한 값을 계산해 최대값을 갱신한다
# 4) 1)로 돌아가 새로운 초기 좌표(i, j) 정한다. brute-forcely 순회한다
# 5) 순회를 마치고 최대값을 출력한다
# TIL
# O(N)인 초기화 함수(reset_visited)를 brute-force에 이용하는 것은 가볍지 않은 코드이다. ... | chankoo/problem-solving | graph/14500-테트로미노.py | 14500-테트로미노.py | py | 3,502 | python | ko | code | 1 | github-code | 36 |
20591380597 | from django.contrib.auth.models import AbstractUser
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from api_yamdb.settings import ADMIN, MODERATOR, ROLE_CHOICES, USER
from .validators import validate_year
class User(AbstractUser):
"""Модель пользователя, доба... | QBC1/api_yamdb | api_yamdb/reviews/models.py | models.py | py | 4,957 | python | en | code | 2 | github-code | 36 |
13081546133 | from graphics import *;
from random import *
window = GraphWin("Window", 500,500);
window.setBackground("white")
square = []
for x in range(0,588):
rx = randint(0,500)
ry = randint(0,500)
orx = rx+20
ory = ry+20
y = Rectangle(Point(rx, ry), Point(orx, ory))
y.draw(window)
rgb= randint(0,255)
y... | Kevinloritsch/Buffet-Dr.-Neato | Python Warmup/Warmup #7/run7.py | run7.py | py | 1,194 | python | en | code | 1 | github-code | 36 |
12484573322 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pathlib import Path
from urllib.parse import urlparse
from urllib.request import urlretrieve
from sklearn.metrics import roc_auc_score
def download(url):
"""Downloads a file if it doesn't already exist.
Args:
url: string or... | drivendataorg/tutorial-flu-shot-learning | utils.py | utils.py | py | 3,053 | python | en | code | 2 | github-code | 36 |
1729374906 | #
# @lc app=leetcode.cn id=26 lang=python3
#
# [26] 删除有序数组中的重复项
#
# @lc code=start
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
length = len(nums)
i, j = 0, 1
if length == 0:
return 0
# for j in range(1,length):
# if nums[i] != nums[j]... | mckaymckay/shuati | 26.删除有序数组中的重复项.py | 26.删除有序数组中的重复项.py | py | 641 | python | en | code | 0 | github-code | 36 |
36953625709 | __all__ = [
'MatchesException',
'Raises',
'raises',
]
import sys
from testtools.compat import (
classtypes,
_error_repr,
isbaseexception,
istext,
)
from ._basic import MatchesRegex
from ._higherorder import AfterPreproccessing
from ._impl import (
Matcher,
Mismatch,
)
... | mongodb/mongo | src/third_party/wiredtiger/test/3rdparty/testtools-0.9.34/testtools/matchers/_exception.py | _exception.py | py | 4,567 | python | en | code | 24,670 | github-code | 36 |
16253007713 | #!/usr/bin/env python3
"""
Database Aggregator from a Kafka Consumer.
Author: Santhosh Balasa
Email: santhosh.kbr@gmail.com
Date: 18/May/2021
"""
import sys
import logging
import psycopg2
from kafka import KafkaConsumer
logging.basicConfig(
format=f"%(asctime)s %(name)s %(levelname)-8s %(message)s",
level=l... | sbalasa/WebMonitor | db_aggregator.py | db_aggregator.py | py | 2,697 | python | en | code | 1 | github-code | 36 |
37597891395 | # -*- coding: utf-8 -*-
"""
Created on Thu May 23 20:49:32 2019
@author: 18443
"""
import os
import time
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data as Data
from torch import optim
from torch.utils.data import DataLoader
import numpy as np
i... | yudmoe/neural-combination-of-HCTR | threeinput_training.py | threeinput_training.py | py | 14,833 | python | en | code | 4 | github-code | 36 |
3715520265 | import cv2
import numpy as np
def get_crops(img, annotations, padding=0):
crops = []
new_img = img.copy() # Prevent drawing on original image
for a in annotations:
c = a['coordinates']
y1, y2 = int(c['y'] - c['height'] / 2 - padding), int(c['y'] + c['height'] / 2 + padding)
x1, x2 = int(c['x'] - c['width'] /... | mattzh72/sframe-visualizer | tools/utils/segment.py | segment.py | py | 1,936 | python | en | code | 0 | github-code | 36 |
38346693249 | def solution(n):
number3 = ""
while n >= 3:
number3 = str(n % 3) + number3
n //= 3
number3 = str(n) + number3
answer = 0
for i in range(0, len(number3)):
answer += int(number3[i]) * 3**(i)
return answer
print(solution(3))
# int(x, radix) : radix 진수로 표현된 문자열 x를 10진수로 ... | Huey-J/Algorithm_Practice | 파이썬/프로그래머스 Lv1/3진법 뒤집기 (int 진법 변환).py | 3진법 뒤집기 (int 진법 변환).py | py | 652 | python | ko | code | 0 | github-code | 36 |
13145223871 | #!/usr/bin/env python3
import argparse
import configparser
import json
import os
import tempfile
import shutil
import subprocess
import stat
import time
import dateutil
import dateutil.parser
import urllib.parse
from submitty_utils import dateutils, glob
import grade_items_logging
import write_grade_history
import in... | alirizwi/Submitty | bin/grade_item.py | grade_item.py | py | 29,887 | python | en | code | null | github-code | 36 |
40753869339 | #!/user/bin/env python3 -tt
"""
Task:
https://adventofcode.com/2019/day/9
"""
# Imports
import sys
import os
import re
import math
import time
import itertools
# Global variables
#task="d-9.test"
task="d-9"
infile=task + ".input"
def readInput():
with open('input/' + infile) as file:
data = file.read()
... | peter-steiner/adventofcode-2019 | d-9.py | d-9.py | py | 5,123 | python | en | code | 0 | github-code | 36 |
39489518389 | def solve():
n, k = map(int, input().split())
ll = []
for i in range(1, n+1):
if n % i == 0:
ll.append(i)
if len(ll) == k:
return ll[-1]
return 0
if __name__ == '__main__':
print(solve())
| bangalcat/Algorithms | algorithm-python/boj/boj-2501.py | boj-2501.py | py | 257 | python | en | code | 1 | github-code | 36 |
35366813632 | # Image Credits
# Bullet and Spaceship sprite: https://q.utoronto.ca/courses/288975/files/24417060?module_item_id=4444455
# Dinosaur sprite: https://arks.itch.io/dino-characters
# Block sprite: https://replit.com/talk/ask/Pygame-Sprite-Graphics/38044
# Gem, Box, Half platform: https://opengameart.org/content/platformer... | mashalll/cct211 | main.py | main.py | py | 10,968 | python | en | code | 0 | github-code | 36 |
3494867644 | #!/usr/bin/env python3
# Caoimhe De Buitlear: 19378783
# I acknowledge the DCU Academic Integrity Policy: https://www.dcu.ie/sites/default/files/policy/1_-_integrity_and_plagiarism_policy_ovpaa-v4.pdf
from queue import Queue
from format import format_rr
def round_r(arr):
#time quantum is 10 milliseconds
... | debuitc4/scheduling_ | round_robin.py | round_robin.py | py | 2,455 | python | en | code | 0 | github-code | 36 |
71607160424 | import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate
import pyximport
pyximport.install()
import heat_solver
def coeff_dis(x):
alpha2 = np.zeros(len(x))
for i in range(len(x)):
if x[i] > 0.5:
alpha2[i]= 10
elif x[i]< 0.3:
alpha2[i]= 5
else:
alpha2[i] = 1
return alpha2... | jedman/numerics | src1/heat_nl_dis.py | heat_nl_dis.py | py | 2,702 | python | en | code | 0 | github-code | 36 |
36491984140 | """
Module: Classes which are "services" that encapsulate domain logic.
Utilizing Strategy pattern for course registration-related functionality.
"""
from abc import ABC, abstractmethod
import db_utils
class RegistrationContext:
"""Context for performing registration actions via a registration strategy
"""
... | colebryant/course-registration-system | src/services.py | services.py | py | 19,419 | python | en | code | 0 | github-code | 36 |
12507519121 | # BFS
# 이모티콘
from collections import deque
s = int(input())
q = deque([(1, 0, 0)]) # 만들어진 이모티콘, 시간
visited = [[False] * 1001 for _ in range(1001)]
visited[1][0] = True
while q:
now, copy, sec = q.popleft()
if now == s:
print(sec)
break
for i in ((now, now), (now+copy, copy), (now-1... | Hong-Jinseo/Algorithm | baekjoon/14226.py | 14226.py | py | 565 | python | en | code | 0 | github-code | 36 |
72404306664 | import re
def react(s):
result = []
for c in s:
complement = c.lower() if c.isupper() else c.upper()
if result and result[-1] == complement:
del result[-1]
else:
result.append(c)
return ''.join(result)
assert react('aA') == ''
assert react('abBA') == ''
asse... | jorendorff/advent-of-code | 2018/05/polymer.py | polymer.py | py | 944 | python | en | code | 3 | github-code | 36 |
31757113296 | from django.db import models, transaction
from django.contrib.auth.models import AbstractUser
from django.core.exceptions import ValidationError
from django.db.models import JSONField
from django.db.models.signals import post_save
from django.dispatch import receiver
USER_TYPE_CHOICES = (
("customer", "Customer"),... | A7med3365/Project4-Backend | shop/models.py | models.py | py | 6,379 | python | en | code | 0 | github-code | 36 |
32233049619 | def surroundedRegions(board):
if len(board) <=2:
return board
oNotOnBoarder = []
oOnBoarder = []
directionMatrix = [[-1,0],[1,0],[0,-1],[0,1]]
for i in range (len(board)):
for j in range (len(board[0])):
if board[i][j] == 'O':
if i == 0 or i == len(board) - 1 or j == 0 or j == len(board[0]) - 1:
... | Gale6/leetcode--codes | surroundedRegions.py | surroundedRegions.py | py | 1,094 | python | en | code | 0 | github-code | 36 |
36777613557 | from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
driver = webdriver.Chrome()
driver.get('https://www.dummyticket.com/dummy-ticket-for-visa-application/')
driver.maximize_window()
d... | blessycheriyan/Selenium_From_Scratch | part-13/bootstrap.py | bootstrap.py | py | 651 | python | en | code | 0 | github-code | 36 |
3855782251 | # %%
from sklearn.datasets import load_sample_image
import matplotlib.pyplot as plt
import seaborn as sns
with sns.axes_style('dark'):
img = load_sample_image('china.jpg')
plt.imshow(img)
# %%
print (img.shape)
# Rescacle the color so that they lie btw 0 and 1, then reshape the array to be
# a typical scikit-le... | haininhhoang94/wqu | MScFE650/Kmean_image.py | Kmean_image.py | py | 962 | python | en | code | 21 | github-code | 36 |
35864159569 | # Import dependencies
import numpy as np
from keras.models import Sequential
from keras.layers import Activation, Dropout, UpSampling2D, Conv2D, Conv2DTranspose, MaxPooling2D
from keras.layers.normalization import BatchNormalization
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
... | codeXing8/LaneRecognition | keras-cnn/train.py | train.py | py | 3,943 | python | en | code | 2 | github-code | 36 |
71760950503 | """module for containing the code that produces charts"""
import os
from bokeh.charts import Bar, output_file, show, Line
from bokeh.models import HoverTool
# bar chart showing total response by HH group split by digital/paper
def bar_response(results_list, output_path):
output_dir = os.path.join(output_path, "c... | ONSdigital/FOCUS | create_graphs.py | create_graphs.py | py | 1,086 | python | en | code | 0 | github-code | 36 |
42095536498 | from subprocess import call
import win32api
import win32gui
import win32con
import win32com.client
from enum import Enum
import sounddevice as sd
from scipy.io.wavfile import read
import requests
import json
import numpy as np
from settings import Settings
from logging import debug, warning, error
class MixerCommand... | schms27/raspi.pico.collection | pico.hid.service/sound_mixer.py | sound_mixer.py | py | 6,492 | python | en | code | 1 | github-code | 36 |
24856744056 | def double_char(string):
result = "".join(x * 2 for x in string)
print(result)
while True:
command = input()
if command == "End":
break
elif command == "SoftUni":
continue
else:
double_char(command) | BorisAtias/SoftUni-Python-Fundamentals-course | Basic Syntax, Conditional Statements and Loops - Exercise/07. Double Char.py | 07. Double Char.py | py | 266 | python | en | code | 0 | github-code | 36 |
40513708895 | import sys
from textblob import TextBlob
import redis
import json
from multiprocessing import Pool
import signal
import logging
import cPickle
import sys
sys.path.insert(0, '../NLP/Wrapper/')
sys.path.insert(0, '../NLP/')
sys.path.insert(0, '../NLP/NaiveBayes')
sys.path.insert(0, '../NLP/MaximumEntropy')
sys.path.inser... | archanl/thetweetrises | backend/tweet_categorize.py | tweet_categorize.py | py | 5,629 | python | en | code | 1 | github-code | 36 |
8451674313 | def count_inversion(nums):
def count_inversion_subarray(l, r):
def merge_sorted_count_inversions(l, m, r):
sorted_A = []
left_start, right_start, inversion_count = l, m, 0
while left_start < m and right_start < r:
if nums[left_start] >= nums[right_start... | kashyapa/coding-problems | epi/revise-daily/11_honors_class/inversion_count.py | inversion_count.py | py | 1,017 | python | en | code | 0 | github-code | 36 |
2465805518 | import glob
import os
import statistics
from .pid_data_evaluator import PidDataEvaluator
class OcrEvaluator:
def __init__(self, options):
# set properties
self.correct_line_ocr_log = options.correct_line_ocr_log
self.eval_main_text_only = options.eval_main_text_only
self.eval_annot... | ndl-lab/ndlocr_cli | submodules/ocr_line_eval_script/ocr_evaluator/ocr_evaluator.py | ocr_evaluator.py | py | 7,152 | python | en | code | 325 | github-code | 36 |
18798611360 | required_skills=['python','github','linux']
candidates={
'kannu':{'java','linux','python'},
'mustaf':{'github','java','html','css','python','linux'}
}
interviewees =set()
for candidate , skills in candidates.items():
#if skills.issuperset(required_skills):
if skills > set(required_skills):
... | DhanKumari/python_2 | candidate.py | candidate.py | py | 386 | python | en | code | 0 | github-code | 36 |
4109177627 | import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import pandas as pd
import pickle
import json
import dash_table
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
"""... | arsalhuda24/credit_card_fraud_detection | fraud_detection/dash-app/app.py | app.py | py | 1,654 | python | en | code | 0 | github-code | 36 |
9824574989 | """
Classes related to OpenAPI-defined operations and their arguments and parameters.
"""
from __future__ import print_function
import argparse
import json
def parse_boolean(value):
"""
A helper to allow accepting booleans in from argparse. This is intended to
be passed to the `type=` kwarg for Argument... | rovaughn/linode-cli | linodecli/operation.py | operation.py | py | 4,061 | python | en | code | null | github-code | 36 |
15936612595 | import os
import atexit
import asyncio
import aiohttp
import requests
from scraper import scrape
from models import db, Movie
from flask import Flask, jsonify, request, abort
from apscheduler.schedulers.background import BackgroundScheduler
app = Flask(__name__)
# SQLAlchemy configurations
app.config['SQLALCHEMY_DAT... | Joseph-Villegas/JS-New-DVD-Releases | backend/app.py | app.py | py | 6,279 | python | en | code | 0 | github-code | 36 |
40294597567 | import requests
import json
from urllib.parse import urlencode, quote_plus
def getBusInterval() :
api_key = 'g2B7EooEAgEwa++yErKYAhIk93i7tdYXP/3i5nOrRMN0Fmt78AnTzkaJUGqdsIUcqd7ITge5nUX0dAK/luCmFg=='
serviceKey = requests.utils.unquote(api_key)
api_url = 'http://ws.bus.go.kr/api/rest/busRouteInfo/getRoute... | CSID-DGU/2023-2-OSSP1-Idle-3 | data/graphDataProcessing/bus_data_processing/intervalTime/getBusInterval.py | getBusInterval.py | py | 771 | python | en | code | 0 | github-code | 36 |
11998084066 | import htcondor
import classad
import time
def get_existing_resources(self, group):
"""
Get list of worker nodes
"""
try:
coll = htcondor.Collector()
results = coll.query(htcondor.AdTypes.Startd,
'PartitionableSlot=?=True',
["To... | prominence-eosc/prominence | prominence/backend/resources.py | resources.py | py | 1,061 | python | en | code | 2 | github-code | 36 |
7821929073 | from sys import stdin
n = int(input())
ary = [""]*n
for i in range(n): ary[i] = stdin.readline().strip()
answer_record = [0]*len(ary[0])
answer = ""
# 3번 확인 돌림
for i in range(1, n):
# 글자수 만큼 또 비교해봐
for j in range(len(ary[0])):
# ary[0]번에 들어간 문자열이랑 2,3번째꺼랑 다르면 기록
if(ary[0][j] != ary[i][j]):
... | Drizzle03/baekjoon_coding | 20230116/1032.py | 1032.py | py | 559 | python | en | code | 0 | github-code | 36 |
25553186 | from random import *
from time import sleep
#튜플로 랜덤하게 리스트 배치해서 덱 짜기
magic = (["smite", 80, 40], ["ignite", 30, 20], ["orb shield", 0, 10], ["meteor rock", 150, 70], ["originium arts", 100, 45], ["subjective time dilation", 125, 67])
deck = []
mp = 500
def add_magic():
for i in range(0, 3):
temp_magic = [... | kmgyu/baekJoonPractice | some tips/tuple_packing.py | tuple_packing.py | py | 1,742 | python | ko | code | 0 | github-code | 36 |
25464205303 | from django import forms
from .models import Event
from django.core.exceptions import ValidationError
from django.utils import timezone
tz = timezone.get_default_timezone()
class EventForm(forms.ModelForm):
date_date = forms.CharField(max_length=40, required=True, widget=forms.TextInput(attrs={'class': 'form-contr... | voc/voctoimport | event/forms.py | forms.py | py | 1,135 | python | en | code | 0 | github-code | 36 |
30280424346 | import requests
def get_random_wiki_article_link():
WIKI_RANDOM_LINK_API_URL = "https://en.wikipedia.org/w/api.php?action=query&list=random&rnnamespace=0&rnlimit=1&format=json"
response = requests.get(WIKI_RANDOM_LINK_API_URL)
if response.status_code == 200:
random_article_data = response.json()... | hafeezulkareem/python_scripts | get_random_wiki_article_link.py | get_random_wiki_article_link.py | py | 905 | python | en | code | 0 | github-code | 36 |
4062334058 | def main():
## Sort numbers by the sum of their odd digits in descending order.
numbers = [865, 1169, 1208, 1243, 290]
numbers.sort(key=sumOfOddDigits, reverse=True)
print("Sorted by sum of odd digits:")
print(numbers)
def sumOfOddDigits(num):
listNums = list(str(num))
total = 0
... | guoweifeng216/python | python_design/pythonprogram_design/Ch4/4-2-E61.py | 4-2-E61.py | py | 456 | python | en | code | 0 | github-code | 36 |
27893627629 | open_file = open("mapper_gopi.txt", "r")
sort_output = open("sort_data.txt", "w")
lines = open_file.readlines()
lines.sort()
for line in lines:
sort_output.write(line)
open_file.close()
sort_output.close() | chvnaveenkumar/Crypto-Markets | Problem4/sort.py | sort.py | py | 210 | python | en | code | 0 | github-code | 36 |
3640835274 | import torch
import torch.nn as nn
import torch.optim as optim
from torchtext.legacy.datasets import Multi30k
from torchtext.legacy.data import Field, BucketIterator
import spacy
import numpy as np
import random
import math
import time
from model import Seq2Seq, Encoder, Decoder
def train(model, iterator, optimize... | HallerPatrick/two_hot_encoding | multihot/seq2seq/train.py | train.py | py | 4,787 | python | en | code | 6 | github-code | 36 |
16764769514 | import dns.resolver
import sys
'''
Returns the dns records specified in rtypes, if you want to change this script feel free to do it. :)
To run this script just type --> python3 dnsenum.py <domain name> e.g domain name <example.com>
For the first import install dnspython using pip3 install dnspython
'''
def m... | Gl4uc0m4/InformationGatheringTools | dnsenum.py | dnsenum.py | py | 1,299 | python | en | code | 0 | github-code | 36 |
5834016480 | import pygame, time
from math import pi, cos, sin
from random import randrange, random
WIDTH = 900
HEIGHT = 900
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
class Branch:
tree = []
random_seed = []
def __init__(self, startPoint, angle, size, width):
self.width = width
... | YohannPardes/Fractal-tree | Versions/Tree_generator.py | Tree_generator.py | py | 2,195 | python | en | code | 0 | github-code | 36 |
17076521686 | from fastapi import FastAPI, HTTPException, status
import uvicorn
import requests
app = FastAPI(debug=True)
BTCUSD=[]
@app.get('/')
def index():
return {'msg': 'VSETKO JE OK'}
@app.get('/usd2btc')
def USD_current_price():
re = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json')
if re.statu... | fortisauris/PyDevJR_Course | FA02_FASTAPI_BTC/main.py | main.py | py | 1,498 | python | en | code | 2 | github-code | 36 |
42443816173 | abc = str(input(f'Digite uma frase: ')).strip().upper().split()
abc = ''.join(abc)
inv = ''
for letra in range(len(abc)-1, -1, -1):
inv += abc[letra]
print(f'O inverso de {abc} é {inv}.')
if abc == inv:
print(f'É PALÍNDROMO')
else:
print(f'NÃO É PALÍNDROMO')
| JosueFS/Python | Exercicios/Ex053.py | Ex053.py | py | 277 | python | pt | code | 0 | github-code | 36 |
42578251551 | from tkinter import StringVar, Tk
from tkinter.ttk import Frame
import pytest
from pyDEA.core.gui_modules.data_frame_gui import DataFrame
from tests.test_gui_data_tab_frame import ParamsFrameMock
class ParentMock(Frame):
def __init__(self, parent):
super().__init__(parent)
self.progress_bar = {... | araith/pyDEA | tests/test_gui_data_frame.py | test_gui_data_frame.py | py | 998 | python | en | code | 38 | github-code | 36 |
2735470039 | # 3rdpartyimports
import math
from sklearn.model_selection import (
cross_val_score, KFold, train_test_split, GridSearchCV, RepeatedKFold)
import matplotlib.pyplot as plt
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import (OneHotEncoder, StandardScaler,
Polyn... | chadk94/FreeThrowProjections | model.py | model.py | py | 5,208 | python | en | code | 0 | github-code | 36 |
11909593894 | from pprint import pprint
import boto3
import openpyxl
import time
import csv
def put_object(fileHash, request='', today = int(time.time()), dynamodb=None):
if not dynamodb:
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('image-reuse-image-hash-dev')
response = table.put_item(
... | shakazi/aws_essential_scripts | upload_to_db.py | upload_to_db.py | py | 1,821 | python | en | code | 0 | github-code | 36 |
12433334302 | """This module contains definition of the Cell class."""
class Cell:
"""This class stores information about a single cell."""
def __init__(self, position_init, max_velocity_init, mass_init):
self.position = position_init
self.max_velocity = max_velocity_init
self.mass = mass_init
... | natiiix/Cells | Cells/Cell.py | Cell.py | py | 1,335 | python | en | code | 0 | github-code | 36 |
27283966186 | import copy
import math
from pypaq.lipytools.printout import stamp, progress_
from pypaq.lipytools.pylogger import get_pylogger, get_child
from pypaq.mpython.mptools import Que, QMessage
from torchness.tbwr import TBwr
import random
import statistics
import time
from tqdm import tqdm
from typing import Dict, List, Tupl... | piteren/pypoks | podecide/games_manager.py | games_manager.py | py | 25,904 | python | en | code | 19 | github-code | 36 |
22683092245 | from tensorforce.core.layers.layer import Layer
import tensorflow as tf
import numpy as np
from tensorforce.core import Module, parameter_modules
from tensorforce import TensorforceError, util
class Transformer(Layer):
def __init__(self, name, n_head, hidden_size, num_entities, mlp_layer=1, mask_name='', pooling=... | SestoAle/Adaptive-NPCs-with-procedural-entities | new_layers/Transformer.py | Transformer.py | py | 15,414 | python | en | code | 2 | github-code | 36 |
43296309454 | from pypy.interpreter import gateway
from rpython.rlib.objectmodel import dict_to_switch
from rpython.rlib.unroll import unrolling_iterable
app = gateway.applevel("""
def syntax_warning(msg, fn, lineno, offset):
import warnings
try:
warnings.warn_explicit(msg, SyntaxWarning, fn, lineno)
except Syn... | mozillazg/pypy | pypy/interpreter/astcompiler/misc.py | misc.py | py | 3,176 | python | en | code | 430 | github-code | 36 |
751441711 | import torch
from torch import nn
import torch.nn.functional as F
#Useful for nn.Sequential
class Flatten(nn.Module):
def forward(self, input):
return input.view(input.size(0), -1)
#Picked from Udacity's PyTorch course
class CIFARNet(nn.Module):
def __init__(self, z_dim):
super(CIFARNet, self)... | guptv93/saycam-metric-learning | model/cifar_model.py | cifar_model.py | py | 1,929 | python | en | code | 8 | github-code | 36 |
4714548611 | """
Write simple languoid stats to build/languoids.json.
This is to allow comparison between two branches of the repos.
Intended usage:
```
git checkout master
glottolog-admin writelanguoidstats
git checkout <OTHER_BRANCH>
glottolog-admin check --old-languoids
```
"""
try:
from git import Repo
except ImportError:... | glottolog/pyglottolog | src/pyglottolog/admin_commands/writelanguoidstats.py | writelanguoidstats.py | py | 772 | python | en | code | 20 | github-code | 36 |
9512653187 | x, y = input("x,y : ").split(",")
x, y = float(x), float(y)
# Sqaure a
ax1 , ay1 = 0, 0
ax2 , ay2 = 40,40
# Sqare b
bx1 , by1 = -40, -20
bx2 , by2 = 10, 20
# C is intersect of a and b
isInA = x > ax1 and x < ax2 and y > ay1 and y < ay2
isInB = x > bx1 and x < bx2 and y > by1 and y < by2
if isInA and isInB:
prin... | ratchanonp/comproglab | 64-1LAB3/6434480323Lab3P3.py | 6434480323Lab3P3.py | py | 488 | python | en | code | 0 | github-code | 36 |
2114660989 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
class MyUser(models.Model):
id = models.IntegerField(primary_key=True, verbose_name='ID')
username = models.CharField(max_length=255)
@classmethod
def get_sharding_table(cls, id=None):
piece = id % 2... | the5fire/django-sharding-demo | sharding_demo/app/models.py | models.py | py | 1,189 | python | en | code | 0 | github-code | 36 |
15151358717 | # Imports
load("@npm//@bazel/typescript:index.bzl", "ts_library")
load("@build_bazel_rules_nodejs//:index.bzl", "pkg_npm")
load("@npm//@bazel/jasmine:index.bzl", "jasmine_node_test")
load("//tools:defs.bzl",
"SOLUTION_PACKAGE_NAME",
"TYPESCRIPT_PRODMODE_TARGET",
"TYPESCRIPT_DEVMODE_TARGET",
"TYPESCRIPT... | sqlProvider/solution | tools/package.bzl | package.bzl | bzl | 2,038 | python | en | code | 0 | github-code | 36 |
70562638504 | import sys
input = sys.stdin.readline
N = int(input())
schedule = sorted([list(map(int, input().rstrip().split())) for _ in range(N)], key = lambda x : (x[1], x[0]))
tmp = 0
result = 0
for start, end in schedule:
if start >= tmp:
result += 1
tmp = end
print(result)
| zsmalla/algorithm-jistudy-season1 | src/chapter4/1_그리디알고리즘(1)/임지수/1931_python_임지수.py | 1931_python_임지수.py | py | 291 | python | en | code | 0 | github-code | 36 |
72242760743 | from django.shortcuts import render
from django.http.request import QueryDict
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.views.generic.base import TemplateView
from six.moves.urllib.parse import urlparse
from rest_framework.renderers import JSONRenderer
from rest_framework... | bfolks2/django-aviation | prepair/views.py | views.py | py | 4,566 | python | en | code | 2 | github-code | 36 |
10841211976 | import logging
import pathlib
from flask import Blueprint, g, request, make_response
from flask_restplus import Resource, Namespace, fields, abort
from photos.model import SourceFolder
from photos.scanner import scan_source_folder
log = logging.getLogger(__name__)
sources_blueprint = Blueprint("sources", __name__)
... | sebbegg/photos | photos/web/resources/scanner.py | scanner.py | py | 1,419 | python | en | code | 0 | github-code | 36 |
33586861988 | #!/usr/bin/env python3
import sys
from testflows.core import *
append_path(sys.path, "..")
from helpers.common import Pool, join, run_scenario
from helpers.argparser import argparser
@TestModule
@Name("ldap")
@ArgumentParser(argparser)
def regression(self, local, clickhouse_binary_path, parallel=None, stress=None):
... | ByConity/ByConity | tests/testflows/ldap/regression.py | regression.py | py | 1,093 | python | en | code | 1,352 | github-code | 36 |
37130243038 | from tkinter import messagebox
import tkinter as tk
import tkinter.ttk as ttk
from PIL import Image,ImageTk
from pathlib import Path
import random
from minigames.game_components import GamePlay, Player
from minigames.playerdatabase import UserDataBase
class GuessTheNumber(tk.Frame, GamePlay):
'''
... | urasayanoglu/tkinter_minigames | minigames/guessthenumber.py | guessthenumber.py | py | 11,059 | python | en | code | 0 | github-code | 36 |
41629760399 | from django.shortcuts import render, redirect
import smtplib
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserChangeForm
from django.views import... | nrking0/votesite | votesite/views.py | views.py | py | 2,346 | python | en | code | 0 | github-code | 36 |
18255309368 | import sys
sys.path.append("..") # for dev
import api2ch
api = api2ch.Api('b')
print(api.board.name)
api.board = 'vg'
print(api.board.name)
print(api.board.category)
thread = api.get_thread(24536772)
captcha = api.get_captcha()
print(api.get_captcha_img(captcha))
value = input('Captcha answer: ')
api.set_captcha_answ... | slowpojkee/dvach.api | examples/test.py | test.py | py | 479 | python | en | code | null | github-code | 36 |
23013402799 | import socketserver
import os
import re
#strings
help = 'commands:\n'
help += 'start\n'
help += 'exit\n'
#not sure if I still need this:
socketstate = 0
tricksite = ''
#socket server class
class tcpsocket(socketserver.BaseRequestHandler):
def handle(self):
global socketstate
glo... | thcsparky/bigclickskid | phish.py | phish.py | py | 1,571 | python | en | code | 0 | github-code | 36 |
7235498245 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the hackerlandRadioTransmitters function below.
def hackerlandRadioTransmitters(arr, k):
count = 0
i = 0
arr.sort()
while i < len(arr) :
mRange = k
while i < len(arr) - 1 :
diff = abs(arr[i+1... | Suraj-Upadhyay/ProblemSolving | hackerrank/Search/04-HackerlandRadioTransmitters.py | 04-HackerlandRadioTransmitters.py | py | 963 | python | en | code | 1 | github-code | 36 |
18694457154 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 21 11:14:59 2023
@author: giamp
"""
import scipy
import logging
import numpy as np
import hcd
import matplotlib.pyplot as plt
from hppdWC import utils
from hppdWC import plots
def cutInTime(x, y, interval):
'''
Given x (time array), y (values), and interval, eras... | mmtlab/wheelchair_contact_detection | hcd/xcorrelation.py | xcorrelation.py | py | 17,731 | python | en | code | 0 | github-code | 36 |
12430891780 | class Board:
def __init__(self, rows, columns, position):
self.rows = rows
self.columns = columns
self.unmarked = {i for i in position}
self.position = position
def mark(self, number) -> bool:
if number in self.unmarked:
self.unmarked.remove(number)
... | hieu-lee/AoC2021 | Day4/solution.py | solution.py | py | 1,539 | python | en | code | 1 | github-code | 36 |
216104646 |
from ast import Add
from flask import render_template, session, request, url_for, flash, redirect
from loja.produtos.models import Addproduto, Marca, Categoria
from loja import app, db, bcrypt
from .formulario import LoginFormulario, RegistrationForm
from .models import User
import os
@app.route('/admin')
def admi... | ReinierSoares/SiteFlask | loja/admin/rotas.py | rotas.py | py | 2,351 | python | en | code | 0 | github-code | 36 |
23413088374 | # -*- coding: utf-8 -*-
"""
A disk cache layer to store url and its html.
"""
from __future__ import print_function
import os
import zlib
import diskcache
class CompressedDisk(diskcache.Disk): # pragma: no cover
"""
Serialization Layer. Value has to be bytes or string type, and will be
compressed usi... | MacHu-GWU/crawlib-project | crawlib/cache.py | cache.py | py | 3,738 | python | en | code | 1 | github-code | 36 |
17211879792 | from datetime import date
atual = date.today().year
totmaior = 0
totmenor = 0
for c in range(1, 8):
nasc = int(input(f'Em que ano a {c}° pessoa nasceu? '))
idade = atual - nasc
if idade >= 18:
totmaior += 1
else:
totmenor += 1
print(f'No total contamos {totmaior} maior de idade e {totmen... | GRSFFE/PythonExercicios | ex054.py | ex054.py | py | 344 | python | pt | code | 0 | github-code | 36 |
19735062070 | #!/usr/bin/python3
from pyrob.api import *
@task
def task_8_28():
direction = -1
while wall_is_above() == True:
if wall_is_on_the_left() == True:
direction = 1
if direction == -1:
move_left()
elif direction == 1:
move_right()
while wall_is_abov... | miketoreno88/robot-tasks-master-Python | task_18.py | task_18.py | py | 468 | python | en | code | 0 | github-code | 36 |
30024110320 | from itertools import combinations
from scipy.optimize import fsolve
from copy import copy
from pdb import set_trace
INFT = float(10**10)
class Bound(object):
def __init__(self,x,y,r):
self.x , self.y , self.r = x , y , r
def fit(self,another_bound):
if another_bound.x == INFT :
retu... | ElderTrump/ball_in_box | ball_in_box/key_function.py | key_function.py | py | 2,583 | python | en | code | null | github-code | 36 |
39521526537 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 29 02:35:41 2017
@author: samara
"""
from tkinter import *
import InterfaceEstacionamentoV
import Estacionamento
class InterfaceA():
def __init__(self):
self.interface = InterfaceEstacionamentoV.InterfaceV()
self.interface.jan... | samarasleal/Python-ParkingSystem | InterfaceEstacionamentoA.py | InterfaceEstacionamentoA.py | py | 1,944 | python | pt | code | 0 | github-code | 36 |
8247731797 | import cvxopt
import cvxopt.solvers
from cvxopt.solvers import lp
from numpy import array
cvxopt.solvers.options['show_progress'] = False # disable cvxopt output
try:
import cvxopt.glpk
GLPK_IF_AVAILABLE = 'glpk'
# GLPK is the fastest LP solver I could find so far:
# <https://scaron.info/blog/linea... | furiiibond/Tinder | venv/Lib/site-packages/lpsolvers/cvxopt_.py | cvxopt_.py | py | 2,213 | python | en | code | 0 | github-code | 36 |
74157473702 | from django.urls import path
from . import views
app_name = "core"
urlpatterns = [
path('author/', views.AuthorList.as_view(), name='list-author'),
path('author/<int:pk>/', views.AuthorDetail.as_view(), name='detail-author'),
path('book/', views.BookList.as_view(), name='list-book'),
path('book/<int:p... | PauloGuillen/library | libraryapi/core/urls.py | urls.py | py | 377 | python | en | code | 0 | github-code | 36 |
25348981844 | import pandas as pd
def build(gps, game_id):
players = []
for i in gps.PlayerID.unique():
counter = 0
prev_a = 0.0
for j in range(1, 3):
for k in gps[(gps.PlayerID == i) & (gps.Half == j)].FrameID.values: # first half second half
ax = list(gps[(gps.Player... | magickaiyang/archive | datafest/intense_event.py | intense_event.py | py | 1,178 | python | en | code | 0 | github-code | 36 |
42149656698 | from PIL import Image
import numpy as np
import cv2
img = Image.open('back_img.jpg')
size = img.size
x_length = size[0]
print('x_length:', x_length)
y_length = size[1]
print('y_length:', y_length)
im_num = np.array(img)
img_blur = cv2.GaussianBlur(im_num, (5, 5), 0)
img_gray = cv2.cvtColor(img_blur, cv2.COLOR_BG... | magicnian/neteasy | myTest.py | myTest.py | py | 463 | python | en | code | 0 | github-code | 36 |
34788181082 | """First migration
Revision ID: 1e99703f8998
Revises:
Create Date: 2022-03-30 17:34:52.872031
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '1e99703f8998'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto ge... | gilde-der-nacht/website | olymp/app/storage/migrations/versions/1e99703f8998_first_migration.py | 1e99703f8998_first_migration.py | py | 1,893 | python | en | code | 3 | github-code | 36 |
32191704409 | import time
from threading import Timer
import xmlrpc.client
from .edit import Edit
from .utils import firmwareWarning
import json
import os
import base64
class Session(object):
"""
Session object
"""
def __init__(self, sessionURL, mainAPI, autoHeartbeat=True, autoHeartbeatInterval=10):
self.... | ifm/o2x5xx-python | source/rpc/session.py | session.py | py | 12,153 | python | en | code | 3 | github-code | 36 |
947383902 | pkgname = "tig"
pkgver = "2.5.8"
pkgrel = 1
build_style = "gnu_configure"
make_cmd = "gmake"
make_dir = "."
make_install_args = ["install-doc-man"]
hostmakedepends = ["gmake", "automake", "asciidoc", "xmlto", "pkgconf"]
makedepends = ["ncurses-devel"]
depends = ["git"]
pkgdesc = "Text-mode interface for git"
maintainer... | chimera-linux/cports | contrib/tig/template.py | template.py | py | 805 | python | en | code | 119 | github-code | 36 |
23741088080 | #! /Users/tianranmao/Projects/so1.0/venv/bin/python
import requests
from bs4 import BeautifulSoup
import datetime
import pytz
import time
import re
import os
# --------------------------------------------------------------------
# Main Function
# -----------------------------------------------... | timmao78/so1.0 | get_txt.py | get_txt.py | py | 7,564 | python | en | code | 0 | github-code | 36 |
1437749316 | from django.urls import path, include
from . import views
from django.contrib.auth.views import auth_login
urlpatterns = [
path('', views.index, name='main_home'),
path('login', views.index, name='main_login'),
path('account/', views.account, name='main_account'),
path('feed/', views.feed, name='main_f... | chavkin94/YouDeo | main/urls.py | urls.py | py | 570 | python | en | code | 0 | github-code | 36 |
7003663358 | # any all function practice
def all_sum(*args):
total = 0
for i in args:
total += i
return total
# print(all_sum(1,2,3,4)) # correct input
# print(all_sum(1,2,3,4, "salman", ["salman"])) # wrong input
## here we solve the problem of wrong input using all function
def all_add(*args):
if... | salmansaifi04/python | chapter11(enumurator-function_type)/08_any_all_function_practice.py | 08_any_all_function_practice.py | py | 590 | python | en | code | 0 | github-code | 36 |
12198741928 | import pandas as pd
import streamlit as st
import fitz
from PIL import Image
from dataExtractor import DataExtractor
from image2 import Canvas
from firebase import FirebaseDB
import json
from st_keyup import st_keyup
json_data = {'Tear Down': ['cable', 'bomba', 'intake'],
'Production': ['simula... | gapastorv/st_rca_project | v2-incomplete/pages/Parsing.py | Parsing.py | py | 12,399 | python | en | code | 0 | github-code | 36 |
15197021379 | import argparse
import socket
import sys
import json
import urllib.request
import redis
import base64
import re
import boto3
import os
import subprocess
from faker import Faker
import logging
logging.basicConfig(level=logging.DEBUG)
fake = Faker('en_US')
Faker.seed(1337)
kms_client = boto3.client('kms')
kms_key_id =... | SMonaghan/nitro-enclave-with-redis | files/server.py | server.py | py | 5,032 | python | en | code | 0 | github-code | 36 |
35802251836 | import os
import config
from dotenv import load_dotenv
import neuronet
import markups as nav
import actions
import constants
import paths
import user_settings as settings
from utils import set_default_commands
import markovify
import logging
from gtts import gTTS
import asyncio
from aiogram import Bot, types, Dispat... | Lucifer13Freeman/Sunny-Telegram-Bot | bot.py | bot.py | py | 7,710 | python | en | code | 0 | github-code | 36 |
37478764816 | def load_dataset(key_values):
if key_values['dataset'] == 'cora':
from .preprocessing_cora import clean_cora
table, pairs = clean_cora()
elif key_values['dataset'] == 'restaurant':
from .preprocessing_restaurant import clean_restaurant
table, pairs = clean_restauran... | JSLKM/thesis_blocking | blocking/preprocessing_datasets/__init__.py | __init__.py | py | 1,521 | python | en | code | 1 | github-code | 36 |
1488340313 | # Code you have previously used to load data
import pandas as pd
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
# Path of the file to read
file_path = './home-data-fo... | tyrl76/Kaggle | House Prices/main.py | main.py | py | 1,604 | python | en | code | 0 | github-code | 36 |
36810437100 |
MPG = 20
def find_ample_city(gallons, distances):
curr_gas, total_gas, start_city, remaining_gas = 0, 0, 0, 0
for i in range(len(gallons)):
curr_gas = gallons[i]*MPG - distances[i]
if remaining_gas >= 0:
remaining_gas += curr_gas
else:
remaining_gas = curr_gas
... | oc0de/pyEPI | 17/6.py | 6.py | py | 693 | python | en | code | 0 | github-code | 36 |
74577237222 | import subprocess
from pathlib import Path
from typing import List
RESOURCE_PATH = Path("tests/resources")
def call_main(args: List[str]) -> List[str]:
root_path = Path("./")
filename = root_path / "rmsd/calculate_rmsd.py"
cmd = ["python", f"{filename}", *args]
proc = subprocess.Popen(cmd, stdout=... | charnley/rmsd | tests/context.py | context.py | py | 510 | python | en | code | 431 | github-code | 36 |
7775036999 | import sys
from heapq import heappop, heappush, heapify
class edge():
def __init__(self, src, nbr, weigh):
self.src = src
self.nbr = nbr
self.weigh = weigh
v = int(input())
e = int(input())
graph = {}
for i in range(v):
graph[i] = []
for i in range(e):
a, b, c = map(int, input().split... | nishu959/graphpepcoding | graphmuktisolverpep.py | graphmuktisolverpep.py | py | 1,682 | python | en | code | 0 | github-code | 36 |
71354143145 | def animal_cracker(string):
"""
A function that takes two-word string and returns
True if both words begin with the same letter
"""
mystring = string.lower().split(' ')
if mystring[0][0] == mystring[1][0]:
print(f'{mystring} both have the same beginning letter')
else:
print... | Aifedayo/Logic | animal_cracker2.py | animal_cracker2.py | py | 411 | python | en | code | 1 | github-code | 36 |
12171400766 | # numbers 리스트로 만들 수 있는 모든 합의 경우의 수
def solution(numbers):
answer = []
for i in range(len(numbers)):
for j in range(i+1, len(numbers)):
answer.append(numbers[i] + numbers[j])
answer = sorted(list(set(answer)))
return answer
print(solution([2,1,3,4,1]))
| hi-rev/TIL | Programmers/level_1/two_plus.py | two_plus.py | py | 323 | python | ko | code | 0 | github-code | 36 |
37939233633 | """!@namespace httpproxy Transport Layer fuer XMLRPClib"""
import xmlrpclib
import urllib2
class Urllib2Transport(xmlrpclib.Transport):
"""!Transport-Layer fuer das XMLRPC-Modul unter Verwendung von urllib2"""
def __init__(self, opener=None, https=False, use_datetime=0):
xmlrpclib.Transport.__init__(se... | spectal/cobbler_tornado | modules/httpproxy.py | httpproxy.py | py | 1,301 | python | en | code | 0 | github-code | 36 |
35658678468 | """The filtersets tests module."""
import pytest
from django.db.models.query import QuerySet
from django.http.request import HttpRequest
from communication.filtersets import (_get_interlocutors, _get_recipients,
_get_reviews, _get_senders)
pytestmark = pytest.mark.django_db
def... | webmalc/d8base-backend | communication/tests/filtersets_tests.py | filtersets_tests.py | py | 1,658 | python | en | code | 0 | github-code | 36 |
75226770345 | from django.core.exceptions import ValidationError
from django.db import models
from django.urls import reverse
from django.utils.text import slugify
from django_resized import ResizedImageField
from .base import BaseModel
from .images import Images
def file_size(value):
limit = 6 * 1024 * 1024
if value.size ... | KennyDaktyl/miktel_shop | web/models/articles.py | articles.py | py | 2,215 | python | en | code | 0 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.