content
stringlengths
5
1.05M
import torch.nn as nn # 5th Edition: VggNet-16 (up to 90.189%) def Conv3x3BNReLU(in_channels, out_channels): return nn.Sequential( nn.Conv2d(in_channels, out_channels, 3, 1, 1), nn.BatchNorm2d(out_channels), nn.ReLU6(True) ) class VGGNet(nn.Module): def __init__(self): # (train...
import sys sys.path.append('../') import os from pathlib import Path import time import numpy as np import scipy.optimize import pickle from py_diff_pd.common.common import ndarray, create_folder, rpy_to_rotation, rpy_to_rotation_gradient from py_diff_pd.common.common import print_info, print_ok, print_error, PrettyT...
from radix_sort import radix_sort def test_empty_list(): """An empty list will return unchanged""" lst = [] expected = [] actual = radix_sort(lst) assert actual == expected def test_single_item_list(): """A one-itemed list will return unchanged""" lst = [100] expected = [100] a...
import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm, t from scipy.optimize import minimize def pseudo_obs(data): """ take dataframe as argument and returns Pseudo-observations from real data X """ pseudo_obs = data for i in range(len(dat...
import os for dirname, _, filenames in os.walk('/kaggle/input'): for filename in filenames: print(os.path.join(dirname, filename)) def load_images_from_folder(folder): images = [] for filename in os.listdir(folder): img = cv2.imread(os.path.join(folder,filename)) if img is ...
import cv2 import numpy as np img = cv2.imread('download.jpeg') ret, threshold = cv2.threshold(img, 12, 255, cv2.THRESH_BINARY) im2gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, threshold = cv2.threshold(im2gray, 10, 255, cv2.THRESH_BINARY) adaptive_threshold = cv2.adaptiveThreshold(im2gray, 255, cv2.ADAPT...
from typing import Dict, List from MicroTokenizer import get_dict_file from MicroTokenizer.data_structures.dictionary import DictionaryData from MicroTokenizer.data_structures.non_recursive_algorithm import NonRecursiveAlgorithm from MicroTokenizer.data_structures.train_dictionary import TrainDictionary from MicroToke...
import openpyxl from openpyxl import load_workbook wb = load_workbook("testFiles/basicTest.xlsx") name_list = wb.get_sheet_names() print(name_list) ws = wb['Sheet1'] ws.insert_rows(2) for i in range(1,ws.max_column): ws.cell(row=2, column=i).value=ws.cell(row=3, column=i).value wb.save("testFiles/basicTest_2....
################################################################################ """ DJ JOE Website Playlist File Generator -------------------------------------- (c) 2021 - Stanley Solutions - Joe Stanley This application serves an interface to allow the recording of Apple Music or Spotify playlists. """ ###########...
import torch import torch.nn as nn import torch.nn.functional as F from hivemind.server.layers.custom_experts import register_expert_class sample_input = lambda batch_size, hidden_dim: torch.empty((batch_size, hidden_dim)) @register_expert_class('perceptron', sample_input) class MultilayerPerceptron(nn.Module): ...
import logging import os import signal import sys import time from configparser import ConfigParser import dns.resolver import requests SITES_CONFIG = 'config/sites.cfg' URI_UPDATE = 'http://www.ovh.com/nic/update?system=dyndns&hostname=%(hostname)s&myip=%(ip)s' URI_GET_IP = 'https://ifconfig.me/ip' DNS_RESOLVERS = [...
import AppKit from PyObjCTools.TestSupport import TestCase, min_sdk_level import objc class TestNSDatePickerHelper(AppKit.NSObject): def datePickerCell_validateProposedDateValue_timeInterval_(self, v1, v2, v3): pass class TestNSDatePickerCell(TestCase): def testConstants(self): self.assertEq...
# Generated by Django 2.2.4 on 2019-08-11 14:41 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('alarms_project', '0001_initial'), ] operations = [ migrations.AlterField( model_name='alarm', ...
""" config.py defines default archive appliance server properties """ hostname = "pscaa02" data_port = 17668 mgmt_port = 17665
#!/usr/bin/env python # -*- coding: utf-8 -*- class Queue(object): def __init__(self): self.items = [] def get_size(self): return len(self.items) def is_empty(self): return self.items == [] def enqueue(self, item): self.items.insert(0, item) def dequeue(self): ...
from Functions.Controls.Keyboard.keyboard_pressed import * from Objects.Entity.Character.Character import * from Class.Entity.Character.Character import Character from intValues import * from Functions.NFC.getUID import * if raspberry: from Functions.Server.client import * def switch_heroes(): if rasp...
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> EXTENSIONS = ['ggrc_risk_assessments'] RISK_ASSESSMENT_URL = os.environ.get('GGRC_RISK_ASSESSMENT_URL', 'http://localhost:8080')
#!/usr/bin/python # -*- coding: utf-8 -*- """ [path] cd /Users/brunoflaven/Documents/01_work/blog_articles/stop_starting_start_stopping/pandas_learning_basics/ [file] python pandas_learning_basics_2.py # source - all to know to load pandas_dataframe_importing_csv Pandas https://chrisalbon.com/code/python/data_wra...
import pandas as pd import os #|Load data from single or multiple CSV files into internal DataFrame within "data" object def from_csv(file_path, mode, file_search, index, sep): if mode == 'single': data_name = file_path[file_path.rfind('/')+1:-4] print '-- Loading %s.csv --' % data_name df...
"""Head modules """ import numpy as np from bpnet.utils import dict_prefix_key from bpnet.metrics import ClassificationMetrics, RegressionMetrics import keras.backend as K import tensorflow as tf import keras.layers as kl import gin import os import abc from bpnet.losses import ignoreNaNloss class BaseHead: # lo...
import logging # WARNING = 30 logging.getLogger("matplotlib").setLevel(logging.WARNING) logging.getLogger("paramiko.transport").setLevel(logging.WARNING) # INFO = 20 logging.getLogger("botocore").setLevel(logging.INFO) logging.getLogger("smart_open").setLevel(logging.INFO) logging.getLogger("urllib3").setLevel(loggin...
from . import TransformFunction, string_to_tfarg_function, mime_type_based_transform import htmlmth.mods.javascript remove_comments = TransformFunction("", "remove JavaScript comments", mime_type_based_transform({ ...
import os import sys import pandas import numpy import argparse import glob import re from collections import OrderedDict from sklearn.preprocessing import StandardScaler config_dict={ 'xvector':9, 'pvector':32, 'OneHotvector' :2 } speakers_dict={ 'ffr0001_mmebovary':(1,1), ...
class Solution: """ @param time: @return: return a string represents time """ def nextTime(self, time): timeSplit = time.split(":") if len(time) != 5 or len(timeSplit) != 2: return "-1" minute = int(timeSplit[0]) second = int(timeSplit[1]) if min...
#!/usr/bin/python3 # Copyright (c) 2018-2021 Dell Inc. or its subsidiaries. # # 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 requ...
import pytest from numpy.testing import assert_almost_equal import astropy.units as u from sunpy.instr import fermi from sunpy.time import parse_time @pytest.mark.remote_data def test_download_weekly_pointing_file(): # set a test date date = parse_time('2011-10-01') afile = fermi.download_weekly_pointin...
#!/usr/bin/env python # coding: utf-8 # In[ ]: import time import serial from cached_property import cached_property class MHS2300: def __init__(self, port_name="COM3"): self.port = serial.Serial(port_name, 57600, timeout=0.1) #Always turns on both channels self.port.write(':01,w611,0...
from dataclasses import dataclass from transformers import PretrainedConfig, PreTrainedTokenizer, PreTrainedModel from ..transformersx_base import log, join_path from .models import task_model from .model_config import TaskModelConfig @dataclass class TaskModel: config: PretrainedConfig tokenizer: PreTrained...
#!/usr/bin/env python3 import json import requests s = requests.Session() class NanagogoError(Exception): def __init__(self, status_code, http_status_code, error_message): self.status_code = status_code self.http_status_code = http_status_code self.error_message = error_message class...
import time import board import busio import digitalio import sys from adafruit_mcp230xx.mcp23017 import MCP23017 i2c = busio.I2C(board.SCL, board.SDA) mcp = MCP23017(i2c) # , address=0x20) # MCP23017 alarm1 = mcp.get_pin(0) alarm2 = mcp.get_pin(1) alarm3 = mcp.get_pin(2) alarm1.switch_to_output(value=False) al...
from aiida.orm import Dict, load_node from aiida.engine import submit from aiida import load_profile # import the FleurinpgenCalculation # load ingpen Code # create a StuctureData structures = [Fe_structrure, Ni_structrure, Co_structrure] # create a parameters Dict # options # assemble inputs in a single dic...
from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.test import TestCase import fiber.templatetags.fiber_tags from fiber.models import ContentItem, Page from ...test_util import RenderMixin class TestShowContent(RenderMixin, TestCase): def setUp(self): se...
import numpy as np from skimage import data import napari with napari.gui_qt(): blobs = data.binary_blobs( length=100, blob_size_fraction=0.05, n_dim=3, volume_fraction=0.03 ).astype(float) viewer = napari.view_image(blobs.astype(float), ndisplay=3) n = 50 shape = [[[n, 40, 40], [n, 40, ...
from config import TOKEN, DBHost, DBName, DBUser, DBPassword class Config(object): """ Configuration base, for all environments """ DEBUG = False TESTING = False # We add a secret TOKEN, it is necessary for user authorization through LDAP to work SECRET_KEY = TOKEN CSRF_ENABLED = True...
from django.db import models # No related name is needed here, since symmetrical relations are not # explicitly reversible. class SelfRefer(models.Model): name = models.CharField(max_length=10) references = models.ManyToManyField('self') related = models.ManyToManyField('self') def __unicode__(self): ...
# Module data import requests from bs4 import BeautifulSoup import pandas as pd from datetime import timedelta,date,datetime import matplotlib.pyplot as plt import seaborn as sns import os def wrangle(wd, cache): print("Wrangling data ...") print(str.format('wd={}',wd)) data_path = wd + '/data/data.csv' ...
import torch import numpy as np import matplotlib.pyplot as plt def generate_sample_data(cfg, toTensor, device): np.random.seed(cfg['RANDOM_SEED']) Z = np.random.normal(0, 1, [cfg['NUM_FACTORS'],cfg['NUM_SAMPLES']]) # ~ N(0,1) L = np.random.rand(cfg['NUM_FEATURES'], cfg['NUM_FACTORS']) S = np.abs(np.d...
# -*- coding: utf-8 -*- """Tests all methods on Client""" # Import standard library import glob # Import modules import pytest # Import from package import linksight as ls def test_dataset_match(mock_api, client, match_response): """Test if Dataset.match() returns the expected value and type""" file = glo...
from inspect import getsource import heapq import matplotlib.pyplot as plt import networkx as nx from matplotlib import lines import ipywidgets as widgets from search import GraphProblem, romania_map from notebook import final_path_colors def show_tree(graph_data, node_colors = None): G = nx.Graph(graph_data['g...
import os import click from biom import load_table from deicode.rpca import rpca from deicode._rpca_defaults import (DEFAULT_RANK, DEFAULT_MSC, DEFAULT_MFC, DEFAULT_ITERATIONS, DESC_RANK, DESC_MSC, DESC_MFC, DESC_ITERATIONS) @click.command() @cli...
import query import repo from lazy_record.errors import * from inflector import Inflector, English inflector = Inflector(English) models = {} associations = {} foreign_keys = {} scopes = {} def model_from_name(parent_name): return models[inflector.classify(parent_name)] def _verify_type_match(record, associatio...
class MissingVariableError(Exception): def __init__(self, name): self.name = name self.message = f'The required variable "{self.name}" is missing' super().__init__(self.message) class ReservedVariableError(Exception): def __init__(self, name): self.name = name self.mess...
#!/usr/bin/env python """ Test support for 'with' statements """ # Copyright (C) 2009 Barry Pederson <bp@barryp.org> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2....
# coding=utf-8 from wirecamel import CONF_DIR import re import subprocess import yaml XTERM_TITLE = 'Hostapd console' # Load hostapd configuration def load_config(): hostapd_options = {} with open(CONF_DIR, 'r') as hap_file: for line in hap_file.readlines(): elements = re.findall(r'(.*)=...
#!/usr/bin/python3 # taken from https://github.com/AcutronicRobotics/mara_examples import rclpy from multiprocessing import Process from rclpy.node import Node from rclpy.qos import qos_profile_sensor_data from hrim_actuator_rotaryservo_msgs.msg import GoalRotaryServo from hrim_actuator_gripper_srvs.srv import Contro...
#!/usr/bin/env python3 """ Unit Tests for DynamicArray TODO - Add doctests to source """ import pytest from DynamicArray import DynamicArray class TestDynamicArray(): @classmethod def setup_class(cls): cls.dynamicArray = DynamicArray() @classmethod def teardown_class(cls): if cls...
from tests.system.action.base import BaseActionTestCase class MotionStatuteParagraphSortActionTest(BaseActionTestCase): def test_sort_correct_1(self) -> None: self.create_model("meeting/222", {"name": "name_SNLGsvIV"}) self.create_model( "motion_statute_paragraph/31", {"meeting_id": 22...
from .testing_deployment import RobotpkgTests from .dockerfile import RobotpkgGenerateDockerFile from .src_introspection import RobotpkgSrcIntrospection,RobotpkgPackage from .utils import execute,execute_call,init_environment_variables from .handling_imgs import HandlingImgs from .package_release_candidate import Robot...
""" Classification-based gym environment It is based on https://github.com/deepmind/neural_testbed/blob/master/neural_testbed/generative/classification_envlikelihood.py """ import jax.numpy as jnp import chex from jax import jit import haiku as hk from gym import Env, spaces from typing import Callable, Any from...
# -------------- import pandas as pd from sklearn.model_selection import train_test_split #path - Path of file df=pd.read_csv(path) # Code starts here X=df.drop(['customerID','Churn'],1) y=df['Churn'].copy() X_train,X_test,y_train,y_test=train_test_split(X,y,test_size = 0.3,random_state = 0) # -------------- impor...
import os import sys class Display(object): def __init__(self): pass @staticmethod def header(): sys.stdout.write("╔═════════════╦═══════════════════════╗".center(os.get_terminal_size().columns)) sys.stdout.write("║ ║ Server Provisioning ║".center(os.get_terminal_size().columns)) s...
import sys import os sys.path.append(os.getcwd() + '/src') import unittest import utils class TestUtils(unittest.TestCase): def test_createTabulaRecta(self): tabulaRecta = utils.createTabulaRecta() table = '' for l in tabulaRecta: table += ' '.join(l) + "\n" print table...
import sys import numpy as np import torch from tqdm import tqdm from codes.analysers.graphmask.graphmask_probe import GraphMaskProbe from codes.analysers.information_bottleneck.information_bottleneck_probe import InformationBottleneckProbe from codes.utils.moving_average import MovingAverage from codes.utils.torch_u...
import os import typing from json import decoder, encoder from Mod_NeonOcean_S4_Order import Mod from Mod_NeonOcean_S4_Order.Tools import Package def BuildPackageChanges () -> bool: if not Package.CanBuildPackage(): return False for package in Mod.GetCurrentMod().Packages: # type: Mod.Package baseFileExists =...
from __future__ import annotations import ast import logging import os import requests from pydantic import ValidationError from sutta_publisher.shared.value_objects.edition_config import EditionConfig, EditionMappingList, EditionsConfigs API_URL = os.getenv("API_URL", "") API_ENDPOINTS = ast.literal_eval(os.getenv...
from django.conf.urls import patterns, include, url urlpatterns = patterns('', url( r'^facturacion/factura/print/(?P<idFactura>[0-9]+)', 'facturacion.views.printFactura', name="printFactura"), )
import pytest import payload as pl from .fixtures import Fixtures @pytest.fixture() def billing_schedule(processing_account, customer_account): billing_schedule = pl.BillingSchedule.create( start_date="2019-01-01", end_date="2019-12-31", recurring_frequency="monthly", type="subsc...
from thebutton.genericstep import GenericStep from datetime import datetime as dt step_factories = {} def step_factory(name): def step_factory_impl(fn): step_factories[name.lower()] = fn return fn return step_factory_impl @step_factory("wait") def wait(time): yield GenericStep(time=tim...
from pytorch_lightning import LightningDataModule from torch.utils.data import DataLoader, random_split from torchvision.datasets import STL10 from unsupervised_pretraining.data.stl10albumentations import STL10Albumentations import albumentations as A class STL10DataModule(LightningDataModule): def __init__(self...
import logging import logging.handlers import sys from datetime import datetime from essentials.folders import ensure_folder logger = None def get_app_logger(): global logger if logger is not None: return logger logger = logging.getLogger("app") logger.setLevel(logging.INFO) max_byte...
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ts=2 sw=2 et ai ############################################################################### # Copyright (c) 2012,2013 Andreas Vogel andreas@wellenvogel.net # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and a...
import logging from abc import abstractmethod, ABCMeta from typing import Dict, Optional, Union from twisted.internet.defer import Deferred, fail, succeed, inlineCallbacks from twisted.python import failure from twisted.python.failure import Failure from vortex.DeferUtil import vortexLogFailure from vortex.Payload im...
from ..base import GnuRecipe class LibXcbRecipe(GnuRecipe): def __init__(self, *args, **kwargs): super(LibXcbRecipe, self).__init__(*args, **kwargs) self.sha256 = '4adfb1b7c67e99bc9c2ccb110b2f1756' \ '86576d2f792c8a71b9c8b19014057b5b' self.name = 'libxcb' sel...
import sys, numpy as np from igakit.nurbs import NURBS N = 10 p = 2 if len(sys.argv) >= 2: N = int(sys.argv[1]) if len(sys.argv) >= 3: p = int(sys.argv[2]) U = [0,0, 1,1] V = [0,0,0, 1,1,1] C = np.zeros((2,3,4)) val = np.sqrt(2)*0.5 C[0,0,:] = [ 0,-100, 0,1] C[1,0,:] = [100,-100, 0,1] C[0,1,:] = [ 0,-...
import sys def init(): search_str = "sgtring" # "EIN MUSTER P WIRD IN EINEM GEGEBENEN TEXT GESUCHT" pattern = "gstring" # "KEIN" print(f""" +------------------------------- | String Matcher | +------------------------------- Search text: {search_str} Pattern: {pattern} """) # Naive...
import pymysql def selectUnFinishCompany(): conn = pymysql.connect(host='localhost', user='root', passwd='123', db='tianyan', port=3306, charset='utf8') cur = conn.cursor() # 获取一个游标 sql = "select * from zb_tbcompanyinfo" try: cur.execute(sql) results = cur.fetchall() ...
class MountainRoad: def findDistance(self, start, finish): return 2**.5 * (max(finish) - min(start))
# from tellers import Tellers from modules.schedules import * from modules.timetable import * # tellers = Tellers() #seances = Seances() # seances = Seances()
from attrdict import AttrDict from ..vocab import NULL class SlotBase(AttrDict): REQUIRED_ARGS = [('name', str), ('is_null', bool), ('is_nullable', bool)] def __init__(self, **kwargs): for ra in SlotBase.REQUIRED_ARGS: key = ra[0] value = kwargs[key] super(SlotBase, ...
#!/usr/bin/python import sys import pandas as pd from string import Template def get_duplicated_rows(data_frame): duplicated_element = data_frame.duplicated() return data_frame[duplicated_element] def get_duplicated_row_numbers(duplicate_row_df): return len(duplicate_row_df.index) if len(sys.argv) !=...
import os from collections import namedtuple import sublime from sublime_plugin import WindowCommand, TextCommand, EventListener from ...common import util from .navigate import GsNavigate from ...common.theme_generator import XMLThemeGenerator, JSONThemeGenerator from ..git_command import GitCommand from ..constants...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in co...
def parse_transaction_as_dict(transaction): transaction_dict = {} return transaction
from structure.constants import LAMBDA import sys from typing import List def variable_and_alpha_review(variable_list : List, alpha_list : List, transitions_list : List, initial_variable : str): ''' verify if there is a problem with the variables or in the alpha for chosen language ''' try:...
with open('python\\2020\day5\data.txt') as f: lines = f.readlines() def getRowAndColumn(line): row = 0 column = 0 #follow directions to split first = 0 last = 127 for i in range(6): difference = last-first half = difference//2 + 1 if line[i] == 'B': firs...
# -*- coding: utf-8 -*- """ | '_ \ / _` |_____ / __/ _ \| '_ ` _ \| '_ \ / _` | '__/ _ \ | |_) | (_| |_____| (_| (_) | | | | | | |_) | (_| | | | __/ | .__/ \__, | \___\___/|_| |_| |_| .__/ \__,_|_| \___| |_| |___/ |_| This is used to compare two databases. Takes two connection string...
from __future__ import ( absolute_import, print_function, unicode_literals ) import sys def print_stderr(message): """ Simply print str message to stderr """ print(message, file=sys.stderr) def force_exit(message): """ Exit the program due to some error. Print out message to stde...
from proxybroker.api import Broker import requests import asyncio import logging import multiprocessing from queue import Empty from datetime import datetime logging.basicConfig(level=logging.INFO) class ListMaker: def __init__( self, limit=40, max_resp_time=1.0, countries=None, max_list_length=1000,...
import os import sys import re import numpy as np import math from itertools import repeat from indexparser import parse_index, rev_parse_index from parse49 import parse_49 from genfchk import quicksave VERSION = 'v4.1' # Internal version numbering VERSIONTEXT = ''' Original version honorably delivered by Acid&Fran...
from .base import loader
from net_conf import * RULES_DECODER_STATE_SIZE = RULES_QUERY_ENCODER_STATE_SIZE * 2 WORDS_DECODER_STATE_SIZE = RULES_ENCODER_STATE_SIZE * 2 DJANGO_DATA_SET_TYPE = 'DJANGO' HS_DATA_SET_TYPE = 'HS' DATA_SET_TYPE = DJANGO_DATA_SET_TYPE DATA_SET_BASE_DIR = '../django_data_set/data/' DATA_SET_NAME = 'django_data_set_v2...
# -*- coding: utf-8 -*- # 版权所有 2019 深圳米筐科技有限公司(下称“米筐科技”) # # 除非遵守当前许可,否则不得使用本软件。 # # * 非商业用途(非商业用途指个人出于非商业目的使用本软件,或者高校、研究所等非营利机构出于教育、科研等目的使用本软件): # 遵守 Apache License 2.0(下称“Apache 2.0 许可”), # 您可以在以下位置获得 Apache 2.0 许可的副本:http://www.apache.org/licenses/LICENSE-2.0。 # 除非法律有要求或以书面形式达成协议,否则本软件分发时...
from rest_framework import status from rest_framework import viewsets, parsers from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.response import Response from .models import Billing from .models import DropBox from .serial...
# -*- coding: utf-8 -*- import json from typing import Dict from .block_hash import BlockHash from .consensus_info import ConsensusInfo from ..utils.encoding import encode_b58 class BlockchainStatus: def __init__(self, status): self._status = status self._bbh = BlockHash(self._status.best_block_...
from django.contrib import admin from .models import Profile,Post,Health,Business,Police,Neighbourhood # Register your models here. admin.site.register(Profile) admin.site.register(Post) admin.site.register(Business) admin.site.register(Health) admin.site.register(Police) admin.site.register(Neighbourhood)
from SinGAN_models import * from options import * from utility_functions import * import torch.nn.functional as F import torch import os import imageio import argparse from typing import Union, Tuple from matplotlib.pyplot import cm from math import log import matplotlib.pyplot as plt from skimage.transform.pyramids im...
# coding=utf-8 from time import sleep from gpio_wrapper import gpio_commands from utils import DbSession import pickledb import settings class DeviceWrongAction(Exception): pass class Device: ACTION_SWITCH = 1 ACTION_PULSE = 2 def __init__(self, name, pin, action, reset_state=True): s...
from bot import dp from filters import IsOwner from functions import admin_menu @dp.message_handler(IsOwner(), commands="admin") async def admin(message): await admin_menu(message)
# Copyright 2015 Intel Corporation. # 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 requir...
from cyberbrain import Binding, Symbol def test_hello(tracer, check_golden_file): tracer.start() x = "hello world" # LOAD_CONST, STORE_FAST y = x # LOAD_FAST, STORE_FAST x, y = y, x # ROT_TWO, STORE_FAST tracer.stop()
__author__ = 'Robert Meyer' import multiprocessing as mp import numpy as np import os # For path names working under Windows and Linux from pypet import Environment, cartesian_product def multiply(traj, result_list): """Example of a sophisticated simulation that involves multiplying two values. This time w...
"""Functions for dealing with SOAP in oseoserver.""" from __future__ import absolute_import from lxml import etree from .constants import NAMESPACES from .errors import InvalidSoapVersionError from .auth import usernametoken def get_soap_version(request_element): """Return a request"s SOAP version Support...
import numpy as np import pandas as pd import random import sys import warnings from sklearn.model_selection import train_test_split from collections import Counter from matplotlib import style import matplotlib.pyplot as plt class k_nearest_neighbors(): def __init__(self): #print("init") self....
import json from chatapp import path_util def load_config(): with open(path_util.get_file_path('server', 'server_config.json'), 'r') as server_config_json: server_config = json.load(server_config_json) return server_config
"""A functions module, includes all the standard functions. Combinatorial - factorial, fibonacci, harmonic, bernoulli... Elementary - hyperbolic, trigonometric, exponential, floor and ceiling, sqrt... Special - gamma, zeta,spherical harmonics... """ from sympy.core.basic import Basic import combinatorial import eleme...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- from deprecation import deprecated as Deprecated @Deprecated(deprecated_in="0.0.3", details="Interactive mode is to be removed in 0.0.4", removed_in="0.0.4") def getNum(prompt, valType): """ Function to obtain valid inputs from keyboard :param prompt: Text ...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import copy import io import logging import numpy as np from typing import List import onnx import torch from caffe2.python.onnx.backend import Caffe2Backend from torch.onnx import OperatorExportTypes from .shared import ( ScopedWS, constr...
""" Woopra template tags and filters. """ from __future__ import absolute_import import json import re from django.conf import settings from django.template import Library, Node, TemplateSyntaxError from analytical.utils import ( disable_html, get_identity, get_required_setting, get_user_from_contex...
import aiohttp_jinja2 from aiohttp.web import Request from roll_witch.rolling import command @aiohttp_jinja2.template("roller.jinja2") async def roll(request: Request): data = await request.post() try: bot_operation = command.get_command( message_content=data["roll_operation"] ) ...
#!/usr/bin/python3 #Importing all needed libraries / modules import os import sys import time from time import sleep, strftime import cv2 import mysql.connector #Class for database connection and manipulation class DB_Connection: def __init__(self): try: self.db = mysql.connector.connect( ...