content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
__author__ = 'Sergei'
from model.contact import Contact
class ContactHelper:
def __init__(self, app):
self.app = app
def fill_contact_first_last(self, Contact):
wd = self.app.wd
wd.find_element_by_name("firstname").click()
wd.find_element_by_name("firstname").clear()
w... | python |
"""
twtxt.models
~~~~~~~~~~~~
This module implements the main models used in twtxt.
:copyright: (c) 2016 by buckket.
:license: MIT, see LICENSE for more details.
"""
from datetime import datetime, timezone
import humanize
from dateutil.tz import tzlocal
class Tweet:
"""A :class:`Tweet` rep... | python |
# %% [markdown]
## Acessando todos os parâmetros (genérico)
# %%
def todos_params(*posicionais, **nomeados):
print(f'Posicionais: {posicionais}')
print(f'Nomeados: {nomeados}\n')
todos_params(1,2,3) #3 Parâmetros posicionais e nenhum parâmetro nomeado
todos_params(1,2,3, nome='Victor', solteiro=True) #3 parâ... | python |
import numpy as np
from ivory.callbacks.results import concatenate
def test_libraries(runs):
for run in runs.values():
run.start("both")
for mode in ["val", "test"]:
outputs = []
for run in runs.values():
outputs.append(run.results[mode].output)
for output in out... | python |
from sqlalchemy.orm import Session
from apps.crud.pusher import get_pushers_by_token, get_pushers_by_token_and_type
from apps.serializer.record import RecordSerializer
from apps.pusher import test_wechat, official_wechat, e_mail, android, wechat, qq
type_func_dict = {
1: test_wechat.send_msg,
2: official_wec... | python |
from __future__ import print_function
import logging
import pandas as pd
import numpy as np
import scipy.stats as stats
from matplotlib.backends.backend_pdf import PdfPages
import os.path
from .storemanager import StoreManager
from .condition import Condition
from .constants import WILD_TYPE_VARIANT
from .sfmap import ... | python |
import sys
import os
import glob
import shutil
import xml.etree.ElementTree as ET
if not os.path.exists("../results/"):
os.makedirs("../results/")
if os.path.exists("../results/detection/"):
shutil.rmtree("../results/detection/")
os.makedirs("../results/detection/")
# create VOC format files
xml_list = [f for f i... | python |
"""
Calculate the number of proteins per kingdom / phylum / genus / species per genera for the phages
"""
import os
import sys
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Calculate the kingdom / phylum / genus / species per genera for the phages")
parser.add_argume... | python |
from flask_restful import Resource, reqparse, request
from lib.objects.namespace import Namespace
from lib.objects.lock import Lock
class LockController(Resource):
# TODO Check access as separate method or decorator
# https://flask-restful.readthedocs.io/en/latest/extending.html#resource-method-decorators
... | python |
__author__ = "Polymathian"
__version__ = "0.3.0"
| python |
# coding=utf-8
"""
The MIT License
Copyright (c) 2013 Mustafa İlhan
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, modi... | python |
# This is automatically-generated code.
# Uses the jinja2 library for templating.
import cvxpy as cp
import numpy as np
import scipy as sp
# setup
problemID = "quantile_0"
prob = None
opt_val = None
# Variable declarations
# Generate data
np.random.seed(0)
m = 400
n = 10
k = 100
p = 1
sigma = 0.1
x = np.rand... | python |
from starlette.config import Config
# Configuration from environment variables or '.env' file.
config = Config(".env")
DB_NAME = config("DB_NAME")
TEST_DB_NAME = config("TEST_DB_NAME")
DB_USER = config("DB_USER")
DB_PASSWORD = config("DB_PASSWORD")
DB_HOST = config("DB_HOST")
DB_PORT = config("DB_PORT")
SECRET_KEY = c... | python |
"""Migration for the Submitty system."""
import os
def up(config):
"""
Run up migration.
:param config: Object holding configuration details about Submitty
:type config: migrator.config.Config
"""
os.system("apt install -qy python3-numpy")
os.system("apt install -qy python3-opencv")
os... | python |
# -*- coding: utf-8 -*-
from sqlalchemy import Column, String, Integer, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from src.model.base import Base
from src.model.EstacaoZona import EstacaoZona
class Zona(Base):
__tablename__ = 'Zona'
Zona_id = Column... | python |
import matplotlib.pyplot as plt
from playLA.Matrix import Matrix
from playLA.Vector import Vector
import math
if __name__ == "__main__":
points = [[0, 0], [0, 5], [3, 5], [3, 4], [1, 4],
[1, 3], [2, 3], [2, 2], [1, 2], [1, 0]]
x = [point[0] for point in points]
y = [point[1] for point in poin... | python |
import ast
import json
import os
from base_automation import report
# ---------------------------- terminal ------------------------------------#
@report.utils.step('send terminal command: {command}')
def terminal_command(command):
try:
step_data(f"send command to terminal:\n{command}")
return os... | python |
# PLUGIN MADE BY DANGEROUSJATT
# KEEP CREDIT
# MADE FOR HELLBOT
# BY TEAM HELLBOT
# NOW IN darkbot
import math
from darkbot.utils import admin_cmd, sudo_cmd, edit_or_reply
from userbot import CmdHelp
from userbot import bot as darkbot
@darkbot.on(admin_cmd(pattern="sin ?(.*)"))
@darkbot.on(sudo_cmd(pattern="sin ?(.... | python |
# Copyright 2021 cstsunfu. All rights reserved.
#
# 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 agr... | python |
import os
import os.path
from os.path import exists
import hashlib
import json
import uuid
import pprint
import unittest
from pathlib import Path
from collections import defaultdict
import settings
import pathlib
from cromulent import model, vocab, reader
from cromulent.model import factory
from pipeline.util import C... | python |
import logging
from datalad_lgpdextension.utils.dataframe import Dataframe
from datalad_lgpdextension.writers.dataframe import Dataframe as dfutils
from datalad_lgpdextension.utils.folder import Folder
from datalad_lgpdextension.runner.actions import Actions
from datalad_lgpdextension.utils.generate_config import Gener... | python |
class LinkedListNode:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.num_elements = 0
self.head = None
def push(self, data):
new_node = LinkedListNode(data)
if self.head is None:
self.head = ne... | python |
import numpy as np
def project(W, X, mu=None):
if mu is None:
return np.dot(X,W)
return np.dot(X - mu, W)
def reconstruct(W, Y, mu=None):
if mu is None:
return np.dot(Y,W.T)
return np.dot(Y, W.T) + mu
def pca(X, y, num_components=0):
[n,d] = X.shape
if (num_components <= 0) or (num_components>n):
num_com... | python |
import pytest
from copy import deepcopy
import mosdef_cassandra as mc
import unyt as u
from mosdef_cassandra.tests.base_test import BaseTest
from mosdef_cassandra.writers.inp_functions import generate_input
from mosdef_cassandra.writers.writers import write_mcfs
from mosdef_cassandra.utils.tempdir import *
class Tes... | python |
class Solution:
def largestPerimeter(self, A: List[int]) -> int:
A.sort()
for i in range(len(A)-1, 1, -1):
if A[i-2] + A[i-1] > A[i]:
return A[i-2] + A[i-1] + A[i]
else:
return 0
| python |
class Permissions(object):
# ccpo permissions
VIEW_AUDIT_LOG = "view_audit_log"
VIEW_CCPO_USER = "view_ccpo_user"
CREATE_CCPO_USER = "create_ccpo_user"
EDIT_CCPO_USER = "edit_ccpo_user"
DELETE_CCPO_USER = "delete_ccpo_user"
# base portfolio perms
VIEW_PORTFOLIO = "view_portfolio"
#... | python |
'''
任意累积
描述
请根据编程模板补充代码,计算任意个输入数字的乘积。
注意,仅需要在标注...的地方补充一行或多行代码。
'''
def cmul(a, *b):
input(a)
m = a
for i in b:
m *= i
return m
print(eval("cmul({})".format(input())))
'''
该程序需要注意两个内容:
1. 无限制数量函数定... | python |
from src.preprocessor import preprocessor as preprocessor
from src.error import ApplicationError, error_list
from src.aggregator import Aggregator
from src.constants import MIN_CONTENT_LEN
from flask import Blueprint, request, jsonify
from flask_cors import cross_origin
import io
from flask_limiter import Limiter
from... | python |
'''
@author: Sergio Rojas
@contact: rr.sergio@gmail.com
--------------------------
Contenido bajo
Atribución-NoComercial-CompartirIgual 3.0 Venezuela (CC BY-NC-SA 3.0 VE)
http://creativecommons.org/licenses/by-nc-sa/3.0/ve/
Creado en abril 23, 2016
'''
import matplotlib.pyplot as plt
x = [1.5, 2.7, 3.8, 9.5,12.3]... | python |
import numpy as np
from Activations import Activations
class Layer:
def __init__(self, nNeurons, activation=Activations.linear, input=np.array([0.0])):
if type(input) == Layer:
self.inputs = input.forward()
self.inputLayer = input
else:
self.inputs = np.array([i... | python |
from baconian.common.special import *
from baconian.core.core import EnvSpec
from copy import deepcopy
import typeguard as tg
from baconian.common.error import *
class SampleData(object):
def __init__(self, env_spec: EnvSpec = None, obs_shape=None, action_shape=None):
if env_spec is None and (obs_shape is... | python |
# BSD LICENSE
#
# Copyright(c) 2010-2015 Intel Corporation. All rights reserved.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copy... | python |
#!/usr/bin/python
# Copyright (c)2012 EMC Corporation
# All Rights Reserved
# This software contains the intellectual property of EMC Corporation
# or is licensed to EMC Corporation from third parties. Use of this
# software and the intellectual property contained therein is expressly
# limited to the terms an... | python |
from django.shortcuts import render
from django.shortcuts import get_object_or_404
# from rest_framework import status
# from rest_framework.permissions import IsAuthenticated, IsAdminUser
# from rest_framework.response import Response
# from rest_framework import viewsets
from findance import abstract
from .models im... | python |
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from urlparse import urlparse, parse_qs
import argparse
import concoction
class WebServer(BaseHTTPRequestHandler):
def _set_headers(self):
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()... | python |
from flask import request
from app import newjson,jsonify
from . import api,base_dir
from ..model.live2d import live2dConfig,live2dModel
import os,json
@api.route("/live2d/config/get",endpoint="live2d-config-get",methods = ["GET","POST"])
def live2d_getConfig():
config = request.values.get("config","default",type=... | python |
from django.apps import AppConfig
class FourAppConfig(AppConfig):
name = 'four_app'
| python |
# coding: latin-1
###############################################################################
# eVotUM - Electronic Voting System
#
# generateSecret-app.py
#
# Cripto-4.4.1 - Commmad line app to exemplify the usage of generateSecret
# function (see shamirsecret.py)
#
# Copyright (c) 2016 Universidade do Minho... | python |
import pandas as pd
from actymath.columns.base import Column
from actymath.calc import register
class TestColumn1(Column):
column_name = "q(x{life})"
parameters = {"life": "test"}
dependencies = []
class TestColumn2(Column):
column_name = "timestamp"
parameters = {}
dependencies = []
def t... | python |
#!/bin/env python
#===============================================================================
# NAME: test_api.py
#
# DESCRIPTION: A basic test framework for integration testing.
# AUTHOR: Kevin Dinkel
# EMAIL: dinkel@jpl.nasa.gov
# DATE CREATED: November 19, 2015
#
# Copyright 2015, California Institute of Techn... | python |
from textual import events
from textual.app import App
from textual.widgets import Header, Footer, Placeholder, ScrollView
import json
from rich.panel import Panel
from textual.app import App
from textual.reactive import Reactive
from textual.widget import Widget
import pandas as pd
import numpy as np
from rich.ta... | python |
import time
import pickle
import json
import numpy as np
from threading import Thread
from typing import Dict, List
from nxs_libs.queue import *
from azure.core import exceptions as AzureCoreException
from azure.storage.queue import (
QueueClient,
)
class NxsAzureQueuePuller(NxsQueuePuller):
def __init__(se... | python |
from lib_rovpp import ROVPPV1SimpleAS, ROVPPV1LiteSimpleAS
from .trusted_server import TrustedServer
from lib_secure_monitoring_service.sim_logger import sim_logger as logger
from lib_secure_monitoring_service.report import Report
class ROVSMS(ROVPPV1LiteSimpleAS):
name="ROV V4"
__slots__ = tuple()
tru... | python |
# Copyright 2021 Intel Corporation
#
# 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 |
from keras.models import load_model
from keras.optimizers import SGD, Adam
from skimage.io import imshow
from cnnlevelset.pascalvoc_util import PascalVOC
from cnnlevelset.localizer import Localizer
from cnnlevelset.generator import pascal_datagen, pascal_datagen_singleobj
from cnnlevelset import config as cfg
import s... | python |
from .InteractionRedshift import InteractionRedshift | python |
N = int(raw_input())
if N < 0:
print N * -1
else:
print N
| python |
#!/usr/bin/python
#
# Nagios class.
#
version = "1.2.2"
from core import *
| python |
"""
Created on Wed Feb 5 13:04:17 2020
@author: matias
"""
import numpy as np
from matplotlib import pyplot as plt
from scipy.optimize import minimize
import emcee
import corner
from scipy.interpolate import interp1d
import sys
import os
from os.path import join as osjoin
from pc_path import definir_path
path_git,... | python |
"""Linear Classifiers."""
import numpy as np
from abc import ABC, abstractmethod
from alchina.exceptions import InvalidInput, NotFitted
from alchina.metrics import accuracy_score
from alchina.optimizers import GradientDescent
from alchina.preprocessors import Standardization
from alchina.utils import check_dataset_c... | python |
"""
This is a crawler that downloads 'friends' screenplays.
"""
import re
import requests
from bs4 import BeautifulSoup
from seinfeld_laugh_corpus.corpus_creation.screenplay_downloader.screenplay_downloader import ScreenplayDownloader
def run(input_filename, output_filename):
screenplay_downloader = SeinfeldScr... | python |
"a shared stack module"
stack = []
class error(Exception): pass
def push(obj):
global stack
stack = [obj] + stack
def pop():
global stack
if not stack:
raise error('stack underflow')
top, *stack = stack
return top
def top():
if not stack:
raise error('stack underflow')
... | python |
def solution(A): # O(N)
"""
Given a variable length array of integers, partition them such that the even
integers precede the odd integers in the array. Your must operate on the array
in-place, with a constant amount of extra space. The answer should sc... | python |
# -*- coding: utf-8 -*-
# pylint: disable=redefined-outer-name
"""
Some simple unit tests of the Counter device, exercising the device from
the same host as the tests by using a DeviceTestContext.
"""
import logging
import time
import pytest
import tango
from tango.test_utils import DeviceTestContext
from ska_tango_e... | python |
#!/bin/python3
# Imports
import math
import os
import random
import re
import sys
#
# Instructions
#
def solution_function(a, b):
# Write your code here
return [a, b]
if __name__ == '__main__':
a_count = int(input().strip())
a = []
for _ in range(a_count):
a_item = input()
a.... | python |
# 2017-04-16
"""
Using first half of Knuth-Morris-Pratt (KMP) pattern-matching
for shortest repeating sub-pattern (SRSP) determination in O(n) time
Left edge and right edge are "sacred" locations. If we have a repeating sub-pattern that covers the whole input string, it will exist starting at left edge and exist en... | python |
"""
https://wiki.jikexueyuan.com/project/easy-learn-algorithm/floyd.html
"""
def floyd_warshall(edges, V):
# dp: 顶点对 (i,j) 间距离
dp = [[float('inf')] * V for _ in range(V)]
for i in range(V):
dp[i][i] = 0
# 根据 edges 初始化
for u, v, w in edges:
dp[u][v] = w
# 选择引入中间... | python |
import logging
log = logging.getLogger('agents')
from enforce_typing import enforce_types
from typing import List, Dict
import random
import math
from web3engine import bfactory, bpool, datatoken, dtfactory, globaltokens
from engine.AgentBase import AgentBase
from web3tools.web3util import toBase18
from util.constant... | python |
import os
import tempfile
import tensorflow as tf
from tensorflow.contrib.layers import fully_connected as fc
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.python.client import timeline
batch_size = 100
inputs = tf.placeholder(tf.float32, [batch_size, 784])
targets = tf.placeh... | python |
from .model import FaPN | python |
import sys
import vnpy_chartwizard
sys.modules[__name__] = vnpy_chartwizard
| python |
level = 3
name = 'Arjasari'
capital = 'Patrolsari'
area = 64.98
| python |
"""
模块功能:
1. 采集批改网所有在库作文数据
2. 清洗,预处理
3. 入库信息键:pid作文号、title作文标题、abstract简介、refer参考答案{可能为空}、
spider_time采集时间、source_href答题页面访问链接
"""
from gevent import monkey
monkey.patch_all()
import json
import requests
from lxml import etree
import gevent
from gevent.queue import Queue
from fake_useragent import UserAgent
work_q =... | python |
import threading
import csv
import re
from sqlalchemy import create_engine
from IPython.display import display, Javascript, HTML
from ..python_js.interface_js import load_js_scripts
def threaded(fn):
def wrapper(*args, **kwargs):
threading.Thread(target=fn, args=args, kwargs=kwargs).start()
return wra... | python |
from microbit import *
from math import sqrt
while True:
x, y, z = accelerometer.get_values()
acc = sqrt(x*x + y*y + z*z)
y = int(2 + (acc - 1000) / 100)
display.clear()
if y < 0:
y = 0
if y > 4:
y = 4
for x in range(0, 5):
display.set_pixel(x, y, 9) | python |
from datetime import datetime, timedelta
from discord.ext import commands
from lib.mysqlwrapper import mysql
from lib.rediswrapper import Redis
from typing import Optional
import discord
import lib.embedder
import logging
import uuid
class FriendCode(commands.Cog):
def __init__(self, client):
self.client ... | python |
# -*- coding: utf-8 -*-
# Scrapy settings for telesurscraper project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org/en... | python |
t = int(input())
for q in range(t):
#n,k=input().split()
#n,k=int(n),int(k)
#n,m,k=input().split()
#n,m,k=int(n),int(m),int(k)
#n=int(input())
#n=int(input())
#arr=list(map(int,input().split()))
num=int(input())
n=num%8
if(n==0):
print(num-1,"SL",sep="")... | python |
import pandas as pd
import numpy as np
from sklearn.base import BaseEstimator
from sklearn.base import TransformerMixin
class Clipper(BaseEstimator, TransformerMixin):
def __init__(self, params = {}):
super().__init__()
self.name = self.__class__.__name__
self.p... | python |
# MIT License
#
# Copyright (c) 2017 Tom Runia
#
# 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, ... | python |
from .plot import Plot
import matplotlib.pyplot as plt
from .plot_funcs import average_traits
import numpy as np
class AverageTraitTime(Plot):
def __init__(self):
self.avgtraits = {}
def plot(self, game:"Game", file_path:str, height:int, width:int) -> None:
"""Plot the game information savin... | python |
#!/usr/bin/env python
# Copyright 2011-2021 IBM Corporation
#
# 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 la... | python |
"""Rx Workshop: Observables versus Events.
Part 2 - Dispose Example.
Usage:
python wksp3.py
"""
from __future__ import print_function
import rx
class Program:
"""Main Class.
"""
@staticmethod
def main():
"""Main Method.
"""
subject = rx.subjects.Subject()
subscr... | python |
from __future__ import print_function
import numpy as np
import testing as tm
import unittest
import pytest
import xgboost as xgb
try:
from sklearn.linear_model import ElasticNet
from sklearn.preprocessing import scale
from regression_test_utilities import run_suite, parameter_combinations
except ImportE... | python |
import PIL
print(PIL.PILLOW_VERSION)
import load_data
from load_data import *
import load_data
import gc
import matplotlib.pyplot as plt
from torch import autograd
import patch_config
plt.rcParams["axes.grid"] = False
plt.axis('off')
img_dir = "inria/Train/pos"
lab_dir = "inria/Train/pos/yolo-labels"
... | python |
import time
import os
import getopt
import sys
import datetime
import numpy as np
from milvus import *
import config
import logging
import random
milvus = Milvus()
def is_normalized():
filenames = os.listdir(NL_FOLDER_NAME)
filenames.sort()
vetors = load_vec_list(NL_FOLDER_NAME+'/'+filenames[0])
for ... | python |
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QDateTime, QTimer
# from openssl_lib import OpenSSLLib
from .set_csr import SetCSRView
class CSRData:
def __init__(self):
self.country_name = ''
self.state_name = ''
self.locality_name = ''
self.o... | python |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... | python |
#Python program for continuous and discrete sine wave plot
import numpy as np
import scipy as sy
from matplotlib import pyplot as plt
t = np.arange(0,1,0.01)
#frequency = 2 Hz
f = 2
#Amplitude of sine wave = 1
PI = 22/7
a = np.sin(2*PI*2*t)
#Plot a continuous sine wave
fig, axs = plt.subplots(1,2)
axs[0].... | python |
"""
Module containing NHL game objects
"""
from dataclasses import dataclass
from .flyweight import Flyweight
from .list import List
from .gameinfo import GameInfo
from .team import Team
from .venue import Venue
@dataclass(frozen=True)
class Game(Flyweight):
"""
NHL game object.
This is the detailed docs... | python |
#!/usr/bin/env python
"""Base class for model elements."""
from __future__ import annotations
import logging
import uuid
from typing import TYPE_CHECKING, Callable, Iterator, Protocol, TypeVar, overload
from gaphor.core.modeling.event import ElementUpdated
from gaphor.core.modeling.properties import (
attribute,... | python |
#!/usr/bin/env python
"""
@script: DeployerApp.py
@purpose: Deployer for HomeSetup
@created: Nov 12, 2019
@author: <B>H</B>ugo <B>S</B>aporetti <B>J</B>unior
@mailto: yorevs@hotmail.com
@site: https://github.com/yorevs/homesetup
@license: Please refer to <https://opensource.org/licenses/MIT>
"""
#... | python |
import numpy as np
from deep500.lv0.operators.operator_interface import CustomPythonOp
from deep500.frameworks.reference.custom_operators.python.conv_op_common import get_pad_shape, get_output_shape, get_fullconv_pad_shape, crosscorrelation, crosscorrelation_dilx_flipw, crosscorrelation_swap_axes
from deep500 import Te... | python |
"""CelebA data-module."""
from typing import Any
import albumentations as A
import attr
from pytorch_lightning import LightningDataModule
from ranzen import implements
from conduit.data.datamodules.base import CdtDataModule
from conduit.data.datamodules.vision.base import CdtVisionDataModule
from conduit.data.dataset... | python |
import pytest
def test_repr(module):
v = module.Dict({"x": module.Int(min=0, max=100)}, nullable=True)
assert repr(v) == (
"<Dict(schema=frozendict({'x': <Int(min=0, max=100)>}), nullable=True)>"
)
v = module.Dict({"x": module.LazyRef("foo")})
assert repr(v) == "<Dict(schema=frozendict({'... | python |
"""
Copyright 2021 Dynatrace LLC
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 writing, software
... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Define the main basic Camera interface
This defines the main basic camera interface from which all other interfaces which uses a camera inherit from.
"""
from pyrobolearn.tools.interfaces.interface import InputInterface
__author__ = "Brian Delhaisse"
__copyright__ = "... | python |
# Kenny Sprite Sheet Slicer
# KennySpriteSlice.py
# Copyright Will Blankenship 2015
# This will attempt to correctly slice sprite sheets from the Kenny Donation Collection
import xml.etree.ElementTree
from PIL import Image
import shutil
import os
from .Sprite import Sprite
from .Error import Error
from .SpriteMetaFi... | python |
from quantitative_node import QuantitativeNode
from qualitative_node import QualitativeNode
from dataset import Dataset
from leaf_node import Leaf
from dparser import DParser
import numpy as np
import info_gain
import random
import time
import math
isBenchmark = False
def getMostFrequentClass(result_vector):
if r... | python |
from ad_api.base import Client, sp_endpoint, fill_query_params, ApiResponse
class NegativeKeywords(Client):
@sp_endpoint('/v2/sp/negativeKeywords/{}', method='GET')
def get_negative_keyword(self, keywordId, **kwargs) -> ApiResponse:
r"""
get_negative_keyword(self, keywordId, \*\*kwargs) -> Ap... | python |
# -*- encoding: utf-8 -*-
"""Initialization of Flask REST-API Environment"""
from flask import Flask
from flask_bcrypt import Bcrypt # Bcrypt hashing for Flask
from flask_sqlalchemy import SQLAlchemy
from .config import config_by_name
db = SQLAlchemy() # database object
flask_bcrypt = Bcrypt() # bcrypt hashin... | python |
from context import DBVendor, DBConnection, DBContext
from converters import *
from datasource import * | python |
from collections import OrderedDict
from typing import List
from typing import Union, Dict, Callable, Any
from tequila.ml.utils_ml import preamble, TequilaMLException
from tequila.objective import Objective, Variable, vectorize, QTensor
from tequila.tools import list_assignment
from tequila.simulators.simulator_api i... | python |
import setuptools
setuptools.setup(
name="epaper_standalone",
version="4.0",
license="Apache-2.0",
author="Steve Zheng",
description="Show time, weather and calendar.",
packages=setuptools.find_packages(exclude=['test']),
setup_requires=['Pillow>=5.4'],
package_data={
'cwt': ['u... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''Tests for the virtual file system.'''
from __future__ import unicode_literals
import os
import unittest
from UnifiedLog import virtual_file
from UnifiedLog import virtual_file_system
from tests import test_lib
class VirtualFileSystemTests(test_lib.BaseTestCase):
... | python |
def number_of_equal_elements(list1, list2):
return sum([x == y for x, y in zip(list1, list2)])
| python |
# Portions of code used in this file and implementation logic are based
# on lightgbm.dask.
# https://github.com/microsoft/LightGBM/blob/b5502d19b2b462f665e3d1edbaa70c0d6472bca4/python-package/lightgbm/dask.py
# The MIT License (MIT)
# Copyright (c) Microsoft Corporation
# Permission is hereby granted, free of charg... | python |
import xlsxwriter
class Writer:
def __init__(self, file, name):
self.excelFile = xlsxwriter.Workbook(file)
self.worksheet = self.excelFile.add_worksheet(name)
self.row = 0
self.col = 0
def close(self):
self.excelFile.close()
def write(self, identify, title, score)... | python |
n1 = int(input('Digite um valor:'))
n2 = int(input('digite outro valor:'))
s = n1 + n2
print('A soma de {} e {} vale:{}'.format(n1, n2, s))
| python |
import logging
import time
import alsaaudio
import webrtcvad
from .exceptions import ConfigurationException
logger = logging.getLogger(__name__)
class Capture(object):
MAX_RECORDING_LENGTH = 8
VAD_SAMPLERATE = 16000
VAD_FRAME_MS = 30
VAD_PERIOD = int((VAD_SAMPLERATE / 1000) * VAD_FRAME_MS)
VAD_SILENCE_TIMEO... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.