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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
19404942737 | import os
import json
import fire
import random
import pickle
import math
from tqdm import tqdm
import tensorflow as tf
import numpy as np
from tensorflow.keras import layers
from gated_cnn import GatedCNN
from adaptive_softmax import AdaptiveSoftmax
from data_utils import load_and_process_data, batchify, get_tokenize... | vivekverma239/lm_pretraining | pretrain.py | pretrain.py | py | 20,647 | python | en | code | 3 | github-code | 36 |
74137516264 | from aux_sharing import sharing_parts as shp
from freeCAD_utils import geom_utils as gu
from freeCAD_civil.structures import underpass
from FreeCAD import Vector
from freeCAD_utils import drawing_tools as dt
import Part
from aux_sharing import sharing_IR_wingwall as IR
from aux_sharing import sharing_vars as shv
# Mod... | anaiortega/parametricDesign | examples/RCstruct_typology/three_sided_box_culvert_pilefound/base_models/model_wingwall_IR.py | model_wingwall_IR.py | py | 1,924 | python | en | code | 3 | github-code | 36 |
29432719201 | """
构造MeshSegNet数据集
"""
import os
import vtk
from shutil import copyfile
def convert(dataset: str, img_path: str, label_path: str):
"""
提供原始数据路径和目标数据路径
"""
reader = vtk.vtkPLYReader()
writer = vtk.vtkPolyDataWriter()
# 当前文件夹下的所有子文件夹
folders = [name for name in os.listdir(dat... | XiShuFan/MeshSegNet | step0_prepare.py | step0_prepare.py | py | 2,615 | python | en | code | 0 | github-code | 36 |
5548747359 | import os
from pprint import pprint
from tqdm import tqdm
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
import numpy as np
import utils
from lt_data import t... | limengyang1992/lpl | lpl-longtail-other/train_lpl_cifar100.py | train_lpl_cifar100.py | py | 10,563 | python | en | code | 4 | github-code | 36 |
8555925095 | import os
import sys
import time
import jsbsim
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader, Dataset
from tqdm import tqdm
torch.set_num_threads(8)
sys.path.append(str(jsbsim.get_default_root_dir()) + '/pFCM/... | mrwangyou/IDSD | src/model/idsd.py | idsd.py | py | 6,469 | python | en | code | 4 | github-code | 36 |
34342442803 | import struct
from hid_code import azerty_hid_codes
input_string = input("Input string: ")
for wanted_char in list(input_string):
modif, key = azerty_hid_codes[wanted_char]
raw = struct.pack("BBBBL", modif, 0x00, key, 0x00, 0x00000000)
with open("/dev/hidg0", "wb") as f:
f.write(raw) # press key
... | c4software/string2hid | main.py | main.py | py | 370 | python | en | code | 2 | github-code | 36 |
35674891165 | """
*Prefix*
A prefix.
"""
from abc import ABCMeta
from typing import TypeVar
__all__ = ["Prefix"]
class Prefix:
__metaclass__ = ABCMeta
Meta = TypeVar("Meta")
Control = TypeVar("Control")
Shift = TypeVar("Shift")
Hyper = TypeVar("Hyper")
Super = TypeVar("Super")
Alt = TypeVar... | jedhsu/text | text/_elisp/key/_prefix/_prefix.py | _prefix.py | py | 328 | python | en | code | 0 | github-code | 36 |
37493947110 | ''' Elabore um programa em Python que gere uma matriz aleatória (9x9), com números entre 0 e 10, imprima-a. Após, peça
o quadrante desejado e imprima os elementos desse quadrante. '''
from random import randint
from termcolor import colored
m = [0] * 9
for i in range(9):
m[i] = [0] * 9
for j in range(9):
... | danibassetto/Python | pythonProjectListasExercicio/Lista7/L7_E15.py | L7_E15.py | py | 2,579 | python | en | code | 0 | github-code | 36 |
74054073065 | import os
import copy
import random
"""
Base class for the player + few utilities
DO NOT MODIFY this file.
It will be always replaced by default version of Brute, so any changes will be discarded anyway..
PUT ALL YOUR IMPLEMENTATION TO player.py
"""
class BasePlayer:
def __init__(self, name, dictiona... | malek-luky/Scrabble-Agent | base.py | base.py | py | 5,330 | python | en | code | 0 | github-code | 36 |
14076176482 | from collections import Counter
import numpy as np
import pandas as pd
from matplotlib import pyplot
from backfit.BackfitUtils import init_objects
from backfit.utils.utils import load_new_diffs, load_mcmc_diffs
from utils.utils import extract_runs_w_timestamp
if __name__ == '__main__':
n_users = -1
cats, cat... | rjm49/isaacdata | student_profiling/StudentProfiling.py | StudentProfiling.py | py | 1,235 | python | en | code | 0 | github-code | 36 |
20214118948 | from django.shortcuts import render
from django import forms
from django.core.files.storage import default_storage
from django.http import HttpResponse
from django.core.files.base import File, ContentFile
from django.http import HttpResponse
import markdown2
import random
import copy
from . import util
class NewTitl... | ksondjaja/wiki | encyclopedia/views.py | views.py | py | 5,050 | python | en | code | 0 | github-code | 36 |
26614306732 | import operator
import functools
import logging
import elasticsearch_dsl
from elasticsearch import Elasticsearch
from jam import settings
from jam import exceptions
from jam.backends import query as queries
from jam.backends.base import Backend
logging.getLogger('elasticsearch').setLevel(logging.WARNING)
class Ela... | CenterForOpenScience/jamdb | jam/backends/elasticsearch.py | elasticsearch.py | py | 4,968 | python | en | code | 3 | github-code | 36 |
957433742 | pkgname = "xkeyboard-config"
pkgver = "2.40"
pkgrel = 0
build_style = "meson"
configure_args = ["-Dxorg-rules-symlinks=true", "-Dcompat-rules=true"]
hostmakedepends = ["meson", "pkgconf", "xsltproc", "python", "perl"]
makedepends = ["libx11-devel", "xkbcomp"]
checkdepends = ["gawk"]
depends = ["xkbcomp"]
pkgdesc = "X K... | chimera-linux/cports | main/xkeyboard-config/template.py | template.py | py | 708 | python | en | code | 119 | github-code | 36 |
74418498345 | import numpy as np
import os
from subprocess import call
root_dir = "./exp_results/"
if not os.path.isdir(root_dir):
os.mkdir(root_dir)
fix_params = [
"--data", "./data/ptb/",
#"--data", "./data/wikitext-2/",
"--model", "LSTM",
#"--tied",
"--epochs", "50",
"--batch_size", "20",
"--bpt... | JACKHAHA363/BBBRNN | hp_search.py | hp_search.py | py | 1,273 | python | en | code | 23 | github-code | 36 |
29370556151 | import discord
from redbot.core import commands, Config, app_commands
import asyncio
import aiohttp
from steam.steamid import SteamID
from datetime import datetime
class SteamAPI(commands.Cog):
"""Search for games and player profiles.
Grab your Steam [API Key](https://steamcommunity.com/dev/apikey).
Use t... | dkoz/kozejin-cogs | steamapp/steamapp.py | steamapp.py | py | 8,621 | python | en | code | 0 | github-code | 36 |
16901469870 | ###############################################
# loading
###############################################
import pandas as pd
def train_master(tab_nm):
print(f'load_data.train_master({tab_nm})')
path = "d:/lge/pycharm-projects/kaggle_store_sales/input/"
trans = pd.read_csv(f'{path}/{tab_nm}.csv',
... | pmosoft/kaggle_store_sales | feature/load_data.py | load_data.py | py | 1,343 | python | en | code | 0 | github-code | 36 |
8616054736 | """
Home Work 11
Dmytro Verovkin
robot_dreams
Написати кастомний Exception клас, MyCustomException, який має повідомляти "Custom exception is occured".
"""
class MyCustomException(Exception):
def __init__(self, message="Custom exception is occurred"):
self.message = message
super().__init__(self.... | verovkin/robot_dreams | 11/task2.py | task2.py | py | 393 | python | uk | code | 0 | github-code | 36 |
2889442953 | import os
BASE_DIR = os.path.dirname(__file__)
SECRET_KEY = 'some_secret_key'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'uncertainty',
'uncertainty.tests',
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
... | abarto/django_uncertainty | uncertainty/tests/settings.py | settings.py | py | 379 | python | en | code | 46 | github-code | 36 |
11130591414 | import azure.functions as func
import logging
import json
from azure.data.tables import TableServiceClient
# send to congratiulation message queue
from azure.servicebus import ServiceBusClient, ServiceBusMessage
CONNECTION_STR = "Endpoint=sb://testbus-sk11.servicebus.windows.net/;SharedAccessKeyName=RootManageShare... | IngNoN/UC_Kaffeemaschine | processCoffeeOrder/__init__.py | __init__.py | py | 2,119 | python | en | code | 0 | github-code | 36 |
23070148342 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 22 08:07:59 2016
@author: vijverbe
"""
from ecmwfapi import ECMWFDataServer
server = ECMWFDataServer()
grid = "1.125/1.125"
#server.retrieve({
# 'dataset' : "era5_test",
# 'stream' : "oper/enda", # 'oper' specifies the high resolution daily data, as... | ruudvdent/WAM2layersPython | dowload_scripts/download_lm.py | download_lm.py | py | 2,494 | python | en | code | 23 | github-code | 36 |
43489935655 | import inspect
import logging
from logging.handlers import TimedRotatingFileHandler
log_server = logging.getLogger('server')
log_server.setLevel(logging.DEBUG)
rotate_handler = TimedRotatingFileHandler("log\logs\server.log", when='m', interval=1, backupCount=5)
rotate_handler.suffix = '%Y%m%d'
formatter = logging.Form... | solovyova-1996/async_chat | chat/log/server_log_config.py | server_log_config.py | py | 719 | python | en | code | 0 | github-code | 36 |
42443907633 | matriz = [[],[],[]]
pares = 0
soma3 = 0
for l in range(0,3):
for c in range(0,3):
matriz[l].append(int(input(f'Digite o valor da posição [{l}, {c}]: ')))
for l in matriz:
for c in l:
print(f'[ {c} ]', end='')
if c % 2 == 0:
pares += c
print()
soma3 += l[2]
print('='*... | JosueFS/Python | Exercicios/Ex087.py | Ex087.py | py | 451 | python | pt | code | 0 | github-code | 36 |
7689823177 | def method1(string: str) -> str:
def character_count_array(string: str) -> int:
count = [0] * 256
for i in string:
count[ord(i)] += 1
return count
def first_non_repeating(string: str) -> int:
count = character_count_array(string)
index = -1
k = 0
... | thisisshub/DSA | I_string/C_given_a_string_find_the_leftmost_character_that_does_not_repeat.py | C_given_a_string_find_the_leftmost_character_that_does_not_repeat.py | py | 673 | python | en | code | 71 | github-code | 36 |
40500129775 | #!/usr/bin/env python3
"""Script demonstrating .txt file reading and writing"""
__appname__ = 'basic_io2.py'
__author__ = 'Sam Turner (sat19@ic.ac.uk)'
__version__ = '0.0.1'
__license__ = 'GNU public'
#############################
# FILE OUTPUT
#############################
# Save the elements of a list to a file
l... | SamT123/CMEECoursework | Week2/Code/basic_io2.py | basic_io2.py | py | 528 | python | en | code | 0 | github-code | 36 |
25259786916 | ### Setup
import pandas as pd
from splinter import Browser
from bs4 import BeautifulSoup as bsp
from webdriver_manager.chrome import ChromeDriverManager
import time
# Setup splinter
executable_path = {'executable_path': ChromeDriverManager().install()}
browser = Browser('chrome', **executable_path, headless=False)
... | Robert-A-Norris/web-scraping-challenge | Mission_to_Mars/scrape_mars.py | scrape_mars.py | py | 2,718 | python | en | code | 0 | github-code | 36 |
2769385558 | from discord.ext import commands
from lib.mysqlwrapper import mysql
from typing import Optional
import discord
import lib.embedder
import logging
class Checklist(commands.Cog):
def __init__(self, client):
self.client = client
# Set up the logger
self.logger = logging.getLogger(__name__)
... | guitaristtom/Cherubi | bot/cogs/checklist.py | checklist.py | py | 12,761 | python | en | code | 1 | github-code | 36 |
36445019270 | from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support import expected_conditions as EC
import sys
def execute():
"""
executes script, checks if l... | rayhanrandi/siakwar | driver.py | driver.py | py | 6,467 | python | en | code | 0 | github-code | 36 |
12433729637 | import bdsim
from bdsim.blocks.transfers import Integrator
## Lecture 10.4
# In this notebook, we will learn to model a dynamical system using the bdsim simulation class.
# Learn more at:\
# https://petercorke.github.io/bdsim/
# We will begin by modeling the mass-spring system which resembles the behvior of motors... | rojas70/rvc_python_notebooks | 10.4_blockSim.py | 10.4_blockSim.py | py | 4,156 | python | en | code | 4 | github-code | 36 |
8385911882 | from django import template, forms
from collections import OrderedDict
from ..models import FormLabel
register = template.Library()
# get the form field corresponding to the given block
@register.simple_tag
def block_field(form, block):
if block.name in form.fields: return form[block.name]
return None
# ge... | johncronan/formative | formative/templatetags/form_block.py | form_block.py | py | 3,803 | python | en | code | 4 | github-code | 36 |
40152632978 | """Mel - a command-line utility to help with mole management."""
import argparse
import sys
import mel.cmd.addcluster
import mel.cmd.addsingle
import mel.cmd.error
import mel.cmd.list
import mel.cmd.microadd
import mel.cmd.microcompare
import mel.cmd.microview
import mel.cmd.rotomapautomark
import mel.cmd.rotomapaut... | aevri/mel | mel/cmd/mel.py | mel.py | py | 5,755 | python | en | code | 8 | github-code | 36 |
42779565833 | import argparse
import fastexcel
def get_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("file")
return parser.parse_args()
def main():
args = get_args()
excel_file = fastexcel.read_excel(args.file)
for sheet_name in excel_file.sheet_names:
excel... | ToucanToco/fastexcel | test.py | test.py | py | 409 | python | en | code | 16 | github-code | 36 |
34643324678 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#OnlyOne is an application to remove duplicated files within a specified directory
#Copyright (C) 2014 Carlos Manuel Ferrás Hernández
#
#This file is part of OnlyOne.
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of ... | carlos-ferras/OnlyOne | config.py | config.py | py | 2,295 | python | en | code | 1 | github-code | 36 |
24519178649 | import urllib
from urllib.request import urlopen
import requests
import cv2
import numpy as np
from PIL import Image as im
class CaptchaSolver:
def __init__(self, captcha, captcha_key):
self.captcha = captcha
self.captcha_key = captcha_key
def url_to_image(self):
# get i... | claimclone/TikTokBot | captcha.py | captcha.py | py | 2,698 | python | en | code | null | github-code | 36 |
14761703992 | '''
Description:
Author: caobin
Date: 2021-06-22
Github: https://github.com/bcao19
LastEditors: caobin
LastEditTime: 2021-06-28 23:20:20
'''
#!/home/ASIPP/caobin/anaconda3/bin/python
# -*-coding: UTF-8 -*-
"""
this module get the rho from efit or efitrt
type=1 rho from psi, type=2 rho from sqrt(rho), type=3 rho fro... | bcao19/my-python-code | east_mds/get_rho.py | get_rho.py | py | 1,588 | python | en | code | 0 | github-code | 36 |
30188582457 | #!/usr/bin/python2
# -*- coding: utf-8 -*-
import copy
import numpy as np
import sys
import time
from control_msgs.msg import GripperCommandGoal, GripperCommandAction
from geometry_msgs.msg import Quaternion, PoseStamped
from grasping_msgs.msg import FindGraspableObjectsAction, FindGraspableObjectsGoal
from moveit_co... | osuprg/fetch_mobile_manipulation | mobile_manipulation/src/grasping/grasping.py | grasping.py | py | 7,066 | python | en | code | 5 | github-code | 36 |
69837934825 | list = [14, 10, 17, 13, 4, 8, 6, 7, 13, 13, 17, 18, 8, 17, 2, 14, 6, 4, 7, 12]
copy = list
while True:
while 0 in list:
list.remove(0)
if len(copy) == 0:
print("True")
break
copy.sort(reverse = True)
print(copy)
N = copy[0]
x = 0
copy.remove(copy[0])... | Tyranius/Havel_Hakimi_alg | Havel_Hakimi_alg.py | Havel_Hakimi_alg.py | py | 522 | python | en | code | 0 | github-code | 36 |
4165802056 | # ONLY EDIT FUNCTIONS MARKED CLEARLY FOR QUESTIONS 1 AND 2. DO NOT CHANGE ANY METHOD SIGNATURES OR THE RUNALL METHOD
from flask import Flask, request, jsonify
import json
from time import clock
app = Flask(__name__)
# IMPORTANT: DO NOT CHANGE THIS FUNCTION UNDER ANY CIRCUMSTANCES
@app.route('/runall', methods=['POS... | pythoncodingchallenge/skeleton-repo | vcc-skeleton.py | vcc-skeleton.py | py | 887 | python | en | code | 0 | github-code | 36 |
9204121114 | from SOL4Py.opengl.ZOpenGLObject import *
from SOL4Py.opengl.ZOpenGLQuadric import *
from SOL4Py.opengl.ZOpenGLMateria import *
from SOL4Py.opengl.ZOpenGLTexture2D import *
import math
class ZOpenGLTexturedTorus(ZOpenGLTexture2D):
def __init__(self, filename=None, materia=None, r = 0.1, c = 0.2,
... | sarah-antillia/SOL4Py_V4 | SOL4Py/opengl/ZOpenGLTexturedTorus.py | ZOpenGLTexturedTorus.py | py | 1,966 | python | en | code | 0 | github-code | 36 |
12636485792 | ## 建置Map Gilder
class Map:
boader=1
map=[]
def set_map(self,n):
self.boader=n
for i in range(n):
row=[]
for j in range(n):
row.append("*")
self.map.append(row)
def set_pattern(self,p):
n=int(self.boader/2)-1
if p... | winniepopu/X-village-2018-exercise | Lesson3_Class/ex3_classlife.py | ex3_classlife.py | py | 782 | python | en | code | 0 | github-code | 36 |
5657081633 | #!/usr/bin/env python3
import os
import json
import requests
import sys
def TriggerPipeline(token, commit, ci_ref):
url = "https://circleci.com/api/v2/project/github/mapbox/mobile-metrics/pipeline"
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
}
data =... | mapbox/mapbox-navigation-ios | scripts/trigger-metrics.py | trigger-metrics.py | py | 1,361 | python | en | code | 821 | github-code | 36 |
9237399008 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 10 14:15:37 2022
@author: sunlin
@实现声音震动的单通道模型准确率计算和混淆矩阵生成
"""
from cProfile import label
from utils.confusionMatrixGenerator import confusionMatrixGenerator,plot_confusion_matrix
from utils.accCalculator import accCalculateFrame
from sklearn.metr... | Seafood-SIMIT/Long-Term-Correlation-Feature-Network | utils/classificationPerformance.py | classificationPerformance.py | py | 4,309 | python | en | code | 2 | github-code | 36 |
23783861933 | #!/usr/bin/python3
"""
This module contain a function
that prints a square"""
def print_square(size):
""" This function print a square with
character #
Args:
size(int): This represents the length of the square
raise:
TypeError: if size is not an integer
ValueError: If size is less than 0... | wagzyAyo/alx-higher_level_programming | 0x07-python-test_driven_development/4-print_square.py | 4-print_square.py | py | 747 | python | en | code | 0 | github-code | 36 |
25316015896 |
# coding: utf-8
# In[1]:
import numpy as np
import tensorflow as tf
dataPhase = np.load("trainLenetdataPhase.npy")
dataMag = np.load("trainLenetdataMag.npy")
dataY = np.load("trainLenetdataY.npy")
# In[2]:
from keras.models import Sequential
from keras.layers import Convolution2D
model = Sequential()
model.add... | MarvinChung/sound-classification-CNN | Lenet_with_MagAndPhase.py | Lenet_with_MagAndPhase.py | py | 1,445 | python | en | code | 0 | github-code | 36 |
13092077642 | import sympy as sy
from itertools import permutations
import dill
import pickle
import time
total_start = time.time()
#
#
#The Antimatter Reactor Diagram
#
# /---------- Q1
#P1---------/
# S (K1)
#P2---------|
# | (K2)
#P3---------|
# S (K3)
#P4---------\
# \------... | Northerneye/antimatterReactor | antimatterReactor.py | antimatterReactor.py | py | 10,272 | python | en | code | 0 | github-code | 36 |
19364810539 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 24 19:39:57 2023
@author: Star World
"""
def predict():
name=requst.form['name']
month=request.form['month']
dayofmonth=request.form['dayofmonth']
dayofweek=request.form['dayofweek']
origin=request.form['origin']
if(origin=="msp"):
... | sdayanasdayana9/-Flight-Delay-prediction-for-Aviation-industry-using-Machine-Learning- | Flight Delay prediction for Aviation industry using Machine Learning/flask/untitled0.py | untitled0.py | py | 1,761 | python | en | code | 0 | github-code | 36 |
1578326033 | from tkinter import Label
from tkinter import Entry
from tkinter import Frame
from tkinter import IntVar
from tkinter import Button
from tkinter import Listbox
from tkinter import Toplevel
from tkinter import Scrollbar
from tkinter import StringVar
from tkinter import Radiobutton
from base import BaseDatos
def busque... | due204/Titita | buscar.py | buscar.py | py | 7,868 | python | es | code | 0 | github-code | 36 |
70356004905 | # /home/jay/anaconda3/bin/python
import numpy as np
from sklearn.metrics import log_loss
from scipy.special import expit
# sig = lambda x: 1.0/(1.0+np.exp(-x))
sig = expit
sig_d = lambda x: sig(x) * (1 - sig(x))
sig_to_d = lambda x: x * (1 - x)
# log_loss = lambda y,yhat: np.sum(-(y*np.log(yhat) + (1 - y)*n... | jayswinney/mlp | mlp.py | mlp.py | py | 7,754 | python | en | code | 0 | github-code | 36 |
71894780585 | from django.shortcuts import render, redirect
from .models import Story, TagsModel
from .forms import StoryForm, ProductFilter
from django.http import HttpResponse
from django.views.generic import DetailView, UpdateView, DeleteView
def product_list(request):
filter = ProductFilter(request.GET, queryset=Stor... | youngnastyas/appProject | classifier/main/views.py | views.py | py | 3,724 | python | en | code | 0 | github-code | 36 |
23420929820 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('bar', '0300_auto_20161002_1441'),
('clientes', '0276_auto_20160827_2010'),
('personal', '0272_auto_20160827_2010'),
(... | pmmrpy/SIGB | ventas/migrations/0051_auto_20161002_1441.py | 0051_auto_20161002_1441.py | py | 4,059 | python | es | code | 0 | github-code | 36 |
27114463908 | # Object Oriented Programming
# What is an object?
# A blueprint
# A Car
# Has
# engine, transmissions, tires
# Doors
# Model
# Make
# Seats
# Color
# Type
# Can Doors
... | beattietrey/Coding-Dojo | python_stack/_python/Lectures/oop.py | oop.py | py | 1,780 | python | en | code | 0 | github-code | 36 |
39274547040 | from fastapi import HTTPException, Request
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sentry_sdk import capture_message
from ..auth.auth_handler import verify_jwt
class JWTBearer(HTTPBearer):
def __init__(self, auto_error: bool = True):
# automatic error reportin
su... | LosAltosHacks/api | app/auth/auth_bearer.py | auth_bearer.py | py | 1,344 | python | en | code | 0 | github-code | 36 |
42591857727 | from dataclasses import dataclass, field
from dataclasses_json import dataclass_json
from typing import Tuple, List, Set, Optional, Dict, Iterable
from math import sqrt, asin, sin, cos, pi
from pathlib import Path
Coordinate = Tuple[float, float]
def distance(p1: Coordinate, p2: Coordinate):
return sqrt((p1[0] - ... | bmboucher/rail_baron | python/src/pyrailbaron/map/datamodel.py | datamodel.py | py | 4,986 | python | en | code | 0 | github-code | 36 |
72651462503 | n=int(input())
sq=n*n
n=str(n)
n=n[::-1]
n=int(n)
sq2=n*n
sq2=str(sq2)
sq2=sq2[::-1]
sq2=int(sq2)
print(sq==sq2)
| thandrangiashok/codemind-python | Adam_number.py | Adam_number.py | py | 113 | python | el | code | 0 | github-code | 36 |
40239694832 | #In [1]:
class Point:
pass
#In [2]:
point1 = Point()
point1.x = 1.0
point1.y = 1.0
#In [3]:
point1.hello = lambda x: print('Hello', str(x))
point1.hello('world')
point2 = Point()
#point2.hello('world') #エラー: Pointクラスの定義ではhelloメソッドはない
#In [4]:
class MyClass:
count = 0 # クラス変数countの定義
#In [5]:
print(MyClass.... | maki216syou/study_python | learning_python/example-29.py | example-29.py | py | 2,277 | python | en | code | 0 | github-code | 36 |
33445056109 | from docutils import nodes
from docutils.parsers.rst import Directive, directives
import requests
class Contributor:
"""Main class for the contributors atributes."""
def __init__(self, login, url, contributions=0):
"""Initialize atributes."""
self.contributions = contributions
self.l... | Kubeinit/kubeinit | docs/src/_exts/ghcontributors.py | ghcontributors.py | py | 2,820 | python | en | code | 208 | github-code | 36 |
27005467704 | import os
import json
import logging
from slacker.logger import Logger
from slacker.session import Session
# Default REPL prompt template string. Override with "repl_prompt" field in
# .slacker config file.
#
# Supported identifers:
# ${ro} - display DEFAULT_READ_ONLY_STR when Slacker is running in read-only mode
# $... | netromdk/slacker | slacker/environment/config.py | config.py | py | 4,977 | python | en | code | 14 | github-code | 36 |
74339884902 | '''
Created on Mar 12, 2012
@author: KVogelgesang
'''
# from mock import Mock # http://python-mock.sourceforge.net/
import unittest
import datetime
import sys
sys.path.append("../main/python")
sys.path.append("src/main/python")
import date
class DateTests(unittest.TestCase):
def testdateformat(self):
... | kvogelgesang/test-one-project | testDriven/src/test/date_tests.py | date_tests.py | py | 721 | python | en | code | 0 | github-code | 36 |
28223166240 | import pykka
from site_storage.sсhema import RegularCheck, WatchStatus
from site_storage.messages import UpdateSiteRequest
from site_storage.messages import SiteDeleteResponse, SiteResponse, SubscribeOnSiteUpdates
import os
import urllib.request
from urllib.parse import urldefrag
import time
import threading
from datet... | map82top/site_watcher | site_downloader/actor.py | actor.py | py | 4,456 | python | en | code | 0 | github-code | 36 |
3093689176 | # You will be receiving to-do notes until you get the command "End". The notes will be in the format:
# "{importance}-{note}". Return the list of to-do notes sorted by importance.
# The importance value will always be an integer between 1 and 10 (inclusive).
import re
notes2 = []
notes = [0] * 10
notes1 = []
command = ... | ivn-svn/SoftUniPythonPath | Programming Fundamentals with Python/5_lists_advanced/lab/3_to_do_list.py | 3_to_do_list.py | py | 736 | python | en | code | 1 | github-code | 36 |
33539146773 | #!../python35/python.exe
print ("Content-type: text/html\n")
import cgi
import cgitb; cgitb.enable()
form = cgi.FieldStorage()
import pymysql
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='',db='soccer',autocommit=True)
cur = conn.cursor()
nombre = form.getfirst("nombre");
posicion = form.getf... | cecilianogranados96/Proyecto-Soccer | nuevo_jugador.py | nuevo_jugador.py | py | 977 | python | es | code | 0 | github-code | 36 |
23785755593 | from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from .views import index, PostDetail, news_all, ContactView, TeamDetail, TeamAll, club, CategoryNews, Galery, subscription, \
locations, SubscriptionView
urlpatterns = [
path('', index, name='inde... | dimaProtas/Footballab | main/urls.py | urls.py | py | 983 | python | en | code | 0 | github-code | 36 |
26850908312 | import nextcord
from nextcord.ext import commands
from nextcord import Interaction, SlashOption
from config import settings
class ExampleSlash(commands.Cog):
def __init__(self, bot):
self.bot = bot
@nextcord.slash_command(guild_ids=[settings.GUILD_ID], description="Чистка текущего канала от сообщений"... | Maxim-2005/Kurushi-DiscordBot- | cogs/example_slash.py | example_slash.py | py | 989 | python | ru | code | 0 | github-code | 36 |
12255944849 | import streamlit as st
import pandas as pd
import numpy as np
import base64
import matplotlib.pyplot as plt
import pickle
from PIL import Image
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from xgboost import XGBRegressor
fr... | SahilVora55/ROP_prediction_app | ML_app.py | ML_app.py | py | 14,851 | python | en | code | 1 | github-code | 36 |
17888105443 | from django.shortcuts import render
from django.shortcuts import Http404
from django.shortcuts import HttpResponse
from crawler.tools import crawler,indexJson,search
from django.views.decorators.csrf import csrf_protect
from json import dumps,loads
# Create your views here.
@csrf_protect
def indexPage(request):
co... | roohy/search_engine_server | crawler/views.py | views.py | py | 1,270 | python | en | code | 0 | github-code | 36 |
1353676121 | import cv2
import os
src_dir = 'H:\\document\\ocr\\src\\shixin2'
dst_dir = 'H:\\document\\ocr\\dst-test'
files = os.listdir(src_dir)
for name in files:
im = cv2.imread(os.path.join(src_dir, name))
im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(im_gray, (5, 5), 0)
ret, thres... | magicnian/court | train/pic_func.py | pic_func.py | py | 442 | python | en | code | 1 | github-code | 36 |
19247601785 | """ Contains a pipeline for generating a data set for use with the LightTag
platform
see: https://www.lighttag.io/
"""
import json
from ucla_topic_analysis import get_file_list
from ucla_topic_analysis.data import get_training_file_path
from ucla_topic_analysis.data.coroutines import create_file
from ucla_t... | swang666/applied-finance-project | UCLA-Topic-Analysis/ucla_topic_analysis/data/coroutines/light_tag.py | light_tag.py | py | 2,695 | python | en | code | 1 | github-code | 36 |
71074962345 | class Solution:
def longestPalindrome(self, s: str) -> str:
def helper(left, right):
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
return s[left+1:right]
res = ''
for i in range(len(s)):
re... | nango94213/Leetcode-solution | 0005-longest-palindromic-substring/0005-longest-palindromic-substring.py | 0005-longest-palindromic-substring.py | py | 399 | python | en | code | 2 | github-code | 36 |
23728165480 | # GEO1000 - Assignment 2
# Authors: Max van Schendel
# Studentnumbers: 4384644
from math import radians, cos, sin, asin, sqrt
def haversin(latlonl1, latlon2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
arguments:
latlon1 - tupl... | maxvanschendel/Geomatics | GEO1000/assignment_2/distance.py | distance.py | py | 1,003 | python | en | code | 0 | github-code | 36 |
1450744710 | from dash import Dash, dcc, Output, Input # pip install dash
import dash_bootstrap_components as dbc # pip install dash-bootstrap-components
import plotly.express as px
import pandas as pd # pip install pandas
import geopandas as gpd
df = pd.read_csv("rainfall.csv")
print(df.head())... | Aakanksha-Geo/Average_rainfall_in_India_Dash_Plotly | dash_rainfall_India.py | dash_rainfall_India.py | py | 2,336 | python | en | code | 0 | github-code | 36 |
74469041703 | import requests
import base45
import base64
from typing import Dict, Tuple, Optional
from cose.keys import cosekey, ec2, keyops, curves
from cryptojwt import utils as cjwt_utils
import zlib
from cose.messages import CoseMessage
from pyasn1.codec.ber import decoder as asn1_decoder
from cose.headers import Algorithm, KID... | mahadirz/MySejahtera-Private-API | api.py | api.py | py | 4,743 | python | en | code | 4 | github-code | 36 |
5185672583 | import pymysql
from .config import m_config
from dbutils.persistent_db import PersistentDB
class DBconnect:
def __init__(self, db_config):
self.config = db_config
self.POOL = self.initPool()
self.conn = self.createConnection()
def initPool(self):
POOL = PersistentDB(
... | FortyWinters/autoAnime | src/lib/connect.py | connect.py | py | 1,572 | python | en | code | 1 | github-code | 36 |
7775050449 | class edge():
def __init__(self,src, nbr, weigh):
self.src = src
self.nbr = nbr
self.weigh = weigh
graph = {}
v = int(input())
e = int(input())
for i in range(v):
graph[i]=[]
for i in range(e):
a, b, c= map(int, input().split())
graph[a].append(edge(a, b, c))
graph[b].append(edge(b, a... | nishu959/graphpepcoding | isgraphcyclic.py | isgraphcyclic.py | py | 948 | python | en | code | 0 | github-code | 36 |
74839486183 |
from lxml import etree
import pandas
def getdata(name , lb):
# htmll = etree.parse(name, etree.HTMLParser())
f = open(name, encoding="utf-8")
# 输出读取到的数据
text = f.read()
f.close()
# encode_type = chardet.detect(text)
# text = text.decode(encode_type['encoding'])
htmll = etree.HT... | chenqiuying1023/opensea-supergucci | getinfo2.py | getinfo2.py | py | 3,143 | python | en | code | 1 | github-code | 36 |
75261024425 | table = {
'0': '0000',
'1': '0001',
'2': '0010',
'3': '0011',
'4': '0100',
'5': '0101',
'6': '0110',
'7': '0111',
'8': '1000',
'9': '1001',
'a': '1010',
'b': '1011',
'c': '1100',
'd': '1101',
'e': '1110',
'f': '1111'
}
# https://adventofcode.com/2021/da... | trongbq/AoC | 2021/day16/part1.py | part1.py | py | 1,809 | python | en | code | 0 | github-code | 36 |
23519725289 | # 定义服务器参数
from socket import *
serverPort=12000 # 服务器指定的端口
# 将数据库加载入内存
from pandas import *
from database import *
from manage import *
user=read_csv('user.csv')
friend=read_csv('friend.csv')
message=read_csv('message.csv')
notice=read_csv('notice.csv')
# 处理命令
for i in range(1,200):
# 接收命令
serverSocket=socket(AF_... | lblaoke/SimpleWechat | Server/server.py | server.py | py | 2,725 | python | en | code | 0 | github-code | 36 |
284538317 | import rclpy
from rclpy.node import Node
from person_msgs.msg import Query
def cb(request, response):
if request.name == "葛西柊摩":
request.age = 19
else:
response.age = 255
return response
rclpy.init()
node = Node("talker")
srv = node.create_service(Query, "query", cb)
rclpy.spin(node)
| ShumaKasai/mypkg | mypkg/talker.py | talker.py | py | 323 | python | en | code | 0 | github-code | 36 |
41086969415 | # Импортировал библиотеки
from tkinter import *
from tkinter import messagebox
import pyperclip
import pyshorteners
# Создал окно с помощью: tkinter
root = Tk()
# Прописал название нашего окна
root.title('Link_Converter')
# Задал размер окна с помощью: geometry
root.geometry('600x400')
# Задал цвет фона, нашему окну
r... | Maksim-Lukashyk-1996/Link_Converter | LinkConverter.py | LinkConverter.py | py | 2,512 | python | ru | code | 0 | github-code | 36 |
39612322172 | import numpy as np
import os.path
import math
import scipy.linalg as _la
from math import factorial
import itertools
import time
import os
from scipy.sparse import csc_matrix
#..................................counting number of one
POPCOUNT_TABLE16 = [0] * 2**16
for index in range(len(POPCOUNT_TABLE16)):
POPCOUNT_T... | JeanClaude87/J1_J2 | code/f_function.py | f_function.py | py | 10,651 | python | en | code | 0 | github-code | 36 |
32345698677 | # this module will serve us to translate the json that is being
# outputted from the GSC to a proper SQL query.
import json
class JsontoSQLConverter():
def __init__(self, data_file, table_name):
self.data_file = data_file
self.table_name = table_name
def convert(self):
# load the da... | IliassAymaz/SofterpawIntel | SofterPawInsights/querying/jsontosql.py | jsontosql.py | py | 3,956 | python | en | code | 0 | github-code | 36 |
29658730473 | lst = [2,3,5,9,14,16,18]
target = 20
def ceiling(lst,target):
if (target > lst[len(lst)-1]):
return -1
start = 0
end = len(lst) - 1
while(start <= end):
mid = (start + (end - start)//2)
if (target < lst[mid]): # search left hand side
end = mid - 1
elif(target... | PushpakMaheshwari1/DSA-Practice | Linear_Search/Ceiling_of_a_number.py | Ceiling_of_a_number.py | py | 474 | python | en | code | 0 | github-code | 36 |
74534113703 | '''
En este ejercicio vais a crear la clase Vehículo la cual tendrá los siguientes atributos:
* Color
* Ruedas
* Puertas
Por otro lado crearéis la clase Coche la cual heredará de Vehículo y tendrá los siguientes atributos:
* Velocidad
* Cilindrada
Por último, tendrás que crear un objeto de la clas... | Zequiel92/ejercicio-clases-y-objetos | clases-y-objetos.py | clases-y-objetos.py | py | 968 | python | es | code | 0 | github-code | 36 |
73711972905 | #!/usr/bin/python3
# -*- mode: python; Encoding: utf-8; coding: utf-8 -*-
"""
----------------------------------------------------------------
clipweb
Author: ayaya (ayatec)
GitHub: https://github.com/ayatec/clipweb
----------------------------------------------------------------
"""
# ---------------------------... | ayatec/clipweb | src/python/clipweb.py | clipweb.py | py | 5,127 | python | en | code | 0 | github-code | 36 |
9965509374 | import tensorflow as tf
import numpy as np
import cv2
import random
import PIL.Image
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from modules import *
from utils import *
from RecordReaderAll import *
from SegmentationRefinement import *
HEIGHT=192
WIDTH=256
NUM_P... | art-programmer/PlaneNet | code/RecordSampler.py | RecordSampler.py | py | 4,785 | python | en | code | 386 | github-code | 36 |
3473807793 | import os
import math
import itertools
import micp.kernel as micp_kernel
import micp.info as micp_info
import micp.common as micp_common
import micp.params as micp_params
from micp.kernel import raise_parse_error
DEFAULT_SCORE_TAG = 'Computation.Avg'
class xgemm(micp_kernel.Kernel):
def __init__(self):
... | antoinecarme/xeon-phi-data | intel_software/pkg_contents/micperf/CONTENTS/usr/share/micperf/micp/micp/kernels/_xgemm.py | _xgemm.py | py | 8,876 | python | en | code | 1 | github-code | 36 |
30723392021 | def solution(record):
answer = []
user_name_dict = {}
admin_message_list = []
for rec in record:
data = rec.split(" ")
if(data[0] == 'Leave'):
in_out, user_id = data
else:
in_out, user_id, nickname = data
# 이름 변경
... | Hoony0321/Algorithm | 프로그래머스/lv2/42888. 오픈채팅방/오픈채팅방.py | 오픈채팅방.py | py | 850 | python | en | code | 0 | github-code | 36 |
6209537625 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 31 12:39:09 2023
@author: Mouhamad Ali Elamine
"""
import argparse
import json
parser = argparse.ArgumentParser(description='A1T3')
parser.add_argument('--input_file', type=str, default='./review.json', help='the input file')
parser.add_argument('--output_fi... | elami018/CSCI_5523 | HW1/task3_customized.py | task3_customized.py | py | 1,815 | python | en | code | 0 | github-code | 36 |
71346257703 | from flask import Flask
from pickView import PickView, EventAdd, EventRetrieve
app = Flask(__name__)
app.add_url_rule('/', view_func=PickView.as_view('pick_view'),
methods=['GET'])
app.add_url_rule('/eventAdd', view_func=EventAdd.as_view('event_add'),
methods=['POST'])
app.add_url_rule('/eventRetrieve', view_... | hethune/impicky | picky.py | picky.py | py | 437 | python | en | code | 0 | github-code | 36 |
11483729231 | import re
import glob
import json
import os
def get_enode_info():
result = []
prefix = '/tmp/ansible-eth-node-info-'
for file_name in glob.glob('{}*'.format(prefix)):
node_id = file_name.replace(prefix, '')
with open(file_name) as f:
content = f.read().replace('\n', '')
... | mitnk/bcli | playbooks/ethereum/generate_node_list.py | generate_node_list.py | py | 1,319 | python | en | code | 1 | github-code | 36 |
8460085849 |
#!/usr/bin/python3
# 提取目录下所有图片, 把RGB的图片修改为BGR图片保存
# from PIL import Image
import os.path
import sys, os
import cv2
def convertjpg(inputdir, outdir):
if not os.path.isdir(outdir):
os.makedirs(outdir)
files= os.listdir(inputdir) #得到文件夹下的所有文件名称
sorted_files = sorted(files)
fo... | yywbxgl/onnx_tools | python_script/img_rgb_to_bgr.py | img_rgb_to_bgr.py | py | 1,051 | python | zh | code | 2 | github-code | 36 |
12149097983 | import requests
import json
import os
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# Load token from .env file. Don't put the .env file in source control (git/devops)
token = os.environ.get("PERSONAL_TOKEN")
project_id = os.environ.get("PROJECT_ID")
# API Documentation
# (... | norwegian-geotechnical-institute/labmanager-api-demo | example.py | example.py | py | 1,691 | python | en | code | 0 | github-code | 36 |
23565719069 | # vim: set fileencoding=utf-8 :
import pytest
import pyvips
from helpers import JPEG_FILE, assert_almost_equal_objects
class TestGValue:
def test_bool(self):
gv = pyvips.GValue()
gv.set_type(pyvips.GValue.gbool_type)
gv.set(True)
value = gv.get()
assert value
gv.s... | libvips/pyvips | tests/test_gvalue.py | test_gvalue.py | py | 3,584 | python | en | code | 558 | github-code | 36 |
72745661543 | import fileinput
import copy
from math import prod
file = [x.strip() for x in fileinput.input("AoC-13-Input.txt")]
earliest_time = int(file[0])
b = file[1].split(',')
buses_one = [int(x) for x in b if not x == 'x']
lines = list(fileinput.input("AoC-13-Input.txt"))
t = lines[1].strip().split(',')
times = [(int(y),-x)... | danwigrizer/Advent-of-Code | 2020/13/AoC-13.py | AoC-13.py | py | 1,279 | python | en | code | 0 | github-code | 36 |
4035686825 | #User function Template for python3
class Solution:
def union(self, head1,head2):
temp1 = head1
temp2 =head2
l1 = set()
c1=0
c2=0
while(temp1!=None):
l1.add(temp1.data)
temp1=temp1.next
c1+=1
while(temp2!=None):
... | 20A31A0563/LeetCode | Union of Two Linked Lists - GFG/union-of-two-linked-lists.py | union-of-two-linked-lists.py | py | 1,951 | python | en | code | 0 | github-code | 36 |
33201215587 | from matplotlib import pyplot as plt
import random
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
y_3 = [random.randint(20, 35) for i in range(31)]
y_10 = [random.randint(20, 35) for i in range(31)]
x_3 = range(31)
x_10 = range(40, 71)
plt.figure(figsi... | LelouchCcCC/python-practice | python-practice/Matplotlib/案例/scatter.py | scatter.py | py | 709 | python | en | code | 0 | github-code | 36 |
19789115086 | #create tokenized descriptions
import nltk
from nltk.tokenize import word_tokenize
def tokenize(col):
#creates list of lists, inside lists contains sentences tokenized by word
list_of_lists = []
for sentence in col:
tokens = nltk.word_tokenize(str(sentence))
list_of_lists.append(tokens)
ret... | Valparaiso-Data-Science/general-course-relevance-discovery | tripodscode/analysis copy/tokenizer.py | tokenizer.py | py | 338 | python | en | code | 1 | github-code | 36 |
10809168696 | import os
import shutil
import random
import urllib.request
import zipfile
script_dir = "script/"
programs_dir = "programs/"
def copy_programs():
add_implementation = {
"python3": "pypy3",
"lua": "luajit",
"node": "js",
"php": "hhvm"
}
dir_out = script_dir + "programs/"
... | gareins/dynamic_benchmarks | init.py | init.py | py | 1,744 | python | en | code | 81 | github-code | 36 |
6410830334 | """
Задание 5 (необязательно)
Дан список произвольной длины. Необходимо написать код, который на основе исходного списка составит словарь такого
уровня вложенности, какова длина исходного списка.
Примеры работы программы:
my_list = ['2018-01-01', 'yandex', 'cpc', 100]
Результат: {'2018-01-01': {'yandex': {'cpc': 100}... | NPeganov/netology-python-1-loops2 | task5.py | task5.py | py | 1,097 | python | ru | code | 0 | github-code | 36 |
37635129073 | """ Creates a single data frame that has all the info from all the nurses.
Missing values in the time series have been filled by upsampling where needed. """
import pandas as pd
import os
def read_signal(signal):
df = pd.read_csv(os.path.join(COMBINED_DATA_PATH, f"combined_{signal}.csv"), dtype={'id': str})
... | anchan26/Nurses-Stress-Dataset | 3.merge_data_script.py | 3.merge_data_script.py | py | 1,738 | python | en | code | 0 | github-code | 36 |
4942345877 | import numpy as np
import pygame
from tile import Tile
import algorithme
from button import Button
from timer import Timer
class Board:
def __init__(
self,
name: str, # Nom de la grille
window: pygame.Surface, # Paramètre spécifiant la surface d'affichage
matrix: np.ndarray, # M... | Affell/depinfo_sudoku | board.py | board.py | py | 15,941 | python | en | code | 0 | github-code | 36 |
18036066207 | class Solution:
def maxSubArrayLen(self, nums: List[int], k: int) -> int:
sum_to_index_mapping = {} # key: cumulative sum till index i, value: i
curr_sum = max_len = 0 # set initial values for cumulative sum and max length sum to k
for i in range(len(nums)):
curr_sum += nums[i... | LittleCrazyDog/LeetCode | 325-maximum-size-subarray-sum-equals-k/325-maximum-size-subarray-sum-equals-k.py | 325-maximum-size-subarray-sum-equals-k.py | py | 1,110 | python | en | code | 2 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.