code stringlengths 281 23.7M |
|---|
def process_routes(watch_url_routes, iter_track_time):
failed_routes = []
if watch_url_routes:
watch_routes_start_time = time.time()
for route_info in watch_url_routes:
header = {'Accept': 'application/json'}
if (len(route_info) > 1):
header['Authorization... |
class StyleForm(forms.Form):
bgcolor = forms.CharField(widget=ColorWidget, required=False)
linear_gradient_direction = forms.ChoiceField(choices=Petition.LINEAR_GRADIENT_CHOICES, required=False)
gradient_from = forms.CharField(widget=ColorWidget, required=False)
gradient_to = forms.CharField(widget=Colo... |
def ordered_yaml_dump(data, stream=None, Dumper=yaml.SafeDumper, **kwds):
class OrderedDumper(Dumper):
pass
def _dict_representer(dumper, data):
return dumper.represent_mapping(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items())
OrderedDumper.add_representer(OrderedDict, _dict_repr... |
class CIFARDIAResNet(nn.Module):
def __init__(self, channels, init_block_channels, bottleneck, in_channels=3, in_size=(32, 32), num_classes=10):
super(CIFARDIAResNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.f... |
class upResBlock_3x3(nn.Module):
def __init__(self, in_c, out_c, hid_c=None, conv2d=None, norm_layer=None, non_linear=None):
super(upResBlock_3x3, self).__init__()
if (hid_c is None):
hid_c = in_c
if (conv2d is None):
conv2d = nn.Conv2d
if (norm_layer is None)... |
def repartition_range(tables: List[pa.Table], destination_partition: Partition, repartition_args: dict, max_records_per_output_file: int, s3_table_writer_kwargs: Optional[Dict[(str, Any)]]=None, repartitioned_file_content_type: ContentType=ContentType.PARQUET, deltacat_storage=unimplemented_deltacat_storage, deltacat_s... |
def get_node_ancestors(synset):
ancestors = set()
to_visit = set(synset.parents)
visited = set()
while to_visit:
ancestor = to_visit.pop()
ancestors.add(ancestor)
visited.add(ancestor)
to_visit = (to_visit | (set(ancestor.parents) - visited))
return ancestors |
def connectToNamedPipeViaPrinter(subPipeName='toto'):
accessRequired = 0
hPrinter = PVOID()
targetServer = '\\\\{0}'.format('127.0.0.1')
targetServer = create_unicode_buffer(targetServer)
configBuffer = create_string_buffer(8192)
devModeContainer = cast(configBuffer, POINTER(DEVMODE_CONTAINER))
... |
class _TfDatasetIterable(Iterable[tf.Tensor]):
def __init__(self, dataset: tf.compat.v1.data.Dataset):
self._graph = dataset._graph
with self._graph.as_default():
self._tf_dataset_iterator = tf.compat.v1.data.make_initializable_iterator(dataset)
self._get_next = self._tf_data... |
class SawyerHandlePullEnvV2(SawyerXYZEnv):
def __init__(self):
hand_low = ((- 0.5), 0.4, 0.05)
hand_high = (0.5, 1, 0.5)
obj_low = ((- 0.1), 0.8, (- 0.001))
obj_high = (0.1, 0.9, (+ 0.001))
goal_low = ((- 0.1), 0.55, 0.04)
goal_high = (0.1, 0.7, 0.18)
super().... |
def get_backend_class(connection: str) -> type['testinfra.backend.base.BaseBackend']:
try:
classpath = BACKENDS[connection]
except KeyError:
raise RuntimeError("Unknown connection type '{}'".format(connection))
(module, name) = classpath.rsplit('.', 1)
return getattr(importlib.import_mod... |
def _find_imbalance_tables(sharding_options: List[ShardingOption], target_imbalance: str='perf') -> List[ShardingOption]:
rank_to_target_stats: Dict[(int, float)] = {}
for sharding_option in sharding_options:
for shard in sharding_option.shards:
rank = cast(int, shard.rank)
if (r... |
class Adaptor(a_base.Base):
def __init__(self):
a_base.Base.__init__(self, _ADAPTOR_INFO, _ADAPTOR_OPTIONS)
self.id_re = re.compile('^\\[(.*)\\]-\\[(.*?)\\]$')
self.epoch = datetime.datetime(1970, 1, 1)
def sanity_check(self):
pass
def parse_id(self, id):
match = self... |
_model
def resnest50d(pretrained=False, **kwargs):
model_kwargs = dict(block=ResNestBottleneck, layers=[3, 4, 6, 3], stem_type='deep', stem_width=32, avg_down=True, base_width=64, cardinality=1, block_args=dict(radix=2, avd=True, avd_first=False), **kwargs)
return _create_resnest('resnest50d', pretrained=pretra... |
def simulation_ordered_grouped_hubbard_terms_with_info(hubbard_hamiltonian):
hamiltonian = normal_ordered(hubbard_hamiltonian)
n_qubits = count_qubits(hamiltonian)
side_length = int(numpy.sqrt((n_qubits / 2.0)))
ordered_terms = []
ordered_indices = []
ordered_is_hopping_operator = []
origina... |
_model
def efficientnet_b3_pruned(pretrained=False, **kwargs):
kwargs['bn_eps'] = BN_EPS_TF_DEFAULT
kwargs['pad_type'] = 'same'
model = _gen_efficientnet('efficientnet_b3_pruned', channel_multiplier=1.2, depth_multiplier=1.4, pruned=True, pretrained=pretrained, **kwargs)
return model |
class QuantAct(nn.Module):
def __init__(self, activation_bit, act_range_momentum=0.95, per_channel=False, channel_len=None, quant_mode=False):
super().__init__()
self.activation_bit = activation_bit
self.act_range_momentum = act_range_momentum
self.quant_mode = quant_mode
sel... |
class ExtractFeature(nn.Module):
def __init__(self, opt={}, finetune=True):
super(ExtractFeature, self).__init__()
self.embed_dim = opt['embed']['embed_dim']
self.resnet = resnet18(pretrained=True)
for param in self.resnet.parameters():
param.requires_grad = finetune
... |
def update():
global phase
if ((phase % (8 * np.pi)) > (4 * np.pi)):
m1['angle'] = (315 + (1.5 * np.sin(phase)))
m1a['angle'] = (315 + (1.5 * np.sin(phase)))
else:
m2['angle'] = (135 + (1.5 * np.sin(phase)))
m2a['angle'] = (135 + (1.5 * np.sin(phase)))
phase += 0.2 |
def load_w2v_feature(file, max_idx=0):
with open(file, 'rb') as f:
nu = 0
for line in f:
content = line.strip().split()
nu += 1
if (nu == 1):
(n, d) = (int(content[0]), int(content[1]))
feature = [([0.0] * d) for i in range(max(n, (... |
.unit()
def test_print_collected_tasks_with_nodes(capsys):
dictionary = {Path('task_path.py'): [Task(base_name='function', path=Path('task_path.py'), function=function, depends_on={'depends_on': PathNode(name='in.txt', path=Path('in.txt'))}, produces={0: PathNode(name='out.txt', path=Path('out.txt'))})]}
_print... |
def test_backjumps_after_partial_satisfier(root: ProjectPackage, provider: Provider, repo: Repository) -> None:
root.add_dependency(Factory.create_dependency('c', '*'))
root.add_dependency(Factory.create_dependency('y', '^2.0.0'))
add_to_repo(repo, 'a', '1.0.0', deps={'x': '>=1.0.0'})
add_to_repo(repo, ... |
def test_parses(parses):
finder = FunDefFindingVisitor()
for (f, tree) in parses:
(globs, astree) = parse_object(f)
fundef = finder.visit(astree)
parser = LogicExpressionASTVisitor(globs)
ptree = parser.visit(fundef)
print(ptree, tree)
assert (ptree.return_node ==... |
_if_py38
.flaky
def test_default_transformer_epoch_optim_loop(optim_asset_loader):
asset = optim_asset_loader('default_transformer_epoch_optim_loop')
image_loader = asset.input.image_loader
criterion = asset.input.perceptual_loss
make_torch_ge_1_6_compatible(image_loader, criterion)
transformer = as... |
def parse_ieee_block_header(block: Union[(bytes, bytearray)], length_before_block: Optional[int]=None, raise_on_late_block: bool=False) -> Tuple[(int, int)]:
begin = block.find(b'#')
if (begin < 0):
raise ValueError(('Could not find hash sign (#) indicating the start of the block. The block begin by %r'... |
class AsyncEnum(ENUM):
async def create_async(self, bind=None, checkfirst=True):
if ((not checkfirst) or (not (await bind.dialect.has_type(bind, self.name, schema=self.schema)))):
(await bind.status(CreateEnumType(self)))
async def drop_async(self, bind=None, checkfirst=True):
if ((n... |
class MonolingualDataset(FairseqDataset):
def __init__(self, dataset, sizes, src_vocab, tgt_vocab=None, add_eos_for_other_targets=False, shuffle=False, targets=None, add_bos_token=False, fixed_pad_length=None, pad_to_bsz=None, src_lang_idx=None, tgt_lang_idx=None):
self.dataset = dataset
self.sizes ... |
def test_create_observation_fail(requests_mock):
params = {'species_guess': 'Pieris rapae', 'observed_on_string': (datetime.now() + timedelta(days=1)).isoformat(), 'latitude': 200}
requests_mock.post(f'{API_V0}/observations.json', json=load_sample_data('create_observation_fail.json'), status_code=422)
with ... |
def read_index(index_path: PathType, storage_options: Optional[Dict[(str, str)]]=None) -> Any:
url = str(index_path)
if url.endswith(TABIX_EXTENSION):
return read_tabix(url, storage_options=storage_options)
elif url.endswith(CSI_EXTENSION):
return read_csi(url, storage_options=storage_option... |
_module
class FPN(nn.Module):
def __init__(self, in_channels, out_channels, num_outs, start_level=0, end_level=(- 1), add_extra_convs=False, extra_convs_on_inputs=True, relu_before_extra_convs=False, conv_cfg=None, norm_cfg=None, activation=None):
super(FPN, self).__init__()
assert isinstance(in_cha... |
class Discriminator(nn.Module):
def __init__(self):
super(Discriminator, self).__init__()
self.discriminator = nn.ModuleList([nn.Sequential(nn.ReflectionPad1d(7), nn.utils.spectral_norm(nn.Conv1d(1, 16, kernel_size=15)), nn.LeakyReLU(0.2, True)), nn.Sequential(nn.utils.spectral_norm(nn.Conv1d(16, 64... |
('ruamel.yaml.YAML.load', return_value='mocked pipeline def')
def test_get_pipeline_definition(mocked_yaml):
pipeline = 'pipeline'
pipeline_def = string_loader.get_pipeline_definition(pipeline, None)
mocked_yaml.assert_called_once_with(pipeline)
expected_pipeline_def = PipelineDefinition('mocked pipelin... |
def test_save_load_observables_expressions():
buff = io.BytesIO()
tspan = np.linspace(0, 100, 100)
sim = ScipyOdeSimulator(tyson_oscillator.model, tspan).run()
sim.save(buff, include_obs_exprs=True)
sim2 = SimulationResult.load(buff)
assert (len(sim2.observables) == len(tspan))
assert_raises... |
class MtimeLinemode(LinemodeBase):
name = 'mtime'
def filetitle(self, fobj, metadata):
return fobj.relative_path
def infostring(self, fobj, metadata):
if (fobj.stat is None):
return '?'
return datetime.fromtimestamp(fobj.stat.st_mtime).strftime('%Y-%m-%d %H:%M') |
def test_year():
current_year = datetime.now().year
path = (((Path(__file__).parent.parent / 'we_get') / 'core') / 'we_get.py')
with path.open() as f:
m_content = f.read()
m_content.splitlines()[1]
year = m_content.split('Copyright (c) 2016-')[1].split(' ')[0]
assert (year == str(current... |
def parse():
parser = argparse.ArgumentParser()
parser.add_argument('--ess_iters', help='(int) number of ess samples per iteration', default=20, type=int)
parser.add_argument('--mean', help='(str) latent mean, options = "Constant", "LogRBF"', default='LogRBF')
parser.add_argument('--nomg', help='(int) n... |
def test_bulk_imports(gl, group):
destination = f'{group.full_path}-import'
configuration = {'url': gl.url, 'access_token': gl.private_token}
migration_entity = {'source_full_path': group.full_path, 'source_type': 'group_entity', 'destination_slug': destination, 'destination_namespace': destination}
cre... |
def test_datetime_format_provider(strict_coercion, debug_trail):
retort = Retort(strict_coercion=strict_coercion, debug_trail=debug_trail, recipe=[DatetimeFormatProvider('%Y-%m-%d')])
loader = retort.get_loader(datetime)
assert (loader('3045-02-13') == datetime(year=3045, month=2, day=13))
check_any_dt(... |
def test_call_which_returns_a_string_before_smart_contract_deployed(deploy_client: JSONRPCClient) -> None:
(contract_proxy, receipt) = deploy_rpc_test_contract(deploy_client, 'RpcTest')
deploy_block = receipt['blockNumber']
assert (contract_proxy.functions.ret_str().call(block_identifier=deploy_block) == ''... |
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, stride=1, resample=None):
super().__init__()
self.bn1 = nn.BatchNorm2d(in_planes)
self.conv1 = nn.Conv2d(in_planes, planes, 3, stride=stride, padding=1)
self.bn2 = nn.BatchNorm2d(planes)
self... |
class ProxyManager():
def __init__(self, rpc_client: JSONRPCClient, contract_manager: ContractManager, metadata: ProxyManagerMetadata) -> None:
self.address_to_secret_registry: Dict[(SecretRegistryAddress, SecretRegistry)] = {}
self.address_to_token: Dict[(TokenAddress, Token)] = {}
self.add... |
class TestBaseFairseqModelBase(unittest.TestCase):
def setUpClass(cls):
if (cls is TestBaseFairseqModelBase):
raise unittest.SkipTest('Skipping test case in base')
super().setUpClass()
def setUpModel(self, model):
self.assertTrue(isinstance(model, BaseFairseqModel))
s... |
def save_model(model: nn.Module, iteration: int, suffix: str) -> None:
os.makedirs(args.save_folder, exist_ok=True)
save_path = os.path.join(args.save_folder, '{}_{}_{}_size{}_anchor{}_{}_{}.pth'.format(args.dataset, args.neck, args.backbone, args.image_size, args.anchor_size, ('MG' if args.mutual_guide else 'R... |
class AirInitBlock(nn.Module):
def __init__(self, in_channels, out_channels):
super(AirInitBlock, self).__init__()
mid_channels = (out_channels // 2)
self.conv1 = conv3x3_block(in_channels=in_channels, out_channels=mid_channels, stride=2)
self.conv2 = conv3x3_block(in_channels=mid_ch... |
class MockVoiceChannel(CustomMockMixin, unittest.mock.Mock, HashableMixin):
spec_set = voice_channel_instance
def __init__(self, **kwargs) -> None:
default_kwargs = {'id': next(self.discord_id), 'name': 'channel', 'guild': MockGuild()}
super().__init__(**collections.ChainMap(kwargs, default_kwar... |
class EasyuploadIo(SimpleDownloader):
__name__ = 'EasyuploadIo'
__type__ = 'downloader'
__version__ = '0.02'
__status__ = 'testing'
__pattern__ = '
__config__ = [('enabled', 'bool', 'Activated', True), ('use_premium', 'bool', 'Use premium account if available', True), ('fallback', 'bool', 'Fallb... |
def _setup_common_routes(api_blueprint: Blueprint, spa_blueprint: Blueprint, options: Options) -> None:
cors_options = options.cors
if cors_options:
cors_params = (cors_options if isinstance(cors_options, dict) else {})
CORS(api_blueprint, **cors_params)
_blueprint.route(f'/{ASSETS_PATH.name... |
class Frame():
__slots__ = ('raw',)
def __init__(self, frame: FrameType) -> None:
self.raw = frame
def lineno(self) -> int:
return (self.raw.f_lineno - 1)
def f_globals(self) -> Dict[(str, Any)]:
return self.raw.f_globals
def f_locals(self) -> Dict[(str, Any)]:
return... |
()
def logs_model_config():
conf = {'LOGS_MODEL': 'elasticsearch', 'LOGS_MODEL_CONFIG': {'producer': 'elasticsearch', 'elasticsearch_config': {'host': FAKE_ES_HOST, 'port': FAKE_ES_PORT, 'access_key': FAKE_AWS_ACCESS_KEY, 'secret_key': FAKE_AWS_SECRET_KEY, 'aws_region': FAKE_AWS_REGION}}}
return conf |
class FitEqu(object):
def __init__(self):
super(FitEqu, self).__init__()
def prepare_data(self):
dataset = SpringMassDataset(self.k, self.m, self.A0, self.c)
return dataset.solution()
def prepare_library(self, data):
(is_poly, remove_num) = (False, 50)
(t, x_clean) = ... |
(scope='session')
def session_capabilities(pytestconfig):
driver = pytestconfig.getoption('driver').upper()
capabilities = getattr(DesiredCapabilities, driver, {}).copy()
if (driver == 'REMOTE'):
browser = capabilities.get('browserName', '').upper()
capabilities.update(getattr(DesiredCapabil... |
class Registry():
mapping = {'builder_name_mapping': {}, 'trainer_name_mapping': {}, 'model_name_mapping': {}, 'metric_name_mapping': {}, 'loss_name_mapping': {}, 'optimizer_name_mapping': {}, 'scheduler_name_mapping': {}, 'processor_name_mapping': {}, 'state': {}}
def register_trainer(cls, name):
def w... |
class QubitOperator(SymbolicOperator):
def actions(self):
return ('X', 'Y', 'Z')
def action_strings(self):
return ('X', 'Y', 'Z')
def action_before_index(self):
return True
def different_indices_commute(self):
return True
def renormalize(self):
norm = self.ind... |
def main():
fps = 30
print('Plug in a USB gamepad. Do it! Do it now! Press enter after you have done this.')
wait_for_enter()
pygame.init()
num_joysticks = pygame.joystick.get_count()
if (num_joysticks < 1):
print("You didn't plug in a joystick. FORSHAME!")
return
input_manag... |
def import_parser(path, import_type, parser_func, loader=None):
try:
__import__(import_type)
mod = sys.modules[import_type]
except ImportError:
sys.exit('{0} import error, please make sure that {0} is installed'.format(import_type))
return parser_func(mod, path, loader) |
.parametrize('keys, input_dict, expected', [(['a', 'b'], {'a': 1, 'b': 2, 'c': 3}, {'a': 1, 'b': 2}), (['a', 'b', 'd'], {'a': 1, 'b': 2, 'c': 3}, {'a': 1, 'b': 2}), (['a'], {}, {}), (['a'], {'b': 2}, {})])
def test_build_kwargs(keys, input_dict, expected):
kwargs = tools._build_kwargs(keys, input_dict)
assert (... |
def test_properties():
instance = m.TestProperties()
assert (instance.def_readonly == 1)
with pytest.raises(AttributeError):
instance.def_readonly = 2
instance.def_readwrite = 2
assert (instance.def_readwrite == 2)
assert (instance.def_property_readonly == 2)
with pytest.raises(Attri... |
class TestLegacyAreaParser(unittest.TestCase):
def test_area_parser_legacy(self):
from pyresample import parse_area_file
(ease_nh, ease_sh) = parse_area_file(os.path.join(TEST_FILES_PATH, 'areas.cfg'), 'ease_nh', 'ease_sh')
projection = "{'R': '6371228', 'lat_0': '90', 'lon_0': '0', 'no_defs... |
class CRDLoss(nn.Module):
def __init__(self, opt):
super(CRDLoss, self).__init__()
self.embed_s = Embed(opt.s_dim, opt.feat_dim)
self.embed_t = Embed(opt.t_dim, opt.feat_dim)
self.contrast = ContrastMemory(opt.feat_dim, opt.n_data, opt.nce_k, opt.nce_t, opt.nce_m)
self.criter... |
class Effect2017(BaseEffect):
type = 'passive'
def handler(fit, container, context, projectionRange, **kwargs):
level = (container.level if ('skill' in context) else 1)
fit.drones.filteredItemBoost((lambda drone: drone.item.requiresSkill('Drones')), 'hp', (container.getModifiedItemAttr('hullHpBo... |
class LinearFunction(torch.autograd.Function):
def forward(ctx, input, weight, bias):
output = linear_blaslt.forward(input, weight, bias)
ctx.save_for_backward(input, weight)
return output
def backward(ctx, grad_output):
(input, weight) = ctx.saved_tensors
if weight.requi... |
class EditorTabContextMenu(Menu):
def __init__(self, *args, **kwds):
Menu.__init__(self, *args, **kwds)
self._index = (- 1)
def setIndex(self, index):
self._index = index
def build(self):
icons = pyzo.icons
self.addItem(translate('menu', 'Save ::: Save the current fil... |
def train_vae_model():
parser = argparse.ArgumentParser()
parser.add_argument('--dataset', type=str, help='specify the dataset')
parser.add_argument('--split', type=int, default=0, help='specify the split of dataset for experiment')
parser.add_argument('--batch_size', type=int, default=500, help='specif... |
def do_import(parent, library):
db_path = os.path.expanduser('~/.local/share/rhythmbox/rhythmdb.xml')
handler = RBDBContentHandler(library)
try:
xml.sax.parse(db_path, handler)
except Exception:
util.print_exc()
handler.finish()
msg = _('Import Failed')
ErrorMessa... |
def setup_roles(application: Application) -> Roles:
if isinstance(application.bot_data, RolesBotData):
roles = application.bot_data.get_roles()
if (roles is None):
roles = Roles(application.bot)
application.bot_data.set_roles(roles)
return roles
return rol... |
class DataModuleFromConfig(pl.LightningDataModule):
def __init__(self, batch_size, train=None, validation=None, test=None, wrap=False, num_workers=None):
super().__init__()
self.batch_size = batch_size
self.dataset_configs = dict()
self.num_workers = (num_workers if (num_workers is n... |
def test_shape(zarr_dataset: ChunkedDataset, dmg: LocalDataManager, cfg: dict) -> None:
hist_length = 10
cfg['raster_params']['map_type'] = 'py_satellite'
cfg['raster_params']['filter_agents_threshold'] = 1.0
cfg['model_params']['history_num_frames'] = hist_length
rasterizer = build_rasterizer(cfg, ... |
def test_creating_simple_background():
background = Background('Background', 'I am a Background', 'foo.feature', 1, parent=None)
assert (background.id is None)
assert (background.keyword == 'Background')
assert (background.sentence == 'I am a Background')
assert (background.path == 'foo.feature')
... |
def _eval_forward_ref(val: str, ctx: Context, *, is_typeddict: bool=False, allow_unpack: bool=False) -> Value:
try:
tree = ast.parse(val, mode='eval')
except SyntaxError:
ctx.show_error(f'Syntax error in type annotation: {val}')
return AnyValue(AnySource.error)
else:
return _... |
def subscribe(email: str, ip: str) -> SubscriptionResult:
if (not settings.FLODESK_API_KEY):
raise ValueError('Flodesk integration is not configured')
subscriber = get_subscriber(email)
if (not subscriber):
return subscribe_email(email, ip)
email_status = subscriber.get('status')
seg... |
class LeNet_5(PruningModule):
def __init__(self, mask=False):
super(LeNet_5, self).__init__()
linear = (MaskedLinear if mask else Linear)
self.conv1 = nn.Conv2d(1, 20, kernel_size=(5, 5))
self.conv2 = nn.Conv2d(20, 50, kernel_size=(5, 5))
self.fc1 = linear(800, 500)
s... |
def url_to_storage_plugin_in_event_loop(url_path: str, event_loop: asyncio.AbstractEventLoop, storage_options: Optional[Dict[(str, Any)]]=None) -> StoragePlugin:
async def _url_to_storage_plugin() -> StoragePlugin:
return url_to_storage_plugin(url_path=url_path, storage_options=storage_options)
return e... |
class NfsdCollector(diamond.collector.Collector):
PROC = '/proc/net/rpc/nfsd'
def get_default_config_help(self):
config_help = super(NfsdCollector, self).get_default_config_help()
config_help.update({})
return config_help
def get_default_config(self):
config = super(NfsdColle... |
def patch_asyncio():
if (not (sys.version_info < (3, 7))):
return
def _get_context():
state = _get_state()
ctx = getattr(state, 'context', None)
if (ctx is None):
ctx = contextvars.Context()
state.context = ctx
return ctx
def _set_context(ctx):... |
class PlayEntityPositionAndRotation(Packet):
id = 40
to = 1
def __init__(self, entity_id: int, dx: int, dy: int, dz: int, yaw: float, pitch: float, on_ground: bool) -> None:
super().__init__()
self.entity_id = entity_id
(self.dx, self.dy, self.dz) = (dx, dy, dz)
self.yaw = ya... |
class ScheduledScanAdmin(admin.ModelAdmin):
list_display = ('id', 'site_name', 'start_time', 'scan_engine', 'start_datetime', 'scan_binary', 'scan_command', 'targets', 'excluded_targets', 'scan_status', 'completed_time', 'result_file_base_name', 'pooled_scan_result_file_base_name', 'scan_binary_process_id')
lis... |
def seq(*parsers: Parser, **kw_parsers: Parser) -> Parser:
if ((not parsers) and (not kw_parsers)):
return success([])
if (parsers and kw_parsers):
raise ValueError('Use either positional arguments or keyword arguments with seq, not both')
if parsers:
def seq_parser(stream, index):
... |
def make_releasenotes(summary, prev_pdfium, new_pdfium, prev_tag, new_tag, c_updates):
relnotes = ''
relnotes += f'''## Changes (Release {new_tag})
'''
relnotes += '### Summary (pypdfium2)\n\n'
if summary:
relnotes += (summary + '\n')
relnotes += _get_log('pypdfium2', RepositoryURL, ProjectD... |
class SentencePieceExtractor():
def __init__(self, model: str):
requires_backends(self, 'sentencepiece')
from sentencepiece import SentencePieceProcessor
self.sp = SentencePieceProcessor()
self.sp.Load(model)
def extract(self) -> Tuple[(Dict[(str, int)], List[Tuple])]:
sp... |
def calculate_tuple_fallback(typ: TupleType) -> None:
fallback = typ.partial_fallback
assert (fallback.type.fullname == 'builtins.tuple')
items = []
for item in typ.items:
if isinstance(item, UnpackType):
unpacked_type = get_proper_type(item.type)
if isinstance(unpacked_t... |
class Effect6222(BaseEffect):
runTime = 'early'
type = ('projected', 'active')
def handler(fit, module, context, projectionRange, **kwargs):
if ('projected' not in context):
return
if fit.ship.getModifiedItemAttr('disallowOffensiveModifiers'):
return
if (modul... |
def test_PlotItem_preserve_external_visibility_control():
item = pg.PlotItem()
curve1 = pg.PlotDataItem(np.random.normal(size=10))
curve2 = pg.PlotDataItem(np.random.normal(size=10))
item.addItem(curve1)
curve1.hide()
item.addItem(curve2)
assert (not curve1.isVisible())
item.removeItem(c... |
class calibrate(menu):
def __init__(self):
super(calibrate, self).__init__(_('calibrate'), [level(_('level')), ValueEdit(_('heading'), self.getheading, 'imu.heading_offset'), ValueCheck(_('lock'), 'imu.compass.calibration.locked'), calibrate_rudder_feedback(), calibrate_info()])
self.lastcounter = 0... |
_datapipe('flatten')
class FlattenIterDataPipe(IterDataPipe[T_co]):
datapipe: IterDataPipe
indices: Set[Hashable] = set()
def __init__(self, datapipe: IterDataPipe, indices: Optional[Union[(Hashable, List[Hashable])]]=None) -> None:
super().__init__()
self.datapipe = datapipe
if indi... |
def collect_dep_env(data):
try:
data.append(('torchvision', ((str(torchvision.__version__) + ' ') + os.path.dirname(torchvision.__file__))))
except AttributeError:
data.append(('torchvision', 'unknown'))
try:
import hydra
data.append(('hydra', ((str(hydra.__version__) + ' ') ... |
def url(*, info):
model = completionmodel.CompletionModel(column_widths=(40, 50, 10))
quickmarks = [(url, name) for (name, url) in objreg.get('quickmark-manager').marks.items()]
bookmarks = objreg.get('bookmark-manager').marks.items()
searchengines = [(k, v) for (k, v) in sorted(config.val.url.searcheng... |
def test_group_deploy_tokens(gl, group):
deploy_token = group.deploytokens.create({'name': 'foo', 'scopes': ['read_registry']})
assert (deploy_token in group.deploytokens.list())
assert (set(group.deploytokens.list()) <= set(gl.deploytokens.list()))
deploy_token = group.deploytokens.get(deploy_token.id)... |
class Nadam(Optimizer):
def __init__(self, lr=0.002, beta_1=0.9, beta_2=0.999, epsilon=1e-08, schedule_decay=0.004, **kwargs):
super(Nadam, self).__init__(**kwargs)
with K.name_scope(self.__class__.__name__):
self.iterations = K.variable(0, dtype='int64', name='iterations')
s... |
def test_load_editable_with_import_package(repository: InstalledRepository) -> None:
editable = get_package_from_repository('editable-with-import', repository)
assert (editable is not None)
assert (editable.name == 'editable-with-import')
assert (editable.version.text == '2.3.4')
assert (editable.so... |
def total_intersect_and_union(results, gt_seg_maps, num_classes, ignore_index, label_map=dict(), reduce_zero_label=False):
num_imgs = len(results)
assert (len(gt_seg_maps) == num_imgs)
total_area_intersect = np.zeros((num_classes,), dtype=np.float)
total_area_union = np.zeros((num_classes,), dtype=np.fl... |
def _find_ammo_for(ammo_names: tuple[(str, ...)], ammo_pickup_configuration: AmmoPickupConfiguration) -> tuple[((AmmoPickupDefinition | None), bool)]:
for (ammo, ammo_state) in ammo_pickup_configuration.pickups_state.items():
if (ammo.items == ammo_names):
return (ammo, ammo_state.requires_main_... |
class TestIntelHex16bit(TestIntelHexBase):
def setUp(self):
self.f = StringIO(hex16)
def tearDown(self):
self.f.close()
del self.f
def test_init_from_file(self):
ih = intelhex.IntelHex16bit(self.f)
def test_init_from_ih(self):
ih = intelhex.IntelHex(self.f)
... |
def save_model_and_optimizer_sharded(model, rank, cfg, optim=None, verbose=True):
folder_name = ((((cfg.dist_checkpoint_root_folder + '/') + cfg.dist_checkpoint_folder) + '-') + cfg.model_name)
save_dir = (Path.cwd() / folder_name)
if (rank == 0):
print(f'Saving model to {save_dir}')
distributed... |
class TestRuntimeTypeGuard(TestNameCheckVisitorBase):
_passes()
def test_runtime(self):
from typing_extensions import Annotated
from annotated_types import Predicate
from pyanalyze.runtime import is_compatible
IsLower = Annotated[(str, Predicate(str.islower))]
def want_lo... |
def crop_to_square(image):
(height, width) = (tf.shape(image)[0], tf.shape(image)[1])
if (height > width):
image = tf.image.crop_to_bounding_box(image, ((height - width) // 2), 0, width, width)
elif (width > height):
image = tf.image.crop_to_bounding_box(image, 0, ((width - height) // 2), he... |
def grids_available(*grid_names, check_network=True, check_all=False):
if (check_network and pyproj.network.is_network_enabled()):
return True
available = [(Path(get_data_dir(), grid_name).exists() or Path(get_user_data_dir(), grid_name).exists()) for grid_name in grid_names]
if check_all:
r... |
def test_legacy_record_update_listener():
zc = Zeroconf(interfaces=['127.0.0.1'])
with pytest.raises(RuntimeError):
r.RecordUpdateListener().update_record(zc, 0, r.DNSRecord('irrelevant', const._TYPE_SRV, const._CLASS_IN, const._DNS_HOST_TTL))
updates = []
class LegacyRecordUpdateListener(r.Reco... |
def get_item_id_for_item(item: ResourceInfo) -> str:
assert isinstance(item, ItemResourceInfo)
if ('item_capacity_id' in item.extra):
return item.extra['item_capacity_id']
try:
return item.extra['item_id']
except KeyError as e:
raise KeyError(f'{item.long_name} has no item ID.') ... |
class AudioEncoder(nn.Module):
def __init__(self):
super(AudioEncoder, self).__init__()
self.audio_encoder = Sequential(Conv2d(1, 128, kernel_size=4, stride=2, padding=1, padding_mode='zeros'), BatchNorm2d(128), ReLU(), Dropout(0.25), Conv2d(128, 128, kernel_size=4, stride=2, padding=1, padding_mode... |
class KnownValues(unittest.TestCase):
def test_ea_adc2(self):
(e, t_amp1, t_amp2) = myadc.kernel_gs()
self.assertAlmostEqual(e, (- 0.), 6)
myadcea = adc.radc_ea.RADCEA(myadc)
(e, v, p, x) = myadcea.kernel(nroots=3)
self.assertAlmostEqual(e[0], 0., 6)
self.assertAlmost... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.