text stringlengths 3.07k 12.6k |
|---|
'''
Only one leaderboard, so should be static class, but Python code module
is not up to the job, so full class used instead.
'''
import os, pygame, csv
import shared, player
class ScoreData():
''' internal class for Leaderboard use only'''
def __init__(self, line:list):
''' line is a list or tuple '''
... |
from .exception import BreatheError
from sphinx.application import Sphinx
import os
import fnmatch
from typing import Dict
class ProjectError(BreatheError):
pass
class NoDefaultProjectError(ProjectError):
pass
class AutoProjectInfo:
"""Created as a temporary step in the automatic xml generation pr... |
#!/usr/bin/env python3
"""
# $Id: cleanup-blastdb-volumes.py 590894 2019-08-07 14:59:53Z camacho $
# ===========================================================================
#
# PUBLIC DOMAIN NOTICE
# National Center for Biotechnology Information
#
# This software/database... |
from PyQt5 import QtCore
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import QWidget, QLabel, QGridLayout, QFrame, QSizePolicy
from twisted.internet.defer import inlineCallbacks
from EGGS_labrad.lib.clients.Widgets import TextChangingButton
from EGGS_labrad.lib.servers.ARTIQ.device_db import device_db
class T... |
# -*- coding: utf-8 -*-
import re
import pytest
from mimesis import Generic
from .test_providers import patterns
class TestGeneric(object):
def test_str(self, generic):
assert re.match(patterns.STR_REGEX, str(generic))
def test_base_person(self, generic):
result = generic.person.username... |
# Code to extract 2D images from .hdf5 files
### June 9, 2020
##### <NAME> (<EMAIL>)
import numpy as np
import h5py
import os
import sys
import glob
import argparse
import time
from scipy.ndimage import gaussian_filter ### For gaussian filtering
## modules for parallelization of python for loop
from multiprocessi... |
"""Config flow for Cast."""
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.helpers import config_validation as cv
from .const import CONF_IGNORE_CEC, CONF_KNOWN_HOSTS, CONF_UUID, DOMAIN
IGNORE_CEC_SCHEMA = vol.Schema(vol.All(cv.ensure_list, [cv.string]))
KNOWN_HOSTS_SCHEMA = vol... |
# -*- coding: utf-8 -*-
"""
Copyright (C) 2019 <NAME> (@dagwieers) <<EMAIL>>
This file implements the Kodi xbmc module, either using stubs or alternative functionality
SPDX-License-Identifier: GPL-3.0-only
See LICENSES/GPL-3.0-only.md for more information.
"""
# pylint: disable=unused-argument
from __... |
"""Support to the Logi Circle cameras."""
import asyncio
from datetime import timedelta
import logging
import voluptuous as vol
from homeassistant.components.camera import (
ATTR_ENTITY_ID, ATTR_FILENAME, CAMERA_SERVICE_SCHEMA, DOMAIN,
PLATFORM_SCHEMA, SUPPORT_ON_OFF, Camera)
from homeassistant.const import (... |
#!/usr/bin/python3
from __future__ import print_function
import libvirt
import logging
import time
import xml.etree.ElementTree as ET
import sys
import socket
# Needed for compatibility as there is no TimeoutError in python2.
if sys.version_info[0] < 3:
TimeoutException = socket.timeout
else:
TimeoutException... |
import argparse
import py_compile
import re
import sys
import shutil
import stat
import os
import tempfile
from pathlib import Path
from zipfile import ZipFile, ZIP_DEFLATED
import subprocess
TKTCL_RE = re.compile(r'^(_?tk|tcl).+\.(pyd|dll)', re.IGNORECASE)
DEBUG_RE = re.compile(r'_d\.(pyd|dll|exe)$', re.IGNORECASE)
... |
import os
import json
import difflib
import hashlib
import tempfile
import subprocess
import shutil
from contextlib import contextmanager
from pygments import highlight
from pygments.lexers import CssLexer, DiffLexer
from pygments.formatters import HtmlFormatter
from jsonview.decorators import json_view
from django i... |
import matplotlib.pyplot as plt
#import matplotlib.pyplot as plt
from vib_empirical_analysis import minmax, periods, amplitudes
import sys
sys.path.insert(0, "../../../src/odespy/")
import odespy
import numpy as np
def f(u, t, w=1):
# v, u numbering for EulerCromer to work well
v, u = u # u is array of length... |
##
# Copyright (c) 2005-2017 Apple Inc. 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 l... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: input_source_base.py
from abc import ABCMeta, abstractmethod
import copy
import six
from six.moves import zip
from contextlib import contextmanager
import tensorflow as tf
from ..utils.argtools import memoized, call_only_once
from ..callbacks.base import CallbackF... |
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import KFold
from sklearn.metrics import accuracy_sc... |
"""Posix-specific implementation of process utilities.
This file is only meant to be imported by process.py, not by end-users.
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2010-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License... |
import inspect
from traychain import op, ref
from traychain.state import State
from traychain.util import form_of, requires, to_json, uri, Context, URI
from traychain.value import Nil, Value
from . import _get_rtype, is_none, resolve_class
EMPTY = inspect.Parameter.empty
class Method(object):
__uri__ = uri(op... |
import time
import os
import string
import queue
import encoder
from tqdm import tqdm
import sys
import json
import gzip
import struct
from tensorflow.core.example import example_pb2
import pyrouge
import logging
import codecs
import csv
# bpe vocab
field_empty = 28920
eos = 50256
def clean_space(sent_in):
'''
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 18-11-20 上午11:53
# @Author : Vitan
# @File : Qunar.py
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ... |
from cv2 import cv2
from copy import deepcopy
from numpy import array, zeros, iinfo, finfo, uint8, size, r_, append
import json
class Node(object):
def __init__(self, name=None, value=None, flag=False):
super().__init__()
self.flag_ = flag
self.name_ = name
self.value_ = v... |
#!/usr/bin/python
import sys
import os
import time
import re
def license(filename):
result = """/**
* @file """ + filename + """
* @author <NAME> <YOUR EMAIL ADDRESS>
*
* @version """ + time.strftime("%Y-%m-%d") + """
* Created on """ + time.strftime("%Y-%m-%d") + """.
*/
"""
return result
def checkName(modu... |
# -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
# coding=utf-8
# Copyright 2021 The Google Research 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 applicab... |
import sys
from sentry_sdk.hub import Hub, _should_send_default_pii
from sentry_sdk._compat import reraise
from sentry_sdk.utils import (
AnnotatedValue,
capture_internal_exceptions,
event_from_exception,
logger,
)
from sentry_sdk.integrations import Integration
from sentry_sdk.integrations._wsgi_commo... |
import openmm.unit as unit
from .stage_integrator import BoostType
from .stage_integrator import GamdStageIntegrator
from abc import ABC
from abc import abstractmethod
class TrackedValue:
def __init__(self, boost_type, group, tracked_integrator, tracked_simulation):
self.__boost_type = boost_type
s... |
#
# The contents of this file are subject to the Mozilla Publics
# License Version 1.1 (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.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis... |
import os
import logging
import numpy as np
import GPUtil
from source.constants import ROOT_LOGGER_STR
import tensorflow as tf
from tensorflow.python.eager import context
from tensorflow.python.ops import summary_ops_v2
logger = logging.getLogger(ROOT_LOGGER_STR + '.' + __name__)
def gpu_session(num_gpus=None, gpus=... |
# Copyright 2020 The Magenta 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 ... |
#!/usr/bin/env python3
###############################################################################
# #
# RMG - Reaction Mechanism Generator #
# ... |
# Lint as: python3
# Copyright 2018, The TensorFlow Federated 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 ... |
# Copyright (c) 2014 Mirantis, 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... |
import asyncio
import json
import logging
import os
import pkgutil
import zlib
from concurrent.futures import ThreadPoolExecutor
import aiobotocore
import botocore
import kinto_http
import raven
from raven.handlers.logging import SentryHandler
from ruamel import yaml
from kinto_wizard.async_kinto import AsyncKintoClie... |
#------------------------------------------------------------------------------
# Copyright (c) 2013, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-------------------------------------------------... |
from pycket import values
from pycket.arity import Arity
from pycket.base import W_Object
from pycket.cont import call_cont, continuation, BaseCont
from pycket.error import SchemeException
from pycket.hash.persistent... |
from pathlib import Path
import h5py
import pytest
from dxtbx.format import nexus
# Some names for sample NXentries in a dummy NeXus file.
entry_names = "/entry", "/another_entry", "/yet_another_entry"
@pytest.fixture(scope="session")
def nexus_file(tmp_path_factory) -> Path:
"""
Create a dummy NXmx-flavou... |
#!/usr/bin/env python
from distutils.core import setup
import distutils.command.build
import distutils.command.clean
from distutils import log
from distutils.spawn import find_executable
import subprocess
import shutil
import shlex
import os.path
import glob
from urllib import urlopen
import zipfile
try:
import cSt... |
# 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... |
"""Objects representing data returned from the Archiver Appliance."""
import logging
import numpy
import pytz
from . import utils
DIFFERENT_PV_ERROR = 'All concatenated ArchiveData objects must have the same PV name'
TIMESTAMP_WARNING = 'Timestamps not monotonically increasing: {} -> {}'
class ArchiveEvent(object)... |
"""
Created on April, 2018
@author: <NAME>
visualize code for SUNRGBD
"""
import matplotlib.pyplot as plt
import numpy as np
from random import random as rand
from mpl_toolkits.mplot3d import Axes3D
def show_2dboxes(im, bdbs, color_list=[], random_color=True, scale=1.0):
"""
Visualize the bounding boxe... |
# Implementation of classic arcade game Pong
# <NAME> - 6th Nov 2013
# http://www.codeskulptor.org/#user23_alOd8kS55ui1Z17.py
import simplegui
import random
# initialize globals - pos and vel encode vertical info for paddles
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20
PAD_WIDTH = 8
PAD_HEIGHT = 80
HALF_PAD_WIDTH... |
import json, os, logging, sys,time, boto3
from akamai.netstorage import Netstorage, NetstorageError
REGION_NAME = os.environ['REGION']
QUEUE_URL = os.environ['QUEUE_URL']
CPCODE = os.environ['CPCODE']
S3_BUCKET = os.environ['BUCKET']
SECRET = os.environ['NS_SECRET']
logger = logging.getLogger("AKAM:S3-NS-SYNC")
... |
import cv2
from os import listdir,path
import json
import numpy as np
from collections import defaultdict
def labelSort(x):
return x.label
class FurnitureItem:
'''Data structure to hold the different 3D properties of the object'''
def __init__(self, label,box):
self.label = la... |
# 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, overload
from ... import _utilities
fro... |
#! /usr/bin/env python
import time
import torch
from torch.nn import parameter
from torch.optim import SGD
from torch.optim.lr_scheduler import OneCycleLR
from torch.utils.data import DataLoader
from pathlib import Path
from xvision.utils import get_logger, Saver
from xvision.datasets.loader import repeat_loader
from x... |
import copy
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
# Used for Atari
class Conv_Q(nn.Module):
def __init__(self, frames, num_actions):
super(Conv_Q, self).__init__()
self.c1 = nn.Conv2d(frames, 32, kernel_size=8, stride=4)
self.c2 = nn.Conv2d(3... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 24 12:28:37 2020
@author: lilianschuster
some helper functions to minimize the bias, optimise std_quot and tos
compute performance statistics
"""
import scipy
import matplotlib.pyplot as plt
import numpy as np
# imports from local MBsandbox packag... |
# Copyright 2022 Canonical Ltd.
# See LICENSE file for licensing details.
#
import base64
from pathlib import Path
from unittest.mock import patch, MagicMock
import pytest
import yaml
from charm import KubernetesAutoscalerCharm
from ops.model import ActiveStatus, BlockedStatus, ModelError
from ops.testing import Har... |
# tests.test_datasets.test_paths
# Tests for the dataset path utilities
#
# Author: <NAME> <<EMAIL>>
# Created: Thu Jul 26 14:28:14 2018 -0400
#
# ID: test_path.py [7082742] <EMAIL> $
"""
Tests for the dataset path utilities
"""
##########################################################################
## Imports
##... |
# -*- coding: utf-8 -*-
"""Create interior elevations for selected rooms and place them on sheets.
NOTE:
"""
__author__ = "nWn"
__title__ = "Interior\n Elevations"
# Import
from pyrevit import revit, DB
from pyrevit import script
from pyrevit import forms
# Store current document into variable
doc = __revit__.Acti... |
import chainer
from chainer import backend
from chainer import function_node
from chainer.functions.activation import sigmoid
from chainer import utils
from chainer.utils import type_check
class SigmoidCrossEntropy(function_node.FunctionNode):
"""Sigmoid activation followed by a sigmoid cross entropy loss."""
... |
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.views import generic
from django.shortcuts import redirect
from django.urls import *
from .models import *
from .forms import *
from django_filters.views import FilterView
from .filters import HeritageSiteFilter... |
from pyhive import hive
from TCLIService.ttypes import TOperationState
import numpy as np
import cudf
from itertools import repeat
import pandas as pd
def convertHiveTypeToCudfType(hiveType):
if(hiveType == 'int' or hiveType == 'integer'):
return 3 # INT32
elif(hiveType == 'string' or hiveType.starts... |
# imdbfolder_coco.py
# created by <NAME> [<EMAIL>]
# Copyright © The University of Oxford, 2017-2020
# This code is made available under the Apache v2.0 licence, see LICENSE.txt for details
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cud... |
# 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
# d... |
"""
Copyright (c) 2017 Dependable Systems Laboratory, EPFL
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,... |
# -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext, ugettext_lazy
from wagtail.contrib.settings.models import BaseSetting, register_setting
from wagtail.wagtailadmin.edit_handlers import (
FieldPanel, MultiFieldPanel, ObjectList, StreamFieldPanel, TabbedInterface)
f... |
import yaml
from core.checks import CallbackHelper
from core.searchtools import FileSearcher
from core.analytics import LogEventStats, SearchResultIndices
from core import utils
from core.plugins.openstack import (
AGENT_ERROR_KEY_BY_TIME,
OpenstackChecksBase,
OpenstackEventChecksBase,
)
YAML_PRIORITY = 9... |
"""""" """""" """""" """""" """
POSTPROCESSING FUNCTIONS
""" """""" """""" """""" """"""
import math
import numpy as np
from scipy.signal import find_peaks
from utils.keypoints import KEYPOINT_DICT
def find_camera_facing_side(keypoints):
"""Returns whether the cyclist is facing the camera with his left or right ... |
# Copyright 2021 The gRPC 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 wri... |
"""
Module for layers that are typically used as output
(c) 2020 d373c7
"""
import torch
import torch.nn as nn
from math import sqrt
from .common import Layer
from ...features.common import FeatureCategorical
from ...features.tensor import TensorDefinition
from collections import OrderedDict
from typing import List, Tu... |
import pygame, random, math
class WallRectangular:
def __init__(self, surface, color, rect):
self.surface = surface
self.rect = rect
self.color = color
def draw(self):
pygame.draw.rect(self.surface, self.color, self.rect)
def putOut(self, other):
if self.rect.colli... |
import sys
from django.db.models import Q as QNode
__author__ = '<NAME>'
class QFactory(object):
"""
Usage:
>>> Q.username.get_path()
'username'
>>> Q.user.username.get_path()
'user__username'
Typical usage:
>>> Q.user.username == '<NAME>'
<Q: (AND: ('user__username', '<NAME>')... |
# coding=utf-8
# Copyright 2022 The HuggingFace Datasets Authors and DataLab 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
#
# Unless required by applicable law or agreed to in wri... |
# train/test scene graph based image retrieval
import argparse
import os
import torch
from maskrcnn_benchmark.image_retrieval.evaluation import run_evaluation
from maskrcnn_benchmark.image_retrieval.modelv2 import SGEncode
from maskrcnn_benchmark.image_retrieval.dataloader import get_loader
from maskrcnn_benchmark.... |
# Lint as: python3
# Copyright 2019, The TensorFlow Federated 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 ... |
import sys
import io
import itertools
import logging
import pandas as pd
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
import re
from .log_config import logger
def emptyDf(size, region, date):
"""Returns a df full of NA i.e empty df
... |
"""
steep.py
Computes similarity (Pearson or Spearman correlation).
If given 1 gct, steep will compute all pairwise similarities between its columns.
If given 2 gcts, steep will compute pairwise similarities between the columns of
gct1 and the columns of gct2 (samples from gct1 will be in the rows).
Required input is ... |
'''
Test normalizations of the Accept-Encoding header field.
'''
# 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 ... |
import tempfile;
import argparse;
import subprocess;
import calendar;
import time;
import random;
import os;
import pysam;
import gzip;
def main():
#Arguments passed
parser = argparse.ArgumentParser()
parser.add_argument("--vcf", required=True, help="Genotype VCF for sample (gzipped with index).")
parser.add_argu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for fragment.py"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import logging
from rdkit import Chem
from molvs.standardize import Standardizer
from molvs.fragment import FragmentRemover
logging... |
# -*- coding: utf-8 -*-
from django.conf import settings
from django.http import Http404
from django.shortcuts import redirect, render
import basket
import commonware.log
from session_csrf import anonymous_csrf
from tower import ugettext as _
from amo import messages
from mkt.developers.forms import DevNewsletterForm... |
#!/usr/bin/python3
import os
import sys
import errno
import time
import datetime
import argparse
import array
import math
import multiprocessing
import tempfile
import shutil
from time import sleep
class bf(object):
bf_commands = '+-.,><[]'
max_bf_array_size = 30000
code = None
scene = None
@staticmethod
def ... |
import itertools
import random
import numpy as np
from torch.utils.data import Dataset
from megatron import get_tokenizer
from megatron import get_args
from megatron.data.dataset_utils import get_indexed_dataset_
from megatron.data.realm_dataset_utils import get_block_samples_mapping
def get_ict_dataset(use_titles=... |
# SPDX-FileCopyrightText: 2015 <NAME>
#
# SPDX-License-Identifier: Apache-2.0
import calendar
import time
from datetime import datetime
from email.utils import formatdate, parsedate
from pprint import pprint
from mock import Mock
from requests import Session, get
from requests.structures import CaseInsensitiveDict
f... |
from __future__ import annotations
import os
import logging.config
from shutil import rmtree
import numpy as np
from tqdm import tqdm
from multiprocessing import Pool, cpu_count, freeze_support
from gooey import Gooey, GooeyParser
from imageio import get_reader
from plais.parse_config import parse_config
from plais.... |
import os
import sys
import shutil
from pathlib import Path
from filecmp import dircmp
from glob import glob
from os.path import basename, splitext, join, dirname
__dir__ = Path(__file__).absolute().parent
# Remove current dir from sys.path, otherwise setuptools will peek up our
# module instead of system's.
sys.path.... |
"""
.. module:: config
:platform: Unix, Windows
:synopsis: Sets up the entire config list for the other modules
.. moduleauthor:: <NAME> <<EMAIL>>
"""
# requires python 3
import configparser
CONFIG_FILE = "config.ini"
def get_config():
"""
Pulls in all the configuration options from ini files
Retu... |
# -*- coding: utf-8 -*-
from cobradb.dumping.model_dumping import dump_model
from cobradb.loading import load_model, load_genome
from cobradb.base import *
from cobradb.models import *
import pytest
import logging
import cobra.io
from os.path import join, exists
import shutil
# Dumping
@pytest.fixture(scope='sessio... |
import os
from omniidl import idlvisitor, output, idlast
import jnutils
import string
class InterfaceVisitor (idlvisitor.AstVisitor):
def __init__(self):
self.directoryParts = []
self.directory = ''
self.package = ''
self.out = None
def calculateDirectory(self):
self.di... |
# Repository: https://gitlab.com/quantify-os/quantify-core
# Licensed according to the LICENCE file on the master branch
"""Module containing analysis utilities for calibration procedures.
In particular, manipulation of data and calibration points for qubit readout
calibration.
"""
from __future__ import annotations
... |
"""
Implementation of ResNet based on the paper:
https://arxiv.org/pdf/1512.03385.pdf
Reference:
https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
"""
import os
import time
import argparse
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transform... |
from http import HTTPStatus
from cerberus import Validator # type: ignore
from fastapi import status
from fastapi.exceptions import HTTPException
from fastapi.openapi.models import APIKey, APIKeyIn
from fastapi.params import Security
from fastapi.security.api_key import APIKeyHeader, APIKeyQuery
from fastapi.security... |
"""Metrics used across Foreshadow for smart decision making."""
import pandas as pd
from pandas.api.types import is_numeric_dtype, is_string_dtype
from foreshadow.logging import logging
from foreshadow.utils import check_series
class MetricWrapper:
"""Class that wraps around the metric calculation function.
... |
""" This file is experimental and may disappear without warning """
from __future__ import print_function, division, absolute_import
import logging
from math import log
import os
from warnings import warn
import dask.bytes.core
from dask.delayed import delayed
from toolz import merge
from hdfs3 import HDFileSystem
f... |
import flask
from relation_engine_server.utils import (
arango_client,
spec_loader,
auth,
bulk_import,
pull_spec,
config,
parse_json
)
from relation_engine_server.utils.json_validation import run_validator
from relation_engine_server.exceptions import InvalidParameters
api_v1 = flask.Bluepr... |
import numpy as np
import scipy.sparse as sp
import tensorflow as tf
import yaml
from pymongo import MongoClient
def to_sparse_tensor(M, value=False):
"""Convert a scipy sparse matrix to a tf SparseTensor or SparseTensorValue.
Parameters
----------
M : scipy.sparse.sparse
Matrix in Scipy spar... |
# -*- coding: utf-8 -*-
# @Date : 2018/3/29
# @Author : Shu
# @Email : <EMAIL>
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, BooleanField, FloatField, DateTimeField
from wtforms.validators import DataRequired, Length, Optional, ValidationError
from .validators import WalletUnique... |
import os
import pprint
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from bag import BagProject
from bag.io import load_sim_results, save_sim_results, load_sim_file
# Global variables
# schematic generator library/cell name
tb_lib = 'ee240b_mos... |
import os
import cv2
from base_camera import BaseCamera
import datetime # WS
import rpi_status as ws # WS module
from time import time # WS
def sec_to_dhms(sec): # seconds to day, hour, min, sec
dd, r = divmod(sec, 24*3600)
hh, r = divmod(r, 3600)
mm, ss = divmod(r, 60)
retu... |
import numpy as np
import scipy
def build_H(n, d_v, d_c, seed=None):
"""
Builds a regular Parity-Check Matrix H (n, d_v, d_c) following Callager's algorithm.
Parameters:
n: Number of columns (Same as number of coding bits)
d_v: number of ones per column (number of parity-check equations includi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2017 The Procyon 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
#
# Un... |
# from_wkt and to_wkt are taken from geoalchemy
# Otherwise based on
# https://github.com/zzzeek/sqlalchemy/blob/master/examples/postgis/postgis.py
import re
from sqlalchemy.sql import expression
from fire.api.model import columntypes
__all__ = ["Geometry", "Point", "Bbox"]
class Geometry(expression.Function):
... |
# Script used for Epic Link Corrector in next-gen Projects
"""
Script : Epic Link Corrector for Next-gen Projects
Author : <NAME>
Platform : Atlassian Jira Cloud
Version : 1.0
**************************************************************************
Required libraries : requests
Download URL : http://python... |
# -*- coding: utf-8 -*-
"""Provides a ``CacheKeyGenerator`` utility that generates a cache key when
called with a list of arguments and ``get_token`` and ``set_token`` functions
to get and set the token that's used as the cache key fragment for model
instances when they're provided as args when calling the ``Cac... |
import os
import configparser
from datetime import datetime
from osgeo import gdal
def get_config(config_file, section_name='GENERAL'):
"""Returns the content of a `config.ini` file as a dictionary.
Parameters
----------
config_file: str
Full path to the config file that should be parsed ... |
from django.db.models.base import ModelBase
from cms.models.pagemodel import Page
from os.path import join
from datetime import datetime, date
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe
from django.template.loader import render_to_s... |
import numpy as np
import json, os, sys, random, time
from sklearn.metrics import f1_score, accuracy_score
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data as Data
import torch.optim as optim
t0 = time.time()
# 参数
max_len = 500
batch_size = 64
label_size = 8
embed_size, kerne... |
from __future__ import absolute_import, unicode_literals
from .Darcy_CVFEM import Darcy_CVFEM
from ..models import (BC, Analysis, Connectivity, Mesh, Nodes, Preform, Resin,
Section, Step, Results)
from time import sleep
import numpy as np
from celery import shared_task
import os
imp... |
import io
import json
import os, os.path
import subprocess
import sys
import urllib.request
from urllib.error import URLError, HTTPError
import re
from version import __version__
import random
import itertools
import bisect
import logging
def is_bundled():
return getattr(sys, 'frozen', False)
def local_path(path=... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.