text
stringlengths
3.07k
22.1k
import argparse import math import numpy as np import socket import importlib import os os.environ["CUDA_VISIBLE_DEVICES"] = "3" import sys import torch import torch.nn as nn from torch.autograd import Variable from torch.backends import cudnn from sklearn.neighbors import NearestNeighbors from sklearn.neighbors impor...
from __future__ import absolute_import import sympy from . import stepprinter from .stepprinter import replace_u_var from sympy.integrals.manualintegrate import ( _manualintegrate, integral_steps, evaluates, ConstantRule, ConstantTimesRule, PowerRule, AddRule, URule, PartsRule, CyclicPartsRule, TrigRule, E...
#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Create (if needed) and sync a nested checkout of Skia inside of Chrome. """ import optparse import os import re import shlex i...
from itertools import count import os import struct from .constants import ( KOD, ENC, NULL, RECORD_SEP, get_sentinel, PK_SENTINEL, BANK_DAT_FILE_NAME, BANK_TAD_FILE_NAME, STRU_DAT_FILE_NAME ) class CronosException(Exception): """General parsing errors.""" def vword(bytes_data, offs...
from __future__ import print_function import os import sys import logging import io import pytest import numpy as np try: from pathlib import Path except ImportError: try: from pathlib2 import Path # For Python2 except ImportError: raise ImportError("No pathlib or pathlib2 found") from dtai...
import cv2 import sys #import dlib from PyQt5 import QtCore from PyQt5 import QtWidgets from PyQt5 import QtGui from PyQt5.QtWidgets import * from picamera.array import PiRGBArray from picamera import PiCamera import numpy as np import tensorflow as tf import pygame from tflite_runtime.interpreter import ...
""" script for training the MSG-GAN on given dataset """ import argparse import numpy as np import torch as th from torch.backends import cudnn # define the device for the training script device = th.device("cuda" if th.cuda.is_available() else "cpu") # enable fast training cudnn.benchmark = True # set seed = 3 th...
import spacy class MissingParenthesis(Exception): """Raised when a sentence starts with parenthesis""" pass class MissingNoun(Exception): """Raised when a word refers to a non-existing noun""" pass class SentencesLoader: def __is_known_token(self, table, token): atributes = [ ...
import sys import time from collections import namedtuple import numpy as np import os # import pandas as pd # slow # from pandas import DataFrame import pyhooker import ctypes import re import datetime as dt import csv # # used for pyinstaller # import six # import packaging # import packaging.version # import packa...
from _context import kgmodels from kgmodels import util from util import d import torch from torch import nn import torch.nn.functional as F from torch.autograd import Variable import rdflib as rdf import pandas as pd import numpy as np import random, sys, tqdm from tqdm import trange import rgat from argparse i...
from railrl.envs.multitask.multitask_env import MultitaskToFlatEnv from railrl.envs.multitask.point2d import MultitaskPoint2DEnv from railrl.envs.mujoco.pusher2d import Pusher2DEnv from railrl.envs.wrappers import NormalizedBoxEnv from railrl.exploration_strategies.base import ( PolicyWrappedWithExplorationStrategy...
from . import sg_pt, Buffer, sg_cmds from .sense import Sense from .cmd import Command from .enum import DoPTResult, StatusCodes, PTResult, ErrorCategories, PTFlags from typing import Optional, Dict from weakref import WeakValueDictionary from functools import wraps class SCSIError(RuntimeError): def __init__(sel...
import threading import time import grovepi import pika import json from config import * from grove_rgb_lcd import * from plugwise.api import* # Used to build a connection to the broker with data from the configuration file credentials = pika.PlainCredentials(username, password) # Two exchanges are used for sensors a...
import numpy as np from scipy import fftpack # numbers of the form 2^n3^m5^r, even only and r<=1 fastFFT = np.array( [2, 4, 6, 8, 10, 12, 16, 20, 24, 32, 40, 48, 64, 80, 96, 128, 144, 160, 192, 256, 288, 320, 384, 432, 480, 512, 576, 640, 720, 768, 864, 960, 1024, 1152, 1280, 1440, 1536, 1728, 1920, 2048, 230...
__author__ = '<NAME>' import numpy as np import cv2 import math def estimate_camera(model3D, fidu_XY, pose_db_on=False): if pose_db_on: rmat, tvec = calib_camera(model3D, fidu_XY, pose_db_on=True) tvec = tvec.reshape(3,1) else: rmat, tvec = calib_camera(model3D, fidu_XY) RT = np.h...
#!/usr/bin/env python3 # # create_verilog_library.py # #---------------------------------------------------------------------------- # Given a destination directory holding individual verilog files of a number # of modules, create a single verilog library file named <alllibname> and place # it in the same directory. T...
""" DeeplabV2 """ from collections import OrderedDict from torch.nn import * import torch.nn.functional as F class DeeplabV2(Module): def __init__(self, num_classes=21, resnet_based_type=101): super(DeeplabV2, self).__init__() if resnet_based_type == 18: self.conv1 = _building_block_la...
import logging from misskey import Misskey, NoteVisibility import websockets import asyncio, aiohttp import json import datetime import sys import traceback import re import math import time import textwrap import requests try: import config_my as config except ImportError: import config from PIL import Image...
import streamlit as st import psycopg2 import inspect import sys import os import importlib import functions.fn_db as fn_db import functions.fn_plot as fn_plot import pandas as pd import numpy as np import webbrowser import markdown import base64 import matplotlib.pyplot as plt from matplotlib.font_manager import FontP...
from os import name import re from dash_html_components.Tr import Tr import numpy as np import pandas as pd from collections import defaultdict from urllib.request import urlopen import json from datetime import datetime import sys import os import statsmodels.api as sm from pathlib import Path from sklearn.linear_mod...
import numpy as np import copy import argparse import torch import pdb import sys import matplotlib.pyplot as plt import pygame from PIL import Image sys.path.insert(0, '..') # NOQA: E402 from featureExtractor.drone_feature_extractor import dist_2d, norm_2d from featureExtractor.drone_feature_extractor import get_rot...
import boto3 import re import json import botocore.exceptions as boto_exceptions import core def delete_non_default_policy_versions(policy_arn, iam_client=None, logger=None): if iam_client is None: iam_client = boto3.client('iam') if logger is None: logger = core.set_logger() logger.info("...
import pytest from excitertools import Iter, insert_separator, concat def test_basic(): it = Iter(range(5)) assert list(it) == [0, 1, 2, 3, 4] @pytest.mark.parametrize( "container,it,expected", [ (list, range(5), [0, 1, 2, 3, 4]), (set, range(5), {0, 1, 2, 3, 4}), (dict, zip...
import torch from torch.optim import Optimizer from enum import IntEnum from functools import reduce import numpy as np class OptimizerMethod(IntEnum): QP = 0 CAYLEY = 2 PG = 3 AM2 = 5 QP2 = 7 class ProjectedGradient(Optimizer): def __init__(self, params, lr=1.0, beta=0.5): ...
# condig: utf-8 __all__ = ['generate_result_csv'] import csv, re, json, shutil, os from os import path from datetime import datetime from collections import OrderedDict from logging import getLogger from html.parser import HTMLParser from urllib.parse import ( parse_qs, ) from time import sleep from httpclient i...
"""Utility functions.""" import datetime import io import os from typing import IO, Any, List, Optional, Union, cast from wrapt import ObjectProxy # type: ignore from .constants import EPOCH from .typing import PathLike, PathLikeOrFile __all__ = [ "ensure_open", "filestring", "isio", "xor", "co...
# Copyright 2019 PIQuIL - 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 agreed ...
from sanic import Sanic from sanic.log import logger from sanic.response import json as J from sanic.views import HTTPMethodView from sanic import __version__ as sanic_version from packaging import version import marshmallow as ma from webargs import fields, ValidationError from webargs_sanic.sanicparser import parse...
import numpy as np from scipy.stats import entropy from scipy.optimize import linear_sum_assignment from scipy.special import logsumexp, digamma, betaln, binom, gammaln def get_binom_coeff(AD, DP, max_val=700, is_log=True): """Get the binomial coefficients """ # Since binom can't give log value, the maxim...
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """A collection of statistical utility functions to be used by metrics.""" import bisect import math def Clamp(value, low=0.0, high=1.0): """Clamp a val...
# Copyright 2021 The Scenic Authors. # # 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 w...
"""Main module.""" import os import sys from collections import OrderedDict from itertools import chain from subprocess import Popen, PIPE import click import yaml from pip._internal.utils.misc import get_installed_distributions from importlib import import_module flatten = chain.from_iterable def _dict_represent...
from __future__ import print_function import re import os import sys import time import json import glob import Queue import pickle import anydbm import argparse import traceback import functools import threading # import subprocess import contextlib import collections from datetime import datetime from ceph_daemon i...
# coding: utf-8 # Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """Tests for /query api endpoint.""" # pylint: disable=too-many-arguments # pylint: disable=too-few-public-methods import itertools import re import sys from six import add_metaclass from s...
"""" # DeepCTR https://github.com/shenweichen/DeepCTR https://deepctr-doc.readthedocs.io/en/latest/Examples.html#classification-criteo DeepCTR is a **Easy-to-use**,**Modular** and **Extendible** package of deep-learning based CTR models along with lots of core components layers which can be used to easily build cust...
#!/usr/bin/env python import serial import struct # Opcodes for operating the controller OP_MOVE = 0x00 OP_WRITE = 0x01 OP_READ = 0x02 OP_STATUS = 0x03 OP_MOVES = 0x04 OP_ERROR = 0xff OP_HALT = 0x11 OP_SET_POS = 0x30 OP_HIRES = 0x31 # Opcodes for I2C extension OP_I2C_TEMP = 0x13 OP_I2C_IO_W = 0x14 OP_I2C...
from collections import defaultdict import pathlib import onnx CWD = pathlib.Path(f"{__file__}").parent import numpy as np def load_model(model_name): path = f"{CWD}/{model_name}" return onnx.load(path) def compute_size(n, shape_map, node_map, include_output=True): sizes = [shape_map[i] for i in n.input] ...
#!/usr/bin/env python3 ############## ROS Import ############### import rospy import std_msgs from sensor_msgs.msg import Image import numpy as np import random import time import itertools import os import cv2 from cv_bridge import CvBridge, CvBridgeError #import jetson.inference #import jetson.utils #net = jetson....
"""Read data from a LAMMPS data file.""" import sys # Format for GROMACS gro files: _GRO_FMT = [ ('{:5d}', 5), ('{:5s}', 5), ('{:5s}', 5), ('{:5d}', 5), ('{:8.3f}', 8), ('{:8.3f}', 8), ('{:8.3f}', 8), ] _GRO_BOX_FMT = '{:15.9f}' # Sections of data file with topology information: TOPOLOGY_I...
from SmoothPlannerClass import SmoothPathPlanner, planShortest import matplotlib.pyplot as plt import numpy as np from numpy import sin, cos, tan import time from scipy.io import savemat def singleSourceGoal(): dT = 0.1 initialState = [0.0, 0.0, 0.5*np.pi, 0, 0.3] finalState = [0.0, 15.0, 0.5*np.pi, 0, 0....
import numpy as np import matplotlib as mpl import os, sys, math, random, tarfile, glob, time, yaml, itertools import parse import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader from torchvision import transforms, utils from utils import * from logger imp...
""" Tests for the reference loader for EarningsCalendar. """ import blaze as bz from blaze.compute.core import swap_resources_into_scope import pandas as pd from six import iteritems from zipline.pipeline.common import ( ANNOUNCEMENT_FIELD_NAME, DAYS_SINCE_PREV, DAYS_TO_NEXT, NEXT_ANNOUNCEMENT, PRE...
import tenseal as ts import torch import base64 class F: @staticmethod def init_encrypt(poly_modulus_degree=8192,bits_scale=26): coeff_mod_bit_sizes=[31, bits_scale, bits_scale, bits_scale, bits_scale, bits_scale, bits_scale, 31] context = ts.context( ts.SCHEME_TYPE.CKKS, poly_modulus_degree, coeff_mod_...
# -*- coding: utf-8 -*- """ Implementation of the Simple MountainCar Environment and the Simple Mountain Car Preference Environment; these are as described in "EPMC: Every Visit Preference Monte Carlo for Reinforcement Learning" by <NAME> and <NAME> (2013) and in "Efficient Preference-based Reinforcement Learning" by...
# !/usr/bin/env python # -*- coding: utf-8 -*- # # Filename: docudatamodel.py # Project: cthreepo # Author: <NAME> # Created: Saturday, 1st December 2018 10:40:25 am # License: BSD 3-clause "New" or "Revised" License # Copyright (c) 2018 <NAME> # Last Modified: Friday, 31st May 2019 11:29:19 am # Modified By: <NAME> ...
import pandas as pd import numpy as np def read_superratings(s): return pd.read_excel(pd.ExcelFile(s)) def colour_green_dark(x): return '\cellcolor{CT_green1}(' + str(int(x)) + ')' def colour_green_light(x): return '\cellcolor{CT_green2}(' + str(int(x)) + ')' def colour_red_light(x): return ...
import tvm from tvm import relay, autotvm from tvm.contrib.utils import tempdir from tvm.contrib import ndk from tvm import te, topi from tvm.topi import nn from numbers import Integral import numpy as np def get_const_tuple(in_tuple): """Verifies input tuple is IntImm or Var, returns tuple of int or Var. Para...
import os import time import unittest from OpenDrive import net_interface from OpenDrive.client_side import file_changes_json as c_json from OpenDrive.client_side import interface from OpenDrive.client_side import merge_folders from OpenDrive.client_side import paths as c_paths from OpenDrive.general import merge_fold...
import base64 import warnings from contextlib import contextmanager from cryptography import exceptions as cryptexc from cryptography.hazmat import backends from cryptography.hazmat.primitives import ciphers, hashes, hmac from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives...
import os import math import youtokentome import streamlit as st import torch import torch.nn.functional as F from src.model import model st.write('# Utterance Generation') @st.cache def load_model(): model.load_state_dict(torch.load(os.path.join("model", 'model.pt'), map_location=torch.device('cpu'))) bpe_mode...
import redis import time import subprocess import multiprocessing from multiprocessing import Process, Pipe import os def start_flask(): print('Starting flask') subprocess.Popen(['cd extraction && gunicorn --workers 4 --bind 0.0.0.0:5000 wsgi:app'], shell=True) time.sleep(10) def start_redis(redis_db_path...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2019 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...
''' Binance Balancer 2020 - <NAME> Re-balances every hour based on manually fixed allocations Defaults to limit orders which are cancelled if unfilled and recalculated for the new rebalance ''' import math import time import pandas as pd import numpy as np from binance.client import Client from apscheduler.schedulers...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-LOG 蓝鲸日志平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-LOG 蓝鲸日志平台 is licensed under the MIT License. License for BK-LOG 蓝鲸日志平台: ------------------------------------------------...
# -*- coding: utf-8 -*- """SOURCE: https://github.com/kuszaj/claptcha""" """This module defines Claptcha and ClaptchaError classes.""" import sys import os import random from functools import wraps from io import BytesIO from PIL import Image, ImageDraw, ImageFont class ClaptchaError(Exception): """Exception c...
import math import numpy as np import chainer from chainer.backends.cuda import get_array_module from chainer import reporter import chainer.functions as F import chainer.links as L from chainer import initializers major, _, _ = chainer.__version__.split(".") MAJOR = int(major) if MAJOR >= 5: from chainer import s...
# Copyright 2018 Cambridge Quantum Computing # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
import time import argparse import os import sys import torch import cv2 import numpy as np import detectron2.utils.comm as comm from detectron2.checkpoint import DetectionCheckpointer from detectron2.data import build_detection_test_loader, build_detection_train_loader from detectron2.config import get_cfg from detect...
#!/usr/bin/env python import os import pysam import argparse import subprocess import logging from uuid import uuid4 from collections import defaultdict as dd from bx.intervals.intersection import Intersecter, Interval FORMAT = '%(asctime)s %(message)s' logging.basicConfig(format=FORMAT) logger = logging.getLogger(...
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distrib...
# -*- coding: utf-8 -*- # Copyright (c) 2020. Distributed under the terms of the MIT License. import numpy as np import pytest from vise.analyzer.dos_data import DosBySpinEnergy, DosPlotData from vise.analyzer.plot_dos import DosPlotter, DosMplSettings from vise.tests.helpers.assertion import assert_msonable from vis...
import numpy as np import xml.etree.cElementTree as ET from xml.dom import minidom from ase.data import atomic_masses from ase.units import eV, Hartree, Bohr, Ry, J import os from collections import Iterable, namedtuple from itertools import groupby from TB2J.utils import symbol_number import pickle def write_multib...
# Lint as: python2, python3 # Copyright 2019 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 # #...
import subprocess import re import os import shutil import argparse from pathlib import Path import multiprocessing from functools import partial import time import sys # Yapf requires python 3.6+ if not (sys.version_info.major == 3 and sys.version_info.minor >= 6): raise RuntimeError( "Requires Python 3.6...
import discord import pymongo from discord.ext import commands import math import datetime import random import asyncio import tools from discord.ext.commands import MemberConverter import logging logger = logging.getLogger(__name__) class Levels(commands.Cog): """Level related commands""" def __init__(self,...
import os import json import pickle import joblib import pandas as pd from flask import Flask, jsonify, request from peewee import ( Model, IntegerField, FloatField, TextField, IntegrityError,BooleanField ) from playhouse.shortcuts import model_to_dict from playhouse.db_url import connect from numpy import nan...
from collections import defaultdict import logging from threading import Thread import time import numpy as np import pandas as pd import cudf as gd from toolz import first, assoc from tornado import gen try: import sparse import scipy.sparse as ss except ImportError: sparse = False ss = False from d...
import os import numpy as np import pandas as pd import matplotlib.pyplot as plt plt.rcParams.update({'font.size': 18}) from textwrap import wrap def plot_metrics_bar(result_dirs, plot_dir, metrics="Acc", prefix="pancreas", groupby="features"): '''Plot Acc, ARI, macroF1 for different methods x-axis is...
# Basic libs import os import tensorflow as tf import numpy as np import time import pickle import open3d # OS functions from os import makedirs, listdir from os.path import exists, join, isfile, isdir import os.path as path # Dataset parent class from datasets.common import Dataset # ------------------------------...
import pytest from rotkehlchen.constants.assets import A_ETH from rotkehlchen.exchanges.data_structures import Trade from rotkehlchen.fval import FVal from rotkehlchen.history import limit_trade_list_to_period from rotkehlchen.tests.utils.constants import ETH_ADDRESS1, ETH_ADDRESS2, ETH_ADDRESS3 from rotkehlchen.tests...
# 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 app...
"""This module implements the XMLTVListing listing class.""" #pylint: disable=line-too-long import hashlib import logging import shutil import zlib from collections.abc import Hashable from datetime import datetime from functools import partial from os import PathLike from pathlib import Path from typing import IO, Any...
# Make sure the dependencies are installed using the command # pip/pip3 install -r ./requirements.txt --upgrade import time import json import os from joblib import Parallel, delayed import pandas as pd import numpy as np import scipy from sklearn.model_selection import train_test_split, KFold from sklearn.metrics i...
''' Copyright (c) 2017 <NAME> This file is part of mac_apt (macOS Artifact Parsing Tool). Usage or distribution of this software/code is subject to the terms of the MIT License. ''' import os from plugins.helpers.macinfo import * from plugins.helpers.writer import * import logging import biplist im...
#!/usr/bin/env python """ The script provides interface to base classes for generating SAR+Labels datacube """ import enum import os from pathlib import Path from icecube.bin.config import CubeConfig from icecube.bin.sar_cube.sar_datacube import SARDatacube from icecube.bin.sar_cube.slc_datacube import SLCDatacube fr...
""" Downstream task: BBBP: Binary labels of blood-brain barrier penetration(permeability) Dataset source: DeepChem """ import os, sys, argparse, time import json from tqdm import tqdm from rdkit import Chem import deepchem as dc import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as o...
import os, time, sys import numpy as np from pypianoroll import Multitrack, BinaryTrack, StandardTrack import cfp import torch import torch.nn as nn import torch.nn.functional as F import argparse def smoothing(roll): # step1 Turn consecutively pitch labels into notes. new_map = np.zeros(roll.shape) min_n...
# ###################################################################### # Copyright (c) 2014, Brookhaven Science Associates, Brookhaven # # National Laboratory. All rights reserved. # # # # Redistribution and use in ...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch import torch.nn.functional as F from torch import nn class FPN(nn.Module): """ Module that adds FPN on top of a list of feature maps. The feature maps are currently supposed to be in increasing depth order, and must b...
# -*- coding: utf-8 -*- import pytest from requests3._structures import CaseInsensitiveDict, LookupDict, HTTPHeaderDict from urllib3._collections import HTTPHeaderDict as U3HeaderDict class TestCaseInsensitiveDict: @pytest.fixture(autouse=True) def setup(self): """CaseInsensitiveDict instance with "...
""" This is converter of indexed gif files (1-8 colors) to Atari .asm data file. Requires pillow package to be installed. """ import os import argparse import logging import math import itertools from PIL import Image from atrtools.compress import Compress from atrtools.uncompress import Uncompress6502 def log(): r...
# -*- coding: utf-8 -*- from itertools import chain import os from unittest.case import TestCase import math import sys project_dir = os.path.join(os.path.dirname(__file__), '..') project_dir = os.path.normpath(project_dir) sys.path.append(project_dir) from atores import Obstaculo, Porco, PassaroVermelho, PassaroAma...
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function __all__ = ['RegistrationError', 'SimpleEntryFactory', 'EntryFactory'] import os from collections import defaultdict from fsfs import api, models, channels class RegistrationError(Exception): pass class SimpleEntryFactory(ob...
import sys import global_const import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable, Function if __name__ == "__main__": import os sys.path.append(os.path.join(global_const.CODEPATH, '../pyscatwave')) try: from scattering.scattering1d.util...
#!/usr/bin/env python import sys import shutil import os import select import unittest import argparse import time from multiprocessing import Process, Pipe from framework import VppTestRunner from debug import spawn_gdb from log import global_logger from discover_tests import discover_tests from subprocess import che...
# This Python file uses the following encoding: utf-8 #!/usr/bin/env python from gpiozero import CPUTemperature import psutil import os import serial import mysql.connector import config import json from datetime import datetime from shutil import copyfile import time import plotly.express as px from paramiko import S...
from cnct import R from reports.utils import ( convert_to_datetime, Progress, delta, get_parameter, get_ta_parameter, ) from concurrent import futures def generate(client, parameters, progress_callback): subscriptions_rql = R() if not parameters.get("products") or len(parameters['products'...
import pytest import mxnet as mx from mxnet import nd import numpy as np from rl_coach.architectures.mxnet_components.utils import * @pytest.mark.unit_test def test_to_mx_ndarray(): # scalar assert to_mx_ndarray(1.2) == nd.array([1.2]) # list of one scalar assert to_mx_ndarray([1.2]) == [nd.array([1...
import sys from pathlib import Path sys.path.append(str(Path(__file__).parent.parent)) from config import ANALYSIS as cfg import analysis.utils as utils import portion as P import pickle import os from analysis.transcript_parsing import parse def seg_invalid(row): """ This functions specifies what makes a se...
#!/usr/bin/env python3 from stl import mesh from mpl_toolkits import mplot3d from matplotlib import pyplot import math import numpy as np from math import pi import matplotlib.pyplot as plt def eul2rotm(phi,theta,gamma): ''' phi rotazione lungo z, theta rotazione lungo y, gamma rotazione lungo x''' phi = np.d...
import os import time import gc import torch as th import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader from PIL import Image from ctcdecode import CTCBeamDecoder import pytorch_lightning as pl from pytorch_lightning import seed_everything, Trainer from pytorch_lightning.ca...
import openmdao.api as om import numpy as np class SlotArea(om.ExplicitComponent): """ Component that calculates the slot area based on an polygonal approximation of the tooth geometry """ def initialize(self): self.options.declare("num_slots", types=int) def setup(self): self...
"""Extremely simple model where all parameters are from convolutions. """ import math import tensorflow as tf import numpy as np from cleverhans import initializers from cleverhans.serial import NoRefModel class Layer(object): def get_output_shape(self): return self.output_shape class Conv2D(Layer): """ A ...
#!/usr/bin/env python import xml.etree.ElementTree as etree from .core import NEWSMLG2_NS, BaseObject, GenericArray class CommonAttributes(BaseObject): attributes = { # An XML-specific identifier for the element. 'id': 'id', # An open placeholder for categorization. 'class': 'clas...
import inspect import wrapt from krules_core.subject import SubjectProperty, SubjectExtProperty, PayloadConst, PropertyType class Subject(object): """ Subject implementation Needs a storage strategy implementation """ def __init__(self, name, event_info={}, event_data=None, use_cache_default=T...
import datetime from datetime import timezone import google.auth import pandas as pd import pandas_gbq import requests from google.cloud import storage from pandas import DataFrame def get_vm_custom_envs(meta_key: str): response = requests.get( "http://metadata.google.internal/computeMetadata/v1/instance...
"""Functions/Classes for modeling Finite Functions as And Inverter Graphs.""" from __future__ import annotations import re from functools import reduce from typing import Any, Callable, Optional, Union from uuid import uuid1 import aiger_bv as BV import aiger_ptltl as LTL import attr import funcy as fn from pyrsiste...
#!/usr/bin/env python3 # coding: utf-8 # # $Id: rogue_test03.py 894 $ # SPDX-License-Identifier: BSD-2-Clause # """ from http://www.roguebasin.com/index.php?title=Roguelike_Tutorial,_using_python3%2Btdl,_part_3 """ import tdl from random import randint # actual size of the window SCREEN_WIDTH = 80 SCREEN_HEIGHT ...
import torch from .torch_helpers import NamedTensor from .utils import make_tuple from .nn import nn from .distributions import ndistributions import opt_einsum as oe class NTorch(type): def __getattr__(cls, name): if name in cls._build: def call(*args, **kwargs): assert "name...
""" This module provides all required functionality for the communication between the application master and workers. """ import dramatiq import os import msgpack import msgpack_numpy import uuid import logging import sys import asyncio from async_timeout import timeout from dramatiq.brokers.redis import RedisBroker ...