code stringlengths 281 23.7M |
|---|
def inline_small_list(sizemax=11, sizemin=0, immutable=False, unbox_num=False, nonull=False, attrname='list', factoryname='make', listgettername='_get_full_list', listsizename='_get_size_list', gettername='_get_list', settername='_set_list'):
if (not config.type_size_specialization):
sizemin = sizemax = 0
... |
def find_singledispatch_register_impls(modules: list[MypyFile], errors: Errors) -> SingledispatchInfo:
visitor = SingledispatchVisitor(errors)
for module in modules:
visitor.current_path = module.path
module.accept(visitor)
return SingledispatchInfo(visitor.singledispatch_impls, visitor.deco... |
.parametrize('bitsize', [3, 4, 5])
def test_hamming_weight_compute(bitsize: int):
gate = HammingWeightCompute(bitsize=bitsize)
gate_inv = (gate ** (- 1))
assert_decompose_is_consistent_with_t_complexity(gate)
assert_decompose_is_consistent_with_t_complexity(gate_inv)
assert_valid_bloq_decomposition(... |
class FiduceoMviriFullFcdrFileHandler(FiduceoMviriBase):
nc_keys = FiduceoMviriBase.nc_keys.copy()
nc_keys['VIS'] = 'count_vis'
def _get_calib_coefs(self):
coefs = super()._get_calib_coefs()
coefs['VIS'].update({'years_since_launch': np.float32(self.nc['years_since_launch']), 'a0': np.float3... |
class KazooTreeCacheTests(KazooAdaptiveHandlerTestCase):
def setUp(self):
super(KazooTreeCacheTests, self).setUp()
self._event_queue = self.client.handler.queue_impl()
self._error_queue = self.client.handler.queue_impl()
self.path = None
self.cache = None
def tearDown(sel... |
class Core(object):
def __init__(self):
self.features = []
self._features_to_run = OrderedDict()
self._feature_id_lock = Lock()
self._feature_id = 0
self._scenario_id_lock = Lock()
self._scenario_id = 0
def features_to_run(self):
return [f for f in self._f... |
class _StochasticFactory():
def parse_distribution(element):
if (element.find('NormalDistribution') is not None):
return NormalDistribution.parse(element.find('NormalDistribution'))
elif (element.find('UniformDistribution') is not None):
return UniformDistribution.parse(eleme... |
def do_setup():
root = get_root()
try:
cfg = get_config_from_root(root)
except (EnvironmentError, configparser.NoSectionError, configparser.NoOptionError) as e:
if isinstance(e, (EnvironmentError, configparser.NoSectionError)):
print('Adding sample versioneer config to setup.cfg'... |
def get_repository_from_config(config_file: str, repository: str, repository_url: Optional[str]=None) -> RepositoryConfig:
if repository_url:
_validate_repository_url(repository_url)
return {'repository': repository_url, 'username': None, 'password': None}
try:
return get_config(config_f... |
.asyncio(scope='class')
class TestClassScopedLoop():
loop: asyncio.AbstractEventLoop
async def test_remember_loop(self):
TestClassScopedLoop.loop = asyncio.get_running_loop()
async def test_this_runs_in_same_loop(self):
assert (asyncio.get_running_loop() is TestClassScopedLoop.loop) |
class Effect6688(BaseEffect):
type = ('projected', 'active')
def handler(fit, container, context, projectionRange, **kwargs):
if ('projected' not in context):
return
if fit.ship.getModifiedItemAttr('disallowAssistance'):
return
if (container.getModifiedItemAttr('m... |
class AppInformation(EventPlugin):
PLUGIN_ID = 'AppInformation'
PLUGIN_NAME = _('Application Information')
PLUGIN_DESC = _('Various information about the application and its environment.')
PLUGIN_CAN_ENABLE = False
PLUGIN_ICON = Icons.PREFERENCES_SYSTEM
def PluginPreferences(self, *args):
... |
def save_cache():
global cache
print('Saving cache')
cache['last_run'] = datetime.strftime(datetime.now().replace(hour=0, minute=0, second=0), '%Y-%m-%dT%H:%M:%SZ')
try:
with open(os.path.join(cache_dir, 'cache.pickle'), 'wb') as input_file:
pickle.dump(cache, input_file)
except ... |
def extract_current_step(current_status_string):
step_increment = re.search('Step ([0-9]+)/([0-9]+) :', current_status_string)
if step_increment:
return int(step_increment.group(1))
step_increment = re.search('Step ([0-9]+) :', current_status_string)
if step_increment:
return int(step_in... |
def get_relational_data(user_id, item_id, data):
(r0, r1, r2, r3) = ([], [], [], [])
(e1, e2, e3) = ([], [], [])
all_items = data.items.values()
t1 = time()
pos = data.user_positive_list[user_id]
id1 = data.items_traverse[item_id]
movie1 = data.movie_dict[id1]
ru_list = list(pos)
if ... |
def ql_syscall_terminate_with_payload(ql, pid, reason_namespace, reason_code, payload, payload_size, reason_string):
ql.log.debug(('terminate_with_payload(pid: %d, reason_namespace: 0x%x, reason_code: 0x%x, payload: 0x%x payload_size: 0x%x, reason_string: 0x%x)' % (pid, reason_namespace, reason_code, pa... |
def get_similar_cids(base, MaxRecords):
if (type(base) == int):
base = str(base)
cids = pcp.get_compounds(base, searchtype='similarity', MaxRecords=MaxRecords)
results = []
for x in cids:
print(x.cid)
csd_codes = check_for_ccdc_structures(x.cid)
if (len(csd_codes) > 0):
... |
class SvgRenderer(Renderer):
def __init__(self, width, height, filename):
self._width = width
self._height = height
if filename.startswith('~'):
filename = os.path.expanduser(filename)
self._filename = filename
def render(self, scene: WorldObject, camera: Camera):
... |
class OptimizationConfig(FairseqDataclass):
max_epoch: int = field(default=0, metadata={'help': 'force stop training at specified epoch'})
max_update: int = field(default=0, metadata={'help': 'force stop training at specified update'})
stop_time_hours: float = field(default=0, metadata={'help': 'force stop ... |
class DocStringParser():
def __init__(self, function_name: str) -> None:
self.function_name = function_name
self.state = [STATE_INIT]
self.accumulator = ''
self.arg_type: (str | None) = None
self.arg_name = ''
self.arg_default: (str | None) = None
self.ret_typ... |
def setup_scene(env, traj_data):
scene_num = traj_data['scene']['scene_num']
object_poses = traj_data['scene']['object_poses']
dirty_and_empty = traj_data['scene']['dirty_and_empty']
object_toggles = traj_data['scene']['object_toggles']
scene_name = ('FloorPlan%d' % scene_num)
env.reset(scene_na... |
def use_optimizer(network, params):
if (params['optimizer'] == 'sgd'):
optimizer = torch.optim.SGD(network.parameters(), lr=params['lr'], weight_decay=params['l2_regularization'])
elif (params['optimizer'] == 'adam'):
optimizer = torch.optim.Adam(network.parameters(), lr=params['lr'], betas=para... |
def register_train_step(name):
def register_train_step_fn(func):
if (name in TRAIN_STEP_REGISTRY):
raise ValueError('Cannot register duplicate train step ({})'.format(name))
if (func.__name__ in TRAIN_STEP_NAMES):
raise ValueError('Cannot register task with duplicate train st... |
def train(hparams, scope=None, target_session=''):
params = hparams.values()
for (key, val) in params.items():
hparams.logger.info(((str(key) + ':') + str(val)))
print('load and cache data...')
if (hparams.train_file is not None):
cache_data(hparams, hparams.train_file, flag='train')
... |
class StubClass():
def __init__(self, orig, check_attributes_also=False):
self.orig = orig
self.check_attributes_also = check_attributes_also
def __call__(self, stub):
for attribute_name in dir(stub):
self.check_compliance(stub, attribute_name)
stub._stubbed_class = s... |
def pin_memory(data_queue, pinned_data_queue, sema):
while True:
data = data_queue.get()
data['xs'] = [x.pin_memory() for x in data['xs']]
data['ys'] = [y.pin_memory() for y in data['ys']]
pinned_data_queue.put(data)
if sema.acquire(blocking=False):
return |
def test_prepare_nu_t_counts():
num_bits_p = 6
m_param = (2 ** ((2 * num_bits_p) + 3))
num_bits_m = (m_param - 1).bit_length()
expected_cost = ((((3 * (num_bits_p ** 2)) + num_bits_p) + ((4 * num_bits_m) * (num_bits_p + 1))) + 4)
expected_cost += ((((2 * 4) * (num_bits_p - 1)) + (6 * num_bits_p)) + ... |
class AddGaussianLoss(layers.Layer):
def __init__(self, **kwargs):
super(AddGaussianLoss, self).__init__(**kwargs)
self.lamb_kl = self.add_weight(shape=(), name='lamb_kl', trainable=False)
def call(self, inputs):
(mu, std) = inputs
var_dist = tfp.MultivariateNormalDiag(loc=mu, sc... |
def test_FilterGE():
dm = skc.mkdm(matrix=[[7, 5, 35], [5, 4, 26], [5, 6, 28], [1, 7, 30], [5, 8, 30]], objectives=[max, max, min], weights=[2, 4, 1], alternatives=['PE', 'JN', 'AA', 'MM', 'FN'], criteria=['ROE', 'CAP', 'RI'])
expected = skc.mkdm(matrix=[[7, 5, 35], [5, 6, 28], [5, 8, 30]], objectives=[max, max... |
_lr_scheduler('triangular')
class TriangularSchedule(FairseqLRScheduler):
def __init__(self, args, optimizer):
super().__init__(args, optimizer)
if (len(args.lr) > 1):
raise ValueError('Cannot use a fixed learning rate schedule with triangular. Consider --lr-scheduler=fixed instead.')
... |
class PublicKey(PublicKeyBase):
TESTNET_VERSION = 111
MAINNET_VERSION = 0
def from_point(p):
return PublicKey(p.x, p.y)
def from_int(i):
point = ECPointAffine.from_int(bitcoin_curve, i)
return PublicKey.from_point(point)
def from_base64(b64str, testnet=False):
return ... |
def update_summary(epoch, train_metrics, eval_metrics, filename, write_header=False):
rowd = OrderedDict(epoch=epoch)
rowd.update([(('train_' + k), v) for (k, v) in train_metrics.items()])
rowd.update([(('eval_' + k), v) for (k, v) in eval_metrics.items()])
with open(filename, mode='a') as cf:
d... |
def test_make_cf_dataarray_lonlat():
from pyresample import create_area_def
from satpy.cf.data_array import make_cf_data_array
from satpy.resample import add_crs_xy_coords
area = create_area_def('mavas', 4326, shape=(5, 5), center=(0, 0), resolution=(1, 1))
da = xr.DataArray(np.arange(25).reshape(5,... |
class FacebookOAuth2(BaseOAuth2):
name = 'facebook'
REDIRECT_STATE = False
RESPONSE_TYPE = None
SCOPE_SEPARATOR = ','
AUTHORIZATION_URL = '
ACCESS_TOKEN_URL = '
REVOKE_TOKEN_URL = '
REVOKE_TOKEN_METHOD = 'DELETE'
USER_DATA_URL = '
EXTRA_DATA = [('id', 'id'), ('expires', 'expires'... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('tsv')
parser.add_argument('--output-dir', required=True)
parser.add_argument('--output-name', required=True)
args = parser.parse_args()
os.makedirs(args.output_dir, exist_ok=True)
transcriptions = {}
with open(args.tsv, ... |
def update_sync_status_to_sync_now(mirror):
if (mirror.sync_status == RepoMirrorStatus.SYNCING):
return None
retries = max(mirror.sync_retries_remaining, 1)
query = RepoMirrorConfig.update(sync_transaction_id=uuid_generator(), sync_status=RepoMirrorStatus.SYNC_NOW, sync_expiration_date=None, sync_re... |
def run_data_migration(apps, schema_editor):
Task = apps.get_model('tasks', 'Task')
set_null_to_blank(Task.objects.all(), ['uri', 'uri_prefix', 'key', 'comment', 'title_lang1', 'title_lang2', 'title_lang3', 'title_lang4', 'title_lang5', 'text_lang1', 'text_lang2', 'text_lang3', 'text_lang4', 'text_lang5']) |
def read_csv(file_path, QI_INDEX, IS_CAT, IS_DATETIME, SA_INDEX, header=False, delimiter=',', encoding='utf-8', TIME_FORMAT_STR='%Y-%m-%d %H:%M:%S'):
QI_num = len(QI_INDEX)
data = []
intuitive_dict = []
intuitive_order = []
intuitive_number = []
for i in range(QI_num):
intuitive_dict.app... |
class TestNonChrootClient(KazooTestCase):
def test_create(self):
client = self._get_nonchroot_client()
assert (client.chroot == '')
client.start()
node = uuid.uuid4().hex
path = client.create(node, ephemeral=True)
client.delete(path)
client.stop()
def test... |
def test_sorm():
(options, stochastic_model, limit_state) = setup()
Analysis = ra.Sorm(analysis_options=options, stochastic_model=stochastic_model, limit_state=limit_state)
Analysis.run()
print(Analysis.betag_breitung)
print(Analysis.betag_breitung_m)
assert (pytest.approx(Analysis.betaHL, abs=0... |
class SphereMarginProduct(nn.Module):
def __init__(self, in_feature, out_feature, m=4, base=1000.0, gamma=0.0001, power=2, lambda_min=5.0, iter=0):
assert (m in [1, 2, 3, 4]), 'margin should be 1, 2, 3 or 4'
self.in_feature = in_feature
self.out_feature = out_feature
self.m = m
... |
class DecisionMatrixDominanceAccessor(AccessorABC):
_default_kind = 'dominance'
def __init__(self, dm):
self._dm = dm
_cache(maxsize=None)
def _dominance_cache(self):
dm = self._dm
reverse = dm.minwhere
(dominance_cache, alts_numpy) = ({}, {})
for (a0, a1) in it.c... |
.parametrize('outformat', ['TEXT', 'JSON'])
def test_non_json_instance_mixed_with_valid_and_invalid_data(run_line, tmp_path, outformat):
schema = (tmp_path / 'schema.json')
malformed_instance = (tmp_path / 'malformed_instance.json')
good_instance = (tmp_path / 'good_instance.json')
bad_instance = (tmp_p... |
def _applyfcn(obj, name, attrfcn, dictfcn, listfcn):
if (name[0] == '['):
key = ast.literal_eval(name[1:(- 1)])
if isinstance(obj, dict):
return dictfcn(obj, key)
elif isinstance(obj, list):
return listfcn(obj, key)
else:
msg = 'The parameter with ... |
class PyAnalogClock(QWidget):
timeChanged = pyqtSignal(QTime)
timeZoneChanged = pyqtSignal(int)
def __init__(self, parent=None):
super(PyAnalogClock, self).__init__(parent)
self.timeZoneOffset = 0
timer = QTimer(self)
timer.timeout.connect(self.update)
timer.timeout.c... |
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName('MainWindow')
MainWindow.resize(573, 468)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName('centralwidget')
self.vboxlayout = QtWidgets.QVBoxLayout(self.cen... |
def best_matches(current: str, options: Collection[str], n: int) -> list[str]:
if (not current):
return []
options = [o for o in options if (_real_quick_ratio(current, o) > 0.75)]
if (len(options) >= 50):
options = [o for o in options if (abs((len(o) - len(current))) <= 1)]
ratios = {opt... |
def find_compatible_wheel(wheels: Sequence[T], identifier: str) -> (T | None):
(interpreter, platform) = identifier.split('-')
for wheel in wheels:
(_, _, _, tags) = parse_wheel_filename(wheel.name)
for tag in tags:
if (tag.abi == 'abi3'):
if (not (interpreter.startsw... |
class SmartStrip(SmartDevice):
def __init__(self, host: str, *, config: Optional[DeviceConfig]=None, protocol: Optional[TPLinkProtocol]=None) -> None:
super().__init__(host=host, config=config, protocol=protocol)
self.emeter_type = 'emeter'
self._device_type = DeviceType.Strip
self.a... |
def get_h36m_generator(loader, dynamic_length=True, opt=None):
while True:
for (i, data) in enumerate(loader):
seq_len = loader.dataset.get_seq_len()
pose_2d = data['pose_2d'].permute(1, 0, 2, 3).float().cuda()
pose_3d = data['pose_3d'].permute(1, 0, 2, 3).float().cuda()
... |
class BadDestroyMap(DebugModeError):
def __init__(self, node, idx, old_val, new_val, perform):
super().__init__()
self.node = node
self.idx = idx
self.old_val = old_val
self.new_val = new_val
self.perform = perform
def __str__(self):
sio = StringIO()
... |
def main():
(opts, args) = parse_args()
assert opts.build_root
assert opts.dest_dir
dest_arch = None
if opts.dest_arch:
if opts.dest_arch.endswith('.tar'):
dest_arch = tarfile.open(opts.dest_arch, 'w', dereference=True)
elif (opts.dest_arch.endswith('.tar.gz') or opts.des... |
class ContextualEmbedV2(nn.Module):
def __init__(self, model_path, padding_idx=0):
super(ContextualEmbedV2, self).__init__()
state_dict = torch.load(model_path)
self.rnn1 = nn.LSTM(300, 300, num_layers=1, bidirectional=True)
self.rnn2 = nn.LSTM(600, 300, num_layers=1, bidirectional=T... |
def anonymize_ip_address(ip_address):
ip_mask = int('0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000', 16)
try:
ip_obj = ipaddress.ip_address(force_str(ip_address))
except ValueError:
return None
anonymized_ip = ipaddress.ip_address((int(ip_obj) & ip_mask))
return anonymized_ip.compressed |
def thc_objective_grad(xcur, norb, nthc, eri, verbose=False):
etaPp = numpy.array(xcur[:(norb * nthc)]).reshape(nthc, norb)
MPQ = numpy.array(xcur[(norb * nthc):((norb * nthc) + (nthc * nthc))]).reshape(nthc, nthc)
CprP = numpy.einsum('Pp,Pr->prP', etaPp, etaPp)
Iapprox = numpy.einsum('pqU,UV,rsV->pqrs'... |
class GameModel(Model):
class Meta():
read_capacity_units = 1
write_capacity_units = 1
table_name = 'GameModel'
host = '
player_id = UnicodeAttribute(hash_key=True)
created_time = UTCDateTimeAttribute(range_key=True)
winner_id = UnicodeAttribute()
loser_id = UnicodeAt... |
class Migration(migrations.Migration):
dependencies = [('adserver', '0015_publisher_unauthed_ads')]
operations = [migrations.AlterModelOptions(name='adtype', options={'ordering': ('order', 'name')}), migrations.AddField(model_name='adtype', name='description', field=models.CharField(blank=True, default='', help... |
def slugify(s, ok=SLUG_OK, lower=True, spaces=False, only_ascii=False, space_replacement='-'):
if (only_ascii and (ok != SLUG_OK) and hasattr(ok, 'decode')):
try:
ok.decode('ascii')
except UnicodeEncodeError:
raise ValueError(('You can not use "only_ascii=True" with a non asc... |
def get_normal_loss(input, label, num_output, lambda_value, m_value=4):
feature_dim = input.get_shape()[1]
weight = tf.get_variable('weight', shape=[num_output, feature_dim], regularizer=l2_regularizer, initializer=xavier)
prob_distribution = tf.one_hot(label, num_output)
weight = tf.nn.l2_normalize(wei... |
def test_service_browser_started_after_zeroconf_closed():
zc = Zeroconf(interfaces=['127.0.0.1'])
type_ = '_hap._tcp.local.'
class MyServiceListener(r.ServiceListener):
pass
listener = MyServiceListener()
zc.close()
with pytest.raises(RuntimeError):
r.ServiceBrowser(zc, type_, No... |
class WeightSvdModuleSplitter():
def split_module(cls, module, name, rank, svd_lib_ref):
if isinstance(module, Conv2d):
split_modules = cls.split_conv_module(module, name, rank, svd_lib_ref)
elif isinstance(module, Linear):
split_modules = cls.split_fc_module(module, name, ra... |
def key(w, probability=1.0):
if (random.random() > probability):
return w
'\n Swaps $n$ letters with their nearest keys\n '
w = list(w)
i = random.randint(0, (len(w) - 1))
char = w[i]
caps = char.isupper()
if (char in NN):
w[i] = NN[char.lower()][random.randint(0, (len(NN... |
.parametrize('username,password', users)
def test_delete(db, client, username, password):
client.login(username=username, password=password)
instances = Task.objects.all()
for instance in instances:
url = reverse(urlnames['detail'], args=[instance.pk])
response = client.delete(url)
a... |
class APIKeyBucket():
def __init__(self, apikeys: [str], kps: int):
self.apikeys = apikeys
self.kps = kps
self._last_get_time = 0
self._get_interval = (1 / (len(self.apikeys) * kps))
self._lock = DeferredLock()
def get(self) -> str:
self._lock.acquire()
no... |
def apply_signature(value, sig, utf8_strings=False):
if (sig in TYPE_MAP):
return TYPE_MAP[sig](value)
elif sig.startswith('a{'):
return dbus.Dictionary(value, signature=sig[2:(- 1)])
elif sig.startswith('a('):
return dbus.Struct(value, signature=sig[2:(- 1)])
elif sig.startswith... |
class PolicyInformation():
def __init__(self, policy_identifier: ObjectIdentifier, policy_qualifiers: (typing.Iterable[(str | UserNotice)] | None)) -> None:
if (not isinstance(policy_identifier, ObjectIdentifier)):
raise TypeError('policy_identifier must be an ObjectIdentifier')
self._po... |
def test_SKCMethodABC_already_defined__skcriteria_parameters():
class Base(methods.SKCMethodABC):
_skcriteria_dm_type = 'foo'
_skcriteria_parameters = ['x']
def __init__(self, x):
pass
class Foo(Base):
def __init__(self, x):
pass
assert (Foo._skcriteri... |
class Solution():
def isNumber(self, s: str) -> bool:
s = s.lower()
state = [{}, {'blank': 1, 'sign': 2, 'digit': 3, '.': 4}, {'digit': 3, '.': 4}, {'digit': 3, '.': 5, 'e': 6, 'blank': 9}, {'digit': 5}, {'digit': 5, 'e': 6, 'blank': 9}, {'sign': 7, 'digit': 8}, {'digit': 8}, {'digit': 8, 'blank': 9... |
class Model2onnx(Callback):
def __init__(self, saved_model_path: str, metadata: dict=None, save_on_epoch_end: bool=False) -> None:
super().__init__()
self.saved_model_path = saved_model_path
self.metadata = metadata
self.save_on_epoch_end = save_on_epoch_end
try:
... |
def convert_heads_to_classy_model(state_dict, out_prefix, num_fc_layers, use_bn_head=False, use_bias_head_fc=True):
logger.info('Converting head...')
converted_dict = {'block3-2': {'default_head': {}}}
if (num_fc_layers > 1):
out_dict = {}
for idx in range((num_fc_layers - 1)):
l... |
def test_asking_qm_questions():
type_ = '_quservice._tcp.local.'
zeroconf = r.Zeroconf(interfaces=['127.0.0.1'])
old_send = zeroconf.async_send
first_outgoing = None
def send(out, addr=const._MDNS_ADDR, port=const._MDNS_PORT):
nonlocal first_outgoing
if (first_outgoing is None):
... |
def formatAll(list, width=79):
text = '__all__ = ['
indent = len(text)
limit = (width - indent)
length = 0
for item in list:
length += (len(item) + 4)
if (length > limit):
text += ('\n' + (' ' * indent))
length = (len(item) + 4)
text += (('"' + item) +... |
def main(args):
wav_scp = codecs.open((Path(args.path) / 'wav.scp'), 'r', 'utf-8')
textgrid_flist = codecs.open((Path(args.path) / 'textgrid.flist'), 'r', 'utf-8')
utt2textgrid = {}
for line in textgrid_flist:
path = Path(line.strip())
uttid = path.stem
utt2textgrid[uttid] = path... |
('/add/host_group', methods=['POST'])
_wrapper_json
_web_opration_log('add_host', get_op_info=add_host_group_log)
def add_host_group():
params = request.get_json(force=True)
(group_name, group_type, hosts) = _check_and_format_params(params['group_name'], params['hosts'])
HostGroupConfDal.add_host_group(grou... |
def _find_vcvarsall(plat_spec):
(_, best_dir) = _find_vc2017()
if (not best_dir):
(best_version, best_dir) = _find_vc2015()
if (not best_dir):
log.debug('No suitable Visual C++ version found')
return (None, None)
vcvarsall = os.path.join(best_dir, 'vcvarsall.bat')
if (not os.... |
def test_force_locale_with_threading():
app = flask.Flask(__name__)
babel.Babel(app, locale_selector=(lambda : 'de_DE'))
semaphore = Semaphore(value=0)
def first_request():
with app.test_request_context():
with babel.force_locale('en_US'):
assert (str(babel.get_locale... |
def build_and_predict_model(ml_input_df):
import cudf
feature_names = (['college_education', 'male'] + [('clicks_in_%d' % i) for i in range(1, 8)])
X = ml_input_df[feature_names]
X = ((X - X.mean()) / X.std())
y = ml_input_df['clicks_in_category']
if isinstance(ml_input_df, cudf.DataFrame):
... |
def test_create_group_deploy_token(gitlab_cli, group):
name = 'group-token'
username = 'root'
expires_at = '2021-09-09'
scopes = 'read_registry'
cmd = ['-v', 'group-deploy-token', 'create', '--group-id', group.id, '--name', name, '--username', username, '--expires-at', expires_at, '--scopes', scopes... |
class BCNet(nn.Module):
def __init__(self, v_dim, q_dim, h_dim, h_out, act='ReLU', dropout=[0.2, 0.5], k=3):
super(BCNet, self).__init__()
self.c = 32
self.k = k
self.v_dim = v_dim
self.q_dim = q_dim
self.h_dim = h_dim
self.h_out = h_out
self.v_net = F... |
class NameInferenceError(InferenceError):
def __init__(self, message: str='{name!r} not found in {scope!r}.', name: (str | None)=None, scope: (nodes.LocalsDictNodeNG | None)=None, context: (InferenceContext | None)=None, **kws: Any) -> None:
self.name = name
self.scope = scope
self.context =... |
def build_filter_query(key, values):
if (not values):
return ''
if key.startswith('~#'):
nheader = key[2:]
queries = [f'#({nheader} = {i})' for i in values]
if (len(queries) > 1):
return ('|(%s)' % ', '.join(queries))
else:
return queries[0]
el... |
def flag_str(event_name, field_name, value):
string = ''
if flag_fields[event_name][field_name]:
print_delim = 0
for idx in sorted(flag_fields[event_name][field_name]['values']):
if ((not value) and (not idx)):
string += flag_fields[event_name][field_name]['values'][i... |
def versions_from_parentdir(parentdir_prefix, root, verbose):
rootdirs = []
for i in range(3):
dirname = os.path.basename(root)
if dirname.startswith(parentdir_prefix):
return {'version': dirname[len(parentdir_prefix):], 'full-revisionid': None, 'dirty': False, 'error': None, 'date':... |
def init_pretrained_weights(model, model_url):
pretrain_dict = model_zoo.load_url(model_url)
model_dict = model.state_dict()
pretrain_dict = {k: v for (k, v) in pretrain_dict.items() if ((k in model_dict) and (model_dict[k].size() == v.size()))}
model_dict.update(pretrain_dict)
model.load_state_dict... |
def cli_main(modify_parser=None):
parser = options.get_training_parser()
args = options.parse_args_and_arch(parser, modify_parser=modify_parser)
if args.profile:
with torch.cuda.profiler.profile():
with torch.autograd.profiler.emit_nvtx():
distributed_utils.call_main(args... |
def get_data(relative_path: str) -> str:
from pkg_resources import resource_filename
fn = resource_filename('qubekit', os.path.join('data', relative_path))
if (not os.path.exists(fn)):
raise ValueError(f"{relative_path} does not exist. If you have just added it, you'll have to re-install")
retur... |
def measure_rss_deltas(rss_deltas: List[int], interval: timedelta=_DEFAULT_MEASURE_INTERVAL) -> Generator[(None, None, None)]:
baseline_rss_bytes = psutil.Process().memory_info().rss
stop_event = Event()
thread = Thread(target=_measure, args=(rss_deltas, interval, baseline_rss_bytes, stop_event))
thread... |
_canonicalize
_rewriter([pt_abs])
def local_abs_lift(fgraph, node):
if ((node.op == pt_abs) and node.inputs[0].owner):
assert (node.nin == 1)
if (node.inputs[0].owner.op == mul):
return [mul(*[pt_abs(i) for i in node.inputs[0].owner.inputs])]
if (node.inputs[0].owner.op == true_d... |
def test_history_expanded_with_invalid_options(base_app):
options_to_test = ['-r', '-e', '-o file', '-t file', '-c']
for opt in options_to_test:
(out, err) = run_cmd(base_app, ('history -x ' + opt))
assert (len(out) == 4)
assert (out[0] == '-s and -x cannot be used with -c, -r, -e, -o, o... |
def _fit_desoto_sandia_diode(ee, voc, vth, tc, specs, const):
try:
import statsmodels.api as sm
except ImportError:
raise ImportError('Parameter extraction using Sandia method requires statsmodels')
x = ((specs['cells_in_series'] * vth) * np.log((ee / const['E0'])))
y = (voc - (specs['be... |
def run_unittests(project_path, dirs=[], coverage=False):
if (not coverage):
run_command(_Python_path, os.path.join(project_path, 'test', 'runtest.py'), '-verbose', str((_Verbose + 1)), '-clean', '-pre', *dirs)
else:
run_command(_Coverage, '-x', os.path.join(project_path, 'test', 'runtest.py'), ... |
def all_inputs_are_scalar(node):
ndims_input = [inp.type.ndim for inp in node.inputs]
are_inputs_scalars = True
for ndim in ndims_input:
try:
if (ndim > 0):
are_inputs_scalars = False
except TypeError:
are_inputs_scalars = False
return are_inputs_s... |
def get_constraints(total: Optional[int]=None, chunksize: Optional[int]=None, sequential_threshold: int=1, max_depth: Optional[int]=None, max_size: Optional[int]=None, max_leaves: Optional[int]=None, branch_factor: int=2) -> TreeConstraints:
cls = TreeConstraintsSize
if (total is None):
if (chunksize is... |
def test_files_reordered_when_seed_not_reset(ourtester):
code = '\n def test_it():\n pass\n '
ourtester.makepyfile(test_a=code, test_b=code, test_c=code, test_d=code)
args = ['-v', '--randomly-seed=15']
args.append('--randomly-dont-reset-seed')
out = ourtester.runpytest(*args)
... |
class AffineMul(torch.autograd.Function):
def forward(ctx, input, gamma, row_rank, col_rank, ddp_rank, model_parallel_size, dim, dtype):
with torch.no_grad():
if (row_rank == 0):
gamma_temp = gamma.clone()
else:
gamma_temp = torch.zeros(dim, dtype=dtyp... |
class Settlement(Resource):
def __init__(self, client=None):
super(Settlement, self).__init__(client)
self.base_url = (URL.V1 + URL.SETTLEMENT_URL)
def all(self, data={}, **kwargs):
return super(Settlement, self).all(data, **kwargs)
def fetch(self, settlement_id, data={}, **kwargs):
... |
_canonicalize
_stabilize
_rewriter([Blockwise])
def cholesky_ldotlt(fgraph, node):
if (not isinstance(node.op.core_op, Cholesky)):
return
A = node.inputs[0]
if (not ((A.owner is not None) and ((isinstance(A.owner.op, (Dot, Dot22)) and (A.owner.inputs[0].type.ndim == 2)) or (A.owner.op == _matrix_mat... |
class PlaneWaveHamiltonianTest(unittest.TestCase):
def test_plane_wave_hamiltonian_integration(self):
length_set = [2, 3, 4]
spinless_set = [True, False]
length_scale = 1.1
for geometry in [[('H', (0,)), ('H', (0.8,))], [('H', (0.1,))], [('H', (0.1,))]]:
for l in length_s... |
class Timer(Signal):
def __init__(self, interval=1.0, oneshot=True):
Signal.__init__(self)
self.interval = interval
self.oneshot = oneshot
self._timeout = 0
def interval():
def fget(self):
return self._interval
def fset(self, value):
if (no... |
def config_optimizer(optimizer_name, learning_rate, decay=0.9, momentum=0.9):
if (optimizer_name == 'momentum'):
return tf.train.MomentumOptimizer(learning_rate, momentum=momentum)
elif (optimizer_name == 'rmsprop'):
return tf.train.RMSPropOptimizer(learning_rate, decay=decay, momentum=momentum)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.