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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
24844272085 | from flask import Flask,jsonify,request
from flask_cors import CORS, cross_origin
import shcheck
from sslscan import SSLChecker
from urllib.parse import urlparse
app = Flask(__name__)
@app.route('/status', methods=["GET"])
@cross_origin(supports_credentials=True)
def home():
return 'Server is running'
@app.route(... | Aman-Codes/webevaluator | backend/python/security_header/app.py | app.py | py | 1,006 | python | en | code | 15 | github-code | 90 |
29627673201 | from app import app, db
from flask import jsonify, request
from app.util import auth_required
from app.models import StreamLog, Broadcaster
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
import json
COMMON_ERRORS = {
'backendError': "yt_backend_error",
'liv... | Amperture/amp-stream-viewer | app/youtube.py | youtube.py | py | 6,006 | python | en | code | 0 | github-code | 90 |
18440794489 | import sys
def input():
return sys.stdin.readline().rstrip()
def rec(i,a,b,c):
if i==N:
if a==0 or b==0 or c==0:
return 10**12
return abs(a-A)+abs(b-B)+abs(c-C)
res=rec(i+1,a,b,c);
res=min(res,rec(i+1,a+l[i],b,c)+(10 if a else 0))
res=min(res,rec(i+1,a,b+l[i],c)+(10 if b else 0))
res=min(re... | Aasthaengg/IBMdataset | Python_codes/p03111/s655916918.py | s655916918.py | py | 464 | python | en | code | 0 | github-code | 90 |
17072036412 | from os import name
from . import views
from django.conf.urls import include, url
from django.urls import path, include
from mystorev2.views import Dashboard, RegistrationView, AdminView, AdminGroupList, AdminGroupUpdate, admindb
from .views import AdminUpdate, LandingView, WarehouseCreate, WarehouseList, WarehouseUpda... | sudo-monkey/python-CRUD-inventory | mystorev2/urls.py | urls.py | py | 2,175 | python | en | code | 0 | github-code | 90 |
33664346457 | class Solution(object):
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
result = []
def DFS(queens, xy_diff, xy_sum):
p = len(queens)
if p == n:
result.append(queens);
return None
... | algorithm004-04/algorithm004-04 | Week 07/id_539/LeetCode_4_539.py | LeetCode_4_539.py | py | 612 | python | en | code | 66 | github-code | 90 |
152735261 | import dataclasses
from typing import TYPE_CHECKING
import inject
from returns.maybe import Nothing
from returns.pipeline import flow
from returns.pointfree import bind_result
from returns.result import Success
from board.repositories import ReservationsRepo
from board.usecases.mixins import ReservationSelectMixin
fr... | pmisters/django-code-example | board/usecases/_attach_contact_to_reservation.py | _attach_contact_to_reservation.py | py | 3,231 | python | en | code | 0 | github-code | 90 |
17961105619 | from operator import mul
from functools import reduce
A = input()
N = len(A)
ans = N*(N-1)//2
def cmb(n,r):
r = min(n-r,r)
if r == 0: return 1
over = reduce(mul, range(n, n - r, -1))
under = reduce(mul, range(1,r + 1))
return over // under
for i in range(26):
num = A.count(chr(ord('a') + i))... | Aasthaengg/IBMdataset | Python_codes/p03618/s344535834.py | s344535834.py | py | 382 | python | en | code | 0 | github-code | 90 |
18033012009 | import sys
input = sys.stdin.readline
def warshall_floyd(d):
#d[i][j]: iからjへの最短距離
for k in range(n):
for i in range(n):
for j in range(n):
d[i][j] = min(d[i][j],d[i][k] + d[k][j])
return d
inf=float("inf")
n,m=map(int,input().split())
G=[[inf]*n for _ in range(n)]
for _ i... | Aasthaengg/IBMdataset | Python_codes/p03837/s429602773.py | s429602773.py | py | 705 | python | en | code | 0 | github-code | 90 |
28590045975 | """Utilizando listas faça um programa que faça 5 perguntas para uma pessoa sobre um crime. As perguntas são:
"Telefonou para a vítima?"
"Esteve no local do crime?"
"Mora perto da vítima?"
"Devia para a vítima?"
"Já trabalhou com a vítima?" O programa deve no final emitir uma classificação sobre a participação da p... | santospat-ti/Python_ExListas | ex14.py | ex14.py | py | 1,320 | python | pt | code | 0 | github-code | 90 |
18360874591 | from __future__ import print_function
import os
import vtk, qt, ctk, slicer
from DICOMLib import DICOMPlugin
from DICOMLib import DICOMLoadable
#
# This is the plugin to handle translation of diffusion volumes
# from DICOM files into MRML nodes. It follows the DICOM module's
# plugin architecture.
#
class DICOMDiffu... | SlicerDMRI/SlicerDMRI | Modules/Scripted/DMRIPlugins/DICOMDiffusionVolumePlugin.py | DICOMDiffusionVolumePlugin.py | py | 7,195 | python | en | code | 62 | github-code | 90 |
43046671027 | from django.urls import path, include
from . import product_view
from . import category_view
from . import search_result_view
from . import account_view
from . import favorites_view
from . import cart_view
from . import order_view
urlpatterns = [
path(
"product/",
include(
[
... | Jamison-Chen/my_online_shop_backend | my_online_shop/shop/urls.py | urls.py | py | 1,419 | python | en | code | 0 | github-code | 90 |
18317232029 | N = int(input())
A = list(map(int,input().split()))
ans = 10**18
left = 0
right = sum(A)
for i in range(N):
ans = min(ans, abs(left-right))
left += A[i]
right -= A[i]
print(ans) | Aasthaengg/IBMdataset | Python_codes/p02854/s489661410.py | s489661410.py | py | 189 | python | en | code | 0 | github-code | 90 |
7032649597 | from os import rename, mkdir
from sys import argv
# <name of motion>_<Wrist or bicep sensors>_<accel, gyro, or magn><trial num>
def main(args):
num_args = 9
if len(args) != num_args:
print('Usage: <accel.csv wrist> <gyro.csv wrist> <magn.csv wrist>')
print(' <accel.csv bicep> <gyro.csv b... | MedLaunch/Myotera_GitHub | datasets/rename.py | rename.py | py | 1,022 | python | en | code | 4 | github-code | 90 |
27061060732 | from typing import Dict, Union
import json
import boto3
class MessagePublisher:
def __init__(self):
self._iot_client = boto3.client('iot-data')
def publish(self, topic: str, message: Union[str, Dict]) -> None:
if isinstance(message, dict):
payload = json.dumps(message, ensure_as... | pondelion/irdl-backend | irdl/services/remote_command/publisher.py | publisher.py | py | 491 | python | en | code | 0 | github-code | 90 |
9419672361 | from django.shortcuts import render
from django.views.generic import TemplateView, ListView
from .forms import *
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib import auth
from django.contrib import messages
import os
from django.http impor... | saipavanrnv/programming_hub | coding_hub/views.py | views.py | py | 3,316 | python | en | code | 0 | github-code | 90 |
18224561529 | from math import floor, ceil
a, b, n = map(int, input().split())
# a, b, n = 10, 8, 10
num = min(b-1, n)
#n以下で最大のbの倍数
print(floor(a*num/b) - a*floor(num/b))
# ans = 0
# for i in range(1,100):
# tmp = floor(a*i/b) - a*floor(i/b)
# print("i", i, "tmp", tmp)
# ans = max(ans, tmp)
# if a > b:
# print... | Aasthaengg/IBMdataset | Python_codes/p02696/s687865718.py | s687865718.py | py | 412 | python | en | code | 0 | github-code | 90 |
21894996592 | """ Advent of Code, 2020: Day 03, a """
with open(__file__[:-5] + "_input") as f:
inputs = list(f)
rows = [line.strip() for line in inputs]
def run():
""" Step through each row and every 3rd column to find collisions """
trees = 0
x = 0
width = len(rows[0])
for line in rows[1:]:
x += ... | nickspoons/adventofcode | python/2020/aoc_03_a.py | aoc_03_a.py | py | 482 | python | en | code | 0 | github-code | 90 |
1980598405 | import socket
from .common import * # noqa
DEBUG = True
INTERNAL_IPS = ['127.0.0.1']
hostname, _, ips = socket.gethostbyname_ex(socket.gethostname())
INTERNAL_IPS += [ip[:-1] + '1' for ip in ips]
ALLOWED_HOSTS.extend(['127.0.0.1', 'localhost'])
INSTALLED_APPS.append('debug_toolbar')
# Insert debug_toolbar middlew... | thiras/cookiecutter-docker-django | {{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/settings/dev.py | dev.py | py | 577 | python | en | code | 4 | github-code | 90 |
16403990969 | def solve(graph,removed_v):
if len(removed_v) == len(graph):
global count
count += 1
else:
degrees = {}
for v in graph.keys():
if v not in removed_v:
degrees[v] = 0
for inVertex,outList in graph.items():
if inVertex not in removed_v... | HacoK/SolutionsOJ | 2-1/solution.py | solution.py | py | 1,108 | python | en | code | 3 | github-code | 90 |
5627062728 | from typing import Optional, Dict
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from starlette.responses import FileResponse
from datetime import datetime
import uvicorn
import glob
import json
app = FastAPI()
app.add_middleware(
CORSMiddleware, allow_origins=["*"], allow_methods... | magnusbarata/slice-matching-annotator | backend/main.py | main.py | py | 1,591 | python | en | code | 0 | github-code | 90 |
23736589337 | n = int(input())
sum_marks = 0.0
total_sum = 0.0
presentation_count = 0
presentation = input()
while presentation != 'Finish':
presentation_count += 1
for i in range(1, n+1):
mark = float(input())
sum_marks += mark
total_sum += mark
print(f'{presentation} - {sum_marks/n:.2f}')
... | krstoilo/SoftUni-Basics | Python-Basics/loops/train_the_trainers.py | train_the_trainers.py | py | 444 | python | en | code | 0 | github-code | 90 |
42504681606 | import cv2
import numpy as np
class OpticalFlowAnalyzer:
def getOpticalFlowMagnitude(self, path_to_video):
cap = cv2.VideoCapture(path_to_video)
ret, frame1 = cap.read()
frame1 = cv2.resize(frame1, (240, 160))
prvs = cv2.cvtColor(frame1,cv2.COLOR_BGR2GRAY)
mean_mags = []
... | Tartar-san/montage.ai | video_analysis/OpticalFlowAnalyzer.py | OpticalFlowAnalyzer.py | py | 1,343 | python | en | code | 4 | github-code | 90 |
18230506426 | #!/usr/bin/env python3
import sqlalchemy as sa
import ws.utils
from ws.client.api import ShortRecentChangesError
import ws.db.selects as selects
from .GrabberBase import GrabberBase
class GrabberProtectedTitles(GrabberBase):
INSERT_PREDELETE_TABLES = ["protected_titles"]
def __init__(self, api, db):
... | lahwaacz/wiki-scripts | ws/db/grabbers/protected_titles.py | protected_titles.py | py | 5,406 | python | en | code | 27 | github-code | 90 |
39129159318 | from django.urls import path
from . import views
urlpatterns = [
path('sets/', views.set, name='set'),
path('myset/', views.my_set, name='myset'),
path('addset/', views.sets_add, name='setadd'),
path('set/', views.SetCreateView.as_view(), name='create'),
]
| 4ulkoff/coso | calculate/urls.py | urls.py | py | 275 | python | en | code | 0 | github-code | 90 |
15327399168 | """
This file is the implementation of following algorithm:
1. Obtain frame from camera.
2. Rotate camera so that socket is in the center of the image.
3. Move towards the socket until the average depth of pixels around socket is 35cm.
4. De-project several basepoints (points at socket surface) from pixel to camera coo... | viacheslavm21/PhoenixBot | cnn2d/algorithm.py | algorithm.py | py | 20,252 | python | en | code | 0 | github-code | 90 |
14643079230 | import traceback
import re
from datetime import date
from werkzeug.exceptions import HTTPException, BadRequest, default_exceptions
from flask import Flask, json, current_app, request, Request, url_for
from flask.ext.babelex import Babel, get_locale
from flask_beaker import BeakerSession
import flask_bootstrap
#######... | Vickyogesh/quiz-platform | wsgi/quiz/appcore.py | appcore.py | py | 6,578 | python | en | code | 0 | github-code | 90 |
17949420259 | def main():
width, height, target = map(int, input().split())
answer = False
if target == 0:
answer = True
else:
for i in range(height):
if answer:
break
for j in range(width):
if (width - j) * (height - i) + i * j == target:
... | Aasthaengg/IBMdataset | Python_codes/p03592/s876678957.py | s876678957.py | py | 452 | python | en | code | 0 | github-code | 90 |
8673261842 | import pandas as pd
csv_pd = pd.read_csv(r'E:\李震祥\PYGIT\PYref\ReviewCode\pandas\Data\各省市订单数据.csv', encoding='utf-8')
xx = csv_pd.loc[:, "name"]
result = pd.DataFrame(columns=['name'])
result['name'] = csv_pd.apply(lambda x: x["name"] + "res", axis=1)
# 1、查询列 范围Series
df_colu_alpha = csv_pd.loc[:, "name"] # 返回一个Seri... | muyuchenzi/PYref | ReviewCode/pandas/basic_skill/pand_search.py | pand_search.py | py | 1,219 | python | en | code | 0 | github-code | 90 |
27677208080 | import numpy as np
import scipy.linalg as la
def get_random_patch(data, n_frames, crop_sz, margin=4):
t, n, m = data.shape
start_frame = np.random.randint(t - n_frames)
start_i = margin + np.random.randint(n - 2 * margin - crop_sz)
start_j = margin + np.random.randint(m - 2 * margin - crop_sz)
ret... | cwindolf/form-motion-tfp | util.py | util.py | py | 1,815 | python | en | code | 1 | github-code | 90 |
22209029879 | import sys, os, glob
from subproc import run_subproc
from binCrop import binCrop
from PIL import Image
def dm4_to_tiff(fullfilename,x1,y1,x2,y2,bin):
""" Convert the .dm4 file to a .tiff after cropping and binning. """
# Initalize some filename variables
path,f = os.path.split(fullfilename)
filebasenam... | Wflying1224/K2-data-scripts | Hour_00/getImage.py | getImage.py | py | 1,729 | python | en | code | 0 | github-code | 90 |
7165355520 | import pygame
import math
from PodSixNet.Connection import ConnectionListener, connection
from time import sleep
class BoxesGame(ConnectionListener):
def __init__(self):
pass
pygame.init()
pygame.font.init()
width, height = 389, 489
#initialize the screen
self.screen = pygame.display.set_mode((width, h... | gordonseto/Boxes | Boxes.py | Boxes.py | py | 6,662 | python | en | code | 0 | github-code | 90 |
6027611952 | # 1. 바라보고 있는 방향 이동 불가
# 반시계 방향으로 90도 방향 바꿈 : dir = [[~],[~]]
# 2. 바라보고 있는 방향 이동 가능
# 바로 앞이 격자 밖이면 이동하여 탈출
# 아닐 때, 현재 방향으로 한칸 이동했을 때, '지금 바라보는 방향'의 오른쪽에 벽이 있으면 앞으로 한 칸 이동
# 현재 방향으로 한칸 이동했을 때, 벽 없으면 시계방향으로 90도 방향 틀어 한칸 더 전진
import sys
sys.setrecursionlimit(10000)
def escape(x,y,cur_dir) :
global time,cnt, po... | jooyun-1/codetree-TILs | 231211/벽 짚고 미로 탈출하기/escape-maze-with-wall-following.py | escape-maze-with-wall-following.py | py | 1,838 | python | ko | code | 0 | github-code | 90 |
17990647199 | N = int(input())
s = []
for i in range(N):
s.append(int(input()))
S = sum(s)
if S%10 != 0:
print(S)
else:
b = True
for j in range(N):
if s[j]%10 == 0:
continue
else:
b = False
if b:
print(0)
else:
s.sort()
for k in range(N):
if s[k]%10 != 0:
print(S-s[k])
... | Aasthaengg/IBMdataset | Python_codes/p03699/s939676305.py | s939676305.py | py | 333 | python | en | code | 0 | github-code | 90 |
40140074835 | # File : findZigZagSequence.py
# Version : 1.0.0
# Description : Solution to the findZigZagSequence problem
#
# Date: : Feb 06, 2023
# Author : Mr. X
# License : Creative Commons CC0
# Given an array of n distinct integers, transform the array into a zig zag
# seq... | gone-still/codingQuestions | 008 - findZigZagSequence/findZigZagSequence.py | findZigZagSequence.py | py | 1,737 | python | en | code | 0 | github-code | 90 |
19821280890 | """
Title: Directory Tracker
Description: For tracking the directories created / used
Author: Janzen Choi
"""
# Libraries
import os
# Constants
DEFAULT_PATH = './'
DEFAULT_FOLDER = 'folder'
# Tracker Class
class Tracker:
# Constructor
def __init__(self, path, folder):
self.path = path
s... | janzenchoi/creep | src/packages/io/tracker.py | tracker.py | py | 827 | python | en | code | 0 | github-code | 90 |
18027903699 | def main():
n = int(input())
s = input()
x = 0
max_s = 0
for i in range(n):
if s[i] == 'I':
x += 1
elif s[i] == 'D':
x -= 1
if max_s < x:
max_s = x
print(max_s)
if __name__ == "__main__":
main()
| Aasthaengg/IBMdataset | Python_codes/p03827/s121245370.py | s121245370.py | py | 288 | python | en | code | 0 | github-code | 90 |
7389268346 | from typing import Dict
from fastapi import APIRouter, Depends
from .depends import *
router = APIRouter()
@router.post('/solve-inverse')
async def solve_inverse(
inv: InverseRepository = Depends(get_inverse_repository),
req: Dict = {}
):
return await inv.solve_inverse(req) | illumi1717/Nummet | nummet_back/endpoints/InverseRouter.py | InverseRouter.py | py | 312 | python | en | code | 0 | github-code | 90 |
70607631658 | from lib.Core import hook
from lib import logger
from random import randint
from time import sleep
port_rotate_count = 0
port_clicked = False
def call(t, d):
global port_clicked
if not hook.hack_available() and not port_clicked:
port = select_port(t)
if port.is_displayed() and port.is_enabled... | ritonis/TypeSense | lib/Core/AutoPort.py | AutoPort.py | py | 845 | python | en | code | 1 | github-code | 90 |
2923438027 | from __future__ import absolute_import, unicode_literals, print_function
import sys
import random
import pymc3 as pm
import numpy as np
import pandas as pn
import h5py
import scipy.stats as st
from scipy.linalg import inv as inverse
import matplotlib
matplotlib.use('PDF')
import matplotlib.pyplot as plt
from matplotli... | olivares-j/Kalkayotl | kalkayotl/inference.py | inference.py | py | 20,064 | python | en | code | 9 | github-code | 90 |
18332387489 | """
気付き
1、float('inf')はちょい遅いみたい
2、input()よりもinput = sys.stdin.readlineの方が爆速らしい(知らんがな)
"""
import sys
inf = 10 ** 15
input = sys.stdin.readline
N, M, L = map(int, input().split())
dp = [[inf] * N for _ in range(N)]
for _ in range(M):
a, b, c = map(int, input().split())
dp[a-1][b-1] = c
dp[b-1][a-1] = c
for ... | Aasthaengg/IBMdataset | Python_codes/p02889/s296342711.py | s296342711.py | py | 1,082 | python | en | code | 0 | github-code | 90 |
26476566778 | from typing import *
from pprint import pprint
from collections import defaultdict
import tempfile
def get_line() -> 'str | None':
try:
return input().strip("\n")
except EOFError:
return None
ans = 0
# tail = [0, 0]
tails = [[0, 0] for _ in range(9)]
visited = set([(0, 0)])
head = [0, 0]
... | nkitsaini/advent-of-code-2022 | py/d9-2.py | d9-2.py | py | 1,548 | python | en | code | 0 | github-code | 90 |
42227399250 | # HW: BMI Evaluation
# By using the skeleton of code below.
def bmi_evaluate(w, h):
'''
คำนวณค่า BMI โดยน้ำหนัก (w) มีหน่วยเป็น kg และส่วนสูง (h) มีหน่วยเป็น cm
แล้วประเมินความสมดุลของน้ำหนักตัวต่อส่วนสูงว่าอยู่ในเกณฑ์ที่เหมาะสมหรือไม่
'''
b = w / (h/100)**2
### BEGIN SOLUTION
if b < ... | ppoohh25/Computer-programing | Python/Ch.6/2.py | 2.py | py | 1,081 | python | th | code | 0 | github-code | 90 |
2424542475 | from random import choice, randint
import eval
x = randint(1,11)
y = randint(1,11)
op1 = ["+", "-", "*", "/"]
op = choice(op1)
res = eval.calc(x, y, op)
error = choice([-1,0,0,1])
display = res + error
print(x, op, y, "=", display)
ans = input("(Y/N)? ").lower()
if ans == "y":
if error == 0:
print("Yay")... | ellynnhitran/Fundamentals_C4T4 | Session07/freakingmath.py | freakingmath.py | py | 474 | python | en | code | 0 | github-code | 90 |
72606925416 | import datetime
from django.db import transaction
from payroll.models import TimeSheet, TimeReport
from payroll.utils import DATE_FORMAT, get_pay_rate
@transaction.atomic
def handle_uploaded_file(f):
time_sheet = []
for idx, line in enumerate(f):
if idx > 0:
time_info = line.decode('utf-... | HanyinZhang/SimplePayroll | payroll/handlers.py | handlers.py | py | 1,608 | python | en | code | 0 | github-code | 90 |
27251609730 | from rest_framework import serializers
from app.models import TimeRegistration
class TimeRegistrationSerializer(serializers.ModelSerializer):
registration_day = serializers.DateField(format="%m/%d/%Y",
input_formats=["%m/%d/%Y",
... | candale/time_reg | app/serializers.py | serializers.py | py | 1,820 | python | en | code | 0 | github-code | 90 |
7665197710 | def binary_search(list, target):
first = 0
last = len(list) - 1
while first <= last:
mid_point = (first + last) // 2
if list[mid_point] == target:
return mid_point
elif list[mid_point] < target:
first = mid_point + 1
else:
last = mid_point - 1
return None
def verify(resu... | analogdev-eth/Data-Structures-and-Algorithms | binary_search.py | binary_search.py | py | 535 | python | en | code | 1 | github-code | 90 |
4433098311 | import matplotlib.pyplot as plt
import numpy as np
#Função: 2x +1
# vetorX =[0,1,2,3,4,5]
# vetorY =[1,3,5,7,9,11]
#Criar figura
# fig = plt.figure(figsize=(5,5))
# plt.plot(vetorX,vetorY, label = 'Função y= 2x + 1', color = 'g')
#plt.show()
def f(x):
y = 2*x +1
return y
vetorX = np.arange(-10,10,0.1)
vetor... | Carolissis/Exercicios | Primeiro_periodo/Aula MAT/graficos/testegrafico.py | testegrafico.py | py | 385 | python | en | code | 0 | github-code | 90 |
15301419150 | import datetime
import backtrader as bt
from indikeppar import *
import csv
import numpy as np
class KepparStrat(bt.Strategy):
params = (("printlog", True), ("quantity", 200))
def log(self, txt, dt=None, doprint=False):
"""Logging function for strategy"""
if self.params.printlog or doprint:
... | wuchiwo/MAMF | temp-disposal/backtesting-Keppar.py | backtesting-Keppar.py | py | 3,021 | python | en | code | 2 | github-code | 90 |
71109571816 | import unittest
from typing import List
from .day_011 import solve_one, solve_two, visualize, search_paths, surrounding_coords
def to_grid(raw: str) -> List[List[str]]:
return [list(x) for x in raw.splitlines()]
test_raw = """L.LL.LL.LL
LLLLLLL.LL
L.L.L..L..
LLLL.LL.LL
L.LL.LL.LL
L.LLLLL.LL
..L.L.....
LLLLLLLL... | jwelch92/advent-of-code-2020 | days/011/test_day_011.py | test_day_011.py | py | 3,617 | python | en | code | 0 | github-code | 90 |
22259020842 | # 걍풀어도 lv1이라 풀리긴 하는데 어렵게 나오면 시간초과 나올수도있어서
# 빠른 풀이가 필요할 수 있음 (예를들면 lessons_12923_숫자블록_약수구하기)
# 빠른풀이 :
# 어떤 수의 약수가 홀수라는 말은 그 수가 다른 수의 제곱수라는걸 의미한다.
# 즉 left이상 right 이하 제곱수들을 찾으면 된다.
# 수열의 합을 이용하면 합도 빠르게 구할 수 있다. https://prgms.tistory.com/57
def numof(num_):
cnt = 0
for i in range(1, num_ + 1):
if (num_ %... | JisungKim94/CodingTest | Programmers/lessons_77884_약수의개수와덧셈_효율적풀이.py | lessons_77884_약수의개수와덧셈_효율적풀이.py | py | 901 | python | ko | code | 0 | github-code | 90 |
1619463141 | import pygame
import constants
class UserPlayer(pygame.sprite.Sprite):
def __init__(self, image_path, x, y):
super().__init__()
self.image = pygame.image.load(image_path).convert_alpha()
self.scaled_background = pygame.transform.scale(self.image,
... | ubongjc/topping_battle | Pygame/players/user_player.py | user_player.py | py | 4,027 | python | en | code | 0 | github-code | 90 |
70931791016 | from ..core.js import JsUtils
from ..core.css import css_files_loader
from ..core.html import Standalone, html_template_loader
from . import npm, node, templates
import logging
import zipfile
import re
import json
import subprocess
from collections import OrderedDict
from typing import Any, Dict, List, Union
from path... | epykure/epyk-ui | epyk/web/angular.py | angular.py | py | 38,985 | python | en | code | 71 | github-code | 90 |
18579391359 | #!/usr/bin/env python3
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)
N, H = map(int, input().split())
A = []
B = []
for i in range(N):
a, b = map(int, input().split())
A.append(a)
B.append(b)
max_a = max(... | Aasthaengg/IBMdataset | Python_codes/p03472/s374158709.py | s374158709.py | py | 884 | python | en | code | 0 | github-code | 90 |
12121874117 | """
Task to group parallel running tasks
"""
import sys
import logging
from teuthology import run_tasks
from teuthology import parallel
log = logging.getLogger(__name__)
def task(ctx, config):
"""
Run a group of tasks in parallel.
example::
- parallel:
- tasktest:
- taskt... | ceph/teuthology | teuthology/task/parallel.py | parallel.py | py | 2,033 | python | en | code | 153 | github-code | 90 |
17930708619 | n = int(input())
l0=2
l1 = 1
l = l0 + l1
for i in range(n-2):
l0 = l1
l1 = l
l = l0 + l1
if n==1:
print(l1)
else:
print(l)
| Aasthaengg/IBMdataset | Python_codes/p03544/s694521321.py | s694521321.py | py | 139 | python | en | code | 0 | github-code | 90 |
21416219544 | from lib2to3.pytree import type_repr
import mariadb
from models.items import Item_M
from models.scrapper import getUrl
conn_params = {
'user': '',
'password': '',
'host':'localhost',
'database': 'products_eb'
}
class Classs_M:
@staticmethod
def find_by_name(name):
conn = mariadb.c... | Soria-c/Inventario_App_Android | API/models/classes.py | classes.py | py | 3,440 | python | en | code | 0 | github-code | 90 |
21541231842 | from rest_framework import serializers
from rest_framework_gis import serializers as gis_serializers
from drf_spectacular.utils import extend_schema_field
from safers.users.models import Organization
from safers.core.fields import UnderspecifiedDateTimeField
from safers.chatbot.models import Communication
from .ser... | astrosat/safers-dashboard-api | server/safers/chatbot/serializers/serializers_communications.py | serializers_communications.py | py | 3,136 | python | en | code | 0 | github-code | 90 |
22153282318 | #coding:utf-8
from django.db import connection,transaction
from django.shortcuts import render,HttpResponse
from django.core.exceptions import ObjectDoesNotExist
#from django.views.decorators.csrf import csrf_exempt
import json
from App.utils import log,AppException
from App.models import *
from App.ueditor.views impor... | zhangtaoqd/website | App/views.py | views.py | py | 11,762 | python | en | code | 0 | github-code | 90 |
70618255657 | import numpy as np
class Config:
def __init__(self):
# data path
self.train_images_path = './train_images/'
self.train_labels_path = './train_labels/'
self.test_images_path = './test_images/'
self.test_labels_path = './test_labels/'
self.model_path = './model/'
... | Julymycin/U-Net_keras_cardiovascular | config.py | config.py | py | 763 | python | en | code | 0 | github-code | 90 |
23434765882 | # -*- coding: utf-8 -*-
# Author: Xiaoming Qin
"""Train a convolutional neural network"""
import sys
import os
import torch
import argparse
import time
import numpy as np
import matplotlib.pyplot as plt
import torch.nn as nn
from PIL import Image
from os.path import join as pjoin
from torch.autograd import Variable
... | bledem/webvision | train.py | train.py | py | 24,465 | python | en | code | 0 | github-code | 90 |
28300144675 | from unittest import TestCase
from command.controllers.RemoteControl import RemoteControl
from command.vendors.Light import Light
from command.vendors.Stereo import Stereo
from command.vendors.CeilingFan import CeilingFan
from command.commands.LightOnCommand import LightOnCommand
from command.commands.LightOffCommand i... | gsegon/design_patterns | command/tests/test_RemoteControl.py | test_RemoteControl.py | py | 3,658 | python | en | code | 0 | github-code | 90 |
39714051397 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 14 23:43:27 2018
@author: diegosoaresub
"""
from sklearn.externals import joblib
class PredictLoan:
def __init__(self):
print('Loading Gradient Boosting Model...')
self.clf = joblib.load('gradient_boosting_model.pkl')
... | diegosoaresub/loan_negotiation | predict/WsPredict/predict_loan.py | predict_loan.py | py | 567 | python | en | code | 0 | github-code | 90 |
40421069469 | import openjij.cxxjij.graph as G
import numpy as np
class Ferro(G.Dense):
def __init__(self, N, JJ):
super().__init__(N)
for i in range(N):
for j in range(i):
self[i, j] = -JJ
self[j, i] = -JJ
class SK(G.Dense):
def __init__(self, N, mu=0, sig=1):
... | Ryuta339/QMCSample | workspace/models.py | models.py | py | 1,537 | python | en | code | 0 | github-code | 90 |
71465703977 | # IMPORTS
from flask import (Flask, flash, render_template, request, session, url_for)
from flask_mysqldb import MySQL, MySQLdb
import bcrypt
# INITIALIZATIONS
app = Flask(__name__)
sql = MySQL(app)
# CONFIGURATIONS
app.config["SECRET_KEY"] = "notsecret"
app.config["MYSQL_HOST"] = "localhost"
app.config["MYSQL_USER... | Qoddeus/solid-lamp | app.py | app.py | py | 11,961 | python | en | code | 0 | github-code | 90 |
10231993096 | # coding=utf-8
import numpy as np
from bilstm_crf import BiLSTM_CRF
from collections import defaultdict
import preprocess as p
from evaluate import evaluate1
import os
from keras.optimizers import Adam
os.environ["CUDA_VISIBLE_DEVICES"] = "1,2,3,4"
def get_X_orig(X_data, index2char):
"""
:param X_data: index_... | MenglinLu/Chinese-clinical-NER | word2vec_bilstm_crf/predict_bilstm_crf.py | predict_bilstm_crf.py | py | 6,975 | python | en | code | 331 | github-code | 90 |
17436767970 | """
GEMASTIK 2017
TIM DEEPSTUDY UNIVERSITAS INDONESIA
Joseph Jovito | Kerenza Dexolodeo | Wisnu Pramadhitya Ramadhan
Prediksi Fluktuasi Nilai Tukar Mata Uang Melalui Konten Berita Daring
Desc:
"""
import sqlite3
import sys
import settings
from Database import Database
from Models import Boosting, Neighbors, balanc... | ristek-deepstudy/gemastik-2017-prediksi-kurs | src/python_timeseries_tf.py | python_timeseries_tf.py | py | 6,524 | python | en | code | 1 | github-code | 90 |
18102131559 | from sys import stdin
from collections import deque
n = int(stdin.readline())
M = [[0] * (n + 1) for _ in range(n + 1)]
d = [200] * (n + 1)
def bfs():
d[1] = 0
dq = deque()
dq.append(1)
while len(dq) > 0:
u = dq.popleft()
for v in range(1, n + 1):
if M[u][v] == 0 or d[v] != 2... | Aasthaengg/IBMdataset | Python_codes/p02239/s955254965.py | s955254965.py | py | 586 | python | en | code | 0 | github-code | 90 |
17452735972 | from .bigBird import BigBirdDataset
from .coco import CocoDataset
from .obj_det import ObjectDetectionDataset
def coco_filter(ds):
"""
Filter all (im, bbox) pairs where segmentation area is greater than bounding
box area, and where larger side of bbox is greater than smaller side of image.
"""
num_... | siddancha/FlowVerify | flowmatch/datasets/__init__.py | __init__.py | py | 2,652 | python | en | code | 2 | github-code | 90 |
18344635059 | def main(n,k,s):
l=[0]
for i in range(1,n):
if s[i]==s[i-1]:
l[-1]+=1
else:
l.append(0)
print(min(n-1,sum(l)+k*2))
if __name__=='__main__':
import sys
input = sys.stdin.readline
n,k=map(int,input().split())
s=input()
main(n,k,s)
| Aasthaengg/IBMdataset | Python_codes/p02918/s509202794.py | s509202794.py | py | 270 | python | en | code | 0 | github-code | 90 |
72118058218 | import json
import time
import urllib.request as urllib2
from prometheus_client import start_http_server
from prometheus_client.core import GaugeMetricFamily, REGISTRY
class JenkinsCollector(object):
def collect(self):
metric = GaugeMetricFamily(
'jenkins_job_last_successful_build_timestamp_seco... | kamrajshahapure/myRepo | exp.py | exp.py | py | 751 | python | en | code | 0 | github-code | 90 |
9188733017 |
class ReferentBelief:
"""
Store a visual world with a probability distribution.
"""
def __init__(self, VisualWorld):
self.VisualWorld = VisualWorld
self.objectcounters = [0]*len(VisualWorld.objects)
self.featurecounters = [0]*len(VisualWorld.objects)
self.prob = [1]*le... | julianje/CommonGround | ReferentBelief.py | ReferentBelief.py | py | 1,767 | python | en | code | 0 | github-code | 90 |
43176533312 | import os
import time
from glob import glob
from pathlib import Path
import pandas as pd
import pytorch_lightning as pl
import sastvd as svd
import sastvd.linevd as lvd
from ray.tune import Analysis
def main(config, df):
"""Get test results."""
main_savedir = svd.get_dir(svd.outputs_dir() / "rq_results_new")... | davidhin/linevd | sastvd/scripts/rqtest.py | rqtest.py | py | 3,764 | python | en | code | 47 | github-code | 90 |
31663594395 | # -*- coding:utf-8 -*-
class Solution:
def hasPath(self, matrix, rows, cols, path):
# write code here
if not matrix:
return False
if not matrix[0]:
return False
def helper(i, j, p, v):
if not p:
return True
if i < 0 or ... | wzwhit/leetcode | 剑指offer/面12矩阵中的路径.py | 面12矩阵中的路径.py | py | 1,081 | python | en | code | 0 | github-code | 90 |
40064749381 | from soduku_solver.boards import Board
def solve(board: Board) -> bool:
pos = board.get_next_unresolved()
if not pos:
# Last field is resolved
return True
for num in board.get_available_numbers(pos):
board.set(pos, num)
if solve(board):
return True
bo... | johanvergeer/sudoku-solver | soduku_solver/solver.py | solver.py | py | 353 | python | en | code | 0 | github-code | 90 |
2277340224 | import unittest
import os
from textwrap import dedent
from os.path import join
from zc.buildout.testing import buildoutSetUp, buildoutTearDown
from zc.buildout.testing import install_develop
MULTICORE_CONF = """
[buildout]
parts = solr-mc
[solr-mc]
recipe = collective.recipe.solrinstance:mc
host = 127.0.0.1
port = 12... | naro/collective.recipe.solrinstance | collective/recipe/solrinstance/tests/test_solr_4.py | test_solr_4.py | py | 8,449 | python | en | code | null | github-code | 90 |
18579770649 | import sys
def LI(): return list(map(int,sys.stdin.readline().rstrip().split())) #空白あり
def S(): return sys.stdin.readline().rstrip()
N,H = map(int,S().split())
ab = [LI() for i in range(N)]
A = [(ab[i][0],1) for i in range(N)]
B = [(ab[i][1],2) for i in range(N)]
from operator import itemgetter
C = sorted(A+B,key... | Aasthaengg/IBMdataset | Python_codes/p03472/s837355274.py | s837355274.py | py | 621 | python | en | code | 0 | github-code | 90 |
74299015657 | """
BlacKnight
"""
__author__ = 'dkudrow'
import logging
from argparse import ArgumentParser
from client import BlacKnightClient
from eucalyptus import Eucalyptus
from util import Util
def main():
"""
Start the BlacKnight daemon.
"""
logging.basicConfig()
logging.getLogger('blacknight').setLeve... | dkudrow/BlacKnight | blacknight/__init__.py | __init__.py | py | 2,237 | python | en | code | 1 | github-code | 90 |
18112730159 | def get_char_value(char):
if char == "C":
return 1;
if char == "A":
return 2;
if char == "G":
return 3;
if char == "T":
return 4;
def get_string_value(string):
s = 0;
p = 1;
for char in string:
s += p * get_char_value(char);
p *= 5;
return... | Aasthaengg/IBMdataset | Python_codes/p02269/s106531270.py | s106531270.py | py | 1,422 | python | en | code | 0 | github-code | 90 |
5077716460 | #Question 1:
# Accept two integer numbers from a user and return their product and
# if the product is greater than 1000, then return their sum
num1 = int(input('Enter the first number : '))
num2 = int(input('Enter Second number : '))
product = num1 * num2
if product > 1000:
print(num1 + num2)
else:
print('... | sthnischal/Programming-Practice | 1. Python Basic Exercise for Beginners/1. greater number.py | 1. greater number.py | py | 358 | python | en | code | 0 | github-code | 90 |
35619145246 | class Location(object):
def __init__(self, location_id, path_description, description, printer, events):
"""description stores what will be seen when the player looks around.
paths lists the paths the player can take from this location.
objects lists the objects found at this location. Each may be visible or i... | rjmcf/HailTraveller | location.py | location.py | py | 1,805 | python | en | code | 0 | github-code | 90 |
73600634858 | import operator
def person_lister(func):
def inner(people):
people = sorted(people, key=lambda l: int(l[2]))
l = []
for person in people:
l.append(func(person))
return l
return inner
@person_lister
def name_format(person):
return ("Mr. " if person[3] == "M" else "... | aruzhantlek/webdev2019 | 10 week/HackerRank/9.py | 9.py | py | 486 | python | en | code | 0 | github-code | 90 |
18234221319 | import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007
def main():
N = int(readline())
ans = 0
for n in range(N + 1):
if n % 3 and n % 5:
ans += n
print(ans)
return
if __n... | Aasthaengg/IBMdataset | Python_codes/p02712/s618995734.py | s618995734.py | py | 352 | python | en | code | 0 | github-code | 90 |
31686488985 | # PGD code, generic
import time
import pandas as pd
import numpy as np
import sys
from math import *
pd.options.display.precision = 2
pd.set_option('display.precision', 2)
def progress_bar(i, n, size):
percent = float(i) / float(n)
sys.stdout.write("\r"
+ str(int(i)).rjust(3, '0')
... | JosepFanals/Power-systems-projects | ASD/Code/PGD/all2_refactored.py | all2_refactored.py | py | 14,597 | python | en | code | 2 | github-code | 90 |
42648739248 | import os
import json
import random
import sys
from t0_config import DATA_SPLITS_SIZES
random.seed(42)
keys = DATA_SPLITS_SIZES.keys()
full_data_dir = "../data"
sampled_data_dir = "../{}".format(sys.argv[1])
upper_limit = int(sys.argv[2])
os.makedirs(sampled_data_dir, exist_ok=True)
for i, key in enumerate(DATA_... | INK-USC/FiD-ICL | t0/data_prep/subsample.py | subsample.py | py | 1,033 | python | en | code | 10 | github-code | 90 |
9001716141 | #!/usr/bin/env python3
import json
from aws_cdk import core as cdk
from aws_cdk import aws_codecommit as codecommit
from lib.pr_construct import PRConstruct
from lib.lambda_construct import LambdaConstruct
_env_dev = cdk.Environment(account="", region="")
_repo_arn = ""
class DeployStack(cdk.Stack):... | quixoticmonk/PRworkflow-CDK | app.py | app.py | py | 1,005 | python | en | code | 0 | github-code | 90 |
37114865864 | import subprocess
import app.config as config
def pdf2html(pdf_path):
fn = pdf_path.split('/')[-1].replace('.pdf', '')
options = [
# '--fit-width=%s',
'--embed cijo',
'--process-outline=0',
'--optimize-text=1',
'--dest-dir=%s/%s' % (config.HTML_DIR, fn),
'--css-... | kaigezhang/yinwen | back/services/pdf2html.py | pdf2html.py | py | 433 | python | en | code | 0 | github-code | 90 |
18344304189 | n, k = [int(i) for i in input().split()]
s = input()
n_group = 0
now = s[0]
cnt = 0
happy = 0
s += 'z'
for i in s:
if now != i:
n_group += 1
if cnt > 1:
happy += cnt - 1
cnt = 1
else:
cnt += 1
now = i
for i in range(k):
if n_group > 2:
n_group -= 2
happy += 2
else:
happy += 1
if happy > n - 1:
h... | Aasthaengg/IBMdataset | Python_codes/p02918/s071482660.py | s071482660.py | py | 346 | python | en | code | 0 | github-code | 90 |
33095048151 | "=============Логические и условные операторы==========="
# логические операторы - выражения, которые возвращают True, если выражение верное, False - если не верное
# равенство
5==5 # True
4==5 # False
# не равенство
4!=5 # True
5!=5 # False
# больше
5>4 # True
4>5 # False
5>5 # False
# меньше
5<4 # False
5<10 # Tr... | ertayx/python_31_lections | basics/logic_operations.py | logic_operations.py | py | 5,198 | python | ru | code | 3 | github-code | 90 |
1633722825 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from downscale.eval.evaluation import Evaluation
class EvaluationFromArrayXr(Evaluation):
def __init__(self, v, array_xr=None, prm={"verbose": True}):
super().__init__(v, prm=prm)
if array_xr is not None:
array_x... | louisletoumelin/wind_downscaling_cnn | downscale_/downscale/eval/eval_array_xr.py | eval_array_xr.py | py | 10,099 | python | en | code | 1 | github-code | 90 |
72477572456 | #!/usr/bin/env python3
import time
def imprime_nome(nome, sobrenome="Sabugosa"):
# escopo local {nome: ..., sobrenome: ..}
print(f"Seu nome é {nome} {sobrenome}")
imprime_nome("Daniel", "Volponi")
imprime_nome("Linus", "Torvalds")
imprime_nome("Linus")
def conecta(host, timeout=10):
print(f"Conectando ... | danielvolponi/python-base | valores_default.py | valores_default.py | py | 469 | python | pt | code | 0 | github-code | 90 |
18267122709 | M = 10**9 + 7
n,a,b = map(int, input().split())
def modinv(n):
return pow(n, M-2, M)
def comb(n, r):
num = denom = 1
for i in range(1,r+1):
num = (num*(n+1-i))%M
denom = (denom*i)%M
return num * modinv(denom) % M
print((pow(2, n, M) - comb(n, a) - comb(n, b) - 1) % M) | Aasthaengg/IBMdataset | Python_codes/p02768/s423059519.py | s423059519.py | py | 303 | python | en | code | 0 | github-code | 90 |
8462317340 | import warnings
from typing import Dict, \
Optional, \
Any
from keras import backend as K
from keras.layers import Dense, \
Input, \
Lambda
from keras.models import Model
from transformer.model.decoder import Decoder
from transformer.model.embedder import Embedder
from transformer.model.encoder import... | ViktorStagge/transformer | transformer/model/model.py | model.py | py | 8,922 | python | en | code | 0 | github-code | 90 |
19328798303 | # define Python user-defined exceptions
class Error(Exception):
"""Base class for other exceptions"""
def __init__(self):
print("Izuzetak osnovne klase")
class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
def __init__(self):
print("Izuzetak klase ValueToo... | SavkeSD/python-it-academy | Python-OOP/izuzeci-Klase.py | izuzeci-Klase.py | py | 1,316 | python | en | code | 0 | github-code | 90 |
15482300205 |
from metawards import OutputFiles
import pytest
import os
script_dir = os.path.dirname(__file__)
def test_openfiles(prompt=None):
outdir = os.path.join(script_dir, "test_openfiles_output")
if os.path.exists(outdir):
OutputFiles.remove(outdir, prompt=prompt)
of = OutputFiles(outdir)
asser... | chryswoods/MetaWards | tests/test_outputfiles.py | test_outputfiles.py | py | 1,537 | python | en | code | null | github-code | 90 |
19148955817 | '''Importando parâmetros da orm'''
from sqlalchemy import Column, Integer, String, ForeignKey, Boolean, Enum, DateTime
from sqlalchemy.orm import relationship
from datetime import datetime
from ..database import Base
class Matricula(Base):
__tablename__ = "matricula"
idTurma: int = Column("idTurma", Foreign... | fga-eps-mds/2022.2-Amis-Service | src/model/model.py | model.py | py | 4,136 | python | pt | code | 2 | github-code | 90 |
42325199498 | import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from dataset_sisfall import SiSFallDataset
from protopnet import AProtoPNet
from sklearn.metrics import confusion_matrix
import seaborn as sn
import pandas as pd
import matplotlib.pyplot as plt
def test(model, test_loader, d... | ilovesea/ProtoPLSTM | plt_cm.py | plt_cm.py | py | 2,297 | python | en | code | 0 | github-code | 90 |
34908170019 | # -*- coding: utf-8 -*-
import pymysql
class DBConn:
def __init__(self):
while(True):
quit = input('1.Logowanie, 2.Wyjście ')
if(quit == '2'):
break
self.connString()
perm = self.login()
if(perm.upper() == 'A'):
... | lmirkowski/Projekt-KINO-interfejs-w-Python | projekt.py | projekt.py | py | 9,882 | python | pl | code | 0 | github-code | 90 |
7318879041 | import pygame, math, os
import content.modules.Util as Util
class Background(pygame.surface.Surface):
def __init__(self, canvas, x, y):
super().__init__((x, y))
self.fill((0, 0, 0))
self.image = pygame.image.load(os.path.join(Util.rootDirectory, "content/assets/sprites/grass.png"))
... | HooferDevelops/Golf | content/objects/Background.py | Background.py | py | 620 | python | en | code | 0 | github-code | 90 |
34963740196 | from datetime import timedelta, time
from time import sleep
import responses
from django.utils import timezone
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase
from kw_webapp import constants
from kw_webapp.models import Announcement, Vocabulary
from kw_webapp.tasks import get_vo... | Kaniwani/kw-backend | kw_webapp/tests/serializers/test_profile_api.py | test_profile_api.py | py | 16,051 | python | en | code | 71 | github-code | 90 |
18368382379 | N = int(input())
A = [int(input()) for _ in range(N)]
sort_A = sorted(A, reverse=True)
max_value = sort_A[0]
second_value = sort_A[1]
ans = []
for a in A:
if a < max_value:
ans.append(max_value)
elif a == max_value:
ans.append(second_value)
print(*ans, sep='\n')
| Aasthaengg/IBMdataset | Python_codes/p02971/s861272658.py | s861272658.py | py | 291 | 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.