code stringlengths 281 23.7M |
|---|
class Migration(migrations.Migration):
dependencies = [('sites', '0002_alter_domain_unique'), ('projects', '0026_django2')]
operations = [migrations.AlterModelManagers(name='project', managers=[('objects', django.db.models.manager.Manager()), ('on_site', django.contrib.sites.managers.CurrentSiteManager())]), mi... |
def parse_col(toks, start_idx, tables_with_alias, schema, default_tables=None):
tok = toks[start_idx]
if (tok == '*'):
return (start_idx + 1)
if ('.' in tok):
(alias, col) = tok.split('.')
table = tables_with_alias[alias]
if (table not in schema):
schema[table] = ... |
def get_criterion(p):
if (p['criterion'] == 'simclr'):
from losses.losses import SimCLRLoss
criterion = SimCLRLoss(**p['criterion_kwargs'])
elif (p['criterion'] == 'scan'):
from losses.losses import SCANLoss
criterion = SCANLoss(**p['criterion_kwargs'])
elif (p['criterion'] =... |
def change_yolov6m():
state_dict = OrderedDict()
stem = []
new_key_more = []
ckpt_state = ckpt['model'].state_dict()
for (key, weight) in ckpt['model'].state_dict().items():
new_key = ''
new_key_origin = key.split('.')[0:]
if (new_key_origin[1] == 'stem'):
new_key... |
class Meta():
def __init__(self, data):
self._meta = data.pop('meta', {})
self._links = data.pop('links', {})
self._included = data.pop('included', {})
def retrieve(self, data):
if (not self._included):
return data
return next(filter((lambda x: (x['id'] == dat... |
def test_run_step_groups_none_groups():
with pytest.raises(ValueError) as err:
StepsRunner(get_valid_test_pipeline(), Context()).run_step_groups(groups=None, success_group='arb success', failure_group='arb fail')
assert (str(err.value) == 'you must specify which step-groups you want to run. groups is No... |
def calc_loss(output, y, z_r):
y_masked = tf.where(z_r, y, (0 * tf.ones_like(y)))
y_masked_flat_refined = tf.reshape(y_masked, [(- 1), (IMAGE_HEIGHT * IMAGE_WIDTH)])
o_masked = tf.where(z_r, output, (0 * tf.ones_like(y)))
o_masked_flat_refined = tf.reshape(o_masked, [(- 1), (IMAGE_HEIGHT * IMAGE_WIDTH)]... |
class OpenIdStore(BaseOpenIDStore):
def __init__(self, strategy):
super().__init__()
self.strategy = strategy
self.storage = strategy.storage
self.assoc = self.storage.association
self.nonce = self.storage.nonce
self.max_nonce_age = ((6 * 60) * 60)
def storeAssoci... |
class TestAssert(TestNameCheckVisitorBase):
_passes()
def test_assert_never_fails(self):
def capybara():
tpl = ('this', "doesn't", 'work')
assert tpl
_passes()
def test_assert_bad_bool(self):
class X(object):
def __bool__(self):
raise E... |
((not torch.cuda.is_available()), 'test requires a GPU')
class TestGradientScalingAMP(unittest.TestCase):
def setUp(self):
self.x = torch.tensor([2.0]).cuda().half()
weight = 3.0
bias = 5.0
self.error = 1.0
self.target = torch.tensor([(((self.x * weight) + bias) + self.error)... |
('I set the section start type to {start_type}')
def when_I_set_the_section_start_type_to_start_type(context: Context, start_type: str):
new_start_type = {'None': None, 'CONTINUOUS': WD_SECTION.CONTINUOUS, 'EVEN_PAGE': WD_SECTION.EVEN_PAGE, 'NEW_COLUMN': WD_SECTION.NEW_COLUMN, 'NEW_PAGE': WD_SECTION.NEW_PAGE, 'ODD_... |
(scope='function')
def backend(request, backend_name, xephyr, wayland_session):
if (backend_name == 'x11'):
from test.backend.x11.conftest import XBackend
(yield XBackend({'DISPLAY': xephyr.display}, args=[xephyr.display]))
elif (backend_name == 'wayland'):
from test.backend.wayland.conf... |
def load_single_data(task, train_lines):
if (task in ['SST-2', 'mr', 'cr']):
label_list = {}
for line in train_lines:
label = get_label(task, line)
label = str(label)
text = get_text(task, line)
if (label not in label_list):
label_list[... |
def fas(data: ndarray, nodes: List[Node], independence_test_method: CIT_Base, alpha: float=0.05, knowledge: (BackgroundKnowledge | None)=None, depth: int=(- 1), verbose: bool=False, stable: bool=True, show_progress: bool=True) -> Tuple[(GeneralGraph, Dict[(Tuple[(int, int)], Set[int])], Dict[(Tuple[(int, int, Set[int])... |
(web_fixture=WebFixture)
class ResultScenarios(Fixture):
def json(self):
self.method_result = JsonResult(IntegerField(), catch_exception=Exception)
self.value_to_return = 1
self.expected_response = '1'
self.exception_response = '"exception text"'
self.expected_charset = self.... |
def test_cell_n3(mesh=([9] * 3)):
cell = pbcgto.Cell()
cell.unit = 'A'
cell.atom = 'C 0., 0., 0.; C 0.8917, 0.8917, 0.8917'
cell.a = '0. 1.7834 1.7834\n 1.7834 0. 1.7834\n 1.7834 1.7834 0. '
cell.basis = 'gth-szv'
cell.pseudo = 'gth-pade'
ce... |
def _warn_on_old_setuptools(_version: str=setuptools.__version__) -> None:
if (int(_version.split('.')[0]) < 61):
warnings.warn(RuntimeWarning(f'''
ERROR: setuptools=={_version} is used in combination with setuptools_scm>=8.x
Your build configuration is incomplete and previously worked by accident!
setuptoo... |
class NestedDict():
def __init__(self) -> None:
self.dict: Dict[(str, Any)] = {}
def get_or_create_nest(self, key: Key, *, access_lists: bool=True) -> dict:
cont: Any = self.dict
for k in key:
if (k not in cont):
cont[k] = {}
cont = cont[k]
... |
def raises_exc(exc: Union[(Type[E], E)], func: Callable[([], Any)], *, match: Optional[str]=None) -> E:
exc_type = (exc if isinstance(exc, type) else type(exc))
with pytest.raises(exc_type, match=match) as exc_info:
func()
assert (_repr_value(exc_info.value) == _repr_value(exc))
return exc_info.... |
class TestDraw():
def test_univariate(self):
with pm.Model():
x = pm.Normal('x')
x_draws = pm.draw(x)
assert (x_draws.shape == ())
(x_draws,) = pm.draw([x])
assert (x_draws.shape == ())
x_draws = pm.draw(x, draws=10)
assert (x_draws.shape == (10,))... |
.parametrize(('widget_field', 'field_name'), [('show_boss_life', 'show_boss_lifebar'), ('show_enemy_life', 'show_enemy_life'), ('show_enemy_damage', 'show_enemy_damage'), ('show_player_damage', 'show_player_damage'), ('show_death_counter', 'show_death_counter'), ('enable_auto_tracker', 'enable_auto_tracker')])
def test... |
def compatible_platforms(provided, required):
if ((provided is None) or (required is None) or (provided == required)):
return True
reqMac = macosVersionString.match(required)
if reqMac:
provMac = macosVersionString.match(provided)
if (not provMac):
provDarwin = darwinVers... |
def setUpModule():
global cell, mf, kmf, kpts
cell = pgto.Cell()
cell.atom = '\n He 0 0 1\n He 1 0 1\n '
cell.basis = '321g'
cell.a = (np.eye(3) * 3)
cell.mesh = ([8] * 3)
cell.verbose = 7
cell.output = '/dev/null'
cell.spin = 2
cell.build()
nk = [2, 2, 1]
kpts =... |
class ServerHost(abc.ABC):
def port(self) -> int:
raise NotImplementedError
def contrib_auth_token(self) -> str:
raise NotImplementedError
def contrib_secret(self) -> str:
def user_agent(self) -> Optional[str]:
def log_exception(self, exc: BaseException) -> None:
def log(self, me... |
def _registerBuiltinFunctions():
try:
import apex
OptimizerRegistry.register('Lamb')(apex.optimizers.FusedLAMB)
except:
raise ImportError('`import apex` failed. Apex not installed.')
OptimizerRegistry.register('Adam')(torch.optim.Adam)
LrSchedulerRegistry.register('ReduceLROnPlat... |
class CodeManager():
def __init__(self, owner):
self.code_blocks = {}
self.key_pressed_blocks = {}
self.broadcast_blocks = {}
self.clicked_blocks = []
self.current_block: CodeBlock = None
self.owner = owner
def process_key_pressed(self, key):
if (key in se... |
def get_sample_fn(params, is_training=False, use_prior=False, reuse=False, output_length=None):
def model(inputs):
outputs = get_singleseq_encoding_model(inputs, params, is_training, reuse)
outputs = get_latent_encoding_model(inputs, outputs, params, is_training, use_prior, reuse)
outputs = ... |
def test_vgg():
with pytest.raises(KeyError):
VGG(18)
with pytest.raises(AssertionError):
VGG(11, num_stages=0)
with pytest.raises(AssertionError):
VGG(11, num_stages=6)
with pytest.raises(AssertionError):
VGG(11, dilations=(1, 1), num_stages=3)
with pytest.raises(Typ... |
def stat_all_lite_sell(tmp_datetime):
datetime_str = tmp_datetime.strftime('%Y-%m-%d')
datetime_int = tmp_datetime.strftime('%Y%m%d')
print('datetime_str:', datetime_str)
print('datetime_int:', datetime_int)
sql_1 = '\n SELECT `date`,`code`,`name`,`latest_price`,`quote_change`,`ups_downs`... |
def _name_from_filename(metafile):
(rootdir, basename) = os.path.split(metafile)
if (basename == 'pyproject.toml'):
dirname = os.path.dirname(rootdir)
name = (dirname[3:] if dirname.startswith('bm_') else None)
elif (basename.startswith('bm_') and basename.endswith('.toml')):
name = ... |
def get_data():
data = {}
data['instances'] = []
for npz_file in sorted((here / 'data').listdir()):
if (not re.match('[0-9]+.npz', npz_file.basename())):
continue
instance = dict(np.load(npz_file))
instance['id'] = int(npz_file.basename().stem)
data['instances'].a... |
class Lzma(Codec):
codec_id = 'imagecodecs_lzma'
def __init__(self, level=None):
self.level = level
def encode(self, buf):
return imagecodecs.lzma_encode(buf, level=self.level)
def decode(self, buf, out=None):
return imagecodecs.lzma_decode(buf, out=_flat(out)) |
def f1(items):
results = list(zip(*items))
(gold_positives, pred_positives) = (defaultdict(list), defaultdict(list))
for (gold, pred, question) in zip(results[0], results[1], results[2]):
gold_positives[question].append(gold)
pred_positives[question].append(pred)
f1 = []
for question... |
class TestHalfStudentT(BaseTestDistributionRandom):
def halfstudentt_rng_fn(self, df, loc, scale, size, rng):
return np.abs(st.t.rvs(df=df, loc=loc, scale=scale, size=size, random_state=rng))
pymc_dist = pm.HalfStudentT
pymc_dist_params = {'nu': 5.0, 'sigma': 2.0}
expected_rv_op_params = {'nu': ... |
def wait_until_passes(timeout, retry_interval, func, exceptions=Exception, *args, **kwargs):
start = timestamp()
while True:
try:
func_val = func(*args, **kwargs)
break
except exceptions as e:
time_left = (timeout - (timestamp() - start))
if (time_... |
def get_nuc(mydf, kpts=None):
from pyscf.pbc.dft import gen_grid
(kpts, is_single_kpt) = _check_kpts(mydf, kpts)
cell = mydf.cell
mesh = mydf.mesh
charge = (- cell.atom_charges())
Gv = cell.get_Gv(mesh)
SI = cell.get_SI(mesh=mesh)
rhoG = numpy.dot(charge, SI)
coulG = tools.get_coulG(... |
def test_source_add_secondary(tester: CommandTester, source_existing: Source, source_secondary: Source, poetry_with_source: Poetry) -> None:
tester.execute(f'--priority=secondary {source_secondary.name} {source_secondary.url}')
assert_source_added(tester, poetry_with_source, source_existing, source_secondary) |
def test_pbsproscript_generator():
jd = rs.job.Description()
jd.name = 'Test'
jd.executable = '/bin/sleep'
jd.arguments = 10
jd.environment = {'test_env': 15, 'RADICAL_BASE': '/tmp'}
jd.working_directory = '/home/user'
jd.output = 'output.log'
jd.error = 'error.log'
jd.processes_per_... |
def test_validate_regex(db, source_schema, debug=True):
dbt_vars = {'source_schema': source_schema}
print(f'Running setup and tests for {db}')
dbt_seed(f'--select public_macros.validating', db, dbt_vars)
dbt_run(f'--select public_macros.validating', db, dbt_vars)
dbt_test(f'--select public_macros.va... |
class TestLoadProjectFromConfig():
def test_no_project_no_project_dirs(self, config_file):
assert (Project.from_config(config_file.model, 'foo') is None)
def test_project_empty_string(self, config_file, temp_dir):
config_file.model.projects[''] = str(temp_dir)
assert (Project.from_config... |
def register_event_loop_telemetry(app: FastAPI):
_event('startup')
async def add_fastapi_event_loop_monitoring():
app.state.fastapi_event_loop_schedule_latency_metrics = metrics.Histogram('anyscale_fastapi_event_loop_schedule_latency', description='Latency of getting yielded control on the FastAPI event... |
def get_default_configs():
config = ml_collections.ConfigDict()
config.training = training = ml_collections.ConfigDict()
config.training.batch_size = 128
training.n_iters = 1300001
training.snapshot_freq = 50000
training.log_freq = 50
training.eval_freq = 100
training.snapshot_freq_for_p... |
class InputFeedRNNDecoder(RNNDecoderBase):
def _run_forward_pass(self, tgt, memory_bank, memory_lengths=None, memory_bank_utterance=None, memory_lengths_utterance=None, hier_matrix=None):
input_feed = self.state['input_feed'].squeeze(0)
(input_feed_batch, _) = input_feed.size()
(_, tgt_batch... |
def test_formatter_encodings():
from pygments.formatters import HtmlFormatter
fmt = HtmlFormatter()
tokens = [(Text, 'a')]
out = format(tokens, fmt)
assert isinstance(out, str)
assert ('a' in out)
fmt = HtmlFormatter(encoding='latin1')
tokens = [(Text, 'a')]
assert ('a'.encode('latin... |
class UnderwaterDecorator(ChartDecorator):
def __init__(self, series: QFSeries, colors_alpha: float=1.0, key: str=None):
super().__init__(key)
self.series = series
self._colors_alpha = colors_alpha
def decorate(self, chart: 'Chart') -> None:
drawdown_series = drawdown_tms(self.se... |
def urdf_add_collision(builder, link, collisions, density, shape_ke, shape_kd, shape_kf, shape_mu):
for collision in collisions:
origin = urdfpy.matrix_to_xyz_rpy(collision.origin)
pos = origin[0:3]
rot = wp.quat_rpy(*origin[3:6])
geo = collision.geometry
if geo.box:
... |
_required
def invite_accept(request, orgslugname):
if (orgslugname == ''):
return HttpResponse(status=500)
pytitionuser = get_session_user(request)
try:
org = Organization.objects.get(slugname=orgslugname)
except Organization.DoesNotExist:
raise Http404(_('not found'))
if (or... |
class Multisig_Wallet(Deterministic_Wallet):
def __init__(self, db, storage, *, config):
self.wallet_type = db.get('wallet_type')
(self.m, self.n) = multisig_type(self.wallet_type)
Deterministic_Wallet.__init__(self, db, storage, config=config)
def get_public_keys(self, address):
... |
def fused_leaky_relu(input, bias, negative_slope=0.2, scale=(2 ** 0.5)):
rest_dim = ([1] * ((input.ndim - bias.ndim) - 1))
input = input.cuda()
if (input.ndim == 3):
return (F.leaky_relu((input + bias.view(1, *rest_dim, bias.shape[0])), negative_slope=negative_slope) * scale)
else:
retur... |
class TestWeighting():
(params=['A', 'C', 'Z'])
def weighting(self, request):
return request.param
def test_weighting_functions(self, weighting):
frequencies = NOMINAL_THIRD_OCTAVE_CENTER_FREQUENCIES
values = WEIGHTING_VALUES[weighting]
function_values = WEIGHTING_FUNCTIONS[w... |
class InvertedResidual(nn.Module):
def __init__(self, inp, oup, kernel_size, stride, expand_ratio, act, se):
super(InvertedResidual, self).__init__()
assert (stride in [1, 2])
self.stride = stride
self.act = act
self.se = se
padding = (kernel_size // 2)
hidden... |
def main():
parser = argparse.ArgumentParser(description='ReID Baseline Inference')
parser.add_argument('--config_file', default='', help='path to config file', type=str)
parser.add_argument('opts', help='Modify config options using the command-line', default=None, nargs=argparse.REMAINDER)
args = parse... |
def test_percent_not_hundred_before_complete(ansi_io: BufferedIO) -> None:
bar = ProgressBar(ansi_io, 200, 0)
bar.start()
bar.display()
bar.advance(199)
bar.advance()
output = [' 0/200 [>] 0%', ' 199/200 [>] 99%', ' 200/200 [] 100%']
expected = generate_output(output)
assert (expect... |
def get_cuda_bare_metal_version(cuda_dir):
raw_output = subprocess.check_output([(cuda_dir + '/bin/nvcc'), '-V'], universal_newlines=True)
output = raw_output.split()
release_idx = (output.index('release') + 1)
release = output[release_idx].split('.')
bare_metal_major = release[0]
bare_metal_min... |
def new_level_nbt(version: tuple, level_name: str, spawn: tuple, seed: int) -> nbt.TAG_Compound:
return nbt.TAG_Compound('', [nbt.TAG_Compound('Data', [nbt.TAG_Byte('allowCommands', 0), nbt.TAG_Double('BorderCenterX', 0), nbt.TAG_Double('BorderCenterZ', 0), nbt.TAG_Double('BorderDamagePerBlock', 0.2), nbt.TAG_Doubl... |
def get_control_lateral(text):
match = re.search('(\\d+)% to the (right|left)\\.', text, re.IGNORECASE)
if match:
(percentage, direction) = match.groups()
value = (int(percentage) / 100.0)
if (direction.lower() == 'right'):
value *= (- 1)
return value
return None |
class BootstrapGridsUI(UserInterface):
def assemble(self):
basics = self.define_view('/gridBasics', title='Grid basics', page=GridBasicsPage.factory())
page_layout = self.define_view('/pageLayout', title='Page layout', page=PageLayoutPage.factory())
container_layout = self.define_view('/cont... |
def save_categories_to_csv_file(categories, csv_path):
categories.sort(key=(lambda x: x['id']))
with tf.gfile.Open(csv_path, 'w') as csvfile:
writer = csv.writer(csvfile, delimiter=',', quotechar='"')
for category in categories:
writer.writerow([category['id'], category['name']]) |
def test_list_mixin_with_attributes(gl):
class M(ListMixin, FakeManager):
_types = {'my_array': gl_types.ArrayAttribute}
url = '
responses.add(method=responses.GET, headers={}, url=url, json=[], status=200, match=[responses.matchers.query_param_matcher({'my_array[]': ['1', '2', '3']})])
mgr = M(... |
def _unpack_db(content, local_file_name):
zip_contents = io.BytesIO(content)
with zipfile.ZipFile(zip_contents) as zip_file:
inner_file_name = zip_file.namelist()[0]
with zip_file.open(inner_file_name) as zipped_db_file:
with open(local_file_name, 'w+b') as db_file:
d... |
def write_features(fobj, collection, sequence=False, geojson_type='feature', use_rs=False, **dump_kwds):
if sequence:
for feat in collection():
(xs, ys) = zip(*coords(feat))
bbox = (min(xs), min(ys), max(xs), max(ys))
if use_rs:
fobj.write(u'\x1e')
... |
class Model(ModelDesc):
def get_policy(self, role_id, state, last_cards, minor_type):
batch_size = tf.shape(role_id)[0]
gathered_outputs = []
indices = []
for idx in range(1, 4):
with tf.variable_scope(('policy_network_%d' % idx)):
id_idx = tf.where(tf.equ... |
class VNet(MetaModule):
def __init__(self, input, hidden, output):
super(VNet, self).__init__()
self.linear1 = MetaLinear(input, hidden)
self.relu = nn.ReLU(inplace=True)
self.linear2 = MetaLinear(hidden, output)
def forward(self, x):
x = self.linear1(x)
x = self.... |
class GhauriAdvance():
def __execute_expression(self, url, data, vector, parameter, headers, base, injection_type, payloads, backend='', proxy=None, is_multipart=False, timeout=30, delay=0, timesec=5, attack=None, match_string=None, suppress_output=False, query_check=False, list_of_chars=None, not_match_string=None... |
.requires_internet
def test_sync_project_dependencies(hatch, helpers, temp_dir, config_file):
config_file.model.template.plugins['default']['tests'] = False
config_file.save()
project_name = 'My.App'
with temp_dir.as_cwd():
result = hatch('new', project_name)
assert (result.exit_code == 0), ... |
def test_varyings_struct_position1():
code1 = '\n fn vs_main() -> Varyings {\n }\n fn fs_main(varyings : Varyings) {\n }\n '
code2 = '\n struct Varyings {\n };\n\n fn vs_main() -> Varyings {\n }\n fn fs_main(varyings : Varyings) {\n }\n '
code3 = resolve_varyings(code1)
... |
def generate_vtables(base: ClassIR, vtable_setup_name: str, vtable_name: str, emitter: Emitter, shadow: bool) -> str:
def trait_vtable_name(trait: ClassIR) -> str:
return '{}_{}_trait_vtable{}'.format(base.name_prefix(emitter.names), trait.name_prefix(emitter.names), ('_shadow' if shadow else ''))
def t... |
def read_values(base, key):
try:
handle = RegOpenKeyEx(base, key)
except RegError:
return None
d = {}
i = 0
while True:
try:
(name, value, type) = RegEnumValue(handle, i)
except RegError:
break
name = name.lower()
d[convert_mbcs... |
def test_format_skeleton(timezone_getter):
dt = datetime(2007, 4, 1, 15, 30)
assert (dates.format_skeleton('yMEd', dt, locale='en_US') == 'Sun, 4/1/2007')
assert (dates.format_skeleton('yMEd', dt, locale='th') == '. 1/4/2007')
assert (dates.format_skeleton('EHm', dt, locale='en') == 'Sun 15:30')
ass... |
class CodeGeneratorDraft04(CodeGenerator):
FORMAT_REGEXS = {'date-time': '^\\d{4}-[01]\\d-[0-3]\\d(t|T)[0-2]\\d:[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:[+-][0-2]\\d:[0-5]\\d|[+-][0-2]\\d[0-5]\\d|z|Z)\\Z', 'email': '^[^]+[^]+\\.[^]+\\Z', 'hostname': '^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])\\.)*([A-Za-z0-9... |
class AwkLexer(RegexLexer):
name = 'Awk'
aliases = ['awk', 'gawk', 'mawk', 'nawk']
filenames = ['*.awk']
mimetypes = ['application/x-awk']
url = '
version_added = '1.5'
tokens = {'commentsandwhitespace': [('\\s+', Text), ('#.*$', Comment.Single)], 'slashstartsregex': [include('commentsandwhi... |
def get_info(python=sys.executable):
if (python and (python != sys.executable)):
import subprocess
argv = [python, __file__]
try:
text = subprocess.check_output(argv, encoding='utf-8')
except subprocess.CalledProcessError:
raise Exception(f'could not get info ... |
def infer_property(node: nodes.Call, context: (InferenceContext | None)=None) -> objects.Property:
if (len(node.args) < 1):
raise UseInferenceDefault
getter = node.args[0]
try:
inferred = next(getter.infer(context=context))
except (InferenceError, StopIteration) as exc:
raise Use... |
class TransformerAttentionSepModule(nn.Module):
def __init__(self, dim, num_heads, dropout, **kwargs):
super().__init__()
_check_dim_and_num_heads_consistency(dim, num_heads)
self.dim = dim
self.num_heads = num_heads
self.head_dim = (dim // num_heads)
self.attn_query ... |
def prepare_predict_dataset1(args):
matches = DataCleaner(args)
used_column = ['rally_id', 'player', 'type', 'player_location_x', 'player_location_y', 'opponent_location_x', 'opponent_location_y', 'ball_round', 'set', 'match_id']
matches = matches[used_column]
(player_codes, player_uniques) = pd.factori... |
def get_walks_intersection_ops(forward_seed_ops, backward_seed_ops, forward_inclusive=True, backward_inclusive=True, within_ops=None, within_ops_fn=None, control_inputs=False, control_outputs=None, control_ios=None):
(control_inputs, control_outputs) = check_cios(control_inputs, control_outputs, control_ios)
fo... |
class ParallelSentencesDataset(Dataset):
def __init__(self, student_model: SentenceTransformer, teacher_model: SentenceTransformer, batch_size: int=8, use_embedding_cache: bool=True):
self.student_model = student_model
self.teacher_model = teacher_model
self.datasets = []
self.datase... |
class PooledEmbeddingsAwaitable(Awaitable[torch.Tensor]):
def __init__(self, tensor_awaitable: Awaitable[torch.Tensor]) -> None:
super().__init__()
self._tensor_awaitable = tensor_awaitable
def _wait_impl(self) -> torch.Tensor:
ret = self._tensor_awaitable.wait()
return ret
d... |
class TestExcelImport(TestCaseWithFileOutput):
_tmp_dir = join(dirname(__file__), 'tmp')
_templates_dir = join(dirname(__file__), 'dummies')
def setUp(self):
dates = DatetimeIndex(date_range(start='2014-01-01', freq='d', periods=10))
returns = np.arange(0, 1, 0.1)
self.test_series = ... |
class WarmupCosineLR(torch.optim.lr_scheduler._LRScheduler):
def __init__(self, optimizer: torch.optim.Optimizer, max_iters: int, warmup_factor: float=0.001, warmup_iters: int=1000, warmup_method: str='linear', last_epoch: int=(- 1)):
logger.warning('WarmupCosineLR is deprecated! Use LRMultipilier with fvco... |
class ModelCatalog(object):
S3_C2_DETECTRON_PREFIX = '
C2_IMAGENET_MODELS = {'MSRA/R-50': 'ImageNetPretrained/MSRA/R-50.pkl', 'MSRA/R-101': 'ImageNetPretrained/MSRA/R-101.pkl', 'FAIR/R-50-GN': 'ImageNetPretrained//R-50-GN.pkl', 'FAIR/R-101-GN': 'ImageNetPretrained//R-101-GN.pkl', 'FAIR/X-101-32x8d': 'ImageNetPr... |
def balanceproof_from_envelope(envelope_message: EnvelopeMessage) -> BalanceProofSignedState:
assert envelope_message.sender, 'envelope_message must be signed'
return BalanceProofSignedState(nonce=envelope_message.nonce, transferred_amount=envelope_message.transferred_amount, locked_amount=envelope_message.lock... |
class LatentsDatasetInference(Dataset):
def __init__(self, latents, opts):
self.latents = latents
self.opts = opts
if ((self.opts.editing_type in ['hairstyle', 'both']) and (self.opts.input_type.split('_')[0] == 'text')):
with open(self.opts.hairstyle_description, 'r') as fd:
... |
class DumperProvider(ProviderWithAttachableRC, ABC):
_provision_action
def _outer_provide_dumper(self, mediator: Mediator, request: DumperRequest):
self._request_checker.check_request(mediator, request)
return self._provide_dumper(mediator, request)
def _provide_dumper(self, mediator: Mediat... |
.parametrize('temp_model', ['sapm_temp', 'faiman_temp', 'pvsyst_temp', 'fuentes_temp', 'noct_sam_temp'])
def test_infer_temp_model(location, sapm_dc_snl_ac_system, pvwatts_dc_pvwatts_ac_pvsyst_temp_system, pvwatts_dc_pvwatts_ac_faiman_temp_system, pvwatts_dc_pvwatts_ac_fuentes_temp_system, pvwatts_dc_pvwatts_ac_noct_sa... |
def test_estimates_expectation_value_pauli_nonoise():
evals = numpy.array([(- 1), (+ 1)])
true_amps = numpy.array([0.2, 0.8])
true_expectation_value = numpy.dot(evals, true_amps)
estimator = PhaseFitEstimator(evals)
sim_points = estimator.get_simulation_points()
phase_function = numpy.array([num... |
def _test_dataframe_shuffle(backend, protocol, n_workers, _partitions):
if (backend == 'cudf'):
cudf = pytest.importorskip('cudf')
with LocalCluster(protocol=protocol, dashboard_address=None, n_workers=n_workers, threads_per_worker=1, worker_class=IncreasedCloseTimeoutNanny, processes=True) as cluster:
... |
def find_occurrences(project, resource, offset, unsure=False, resources=None, in_hierarchy=False, task_handle=taskhandle.DEFAULT_TASK_HANDLE):
name = worder.get_name_at(resource, offset)
this_pymodule = project.get_pymodule(resource)
(primary, pyname) = evaluate.eval_location2(this_pymodule, offset)
def... |
class TypeFixture():
def __init__(self, variance: int=COVARIANT) -> None:
self.oi = self.make_type_info('builtins.object')
self.o = Instance(self.oi, [])
def make_type_var(name: str, id: int, values: list[Type], upper_bound: Type, variance: int) -> TypeVarType:
return TypeVarType... |
def test_none_activated(tester: CommandTester, venvs_in_cache_dirs: list[str], mocker: MockerFixture, env: MockEnv) -> None:
mocker.patch('poetry.utils.env.EnvManager.get', return_value=env)
tester.execute()
expected = '\n'.join(venvs_in_cache_dirs)
assert (tester.io.fetch_output().strip() == expected) |
def get_plugin(module_name, sources, **build_kwargs):
assert (verbosity in ['none', 'brief', 'full'])
if (module_name in _cached_plugins):
return _cached_plugins[module_name]
if (verbosity == 'full'):
print(f'Setting up PyTorch plugin "{module_name}"...')
elif (verbosity == 'brief'):
... |
def get_walks_union_ops(forward_seed_ops, backward_seed_ops, forward_inclusive=True, backward_inclusive=True, within_ops=None, within_ops_fn=None, control_inputs=False, control_outputs=None, control_ios=None):
(control_inputs, control_outputs) = check_cios(control_inputs, control_outputs, control_ios)
forward_o... |
class FungiConverter(DatasetConverter):
NUM_TRAIN_CLASSES = 994
NUM_VALID_CLASSES = 200
NUM_TEST_CLASSES = 200
def create_splits(self):
with tf.io.gfile.GFile(os.path.join(self.data_root, 'train.json')) as f:
original_train = json.load(f)
with tf.io.gfile.GFile(os.path.join(s... |
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = c... |
def args_dict(args):
args.dataset = {'train': args.train, 'val': args.val, 'test': args.test, 'matching': args.matching}
args.setting = {'sample_rate': args.sample_rate, 'segment': args.segment, 'pad': args.pad, 'stride': args.set_stride}
args.manner = {'in_channels': args.in_channels, 'out_channels': args.... |
def get_params(opt, size):
(w, h) = size
new_h = h
new_w = w
if (opt.preprocess_mode == 'resize_and_crop'):
new_h = new_w = opt.load_size
elif (opt.preprocess_mode == 'scale_width_and_crop'):
new_w = opt.load_size
new_h = ((opt.load_size * h) // w)
elif (opt.preprocess_mo... |
def data_loader(rng: jax.random.PRNGKey, dataset: Dataset, batch_size: int, shuffle: bool=False, drop_last=True):
if shuffle:
batch_idx = jax.random.permutation(rng, len(dataset))
batch_idx = np.asarray(batch_idx)
else:
batch_idx = np.arange(len(dataset))
if drop_last:
steps_... |
def test_cursor():
count = 1
assert (ansi.Cursor.UP(count) == f'{ansi.CSI}{count}A')
assert (ansi.Cursor.DOWN(count) == f'{ansi.CSI}{count}B')
assert (ansi.Cursor.FORWARD(count) == f'{ansi.CSI}{count}C')
assert (ansi.Cursor.BACK(count) == f'{ansi.CSI}{count}D')
x = 4
y = 5
assert (ansi.C... |
def run_job_locally(job_command, log_path, args, no_launch=False, log_file_prefix=''):
cmd_file = os.path.join(log_path, (log_file_prefix + 'launch.sh'))
with open(cmd_file, 'w') as out_f:
if args.conda_env:
print(f'source activate {args.conda_env}', file=out_f)
echo_system_info(out_... |
_scoped
class InvestmentOrder(Base):
__tablename__ = 'rspnsv_disc_investment_order'
id = Column(Integer, primary_key=True)
agreed_to_terms = Column(Boolean)
new_or_existing = Column(UnicodeText)
existing_account_number = Column(Integer)
name = Column(UnicodeText)
surname = Column(UnicodeText... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.