text stringlengths 3.07k 22.1k |
|---|
"""
We use the architecture in the paper. https://arxiv.org/abs/1606.00704
"""
import argparse
import pprint
import sys
from itertools import chain
import torch
import torch.nn as nn
from torchlib.common import FloatTensor
from torchlib.generative_model.gan.bigan_ali.bigan_ali import ALI
from torchlib.dataset.image.... |
"""Module for all Alias types. Alias types are types that handle to conversion for other types.
All builtin types (int, str, float, etc...) have a corresponding Alias type.
"""
from __future__ import annotations
import enum
import pathlib
import typing as t
import ipaddress
import dataclasses
import _io # type: ignor... |
import cv2
cv2.setNumThreads(0)
import glob
import sys
import collections
import time
import numpy as np
import random
import albumentations as A
def transformImg(image, seed=42, trans=False):
# TODO: 这样设置随机种子是否合理?有没有更好的方法?
# set a certain random seed to make the same transformation for all image... |
import codecs
from collections import defaultdict
import itertools
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import random
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
import scipy
import scipy.spatial.distance
import sys
import utils
__author__ = "<NAME>"
__vers... |
#!/usr/bin/env python
"""
angular_spec_doa.py
Written by <NAME> <<EMAIL>>
"""
import time # debug
import sys # debug
import math
import argparse
import numpy as np
import apkit
# Microphone 3D coordinates (unit is meter)
_MICROPHONE_COORDINATES = np.array([[-0.0267, 0.0343, 0.2066],
... |
import inspect
import re
from textwrap import wrap
from celery.exceptions import NotRegistered
from firexapp.plugins import plugin_support_parser
from firexapp.application import import_microservices, get_app_task
class InfoBaseApp:
def __init__(self):
self._list_sub_parser = None
self._info_sub_p... |
#!/usr/bin/python
import os
import os.path
import subprocess
import re
import pwd
import logging
import argparse
import yaml
import itertools
import collections
import errno
from functools import partial
logger = logging.getLogger( __name__ )
class callmap( object ):
'''like starmap, but handles dicts via kwargs'''... |
import torch
from torch import nn
from torch.nn import functional as F, Parameter
import numpy as np
def array1d_repr(t, format='{:.3f}'):
res = ''
for i in range(len(t)):
res += format.format(float(t[i]))
if i < len(t) - 1:
res += ', '
return '[' + res + ']'
class SteFloo... |
import re
import time
from typing import Dict
from .meters import BaseMetric, CallbackGauge, Counter, Event, Gauge, Histogram, Meter, \
SimpleGauge, Timer
class MetricsRegistry(object):
"""
A single interface used to gather metrics on a service. It keeps track of
all the relevant Counters, Meters, Hi... |
from typing import List, Tuple, Callable, Optional, NamedTuple
import unicodedata
from allennlp_models.rc.dataset_readers.utils import STRIPPED_CHARACTERS
from src.data.types import Span
def get_sequence_boundaries(special_tokens_mask: List[int]):
"""
Returns the token index boundaries of a sequence that wa... |
import tensorflow as tf
import numpy as np
from .utils import gaussian_blur
from .quickdraw_utils import scale_and_rasterize, stroke_three_format
def rasterize_prediction(image, sketch, class_name, prediction):
png_dimensions = image.shape[:-1]
stroke_three = stroke_three_format(prediction)
r... |
# -*- coding: utf-8 -*-
###############################################################################
# Copyright (c), Forschungszentrum Jülich GmbH, IAS-1/PGI-1, Germany. #
# All rights reserved. #
# This file is part of the aiida-jutools package. ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import os
import sys
import time
import shutil
import socket
import logging
import urllib
import urllib2
import zipfile
import difflib
import xmlrpclib
dirname = os.path.dirname(os.path.realpath( __file__ ))
sys.path.append(os.path.join(dirname,".."))
from Me... |
import pandas as pd
import numpy as np
from CONF import couList,iso2,urlbase
import dash_html_components as html
import dash_table
import datetime
mobData={}
mobDataGoogle={}
def getMobilityDataGoogle1(cou):
if not cou in mobDataGoogle:
Fname=urlbase+'mobCouGoogle/2020_'+iso2[cou]+'_Region_Mobility_Report... |
"""The Seasonal Calendar
Devised by Galvin Industries, LLC.
See: https://thenewcalendar.com"""
from bisect import bisect
from dataclasses import dataclass
from datetime import time, timedelta, tzinfo
from itertools import accumulate
from operator import add
from typing import List, Optional
from nerdcal._base impor... |
#import open3d as o3d
import os
import sys
import logging
import numpy
import numpy as np
import torch
import torch.utils.data
import transforms3d.euler as t3d
import transforms3d
import time
from learning3d.models import PointNet, iPCRNet, RPMNet, PointNetLK
from learning3d.models import DGCNN, DCP, PRNet
from learn... |
import matplotlib.colors as mcolors
import gensim
import gensim.corpora as corpora
from operator import index
from wordcloud import WordCloud
from pandas._config.config import options
import pandas as pd
import streamlit as st
import plotly.express as px
import plotly.graph_objects as go
import matplotlib.pyplot as plt... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `pretty_table_printer` package."""
import pytest
from pretty_table_printer import pretty_table_printer
from datetime import datetime
from decimal import Decimal
from pretty_table_printer import (
ColumnSpec,
RowCollection,
pretty_date,
pret... |
import math
from typing import DefaultDict
import numpy as np
import pandas as pd
import os
from rl_env.adv_spd_env_road_multi import Vehicle, TrafficSignal, AdvSpdEnvRoadMulti
from gym import spaces
class SectionMaxSpeed(object):
def __init__(self, offset_info, track_length, min_speed=30, max_speed=50,... |
"""Float class.
Represents an unbounded float using a widget.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distribute... |
import warnings
from typing import Any, Callable, List
from skimage import measure
from scipy import ndimage
import tensorflow as tf
import tensorflow_addons as tfa
import numpy as np
class InitializableMetric(tf.keras.metrics.Metric):
""" Metric that has to be initialized from model configuration. """
de... |
# Copyright (c) 2016-2017 Adobe Systems Incorporated. All rights reserved.
#
# 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... |
from style_grader_functions import check_if_function, check_if_function_prototype
from pyparsing import Literal, Word, Optional, ParseException, Group, SkipTo, alphanums, LineStart, srange
import re
def check_int_for_bool(self, code):
if check_if_function(code):
function_regex = re.compile(r"^\s*(\w+)\... |
"""Tests for the module :mod:`esmvaltool.cmorizers.obs.utilities`."""
from unittest.mock import Mock
import dask.array as da
import iris
import numpy as np
import pytest
from cf_units import Unit
import esmvaltool.cmorizers.obs.utilities as utils
def np_to_da(array, lazy):
"""Convert numpy array to dask array.... |
from typing import Union
import pandas as pd
from sklearn.base import BaseEstimator
from ira.analysis.timeseries import smooth, rsi, ema
from ira.analysis.tools import srows, scols, apply_to_frame, ohlc_resample
from qlearn.core.base import signal_generator
from qlearn.core.data_utils import pre_close_time_shift
from... |
import dataclasses
from collections import Counter
from itertools import compress
import numpy as np
import pandas as pd
import pytest
from ..tree import (
Node,
PeriodicPatternMiner,
Tree,
combine_horizontally,
combine_vertically,
encode_leaves,
get_occs,
greedy_cover,
grow_horizo... |
# Copyright 2018 <NAME>. 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 ... |
#!/usr/bin/env python
import rospy
import tf
from nav_msgs.msg import OccupancyGrid, Odometry
import math
import numpy as np
import copy
import time
import threading
from std_srvs.srv import Trigger
merged_map=OccupancyGrid()
map_list=[]
_started=False
map_object=[]
odom_list=[]
odom_object=[]
map_pending=[]
map_merg... |
# Copyright 2016-2020 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
#
# or in the "license" f... |
import sys
import torch
import os
from tqdm import tqdm
import torch.distributed as dist
import torch.nn as nn
import torch.multiprocessing as mp
from torch.utils.data import DataLoader
from helen.modules.python.models.dataloader import SequenceDataset
from helen.modules.python.TextColor import TextColor
from helen.mo... |
#!/usr/bin/env python3
import argparse
import collections
import os
import re
import sys
import subprocess
SECTION = re.compile(r'^\[(.+)\]')
VERSION = re.compile(r'(version\s*=\s*")(.+)(")')
DEPENDENCIES = re.compile(r'^(?:dependencies|build-dependencies|target\..+?\.dependencies|dependencies\.(\w+))$')
INTERNAL_CRAT... |
# import boto3
# from botocore.errorfactory import ClientError
from loguru import logger
from .base_storage import Storage
from dataclasses import dataclass
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload
from google.oauth2 impor... |
from abc import ABC
import requests
import re
import urllib
from typing import List, Dict
from django.utils import timezone
from data_refinery_common.models import (
Batch,
File,
SurveyJobKeyValue
)
from data_refinery_foreman.surveyor import utils
from data_refinery_foreman.surveyor.external_source import E... |
from testflows.core import *
import datetime
from datetime64_extended_range.requirements.requirements import *
from datetime64_extended_range.tests.common import *
@TestScenario
@Requirements(
RQ_SRS_010_DateTime64_ExtendedRange_NonExistentTime_InvalidDate("1.0")
)
def invalid_date(self):
"""Check how non-ex... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Google
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
... |
# Copyright 2016 The Cebes Authors. All Rights Reserved.
#
# Licensed under the Apache License, version 2.0 (the "License").
# You may not use this work except in compliance with the License,
# which is available at www.apache.org/licenses/LICENSE-2.0
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRAN... |
"""
MCMC Model Comparison
---------------------
This example uses Bayesian MCMC to select between two models for a dataset.
The dataset is a mixture of two gaussian distributions, and two MCMC models
are fit: one with a single gaussian, one with two gaussians of different
widths.
"""
# Author: <NAME>
# License: BSD
# ... |
import sys
from pathlib import Path
import numpy as np
from diffpy.utils.parsers.loaddata import loadData
from scipy.constants import physical_constants
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
from matplotlib.gridspec import GridSpec
from matplotlib.colors import LinearSegmentedCol... |
from __future__ import print_function, unicode_literals, absolute_import, division
import numpy as np
from time import time
from .utils import _normalize_grid
import splinegenerator as sg
import tensorflow as tf
def non_maximum_suppression(coord, prob, grid=(1,1), b=2, nms_thresh=0.5, prob_thresh=0.5, verbose=False,... |
# author: <NAME>
import numpy as np
from scipy.stats import randint,norm,multivariate_normal, ortho_group
from scipy.linalg import subspace_angles, orth
from scipy import optimize
from scipy import linalg
from sklearn.cluster import KMeans
from cluster.selfrepresentation import ElasticNetSubspaceClustering
import seab... |
# Copyright 2022 <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 required by applicable law or agreed to in writing, so... |
# coding: utf-8
"""
"""
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
#Mandatory imports
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import log_loss
from sklearn.model_selection impor... |
import os, types, gzip
class VCFEntry(object) :
"""A single entry in a VCF file"""
def __init__(self, vcfFile, line, lineNumber) :
#CHROM POS ID REF ALT QUAL FILTER INFO FORMAT NA00001 NA00002 NA00003
#20 14370 rs6054257 G A 29 ... |
import random
from cave import *
""" Define all the general stuff """
"""Define the movements between the rooms"""
@when('go north', direction = 'north')
@when('go west', direction = 'west')
@when('go south', direction = 'south')
@when('go east', direction = 'east')
def go (direction):
global current_room
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `pyfesom2` package."""
import pytest
import os
import numpy as np
import xarray as xr
import matplotlib.pylab as plt
# import matplotlib
from matplotlib.testing.compare import compare_images
from matplotlib.testing.decorators import _image_directories
from ... |
#!/usr/bin/env python3
"""
Laskee auringonlaskun ja lähettää ULKOLUUKKU_KIINNI_VIIVE jälkeen komennon sulkea luukku.
Scripti kuuntelee myös mqtt-viestiä siitä laitetaanko luukku pois tai päälle.
Mikäli mqtt-viesti ohjaa luukun kiinni,lähetetään ennakolta tutkittu kaukosaatimen koodi vastaanottimeen
käyttämällä FS... |
import re
from qtpy import QT_VERSION
from qtpy import QtCore
from qtpy import QtGui
from qtpy import QtWidgets
from qtpy.QtWidgets import QGraphicsScene, QGraphicsView, QCompleter
from qtpy.QtCore import Qt
QT5 = QT_VERSION[0] == '5' # NOQA
from labelme.logger import logger
import labelme.utils
# TODO(unknown):
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import time
import numpy as np
import tensorflow as tf
from utils import softmax
import model
from data_reader import load_data, DataReader
import codecs
flags = tf.flags
# data
flags.DEFINE_string... |
import os
import cv2
import glob
import json
import pickle
import joblib
import numpy as np
import matplotlib.pyplot as plt
N, M = 11, 8
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
def extract_images(filename, outdir, step=5):
os.makedirs(outdir, exist_ok=True)
vid = cv2.VideoC... |
import os
import time
import re
from show.form import *
from show.models import UserFiles,UserUp
from django.shortcuts import render
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.http import ... |
# -*- coding: utf-8 -*-
# © 2016 <NAME> <<EMAIL>>, Trustcode
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from datetime import datetime
from random import SystemRandom
from odoo import api, models, fields
from odoo.exceptions import UserError
class PosOrder(models.Model):
_inherit = "pos.... |
# SPDX-License-Identifier: BSD-3-Clause
# Copyright (c) 2021 Scipp contributors (https://github.com/scipp)
# @file
# @author <NAME>
import numpy as np
import scipp as sc
from ..factory import make_dense_data_array, make_dense_dataset
from .plot_helper import plot
import matplotlib
matplotlib.use('Agg')
# TODO: For no... |
import numpy as np
import tvm
from tvm import te
from tvm.topi.utils import get_const_tuple
from ..util import util_convert_csr_to_dds
from ..op import vanilla_spmm_csr_x86, schedule_vanilla_spmm_csr_x86, \
vanilla_spmm_dds_x86, schedule_vanilla_spmm_dds_x86, \
vanilla_spmm_csr_cuda, schedule_vanilla_spmm_csr_... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# Formal
# ======
#
# Copyright 2013 <NAME>
# Copyright 2015-2019 Heiko 'riot' Weinen <<EMAIL>> and others.
#
# This file has been changed and this notice has been added in
# accordance to the Apache License
#
# Licensed under the Apache License, Version 2.0 (the "License... |
#!/usr/bin/python3
import argparse
from arg_parser import get_parser
import datetime
from nltk.translate import bleu_score
import numpy
import progressbar
import six
import chainer
from chainer.backends import cuda
import chainer.functions as F
import chainer.links as L
from chainer import training
from chainer.trai... |
"""
Example generation for the scikit learn
Generate the rst files for the examples by iterating over the python
example files.
Files that generate images should start with 'plot'
"""
import os
import sys
import shutil
import traceback
import glob
import token, tokenize
rst_template = """
:orphan:
.. _example_%(... |
#!/usr/bin/env python
"""
Infer connections between neurons from arborizations.
"""
import csv
import itertools
import networkx as nx
import voluptuous as vol
from parse_arborization import NeuronArborizationParser
def is_arbor(a):
"""
A valid arborization dict must adhere to the following schema:
{'ne... |
import os,sys
import math
import re, subprocess
from optparse import OptionParser
CHROM_CONVERT = {'chrI':'chr1','chrII':'chr2','chrIII':'chr3','chrIV':'chr4','chrV':'chr5','chrVI':'chr6',
'chrVII':'chr7','chrVIII':'chr8','chrIX':'chr9','chrX':'chr10','chrXI':'chr11','chrXII':'chr12',
... |
import logging
import os
from datetime import datetime, timedelta
from decimal import Decimal
from pathlib import Path
import pytest
import requests
import responses
from pricehist import exceptions, isocurrencies
from pricehist.price import Price
from pricehist.series import Series
from pricehist.sources.ecb import ... |
import multiprocessing
import contextvars
from concurrent.futures import Executor, ThreadPoolExecutor
from contextlib import contextmanager
from typing import Callable, Iterator, Optional
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base, DeclarativeMeta
from sqlalchemy.orm i... |
# -*- coding: utf-8 -*-
from collections import namedtuple
from unittest import mock
import pytest
import sqlalchemy as sa
from pyramid import security
from h.auth import role, util
from h.models import AuthClient
from h.models.auth_client import GrantType
from h.services.user import UserService
FakeUser = namedtup... |
import sys
import argparse
import h5py
import numpy as np
import torch
from torch import nn
from torch import cuda
from util.holder import *
from util.util import *
from preprocess.preprocess import pad
from hf.roberta_for_srl import *
import traceback
#import spacy
#spacy_nlp = spacy.load('en')
# use nltk instead as ... |
"""Evaluate Python expressions and statements embedded in plaintext."""
# Enable eepyc to evaluate its own source file (used for generating
# the readme file).
# {{e eepyc }}
# {{%
__all__ = ['Evaluator']
__version__ = "0.3.0"
__author__ = "<NAME>"
import io
import itertools
import re
import sys
import textwrap
cl... |
# Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the MIT license.
# See the LICENSE file in the project root for more information.
from __future__ import annotations # Allow subscripting Field
from collections.abc import Mapping as abc_Mapping, Seq... |
from __future__ import annotations
from homeassistant.components.climate import (
DOMAIN as PLATFORM_CLIMATE,
ClimateEntity,
)
from homeassistant.components.climate.const import (
PRESET_AWAY, PRESET_COMFORT, PRESET_SLEEP, SUPPORT_PRESET_MODE, SUPPORT_TARGET_TEMPERATURE,
CURRENT_HVAC_HEAT, CURRENT_HVAC... |
# Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES. 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 requ... |
class Joins(object):
inner_join = 1,
left_join = 2,
cross_join = 3
@staticmethod
def str(join):
if join == Joins.inner_join:
return 'INNER JOIN'
elif join == Joins.left_join:
return 'LEFT JOIN'
else:
return 'CROSS JOIN'
class Query(objec... |
"""Test cases for the grammar search invention approach."""
import pytest
import numpy as np
from predicators.src.approaches.grammar_search_invention_approach import (
_PredicateGrammar, _DataBasedPredicateGrammar,
_SingleFeatureInequalitiesPredicateGrammar, _create_grammar,
_halving_constant_generator, _F... |
#!/usr/bin/python3
import argparse
import sys
import time
import logging
import os
import re
import fileinput
log = logging.getLogger("mem")
class Entry:
def __init__(self, address=None, name=None, size=None, **kwargs):
super().__init__()
self.address = address
self.name = name
... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from scipy import stats
# Credit to @magsguist
def explore_univariate(train, cat_vars, quant_vars):
for var in cat_vars:
_explore_univariate_categorical(train, v... |
from math import log
from termcolor import colored
from re import search, IGNORECASE
from Nemesis.lib.Globals import Color
from Nemesis.lib.Globals import base64char, hexchar, dom_sources_regex, dom_sinks_regex, extractor
from Nemesis.lib.Globals import subdomain_regex, path_regex, single_path_regex, experimental_path... |
#!/usr/bin/env python3
import math
import calendar
from datetime import datetime, timedelta
import dataset
from string import Template
class DeltaTemplate(Template):
delimiter = "%"
# Helper date conversion functions
def date_to_datetime(date):
return(datetime.strptime(date, '%m/%d/%Y'))
def datestamp_to_d... |
import csv
import logging
import time
from datetime import timedelta
from decimal import Decimal
from cryptocompy import price
from forex_python.converter import CurrencyRates, RatesNotAvailableError
from src.DateUtils import parse_date, date_to_string, get_start_of_year, get_start_of_year_after
from src.NumberUtils ... |
# MIT License
# Copyright (c) 2017 GiveMeAllYourCats
# 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, mer... |
import angr
import claripy
import archinfo
import copy
import logging
from .base_state_snapshot import BaseStateSnapshot
from .angr_utils import MAX_DEAD_VARS, NVIC_RET_START
l = logging.getLogger("LIVENESS")
class StackFrame:
def __init__(self, base_sp=None, tracked_addrs=None):
# We use a None base_sp a... |
# Copyright 2018 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.
"""Utility functions for processing a flaky test's pass rates."""
from services.flake_failure import flake_constants
from waterfall import waterfall_config
... |
# Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import os
from datetime import datetime
from math import ceil
from typing import Union
from openvino.runtime import Core, get_version, AsyncInferQueue
from .utils.constants import MULTI_DEVICE_NAME, HETERO_DEVICE_NAME, CPU_DEVICE_NAME, ... |
#!/usr/bin/env python3
# Analyze votes as per http://madisonvoices.com/pdffiles/2008_2012_ElectionsResultsAnomaliesAndAnalysis_V1.5.pdf
# looking for votes swapped by tabulation machinery.
#
# The main data structure is a dictionary with keys representing choices and values a list of the numbers
# per precinct in nonde... |
import contextlib
import inspect
from typing import Callable
import unittest
from unittest import mock
import warnings
import numpy
import cupy
from cupy._core import internal
import cupyx
import cupyx.scipy.sparse
from cupy.testing._pytest_impl import is_available
if is_available():
import pytest
_skipif:... |
import torch
from torch import nn
from .module import Module, _try_build_bd_module
# Adapted from nn.Sequential
# https://pytorch.org/docs/stable/_modules/torch/nn/modules/container.html#Sequential
class BaseCollection(nn.Sequential, Module):
# Dict_out can be None (output is not a collection), True (give dict ou... |
#!/usr/bin/env python
# $Id: bpy_introspect_ui.py 34890 2011-02-16 02:51:56Z campbellbarton $
# ***** BEGIN GPL LICENSE BLOCK *****
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either vers... |
import numpy as np
import params
from helpers.propagation import mean_filter
from matplotlib import pyplot as plt
from helpers.plot_helpers import gauge, generate_graph
def speech_time_comparison(speech_time, path):
"""Plots pie charts to show speech comparison"""
fig, ax = plt.subplots(1)
ax.pie(speech_t... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import vim
from ncm2 import Ncm2Source, getLogger
import re
import jedi
import os
from jedi import settings
from itertools import zip_longest
logger = getLogger(__name__)
import_pat = re.compile(r'^\s*(from|import)')
callsig_pat = re.compile(r'[\(,]$')
... |
import html
import importlib.resources
import itertools
import pathlib
import re
import string
from typing import Callable, Dict, Iterator, List, Tuple, Union
from attr import attrib, attrs
from flask import render_template
import numba
import numpy as np
from steady_cell_phenotype.equation_system import EquationSyst... |
import numpy as np
import torch
from torch.nn import functional as F
from maskrcnn_benchmark.config import cfg
from maskrcnn_benchmark.modeling.make_layers import make_fc
from maskrcnn_benchmark.structures.bounding_box import BoxList
import torch.nn as nn
from .vg_loss import VGLoss
from maskrcnn_benchmark.modeling.box... |
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
#--------------------------------------------------------------------------
# Generate test data for a longformer model, so that we can use onnxrunti... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import time
from six.moves import range
import tensorflow as tf
import numpy as np
import zhusuan as zs
from examples import conf
from examples.utils im... |
"""MBPO"""
import gym
import time
import argparse
import numpy as np
import tensorflow as tf
from typing import Union, Tuple, List, Type
from algorithms.mopo.models import FFModel, sac_actor_fc_continuous_network, critic_fc_network
from util.replay_buffer import ReplayBuffer
from algorithms.mopo.sac import SACAgent
fr... |
# For python 2 and 3 compatibility
from __future__ import print_function
import sys
if sys.version_info[0] < 3:
input = raw_input
import argparse
import os
import stat
import shutil
import getpass
CONF_EXTENSION = ".multivisdom"
ACTION_STOP = 0
ACTION_LIST = 1
ACTION_ADD = 2
ACTION_DEL = 3
ACTION_PASS = 4
ACT... |
#
# Copyright (c) 2021 Wind River Systems, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY ... |
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
#
#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... |
#!/usr/bin/env python
# coding: utf-8
import numpy as np
import math
import os
from matplotlib import pyplot as plt
from matplotlib.colors import LogNorm
import pandas as pd
import seaborn as sns
from termcolor import colored
import time
import sys
sys.path.append('.')
import FeatureSampler as FS
import importlib
impo... |
import json
import logging
import logging.handlers
import sys
import traceback
import treq
from twisted.internet import defer
import twisted.python.log
from lbrynet import __version__ as lbrynet_version, build_type, conf
from lbrynet.core import utils
class HTTPSHandler(logging.Handler):
def __init__(self, url,... |
"""
Fine tune forward model using data generate by itself.
choose S_init, S_goal
controller gives a_1
excute a_1, get transition S_init, a_1, S_next
use this transition to renforce the forward model
Choose S_init, S_goal
1. using Policy (Fine tune in policy distribution)
2. randomly choose one (if not state spac... |
import os, re, sys, copy, warnings
import tensorflow as tf
if tf.__version__.split('.')[0] == '2':
tf = tf.compat.v1
tf.disable_v2_behavior()
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(BASE_DIR)
sys.path.insert(0, ROOT_DIR)
from collections import defaultdict
from config ... |
"""Tests for graphein.protein.graphs"""
from functools import partial
from pathlib import Path
import networkx as nx
import pytest
from graphein.protein.config import ProteinGraphConfig
from graphein.protein.edges.distance import (
add_aromatic_interactions,
add_aromatic_sulphur_interactions,
add_cation_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: <NAME> <<EMAIL>>
"""
This module contains code for retrieving HTML embed codes for all images in a
given Flickr photoset/album URL.
Unforturnately, not all photosets which are visible on the website can be
accessed via Flickr's REST API. We can't simply extract ... |
import inspect
import csv
import numpy as np
from brian2 import *
from copy import deepcopy
from voltagebudget.util import burst
from voltagebudget.util import pulse
def shadow_adex(N, time, ns, ts, **adex_kwargs):
"""Est. the 'shadow voltage' of the AdEx membrane voltage."""
# In the neuron can't fire, we're... |
import builtins
import json
import os
import requests
from django.core.wsgi import get_wsgi_application
from queue import Queue
from threading import Condition
from timeit import default_timer as timer
from data_conversion_subsystem.config.config import DCS_CONFIG
from data_conversion_subsystem.supervisor.supervisor ... |
#! /usr/bin/env python
# ______________________________________________________________________
'''test_multiarray_api
Test the code generation utility class numba.multiarray_api.MultiarrayAPI.
'''
# ______________________________________________________________________
import ctypes
import llvm.core as lc
import ll... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.