text
stringlengths
3.07k
12.6k
"""Decoy stubbing and spying library.""" from typing import Any, Callable, Generic, Optional, cast, overload from . import matchers, errors, warnings from .core import DecoyCore, StubCore from .types import ClassT, FuncT, ReturnT # ensure decoy does not pollute pytest tracebacks __tracebackhide__ = True class Decoy...
""" Support for HydroQuebec. Official component deprecated after HA 100.3 Use as custom_component pip3 install --target /config/deps --no-dependencies https://github.com/llluis/pyhydroquebec/archive/master.zip#pyhydroquebec==3.0.5 Get data from 'My Consumption Profile' page: https://www.hydroquebec.com/portail/en/grou...
from math import * from random import * from typing import Union, List, Optional, Type, Sequence EXPRESSION_ARGS = { "time": { "name": "time", "doc": """ Holds variables that reference the current training time. """, "args": { "epoch": { "type": ...
from colorama import init, Style, Fore, Back import sys, itertools, threading, time, requests from pprint import pprint from tabulate import tabulate from Spinner import Spinner init(autoreset=True) API_URL = 'https://api.github.com/' API_URL_1 = 'https://api.github.com/users/' usage = 'python github.py <username>\...
import time from dotenv import load_dotenv import request_interface load_dotenv() import os import struct import wave from datetime import datetime from threading import Thread import pvporcupine from pvrecorder import PvRecorder import SpeechRecognition import TextToSpeech client = TextToSpeech.create_client() M...
# MIT License # # Copyright (C) IBM Corporation 2019 # # 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...
import numpy as np from pandas.io.parsers import read_csv from sklearn.utils import shuffle import cv2 import matplotlib.pyplot as plt from keras.models import load_model def load_data(test=False): """ 当 test 为真, 加载测试数据, 否则加载训练数据 """ FTRAIN = './data/training.csv' FTEST = './data/test.csv' ...
# TODO : can be removed later import os import cv2 import numpy as np from CoarseNet import minutiae_net_utils, coarse_net_utils, coarse_net_model from FineNet import fine_net_model coarse_net = coarse_net_model.get_coarse_net_model( (None, None, 1), '/home/jakub/projects/bp/minutiae_classificator/models/Coar...
# Copyright (c) 2019 Uber Technologies, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
# -*- coding: utf-8 -*- """ Spyder Editor #, usecols=(2,0) #delimiter='\t' # for tab, default: whitespace This is a temporary script file. """ import numpy as np import ntpath import matplotlib.pyplot as plt from tkinter import filedialog as fd import os import ntpath import matplotlib.pyplot as p...
# -*- coding: utf-8 -*- import pandas as pd import numpy as np from config import _export_dir def preprocess(df, df2, df3, new_node_ids): def conditional_float_to_string(param): if np.isnan(param): new_param = 'none' else: new_param=str(int(param)) return new_p...
#!/usr/bin/env python3 # Copyright (c) 2016 <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, merg...
# Copyright 2017 Delft Robotics BV # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer....
import argparse import threading import time from typing import Union import influxdb from influxdb_client import InfluxDBClient from influxdb_client.client.write_api import WriteOptions class Writer: def __init__(self, influxdb_client: Union[InfluxDBClient, influxdb.InfluxDBClient], batch_size: int, ...
import torch import torch.nn as nn from .dropout import VariationalNormalEpanechnikovDropout __all__ = [ 'WordEmbeddings', 'VectorFirstEmbeddings', 'VectorLastEmbeddings', 'VectorInsideEmbeddings', ] class WordEmbeddingsBase(nn.Module): def __init__(self, vocab_size, ...
import os.path import time import msgpack import requests from requests.compat import urljoin, urlparse from .local import CatalogConfig from .remote import RemoteCatalogEntry from .utils import clamp, flatten, reload_on_change, make_prefix_tree class State(object): """Base class representing the state of a cat...
import torch as _torch import numpy as _np from typing import Union, List, Tuple from .layers import Conv2d, BatchNorm2d from .layers import Encoder2d, Dense2d from ._conversions import bounding_boxes_to_tensor, images_to_tensor from ._conversions import tensor_to_bounding_boxes from ._neural_network_classifier import ...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import binascii import nfc import pigpio import RPi.GPIO as GPIO import time import yaml from statemachine import StateMachine class ServoControllerPigpio(): def __init__(self, pin=18, frequency=50, limit_angle_f=180.0, limit_angle_r=0.0): self._pin = pin ...
from modules import checks from modules import filerw # <html><head> [headWriter] </head><body> [bodyWriter] </body></html> def buildIndexHtmlFile(indexHtmlHeadWriterFunction, indexHtmlBodyWriterFunction, settings): htmlFile = settings.htmlOutputFile settings.indentDepth = 2 htmlFile.write("<html>\n") htmlFile...
import sys, os, time, array, fcntl, unittest from struct import pack, unpack class DeviceMem(object): PATH = '/dev/zc_dma_mem_0' mem_write_1 = lambda self, addr, v: self.mem_write(addr, pack('B', v)) mem_write_2 = lambda self, addr, v: self.mem_write(addr, pack('H', v)) mem_write_4 = lambda self, ad...
# # Copyright <NAME> 2007,2008 # """ Code that wraps C++ HMM python module L{hmm._hmm}. Also contains code useful in its own right. """ from _hmm import * import os if os.name == 'nt': try: import _fpu as fpu except: from warnings import warn warn('Could not import FPU module: Only u...
import numpy as np import copy from app import models, schemas from fastapi import APIRouter, Depends, HTTPException, Body, status from sqlalchemy.orm import Session from sqlalchemy.orm.attributes import flag_modified from app.db.get_db import get_db from app.api.endpoint.login import oauth2_scheme from app.crud import...
# Mostly thanks to this implementation: # https://github.com/kupuguy/aoc2021/blob/main/src/day18.py # I was writing it with a binary tree implementation, but that did not go anywhere. # I did copy almost all the logic from the link above, but I ended up using my old # implementation with SnailNode as well. Most of what...
# -*- coding: utf-8 -*- """ @author: Taoting 将用coco格式的json转化成labeime标注格式的json """ import json import cv2 import numpy as np import os import pycocotools.mask as mask def polygonFromMask(maskedArr): # https://github.com/hazirbas/coco-json-converter/blob/master/generate_coco_json.py contours, _ = cv2.findContour...
import datetime from typing import Sequence, Optional, Tuple, List, Dict from pydantic import BaseModel import pyexlatex as pl from pyexlatex.models.landscape import Landscape from lectures.lab_exercise import LabExerciseGroup, LabExerciseLecture from lectures.model import Lecture, LectureGroup class ScheduleProjec...
"""Test default.py.""" from __future__ import unicode_literals from faker import Faker from pyramid import testing from learning_journal.data.entry_data import ENTRIES from learning_journal.models.mymodel import Base from learning_journal.models import Journal from datetime import datetime import pytest import random ...
# coding: utf-8 """ Contains handling of ASC logging files. Example .asc files: - https://bitbucket.org/tobylorenz/vector_asc/src/47556e1a6d32c859224ca62d075e1efcc67fa690/src/Vector/ASC/tests/unittests/data/CAN_Log_Trigger_3_2.asc?at=master&fileviewer=file-view-default - under `test/data/logfile.asc` """ fro...
import random import time from datetime import datetime, timedelta from flask import Blueprint from tinydb import Query from foodapp.db import * from webargs import fields from webargs.flaskparser import use_args user_bp = Blueprint('user', __name__, url_prefix='/api') new_user_args = { 'bot_token': fields.Str...
from nose.tools import * from pyccg.chart import * from pyccg.lexicon import Lexicon from pyccg.logic import * def _make_lexicon_with_derived_category(): lex = Lexicon.fromstring(r""" :- S, NP the => S/NP {\x.unique(x)} foo => NP {\x.foo(x)} bar => NP {\x.bar(x)} baz => NP {\x.baz(x)} """, include_se...
from typing import Tuple, Union, Optional, Callable import numpy as np from axi import Drawing from perlin_numpy import generate_perlin_noise_2d from shapely.geometry import LineString, MultiLineString, Point, LinearRing from tqdm import tqdm def circle_pack(width: int, height: int, min_separation: float) -> list[np...
from flask_restplus import Resource, Namespace from flask_restplus import fields from flask import request, Response from flask_jsonpify import jsonify from com.beiwei.es.search import es_get_data from com.beiwei.stats.eemd import eemd_analysis, ceemd_analysis from com.beiwei.plots.plot import plot_eemd from com.beiwei...
from fm_config import * class smt(): def __init__(self): self.init_dfs() self.load_sub_data() def init_dfs(self): self.sm_df = pd.DataFrame({'prop':0.0, 'mem_prop':0.0, '_count':0, ...
# Copyright (c) 2017–2018 crocoite contributors # # 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, ...
import sys import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as ticker import pandas as pd from meta_data import CVMetaData from smooth import * # Global variables S = 1.397 # Cross section area (height in 2D) c = 34000 # Sound speed rho = 1.3e-3 # Air density to_newton = 1e-5 # Convert ...
#!/usr/bin/env python """ Script to plot distributions of various quantities in a set of phosim instance catalog files produced by generateInstCat.py. """ import os import gzip import argparse from collections import defaultdict import numpy as np import matplotlib.pyplot as plt class HistArray(object): "Class to ...
NEXT_ALPHA_DICT = { "a":"b", "b":"c", "c":"d", "d":"e", "e":"f", "f":"g", "g":"h", "h":"i", "i":"j", "j":"k", "k":"l", ...
""" Configuration """ import collections import copy import functools import json import os import random import shutil import subprocess import sys import tempfile import numpy as np __all__ = [ "get_rcdir", "get_config_filename", "default_config", "get_config", "get_rl_history_filename", "...
"""ETL Processes""" import numpy as np from scipy import stats from .base import RecipeBase from .scrapers import stockmarket from .simulate import StockDaySim __all__ = ['prep_pricing_data', 'UpDownIndicator'] class UpDownIndicator(RecipeBase): valid_type = 'market' def __init__(self, symbol='SPY', timeof...
import os import sys from memory_profiler import profile as mprofile #sys.path.insert(0, "../../") from prediksicovidjatim.data.map import MapDataRepo, MapDataPred, MapDataReal from prediksicovidjatim import util, config, database from prediksicovidjatim.modeling import SeicrdRlcModel from prediksicovidjatim.mapping im...
# -*- coding: utf-8 -*- """ Created on Tue Jun 16 11:55:48 2020 @author: Casper """ import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import SimpleITK as sitk import random from src.data.data_loader import generate_heatmap import os from skimage import transform def visualiz...
import textwrap from django.test import TestCase from bs4 import BeautifulSoup from lxml import etree from bc.cases.backends.respond.constants import ( APTEAN_FORM_COMMENT, APTEAN_FORM_COMPLAINT, APTEAN_FORM_COMPLIMENT, APTEAN_FORM_DISCLOSURE, APTEAN_FORM_FOI, APTEAN_FORM_SAR, DESCRIPTION...
import numpy as np from typing import Dict, List, Any """ evaluation metric for segment-level precision/recall of video infringement localization """ def seg_len_accumulate(segments: np.ndarray, type: str = 'union') -> int: """ get accumulated length of all line segments union: the intersection area is c...
"""Implementation of state API.""" import logging import os import zlib import sqlite3 import tempfile import fnmatch import yaml from treadmill import context from treadmill import schema from treadmill import exc from treadmill import zknamespace as z from treadmill import zkutils _LOGGER = logging.getLogger(_...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jun 7 14:33:03 2020 #Classifier to distinguish between patients with a pouch phenotypes (normal pouch vs. pouchitis) based on bacterial speceis, metabolic pathways or enzmes profiles. #Author: Vadim (Dani) Dubinsky (<EMAIL>) """ import sys import pan...
#copyright 2021, Auton Systems LLC import argparse parser = argparse.ArgumentParser(description='run simulations') parser.add_argument('-N','--N_Samples', type=int, default=100, help='Number of samples to run') parser.add_argument('-n','--N_Workers', type=int, default=2, help='Number of workers to use') parser.add_ar...
""" Access functionality for resources. :copyright: Copyright 2010-2014 by <NAME> :license: BSD, see LICENSE for details. """ from qal.common.meta import list_prefixed_classes from qal.common.json import json_add_child_properties from qal.common.recurse import Recurse from qal import __version__ d...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import datetime from dateutil.parser import parse import paho.mqtt.client as paho import yaml import json import time from _thread import start_new_thread import copy def read_configuration(path="config.yaml"): """ opens and reads yaml configuration f...
import arrayfire as af import typing as tp class DeviceMemoryInfo: def __init__(self, allocated_buffers: int, allocated_bytes: int, locked_buffers: int, locked_bytes: int) -> None: self._allocated_buffers = allocated_buffers self....
import pickle import json from sklearn import preprocessing from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity import numpy as np from datasets import DATASET import math class Similarity: __slots__ = ['src_files', 'src_strings'] def ...
#!/usr/bin/env python3 import os import apt from pprint import pprint from dockerfile_parse import DockerfileParser from IPython.terminal.debugger import set_trace as keyboard # This script updates each library in the Dockerfile to the newest version. # Each `apt-get install` command needs to be formatted with one lib...
from abc import ABC from typing import Iterator, Union, Type import analysis.p_types as p_types from analysis.itxyek_base import ITXYEK, XYPoint from analysis.metrics_base import MetricValueUndefined, METRIC_TYPE from analysis.physics import AngleCalc, Velocity, Acceleration """ When calculating angle, speed, etc. us...
""" @file: back_propagation_nn.py @author: magician @date: 2019/4/22 """ import math import random import numpy as np np.seterr(all='ignore') def sigmoid(x): return 1 / (1 + np.exp(-x)) def dsigmoid(y): return y * (1.0 - y) def tanh(x): return math.tanh(x) def dtanh(y): return 1 - y * y class...
# This little code fragment implements a fourth order compact finite difference scheme with edge formulae # RMC May 2019 <NAME>, in Alcala de Henares from numpy import linalg as LA import numpy as np # Already done earlier in the notebook from scipy import sparse import scipy as sp # Already done earlier in the notebo...
import warnings import numpy as np from .target_space import TargetSpace from .event import Events, DEFAULT_EVENTS from .logger import _get_default_logger from .util import UtilityFunction, acq_max, ensure_rng from sklearn.gaussian_process.kernels import Matern from sklearn.gaussian_process import GaussianProcessRegr...
from QuantTorch.layers import DorefaConv2d, LinearDorefa from QuantTorch.functions import DorefaQuant, nnQuantWeight import torch import pytest from random import randint def equals(a, b, epsilon=1e-12): return torch.all(torch.lt( torch.abs(a-b), epsilon )) def test_lin_layer_train(): """ Test the eval ...
"""Handle CLI tool configuration and commands.""" import copy from datetime import datetime import multiprocessing as mp import pathlib import sys import click from loguru import logger from ._config import load_config, save_config from .core import TxtFerret from ._default import LOG_HEADERS def set_logger(**cli_...
# -*- coding: utf-8 -*- import hashlib from django.db import transaction from player.tenhou.models import TenhouStatistics, TenhouNickname from utils.general import get_month_first_day, get_month_last_day from utils.tenhou.current_tenhou_games import lobbies_dict from utils.tenhou.points_calculator import PointsCalcu...
""" `yarl` (Yet another URL library) wrapper on `str` type. You should do NOT use this module in new code. Use `yarl` directly instead. ```python >>> url = URL('https://www.python.org') >>> url / 'foo' / 'bar' URL('https://www.python.org/foo/bar') >>> url / 'foo' % {'bar': 'baz'} URL('https://www.python.org/foo?bar=b...
import os from bootstrap_modal_forms.generic import BSModalCreateView, BSModalUpdateView from django.contrib import messages from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse_lazy from django.utils....
from math import sqrt, log, exp from scipy.optimize import root_scalar from scipy.stats import binom import numpy as np class ShuffleAmplificationBound: """Base class for "privacy amplification by shuffling" bounds.""" def __init__(self, name='BoundBase', tol=None): """Parameters: name (s...
import albumentations as A import argparse import cv2 import json, os import shutil from tqdm import tqdm from common import transform, convert_8coords_to_4coords, CheckExistsDir from coco_validation import valid_data from pycocotools.coco import COCO crane_color = (255, 255, 0) container_color = (255, 0, 0) ss_color...
""" Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 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/L...
import time from deluge_client import DelugeRPCClient def format_time(secs): if secs < 60: time_str = '{:d}s'.format(secs) elif secs < 3600: time_str = '{:d}m {:d}s'.format(secs // 60, secs % 60) elif secs < 86400: time_str = '{:d}h {:d}m'.format(secs // 3600, secs // 60 % 60) ...
""" open_discussions views """ from django.conf import settings from django.http import ( Http404, HttpResponse, HttpResponsePermanentRedirect, HttpResponseNotFound, HttpResponseForbidden, HttpResponseBadRequest, ) from django.shortcuts import render, get_object_or_404 from django.urls import re...
#!/usr/bin/env python3 import math import sys import curses from time import sleep from copy import deepcopy from curses import wrapper def transform(vertex): # First: Cart. to polar, throw out r x, y, z = vertex angle_h = math.atan(y/x) angle_v = math.asin(z/math.sqrt(x**2+y**2+z**2)) pixel_x = int((angle_h+(F...
from os.path import join import sys import numpy as np import pickle from asdl.asdl import ASDLGrammar from asdl.hypothesis import Hypothesis, ApplyRuleAction from components.action_info import get_action_infos from components.dataset import Example from components.vocab import VocabEntry, Vocab from asdl.lang.streg...
import cv2, os, glob import numpy as np from xml.etree import ElementTree as ET from .base import TextDetectionDatasetBase, Compose from ..._utils import DATA_ROOT, _check_ins, _get_xml_et_value SynthText_class_labels = ['text'] SynthText_class_nums = len(SynthText_class_labels) ICDARText_ROOT = os.path.join(DATA_RO...
from itertools import chain import click from layerslib import cloudfront as CF from layerslib import ec2 as EC2 from .utils import J, my_ipaddress, setup @click.group() @click.option("--profile_name", "-p", default=None) @click.pass_context def ec2(ctx, profile_name): setup(ctx, profile_name) @ec2.command()...
import pandas as pd import plotly.graph_objs as go def cleandata(dataset, keepcolumns = ['Country Name', '1990','2000', '2010', '2019'], value_variables = ['1990', '2000', '2010', '2019']): """Clean world bank data for a visualizaiton dashboard Keeps data range of dates in keep_columns variable and data for ...
import time from datetime import timedelta import faiss import numpy as np import torch import torch.nn as nn from utils import utils def validate(val_loader, model, criterion, args): batch_time = utils.AverageMeter('Time', ':6.3f') losses = utils.AverageMeter('Loss', ':.4e') top1 = utils.AverageMeter('...
import shutil from inspect import getfile from pathlib import Path import dectate import pytest from kaybee.plugins.resources.directive import ResourceDirective from kaybee.plugins.resources.handlers import ( handle_builderinited, initialize_resources_container, register_template_directory, add_direct...
""" This module is intended to provide a thin wrapper for the dcos-cli *binary* The dcos-cli in some versions is highly dependent upon state and is not the most direct interface for interacting with a DC/OS cluster. Under the hood, the CLI is just a helper for making calls to the HTTP REST APIs so often users will get...
"""Workspace rules (GHC binary distributions)""" load("@bazel_skylib//lib:paths.bzl", "paths") _GHC_BINS = { "8.4.1": { "linux-x86_64": ("https://downloads.haskell.org/~ghc/8.4.1/ghc-8.4.1-x86_64-deb8-linux.tar.xz", "427c77a934b30c3f1de992c38c072afb4323fe6fb30dbac919ca8cb6ae98fbd9"), "darwin-x86_6...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import absolute_import import _pickle as pickle import numpy as np import random import os from .utils import pad_seq, bytes_to_file, \ read_split_image, shift_and_resize_image, normalize_image class PickledImageProvider(object): de...
from django.core.exceptions import ValidationError from django.core.validators import RegexValidator from django.db import models from django.db.models.signals import pre_save, post_save from django.dispatch import receiver from bibliography.models import Source from brit.models import NamedUserObjectModel from maps.m...
#!/usr/bin/env python3 import argparse from collections import namedtuple import logging import os import requests import sys import http.client import json API_TOKEN_ENVVAR = 'METERIAN_API_TOKEN' TIMEOUT = namedtuple('literal', 'text status_code')(text='{"status":"timeout"}', status_code=999) LANGUAGES = [ 'java',...
# Para ler aquivos TSV, CSV (tudo a mesma coisa, só muda se é separado por tab ou ; , etc) # O nome é csv pois o separado por , (comma) é o mais comum (padrão excel, por assim dizer) import csv # Para dar parse já que a linha é codificada em url (quando tem algum caractere especial # tipo em Zürich, vai estar codifica...
import os import string import sys import unittest from collections import defaultdict from uuid import UUID from uuid import uuid4 from shortuuid.main import decode from shortuuid.main import encode from shortuuid.main import get_alphabet from shortuuid.main import random from shortuuid.main import set_alphabet from ...
__author__ = 'robert' import numpy as np import pandas as pd import logging import os # For path names working under Linux and Windows from pypet import Environment, cartesian_product def run_neuron(traj): """Runs a simulation of a model neuron. :param traj: Container with all parameters. :re...
#!/usr/bin/env python3 # Copyright (C) Alibaba Group Holding Limited. """ S3D/S3DG branch. """ import torch import torch.nn as nn from models.base.base_blocks import ( BRANCH_REGISTRY, InceptionBaseConv3D ) class InceptionBlock3D(nn.Module): """ Element constructing the S3D/S3DG. See models/base/b...
import json from abc import abstractmethod from typing import Dict, List, Tuple, Iterable, Optional, Set from jellycc.project.grammar import Terminal, CodeBlock, SharedGrammar from jellycc.utils.error import CCError from jellycc.utils.source import SrcLoc class Type: def __init__(self) -> None: pass def get_ori...
################################################################################ # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this...
from typing import Any, Callable, Dict, List, Optional, TypeVar, cast import attr from ..models import Response from ..runner import events from ..runner.serialization import SerializedCase, deduplicate_checks from ..utils import merge S = TypeVar("S", bound=events.ExecutionEvent) SerializeFunc = Callable[[S], Optio...
#BlockComPhone Pi Notification Central from PitftGraphicLib import * import sys import os import time initdis() # Slot Configuration def slotconf(slot, app): if slot == 1: make_button(app[0], 25, 95, 27, 205, 5, app[1], app[2], app[3]) if slot == 2: make_button(app[0], 25, 132,...
import os import re import numpy as np from os.path import exists from obspy.core import Stream, Trace from obspy.geodetics import gps2dist_azimuth from mtuq.util import fullpath, unzip, url2uuid, urlopen_with_retry from mtuq.util.signal import get_distance_in_m, get_distance_in_deg GREENS_TENSOR_FILENAMES = [ ...
import random import typing from ..config import settings from ..maths.vector import UP, UP_RIGHT, UP_LEFT, DOWN, DOWN_LEFT, DOWN_RIGHT, LEFT, RIGHT from ..maths import Position from ..tiles import Tile, get_tile from ..utils import terminal from .cooridors import Cooridor from .levels import Level from ..ecs import E...
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
""" ct_utils.py Script with shared utility functions, such as truncating floats """ import inspect import json import math import os import jsonpickle import numpy as np def truncate_float_array(xs, precision=3): """ Vectorized version of truncate_float(...) Args: x (list of float) List ...
''' RenameBot This file is a part of mrvishal2k2 rename repo Dont kang !!! © Mrvishal2k2 ''' import pyrogram from pyrogram import Client, filters from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup,ForceReply from root.utils.utils import * from root.utils.uploader import uploader import asyncio from ...
import time import math import random import numpy as np import os import sys from pathlib import Path CURRENT_PATH = str(Path(__file__).resolve().parent.parent.parent) olympics_path = os.path.join(CURRENT_PATH) sys.path.append(olympics_path) object_path = '/olympics' sys.path.append(os.path.join(olympics_path+object...
# Copyright 2010 New Relic, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
# coding=utf-8 from LxBasic import bscMtdCore, bscMethods, bscObjects from LxPreset import prsConfigure # from LxCore.preset.prod import scenePr # from LxGui.qt import qtWidgets_, qtChart_, guiQtWidgets # none = '' # def setListScRenderImageCustomize( parentUi, customizes, projectName, ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from datetime import timedelta from django.db import models from django.conf import settings from django.db.models import F from django.utils import timezone from django.dispatch import receiver from django.contrib.contenttypes.fields import GenericForeig...
import os import numpy as np import torch import torch.utils.data as data_utils from torch import nn from torch.autograd import Variable from torch.functional import F from torch.nn.modules import upsampling from torch.optim import Adam from torchvision.datasets import utils def get_data_loader(dataset_location, bat...
# CORE PACKAGES import sys, os import nbimporter import matplotlib.pyplot as plt from multiprocessing import Pool import nilearn.plotting import nibabel import pandas as pd import numpy as np import h5py import pickle # SETTING DIRECTORY VARIABLES SRC_DIR = os.path.dirname(os.path.realpath(__file__)) PROJ_DIR = os.p...
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """ Tests a variety of export options with our surgery methods applied, including torchscript, torch.fx, and ONNX. """ import os import pathlib from typing import Any, Callable, Type import pytest import torch import torch.fx from compo...
import numpy as np import sklearn from sklearn.neural_network import MLPClassifier from scipy.optimize import fmin_l_bfgs_b import io import os import sys import tempfile import contextlib class MLPClassifierLBFGS(MLPClassifier): ''' Multi-layer Perceptron classifier which uses L-BFGS to optimize. Parameter...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # pyre-ignore-all-errors[2,33] from collections import defaultdict from typing import Any, Counter, DefaultDict, Dict, Optional, Tuple, Union import torch.nn as nn from torch import Tensor from .jit_analysis import JitModelAnalysis from .jit_han...
import numpy as np import pytest import pandas as pd from pandas import compat from pandas.core.arrays.numpy_ import PandasArray, PandasDtype import pandas.util.testing as tm from . import base @pytest.fixture def dtype(): return PandasDtype(np.dtype('float')) @pytest.fixture def allow_in_pandas(monkeypatch):...