code stringlengths 281 23.7M |
|---|
class RHEL5_Network(FC6_Network):
removedKeywords = FC6_Network.removedKeywords
removedAttrs = FC6_Network.removedAttrs
def __init__(self, writePriority=0, *args, **kwargs):
FC6_Network.__init__(self, writePriority, *args, **kwargs)
self.bootprotoList.append(BOOTPROTO_QUERY)
def _getPars... |
class InteractiveBrowser(RefBrowser):
def __init__(self, rootobject, maxdepth=3, str_func=gui_default_str_function, repeat=True):
if (tkinter is None):
raise ImportError('InteractiveBrowser requires Tkinter to be installed.')
RefBrowser.__init__(self, rootobject, maxdepth, str_func, repe... |
def build_prompt(cur_cls_name: str, sentence: str, event_ontology: dict, args) -> str:
if args.event_detection:
sentence = sentence.replace('"', "'")
text_prompt = 'def assert_event_trigger_words_and_type(event_text, trigger_words: List[str], event_type):\n # trigger word need to be a word in the... |
class OneSlackSSVM(BaseSSVM):
def __init__(self, model, max_iter=10000, C=1.0, check_constraints=False, verbose=0, negativity_constraint=None, n_jobs=1, break_on_bad=False, show_loss_every=0, tol=0.001, inference_cache=0, inactive_threshold=1e-05, inactive_window=50, logger=None, cache_tol='auto', switch_to=None):
... |
def validator(xmlfile):
try:
tree = ET.parse(xmlfile)
except ET.ParseError:
raise ValidationError(_('Cannot parse the style file. Please ensure your file is correct.'))
root = tree.getroot()
if ((not root) or (not (root.tag == 'qgis_style'))):
raise ValidationError(_('Invalid roo... |
class PytorchModuleHook(metaclass=ABCMeta):
def hook(self, *args, **kwargs):
def hook_type(self) -> str:
def register(self, module):
assert isinstance(module, torch.nn.Module)
if (self.hook_type == 'forward'):
h = module.register_forward_hook(self.hook)
elif (self.hook_ty... |
class TrainRegSet(torch.utils.data.Dataset):
def __init__(self, data_root, image_size):
super().__init__()
self.transform = transforms.Compose([transforms.Resize((image_size, image_size)), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
self.imgs = torchvision... |
class Effect8468(BaseEffect):
type = 'passive'
def handler(fit, module, context, projectionRange, **kwargs):
module.forceItemAttr('isBlackOpsJumpPortalPassenger', module.getModifiedChargeAttr('isBlackOpsJumpPortalPassenger'), **kwargs)
module.forceItemAttr('isBlackOpsJumpConduitPassenger', modul... |
class TFConvNextPreTrainedModel(TFPreTrainedModel):
config_class = ConvNextConfig
base_model_prefix = 'convnext'
main_input_name = 'pixel_values'
def dummy_inputs(self) -> Dict[(str, tf.Tensor)]:
VISION_DUMMY_INPUTS = tf.random.uniform(shape=(3, self.config.num_channels, self.config.image_size, ... |
def direct_junction_right_multi_lane_fixture():
junction_creator_direct = xodr.DirectJunctionCreator(id=400, name='second_highway_connection')
main_road = xodr.create_road(xodr.Line(200), 1, right_lanes=3, left_lanes=3)
small_road = xodr.create_road(xodr.Line(200), 2, right_lanes=2, left_lanes=0)
return... |
class TLNK(TestCase):
def test_default(self):
frame = LNK()
self.assertEqual(frame.frameid, u'XXX')
self.assertEqual(frame.url, u'')
def test_upgrade(self):
url = '
frame = LNK(frameid='PIC', url=url, data=b'\x00')
new = LINK(frame)
self.assertEqual(new.fr... |
class TestPositions(zf.WithMakeAlgo, zf.ZiplineTestCase):
START_DATE = pd.Timestamp('2006-01-03', tz='utc')
END_DATE = pd.Timestamp('2006-01-06', tz='utc')
SIM_PARAMS_CAPITAL_BASE = 1000
ASSET_FINDER_EQUITY_SIDS = (1, 133)
SIM_PARAMS_DATA_FREQUENCY = 'daily'
def make_equity_daily_bar_data(cls, c... |
def test_unique_uri_validator_serializer_create_error(db):
validator = ViewUniqueURIValidator()
serializer = ViewSerializer()
with pytest.raises(RestFameworkValidationError):
validator({'uri_prefix': settings.DEFAULT_URI_PREFIX, 'uri_path': View.objects.filter(uri_prefix=settings.DEFAULT_URI_PREFIX)... |
class VcfWriter():
def __init__(self, output, header_str):
self.output = output
self.header_str = header_str
tmp = tempfile.NamedTemporaryFile(mode='w', suffix='.vcf')
self.vcf = Writer.from_string(tmp, self.header_str)
print(self.header_str, end='', file=self.output)
def... |
class discriminatorLoss(nn.Module):
def __init__(self, dim_ins, loss=nn.BCEWithLogitsLoss()):
super(discriminatorLoss, self).__init__()
self.classifier = []
for dim in dim_ins:
self.classifier.append(Discriminator(dim_in=dim, dim_out=2).cuda())
self.avg_pool = nn.Adaptive... |
class biased_softplus(nn.Module):
def __init__(self, bias: float, min_val: float=0.01) -> None:
super().__init__()
self.bias = inv_softplus((bias - min_val))
self.min_val = min_val
def forward(self, x: torch.Tensor) -> torch.Tensor:
return (torch.nn.functional.softplus((x + self.... |
class Network():
def __init__(self, name=None, func=None, **static_kwargs):
self._init_fields()
self.name = name
self.static_kwargs = dict(static_kwargs)
(module, self._build_func_name) = import_module(func)
self._build_module_src = inspect.getsource(module)
self._bui... |
class Effect3480(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Large Energy Turret')), 'trackingSpeed', ship.getModifiedItemAttr('shipBonusAB2'), skill='Amarr Battleship', **kwargs) |
class FC3_DisplayMode(KickstartCommand):
removedKeywords = KickstartCommand.removedKeywords
removedAttrs = KickstartCommand.removedAttrs
def __init__(self, writePriority=0, *args, **kwargs):
KickstartCommand.__init__(self, writePriority, *args, **kwargs)
self.displayMode = kwargs.get('displa... |
class AWSSession(Session):
def __init__(self, session=None, aws_unsigned=None, aws_access_key_id=None, aws_secret_access_key=None, aws_session_token=None, region_name=None, profile_name=None, endpoint_url=None, requester_pays=False):
if (aws_unsigned is None):
aws_unsigned = parse_bool(os.getenv... |
def get_source_fields(fields=None):
if (fields is None):
fields = {}
fields['src'] = torchtext.data.Field(pad_token=Constants.PAD_WORD, eos_token=Constants.EOS_WORD, include_lengths=True)
fields['indices'] = torchtext.data.Field(use_vocab=False, dtype=torch.long, sequential=False)
return fields |
def get_all_metrics(test, gen, k=None, n_jobs=1, device='cpu', batch_size=512, test_scaffolds=None, ptest=None, ptest_scaffolds=None, pool=None, gpu=None, train=None):
if (k is None):
k = [1000, 10000]
disable_rdkit_log()
metrics = {}
if (gpu is not None):
warnings.warn('parameter `gpu` ... |
def format_args(args: Sequence[Any]=None, kwargs: Mapping[(str, Any)]=None) -> str:
if (args is not None):
arglist = [utils.compact_text(repr(arg), 200) for arg in args]
else:
arglist = []
if (kwargs is not None):
for (k, v) in kwargs.items():
arglist.append('{}={}'.forma... |
class Effect6683(BaseEffect):
type = ('projected', 'active')
def handler(fit, container, context, projectionRange, **kwargs):
if ('projected' not in context):
return
if fit.ship.getModifiedItemAttr('disallowOffensiveModifiers'):
return
appliedBoost = container.get... |
def test_hrnet_backbone():
extra = dict(stage1=dict(num_modules=1, num_branches=1, block='BOTTLENECK', num_blocks=(4,), num_channels=(64,)), stage2=dict(num_modules=1, num_branches=2, block='BASIC', num_blocks=(4, 4), num_channels=(32, 64)), stage3=dict(num_modules=4, num_branches=3, block='BASIC', num_blocks=(4, 4... |
class BiLevelDatasetSpecification(collections.namedtuple('BiLevelDatasetSpecification', 'name, superclasses_per_split, classes_per_superclass, images_per_class, superclass_names, class_names, path, file_pattern')):
def initialize(self, restricted_classes_per_split=None):
if (self.file_pattern not in ['{}.tf... |
def test_list_lid_groups():
with Simulation(MODEL_LIDS_PATH) as sim:
for (i, group) in enumerate(LidGroups(sim)):
if (i == 0):
assert ('subcatchment {} has {} lid units'.format(group, len(group)) == 'subcatchment 1 has 0 lid units')
if (i == 1):
assert... |
class Discriminator(BaseNetwork):
def __init__(self, style_dim=64, max_conv_dim=512):
super().__init__()
dim_in = 64
blocks = []
blocks += [spectral_norm(nn.Conv2d(3, dim_in, 3, 1, 1))]
repeat_num = (int(np.log2(256)) - 2)
for _ in range(repeat_num):
dim_o... |
class ReadPoTestCase(unittest.TestCase):
def test_preserve_locale(self):
buf = StringIO('msgid "foo"\nmsgstr "Voh"')
catalog = pofile.read_po(buf, locale='en_US')
assert (Locale('en', 'US') == catalog.locale)
def test_locale_gets_overridden_by_file(self):
buf = StringIO('\nmsgid ... |
class SAM(nn.Module):
def __init__(self, n_feat, kernel_size, bias):
super(SAM, self).__init__()
self.conv1 = conv(n_feat, n_feat, kernel_size, bias=bias)
self.conv2 = conv(n_feat, 1, kernel_size, bias=bias)
self.conv3 = conv(1, n_feat, kernel_size, bias=bias)
def forward(self, x... |
def main() -> None:
parser = argparse.ArgumentParser(description='Format files with usort.', fromfile_prefix_chars='')
parser.add_argument('filenames', nargs='+', help='paths to lint')
args = parser.parse_args()
with concurrent.futures.ThreadPoolExecutor(max_workers=os.cpu_count(), thread_name_prefix='T... |
def get_split(split_name, dataset_dir, file_pattern=None, reader=None):
if (split_name not in SPLITS_TO_SIZES):
raise ValueError(('split name %s was not recognized.' % split_name))
if (not file_pattern):
file_pattern = _FILE_PATTERN
file_pattern = os.path.join(dataset_dir, (file_pattern % sp... |
def direct_junction_left_lane_fixture():
junction_creator_direct = xodr.DirectJunctionCreator(id=400, name='second_highway_connection')
main_road = xodr.create_road(xodr.Line(200), 1, right_lanes=3, left_lanes=3)
small_road = xodr.create_road(xodr.Line(200), 2, right_lanes=0, left_lanes=1)
return (main_... |
def main():
args = parser.parse_args()
if (args.seed is not None):
random.seed(args.seed)
torch.manual_seed(args.seed)
cudnn.deterministic = True
warnings.warn('You have chosen to seed training. This will turn on the CUDNN deterministic setting, which can slow down your training ... |
def test_typeddict_attribute_errors(c: Converter) -> None:
class C(TypedDict):
a: int
b: int
try:
c.structure({}, C)
except Exception as exc:
assert (transform_error(exc) == ['required field missing $.a', 'required field missing $.b'])
try:
c.structure({'b': 1},... |
def nufft_adjoint(input, coord, oshape, oversamp=1.25, width=4):
ndim = coord.shape[(- 1)]
beta = (np.pi * (((((width / oversamp) * (oversamp - 0.5)) ** 2) - 0.8) ** 0.5))
oshape = list(oshape)
os_shape = _get_oversamp_shape(oshape, ndim, oversamp)
coord = _scale_coord(coord, oshape, oversamp)
o... |
class RaveberryTest(TransactionTestCase):
celery_worker: Any
def setUpClass(cls) -> None:
super().setUpClass()
cls.celery_worker = start_worker(app, perform_ping_check=False)
cls.celery_worker.__enter__()
logging.getLogger().setLevel(logging.WARNING)
def tearDownClass(cls) ->... |
def test_change_level_undo(pytester: Pytester) -> None:
pytester.makepyfile("\n import logging\n\n def test1(caplog):\n caplog.set_level(logging.INFO)\n # using + operator here so fnmatch_lines doesn't match the code in the traceback\n logging.info('log from ' + 'test1... |
def test_canonicalize_vcf(shared_datadir, tmp_path):
path = path_for_test(shared_datadir, 'sample.vcf.gz')
output = tmp_path.joinpath('vcf.zarr').as_posix()
canonicalize_vcf(path, output)
with gzip.open(path, 'rt') as f:
assert ('NS=3;DP=9;AA=G;AN=6;AC=3,1' in f.read())
with open(output, 'r'... |
def m3u8_to_mp3(url, name):
ts_content = get_ts(url)
if (ts_content is None):
raise TypeError('Empty mp3 content to save.')
tmp_file = NamedTemporaryFile(delete=False, suffix='.mp3')
tmp_file.write(ts_content)
tmp_file.close()
audioclip = AudioFileClip(tmp_file.name)
audioclip.write_... |
(shared_memory=True)
def createvectors(smm=None, sm=None):
vec_size =
start = timer()
a = b = np.array(np.random.sample(vec_size), dtype=np.float32)
shma = smm.SharedMemory(a.nbytes)
shmb = smm.SharedMemory(b.nbytes)
names = (shma.name, shmb.name, a.shape, b.shape, a.dtype, b.dtype)
duratio... |
def _get_best_indexes(logits, n_best_size):
index_and_score = sorted(enumerate(logits), key=(lambda x: x[1]), reverse=True)
best_indexes = []
for i in range(len(index_and_score)):
if (i >= n_best_size):
break
best_indexes.append(index_and_score[i][0])
return best_indexes |
def main(cfg, args):
print(f'...Evaluating on {args.eval_ds.lower()} {args.eval_set.lower()} set...')
device = 'cuda'
model = Token3d(num_blocks=cfg.MODEL.ENCODER.NUM_BLOCKS, num_heads=cfg.MODEL.ENCODER.NUM_HEADS, st_mode=cfg.MODEL.ENCODER.SPA_TEMP_MODE, mask_ratio=cfg.MODEL.MASK_RATIO, temporal_layers=cfg.... |
def test_DecisionMatrix_self_eq(data_values):
(mtx, objectives, weights, alternatives, criteria) = data_values(seed=42)
dm = data.mkdm(matrix=mtx, objectives=objectives, weights=weights, alternatives=alternatives, criteria=criteria)
same = dm
assert (dm is same)
assert dm.equals(same) |
def add_aoi_metadata_to_map(aoi, map):
aoi = dataset.loc[aoi]
aoi_style = {'color': '#c0392b', 'fill': False}
aoi_polygon = Polygon(AOIGenerator.bounds_to_bounding_box(*eval(aoi['bounds'])))
aoi_geojson = folium.GeoJson(aoi_polygon, style_function=(lambda x: aoi_style))
aoi_geojson.add_to(map)
a... |
def _walk_refs(log):
for (i, line) in enumerate(log.split('\n')):
for ref in line.split(', '):
match = re.fullmatch('origin/chromium/(\\d+)', ref.strip())
if match:
return (int(match.group(1)), i)
assert False, 'Failed to find versioned commit - log too small?' |
def ADMM_bqp_unconstrained(A, b, all_params=None):
initial_params = {'std_threshold': 1e-06, 'gamma_val': 1.0, 'gamma_factor': 0.99, 'initial_rho': 5, 'learning_fact': (1 + (3 / 100)), 'rho_upper_limit': 1000, 'history_size': 5, 'rho_change_step': 5, 'rel_tol': 1e-05, 'stop_threshold': 0.001, 'max_iters': 10000.0, ... |
def test_no_keys_with_formatting():
context = Context({'k1': 'v1', 'k2': 'x{k1}x', 'k3': [0, 1, 2], 'debug': {'format': True}})
with patch_logger('pypyr.steps.debug', logging.INFO) as mock_logger_info:
debug.run_step(context)
assert (mock_logger_info.mock_calls == [call("\n{'debug': {'format': True}... |
class OHMultiView(object):
def __init__(self, mean, std, views='ww', aug='auto'):
assert all(((v in 'wst') for v in views))
assert (aug in ['rand', 'auto'])
self.views = views
self.weak = transforms.Compose([transforms.Resize((256, 256)), transforms.RandomCrop(224), transforms.Random... |
def _do_download(version, download_base, to_dir, download_delay):
egg = os.path.join(to_dir, ('setuptools-%s-py%d.%d.egg' % (version, sys.version_info[0], sys.version_info[1])))
if (not os.path.exists(egg)):
archive = download_setuptools(version, download_base, to_dir, download_delay)
_build_egg... |
def sorino_ratio(qf_series: QFSeries, frequency: Frequency, risk_free: float=0) -> float:
annualised_growth_rate = cagr(qf_series, frequency)
negative_returns = qf_series[(qf_series < 0)]
annualised_downside_vol = get_volatility(negative_returns, frequency, annualise=True)
ratio = ((annualised_growth_ra... |
def test_bpe_codes_adapter():
test_f = StringIO('#version:2.0\ne n \ne r \ne n</w> ')
adapted = adapt_bpe_codes(test_f)
assert (adapted.readline() == '#version:2.0\n')
assert (adapted.readline() == 'e n\n')
assert (adapted.readline() == 'e r\n')
for line in adapted:
assert (line == 'e n<... |
def test_jedi_completion_ordering(config, workspace):
com_position = {'line': 8, 'character': 0}
doc = Document(DOC_URI, workspace, DOC)
config.update({'plugins': {'jedi_completion': {'resolve_at_most': math.inf}}})
completions = pylsp_jedi_completions(config, doc, com_position)
items = {c['label']:... |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
padding = (2 - stride)
... |
class KnownValues(unittest.TestCase):
def test_ea_adc2(self):
myadc.method_type = 'ea'
(e, v, p, x) = myadc.kernel(nroots=3)
e_corr = myadc.e_corr
self.assertAlmostEqual(e_corr, (- 0.), 6)
self.assertAlmostEqual(e[0], (- 0.), 6)
self.assertAlmostEqual(e[1], 0., 6)
... |
class ThreeInterpolate(Function):
def forward(ctx, features: torch.Tensor, idx: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:
assert features.is_contiguous()
assert idx.is_contiguous()
assert weight.is_contiguous()
(B, c, m) = features.size()
n = idx.size(1)
ct... |
def AugmentedLayer(pad_zeros):
def init_fun(rng, input_shape):
output_shape = (input_shape[:(- 1)] + ((pad_zeros + input_shape[(- 1)]),))
return (output_shape, ())
def apply_fun(params, inputs, **kwargs):
x = inputs
xzeros = _augment(x, pad_zeros)
return xzeros
return... |
_transform('ImgPilToMultiCrop')
class ImgPilToMultiCrop(ClassyTransform):
def __init__(self, total_num_crops, num_crops, size_crops, crop_scales):
assert (np.sum(num_crops) == total_num_crops)
assert (len(size_crops) == len(num_crops))
assert (len(size_crops) == len(crop_scales))
tra... |
_module()
class SCNetMaskHead(FCNMaskHead):
def __init__(self, conv_to_res=True, **kwargs):
super(SCNetMaskHead, self).__init__(**kwargs)
self.conv_to_res = conv_to_res
if conv_to_res:
assert (self.conv_kernel_size == 3)
self.num_res_blocks = (self.num_convs // 2)
... |
class ExportToFolderDialog(Dialog):
def __init__(self, parent, pattern):
super().__init__(title=_('Export Playlist to Folder'), transient_for=parent, use_header_bar=True)
self.set_default_size(400, (- 1))
self.set_resizable(True)
self.set_border_width(6)
self.vbox.set_spacing... |
class ParameterQuantizer(torch.autograd.Function):
def compute_gradients(tensor: torch.Tensor, grad: torch.Tensor, intermediate_result: IntermediateResult, channel_axis: int) -> Tuple[(torch.Tensor, torch.Tensor)]:
tensor_grad = (intermediate_result.mask_tensor * grad)
(tensor_encoding_min_grad, ten... |
class DebugMode(contextlib.AbstractContextManager):
from setuptools_scm import _log as __module
def __init__(self) -> None:
self.__stack = contextlib.ExitStack()
def __enter__(self) -> Self:
self.enable()
return self
def __exit__(self, exc_type: (type[BaseException] | None), exc_... |
def extract_javascript(fileobj: _FileObj, keywords: Mapping[(str, _Keyword)], comment_tags: Collection[str], options: _JSOptions, lineno: int=1) -> Generator[(_ExtractionResult, None, None)]:
from babel.messages.jslexer import Token, tokenize, unquote_string
funcname = message_lineno = None
messages = []
... |
def simxGetObjectPosition(clientID, objectHandle, relativeToObjectHandle, operationMode):
position = (ct.c_float * 3)()
ret = c_GetObjectPosition(clientID, objectHandle, relativeToObjectHandle, position, operationMode)
arr = []
for i in range(3):
arr.append(position[i])
return (ret, arr) |
def GetUnit(itemsets):
count = 0
unit = S[str(itemsets[0])][:]
for i in range(1, len(itemsets)):
for j in range(SeqNum):
unit[j] = sorted(list((set(unit[j]) & set(S[str(itemsets[i])][j]))))
for i in range(SeqNum):
count += len(unit[i])
return (count, unit) |
def main() -> None:
args = _get_command_line_arguments()
logging.getLogger().setLevel(logging.DEBUG)
input_dir = Path(args[Args.INPUT_VIDEOS_DIR])
if (not input_dir.is_dir()):
raise ValueError(f'Input directory failed is_dir(): {input_dir}')
features_dir = Path(args[Args.FEATURES_DIR])
f... |
class AddNewModelCommand(BaseTransformersCLICommand):
def register_subcommand(parser: ArgumentParser):
add_new_model_parser = parser.add_parser('add-new-model')
add_new_model_parser.add_argument('--testing', action='store_true', help='If in testing mode.')
add_new_model_parser.add_argument('... |
class RSAPrivateKey(PrivateKey):
def __init__(self):
self._private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
_process_wide_key = None
_process_wide_key_lock = threading.RLock()
def process_wide(cls) -> RSAPrivateKey:
if (cls._process_wide_key is None):
... |
class Effect604(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Large Projectile Turret')), 'speed', ship.getModifiedItemAttr('shipBonusMB2'), skill='Minmatar Battleship', **kwargs) |
def process_dataset(fasta_dir: Path, h5_dir: Optional[Path], glob_pattern: str, num_workers: int, tokenizer_file: Path, tokenizer_blocksize: int, kmer_size: int, train_val_test_split: Optional[Dict[(str, float)]], node_rank: int, num_nodes: int, subsample: int) -> None:
if (not fasta_dir):
raise ValueError(... |
def _parse_converter(ctx: mypy.plugin.ClassDefContext, converter_expr: (Expression | None)) -> (Converter | None):
if (not converter_expr):
return None
converter_info = Converter()
if (isinstance(converter_expr, CallExpr) and isinstance(converter_expr.callee, RefExpr) and (converter_expr.callee.full... |
class AllowMoveAZPSimulatedAnnealing(AllowMoveStrategy):
def __init__(self, init_temperature, sa_moves_term=float('inf')):
self.observers_min_sa_moves = []
self.observers_move_made = []
self.t = init_temperature
if ((not isinstance(sa_moves_term, numbers.Integral)) or (sa_moves_term ... |
def test_geographic_crs__from_methods():
assert_maker_inheritance_valid(GeographicCRS.from_epsg(4326), GeographicCRS)
assert_maker_inheritance_valid(GeographicCRS.from_string('EPSG:4326'), GeographicCRS)
assert_maker_inheritance_valid(GeographicCRS.from_proj4('+proj=latlon'), GeographicCRS)
assert_maker... |
class Pick(Object):
public_id = ResourceReference.T(xmlstyle='attribute', xmltagname='publicID')
comment_list = List.T(Comment.T())
time = TimeQuantity.T()
waveform_id = WaveformStreamID.T(xmltagname='waveformID')
filter_id = ResourceReference.T(optional=True, xmltagname='filterID')
method_id = ... |
class CanineConfig(PretrainedConfig):
model_type = 'canine'
def __init__(self, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=16384, type_vocab_size=16, initializer_range... |
class COR(IntFlag):
COMPARISON_RESULT_HI = (1 << 14)
COMPARISON_RESULT_GO = (1 << 13)
COMPARISON_RESULT_LO = (1 << 12)
OVERHEAT_DETECTION = (1 << 11)
OVERLOAD_DETECTION = (1 << 10)
OSCILLATION_DETECTION = (1 << 9)
COMPLIANCE_DETECTION = (1 << 8)
SYNCHRONOUS_OPERATION_MASTER_CHANNEL = (1 ... |
class RegistryQueryCommand(ops.cmd.DszCommand):
def __init__(self, plugin='registryquery', prefixes=[], arglist=None, dszquiet=True, hive='l', **optdict):
ops.cmd.DszCommand.__init__(self, plugin=plugin, dszquiet=dszquiet, **optdict)
self.hive = hive
if ('key' in optdict):
self.k... |
('auditwheel.elfutils.open')
('auditwheel.elfutils.ELFFile')
class TestElfFileFilter():
def test_filter(self, elffile_mock, open_mock):
result = elf_file_filter(['file1.so', 'file2.so'])
assert (len(list(result)) == 2)
def test_some_py_files(self, elffile_mock, open_mock):
result = elf_f... |
class A2C_ACKTR():
def __init__(self, actor_critic, value_loss_coef, entropy_coef, lr=None, eps=None, alpha=None, max_grad_norm=None, acktr=False, dril=None):
self.actor_critic = actor_critic
self.acktr = acktr
self.value_loss_coef = value_loss_coef
self.entropy_coef = entropy_coef
... |
.parametrize('num_workers', [1, 2])
def test_train_client(tmpdir, start_ray_client_server_2_cpus, num_workers):
assert ray.util.client.ray.is_connected()
model = BoringModel()
strategy = RayStrategy(num_workers=num_workers)
trainer = get_trainer(tmpdir, strategy=strategy)
train_test(trainer, model) |
class CifarResNet(nn.Module):
def __init__(self, block, depth, channels=3):
super(CifarResNet, self).__init__()
assert (((depth - 2) % 6) == 0), 'depth should be one of 20, 32, 44, 56, 110'
layer_blocks = ((depth - 2) // 6)
self.conv_1_3x3 = nn.Conv2d(channels, 16, kernel_size=3, str... |
class ThreeParallelBloqs(Bloq):
def signature(self) -> Signature:
return Signature.build(stuff=3)
def build_composite_bloq(self, bb: 'BloqBuilder', stuff: 'SoquetT') -> Dict[(str, 'SoquetT')]:
stuff = bb.add(TestParallelCombo(), reg=stuff)
stuff = bb.add(TestParallelCombo(), reg=stuff)
... |
class nnUNetTrainerVanillaAdam3en4(nnUNetTrainerVanillaAdam):
def __init__(self, plans: dict, configuration: str, fold: int, dataset_json: dict, unpack_dataset: bool=True, device: torch.device=torch.device('cuda')):
super().__init__(plans, configuration, fold, dataset_json, unpack_dataset, device)
s... |
def test_read_tmy3_no_coerce_year():
coerce_year = None
(data, _) = tmy.read_tmy3(TMY3_TESTFILE, coerce_year=coerce_year, map_variables=False)
assert (1997 and (1999 in data.index.year))
assert (data.index[(- 2)] == pd.Timestamp('1998-12-31 23:00:00-09:00'))
assert (data.index[(- 1)] == pd.Timestamp... |
def os_stat():
orig_os_stat = os.stat
file_mappings = {}
def add_mapping(original, replacement):
file_mappings[original] = replacement
def my_os_stat(*args, **kwargs):
if (args[0] in file_mappings):
args = ((file_mappings.pop(args[0]),) + args[1:])
return orig_os_stat... |
class OpsTestIndicesToDenseVector(tf.test.TestCase):
def test_indices_to_dense_vector(self):
size = 10000
num_indices = np.random.randint(size)
rand_indices = np.random.permutation(np.arange(size))[0:num_indices]
expected_output = np.zeros(size, dtype=np.float32)
expected_out... |
def test_simple_unittest(pytester: Pytester) -> None:
testpath = pytester.makepyfile("\n import unittest\n class MyTestCase(unittest.TestCase):\n def testpassing(self):\n self.assertEqual('foo', 'foo')\n def test_failing(self):\n self.assertEqual('fo... |
def RewireTails():
ToAdd = []
ToRemove = []
for source in Graph:
for target in Graph[source]:
if (len(target) == 1):
NewTarget = (source + target)
while (len(NewTarget) > 1):
if (NewTarget in Graph):
ToAdd.append... |
class GeneratorHubInterface(nn.Module):
def __init__(self, args, task, models):
super().__init__()
self.args = args
self.task = task
self.models = nn.ModuleList(models)
self.src_dict = task.source_dictionary
self.tgt_dict = task.target_dictionary
for model in ... |
class ELF_Phdr():
def __init__(self, p_type, p_offset, p_vaddr, p_paddr, p_filesz, p_memsz, p_flags, p_align):
self.p_type = p_type
self.p_offset = p_offset
self.p_vaddr = p_vaddr
self.p_paddr = p_paddr
self.p_filesz = p_filesz
self.p_memsz = p_memsz
self.p_fl... |
def test_validate_manifest_with_unencoded_unicode():
test_dir = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(test_dir, 'manifest_unencoded_unicode.json'), 'r') as f:
manifest_bytes = f.read()
manifest = DockerSchema1Manifest(Bytes.for_string_or_unicode(manifest_bytes))
diges... |
def find_boundaries(s, w):
ind = w.i
if (((ind + 2) < len(s)) and (s[(ind + 1)].text == "'") and s[(ind + 2)].like_num):
return (ind, (ind + 3))
if (((ind - 2) >= 0) and (s[(ind - 1)].text == "'") and s[(ind - 2)].like_num):
return ((ind - 2), (ind + 1))
if (s[ind].ent_iob == 2):
... |
class TrackNumbers(Gtk.VBox):
def __init__(self, prop, library):
super().__init__(spacing=6)
self.title = _('Track Numbers')
self.set_border_width(12)
label_start = Gtk.Label(label=_('Start fro_m:'), halign=Gtk.Align.END)
label_start.set_use_underline(True)
spin_start... |
def parse_args():
parser = argparse.ArgumentParser(description='kmeans for anchor box')
parser.add_argument('-root', '--data_root', default='/mnt/share/ssd2/dataset', help='dataset root')
parser.add_argument('-d', '--dataset', default='coco', help='coco, voc.')
parser.add_argument('-na', '--num_anchorbo... |
def test_DecisionMatrixStatsAccessor_dir(decision_matrix):
dm = decision_matrix(seed=42, min_alternatives=10, max_alternatives=10, min_criteria=3, max_criteria=3)
stats = data.DecisionMatrixStatsAccessor(dm)
expected = set(data.DecisionMatrixStatsAccessor._DF_WHITELIST)
result = dir(stats)
assert (n... |
def init_from_config(conf: 'configmodule.ConfigContainer') -> None:
assert (_args is not None)
if _args.debug:
init.debug('--debug flag overrides log configs')
return
if ram_handler:
ramlevel = conf.logging.level.ram
init.debug('Configuring RAM loglevel to %s', ramlevel)
... |
def prenet(inputs, is_training, layer_sizes, scope=None):
x = inputs
drop_rate = (0.5 if is_training else 0.0)
with tf.variable_scope((scope or 'prenet')):
for (i, size) in enumerate(layer_sizes):
dense = tf.layers.dense(x, units=size, activation=tf.nn.relu, name=('dense_%d' % (i + 1)))
... |
_ARCH_REGISTRY.register()
class Distiller(Baseline):
def __init__(self, cfg):
super(Distiller, self).__init__(cfg)
num_classes = cfg.MODEL.HEADS.NUM_CLASSES
feat_dim = cfg.MODEL.BACKBONE.FEAT_DIM
norm_type = cfg.MODEL.HEADS.NORM
cfg_t = get_cfg()
cfg_t.merge_from_file... |
def fetch_RW(path):
data_path = os.path.join(path, 'rw/rw.txt')
if (not os.path.exists(data_path)):
os.makedirs(path, exist_ok=True)
archive_path = os.path.join(path, 'rw.zip')
download(' archive_path)
with zipfile.ZipFile(archive_path, 'r') as zip_ref:
zip_ref.extrac... |
def test_resolve_module_exports_from_file_log_on_max_depth(caplog):
path = ((JS_FIXTURES_DIR / 'export-resolution') / 'index.js')
assert (resolve_module_exports_from_file(path, 0) == set())
assert (len(caplog.records) == 1)
assert caplog.records[0].message.endswith('max depth reached')
caplog.record... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.