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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
40299316415 | #!-*- coding:utf-8 -*-
from datetime import date
from datetime import datetime
from google.appengine.ext import ndb
from google.appengine.api import search
from lib.controller import *
from models.user_model import UserModel
# テストデータ作成
UserModel(id="user1", user_name=u"鈴木 一郎", height=172, birthday=date(1980, 1, 1))... | nomiso0125/gcp-memo | controllers/front/search_api.py | search_api.py | py | 2,620 | python | en | code | 1 | github-code | 54 |
5980404077 | import RPi.GPIO as GPIO # GPIO control module
import time # time module
LED = 17
# wPi. 0(GPIO. 0), BCM. 17, Physical-Pin. 11
GPIO.setmode(GPIO.BCM) # set BCM mode
GPIO.setup(LED, GPIO.OUT) # OUTPUT setting
try : # Normal operation
while True : # infinite loop
GPIO.output(LED, False) # L... | WiseJoo/Raspberry_Pi | exer_Src/led/python_ver/led01.py | led01.py | py | 588 | python | en | code | 0 | github-code | 54 |
13586833562 | """new field named entry time is add
Revision ID: 9ae6c229e0fd
Revises: b9713203cfc6
Create Date: 2020-02-20 02:39:17.094442
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '9ae6c229e0fd'
down_revision = 'b9713203cfc6'
branch_labels = None
depends_on = None
d... | ashraful000/Biometric-ticketing-system | migrations/versions/9ae6c229e0fd_new_field_named_entry_time_is_add.py | 9ae6c229e0fd_new_field_named_entry_time_is_add.py | py | 684 | python | en | code | 0 | github-code | 54 |
70151708323 | #hap = 0
#exi = {}
#for i in chu:
# exi[i] = True
# hap += i
#def dfs(chu,want,hap,wich):
# if hap == want: return True
# for i in range(wich + 1, len(chu)):
# if want >= hap + chu[i]:
# chk = dfs(chu,want,hap+chu[i],i)
# if chk: return True
# return False
#for i in rang... | freshbell/Coding-Practice | Algorithm/greedy/저울.py | 저울.py | py | 1,039 | python | en | code | 0 | github-code | 54 |
100938202 | # Uses python3
import sys
def optimal_summands(n):
summands = []
k = 1
if (n <= 2*k):
summands.append(n)
return summands
while(n > 2*k):
summands.append(k)
n = n-k
k += 1
summands.append(n)
return summands
if __name__ == '__main__':
n = int(input()... | vinoth-madhavan/Coursera-Specialisation-Algorithms-and-Data-Structures | 1_Algorithmic_Toolbox/week3_greedy_algorithms/6_maximum_number_of_prizes/different_summands.py | different_summands.py | py | 431 | python | en | code | 0 | github-code | 54 |
7875778081 | import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
import pandas as pd
base_url = "https://naruto.fandom.com"
url = base_url + "/wiki/Category:Characters"
# Function to scrape character data from a given URL
def scrape_character_data(url):
response = requests.get(url)
# Send a re... | olaf-siestrzykowski/scraping_naruto_data | scrape_naruto_characters.py | scrape_naruto_characters.py | py | 2,741 | python | en | code | 0 | github-code | 54 |
11052702983 | from flask import Flask, request, redirect
from twilio.twiml.messaging_response import MessagingResponse
from flask_ngrok import run_with_ngrok
app = Flask(__name__)
@app.route("/sms", methods=['GET', 'POST'])
def incoming_sms():
"""Send a dynamic reply to an incoming text message"""
# Get the message th... | a8-s/Jobcall- | jobcall_2.py | jobcall_2.py | py | 732 | python | en | code | 0 | github-code | 54 |
25251281504 | from functions import *
class BombCryptoBot():
# User variables
metamask_pass = False
lang_sel = "en"
pathfind_renew_interval = 3
hero_test_after_maps = 5
hero_test_after_mins = 20
chest_delay = 60
min_stam = 25
debugVar = False
wait_loading = 60
# Time variables
key_validated = False
last_ping_pong = 0... | BombCryptoBot/BombCryptoBot-v4 | bombcryptobot.py | bombcryptobot.py | py | 29,429 | python | en | code | 0 | github-code | 54 |
29976506040 | # 给定一个字符串 s 和一个整数 k,你需要对从字符串开头算起的每隔 2k 个字符的前 k 个字符进行反转。
#
#
# 如果剩余字符少于 k 个,则将剩余字符全部反转。
# 如果剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符,其余字符保持原样。
#
#
#
#
# 示例:
#
# 输入: s = "abcdefg", k = 2
# 输出: "bacdfeg"
#
#
#
#
# 提示:
#
#
# 该字符串只包含小写英文字母。
# 给定字符串的长度和 k 在 [1, 10000] 范围内。
#
# Related Topics 字符串
#... | CatonChen/study_made_me_happy | leetcode/editor/cn/[541]反转字符串 II.py | [541]反转字符串 II.py | py | 986 | python | zh | code | 0 | github-code | 54 |
6669081742 | import argparse
import logging
from multiprocessing import cpu_count
from pathlib import Path
from typing import Dict, List
import h5py
import torch
from torchvideo.samplers import FullVideoSampler
from torch.utils.data import DataLoader, Dataset as TorchDataset
from config.application import RGBConfig
from config.js... | willprice/play-fair | src/scripts/extract_features.py | extract_features.py | py | 3,769 | python | en | code | 17 | github-code | 54 |
45407900791 | import sdl2
def увек(резултат, функција, аргументи):
raise Exception(резултат, аргументи)
def ок_0(резултат, функција, аргументи):
if резултат != 0:
raise Exception(резултат, аргументи)
return резултат
def нок_м1(резултат, функција, аргументи):
if резултат == -1:
raise Exception(ре... | cohadar/mrd | код/мрд/провере.py | провере.py | py | 1,826 | python | sr | code | 0 | github-code | 54 |
501643351 | import os
import yaml
from django.apps import apps
from django.core.files import File
from django.core.management.base import BaseCommand
from django.db import transaction
from django.dispatch import receiver
from django.core.exceptions import FieldDoesNotExist
from django.db.models.signals import post_save
import sh... | CenterForOpenScience/SHARE | share/management/commands/loadsources.py | loadsources.py | py | 5,492 | python | en | code | 97 | github-code | 54 |
32028994868 | def left_lesser(num1, num2):
if num1 < num2:
return True
else:
return False
def merge_lists(left, right, left_lesser):
merged_list = []
i = 0
j = 0
while i < len(left) and j < len(right):
if left_lesser(left[i], right[j]):
merged_list.append(left[i])
... | devonjs/MIT_Introduction_CompSci_Python_Problems | week5/merge_sort.py | merge_sort.py | py | 1,340 | python | en | code | 0 | github-code | 54 |
71711041122 | import os
import random
import subprocess
def node_newdomain(domain,port):
os.system('sudo mkdir /var/www/html/'+str(domain))
os.system('sudo chown -R www-data:www-data /var/www/html/'+str(domain))
config='''
server{
listen 80;
server_name '''+domain+''';
location / {
proxy_set_hea... | FDX100/lara_hoster | lara_hoster.py | lara_hoster.py | py | 8,735 | python | en | code | 5 | github-code | 54 |
14765785304 | import pandas as pd
import numpy as np
import re
import nltk
from nltk.corpus import stopwords
import multiprocessing as mp
from nltk.stem.porter import PorterStemmer
from nltk.stem import WordNetLemmatizer
class TextPreprocessor:
def __init__(self, variety="BrE", user_abbrevs={}, n_jobs=1):
"""
... | ayush714/SMS_Spam_Detection | code/text_preprocessing.py | text_preprocessing.py | py | 2,815 | python | en | code | 6 | github-code | 54 |
34415708061 | from web3 import Web3
from web3.middleware import geth_poa_middleware
import json
import environ
import os
ROOT_DIR = os.path.abspath(os.curdir) + "/breakchain_api/"
env = environ.Env()
environ.Env.read_env()
def get_staking_metrics():
w3 = Web3(Web3.HTTPProvider('https://rpc-mumbai.matic.today'))
w3.middlewa... | breakchain/breakchain-protocol-metrics-api | breakchain_api/stakingMetrics.py | stakingMetrics.py | py | 1,770 | python | en | code | 0 | github-code | 54 |
18462934758 | import streamlit as st
from ml_model.get_model import preprocess_new_data,predict_new_data
import pandas as pd
import plotly.express as px
import joblib
st.set_page_config(page_title='Immo', page_icon='🏠', layout='wide')
st.title("Find the price of your dream property")
st.subheader("First, let's have a look at the o... | Spike815/Immoweb_application | home.py | home.py | py | 3,866 | python | en | code | 0 | github-code | 54 |
44869970669 | import matplotlib.pyplot as plt
import numpy as np
f = lambda x,y: np.array([5*x-x*y-y**2+1, 5*y-x**3+y**2-3])
def next_iter(last_val):
x_n, y_n = last_val
jacobi = np.array([ [5-y_n, x_n-2*y_n ],
[3*(x_n**2), 5+2*y_n ] ])
inv_jac = np.linalg.inv(jacobi)
return last_val - inv_jac @ f(x_n, y_n)
def ite... | mazunki/uio | MAT1110/oblig2/iterartioncontraction.py | iterartioncontraction.py | py | 680 | python | en | code | 2 | github-code | 54 |
14803092916 | import torch
from baselines.common.vec_env.vec_env import VecEnvWrapper
from dg_util.python_utils import pytorch_util as pt_util
class HabitatVecEnvWrapper(VecEnvWrapper):
def __init__(self, venv):
observation_space = venv.observation_spaces[0]
action_space = venv.action_spaces[0]
super(H... | facebookresearch/splitnet | utils/env_util.py | env_util.py | py | 1,999 | python | en | code | 59 | github-code | 54 |
72358972003 | """Transform draft data into CSV."""
import csv
import os
from typing import Callable
from loguru import logger
from league_history_collector.collectors.models import League
def set_drafts(
file_name: str,
league: League,
manager_id_mapper: Callable[[str], str],
player_id_mapper: Callable[[str, str... | lynshi/league-history-collector | league_history_collector/transformer/csv/draft.py | draft.py | py | 2,626 | python | en | code | 0 | github-code | 54 |
23305206444 | import numpy as np
import pandas as pd
path = "G:\AI\mfcc.csv"
arr = np.loadtxt(path, delimiter=',')
l = []
def distance(vector1, vector2):
d = 0
for a, b in zip(vector1, vector2):
d += (a-b)**2
return d**0.5
for i in arr:
len_i = len(i)
label_row = []
for j in range(0, len_i):
... | ZhuPan2016/KNN | knn2.py | knn2.py | py | 978 | python | en | code | 0 | github-code | 54 |
24868072298 | import g2d
import random
import datetime
class Game:
"""
Generica classe game utilizzata durante la partita vera e propria
"""
def __init__(self):
self._boxes = [] # Lista delle caselle
self._matrix = [] # Matrice con il numero di ogni casella
self._statematrix = [] # Matric... | manuelcarini/Hitori | hitori.py | hitori.py | py | 21,305 | python | it | code | 0 | github-code | 54 |
15695505795 | #!/usr/bin/env python
# coding: utf-8
# ----------
#
#
# #Please note that this isn't a solution.
# The following notebook might be helpful to **beginners**, such as myself.
# It provides a **general work flow** you might follow to solve Machine learning problems such as the **Titanic challenge** and many more.
# ... | nischalshrestha/automatic_wat_discovery | Notebooks/py/harinsingh/swimming-in-the-titanic-data-python-way/swimming-in-the-titanic-data-python-way.py | swimming-in-the-titanic-data-python-way.py | py | 5,814 | python | en | code | 2 | github-code | 54 |
72522160802 | def id(line):
binary = 0
for char in line:
if char == "F" or char == "L":
binary = binary<<1
else:
binary = (binary<<1) + 1
return binary
with open("input5") as input5:
text = input5.read()
m = id(text.split("\n")[0])
for line in text.split("\n")[1:-1]:
... | ArthanJans/AdventOfCode2020 | 5.py | 5.py | py | 388 | python | en | code | 0 | github-code | 54 |
39120881275 | """
Faça uma prova de matemática para crianças que estão aprendendo a somar números inteiros menores do que 100. Escolha
números aleatórios entre 1 e 100, e mostre na tela a pergunta. Faça cinco perguntas ao aluno, e mostre para ele as
perguntas e as respostas corretas, além de quantas vezes o aluno acertou.
"""
print(... | VitorKruel102/Curso_Programando_em_Python | Exercicios_Seção05/Exercicio_29_S05.py | Exercicio_29_S05.py | py | 1,200 | python | pt | code | 0 | github-code | 54 |
19671592040 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 25 15:58:59 2022
@author: zhetao Jia
To run the code, execute::
mpirun -n 16 python file_name.py
"""
import emopt
from RelatedPackages.fdfds import fdfds
from RelatedPackages.plot_iteration_FWM import plot_iteration_FWM
from RelatedPackage... | zhetaoj/InverseFWM | Emopt_InvFWM2D_main.py | Emopt_InvFWM2D_main.py | py | 14,507 | python | en | code | 0 | github-code | 54 |
12320642558 | import http.server
from threading import Thread
import os.path
import mimetypes
class HTTPHandler:
def __init__(self, config):
self.config = config
handler = HTTPHandler.make_http_handler(self.config['media_dir'])
self.httpd = http.server.HTTPServer(('', self.config['media']['port']), hand... | Surye/relaygram | relaygram/http_server.py | http_server.py | py | 1,712 | python | en | code | 5 | github-code | 54 |
2589850069 | #
# Test in line with 2d guiding example
#
import math
import sys
from manta import *
from helperInclude import *
# solver params
res0 = 30
scale = 2
res = res0*scale
gs = vec3(res,res,1)
s = Solver(name='main', gridSize = gs, dim=2)
s.timestep = 2.0/scale
# IOP (=1), ADMM (=2) or PD (=3)
# params
valAtMin = 1
valA... | thunil/tempoGAN | tools/tests/test_1050_guiding2d.py | test_1050_guiding2d.py | py | 1,979 | python | en | code | 167 | github-code | 54 |
26973468051 | from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.index, name='blog-home'),
path('about/', views.about, name='blog-about'),
path('post/<int:id>', views.post, name='blog-post'),
path('post/... | gangasandhu/blog_app | blog_app/blog/urls.py | urls.py | py | 691 | python | en | code | 0 | github-code | 54 |
37621160419 | count = 0
for i in range(1,10000):
s = str(i)
for j in range(len(s)):
#print(s[j])
if int(s[j]) == 8:
count += 1
print(count)
"""
count = 0
for i in range(1,10000):
#자릿수 상관하지 않고 '8' = 문자로서의 8이 있는지 검사
for j in str(i):
if j == '8':
count += 1... | dyrnfmxm/python_practice | for_practice2_google_test.py | for_practice2_google_test.py | py | 483 | python | ko | code | 0 | github-code | 54 |
870471947 | import tableauserverclient as TSC #import server client
def loginToSite(email,pwd,site):
tableau_auth = TSC.TableauAuth(email,pwd,site)
server = TSC.Server('https://10ax.online.tableau.com') #Link of Your tableau site
server.auth.sign_in(tableau_auth)
return server
def createGroup(name_of_group,server... | sandeepmandal70/TableauAPI | group.py | group.py | py | 1,398 | python | en | code | 0 | github-code | 54 |
18078189369 | from os import path
import re
from typing import List, Dict, Pattern
def handle_toxins(file_name: str) -> None:
complement: Dict[str, str] = {"A": "T", "T": "A", "C": "G", "G": "C"}
sequences_3_5: List[str] = []
re_toxins: Pattern = re.compile(r">(.*)\n([ATCG\n]*)\n?")
with open(file_name) as toxins... | henrique-tavares/IFB-Introducao-a-Bioinformatica | PB/02/a.py | a.py | py | 1,112 | python | en | code | 0 | github-code | 54 |
2497340905 | import pandas as pd
import numpy as np
import xgboost as xgb
train = pd.read_csv("../input/train.csv")
test = pd.read_csv("../input/test.csv")
submission = pd.read_csv("../input/sampleSubmission.csv")
#target is class_1, ..., class_9 - needs to be converted to 0, ..., 8
train['target'] = train['target'].apply(... | sajedjalil/Data-Science-Pipeline-Detector | dataset/otto-group-product-classification-challenge/Jarek/exampe.py | exampe.py | py | 991 | python | en | code | 8 | github-code | 54 |
16916405336 | from flask import Blueprint, jsonify, request
from ..extensions.database import db
from .login import token_required
from ..models import Quiz, Question
quiz = Blueprint('quiz', __name__)
@quiz.route('/api/quizzes', methods=['GET'])
@token_required
def get_all_quizzes(current_user):
quizzes = Quiz.query.filter_b... | Silkypaladin/FlaskAPI | api/routes/quiz.py | quiz.py | py | 2,291 | python | en | code | 0 | github-code | 54 |
41642920244 | import string
class Solution:
def isPalindrome(self, s: str) -> bool:
i =0
j = len(s) - i - 1
while i <= len(s)//2:
while i < len(s) and s[i] not in string.ascii_letters and s[i] not in string.digits:
i +=1
while j>= 0 and s[j] not in string.ascii... | 224nth/leetcode | apple/is_palindrome.py | is_palindrome.py | py | 622 | python | en | code | 0 | github-code | 54 |
70566236322 | """Setup script for code_generator project"""
import code_generator
import os.path
from setuptools import setup, find_packages
THIS_FOLDER = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(THIS_FOLDER, "README.md")) as handle:
README_TEXT = handle.read()
setup(
name="code_generator",
... | AdamMinge/egnite_client | tools/code_generator/setup.py | setup.py | py | 902 | python | en | code | 0 | github-code | 54 |
24591101700 | #base config file
_base_='../swin/mask_rcnn_swin-s-p4-w7_fpn_fp16_ms-crop-3x_coco.py'
#declare self-customed dataset type
dataset_type='CocoDataset'
#images directory
prefix='./data/taco'
#classes list
classes=('Can', 'Carton/Paper', 'GlassBottle',
'Other', 'PlasticBottle', 'PlasticOther', 'Wrapper')
# cla... | crepuscularlight/ARC_SWIN_DETECTION | mmdetection/configs/MaskRCNN-swin/taco_own_extend_swin.py | taco_own_extend_swin.py | py | 1,346 | python | en | code | 1 | github-code | 54 |
5347215609 | import h5py
import numpy as np
import argparse
parser = argparse.ArgumentParser(description='Cut out a subset')
ra_min = 60
ra_max = 61
dec_min = -31
dec_max = -30
def trim_file(input_file, output_file, group_name, thin):
file_in = h5py.File(input_file, 'r')
file_out = h5py.File(output_file, 'w')
group_... | LSSTDESC/TXPipe | bin/cut_out_example.py | cut_out_example.py | py | 1,150 | python | en | code | 17 | github-code | 54 |
42009013102 | """Лаунчер"""
import subprocess
PROCESS = []
while True:
ACTION = input('Выберите действие: q - выход, '
's - запустить сервер и клиенты, x - закрыть все окна: ')
# Команда для выхода
if ACTION == 'q':
break
elif ACTION == 's':
# Запускаем сервер по команде
... | armornik/client_messendger | launcher_mode.py | launcher_mode.py | py | 1,341 | python | ru | code | 0 | github-code | 54 |
74445237921 | #This is a program to censor any words a user wants to censor from a passage of text.
def censor(text,words):
a=[]
a.append(text)
for i in range (0,len(words)):
b=words[i]
c=a[i]
d=(c.replace(words[i],(b[0]+(len(b)-2)*'*'+b[len(b)-1])))
a.append(d)
return a[-... | maelnagg/morepos | censor.py | censor.py | py | 541 | python | en | code | 0 | github-code | 54 |
6243776601 | from db.connection import connection, pool, cursor
def seed(playlists, users, restaurants, votes):
def create_users_table(cursor) -> None:
cursor.execute(
"""
DROP TABLE IF EXISTS users CASCADE;
CREATE TABLE users
(
user_ema... | a1v0/be-restaurant-playlists | db/seed.py | seed.py | py | 3,757 | python | en | code | 0 | github-code | 54 |
779888949 | # Guitar Note Tester
# a Pygame app designed to help a guitar player learn to find the position of staff notes on a fretboard
# created by Kevin Aldrich on July 22, 2014
#
import pygame
from pygame.locals import *
import math
import numpy
import random
import time
import pdb
# by Timothy Downs, inputbox writ... | kaldric2/GuitarNoteTester_Python | GuitarNoteTester_4.0.py | GuitarNoteTester_4.0.py | py | 7,493 | python | en | code | 0 | github-code | 54 |
9324633467 | import csv
import sys
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
TEST_SIZE = 0.4
def main():
# Check command-line arguments
if len(sys.argv) != 2:
sys.exit("Usage: python shopping.py data")
# Lo... | brennonatal/cs50-AI | week4/shopping/shopping.py | shopping.py | py | 4,721 | python | en | code | 1 | github-code | 54 |
21848851201 | from tools.db_manager import db
from tools.db_manager import patch_reader
import functools
import hashlib
import re
_dev_mode = False
def set_config_files(files):
db.set_config_files(files)
def set_dev_mode(value):
global _dev_mode
if value and not db.is_host_local():
raise Exception(
... | ProofOfDonut/pillsbury | tools/db_manager/db_instance.py | db_instance.py | py | 3,202 | python | en | code | 3 | github-code | 54 |
95937494 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 27 19:30:48 2021
@author: 53055
"""
import Model_2
import LP
import pickle
if __name__ == "__main__":
S = Model_2.StateSpace()
F = Model_2.FinalState(S)
c = Model_2.initState(S)
A_H, A_R = Model_2.ActionSpace(S)
Cost_H, Cost_R = Model_2.Cost(h = 25)... | alexalvis/HRI-StackelBerg | new_example_2/Test.py | Test.py | py | 624 | python | en | code | 0 | github-code | 54 |
15059761894 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from typing import List, Tuple, Union
import discord
from source.command import Command
ICONS_B = {
"MAIN": ":book:",
"CAUT": ":exclamation:",
}
COMMANDS_B = {
"HLP": Command("!help", "今見ているこの画面を表示します。"),
"HLPG": Command("!help_game", "各ゲームの概要を説明します。"),
... | tsubasa283paris/discord_the_array_book | source/game_controller.py | game_controller.py | py | 7,060 | python | ja | code | 0 | github-code | 54 |
341510406 | from setuptools import setup, find_packages
entry_point = 'my_proj_res = ' \
'myproj.run:main'
# get the dependencies and installs
with open('requirements.txt', 'r', encoding='utf-8') as f:
requires = [x.strip() for x in f if x.strip()]
setup(
name='myproj',
version='0.1',
packages=find... | arashbaghaeilakehqb/my_proj_gh | src/python/setup.py | setup.py | py | 749 | python | en | code | 0 | github-code | 54 |
73371549283 | #
# Name: Julian Lankstead
# Student Number: 101043448
#
# References: Gaddis, T (2015). "Starting Out With Python"
#Welcome Statement!!!!
print("Welcome to the Boston Bruins quiz! ")
#The First List
list1 = [['MC', 1, 'What year did were the Boston Bruins founded?'],
['MC', 2, 'Who is the GM of the Bruins?'],
... | jlanks/SlicinAndDicin | Q2.py | Q2.py | py | 3,261 | python | en | code | 0 | github-code | 54 |
18584576557 | #An Yong Shyan, S10258126B
#Prompt user to enter a number
num = int(input("Please enter a number: "))
#Use a while loop to times 1 to 10
multiplier = 1
while multiplier <= 10:
print(' ' + str(num), "x", multiplier, "=", num * multiplier)
multiplier += 1
#Print the end
print('The End') | Koyonari/NP-Programming | Semester 1/Weekly Exercises/Week 6/TimesTable.py | TimesTable.py | py | 312 | python | en | code | 0 | github-code | 54 |
7658442222 | from datetime import date
import logging
import requests
import re
import os
import urllib3
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
logger = logging.getLogger(__name__)
def _check_url(url):
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWar... | InseeFrLab/pynsee | pynsee/download/_check_url.py | _check_url.py | py | 3,151 | python | en | code | 58 | github-code | 54 |
25252758307 | # Import the database object (db) from the main application module
# We will define this inside /base/__init__.py in the next sections.
from flywheel import Field, NUMBER, STRING, GlobalIndex
from base.common.models import DyBase
# Define a User model
class Rule(DyBase):
__tablename__ = 'rule'
__metadata__ = ... | shikarkhane/vcal | base/mod_rule/models.py | models.py | py | 1,068 | python | en | code | 0 | github-code | 54 |
32132764180 | #!/usr/bin/env python3
import os
import subprocess
DIR = "."
for file in os.listdir(DIR):
if file.endswith(".dot"):
svg_file = file.replace(".dot", ".svg")
subprocess.run(["dot", "-Tsvgz", "-o", svg_file, file]) | sambacha/preprocessing | gen_dots.py | gen_dots.py | py | 234 | python | en | code | 1 | github-code | 54 |
6876652902 | from PySide.QtCore import *
from PySide.QtGui import *
import webbrowser
class Console(QDialog):
def __init__(self, parent):
super(Console, self).__init__(parent)
self.parent = parent
self.setWindowTitle("Developer Console")
self.desc = 'Developer console for The Mapper ver... | baldengineers/mapper | console.py | console.py | py | 3,744 | python | en | code | 0 | github-code | 54 |
29291831098 | import nltk
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
from bs4 import BeautifulSoup
import requests
nltk.download('stopwords')
nltk.download('wordnet')
nltk.download('punkt')
stop_words = set(stopwords.words('english'))
lemmatizer = WordNetLemmat... | MidnightStudioOfficial/Ava | src/test16.py | test16.py | py | 1,121 | python | en | code | 2 | github-code | 54 |
21968521170 | from unittest import TestCase
from server import app
from model import connect_to_db, db, example_data
from flask import session
import json
from unittest.mock import patch
import spotify_api
class FlaskTestsBasic(TestCase):
"""Flask tests."""
def setUp(self):
"""Stuff to do before every test."""
... | corinnejachelski/synaesthetic | tests.py | tests.py | py | 5,407 | python | en | code | 0 | github-code | 54 |
71678162401 | import copy
class Boggle():
def __init__(self, grid):
self.grid = grid
self.height = len(grid)
self.width = len(grid[0])
def _getNeighbours(self, i, j):
def returnHigher(number, limit):
if number + 1 >= limit:
return limit-1
else:
return number+1
def returnLower(nu... | ijc-90/coding-playground | binaryTrees/boggle.py | boggle.py | py | 1,822 | python | en | code | 0 | github-code | 54 |
2857577632 | #!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
def format_bytes(byts):
byts = bytearray(byts)
byts = [hex(b)[2:] for b in byts]
return ' '.join(byts)
| Sabesan2000/SOFE-QUAILTY-FINAL | Calibre/src/calibre/ebooks/mobi/debug/__init__.py | __init__.py | py | 316 | python | en | code | 1 | github-code | 54 |
21218083797 | file = input('Please enter valid file: ')
try:
fHandle = open(file)
except:
print('File does not exist')
exit()
try:
temp = dict()
for line in fHandle:
words = line.split()
if len(words) > 0 and words[0] == 'From':
temp1 = words[1].split('@')
if temp1[1] not in temp:
temp[temp1[1]] = 1
else:
... | DhavalLalitChheda/class_work | Programs/FromDictionary2.py | FromDictionary2.py | py | 407 | python | en | code | 0 | github-code | 54 |
22667057682 | from odoo import api, models, fields, tools
class PickingShopify(models.Model):
_name = 'method_ltdc.shopify_report_delivery'
_description = "Moviemto de productos por Shopify"
_auto = False
# _order = 'product_id desc'
origin = fields.Char(string='Orden')
date_done = fields.Datetime(string='F... | Cesar250101/method_ltdc | report/shopify_delivery.py | shopify_delivery.py | py | 1,531 | python | en | code | 0 | github-code | 54 |
37625017883 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"... | qianlongzju/Leet_Code | Algorithms/py/572.SubtreeOfAnotherTree.py | 572.SubtreeOfAnotherTree.py | py | 993 | python | en | code | 0 | github-code | 54 |
43784316389 | from random import randrange
import random
import re
import string
print("😎😎😎😎😎😎😎😎😎😎😎😎😎😎😎😎😎😎😎😎😎😎😎😎😎😎😎😎😎😎😎😎😎😎😎😎😎😎😎😎😎")
print("==============================================================")
print(" PATI 1) MASTER STR (index, split, replace, lower, upper, title)")
print("=======... | mathieu509/Parilus50 | srt.py | srt.py | py | 21,178 | python | en | code | 0 | github-code | 54 |
20107974730 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by HazzaCheng on 2020-01-28
from abc import abstractmethod
import numpy as np
from sklearn.metrics import roc_auc_score, accuracy_score
from Configurations import CLASS_NUM
from tools import timeit
def auc_metric(solution, prediction):
solution = np.array(... | caibaibai/AutoDL2019 | AutoDL_sample_code_submission/model_manager.py | model_manager.py | py | 4,330 | python | en | code | null | github-code | 54 |
24864526814 | from typing import Dict, List, Optional
from snuba_sdk import Column, Condition, Op
from sentry.search.events.builder import QueryBuilder
from sentry.search.events.types import ParamsType
from sentry.snuba.dataset import Dataset
from sentry.snuba.referrer import Referrer
from sentry.utils.snuba import raw_snql_query
... | herisutrisno/sentry | src/sentry/profiles/flamegraph.py | flamegraph.py | py | 1,010 | python | en | code | null | github-code | 54 |
41856240057 | def get_priority(letter_in):
# doing some magic
if letter_in.islower():
pri = ord(letter_in) - 96
else:
pri = ord(letter_in) - 38
return pri
def part1(input_file):
with open(input_file, "r") as f:
total_pri = 0
for bag in f.readlines():
no_items = len(ba... | caroliwi/advent-of-code | day3.py | day3.py | py | 925 | python | en | code | 0 | github-code | 54 |
5560992598 | #!/usr/bin/python
def valid_args(args):
arg_count = len(args)
# Validate amount of arguments
if arg_count < 3:
exit("Argument missing. Example format, 'pizzabot.py 5x5 (5,5)'")
def valid_grid(size):
# Split grid on the x
parsed_size = size.lower()
grid_split = parsed_size.split("x")
... | finnegan28/pizzabot-challenge | commands.py | commands.py | py | 3,423 | python | en | code | 1 | github-code | 54 |
71559583202 | import os
from os.path import join
def run_public_domain_vectors():
from spiders.publicdomainvectors import CsvGenerator
base_path = 'PATH'
init_num = 49
path = join(base_path, f'{init_num}')
while os.path.exists(path):
generator = CsvGenerator(path, 'Signs/Symbols')
generator.g... | barisariburnu/python-shutterstock-csv-generator | main.py | main.py | py | 723 | python | en | code | 0 | github-code | 54 |
33809758659 | # Given: N
# Return: a list counting up and down by 1 that has length
# N
# Examples: N = 5
# Output: [1, 2, 3, 2, 1]
# N = 6
# Output: [1, 2, 3, 3, 2, 1]
# create a list of integers starting from 1, increasing by
# 1 each element until N // 2, adding the potential single
# middle digit of N is odd, then decreasing by... | ameru/pm-technical-int-prep | CodePath Sample Questions/CountingUpAndDown.py | CountingUpAndDown.py | py | 1,709 | python | en | code | 2 | github-code | 54 |
71587127521 | import argparse
import dgl.function as fn
import numpy as np
import torch
from dgl.data import CiteseerGraphDataset, CoraGraphDataset, PubmedGraphDataset
from torch import nn
from torch.nn import functional as F, Parameter
from tqdm import trange
from utils import evaluate, generate_random_seeds, set_random_state
c... | dmlc/dgl | examples/pytorch/dagnn/main.py | main.py | py | 8,186 | python | en | code | 12,455 | github-code | 54 |
5984342239 | import copy
from typing import Any, Dict, List, Optional, Union
from samtranslator.model.exceptions import ExceptionWithMessage, InvalidResourceAttributeTypeException
from samtranslator.public.intrinsics import is_intrinsics
from samtranslator.public.sdk.resource import SamResourceType
from samtranslator.swagger.swagg... | aws/serverless-application-model | samtranslator/plugins/globals/globals.py | globals.py | py | 19,338 | python | en | code | 9,141 | github-code | 54 |
15524731208 | import torch.nn as nn
import torch
import numpy as np
import random
device = 'cuda' if torch.cuda.is_available() else 'cpu'
dataset_config = {
'lr_path': 'D:/Datasets/TEM-ImageNet-v1.3-master/image/',
'hr_path': 'D:/Datasets/TEM-ImageNet-v1.3-master/noBackgroundnoNoise/',
'channel': 3,
'train_split': ... | KmjGeorge/TEMSR | configs.py | configs.py | py | 1,800 | python | en | code | 0 | github-code | 54 |
9981297566 | def solution(numbers, target):
answer = 0
def dfs(idx, sum_) :
if idx == len(numbers) :
nonlocal answer
if sum_ == target :
answer += 1
return
else :
dfs(idx+1, sum_+numbers[idx])
dfs(idx+1, sum_-numbers[id... | 4-trees-in-summer/Algorithm-CT | 프로그래머스/lv2/43165. 타겟 넘버/타겟 넘버.py | 타겟 넘버.py | py | 365 | python | en | code | 0 | github-code | 54 |
36108578796 | import numpy
nm = input().split()
n = int(nm[0])
m = int(nm[1])
numbers = []
for i in range(0,n,1):
numpy.set_printoptions(sign=' ')
arr = input().rstrip().split(' ')
for j in range(0, len(arr),1):
arr[j] = int(arr[j])
numbers.append(arr)
#my_array = numpy.array(arr).astype(int)
my_array = nu... | gokadroid/Python3Examples | numpy2dArraySumProd.py | numpy2dArraySumProd.py | py | 396 | python | en | code | 0 | github-code | 54 |
10119862155 | import unittest
from unittest.mock import patch
from common import check_licenses, group_by_project, explore_repository
from github import Github
# write test for group_by_project function
class TestGroupByProject(unittest.TestCase):
def test_none(self):
lines = None
expected = {}
self.ass... | fospo/github_pyxplorer | tests.py | tests.py | py | 2,501 | python | en | code | 0 | github-code | 54 |
26851253217 | from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
from gan_scripts.encoder import Encoder
from gan_scripts.decoder_functions import MultiType, CategoricalActivation
from gan_scripts.decoder import Decoder
class AutoEncoder(nn.Module):
def __init__(self, dat... | brianmhartman/Anonymizing-Ratemaking-Datasets-using-GANs | MC-WGAN-GP/gan_scripts/autoencoder.py | autoencoder.py | py | 1,681 | python | en | code | 2 | github-code | 54 |
620084058 | import logging
import os
import random
from functools import partial
import databricks.sdk.core
import pytest
from databricks.sdk import AccountClient, WorkspaceClient
from databricks.sdk.core import Config
from databricks.labs.ucx.mixins.fixtures import * # noqa: F403
from databricks.labs.ucx.mixins.sql import Stat... | rohit-db/ucx | tests/integration/conftest.py | conftest.py | py | 6,199 | python | en | code | null | github-code | 54 |
18068295679 | r"""Utility functions for the prox module"""
from __future__ import division
from builtins import range
import numpy as np
__author__ = """Brendt Wohlberg <brendt@ieee.org>"""
def ndto2d(x, axis=-1):
"""Convert a multi-dimensional array into a 2d array, with the axes
specified by the `axis` parameter fla... | bwohlberg/sporco | sporco/prox/_util.py | _util.py | py | 2,824 | python | en | code | 238 | github-code | 54 |
40057458447 | from unittest import TestCase
from business.wifi.WiFiPoller import WiFiPoller
__author__ = 'raghav'
class TestWiFiPoller(TestCase):
def test_checkLocation(self):
wifiPoller = WiFiPoller()
location = wifiPoller.checkLocation()
self.assertAlmostEquals(location, "{x: 2.6322, y: 1.8822}")
| akshayv/INVI | trunk/business/test/wifi/test_WiFiPoller.py | test_WiFiPoller.py | py | 317 | python | en | code | 1 | github-code | 54 |
27658124098 | #Pedro comprou um saco de ração com peso em quilos. Ele possui dois gatos, para os quais fornece
# a quantidade de ração em gramas. A quantidade diária de ração fornecida para cada gato é sempre
# a mesma. Faça um programa que receba o peso do saco de ração e a quantidade de ração fornecida
# para cada gato, calcule e ... | marinalexia/fatec_program_BancoDeDados | 1_Estrutura_Sequencial/exercicio_7.py | exercicio_7.py | py | 873 | python | pt | code | 0 | github-code | 54 |
21501703954 | print("please give time like this 07:12:23AM(hh:mm:sec AM or PM)")
a=input("enter the time:")
if a[-2:]=="AM" or a[-2:]=="am":
if a[:2]=="12":
print("00"+a[2:-2])
else:
print(a[:-2])
else:
hour=int(a[:2])
if hour<12:
hour=hour+12
print(str(hour)+a[2:-2])
# def timeconver... | rajithagumma/function | military time.py | military time.py | py | 708 | python | en | code | 0 | github-code | 54 |
72052095521 | from typing import List
from fastapi import APIRouter, Depends
from sqlalchemy.engine import Row
from starlette import status
from app.v1.router.admin.permission import get_user
from app.v1.service.customer.cart import CartService
from schemas.associations import CartItemReq
router = APIRouter()
@router.get(
pa... | nguyenanh2222/ecommerce_three_layers | app/v1/router/customer/cart.py | cart.py | py | 1,863 | python | en | code | 0 | github-code | 54 |
25817115057 | #!/usr/bin/env python3
from tabulate import tabulate
def markFinished(cur, con):
try:
query = "SELECT Year FROM Seasons WHERE Finished=0"
cur.execute(query)
seasonList = cur.fetchall()
if len(seasonList) == 0:
print("Oops, no season running right now!")
tmp ... | kjain1810/IPL-database | libs/markFinished.py | markFinished.py | py | 2,267 | python | en | code | 1 | github-code | 54 |
44627079871 | import gc
import numpy as np
import logging
from .base import DataBufferBase
STATE = 0
ACTION = 1
REWARD = 2
DONE = 3
class BatchSet(DataBufferBase):
"""
Class for batched dataset as used in on-policy algorithms, where a batch of data is first collected
with the current policy, several optimization step... | leodestiny/tianshou | tianshou/data/data_buffer/batch_set.py | batch_set.py | py | 5,100 | python | en | code | null | github-code | 54 |
5751051859 | from techniques.config.constants import open_green
from techniques.config.constants import open_red
from techniques.config.constants import close
from techniques.config.utilities import print_title_technique
from techniques.config.utilities import print_mitigation
def print_appcert_dlls():
text = "( AppCert DLLs ... | KevinLiebergen/priv-escalation | project/win/techniques/appcert_dlls.py | appcert_dlls.py | py | 856 | python | en | code | 2 | github-code | 54 |
10649657528 | import numpy as np
def flag_close_pairs(ra, dec, radius):
ra, dec = ra*np.pi/180, dec*np.pi/180
rsq = (radius*np.pi/180)**2
assert ra.ndim == 1 and dec.ndim == 1 and ra.shape[0] == dec.shape[0],\
"bad input"
nval = ra.shape[0]
xyz = np.zeros((nval, 3), dtype=np.float64)
cdec = np.cos(d... | Subaru-PFS/ets_shuffle | ets_shuffle/convenience.py | convenience.py | py | 2,226 | python | en | code | 0 | github-code | 54 |
36877703603 | #!/usr/bin/env python3
# -*- coding: utf-8, vim: expandtab:ts=4 -*-
from PyQt4 import QtGui, QtCore
from SVGWriter import *
from Bounds1D import Bounds1D
"""
* A TokenLayout object lays out a collection of tokens in sequence by placing a stack of property values of each token
* at a position corresponding to the in... | kalregi/What-sWrong_SVG | TokenLayout.py | TokenLayout.py | py | 12,072 | python | en | code | 0 | github-code | 54 |
20494500701 |
# Prompt the user for the filename with item details
filename = input('Enter the filename: ')
def file_handler():
'''
Function opens a file specified by the user
Processes the file and creates two lists
One with text data: item_name and description
The other with numeric ... | georgek2/Python_for_Data_Science | Files/Projects/1_sample/program.py | program.py | py | 2,359 | python | en | code | 0 | github-code | 54 |
2506801703 | import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import (QApplication, QWidget)
from PyQt5.QtGui import (QPainter, QPen)
from PyQt5.QtCore import Qt
class Widget(QWidget):
def __init__(self):
super(Widget, self).__init__()
self.resize(200, 200)
self.move(100, 100)
self.s... | EvanWu146/Mnist_based-in-Lenet5-and-Pytorch | Widget.py | Widget.py | py | 1,514 | python | en | code | 4 | github-code | 54 |
71382973601 | import torch
testLung = False
useContext = True
numberOfEpochs = 5000
testMode = True
trainMode = True
oneShot = True
usePaddedNet=True
vecLengthW = 0.0
trainingFileNamesCSV=''
device=torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
outputPath='.'
maxNumberOfSamples=6 # samples for one batch must be < ... | ToFec/TorchSandbox | src/Options.py | Options.py | py | 1,252 | python | en | code | 0 | github-code | 54 |
24469266348 | from sleap.io.convert import default_analysis_filename, main as sleap_convert
from sleap.io.dataset import Labels
from sleap.io.video import Video
from sleap.instance import Instance
from pathlib import PurePath, Path
import re
import pytest
@pytest.mark.parametrize("format", ["analysis", "analysis.nix"])
def test_a... | talmolab/sleap | tests/io/test_convert.py | test_convert.py | py | 4,285 | python | en | code | 340 | github-code | 54 |
11562788790 | # https://www.acmicpc.net/problem/9020
T = int(input())
#소수 리스트 생성
li = [True] * 10001
li[0] = li[1] = False
for i in range(2,10001):
if li[i] == True:
for j in range(i+i,10001,i):
li[j] = False
#찾기 시작
for _ in range(T):
n = int(input())
a = b = int(n / 2)
while not(a <= 0) :
... | Overclock7/Baekjoon | Python/9020.py | 9020.py | py | 507 | python | ko | code | 0 | github-code | 54 |
42234932876 | import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
BATCH_SIZE = 2048
LR_ORIG = 0.0001
LR_BY_ITSELF = 0.04
# LR_ORIG: CORRECT_D FOR FIRST ENTRY
# 0.01 : 0.0661
# 0.001 : 0.0046
# 0.0001 : 0.000444
# LR_... | samlobel/DIRECT_CURVATURE_ESTIMATION | OLD_use_second_derivative.py | OLD_use_second_derivative.py | py | 4,532 | python | en | code | 0 | github-code | 54 |
11916973017 | from keras import backend as K
from keras.optimizers import Adam
from keras.models import Sequential
from keras.layers import Lambda, Dense, BatchNormalization, Activation, Dropout, Input
class Actor:
"""
Actor (policy) class initialises parameters and
builds models with Keras (see documentation on https:/... | IloBe/RL_Quadcopter_master | agents/Actor.py | Actor.py | py | 5,781 | python | en | code | 0 | github-code | 54 |
22173208776 | import logging
def get_logger(logname, level=logging.INFO):
# set up logging to file - see previous section for more details
logging.basicConfig(level=level,
format='%(asctime)s %(name)-12s %(funcName)s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M',
... | prowler421/cheques-service | python_kafka/utils/logger.py | logger.py | py | 514 | python | en | code | 0 | github-code | 54 |
73427612003 | from flask import Flask, request
from flask_restful import Resource, Api, reqparse
# Resource - reprezentacja jakiegoś konkretnego bytu; zazwyczaj ma odzwierciedlenie w tabeli
from flask_jwt import JWT, jwt_required
from security import authenticate, identity
from user import UserRegister
movies = []
app = Flask(__... | FilipHalon/flask-tutorial | stage2/app.py | app.py | py | 2,223 | python | en | code | 0 | github-code | 54 |
30565473467 | nome = input('Qual seu nome? ')
print('Prazer em te conhecer {:^20}!'.format(nome))#deixa o nome no meio
print('Prazer em te conhecer {:=^20}!'.format(nome))#imprimi =======oi======!
n1 = int(input('Digite um valor: '))
n2 = int(input('digite outro valor: '))
s = n1 + n2
m = n1 * n2
d = n1 / n2
di = n1 // n2
e = n1 ** ... | SmokeBr/Python | 0005.py | 0005.py | py | 619 | python | pt | code | 1 | github-code | 54 |
21234328774 | import os, os.path, sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
import django
django.setup()
#imports for our project
from django.core import management
from django.db import connection
from homepage.models import Choice, Question # Import the model classes we just wrote.
from django.uti... | CameronSpilker/cs-projects-jewel | initialize.py | initialize.py | py | 2,344 | python | en | code | 0 | github-code | 54 |
29662962204 | import collections
import os
import json
import sys
from math import ceil
skills = [u'athletics', u'acrobatics', u'sleight of hand', u'stealth', u'arcana', u'history', u'investigation', u'nature', u'religion', u'animal handling', u'insight', u'medicine', u'perception', u'survival', u'deception', u'intimidation', u'perf... | WillowHayward/5e-SRD | scripts/repairs.py | repairs.py | py | 2,192 | python | en | code | 0 | github-code | 54 |
38467598510 | import copy, os, json
import numpy as np
import tensorflow as tf
class BasicModel(object):
# ------------------------------------------------------------------------------------------------------------------
# ------------------------------------------ INITIALIZATION FUNCTIONS --------------------------------... | fllinares/neural_fingerprints_tf | code/models/basic_model.py | basic_model.py | py | 9,408 | python | en | code | 30 | github-code | 54 |
5345060982 | ''' Merge overlapping intervals problem
Given a list of intervals, merge all the overlapping intervals to produce a list
that has only mutually exclusive intervals.
https://designgurus.org/path-player?courseid=grokking-the-coding-interview&unit=grokking-the-coding-interview_1628743622133_21Unit
My code does it inpl... | codeybear/AlgoStuff | overlapping_intervals/merge_overlapping_intervals.py | merge_overlapping_intervals.py | py | 1,180 | python | en | code | 0 | github-code | 54 |
71587253921 | import dgl
import dgl.function as fn
import dgl.nn.pytorch as dglnn
import torch
import torch.nn as nn
import torch.nn.functional as F
def disable_grad(module):
for param in module.parameters():
param.requires_grad = False
def _init_input_modules(g, ntype, textset, hidden_dims):
# We initialize the ... | dmlc/dgl | examples/pytorch/pinsage/layers.py | layers.py | py | 6,164 | python | en | code | 12,455 | github-code | 54 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.