text
stringlengths
3.07k
12.6k
import Blocks import Item import biomes import IDGenerator import config import random import globals as G import EventHandler import time import WorldSaver import mathhelper import pyfastnoisesimd class DimensionHandler: def __init__(self): self.dimensions = {} self.dim = None def load(self,...
#! /usr/bin/env python3 """ <NAME>'s CDB implemented in Python see http://cr.yp.to/cdb.html """ from __future__ import print_function import os import struct import mmap def uint32_unpack(buf): return struct.unpack('<L', buf)[0] def uint32_pack(n): return struct.pack('<L', n) CDB_HASHSTART = 5381 def...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from urllib2 import urlopen, URLError import httplib from lck.django.common import nested_commit_on_success from lck.djang...
# -*- coding: utf-8 -*- """ Created on 2019/8/27 @author: LoyeLee """ import os import time import requests from lxml import etree from utils import logfunc from config import dburls, filepath logger = logfunc.LogFunc() group_dict = dict() def get_cookies(cookie_no): # 获取豆瓣登录Cookie信息 cookies = {} wit...
# Licensed to Modin Development Team under one or more contributor license agreements. # See the NOTICE file distributed with this work for additional information regarding # copyright ownership. The Modin Development Team licenses this file to you under the # Apache License, Version 2.0 (the "License"); you may not u...
import time from flash.base import cache, BatchCacheQuery from .utils import TestCase from .models import ModelA, ModelB, ModelC, ModelD from .caches import BCacheOnNum, AListCacheOnD class CacheTestCase(TestCase): def tearDown(self): ModelA.objects.raw("DELETE FROM tests_modela") ModelB.objects...
import logging import os from configparser import ConfigParser from functools import lru_cache from typing import Dict, List, Union from fast_world_creator.datapacks import external_datapack as ed, \ random_loot as rl from fast_world_creator.utils import minecraft_utils as mu MC_FOLDER = f"{os.getenv('APPDATA')}/...
""" This script is for training word2vec on a corpus of text collected by the elsapy/pyblio modules """ """ @DACB: All functions before SingleLoader class are helper functions for SingleLoader(). I have successfully used SingleLoader() as a generator for creating word embeddings with word2vec. That successful r...
from datetime import datetime from mock import Mock from github import GithubException from buildtrigger.githubhandler import GithubBuildTrigger from util.morecollections import AttrDict def get_github_trigger(dockerfile_path=""): trigger_obj = AttrDict(dict(auth_token="foobar", id="sometrigger")) trigger =...
# Copyright The OpenTelemetry 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 ...
# Copyright 2016-2021 Swiss National Supercomputing Centre (CSCS/ETH Zurich) # ReFrame Project Developers. See the top-level LICENSE file for details. # # SPDX-License-Identifier: BSD-3-Clause import collections import os import reframe.core.fields as fields import reframe.utility as util import reframe.utility.jsone...
#:/usr/bin/env python2.7 ''' Texture compression tool ======================== This tool is designed to compress images into: - PVRTC (PowerVR Texture Compression), mostly iOS devices - ETC1 (Ericson compression), working on all GLES2/Android devices Usage ----- In order to compress a texture:: texturecompress...
from sympy.matrices.common import _MinimalMatrix, _CastableMatrix from sympy.matrices.matrices import MatrixSubspaces from sympy.matrices import Matrix from sympy.core.numbers import Rational from sympy.core.symbol import symbols from sympy.solvers import solve class SubspaceOnlyMatrix(_MinimalMatrix, _CastableMatrix,...
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P. # # 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 re...
import numpy as np from sklearn.svm import SVC, SVR, LinearSVR from sklearn.linear_model import LogisticRegression from .metrics import MAX_GAIN, avg_gain_ratio, avg_loss_ratio def ultimatum_score(y_true, y_pred): #return 1 - avg_loss_ratio(y_true, y_pred) return avg_gain_ratio(y_true, y_pred) class Acc...
import sys from abc import ABC, abstractmethod from typing import Tuple,List class CalInterface(ABC): # Abstract base class to define interface for DIO calibration # Use calibrate() to perform the calibration @abstractmethod def output_dio_calibration_data(self, dio_mode: str, port: int=0) -> Tuple[i...
from flask import Flask, request, redirect, session, url_for, render_template, jsonify import sys import paramiko import subprocess from apscheduler.schedulers.background import BackgroundScheduler import atexit import json import requests import os import signal import urllib3 urllib3.disable_warnings(urllib3.exceptio...
#!/usr/bin/python # Copyright (c) 2020, 2022 Oracle and/or its affiliates. # This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Apache License v2.0 # See LICENSE.TXT for d...
""" Simple attack showing the Burgers 1d model attack for different epsolons vs accuracy""" # run with python3.8 single_attack_foolbox.py from numpy import exp import torch import torchvision.models as models from foolbox import PyTorchModel, accuracy, samples from foolbox.distances import linf import foolbox.attacks...
import os import time import scipy import random import pickle import torch import json import numpy as np import pandas as pd from urllib import request pd.set_option('display.width', 1000) def adj_to_tensor(adj): if type(adj) != scipy.sparse.coo.coo_matrix: adj = adj.tocoo() sparse_row = torch.Long...
import logging import os from .exceptions import BackupDirError, BackupDirNotFoundError, LockedError from .subprocess import create_subvolume, delete_subvolume, is_btrfs, make_snapshot logger = logging.getLogger(__name__) _sync_dir = '.sync' _sync_lockfile = '.sync_lock' class BaseVolume(object): """some basic...
import numpy as np import warnings from scipy import interpolate from wotan import flatten import utils def lin_interp(flux, flat_window=None, pos_offs=1e5, t_step=utils.min2day(2), inplace=True): # assumes uniformly spaced measurements if flux.ndim == 1: nan = np.isnan(flux) if...
import docx from os import path import os import re CURDIR = path.dirname(path.abspath(__file__)) DOC_NAME = path.join(CURDIR, "diplom.docx") OLDREF_NAME = path.join(CURDIR, "oldref.txt") MATCHREF_NAME = path.join(CURDIR, "newref.txt") REFLIST_TEXT = "Список литературы" regex_ref_in_text = re.compile(r"\[[...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed May 13 22:52:33 2020 @author: ahmetcakmak """ import numpy as np import re import itertools from collections import Counter import gensim from gensim.utils import simple_preprocess from gensim.parsing.preprocessing import STOPWORDS from nltk.stem imp...
# Standard library from collections import OrderedDict import logging import os import pwd import re from distutils.version import LooseVersion # Third-party import pysvn LOG = logging.getLogger(__name__) class SvynWorker(object): """Mediates pysvn calls""" DEF_BRANCHES_DIR = 'branches' DEF_TAG_DIR = ...
"""Collect and parse kobo forms.""" import logging from datetime import datetime, timedelta, timezone from os import getenv from typing import Dict, List from dateutil.parser import parse as dtparser from flask import request import requests from werkzeug.exceptions import BadRequest, InternalServerError, NotFound ...
import smart_imports smart_imports.all() _INTERNAL_LOGICS = {} class PostponedLogic(object): TYPE = None def __init__(self): pass def process(self, main_task): raise NotImplementedError def serialize(self): return {} @classmethod def deserialize(cls, data): return cls(...
from typing import List import re from nltk.tokenize.punkt import PunktSentenceTokenizer from trimtr.util import get_abbrev_types_from_file, get_abs_path class SentenceTokenizer: _unique_instance = None def __new__(cls): raise NotImplementedError('Cannot initialize via Constructor') @classmethod...
import os import csv import json import yaml import logging, logging.handlers from six.moves import cPickle as pickle import h5py import coloredlogs import numpy as np from collections import defaultdict """ Get Logger with given name Args: name: logger name. fmt: log format. (default: %(asctime)s %(name)s: ...
from keras.layers import Input, Reshape, Dropout, Dense, Flatten, BatchNormalization, Activation, ZeroPadding2D from keras.layers.advanced_activations import LeakyReLU from keras.layers.convolutional import UpSampling2D, Conv2D from keras.models import Sequential, Model, load_model #from keras.optimizers import Ada...
# this file deals with the setup and interaction with the receiver thread # interaction is done through a pipeline and a stack # the stack is used to store the bytes of messages sent to this robot # the pipline is used to give other instructions to the thread, things like settings updates # both the stack and pipeline ...
import html import time import asyncio import humanize import datetime from statistics import mean from pyrogram import Client, filters, ContinuePropagation from pyrogram.types import Dialog, Chat, Message from pyrogram.raw import functions from shadowhawk import ObjectProxy as SessionProxy from shadowhawk import ( co...
import contextlib import copy import logging from logging import ( StreamHandler ) from logging.handlers import ( RotatingFileHandler, ) import os from pathlib import Path import pickle import socket import sys from types import TracebackType from typing import ( Dict, Iterator, Type, TypeVar, )...
import multiprocessing as mp import multiprocessing.pool import threading from collections import defaultdict from itertools import chain from queue import SimpleQueue from selectors import DefaultSelector, EVENT_READ from statistics import mean from time import time from typing import Dict, NamedTuple, Optional impor...
# coding: utf-8 from __future__ import absolute_import import re from sentry.stacktraces.platform import get_behavior_family_for_platform _windecl_hash = re.compile(r'^@?(.*?)@[0-9]+$') _rust_hash = re.compile(r'::h[a-z0-9]{16}$') _cpp_trailer_re = re.compile(r'(\bconst\b|&)$') _lambda_re = re.compile(r'''(?x) ...
# -*- coding: utf-8 -*- # # Copyright 2012-2015 Spotify AB # # 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...
"""This module defines the important coordinate systems to be used in reconstruction with the CTA pipeline and the transformations between this different systems. Frames and transformations are defined using the astropy.coordinates framework. This module defines transformations for ground based cartesian and planar sys...
# File: ode2_adaptive.py # File Created: Thursday, 5th September 2019 3:37:03 pm # Author: <NAME> (<EMAIL>) """ 2nd order ODE Adaptive acquisition of data. """ import operator import os import random import sys from time import time from typing import Callable import deap.gp import matplotlib.pyplot as plt import nu...
from PIL import Image, ImageDraw import numpy as np import csv import math import random random.seed() def ReadKeys(image): """Input an image and its associated SIFT keypoints. The argument image is the image file name (without an extension). The image is read from the PGM format file image.p...
import argparse import torch from torch import nn from torchvision import models def get_train_input_args(): """ Command Line Arguments: 1. Data Folder as data_dir 2. Save Folder for checkpoints as --save_dir with default value 'checkpoints' 3. CNN Model Architecture as --arch with default va...
#!/usr/bin/env python import csv import datetime import glob import os import random import socket import subprocess import sys import time # ############################## # Constants # # OUTPUT_MODE # Sets the reporting method for recording temperatures. # Values: # 'carbon': Write temperatures directly...
# -*- coding: utf-8 -*- """Unittest for training utilities.""" import unittest from typing import Type import numpy as np import torch from pykeen.losses import MarginRankingLoss from pykeen.models import Model, TransE from pykeen.training.lcwa import LCWATrainingLoop from pykeen.training.utils import apply_label_s...
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import print_function from __future__ import division from utils.external.faster_rcnn_tensorflow.configs import cfgs import tensorflow as tf import numpy as np def max_length_limitation(length, length_limitation): return tf.cond(tf...
import sys,os from pathlib import Path import cv2 import dlib import numpy as np from contextlib import contextmanager from keras.utils.data_utils import get_file from keras.applications import ResNet50, InceptionResNetV2 from keras.layers import Dense from keras.models import Model #同级目录加一点 pretrained_model = "http...
# # This source file is part of the EdgeDB open source project. # # Copyright 2015-present MagicStack Inc. and the EdgeDB 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...
import os import sys import re import warnings from typing import List, Tuple, Dict FileList = List[str] FlatList = Dict[str, Tuple[str]] class RunError(Exception): def __init__(self, message="RunError: run as module is not allowed."): self.message = message class ArgError(Exception): def __init__...
import os import shutil from pathlib import Path from fixtures import fixture from virtool_workflow.analysis.utils import ReadPaths def handle_base_quality_nan(split_line: list) -> list: """ Parse a per-base quality line from FastQC containing NaN values. :param split_line: the quality line split into a...
"""Some helpers for the course.""" import gzip import pandas as pd import os import requests import shutil from tempfile import TemporaryFile from hashlib import sha256 from rich.console import Console import seaborn as sns num_genomes = 950 assemblies = pd.read_csv( "https://github.com/Gibbons-Lab/2021_microbiom...
""" based on https://flask.palletsprojects.com/en/2.0.x/patterns/fileuploads/ and https://python-visualization.github.io/folium/flask.html """ import os import string import random from flask import Flask, flash, request, redirect, url_for import folium import logging.config from config import HQ_ADDRESS_TXT, N_ENTRI...
import enum import os from base64 import urlsafe_b64encode, urlsafe_b64decode from datetime import datetime import pymongo from bson import ObjectId from slivka import JobStatus from slivka.utils import deprecated class MongoDocument(dict): __collection__ = None def _get_id(self) -> ObjectId: return self.g...
#!/usr/bin/env python3 import argparse import os, sys import libficconvert as lfc # ## command line argument management: def outputpath_arg(string): """output path. format: (`DIR or FILE`, directory, file (if provided), overwrite warning(bool) )""" if os.path.isdir(string): return ["DIR" , os.path.absp...
''' The idea of this module is to avoid imports of external HPI modules and code evaluation via ast module etc. This potentially allows it to be: - robust: can discover modules that can't be imported, generally makes it foolproof - faster: importing is slow and with tens of modules can be noteiceable - secure: can be...
from __future__ import print_function, division, absolute_import import struct import sys import os import re import warnings import llvmlite.binding as ll IS_WIN32 = sys.platform.startswith('win32') MACHINE_BITS = tuple.__itemsize__ * 8 IS_32BITS = MACHINE_BITS == 32 # Python version in (major, minor) tuple PYVERS...
"""General-purpose test script for image-to-image translation. Once you have trained your model with train.py, you can use this script to test the model. It will load a saved model from --checkpoints_dir and save the results to --results_dir. It first creates model and dataset given the option. It will hard-code some...
import torch import pytest from torch.testing import assert_allclose import numpy as np import soundfile as sf import asteroid from asteroid import models from asteroid.models.base_models import BaseModel from asteroid.models import ConvTasNet, DPRNNTasNet, DPTNet, LSTMTasNet from asteroid.models import SuDORMRFNet, Su...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ This file contains the different learning rate schedulers of AutoNet. """ from autoPyTorch.utils.config_space_hyperparameter import add_hyperparameter, get_hyperparameter import torch import torch.optim.lr_scheduler as lr_scheduler import ConfigSpace as CS import Co...
#!/usr/bin/python # -*- coding: utf-8 -*- # __author__="<NAME>" # # 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...
from datetime import datetime import os import numpy as np import pandas as pd import pandas.util.testing as tm import pytest import pandas_datareader.data as web @pytest.yield_fixture def aapl(): aapl = web.Options("aapl", "yahoo") yield aapl aapl.close() @pytest.fixture def month(): # AAPL has ...
# 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...
import math import m5 from m5.objects import * from m5.defines import buildEnv from m5.util import addToPath, fatal # from common import FileSystemConfig addToPath('../configs/') from NVMTypes import * from socket import CPUSocket, DirectorySocket class NoCSystem(RubySystem): def __init__(self): if bui...
import os import sys from osgeo import gdal import numpy as np import geopandas as gpd import pandas as pd from config.definitions import (ROOT_DIR, ancillary_path, pop_path, gdal_rasterize_path, year, city) from mainFunctions.format_conversions import shptoraster def non_match_elements...
from .serializers import ( ParkingListSerializer, ParkingConfigSerializer, ParkingRecordSerializer, ParkingHistorySerializer) from api import util, auth import coreapi import coreschema from datetime import timedelta from rest_framework.response import Response from rest_framework.schemas import AutoSchema impo...
# Copyright 2018-2021 Streamlit 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 wr...
# -- encoding:utf-8 -- import os import itertools import jieba import numpy as np import tensorflow as tf from tensorflow.contrib.learn import preprocessing from gensim import utils from gensim.models import word2vec def default_split_fn(documents): return split_with_char(documents) def split_w...
#!/usr/bin/env python import sys sys.path.append('..') from utils.environment import * from worker import * from network import * import threading from time import sleep import os from graph import * flags = tf.app.flags FLAGS = flags.FLAGS flags.DEFINE_boolean('is_approaching_policy', False, 'If learning approaching...
from nltk.stem import WordNetLemmatizer import time import sys import pickle import numpy as np import collections ################################################ # globals end_token = '#END#' start_token = '#START#' unk_token = '#UNK#' miss_token = '#MISS#' tokens = [end_token, start_token, unk_token] #max sen...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for the view classes.""" import sys import unittest from plaso.cli import views from tests import test_lib as shared_test_lib from tests.cli import test_lib class TestBaseTableView(views.BaseTableView): """Class that implements a table view for testing.""" ...
# -*- coding: utf-8 -*- # python-holidays # --------------- # A fast, efficient Python library for generating country, province and state # specific sets of holidays on the fly. It aims to make determining whether a # specific date is a holiday as fast and flexible as possible. # # Author: ryanss <<EMAIL>> (c) ...
# Copyright (c) <NAME> <<EMAIL>> # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the BSD 3-clauses license. # Original at https://scikit-learn.org/stable/auto_examples/linear_model/plot_sparse_logistic_regression_mnist.html # import functools import pickle import time from pat...
# python ./exps/vis/test.py import os, sys, random from pathlib import Path from copy import deepcopy import torch import numpy as np from collections import OrderedDict lib_dir = (Path(__file__).parent / ".." / ".." / "lib").resolve() if str(lib_dir) not in sys.path: sys.path.insert(0, str(lib_dir)) from nas_201...
""" ******************************************************************************* * Ledger Blue * (c) 2016 Ledger * * 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....
#!/usr/bin/env python3 # # Copyright (c) 2014-present, Facebook, Inc. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals fro...
import os import tensorflow as tf import tensorflow_datasets as tfds import matplotlib.pyplot as plt # version infos print("TensorFlow version: {}".format(tf.__version__)) print("TensorFlow Datasets version: ",tfds.__version__) # data preview ds_preview, info = tfds.load('penguins/simple', split='train', with_info=Tr...
# -*- coding: utf-8 -*- import cv2 import time import sys import numpy as np import os DEVICE_ID = 0 DEFAULT_SIZE = (320, 240) FLIP = True class Rect: def __init__(self, x, y, w, h): self.x = x self.y = y self.w = w self.h = h def modify(self): if self.w < 0: self.w *= -1 sel...
from astropy import units as u from astropy.coordinates import ( HCRS, ITRS as _ITRS, BaseRADecFrame, FunctionTransform, TimeAttribute, frame_transform_graph, ) from astropy.coordinates.builtin_frames.utils import DEFAULT_OBSTIME from astropy.coordinates.matrix_utilities import rotation_matrix ...
import pandas as pd from scipy import stats import numpy as np import re from mne.utils import warn import nilearn def glm_to_tidy(info, statistic, design_matrix, wide=True, order=None): """ Export GLM regression or contrast results in tidy format. Creates a long pandas data frame from regression results...
#!/usr/bin/python # # Copyright 2018-2021 Polyaxon, 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 ...
""" Copied from Piecewise SymPy. The only modification is in `piecewise_eval` where ``` for e, c in _args: if not c.is_Atom and not isinstance(c, Relational): free = c.free_symbols ``` is changed to ``` for e, c in _args: if not c.is_Atom and not isinstance(c, Relational): ...
""" (c) <NAME> function to create scalebar """ import string import matplotlib as mpl import numpy as np import seaborn as sns def scalebar( ax, xsize=None, ysize=None, xunits=None, yunits=None, xleft=-0.01, ybottom=-0.01, bottom=False, right=True, left=False, top=True, ylim=None, xlim=None...
from flask import current_app, request, url_for from .const import PERMISSION_PREFIX def app_template_filter(filter_name=""): def wrap(f): if not hasattr(f, "_filter"): f._filter = filter_name return f return wrap class TemplateFilters(object): security_manager = None ...
import numpy X1 = 'x1' X2 = 'x2' Y1 = 'y1' Y2 = 'y2' BOX_CONSTANTS = [X1, Y1, X2, Y2] class BOX: def __init__(self): pass X1 = 0 Y1 = 1 X2 = 2 Y2 = 3 X1_LEFT = 0 Y1_LEFT = 1 X2_LEFT = 2 Y2_LEFT = 3 X1_RIGHT = 4 Y1_RIGHT = 5 X2_RIGHT = 6 Y2_RIGHT = 7 def re...
import collections import os import pandas as pd import pandas.util.testing as pdt import pytest @pytest.fixture def exon2_bed(negative_control_folder): return os.path.join(negative_control_folder, 'outrigger_output', 'index', 'se', 'exon2.bed') @pytest.fixture def do_not_have_mysql(): ...
import pathlib from typing import Dict, List from cerulean import LocalFileSystem from cerulean import Path def test_create(local_filesystem: LocalFileSystem) -> None: new_path = Path(local_filesystem, pathlib.Path('/')) assert str(new_path) == '/' def test_joinpath(paths: Dict[str, Path]) -> None: new...
# Copyright (c) 2019-2021, 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 agre...
import datetime import logging import os import pickle from typing import Dict, NoReturn import librosa import numpy as np import yaml def create_logging(log_dir: str, filemode: str) -> logging: r"""Create logging to write out log files. Args: logs_dir, str, directory to write out logs filem...
import os import numpy as np import tensorflow as tf import config def _train_preprocess(filename, img, label): # Image processing for training the network. Note the many random # distortions applied to the image. # Randomly crop a [height, width] section of the image. reshaped_image = tf.image.ran...
# time: 2021/5/14 22:28 # File: crf.py # Author: zhangshubo # Mail: <EMAIL> import torch from torch.nn.parameter import Parameter from torch.nn import init class CRFLoss(torch.nn.Module): def __init__(self): super(CRFLoss, self).__init__() def forward(self, crf, y_true, y_pred, mask): return ...
import argparse import datetime import json import logging import os import queue import subprocess import threading import time import bjoern import falcon from falcon_cors import CORS import sigmf from gamutrf.__init__ import __version__ from gamutrf.sigwindows import parse_freq_excluded, freq_excluded q = queue....
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import pytest import sys import requests import src.addGrafanaDataSources as agds from unittest import mock sys.path.append("src") testInfluxDBParams = { 'InfluxDBContainerName': 'greengrass_InfluxDB', ...
import numpy as np import pandas as pd import requests import zipfile import os import pickle from shutil import rmtree from itertools import cycle import torch import torch.utils.data as data_utils def download_ratings_1_10_m(): for data_set_size in (1, 10): url = f'http://files.grouplens.org/datasets/mo...
# pylint: disable=redefined-outer-name # pylint: disable=unused-argument # pylint: disable=unused-variable import asyncio import zipfile from pathlib import Path from typing import AsyncIterable, cast from unittest import mock import fsspec import pytest from faker import Faker from pydantic import AnyUrl, parse_obj_...
#%% import sys import os import os.path as osp from PIL import Image import cv2 import numpy as np import yaml from colorama import Back, Style # assign color options on your text(ref) https://stackoverflow.com/questions/287871/how-to-print-colored-text-to-the-terminal import torch import torchvision.transforms...
# coding: utf-8 """ description: Numpy utility functions and classes author: <NAME> """ __all__ = [ 'create_upper_matrix', 'symmetrize', 'create_symmetric_matrix', 'pairwise_difference', 'is_pos_def', 'rowwise_dissimilarity', 'rowwise_cosine_similarity', 'filter_rows_with_uniqu...
"""The definitions of fud stages.""" import subprocess from enum import Enum from tempfile import NamedTemporaryFile, TemporaryFile from pathlib import Path import sys import logging as log from ..utils import is_debug class SourceType(Enum): """ Enum capturing the kind of source this is. Path: A string...
from abc import ABC from Crypto.Cipher import AES, DES from Crypto.Cipher import DES3 from Crypto.Random import get_random_bytes from Crypto.Util.Padding import pad, unpad class EncryptionMethod(ABC): """ Available encryption methods """ AES = "AES" DES3 = "DES3" DES = "DES" ...
# -*- coding: utf-8 -*- from datetime import datetime, timedelta from django.test import TestCase from django.utils import timezone from django_trips.models import (CancellationPolicy, Facility, Host, Location, Trip, TripSchedule) from django_trips.tests.factories import (CategoryFacto...
#!/usr/bin/env python3 import argparse import collections from datetime import datetime import queue import threading import time from . import execute def _get_locked(lock, data, key): ''' Access data[key] while holding lock ''' with lock: # lock while obtaining key-specific data return data[key] ...
"""Code generation utilities""" from .utils import SchemaInfo, is_valid_identifier, indent_docstring, indent_arglist class CodeSnippet(object): """Object whose repr() is a string of code""" def __init__(self, code): self.code = code def __repr__(self): return self.code SCHEMA_CLASS_TEMP...
from __future__ import print_function import sys import os import timeit import math import argparse import fnmatch import json parser = argparse.ArgumentParser(description="Python protobuf benchmark") parser.add_argument("data_files", metavar="dataFile", nargs="+", help="testing data files.") pars...
#!/usr/bin/env python """ Convert matrix table to a sites-only VCF. Essentially a verbatim copy of: hail-ukbb-200k-callset:mt_to_vcf.py """ import logging import click import hail as hl from gnomad.utils.vcf import adjust_vcf_incompatible_types from gnomad.utils.sparse_mt import default_compute_info from joint_callin...