code stringlengths 281 23.7M |
|---|
def ql_syscall_kernelrpc_mach_vm_map_trap(ql, target, address, size, mask, flags, cur_protection):
ql.log.debug(('[mach] mach vm map trap(target: 0x%x, address: 0x%x, size: 0x%x, mask: 0x%x, flag: 0x%x, cur_protect: 0x%x)' % (target, address, size, mask, flags, cur_protection)))
if ((ql.os.macho_vmmap_end & mas... |
class PropertyInfo(object):
def __init__(self, host, name, tp, doc='', enum=None, getter=propGet, group='Base', internal=False, duplicate=False, default=None):
self.Name = name
self.Type = tp
self.Group = group
self.Doc = doc
self.Enum = enum
self.get = getter.__get__... |
class Client(object):
def __init__(self, instance=None, host=None, user=None, password=None, raise_on_empty=None, request_params=None, use_ssl=True, session=None):
if ((host and instance) is not None):
raise InvalidUsage("Arguments 'instance' and 'host' are mutually exclusive, you cannot use bot... |
def inline_comments_in_inp(filepath, overwrite=False):
newfilename = (os.path.splitext(os.path.basename(filepath))[0] + '_unGUI.inp')
newfilepath = os.path.join(os.path.dirname(filepath), newfilename)
allheaders = get_inp_sections_details(filepath)
with open(filepath) as oldf:
with open(newfilep... |
class TruetypeInfo():
_name_id_lookup = {'copyright': 0, 'family': 1, 'subfamily': 2, 'identifier': 3, 'name': 4, 'version': 5, 'postscript': 6, 'trademark': 7, 'manufacturer': 8, 'designer': 9, 'description': 10, 'vendor-url': 11, 'designer-url': 12, 'license': 13, 'license-url': 14, 'preferred-family': 16, 'prefe... |
def test_select_column_wildcard_with_qualifier():
sql = 'INSERT INTO tab1\nSELECT tab2.*\nFROM tab2 a\n INNER JOIN tab3 b\n ON a.id = b.id'
assert_column_lineage_equal(sql, [(ColumnQualifierTuple('*', 'tab2'), ColumnQualifierTuple('*', 'tab1'))])
sql = 'INSERT INTO tab1\nSELECT a.... |
class AttrVI_ATTR_USB_BULK_OUT_PIPE(RangeAttribute):
resources = [(constants.InterfaceType.usb, 'RAW')]
py_name = ''
visa_name = 'VI_ATTR_USB_BULK_OUT_PIPE'
visa_type = 'ViInt16'
default = NotAvailable
(read, write, local) = (True, True, True)
(min_value, max_value, values) = (1, 15, [(- 1)]... |
class RoundRectItem(QGraphicsObject):
def __init__(self, bounds, color, parent=None):
super(RoundRectItem, self).__init__(parent)
self.fillRect = False
self.bounds = QRectF(bounds)
self.pix = QPixmap()
self.gradient = QLinearGradient()
self.gradient.setStart(self.boun... |
_fixtures(WebFixture, LargeFileUploadInputFixture)
def test_queueing_async_uploads(web_fixture, large_file_upload_input_fixture):
fixture = large_file_upload_input_fixture
fixture.run_hook_after = True
web_fixture.reahl_server.set_app(fixture.new_wsgi_app(enable_js=True))
browser = web_fixture.driver_br... |
def get_xritdecompress_outfile(stdout):
outfile = b''
for line in stdout:
try:
(k, v) = [x.strip() for x in line.split(b':', 1)]
except ValueError:
break
if (k == b'Decompressed file'):
outfile = v
break
return outfile |
def _convert_configs_values_to_bool(dictionary: Dict):
for (key, value) in dictionary.items():
if (value == 'True'):
dictionary[key] = True
elif (value == 'False'):
dictionary[key] = False
elif isinstance(value, List):
for item in value:
if... |
def main():
args = parse_args()
if (len(args.shape) == 1):
input_shape = (1, 3, args.shape[0], args.shape[0])
elif (len(args.shape) == 2):
input_shape = ((1, 3) + tuple(args.shape))
elif (len(args.shape) == 4):
input_shape = tuple(args.shape)
elif (len(args.shape) == 5):
... |
def find_most_similar_index(str_list, target_str):
most_similar_str = None
most_similar_index = None
highest_similarity = 0
for (i, str) in enumerate(str_list):
similarity = str_similarity(str, target_str)
if (similarity > highest_similarity):
most_similar_str = str
... |
def _infer_content_types_from_paths(paths: List[str], content_type_provider: Callable[([str], ContentType)]) -> Dict[(ContentType, List[str])]:
content_type_to_paths = defaultdict(list)
for path in paths:
if (not path.endswith('/')):
content_type_to_paths[content_type_provider(path)].append(... |
class egg_info(InfoCommon, Command):
description = "create a distribution's .egg-info directory"
user_options = [('egg-base=', 'e', 'directory containing .egg-info directories (default: top of the source tree)'), ('tag-date', 'd', 'Add date stamp (e.g. ) to version number'), ('tag-build=', 'b', 'Specify explici... |
class TestConfigPath():
def test_correct(self, isolation):
config = {'path': 'foo/bar.py'}
hook = VersionBuildHook(str(isolation), config, None, None, '', '')
assert (hook.config_path == hook.config_path == 'foo/bar.py')
def test_missing(self, isolation):
config = {'path': ''}
... |
def test_log1mexp_deprecation_warnings():
with pytest.warns(FutureWarning, match='pymc.math.log1mexp_numpy will expect a negative input'):
res_pos = log1mexp_numpy(2)
with warnings.catch_warnings():
warnings.simplefilter('error')
res_neg = log1mexp_numpy((- 2), negative_input=True)
w... |
_arg_scope
def layer_norm(inputs, center=True, scale=True, activation_fn=None, reuse=None, variables_collections=None, outputs_collections=None, trainable=True, begin_norm_axis=1, begin_params_axis=(- 1), scope=None):
with variable_scope.variable_scope(scope, 'LayerNorm', [inputs], reuse=reuse) as sc:
input... |
class CenterCrop_iBims1(object):
def __init__(self, size_image, size_depth):
self.size_image = size_image
self.size_depth = size_depth
def __call__(self, sample):
(image, depth, edges, calib, mask_invalid, mask_transp, mask_wall, mask_wall_paras, mask_table, mask_table_paras, mask_floor,... |
def test_expect_rho(all_qevo):
vec = _data.dense.fast_from_numpy(((np.random.rand((N * N)) + 1) + (1j * np.random.rand((N * N)))))
mat = _data.column_unstack_dense(vec, N)
qobj = Qobj(mat)
op = liouvillian(all_qevo)
for t in TESTTIMES:
Qo1 = op(t)
assert (abs((_data.expect_super(Qo1.... |
def merge_turns(turns):
new_turns = []
for ((file_id, speaker_id), speaker_turns) in groupby(turns, (lambda x: (x.file_id, x.speaker_id))):
speaker_turns = list(speaker_turns)
speaker_it = IntervalTree.from_tuples([(turn.onset, turn.offset) for turn in speaker_turns])
n_turns_pre = len(s... |
class PegasusConfig(PretrainedConfig):
model_type = 'pegasus'
keys_to_ignore_at_inference = ['past_key_values']
attribute_map = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}
def __init__(self, vocab_size=50265, max_position_embeddings=1024, encoder_layers=12, encoder_ffn_d... |
class OptionalPackagesTestCase(unittest.TestCase):
def test_exception(self):
ex = OptionalPackageRequirementError('python-magic')
self.assertTrue(str(ex).startswith('The following packages are missing'))
self.assertRaises(ValueError, OptionalPackageRequirementError, 'PackageThatNotFoundInReq... |
class Solution():
def __init__(self):
self.total = 0
def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:
if (not root):
return
if root:
if (R >= root.val >= L):
self.total += root.val
self.rangeSumBST(root.left, L, R)
... |
def insert_projects_table(file: Path, *, projects: Sequence[Project], input_filename: str, include_info: bool=True):
text = file.read_text()
projects_table = render_projects(projects, include_info=include_info, dest_path=file)
start_str = '<!-- START bin/projects.py -->\n'
start = text.find(start_str)
... |
def static_file(filename, root, mimetype='auto', download=False, charset='UTF-8'):
root = (os.path.abspath(root) + os.sep)
filename = os.path.abspath(os.path.join(root, filename.strip('/\\')))
headers = dict()
if (not filename.startswith(root)):
return HTTPError(403, 'Access denied.')
if ((n... |
def cli_main(modify_parser: Optional[Callable[([argparse.ArgumentParser], None)]]=None) -> None:
parser = options.get_training_parser()
args = options.parse_args_and_arch(parser, modify_parser=modify_parser)
cfg = convert_namespace_to_omegaconf(args)
if distributed_utils.is_master(cfg.distributed_traini... |
class Generator(Object):
seed = Int.T(optional=True, help='Random seed for a reproducible scenario.')
def __init__(self, **kwargs):
Object.__init__(self, **kwargs)
self._seed = None
self._parent = None
self.update_hierarchy()
self._retry_offset = 0
def retry(self):
... |
class _ThreadSafeQueue(Generic[_Type]):
def __init__(self) -> None:
self._loop = get_running_loop()
self._queue: Queue[_Type] = Queue()
self._pending: set[_Type] = set()
def put(self, value: _Type) -> None:
if (value not in self._pending):
self._pending.add(value)
... |
class TestStrategy(Algo):
count = 0
def on_start(self):
self.count = 0
def on_quote(self, instrument):
pass
def on_orderbook(self, instrument):
pass
def on_fill(self, instrument, order):
pass
def on_tick(self, instrument):
self.count += 1
if ((self... |
class OutputChangeNotify(rq.Event):
_code = None
_fields = rq.Struct(rq.Card8('type'), rq.Card8('sub_code'), rq.Card16('sequence_number'), rq.Card32('timestamp'), rq.Card32('config_timestamp'), rq.Window('window'), rq.Card32('output'), rq.Card32('crtc'), rq.Card32('mode'), rq.Card16('rotation'), rq.Card8('conne... |
def debounce(interval_s, keyed_by=None):
def wrapper(func):
timers = {}
lock = threading.Lock()
(func)
def debounced(*args, **kwargs):
sig = inspect.signature(func)
call_args = sig.bind(*args, **kwargs)
key = (call_args.arguments[keyed_by] if keyed... |
class AutoFeatureExtractorTest(unittest.TestCase):
vocab_tokens = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou']
def test_processor_from_model_shortcut(self):
processor = AutoProcessor.from_pretrained('facebook/wav2vec2-base-960h')
self.assertIsInstance(processor, Wav2Vec2Processo... |
def conv2d(inputs, filters, kernel_size, strides, activation, is_training, scope):
with tf.variable_scope(scope):
conv2d_output = tf.layers.conv2d(inputs, filters=filters, kernel_size=kernel_size, strides=strides, padding='same')
batch_norm_output = tf.layers.batch_normalization(conv2d_output, train... |
def crop_img(img, meters_ahead=40, meters_behind=10, meters_left=25, meters_right=25, resolution=0.1):
buffer = (max([meters_ahead, meters_behind, meters_left, meters_right]) * 2)
image_side_length = int((buffer / resolution))
(row_crop, col_crop) = get_crops(meters_ahead, meters_behind, meters_left, meters... |
def populate_storage_for_gc():
preferred = storage.preferred_locations[0]
for storage_row in ImageStorage.select():
content = b'hello world'
storage.put_content({preferred}, storage.blob_path(storage_row.content_checksum), content)
assert storage.exists({preferred}, storage.blob_path(sto... |
def _execute_scenario(feature: Feature, scenario: Scenario, request: FixtureRequest) -> None:
__tracebackhide__ = True
request.config.hook.pytest_bdd_before_scenario(request=request, feature=feature, scenario=scenario)
try:
for step in scenario.steps:
step_func_context = get_step_functio... |
def ReinstallProtocolInterface(context, params):
handle = params['Handle']
if (handle not in context.protocols):
return EFI_NOT_FOUND
dic = context.protocols[handle]
protocol = params['Protocol']
if (protocol not in dic):
return EFI_NOT_FOUND
dic[protocol] = params['NewInterface'... |
.parametrize('q', [quantize(symmetric=True, initialized=True), quantize(symmetric=False, initialized=True), quantize_dequantize(symmetric=True, initialized=True), quantize_dequantize(symmetric=False, initialized=True)])
def test_forward(q: Union[(Quantize, QuantizeDequantize)], x: torch.Tensor):
output = q(x)
i... |
def add_precedence(plist):
plevel = 0
error = 0
for p in plist:
plevel += 1
try:
prec = p[0]
terms = p[1:]
if ((prec != 'left') and (prec != 'right') and (prec != 'nonassoc')):
sys.stderr.write(("yacc: Invalid precedence '%s'\n" % prec))
... |
class MultivariateNormalLikelihood(GaussianLikelihood):
def __init__(self, num_train: int, rank: int=1, batch_shape=torch.Size(), noise_covar_prior=None, noise_prior=None, noise_constraint=None):
Likelihood.__init__(self)
self.num_train = num_train
self.register_parameter(name='noise_covar_f... |
class Data(aslib.Data):
dmesg = {}
start = 0.0
end = 0.0
dmesgtext = []
testnumber = 0
idstr = ''
html_device_id = 0
valid = False
tUserMode = 0.0
boottime = ''
phases = ['kernel', 'user']
do_one_initcall = False
def __init__(self, num):
self.testnumber = num
... |
def evaluate(preds, golds, entity_path):
print('STARTING EVALUATION')
(acc, total) = (0, 0)
domain2kvr_name_domain = {'all': 'ent_index', 'calendar': 'ent_idx_cal', 'navigate': 'ent_idx_nav', 'weather': 'ent_idx_wet'}
F1_pred = {'all': 0, 'calendar': 0, 'navigate': 0, 'weather': 0}
F1_count = {'all'... |
def test_lookup__doesnt_exist(requests_mock):
requests_mock.get(f'{API_V1}/controlled_terms', json=SAMPLE_DATA['get_controlled_terms'], status_code=200)
client = iNatClient()
annotations = [Annotation(controlled_attribute_id=id) for id in [12, 999]]
annotations = client.annotations.lookup(annotations)
... |
class Rectangles(rq.Request):
_request = rq.Struct(rq.Card8('opcode'), rq.Opcode(1), rq.RequestLength(), OP('operation'), KIND('destination_kind'), rq.Card8('ordering'), rq.Pad(1), rq.Window('destination_window'), rq.Int16('x_offset'), rq.Int16('y_offset'), rq.List('rectangles', structs.Rectangle, pad=0)) |
class Task2DatasetConCat(BaseDataset):
def __getitem__(self, index) -> Tuple:
(query_id, idx) = self.samples[index]
product_id = self.database[self.split_dataset][query_id]['product_id'][idx]
example_id = self.database[self.split_dataset][query_id]['example_id'][idx]
dataset = torch.... |
def test_multiple_variables_merge_override(testdir, file_format):
testdir.makepyfile("\n def test(variables):\n assert variables['capabilities']['browser'] == 'Firefox'\n assert variables['capabilities']['browser_version'] == '53.0'\n assert variables['capabilities']['debug']... |
class RCAB(nn.Module):
def __init__(self, conv, n_feat, kernel_size, reduction, bias=True, bn=False, act=nn.ReLU(True), res_scale=1):
super(RCAB, self).__init__()
modules_body = []
for i in range(2):
modules_body.append(conv(n_feat, n_feat, kernel_size, bias=bias))
if... |
class POS(TokenClassificationTask):
def read_examples_from_file(self, data_dir, mode: Union[(Split, str)]) -> List[InputExample]:
if isinstance(mode, Split):
mode = mode.value
file_path = os.path.join(data_dir, f'{mode}.txt')
guid_index = 1
examples = []
with open... |
class BundlerManager():
def __init__(self) -> None:
from poetry_plugin_bundle.bundlers.venv_bundler import VenvBundler
self._bundler_classes: dict[(str, type[Bundler])] = {}
self.register_bundler_class(VenvBundler)
def bundler(self, name: str) -> Bundler:
if (name.lower() not in ... |
def remote_sync(local_dir, remote_dir, protocol):
logging.info('Starting remote sync.')
if (protocol == 's3'):
return remote_sync_s3(local_dir, remote_dir)
elif (protocol == 'fsspec'):
return remote_sync_fsspec(local_dir, remote_dir)
else:
logging.error('Remote protocol not known... |
def parse_args():
parser = argparse.ArgumentParser(description='Initialize PASCAL Context dataset.', epilog='Example: python prepare_pcontext.py', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--download-dir', default=None, help='dataset directory on disk')
args = parser.parse... |
def processForClause(c, table, prior_lcs, prior_globs):
new_schema = None
comp_expr = compile(c.expr.lstrip(), '<string>', 'eval')
for t in table:
if (not new_schema):
new_schema = dict(t.schema)
for (i, v) in enumerate(c.vars):
new_schema[v] = (len(t.schema) ... |
def get_files_from_regex(path):
directory_name = dirname(path)
if (directory_name == ''):
directory_name = '.'
regex = basename(path)
file_names = []
pattern = compile(translate(regex), IGNORECASE)
for file in os.listdir(directory_name):
if pattern.fullmatch(file):
fi... |
class ScaledDotProductAttention(nn.Module):
def __init__(self, temperature, attn_dropout=0.1):
super().__init__()
self.temperature = temperature
self.dropout = nn.Dropout(attn_dropout)
self.softmax = nn.Softmax(dim=2)
def forward(self, q, k, v, mask=None):
attn = torch.bm... |
def flow_model(args, in_channels):
coder = Ff.SequenceINN(in_channels)
print('Normalizing Flow => Feature Dimension: ', in_channels)
for k in range(args.coupling_layers):
coder.append(Fm.AllInOneBlock, subnet_constructor=subnet_fc, affine_clamping=args.clamp_alpha, global_affine_type='SOFTPLUS', per... |
def test_return_value_consistency():
pid_mem_list = memory_usage(timeout=1)
assert (type(pid_mem_list) == list), 'Memory usage of process should be a list'
pid_mem_max = memory_usage(timeout=1, max_usage=True)
assert (type(pid_mem_max) == float), 'Max memory usage of process should be a number'
func... |
def test_run_model_from_poa(sapm_dc_snl_ac_system, location, total_irrad):
mc = ModelChain(sapm_dc_snl_ac_system, location, aoi_model='no_loss', spectral_model='no_loss')
ac = mc.run_model_from_poa(total_irrad).results.ac
expected = pd.Series(np.array([149.280238, 96.678385]), index=total_irrad.index)
a... |
def set_datapipes_seed(datapipes: List[DataPipe], seed_generator: SeedGenerator, distributed_shared: bool) -> None:
for dp in datapipes:
if _is_random_datapipe(dp):
if distributed_shared:
dp.set_seed(seed_generator.generate_shared_seed())
else:
dp.set_... |
def copy_data(input_file, destination_dir, num_threads, tmp_destination_dir):
logging.info(f'Creating directory: {destination_dir}')
if (not ((destination_dir is None) or (destination_dir == ''))):
makedir(destination_dir)
else:
destination_dir = None
if PathManager.isfile(input_file):
... |
def _process_target_sentence(tokens: List[str], origin_sentence: str, target_sentence: str, max_length: int, label_map: dict, tokenizer: BertTokenizer, cls_token_at_end: Optional[bool]=False):
if ('[UNK]' in tokens):
processed_tokens = []
basic_tokens = tokenizer.basic_tokenizer.tokenize(origin_sent... |
def derivatives_in_prolate_spheroidal_coordinates():
a = symbols('a', real=True)
coords = (xi, eta, phi) = symbols('xi eta phi', real=True)
(ps3d, er, eth, ephi) = Ga.build('e_xi e_eta e_phi', X=[(((a * sinh(xi)) * sin(eta)) * cos(phi)), (((a * sinh(xi)) * sin(eta)) * sin(phi)), ((a * cosh(xi)) * cos(eta))]... |
class Solution():
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
letters = dict()
for i in magazine:
letters[i] = (letters.get(i, 0) + 1)
for letter in ransomNote:
if (letter in letters):
if (letters[letter] <= 0):
... |
class webvision_dataloader():
def __init__(self, batch_size, num_class, num_workers, root_dir, log):
self.batch_size = batch_size
self.num_class = num_class
self.num_workers = num_workers
self.root_dir = root_dir
self.log = log
self.transform_train = transforms.Compos... |
def sbml_translator(input_file, output_file=None, convention_file=None, naming_conventions=None, user_structures=None, molecule_id=False, atomize=False, pathway_commons=False, verbose=False):
logger = get_logger(__name__, log_level=verbose)
sbmltrans_bin = pf.get_path('atomizer')
sbmltrans_args = [sbmltrans... |
def DecodeBase58Check(psz: Union[(bytes, str)]) -> bytes:
vchRet = base_decode(psz, base=58)
payload = vchRet[0:(- 4)]
csum_found = vchRet[(- 4):]
csum_calculated = sha256d(payload)[0:4]
if (csum_calculated != csum_found):
raise InvalidChecksum(f'calculated {csum_calculated.hex()}, found {cs... |
_tf
class TFXLMModelTest(TFModelTesterMixin, unittest.TestCase):
all_model_classes = ((TFXLMModel, TFXLMWithLMHeadModel, TFXLMForSequenceClassification, TFXLMForQuestionAnsweringSimple, TFXLMForTokenClassification, TFXLMForMultipleChoice) if is_tf_available() else ())
all_generative_model_classes = ((TFXLMWithL... |
def test_tc_bit_defers():
zc = Zeroconf(interfaces=['127.0.0.1'])
_wait_for_start(zc)
type_ = '_tcbitdefer._tcp.local.'
name = 'knownname'
name2 = 'knownname2'
name3 = 'knownname3'
registration_name = f'{name}.{type_}'
registration2_name = f'{name2}.{type_}'
registration3_name = f'{n... |
def test_text_battery_charging(monkeypatch):
loaded_bat = BatteryStatus(state=BatteryState.CHARGING, percent=0.5, power=15.0, time=1729)
with monkeypatch.context() as manager:
manager.setattr(battery, 'load_battery', dummy_load_battery(loaded_bat))
batt = Battery()
text = batt.poll()
ass... |
def get_display_opts(options, argv=sys.argv):
from Xlib import display, Xatom
import os
name = os.path.splitext(os.path.basename(argv[0]))[0]
optdb = ResourceDB()
leftargv = optdb.getopt(name, argv[1:], options)
dname = optdb.get((name + '.display'), (name + '.Display'), None)
d = display.Di... |
def get_compiled_3_regular_maxcut_circuit(problem: ThreeRegularProblem, device: cirq.Device, gammas: Sequence[float], betas: Sequence[float]) -> Tuple[(List[cirq.Qid], cirq.Circuit, List[cirq.Qid])]:
(initial_qubits, circuit, final_qubits) = get_routed_3_regular_maxcut_circuit(problem_graph=problem.graph, device=de... |
class F27_Url(F18_Url):
removedKeywords = F18_Url.removedKeywords
removedAttrs = F18_Url.removedAttrs
def __init__(self, *args, **kwargs):
F18_Url.__init__(self, *args, **kwargs)
self.metalink = kwargs.get('metalink', None)
self.exclusive_required_options.append(('metalink', '--metal... |
class RetinaNetLossComputation(RPNLossComputation):
def __init__(self, proposal_matcher, box_coder, generate_labels_func, sigmoid_focal_loss, bbox_reg_beta=0.11, regress_norm=1.0):
self.proposal_matcher = proposal_matcher
self.box_coder = box_coder
self.box_cls_loss_func = sigmoid_focal_loss... |
def ex_config():
num_epochs = 20
patience = 100
batch_size = 32
latent_dim = 64
som_dim = [8, 8]
learning_rate = 0.0005
alpha = 1.0
beta = 0.9
gamma = 1.8
tau = 1.4
decay_factor = 0.9
name = ex.get_experiment_info()['name']
ex_name = '{}_{}_{}-{}_{}_{}'.format(name, l... |
def duration(entry, option_key='Duration', **kwargs):
time_string = entry.split(' ')
seconds = 0
minutes = 0
hours = 0
days = 0
weeks = 0
for interval in time_string:
if _re.match('^[\\d]+s$', interval.lower()):
seconds = (+ int(interval.lower().rstrip('s')))
elif... |
def test_main_no_spec(capsys: pytest.CaptureFixture[str]) -> None:
with pytest.raises(SystemExit) as excinfo:
find_extra_reqs.main(arguments=[])
expected_code = 2
assert (excinfo.value.code == expected_code)
err = capsys.readouterr().err
assert err.endswith('error: no source files or directo... |
class DiamondShifted(unittest.TestCase):
def setUpClass(cls):
cell = gto.Cell()
cell.verbose = 4
cell.output = '/dev/null'
cell.atom = 'C 0 0 0; C 0. 0. 0.'
cell.a = '\n 1. 1. 0.\n 0. 1. 1.\n 1. 0. 1.\n '
cell.pseudo = 'gth-hf-rev'
... |
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_config_file', default=None, type=str, required=True, help='The con... |
class Conv3x3(nn.Module):
def __init__(self, in_channels, out_channels, bn_norm, stride=1, groups=1):
super(Conv3x3, self).__init__()
self.conv = nn.Conv2d(in_channels, out_channels, 3, stride=stride, padding=1, bias=False, groups=groups)
self.bn = get_norm(bn_norm, out_channels)
sel... |
class panZoomDisplay(QWidget):
updated = pyqtSignal()
def __init__(self):
super().__init__()
self.setMinimumSize(201, 151)
self.scale = (200 / picam2.camera_properties['ScalerCropMaximum'][2])
self.zoom_level_ = 1.0
self.max_zoom = 7.0
self.zoom_step = 0.1
def... |
def _segmentation_evaluation_old(args: SharedArgs, dataset: Dataset, label_map: Optional[LabelMap], results_dir: Path) -> Optional[SegmentationEvaluation]:
if (not label_map):
return None
if (not _segmentation_results_available(results_dir, dataset.video_data)):
return None
logging.info('Run... |
def optimize(instance, max_time=10000, time_limit=100, threads=1):
model = cp_model.CpModel()
start_vars = dict()
end_vars = dict()
durations = dict()
interval_vars = dict()
for task in instance.tasks:
start_vars[task] = model.NewIntVar(0, max_time, ('start' + task.name))
end_var... |
def parse_interval_string(interval, delimiter='-'):
numbers = '[0-9]'
age_types = '[smhdwy]'
agetypes_re = re.compile(age_types, re.IGNORECASE)
age_spec = ('(?:%s+%s?)+' % (numbers, age_types))
agespec_re = re.compile(age_spec, re.IGNORECASE)
period_re = re.compile(('^%s( *%s *%s?)?$' % (age_spe... |
class TAG_List(TAG, list):
id = 9
def __init__(self, name: str, data: list) -> None:
TAG.__init__(self, name)
list.__init__(self, data)
def pack_data(self) -> bytes:
if (len(self) > 0):
return ((BufferUtil.pack('b', self[0].id) + BufferUtil.pack('i', len(self))) + b''.joi... |
class KnownValues(unittest.TestCase):
def test_nohbrid_lda(self):
td = rks.CasidaTDDFT(mf_lda)
es = (td.kernel(nstates=5)[0] * 27.2114)
self.assertAlmostEqual(lib.fp(es), (- 41.), 5)
ref = [9., 9., 14., 30., 30.]
self.assertAlmostEqual(abs((es - ref)).max(), 0, 5)
def tes... |
.parametrize('history_num_frames', [1, 2, 3, 4])
.parametrize('dataset_cls', [EgoDataset, AgentDataset])
def test_non_zero_history(history_num_frames: int, dataset_cls: Callable, zarr_dataset: ChunkedDataset, dmg: LocalDataManager, cfg: dict) -> None:
cfg['model_params']['history_num_frames'] = history_num_frames
... |
class ConvLayer(nn.Module):
def __init__(self, c_in):
super(ConvLayer, self).__init__()
self.downConv = nn.Conv1d(in_channels=c_in, out_channels=c_in, kernel_size=3, padding=2, padding_mode='circular')
self.norm = nn.BatchNorm1d(c_in)
self.activation = nn.ELU()
self.maxPool =... |
class DataTrainingArguments():
train_file: Optional[str] = field(default=None, metadata={'help': 'The input training data file (a text file).'})
validation_file: Optional[str] = field(default=None, metadata={'help': 'An optional input evaluation data file to evaluate the perplexity on (a text file).'})
over... |
def test_new_style():
assert (get_attrs_shape(NewStyle) == Shape(input=InputShape(constructor=NewStyle, kwargs=None, fields=(InputField(type=int, id='a', default=NoDefault(), is_required=True, metadata=MappingProxyType({}), original=ANY), InputField(type=str, id='_b', default=NoDefault(), is_required=True, metadata... |
class _PrefetchData():
def __init__(self, source_datapipe, buffer_size: int):
self.run_prefetcher: bool = True
self.prefetch_buffer: Deque = deque()
self.buffer_size: int = buffer_size
self.source_datapipe = source_datapipe
self.stop_iteration: bool = False
self.pause... |
def test_generate_range_error():
err_str = generate_range_error(1, constants.INFINITY)
assert (err_str == 'expected at least 1 argument')
err_str = generate_range_error(2, constants.INFINITY)
assert (err_str == 'expected at least 2 arguments')
err_str = generate_range_error(1, 1)
assert (err_str... |
class TestTransformerPhaser(unittest.TestCase):
def test_default(self):
tfm = new_transformer()
tfm.phaser()
actual_args = tfm.effects
expected_args = ['phaser', '0.800000', '0.740000', '3.000000', '0.400000', '0.500000', '-s']
self.assertEqual(expected_args, actual_args)
... |
.parametrize('map_variables', [True, False])
.parametrize('endpoint,function,params,json_response', [('forecast/radiation_and_weather', pvlib.iotools.get_solcast_forecast, dict(api_key='1234', latitude=(- 33.856784), longitude=51.215297, hours='5', period='PT1H', output_parameters='dni'), {'forecast': [{'dni': 0, 'peri... |
class Synapse_AMOS(Dataset):
def __init__(self, split='train', repeat=None, transform=None, unlabeled=False, is_val=False, task='synapse', num_cls=1):
self.ids_list = read_list(split, task=task)
self.repeat = repeat
self.task = task
if (self.repeat is None):
self.repeat =... |
def _create_completion(model: str, messages: list, stream: bool, temperature: float=0.7, **kwargs):
headers = {'Content-Type': 'application/json', 'Accept': '*/*', 'Accept-Language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7,ja;q=0.6,zh-TW;q=0.5,zh;q=0.4'}
data = {'messages': messages, 'model': model}
response =... |
(scope='module')
def chat_permissions():
return ChatPermissions(can_send_messages=True, can_send_polls=True, can_send_other_messages=True, can_add_web_page_previews=True, can_change_info=True, can_invite_users=True, can_pin_messages=True, can_manage_topics=True, can_send_audios=True, can_send_documents=True, can_se... |
class CarveFileSystem(MountpointFileSystemMixin, LoopbackFileSystemMixin, FileSystem):
type = 'carve'
def __init__(self, volume, freespace=True):
super().__init__(volume)
self.freespace = freespace
(dependencies.photorec)
def mount(self):
self._make_mountpoint(suffix='carve')
... |
def learn_density(threshold, use_threshold, distribution, train_set_x, train_set_y, test_set_x, test_set_y):
set_data_type(distribution)
if (distribution == Distribution.RANDOM):
parameter = ParameterPool.RANDOM.value
elif (distribution == Distribution.LOGNORMAL):
parameter = ParameterPool.L... |
class ConvBnReLU3D(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, pad=1):
super(ConvBnReLU3D, self).__init__()
self.conv = nn.Conv3d(in_channels, out_channels, kernel_size, stride=stride, padding=pad, bias=False)
self.bn = nn.BatchNorm3d(out_channels)
... |
class ScaledDotProductAttention(nn.Module):
def __init__(self, temperature, attn_dropout=0.1):
super().__init__()
self.temperature = temperature
self.dropout = nn.Dropout(attn_dropout)
def forward(self, q, k, v, mask=None):
attn = torch.matmul((q / self.temperature), k.transpose(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.