text
stringlengths
3.07k
12.6k
#!/usr/bin/env python # coding: utf-8 import pickle import pandas as pd import numpy import numpy as np from ast import literal_eval from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer from sklearn.metrics.pairwise import linear_kernel, cosine_similarity from nltk.stem.snowball import Snowball...
# Copyright 2021 The TensorFlow Authors. 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 applica...
import torch from eqv_transformer.classfier import Classifier from eqv_transformer.eqv_attention import EquivariantTransformer from lie_conv.lieGroups import SE3, SE2, SO3, T, Trivial # from lie_conv.datasets import SE3aug from forge import flags flags.DEFINE_boolean( "data_augmentation", False, "Apply...
#!/usr/bin/env python3 # coding:utf-8 # Copyright (c) Tsinghua university conversational AI group (THU-coai). # This source code is licensed under the MIT license. """Script for the Evaluation of Chinese Human-Computer Dialogue Technology (SMP2019-ECDT) Task2. This script evaluates the perplexity of the submitted mode...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
from PyQt5.QtCore import pyqtSignal from easydict import EasyDict as edict from pymodaq.daq_utils.daq_utils import ThreadCommand, getLineInfo, DataFromPlugins from pymodaq.daq_viewer.utility_classes import DAQ_Viewer_base from collections import OrderedDict import numpy as np from enum import IntEnum from pymodaq.daq_v...
""" A pattern to create a booking cluster description The properties in this group are mostly from {region} region. The properties are usually booked during {breakpoint} breakpoints by {adults} with {children} and {babies}. These are {avg_spend_per_head} {detached} properties in the {complex} close to {close_to}. The ...
import json from pathlib import Path import datajoint as dj import numpy as np import sortingview as sv import spikeinterface as si from .spikesorting_recording import SpikeSortingRecording from .spikesorting_curation import Curation schema = dj.schema('spikesorting_sortingview') @schema class SortingviewWorkspaceS...
import matplotlib matplotlib.use('Agg') import numpy as np import scipy.stats import matplotlib.pylab as plt import os import sys from .context import vfe from .context import config import pdb np.random.seed(42) # We first define several utility functions def kink_true(x): fx = np.zeros(x.shape) for t in ran...
#!/usr/bin/env python # # Copyright (c) 2015 10X Genomics, Inc. All rights reserved. # from collections import defaultdict import itertools import json import martian import os import sys import tenkit.log_subprocess as tk_subproc import tenkit.safe_json as tk_safe_json import cellranger.chemistry as cr_chem import cel...
""" .. Copyright (c) 2014- <NAME> license http://opensource.org/licenses/MIT Data - preprocessing functions (:mod:`pynance.data.prep`) ========================================================= .. currentmodule:: pynance.data.prep """ import numpy as np import pandas as pd def center(dataset, out=None): """ ...
import numpy as np import sys, os import pprint import time from math import * pp = pprint.PrettyPrinter(indent=2) parentPath = os.path.abspath("../GRASP") if parentPath not in sys.path: sys.path.insert(0, parentPath) from Common.NurseSchedulingProblem import * from Greedy import isFeasible printlog = False ""...
from dagster import check from dagster.config.config_type import ConfigType, ConfigTypeKind from dagster.core.decorator_utils import ( split_function_parameters, validate_decorated_fn_positionals, ) from dagster.core.errors import DagsterInvalidDefinitionError from dagster.utils import ensure_single_item clas...
import mxnet as mx import numpy as np from operator_py.nms import py_nms_wrapper def multiclass_nms(nms, cls_score, bbox_xyxy, min_det_score, max_det_per_image): # remove background cls_score = cls_score[:, 1:] # TODO: the output shape of class_agnostic box is [n, 4], while class_aware box is [n, 4 * (1 +...
from phys2bids import io import math import pytest from pytest import raises @pytest.fixture(scope='function') def loaded_acq_file(samefreq_short_txt_file): chtrig = 2 header_acq, channels_acq = io.read_header_and_channels(samefreq_short_txt_file) # just a few quick checks to make sure the data loaded ...
from django.http import HttpResponse, HttpResponseRedirect from django.views.generic.base import TemplateView, View from django.views.generic.edit import DeleteView, UpdateView from django.views.decorators.clickjacking import xframe_options_sameorigin from sondao.logic.Person import Person as LPerson, Testator from son...
# 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 # distributed under t...
#!/usr/bin/env python # Copyright (2012) Singapore-MIT Alliance for Research and Technology import math def is_close(x1, x2): return abs(x1 - x2) < 0.001 class Point: def __init__(self, x, y, z=0.0): self.x = x self.y = y self.z = z def __repr__(self): return "point(%f, ...
"""Base Class for tabular models.""" import logging import pickle from sdv.metadata import Table LOGGER = logging.getLogger(__name__) class NonParametricError(Exception): """Exception to indicate that a model is not parametric.""" class BaseTabularModel(): """Base class for all the tabular models. T...
from random import choice from django.contrib.auth.hashers import make_password from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, Group, PermissionsMixin, ) from django.db import models from openslides.utils.search import user_name_helper from ..core.config import config fro...
# Copyright 2017 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 wri...
"""Stream new Reddit posts and notify for matching posts.""" import datetime import os import sys import time import apprise import praw import prawcore import yaml CONFIG_PATH = os.getenv("RPN_CONFIG", "config.yaml") LOGGING = os.getenv("RPN_LOGGING", "FALSE") YAML_KEY_APPRISE = "apprise" YAML_KEY_REDDIT = "reddit"...
import numpy as np EPSILON = 1e-10 def _error(actual: np.ndarray, predicted: np.ndarray): """ Simple error """ return actual - predicted def _percentage_error(actual: np.ndarray, predicted: np.ndarray): """ Percentage error Note: result is NOT multiplied by 100 """ return _error(actual...
'''Module implementing the nonlinear full approximation storage (FAS) extension of the multilevel constraint decomposition (MCD) method for the shallow ice approximation (SIA) obstacle problem.''' # TODO: # * convergence and performance studies # * implement random-bed case (for performance only) # * implement m...
''' Main Training Script Currently contains all the training components, as well as ancillary calls to responsible ai, registration, and data loading. ''' import argparse import importlib import json from json.decoder import JSONDecodeError import mlflow import pandas as pd from utils import * from modeling.OEA_mode...
import pytest from CommonServerPython import * from ProofpointThreatResponse import create_incident_field_context, get_emails_context, pass_sources_list_filter, \ pass_abuse_disposition_filter, filter_incidents, prepare_ingest_alert_request_body MOCK_INCIDENT = { "id": 1, "type": "Malware", "summary": ...
# This work is based on original code developed and copyrighted by TNO 2020. # Subsequent contributions are licensed to you by the developers of such code and are # made available to the Project under one or several contributor license agreements. # # This work is licensed to you under the Apache License, Version 2...
"""This module create an client/server interface over an unix socket.""" import os import socket import select import pickle import collections import superdatabase3000.packet as pckt DEFAULT_SOCK_FILENAME = "/tmp/superdatabase3000.sock" BUF_SIZE = 0x1000 # TODO: tweak me def _send_to(sock, msg): """ Sen...
import abc import math import numbers import random import numpy as np class AllowMoveStrategy(abc.ABC): def start_new_component(self, initial_labels, attr, objective_func, comp_idx): """ This method should be called whenever a new connected component is clustered. Parameters ...
#SPDX-License-Identifier: MIT """ Augur library commands for controlling the backend components """ from copy import deepcopy import os, time, atexit, subprocess, click, atexit, logging, sys import psutil import signal import multiprocessing as mp import gunicorn.app.base from gunicorn.arbiter import Arbiter from aug...
import torch from torch.utils.data import Dataset, DataLoader from .util import load_file import os.path as osp import numpy as np import nltk import h5py class VidQADataset(Dataset): """load the dataset in dataloader""" def __init__(self, video_feature_path, video_feature_cache, sample_list_path, vocab, use_...
# Imports from matplotlib import pyplot as plt import seaborn as sns from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import cross_val_score from sklearn.model_selection import cross_val_predict from sklearn.model_selection import KFold from sklearn.model_selection import StratifiedKFold...
import scipy.signal import scipy.fftpack as fftpack import numpy as np import pywt import cv2 from . import array_operation as arr def sin(f,fs,time,theta=0): x = np.linspace(0, 2*np.pi*f*time, int(fs*time)) return np.sin(x+theta) def downsample(signal,fs1=0,fs2=0,alpha=0,mod = 'just_down'): if alpha == 0...
#!/usr/bin/env python2 import urllib2, json, os, sys HEADER = ''' Redirect = { image: function(board, filename) { switch (board) { ''' POST = ''' } }, post: function(board, postID) { switch (board) { ''' TO = ''' } }, to: function(data) { var board, threadID, url; ...
import requests import json import gzip import pandas as pd from urllib.error import HTTPError from datetime import date, timedelta import s3fs def fetch_tmdb_movie_ids(TMDB_IDS_FILE_PATH): """ This function downloads the zipped json file from TMDB with the most recent movie IDs in it. Then it unzippes th...
from django.core.exceptions import ValidationError from django.core.exceptions import MultipleObjectsReturned from django.conf import settings from dojo.decorators import dojo_async_task from dojo.celery import app from dojo.endpoint.utils import endpoint_get_or_create from dojo.utils import max_safe from dojo.models i...
import numpy as np from functools import lru_cache from tqdm import tqdm from const import STATE as S, ACTION as A, REWARD as R, FIGSIZE from first import first_state, zero_q, random, zero_action from show import show_q, show_s import tr_model as m I = S.index ALPHA = 0.01 GAMMA = 0.3 EPSILON = 0.5 NITER = 100 * 1000 ...
# https://stackoverflow.com/questions/7207309/how-to-run-functions-in-parallel from __future__ import print_function import os import time from multiprocessing import Process from typing import List, Tuple, Union from subprocess import Popen, PIPE, STDOUT import cv2 import numpy as np class Preprocess(object): ...
from marshmallow.fields import Field from marshmallow.schema import Schema, SchemaMeta, SchemaOpts import sqlalchemy as sa from sqlalchemy.ext.declarative import DeclarativeMeta from .convert import ModelConverter from .exceptions import IncorrectSchemaTypeError from .load_instance_mixin import LoadInstanceMixin # T...
# Copyright 2015, Aiven, https://aiven.io/ # # This file is under the Apache License, Version 2.0. # See the file `LICENSE` for details. from __future__ import print_function from aiven.client import envdefault, pretty import aiven.client.client import argparse import csv as csvlib import errno import json as jsonlib ...
from django.shortcuts import get_object_or_404, render_to_response from django.shortcuts import render from registration.models import * from events.models import EventNew from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.template import Context from djang...
''' Select a diverse subset of compounds from a library ''' # Import import sys, os, argparse import pandas as pd import numpy as np from concurrent import futures from rdkit import Chem, RDLogger, DataStructs from rdkit.Chem import PandasTools from rdkit.SimDivFilters import rdSimDivPickers def getMACCS_fps(mol): ...
""" Unittest of the process_components_cif_cli.py command line script method based on http://dustinrcollins.com/testing-python-command-line-apps adapted to use nose then converted to pytest """ import os import xml.etree.ElementTree as ET import pytest from pdbeccdutils.scripts.process_components_cif_cli import (PDBe...
# Copyright (C) 2020-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """MVTec shard descriptor.""" import os from glob import glob from pathlib import Path import numpy as np from imageio import imread from PIL import Image from openfl.interface.interactive_api.shard_descriptor import ShardDataset from ...
from .knn_classifier import KNNClassifier from .base_neighbors import BaseNeighbors, KNeighborsBuffer from river import base import itertools import typing import statistics import numpy as np from scipy.spatial import cKDTree from river.utils import dict2numpy from river import base from river.utils.skmultiflow_utils...
import itertools import logging import signal import numpy as np import torch from torch.nn.utils.rnn import pack_sequence, pack_padded_sequence default_sigint_handler = signal.getsignal(signal.SIGINT) def critical(f=None): if f is not None: it = iter(f) else: it = itertools.count() sign...
# -*- coding: utf-8 -*- import csv import datetime import os import sys import time def abort(msg): print('Error!: {0}'.format(msg)) exit(1) def list2file(filepath, ls): with open(filepath, encoding='utf8', mode='w') as f: f.writelines(['{:}\n'.format(line) for line in ls] ) def dtstr2dt(dtstr):...
import os import sys import copy from argparse import ArgumentParser root = os.path.dirname(os.path.abspath(__file__)) _embedded_func = { 'upper': lambda s: s.upper(), 'lower': lambda s: s.lower() } def get_blank(op, total_num): res = total_num - len(op) if res < 1: res = 1 return res...
# SPDX-License-Identifier: MIT import struct from ..utils import * from .asc import StandardASC from .asc.base import * class PMPMessage(Register64): TYPE = 56, 44 class PMP_Startup(PMPMessage): TYPE = 56, 44, Constant(0x00) class PMP_Configure(PMPMessage): TYPE = 56, 44, Constant(0x10) DVA = 47, 0...
# Copyright (c) 2020, 2021 <NAME> # 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, distrib...
import numpy as np import math def standard_propensity(rxn, CRS, concentrations): ''' Standard Propensity function calculates propensity as the concentrations of the reactants raised to their coefficients Arguements: - rxn: Reaction object - CRS: CRS object for system - concentrations: list of molec...
#! /bin/env python """ Examples -------- Create a grid that consists of 2x3 nodes using 'xy' and 'ij' indexing. **ij-indexing** Create a grid of length 2 in the i direction, and 3 in the j direction. >>> g = UniformRectilinear ((2,3), (1,2), (.5, 0), indexing='ij', units=('m', 'km')) >>> g.get_x() array([ 0., 2., ...
# -*- coding: utf-8 -*- {{{ # vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et: # Copyright (c) 2013, Battelle Memorial Institute # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistri...
# Originally from Phen-Cogs https://github.com/phenom4n4n/phen-cogs/blob/master/lock/converters.py from typing import Union import re import discord from unidecode import unidecode from rapidfuzz import process from discord.ext.commands.converter import RoleConverter, Converter from redbot.core import commands from re...
import fo import numpy as np from data import Data class LDPComp: def __init__(self, repeat=1): self.repeat = repeat self.real_dist = [] def calculate_true_dist(self, X, domain): results = np.zeros(domain, dtype=np.int) for i in range(len(X)): if len(X[i]) == 0: ...
import discord import os from discord.ext import commands import random import update_db from hopcroftkarp import HopcroftKarp description = '''CSES Kun a discord bot to practice cses problems''' bot = commands.Bot(command_prefix='?', description=description) update_db.main() @bot.event async def on_ready(): pri...
from sklearn.metrics import accuracy_score, precision_recall_fscore_support import random import logging import sys import argparse import sagemaker import os import torch import os, requests, json, boto3 from transformers import DistilBertTokenizer from transformers import DistilBertTokenizerFast from transformers imp...
import os from typing import Union from flask_login import UserMixin from azure.batch.models import CloudJob, CloudTask from .application import db class DbUser(db.Model, UserMixin): id = db.Column(db.String, primary_key=True) role = db.Column(db.String) def __init__(self, user_id: str): self....
import math import os.path import numpy as np # import h2_jj T0 = 273.0 atm2bar = 1.01325 # convert atm to bars GHz = 29.9792458 # convert cm^-1 to GHz tablename = 'orton_H2.tables' h2etc = {'eh2h2': 0, 'nh2h2': 1, 'eh2he': 2, 'nh2he': 3, 'eh2ch4': 4, 'nh2ch4': 5} h2type = {'e': 0, 'n': 1} Ttab = [] h2vab = [] ...
from abc import ABC, abstractmethod from enum import Enum, auto from resotolib.core.ca import TLSData from resotolib.graph import Graph from resotolib.core import resotocore from resotolib.core.actions import CoreActions from resotolib.args import ArgumentParser from resotolib.config import Config from resotolib.logger...
import os import json import demistomock as demisto from tempfile import mkdtemp from Anomali_ThreatStream_v2 import main, file_name_to_valid_string, get_file_reputation, Client import emoji import pytest def util_load_json(path): with open(path, mode='r', encoding='utf-8') as f: return json.loads(f.read(...
from environment import Environment import os import matplotlib.pyplot as plt import numpy as np import random import torch import torch.nn as nn import torch.optim as optim from torch.nn.utils import clip_grad_norm_ class ReplayBuffer: def __init__(self, column, max_size, batch_size): self.current_state ...
import argparse import os import pathlib import re import sys try: from PIL import Image except: raise Exception("Please install PIL e.g. 'sudo apt-get install python3-pil'") import struct import io import shutil SCRIPT_DIR = pathlib.Path(__file__).parent def create_color16(r, g, b): return (((r << (11 - ...
import json import logging import sys from datetime import datetime import boto3 from job_requester import JobRequester from job_requester import Message """ How tests are executed: - Put tickets on the request queue, in-progress pool and dead letter queue; create Message objects (request identifiers) that corresp...
import pandas as pd import numpy as np import ast import sys fdata_template = '../../data/fma_metadata/{}' modeldata_template = '../../in/metadata/{}' graphs_template = '../../out/graphs/{}' genres_fpath = fdata_template.format('genres.csv') tracks_fpath = fdata_template.format('tracks.csv') class DataSize: """...
import argparse import datetime import logging import os import re import json from dataactcore.config import CONFIG_BROKER from dataactcore.interfaces.db import GlobalDB from dataactcore.logging import configure_logging from dataactcore.models.domainModels import DUNS from dataactcore.utils.parentDuns import update_m...
import math import numpy as np import pandas as pd def roundup(x, n=10): """Round up x to multiple of n.""" return int(math.ceil(x / n)) * n def running_mean(x, N): """Calculate running/rolling mean or moving average. Thanks to https://stackoverflow.com/a/27681394/6528729 """ cumsum = np.cum...
"""jumpstart a tilemill project based on a dataset from a clld app.""" from __future__ import unicode_literals, division, absolute_import, print_function import sys import os from zipfile import ZipFile import json from base64 import b64encode from cgi import escape from six import text_type, PY3 from six.moves.urllib...
from elasticsearch import Elasticsearch import os import zipfile import shutil import urllib.request import logging import lzma import json import tarfile import hashlib logger = logging.getLogger(__name__) # index settings with analyzer to automatically remove stop words index_settings = { "settings": { ...
"""Decoding functions using multiple attentions for RNN decoders. See http://arxiv.org/abs/1606.07481 The attention mechanisms used in Neural Monkey are inherited from the ``BaseAttention`` class defined in this module. The attention function can be viewed as a soft lookup over an associative memory. The *query* vec...
from typing import Tuple import pytest from ground.hints import Scalar from hypothesis import given from hypothesis.errors import HypothesisWarning from hypothesis.strategies import DataObject from hypothesis_geometry.hints import Strategy from hypothesis_geometry.planar import multicontours from tests import strateg...
# The MIT License # Copyright (c) 2021- Nordic Institute for Interoperability Solutions (NIIS) # Copyright (c) 2017-2020 Estonian Information System Authority (RIA) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"...
#!/usr/bin/env python3 """ Minecraft mob spawner generator with setblock commands in vanilla minecraft E.g. usage: ./mob_grinder.py -x 82 -z 358 -y 60 -b minecraft:cobblestone Capture the output and paste it into the console """ import argparse import math def set_block(x, y, z, block_id): """ Set a block...
# ubirch key store # # @author <NAME> # # Copyright (c) 2018 ubirch GmbH. # # 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...
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt import keras from keras.datasets import cifar10, mnist from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Conv2D, MaxP...
from tensorflow.keras.layers import Add, BatchNormalization, Conv2D, Dense, Flatten, LeakyReLU, PReLU, Lambda from tensorflow.keras import models, layers from tensorflow.keras.models import Sequential from tensorflow.keras.applications.vgg19 import VGG19 from model.common import pixel_shuffle, normalize_01, normalize_m...
""" Capstone Team Project. Code to run on a LAPTOP (NOT the robot). This code contains the one and only MAIN function for running on the laptop. This code: 1. Displays and runs the Graphical User Interface (GUI), and 2. Talks to the robot (by sending MQTT messages) through the GUI, and 3. Listens for message...
import glob import os import pickle from collections import defaultdict import cv2 import numpy as np import tensorflow as tf from tf_bodypix.api import BodyPixModelPaths, download_model, load_model from tasks.base import BaseTask, ObjectInImage from tasks.utils.crop_window import * from tasks.utils.detect_face impor...
#!/usr/bin/python ''' (C) Copyright 2018 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 ...
import numpy as np import torch import torch.nn as nn import progressbar import time import copy def initialization(init_method, W, is_tensor=True): """ Initializes the provided tensor. Parameters: ----------- * init_method : str (default = 'glorot_uniform') Initialization method to use....
### Reverse Polish Calculator import math ### CLASSES ### class Stack(list): """ Object to realize & handle stack Access to stack only through its methods """ def __init__(self): """ Init stack as list """ super().__init__() self.clear_stack() def clear_stack(self): ...
import os import re import pylcs from tqdm import tqdm import itertools from multiprocessing import Pool from functools import partial import time def transcribe(sequence): return sequence.replace('T', 'U') def translate_rna(s): codon2aa = {"AAA":"K", "AAC":"N", "AAG":"K", "AAU":"N", "ACA":"T"...
import configparser import os import pytest from twtxt.config import Config from twtxt.models import Source @pytest.fixture(scope="session") def config_dir(tmpdir_factory): cfg = configparser.ConfigParser() cfg.add_section("twtxt") cfg.set("twtxt", "nick", "foo") cfg.set("twtxt", "twtfile", "~/foo....
import subprocess import os import sys import re from workflow import Workflow3 adb_path = os.getenv('adb_path') serial = os.getenv('serial') api = os.getenv('device_api') ip = os.getenv("ip") def wordMatch(arg, sentence): words = arg.lower().split(" ") sentenceComponents = sentence.lower().split(" ") f...
from email.message import EmailMessage from iqoptionapi.stable_api import IQ_Option from colorama import init, Fore, Back, Style from datetime import datetime from talib import * import sys import threading import os import numpy import json, requests import time import talib #from talib import MA_Type, EMA, BBANDS os...
import time from os import path from os.path import expanduser from fabric.api import env, put, run, sudo, task from fabric.context_managers import prefix from fabric.contrib.project import rsync_project from fabric.operations import local, run with open(expanduser('~') + '/ansible-playbooks/env/bvspca.py', 'r') as c...
# Copyright 2022 Canonical Ltd. # See LICENSE file for licensing details. # # Learn more about testing at: https://juju.is/docs/sdk/testing import unittest.mock as mock from pathlib import Path import pytest import yaml from ops.model import BlockedStatus, MaintenanceStatus, WaitingStatus from ops.testing import Harn...
""" Support for MQTT lights. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/light.mqtt/ """ import logging from functools import partial import homeassistant.components.mqtt as mqtt from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_...
# # Copyright (c) Contributors to the Open 3D Engine Project. # For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # # ''' Usage: Use EC2 role to upload all .zip and .MD5 files in %WORKSPACE% folder to bucket ly-packages-main...
import asyncio import collections import threading from http import HTTPStatus from typing import Any, Iterable, Deque from .types import ( Message, Scope, Environ, StartResponse, ASGIApp, ) __all__ = ("ASGIMiddleware",) class AsyncEvent: def __init__(self, loop: asyncio.AbstractEventLoop) -...
from unittest import TestCase from sys import version_info try: from functools import wraps except ImportError: from django.utils.functional import wraps # Python 2.3, 2.4 fallback. from django.http import HttpResponse, HttpRequest from django.utils.functional import allow_lazy, lazy, memoize from django.view...
#! /usr/bin/env python import math import sys import time import rospy import serial import tf from geometry_msgs.msg import Twist from nav_msgs.msg import Odometry from sensor_msgs.msg import Imu class BaseControl(object): def __init__(self): self.port = rospy.get_param("~port", "/dev/ttyUSB0") ...
from tradester.feeds.static import FuturesTS, SymbolsTS from multiprocessing import Manager, Process from numba import jit from copy import deepcopy from tqdm import tqdm import numpy as np class ClockManager(): """ ClockManager is a central 'clock' to control aspects of iterating through time. ... ...
''' SPDX-License-Identifier: Apache-2.0 Copyright 2017 Massachusetts Institute of Technology. ''' import datetime from cryptography import x509 from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.x509.oid import NameOID from keylime import con...
# Copyright (c) 2020 PaddlePaddle Authors. 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 appli...
import numpy as np def clean_instaces(image, min_area=20): """ Removes smal instances :param image: :return: """ ids, counts = np.unique(image, return_counts=True) removables = [ids for i, ids in enumerate(ids) if counts[i] < min_area] for r in range(0, len(removables)): image[...
"""Weather information for air and road temperature (by Trafikverket).""" from __future__ import annotations from dataclasses import dataclass from datetime import datetime from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, ) from ...
class BVH(object): def __init__(self): super(BVH, self).__init__() self.root = [] self.channel_values = [] self.channel_dict = {} self.position_values = [] self.position_dict = {} self.display_frame = 2000 def load_from_file(self, bvh_file_path): bvh_file = open(bvh_file_path, 'r') bvh_str = b...
from tkinter import Tk from tkinter.filedialog import * import matplotlib matplotlib.use("TkAgg") from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk from matplotlib.figure import Figure class Adjustable: #Makes one Label + Textbox Line def __init__(self, master, name, ini...
# Copyright (C) 2018-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import unittest from unittest.mock import MagicMock from xml.etree.ElementTree import Element, tostring import numpy as np from openvino.tools.mo.back.ie_ir_ver_2.emitter import soft_get, xml_shape, serialize_runtime_info from openvino...