code stringlengths 281 23.7M |
|---|
class SawyerPegUnplugSideV1Policy(Policy):
_fully_parsed
def _parse_obs(obs):
return {'hand_pos': obs[:3], 'peg_pos': obs[3:6], 'unused_info': obs[6:]}
def get_action(self, obs):
o_d = self._parse_obs(obs)
action = Action({'delta_pos': np.arange(3), 'grab_effort': 3})
action[... |
.parametrize('\n unlogged_pulls_ok, kind_name, namespace_name, repository, repository_name,\n timestamp,\n index_response, expected_request, throws\n ', [pytest.param(False, 'non-existing', None, None, None, None, None, None, True, id='Invalid Kind'), pytest.param(False, 'pull_repo', 'user1', Mock(id=1), 'repo1', N... |
def update_changelog() -> None:
print('changes were made, updating changelog')
with open('CHANGELOG.rst', encoding='utf-8') as fp:
content = fp.read()
new_slug = (VENDOR_SLUG + f'''
- Update vendored schemas ({TODAY})
''')
if EXISTING_CHANGELINE_PATTERN.search(content):
content = EXISTIN... |
def evaluate(args, model, features, tag='dev'):
dataloader = DataLoader(features, batch_size=args.test_batch_size, collate_fn=collate_fn, drop_last=False)
(keys, preds) = ([], [])
for (i_b, batch) in enumerate(dataloader):
model.eval()
inputs = {'input_ids': batch[0].to(args.device), 'attent... |
def setup(app: Sphinx) -> None:
schema_file = (Path(__file__).parent.parent / 'vdom-json-schema.json')
current_schema = json.dumps(VDOM_JSON_SCHEMA, indent=2, sort_keys=True)
if ((not schema_file.exists()) or (schema_file.read_text() != current_schema)):
schema_file.write_text(current_schema) |
class _AnnotationContext(Context):
finder: 'TypeshedFinder'
module: str
def show_error(self, message: str, error_code: ErrorCode=ErrorCode.invalid_annotation, node: Optional[ast.AST]=None) -> None:
self.finder.log(message, ())
def get_name(self, node: ast.Name) -> Value:
return self.find... |
()
def plugin_distro(plugin_package: Package, tmp_path: Path) -> metadata.Distribution:
class MockDistribution(metadata.Distribution):
def read_text(self, filename: str) -> (str | None):
if (filename == 'METADATA'):
return '\n'.join([f'Name: {plugin_package.name}', f'Version: {pl... |
def test_exception_specifiers():
c = m.C()
assert (c.m1(2) == 1)
assert (c.m2(3) == 1)
assert (c.m3(5) == 2)
assert (c.m4(7) == 3)
assert (c.m5(10) == 5)
assert (c.m6(14) == 8)
assert (c.m7(20) == 13)
assert (c.m8(29) == 21)
assert (m.f1(33) == 34)
assert (m.f2(53) == 55)
... |
class SetPingRole(TourneyButton):
def __init__(self, ctx: Context, letter: str):
super().__init__(emoji=ri(letter))
self.ctx = ctx
async def callback(self, interaction: discord.Interaction):
(await interaction.response.defer())
m = (await self.ctx.simple('Mention the role you wan... |
class QuantizedCommCodec(Generic[QuantizationContext]):
def encode(self, input_tensor: torch.Tensor, ctx: Optional[QuantizationContext]=None) -> torch.Tensor:
...
def decode(self, input_grad: torch.Tensor, ctx: Optional[QuantizationContext]=None) -> torch.Tensor:
...
def quantized_dtype(self... |
class SquirrelCommand(object):
def fail(self, message):
raise error.ToolError(message)
def make_subparser(self, subparsers):
return subparsers.add_parser(self.__class__.__name__, help='Undocumented.')
def setup(self, parser):
pass
def run(self, parser, args):
pass |
class Order():
def __init__(self, p, score):
self.order = list(range(p))
self.parents = {}
self.local_scores = {}
self.edges = 0
random.shuffle(self.order)
for i in range(p):
y = self.order[i]
self.parents[y] = []
self.local_scores[... |
def _tf_sample_num_chunks(frame_rate, n_video_frames, chunks_per_minute):
num_video_frames_float = tf.cast(n_video_frames, tf.float32)
num_seconds = (num_video_frames_float / frame_rate)
chunks_per_second = (chunks_per_minute / SECONDS_IN_A_MINUTE)
num_chunks_float = (num_seconds * chunks_per_second)
... |
class W_Number(W_Object):
_attrs_ = []
errorname = 'number'
def __init__(self):
raise NotImplementedError('abstract base class')
def immutable(self):
return True
def eqv(self, other):
return self.equal(other)
def hash_eqv(self):
return self.hash_equal(info=None) |
class MediaMigrationView(RedirectView):
prefix = None
permanent = True
query_string = False
def get_redirect_url(self, *args, **kwargs):
image_path = kwargs['url']
if self.prefix:
image_path = '/'.join([self.prefix, image_path])
return '/'.join([settings.AWS_S3_ENDPOI... |
class Effect4057(BaseEffect):
runTime = 'early'
type = ('projected', 'passive')
def handler(fit, beacon, context, projectionRange, **kwargs):
fit.modules.filteredChargeMultiply((lambda mod: mod.charge.requiresSkill('Rockets')), 'emDamage', beacon.getModifiedItemAttr('smallWeaponDamageMultiplier'), s... |
class AVStreamInfo(Structure):
_fields_ = [('last_dts', c_int64), ('duration_gcd', c_int64), ('duration_count', c_int), ('rfps_duration_sum', c_int64), ('duration_error', POINTER(((c_double * 2) * ((((30 * 12) + 30) + 3) + 6)))), ('codec_info_duration', c_int64), ('codec_info_duration_fields', c_int64), ('frame_del... |
class CosineAnnealingLRWithWarmup(object):
def __init__(self, optimizer, T_max, last_epoch=(- 1), verbose=False, min_lr=0, warmup_lr=None, warmup=0):
self.optimizer = optimizer
self.T_max = T_max
self.last_epoch = last_epoch
self.verbose = verbose
self.warmup_lr = warmup_lr
... |
def _prototype_parent_select(caller, new_parent):
ret = None
prototype_parent = protlib.search_prototype(new_parent)
try:
if prototype_parent:
spawner.flatten_prototype(prototype_parent[0], validate=True)
else:
raise RuntimeError('Not found.')
except RuntimeError ... |
class MessageMock(QObject):
got_message = pyqtSignal(message.MessageInfo)
got_question = pyqtSignal(usertypes.Question)
def __init__(self, parent=None):
super().__init__(parent)
self.messages = []
self.questions = []
self._logger = logging.getLogger('messagemock')
(messag... |
class LetterItem(DemoItem):
def __init__(self, letter, parent=None):
super(LetterItem, self).__init__(parent)
self.letter = letter
self.useSharedImage((__file__ + letter))
def createImage(self, transform):
scaledRect = transform.mapRect(QRect(0, 0, 25, 25))
image = QImage... |
def save_ckpt(state, is_best, filename='ckpt.pth.tar', prefix=''):
torch.save(state, (prefix + filename))
if is_best:
shutil.copyfile((prefix + filename), (prefix + 'model_best.pth.tar'))
logging.info('Updating the best model checkpoint: {}'.format((prefix + 'model_best.pth.tar'))) |
def test_path_completion_user_path_expansion(cmd2_app):
if sys.platform.startswith('win'):
cmd = 'dir'
else:
cmd = 'ls'
text = '~{}'.format(os.path.sep)
line = 'shell {} {}'.format(cmd, text)
endidx = len(line)
begidx = (endidx - len(text))
completions_tilde_slash = [match.re... |
class IdentityWeightCreator(WeightCreatorInterface):
def __init__(self, class_weights: np.ndarray) -> None:
self._class_weights = class_weights
def video_weight_inputs(self, video_labels: np.ndarray, video_targets: np.ndarray) -> np.ndarray:
num_frames = video_labels.shape[0]
return np.t... |
class XglcdFont(object):
BIT_POS = {1: 0, 2: 2, 4: 4, 8: 6, 16: 8, 32: 10, 64: 12, 128: 14, 256: 16}
def __init__(self, path, width, height, start_letter=32, letter_count=96):
self.width = width
self.height = max(height, 8)
self.start_letter = start_letter
self.letter_count = let... |
def sstore(computation: BaseComputation) -> None:
(slot, value) = computation.stack_pop_ints(2)
current_value = computation.state.get_storage(address=computation.msg.storage_address, slot=slot)
is_currently_empty = (not bool(current_value))
is_going_to_be_empty = (not bool(value))
if is_currently_em... |
class SpanProtoFewNERDProcessor(FewShotNERProcessor):
def __init__(self, data_args, training_args, model_args, tokenizer=None, post_tokenizer=False, keep_raw_data=True):
super().__init__(data_args, training_args, model_args, tokenizer, post_tokenizer=post_tokenizer, keep_raw_data=keep_raw_data)
para... |
def test_create_bulk_import(gl, resp_create_bulk_import):
configuration = {'url': gl.url, 'access_token': 'test-token'}
migration_entity = {'source_full_path': 'source', 'source_type': 'group_entity', 'destination_slug': 'destination', 'destination_namespace': 'destination'}
migration = gl.bulk_imports.crea... |
class TFAutoModelForSequenceClassification(object):
def __init__(self):
raise EnvironmentError('TFAutoModelForSequenceClassification is designed to be instantiated using the `TFAutoModelForSequenceClassification.from_pretrained(pretrained_model_name_or_path)` or `TFAutoModelForSequenceClassification.from_co... |
def mobilenetv2(clip_X, mode):
width_scale = 1
input_channel = 32
arguments = [[1, 16, 1, 1], [6, 24, 2, 2], [6, 32, 3, 2], [6, 64, 4, 2], [6, 96, 3, 1], [6, 160, 3, 2], [6, 320, 1, 1]]
with tf.variable_scope('Conv2d3x3', reuse=None):
input_channel = int((input_channel * width_scale))
co... |
class DrawInstanceSegmentation(LazyTransport):
_class_names = class_names
def __init__(self):
super().__init__()
self._pub = self.advertise('~output', Image, queue_size=1)
def subscribe(self):
sub_rgb = message_filters.Subscriber('~input/rgb', Image)
sub_ins = message_filters... |
def get_tasks(task_names):
task_names = task_names.split(',')
if ('all' in task_names):
tasks = TASKS
else:
tasks = []
for task_name in task_names:
if (task_name not in TASKS):
raise ValueError(f'Task {task_name} not found!')
tasks.append(task_... |
def format_value(val):
if (val is None):
return '.'
elif isinstance(val, str):
return val
elif isinstance(val, bytes):
return val.decode('utf-8')
try:
lst = [format_value(v) for v in val]
return ','.join(lst)
except TypeError:
return str(val) |
def _build_circuit(qubit_pairs: List[List[cirq.Qid]], use_tsym: bool, depth: int) -> cirq.Circuit:
inter_gen = circuit_blocks.scrambling_block
if use_tsym:
inter_gen = circuit_blocks.tsym_block
random_source = np.random.uniform(0, 4, size=((depth * len(qubit_pairs)), 2))
ret_circuit = circuit_bl... |
class Effect2305(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: (mod.item.group.name == 'Energy Neutralizer')), 'energyNeutralizerAmount', ship.getModifiedItemAttr('eliteBonusReconShip2'), skill='Recon Ships', **kwargs... |
class DragWidget(QFrame):
def __init__(self, parent=None):
super(DragWidget, self).__init__(parent)
self.setMinimumSize(200, 200)
self.setFrameStyle((QFrame.Sunken | QFrame.StyledPanel))
self.setAcceptDrops(True)
boatIcon = QLabel(self)
boatIcon.setPixmap(QPixmap(':/i... |
def test_parse_command_with_args(parser):
line = 'command with args'
statement = parser.parse(line)
assert (statement.command == 'command')
assert (statement == 'with args')
assert (statement.args == statement)
assert (statement.argv == ['command', 'with', 'args'])
assert (statement.arg_list... |
.xfail("not hasattr(os, 'dup')")
def test_fdopen_kept_alive_issue124(pytester: Pytester) -> None:
pytester.makepyfile("\n import os, sys\n k = []\n def test_open_file_and_keep_alive(capfd):\n stdout = os.fdopen(1, 'w', buffering=1, encoding='utf-8')\n k.append(stdout)\n\n ... |
class PreActResNet(Backbone):
def __init__(self, block, num_blocks):
super().__init__()
self.in_planes = 64
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1)
self.layer2 = self._mak... |
class Log(object):
def __init__(self, hparams):
utc_dt = datetime.utcnow().replace(tzinfo=timezone.utc)
bj_dt = utc_dt.astimezone(timezone(timedelta(hours=8)))
logging_filename = (((('logs/' + hparams.log) + '__') + bj_dt.strftime('%Y-%m-%d_%H_%M_%S')) + '.log')
self.logger = logging... |
class _GPT2BPETokenizer(AbstractTokenizer):
def __init__(self, vocab_file, merge_file):
name = 'GPT2 BPE'
super().__init__(name)
self.tokenizer = GPT2Tokenizer(vocab_file, merge_file, errors='replace', special_tokens=[], max_len=None)
self.eod_id = self.tokenizer.encoder['<|endoftext... |
def convert(obj, rule, func, args=(), kwargs=None, fallback=None):
if (kwargs is None):
kwargs = {}
res = None
cvargs = (rule, func, args, kwargs, fallback)
try:
if rule(obj):
res = func(obj, *args, **kwargs)
elif is_mapping(obj):
res = dict(((convert(k, *... |
class KickstartCompleter_Test(TestCase):
def runTest(self):
kshandler = makeVersion(DEVEL)
self.assertIsNotNone(kshandler)
ksc = ksshell.KickstartCompleter(kshandler, {})
self.assertTrue((len(ksc.commands) > 0))
self.assertIn('part', ksc.commands)
ksc._init_matches('p... |
.skipif((sys.version_info < (3, 7)), reason='pre-commit requires Python 3.7+')
def test_new_project_does_not_fail_pre_commit(cwd, pre_commit, putup):
name = 'my_project'
run((f'{putup} --pre-commit --cirrus --gitlab -p my_package --namespace com.blue_yonder ' + name))
with cwd.join(name).as_cwd():
t... |
class Tree(nn.Module):
def __init__(self, levels, block, in_channels, out_channels, stride=1, level_root=False, root_dim=0, root_kernel_size=1, dilation=1, root_residual=False):
super(Tree, self).__init__()
if (root_dim == 0):
root_dim = (2 * out_channels)
if level_root:
... |
def setUpModule():
global mol, mm_coords, mm_charges, mm_radii
mol = gto.M(verbose=5, output='/dev/null', atom='O -1.464 0.099 0.300\n H -1.956 0.624 -0.340\n H -1.797 -0.799 0.206', basis='631G')
mm_coords = [(1.369, 0.146, (- 0.395)), (1.894, 0... |
.parametrize('ansi_sequence', [ansi.Fg.MAGENTA, ansi.Bg.LIGHT_GRAY, ansi.EightBitBg.CHARTREUSE_2A, ansi.EightBitBg.MEDIUM_PURPLE, ansi.RgbFg(0, 5, 22), ansi.RgbBg(100, 150, 222), ansi.TextStyle.OVERLINE_ENABLE])
def test_sequence_str_building(ansi_sequence):
assert ((ansi_sequence + ansi_sequence) == (str(ansi_sequ... |
class PolyTranslator(TypeTranslator):
def __init__(self, poly_tvars: Iterable[TypeVarLikeType], bound_tvars: frozenset[TypeVarLikeType]=frozenset(), seen_aliases: frozenset[TypeInfo]=frozenset()) -> None:
self.poly_tvars = set(poly_tvars)
self.bound_tvars = bound_tvars
self.seen_aliases = se... |
class Task(abc.ABC):
DATASET_PATH: str = None
DATASET_NAME: str = None
def __init__(self, data_dir=None, cache_dir=None, download_mode=None):
self.download(data_dir, cache_dir, download_mode)
self._training_docs = None
self._fewshot_docs = None
def download(self, data_dir=None, c... |
_module()
class ONNXRuntimeRecognizer(EncodeDecodeRecognizer):
def __init__(self, onnx_file: str, cfg: Any, device_id: int, show_score: bool=False):
if ('type' in cfg.model):
cfg.model.pop('type')
EncodeDecodeRecognizer.__init__(self, **cfg.model)
import onnxruntime as ort
... |
def _realign_dfs():
idx_len = 0
idx = None
for df in shared._DFS.values():
if (len(df) > idx_len):
idx_len = len(df)
idx = df.index
for key in shared._DFS.keys():
try:
shared._DFS[key] = _pd.DataFrame(index=idx, data=shared._DFS[key]).drop_duplicates()... |
class TestRotateProperties(EndianTest):
def setUp(self):
self.req_args_0 = {'delta': (- 11867), 'properties': [, , , , , , , , , , , ], 'window': }
self.req_bin_0 = b'r\x00\x00\x0f\x10*\xed!\x00\x0c\xd1\xa5\x01\xd0\x9d\x12Z\xa1Y\x87D_\x89\xe8\x104\xde\xd6#\x1d\xa2=\x05\xd4u\\|\xb6\xb2E\x06\xfb\xb5cF... |
def init(disp, info):
disp.extension_add_method('display', 'record_get_version', get_version)
disp.extension_add_method('display', 'record_create_context', create_context)
disp.extension_add_method('display', 'record_register_clients', register_clients)
disp.extension_add_method('display', 'record_unreg... |
class TestInfo(object):
def test_info(self):
if (not torch.cuda.is_available()):
return
from mmcv.ops import get_compiler_version, get_compiling_cuda_version
cv = get_compiler_version()
ccv = get_compiling_cuda_version()
assert (cv is not None)
assert (ccv... |
class GraphStructuralEncoder(nn.Module):
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1):
super(GraphStructuralEncoder, self).__init__()
self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
self.linear1 = nn.Linear(d_model, dim_feedforward)
se... |
def apply_migrations(data: dict, migrations: Migrations, *, copy_before_migrating: bool=False, version_name: str='version') -> dict:
schema_version = data.get('schema_version', 1)
version = get_version(migrations)
while (schema_version < version):
if copy_before_migrating:
data = copy.de... |
class TestFunctoolsPartial():
def test_infer_partial() -> None:
ast_node = astroid.extract_node("\n from functools import partial\n def test(a, b):\n '''Docstring'''\n return a + b\n partial(test, 1)(3) #\n ")
assert isinstance(ast_node.func, nodes.C... |
_processor('copy')
class CopyProcessor(BaseProcessor):
def __init__(self, config, *args, **kwargs):
self.max_length = config.max_length
def __call__(self, item):
blob = item['blob']
final_blob = np.zeros(((self.max_length,) + blob.shape[1:]), blob.dtype)
final_blob[:len(blob)] = ... |
def get_learning_rate_decay(learning_rate, global_step, params):
if (params.learning_rate_decay in ['linear_warmup_rsqrt_decay', 'noam']):
step = tf.to_float(global_step)
warmup_steps = tf.to_float(params.warmup_steps)
multiplier = (params.hidden_size ** (- 0.5))
decay = (multiplier ... |
def test_query_paths_with_second_try(query_paths_args, valid_response_json):
for try_again in (PFSError.BAD_IOU, PFSError.MISSING_IOU, PFSError.USE_THIS_IOU):
response = ([dict(error_code=try_again.value)] * 2)
assert_failed_pfs_request(query_paths_args, response, expected_requests=2, exception_type... |
def read_MW_dataset(mw_json_fn):
DOMAINS = ['hotel', 'restaurant', 'attraction', 'taxi', 'train']
with open(mw_json_fn, 'r') as f:
data = json.load(f)
dial_dict = {}
examples = defaultdict(list)
idx = 0
for turn in data:
if (not set(turn['domains']).issubset(set(DOMAINS))):
... |
def save_preds(exp, probability, clean):
name = './stats/cifar100/stats{}.pcl'
nm = name.format(exp)
if os.path.exists(nm):
(probs_history, clean_history) = pickle.load(open(nm, 'rb'))
else:
(probs_history, clean_history) = ([], [])
probs_history.append(probability)
clean_history... |
class Tracker():
module: nn.Module
traced: List[nn.Module] = field(default_factory=list)
handles: list = field(default_factory=list)
def _forward_hook(self, m, inputs: Tensor, outputs: Tensor):
has_not_submodules = ((len(list(m.modules())) == 1) or isinstance(m, nn.Conv2d) or isinstance(m, nn.Ba... |
def test_on_menu_action_dependencies(default_main_window, monkeypatch):
mock_show = MagicMock()
monkeypatch.setattr(QtWidgets.QWidget, 'show', mock_show)
default_main_window._on_menu_action_dependencies()
assert (default_main_window.dependencies_window is not None)
assert (default_main_window.depend... |
class Retriever(abc.ABC):
def __init__(self, key: str, on: typing.Union[(str, list)], k: typing.Optional[int], batch_size: int) -> None:
super().__init__()
self.key = key
self.on = (on if isinstance(on, list) else [on])
self.documents = None
self.k = k
self.batch_size... |
(params={'This': POINTER, 'Width': ULONGLONG, 'Register': INT, 'CpuIndex': ULONGLONG, 'Buffer': POINTER})
def hook_SmmWriteSaveState(ql: Qiling, address: int, params):
Width = params['Width']
Register = params['Register']
CpuIndex = params['CpuIndex']
Buffer = params['Buffer']
if (CpuIndex > 0):
... |
def plot_results(allresults, *, xy_fn=default_xy_fn, split_fn=default_split_fn, group_fn=default_split_fn, average_group=False, shaded_std=True, shaded_err=True, figsize=None, legend_outside=False, resample=0, smooth_step=1.0):
if (split_fn is None):
split_fn = (lambda _: '')
if (group_fn is None):
... |
def python_param_net_file():
with tempfile.NamedTemporaryFile(mode='w+', delete=False) as f:
f.write("name: 'pythonnet' force_backward: true\n input: 'data' input_shape { dim: 10 dim: 9 dim: 8 }\n layer { type: 'Python' name: 'mul10' bottom: 'data' top: 'mul10'\n python_param { module... |
.supported(only_if=(lambda backend: backend.cipher_supported(algorithms.SM4((b'\x00' * 16)), modes.ECB())), skip_message='Does not support SM4 ECB')
class TestSM4ModeECB():
test_ecb = generate_encrypt_test(load_nist_vectors, os.path.join('ciphers', 'SM4'), ['draft-ribose-cfrg-sm4-10-ecb.txt'], (lambda key, **kwargs... |
def _adjust_widths_groups_compatibilty(stage_widths, bottleneck_ratios, group_widths):
widths = [int((w * b)) for (w, b) in zip(stage_widths, bottleneck_ratios)]
groud_widths_min = [min(g, w_bot) for (g, w_bot) in zip(group_widths, widths)]
ws_bot = [_quantize_float(w_bot, g) for (w_bot, g) in zip(widths, g... |
def fix_missing_data(contour_data):
contour_data = np.array(contour_data)
if (contour_data.any() == ''):
logger.debug('Missing values detected.')
missing_values = np.where((contour_data == ''))[0]
if (missing_values.shape[0] > 1):
logger.debug("More than one value missing, fi... |
('current-continuation-marks', [default(values.W_ContinuationPromptTag, values.w_default_continuation_prompt_tag)], simple=False)
def current_cont_marks(prompt_tag, env, cont):
from pycket.interpreter import return_value
return return_value(values.W_ContinuationMarkSet(cont, prompt_tag), env, cont) |
def _test():
import torch
pretrained = False
models = [shufflenet_g1_w1, shufflenet_g2_w1, shufflenet_g3_w1, shufflenet_g4_w1, shufflenet_g8_w1, shufflenet_g1_w3d4, shufflenet_g3_w3d4, shufflenet_g1_wd2, shufflenet_g3_wd2, shufflenet_g1_wd4, shufflenet_g3_wd4]
for model in models:
net = model(pr... |
.parametrize('dialect', ['tsql'])
def test_tsql_assignment_operator(dialect: str):
sql = "INSERT INTO foo\nSELECT FirstColumnHeading = 'xyz',\n SecondColumnHeading = ProductID\nFROM Production.Product"
assert_column_lineage_equal(sql, [(ColumnQualifierTuple('ProductID', 'Production.Product'), ColumnQualif... |
def test_cmd_dict_input_with_args():
cmd = get_cmd('tests/testfiles/cmds/args.sh', 'tests\\testfiles\\cmds\\args.bat')
context = Context({'a': 'one', 'b': 'two two', 'c': 'three', 'd': cmd, 'cmd': {'run': '{d} {a} "{b}" {c}'}})
pypyr.steps.cmd.run_step(context)
assert ('cmdOut' not in context) |
class InputOutputOracleLevelDB(InputOutputOracle):
def __init__(self, grammar: TritonGrammar, inputs: List[Input], f_name: str=''):
super(InputOutputOracleLevelDB, self).__init__(grammar, inputs, f_name)
self.db = None
def create(filename: Union[(str, Path)], grammar: TritonGrammar, inputs: List... |
class test_element3(unittest.TestCase):
def test_cat_messages(self):
self.assertEqual(e3.cat_messages([]), b'')
self.assertEqual(e3.cat_messages([b'foo']), b'd\x00\x00\x00\x07foo')
self.assertEqual(e3.cat_messages([b'foo', b'foo']), (2 * b'd\x00\x00\x00\x07foo'))
self.assertEqual(e3.... |
class ResLayer(nn.Sequential):
def __init__(self, block, inplanes, planes, num_blocks, stride=1, dilation=1, avg_down=False, conv_cfg=None, norm_cfg=dict(type='BN'), multi_grid=None, contract_dilation=False, **kwargs):
self.block = block
downsample = None
if ((stride != 1) or (inplanes != (p... |
def parse(quteproc):
html = quteproc.get_content(plain=False)
soup = bs4.BeautifulSoup(html, 'html.parser')
with testutils.ignore_bs4_warning():
print(soup.prettify())
title_prefix = 'Browse directory: '
path = pathlib.Path(soup.title.string[len(title_prefix):])
container = soup('div', i... |
def forwarding(args, bkd_dr: DataReader, model, gids, criterion):
assert torch.cuda.is_available(), 'no GPU available'
cuda = torch.device('cuda')
gdata = GraphData(bkd_dr, gids)
loader = DataLoader(gdata, batch_size=args.batch_size, shuffle=False, collate_fn=collate_batch)
if (not next(model.parame... |
def min_informative_str(obj, indent_level=0, _prev_obs=None, _tag_generator=None):
if (_prev_obs is None):
_prev_obs = {}
indent = (' ' * indent_level)
if (id(obj) in _prev_obs):
tag = _prev_obs[id(obj)]
return (((indent + '<') + tag) + '>')
if (_tag_generator is None):
_... |
def setup_logging(args):
project_name = args.model_ckpt.split('/')[(- 1)]
logger = logging.getLogger(__name__)
log_dir = (Path(args.save_dir) / 'log/')
log_dir.mkdir(exist_ok=True)
filename = f'debug_{accelerator.process_index}.log'
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(nam... |
class _Transition(nn.Sequential):
def __init__(self, num_input_features, num_output_features, stride=2):
super(_Transition, self).__init__()
self.add_module('norm', bn(num_input_features))
self.add_module('relu', nn.ReLU(inplace=True))
self.add_module('conv', nn.Conv2d(num_input_feat... |
def test_AccessorABC_invalid_kind():
class FooAccessor(AccessorABC):
_default_kind = 'zaraza'
def __init__(self):
self.dont_work = None
def _zaraza(self):
pass
acc = FooAccessor()
with pytest.raises(ValueError):
acc('_zaraza')
with pytest.raises(Va... |
def unpack(path: str, dest: str='.') -> None:
with WheelFile(path) as wf:
namever = wf.parsed_filename.group('namever')
destination = (Path(dest) / namever)
print(f'Unpacking to: {destination}...', end='', flush=True)
for zinfo in wf.filelist:
wf.extract(zinfo, destinatio... |
def test_nested_credentials(monkeypatch):
_env_credentialled
def fake_opener(path):
return getenv()
with rasterio.Env(session=AWSSession(aws_access_key_id='foo', aws_secret_access_key='bar')):
assert (getenv()['AWS_ACCESS_KEY_ID'] == 'foo')
assert (getenv()['AWS_SECRET_ACCESS_KEY'] =... |
def _decode_string_to_dict(encoded_value: str, param_type: Type[Dict[(Any, Any)]]) -> Dict[(Any, Any)]:
(key_type, value_type) = typing_inspect.get_args(param_type)
arg_values = {}
for (key, value) in to_dict(encoded_value).items():
arg_values[key_type(key)] = value_type(value)
return arg_values |
def readme_simple():
from sklearn.datasets import load_breast_cancer
from xgboost_ray import RayDMatrix, RayParams, train
(train_x, train_y) = load_breast_cancer(return_X_y=True)
train_set = RayDMatrix(train_x, train_y)
evals_result = {}
bst = train({'objective': 'binary:logistic', 'eval_metric'... |
class NgrokStart(Command):
keyword = 'start'
def assemble(self):
super().assemble()
location_group = self.parser.add_mutually_exclusive_group(required=True)
location_group.add_argument('-l', '--local', action='store_true', dest='local', help='exposes the local machine ssh port')
... |
def get_main_ubo_table(flavors: list[FlavorMeta]):
ret = md_tr('', *(f.table_name for f in flavors))
ret += md_tr('---', *(':---:' for f in flavors))
for filter_meta in search_engines:
ret += md_tr(filter_meta.name, *(md_link(get_badge('uBO - add this filter', 'uBlock Origin', 'uBO', 'add this filte... |
class PrecisionAtRecallDetectionEvaluator(ObjectDetectionEvaluator):
def __init__(self, categories, matching_iou_threshold=0.5, recall_lower_bound=0.0, recall_upper_bound=1.0):
super(PrecisionAtRecallDetectionEvaluator, self).__init__(categories, matching_iou_threshold=matching_iou_threshold, recall_lower_b... |
def test_prints_skip_message_for_uploaded_package(upload_settings, stub_repository, capsys, caplog):
upload_settings.skip_existing = True
stub_repository.package_is_uploaded = (lambda package: True)
result = upload.upload(upload_settings, [helpers.WHEEL_FIXTURE])
assert (result is None)
captured = c... |
def define_D(opt):
gpu_ids = opt['gpu_ids']
opt_net = opt['network_D']
which_model = opt_net['which_model_D']
if (which_model == 'discriminator_vgg_128'):
netD = arch.Discriminator_VGG_128(in_nc=opt_net['in_nc'], base_nf=opt_net['nf'], norm_type=opt_net['norm_type'], mode=opt_net['mode'], act_ty... |
def test_entity_relation():
(tokens, entities, relations) = get_data()
for solver in get_solvers(num_samples=200):
cons = constraint(OrgBasedIn_Org_Loc, solver)
(ner, re) = train(cons)
re = torch.argmax(torch.softmax(re(tokens).view((- 1), 11), dim=(- 1)), dim=(- 1))
ner = torch.... |
def create_test_image(x, y, field_centre, field_side_lengths, field_penumbra, field_rotation, bb_centre, bb_diameter, bb_max_attenuation):
field = create_field_with_bb_func(field_centre, field_side_lengths, field_penumbra, field_rotation, bb_centre, bb_diameter, bb_max_attenuation)
(xx, yy) = np.meshgrid(x, y)
... |
class SuspendUser(IntermediateActionView):
permission_required = ('dictionary.suspend_user', 'dictionary.change_author')
model = Author
page_title = _('Suspend authors')
template_name = 'admin/actions/suspend_user.html'
max_input = 100
def post(self, request):
response = redirect(self.ge... |
class ConvBnReLU3D(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, pad=1, norm_act=InPlaceABN):
super(ConvBnReLU3D, self).__init__()
self.conv = nn.Conv3d(in_channels, out_channels, kernel_size, stride=stride, padding=pad, bias=False)
self.bn = norm_act(out... |
class Solution(object):
def validPalindrome(self, s):
return self.validPalindromeHelper(s, 0, (len(s) - 1), 1)
def validPalindromeHelper(self, s, left, right, budget):
while ((left < len(s)) and (right >= 0) and (left <= right) and (s[left] == s[right])):
left += 1
right ... |
def make_report(parsed):
table = ''
full_table = ''
analyzer_db = None
sniffer_db = None
analyzer_path = '{}{}{}'.format(parsed['locations']['box_output'], parsed['task'], parsed['locations']['analyzer_logs'])
sniffer_path = '{}{}{}'.format(parsed['locations']['box_output'], parsed['task'], pars... |
class TestExponential(BaseTestDistributionRandom):
pymc_dist = pm.Exponential
pymc_dist_params = {'lam': 10.0}
expected_rv_op_params = {'mu': (1.0 / pymc_dist_params['lam'])}
reference_dist_params = {'scale': (1.0 / pymc_dist_params['lam'])}
reference_dist = seeded_numpy_distribution_builder('expone... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.