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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
18258641139 | #!/usr/bin/env python3
def main():
A, B = map(int, input().split())
for price in [str(x) for x in range(10, 1001)]:
a = str(int(price) * 8)
a = int(a[:-2]) if len(a) >= 3 else 0
b = int(price[:-1]) if len(price) >= 2 else 0
if a == A and b == B and a <= 100 and b <= 100:
... | Aasthaengg/IBMdataset | Python_codes/p02755/s929521956.py | s929521956.py | py | 411 | python | en | code | 0 | github-code | 90 |
27729972425 | import h5py
import numpy as np
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers.normalization import BatchNormalization
from keras... | lchauhan8642/Plant-Disease-classification-System | Alexnet/Alexnet_Testing.py | Alexnet_Testing.py | py | 5,378 | python | en | code | 3 | github-code | 90 |
71749268457 | import numpy as np
import pandas as pd
def compute_cos_similarities(vector : np.ndarray, vectors : np.ndarray, vector_norm : float = None,
vectors_norms : np.ndarray = None):
"""Compute the cosine similarities between the given vectors and each one of the column vectors in the given ... | michele98/text_mining_project | utils/similarities.py | similarities.py | py | 5,010 | python | en | code | 0 | github-code | 90 |
33659681997 | #
# @lc app=leetcode.cn id=46 lang=python3
#
# [46] 全排列
#
# https://leetcode-cn.com/problems/permutations/description/
#
# algorithms
# Medium (72.14%)
# Likes: 424
# Dislikes: 0
# Total Accepted: 53.7K
# Total Submissions: 74.2K
# Testcase Example: '[1,2,3]'
#
# 给定一个没有重复数字的序列,返回其所有可能的全排列。
#
# 示例:
#
# 输入: [1,2... | algorithm004-04/algorithm004-04 | Week 02/id_624/LeetCode_46_624.py | LeetCode_46_624.py | py | 955 | python | en | code | 66 | github-code | 90 |
37905265803 | import numpy as np
"""
DO NOT CHANGE THIS VALUE UNLESS THE RADIUS OF THE EARTH CHANGES !!!
"""
"""
Conversion Values
"""
RADIUS_OF_EARTH = 6371.0088 ##In kilometers; Change this to miles if you don't believe in metric system
KMS_TO_METERS = 1000.0
METERS_TO_KILOMETERS = 0.001
MILES_TO_KILOMETERS = 1.60934
KILOMETERS_... | jkAtGitHub/Standard-Deviational-Ellipse | geomutils.py | geomutils.py | py | 2,125 | python | en | code | 0 | github-code | 90 |
41364070570 | def top_3_words(text):
freq = {}
word = ''
for c in text:
if c == "'" and len(word) < 2:
word = ''
continue
if c != ' ' and c not in "!@#$%^&*()_+=[]{};,./:<>?|":
word += c.lower()
if c == ' ' and word != '':
if word in freq:
... | SalvadorGuido/Python | CodeWars/FrequentWords.py | FrequentWords.py | py | 1,562 | python | en | code | 0 | github-code | 90 |
38617688094 | from datetime import datetime
from sqlalchemy import Column, DateTime, Float, ForeignKey, Integer, String
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import relationship
from .base import Base
from .pair import Pair
class ScoutHistory(Base):
__tablename__ = "scout_history"
id = Co... | edeng23/binance-trade-bot | binance_trade_bot/models/scout_history.py | scout_history.py | py | 1,473 | python | en | code | 7,357 | github-code | 90 |
14189206363 | class Solution(object):
# 09-03-2023 Version
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
slow = head
fast = head
while slow and fast:
if slow.next and fast.next and fast.next.next:
slow = slow.nex... | Minho16/leetcode | Daily_problems/MAR23/2023-03-09/LinkedListCycleII_Samu.py | LinkedListCycleII_Samu.py | py | 1,579 | python | en | code | 0 | github-code | 90 |
3704019540 | """
Implements a haversine loss function for use in
TensorFlow models
"""
import tensorflow as tf
import numpy as np
import unittest
def haversine_loss(y_true, y_pred, R=3443.92):
"""
Returns the mean squared haversine distance
between arrays consisting of lattitudes and
longitudes.
Args:
... | gregtozzi/deep_learning_celnav | inference/haversine.py | haversine.py | py | 3,150 | python | en | code | 6 | github-code | 90 |
18483702679 | from collections import deque
N = int(input())
A = [int(input()) for _ in range(N)]
A.sort()
X = deque(A.copy())
B = deque([X.pop()])
flg = True
while X:
if flg:
B.append(X.popleft())
if X:
B.appendleft(X.popleft())
else:
B.append(X.pop())
if X:
B.appe... | Aasthaengg/IBMdataset | Python_codes/p03229/s760591924.py | s760591924.py | py | 717 | python | en | code | 0 | github-code | 90 |
72462977256 | from flask import Flask
from flask import render_template
import boto
app = Flask(__name__)
app.config.from_pyfile('settings.cfg')
@app.template_filter()
def yesno(value, yes, no):
if value:
return yes
return no
@app.route('/')
def elb_status():
conn = boto.connect_elb(
aws_access_key_id=app.config['ACCESS_KEY... | alexluke/AWS-load-balancer-status | monitor.py | monitor.py | py | 1,462 | python | en | code | 0 | github-code | 90 |
32926554622 | from Rscript.RscriptClass import Rscript
MSMS = {}
inFile = open('HeLa-Predict-pep.transcript')
for line in inFile:
line = line.strip()
fields = line.split('\t')
MSMS[fields[0]]=int(fields[1])
inFile.close()
RNASEQ = {}
inFile = open('ERR0498-04-05.unmapped.unique.total.fasta.blated.filtered.seq1.splicing.... | wanghuanwei-gd/SIBS | RNAseqMSMS/7-tandem-sv/predict-protein/1-venn.py | 1-venn.py | py | 1,347 | python | en | code | 0 | github-code | 90 |
26358518811 | """AUTOR:Adrián Agudo Bruno
ENUNCIADO:Escribe un programa que pida una frase, y pase la frase como parámetro a una función que debe eliminar los espacios en blanco (compactar la frase). El programa principal imprimirá por pantalla el resultado final.
"""
def rima(a,b):
if (a[len(a)-1]==b[len(b)-1]):
... | aagudobruno/python | P7/P7E9.py | P7E9.py | py | 717 | python | es | code | 0 | github-code | 90 |
18302071189 | N=int(input())
a=list(map(int,input().split()))
ans = 0
res =1
for i in range(N):
if res != a[i]:
ans += 1
elif res == a[i]:
res += 1
if ans ==N:
print(-1)
else:
print(ans) | Aasthaengg/IBMdataset | Python_codes/p02832/s721551397.py | s721551397.py | py | 194 | python | fr | code | 0 | github-code | 90 |
35933076236 | import cv2
import random
import numpy as np
import matplotlib
matplotlib.use("TkAgg")
import os
from matplotlib import pyplot as plt
grayscale_max = 255
dirsave="./Results/"
dirGT0="./GT0"
dirGT1="./GT1"
dirIP0="./IM0"
dirIP1="./IM1"
def load_image_IP0():
files = os.listdir(dirIP0)
listimgl=[]
#l... | Himani2000/celestini_task | Q3-Image-Process/Image_Process.py | Image_Process.py | py | 6,873 | python | en | code | 0 | github-code | 90 |
38987918173 | import torch
x = torch.Tensor([5, 3])
y = torch.Tensor([2, 1])
print(x * y)
x = torch.zeros([2, 5])
print(x)
x.shape
torch.Size([2, 5])
y = torch.rand([2, 5])
print(y)
#flatten tensor before passing it into neural network
y = y.view([1, 10])
print(y) | BeardedSultan/PytorchIntro | main.py | main.py | py | 257 | python | en | code | 0 | github-code | 90 |
72318331498 | import os
import pytest
pytestmark = [pytest.mark.girder, pytest.mark.girder_client]
try:
from pytest_girder.web_client import runWebClientTest
except ImportError:
# Make it easier to test without girder
pass
@pytest.mark.singular()
@pytest.mark.usefixtures('unbindLargeImage')
@pytest.mark.plugin('larg... | girder/large_image | girder/test_girder/test_web_client.py | test_web_client.py | py | 1,472 | python | en | code | 162 | github-code | 90 |
7714755583 | import requests
from parsel import Selector
from app.constants import PAGE_TARGET
from app.helpers import (
set_new_prices_list,
set_new_units_list,
set_new_values_list_target_1,
set_new_values_list_target_2,
)
def crawler(number_page_target):
url = PAGE_TARGET[number_page_target]
text = requ... | rodrigomaria/crawler | app/crawler.py | crawler.py | py | 3,854 | python | en | code | 0 | github-code | 90 |
21403119252 | import json
import random
random.seed(1)
number_string =input('input the min speed:')
n = float(number_string)
number_string =input('input the max speed:')
m = float(number_string)
with open('pedestrian.json', encoding='utf-8') as a:
data = json.load(a)
x = data['dynamicElements']
for y in range(0,len(x)):... | lisazhanglii/The-Behavior-aware-Methodology-for-Crowd-Management_Vadere | Change_All_Speed.py | Change_All_Speed.py | py | 502 | python | en | code | 1 | github-code | 90 |
24878149943 | from vehicle import vehicle
from car import car
from supercar import supercar
class mechanicgarage():
def __init__(self,ownername, avgcost, amount):
self.__ownername = ownername
self.agcost = avgcost
self.amount = 0
# This method changes color of vehicle and adds cost
def changeColor(se... | sanchezjairo/Car-garage-OOP | Garage.py | Garage.py | py | 1,431 | python | en | code | 0 | github-code | 90 |
17747309645 | from django.shortcuts import render ,redirect
from accounts.models import Patient_Details,Doctor
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import History,DoctorSchedule,Appointment
from datetime import date
# Create your views here.
def doctor_home_view... | Zaman-Shah/Mainproject | doctor/views.py | views.py | py | 5,484 | python | en | code | 0 | github-code | 90 |
23930524965 | from setuptools import setup, find_packages
import os
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name = 'isimage'
, version = '0.1.2'
, packages = find_packages()
, entry_points = {'console_scripts':['analyse_image = isimage.analyse_image:main'
... | ilyapatrushev/isimage | setup.py | setup.py | py | 1,132 | python | en | code | 0 | github-code | 90 |
12084273302 | import itertools
LIMIT = 10**999
fibs = [1, 1]
for i in itertools.count():
next_fib = fibs[-1] + fibs[-2]
fibs.append(next_fib)
if next_fib >= LIMIT:
print(i + 3)
break
| mishajw/projecteuler | src/p025_1000digit_fib.py | p025_1000digit_fib.py | py | 201 | python | en | code | 0 | github-code | 90 |
18177252499 | N = int(input())
A = list(map(int,input().split()))
money=1000
best = money
pos = 1
kabu = 0
#初動 買うか買わないか
if A[0]<=A[1]:
kabu = money//A[0]
money -= kabu*A[0]
pos=0
else:
pos=1
#二回目以降 買うか売るか保留か
for i in range(1,N):
if pos==0:#売り
if A[i-1]>=A[i]:
money+=kabu*A[i-1]
... | Aasthaengg/IBMdataset | Python_codes/p02603/s050789004.py | s050789004.py | py | 605 | python | en | code | 0 | github-code | 90 |
12124862707 | from __future__ import division, print_function, absolute_import
import CoolProp as CP
from CoolProp.CoolProp import PropsSI
from ACHP.MicroChannelCondenser import MicroCondenserClass
from ACHP.MicroFinCorrelations import MicroFinInputs
from ACHP.convert_units import in2m, mm2m, cfm2cms, F2K, kPa2Pa, C2K
Fins=MicroFin... | CenterHighPerformanceBuildingsPurdue/ACHP | ComponentTests/MC_Cond_validation.py | MC_Cond_validation.py | py | 2,916 | python | en | code | 48 | github-code | 90 |
42008473513 | __revision__ = "src/engine/SCons/Tool/jar.py 5134 2010/08/16 23:02:40 bdeegan"
import SCons.Subst
import SCons.Util
def jarSources(target, source, env, for_signature):
"""Only include sources that are not a manifest file."""
try:
env['JARCHDIR']
except KeyError:
jarchdir_set = False
el... | cloudant/bigcouch | couchjs/scons/scons-local-2.0.1/SCons/Tool/jar.py | jar.py | py | 2,502 | python | en | code | 570 | github-code | 90 |
17679457158 | from __future__ import annotations
from typing import TYPE_CHECKING, Generic, TypeVar
from sqlalchemy import tuple_
from sqlalchemy.orm import Session
from telegram import error, ChatMember
from .models import GivenInevitableTitle
from .models import GivenShuffledTitle
from .models import InevitableTitle
from .model... | cl0ne/cryptopotato-bot | devpotato_bot/commands/daily_titles/assign_titles.py | assign_titles.py | py | 6,189 | python | en | code | 2 | github-code | 90 |
13003083228 |
# D4
# 기존 원소들에 새로운 원소를 더한 값들을 추가해주는 방식 + set활용
T = int(input())
for tc in range(1, T+1):
N = int(input())
score = list(map(int, input().split()))
s = len(score)
# 기존 값들에 새로운 값을 각각 더해서 추가하느데 중복을 제거
ans = {0}
for i in range(s):
temp = set()
for j in ans: # ans에 넣으면 길이가 변하니... | hyeinkim1305/Algorithm | SWEA/D4/SWEA_3752_가능한시험점수.py | SWEA_3752_가능한시험점수.py | py | 1,122 | python | ko | code | 0 | github-code | 90 |
35310596867 | import requests
from bs4 import BeautifulSoup
import re
url = 'http://python123.io/ws/demo.html'
r = requests.get(url)
demo = r.text
soup = BeautifulSoup(demo,'html.parser')
print (soup.prettify())
tag = soup.title.parent
for parent in soup.a.parents:
if parent is None:
print(parent)
else:
print... | Ziliang-Luo/crawler | BeautifulSoup.py | BeautifulSoup.py | py | 599 | python | en | code | 0 | github-code | 90 |
73618541738 | from fastapi import APIRouter, Cookie, Depends, Request, Response, status
from fastapi.security import OAuth2PasswordRequestForm
from backend import models
from backend.api.docs import auth as auth_responses
from backend.metrics import auth as auth_metrics
from backend.services.auth import AuthService
from backend.set... | StanislavBeskaev/Chat-FastAPI-React | backend/api/auth.py | auth.py | py | 3,578 | python | en | code | 0 | github-code | 90 |
18211853969 | import sys
input = sys.stdin.readline
from collections import defaultdict, deque
(n, m), g = map(int, input().split()), defaultdict(list)
for i in range(m): a, b = map(int, input().split()); g[a].append(b); g[b].append(a)
s, q = [0, 0] + [-1 for i in range(1, n)], deque([1])
for i in range(2, n + 1):
x = q.popleft... | Aasthaengg/IBMdataset | Python_codes/p02678/s914300599.py | s914300599.py | py | 484 | python | en | code | 0 | github-code | 90 |
27693237784 | from basic.collection.tree import Node
from basic.collection.stack import Stack
def postorder_recursive(head, results):
if not head:
return
postorder_recursive(head.left, results)
postorder_recursive(head.right, results)
results.append(head.val)
return
def postorder_stack(head, results... | xyzacademic/LeetCode | basic/BinaryTree/postorder_traversal.py | postorder_traversal.py | py | 2,481 | python | en | code | 0 | github-code | 90 |
16534897125 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import datetime
from django.utils.timezone import utc
import django_extensions.db.fields
class Migration(migrations.Migration):
dependencies = [
('django_outlook', '0001_initial'),
]
operati... | weijia/django-outlook | django_outlook/migrations/0002_auto_20180628_1240.py | 0002_auto_20180628_1240.py | py | 1,319 | python | en | code | 0 | github-code | 90 |
9116641165 | import logging
import requests
import pandas as pd
import numpy as np
import json
from datetime import datetime, timedelta
from requests.exceptions import RequestException
class BinanceAPI:
def __init__(self):
# self.base_url = "https://api.binance.com/api/v3"
self.base_url = "https://api.binance.u... | parity-asia/hackathon-2023-summer | projects/05-chatdatainsight/src/backend/services/binance.py | binance.py | py | 3,960 | python | en | code | 14 | github-code | 90 |
20352749495 | import pickle
from datetime import date
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
import repository.data_repository as data_repository
with open('helpers\\encoders\\category_encoder.pkl', 'rb') as file:
category_e... | viktor-meglenovski/diplomska_ml | backend/service/training_service.py | training_service.py | py | 10,134 | python | en | code | 0 | github-code | 90 |
27955539533 | from tkinter import *
from tkinter import messagebox
import mysql.connector
from pacotes import criarBanco, telaCompras
from tkinter import ttk
# --------------------------------------------- cores --------------------------------------------
cor0 = '#121010' # Preto
cor1 = '#feffff' # branco
cor2 = '#3fb5a3' # ve... | Eduardo-J-S/Projeto_IP_20221 | main.py | main.py | py | 16,937 | python | pt | code | 1 | github-code | 90 |
13588922190 | from django.urls import path
from . import views
app_name = 'students'
urlpatterns = [
path('', views.index, name='index'), # GET /students/
path('new/', views.new, name='new'), # GET,POST /students/new/
# path('create/', views.create, name='create'), # POST /students/create/ (x)
path('<int:pk>/', vie... | 4th5-deep-a/web | django/crud_review/students/urls.py | urls.py | py | 1,728 | python | en | code | 4 | github-code | 90 |
13394981258 | import json
from typing import List, Union
import pandas as pd
from fastapi import FastAPI
from pydantic import BaseModel
from data import get_list_summary, get_summary
app = FastAPI()
@app.get("/trip/{month}")
def get_summary_srv(month: str, expire: int = 15 * 60):
df = get_summary(month, expr=expire)
re... | husnusensoy/python-workshop | week4/session2/data-service.py | data-service.py | py | 1,149 | python | en | code | 2 | github-code | 90 |
20671197229 | # -*- coding:utf-8 -*-
class Solution:
def VerifySquenceOfBST(self, sequence):
# write code here
if len(sequence) == 0:
return False
return self.check(sequence,0,len(sequence)-1)
def check(self,arr,start,end):
if start>=end:
return True
root = arr[... | shenweichen/coding_interviews | 33.二叉搜索树的后序遍历序列/33.二叉搜索树的后序遍历序列.py | 33.二叉搜索树的后序遍历序列.py | py | 596 | python | en | code | 446 | github-code | 90 |
3393423918 | import networkx as nx
import tweepy
import matplotlib.pyplot as plt
import os
consumer_key = "2mwk5WNYkNcWko6MhmRrivazE"
consumer_secret = "P8NEpxECYgKa5YAWr5O3F6TGFWYeJY78EBd7ZhrEX2PcUkl643"
access_token = "2403140949-iKPTtRJJlsgRT6AV2tWeMBid4lFGV7DxNADI14K"
access_token_secret = "4OZlKin7OekWX7Lx00GDNhYuHT... | arnaucampru/Social-Network-Analysis | pràctica.py | pràctica.py | py | 7,239 | python | en | code | 1 | github-code | 90 |
320125814 | import csv
from net.initialization.header.metrics import metrics_header
from net.utility.msg.msg_metrics_complete import msg_metrics_complete
from net.metrics.utility.my_notation import scientific_notation
def metrics_train_resume_csv(metrics_path: str,
metrics: dict):
"""
Resume... | cirorusso2910/GravityNet | net/resume/metrics_train_resume.py | metrics_train_resume.py | py | 1,704 | python | en | code | 7 | github-code | 90 |
45824483389 | import re
from textwrap import fill
def protein_char_class(alignment=False, nl=True, allow=None, extra_chars=False, stops=False):
'''Returns the character class string for the sequence described,
i.e. '[AC-IK-NP-TVWY\\n]'.
Parameters:
alignment (default=False) Allow '-' character
nl (default=True) All... | berkeleyphylogenomics/BPG_utilities | pfacts003/utils/format_patterns.py | format_patterns.py | py | 8,698 | python | en | code | 1 | github-code | 90 |
28142618430 | import pygame
import sys
import random
from pygame.math import Vector2
class PADDLE:
def __init__(self, x, y, width, height, color, speed):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color
self.speed = speed
def draw_paddle(se... | marvinraj/Pong-Game | backup.py | backup.py | py | 2,805 | python | en | code | 0 | github-code | 90 |
13307184959 | #!/usr/bin/env python3
from bs4 import BeautifulSoup
import json
TWITTER_PREFIX = 'https://twitter.com/'
# Even more code duplication.
# I'm not sure whether this still is a good idea.
def get_details_bundestag(old_entry, soup):
assert old_entry['src'] == 'bundestag'
entry = dict()
entry['src'] = old_e... | Schwenger/House-Of-Tweets | tools/PhotoMiner/parse_each.py | parse_each.py | py | 13,967 | python | en | code | 0 | github-code | 90 |
4679114797 | import os
import copy
import time
import math
import datetime
import warnings
import requests
import rasterio
# from rasterio.merge import merge
from rasterio import Affine, windows
def file_exists(path):
return os.path.isfile(path)
def get_current_timestamp(format_str=None):
if format_str is None:
f... | aiddata/geo-datasets | global_forest_change/utility.py | utility.py | py | 6,757 | python | en | code | 19 | github-code | 90 |
42598331264 | import torch
import torch.nn as nn
import torch.nn.functional as F
class MultiheadAttentionRelative(nn.MultiheadAttention):
"""
Multihead attention with relative positional encoding
"""
def __init__(self, embed_dim, num_heads):
super(MultiheadAttentionRelative, self).__init__(embed_dim, num_h... | rie1010/stereo-transformer | module/attention.py | attention.py | py | 6,276 | python | en | code | null | github-code | 90 |
18343881859 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 9 16:47:54 2020
@author: liang
"""
N = int(input())
B = list(map(int,input().split()))
ans = B[0]
for i in range(1,N-1):
ans += min(B[i-1], B[i])
ans += B[N-2]
print(ans) | Aasthaengg/IBMdataset | Python_codes/p02917/s567760247.py | s567760247.py | py | 225 | python | en | code | 0 | github-code | 90 |
4459083710 | import cv2
import numpy as np
shorten=0.5
cap = cv2.VideoCapture(0)
ret, a = cap.read()
# a = cv2.imread("rgb.jpg",-1)
a=cv2.resize(a,(int(a.shape[1]*shorten),int(a.shape[0]*shorten)))
# scale1=0.7
# scale2=0.5
# x=int(scale1*a.shape[1])
# y=int(scale2*a.shape[0])
# print(a.shape[0],a.shape[1])
# print(x,y... | anamaymb/Myfiles2 | Python/Colourdet.py | Colourdet.py | py | 1,966 | python | en | code | 0 | github-code | 90 |
27497876454 | from torch import nn
from torch.nn import functional as F
from .transformer import Transformer
from .length_predictor import LengthPredictor
class TransformerNonAutoRegressive(Transformer):
def __init__(self, ntoken, d_model, nhead=8, num_encoder_layers=6, num_decoder_layers=6,
dim_fe... | liu-hz18/Non-Autoregressive-Neural-Dialogue-Generation | nag/modules/transformer_nonautoregressive.py | transformer_nonautoregressive.py | py | 3,583 | python | en | code | 1 | github-code | 90 |
23321616416 | #haunted house
import pygame, sys
from pygame.locals import *
import random
from getworkingpath import *
#construct the sound filename
fileSound1=getworkingpath()+"/hauntedhouse.wav"
fileSound2=getworkingpath()+"/fakenews1.wav"
#construct the picture filename
filePicture=getworkingpath()+"/trump.png"
#Frames pr sec... | DeepBlue4222/minecraft_catr | house2.py | house2.py | py | 3,468 | python | en | code | 0 | github-code | 90 |
16571392437 | """
布赖恩·克尼根算法
通过减一,异或,消除右侧的1
"""
class Solution:
def hammingDistance(self, x, y):
xor = x ^ y
distance = 0
# 直接越过0位,操作最右侧的1!!!!!!简直神一样的操作
while xor:
distance += 1
# remove the rightmost bit of '1'
xor = xor & (xor - 1)
return dist... | superggn/myleetcode | else/461-hamming-distance-3.py | 461-hamming-distance-3.py | py | 484 | python | zh | code | 0 | github-code | 90 |
39975479195 | print('-' * 40)
print(f'{"LOJA SUPER BARATÃO":^40}')
print('-' * 40)
total = greater_1000 = cheaper = 0
cheaper_name = ''
while True:
produto = str(input('Nome do Produto: ')).strip().title()
price = float(input('Preço: R$'))
total += price
if price > 1000:
greater_1000 += 1
if cheaper == 0 ... | thiagokawauchi/curso_em_video_python | ex070.py | ex070.py | py | 792 | python | pt | code | 0 | github-code | 90 |
11306833706 | # Set a cronjob to make it work.
from django.utils import timezone
from django.core.management.base import BaseCommand
from ...models import Planning
from ...tasks import send_campaign
class Command(BaseCommand):
help = 'Checks if a dispatch was planned and in case launches it'
def handle(self, *args, **op... | otto-torino/tazebao | tazebao/newsletter/management/commands/dispatch_planned_campaigns.py | dispatch_planned_campaigns.py | py | 615 | python | en | code | 5 | github-code | 90 |
33661672597 | # 20191117
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
MAX = float('inf')
dp = [0] + [MAX] * amount
for i in range(1, amount + 1):
dp[i] = min([dp[i - c] if i - c >= 0 else MAX for c in coins]) + 1
return [dp[amount], -1][dp[amount] == M... | algorithm004-04/algorithm004-04 | Week 05/id_069/LeetCode-322-069.py | LeetCode-322-069.py | py | 323 | python | en | code | 66 | github-code | 90 |
42699222480 | """Django tests for the jugemaj app."""
from django.contrib.auth.models import User
from django.test import TestCase
from django.urls import reverse
from .models import Candidate, Election, NamedCandidate, Vote
class JugeMajTests(TestCase):
"""Mais class for the tests."""
def setUp(self):
"""Create ... | nim65s/django-jugemaj | jugemaj/tests.py | tests.py | py | 4,329 | python | en | code | 0 | github-code | 90 |
37079798953 | fecha = input("Ingrese la fecha en formato 'dia de la semana, numero del dia y numero del mes en formato dia, DD/MM: ")
fecha = fecha.title()
dia_semanas = fecha[0:fecha.find(",")]
dia_numero = int(fecha[fecha.find(" ")+1:fecha.find("/")])
dia_mes = int(fecha[fecha.find("/")+1:])
if (dia_semanas == "Lunes") or (dia_s... | Vale-source/Programacion-1 | ejercicios_clase_condicionales.py | ejercicios_clase_condicionales.py | py | 1,793 | python | es | code | 0 | github-code | 90 |
44399098038 | ''' Read input from STDIN. Print your output to STDOUT '''
#Use input() to read input from STDIN and use print to write your output to STDOUT
def main():
T =int(input())
for i in range(T):
N = int(input())
grev = list(map(int,input().split()))
opp = list(map(int,input().split()))
... | pratikroy311/DS-and-Algo-codes | greedy/beybladeChampionship.py | beybladeChampionship.py | py | 631 | python | en | code | 1 | github-code | 90 |
18397870159 | import heapq
n,k = map(int, input().split())
v = list(map(int, input().split()))
ans = 0
for left in range(n+1):
for right in range(left, n+1):
have = []
heapq.heapify(have)
i = 0
while i < left:
heapq.heappush(have, v[i])
i += 1
cost = left + (n - rig... | Aasthaengg/IBMdataset | Python_codes/p03032/s422249671.py | s422249671.py | py | 787 | python | en | code | 0 | github-code | 90 |
32019521748 | import math
EARTH_RADIUS=6371000
class BikeParkNode():
def __init__(self,address,location,street_name,racks,spaces,placement,mo_installed, yr_installed,Lat,Long):
self.location=location
self.street_name=street_name
self.racks=racks
self.spaces=spaces
self.yr_installed=yr_ins... | uzonwike/BikeParkingSF | BikeParkNode.py | BikeParkNode.py | py | 1,382 | python | en | code | 0 | github-code | 90 |
73820395177 | class Solution(object):
def reachableNodes(self, edges, M, N):
graph = collections.defaultdict(dict)
for node1, node2, nums in edges:
graph[node1][node2] = nums
graph[node2][node1] = nums
heap = [(0, 0)]
dist = {0: 0}
used = {}
result = 0
... | HarrrrryLi/LeetCode | 882. Reachable Nodes In Subdivided Graph/Python 3/solution.py | solution.py | py | 952 | python | en | code | 0 | github-code | 90 |
30255352421 | """
For splitting input into list separated by \n and \t's
"""
class Split_Entry:
def split(entry, func=0):
def remove_dups(xlist):
xlist = list(dict.fromkeys(xlist)) # Remove duplicates due to Dicts only able to have 1 key per item
if '' in xlist:
xlist.remov... | scionsamurai/Pandas-tkinter-excel | file_pal/_funcs/SplitEntry.py | SplitEntry.py | py | 1,822 | python | en | code | 3 | github-code | 90 |
5828099878 | import json
import logging
import requests
import time
from get_token import get_token
from log_setup import Logging
from program_data import PDApi
# =====================================================================
#
# NetApp / SolidFire
# CPE
# mnode support utility
#
# ==========================================... | aakittel/mnode-support-util | storage_healthcheck.py | storage_healthcheck.py | py | 3,566 | python | en | code | 0 | github-code | 90 |
43812651218 | from enum import Enum
class Variable(Enum):
PROGRAMA = "PROGRAMA"
TEMPO_EXECUCAO = "TEMPO"
CUSTOS = "CUSTOS"
@classmethod
def factory(cls, val: str) -> "Variable":
for v in cls:
if v.value == val:
return v
return cls.TEMPO_EXECUCAO
def __repr__(sel... | rjmalves/sintetizador-dessem | sintetizador/model/execution/variable.py | variable.py | py | 357 | python | en | code | 2 | github-code | 90 |
73501536937 | from collections import deque
def solution(m, n, puddles):
dp = [[0 for _ in range(m + 1)] for _ in range(n + 1)]
board = [[0] * (m + 2) for _ in range(n + 2)]
for puddle in puddles:
x, y = puddle
board[y][x] = -1
dp[1][1] = 1
for y in range(1, n + 1):
for x in range(1, m + 1):
if board[y][x] != 0 :
... | Err0rCode7/algorithm | for_retry/wait/programmers/42898.py | 42898.py | py | 1,514 | python | en | code | 0 | github-code | 90 |
18464283569 | #input
import sys
sys.setrecursionlimit(10**7)
N, M = map(int, input().split())
z = [[] for _ in range(N)]
for _ in range(M):
x, y = map(int, input().split())
z[x-1].append(y-1)
#output
#便宜的にすべての点を-1しておく。
#dp[i]を頂点iから始まるpathで最長の長さとする。
#dp[i] = max(dp[v]+1)(vは頂点iから到達できる任意の頂点)
visited = [False] * N
memo = [0] *... | Aasthaengg/IBMdataset | Python_codes/p03166/s720741022.py | s720741022.py | py | 671 | python | ja | code | 0 | github-code | 90 |
12195104069 | from __future__ import absolute_import, division,\
print_function, unicode_literals
import unittest
class CircularQueue(object):
def __init__(self, n):
self.size = n+1
self.data = [0, ]*self.size
self.head = 0
self.tail = 0
def empty(self):
return self.head == sel... | shell909090/data_struct_py | cqueue.py | cqueue.py | py | 1,760 | python | en | code | 0 | github-code | 90 |
71726187498 | from Bio import SeqIO
def read_fasta_dict(fasta: str) -> dict:
"""
Read an input FASTA file and return a dictionary of sequences
Args:
fasta (str): The path to the FASTA file
Returns:
dict: A dictionary of sequences with the sequence name as the key
"""
seqs = {}
with open... | rpetit3/steamboat-py | steamboat/utils/fasta.py | fasta.py | py | 886 | python | en | code | 1 | github-code | 90 |
69891143978 | from tkinter import *
from quiz_brain import QuizBrain
THEME_COLOR = "#375362"
class QuizInterface:
def __init__(self, quiz_brain: QuizBrain):
self.quiz_q = quiz_brain
self.score = 0
self.window = Tk()
self.window.title("Quizzler")
self.window.config(padx=20, pady=20, bg=TH... | bdya-s/Trivia-App | ui.py | ui.py | py | 2,508 | python | en | code | 0 | github-code | 90 |
70160976618 | #!/usr/bin/env python3
"""
Viewer class & window management
"""
# Python built-in modules
from itertools import cycle
# External, non built-in modules
import OpenGL.GL as GL # standard Python OpenGL wrapper
import glfw # lean window system wrapper for OpenGL
from nodeModule import *
from trackball import GLFWTrackba... | christophezei/3d-graphics-underwater-scene | src/viewer.py | viewer.py | py | 4,366 | python | en | code | 0 | github-code | 90 |
1602699062 | import os
import logging
# Initialize logging
import re
import sys
import numpy as np
FORMAT = "{levelname:<8s} {asctime} {name:>30.30s}: {message}"
formatter = logging.Formatter(FORMAT, style="{")
TFAIP_LOG_LEVEL = getattr(logging, os.environ.get("TFAIP_LOG_LEVEL", "INFO").upper())
this_logger = logging.getLogger(_... | Planet-AI-GmbH/tfaip | tfaip/util/logging.py | logging.py | py | 2,969 | python | en | code | 12 | github-code | 90 |
3997175735 | import random
def mergesort(list):
new_list = []
new_list1 = []
new_list2 = []
l = len(list)
mid = random.randint(0, l)
left_list = list[:mid]
right_list = list[mid:]
for i in range(len(left_list)):
mini = min(left_list)
new_list.append(mini)
left_list.remove(min... | prince-prakash/practice_session | pp_mergesort.py | pp_mergesort.py | py | 700 | python | en | code | 0 | github-code | 90 |
17126925777 | # -*- coding: utf-8 -*-
# @author: yangyd
# @file: app_keycode.py
# @time: 2019/9/18 19:11
class KeyCode:
ENTER = 66
HOME = 3
BACK = 4
CALL = 5
POWER = 26
VOLUME_UP = 24
VOLUME_DOWN = 25
| seceast/PyProjects | APP_Auto_Test/study_code/app_keycode.py | app_keycode.py | py | 217 | python | en | code | 0 | github-code | 90 |
8309229598 | from rest_framework.views import APIView
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework import status
from faker import Faker
class PalindromeChecker(APIView, AllowAny):
"""Check given string is palindrome or not
"""
def post(self, ... | neilravi7/palindrome | palindrome_api/views.py | views.py | py | 1,209 | python | en | code | 1 | github-code | 90 |
2546671091 | import subprocess
path = '../java'
cmd = "java -cp " + path + " Main"
times = 100
s = 0
for i in range(times):
s += float(subprocess.check_output(cmd_paillier, shell=True).strip())
print(s/times)
| guyu96/encrypted-domain-DST | py/benchmark.py | benchmark.py | py | 214 | python | en | code | 1 | github-code | 90 |
22487633024 | import aiohttp
import bs4
from discord import option
from discord.ext import commands
from util.EmbedBuilder import EmbedBuilder
from util.Logging import log
async def request(word: str) -> bs4.BeautifulSoup:
url = f"https://www.merriam-webster.com/dictionary/{word}"
async with aiohttp.ClientSession() as ses... | woseek/pax | cogs/MerriamWebster.py | MerriamWebster.py | py | 5,007 | python | en | code | 0 | github-code | 90 |
18054757969 | N, A, B = map(int, input().split())
S = input()
count = 0
count2 = 0
for i in range(N):
if S[i] == "c":
print("No")
elif S[i] == "a":
if count < A+B:
print("Yes")
count += 1
else:
print("No")
elif S[i] == "b":
if count <... | Aasthaengg/IBMdataset | Python_codes/p03971/s378994864.py | s378994864.py | py | 450 | python | en | code | 0 | github-code | 90 |
74834799977 | import logging
from homeassistant import config_entries, exceptions
from homeassistant.core import callback
from . import InvalidAuth
from .const import *
_LOGGER = logging.getLogger(__name__)
@config_entries.HANDLERS.register(DOMAIN)
class StibMivbConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""STIB-... | helldog136/ha-stib-mivb | custom_components/stib_mivb/config_flow.py | config_flow.py | py | 2,762 | python | en | code | 1 | github-code | 90 |
26963193227 | frutas = {"Plátano": 1.35,
"Manzana": 0.80,
"Pera": 0.85,
"Naranja": 0.70}
fruta = input("Que fruta decea comprar? ").title()
kilos = int(input("Cuantos kilos? "))
if fruta in frutas:
print(kilos, 'kilos de', fruta, 'valen', frutas[fruta]*kilos, "$")
else:
print("Lo siento, la fruta", fruta, "no está disponibl... | alex2rive3/practicaPython | tablaFrutas.py | tablaFrutas.py | py | 326 | python | es | code | 0 | github-code | 90 |
41327381740 | #Basic Calculator Made Using Tkinter, will upgrade it into a Scientic Calculator soon, with a mode to switch.
from tkinter import *
import math
top = Tk()
top.geometry("312x370")
top.resizable(0,0)
top.title("Calculator")
def bt_click(item):
global expression
expression = expression + str(item)
i... | rishuu42/TkinterRishitt | Calculator/basiccalculator.py | basiccalculator.py | py | 4,745 | python | en | code | 0 | github-code | 90 |
74110647977 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 20 20:08:16 2019
@author: sarfaraz
"""
import numpy as np
import gdal
# Reading Header file
def hdr_read(path):
row = 0
col = 0
bands = 0
datatype = None
with open(path, "r") as f:
for l in f:
k = l.split()
... | coder-tle/GAN_work_internship | task1/read2.py | read2.py | py | 5,190 | python | en | code | 0 | github-code | 90 |
38414135944 | """
2-D array consists of a collection of elements organized into rows and columns
Elements are referenced as (r, c), indexes starting at 0
Array2D(rows, columns)
num_rows(), num_cols()
clear(value) -- Clears the array by setting each element to value
get_item(r,c), set_item(r, c, value)
"""
from Array_ADT import Arr... | Sakchhi/Algo_DS_Python | 2_Arrays/Array2d_ADT.py | Array2d_ADT.py | py | 1,450 | python | en | code | 0 | github-code | 90 |
6818786600 | # from googletrans import Translator
import pandas as pd
# translator = Translator()
# data = pd.read_excel('2semestr/1dz/3lesson/Grades.xlsx')
# a =translator.translate(data, src = 'en', dest ='uk')
# print(a.text)
# print(a.text)
products = ['Water','Milk', 'Melon', 'Apples']
price = ['15','50','200','60']
data =... | KostyaGoodAlive/python | 2semestr/1dz/3lesson/main.py | main.py | py | 395 | python | en | code | 0 | github-code | 90 |
43470354014 | from flask_app import app
from flask_app.models.dojo import Dojo
from flask import render_template,redirect,request,session,flash
#read all Route
@app.route("/")
def main_page():
dojos= Dojo.get_all_dojos()
return render_template("dojos.html", dojos=dojos)
@app.route("/dojo/create", methods=['POST'])
def crea... | AntonioSC1/Dojos_and_NInjas_core | flask_app/controllers/dojos_controller.py | dojos_controller.py | py | 620 | python | en | code | 0 | github-code | 90 |
3385316255 | # playstore-country-check - testversion - by treysis / https://github.com/treysis
# License: LGPL 2.1
#
# Checks the availability of apps in local variants of Google's PlayStore.
#
# Relies on google-play-scraper (https://github.com/JoMingyu/google-play-scraper),
# install with:
# pip install google-play-scraper
#
... | treysis/playstore-country-check | pcc-threading.py | pcc-threading.py | py | 3,658 | python | en | code | 1 | github-code | 90 |
4274961198 | ####################### DO NOT MODIFY THIS CODE ########################
menu = {
"original cupcake": 2,
"signature cupcake": 2.750,
"coffee": 1,
"tea": 0.900,
"bottled water": 0.750
}
original_flavors = ["vanilla", "chocolate", "strawberry", "caramel", "raspberry"]
original_price = 2
signature_pric... | shaafalab/FoundationsProjectOne | shop.py | shop.py | py | 3,183 | python | en | code | null | github-code | 90 |
17007914801 | from SimEnvironment import SimEnvironment
from Icarous import Icarous
from IcarousRunner import IcarousRunner
from ichelper import GetHomePosition,ReadTrafficInput
import argparse
def checkDAAType(value):
if value.upper() not in ['DAIDALUS','ACAS']:
raise argparse.ArgumentTypeError("%s is an invalid DAA op... | josuehfa/System | CoreSystem/pycarous/RunPySim.py | RunPySim.py | py | 4,544 | python | en | code | 3 | github-code | 90 |
6727840470 | import numpy as np
import pytest
import math
from sklearn.base import clone
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestRegressor
import doubleml as dml
from ._utils import draw_smpls
from ._utils_irm_manual import fit_irm, boot_irm, tune_nuisance_irm
@pytest.fixtu... | DoubleML/doubleml-for-py | doubleml/tests/test_irm_tune.py | test_irm_tune.py | py | 5,984 | python | en | code | 347 | github-code | 90 |
7349978136 | import requests
from bs4 import BeautifulSoup
import pandas as pd
from collections import OrderedDict
class UseBeautifulSoup:
def __init__(self, url):
self.url = url
def get_soup(self) -> BeautifulSoup:
response = requests.get(self.url)
soup = BeautifulSoup(response.text, 'html.parser... | Squirrel-TH/tool-box | common_web_scraping.py | common_web_scraping.py | py | 995 | python | en | code | 0 | github-code | 90 |
39268068219 | import cv2
import numpy as np
import time
import PoseModule as pm
from flask import Flask,jsonify # pip install flask # this is for deployment of the given module
app= Flask(__name__)
def main():
cap = cv2.VideoCapture(0) #for accesing the webcam
detector = pm.poseDetector()
count = 0
dir = 0 #takin... | piyushsir/OSDVirtualVelocity | bicepCurl.py | bicepCurl.py | py | 2,457 | python | en | code | 1 | github-code | 90 |
28741538773 | import itertools
def isprime(num):
if num == 0 or num == 1: return 0
for i in range(2, int((num**1/2))+1):
if num % i == 0:
return 0
return 1
A = []
def getnum(numbers, gotnum, left, index):
if left == 0:
arr = list(map("".join, list(itertools.permutations(gotnum))))
... | MountainNine/ForifAlgorithm | 완전탐색/소수찾기/박병현/main.py | main.py | py | 680 | python | en | code | 0 | github-code | 90 |
33055233468 | def p_valeur(pile):
"""
- prend en paramètre une pile pile
- renvoie le sommet de la pile
Exemple :
>>> p_valeur([2, 3, 5])
>>> 5
>>> p_valeur([])
>>> None
"""
if len(pile) != 0:
l_pile = len(pile)
return pile[l_pile-1]
else:
... | Samoxxxxx/TNSI | TD_Piles&Files.py | TD_Piles&Files.py | py | 3,749 | python | fr | code | 0 | github-code | 90 |
31384162581 | import re
import string
from pprint import pprint
import numpy as np
import pandas as pd
from hyperopt import fmin, tpe, Trials, space_eval, hp
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selecti... | jeremypoulain/nlplay | scripts/skl_sgdlinear_train_script.py | skl_sgdlinear_train_script.py | py | 3,321 | python | en | code | 7 | github-code | 90 |
18242014249 | def calc_factors(N):
"""
約数をlistでreturn
この問題はK>1なので、約数に1を含めてない
"""
i=2
factors={N}
while i*i<=N:
if N%i==0:
factors.add(i)
factors.add(N//i)
i+=1
return list(sorted(factors))
N = int(input())
if N==2:
print(1)
exit()
#割り算しない場合
ans = len... | Aasthaengg/IBMdataset | Python_codes/p02722/s278585178.py | s278585178.py | py | 546 | python | ja | code | 0 | github-code | 90 |
71199297577 | import logging
from datetime import date
from typing import Optional
import numpy as np
import pandas as pd
from anndata import AnnData
from cell2location.models.base._pyro_mixin import (
AutoGuideMixinModule,
PltExportMixin,
QuantileMixin,
init_to_value,
)
from pyro import clear_param_store
from pyro.... | dissatisfaction-ai/scHierarchy | schierarchy/logistic/_logistic_model.py | _logistic_model.py | py | 16,466 | python | en | code | 18 | github-code | 90 |
1882574809 | if __name__ == "__main__":
with open("10-input.txt") as f:
lines = f.readlines()
signal_strenghts = []
registry_buffer = [0, 0]
registry_x = 1
cycle_count = 0
for line in lines:
sanitized_line = line.strip()
instruction = sanitized_line.split()... | blacksd/adeventofcode2022 | 10/10-solution-1.py | 10-solution-1.py | py | 1,374 | python | en | code | 0 | github-code | 90 |
14012153188 | import torch
# Output functions come from https://github.com/pytorch/pytorch/blob/master/torch/_meta_registrations.py
def check_cuda_mm(*args):
for x in args:
assert isinstance(x, torch.Tensor)
assert x.device.type == 'cuda'
def mm_output(a, b):
assert a.dim() == 2, 'a must be 2D'
assert... | hpcaitech/Elixir | elixir/tracer/memory_tracer/output_shape.py | output_shape.py | py | 1,404 | python | en | code | 8 | github-code | 90 |
18161392259 | N = int(input())
p = 10**9 + 7
A = [int(i) for i in input().split()]
S = sum(A)%p
ans = S**2 % p
B = [(i**2%p) for i in A]
ans -= sum(B)%p
if ans < 0:
ans += p
if ans % 2 == 0:
print(ans//2)
else:
print((ans+p)//2) | Aasthaengg/IBMdataset | Python_codes/p02572/s372908487.py | s372908487.py | py | 226 | python | en | code | 0 | github-code | 90 |
18058626189 | from collections import deque
sa = deque(input())
sb = deque(input())
sc = deque(input())
a = len(sa)
b = len(sb)
c = len(sc)
s = sa.popleft()
a -= 1
while True:
if s == "a":
a -= 1
if a == -1:
ans = "A"
break
else:
s = sa.popleft()
elif s == "b":... | Aasthaengg/IBMdataset | Python_codes/p03998/s201955161.py | s201955161.py | py | 589 | python | en | code | 0 | github-code | 90 |
9024390231 |
import pickle
import pandas
import networkx as nx
from nltk import *
import nltk
def oauth_login():
CONSUMER_KEY = 'OCa2LGsxL0EUALx6zRUjQWeHl'
CONSUMER_SECRET = 'JWCtpW8inPkfC6QUJbtfJ9uz02JcO78dC5sJDi4obx5LZcBCc5'
OAUTH_TOKEN = '1100042597370920961-4kzA5Em8CbPk4q8jE6GwnSXp3gSdyS'
OAUTH_TOKEN_SECRET =... | helishah29/Recommendation-System-Twitter | Source_Code_Repo/popularity_hashtag.py | popularity_hashtag.py | py | 16,192 | python | en | code | 1 | github-code | 90 |
31139081908 | import igraph
def distinct_edges_traveled(path_list):
return set(edge for path in path_list for edge in path)
def redundancy(path_list):
distinct_edges = distinct_edges_traveled(path_list)
total_number_of_edges = sum([len(p) for p in path_list])
redundancy_score = (total_number_o... | jonpappalord/geospatial_analytics | AlternativeRouting/routing_measures.py | routing_measures.py | py | 4,924 | python | en | code | 18 | github-code | 90 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.