code stringlengths 281 23.7M |
|---|
def draw_paths_horizontal(times, paths, N, expectations, title=None, KDE=False, marginal=False, marginalT=None, envelope=False, lower=None, upper=None, style='seaborn-v0_8-whitegrid', colormap='RdYlBu_r', **fig_kw):
with plt.style.context(style):
if marginal:
fig = plt.figure(**fig_kw)
... |
def test_channel_update_traces():
with expected_protocol(AnritsuMS464xB, [(':CALC1:PAR:COUN?', '4'), (':CALC1:PAR:COUN?', '12')]) as instr:
assert (len(instr.ch_1.traces) == 16)
instr.ch_1.update_traces()
assert (len(instr.ch_1.traces) == 4)
instr.ch_1.update_traces()
assert ... |
class CheckpointHandler():
def __init__(self, coordinator_args: CoordinatorArguments, collab_optimizer_args: CollaborativeOptimizerArguments, averager_args: AveragerArguments, dht: hivemind.DHT):
self.save_checkpoint_step_interval = coordinator_args.save_checkpoint_step_interval
self.repo_path = coo... |
def type_check_config_vars(tempdir, config_name):
f = open(path.join(tempdir, (config_name + '.pyi')), 'w')
f.write(confreader.config_pyi_header)
for (name, type_) in confreader.Config.__annotations__.items():
f.write(name)
f.write(': ')
f.write(type_)
f.write('\n')
f.clo... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--data_dir', default=None, type=str, required=True, help='The input data dir. Should contain the .tsv files (or other data files) for the task.')
parser.add_argument('--bert_model', default=None, type=str, required=True, help='Bert pre-trai... |
def test(config, env, agent, batch_size, word2id):
agent.model.eval()
(obs, infos) = env.reset()
agent.reset(infos)
(print_command_string, print_rewards) = ([[] for _ in infos], [[] for _ in infos])
print_interm_rewards = [[] for _ in infos]
provide_prev_action = config['general']['provide_prev_... |
def do_virtual_scan(cat_dir, worker_id, num_workers):
object_folders = [dir for dir in os.listdir(cat_dir)]
object_folders.sort()
print(('#Model: %d' % len(object_folders)))
worker_size = int(math.ceil((len(object_folders) / num_workers)))
print(('Worker size: ' + str(worker_size)))
start_idx = ... |
class Pix2PixHDModel(BaseModel):
def name(self):
return 'Pix2PixHDModel'
def init_loss_filter(self, use_gan_feat_loss, use_vgg_loss, use_l1_image_loss):
flags = (True, use_gan_feat_loss, use_vgg_loss, use_l1_image_loss, True, True)
def loss_filter(g_gan, g_gan_feat, g_vgg, g_image, d_rea... |
def assert_dataframe_equality(output_df: DataFrame, target_df: DataFrame) -> None:
if (not ((output_df.count() == target_df.count()) and (len(target_df.columns) == len(output_df.columns)))):
raise AssertionError(f'''DataFrame shape mismatch:
output_df shape: {len(output_df.columns)} columns and {output_df.... |
def _append_sha1_hash_to_table(table: pa.Table, hash_column: pa.Array) -> pa.Table:
hash_column_np = hash_column.to_numpy()
result = []
for hash_value in hash_column_np:
assert (hash_value is not None), f'Expected non-null primary key'
result.append(hashlib.sha1(hash_value.encode('utf-8')).h... |
class Registry(dict):
def __init__(self, *args, **kwargs):
super(Registry, self).__init__(*args, **kwargs)
def register(self, module_name, module=None):
if (module is not None):
_register_generic(self, module_name, module)
return
def register_fn(fn):
_... |
def load_network(ckpt):
g_running = StyledGenerator(code_size).cuda()
discriminator = Discriminator(from_rgb_activate=True).cuda()
ckpt = torch.load(ckpt)
g_running.load_state_dict(ckpt['g_running'])
discriminator.load_state_dict(ckpt['discriminator'])
return (g_running, discriminator) |
class PlayBlockChange(Packet):
id = 11
to = 1
def __init__(self, x: int, y: int, z: int, block_id: int) -> None:
super().__init__()
(self.x, self.y, self.z) = (x, y, z)
self.block_id = block_id
def encode(self) -> bytes:
return (Buffer.pack_position(self.x, self.y, self.z... |
def aes_encrypt(word, key=config.aes_key, iv=None, output='base64', padding=True, padding_style='pkcs7', mode=AES.MODE_CBC, no_packb=False):
if (iv is None):
iv = Crypto_random.read(16)
if (not no_packb):
word = umsgpack.packb(word)
if padding:
word = pad(word, AES.block_size, paddin... |
def solve_euclidian_tsp(points, threads=0, timeout=None, gap=None):
n = len(points)
def subtourelim(model, where):
if (where == GRB.Callback.MIPSOL):
vals = model.cbGetSolution(model._vars)
selected = tuplelist(((i, j) for (i, j) in model._vars.keys() if (vals[(i, j)] > 0.5)))
... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--K', type=int, default=1)
parser.add_argument('--N', type=int, default=1)
parser.add_argument('--n_epoch', type=int, default=200)
parser.add_argument('--batch_size', type=int, default=100)
parser.add_argument('--hidden_add_nois... |
class SecurityListTestCase(WithMakeAlgo, ZiplineTestCase):
START_DATE = pd.Timestamp('2002-01-03', tz='UTC')
assert (START_DATE == sorted(list(LEVERAGED_ETFS.keys()))[0]), 'START_DATE should match start of LEVERAGED_ETF data.'
END_DATE = pd.Timestamp('2015-02-17', tz='utc')
extra_knowledge_date = pd.Tim... |
def _create_channels(channels, h5f, resolution):
for channel in channels:
var_name = ('IMG_' + channel.upper())
var = h5f.create_variable(var_name, (('time',) + dimensions_by_resolution[resolution]), np.uint16, chunks=chunks_1km)
var[:] = values_by_resolution[resolution]
var.attrs['_... |
def find_lr(net, trn_loader, optimizer, loss_fn, init_value=1e-08, final_value=10.0, beta=0.98, device='cuda:1'):
num = (len(trn_loader) - 1)
mult = ((final_value / init_value) ** (1 / num))
lr = init_value
optimizer.param_groups[0]['lr'] = lr
avg_loss = 0.0
best_loss = 0.0
batch_num = 0
... |
def matchPreviousExpr(expr):
rep = Forward()
e2 = expr.copy()
rep <<= e2
def copyTokenToRepeater(s, l, t):
matchTokens = _flatten(t.asList())
def mustMatchTheseTokens(s, l, t):
theseTokens = _flatten(t.asList())
if (theseTokens != matchTokens):
rai... |
class SingleTimeEvent(TimeEvent):
_datetimes_to_data = {}
def schedule_new_event(cls, date_time: datetime, data: Any):
if (date_time not in cls._datetimes_to_data.keys()):
cls._datetimes_to_data[date_time] = data
else:
raise ValueError('Event associated with the given dat... |
.parametrize(('shapes', 'chunks', 'dims', 'exp_unified'), [(((3, 5, 5), (5, 5)), ((- 1), (- 1)), (('bands', 'y', 'x'), ('y', 'x')), True), (((3, 5, 5), (5, 5)), ((- 1), 2), (('bands', 'y', 'x'), ('y', 'x')), True), (((4, 5, 5), (3, 5, 5)), ((- 1), (- 1)), (('bands', 'y', 'x'), ('bands', 'y', 'x')), False)])
def test_un... |
def get_editor_args(fallback_command='nano'):
if ('VISUAL' in os.environ):
editor = os.environ['VISUAL']
elif ('EDITOR' in os.environ):
editor = os.environ['EDITOR']
elif shutil.which('editor'):
editor = 'editor'
else:
editor = fallback_command
try:
editor_arg... |
class banner(scan):
def __init__(self, job, timeout=10):
scan.__init__(self, job)
setattr(self, 'datasize', 0)
if (len(job) > 1):
self.type = job[0].split('|')[1]
self.port = job[0].split('|')[2]
self.scan_type = _whats_your_name()
if (timeout >= 60):
... |
def test_solar_noon():
index = pd.date_range(start='T1200', freq='1s', periods=1)
apparent_zenith = pd.Series([10], index=index)
apparent_azimuth = pd.Series([180], index=index)
tracker_data = tracking.singleaxis(apparent_zenith, apparent_azimuth, axis_tilt=0, axis_azimuth=0, max_angle=90, backtrack=Tru... |
def upgrade(saveddata_engine):
sql = '\n DELETE FROM modules WHERE ID IN\n (\n SELECT m.ID FROM modules AS m\n JOIN fits AS f ON m.fitID = f.ID\n WHERE f.shipID IN ("35832", "35833", "35834", "40340")\n AND m.projected = 1\n )\n '
saveddata_engine.execute(sql) |
def test_membership_with_multiple_payments():
with time_machine.travel('2020-10-10 10:00:00', tick=False):
membership_1 = MembershipFactory(status=MembershipStatus.ACTIVE)
membership_1.add_pretix_payment(organizer='python-italia', event='pycon-demo', order_code='XXYYZZ', total=1000, status=PaymentSt... |
def subscription_registry():
registry = SubscriptionRegistry()
server = mock.create_autospec(HTTPServer, instance=True)
server.server_address = ('localhost', 8989)
with mock.patch('pywemo.subscribe._start_server', return_value=server):
registry.start()
(yield registry)
registry.stop(... |
class BashcompExtractor(FileExtractor):
filename = os.path.join(BPFTOOL_DIR, 'bash-completion/bpftool')
def get_prog_attach_types(self):
return self.get_bashcomp_list('BPFTOOL_PROG_ATTACH_TYPES')
def get_map_types(self):
return self.get_bashcomp_list('BPFTOOL_MAP_CREATE_TYPES')
def get_c... |
def model_to_test_downstream_masks():
inputs = tf.keras.Input(shape=(8, 8, 3))
x = tf.keras.layers.Conv2D(8, (2, 2), activation=tf.nn.relu)(inputs)
residual = x
x = tf.keras.layers.Conv2D(8, (1, 1))(x)
x = (x + residual)
x = tf.keras.layers.BatchNormalization(momentum=0.3, epsilon=0.65)(x)
x... |
class AttrVI_ATTR_BUFFER(Attribute):
resources = [constants.EventType.io_completion]
py_name = 'buffer'
visa_name = 'VI_ATTR_BUFFER'
visa_type = 'ViBuf'
default = NotAvailable
(read, write, local) = (True, False, True)
def __get__(self, instance: Optional['IOCompletionEvent'], owner) -> Opti... |
class Migration(migrations.Migration):
dependencies = [('core', '0010_tag_active')]
operations = [migrations.AddField(model_name='currentsong', name='stream_url', field=models.CharField(blank=True, max_length=2000)), migrations.AddField(model_name='queuedsong', name='stream_url', field=models.CharField(blank=Tr... |
def train(array, num_epochs=50, use_global_sort_loss=False, use_global_unique_index_loss=False, local_sort_loss_windows=[2, 3, 4], local_unique_index_loss_windows=[2, 3, 4], verbose=True):
metadata = Metadata(array)
size = len(array)
model = Net(size)
if verbose:
print_array_diagnostics(array, a... |
def test_xfail_skipif_with_globals(pytester: Pytester) -> None:
pytester.makepyfile('\n import pytest\n x = 3\n .skipif("x == 3")\n def test_skip1():\n pass\n .xfail("x == 3")\n def test_boolean():\n assert 0\n ')
result = pytester.runpytest('-r... |
def parse_args():
parser = argparse.ArgumentParser(description='Print the whole config')
parser.add_argument('config', help='config file path')
parser.add_argument('--graph', action='store_true', help='print the models graph')
parser.add_argument('--options', nargs='+', action=DictAction, help='argument... |
def test_laneposition():
pos = OSC.LanePosition(1, 2, lane_id=1, road_id=2)
prettyprint(pos.get_element())
pos2 = OSC.LanePosition(1, 2, lane_id=1, road_id=2)
pos3 = OSC.LanePosition(1, 1, lane_id=(- 1), road_id=2)
assert (pos == pos2)
assert (pos != pos3)
pos4 = OSC.LanePosition.parse(pos.g... |
def test_cmdstep_runstep_cmd_is_string_formatting_shell_true():
obj = CmdStep('blahname', Context({'k1': 'blah', 'cmd': '{k1} -{k1}1 --{k1}2'}), is_shell=True)
assert obj.is_shell
assert (obj.logger.name == 'blahname')
assert (obj.context == Context({'k1': 'blah', 'cmd': '{k1} -{k1}1 --{k1}2'}))
ass... |
def check_prox_impl(func, values, step=0.5, rtol=1e-05, atol=1e-05, behavior='ret', verbosity=0, opt_kws={}):
assert (behavior in ['ret', 'error', 'warn'])
errors = []
passes = []
for (i, x) in enumerate(values):
prox_out = func.prox(x=x, step=step)
(prox_baseline, opt_out) = numeric_pro... |
class Nurbs(VersionBase):
def __init__(self, order):
self.order = convert_int(order)
self.controlpoints = []
self.knots = []
def __eq__(self, other):
if isinstance(other, Nurbs):
if ((self.get_attributes() == other.get_attributes()) and (self.controlpoints == other.co... |
def read_lexiconp(filename):
ans = []
found_empty_prons = False
found_large_pronprobs = False
whitespace = re.compile('[ \t]+')
with open(filename, 'r', encoding='latin-1') as f:
for line in f:
a = whitespace.split(line.strip(' \t\r\n'))
if (len(a) < 2):
... |
def test_cache_get_hit_no_cache(no_cache):
cache = Cache()
creator_mock = MagicMock()
creator_mock.side_effect = ['created obj1', 'created obj2', 'created obj3', 'created obj4']
with patch_logger('pypyr.cache', logging.DEBUG) as mock_logger_debug:
obj1 = cache.get('one', (lambda : creator_mock('... |
class MessageManager(models.Manager):
def compose(self, sender, recipient, body):
if (not sender.can_send_message(recipient)):
return False
has_receipt = (sender.allow_receipts and recipient.allow_receipts)
message = self.create(sender=sender, recipient=recipient, body=body, has_... |
class BERTAdam(Optimizer):
def __init__(self, params, lr, warmup=(- 1), t_total=(- 1), schedule='warmup_linear', b1=0.9, b2=0.999, e=1e-06, weight_decay_rate=0.01, max_grad_norm=1.0):
if (not (lr >= 0.0)):
raise ValueError('Invalid learning rate: {} - should be >= 0.0'.format(lr))
if (sc... |
def rescale_abscoeff(spec, rescaled, initial, old_mole_fraction, new_mole_fraction, old_path_length_cm, wunit, units, extra, true_path_length, assume_equilibrium):
if __debug__:
printdbg(f'recomputing `abscoeff` from initial {initial} and already rescaled {list(rescaled.keys())}, knowing `old_mole_fraction=... |
def test_transform_types_params_array():
data = {'attr': [1, 2, 3]}
custom_types = {'attr': types.ArrayAttribute}
(new_data, files) = utils._transform_types(data, custom_types, transform_data=True)
assert (new_data is not data)
assert (new_data == {'attr[]': [1, 2, 3]})
assert (files == {}) |
def main(args):
if (args.cuda and torch.cuda.is_available()):
device = torch.device('cuda:0')
else:
device = torch.device('cpu')
(init_dict, train_dict, test_dict) = prepare_data(args.data_loc, args.num_init, args.num_total, test_is_year=False, seed=args.seed)
(init_x, init_y, init_y_var... |
class TranslationConfig(FairseqDataclass):
data: Optional[str] = field(default=None, metadata={'help': 'colon separated path to data directories list, will be iterated upon during epochs in round-robin manner; however, valid and test data are always in the first directory to avoid the need for repeating them in all... |
def make_nspkg_sdist(dist_path, distname, version):
parts = distname.split('.')
nspackage = parts[0]
packages = ['.'.join(parts[:idx]) for idx in range(1, (len(parts) + 1))]
setup_py = DALS((' import setuptools\n setuptools.setup(\n name=%r,\n version=%r,\n ... |
class TransformerDecoderLayer3Add(nn.Module):
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation='relu', normalize_before=False):
super().__init__()
self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
self.text_cross_attn = nn.MultiheadAttent... |
def _format_index(data):
tz_raw = data.columns[1]
timezone = TZ_MAP.get(tz_raw, tz_raw)
datetime = (data['DATE (MM/DD/YYYY)'] + data[tz_raw])
datetime = pd.to_datetime(datetime, format='%m/%d/%Y%H:%M')
data = data.set_index(datetime)
data = data.tz_localize(timezone)
return data |
class Caltech101(DatasetBase):
dataset_dir = 'caltech-101'
def __init__(self, root, num_shots):
self.dataset_dir = os.path.join(root, self.dataset_dir)
self.image_dir = os.path.join(self.dataset_dir, '101_ObjectCategories')
self.split_path = os.path.join(self.dataset_dir, 'split_zhou_Cal... |
class ModuleIdentifierOpInfo():
def __init__(self, module_name, op_type, tf_op, pattern_type: str=None, internal_ops: List[tf.Operation]=None):
self._module_name = module_name
self._op_type = op_type
self._tf_op = tf_op
self._pattern_type = pattern_type
self._attributes = {}
... |
class TransformerEncoderBlock(nn.Sequential):
def __init__(self, emb_size=80, drop_p=0.5, forward_expansion=4, forward_drop_p=0.0, **kwargs):
super().__init__(ResidualAdd(nn.Sequential(nn.LayerNorm(emb_size), MultiHeadAttention(emb_size, **kwargs), nn.Dropout(drop_p))), ResidualAdd(nn.Sequential(nn.LayerNor... |
def test_date_and_delta() -> None:
now = dt.datetime.now()
td = dt.timedelta
int_tests = (3, 29, 86399, 86400, (86401 * 30))
date_tests = [(now - td(seconds=x)) for x in int_tests]
td_tests = [td(seconds=x) for x in int_tests]
results = [((now - td(seconds=x)), td(seconds=x)) for x in int_tests]... |
class MemoryCgroupCollector(diamond.collector.Collector):
def process_config(self):
super(MemoryCgroupCollector, self).process_config()
self.memory_path = self.config['memory_path']
self.skip = self.config['skip']
if (not isinstance(self.skip, list)):
self.skip = [self.sk... |
def _build_vectors():
count = 0
output = []
key = None
plaintext = binascii.unhexlify((32 * '0'))
for size in _SIZES_TO_GENERATE:
for keyinfo in _RFC6229_KEY_MATERIALS:
key = _key_for_size(size, keyinfo)
cipher = ciphers.Cipher(algorithms.ARC4(binascii.unhexlify(key))... |
class WaveformSeekBar(Gtk.Box):
def __init__(self, player, library):
super().__init__()
self._player = player
self._rms_vals = []
self._hovering = False
self._elapsed_label = TimeLabel()
self._remaining_label = TimeLabel()
self._waveform_scale = WaveformScale(... |
class MultiHeadedAttention(nn.Module):
def __init__(self, num_heads: int, dim_model: int, dropout: float=0.1, device: Optional[torch.device]=None) -> None:
super().__init__()
assert ((dim_model % num_heads) == 0)
self.d_k: int = (dim_model // num_heads)
self.num_heads = num_heads
... |
def test_pyright_baseline():
test_file = (Path(__file__).parent / 'dataclass_transform_example.py')
diagnostics = parse_pyright_output(test_file)
expected_diagnostics = {PyrightDiagnostic(severity='information', message='Type of "Define.__init__" is "(self: Define, a: str, b: int) -> None"'), PyrightDiagnos... |
def main(argv):
lr_start = FLAGS.start_lr
lr_end = FLAGS.end_lr
epochs = FLAGS.epochs
multiplier = ((lr_end / lr_start) ** (1 / epochs))
decayed_lr = [(lr_start * (multiplier ** x)) for x in range(epochs)]
train_kargs = {'epochs': epochs, 'learning_rate': decayed_lr}
directory = FLAGS.model_... |
def t2_circuit_execution() -> Tuple[(qiskit.result.Result, np.array, List[int], float)]:
num_of_gates = np.linspace(1, 30, 10).astype(int)
gate_time = 0.11
qubits = [0]
n_echos = 5
alt_phase_echo = True
(circs, xdata) = t2_circuits(num_of_gates, gate_time, qubits, n_echos, alt_phase_echo)
t2... |
def compute_value_of_function(info: FunctionInfo, ctx: Context, *, result: Optional[Value]=None) -> Value:
if (result is None):
result = info.return_annotation
if (result is None):
result = AnyValue(AnySource.unannotated)
if isinstance(info.node, ast.AsyncFunctionDef):
visitor = IsGe... |
class BrowserBasedOAuth1(BaseOAuth1):
REQUEST_TOKEN_URL = ''
OAUTH_TOKEN_PARAMETER_NAME = 'oauth_token'
REDIRECT_URI_PARAMETER_NAME = 'redirect_uri'
ACCESS_TOKEN_URL = ''
def auth_url(self):
return self.unauthorized_token_request()
def get_unauthorized_token(self):
return self.st... |
def _unpack_iterable_of_pairs(val: Value, ctx: CanAssignContext) -> Union[(Sequence[KVPair], CanAssignError)]:
concrete = concrete_values_from_iterable(val, ctx)
if isinstance(concrete, CanAssignError):
return concrete
if isinstance(concrete, Value):
vals = unpack_values(concrete, ctx, 2)
... |
def load_manage_dict(filename=None):
manage_filename = None
if (not MANAGE_DICT):
if filename:
manage_filename = filename
elif os.path.exists(MANAGE_FILE):
manage_filename = MANAGE_FILE
elif os.path.exists(HIDDEN_MANAGE_FILE):
manage_filename = HIDDEN_... |
def copy_model(src_model_name, tgt_model_name):
src_model_path = get_model_path(src_model_name)
model_dir = (Path(__file__).parent / 'pretrained')
tgt_model_path = (model_dir / tgt_model_name)
assert (not tgt_model_path.exists()), (('provided model name ' + tgt_model_name) + ' has already exist. Conside... |
def _infer_instance_from_annotation(node: nodes.NodeNG, ctx: (context.InferenceContext | None)=None) -> Iterator[(UninferableBase | bases.Instance)]:
klass = None
try:
klass = next(node.infer(context=ctx))
except (InferenceError, StopIteration):
(yield Uninferable)
if (not isinstance(kla... |
class ConvertToTranscribedDataTest(unittest.TestCase):
def test_convert_to_transcribed_data(self):
result_aligned = {'segments': [{'words': [{'word': 'UltraSinger', 'start': 1.23, 'end': 2.34, 'confidence': 0.95}, {'word': 'is', 'start': 2.34, 'end': 3.45, 'confidence': 0.9}, {'word': 'cool!', 'start': 3.45... |
def makeUpdateMatrix(qnnArch, unitaries, trainingData, storedStates, lda, ep, l, j):
numInputQubits = qnnArch[(l - 1)]
summ = 0
for x in range(len(trainingData)):
firstPart = updateMatrixFirstPart(qnnArch, unitaries, storedStates, l, j, x)
secondPart = updateMatrixSecondPart(qnnArch, unitari... |
_grad()
def convert_s3prl_checkpoint(base_model_name, config_path, checkpoint_path, model_dump_path):
checkpoint = torch.load(checkpoint_path, map_location='cpu')
if (checkpoint['Config']['downstream_expert']['modelrc']['select'] not in SUPPORTED_MODELS):
raise NotImplementedError(f'The supported s3prl ... |
def _get_new_season_shows(config, db):
handlers = services.get_link_handlers()
for site in db.get_link_sites():
if (site.key not in handlers):
warning('Link site handler for {} not installed'.format(site.key))
continue
handler = handlers.get(site.key)
info(' Chec... |
def get_path_iterator(tsv, nshard, rank):
with open(tsv, 'r') as f:
root = f.readline().rstrip()
lines = [line.rstrip() for line in f]
tot = len(lines)
shard_size = math.ceil((tot / nshard))
(start, end) = ((rank * shard_size), min(((rank + 1) * shard_size), tot))
ass... |
def vcf_fields(category, max_number):
return builds(Field, category=just(category), vcf_key=vcf_field_keys(category), vcf_type=vcf_types(category), vcf_number=vcf_numbers(category, max_number)).filter((lambda field: (((field.vcf_type == 'Flag') and (field.vcf_number == '0')) or ((field.vcf_type != 'Flag') and (fiel... |
def log_stats_finegrainedness(nodes, get_leaves_fn, get_lowest_common_ancestor_fn, graph_name=None, num_per_height_to_print=2, num_leaf_pairs=10000, path='longest'):
logging.info('Finegrainedness analysis of %s graph using %s paths in finding the lowest common ancestor.', graph_name, path)
leaves = get_leaves_f... |
def log_returns(returns, benchmark=None, grayscale=False, figsize=(10, 5), fontname='Arial', lw=1.5, match_volatility=False, compound=True, cumulative=True, resample=None, ylabel='Cumulative Returns', subtitle=True, savefig=None, show=True, prepare_returns=True):
title = ('Cumulative Returns' if compound else 'Retu... |
def test_resnest_backbone():
with pytest.raises(KeyError):
ResNeSt(depth=18)
model = ResNeSt(depth=50, radix=2, reduction_factor=4, out_indices=(0, 1, 2, 3))
model.init_weights()
model.train()
imgs = torch.randn(2, 3, 224, 224)
feat = model(imgs)
assert (len(feat) == 4)
assert (f... |
def get_ner_fmeasure(golden_lists, predict_lists, label_type='BMES'):
sent_num = len(golden_lists)
golden_full = []
predict_full = []
right_full = []
right_tag = 0
all_tag = 0
for idx in range(0, sent_num):
golden_list = golden_lists[idx]
predict_list = predict_lists[idx]
... |
def get_args_parser():
parser = argparse.ArgumentParser('Prepare images of trash for detection task')
parser.add_argument('--dataset_dest', help='paths to annotations', nargs='+', default=['annotations/annotations-epi.json'])
parser.add_argument('--split_dest', help='path to destination directory', default=... |
class IntelHexError(Exception):
_fmt = 'IntelHex base error'
def __init__(self, msg=None, **kw):
self.msg = msg
for (key, value) in dict_items_g(kw):
setattr(self, key, value)
def __str__(self):
if self.msg:
return self.msg
try:
return (sel... |
def get_insaneDA_augmentation(dataloader_train, dataloader_val, patch_size, params=default_3D_augmentation_params, border_val_seg=(- 1), seeds_train=None, seeds_val=None, order_seg=1, order_data=3, deep_supervision_scales=None, soft_ds=False, classes=None, pin_memory=True, regions=None):
assert (params.get('mirror'... |
.parametrize('username,password', users)
def test_update_m2m(db, client, username, password):
client.login(username=username, password=password)
instances = Section.objects.all()
for instance in instances:
pages = [{'page': section_page.page_id, 'order': section_page.order} for section_page in insta... |
class LeaveGroupCall(Scaffold):
async def leave_group_call(self, chat_id: Union[(int, str)]):
if (self._app is None):
raise NoMTProtoClientSet()
if (not self._is_running):
raise ClientNotStarted()
chat_id = (await self._resolve_chat_id(chat_id))
chat_call = (a... |
def _avg_pool(name, tuple_fn):
_args('v', 'is', 'is', 'is', 'i', 'i', 'none')
def symbolic_fn(g, input, kernel_size, stride, padding, ceil_mode, count_include_pad, divisor_override=None):
padding = sym_help._avgpool_helper(tuple_fn, padding, kernel_size, stride, divisor_override, name)
if (not s... |
def reduce_by_error(logs, error_filter=None):
counter = Counter()
counter.update([x[1] for x in logs])
counts = counter.most_common()
r = {}
for (error, count) in counts:
if ((error_filter is None) or (error not in error_filter)):
r[error] = {'count': count, 'failed_tests': [(x[2... |
class IrreversibleBlock(nn.Module):
def __init__(self, f, g):
super().__init__()
self.f = f
self.g = g
def forward(self, x, f_args, g_args):
(x1, x2) = torch.chunk(x, 2, dim=1)
y1 = (x1 + self.f(x2, **f_args))
y2 = (x2 + self.g(y1, **g_args))
return torch.... |
class BinarySearchPredicate():
def __init__(self, A: int, B: int, tolerance: int) -> None:
self.left = A
self.right = B
self.tolerance = tolerance
self.first = True
def next(self, prior_result: bool) -> Optional[int]:
if ((self.right - self.left) < self.tolerance):
... |
def assert_psm3_equal(data, metadata, expected):
assert np.allclose(data.Year, expected.Year)
assert np.allclose(data.Month, expected.Month)
assert np.allclose(data.Day, expected.Day)
assert np.allclose(data.Hour, expected.Hour)
assert np.allclose(data.Minute, expected.Minute)
assert np.allclose... |
def postprocess_db_names(values, scheme, dict_values):
(table_names, col_names) = match_sql_db_names(scheme, dict_values)
new_values = []
for gk in values:
if (gk is not None):
if (gk.type == 'tbl'):
gk = GroundingKey.make_table_grounding(table_names[gk.keys[0]])
... |
class Metadata(Tags):
__module__ = 'mutagen'
def __init__(self, *args, **kwargs):
if (args or kwargs):
self.load(*args, **kwargs)
()
def load(self, filething, **kwargs):
raise NotImplementedError
(writable=False)
def save(self, filething=None, **kwargs):
raise... |
def pytest_runtestloop(session):
try:
from telegram.utils.deprecate import TelegramDeprecationWarning
session.add_marker(pytest.mark.filterwarnings('ignore::telegram.utils.deprecate.TelegramDeprecationWarning'))
except ImportError:
pass
try:
from telegram.warnings import PTBD... |
(frozen=True)
class ValueUnit():
value = attr.ib()
orig_value = attr.ib(kw_only=True)
tokenized_value = attr.ib(default=None, kw_only=True)
bert_tokens = attr.ib(default=None, kw_only=True)
value_type = attr.ib(default=None, kw_only=True)
column = attr.ib(default=None, kw_only=True)
table = ... |
def test_rouge(cand, ref_1, ref_2, ref_3):
current_time = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime())
tmp_dir = '.rouge-tmp-{}'.format(current_time)
try:
if (not os.path.isdir(tmp_dir)):
os.mkdir(tmp_dir)
os.mkdir((tmp_dir + '/candidate'))
os.mkdir((tmp_d... |
def load_app_and_run_server() -> None:
sys.path.append(os.getcwd())
shutdown_event = register_signal_handlers()
args = parse_args(sys.argv[1:])
with args.config_file:
config = read_config(args.config_file, args.server_name, args.app_name)
assert config.server
if is_metrics_enabled(config... |
(web_fixture=WebFixture)
class FileUploadInputFixture(Fixture):
def file_was_uploaded(self, filename):
return (Session.query(PersistedFile).filter_by(filename=os.path.basename(filename)).count() == 1)
file_to_upload1_name = 'file1.html'
file_to_upload2_name = 'file2.gif'
file_to_upload1_content ... |
class ConcatConv2d(nn.Conv2d, DiffEqModule):
def __init__(self, in_channels: int, out_channels: int, kernel_size: _size_2_t, stride: _size_2_t=1, padding: _size_2_t=0, dilation: _size_2_t=1, groups: int=1, bias: bool=True, padding_mode: str='zeros'):
super(ConcatConv2d, self).__init__(in_channels=(in_channe... |
def parse_lambda_config(x):
split = x.split(',')
if (len(split) == 1):
return (float(x), None)
else:
split = [s.split(':') for s in split]
assert all(((len(s) == 2) for s in split))
assert all((k.isdigit() for (k, _) in split))
assert all(((int(split[i][0]) < int(spli... |
class HfArgumentParser(ArgumentParser):
dataclass_types: Iterable[DataClassType]
def __init__(self, dataclass_types: Union[(DataClassType, Iterable[DataClassType])], **kwargs):
if ('formatter_class' not in kwargs):
kwargs['formatter_class'] = ArgumentDefaultsHelpFormatter
super().__i... |
def main():
parser = arguments.get_argument_parser()
opt = parser.parse_args()
if (not os.path.exists(opt.model_name)):
os.makedirs(opt.model_name)
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)
tb_logger.configure(opt.logger_name, flush_secs=5)
logger = loggin... |
def _get_tzd(timeinseconds=None):
if (timeinseconds is None):
timeinseconds = time.time()
tzd = time.strftime('%z', time.localtime(timeinseconds))
if Globals.use_compatible_timestamps:
time_separator = '-'
else:
time_separator = ':'
if (tzd == '+0000'):
return 'Z'
... |
def common_arg_parser():
parser = arg_parser()
parser.add_argument('--env', help='environment ID', type=str, default='Reacher-v2')
parser.add_argument('--seed', help='RNG seed', type=int, default=None)
parser.add_argument('--alg', help='Algorithm', type=str, default='ppo2')
(parser.add_argument('--n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.