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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
70601213475 |
from typing import Any
from django import http
from django.shortcuts import render, redirect
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from common.models import Insumo, Proveedor
from django.views import View
from django.views.decorators.csrf import csrf_... | leanmsan/proyecto-ITSE | NeumaticosSgo/insumos/views.py | views.py | py | 2,674 | python | es | code | 2 | github-code | 1 |
32497373603 | # https://leetcode.com/problems/middle-of-the-linked-list/
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
first, second = head, he... | augini/algorithms_ds | Leetcode/876.py | 876.py | py | 452 | python | en | code | 2 | github-code | 1 |
5593742103 | tags = set()
fo = open("a_example.txt","r")
photos = []
for i in fo:
photos.append(i)
photos = [photos[0]]+[photos[1]]+[photos[2]+photos[3]]+[photos[4]]
photos[2] = "H 3 selfie smile garden\n"
# print(photos)
for i in range(len(photos)):
x = len(photos[i])
photos[i] = photos[i][:x-1]
n = int(photos[0])
n =... | mayank-kumar-giri/Competitive-Coding | HashCode/test.py | test.py | py | 1,649 | python | en | code | 0 | github-code | 1 |
72919968353 | from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import (
IndexView,
AutorListCreateAPIView,
AutorRetrieveUpdateDestroyAPIView,
CategoriaListCreateAPIView,
CategoriaRetrieveUpdateDestroyAPIView,
EditorialListCreateAPIView,
EditorialRetrieveU... | aaronbarra040998/biblioteca-v | proyecto/api/urls.py | urls.py | py | 1,291 | python | en | code | 0 | github-code | 1 |
16540656841 | import os
import shutil
import random
import glob
def mv_file(img, num) :
img_path_list = os.listdir(img)
#img_path_list = glob.glob(f"{img}/*." + img_ext)
random.shuffle(img_path_list)
if num > len(img_path_list):
print('Length need to be small than:', len(img_path_list))
... | gongzir1/yolo_fl | data_splitter_new.py | data_splitter_new.py | py | 1,345 | python | en | code | 0 | github-code | 1 |
32668845053 | #!/usr/bin/python3
#-*- coding: utf-8 -*-
#-*- author:zhangjiao -*-
import random
import json
from ATM.user import User
from ATM.card import Card
from ATM.user import User
# from day02.atm.card import Card
# from E.python.
class ATM:
userDict={}
islogin = None
@staticmethod
def welcome():
pri... | xiaoxiaozhang3/python3.6 | python/dem/ATM/atm.py | atm.py | py | 3,393 | python | en | code | 0 | github-code | 1 |
30714323241 | import random
import copy
class Osobnik:
def __init__(self, chromosom, waga = 0, wartosc = 0, procentNaKole = 0):
self.chromosom = chromosom
self.procentNaKole = procentNaKole
self.waga = waga
self.wartosc = wartosc
def __repr__(self) -> str:
return "CH = " + str(self.chr... | zulux99/sztuczna-inteligencja | zad3.py | zad3.py | py | 4,047 | python | pl | code | 0 | github-code | 1 |
15876514759 |
import transformers
from utils import printf
import copy
class prompt:
def __init__(self, tokenizer, max_len, add_eos=True):
self.tokenizer = tokenizer
self.max_len = max_len
self.add_eos=add_eos
class instruct_prompt(prompt):
prompt = (
"Below is an instruction that describes... | Facico/Chinese-Vicuna | prompt.py | prompt.py | py | 9,178 | python | en | code | 4,045 | github-code | 1 |
24922075531 | def astar(start, end):
# initialize queue and explored
priorityQueue = []
visited = {}
heapq.heappush(priorityQueue,
(0, start, None, None, 0)) # (cost, current node, parent node, action taken, parent heuristic)
# while there are still values in the queue
while priorityQueue... | aroy97/3D-Cave-Traversal | astar.py | astar.py | py | 1,553 | python | en | code | 0 | github-code | 1 |
29980155080 | import csv
import logging
import multiprocessing
import os
import pickle
import sys
import traceback
import cv2
import imutils
import imutils.contours
import numpy as np
from imutils.perspective import four_point_transform
import register_image
base_template = None
base_tables = None
DESIRED_HEIGHT = 779
DESIRED_WID... | tauseefahmed600/bubble-sheet-reader | app/bubble_sheet_reader.py | bubble_sheet_reader.py | py | 17,872 | python | en | code | 2 | github-code | 1 |
39008828046 | ###실습1~3
#1. 1~30의 값을 가진 리스트 생성
#2. 첫번째 값을 1000으로 변경
#3. 끝의 값을 3000으로 변경
###
nList = []
for i in range(1,31,1):
nList.append(i)
print("1:", nList)
nList[0] = 1000
print("2:", nList)
nList[-1] = 3000
print("3:", nList)
###실습 4~6
#4. 리스트 값에 31~40을 추가
#5. 리스트에서 100 이상인 값을 인덱스+1 값으로 변경
#6. 리스트에서 인덱스 ... | Patron102/main | 파이썬 과제/230329_54.py | 230329_54.py | py | 2,094 | python | ko | code | 2 | github-code | 1 |
73789734115 | import numpy as np
import cv2
import dlib
import torch
import torch.nn as nn
import torchvision.transforms as transforms
from torchvision import models
from PIL import Image
import pygame
device = torch.device('cpu')
num_classes = 4
path = 'epoch-99.pt'
classes = {'closed': 0, 'normal': 1, 'side': 2, 'yawn': 3}
model... | Nithya-Satheesh/Drowsiness-And-Distraction-Detection-System | real-time.py | real-time.py | py | 3,070 | python | en | code | 1 | github-code | 1 |
22527795129 | from pyteal import *
""" Project Program """
def approval_program():
### GLOBAL VARIABLES ###
organizer_key = Bytes("organizer")
goal_amount_key = Bytes("goal")
creation_time_key = Bytes("creation")
destruction_time_key = Bytes("destruction")
destruction_time_enabled_key = Bytes("dest_allowed")
closes_after_... | Cryptonate-ACJTT/cryptonate-server | src/contracts/pyTEAL/project.py | project.py | py | 4,676 | python | en | code | 0 | github-code | 1 |
29483005334 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/6/6 下午7:58
# @Author : Jame
# @Site :
# @File : feature_engineering.py
# @Software: PyCharm
import pandas as pd
path1= r""
path2= r""
train = pd.read_csv(path1)
test1 = pd.read_csv(path2)
train.loc[train['label']==-1,'label'] = 0
test1['label'... | jame-zhang/2018_tencent_ad_algo | lgb_libsvm/feature_engineering/feature_engineering.py | feature_engineering.py | py | 6,766 | python | en | code | 4 | github-code | 1 |
5606702695 | from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import *
from future.utils import with_metaclass
import copy
import types
import wizzat.decorators
from wizzat.pghelper import *
from wizzat.util import set_defaults
__all__ = [
'DBTable',
'DBTableError',
'D... | wizzat/wizzat.py | wizzat/dbtable.py | dbtable.py | py | 13,346 | python | en | code | 6 | github-code | 1 |
15436207408 | from flask import Flask, jsonify, request
import cv2
import tensorflow as tf
import keras
import numpy as np
import requests
from labels.dog_label import dog_label
app = Flask(__name__)
MODEL_PATH = "./models/loaded_2.h5"
app.run(host='0.0.0.0', port=5000)
def load_model():
loaded_model = keras.models.load_mo... | devRangers/smg-ana-prototype | data/app.py | app.py | py | 1,309 | python | en | code | 0 | github-code | 1 |
36307774911 | from twilio.rest import Client
import os
def send(body='Some body', to=''):
# Your Account Sid and Auth Token from twilio.com/console
# DANGER! This is insecure. See http://twil.io/secure
account_sid = os.getenv("sid")
auth_token = os.getenv("token")
sender = os.getenv("from_")
recepient = os.g... | gmihov001/Queue-Mgmt-API-Flask | src/sms.py | sms.py | py | 514 | python | en | code | 0 | github-code | 1 |
30329408627 | import sqlite3
from flask import Flask, render_template, jsonify, request, json
from flask_socketio import SocketIO, send, emit, join_room
import paho.mqtt.publish as publish
import time
import datetime
import pygal
from random import random
# import json
# import eventlet
# eventlet.monkey_patch()
app = Flask(__name_... | Niraj-Kamdar/IoT-Dashboard | myapp.py | myapp.py | py | 8,315 | python | en | code | 2 | github-code | 1 |
32271389388 | import os
import azure.cognitiveservices.speech as speechsdk
def recognize_from_microphone():
# This example requires environment variables named "SPEECH_KEY" and "SPEECH_REGION"
speech_key = 'bb8bd625ed4e4a4ba60392152e02eb7c'
speech_region = 'eastus'
speech_config = speechsdk.SpeechConfig(subscription... | AlexOlivaresP/Transcriptor-RPC | voz.py | voz.py | py | 1,468 | python | en | code | 0 | github-code | 1 |
18972801594 | import telegram
import telegram.ext
import time
import threading
# custom library
from handler import SuperHandler
import callback
import exrates
# token of the bot. For individual use, you should enter yous
TOKEN = open('token.txt', mode='r').read()
# add functionality to the bot
def create_updater(token) -> telegr... | AndrewChmutov/TelegramWallet | main.py | main.py | py | 1,115 | python | en | code | 2 | github-code | 1 |
16565100780 | from os import path
from setuptools import setup, find_packages
from powerdataclass.VERSION import __VERSION__
package_name = 'powerdataclass'
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
na... | arishpyne/powerdataclass | setup.py | setup.py | py | 1,210 | python | en | code | 9 | github-code | 1 |
24328717943 | """Read NestedSamples from UltraNest results."""
import os
import json
from anesthetic.samples import NestedSamples
def read_ultranest(root, *args, **kwargs):
"""Read UltraNest files.
Parameters
----------
root : str
root name for reading files in UltraNest format, i.e. the files
``<r... | handley-lab/anesthetic | anesthetic/read/ultranest.py | ultranest.py | py | 1,314 | python | en | code | 51 | github-code | 1 |
71631120355 | from utils import mock_fairseq
mock_fairseq() # noqa: E402
from tseval.qats import get_qats_train_data, evaluate_scoring_method_on_qats
from tseval.feature_extraction import get_all_vectorizers
def test_get_qats_train_data():
sentences, labels = get_qats_train_data(aspect='simplicity')
assert sentences.shape... | facebookresearch/text-simplification-evaluation | tests/test_qats.py | test_qats.py | py | 566 | python | en | code | 46 | github-code | 1 |
25515683214 | """Convert prediction of Network to .tei file and correct the _predict.txt file"""
from lxml import etree
import lxml.etree as ET
import time
import argparse
#file_network_input = open("/home/svogel/projects/textimaging/rnng-master/Franz_Kafka_Das_Urteil_graminput.txt", "r") #Thomas_Mann_Der_Tod_in_Venedig_Neu_gramin... | Psarpei/Recognition-of-logical-document-structures | RNNG/scripts/prediction_to_XML.py | prediction_to_XML.py | py | 8,612 | python | en | code | 5 | github-code | 1 |
38684301063 | import cv2
import numpy as np
from PIL import Image, ImageOps, ImageTk, ImageFilter
def apply_median_filter(img, ksize):
# Apply the median filter
img = cv2.medianBlur(img, ksize)
# Convert the NumPy array to a PIL image
# pil_img = Image.fromarray(img)
# return pil_img
return img
def apply_... | nicole-kozhuharova/bachelorArbeit | venv/bachelorArbeit/algorithm/functions/medianFilterFunc.py | medianFilterFunc.py | py | 1,449 | python | en | code | 0 | github-code | 1 |
31944377025 | from PyQt5.QtCore import QCoreApplication
from PyQt5.QtGui import QColor
from qgis.PyQt.Qt import QVariant
from qgis.core import (QgsProcessing,
QgsFeatureSink,
QgsProcessingAlgorithm,
QgsProcessingParameterFeatureSource,
QgsPro... | dsgoficial/Ferramentas_Producao | modules/qgis/processingAlgs/spellCheckerAlg.py | spellCheckerAlg.py | py | 6,299 | python | en | code | 2 | github-code | 1 |
73078421474 | from sklearn.decomposition import KernelPCA
from matplotlib import pyplot as plt
import pandas as pd, numpy as np, os
import pywt
base_path = os.path.dirname(os.path.abspath(__file__))
data_path = os.path.join(base_path, "../data/12053002165")
output_path = os.path.join(base_path, "../data/solar")
if not os.... | apie0419/solar_power_prediction | hourahead/process_data.py | process_data.py | py | 3,653 | python | en | code | 3 | github-code | 1 |
959238114 | import argparse
import os
import torch
import torchvision as tv
from at_learner_core.utils import transforms
from at_learner_core.configs import dict_to_namespace
from at_learner_core.utils import transforms as transforms
from at_learner_core.utils import joint_transforms as j_transforms
from at_learner_core.utils imp... | AlexanderParkin/CASIA-SURF_CeFA | rgb_track/configs_final_exp.py | configs_final_exp.py | py | 7,365 | python | en | code | 149 | github-code | 1 |
29111556856 | from app.main.constants import DISTANCE_TO_NEIGHBOURS
from app.main.models.adjacent_polygon import Adjacent_Polygon
from app.main.models.polygon import Polygon
from app.main.services.extraction_helper import ExtractionHelper
class NeighbourExtraction():
def get_neighbours(self, polygons: list, this_polygon: Polyg... | nchalimba/building-plan-processor | app/main/services/neighbour_extraction.py | neighbour_extraction.py | py | 1,296 | python | en | code | 0 | github-code | 1 |
24879624643 | from pydantic import ValidationError
from saltapi.web.schema.common import ProposalCode
import pytest
@pytest.mark.parametrize("code", ["2021-1-SCI-001", "2022-2-ORP-007", "2023-1-DDT-001"])
def test_valid_proposal_code(code: str):
assert ProposalCode.validate(code) == code
@pytest.mark.parametrize(
"inval... | saltastroops/salt-api | tests/schema/test_proposal_code_input.py | test_proposal_code_input.py | py | 920 | python | en | code | 0 | github-code | 1 |
23718020693 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 15 08:02:43 2018
@author: mfromano
"""
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 2 10:31:21 2018
@author: mfromano
"""
# run hua-an's motion correction
import motion_correction2
import scipy.io as sio
import numpy as... | HanLabBU/micro-control-final | matlab_src/bin/hua-an_code/test_motion_correct_results.py | test_motion_correct_results.py | py | 614 | python | en | code | 1 | github-code | 1 |
35773688788 | from protobuf.message import Message
from protobuf.property import Property
from protobuf.typed import TYPES, WIRE_TYPES
from protobuf.ProtobufSyntaxError import ProtobufSyntaxError
PRIORITIES = {
'required',
'optional',
'repeated'
}
def _read_file(filename):
with open(filename) as f:
code = ... | vtarasovaaa/protobuf | protobuf/pb_parser.py | pb_parser.py | py | 4,316 | python | en | code | 0 | github-code | 1 |
25726834679 | from crawlerbots.facebookCrawlerBot import main as fbMain
# from crawlerbots.kakaostoryCrawlerBot import main as kksMain
# from crawlerbots.instagramCrawlerBot import main as instaMain
from crawlerbots.db_mysql_select import DatabaseConnection
from self import self
page = DatabaseConnection()
facebook_list = []
kakaoS... | Tenspace/SCI_2019 | crawlerbots/crawler_starter_origin_20190221.py | crawler_starter_origin_20190221.py | py | 581 | python | en | code | 0 | github-code | 1 |
12194770935 | import nextcord
from nextcord.ext import commands, tasks
import openai
import os
import re
from langdetect import detect
from config import TRANSLATE_CHANNEL
# Initialize the OpenAI API
openai.api_key = os.environ['Key_OpenAI']
def is_english(text):
try:
return detect(text) == 'en'
except:
ret... | CryptoAutistic80/Nextcord-Cog-Bot | cogs/translator.py | translator.py | py | 4,573 | python | en | code | 1 | github-code | 1 |
41898385777 | import os
from astropy.io import fits
import numpy as np
from . import db_indicies as dbi
from . import load_fits
# Indicies of fits file arrays2018/180625/101501_180625.1129.fits
FLG_IND = 4
TEL_DIV_IND = 5
def write_back_tellurics(spectrum_path, model, pwv, order_wv_ranges, shards):
# 1: Open file
f = fits.o... | chrisleet/selenite | selenite/load_store/write_fits.py | write_fits.py | py | 3,256 | python | en | code | 0 | github-code | 1 |
22136190314 | # Define a function factorial() with one input n. [The default value of n needs to
# be 5]. Use the factorial() function and other inbuilt functions to find the
# maximum between the following:
# 1. 5!+3!-21 and 2!+4!+12
# 2. 26!+31! and 22!+35!
# 3. 21!+34!-15! and 31!+27!-19!
# Hint: you can use the min() and max() i... | pandey-ankur-au17/Python | coding-challenges/week04/day01/ccQ1.py | ccQ1.py | py | 716 | python | en | code | 0 | github-code | 1 |
18408969522 | import unittest
from astar import *
class TestAStar(unittest.TestCase):
def test_heuristic(self):
h_test = h((5, 4), (10, 7))
h2_test = h((10, 3), (100, 20))
self.assertEqual(h_test, 8)
self.assertEqual(h2_test, 107)
if __name__ == '__main__':
unittest.main()
| AlexanderAmaechi/ProjektPY21-10 | test_heuristic.py | test_heuristic.py | py | 306 | python | en | code | 0 | github-code | 1 |
73021062754 | from tkinter import *
from PIL import ImageTk, Image
root = Tk()
root.title('leer coderen bij Codemy.com')
root.iconbitmap('c:/gui/ ')
my_img1 = ImageTk.PhotoImage(Image.open("IMG_1136.png"))
my_img2 = ImageTk.PhotoImage(Image.open("IMG_2004.png"))
#image_list = [my_img1, my_img2]
#my_label = Label(image=my_img1)
... | herucara/python-2021 | kijken.py | kijken.py | py | 743 | python | en | code | 0 | github-code | 1 |
40964213255 | #!/usr/bin/env python3
from itertools import permutations
def count_sums(l: list[int], target, i: int=0, sum_=0):
global counter
if sum_ == target:
counter += 1
return
if sum_ < target and i < len(l):
# Try to add the current element and already move our index to the next
... | dubgeiser/aoc2015 | 17/1.py | 1.py | py | 706 | python | en | code | 0 | github-code | 1 |
73884105633 | import pandas as pd
import numpy as np
import time
# Doc du lieu VCB 2009->2018
dataset_train = pd.read_csv('5000000 BT Records.csv')
training_set = dataset_train.iloc[:, 1:2].values
# print(training_set)
no_of_sample = len(training_set)
print(no_of_sample)
WINDOW_SIZE = 7 # 7 ngay
HORIZON_SIZE = 1 # 1 ngay
start =... | thangnch/MIAI_RNN_Data_Preparing | load_new.py | load_new.py | py | 947 | python | en | code | 0 | github-code | 1 |
3262660902 | import tkinter as tk
from tkinter import ttk
from chessengine import Chess
from dbmanager import ChessDatabase
class ChessGUI:
"""Responsible for handling the Tkinter GUI."""
def __init__(self):
self.init_window = tk.Tk()
self.init_window.geometry("220x250")
# Handling white's widget... | EamonnER/Pygame-Chess | gui.py | gui.py | py | 6,407 | python | en | code | 0 | github-code | 1 |
10453439788 | import torch.utils.data as data
import PIL.Image as Image
import os
import numpy as np
import torch
from torch.utils.data import DataLoader
from torch import autograd, optim
from torchvision.transforms import transforms
from networks.cenet import CE_Net_
import cv2
import nibabel as nib
import time
x_transforms = tra... | 18792676595/U-Net-for-liver-tumor-segmentation | nii_to_endnii.py | nii_to_endnii.py | py | 4,742 | python | en | code | 2 | github-code | 1 |
19953368465 | import streamlit as st
from streamlit_extras.switch_page_button import switch_page
def add_eyewitness():
st.header("Add an eyewitness")
name = st.text_input("Enter the name of the eyewitness", key='name')
desc = st.text_input("Enter a description of the witness", key = 'desc')
pic = st.file_upload... | mopasha1/interrogAIte | functions.py | functions.py | py | 2,674 | python | en | code | 0 | github-code | 1 |
14416409655 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 19 23:05:06 2023
@author: hp
"""
#Write A Python Program To Get Number To Check, Whether It Is Positive OR Negative
n=int(input("Enter a number : "))
if(n>0):
print("Positive Number")
else:
print("Negative Number") | AiswaryaRamesan/Python | positive negative.py | positive negative.py | py | 271 | python | en | code | 0 | github-code | 1 |
32816595902 | from account.models import Account, EmailAddress
from mozilla_django_oidc.auth import OIDCAuthenticationBackend, default_username_algo
class PinaxOIDCAuthenticationBackend(OIDCAuthenticationBackend):
def create_user(self, claims):
"""
Create a user account for the given claims.
This meth... | deep-philology/DeepVocabulary | deep_vocabulary/auth.py | auth.py | py | 2,668 | python | en | code | 3 | github-code | 1 |
6900603378 | import os
import jinja2
import yaml
def load_config(config_directory, env_file, config_env_overrides=None):
if config_env_overrides is None:
config_env_overrides = {}
with open(os.path.join(config_directory, env_file)) as env_fd:
config_env = yaml.load(env_fd)
for key, value in config_e... | vvgolubev/blabbermouth | blabbermouth/util/config.py | config.py | py | 952 | python | en | code | 0 | github-code | 1 |
7414751146 | from __future__ import unicode_literals, print_function, division
__author__ = "mozman <mozman@gmx.at>"
from .compatibility import is_stream, StringIO
from .filemanager import FileManager
class ByteStreamManager(FileManager):
def __init__(self, buffer=None):
if is_stream(buffer):
self._zipfi... | T0ha/ezodf | ezodf/bytestreammanager.py | bytestreammanager.py | py | 835 | python | en | code | 61 | github-code | 1 |
19707782223 | from setuptools import setup, find_packages
import os
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as README:
DESCRIPTION = README.read()
with open('requirements.txt') as f:
required = f.read().splitlines()
setup(
name='OpenReader',
version='0.1',
packages = find_packages(),
... | craigsonoffergus/OpenReader | setup.py | setup.py | py | 580 | python | en | code | 1 | github-code | 1 |
10989914554 | from typing import Tuple, Optional
import torch
from torch import nn
from towhee.models.max_vit.max_vit_block import MaxViTStage
from towhee.models.max_vit.configs import get_configs
from towhee.models.utils import create_model as towhee_model
class MaxViT(nn.Module):
"""
Implementation of the MaxViT propose... | towhee-io/towhee | towhee/models/max_vit/max_vit.py | max_vit.py | py | 7,262 | python | en | code | 2,843 | github-code | 1 |
8702203975 | import streamlit as st
import altair as alt
import inspect
from vega_datasets import data
@st.experimental_memo
def get_chart_67593(use_container_width: bool):
import altair as alt
import pandas as pd
data = pd.DataFrame([dict(id=i) for i in range(1, 101)])
person = (
"M1.7 -1.7h-0.8c... | streamlit/release-demos | 1.16.0/demo_app_altair/pages/143_Isotype_Grid.py | 143_Isotype_Grid.py | py | 1,562 | python | en | code | 78 | github-code | 1 |
7774993339 | def rsp(mine, yours):
allowed = ['가위', '바위', '보']
if mine not in allowed:
raise ValueError("'가위', '바위', '보' 가운데 하나의 값만 입력받을 수 있습니다.")
if yours not in allowed:
raise ValueError("'가위', '바위', '보' 가운데 하나의 값만 입력받을 수 있습니다.")
# rsp('가위','바')
# try-except 문을 넣어서 예외를 잡아내면 프로그램이 종료되지 않는다.
try:
rs... | EscFrog/Try-helloworld-python | raise.py | raise.py | py | 918 | python | ko | code | 0 | github-code | 1 |
13698381326 | """djangoProject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class... | jvallee/EmailTemplate | djangoProject/djangoProject/urls.py | urls.py | py | 2,252 | python | en | code | 1 | github-code | 1 |
22858584426 | #求菲波那切数列
# 1 1 2 3 5 8 13 21 34 55
'''用函数实现'''
def fib1(n):
stack=[]
if n == 0 or n == 1:
return 1
else:
stack.append(1)
stack.append(1)
for i in range(2,n):
stack.append(stack[i-1]+stack[i-2])
return stack
print (fib1(8))
def fib2(n):
count=0
a,b =0,1
... | linuxsed/python_script | fib_sequence.py | fib_sequence.py | py | 1,012 | python | en | code | 0 | github-code | 1 |
35710766990 | from YNABpy import Parser
YNAB_DATA_FILE = "F:/Development/PortableGit/YNABpy/YNABpy/test_budget.ynab3"
yparser = Parser.YNAB3_Parser(YNAB_DATA_FILE)
transaction_lister = yparser.get_transaction_lister()
category_lister = yparser.get_category_lister()
# test filtering transaction list based on category name substrin... | MarkNenadov/YNABpy | examples/filtering.py | filtering.py | py | 2,288 | python | en | code | 3 | github-code | 1 |
34139314803 | class Solution:
def isValid(self, s: str) -> bool:
newStack = []
dic = {")": "(", "}": "{", "]":"["}
for x in s:
if x in dic:
if newStack and newStack[-1] == dic[x]:
newStack.pop()
else:
return False... | rawanelbanaa/ProblemSolving_LeetCode | 0020-valid-parentheses/0020-valid-parentheses.py | 0020-valid-parentheses.py | py | 437 | python | en | code | 0 | github-code | 1 |
5638788836 | #!/usr/bin/python
"""
starter code for exploring the Enron dataset (emails + finances)
loads up the dataset (pickled dict of dicts)
the dataset has the form
enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }
{features_dict} is a dictionary of features associated with that person... | Nasafato/EnronEmailAnalysis | datasets_questions/explore_enron_data.py | explore_enron_data.py | py | 3,809 | python | en | code | 0 | github-code | 1 |
23869949206 | def heapsort(arr):
"""
Sorts an array using the heapsort algorithm.
Parameters:
arr (list): The array to be sorted.
"""
n = len(arr)
# Build a max heap
for i in range(n // 2 - 1, -1, -1):
heap(arr, n, i)
# Move the largest element to the end and heapify the remaining e... | pupperemeritus/dsa-and-daa | heapsort.py | heapsort.py | py | 1,541 | python | en | code | 0 | github-code | 1 |
3237033272 | # -*- coding: utf-8 -*-
# Traffic Data Process Automatically
# Xin Meng
# 2015.11.02
# This script is used for process the traffic txt file.
# 1. Set the configure
# 2. Run this script and get the result.
import csv
import os
import logging
import re
import utils.network
__author__ = 'xin'
# configuration variable
#... | xinmeng1/MobileBotnetAnalysisLab | old/TrafficDataProcessAuto.py | TrafficDataProcessAuto.py | py | 37,434 | python | en | code | 3 | github-code | 1 |
40068698885 | from django.shortcuts import render, redirect
from .forms import ContatoForm, ProdutoModelForm, ClienteModelForm
from django.contrib import messages
from .models import Cliente, Produto
# Create your views here.
def index(request):
prod = Produto.objects.all()
context ={
'prod': prod
}
retur... | P4J3/django2 | core/views.py | views.py | py | 2,205 | python | pt | code | 0 | github-code | 1 |
8932247394 | #!/usr/bin/python3
from fdactuator import FdActuator
from fddevice import FdDevice
class LsSv004ig5a_1(FdActuator):
def __init__(self, connInfo):
self.mqttTopic = 'speed'
self.on = False
super().__init__(connInfo)
def writeFreq(self, slaveId, value): # 주파수 설정
act = {'atype': 'modbus', 'slaveid':... | boninlab/smartFeeder | feeder/actuators/lssv004ig5a_1.py | lssv004ig5a_1.py | py | 1,141 | python | en | code | 0 | github-code | 1 |
73457122595 | import random
import subprocess as sub
import time
samples = 100
u = 10 ** 9
n = 100
while n <= 1000000:
stabil = 0
totalTime = 0
for i in range(0, samples):
houses = random.sample(range(0, u), n)
houses.sort()
start = time.time()
p = sub.Popen("./g", stdin=sub.PIPE, stdo... | Lucpp101010/BwInf39-Runde2 | Aufgabe3/Programme/Beispiele/tester.py | tester.py | py | 842 | python | en | code | 1 | github-code | 1 |
10924482819 | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.support.ui import WebDriverWait
import time
def no_delay_output():
"""
... | logonmy/spider-mz | utils/selenium_utils.py | selenium_utils.py | py | 2,840 | python | en | code | 0 | github-code | 1 |
17422403783 | import json
from glob import glob
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Union
import numpy as np
import torch
import yaml
from PIL import Image
from sklearn.model_selection import train_test_split
from termcolor import colored
from torch.utils.data import Dataset
from torchvi... | GerasimovIV/kvasir-seg | src/data_utils/dataset.py | dataset.py | py | 8,726 | python | en | code | 0 | github-code | 1 |
12119523482 | #!/usr/bin/env pypy
import math
import fileinput
maxp = int(math.pow(10, 6))
maxn = math.pow(10, 18)
def gen_primes():
primes = []
p = [False for _ in range(maxp)]
for i in range(2, maxp, 1):
if p[i]:
continue
primes.append(i)
for j in range(i, maxp, i):
p... | i2tsuki/competition | atcoder/abc250/abc250.py | abc250.py | py | 706 | python | en | code | 0 | github-code | 1 |
29574600002 | def series(N:int):
series_sum = 0
for i in range(1, N+1):
series_sum = series_sum + i*i
return series_sum
if __name__ == '__main__':
print("Problem 4")
print("ID: 2019-2-60-025")
print()
n = int(input("Enter a number: "))
if n <= 0:
while True:
n = int(inp... | TanvirMobasshir/CSE303 | LAB/lab_1/4.py | 4.py | py | 449 | python | en | code | 0 | github-code | 1 |
36658809155 | import tensorflow as tf
from nmt import rnn_utils
from nmt.encoders.abstract_encoder import EmbeddingEncoder
class UniRNNEncoder(EmbeddingEncoder):
def encode(self, inputs, length, mode, params=None):
default_params = self.default_config()
if params:
default_params.update(**params)
... | naivenlp/naivenmt-legacy | nmt/encoders/uni_encoder.py | uni_encoder.py | py | 1,804 | python | en | code | 9 | github-code | 1 |
71508832995 | fname = "words.txt"
try:
handle = open(fname,"r")
words = []
while True:
content = handle.readline()
if content == "":
break
else:
words.append(content)
handle.close()
except IOError:
print("No such file!")
words.sort()
print("Words in an alphabetic... | jumpalottahigh/python-viope-practice | ex9-3.py | ex9-3.py | py | 360 | python | en | code | 0 | github-code | 1 |
5130368081 | # !/usr/bin/env python.
# -*- coding: utf-8 -*-
import os
import glob
import fiona
import matplotlib
import pandas as pd
import numpy as np
import wradlib as wrl
import matplotlib.pyplot as plt
from matplotlib import path
from osgeo import osr
from pathlib import Path
from matplotlib.colors impor... | AbbasElHachem/extremes | _57_plot_radar_events_BW_.py | _57_plot_radar_events_BW_.py | py | 5,414 | python | en | code | 0 | github-code | 1 |
72558407395 | import uuid
from abc import ABC, abstractmethod
from decimal import Decimal
from typing import List, Optional, Dict
from pydantic import BaseModel, Field, computed_field
from cache.store import get_provider_html
from models.models import ProviderVehiclesRequest, ProviderStoreItem
class Calculator(ABC, BaseModel):
... | martijnboers/WelkeDeelauto | backend/models/interface.py | interface.py | py | 1,563 | python | en | code | 0 | github-code | 1 |
8182815992 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
% EEE6230- Scientific Software Development for Biomedical Imaging
% Project 2:: Programming Lab 2
"""
#%% import required libraries
import numpy as np
#%% part 1: Householder reduction to bidiagonal form
def householder_transformation(b, k):
'''
Arguments:
... | CWright96/EEE6230-project-2 | sol_project2_lab2.py | sol_project2_lab2.py | py | 2,838 | python | en | code | 0 | github-code | 1 |
34554021174 | import beyond.Reaper
import beyond.Screen
@ProgramStart
class Main(Screen):
def Setup(o, e):
e.Title("Reaper Transport Example")
with e.Horizontal():
e.Stretch()
e.Button("Play")
e.Size(200, 200)
e.Stretch()
e.Button("Stop")
e.Size(200, 200)
e.Stretch()
def ... | Samelot/Reaper | beyond Python V26/Examples Reaper/Transport.py | Transport.py | py | 421 | python | en | code | 12 | github-code | 1 |
26357836135 | import os, sys, subprocess, time
import util
thisDir = os.path.dirname(os.path.realpath(__file__))
def osSys(p_input, p_display=True):
if p_display:
util.message("# " + p_input)
rc = os.system(p_input)
return rc
def exit_rm_backrest(msg):
util.message(f"{msg}", "error")
osSys("./nc remo... | pgEdge/nodectl | src/backrest/install-backrest.py | install-backrest.py | py | 2,840 | python | en | code | 7 | github-code | 1 |
3516908942 | import sys;input=sys.stdin.readline
N=int(input())
stack=[]
s=0
for _ in range(N):
i=input().rstrip().split()
if i[0]=='push':
stack.append(i[1])
s+=1
elif i[0]=='pop':
if s!=0:
print(stack.pop())
s-=1
else:
print(-1)
elif i[0]=='size'... | leezzangmin/pythonBOJ | 파이썬/10828.py | 10828.py | py | 539 | python | en | code | 0 | github-code | 1 |
11936442081 | print("hello python")
print("你好世界")
age = 23
message = "Happy " + str(age) + "rd Birsrthday !"
print(message)
row = 1
while row <= 9:
col = 1
while col <= row:
print("%d*%d=%d" % (col, row, col * row ), end="\t")
col += 1
print("")
row += 1 | nielei-26/hello-word | python基础/01_Python基础/hm_01_hello.py | hm_01_hello.py | py | 280 | python | en | code | 0 | github-code | 1 |
33179678645 | # Importing Module
from pygame import mixer
import customtkinter, tkinter
from PIL import Image
import eyed3
import os
mixer.init()
# Variables
sList = []
musicFolder = "/home/bir/Music/"
current = ''
start = False
fname = "assets/notfound.jpg"
# Functions
def changeThumb():
global fname, playImg, mImg
audio... | birgrewal/Music-Player-Python | main.py | main.py | py | 3,821 | python | en | code | 1 | github-code | 1 |
41035595174 | """
Debug ORMAdapter calls within ORM runs.
Demos::
python tools/trace_orm_adapter.py -m pytest \
test/orm/inheritance/test_polymorphic_rel.py::PolymorphicAliasedJoinsTest::test_primary_eager_aliasing_joinedload
python tools/trace_orm_adapter.py -m pytest \
test/orm/test_eager_relations.py::L... | sqlalchemy/sqlalchemy | tools/trace_orm_adapter.py | trace_orm_adapter.py | py | 6,124 | python | en | code | 8,024 | github-code | 1 |
33912908185 | #! python3
# from itertools import *
from decimal import Decimal
from copy import copy
from math import floor
from math import sqrt
import sys
GetNthTriangleNumber = lambda n: n*(n+1)/2
def GetDivisors(n):
divisors = []
start = floor(n/2)+1
while start > 0:
if not n%start:
divisors.ap... | Demonslyr/ProjectEuler | Problem12/Problem12.py | Problem12.py | py | 1,251 | python | en | code | 0 | github-code | 1 |
10002081821 | import ipv6_utils
import log
from static import OF_TABLE_NUM
from static import WLAN_IFACE
from static import GW_IFACE
from switch import OFRule
from switch import Switch
from switch import Link
from switch import AccessPointConf
from switch import GatewayConf
from event import *
# End import from iJOIN solution fil... | ODMM/openflow-dmm | nmm/nmm.py | nmm.py | py | 12,501 | python | en | code | 3 | github-code | 1 |
42152249060 | """
Define commonly used dialogs.
"""
import ceGUI
import cx_Exceptions
import cx_Logging
import os
import wx
__all__ = [ "AboutDialog", "PreferencesDialog", "SelectionListDialog",
"SelectionCheckListDialog", "SelectionTreeDialog" ]
class AboutDialog(ceGUI.Dialog):
baseSettingsName = "w_About"
c... | anthony-tuininga/cx_PyGenLib | ceGUI/CommonDialogs.py | CommonDialogs.py | py | 10,197 | python | en | code | 3 | github-code | 1 |
37774857793 | import argparse
import sys
from os.path import dirname, realpath
sys.path.append(dirname(dirname(realpath(__file__))))
import project.data.dataset_utils as data_utils
import project.models.model_utils as model_utils
import project.training.train_utils as train_utils
import torch.nn as N
import os
import torch
import da... | Sanger2000/Predicting-Lung-Cancer-Disease-Progression-from-CT-reports | scripts/main.py | main.py | py | 5,433 | python | en | code | 0 | github-code | 1 |
24013966504 | # contains function which returns True if the value is in the array, return False otherwise
# First, the function loops through the range of the length of the array
# Then, comparing the value to each value of the elements using .get method
# Return True if it matches any value within the array, it will return False ot... | Mahalinoro/python-ds-implementations | array/helper_functions.py | helper_functions.py | py | 1,971 | python | en | code | 0 | github-code | 1 |
12446665048 | import math
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
df = pd.read_csv('S&P500.csv')
#Select date variable
data = df.filter(['Adj Close'])
data = data.values
#Get the number of rows t... | Susannnn/Stock-Price-Prediction | LR.py | LR.py | py | 1,369 | python | en | code | 0 | github-code | 1 |
43758227481 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import os.path as osp
from os.path import join as pjoin
import numpy as np
# from distutils import spawn
# run: pip install easydict
from easydict import EasyDict as edict
__C = edict()
# get config ... | InnerPeace-Wu/imaterialist_challenge-furniture | lib/config.py | config.py | py | 3,576 | python | en | code | 2 | github-code | 1 |
234780590 | import json
import pickle
import time
from hashlib import sha256
# Block class
# Block is a class that contains the data and the hash of the previous block
# The hash of the previous block is used to link the blocks together
# The hash of the block is used to verify the integrity of the chain
# We plan to use the block... | huangjien/datachain | blockchain.py | blockchain.py | py | 4,690 | python | en | code | 0 | github-code | 1 |
27166856149 | import logging
from typing import List
import requests
from config import settings
from models.media import Media
class YouTubeService:
API_URL = 'https://www.googleapis.com/youtube/v3/'
def search_video(self, query: str) -> List[Media]:
search_url = self.API_URL + 'search'
search_params ... | pythrick/playlist-bot | src/services/youtube.py | youtube.py | py | 1,252 | python | en | code | 4 | github-code | 1 |
17087609247 | """
Author: Bradley Fernando
Purpose: Uses Netmiko to connect to devices directly instead of using the
plugin. Cisco devices also establish connections via SSH keys.
Usage:
python exercise3.py
Output:
cisco4#
cisco3#
nxos2#
arista2#
arista3#
pyclass@srx1>
arista1#
arista4... | bfernando1/nornir-automation | week7/exercise3/exercise3.py | exercise3.py | py | 716 | python | en | code | 1 | github-code | 1 |
38722585148 | import os
import pandas as pd
from tqdm import tqdm
from geopy.geocoders import Nominatim
loc_app = Nominatim(user_agent="tutorial")
data_load_path = os.path.join('..', '..', 'data', 'train.csv')
data_dump_path = os.path.join('..', '..', 'data', 'df_for_plot_on_map.csv')
def recognize_location(location: str):
... | tedey-01/TweetsAnalyzer | utility_scripts/UI/plot_tools.py | plot_tools.py | py | 1,294 | python | en | code | 0 | github-code | 1 |
25544764801 | #this program is going to choose the students order of presentation in class
from random import shuffle
student1 = str(input("First student\n"))
student2 = str(input("second student\n"))
student3 = str(input("Third student\n"))
student4 = str(input("Forth student\n"))
lista = [student1, student2, student3, student4]
s... | flaviasilvaa/ProgramPython | 20.RandomInOrder.py | 20.RandomInOrder.py | py | 378 | python | en | code | 0 | github-code | 1 |
39998519394 | import unittest
import os
import shutil
import copy
import config as cfg
from analyzer import Analyzer
class ConfigTestCase(unittest.TestCase):
def test_analyzer(self):
ana1 = cfg.Analyzer(
Analyzer,
toto = '1',
tata = 'a'
)
# checking that the ana... | cbernet/heppy | heppy/framework/test_config.py | test_config.py | py | 2,810 | python | en | code | 9 | github-code | 1 |
11698570762 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 21 16:33:43 2022
@author: ppxmg2
"""
from expected_events_discrete_clustered import load_eff
import os
import numpy as np
def trapezium(x, y):
area = 0
for i in range(len(x) - 1):
area += (x[i+1] - x[i]) * (y[i] + 0.5*(x[i+1]-x[i])... | gortonm/PBH_microlensing_clustering | compute_smooth_mean.py | compute_smooth_mean.py | py | 1,393 | python | en | code | 0 | github-code | 1 |
38177141824 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# N-Queens
import sys
import copy
import time
# 行列作成
def make_matrix(n):
matrix = []
for x in range(n):
array = []
for y in range(n):
array.append(True)
matrix.append(array)
return matrix
# クイーンの範囲を無効化
def add_hand(hands, ... | hiromitsu-murakami/NQueens | nqueen.py | nqueen.py | py | 1,898 | python | en | code | 1 | github-code | 1 |
43472856046 | from django import forms
from datetime import *
from .models import Transaccion
from ..cliente.models import Cliente
from ..user.models import User
class TransaccionForm(forms.ModelForm):
# constructor
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.Me... | chrisstianandres/pagos | apps/transaccion/forms.py | forms.py | py | 2,002 | python | en | code | 0 | github-code | 1 |
1117221641 | import os
import re
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import convertapi
import cv2
import pytesseract
from pdfminer.high_level import extract_text
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from django.shortcuts import render
from .forms imp... | samarth-ty/pdf_parser | app/views.py | views.py | py | 5,994 | python | en | code | 0 | github-code | 1 |
12565261862 | # -*- coding: utf-8 -*-
import itertools
from Text_terms import *
from Symmetrical_summ import *
from Templates import *
# пересчет весов для предложений
def countFinalWeights(tf_weights, stemmed_text, stemmed_pnn):
weighted_terms = dict(tf_weights.items())
total_sents_in_text = stemmed_text.len
... | Svetych/aspect_ats_system | Auto_text_summ.py | Auto_text_summ.py | py | 12,128 | python | ru | code | 1 | github-code | 1 |
9788431256 | from django.core.exceptions import ValidationError
from datamodel import tests
from datamodel.models import Game, GameStatus, Move, Ganador
from logic.views import mueve_ia
class GameMoveTests(tests.BaseModelTest):
def setUp(self):
super().setUp()
def test1(self):
"""IA debe mover hacia adel... | vatojavier/psi | logic/tests_junio.py | tests_junio.py | py | 2,373 | python | en | code | 1 | github-code | 1 |
37376799747 | """
Reto6
Nombre: Patricio de Jesús Vargas Ramírez
Fecha: 08/02/2023
Descripción: Indice de masa corporal
"""
altura = float(input("Ingresa tu altura en metros: ")) # Ingresamos un valor
peso = float(input("Ingresa tu peso en kilogramos: ")) # Ingresamos un segundo valor
imc = peso / (altura ** 2) ... | PatricioVargasR/poo_vrpj_ti21 | Retos/reto6.py | reto6.py | py | 778 | python | es | code | 0 | github-code | 1 |
7531610125 | import torch
from torch.nn.utils.rnn import pad_sequence
from transformers4ime.data.logits_processor import ConstrainedLogitsProcessor
class PinyinGPTConcatLogitsProcessor(ConstrainedLogitsProcessor):
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, constraint_id) -> torch.FloatTensor:... | VisualJoyce/Transformers4IME | src/transformers4ime/data/logits_processor/pinyingpt_concat.py | pinyingpt_concat.py | py | 976 | python | en | code | 17 | github-code | 1 |
7459364873 | import sys
sys.stdin = open('input.txt')
def get_positon(direction, position):
shop_position = []
if direction == 1:
shop_position.append(position)
shop_position.append(height)
elif direction == 2:
shop_position.append(position)
shop_position.append(0)
elif direction ==... | coolihans/TIL | Algorithms/boj/boj-IM/2564_경비원/김무종.py | 김무종.py | py | 2,196 | python | en | code | 0 | github-code | 1 |
29973236400 | granja_A = [[10,22,33,45],
[11,12,12,13],
[14,15,77,43]]
granja_B = [[66,44,22,55],
[1,2,3,4],
[4,6,5,7]]
def sumar_granjas(m1,m2):
if len(m1) == len(m2) and len(m1[0]) == len(m2[0]):
m3 = []
for i in range(len(m1)):
m3.append([])
... | AndHak/Universidad-Semestre1-Python | Matricez5.py | Matricez5.py | py | 681 | python | en | code | 2 | github-code | 1 |
71860685793 | import os # for parsing directories
from trace import Trace
from app_checker import App_Checker
class App:
# defaults the ID of an app to the package name used as the directory name
# info only for not constructing whole thing, mostly to quickly get missing info of app only
def __init__(self, app_dir_arg, app_info... | annie-r/parse_Rico | code/app.py | app.py | py | 5,570 | python | en | code | 0 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.