content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
def get_sitekey(driver):
return driver.find_element_by_class_name("g-recaptcha").get_attribute(
"data-sitekey"
) | python |
# Authors: James Bergstra
# License: MIT
import numpy as np
import time
import pyopencl as cl
import numpy
mf = cl.mem_flags
PROFILING = 0
ctx = cl.create_some_context()
if PROFILING:
queue = cl.CommandQueue(
ctx,
properties=cl.command_queue_properties.PROFILING_ENABLE)
else:
queue = cl.Comm... | python |
def one():
return 1
| python |
# Copyright (c) 2020 Xvezda <xvezda@naver.com>
#
# Use of this source code is governed by an MIT-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT.
__title__ = 'maskprocessor'
__version__ = '0.0.5'
| python |
from django.shortcuts import render
def index(request):
return render(request,'front_end/index.html')
def additional(request):
return render(request,'front_end/additional.html') | python |
#
# Copyright 2015 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | python |
# ===================== exercicio 4 =====================
'''
EXERCICIO: Escreva uma funcao que recebe um objeto de colecoes
e retorna o valor do maior numero dentro dessa colecao
faca outra funcao que retorna o menor numero dessa colecao
'''
def maior(colecao):
maior_item = colecao[0]
for item in c... | python |
#!/usr/bin/env python3
# Copyright (C) 2017-2020 The btclib developers
#
# This file is part of btclib. It is subject to the license terms in the
# LICENSE file found in the top-level directory of this distribution.
#
# No part of btclib including this file, may be copied, modified, propagated,
# or distributed except... | python |
from gatco.response import json, text
from application.server import app
from application.database import db
from application.extensions import auth
from random import randint
from application.models.model import User, Role,TodoSchedule,TodoScheduleDetail,EmployeeRelTodo
# @app.route("/api/v1/todoschedule", methods=... | python |
from django.conf.urls import url
from .views import message_list
from .views import message_read
urlpatterns = [
url(r'^list$', message_list),
url(r'^read/(?P<message_id>\d+)', message_read),
]
| python |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... | python |
import setuptools, os
PACKAGE_NAME = ''
VERSION = ''
AUTHOR = ''
EMAIL = ''
DESCRIPTION = ''
GITHUB_URL = ''
parent_dir = os.path.dirname(os.path.realpath(__file__))
import_name = os.path.basename(parent_dir)
with open(f'{parent_dir}/README.md', 'r') as f:
long_description = f.read()
setuptools.setup(
name=... | python |
import inspect
from pathlib import PurePath
from typing import List, Dict, Callable, Optional, Union, Tuple
from .. import util
from .calculator import Calculator
from .config_function import ConfigFunction
from .config_item import ConfigItem
from .config_item import ConfigItem
from .parser import Parser, PropertyKeys... | python |
class InitError(Exception):
pass
class SendMsgError(Exception):
pass
class GetAccessTokenError(Exception):
pass
class GetUserTicketError(Exception):
pass
class APIValueError(Exception):
pass
class UploadTypeError(Exception):
pass
class UploadError(Exception):
pass
class SuiteTi... | python |
from jinja2 import Environment, FileSystemLoader
from http_server import Content, web_server
file_loader = FileSystemLoader('templates')
env = Environment(loader=file_loader)
data = {
"name": "HMTMCSE",
"age": 30,
"register_id": 12,
}
template = env.get_template('page.html')
output = template.render(data... | python |
"""
Tests of the Block class
"""
try:
import unittest2 as unittest
except ImportError:
import unittest
from neo.core.block import Block
class TestBlock(unittest.TestCase):
def test_init(self):
b = Block(name='a block')
self.assertEqual(b.name, 'a block')
self.assertEqual(b.file_or... | python |
from django.shortcuts import render,redirect
from django.http import HttpResponse, JsonResponse
from django.http.response import HttpResponseRedirect
from django.contrib.auth import authenticate, logout
from django.contrib.auth import login as save_login
from django.contrib.auth.forms import AuthenticationForm as AF
fr... | python |
import autoparse
@autoparse.program
def main(host, port=1234, *, verbose=False, lol: [1, 2, 3] = 1):
"""Do something.
Positional arguments:
host The hostname to connect to.
port The port to connect to.
Optional arguments:
--verbose Print more status messages.
... | python |
#Programa 4.5 = Conta de telefone com três faixas de preço
minutos = int (input("Quantos minutos você utilizou este mês: "))
if minutos < 200:
preco = 0.20
else:
if minutos < 400:
preco = 0.18
else:
preco = 0.15
print(f"Você vai pagar este mês: RS {minutos * preco:6.2f}")
| python |
"""
Script reads in monthly data reanalysis (ERA-Interim or ERAi) on grid of
1.9 x 2.5 (latitude,longitude). Data was interpolated on the model grid using
a bilinear interpolation scheme.
Notes
-----
Author : Zachary Labe
Date : 19 February 2019
Usage
-----
[1] readDataR(variable,level,detrend,sli... | python |
from argparse import ArgumentParser
from dataclasses import dataclass
from typing import Optional
from environs import Env
@dataclass
class Config:
SUPERUSER: str
DATABASE_PATH: str
PBKDF2_PWD_HASHER_HASH_FUNC: str
PBKDF2_PWD_HASHER_ITERATIONS: int
PBKDF2_PWD_HASHER_SALT_LENGTH: int
MAX_YEARS... | python |
import argparse
import os
import warnings
import mmcv
import torch
from mmcv import Config, DictAction
from mmcv.cnn import fuse_conv_bn
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import (get_dist_info, init_dist, load_checkpoint,
wrap_fp16_model)
fro... | python |
#! coding: utf-8
from django.utils.translation import ugettext_lazy as _, get_language
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.core.cache import cache
from log.mod... | python |
from nltk.tree import *
#import hobbs
dp1 = Tree('dp', [Tree('d', ['the']), Tree('np', ['dog'])])
dp2 = Tree('dp', [Tree('d', ['the']), Tree('np', ['cat'])])
vp = Tree('vp', [Tree('v', ['chased']), dp2])
tree = Tree('s', [dp1, vp])
#print(tree)
t=tree.treepositions()
#print(t)
#for i in tree:
# print('\n',i,'\n')
#... | python |
"""
Depth first traversal includes 3 traversing methods:
1. Inorder
2. Preorder
3. Postorder
"""
from typing import Optional
from binary_tree_node import Node # type: ignore
def inorder(root: Optional[Node]) -> None:
"""
In inorder traversal we recursively traverse in following manner:
1. We travers... | python |
import unittest
from .solution import FreqStack
from ..utils import proxyCall
class TestCase(unittest.TestCase):
def setUp(self):
self.stack = FreqStack()
def test_example_one(self):
allCmds = ["push","push","push","push","push","push","pop","pop","pop","pop"]
allArgs = [[5],[7],[5],[... | python |
num = 1
num = 2
num=- 3
num=4
num = 5
| python |
"""
Purpose: Stackoverflow answer
Date created: 2021-01-09
URL: https://stackoverflow.com/questions/65643483/bokeh-plot-is-empty/65643667#65643667
Contributor(s):
Mark M.
"""
import re
import pandas as pd
import bokeh
sample = """
2018-10-22 7468.629883 2.282400e+09 0.263123 NASDAQ
2018-10-23 7437.540039... | python |
import os
import traceback
from copy import deepcopy
from time import sleep
import django_rq
import kubernetes.stream as stream
import websocket
from django.utils import timezone
from kubernetes import client, config
from rq import get_current_job
from api.models import KubePod, ModelRun
from master.settings import M... | python |
# email_outbound/models.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from django.core.mail import EmailMultiAlternatives
from django.apps import apps
from django.db import models
from wevote_functions.functions import extract_email_addresses_from_string, generate_random_string, \
positive_value... | python |
from django.urls import path, include
urlpatterns = [
path('launches/', include('api_spacex.launches.urls'))
]
| python |
# TRAINS - Keras with Tensorboard example code, automatic logging model and Tensorboard outputs
#
# Train a simple deep NN on the MNIST dataset.
# Gets to 98.40% test accuracy after 20 epochs
# (there is *a lot* of margin for parameter tuning).
# 2 seconds per epoch on a K520 GPU.
from __future__ import print_function
... | python |
from data.db.db import *
async def GivePlayerGold(interaction,arg1,arg2,owner_id):
if interaction.user.id==owner_id:
execute(f"SELECT Gold FROM PlayerEconomy WHERE UserID = ?",arg1)
reply = cur.fetchall()
Gold = reply[0][0]
Gold = int(Gold) + int(arg2)
execute("UPDATE Pla... | python |
from .mongodbRepositorio import conexaoBanco, inserirDocumento
import datetime
from bson import ObjectId
import re
def salvarDoadorBD(registro, nome, dt_cadastro, cidade,
bairro, grupoabo, fatorrh, fone, celular, sexo,
dt_nascimento, dt_ultima_doacao, dt_proximo_doacao, mongodb):
... | python |
import zof
APP = zof.Application(__name__)
FLOW_MOD = zof.compile('''
type: FLOW_MOD
msg:
table_id: $table
command: ADD
match: []
instructions:
- instruction: APPLY_ACTIONS
actions:
- action: OUTPUT
port_no: $port
''')
@APP.message('CHANNEL_UP')
def channel_up... | python |
#!/usr/bin/python3
# Grab data from the Riff.CC MySQL service and render it to the Curator's PostgreSQL database
# Credits:
# - https://stackoverflow.com/questions/10195139/how-to-retrieve-sql-result-column-value-using-column-name-in-python
# - https://github.com/PyMySQL/PyMySQL
# - https://stackoverflow.com/questi... | python |
#!/usr/bin/env python
# Copyright (C) 2015 Dmitry Rodionov
# This software may be modified and distributed under the terms
# of the MIT license. See the LICENSE file for details.
from ..dtrace.apicalls import apicalls
import inspect
from sets import Set
from os import sys, path
def choose_package_class(file_type, fi... | python |
from PIL import Image, ImageDraw
from vk_bot.config import *
import io, requests, random, os
from vk_bot.core.modules.basicplug import BasicPlug
from vk_bot.core.modules.upload import Upload
class Quote(BasicPlug, Upload):
doc = "Фильтр Вьетнам"
command = ("вьетнам",)
def main(self):
url = self.even... | python |
from data import Data
from projects.job import Job
import json
from .service import Service
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
class Firestore(Service):
def __init__(self, service_account_path_file, timestamp_name='timestamp', collection='default'):
... | python |
"""Prepare a lexical data file for spacy train."""
import gzip
import json
import math
import sys
import typer
from itertools import islice
from pathlib import Path
def main(
full_vocabulary_path: Path = typer.Argument(..., help='Path to the full vocabulary'),
input_vocabulary_path: Path = typer.Argument(...... | python |
# coding=utf-8
"""
Singular Value Decomposition Based Collaborative Filtering Recommender
[Rating Prediction]
Literature:
Badrul Sarwar , George Karypis , Joseph Konstan , John Riedl:
Incremental Singular Value Decomposition Algorithms for Highly Scalable Recommender Systems
Fifth I... | python |
#!/usr/bin/python
import numpy
from pylab import *
from numpy import *
from scipy import *
from scipy.stats import mode
from scipy.misc.common import factorial
from scipy.spatial.distance import correlation,euclidean
from math import log
import os
path=os.getenv('P_Dir')
#Mutual information
'''
Definition:
... | python |
from app import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
login = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
password = db.Column(db.String(120))
last_login = db.Column(db.TIMESTAMP)
def get_id(self):... | python |
import tensorflow as tf
def sample_gumbel(shape, eps=1e-20):
"""Sample from Gumbel(0, 1)"""
U = tf.random_uniform(shape,minval=0,maxval=1)
return -tf.log(-tf.log(U + eps) + eps)
def gumbel_softmax_sample(logits, temperature):
""" Draw a sample from the Gumbel-Softmax distribution"""
y = logits + s... | python |
# -*- coding: utf-8 -*-
'''
Tests neo_utils.core.
@author: Pierre Thibault (pierre.thibault1 -at- gmail.com)
@license: MIT
@since: 2010-11-10
'''
__docformat__ = "epytext en"
import unittest
from neo_utils.core import count
from neo_utils.core import every
from neo_utils.core import inverse_linked_list
from neo_ut... | python |
###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) Tavendo GmbH
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software with... | python |
#!/usr/bin/env python3
"""
Created on Fri Sep 20 12:37:07 2019
@author: mikhail-matrosov
"""
from pycoercer.basic_validator import BasicValidator
class Options():
def __init__(self,
allow_unknown=True,
purge_unknown=False,
require_all=False,
br... | python |
""" owns all PlaybackController AVS namespace interaction
https://developer.amazon.com/public/solutions/alexa/alexa-voice-service/reference/playbackcontroller
"""
from __future__ import unicode_literals
class PlaybackController(object):
""" owns all PlaybackController AVS namespace interaction """
def _... | python |
import logging
import json
import jsonpickle
from tqdm.autonotebook import tqdm
from seml.database import get_collection
from seml.settings import SETTINGS
States = SETTINGS.STATES
__all__ = ['get_results']
def parse_jsonpickle(db_entry):
import jsonpickle.ext.numpy as jsonpickle_numpy
jsonpickle_numpy.re... | python |
from airflow.decorators import dag
from airflow.providers.airbyte.operators.airbyte import AirbyteTriggerSyncOperator
from airflow.providers.airbyte.sensors.airbyte import AirbyteJobSensor
from airflow.utils.dates import days_ago
@dag(start_date=days_ago(1), schedule_interval=None, tags=["example"])
def airbyte():
... | python |
class Solution:
def partitionLabels(self, S):
"""
:type S: str
:rtype: List[int]
"""
idxes = dict(zip(S, range(len(S))))
ans, left, right = [], 0, 0
for i, ch in enumerate(S):
right = max(right, idxes[ch])
if right == i:
... | python |
from typing import AnyStr
from typing import Union
from typing import Type
from nezzle.graphics.edges.baseedge import BaseEdge
from nezzle.graphics.edges.edgefactory import EdgeClassFactory
class EdgeConverter(object):
@staticmethod
def convert(edge: BaseEdge, edge_type: Union[Type, AnyStr]):
if is... | python |
# -*- coding: utf-8 -*-
import re
import os
class Config:
src = 'src/WS101.md'
dest = 'WS101.md'
pattern = '{{import\((.+)\)}}'
def import_resource(match):
if not match:
return ''
path = match.groups()[0]
return ('# file: ' + path + '\n' +
'# ' + ('-' * (6 + len(path)... | python |
"""Public API for yq"""
load("//lib/private:yq.bzl", _is_split_operation = "is_split_operation", _yq_lib = "yq_lib")
_yq_rule = rule(
attrs = _yq_lib.attrs,
implementation = _yq_lib.implementation,
toolchains = ["@aspect_bazel_lib//lib:yq_toolchain_type"],
)
def yq(name, srcs, expression = ".", args = []... | python |
"""The output package contains the various output modules."""
from pathlib import Path
from typing import Any, Optional, Tuple
from tunable import Selectable, Tunable
from ..simulation.simulator import World
ShapeType = Tuple[int, int]
def ensure_path(path: str) -> str:
"""
Ensures that the parent director... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
##
# Copyright (C) Benjamin D. McGinnes, 2013-2018
# ben@adversary.org
# OpenPGP/GPG key: 0x321E4E2373590E5D
#
# Version: 0.1.2
#
# BTC: 1KvKMVnyYgLxU1HnLQmbWaMpDx3Dz15DVU
#
#
# Requirements:
#
# * Python 3.4 or later.
# * GPGME 1.10.0 or later with Python bindings.
#... | python |
# temp.py
import os
import time
import RPi.GPIO as GPIO
import Adafruit_DHT as dht
sensor = dht.DHT11
temp_pin =4
red= 17
green= 27
GPIO.setmode(GPIO.BCM)
GPIO.setup(green, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(red,GPIO.OUT,initial=GPIO.LOW)
GPIO.setwarnings(False)
def printTemp():
h, t = dht.r... | python |
import re
from datetime import datetime
from unittest.mock import patch
import pytest
from requests import Response
from requests.exceptions import RequestException
from http_nudger.monitor import url_check
URL = "https://google.com"
@pytest.fixture
def http_response():
resp = Response()
resp.status_code =... | python |
import numpy as np
from itertools import combinations
from sklearn import gaussian_process
from from_fits import create_image_from_fits_file
from simulations import simulate
# First find best NCLEAN using cv_cc.py
# Plot covariance matrix of the residuals (not difmap, but, probably, AIPS?)
# Plot covariogramm, GP f... | python |
def app_data_preparation(file_list, lock_period, impute):
'''
recieves file list of data file names/paths in a certain order:
1) icp das
2) metering devices
3) SVO
4) VDNH
5) COVID
6) self-isolation index
lock_period - can be specified as tuple (start date, edn date)in case new lock... | python |
"""
Boronic Acid Factory
====================
"""
from ..functional_groups import BoronicAcid
from .functional_group_factory import FunctionalGroupFactory
from .utilities import _get_atom_ids
class BoronicAcidFactory(FunctionalGroupFactory):
"""
Creates :class:`.BoronicAcid` instances.
Creates function... | python |
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 2 10:36:23 2019
@author: Bahman
"""
import csv
import math
import numpy as np
import random
from matplotlib import pyplot as plt
def readMyCSVData(fileName):
with open(fileName, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
... | python |
from opendc.models.scenario import Scenario
from opendc.models.portfolio import Portfolio
from opendc.util.rest import Response
def GET(request):
"""Get this Scenario."""
request.check_required_parameters(path={'scenarioId': 'string'})
scenario = Scenario.from_id(request.params_path['scenarioId'])
... | python |
from pdb_util import get_interatomic_distance
from gcd_pdb import read_pdb
from pdb_parsing_tools import get_resname, get_atom, isatom
# rename atoms of a particular residue according to a pair of templates
def rename_atoms_of_selected_residue(
pdbfile, resname, template_pdb_start, template_pdb_target, newfilename):... | python |
__author__ = "Alex Rudy"
__version__ = "0.6.0"
| python |
from datetime import datetime
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.executors.pool import ProcessPoolExecutor
from .models import Timelapse
from . import appbuilder
import cv2
import os
HOST_URL = appbuilder.ap... | python |
# Given a string and a pattern, find all anagrams of the pattern in the given string.
# Anagram is actually a Permutation of a string.
# Example:
# Input: String="ppqp", Pattern="pq"
# Output: [1, 2]
# Explanation: The two anagrams of the pattern in the given string are "pq" and "qp".
# Input: String="abbcabc", Patte... | python |
import numpy as np
import imageio
import cv2
import sys, os
#Processing Original Image
def process_img(location_img):
image = imageio.imread(location_img)
image = image.astype(np.float32)/255
return image
#Load and construct Ground Truth
def read_gt(location_gt):
entries = os.listdir(location_gt... | python |
import os
import urllib
from google.appengine.api import users
from google.appengine.ext import ndb
import jinja2
import webapp2
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.ext.autoescape'],
autoescape=True)
class HomePageHandler(webapp... | python |
import typing as t
from dataclasses import (
InitVar,
dataclass,
field,
)
from .container import (
DIContext,
get_di_container,
)
from .errors import (
ConfigError,
DIErrors,
)
@dataclass(frozen=True)
class Inject:
"""
A class that can serve as:
* a descriptor for a `Comp... | python |
#!/usr/bin/env python
import sys
from os import path, makedirs
from argparse import ArgumentParser
import pickle
import math
from random import sample
import numpy as np
from time import time
from scipy.signal import gaussian
from skimage import io
from skimage.feature import ORB, match_descriptors, plot_matches
fro... | python |
from typing import List, Dict
from .exceptions import ProductsNotFound
from .interfaces import CartProduct
from ...repositories.interfaces import AbstractRepository
def dict_to_products(
requested_products: List[Dict], product_repository: AbstractRepository
) -> List[CartProduct]:
requested_ids = {p["id"] fo... | python |
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
from pandas import *
import os, os.path
import sys
sys.path.append('/home/will/HIVReportGen/AnalysisCode/')
# <codecell>
store = HDFStore('/home/will/HIVReportGen/Data/SplitRedcap/2013-01-16/EntireCohort.hdf')
# <codecell>
redcap_data = store['redc... | python |
# Copyright (c) 2017 Niklas Rosenstein
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, ... | python |
from __future__ import annotations
import toolsql
contract_creation_blocks_schema: toolsql.DBSchema = {
'tables': {
'contract_creation_blocks': {
'columns': [
{
'name': 'address',
'type': 'Text',
'primary': True,
... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from argparse import ArgumentParser
from gspread import authorize
from json import dumps
from oauth2client.service_account import ServiceAccountCredentials
from copy import deepcopy
prefix_github = 'https://github.com/'
prefix_mirror = 'FIWARE-GEs/'
scope = ['https://spr... | python |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import models.spiking_util as spiking
"""
Relevant literature:
- Zenke et al. 2018: "SuperSpike: Supervised Learning in Multilayer Spiking Neural Networks"
- Bellec et al. 2020: "A solution to the learning dilemma for recurrent networks ... | python |
################################################################################
# Project : AuShadha
# Description : Surgical History Views
# Author : Dr.Easwar T.R
# Date : 16-09-2013
# License : GNU-GPL Version 3,Please see AuShadha/LICENSE.txt for details
##################################... | python |
"""First_Django_Project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home'... | python |
# -*- coding: utf-8 -*-
""" ADDL: Alzheimer's Disease Deep Learning Tool
Preprocess Pipeline:
Required arguments:
-P, --preprocess Data preprocess pipeline flag
--P_input_data_dir P_INPUT_DATA_DIR
Input directory containing original NIfTI files
--P_t... | python |
from .serverless import ServerlessHandler
| python |
#!/usr/bin/env python
#Script in dev for send commands to multiple switches at once through Telnet.
import telnetlib
import time
TELNET_PORT = 23
TELNET_TIMEOUT = 6
def send_command(remote_conn, cmd):
cmd = cmd.rstrip()
remote_conn.write(cmd + '\n')
time.sleep(6)
return remote_conn.read_very_eager()... | python |
# Importar librería
import os
# Declaracion de variables
clientes = []
numCuentas = 0
opcion = 0
# Declaración de métodos
def crearCuenta(clientes):
global numCuentas
# Con este método se crea una cuenta bancaria
nombre = input('Introduzca nombre: ')
apellido = input('Introduzca apellido: ')
# Se crea lista ... | python |
from kedro.pipeline import Pipeline
from kedro_mlflow.pipeline.pipeline_ml import PipelineML
def pipeline_ml(
training: Pipeline, inference: Pipeline, input_name: str = None,
) -> PipelineML:
pipeline = PipelineML(
nodes=training.nodes, inference=inference, input_name=input_name
)
return pipe... | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#http://www.cnblogs.com/way_testlife/archive/2011/04/17/2019013.html
import Image
im = Image.open("a.jpg")
#分别打印图片的原格式,高和宽的数组、颜色模式
print im.format, im.size, im.mode
#显示图片
im.show()
| python |
# ----------------------------------
# CLEES DirectControl
# Author : Tompa
# ----------------------------------
# --- General libs
import json
# --- Private Libs
import clees_mqtt
# VAR ---
Dircntl = []
Repmsg = []
def init():
global Dircntl
global Repmsg
with open... | python |
from flask import Flask, request, jsonify
import json
import requests
import shutil
import logging
import boto3
from botocore.exceptions import ClientError
import os
from flask_sqlalchemy import SQLAlchemy
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from datetime import datetime
... | python |
# -*- coding: utf-8 -*-
"""
Created on Tue May 29 11:23:10 2018
@author: eemeg
"""
def ICASAR(n_comp, spatial_data = None, temporal_data = None, figures = "window",
bootstrapping_param = (200,0), ica_param = (1e-4, 150), tsne_param = (30,12), hdbscan_param = (35,10),
out_folder = '... | python |
#!/usr/bin/env python3
"""
Aggregate machine ads into time bins by site
"""
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
import elasticsearch
import elasticsearch_dsl as edsl
import datetime
import dateutil
import re
import logging
import time
from urllib.parse import urlparse, urlunparse
def ... | python |
# file: asynchronous-inquiry.py
# auth: Albert Huang <albert@csail.mit.edu>
# desc: demonstration of how to do asynchronous device discovery by subclassing
# the DeviceDiscoverer class
# $Id: asynchronous-inquiry.py 405 2006-05-06 00:39:50Z albert $
#
# XXX Linux only (5/5/2006)
import bluetooth
import select
c... | python |
#!/usr/bin/env python
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, window, asc, desc, lead, lag, udf, hour, month, stddev, lit
from pyspark.sql.window import Window
from pyspark.sql.types import FloatType, IntegerType, DateType
from pyspark import SparkConf
import yaml
import datetime
imp... | python |
from django.core.exceptions import ValidationError
from cyder.base.tests import ModelTestMixin
from cyder.core.ctnr.models import Ctnr
from cyder.core.system.models import System
from cyder.cydhcp.constants import STATIC
from cyder.cydhcp.interface.static_intr.models import StaticInterface
from cyder.cydhcp.network.mo... | python |
"""
This file is part of the opendrive-beamng project.
--------------------------------------------------------------------------------
Server class - deals with initialization, configuring of the environment, sim
launch and socket comms.
Notes:
- Set `BNG_HOME` env variable to beamNG.tech path
TODO:
- Swit... | python |
import discord
import gspread
from discord.ext import commands
from oauth2client.service_account import ServiceAccountCredentials
from gspread.exceptions import CellNotFound
class Gsheets:
@classmethod
def start(cls):
"""Starts gsheets API instance."""
scope = ['https://spreadsheets.google.com... | python |
import sys
import os
import numpy as np
import time
from PIL import Image
APS = 100;
TileFolder = sys.argv[1] + '/';
heat_map_out = 'patch-level-color.txt';
def whiteness(png):
wh = (np.std(png[:,:,0].flatten()) + np.std(png[:,:,1].flatten()) + np.std(png[:,:,2].flatten())) / 3.0;
return wh;
def blackness(p... | python |
# see: https://github.com/gabrielfalcao/HTTPretty/issues/242#issuecomment-160942608
from httpretty import HTTPretty as OriginalHTTPretty
try:
from requests.packages.urllib3.contrib.pyopenssl \
import inject_into_urllib3, extract_from_urllib3
pyopenssl_override = True
except:
pyopenssl_override = Fa... | python |
import contextlib
import random
import time
from sorting import (
bubble_sort,
selection_sort,
insertion_sort,
merge_sort,
)
@contextlib.contextmanager
def timeit(name):
start = time.time()
yield
end = time.time()
took = end - start
print(f"The {name} took {took:.4f}s")
def near... | python |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from TreeNode import *
class Solution:
def recoverFromPreorder(self, S: str) -> TreeNode:
s = S.split("-") # s = ['1... | python |
# Generated by Django 3.0.2 on 2020-01-12 12:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('newshows', '0002_setting_profile'),
]
operations = [
migrations.AddField(
model_name='setting',
name='... | python |
import requests
import json
#Assignment Object
#Properties: TOKEN, id, name, description, created_at, updated_at, due_at
#Functions:
class Assignment:
def __init__(self, TOKEN, assignment_id, assignment_name, assignment_description, assignment_created_at, assignment_updated_at, assignment_due_at):
self.TO... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.