code stringlengths 281 23.7M |
|---|
def train(train_loader, model, criterion, optimizer, epoch, args, tensor_writer=None):
batch_time = AverageMeter('Time', ':6.3f')
data_time = AverageMeter('Data', ':6.3f')
losses = AverageMeter('Loss', ':.4e')
top1 = AverageMeter('', ':6.2f')
top5 = AverageMeter('', ':6.2f')
progress = ProgressM... |
class Image(SensorData):
def __init__(self, frame_number, width, height, image_type, fov, raw_data):
super(Image, self).__init__(frame_number=frame_number)
assert (len(raw_data) == ((4 * width) * height))
self.width = width
self.height = height
self.type = image_type
... |
def test_single_param_not_dotted_list_values():
param = 'SomethingOrOther'
values = (123, 765, 3512, 756437, 3125)
result = enumerate_param(param, values)
expected = {'SomethingOrOther.1': 123, 'SomethingOrOther.2': 765, 'SomethingOrOther.3': 3512, 'SomethingOrOther.4': 756437, 'SomethingOrOther.5': 312... |
def add_artifacts(resource_database: ResourceDatabase, mode: LayoutArtifactMode, artifact_minimum_progression: int) -> PoolResults:
item_pool: list[PickupEntry] = []
artifacts_to_place = mode.value
for i in range(artifacts_to_place):
item_pool.append(create_artifact(i, artifact_minimum_progression, ... |
class Collate(nn.Module):
def __init__(self, transform=None, device=None):
super().__init__()
self.transform = transform
self.device = device
_mode()
def __call__(self, x: ImageNetData):
out = x.apply((lambda _tensor: _tensor.as_tensor())).pin_memory().to(self.device)
... |
class Application(object):
def __init__(self, conf, options):
self.conf = conf
self.options = options
logging.basicConfig(format=LOG_FORMAT)
self.logger = logging.getLogger()
self.log_filename = None
def setup_log(self, prefix):
prefix = re.sub('[^A-Za-z0-9_-]+', ... |
class AoAModel3_d1_24heads(AttModel):
def __init__(self, opt):
super(AoAModel3_d1_24heads, self).__init__(opt)
self.num_layers = 2
self.use_mean_feats = getattr(opt, 'mean_feats', 1)
if (opt.use_multi_head == 2):
del self.ctx2att
self.ctx2att = (lambda x: x)
... |
class DictTransactionManager(ModbusTransactionManager):
def __init__(self, client, **kwargs):
self.transactions = {}
super().__init__(client, **kwargs)
def __iter__(self):
return iter(self.transactions.keys())
def addTransaction(self, request, tid=None):
tid = (tid if (tid is... |
def plan_and_preprocess(task_string, processes_lowres=default_num_threads, processes_fullres=3, no_preprocessing=False):
from d_lka_former.experiment_planning.experiment_planner_baseline_2DUNet import ExperimentPlanner2D
from d_lka_former.experiment_planning.experiment_planner_baseline_3DUNet import ExperimentP... |
_required
_cache
def version_feedback(request, package_name, version):
plugin = get_object_or_404(Plugin, package_name=package_name)
version = get_object_or_404(PluginVersion, plugin=plugin, version=version)
is_user_plugin_owner: bool = (request.user in plugin.editors)
is_user_has_approval_rights: bool ... |
class CommentMixin(LoginRequiredMixin, SuccessMessageMixin):
model = Comment
fields = ('content',)
template_name = 'dictionary/edit/comment_form.html'
def form_invalid(self, form):
for error in form.errors['content']:
notifications.error(self.request, error)
return super().fo... |
class CondConv(nn.Module):
def __init__(self, in_planes, out_planes, kernel_size, stride, padding=0, dilation=1, grounps=1, bias=True, K=4, init_weight=True):
super().__init__()
self.in_planes = in_planes
self.out_planes = out_planes
self.kernel_size = kernel_size
self.stride... |
def test_solver_can_resolve_sdist_dependencies_with_extras(solver: Solver, repo: Repository, package: ProjectPackage, fixture_dir: FixtureDirGetter) -> None:
pendulum = get_package('pendulum', '2.0.3')
cleo = get_package('cleo', '1.0.0')
repo.add_package(pendulum)
repo.add_package(cleo)
path = (fixt... |
def perturb_iterative(xvar, yvar, predict, nb_iter, eps, eps_iter, loss_fn, delta_init=None, minimize=False, ord=np.inf, clip_min=0.0, clip_max=1.0):
if (delta_init is not None):
delta = delta_init
else:
delta = torch.zeros_like(xvar)
delta.requires_grad_()
for ii in range(nb_iter):
... |
def save_tf_session_single_gpu(sess: tf.compat.v1.Session(), path: 'str', input_tensor: 'str', output_tensor: 'str'):
with sess.graph.as_default():
init = tf.compat.v1.global_variables_initializer()
sess.run(init)
inputs = sess.graph.get_tensor_by_name(input_tensor)
train_out = sess.graph.ge... |
def load_model(model, model_path, opt, optimizer=None):
start_epoch = 0
checkpoint = torch.load(model_path, map_location=(lambda storage, loc: storage))
print('loaded {}, epoch {}'.format(model_path, checkpoint['epoch']))
state_dict_ = checkpoint['state_dict']
state_dict = {}
for k in state_dict... |
class ArgumentCheckedCallable():
def __init__(self, target, explanation=None):
self.target = target
self.explanation = explanation
def __call__(self, *args, **kwargs):
self.checkargs(*args, **kwargs)
return self.target(*args, **kwargs)
def checkargs(self, *args, **kwargs):
... |
class CLUEProcessor(CLSProcessor):
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)
param = {p.split('=')[0... |
def format_to_lines(args):
corpora = {'train': [], 'valid': [], 'test': []}
read_root_path = Path(args.raw_path)
for corpus_type in ['valid', 'test', 'train']:
read_path = (read_root_path / corpus_type)
for fp in read_path.iterdir():
corpora[corpus_type].append(fp)
save_root_... |
class _CppLintState(object):
def __init__(self):
self.verbose_level = 1
self.error_count = 0
self.filters = _DEFAULT_FILTERS[:]
self.counting = 'total'
self.errors_by_category = {}
self.output_format = 'emacs'
def SetOutputFormat(self, output_format):
self... |
class GroupViTVisionConfig(PretrainedConfig):
model_type = 'groupvit_vision_model'
def __init__(self, hidden_size=384, intermediate_size=1536, depths=[6, 3, 3], num_hidden_layers=12, num_group_tokens=[64, 8, 0], num_output_groups=[64, 8, 8], num_attention_heads=6, image_size=224, patch_size=16, num_channels=3, ... |
def runMssqlInfoModule(args):
if (checkOptionsGivenByTheUser(args, ['get-max-info'], checkAccount=False) == False):
return EXIT_MISS_ARGUMENT
if (args['get-max-info'] == True):
mssqlInfo = MssqlInfo(args)
productName = mssqlInfo.__getRemoteVersionThroughTDSResponse__()
args['prin... |
def parse_frame(data, count, mask, extensions):
reader = StreamReader()
for _ in range(count):
reader.feed_data(data)
parser = Frame.parse(reader.read_exact, mask=mask, extensions=extensions)
try:
next(parser)
except StopIteration:
pass
else:
... |
class Counter(dict):
def __missing__(self, k):
return 0
def update(self, other):
for (k, v) in other.items():
self[k] += v
def subtract(self, other):
for (k, v) in other.items():
self[k] -= v
if (self[k] <= 0):
del self[k]
def s... |
def _lcs(a, b):
dp = _lcs_dp(a, b)
i = len(a)
j = len(b)
lcs = deque()
while ((i > 0) and (j > 0)):
if (a[(i - 1)] == b[(j - 1)]):
lcs.appendleft(a[(i - 1)])
i -= 1
j -= 1
elif (dp[(i - 1)][j] >= dp[i][(j - 1)]):
i -= 1
else:
... |
class QdrantClient(QdrantFastembedMixin):
def __init__(self, location: Optional[str]=None, url: Optional[str]=None, port: Optional[int]=6333, grpc_port: int=6334, prefer_grpc: bool=False, Optional[bool]=None, api_key: Optional[str]=None, prefix: Optional[str]=None, timeout: Optional[float]=None, host: Optional[str... |
class TestKeyedTensor(unittest.TestCase):
def test_key_lookup(self) -> None:
tensor_list = [torch.Tensor([[1.0, 1.0]]), torch.Tensor([[2.0, 2.0], [3.0, 3.0]])]
keys = ['dense_0', 'dense_1']
kt = KeyedTensor.from_tensor_list(keys, tensor_list, cat_dim=0, key_dim=0)
self.assertEqual(kt... |
class TurnOnBehavior(BaseModel):
preset: Optional[int] = Field(alias='index', default=None)
mode: BehaviorMode
_validator
def _mode_based_on_preset(cls, values):
if (values['preset'] is not None):
values['mode'] = BehaviorMode.Preset
else:
values['mode'] = Behavio... |
.parametrize(('filename', 'info'), WHEEL_INFO_TESTS, ids=[t[0] for t in WHEEL_INFO_TESTS])
def test_wheel_info(filename, info):
if inspect.isclass(info):
with pytest.raises(info):
Wheel(filename)
return
w = Wheel(filename)
assert ({k: getattr(w, k) for k in info.keys()} == info) |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--game', required=True)
parser.add_argument('--preset', default='Starter Preset')
parser.add_argument('--target-seed-count', type=int, default=100)
parser.add_argument('--process-count', type=int, default=6)
args = parser.parse_... |
class GameResult(Object):
def from_dict(self):
super().from_dict()
self.rank = self._data.get('rank')
self.game_result = self._data.get('gameResult')
self.team_id = self._data.get('teamId')
self.stats = Stats(self._data.get('stats', {}))
self.account_id = self._data.g... |
.parametrize('mtime_minus_now,needs_upgrade', [(((- shared_libs.SHARED_LIBS_MAX_AGE_SEC) - (5 * 60)), True), (((- shared_libs.SHARED_LIBS_MAX_AGE_SEC) + (5 * 60)), False)])
def test_auto_update_shared_libs(capsys, pipx_ultra_temp_env, mtime_minus_now, needs_upgrade):
now = time.time()
shared_libs.shared_libs.cr... |
def set_graph_random_seed(datapipe: DataPipe, seed_generator: SeedGenerator) -> DataPipe:
graph = traverse_dps(datapipe)
sharding_filter_dps = find_dps(graph, ShardingFilter)
cache = set()
dps_before_sharding = []
for sf_dp in sharding_filter_dps:
dps = list_dps(traverse_dps(sf_dp))
... |
.requires_user_action
class EVENT_MOUSEMOTION(InteractiveTestCase):
def on_mouse_motion(self, x, y, dx, dy):
print(('Mouse at (%f, %f); relative (%f, %f).' % (x, y, dx, dy)))
def test_motion(self):
w = Window(200, 200)
try:
w.push_handlers(self)
while (not w.has_e... |
def main():
parser = build_parser()
args = parser.parse_args()
assert args.output.endswith('.h5ad'), 'Output file must be in .h5ad format'
threads = min(args.threads, len(args.prefix))
pool = multiprocessing.Pool(threads)
adatas = list(pool.map(read_prefix, args.prefix))
pool.close()
poo... |
def get_parser(desc, default_task='translation'):
usr_parser = argparse.ArgumentParser(add_help=False, allow_abbrev=False)
usr_parser.add_argument('--user-dir', default=None)
(usr_args, _) = usr_parser.parse_known_args()
utils.import_user_module(usr_args)
parser = argparse.ArgumentParser(allow_abbre... |
def make_layers(cfg, batch_norm=False):
layers = []
in_channels = 3
for v in cfg:
if (v == 'M'):
layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
else:
v = int(v)
conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)
if batch_norm:
... |
class OpenWithInvalidFlagsTest(FakeFileOpenTestBase):
def test_capital_r(self):
with self.assertRaises(ValueError):
self.open('some_file', 'R')
def test_capital_w(self):
with self.assertRaises(ValueError):
self.open('some_file', 'W')
def test_capital_a(self):
... |
def check_render_rest(data_root, verbose=False):
(_, video_paths) = get_json_files(data_root)
fields = ('description', 'summary')
error_by_path = {}
valid = True
for file_path in video_paths:
with open(file_path, encoding='UTF-8') as fp:
blob = json.load(fp)
for field... |
class TransfoXLConfig(PretrainedConfig):
pretrained_config_archive_map = TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP
def __init__(self, vocab_size=267735, cutoffs=[20000, 40000, 200000], d_model=1024, d_embed=1024, n_head=16, d_head=64, d_inner=4096, div_val=4, pre_lnorm=False, n_layer=18, tgt_len=128, ext_len=0, ... |
def _modify_tensor_quantizers(input_output_tensor_quantizers: TensorQuantizersTupleType, setting_name: str, quantizer_setting: Union[(dict, bool)], modified_tensor_quantizers: Dict[(TensorQuantizer, Set)]):
setting_type = get_setting_type(setting_name)
tensor_quantizers_to_modify = _get_tensor_quantizers_to_mod... |
class SysModulesSnapshot():
def __init__(self, preserve: Optional[Callable[([str], bool)]]=None) -> None:
self.__preserve = preserve
self.__saved = dict(sys.modules)
def restore(self) -> None:
if self.__preserve:
self.__saved.update(((k, m) for (k, m) in sys.modules.items() i... |
def _check_and_occupation(video_path, result_path):
if os.path.isfile(result_path):
return True
try:
if (not os.path.isdir(video_path)):
os.makedirs(video_path)
except OSError as err:
print(err)
with open(result_path, 'w') as f:
f.write('Occ')
return False |
class FairseqBMUF(FairseqOptimizer):
def __init__(self, args, optimizer):
super().__init__(args)
self._optimizer = optimizer
self._num_updates = 0
self.sync_iter = self.args.global_sync_iter
self.block_momentum = self.args.block_momentum
self.block_lr = self.args.bloc... |
class TestComplexObject():
def test_repr_smoke(self):
class TestObject(pystiche.ComplexObject):
pass
test_object = TestObject()
assert isinstance(repr(test_object), str)
def test_repr(self):
_properties = OrderedDict((('a', 1),))
extra_properties = OrderedDict... |
class _Linux(_Platform):
def _get_data_path(self):
base_path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..'))
def _checkpath(fname):
return os.path.exists(os.path.join(base_path, fname))
if all(map(_checkpath, ('INSTALL', 'setup.py', 'pytrainer/main.py', 'locale'... |
def test_initiator_lock_expired():
amount = (UNIT_TRANSFER_AMOUNT * 2)
pseudo_random_generator = random.Random()
channels = factories.make_channel_set_from_amounts([amount, 0])
block_number = 10
transfer_description = factories.create(factories.TransferDescriptionProperties(secret=UNIT_SECRET, token... |
class TestMakeOrder():
def test_subclasses_cannot_be_compared(self):
class A():
a = attr.ib()
class B(A):
pass
a = A(42)
b = B(42)
assert (a <= a)
assert (a >= a)
assert (not (a < a))
assert (not (a > a))
assert (NotImpl... |
.parametrize('obj,expected', [(block('provider', 'aws', {}), 'aws'), (block('provider', 'aws', {}).alias, 'aws'), (block('provider', 'aws', {'region': 'eu-west-1'}), 'aws'), (block('provider', 'aws', {'region': 'eu-west-1'}).alias, 'aws'), (block('provider', 'aws', {'alias': 'nonprod'}), 'aws.nonprod'), (block('provide... |
_start_docstrings('Bert Based model to embed queries or document for document retrieval.', RETRIBERT_START_DOCSTRING)
class RetriBertModel(RetriBertPreTrainedModel):
def __init__(self, config: RetriBertConfig) -> None:
super().__init__(config)
self.projection_dim = config.projection_dim
self... |
_vision
_torch
class Pix2StructProcessorTest(unittest.TestCase):
def setUp(self):
self.tmpdirname = tempfile.mkdtemp()
image_processor = Pix2StructImageProcessor()
tokenizer = T5Tokenizer.from_pretrained('t5-small')
processor = Pix2StructProcessor(image_processor, tokenizer)
... |
def _normalize_dates(data):
def normalize_date(x):
if isinstance(x, pa.tslib.NaTType):
return ValueError()
elif (isinstance(x, pa.tslib.Timestamp) or isinstance(x, dt.datetime)):
return dt.datetime(*x.timetuple()[:6], tzinfo=(x.tzinfo or pytz.utc))
elif isinstance(x, ... |
def get_pipes(maxage=timedelta(seconds=0), targetID=None, use_volatile=False, cmd_options=dict()):
pipes_cmd = ops.cmd.getDszCommand('netconnections', complexity='PipesOnly', **cmd_options)
return ops.project.generic_cache_get(pipes_cmd, maxage=maxage, cache_tag=NETSTAT_PIPES_LIST_TAG, targetID=targetID) |
_images
def test_process(host, docker_image):
init = host.process.get(pid=1)
assert (init.ppid == 0)
assert (init.euid == 0)
assert (init.user == 'root')
(args, comm) = {'rockylinux9': ('/usr/sbin/init', 'systemd'), 'debian_bookworm': ('/sbin/init', 'systemd')}[docker_image]
assert (init.args ==... |
class Ljpeg(Codec):
codec_id = 'imagecodecs_ljpeg'
def __init__(self, bitspersample=None):
self.bitspersample = bitspersample
def encode(self, buf):
buf = protective_squeeze(numpy.asarray(buf))
return imagecodecs.ljpeg_encode(buf, bitspersample=self.bitspersample)
def decode(self... |
def add_constant(s, cst, unit=None, var=None, inplace=False):
var = _get_unique_var(s, var, inplace)
if (unit is not None):
Iunit = s.units[var]
if (unit != Iunit):
from radis.phys.convert import conv2
cst = conv2(cst, unit, Iunit)
if (not inplace):
s = s.copy... |
class Effect1361(BaseEffect):
type = 'passive'
def handler(fit, container, context, projectionRange, **kwargs):
level = (container.level if ('skill' in context) else 1)
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Weapon Disruption')), 'capacitorNeed', (container.getModifie... |
def get_quantity(name):
try:
q = list(quantities[name])
except KeyError:
raise ValueError('Unknown quantity. Quantity is not yet specified.')
try:
u = units[name]
except KeyError:
raise RuntimeError('Unknown unit. Quantity has been specified but unit has not.')
q[1] =... |
def _timedelta_offset_str(tdelta: timedelta) -> str:
offset_s = tdelta.total_seconds()
offset_h = int((offset_s / 3600))
offset_m = int(((offset_s / 60) % 60))
offset_t = time(abs(offset_h), abs(offset_m))
operator = ('+' if (offset_s > 0) else '-')
offset = offset_t.strftime('{}%H:%M'.format(op... |
class Tracker():
def __init__(self) -> None:
if (not self.has_cookie()):
self.set_cookie()
self.user_id = self.get_cookie()['id']
self.env = self.get_environment()
def cookie_path(self):
return os.path.join(self.cookie_dir, '.user.yml')
def cookie_dir(self):
... |
def bose_hubbard(x_dimension, y_dimension, tunneling, interaction, chemical_potential=0.0, dipole=0.0, periodic=True):
n_sites = (x_dimension * y_dimension)
hubbard_model = BosonOperator()
for site in range(n_sites):
right_neighbor = _right_neighbor(site, x_dimension, y_dimension, periodic)
... |
.parametrize('api', ['cufile', 'posix', 'cufile-mfma', 'cufile-mf', 'cufile-ma', 'zarr'])
def test_single_node_io(run_cmd, tmp_path, api):
if ('zarr' in api):
kz = pytest.importorskip('kvikio.zarr')
if (not kz.supported):
pytest.skip(f'requires Zarr >={kz.MINIMUM_ZARR_VERSION}')
retc... |
class ClassFeatures():
def __init__(self, numbers=19, proto_momentum=0.9999, dev=torch.device('cpu')):
self.class_numbers = numbers
self.class_features = [[] for _ in range(self.class_numbers)]
self.dev = dev
self.num = np.zeros(numbers)
self.proto_momentum = proto_momentum
... |
def main():
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
if ((len(sys.argv) == 2) and sys.argv[1].endswith('.json')):
(model_args, data_args, training_args) = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
else:
(model_args, data_args,... |
class Passaro(Ator):
velocidade_escalar = 10
def __init__(self, x=0, y=0):
super().__init__(x, y)
self._x_inicial = x
self._y_inicial = y
self._tempo_de_lancamento = None
self._angulo_de_lancamento = None
def foi_lancado(self):
return True
def colidir_com_... |
class ResNet_b(nn.Module):
def __init__(self, block, layers, num_classes=1000, number_net=4, zero_init_residual=False, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None):
super(ResNet_b, self).__init__()
if (norm_layer is None):
norm_layer = nn.BatchNorm2d
... |
def upgrade(saveddata_engine):
saveddata_engine.execute('DELETE FROM damagePatterns WHERE name LIKE ? OR ID LIKE ?', ('Uniform', '1'))
saveddata_engine.execute('INSERT INTO damagePatterns (ID, name, emAmount, thermalAmount, kineticAmount, explosiveAmount, ownerID) VALUES (?, ?, ?, ?, ?, ?, ?)', (1, 'Uniform', 2... |
def _run_command(args: List[str], *, stdin: BinaryIO, timeout: int) -> 'subprocess.CompletedProcess[bytes]':
logging.debug('$ %s', ' '.join(args))
start_time = time.monotonic()
try:
return subprocess.run(args, stdin=stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=IS_WINDOWS, timeout=tim... |
class Adaptor(a_base.Base):
def __init__(self):
a_base.Base.__init__(self, _ADAPTOR_INFO, _ADAPTOR_OPTIONS)
def sanity_check(self):
pass
def get_lease_target(self, tgt):
lease_tgt = rsurl.Url(tgt)
lease_tgt.path = '/shell_file_adaptor_command_shell/'
return lease_tgt |
def _token_data(access=[], context=None, audience=TEST_AUDIENCE, user=TEST_USER, iat=None, exp=None, nbf=None, iss=None, subject=None):
if (subject is None):
(_, subject) = build_context_and_subject(ValidatedAuthContext(user=user))
return {'iss': (iss or instance_keys.service_name), 'aud': audience, 'nb... |
def _generate_deprecation_message(since, message='', name='', alternative='', pending=False, obj_type='attribute', addendum='', removal=''):
if (removal == ''):
removal = 'soon'
elif removal:
if pending:
raise ValueError('A pending deprecation cannot have a scheduled removal')
... |
def test_scalar_array_types_store(i8: wp.array(dtype=wp.int8), u8: wp.array(dtype=wp.uint8), i16: wp.array(dtype=wp.int16), u16: wp.array(dtype=wp.uint16), i32: wp.array(dtype=wp.int32), u32: wp.array(dtype=wp.uint32), i64: wp.array(dtype=wp.int64), u64: wp.array(dtype=wp.uint64), f32: wp.array(dtype=wp.float32), f64: ... |
def remap_log_file(input_log_file, remap_dict_file, output_log_file, item_feat_dict_file):
with open(remap_dict_file, 'rb') as f:
uid_remap_dict = pkl.load(f)
iid_remap_dict = pkl.load(f)
cid_remap_dict = pkl.load(f)
sid_remap_dict = pkl.load(f)
item_feat_dict = {}
newlines =... |
class RandomRotation(object):
def __init__(self, degrees, resample=False, expand=False, center=None):
if isinstance(degrees, numbers.Number):
if (degrees < 0):
raise ValueError('If degrees is a single number, it must be positive.')
self.degrees = ((- degrees), degrees... |
class MoleculeDataLoader(DataLoader):
def __init__(self, dataset: MoleculeDataset, batch_size: int=50, num_workers: int=8, class_balance: bool=False, shuffle: bool=False, seed: int=0, pin_memory: bool=False):
self._dataset = dataset
self._batch_size = batch_size
self._num_workers = num_worke... |
def get_paths(args):
if args.paths:
prefix = 'file://'
prefix_length = len(prefix)
paths = [(path[prefix_length:] if path.startswith(prefix) else path) for path in args.paths]
else:
start_directory = os.environ.get('PWD')
is_valid_start_directory = (start_directory and os... |
class MarkImportsUnreachableVisitor(TraverserVisitor):
def visit_import(self, node: Import) -> None:
node.is_unreachable = True
def visit_import_from(self, node: ImportFrom) -> None:
node.is_unreachable = True
def visit_import_all(self, node: ImportAll) -> None:
node.is_unreachable =... |
def value_from_ast(ast_node: ast.AST, ctx: Context, *, error_on_unrecognized: bool=True) -> Value:
val = _Visitor(ctx).visit(ast_node)
if (val is None):
if error_on_unrecognized:
ctx.show_error('Invalid type annotation', node=ast_node)
return AnyValue(AnySource.error)
return val |
class SyntheticImageDataset(Dataset):
DEFAULT_SIZE = 50000
def __init__(self, cfg, path: str, split: str, dataset_name: str, data_source='synthetic'):
super(SyntheticImageDataset, self).__init__()
self.cfg = cfg
self.split = split
self.data_source = data_source
self._num_... |
def compare_dicom_cli(command, original, expected):
pydicom.write_file(ORIGINAL_DICOM_FILENAME, original)
try:
subprocess.check_call(command)
cli_adjusted_ds = pydicom.read_file(ADJUSTED_DICOM_FILENAME, force=True)
assert (str(cli_adjusted_ds) == str(expected))
finally:
remov... |
def _test_tensor_list_sync_state(dst_rank: Optional[int]=None) -> None:
device = init_from_env()
if (dist.get_rank() == 0):
state_data = {_METRIC_NAME: {'seen': [torch.tensor(1, device=device), torch.tensor(3, device=device)], 'total': [torch.tensor(1, device=device)]}}
elif (dist.get_rank() == 1):
... |
class PQStatCat():
def __init__(self):
self.iou = 0.0
self.tp = 0
self.fp = 0
self.fn = 0
def __iadd__(self, pq_stat_cat):
self.iou += pq_stat_cat.iou
self.tp += pq_stat_cat.tp
self.fp += pq_stat_cat.fp
self.fn += pq_stat_cat.fn
return self |
class TestUDPCollector(CollectorTestCase):
def setUp(self, allowed_names=None):
if (not allowed_names):
allowed_names = []
config = get_collector_config('UDPCollector', {'allowed_names': allowed_names, 'interval': 1})
self.collector = UDPCollector(config, None)
def test_impor... |
def _check_dsa_parameters(parameters: DSAParameterNumbers) -> None:
if (parameters.p.bit_length() not in [1024, 2048, 3072, 4096]):
raise ValueError('p must be exactly 1024, 2048, 3072, or 4096 bits long')
if (parameters.q.bit_length() not in [160, 224, 256]):
raise ValueError('q must be exactly... |
class _ResultProxy():
_metadata = True
def __init__(self, context):
self._context = context
def context(self):
return self._context
async def execute(self, one=False, return_model=True, status=False, return_context=False):
context = self._context
param_groups = []
... |
class FatalError(RxHeader):
def __init__(self, sock: socket.socket) -> None:
super().__init__(sock, 'FatalError')
self.error_code = FATALERRORMESSAGE[self.control_code]
assert (self.message_parameter == 0)
self.error_message = receive_exact(sock, self.payload_length) |
.parametrize('username,password', users)
.parametrize('project_id', projects)
def test_project_update_get(db, client, username, password, project_id):
client.login(username=username, password=password)
url = reverse('project_update', args=[project_id])
response = client.get(url)
if (project_id in change... |
def bottleneck(x, out_channels, stride=1, expansion=4, name=''):
res = x
x = Conv2D(out_channels, 1, 1, use_bias=False, name=(name + '/conv1'))(x)
x = BatchNormalization(name=(name + '/bn1'))(x)
x = ReLU(name=(name + '/relu1'))(x)
x = Conv2D(out_channels, 3, stride, 'same', use_bias=False, name=(nam... |
class RtorrentSweep(ScriptBaseWithConfig):
ARGS_HELP = '<space requirement>|SHOW'
def add_options(self):
super(RtorrentSweep, self).add_options()
self.add_bool_option('-n', '--dry-run', help='do not remove anything, just tell what would happen')
self.add_value_option('-p', '--path', 'PAT... |
def read_csv(csv_file, class_whitelist=None, capacity=0):
start = time.time()
entries = defaultdict(list)
boxes = defaultdict(list)
labels = defaultdict(list)
scores = defaultdict(list)
reader = csv.reader(csv_file)
for row in reader:
assert (len(row) in [7, 8]), ('Wrong number of co... |
def execute_subprocess_async(cmd, env=None, stdin=None, timeout=180, quiet=False, echo=True) -> _RunOutput:
loop = asyncio.get_event_loop()
result = loop.run_until_complete(_stream_subprocess(cmd, env=env, stdin=stdin, timeout=timeout, quiet=quiet, echo=echo))
cmd_str = ' '.join(cmd)
if (result.returnco... |
class BMPImageDecoder(ImageDecoder):
def get_file_extensions(self):
return ['.bmp']
def decode(self, filename, file):
if (not file):
file = open(filename, 'rb')
bytes = file.read()
buffer = ctypes.c_buffer(bytes)
if (bytes[:2] != b'BM'):
raise Imag... |
def is_qmk_firmware(qmk_firmware):
paths = [qmk_firmware, (qmk_firmware / 'quantum'), (qmk_firmware / 'requirements.txt'), (qmk_firmware / 'requirements-dev.txt'), (qmk_firmware / 'lib/python/qmk/cli/__init__.py')]
for path in paths:
if (not path.exists()):
return False
return True |
class DatabaseSchema():
def __init__(self, table_json=None, db_id=None, table_names=None, column_names=None, primary_keys=None, foreign_keys=None, type_for_column_for_table=None, table_data=None, column_key_in_table=None, column_used_with_keys=None):
if (table_json is not None):
(db_id, table_na... |
class CargoInfo():
def __init__(self, itemID, amount):
self.itemID = itemID
self.amount = amount
def fromCargo(cls, cargo):
if (cargo is None):
return None
info = cls(itemID=cargo.itemID, amount=cargo.amount)
return info
def toCargo(self):
item = M... |
class CountingIterator(object):
def __init__(self, iterable, start=0):
self.iterable = iterable
self.count = start
self.itr = iter(self)
self.len = (start + len(iterable))
def __len__(self):
return self.len
def __iter__(self):
for x in self.iterable:
... |
def _get_quadratic_model(xs: List[np.ndarray], ys: List[float], xopt: np.ndarray) -> Pipeline:
linear_model = LinearRegression(fit_intercept=False)
model = Pipeline([('poly', PolynomialFeatures(degree=2)), ('linear_model', linear_model)])
shifted_xs = [(x - xopt) for x in xs]
model = model.fit(shifted_x... |
_MODELS.register_module()
class SMPL(nn.Module):
def __init__(self, smpl_path, joints_regressor):
super().__init__()
assert has_smpl, 'Please install smplx to use SMPL.'
self.smpl_neutral = SMPL_(model_path=smpl_path, create_global_orient=False, create_body_pose=False, create_transl=False, g... |
class CNN(nn.Module):
def __init__(self, in_word_embedding_dimension: int, out_channels: int=256, kernel_sizes: List[int]=[1, 3, 5]):
nn.Module.__init__(self)
self.config_keys = ['in_word_embedding_dimension', 'out_channels', 'kernel_sizes']
self.in_word_embedding_dimension = in_word_embeddi... |
def load_checkpoint(model, optimizer, lr_scheduler, load_arg='load'):
args = get_args()
load_dir = getattr(args, load_arg)
if isinstance(model, torchDDP):
model = model.module
tracker_filename = get_checkpoint_tracker_filename(load_dir)
if (not os.path.isfile(tracker_filename)):
prin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.