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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
33744141559 | from inspect import indentsize
import scrapy
from scrapy.crawler import CrawlerProcess
import json
class OLX(scrapy.Spider):
name = 'india_olx'
headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0'}
custom_settings = {
'FEED_FORMAT' : 'csv',
... | markokow/upwork_scrapers | scrapy_practice/olx_india/olx_india/spiders/olx_india.py | olx_india.py | py | 1,520 | python | en | code | 1 | github-code | 54 |
11356522410 | """
A collection of functions for particle physics calulations
"""
from typing import Tuple
import numpy as np
import torch as T
from .torch_utils import empty_0dim_like
def change_cords(
data: T.tensor, old_cords: list, new_cords: list
) -> Tuple[T.Tensor, list]:
"""Converts a tensor from spherical/to cart... | mattcleigh/neutrino_flows | nureg/physics.py | physics.py | py | 8,523 | python | en | code | 3 | github-code | 54 |
26011322230 | # Return the First Element in a List
def list_first(lis): # function declaration
print(lis[0]) # print first value of list
n=int(input('Enter the number of elements'))
lis=[]
for i in range(n): # loop... | Shivkpra/Python_Assignment_Program | Question_9(function).py | Question_9(function).py | py | 424 | python | en | code | 0 | github-code | 54 |
73665490403 | #%%
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score
from sklearn.metrics import roc_auc_score
from sklearn.manifold import TSNE
import numpy as np
import matplotlib.pyplot as plt
# from mpl_toolkits import mplot3d
from model_old import *
from tr... | jloh0017/FYP-A-Code | drive-download-20230328T080407Z-001/main.py | main.py | py | 21,563 | python | en | code | 0 | github-code | 54 |
16358173847 | # see https://github.com/yangkky/distributed_tutorial/blob/master/src/mnist-mixed.py
'''
sudo apt install python3-dev python3-pip virtualenv
virtualenv --system-site-packages -p python3 ./venv
source ./venv/bin/activate
git clone https://github.com/enijkamp/apex_example.git
cd apex_example
pip3 install -r requirement... | enijkamp/apex_example | test_apex_distributed_spawn.py | test_apex_distributed_spawn.py | py | 5,405 | python | en | code | 1 | github-code | 54 |
27424424897 | import configparser
import mysql.connector
config = configparser.ConfigParser()
config.read('configuration.ini')
mysql_config = config['mysql']
def db_execute(sql: str):
database = mysql.connector.connect(**mysql_config)
cursor = database.cursor()
cursor.execute(sql)
result = cursor.fetchall()
c... | andruhus/send-more-money | backend/source/util/database.py | database.py | py | 373 | python | en | code | 0 | github-code | 54 |
25156208956 | import random
import pickle
def random_walk_next_step(previous, floor, ceiling, step_size):
r = random.randint(-1*step_size, step_size)
next_position = previous + r
next_position = min(next_position, ceiling)
next_position = max(floor, next_position)
return next_position
def write_pickle(fnam... | spottedquoll/akira_fsm | utils.py | utils.py | py | 540 | python | en | code | 0 | github-code | 54 |
532443790 | import pandas as pd
import numpy as np
from scipy import spatial
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
import csv
import pickle
# np.save("glove_clics3_embedding_dict",[embeddings_dict],allow_pickle=True)
def get_relations(n_hot,format):
r = []
for i in range(len(n_hot)):... | NevermoreCY/yuchen2020 | codes for reference/codes with GloVe and ConceptNet/extract_input_for_nn.py | extract_input_for_nn.py | py | 5,319 | python | en | code | 0 | github-code | 54 |
35830252568 | import vk
import setup as S
def auth():
session = vk.Session(access_token=S.access_token)
if not session:
raise Exception('Can not establish connection')
api = vk.API(session, scope='wall, messages', v='5.130', lang='ru', timeout=10)
return api
def getUserNameFromId(user_id):
api = auth()
... | Deep-North/test_api_vk | vk_api.py | vk_api.py | py | 1,294 | python | en | code | 0 | github-code | 54 |
6893355106 | import random
def get_random_soup():
data_soup = [
'Суп с курицей ,картошкой,марковкой',
'Суп с рыбой,яйцом, картошкой',
'Суп с гречкой и курица',
'Суп с рисом и курица',
'Суп с вермишелью',
'Суп с фрикадельками и рисом',
'Суп с фрикадельками и вермишелью',
... | weingeneer/DietOfTatyana | main.py | main.py | py | 4,697 | python | ru | code | 0 | github-code | 54 |
18709844542 | import matplotlib.pyplot as plt
import numpy as np
#data
x = np.linspace(0, 2 * np.pi, 400)
y = [np.sin(x), np.sin(x**2), np.cos(x**2)]
title = ['y1','y2','y3']
#plot
numPlots = len(y)
f = plt.figure()
ax = []
for i in range(numPlots):
ax.append(f.add_subplot(numPlots,1,i+1))
ax[i].plot(x, y[i])
ax... | sahilm89/stack_overflow_random | loopOverSubplots.py | loopOverSubplots.py | py | 457 | python | en | code | 0 | github-code | 54 |
8060538042 | import API
import requests
import json
import pprint
url = "https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest"
headers = {
'X-CMC_PRO_API_KEY': API.Api_key,
"accepts": "application/json",
}
params = {
"id": "4172",
"convert": "USD"
}
response = requests.get(url, para... | pangchay/Luna-Spot-trade-Tracker | luna_price.py | luna_price.py | py | 455 | python | en | code | 0 | github-code | 54 |
28674505688 | import networkx as nx
import random
for p in range(0,101,1):
size = 0
degreeSeq = []
noOfNodes = 10000
for i in range(noOfNodes):
if random.uniform(0, 1) <= (float(p)/100):
degreeSeq.append(int(1))
else:
degreeSeq.append(int(3))
vector = []
for i in ... | santro92/Network-Analysis-And-Modelling | Problem Set/Problem Set 3/Code/p6.py | p6.py | py | 1,068 | python | en | code | 0 | github-code | 54 |
30707023889 | import glob, os
import librosa
base_path = "/home/deepak/Comp/asr_data_preprocessing_v2/"
processed_path = base_path + 'test_v1/'
names = []
files_path = processed_path
new_path = base_path + 'test_filter/'
print("SOURCE PATH :: ", files_path)
print("DESTINATION PATH :: ", new_path)
count = 0
for f in glob... | mishra011/asr_data_preprocessing | unsupervised/copy_wav_files.py | copy_wav_files.py | py | 460 | python | en | code | 0 | github-code | 54 |
37442566071 | #!/usr/bin/python3
"""
This module contains a function that
prints a text with 2 new lines after
each of these characters: . ? and :
"""
def text_indentation(text):
"""
this funtion receives a text
and prints 2 new lines after each of these characters . ? and :
@text: given text
"""
if not isi... | sahinmeric/holbertonschool-higher_level_programming | 0x07-python-test_driven_development/5-text_indentation.py | 5-text_indentation.py | py | 842 | python | en | code | 1 | github-code | 54 |
17937225432 | from utils import *
import pygame
from hiticon import HitIcon, HitLevel
class Scorekeeper:
def __init__(self, world):
self.world = world
self.unhit_notes: list[float] = []
self.hit_icons: list[HitIcon] = []
self.hp = 100
self.shown_hp = 0
@property
de... | quasar098/midi-playground | scorekeeper.py | scorekeeper.py | py | 4,200 | python | en | code | 51 | github-code | 54 |
5313921541 | # Função - Como Declarar, Chamar e Usar funções
# O escopo da declaração de uma função é:
# def nome-funcao(argumentos):
# código
# código
# ...
# return valor
# Há duas coisas opcionais:
# Argumentos (informações que você passa para a função, ao chamar ela)
# Retornar valor (informações qu... | davieduardo94/py_tests | funcoes/funcoes.py | funcoes.py | py | 993 | python | pt | code | 0 | github-code | 54 |
32373333636 | import cv2
import numpy as np
#from matplotlib import pyplot as plt
import os
import glob
#Global input data and expected output
#Initilized
n = 2500
X = np.empty((0, n), int)
y = np.empty((0), int)
#Function to make a dataset from raw images in a directory
#Parameters : m-number of training examples
... | Obed-Immanuel/Gender-Identification-LogisticRegression | Project File.py | Project File.py | py | 8,506 | python | en | code | 1 | github-code | 54 |
41865135886 | import sys
import ast
import pandas as pd
import docplex.mp
from collections import namedtuple
from docplex.mp.model import Model
from docplex.mp.environment import Environment
import docplex.mp.conflict_refiner as cr
import random
import time
############ UTIL ############
conv_bin = lambda x: 0 if x==0 else 1
def s... | kevinkiki/MEMCCNF | Model_3.5.py | Model_3.5.py | py | 15,046 | python | en | code | 0 | github-code | 54 |
32556288666 | #!/usr/bin/env python3
import sys
Q_BOUND = 2*10**5
N_BOUND = 2*10**5
M_BOUND = 2*10**5
assert_no_windows_newline = False
if assert_no_windows_newline:
inp = sys.stdin.buffer.read().decode()
else:
inp = sys.stdin.read().replace('\r\n', '\n')
A = [int(x) for x in inp.split()]; ii = 0
correct_inp = []
n,m = ... | Kodsport/kth-challenge-2022 | boxarrowdiagram/input_validators/validate.py | validate.py | py | 989 | python | en | code | 0 | github-code | 54 |
2059548787 |
import numpy as np
import pandas as pd
from Feature_Extraction.src.hungarian import Hungarian
from sklearn.preprocessing import MinMaxScaler
from Feature_Extraction.src.CommonFunctions import *
def getSimilarity(Features1, Features2):
featureNum = len(Features1)
Features1Arr = np.array(Features1[["deltay", ... | khan-yin/WHUT_MCM2020 | 第2场训练赛/Fingerprint feature extraction/Fingerprint feature extraction latex/code/matchMinutiae.py | matchMinutiae.py | py | 1,913 | python | en | code | 20 | github-code | 54 |
34606412987 | """
Setup script for the Rust GitHub Actions.
The output of this will be used as arguments for the GitHub Actions matrix.
see: https://docs.github.com/en/actions/using-jobs/using-a-matrix-for-your-jobs
"""
import re
import json
import itertools
import toml
from fnmatch import fnmatch
from pathlib import Path
from p... | BrickyChen/hash | .github/scripts/rust/setup.py | setup.py | py | 6,270 | python | en | code | null | github-code | 54 |
38662026394 | import obsplan
import datetime
import time
import numpy
import pylab
def read_bright_objects(filename):
def parsetime(v):
return(numpy.datetime64(datetime.datetime.strptime(v.decode(), '%d %b %Y %H:%M:%S.%f')))
a = numpy.dtype( {'names': ['Time','Sun_RA','Sun_Dec','SunProbeEarthAngle', 'Radius',\
... | jagophile/ArcusOpSim | run_obsplan_v1.py | run_obsplan_v1.py | py | 4,129 | python | en | code | 0 | github-code | 54 |
27898333026 | # -*- coding = utf-8 -*-
# @Time : 2021/7/8 13:16
# @Author : 黄鹏龙
# @File : visualizatingWeb.py
# @Software : PyCharm
from flask import Flask, render_template
import sqlite3
app = Flask(__name__)
@app.route('/')
def qiancheng_index():
# 1、连接数据库并获取游标
conn = sqlite3.connect(r"db\51jobDatabase.db")
cur = co... | huangPengL/51job_spider | visualizatingWeb.py | visualizatingWeb.py | py | 2,445 | python | en | code | 2 | github-code | 54 |
40918392947 | from solution import rotate_left, rotate_right
TRIPLE = (42, 'a', None)
print('TRIPLE', TRIPLE)
def test_rotate_left():
print('rotate_left:', ('a', None, 42))
print(rotate_left(TRIPLE) == ('a', None, 42))
if rotate_left(rotate_left(rotate_left(TRIPLE))) == TRIPLE:
print('test Ok!')
else:
... | natsumemaya/hexlet_tasks | 1_hexlet_basic/rotation/tests.py | tests.py | py | 697 | python | en | code | 0 | github-code | 54 |
40598070441 | import random, pylab
N = 5
pi = [[1.1 / 5.0, 0], [1.9 / 5.0, 1], [0.5 / 5.0, 2], [1.25 / 5.0, 3], [0.25 / 5.0, 4]]
x_val = [a[1] for a in pi]
y_val = [a[0] for a in pi]
pi_mean = sum(y_val) / float(N)
long_s = []
short_s = []
for p in pi:
if p[0] > pi_mean:
long_s.append(p)
else:
... | weka511/smac | tutorial_4/walker_test.py | walker_test.py | py | 1,417 | python | en | code | 18 | github-code | 54 |
28549399108 | # script for training a neural network
from processing_functions import (get_input_args)
from model_functions import (set_data_dir, load_data, load_model, define_classifier, training_network, save_checkpoint)
def main():
# get inputs from the user for training checkpoint direction, architecture, learning rate, hi... | chrisy-d1989/udacityaipython | Part2/train.py | train.py | py | 1,235 | python | en | code | 0 | github-code | 54 |
16174939047 | import RPi.GPIO as GPIO
import time
def button_callback(channel):
print("push detected!")
GPIO.output(10, GPIO.HIGH)
time.sleep(.1)
GPIO.output(10, GPIO.LOW)
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(10,GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(8, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO... | finnschi/rasberrysandbox | detector.py | detector.py | py | 478 | python | en | code | 0 | github-code | 54 |
7786354407 | """
8-9. Messages
Make a list containing a series of short text messages. Pass the list to
a function called show_messages(), which prints each text message.
"""
def show_messages(messages):
"""Prints a list of messages."""
for message in messages:
print(message)
short_messages = [
'Hello world!',
... | xerifeazeitona/PCC_Basics | chapter_08/exercises/09_messages.py | 09_messages.py | py | 410 | python | en | code | 0 | github-code | 54 |
31375741817 | from const import *
import plotly.express as px
df = df.copy(deep=True)
def genre_by_year(genre, type_):
res = (
df[(df["listed_in"].str.contains(genre)) & (df["type"] == type_)]
.groupby(["year_added"])
.size()
.reset_index(name="count")
)
fig = px.line(
res,
... | osamaoun97/Data_visualisation_project_ITI | src/graphs/genre_by_year.py | genre_by_year.py | py | 878 | python | en | code | 4 | github-code | 54 |
38820012852 | import sqlite3
class database():
def __init__(self, db_loc):
self.con = sqlite3.connect("./" + db_loc)
self.c = self.con.cursor()
self.initial_setup()
def __del__(self):
self.con.commit()
self.con.close()
def initial_setup(self):
symb = input("Symbol to test: ")
sym = self.c.execute("SELECT * F... | git4unrealnondev/TastyWorks-Account-Info-Puller | query.py | query.py | py | 1,530 | python | en | code | 0 | github-code | 54 |
17800807331 | import os
import json
import openai
import asyncio
import aiohttp
import discord
from keep_alive import keep_alive
from discord.ext import commands
import httpx
with open("prompts.json") as f:
data = json.load(f)
ASSIST = data["Assistant"]
ERP = data["ERPALPHA"]
FURRY = data["FURRY"]
SAD = data["SAD"]
# Set up the ... | mishalhossin/HaruniAI | main.py | main.py | py | 17,439 | python | en | code | 0 | github-code | 54 |
1225492831 | from __future__ import absolute_import
from dl_sqlalchemy_promql.connection import Connection
from dl_sqlalchemy_promql.errors import (
DatabaseError,
DataError,
Error,
IntegrityError,
InterfaceError,
InternalError,
NotSupportedError,
OperationalError,
ProgrammingError,
Warning,... | datalens-tech/datalens-backend | lib/dl_sqlalchemy_promql/dl_sqlalchemy_promql/dbapi.py | dbapi.py | py | 725 | python | en | code | 99 | github-code | 54 |
13510074470 | import torch
import cv2
import math
def uncompress_image(data):
for d in data:
# decode imgs_jpeg_encoded -> imgs
if 'imgs_jpeg_encoded' in d:
assert 'imgs' not in d
d['imgs'] = []
for img_jpeg_encoded in d['imgs_jpeg_encoded']:
d['imgs'].append(c... | facebookresearch/fairo | perception/sandbox/eyehandcal/src/eyehandcal/utils.py | utils.py | py | 6,333 | python | en | code | 826 | github-code | 54 |
12788089302 | #!/usr/bin/env python
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Simulation with reactive streams #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
"""Interactive simulation with transition graph representation of mixing p... | AlexCAB/SWRS | Python/scripts/mixing_example/transition_graph_interactive_simulation.py | transition_graph_interactive_simulation.py | py | 10,261 | python | en | code | 0 | github-code | 54 |
70586656483 | import platform
import os
import subprocess
import ycm_core
SOURCE_EXTENSIONS = [ '.cpp', '.cxx', '.cc', '.c', '.m', '.mm' ]
# These are the compilation flags that will be used in case there's no
# compilation database set (by default, one is not set).
# CHANGE THIS LIST OF FLAGS. YES, THIS IS THE DROID YOU HAVE BEEN... | cymoo/vbuntu | config/.ycm_extra_conf.py | .ycm_extra_conf.py | py | 3,563 | python | en | code | 2 | github-code | 54 |
35694189805 | # app/__init__.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def create_app():
app = Flask(__name__, template_folder="templates", static_folder="static")
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'your_secret_key... | YashBur/JobSage | app/__init__.py | __init__.py | py | 472 | python | en | code | 0 | github-code | 54 |
568282727 | import base64
import binascii
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from smtplib import SMTP_SSL, SMTPException
from domain.entity import Email
from domain.entity.email import Attachment
from domain.exception ... | iaaiba/notification-service | infrastructure/repository/email_sender.py | email_sender.py | py | 1,847 | python | en | code | 0 | github-code | 54 |
69944182241 | # Fenêtre d'attribution principale (frames vertes et jaunes)
import sys
import tkinter as tk
import tkinter.messagebox, tkinter.simpledialog
from tkinter import ttk
import importlib
from . import config, dataclasses, bdd, tools, fichier, attribution, exportation, publication, fiches, assistant
# Variables globales
... | loic-simon/club-q | source/blocs/main.py | main.py | py | 12,761 | python | fr | code | 1 | github-code | 54 |
74450140640 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from sklearn.metrics import mean_squar... | jayvelasco1990/data-science-viz | tensorflow/regression.py | regression.py | py | 3,155 | python | en | code | 0 | github-code | 54 |
16205613121 | import os
import logging
import pandas as pd
OUT = "OUT"
ACTION = "action"
FLAG_GO = "flag_go"
DONE = "strategy_done"
ORDERS = "orders"
logger = logging.getLogger(__name__)
def get_balance(path):
with open(os.path.join(path, 'flag_go'), 'r') as f:
ret = f.read()
return ret
def can_i_run(path):
... | edge7/tas | utility/mql4_socket.py | mql4_socket.py | py | 1,010 | python | en | code | 0 | github-code | 54 |
15186953224 | # угадай число
import random
random_number = random.randrange(1, 100)
guess_mode = 0
while True:
user_guess=int(input("Угдайте число от 1 до 100"))
guess_mode += 1
if user_guess > random_number:
print('Число должно быть меньше')
elif user_guess < random_number:
print('Число должно быть б... | va-proger/learning-one-py | hm3-2.py | hm3-2.py | py | 546 | python | ru | code | 0 | github-code | 54 |
30414483768 | from torch.utils.data import Dataset
from PIL import Image
import random
import os
class UnpairedImagesFolder(Dataset):
def __init__(self, root, transform=None):
self.root = root
self.transform = transform
self.filesA = os.listdir(os.path.join(root, "trainA"))
self.filesB = os.li... | killf/remove_glasses | datasets/UnpairedImagesFolder.py | UnpairedImagesFolder.py | py | 805 | python | en | code | 0 | github-code | 54 |
21831239778 | # encoding: utf-8
import pandas as pd
import numpy as np
import os
import data
def get_k_day_volatility(code,
days,
start_date,
end_date):
"""
获得k日波动率
"""
fname = data.get_filename(code)
df = data.read_data(fname)
df =... | alxsoares/zjsxzy_in_js | factor-investing/src/factorinv/defensive.py | defensive.py | py | 553 | python | en | code | 0 | github-code | 54 |
20151493483 | import heapq
class Solution:
"""
@param points: a list of points
@param origin: a point
@param k: An integer
@return: the k closest points
"""
def topk(self, nums, k):
# write your code here
self.heap = []
for num in nums:
heapq.heappush(self.heap, -num... | invokerkael918/HashAndHeap | Top k Largest Numbers.py | Top k Largest Numbers.py | py | 467 | python | en | code | 0 | github-code | 54 |
22867634900 | db = {101:{'name':'Jay', 'address': 'Talegoan', 'id': 101, 'salary':20000}}
def dashboard():
print("\t\t Welcome to Employee Management System")
print("""
Manu
1) Create new Employee record
2) Read Employee record
3) update employee reocrd
... | tedy-art/Python | 100.The_K_Academy/Projects/Employee_management_sytem/Employee_management_system.py | Employee_management_system.py | py | 2,629 | python | en | code | 2 | github-code | 54 |
30660763963 | """ This module hoasts the Data class used to store the user's scores and settings in gui """
import matplotlib.pylab as plt
import numpy as np
import time
from timetracker.logs import Logger
from matplotlib.figure import Figure
from matplotlib import gridspec
from mpl_toolkits.axes_grid1 import make_axes_locatable
fro... | RupertDodkins/timetracker | timetracker/gui/reports.py | reports.py | py | 11,921 | python | en | code | 0 | github-code | 54 |
4747305264 | import pybullet as p
import pyrosim.pyrosim as pyrosim
from pyrosim.neuralNetwork import NEURAL_NETWORK
import os
from sensor import SENSOR
from motor import MOTOR
import constants as c
import math
import random
class ROBOT:
def __init__(self, solutionID, test, evolved):
self.sensor... | alexsaavedraa/Exploration-Of-Genetic-Algorithm-Efficiency | robot.py | robot.py | py | 3,039 | python | en | code | 0 | github-code | 54 |
31945793102 | from django.contrib.auth import get_user_model
from django.db import models
User = get_user_model()
class Subscribe(models.Model):
user = models.ForeignKey(
User,
related_name='subscriber',
verbose_name='Подписчик',
on_delete=models.CASCADE,
)
author = models.ForeignKey(
... | DrMojito/foodGram | backend/foodgram/users/models.py | models.py | py | 589 | python | en | code | 0 | github-code | 54 |
39364482295 | from django.urls import path
from . import views
app_name = 'main'
urlpatterns = [
# 메인 페이지
path('', views.index, name='index'),
# 글 작성 URL
path('create/', views.create, name='create')
# 글 삭제 및 수정 없음
] | BonHyuck/hpcs | main/urls.py | urls.py | py | 254 | python | ko | code | 0 | github-code | 54 |
23213907907 |
class Host:
# host - dict, one of multiple dicts in json response of get_hosts in hosts array
def __init__(self, host):
self.id = host["id"] # str
self.mac = host["mac"] # str
self.vlan = host["vlan"] # str
self.innerVl... | 0x41gawor/2020Z_PKC_ONOS | Model/Host.py | Host.py | py | 1,226 | python | en | code | 0 | github-code | 54 |
40334924010 | import logging
from discord.ext import commands
import discord
import asyncio
logger = logging.getLogger("Voting_Cog")
class Voting:
def __init__(self, bot):
self._logger = logger
self.bot = bot
self._votings = {}
@commands.command(name="createvote", pass_context=True, no_pm=True)
... | NicoWeidmann/discord-NicoBot | cogs/votingbot.py | votingbot.py | py | 7,142 | python | en | code | 1 | github-code | 54 |
72420385440 |
def rotationAssignment(name,numofrotations):
for i in range(numofrotations):
temp=name[len(name)-1]+name[0:len(name)-1]
name=temp
return name
name=str(input('Enter the string '))
iterations= int(input('Enter the iterations '))
output=rotationAssignment(name,iterations)
print('your output is... | ayyubyaqub/mysane | accounts/test.py | test.py | py | 339 | python | en | code | 0 | github-code | 54 |
27406907686 | import os
import networkx as nx
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
from scipy.optimize import curve_fit
from scipy.interpolate import interp1d
from scipy.signal import savgol_filter
from QwakBenchmark import QWAKBenchmark
from OperatorBenchmark import OperatorBenchmark
if __n... | JaimePSantos/QWAK | benchmark/runAnalyzer.py | runAnalyzer.py | py | 10,097 | python | en | code | 2 | github-code | 54 |
28118566018 | d=input()
d=d.split()
l1=[]
for i in d:
l1.append(i)
g=int(l1[0])
r=int(l1[1])
for num in range(g,r):
ord=len(str(num))
s= 0
te = num
while te > 0:
di = te% 10
s+= di**ord
te //= 10
if num == s:
print(num)
| Narendon123/python | 19.py | 19.py | py | 278 | python | en | code | 0 | github-code | 54 |
26587587422 | '''
Author : Ashutosh Kumar
Version : 1.0
Description :
Email : ashutoshkumardbms@gmail.com
'''
import pymongo
myclient = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = myclient['booklibrary']
mycol = mydb['books']
flag = 1
mydoc = ""
try:
print(" Let's search for a Book ! ")
while 1 == flag:
... | Ashutoshcoder/python-codes | Mongo-Example-Implementation/Books/searchBook.py | searchBook.py | py | 1,320 | python | en | code | 2 | github-code | 54 |
27814768174 | class Node():
def __init__(self,value):
self.value = value
self.next = None
self.prev = None
class DoubleLinkedList():
def __init__(self):
self.first = None
def add(self,value):
if not self.first:
self.first = Node(value)
else:
curren... | moisesgomez00/AED | Unidad_1/EjerciciosPropios/ListaDoblementeEnlazadaClases.py | ListaDoblementeEnlazadaClases.py | py | 849 | python | en | code | 0 | github-code | 54 |
11544448373 | import os
import pyaudio
import wave
import numpy as np
import struct
chunk = 1024
sample_format = pyaudio.paInt16
channels = 1
fs = 44100
seconds = 60
filename = 'out.wav'
input_device_index=1
rows, columns = os.popen('stty size', 'r').read().split()
p = pyaudio.PyAudio()
stream = p.open(format=sample_format, cha... | Stuart-Wilcox/lights-controller | src/microphone.py | microphone.py | py | 1,554 | python | en | code | 0 | github-code | 54 |
41223759124 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import sys
import subprocess
import shlex
from logging import getLogger
logger = getLogger("wrap")
from ykdl.compact import compact_tempfile
posix = os.name == 'posix'
# The maximum length of cmd string
if posix:
# Us... | tjyang15/video | ykdl/util/wrap.py | wrap.py | py | 4,455 | python | en | code | 3 | github-code | 54 |
7397313032 | # Two Sum
# from itertools import combinations
# class Solution:
# def twoSum(self, nums: list[int], target: int) -> list[int]:
# nC2 = list(combinations(nums, 2))
# indexes = list(combinations(range(len(nums)), 2))
# sum_c = list(map(sum, nC2))
# t_idx = sum_c.index(target)
# ... | ppp5649/python-study | leetcode/week 3/Two Sum.py | Two Sum.py | py | 1,208 | python | ko | code | 0 | github-code | 54 |
9124024090 |
class Solution:
def longestPalindrome(self, s: str) -> str:
N = len(s)
longestLength = 0
left = 0
right = 0
# create N x N dynamic programming table and init with setting i==j true
# because a word of length 1 is always palindromic
dp = [[False for n in range... | minhyeong-joe/leetcode-challenge | DynamicProgramming/LongestPalindromicSubstring/solution.py | solution.py | py | 1,378 | python | en | code | 0 | github-code | 54 |
14687121632 | import os
from os import getenv
from dotenv import load_dotenv
if os.path.exists("local.env"):
load_dotenv("local.env")
load_dotenv()
admins = {}
SESSION_NAME = getenv("SESSION_NAME", "session")
BOT_TOKEN = getenv("BOT_TOKEN")
BOT_NAME = getenv("BOT_NAME", "Venom")
API_ID = int(getenv("API_ID"))
API_HASH = getenv... | SHIVAM-1294/xop | config.py | config.py | py | 1,230 | python | en | code | 0 | github-code | 54 |
35405278360 | import json
from DataStream import *
from AbcStream import *
from DefStream import *
from FrameStream import *
class UninitializedStream(DataStream):
def HandleStream(self, data):
jsonstr = data.decode('utf8')
identifier = json.loads(jsonstr)
stream_type = identifier['type']
if... | alexweav/ADAF | Server/UninitializedStream.py | UninitializedStream.py | py | 958 | python | en | code | 2 | github-code | 54 |
40492097890 | import pygame as pg
from Camera import Camera
import sys
from controllerOff import controllerOFF
from objectRW import loadObject
# the screen object represents the screen/hardware of the game system
# it draws the layers of each level and
class SCREEN:
def __init__(self, Height = 1280, Width = 1920, fps = 120, r... | dunn0052/GTD_engine | dev/SCREEN.py | SCREEN.py | py | 4,540 | python | en | code | 0 | github-code | 54 |
73181425122 | #!/usr/bin/env python
import argparse
import codecs
def _parse_args():
"""Parse arguments."""
parser = argparse.ArgumentParser()
parser.add_argument('file_path', help='Path of file to convert.')
parser.add_argument('output', help='Output location of file.')
return parser.parse_args()
def _reg_f... | LondonAppDev/dual-boot-bluetooth-pair | clean_reg_file.py | clean_reg_file.py | py | 1,202 | python | en | code | 104 | github-code | 54 |
9350261102 | import numpy as np
class EdgeIndex(object):
'''
find the index of the edge from node i to node j in edges
'''
def __init__(self, edge) -> None:
self.num_nodes = edge.max() + 1
self.index = {code:idx for idx, code in enumerate(self.encode(edge[0], edge[1]))}
def enco... | EricZhangSCUT/SPIN-CGNN | code/CGraph.py | CGraph.py | py | 4,270 | python | en | code | 1 | github-code | 54 |
21557357420 | import sqlite3
sqlite_file = 'globaldata.db' # name of the sqlite database file
table_name = 'userdata' # name of the table to be created
new_field = 'userid' # name of the column
field_type = 'INTEGER'
new_field = 'geolocation'
field_type = 'INTEGER'
new_field = 'fav'
field_type = 'TEXT' # column data type
# Co... | loophac/projectsneak | db_init.py | db_init.py | py | 633 | python | en | code | 1 | github-code | 54 |
35617097097 | from pathlib import Path
import torch
from torch import nn
from torch.hub import load_state_dict_from_url
from torchvision.models.inception import Inception3 # type: ignore[import]
from torchvision.models.feature_extraction import create_feature_extractor, get_graph_node_names # type: ignore[import]
from torchvision... | sebastianberns/cleanfeatures | models/inception.py | inception.py | py | 3,468 | python | en | code | 2 | github-code | 54 |
24537839765 | # Databricks notebook source
from mlflow.tracking import MlflowClient
client = MlflowClient()
# COMMAND ----------
model_name = "spark-lr-model"
# COMMAND ----------
# Delete a registered model along with all its versions
client.delete_registered_model(name=model_name)
# COMMAND ----------
versions=[1, 2, 3]
for... | methodidacte/databricks | NYCITIBIKE/00 - delete registered models.py | 00 - delete registered models.py | py | 432 | python | en | code | 0 | github-code | 54 |
33726721057 | '''
HEAP SORT
It is a sorting technique based on the heap data structure.
Heap is a complete binary tree, in which every level except the last, is filled
completely with its nodes, and nodes are far left.
We implement this sorting in an array using Max Heap, in which the parent node
value is greater than it child node... | smv1999/CompetitiveProgrammingQuestionBank | Sorting Algorithms/heap_sort.py | heap_sort.py | py | 2,065 | python | en | code | 1,181 | github-code | 54 |
37134340422 | import random
from ordenamiento import *
#genera un grupo de varias familias
def generarFamilias(num_familias, grupo, cont):
if num_familias == 1:
return grupo
else:
num_familiares = random.randint(2, 12)
familia = []
i = 0
familiar = 0
while i < num_familiares:
... | PalacioRpo/Estructuras2 | generadorDatos.py | generadorDatos.py | py | 2,957 | python | es | code | 0 | github-code | 54 |
16491804970 | import cv2
import math
import numpy as np
import matplotlib.pyplot as plt
image = cv2.imread('iiitd1.png')
image = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)
lbp = np.zeros(image.shape)
image = cv2.copyMakeBorder(image, 1,1,1,1,cv2.BORDER_CONSTANT)
xmoves = [-1,-1,-1, 0, 1, 1, 1, 0]
ymoves = [-1, 0, 1, 1, 1, 0,-1,-1]
for... | abhishekrajgaria/Computer-Vision | midsem/codem2.py | codem2.py | py | 732 | python | en | code | 0 | github-code | 54 |
14350153343 | import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import warnings
from methods.extraction import dictToVec
from scipy.spatial.distance import pdist
from methods.graph_transformations import causality_matrix
class Participant():
def __init__(self, pid, experiment, conditi... | Vbtesh/less_is_more_continuous_time_active_learning | classes/participant.py | participant.py | py | 25,327 | python | en | code | 1 | github-code | 54 |
74978042400 | import os
import subprocess
# get current ip
p = subprocess.Popen(['curl', 'ifconfig.me'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdout, stderr = p.communicate()
default_ip = stdout.decode('utf-8')
IP = input(f'Please input your remote IP (default {default_ip}): ')
if IP == '':
IP = default_ip
PORT = ... | JiaweiHe98/openvpnConfigTools | generateServerAndClientConfig.py | generateServerAndClientConfig.py | py | 4,180 | python | en | code | 0 | github-code | 54 |
23246698879 | import numpy as np
import keras
import os.path
from keras.layers import Conv1D
import keras.backend as K
from keras.engine.topology import Layer
import tensorflow as tf
import nnhealpix.map_ordering
class OrderMap(Layer):
"""Defines the keras layer that reorders the inputs map to then perform
convolution on t... | AlleneChristopher/NNhealpix | nnhealpix/layers/blocks.py | blocks.py | py | 5,535 | python | en | code | null | github-code | 54 |
40498408697 | class Solution:
def invalidTransactions(self, transactions: List[str]) -> List[str]:
res = set()
hashmap = collections.defaultdict(list)
for t in transactions:
t = t.split(",")
hashmap[t[0]].append(t)
#print(hashmap)
for key in hashmap:
... | FawneLu/leetcode | 1169/Solution.py | Solution.py | py | 697 | python | en | code | 1 | github-code | 54 |
2067737144 | #!/usr/bin/python3
""" Fetches contents of URL and prints to console """
from urllib.request import urlopen
from urllib.error import HTTPError
from sys import argv
if __name__ == '__main__':
try:
with urlopen(argv[1]) as response:
body = response.read()
decodedbody = body.decode("u... | amberwagoner/holbertonschool-higher_level_programming | 0x0C-python-network_1/3-error_code.py | 3-error_code.py | py | 440 | python | en | code | 0 | github-code | 54 |
3920482712 | import rospy
from numpy import float64, int64
from gtec_msgs.msg import Ranging
from pozyx_simulation.msg import uwb_data
from std_msgs.msg import Float64
def callback(data):
global sequence
global save
global uwb
if (data.seq != sequence):
pub.publish(uwb)
uwb = uwb_data()
for... | KasperMollerHansen/Robot_localization_for_outdoor_application | uwb_husky/scripts/uwb_pozyx.py | uwb_pozyx.py | py | 1,259 | python | en | code | 1 | github-code | 54 |
36094873318 | """A line-for-line port of Mark McClure's JavaScript polyline decoder:
http://facstaff.unca.edu/mcmcclur/GoogleMaps/EncodePolyline/decode.js
"""
def decode(encoded):
"""Decodes the given polyline string and returns a list of (lat, lng)
pairs.
"""
length = len(encoded)
index = 0
points = []
... | mccutchen/street-view-traveler | polyline.py | polyline.py | py | 1,064 | python | en | code | 0 | github-code | 54 |
31750967230 | from typing import List
import torch
from torch import nn
import torch.distributions as ds
import torch.nn.functional as F
from math import sqrt
import sys, random, math, os
import heapq
import util
from util import d, tic, toc
from multiprocessing import Pool
from itertools import accumulate
"""
TODO:
Simpli... | pbloem/gated-rgcn | kgmodels/simple.py | simple.py | py | 26,226 | python | en | code | 2 | github-code | 54 |
25965839778 | #!/bin/python3
import sys
t = int(input().strip())
for a0 in range(t):
count=0
n,k = input().strip().split(' ')
n,k = [int(n),int(k)]
a = [int(a_temp) for a_temp in input().strip().split(' ')]
if(n>=k):
for i in a:
if(i<0 or i==0):
count=count+1
if (c... | KeerthiThatipally/HackerRank | AngryProfessor.py | AngryProfessor.py | py | 396 | python | en | code | 0 | github-code | 54 |
12624007301 | # SIMPLE ARIMA FORECAST OF BLS NONFARM PAYROLLS.
# Note: Produces ARIMA forecasts of BLS NSA payrolls, as well as implied
# BLS seasonal adjustment factors. Combines into a 12-month-ahead forecast
# of monthly SA nonfarm payrolls.
#
# Andrew Chamberlain, Ph.D.
# Glassdoor Economic Research
# Web: glassdoor.com/research... | glassdooreconomicresearch/jobs-day-arima-forecast | arima_jobs_day.py | arima_jobs_day.py | py | 4,531 | python | en | code | 2 | github-code | 54 |
29863959132 | # pin out pwm bcm12 - board 32 pwm direito
# pin out d bcm 16 - board 36 direito
# pin out d bcm 20 - board 38 direito
# pin out pwm bcm 13 - board 33 esquerdo
# pin out d bcm 19 - board 35 esuqerdo
# pin out d bcm 26 - board 37 esuqerdo
import RPi.GPIO as gpio
import time
gpio.setwarnings(False)
#Configuring GPI... | lffspaniol/TCC | test.py | test.py | py | 834 | python | en | code | 0 | github-code | 54 |
20698088095 | import logging
import os
import datetime
from alive_progress import config_handler
LOG_DIR = 'logs/'
now = datetime.datetime.now()
if not os.path.isdir(LOG_DIR):
os.mkdir(LOG_DIR)
logging.basicConfig(filename="{}/{}.log".format(LOG_DIR, now), level=logging.DEBUG, filemode='w', format='[%(asctime)s %(levelname)8... | eliblaney/pdb-learn | config.py | config.py | py | 636 | python | en | code | 0 | github-code | 54 |
20656473795 | from flask import Flask, request, redirect
from threading import Thread
from flask_cors import CORS
import os
import json
import socket
import platform
from flask_socketio import SocketIO
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
CORS(app)
socketio = SocketIO(app, allowed_cors_origins = "*")
app.conf... | popQA17/OneLink | server.py | server.py | py | 1,917 | python | en | code | 0 | github-code | 54 |
73296236961 | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
from model.nls.cgnl import SpatialCGNLx
from model.nls.cc import CrissCrossAttention
from model.nls.anl import APNB
from model.nls.basic import Stage
__all__ = ['PreResNet', 'preresnet20', 'preresnet32', 'preresnet44', 'preresnet56',
... | zh460045050/SNL_ICCV2021 | SNL-Classification/model/preresnet_snl.py | preresnet_snl.py | py | 9,882 | python | en | code | 95 | github-code | 54 |
40605408763 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 12 10:44:33 2018
@author: Enrique
"""
from time import time_ns, sleep
from threading import Thread, Event
from queue import Queue, Empty
class HiloCuentaAtras(Thread):
def __init__(self, input_q):
super(HiloCuentaAtras, self).__init__()
self.... | ESapenaVentura/ComputAv | Ordenador/Cuenta_atras.py | Cuenta_atras.py | py | 1,759 | python | es | code | 0 | github-code | 54 |
70926834082 | import heapq
class Solution:
def scheduleCourse(self, courses: List[List[int]]) -> int:
max_heap = []
heapq.heapify(max_heap)
total_time = 0
for t, endt in sorted(courses, key=lambda x:x[1]):
total_time += t
heapq.heappush(max_heap, -t)
... | hogilkim/leetcode | 630. Course Schedule III.py | 630. Course Schedule III.py | py | 457 | python | en | code | 0 | github-code | 54 |
34119154334 | from typing import Optional
from fastapi import FastAPI,Response,status
from pydantic import BaseModel
import random
from fastapi.exceptions import HTTPException
app = FastAPI()
created_post = []
class postparameters(BaseModel):
title : str
content : str
rating : Optional[int] = 50
def find_post(id):
f... | johngachara/restapi | main.py | main.py | py | 1,600 | python | en | code | 0 | github-code | 54 |
33827068815 | """
Created on January 2021
@author: Niko Suchowitz
"""
import time
import numpy as np
import os
# Pipeline and nodes
import pandas as pd
from fedot.core.pipelines.pipeline import Pipeline
from fedot.core.pipelines.node import PrimaryNode, SecondaryNode
from fedot.utilities.ts_gapfilling import ModelGapFiller
def f... | nSucho/comparison_gapfilling | interpolation_fedot.py | interpolation_fedot.py | py | 2,750 | python | en | code | 1 | github-code | 54 |
16054521325 | from collections import namedtuple
class Goat:
legs_number = 4
def __init__(self, height, weight):
self.height = height
self.weight = weight
def __str__(self):
return f'wight = {self.weight}, height = {self.height}'
'''namedtuple'''
Point = namedtuple('Point', ['x', 'y', 'z']... | nbox363/lections_mipt_khirianov | classes.py | classes.py | py | 903 | python | en | code | 0 | github-code | 54 |
74692427361 | # Импортируем класс, который говорит нам о том,
# что в этом представлении мы будем выводить список объектов из БД
from django.views.generic import (
ListView, DetailView, CreateView, UpdateView, DeleteView,
)
from .models import Product, Subscriptions, Category
# -----------------
from django.http import HttpRespo... | Met-s/Kurss_D | django_d4/simpleapp/views.py | views.py | py | 11,705 | python | ru | code | 0 | github-code | 54 |
3761334185 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import serial
import struct
import platform
import serial.tools.list_ports
import math
import time
import pandas as pd
# This file is compatible with python 2.7 and 3.7 in rapsberry pi 4B
def printSerialData(acceleration, angularVelocity, angle_degree, magnetometer):
... | samwong0127/smart-bicycle | IMU/hfi_a9_export_linux_2.py | hfi_a9_export_linux_2.py | py | 9,952 | python | en | code | 0 | github-code | 54 |
37153178434 | #!/usr/bin/python3
import os
import sys
from sys import argv
import binascii
import re
import json
sys.path.append(sys.path[0] + "/..")
sys.path.append(sys.path[0] + "/../protobuf_release/py")
import PbInput_pb2
import PbOutput_pb2
import PbMap_pb2
import base64
from commonUtils import *
def tryPrintMap(filename)... | kongshuiJ/LogAnalyser | src/test.py | test.py | py | 2,057 | python | en | code | 0 | github-code | 54 |
74708259041 | import importlib
import os
class describe:
"""
描述自己的调用方式以及所需参数
key: 方法键
frpara: 第一参数所占寄存器数量 (可选)
separa: 第二参数所占寄存器数量 (可选)
"""
def __init__(self, key: str, frpara: int = 0, separa: int = 0, output: bool = False):
self.key = key
self.frpara = frpara
self.separa = sepa... | beibao233/DP911-Simulator | DP911/Functions/__init__.py | __init__.py | py | 1,347 | python | en | code | 0 | github-code | 54 |
35746545152 | #!/usr/bin/python3
from lxml import etree
import os, sys
import pickle
import requests
def allCulturalPodcastURL(page):
return "https://podcast.rthk.hk/podcast/programmeList.php?type=audio&cid=0&page="+page+"&order=stroke&lang=zh-CN"
page = 0
remainder = '99'
ProgOf = {}
while (remainder != '0'):
page = page + ... | raylexlee/grabRTHKpodcasts | SaveProgOf.py | SaveProgOf.py | py | 830 | python | en | code | 0 | github-code | 54 |
29433553618 | from sqlalchemy import Column, String, Integer, ForeignKey, and_, Boolean, DateTime
from sqlalchemy.orm import relationship, backref
from Modules.Config.base import Base
from Modules.Config.Data import Message
from Modules.Classes.Experiment import Experiment
from Modules.Classes.Diagram import Diagram
from Modules.Cla... | toolexp/ET_Server | Modules/Classes/ExperimentalScenario.py | ExperimentalScenario.py | py | 23,220 | python | en | code | 0 | github-code | 54 |
40123858473 | import numpy as np
import pandas as pd
import seaborn as sns
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import warnings
warnings.filterwarnings('ignore')
df = sns.load_dataset('penguins')
df.head()
df.info... | monamienamie/TIL | 1127_penguins_LR.py | 1127_penguins_LR.py | py | 1,964 | python | en | code | 1 | github-code | 54 |
16093254507 | import logging
import os
import sys
from datetime import datetime, timedelta
from web3 import Web3, HTTPProvider
from auction_keeper.urn_history import UrnHistory
from pymaker.deployment import DssDeployment
logging.basicConfig(format='%(asctime)-15s %(levelname)-8s %(message)s', level=logging.DEBUG)
logging.getLogg... | grandizzy/auction-keeper | tests/manual_test_urn_history.py | manual_test_urn_history.py | py | 2,785 | python | en | code | null | github-code | 54 |
72429642080 | import time
from marshmallow import Schema, fields
from common.app_model import DataResult
class AcquireInputData:
def __init__(self, device: str, method: str, alias: str):
self.device = device
self.method = method
self.alias = alias
class AcquireInputDataSchema(Schema):
device = fi... | jsmoyam/zserver | sky_modules/acquire_module/model_acquire_module.py | model_acquire_module.py | py | 1,460 | python | en | code | 0 | github-code | 54 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.