text
stringlengths
3.07k
12.6k
# ---------------------------------------------------------------------------- # Copyright (c) 2017-2020, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
import pytest from rdkit import Chem from polymetrizer.graph import AtomGraph, MolecularGraph from polymetrizer import Monomer from .smiles import ACE, CYS, PRO, CYS3, CYS3PRO, CYS3PRO2 @pytest.fixture() def ace_graph(): return MolecularGraph.from_smiles(ACE) @pytest.fixture() def cys_graph(): return Mole...
#!/usr/bin/env python3 import argparse import allel import numpy as np import pandas as pd # this script generate a dataframe file for allele depths for each samples def init_argparser(): p = argparse.ArgumentParser() p.add_argument('-o', '--outfile', default='outdepths.txt') p.add_argument('-b', '--bed...
#coding=utf-8 import numpy as np import functools import tensorflow as tf import keras from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten import matplotlib.pyplot as plt plt.switch_backend('agg') class LossHistory(keras.callbacks.Callback): def on_train_begin(self, logs={}): ...
# Borrowed for PyTorch repo # This script outputs relevant system environment info # Run it with `python collect_env.py`. import re import subprocess import sys from collections import namedtuple from setup import NeodroidPackage import neodroid PY3 = sys.version_info >= (3, 0) # System Environment Information Syst...
""" python version compatibility code """ import sys import inspect import types import re import functools import py import _pytest try: import enum except ImportError: # pragma: no cover # Only available in Python 3.4+ or as a backport enum = None _PY3 = sys.version_info > (3, 0) _PY2 = not _PY3 ...
import re import random import itertools import math from collections import defaultdict from src.utilities import * from src import channels, users, debuglog, errlog, plog from src.functions import get_players, get_all_players, get_main_role, get_reveal_role, get_target from src.decorators import command, event_liste...
import double_integrator import neural_network_lyapunov.control_lyapunov as control_lyapunov import neural_network_lyapunov.mip_utils as mip_utils import torch.nn as nn import torch import numpy as np import cvxpy as cp import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # noqa """ This file exerci...
#!/usr/bin/python # -*- coding: UTF-8 -*- import numpy as np import os # import dependencies from data_generator import Generator from model import Siamese_GNN from Logger import Logger import time import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt #Pytorch requirements import unicodedata im...
from __future__ import (absolute_import, unicode_literals) from collections import OrderedDict from django import template from django.core.urlresolvers import reverse register = template.Library() # TODO Cleanup this file. Lot unnused @register.simple_tag(takes_context=True) def update_plugin_groups_counter(con...
import collections import json import numpy as np import warnings from . import c, exceptions PY_TO_DTYPE = { bool: np.dtype(bool), int: np.dtype(int), float: np.dtype(float), } VALID_PY_TYPES = { bool, int, float, } VALID_NP_TYPES = { np.bool_, np.int8, np.uint8, np.int16...
import tensorflow as tf import numpy as np from random import choice, uniform from collections import deque from cnn import Cnn from config import LEARNING_RATE, EPSILON_GREEDY_START_PROB, EPSILON_GREEDY_END_PROB, EPSILON_GREEDY_MAX_STATES, \ MAX_MEM, BATCH_SIZE, VISION_W, VISION_B, VISION_F, TARGET_NETWORK_UPDATE...
from collections import deque import os import cv2 from .wrapper_base import Wrapper, ObservationWrapper import gym import gym.spaces as spaces import numpy as np os.environ.setdefault("PATH", "") cv2.ocl.setUseOpenCL(False) class FrameStack(Wrapper): def __init__(self, env, k): """Stack k last frames."...
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT license. """ python -m tf2onnx.convert : tool to convert a frozen tensorflow graph to onnx """ from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import tens...
# Copyright 2018 The TensorFlow Probability 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 o...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from...
"""The Admin module for the Bower Cache registry.""" import logging from django import forms from django.core.exceptions import ValidationError from django.conf import settings from django.conf.urls import patterns, url from django.contrib import admin, messages from django.contrib.admin.views.main import ChangeList f...
import os import sys import logging import paddle import argparse import functools import math import paddle.fluid as fluid sys.path.append("..") import imagenet_reader as reader import models sys.path.append("../../") from utility import add_arguments, print_arguments from paddle.fluid.contrib.slim import Compressor ...
"""Utilities to combine converted images into atlas and to create manifest.""" import math import os from absl import logging from PIL import Image # Manifest Key names MANIFEST_IMAGE_NAME_KEY = 'image_name' MANIFEST_SOURCE_IMAGE_KEY = 'source_image' MANIFEST_OFFSET_X_KEY = 'offset_x' MANIFEST_OFFSET_Y_KEY = 'offset_...
#!/usr/bin/env python from funlib.show.neuroglancer import add_layer import argparse import daisy import glob import neuroglancer import os import webbrowser import numpy as np import zarr parser = argparse.ArgumentParser() parser.add_argument( '--file', '-f', type=str, action='append', help="The ...
import os import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from utils import * import numpy as np import argparse from itertools import product from torch.utils.data import DataLoader def main(args): test_hard_accs, test_accs = [], [] with open("runs.txt", "a") as f: ...
import tensorflow as tf from tensorflow.python.framework import ops import open3d if open3d.core.cuda.device_count() > 0: from open3d.ml.tf.ops import furthest_point_sampling, three_nn, three_interpolate, three_interpolate_grad, ball_query def furthest_point_sample(xyz, npoint): """Uses iterative furthest p...
#!/usr/bin/env python3 import math import argparse from collections import Counter import config as cfg def main(args): def get_log_prob(n_gram, model, caches): """ This is a nested method that will be passed to eval_model(). Args: n_gram (tuple of str): represents an n-gram...
import camelot import json def get_table_height(table): all_y = [] for item in table.rows: all_y.extend(item) all_y = list(all_y) return max(all_y) - min(all_y) def get_table_width(table): all_x = [] for item in table.cols: all_x.extend(item) all_x = list(all_x) ret...
import os import time from itertools import count import ciso8601 import requests from dotenv import load_dotenv from terminaltables import SingleTable LANGUAGES = [ "Java", "C++", "Python", "Javascript", "Go", "Ruby", "Swift", "PHP" ] PUBLISHED...
""" Copyright 2017-present Airbnb, 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 writing, sof...
"""Animations interpolate a property between two values over a number of frames. They can be combined to run at the same time, or directly after each other.""" class Animation(object): """ Creates an animation on *property*, with the specified *easing*, to last *duration* in seconds. The following exa...
import versions from . import framework as fw import random, json, datetime, math version = versions.Version(1, 9, 0) nihonium_minver = versions.Version(0, 12, 0) alt_minvers = {} did_roll = False pc_len = datetime.timedelta(minutes=30) def rollADice(bot_data, thread_data, user_data, action="roll"): global did_r...
# -- coding: utf-8 -- # Copyright 2018 <NAME> <<EMAIL>> import pickle import zipfile import os import shutil import tempfile """ This small utility can save and load python objects to a single file. It uses ZIP DEFLATE compression method in order to keep the file small. It works in a similar way as numpy.savez_compr...
from operator_api.decorators import notification_on_error import logging import traceback import sys from celery import shared_task, exceptions from django.conf import settings from celery.utils.log import get_task_logger from django.db import transaction from contractor.interfaces import NOCUSTContractInterface, Loca...
""" Test fusing two directory trees / wheels """ import os from os.path import (join as pjoin, relpath, isdir, dirname, basename) import shutil from ..tools import (cmp_contents, get_archs, zip2dir, dir2zip, back_tick, open_readable) from ..fuse import fuse_trees, fuse_wheels from ..tmpdirs impor...
import argparse import os import time import numpy as np import chainer from chainer import cuda import pyprind import utils import treetk import dataloader import treesamplers # NOTE import metrics def main(args): #################### # Arguments tree_sampling = args.tree_sampling # NOTE trial_nam...
import cv2 import face_recognition import json import mysql.connector import numpy as np import os import pickle from datetime import datetime from dotenv import load_dotenv from pathlib import Path env_path = Path('../..') / '.env' load_dotenv(dotenv_path=env_path) def insert_attendance(attendance, dat...
import shutil import tempfile import unittest import inspect import os.path import sqlalchemy import logging import json from ..initialize import Initialize from ..ingest.IngestRSS import IngestRSS from ..features.BagOfWords import BagOfWords from ..features.Datasource import Datasource from ..dim_reduce.LSI import LS...
import numpy as np import tensorflow as tf from tensorflow.contrib.keras import backend as K import os import matplotlib.pyplot as plt from tensorflow.python.keras.models import Sequential, load_model from tensorflow.python.keras.layers import Dense, Activation, Dropout from sklearn.metrics import confusion_matrix, cla...
import json import os from datetime import date, datetime from pathlib import Path from time import sleep import requests import servicemanager import spotipy import spotipy.util as util import win32event import win32service import win32serviceutil import ssmi config_dir = str(Path.home()) + '\\SSMI' def writeLog(...
import m5 from m5.defines import buildEnv from m5.objects import * from m5.util import addToPath, fatal import math class NoCSocket(object): """docstring for NoCSocket.""" def __init__(self): super(NoCSocket, self).__init__() self.controller = 0 class DirectorySocket(NoCSocket): """...
import torch import torch.optim as optim import plot as plotter import matplotlib.pyplot as plt def train_init(q, data, targets, n_init_train_steps=1000, lr=0.5): optimizer = optim.SGD(q.parameters(), lr=lr) for i in range(n_init_train_steps): optimizer.zero_grad() q_vals = q(data) los...
""" Utilities module. """ import itertools import numpy as np import os import zlib # import logging # # from pprint import pprint, pformat # # logger = logging.getLogger("k3d") # fh = logging.FileHandler('k3d.log') # logger.addHandler(fh) # logger.setLevel(logging.DEBUG) # pylint: disable=unused-argument # noinsp...
import os import glob import pandas as pd import numpy as np import scipy as sp import scipy.interpolate # Welib https://github.com/ebranlard/welib import welib import welib.fast.fastlib as fastlib import welib.tools.clean_exceptions from welib.weio.fast_input_deck import * from welib.weio.fast_input_file import * de...
# writers.py - re/encoding csv.writer wrappers # TODO: consider Writer.writerow(<iterable>) (Python 3.5 compat) from __future__ import unicode_literals import io import csv from ._common import PY2, ENCODING, DIALECT from ._common import none_encoding, is_8bit_clean, csv_args from ._dispatch import register_writer ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.core.files.base import ContentFile from django.core.files.uploadedfile import InMemoryUploadedFile from django.db import IntegrityError from django.db.models import F from django.http import JsonResponse, HttpResponseForbidden, HttpResponseBad...
## # .python.element ## import os from abc import ABCMeta, abstractproperty, abstractmethod from .string import indent from .decorlib import propertydoc class RecursiveFactor(Exception): """ Raised when a factor is ultimately composed of itself. """ pass class Element(object, metaclass = ABCMeta): """ The purpo...
# Copyright (c) 2021-2022, NVIDIA 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...
# coding=utf-8 # Copyright 2020 The Trax 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 a...
# Copyright 2020 Google LLC. 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 a...
import os from CPAC.pipeline import nipype_pipeline_engine as pe import nipype.interfaces.utility as util def compute_fisher_z_score(correlation_file, timeseries_one_d): """ Computes the fisher z transform of the input correlation map If the correlation map contains data for multiple ROIs then the fun...
"""Helper functions for Convolutional Sparse Coding. Author : tommoral <<EMAIL>> """ import numpy as np from scipy import signal from .shape_helpers import get_full_support, get_valid_support def compute_ztz(z, atom_support, padding_support=None): """ ztz.shape = n_atoms, n_atoms, 2 * atom_support - 1 ...
# Copyright (C) 2019 Intel Corporation # SPDX-License-Identifier: BSD-3-Clause """ Contains classes and functions related to parsing a file, and building a tree of nodes from it. """ import os from codebasin.file_source import get_file_source from . import preprocessor # pylint : disable=no-name-in-module from . impo...
import binascii import base64 import datetime from rest_framework import serializers from . import models, utils # pylint: disable=abstract-method # pylint complains about missing optional `create` and `update` methods in # a bunch of serializers # Custom Fields class Base64Field(serializers.Field): def to_rep...
import argparse import sys import torch import torch.nn as nn import torch.optim as optim from tqdm import tqdm import utils.classfiers as cl import utils.utils as utils import torch.nn.functional as F import numpy as np def main(args): torch.manual_seed(17) # Randomly seed PyTorch # Load train, dev, te...
import numpy as np import matplotlib.pyplot as plt import random import math from numpy.random import default_rng rng = default_rng() # Generating data following a gaussian distribution def generate_centered_gaussian(N, cov): data = rng.multivariate_normal( (0,0), cov, size = N, check_valid='ignore') retu...
from flask_bcrypt import Bcrypt from flask_login import LoginManager from flask_admin import Admin from flask_session import Session from functools import * from flask_security import Security, UserMixin, RoleMixin, login_required, current_user from flask.sessions import SessionInterface, SessionMixin from werkzeug.da...
import json import codecs import operator import numpy as np from math import exp, isnan from time import time CLIMBING_AREAS_FILE = './data/rock-climbing/flattened-climbing-routes-2019.json' COUNTIES_FILE = './data/us-census/us-county-lat-long-2017.txt' ZIPCODES_FILE = './data/us-census/us-zipcode-lat-long-2017.txt' ...
import discord from discord.ext import commands import utils import json import yaml on_strs = ["yes", "y", "true", "t", "1", "enable", "on"] off_strs = ["no", "n", "false", "f", "0", "disable", "off"] default_settings = { k: v["default"] for k, v in utils.options.items()} # Change server settings. class Setting...
# -*- 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. ##############################################################...
import torch import torch.nn as nn import math import time from nets.adaptive_conv import AdaptiveConv2d from nets.network_init import GaussianInit, MSRAInit class VGGNetwork(nn.Module): def __init__(self, cfg='VGG16', batch_norm=False): super(VGGNetwork, self).__init__() self.layers ...
from __future__ import unicode_literals import ctypes import logging import re import psycopg2.extensions from .utils import ( AllDatabases, Timer, UserError, ensure_unicode, lower1, urlparse, urlunparse, ) class ChangeLogger(logging.getLoggerClass()): def change(self, msg, *args, *...
import logging import random import asyncio import time import typing import aiohttp import json import discord import discord.ext.commands as commands from bot.consts import Colors from bot.utils.converters import Duration from datetime import datetime from bot.messaging.events import Events log = logging.getLogge...
#!/usr/bin/env python import glob import json import os import click from collections import defaultdict, OrderedDict from utils import ( reformat_phone_number, reformat_address, get_data_dir, get_jurisdiction_id, dump_obj, ocd_uuid, ) def process_link(link): if not link["note"]: d...
# -*- coding: utf-8 -*- # -------------------------------- # Name: xywy_crawler.py # Author: <EMAIL> # @Time 2020/7/19 上午11:56 # Description: 寻医问药网站数据爬取器 # -------------------------------- import requests as r import os from lxml import etree def crawl_disease(): """ description: 抓取疾病...
import chainer import chainer.functions as F import chainer.links as L class Discriminator(chainer.Chain): """Discriminator of Cycle-GAN. (70x70 PatchGAN) Note: Batch normalization will be instance normalization if batch size is 1. """ def __init__(self): super(Discriminator, self)....
from types import ClassType import warnings from django.contrib.contenttypes.models import ContentType from django.db import models from django.db.models.fields.related import OneToOneField from django.db.models.manager import Manager from django.db.models.query import QuerySet class InheritanceQuerySet(QuerySet): ...
# coding=utf-8 # Copyright 2021 The Uncertainty Baselines 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 ap...
#!/usr/bin/env python3 # ======---------------------------------------------------------------====== # # # # Copyright 2021 <NAME> <<EMAIL>> # # ...
# -*- coding: utf-8 -*- import argparse import sys, time import chainer import chainer.optimizers import chainer.serializers import chainer.functions as F from chainer import Variable from chainer import cuda import numpy as np from model import LetterClassifyer def argument(): parser = argparse.ArgumentParser()...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on 20.04.2021 - 22:09 @author: ALPARSLAN """ from selenium import webdriver import time import re import pandas as pd from collections import defaultdict import getpass import argparse def main(watchlist=False, email=None, passwd=None): """ Selenium s...
import numpy as np from scipy import stats from copy import copy import warnings from scipy.stats import f_oneway, f from .dataset import Dataset __all__ = ['Dataset'] class VarianceThreshold: """ The variance threshold is a simple baseline approach to feature selection. It removes all features which vari...
# 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...
# Deprecated code from typing import Dict, List, Tuple from rtree import index from itertools import combinations from ContextAccessor import ContextAccessor from utils import * def device_state_conflict(dis_i, dis_j): total_j = sum(dis_j) prob = 0 for idx, p in enumerate(dis_i): prob += p * (tota...
# Code generated by lark_sdk_gen. DO NOT EDIT. from pylark.lark_request import RawRequestReq, _new_method_option from pylark import lark_type, lark_type_sheet, lark_type_approval import attr import typing import io @attr.s class GetDriveCommentListReq(object): file_type: lark_type.FileType = attr.ib( fac...
import logging from typing import List import discord from discord.ext import commands from phelper.bot import PotiaBot class AlumniRole(commands.Cog): _VALID_MEMBER_ROLE = [ 880773390305206276, 880773390305206275, 880773390305206274, ] _ALUMNUS_ID = 890102605789937745 def __...
#!/usr/bin/python # Copyright (c) 2014 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. """Generate new bench expectations from results of trybots on a code review.""" import collections import compare_codereview import...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from collections import defaultdict import argparse import cv2 import glob import logging import os import sys import time from caffe2.python import workspace from core...
#Need for Speed: Edge stuff is handled here. import dbo import cas import payload import ebx import io import os from struct import pack,unpack def readStringBuffer(f,len): result=b"" end=f.tell()+len result=b"" while 1: byte=f.read(1) if byte==b"\x00": break result+=byte ...
from interface import implements from datashape import istabular from .core import ( bind_expression_to_resources, ) from zipline.pipeline.common import ( EVENT_DATE_FIELD_NAME, FISCAL_QUARTER_FIELD_NAME, FISCAL_YEAR_FIELD_NAME, SID_FIELD_NAME, TS_FIELD_NAME, ) from zipline.pipeline.loaders.bas...
# # This file is part of Brazil Data Cube Collection Builder. # Copyright (C) 2019-2020 INPE. # # Brazil Data Cube Collection Builder is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. # """Define interface for validate request date.""" ...
# ------------------------------------------------------------------------------ # # Project: pytdml # Authors: <NAME>, <NAME> # Created: 2022-05-04 # Email: <EMAIL> # # ------------------------------------------------------------------------------ # # Copyright (c) 2022 OGC Training Data Markup Language for AI Standar...
"""Convert a single Geojson file to the format understood by StreetViewGame. This expects that the input file contains a FeatureCollection. The output format is as follows: * each shape is in its own file * index.json file has names for all shapes and links to their files * "properties" section of each shape has: ...
# This is some old code used to try and extrapolate parameter cost # from some sample measurements. In the end I decided to throw it # all out and just do the following: # # 1. measure the maximum memory that can be used # 2. scale t to get the desired duration # # This change is motivated by # # 1. the desire to...
# Copyright # 2019 Department of Dermatology, School of Medicine, Tohoku University # # 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/LICENS...
import os import hashlib import json import time import rsa from dotenv import load_dotenv, find_dotenv from blockchainpg.blockchain_utils import convertToPrivKey, convertToPubKey load_dotenv(find_dotenv()) """ The transaction class holds all aspects of a transaction object, which includes the addresses, timestamp, ...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in co...
""" Python wrapper and related helpers for directed_network using proxy widgets. """ from jp_doodle import doodle_files, dual_canvas, nd_frame, data_tables, svg_translation from jp_doodle.dual_canvas import clean_dict import jp_proxy_widget import csv from IPython.display import display, HTML import numpy as np direc...
from __future__ import print_function import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm from matplotlib import colors from collections import defaultdict df = pd.read_csv('stats.txt', index_col=0, dtype={'game': 'str'}) # start and end points for each set (0 large numbe...
import cv2 import numpy as np import gym from gym import spaces class NoopResetEnv(gym.Wrapper): def __init__(self, env, noop_max=30): """Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0. """ gym.Wrapper.__init__(self, env) s...
#!/usr/bin/env python3 ''' MIT No Attribution Copyright Amazon Web Services 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, co...
import os.path as osp import torch from cogdl.data import Graph, Dataset from cogdl.utils import download_url def read_triplet_data(folder): filenames = ["train2id.txt", "valid2id.txt", "test2id.txt"] count = 0 edge_index = [] edge_attr = [] count_list = [] triples = [] num_entities = 0 ...
""" 396. Rotate Function Medium You are given an integer array nums of length n. Assume arrk to be an array obtained by rotating nums by k positions clock-wise. We define the rotation function F on nums as follow: F(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1]. Return the maximum value of F(0), F(1)...
import os import logging import hashlib import binascii from fourcdl.utils import write_to_file logger = logging.getLogger(__name__) def md5(fname, hex=True): # construct a hash object by calling the appropriate constructor function hash_md5 = hashlib.md5() # open file in read-only byte-mode with op...
import numpy as np import pandas as pd import pytest from etna.datasets.tsdataset import TSDataset from etna.models import NaiveModel from etna.transforms.decomposition import STLTransform from etna.transforms.decomposition.stl import _OneSegmentSTLTransform def add_trend(series: pd.Series, coef: float = 1) -> pd.Se...
import asyncio import inspect import warnings # 3p from asyncpg.protocol import Protocol as orig_Protocol import asyncpg.protocol import asyncpg.connect_utils import asyncpg.pool import wrapt # project from ddtrace.ext import net, db from ddtrace.pin import Pin from .connection import AIOTracedProtocol from ...utils....
# Copyright 2017 Databricks, 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 writin...
# -*- coding: utf-8 -*- from __future__ import print_function import os import smtplib import zipfile import shutil import pickle import copy import json from email.mime.text import MIMEText from logging.handlers import RotatingFileHandler from datetime import datetime from dotenv import load_dotenv from celery.except...
import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import make_interp_spline from scipy import interpolate imput_path = '30/submission/' gt_path = 'groundtruth/' def compute_ap(rec,prec): # correct AP calculation # first append sentinel values at the end mrec = np.concatenate(([0.],...
from bluesky_live.run_builder import RunBuilder from bluesky_live.event import CallbackException import pytest from ...models.plot_specs import ( AxesAlreadySet, Figure, FigureList, Axes, Line, Image, ) # Generate example data. with RunBuilder() as builder: builder.add_stream("primary", d...
import numpy as np import cvxopt import cvxopt.solvers def lp_general_graph(unaries, edges, edge_weights): if unaries.shape[1] != edge_weights.shape[1]: raise ValueError("incompatible shapes of unaries" " and edge_weights.") if edge_weights.shape[1] != edge_weights.shape[2]: ...
""" This script compares HVAE, VAE, and NF models for a Gaussian model with Gaussian prior """ import numpy as np import matplotlib.pyplot as plt import tensorflow as tf import scipy.stats import time import pickle import os from conf import params from experiment_classes import HVAE, NF, VB seed = 12345 np.random.s...
#!/usr/bin/python # vim: set fileencoding=utf-8 from collections import namedtuple from datetime import datetime import yaml import pykintone import pykintone.model_result as mr KintoneEnv = namedtuple('KintoneEnv', ['kintone', 'meibo_app_id', 'book_app_id', 'log_app_id']) API_USER = 'Administrator' SYSTEM_US...
import fjm from preprocessor import resolve_macros from tempfile import mkstemp import os from time import time from defs import * from fj_parser import parse_macro_tree import pickle def lsb_first_bin_array(int_value, bit_size): return [int(c) for c in bin(int_value & ((1 << bit_size) - 1))[2:].zfill(bit_size)[-...