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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
4758294095 | from typing import Dict, Any
import click
from .root import cli
#: Modules to import in interactive shell.
SHELL_MODULES = dict(
metric='gambit.metric',
kmers='gambit.kmers',
)
@cli.group(
name='debug',
hidden=True,
)
def debug_group():
"""Tools for debugging and testing."""
pass
def make_shell_ns(ctx) ->... | jlumpe/gambit | gambit/cli/debug.py | debug.py | py | 1,417 | python | en | code | 16 | github-code | 6 |
38386651149 | from network import WLAN
import machine
wlan = WLAN()
#wlan.init(mode=WLAN.AP, ssid='hello world')
#use the line below to apply a password
wlan.init(mode=WLAN.AP, ssid="hi", auth=(WLAN.WPA2, "12345678"))
print(wlan.ifconfig(id=1)) #id =1 signifies the AP interface
wlan = WLAN(mode=WLAN.STA_AP)
nets = ... | MatiasRaya/IoT-PS | Ejemplos/WIFI/wifi_create.py | wifi_create.py | py | 676 | python | en | code | 1 | github-code | 6 |
10383640973 | import unittest
import torch
from executorch.backends.xnnpack.test.tester import Tester
class TestSub(unittest.TestCase):
class Sub(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, x, y):
z = x - y
return z
def test_fp32_sub(self... | pytorch/executorch | backends/xnnpack/test/ops/sub.py | sub.py | py | 926 | python | en | code | 479 | github-code | 6 |
13321449104 | from airflow.models import Variable
from airflow.hooks.postgres_hook import PostgresHook
from rock.utilities import safeget, get_delta_offset, find_supported_fields
import requests
class ContentItemCategory:
def __init__(self, kwargs):
self.kwargs = kwargs
self.headers = {
"Authorizat... | CrossingsCommunityChurch/apollos-shovel | dags/rock/rock_content_item_categories.py | rock_content_item_categories.py | py | 5,576 | python | en | code | 0 | github-code | 6 |
42385607904 | # -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
class ChowSortPipeline(object):
def process_item(self, item, spider):
if item['name']:
item['name'] = ... | jasonhellwig/Chowhound_Recipe_Sorter | chow_sort/pipelines.py | pipelines.py | py | 480 | python | en | code | 1 | github-code | 6 |
13276332357 | from pathlib import Path
import os
import pandas as pd
from tensorboard.backend.event_processing.event_accumulator import EventAccumulator
# extract the data and save them in a CSV file
tb_path = Path("experiments") / "MPP" / "lohi" / "cdata" / "freesolv" / "lohi" / f"split_0" / "fold_0" / \
"model_0"
tb_fi... | kalininalab/DataSAIL | experiments/MPP/check.py | check.py | py | 891 | python | en | code | 4 | github-code | 6 |
40894632303 |
def sieve_of_Sundaram(n):
k = (n - 2) // 2 #only check up to the upper limit number as divided by 2
primes = 2
integers_list = [True] * (k + 1) #initialize a a membership list to the above limit, defaulting to true
for i in range(1, k + 1): #sets up a loop to from i and j (as equal) to to inc... | jmpilot/Project-Euler | eu_10.py | eu_10.py | py | 904 | python | en | code | 0 | github-code | 6 |
37946580665 | from sklearn import tree
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
from sklearn.naive_bayes import GaussianNB
import numpy as np
# Data and labels
# [Height, Weight ,Shoe Size]
X = [[181, 80, 44], [177, 70, 43], [160, 60, 38], [154, 54, 37... | vjgpt/gender_classification | gender_classify.py | gender_classify.py | py | 1,542 | python | en | code | 1 | github-code | 6 |
6166864226 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 6 13:11:44 2017
@author: Francesco
"""
import serial
import numpy as np
import time
PORT = "COM10"
BAUD = 115200
port = serial.Serial(PORT,BAUD,timeout=1)
START = 1
#BUNDLE SHAPE: |!|!|!|CH0_msb|CH0_lsb|ch1_msb|ch1_lsb|......|ch7_lsb|!|!|!|
NUM_CH... | FrancesoM/UnlimitedHand-Learning | python_side/read_bytes_over_serial.py | read_bytes_over_serial.py | py | 3,070 | python | en | code | 1 | github-code | 6 |
19638669363 | import matplotlib.pylab as plt
#import cv2
import numpy as np
import scipy as sp
from scipy.fftpack import fft, fftfreq, ifft, fft2, ifft2, fftshift, ifftshift
arbol=plt.imread("arbol.png")
#plt.imshow(arbol)
#transformada
base,altura=np.shape(arbol)
trans = fft2(arbol)
shi=fftshift(trans)
grashi=np.abs(shi)
fgraf... | saquijano/quijanoSantiagoHW3 | Fourier2D.py | Fourier2D.py | py | 1,691 | python | en | code | 0 | github-code | 6 |
41699189850 | #!/usr/bin/python3
import socket
#Creating socket object
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname() #Host is the server IP
port = 444 #Port to listen on
#Binding to socket
serversocket.bind((host, port))
#Starting TCP listener
serversocket.listen(3)
while True:
... | olivertepper/Python-Pentesting | TCP_Server.py | TCP_Server.py | py | 616 | python | en | code | 0 | github-code | 6 |
72078430587 | # %%
from datetime import date
import requests
from json import dump, load
# %%
class Search:
def __init__(self, keyword, url="http://localhost:8080/search", getResult=True):
self.keyword = keyword
self.url = url
self.resultMax = 2
self.infoBoxMax = 1
if getResult:
... | arromaljj/FinalProjectArromal | backend/backend_core/search.py | search.py | py | 2,723 | python | en | code | 0 | github-code | 6 |
74121185787 | __topotests_file__ = "bgp_comm_list_delete/test_bgp_comm-list_delete.py"
__topotests_gitrev__ = "4953ca977f3a5de8109ee6353ad07f816ca1774c"
# pylint: disable=wildcard-import,unused-import,unused-wildcard-import
from topotato.v1 import *
@topology_fixture()
def topology(topo):
"""
[ r1 ]
|
{ s1 }
... | opensourcerouting/topotato | test_bgp_comm-list_delete.py | test_bgp_comm-list_delete.py | py | 3,054 | python | en | code | 0 | github-code | 6 |
70283377149 | import streamlit as st
from collections import Counter
import nltk
from nltk.corpus import stopwords
import torch
from datasets import load_dataset
import time
import sys, os
import logging
from transformers import AutoTokenizer, AutoModel
#custom packages
sys.path.insert(1, os.getcwd())
from src import constant ... | geraldlab/semantic_search | Search.py | Search.py | py | 3,971 | python | en | code | 0 | github-code | 6 |
36060705055 | from config.log import log
from central.servidor_central import servidor_central
if __name__ == "__main__":
log()
# print('Informe o caminho do arquivo de configuração da sala 01:')
# sala_01 = input()
# print('Informe o caminho do arquivo de configuração da sala 02:')
# sala_02 = input()
sala... | AntonioAldisio/FSE-2022-2-Trabalho-1 | src/app_servidor_central.py | app_servidor_central.py | py | 428 | python | pt | code | 0 | github-code | 6 |
16205876862 | from typing import Any
from xdsl.dialects import scf
from xdsl.interpreter import (
Interpreter,
InterpreterFunctions,
PythonValues,
ReturnedValues,
impl,
impl_terminator,
register_impls,
)
@register_impls
class ScfFunctions(InterpreterFunctions):
@impl(scf.If)
def run_if(self, in... | xdslproject/xdsl | xdsl/interpreters/scf.py | scf.py | py | 1,102 | python | en | code | 133 | github-code | 6 |
20538164969 | # https://leetcode.com/problems/count-and-say
"""
Time complexity:- O(2^n)
Space Complexity:- O(n)
"""
class Solution:
def countAndSay(self, n: int) -> str:
# Base case: when n is 1, return "1"
if n == 1:
return "1"
# Recursively calculate the (n-1)-th term of the count-and-s... | Amit258012/100daysofcode | Day28/count_and_say.py | count_and_say.py | py | 1,129 | python | en | code | 0 | github-code | 6 |
42415152108 | PORT = 5000
TEMPLATE_DIR = 'chatroom/templates'
SQL = dict(
db_uri = 'postgres://{user}:{pasw}@{host}:{port}/{data}',
heroku = dict(
host = 'ec2-54-83-43-49.compute-1.amazonaws.com',
port = '5432',
user = 'qetxaijgzmpbzi',
pasw = 'Y-c4N56681GgE3-stOTQJ7SN3Y',
data = 'd53kkgjq3l22j5'
)
) | activaigor/chatroom | chatroom/settings.py | settings.py | py | 307 | python | en | code | 1 | github-code | 6 |
71879426428 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 4 13:55:34 2020
@author: Kangqi Fu
"""
from numpy import loadtxt, reshape
from pylab import ioff
import matplotlib.pyplot as plt
from glob import glob
import os
ioff()
fileNames = glob("./output/Solution*.dat")
fileNames.sort()
for fileName in ... | KennyKangMPC/CS-759 | final_project/scalarAdvection2D/plotAdv.py | plotAdv.py | py | 1,290 | python | en | code | 4 | github-code | 6 |
24680896779 | from fastapi import APIRouter, Depends, HTTPException, status, Request
from typing import Union
import requests
from db.models import ENV, Session, get_db
from db import schemas, crud
from dependencies import utils
import json
router = APIRouter(prefix="/auth")
@router.post("/login", response_model=schemas.TokenBase... | CosasU-Edipizarro/iic2173-2022-1 | backend/routers/auth.py | auth.py | py | 2,205 | python | en | code | 0 | github-code | 6 |
22656015465 | from model import common
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
from torch.nn import functional as F
import numpy as np
def make_model(args, parent=False):
return RCGB(args)
class CGConv2d(nn.Conv2d):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
... | akashpalrecha/superres-deformable | src/model/cgc_rcan.py | cgc_rcan.py | py | 8,589 | python | en | code | 1 | github-code | 6 |
70267230269 |
import os
import sys
import time
import config
import traceback
cur_dir = os.path.dirname(os.path.abspath(__file__))
#sys.path.append(os.path.join(cur_dir, "..", "epyk-ui"))
from epyk.core.js import Imports
from epyk.core.py import PyRest
PyRest.TMP_PATH = config.OUTPUT_TEMPS
Imports.STATIC_PATH = "./../../static... | epykure/epyk-templates | PacthRunner.py | PacthRunner.py | py | 5,254 | python | en | code | 17 | github-code | 6 |
42367832431 | # -*- coding: utf-8 -*-
class StringUtils:
@staticmethod
def truncate(result, max_bytes: int):
str_bytes = str(result).encode('utf-8', 'ignore')
str_bytes_len = len(str_bytes)
if str_bytes_len > max_bytes:
truncated_len = str_bytes_len - max_bytes
str_for_logg... | rashmi43/platform-engine | asyncy/utils/StringUtils.py | StringUtils.py | py | 523 | python | en | code | 0 | github-code | 6 |
20331901079 | """
Assignment 2
Csoport: 524/2
Név: Velican László
Azonosító: vlim2099
Segéd függvények amelyek meghívódnak a szerverben/kliensben vagy máashol
"""
import sympy
import random
#Generál egy kártya paklit két jokerrel amik még egyáltalán nincsenek összekeverve
def generateDeck ():
deck = [];
for i in range(1,5... | Laccer01/Kriptografia | assign3/auxiliaryFunctions.py | auxiliaryFunctions.py | py | 1,590 | python | hu | code | 0 | github-code | 6 |
14755245936 | # Escribir un programa que reciba una cadena de caracteres y devuelva un diccionario con cada palabra que contiene y su frecuencia.
# Escribir otra función que reciba el diccionario generado con la función anterior y devuelva una tupla con la palabra más repetida y su frecuencia.
def longitud_palabras (text):
"""... | gonrodri18/Python | funciones/ejercicio11.py | ejercicio11.py | py | 1,238 | python | es | code | 0 | github-code | 6 |
39007586537 | import os
import shutil
from rich.prompt import Prompt
from rich.table import Table
from create_folder import create_folder
def delete_user(console):
path = "./user-docs"
user_to_del = str()
user_path = str()
while True:
os.system('clear')
console.print(f"[red]So you want to delete a... | mcsadri/automation | automation/delete_user.py | delete_user.py | py | 2,920 | python | en | code | 0 | github-code | 6 |
15056144032 | """Production settings and globals."""
import yaml
from os import environ
from os.path import dirname, join
from common import *
########## JSON CONFIGURATION
SERVICE_NAME = 'djangoapp'
CONFIG_ROOT = environ.get('CONFIG_ROOT', dirname(SITE_ROOT))
with open(join(CONFIG_ROOT, SERVICE_NAME) + ".auth.yaml") as aut... | eduNEXT/django-example-app | app/settings/prod.py | prod.py | py | 4,929 | python | en | code | 1 | github-code | 6 |
26115632417 | import re
from collections import Counter
import configuration
def count_requests_with_server_error():
regex = re.compile(r'\d+\.\d+\.\d+\..+[A-Z]{3,4} .+HTTP.+" 5.. \d+.+$', re.MULTILINE)
with open(configuration.repo_root() + '/access.log', 'r') as file:
ip = [match.split()[0] for match in re.findal... | sh4rkizz/2022-1-QAPYTHON-VK-A-Mahonin | homework5/py_scripts/clients_with_most_server_based_errors.py | clients_with_most_server_based_errors.py | py | 993 | python | en | code | 0 | github-code | 6 |
25209339138 | import RPi.GPIO as GPIO, time
import sys
import threading
import queue
stepPin = 10
dirPin = 12
enablePin = 8
count = 0
GPIO.setmode(GPIO.BOARD)
GPIO.setup(stepPin, GPIO.OUT) #STEP
GPIO.setup(dirPin, GPIO.OUT) #DIR
GPIO.setup(enablePin, GPIO.OUT) #ENABLE
GPIO.setup(37, GPIO.IN) #input
GPIO.output(enablePin, True)
... | YannickAaron/WebUIStepperMotorControl | old/test.py | test.py | py | 2,378 | python | en | code | 0 | github-code | 6 |
38030608194 | #!/usr/bin/env python3
import rclpy
from crazyflie_msgs.msg import AttitudeCommand
from .crazyradio.base_control_node import BaseControlNode
import math
def convert_thrust(in_: float):
"""
- converts scalar from 2.5 to 10 to range of 10001 to 60000
- returns 0 if in_ is 0
- returns int
"""
thru... | AlboAlby00/CrazyflieControllers | crazyflie_ros2_driver/crazyflie_ros2_driver/crazyflie_hw_attitude_driver.py | crazyflie_hw_attitude_driver.py | py | 3,051 | python | en | code | 0 | github-code | 6 |
12791274360 | # -*- coding: utf-8 -*-
import requests
import time
import datetime
import sys
import boto3
from boto3.dynamodb.conditions import Key, Attr
from botocore.exceptions import ClientError
import json
import telegram
from PIL import Image
from io import BytesIO
import asyncio
import re
import os
import top_holding
bot_id... | EddieKuo723/ARK-Invest-Trading-Desk | ARK_Sticker_Set/lambda_function.py | lambda_function.py | py | 4,404 | python | en | code | 1 | github-code | 6 |
6834567910 | from typing import Optional, Tuple, Union
import torch.nn as nn
from diffusers.models import UNet2DConditionModel
from diffusers.models.unet_2d_blocks import UNetMidBlock2DCrossAttn
from diffusers.models.embeddings import Timesteps, TimestepEmbedding
from diffusers.configuration_utils import register_to_config
from b... | srpkdyy/VideoLDM | videoldm.py | videoldm.py | py | 16,886 | python | en | code | 76 | github-code | 6 |
34352982765 | import cv2
#load pre trained data
trained_face_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
#choose image to detect face in
#img = cv2.imread('52-05.jpg')
#img = cv2.imread('img2p.jpg')
webcam = cv2.VideoCapture(1) #detect face in video
#key = cv2.waitKey(1)
#iterate over frames
while True:
... | mirethy/cl-python-opencv-facedetect | face.py | face.py | py | 959 | python | en | code | 0 | github-code | 6 |
6187356527 | #!/usr/bin/env python3
"""
A function that uses the requests module to obtain the HTML content
of a particular URL and return it
"""
import redis
import requests
from functools import wraps
r = redis.Redis()
def url_access_count(method):
"""
A decorator for the get_page function.
"""
@wraps(method)... | Cyril-777/alx-backend-storage | 0x02-redis_basic/web.py | web.py | py | 1,141 | python | en | code | 0 | github-code | 6 |
25507482715 | # Document : 1 HelloWorld.py
# Created on: 13-07-2019, 06:05:07 PM
# Author : Nivesh-GC
# Udemy: Complete Python BootCamp
# https://www.youtube.com/watch?v=DjEuROpsvp4
# Setting up a Python Development Environment in Atom
print('Hello World of Atom')
a = 50
b = 50
c = a + b
d = type(c)
print(d)
| cnivesh009/udemy-python | 1 HelloWorld.py | 1 HelloWorld.py | py | 302 | python | en | code | 0 | github-code | 6 |
24013644968 | import warnings
from dataclasses import dataclass
from typing import List, Optional
import keopscore
import torch
from pykeops.torch import Genred
from falkon.mmv_ops.utils import _get_gpu_info, _start_wait_processes, create_output_mat
from falkon.options import BaseOptions, FalkonOptions
from falkon.utils import dec... | FalkonML/falkon | falkon/mmv_ops/keops.py | keops.py | py | 8,589 | python | en | code | 157 | github-code | 6 |
70374444349 | import os
import shutil
import sys
import pytest
import torch
from ivory.core.client import create_client
@pytest.fixture(scope="module")
def runs():
sys.path.insert(0, os.path.abspath("examples"))
client = create_client(directory="examples")
runs = []
for name in ["tensorflow", "nnabla", "torch2"]:... | daizutabi/ivory | tests/libs/conftest.py | conftest.py | py | 1,061 | python | en | code | 0 | github-code | 6 |
26344548844 | from unittest import TestCase
import glob
from lxml import etree
class ValidationError(Exception):
pass
class TestSampleFileValidation(TestCase):
def test_ukrdc_sample_files(self):
# For each sample file
for sample_path in glob.glob("sample_files/ukrdc/*.xml"):
# Run as a subtes... | renalreg/resources | tests/test_sample_files.py | test_sample_files.py | py | 2,213 | python | en | code | 0 | github-code | 6 |
11093803614 | from django.conf.urls import url
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^$', views.first_view, name='first_view'),
url(r'^uimage/$', views.uimage, name='uimage'),
url(r'^dface/$', views.dface, name='dface'),
url(r'^crop/$',... | neemiasbsilva/django-api-computer-vision | pipeline/urls.py | urls.py | py | 753 | python | en | code | 3 | github-code | 6 |
71877606587 | from urllib.parse import quote_plus
from bs4 import BeautifulSoup
#selenium : web test에 사용되는 프레임워크, webdriver API를 통해 렌더링이 완료된 후의 DOM 결과물에 접근할 수 있음(브라우저 제어가 필요)
#pip install selenium
#직접 브라우저를 제어하기 때문에 header값 없이도 크롤링이 가능
#여기선 Chrome 사용 webdriver 설치 : https://chromedriver.chromium.org/downloads
from selenium import web... | BrokenMental/Python-Study | googleCrawl.py | googleCrawl.py | py | 1,197 | python | ko | code | 0 | github-code | 6 |
22270481857 |
import Classes as Cls
import scr.FormatFunctions as Format
import scr.SamplePathClasses as PathCls
import scr.FigureSupport as Figs
import scr.StatisticalClasses as Stat
import P1 as P1
alpha = P1.alpha
#Find comparative outcome
def get_compare(sim_output_fair, sim_output_unfair):
increase = Stat.DifferenceSta... | etraskyoung/HPM573S18_Trask-Young_HW8 | SteadySupport.py | SteadySupport.py | py | 783 | python | en | code | 0 | github-code | 6 |
24618666253 | from django.core.mail import send_mail
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Count
from django.shortcuts import render, get_object_or_404, redirect
from django.views.decorators.http import require_POST
from django.views.generic import ListView
from taggit.... | VEIIEV/djangoProject_Blog | blog/views.py | views.py | py | 8,614 | python | ru | code | 0 | github-code | 6 |
37300509850 | import sqlite3, sys
from pathlib import Path
from . import Notes
from tqdm import tqdm
db_path = "database/xhs_tesla_notes.db"
def fill(db_path=db_path):
blank_query = "SELECT COUNT(*) FROM notes WHERE content is ''"
try:
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
amount... | Lucascuibu/xis_topic_py | ai_category/fill_blank.py | fill_blank.py | py | 1,927 | python | en | code | 0 | github-code | 6 |
25208897980 | from dataclasses import dataclass, asdict, field, make_dataclass
from typing import List, Union, Any, Dict
from enum import Enum
from sigrok.core.classes import ConfigKey
__all__ = [
"SrBlankState",
"SrDeviceState",
#"SrFileState",
#"AnalogChannel",
#"LogicChannel",
]
colorsArray = [
'#fce94f'... | drdbrr/webrok | pysigrok/srtypes.py | srtypes.py | py | 5,361 | python | en | code | 2 | github-code | 6 |
34273049354 | from flask import Flask
from flask_cors import CORS
from flask_marshmallow import Marshmallow
from config import config
from .main import main as main_blueprint
'''
Application factory for application package. \
Delays creation of an app by moving it into a factory function that can be \
explicitly invoked from script... | daronphang/stock_app_backend | app/__init__.py | __init__.py | py | 997 | python | en | code | 0 | github-code | 6 |
4534932686 | #import mxnet.ndarray as nd
from mxnet import nd
from mxnet import autograd
# REF [site] >> https://gluon-crash-course.mxnet.io/ndarray.html
def ndarray_example():
a = nd.array(((1, 2, 3), (5, 6, 7)))
b = nd.full((2, 3), 2.0)
b.shape, b.size, b.dtype
# Operations.
x = nd.ones((2, 3))
y = nd.random.uniform(-1, 1... | sangwook236/SWDT | sw_dev/python/rnd/test/machine_learning/mxnet/mxnet_basic.py | mxnet_basic.py | py | 1,497 | python | en | code | 17 | github-code | 6 |
5519173983 | import sys
import logging
import click
import os
sys.path.append('.')
from src.classes import Dataset
logger = logging.getLogger(__name__)
@click.command()
@click.option(
'--n_images', default=10,
help="Number of images per tissue"
)
@click.option(
'--n_tissues', default=6,
help="Number of tissues wi... | willgdjones/HistoVAE | scripts/patches.py | patches.py | py | 825 | python | en | code | 10 | github-code | 6 |
33379210836 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('spurt', '0020_linkpost_scrape_token'),
]
operations = [
migrations.RenameField(
model_name='linkpost',
... | steezey/spurt | spurt/migrations/0021_auto_20150122_0128.py | 0021_auto_20150122_0128.py | py | 402 | python | en | code | 0 | github-code | 6 |
37957130845 | from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.http import MediaFileUpload
import subprocess
import os
from os.path import join
... | vjgpt/twitter-pipeline | dags/daglibs/upload.py | upload.py | py | 2,218 | python | en | code | 9 | github-code | 6 |
26528967131 | import collections
from oneview_redfish_toolkit.api.errors import \
OneViewRedfishException
from oneview_redfish_toolkit.api.errors import \
OneViewRedfishResourceNotFoundException
from oneview_redfish_toolkit.api.redfish_json_validator import \
RedfishJsonValidator
from oneview_redfish_toolkit import conf... | HewlettPackard/oneview-redfish-toolkit | oneview_redfish_toolkit/api/redfish_error.py | redfish_error.py | py | 3,585 | python | en | code | 16 | github-code | 6 |
40687962293 | import json
import logging
import threading
import traceback
from enum import Enum
from typing import Any, Dict, List, Optional, Set, Tuple
from lte.protos.policydb_pb2 import FlowMatch
from magma.common.redis.client import get_default_client
from magma.configuration.service_configs import load_service_config
from mag... | magma/magma | lte/gateway/python/magma/pipelined/qos/common.py | common.py | py | 22,178 | python | en | code | 1,605 | github-code | 6 |
15418635020 | # -*- coding: utf-8 -*-
#!/usr/bin/env python3.5
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import RegPeopleForm, RegUserForm
def createuser(request):
if request.method == "POST":
uform = RegUserForm(data=request.POST)
pform = RegPeopleForm(data=r... | MyriamBel/testwork | Reg/views.py | views.py | py | 725 | python | en | code | 0 | github-code | 6 |
9357978894 | #!/usr/bin/env/python
# coding: utf-8
# YouTube Data API Collector
# Mat Morrison @mediaczar
# Last updated: 2020-03-31
''' Query the YouTube Data API for an individual channel URL or a file list of URLs.
You may also specify which 'page' you'd like to start on (useful when the script
breaks during a long data cap... | DigitalWhiskey/youtube_collector | youtube_collector.py | youtube_collector.py | py | 8,081 | python | en | code | 0 | github-code | 6 |
21097762911 | """
Honk Settings.
"""
import environ
from pathlib import Path
from google.oauth2 import service_account
env = environ.Env(
# set casting, default value
DEBUG=(bool, False),
)
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR: Path = Path(__file__).resolve().parent.parent
# reading ... | rafamoreira/honk | honk-web/honk/settings.py | settings.py | py | 3,860 | python | en | code | 0 | github-code | 6 |
24213199857 | import pygame
import serial
import time
import sys
class GUI:
def __init__(self):
# screen
pygame.init()
self.screen = pygame.display.set_mode((350, 400))
self.DELTA = 40
self.wide_value = 7500
self.angle_y = 3890
self.angle_x = 1230
s... | chinchilla2019/bebentos | main_and_pictures/main.py | main.py | py | 7,165 | python | en | code | 0 | github-code | 6 |
17962113365 | import sqlite3 as sql
from datetime import date
from model.classes import User, Country, Tasting
def initCon() -> sql:
"""
Initialize connection
:return connection:
"""
return sql.connect('../coffeeDB.db')
def createCursor(con: sql.Connection) -> sql.Cursor:
"""
Creates cursor
:para... | jathavaan/CoffeeDB | model/DBMS.py | DBMS.py | py | 15,711 | python | en | code | 0 | github-code | 6 |
277437358 | import torch
import numpy as np
from shapmagn.global_variable import DATASET_POOL
from shapmagn.utils.obj_factory import partial_obj_factory
# todo reformat the import style
class DataManager(object):
def __init__(
self,
):
"""
the class for data management
return a dict, each t... | uncbiag/shapmagn | shapmagn/datasets/data_manager.py | data_manager.py | py | 3,588 | python | en | code | 94 | github-code | 6 |
32724214710 | from setuptools import find_packages, setup
VERSION = "0.1"
INSTALL_REQUIRES = [
"alembic==1.9.4",
"apischema==0.15.6",
"asyncio==3.4.3",
"configparser==5.3.0",
"fastapi[all]==0.92.0",
"psycopg2==2.9.1",
"python-binance==1.0.16",
"python-telegram-bot==20.0a2",
"SQLAlchemy==1.4.37",... | DanielDucuara2018/report_calculation | setup.py | setup.py | py | 1,329 | python | en | code | 0 | github-code | 6 |
73944509946 | import os
import numpy as np
import cv2
from config import cfg
from numpy.linalg import inv
import sys
class RawData(object):
def __init__(self, use_raw = False):
self.mapping_file = cfg.MAPPING_FILE
self.rand_map = cfg.RAND_MAP
self.path_prefix = ""
self.ext = ""
self.file... | yzhou-saic/MV3D_Yang | src/raw_data_from_mapping.py | raw_data_from_mapping.py | py | 6,272 | python | en | code | 2 | github-code | 6 |
40128531124 | if 0:
N = int(input())
Q = int(input())
queries = []
for i in range(Q):
queries.append([int(x) for x in input().split()])
else:
N = 100000
queries = [
[2, 1, 2],
[4, 1, 2]
] * 10000
queries.append([4, 1, 2])
Q = len(queries)
def reverseTime(x, y):
# prin... | nishio/atcoder | PAST3/i_old.py | i_old.py | py | 889 | python | en | code | 1 | github-code | 6 |
17650834567 | from Node import Node
import copy
class LinkedList:
def __init__(self) -> None:
self.HeadNode = None
def Insert(self,NodeToInsert:Node):
NodeToInsert.Next = self.HeadNode
self.HeadNode = NodeToInsert
def Search(self,Key):
CurrentNode = self.HeadNode
while Curre... | AbhinavPradeep/HashTableWithListChaining | LinkedList.py | LinkedList.py | py | 717 | python | en | code | 0 | github-code | 6 |
36689801955 | from ..nmf import (PreambleEndRecord, ViaRecord, VersionRecord,
ModeRecord, KnownEncodingRecord, UpgradeRequestRecord,
UpgradeResponseRecord, Record, register_types,
SizedEnvelopedMessageRecord, PreambleAckRecord, EndRecord)
from .gssapi import GSSAPIStream
cla... | ernw/net.tcp-proxy | nettcp/stream/nmf.py | nmf.py | py | 1,954 | python | en | code | 54 | github-code | 6 |
10158111328 | from django.shortcuts import render, redirect
from app14.models import ProductModel
def openmainpage(request):
if request.method == "POST":
name = request.POST.get("product_name")
price = request.POST.get("product_price")
photo = request.FILES["product_photo"]
ProductModel(name=nam... | suchishree/django_assignment1 | project14/app14/views.py | views.py | py | 443 | python | en | code | 0 | github-code | 6 |
26043231137 | import cv2
import pickle
import numpy as np
espacios = []
with open('prueba.pkl', 'rb') as file:
espacios = pickle.load(file)
video = cv2.VideoCapture('video.mp4')
# Inicializar el contador de cuadros ocupados
full = 0
# Inicializar el estado de cada cuadro
estado = [False] * len(espacios)
while True:
chec... | Kinartb/CC431A_Grafica | PC1/PC1_TRABAJO/main.py | main.py | py | 1,599 | python | es | code | 0 | github-code | 6 |
19772432260 | #!/usr/bin/env python
# coding: utf-8
# In[40]:
import math
import pandas as pd
import numpy as np
from pyspark.sql import SparkSession
import pyspark.sql.functions as fc
import json
import requests
spark = SparkSession.builder.config("spark.sql.warehouse.dir", "file:///C:/temp").appName("readCSV").getOrCreate()
Da... | Lucas0717/house-search | spark_py/process_distinct_school.py | process_distinct_school.py | py | 3,500 | python | en | code | 0 | github-code | 6 |
42339522829 | from gtts import gTTS
import speech_recognition as sr
import os
import time
import webbrowser
r = sr.Recognizer()
order = "what can i do for you?"
tts = gTTS(order)
tts.save("order.mp3")
os.startfile(r"C:\Users\Yodi\PycharmProjects\try\order.mp3")
time.sleep(3)
arr = [["Paradise", "someone"], ["kZ2xL_N... | yodifm/SpeechRecognition | SR/main.py | main.py | py | 1,657 | python | en | code | 0 | github-code | 6 |
6412275616 | #======================================================================================
# Напишите программу, которая принимает на вход цифру, обозначающую день недели,
# и проверяет, является ли этот день выходным.
#======================================================================================
week = [1, 2, 3... | screwupug/Python_GeekBrains | sem1/sem1_homework1.py | sem1_homework1.py | py | 860 | python | ru | code | 0 | github-code | 6 |
43424744194 | import os
from aiohttp import web
from cdtz import config
LIST_TZ = []
def create_list_tz():
"""Create list timezones. """
dir_zoneinfo = '/usr/share/zoneinfo'
for dirpath, dirnames, filenames in os.walk(dir_zoneinfo):
for file in filenames:
filepath = os.path.join(dirpath, file)
... | IrovoyVlad/cusdeb-tz | bin/server.py | server.py | py | 967 | python | en | code | 0 | github-code | 6 |
18921275912 | """Test the codeclimate JSON formatter."""
from __future__ import annotations
import json
import os
import pathlib
import subprocess
import sys
from tempfile import NamedTemporaryFile
import pytest
from ansiblelint.errors import MatchError
from ansiblelint.file_utils import Lintable
from ansiblelint.formatters impor... | ansible/ansible-lint | test/test_formatter_sarif.py | test_formatter_sarif.py | py | 8,597 | python | en | code | 3,198 | github-code | 6 |
4306296022 | import pandas as pd
import numpy as np
def inference_input_processing(df: pd.DataFrame) -> np.array:
"""
The input of the function is a dataframe with the corresponding columns: x1, x2, ..., x6, z,
and the output is processed data input, ready to broadcast to model
:param df:
:return:
"""
#... | tarasevic-r/multi-task-learning | utils/data_processing.py | data_processing.py | py | 770 | python | en | code | 0 | github-code | 6 |
3666745897 | from flask import Flask, request
from flask_cors import CORS
from pingback import ping_urls
app = Flask(__name__)
cors = CORS(app, resources=r'/pingback/', methods=['POST'])
@app.route('/pingback/', methods=['GET', 'POST'])
def api():
if request.method == 'POST':
try:
if request.is_json:
... | yingziwu/pingback | api.py | api.py | py | 924 | python | en | code | 0 | github-code | 6 |
34825650741 | from machine import Pin, Timer
import time
class SensorLinha:
"""Classe para controlar os sensores de linha"""
# Pinos dos sensores de linha
R_TCRT = 26
L_TCRT = 25
# Contagem para o debounce
CONTAGEM = 10
def __init__(self):
self.sensor_direita = Pin(self.R_TCRT, Pin... | NycolasAbreu/Buggy_TCC | Buggy/sensor_linha.py | sensor_linha.py | py | 1,777 | python | pt | code | 0 | github-code | 6 |
40322657669 | # i have created this file prajakta ...
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
return render(request,'index.html')
def analyze(request):
#get the text
djtext=request.POST.get('text','default')
#checkbox value
removepunc=request.POST.get('remove... | maneprajakta/textprox | harry/views.py | views.py | py | 2,439 | python | en | code | 3 | github-code | 6 |
29979204168 | import gensim
from gensim.models import Word2Vec
import gradio as gr
# Load your trained Word2Vec model
model = Word2Vec.load("word2vecsg2.model")
def recommend_ingredients(*ingredients):
# Filter out any None values from the ingredients
ingredients = [i for i in ingredients if i]
# Get most similar ingr... | egecandrsn/FoodPair.v0 | app.py | app.py | py | 1,134 | python | en | code | 0 | github-code | 6 |
70779220028 | import os
from accelerate.utils import is_tpu_available
from ..dataset import FlattenDataset, ReprDataset
from ..models import CachedS4, FlattenS4
from ..utils.trainer_utils import PredLoss, PredMetric
from . import register_trainer
from .base import Trainer
@register_trainer("flatten_s4")
class FlattenS4Trainer(Tr... | starmpcc/REMed | src/trainer/s4.py | s4.py | py | 1,418 | python | en | code | 8 | github-code | 6 |
39069895078 | import time
import serial
import re
from .haversine import haversine
from threading import Thread
from datetime import datetime, timedelta
class Gps:
def __init__(self, serial_port: str, timezone_hours: int = 0, serial_baudrate: int = 9600, round_number: int = 2):
self.__serial = serial.Serial(serial_po... | policumbent/bob | modules/gps/src/steGPS/gps.py | gps.py | py | 5,732 | python | en | code | 4 | github-code | 6 |
5010903927 | def multiplyMatrices(matrix1, matrix2):
if checkIfMatrixIsValid(matrix1) == False:
return None
if checkIfMatrixIsValid(matrix2) == False:
return None
ROW1,COL1 = getMatrixSize(matrix1);
ROW2,COL2 = getMatrixSize(matrix2);
if COL1 != ROW2: # cannot multiply matrices that do not sat... | bishop1612/ECE364 | Lab03/operationOnMats.py | operationOnMats.py | py | 2,145 | python | en | code | 0 | github-code | 6 |
3019093477 | def sumarValores(conj, ind):
izq = conj[0]
der = 0
for i in range(ind):
izq += conj[i]
print("izq", izq)
for j in range(ind+1, len(conj)):
der += conj[j]
print("der", izq)
return der, izq
def esSolucion(conj, ind, tupla):
if ind < len(tupla):
return False... | medranoGG/AlgorithmsPython | 06.Backtracking/SumaSubconjuntoIgual.py | SumaSubconjuntoIgual.py | py | 1,648 | python | es | code | 0 | github-code | 6 |
529377311 | from email.Utils import formataddr
from zope import interface, component
from zope.app.component.hooks import getSite
from zope.traversing.browser import absoluteURL
from zojax.principal.profile.interfaces import IPersonalProfile
message = u"""
Your invitation code: %s
Or use link %s
"""
class InvitationMail(obje... | Zojax/zojax.personal.invitation | src/zojax/personal/invitation/template.py | template.py | py | 990 | python | en | code | 1 | github-code | 6 |
38810369305 | import numpy as np
from copy import deepcopy
from .node import Node
from .mesh import Mesh
from .transform import Transform
class Camera(Node):
def __init__(self, focal_length, width, height, near_depth, far_depth, transform=Transform.none):
super(Camera, self).__init__(
mesh=Mesh(vertices=n... | kaedenwile/Wile-Graphics | engine/camera.py | camera.py | py | 3,234 | python | en | code | 18 | github-code | 6 |
29474328826 | """ Hand-not-Hand creator """
""" this code is complete and ready to use """
import random
import pandas as pd
from sklearn.naive_bayes import MultinomialNB
import helpers
#utility funtcion to compute area of overlap
def overlapping_area(detection_1, detection_2):
x1_tl = detection_1[0]
x2_tl = detection_2[0... | tqiu8/asl-cv | train_hand_detector.py | train_hand_detector.py | py | 5,815 | python | en | code | 0 | github-code | 6 |
35471156635 | # -*- coding: utf-8 -*-
from torch import cuda
import transformers
from transformers import AutoTokenizer
from transformers import DataCollatorForTokenClassification, AutoConfig
from transformers import AutoModelForTokenClassification, TrainingArguments, Trainer
from datasets import load_metric, Dataset
import pandas... | Odeuropa/wp3-information-extraction-system | SmellClassifier/training/train.py | train.py | py | 13,483 | python | en | code | 2 | github-code | 6 |
74131023869 | #!/usr/bin/python
# Ce programme envoie la chaine 12345678 vers TTN
# Importer les bibliothèques
import serial
import time
# Définition des flags
is_join = False # On peut joindre la carte
is_exist = False # La carte Grove LoRa E5 a été détectée
# Définition du timeout
read_timeout = 0.2
# Créer ... | framboise314/Seeedstudio-Grove-E5-LoRa | programmes/lora-E5.py | lora-E5.py | py | 2,569 | python | fr | code | 3 | github-code | 6 |
5131563876 | from django.contrib.auth import get_user_model
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from .validators import validate_year
NUMBER_OF_SYMBOLS = 20
User = get_user_model()
class Category(models.Model):
name = models.CharField(
verbose_name='На... | Toksi86/yamdb_final | api_yamdb/reviews/models.py | models.py | py | 3,953 | python | en | code | 0 | github-code | 6 |
18573808607 | from Utilities import say
import Utilities
import json
import Room
class Thing:
"""The basic class for all non-Room objects in the game"""
def __init__(self, id, name):
self.id = id
self.name = name
self.adjectives = []
self.alternate_names = []
# how the item should appear in a list. A book. An apple. A ... | LindseyL610/CS467-AdventureProject | Thing.py | Thing.py | py | 66,406 | python | en | code | 0 | github-code | 6 |
37131271257 | #!/usr/bin/env python
#_*_coding:utf-8_*_
import numpy as np
from sklearn.decomposition import PCA
def pca(encodings, n_components = 2):
encodings = np.array(encodings)
data = encodings[:, 1:]
shape = data.shape
data = np.reshape(data, shape[0] * shape[1])
data = np.reshape([float(i) for i in data], s... | Superzchen/iFeature | clusters/pca.py | pca.py | py | 505 | python | en | code | 152 | github-code | 6 |
36696903435 | from typing import Dict, List
from tips.framework.actions.sql_action import SqlAction
from tips.framework.actions.sql_command import SQLCommand
from tips.framework.metadata.additional_field import AdditionalField
from tips.framework.metadata.table_metadata import TableMetaData
from tips.framework.metadata.column... | ProjectiveGroupUK/tips-snowpark | tips/framework/actions/append_action.py | append_action.py | py | 4,223 | python | en | code | 2 | github-code | 6 |
13969225316 | import tweepy
import math
from io import open
#consumer key, consumer secret, access token, access secret.
ckey="x"
csecret="x"
atoken="x-x"
asecret="x"
auth = tweepy.OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
api = tweepy.API(auth)
hashtag = 'dilma'
result_type = 'recent'
total = 350
iterac... | ZackStone/PUC_6_RI | Test/twitter_api_search_3.py | twitter_api_search_3.py | py | 1,072 | python | en | code | 0 | github-code | 6 |
5503988928 | # https://www.hackerrank.com/challenges/validating-named-email-addresses/problem
import email.utils
import re
email_pattern = r'([a-zA-Z](\w|\d|_|-|[.])*)@([a-zA-Z])*[.]([a-zA-Z]{1,3})'
def is_valid_email_address(person):
email = person[1]
return re.fullmatch(email_pattern, email) is not None
people = []... | Nikit-370/HackerRank-Solution | Python/validating-parsing-email-address.py | validating-parsing-email-address.py | py | 524 | python | en | code | 10 | github-code | 6 |
17763602061 | '''
UserList objects¶
This class acts as a wrapper around list objects. It is a useful base class for your own list-like classes which can inherit
from them and override existing methods or add new ones. In this way, one can add new behaviors to lists.
The need for this class has been partially supplanted by the abil... | aparna0/competitive-programs | 1collections module/userlist and usersting.py | userlist and usersting.py | py | 2,368 | python | en | code | 0 | github-code | 6 |
45712336216 |
svenskord = ["katt", "bil", "buss", "apa"]
facit =["cat", "car", "bus", "monkey"]
engelskord = [" ", " ", " ", " "]
y = int(0)
for x in svenskord:
print("skriv på engelska ordet " + x)
engelskord [y] = input ("Engelska ")
if facit [y] == engelskord [y]:
print ("Rätt!")
else:
... | Svampen10/https---github.com-Svampen10-Coolkoder | First projects/glossor2.py | glossor2.py | py | 352 | python | no | code | 0 | github-code | 6 |
21841418859 | '''
Jack Gallimore, Bucknell University, 2015
'''
import numpy
def acf(series):
n = len(series)
data = numpy.asarray(series)
mean = numpy.mean(data)
c0 = numpy.sum((data - mean) ** 2) / float(n)
def r(h):
acf_lag = ((data[:n - h] - mean) * (data[h:] - mean)).sum() / float(n) / c0
... | katelynallers/BD_HIGHRES | dreamZPT/acftest.py | acftest.py | py | 449 | python | en | code | 0 | github-code | 6 |
19990663885 | from django.conf.urls import url
from . import views
# 编写url尤其注意正则表达式匹配字符串的结尾,否则会引起冲突而达不到理想中的效果
urlpatterns = [
url(r'^$', views.index),
url(r'^(\d+)/$', views.detail),
url(r'^grades/$', views.grades),
url(r'^students/$', views.students),
url(r'^grades/(\d+)$', views.gradeStudents),
url(r'^a... | Evanavevan/Django_Project | Project1/MyApp/urls.py | urls.py | py | 427 | python | en | code | 0 | github-code | 6 |
70454780987 | #Libraries----------------------------------------------------------------------
"""
Dependencies and modules necessary for analytical functions to work
"""
#Cheminformatics
import rdkit
from rdkit import Chem
from rdkit.Chem import AllChem
from rdkit.Chem import Draw
from rdkit.Chem.Draw import IPythonConsole
from r... | AusteKan/Chemexpy | chemexpy/chemexpy/similarity_dendogram.py | similarity_dendogram.py | py | 2,593 | python | en | code | 0 | github-code | 6 |
3981451688 | '''
Given a sorted list of numbers, change it into a balanced binary search tree. You can assume there will be no duplicate numbers in the list.
Here's a starting point:
'''
from collections import deque
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = ... | MateuszMazurkiewicz/CodeTrain | InterviewPro/2019.11.22/task.py | task.py | py | 1,347 | python | en | code | 0 | github-code | 6 |
3307614760 | # the idea is that we'll have a secret word that we store inside of our program and then the user
# will interact with the program to try and guess the secret word
# we want the user to be able to keep guessing what the secret word is until they finally get the word.
secret_word = "hello"
guess = ""
guess_count = 0
g... | Olayinka2020/ds_wkday_class | guess.py | guess.py | py | 929 | python | en | code | 0 | github-code | 6 |
24535932614 | LOBBYPORT = 16969
SERVERPORT = 8888
GAME_FILE_LOCATION = "tmp"
DOLPHIN_PATH = "/Users/dpenning/Github/dolphin/gui_build/Binaries/Dolphin.app/Contents/MacOS/Dolphin"
DEBUG = True
GAME_CLASS_DEBUG = True
GAME_NO_DOLPHIN = True
BASE_URL = 'http://127.0.0.1:' + LOBBYPORT + "/"
DEBUG_GAME_DICT = {
"p1_stocks": 4,
"p1_... | dpenning/Sm4shed | SmashedLobby/config.py | config.py | py | 454 | python | en | code | 2 | github-code | 6 |
34519324302 |
''' Pydantic Models '''
from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel
class User(BaseModel):
id: int
name = "Yebin Lee"
signup_ts : Optional[datetime]=None
friends: List[int]=[]
external_data = {
"id":"123",
"signup_ts":"2017-06-01 12:2... | YebinLeee/fast-api | Study_FastAPI/pydantic_models.py | pydantic_models.py | py | 481 | python | en | code | 0 | github-code | 6 |
21991351436 | import rclpy
from bitbots_moveit_bindings.libbitbots_moveit_bindings import initRos
from rclpy.node import Node
import random
import os
class AbstractRosOptimization:
def __init__(self, robot_name, wandb=False):
self.robot_name = robot_name
self.wandb = wandb
# need to init ROS for python... | bit-bots/parallel_parameter_search | parallel_parameter_search/abstract_ros_optimization.py | abstract_ros_optimization.py | py | 1,196 | python | en | code | 2 | github-code | 6 |
20763005925 | from datetime import datetime
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters import Text
from aiogram.types import Message, CallbackQuery, LabeledPrice, PreCheckoutQuery, ContentType, ShippingQuery
from data.config import PAYMENT_TOKEN
from data.shop_config import IS_PREPAYMENT, CURRENCY, N... | shehamane/kuriBot | src/handlers/users/ordering.py | ordering.py | py | 3,797 | python | en | code | 0 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.