code stringlengths 281 23.7M |
|---|
def test_filter_submissions_by_tags(graphql_client, user, submission_factory, mock_has_ticket):
graphql_client.force_login(user)
submission = submission_factory(tags=['cat'])
submission_factory(conference=submission.conference, tags=['dog', 'bear'])
submission_3 = submission_factory(conference=submissio... |
def pad_to_batch(dataset, batch_size):
def _pad_to_batch(*args):
flat_args = tf.nest.flatten(args)
for tensor in flat_args:
if (tensor.shape.ndims is None):
raise ValueError(('Unknown number of dimensions for tensor %s.' % tensor.name))
if (tensor.shape.ndims ... |
def _get_cuts(transition, direction):
n = transition.network.size
if (direction is Direction.BIDIRECTIONAL):
yielded = set()
for cut in chain(_get_cuts(transition, Direction.CAUSE), _get_cuts(transition, Direction.EFFECT)):
cm = utils.np_hashable(cut.cut_matrix(n))
if (cm... |
.fast
def test_cut_slices(verbose=True, plot=True, close_plots=True, *args, **kwargs):
from radis.misc.warning import SlitDispersionWarning
_clean(plot, close_plots)
threshold = 0.01
w = np.arange(4000, 4400, 0.01)
w_slit = np.arange(4198, 4202, 0.1)
slices = _cut_slices(w, w_slit, linear_disper... |
class Accuracy(metrics.Accuracy):
def update(self, output: Dict) -> None:
logits = output['logits']
targets = output['targets']
lens = output['lens']
indices = torch.argmax(logits, dim=(- 1))
correct = torch.eq(indices, targets)
mask = generate_length_mask(lens).to(lo... |
def split_sections(s):
section = None
content = []
for line in yield_lines(s):
if line.startswith('['):
if line.endswith(']'):
if (section or content):
(yield (section, content))
section = line[1:(- 1)].strip()
content =... |
class OpenWrapper():
name: str
mode: str = 'w'
def __enter__(self) -> Any:
Path(self.name).parent.mkdir(parents=True, exist_ok=True)
self.file = open(self.name, self.mode)
return self.file
def __exit__(self, exception_type: Type[BaseException], exception_value: BaseException, tra... |
def get_dkl_model(dataset='MNIST', binary=False):
num_classes = (2 if binary else (100 if (dataset == 'CIFAR100') else 10))
feature_extractor = (LeNetMadry(binary=False, feature_extractor=True) if (dataset == 'MNIST') else resnet.ResNet18(num_classes=num_classes, feature_extractor=True))
feature_extractor.c... |
(cc=STDCALL, params={'ProcessHandle': HANDLE, 'ProcessInformationClass': PROCESSINFOCLASS, 'ProcessInformation': PVOID, 'ProcessInformationLength': ULONG, 'ReturnLength': PULONG})
def hook_ZwQueryInformationProcess(ql: Qiling, address: int, params):
return _QueryInformationProcess(ql, address, params) |
class MetaSingleton(type):
def __init__(self, *args, **kwargs):
self.__instance = None
super(MetaSingleton, self).__init__(*args, **kwargs)
def __call__(self, *args, **kwargs):
if (self.__instance is None):
self.__instance = super(MetaSingleton, self).__call__(*args, **kwargs... |
class SrtmTiff(object):
tile = {}
def __init__(self, filename):
self.tile = self.load_tile(filename)
def load_tile(self, filename):
dataset = gdal.Open(filename)
geotransform = dataset.GetGeoTransform()
xsize = dataset.RasterXSize
ysize = dataset.RasterYSize
l... |
def _squad_convert_example_to_features(example, max_seq_length, doc_stride, max_query_length):
features = []
(doc_tokens, char_to_word_offset) = ([], [])
prev_is_whitespace = True
for c in example.context_text:
if _is_whitespace(c):
prev_is_whitespace = True
else:
... |
class ReadCoilsRequest(ReadBitsRequestBase):
function_code = 1
function_code_name = 'read_coils'
def __init__(self, address=None, count=None, slave=0, **kwargs):
ReadBitsRequestBase.__init__(self, address, count, slave, **kwargs)
def execute(self, context):
if (not (1 <= self.count <= 20... |
class LDAPUrl():
attr2extype = {'who': 'bindname', 'cred': 'X-BINDPW'}
def __init__(self, ldapUrl=None, urlscheme='ldap', hostport='', dn='', attrs=None, scope=None, filterstr=None, extensions=None, who=None, cred=None):
self.urlscheme = urlscheme.lower()
self.hostport = hostport
self.dn... |
class RPNTest(unittest.TestCase):
def get_gt_and_features(self):
num_images = 2
images_tensor = torch.rand(num_images, 20, 30)
image_sizes = [(10, 10), (20, 30)]
images = ImageList(images_tensor, image_sizes)
image_shape = (15, 15)
num_channels = 1024
features... |
class BasicModule(nn.Module):
def __init__(self, inDim, outDim, hidden_dim=1000, dp_rate=0.3):
super(BasicModule, self).__init__()
self.layers = nn.Sequential(nn.Linear(inDim, hidden_dim), nn.ReLU(), nn.Dropout(p=dp_rate), nn.Linear(hidden_dim, outDim))
def forward(self, x):
return self.... |
def channel_pruning_example(config: argparse.Namespace):
data_pipeline = ImageNetDataPipeline(config)
model = models.resnet18(pretrained=True)
if config.use_cuda:
model.to(torch.device('cuda'))
model.eval()
accuracy = data_pipeline.evaluate(model, use_cuda=config.use_cuda)
logger.info('O... |
class SemanticAnalyzerPreAnalysis(TraverserVisitor):
def visit_file(self, file: MypyFile, fnam: str, mod_id: str, options: Options) -> None:
self.platform = options.platform
self.cur_mod_id = mod_id
self.cur_mod_node = file
self.options = options
self.is_global_scope = True
... |
class AbbreviatedFirstNameAnalyzer(_InitialsAnalyzer):
TAG_PATTERN = 'NOUN,anim,%(gender)s,Sgtm,Name,Fixd,Abbr,Init sing,%(case)s'
def init(self, morph):
super(AbbreviatedFirstNameAnalyzer, self).init(morph)
self._tags_masc = [tag for tag in self._tags if ('masc' in tag)]
self._tags_femn... |
class TrainLoop():
def __init__(self, *, model, diffusion, data, batch_size, microbatch, lr, ema_rate, log_interval, save_interval, resume_checkpoint, use_fp16=False, fp16_scale_growth=0.001, schedule_sampler=None, weight_decay=0.0, lr_anneal_steps=0, class_cond=False):
self.model = model
self.diffu... |
def project_version():
version = None
if (not version):
try:
output = subprocess.check_output(['git', 'describe', '--tags', '--always'], stderr=open(os.devnull, 'wb')).strip().decode()
except (FileNotFoundError, subprocess.CalledProcessError):
pass
else:
... |
class JSCoverage(object):
def __init__(self, client: CDPSession) -> None:
self._client = client
self._enabled = False
self._scriptURLs: Dict = dict()
self._scriptSources: Dict = dict()
self._eventListeners: List = list()
self._resetOnNavigation = False
async def s... |
.pydicom
def test_identifier_is_sequence_vr():
replacement_strategy = pseudonymisation_api.pseudonymisation_dispatch
logging.info('Using pseudonymisation strategy')
identifying_keywords_no_SQ = ['PatientID', 'RequestedProcedureID']
identifying_keywords_with_SQ_vr = ['PatientID', 'RequestedProcedureID', ... |
def parse_arguments(parser):
parser.add_argument('--mode', type=str, default='test')
parser.add_argument('--device', type=str, default='cuda')
parser.add_argument('--seed', type=int, default=42)
parser.add_argument('--digit2zero', action='store_true', default=True)
parser.add_argument('--dataset', t... |
def configure(config: Config) -> None:
cucumber_json_path = config.option.cucumber_json_path
if (cucumber_json_path and (not hasattr(config, 'workerinput'))):
config._bddcucumberjson = LogBDDCucumberJSON(cucumber_json_path)
config.pluginmanager.register(config._bddcucumberjson) |
class nnUNetTrainer_probabilisticOversampling_010(nnUNetTrainer_probabilisticOversampling):
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, unp... |
class struct_tagLAYERPLANEDESCRIPTOR(Structure):
__slots__ = ['nSize', 'nVersion', 'dwFlags', 'iPixelType', 'cColorBits', 'cRedBits', 'cRedShift', 'cGreenBits', 'cGreenShift', 'cBlueBits', 'cBlueShift', 'cAlphaBits', 'cAlphaShift', 'cAccumBits', 'cAccumRedBits', 'cAccumGreenBits', 'cAccumBlueBits', 'cAccumAlphaBits... |
def assert_attrs_equal(attrs, attrs_exp, tolerance=0):
keys_diff = set(attrs).difference(set(attrs_exp))
assert (not keys_diff), 'Different set of keys: {}'.format(keys_diff)
for key in attrs_exp:
err_msg = 'Attribute {} does not match expectation'.format(key)
if isinstance(attrs[key], dict)... |
class GpioHooks():
def __init__(self, ql, pin_num):
self.ql = ql
self.hook_set_func = ([None] * pin_num)
self.hook_reset_func = ([None] * pin_num)
def hook_set(self, pin, func, *args, **kwargs):
self.hook_set_func[pin] = (func, args, kwargs)
def hook_reset(self, pin, func, *a... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('file', type=str, help='Path to the snapshot file.')
parser.add_argument('--max-path-length', '-l', type=int, default=1000)
parser.add_argument('--speedup', '-s', type=float, default=1)
parser.add_argument('--deterministic', '-... |
def main(argv):
import time
start = time.time()
(parser, subparsers) = setup_args()
for c in codecs:
cparser = subparsers.add_parser(c.__name__.lower(), help=f'{c.__name__}')
setup_common_args(cparser)
c.setup_args(cparser)
args = parser.parse_args(argv)
codec_cls = next(... |
def test_convert_outer_out_to_in_mit_sot():
rng_state = np.random.default_rng(1234)
rng_tt = pytensor.shared(rng_state, name='rng', borrow=True)
rng_tt.tag.is_rng = True
rng_tt.default_update = rng_tt
def input_step_fn(y_tm1, y_tm2, rng):
y_tm1.name = 'y_tm1'
y_tm2.name = 'y_tm2'
... |
class Command(BaseCommand):
def get_success_pages(self):
return Page.objects.filter(path__startswith='about/success/')
def image_url(self, path):
new_url = path.replace(settings.MEDIA_ROOT, settings.MEDIA_URL)
return new_url.replace('//', '/')
def fix_image(self, path, page):
... |
def test_multiple_inheritance_python():
class MI1(m.Base1, m.Base2):
def __init__(self, i, j):
m.Base1.__init__(self, i)
m.Base2.__init__(self, j)
class B1(object):
def v(self):
return 1
class MI2(B1, m.Base1, m.Base2):
def __init__(self, i, j):
... |
class Issue(Model):
id = IntType(required=True)
node_id = StringType(required=True)
url = StringType(required=True)
repository_url = StringType(required=True)
labels_url = StringType(required=True)
comments_url = StringType(required=True)
events_url = StringType(required=True)
html_url =... |
.skipif((not HAVE_DEPS_FOR_RESOURCE_ESTIMATES), reason='pyscf and/or jax not installed.')
.slow
def test_cc_helper_rhf():
cell = gto.Cell()
cell.atom = '\n C 0. 0. 0.\n C 1. 1. 1.\n '
cell.basis = 'gth-szv'
cell.pseudo = 'gth-hf-rev'
cell.a = '\n 0., 3., 3.\n 3., 0., 3.\n 3... |
class QuantPruneTest(unittest.TestCase):
((torch.cuda.device_count() <= 1), 'Not enough GPUs available')
def test_qebc_pruned_tw(self) -> None:
batch_size: int = 4
world_size = 2
local_device = torch.device('cuda:0')
num_embedding = 100
emb_dim = 64
pruned_entry =... |
def is_user_an_admin():
import os
if (os.name == 'nt'):
try:
os.listdir(os.sep.join([os.environ.get('SystemRoot', 'C:\\windows'), 'temp']))
except Exception:
return False
else:
return True
else:
return (('SUDO_USER' in os.environ) and (os.g... |
class AppBuildTelemetry(BaseModel, extra='forbid'):
name: str = Field(..., description='')
version: str = Field(..., description='')
features: Optional['AppFeaturesTelemetry'] = Field(default=None, description='')
system: Optional['RunningEnvironmentTelemetry'] = Field(default=None, description='')
... |
def create_manifest_for_testing(repository, differentiation_field='1', include_shared_blob=False):
layer_json = json.dumps({'config': {}, 'rootfs': {'type': 'layers', 'diff_ids': []}, 'history': []})
(_, config_digest) = _populate_blob(layer_json)
remote_digest = sha256_digest(b'something')
builder = Do... |
def get_metadata(path: str) -> 'Metadata':
parsed = mutagen.File(path, easy=True)
if (parsed is None):
raise ValueError
metadata: 'Metadata' = {}
if (parsed.tags is not None):
if ('artist' in parsed.tags):
metadata['artist'] = parsed.tags['artist'][0]
if ('title' in p... |
def download_clip_wrapper(row, label_to_dir, trim_format, tmp_dir):
output_filename = construct_video_filename(row, label_to_dir, trim_format)
clip_id = os.path.basename(output_filename).split('.mp4')[0]
if os.path.exists(output_filename):
status = tuple([clip_id, True, 'Exists'])
return sta... |
def get_peft_model_state_dict(model, state_dict=None, adapter_name='default'):
config = model.peft_config[adapter_name]
if (state_dict is None):
state_dict = model.state_dict()
if (config.peft_type in (PeftType.LORA, PeftType.ADALORA)):
bias = config.bias
if (bias == 'none'):
... |
def path_typed_attrs(draw: DrawFn, defaults: Optional[bool]=None, kw_only: Optional[bool]=None) -> Tuple[(_CountingAttr, SearchStrategy[Path])]:
from string import ascii_lowercase
default = NOTHING
if ((defaults is True) or ((defaults is None) and draw(booleans()))):
default = Path(draw(text(ascii_l... |
def test_update_questionsets(db, settings):
xml_file = (((Path(settings.BASE_DIR) / 'xml') / 'elements') / 'questionsets.xml')
root = read_xml_file(xml_file)
version = root.attrib.get('version')
elements = flat_xml_to_elements(root)
elements = convert_elements(elements, version)
elements = order... |
def test_installer_required_extras_should_not_be_removed_when_updating_single_dependency_pypi_repository(locker: Locker, repo: Repository, package: ProjectPackage, installed: CustomInstalledRepository, env: NullEnv, mocker: MockerFixture, config: Config) -> None:
mocker.patch('sys.platform', 'darwin')
pool = Re... |
class TestSwitchInlineQueryChosenChat(TestSwitchInlineQueryChosenChatBase):
def test_slot_behaviour(self, switch_inline_query_chosen_chat):
inst = switch_inline_query_chosen_chat
for attr in inst.__slots__:
assert (getattr(inst, attr, 'err') != 'err'), f"got extra slot '{attr}'"
... |
.parametrize('\n repository,\n day,\n count_response, expected_request, expected_count, throws\n ', [pytest.param(FAKE_REPOSITORIES['user1/repo1'], parse('2018-03-08').date(), COUNT_RESPONSE, COUNT_REQUEST, 1, False, id='Valid Count with 1 as result')])
def test_count_repository_actions(repository, day, count_respo... |
class TalkieRoot(Talkie):
def __init__(self, **kwargs):
self._listeners = listdict()
Talkie.__init__(self, **kwargs)
def talkie_connect(self, path, listener):
connection = TalkieConnection(self, path, listener)
self._listeners[path].append(connection._ref_listener)
return... |
(frozen=True)
class PrimePerGameOptions(PerGameOptions):
input_path: (Path | None) = None
output_directory: (Path | None) = None
output_format: str = 'iso'
use_external_models: set[RandovaniaGame] = dataclasses.field(default_factory=set)
def as_json(self):
return {**super().as_json, 'input_p... |
class TrainNetwork(object):
def __init__(self, args):
super(TrainNetwork, self).__init__()
self.args = args
self.dur_time = 0
self._init_log()
self._init_device()
self._init_data_queue()
self._init_model()
def _init_log(self):
self.args.save = ((((... |
class TestSyntheticLocate():
def setup_method(self) -> None:
lattice = spaghetti.regular_lattice((0, 0, 10, 10), 9, exterior=True)
ntw = spaghetti.Network(in_data=lattice)
gdf = spaghetti.element_as_gdf(ntw, arcs=True)
street = geopandas.GeoDataFrame(geopandas.GeoSeries(gdf['geometry... |
class ConvNet(nn.Module):
def __init__(self, input_dim, output_dim):
super(ConvNet, self).__init__()
(c, h, w) = input_dim
self.conv_1 = nn.Conv2d(in_channels=c, out_channels=32, kernel_size=8, stride=4)
self.conv_2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=4, stride=2... |
def handle_code(code, vk_packet=True):
code_keys = []
if (code in CODES):
code_keys.append(KeyAction(CODES[code]))
elif (len(code) == 1):
code_keys.append(KeyAction(code))
elif (' ' in code):
(to_repeat, count) = code.rsplit(None, 1)
if (to_repeat == 'PAUSE'):
... |
def get_task(args):
task_name = args.task_name
data_cache_dir = args.data_cache_dir
if (task_name == 'mnli'):
if (os.path.isfile(os.path.join(args.output_dir, f'train_examples_seed_{args.seed}.json')) and os.path.isfile(os.path.join(args.output_dir, f'eval_examples_seed_{args.seed}.json'))):
... |
class TFMobileViTIntermediate(tf.keras.layers.Layer):
def __init__(self, config: MobileViTConfig, hidden_size: int, intermediate_size: int, **kwargs) -> None:
super().__init__(**kwargs)
self.dense = tf.keras.layers.Dense(intermediate_size, name='dense')
if isinstance(config.hidden_act, str):... |
class Migration(migrations.Migration):
dependencies = [('digest', '0037_auto__1548')]
operations = [migrations.AlterField(model_name='item', name='tags', field=taggit_autosuggest.managers.TaggableManager(help_text='A comma-separated list of tags.', through='taggit.TaggedItem', to='taggit.Tag', verbose_name='Tag... |
class TestImageProcedure(Procedure):
X_start = FloatParameter('X Start Position', units='m', default=0.0)
X_end = FloatParameter('X End Position', units='m', default=2.0)
X_step = FloatParameter('X Scan Step Size', units='m', default=0.1)
Y_start = FloatParameter('Y Start Position', units='m', default=(... |
class RTypeVisitor(Generic[T]):
def visit_rprimitive(self, typ: RPrimitive) -> T:
raise NotImplementedError
def visit_rinstance(self, typ: RInstance) -> T:
raise NotImplementedError
def visit_runion(self, typ: RUnion) -> T:
raise NotImplementedError
def visit_rtuple(self, typ: RT... |
def _set_platform_dir_class() -> type[PlatformDirsABC]:
if (sys.platform == 'win32'):
from .windows import Windows as Result
elif (sys.platform == 'darwin'):
from .macos import MacOS as Result
else:
from .unix import Unix as Result
if ((os.getenv('ANDROID_DATA') == '/data') and (... |
class NeighborDistance():
def __init__(self, gdf, spatial_weights, unique_id, verbose=True):
self.gdf = gdf
self.sw = spatial_weights
self.id = gdf[unique_id]
results_list = []
data = gdf.set_index(unique_id).geometry
for (index, geom) in tqdm(data.items(), total=data... |
class SequentialGeventHandler(object):
name = 'sequential_gevent_handler'
queue_impl = gevent.queue.Queue
queue_empty = gevent.queue.Empty
sleep_func = staticmethod(gevent.sleep)
def __init__(self):
self.callback_queue = self.queue_impl()
self._running = False
self._async = N... |
.skip_fips(reason='FIPS self-test sets allow_customize = 0')
_if_memtesting_not_supported()
class TestAssertNoMemoryLeaks():
def test_no_leak_no_malloc(self):
assert_no_memory_leaks(textwrap.dedent('\n def func():\n pass\n '))
def test_no_leak_free(self):
assert_no_memor... |
class VerilogTBGenPass(BasePass):
case_name = MetadataKey(str)
vtbgen_hooks = MetadataKey(list)
def __call__(self, top):
if (not top._dsl.constructed):
raise VerilogImportError(top, f'please elaborate design {top} before applying the TBGen pass!')
assert (not top.has_metadata(sel... |
class SimpleCNNMNIST_header(nn.Module):
def __init__(self, input_dim, hidden_dims, output_dim=10, input_channels=1):
super(SimpleCNNMNIST_header, self).__init__()
self.conv1 = nn.Conv2d(input_channels, 6, 5)
self.relu = nn.ReLU()
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn... |
def _feature_tokenize(string, layer=0, tok_delim=None, feat_delim=None, truncate=None):
tokens = string.split(tok_delim)
if (truncate is not None):
tokens = tokens[:truncate]
if (feat_delim is not None):
tokens = [t.split(feat_delim)[layer] for t in tokens]
return tokens |
def run_data_migration(apps, schema_editor):
Project = apps.get_model('projects', 'Project')
Task = apps.get_model('tasks', 'Task')
View = apps.get_model('views', 'View')
for project in Project.objects.all():
tasks = Task.objects.filter(sites=settings.SITE_ID)
for task in tasks:
... |
class model_gx(nn.Module):
def __init__(self, input_size, output_size):
super(model_gx, self).__init__()
self.linear1 = nn.Linear(input_size, 256)
self.bn1 = nn.BatchNorm1d(256)
self.linear2 = nn.Linear(256, 128)
self.bn2 = nn.BatchNorm1d(128)
self.linear3 = nn.Linear... |
def playground(cfg):
set_seed(cfg)
state_dict = find_model(cfg.resume_path)
train_dataset = ParameterDataset(dataset_dir=cfg.dataset.path, dataset_name=cfg.dataset.name, num_test_runs=cfg.dataset.num_test_runs, openai_coeff=cfg.dataset.openai_coeff, normalizer_name=cfg.dataset.normalizer, split='train', tra... |
_grad()
def predict(dataloader, model, n_samples=1, T=1):
py = []
for (x, _) in dataloader:
x = x.cuda()
py_ = 0
for _ in range(n_samples):
f_s = model.forward(x)
py_ += torch.softmax((f_s / T), 1)
py_ /= n_samples
py.append(py_)
return torch.c... |
def test_ip6_addresses_to_indexes():
interfaces = [1]
with patch('zeroconf._utils.net.ifaddr.get_adapters', return_value=_generate_mock_adapters()):
assert (netutils.ip6_addresses_to_indexes(interfaces) == [(('2001:db8::', 1, 1), 1)])
interfaces_2 = ['2001:db8::']
with patch('zeroconf._utils.net... |
def generate(opts):
cli.validate_password_if_provided(opts)
print('Will generate a root CA and two certificate/key pairs (server and client)')
g.generate_root_ca(opts)
cn = opts.common_name
name = 'server_{}'.format(cn)
g.generate_leaf_certificate_and_key_pair('server', opts, name)
name = 'c... |
def list_from_param(param):
if (not param):
return []
elif isinstance(param, list):
return param
elif isinstance(param, str):
if isfile(param):
with read_file(param) as f:
return f.read().splitlines()
else:
return param.split(',') |
def train(start_epoch):
global EPOCH_CNT
min_loss = .0
loss = 0
for epoch in range(start_epoch, MAX_EPOCH):
EPOCH_CNT = epoch
log_string(('**** EPOCH %03d ****' % epoch))
log_string(('Current learning rate: %f' % get_current_lr(epoch)))
log_string(('Current BN decay momen... |
class RulePtr():
__slots__ = ('rule', 'index')
rule: Rule
index: int
def __init__(self, rule: Rule, index: int):
assert isinstance(rule, Rule)
assert (index <= len(rule.expansion))
self.rule = rule
self.index = index
def __repr__(self):
before = [x.name for x ... |
_specialize
_rewriter([pt_pow])
def local_pow_to_nested_squaring(fgraph, node):
odtype = node.outputs[0].dtype
xsym = node.inputs[0]
ysym = node.inputs[1]
y = get_constant(ysym)
if isinstance(y, np.ndarray):
assert (y.size == 1)
try:
y = y[0]
except IndexError:
... |
class STM32F4xxFlash(QlPeripheral):
class Type(ctypes.Structure):
_fields_ = [('ACR', ctypes.c_uint32), ('KEYR', ctypes.c_uint32), ('OPTKEYR', ctypes.c_uint32), ('SR', ctypes.c_uint32), ('CR', ctypes.c_uint32), ('OPTCR', ctypes.c_uint32), ('OPTCR1', ctypes.c_uint32)]
def __init__(self, ql: Qiling, label... |
def get_dataloader(root_dir, local_rank, batch_size, dali=False, seed=2048, num_workers=2) -> Iterable:
rec = os.path.join(root_dir, 'train.rec')
idx = os.path.join(root_dir, 'train.idx')
train_set = None
if (root_dir == 'synthetic'):
train_set = SyntheticDataset()
dali = False
elif ... |
class BadgeScannerQuery():
(permission_classes=[IsAuthenticated])
def badge_scan(self, info: Info, id: strawberry.ID) -> (BadgeScan | None):
try:
scan = models.BadgeScan.objects.get(id=id, scanned_by_id=info.context.request.user.id)
except models.BadgeScan.DoesNotExist:
r... |
class DisjunctiveTrie():
def __init__(self, nested_token_ids: List[List[int]], no_subsets=True):
self.max_height = max([len(one) for one in nested_token_ids])
root = dict()
for token_ids in nested_token_ids:
level = root
for (tidx, token_id) in enumerate(token_ids):
... |
def apply_diff(cache_dir: str, diff_file: str, sqlite: bool=False) -> None:
cache = make_cache(cache_dir, sqlite)
with open(diff_file) as f:
diff = json.load(f)
old_deps = json.loads(cache.read('.json'))
for (file, data) in diff.items():
if (data is None):
cache.remove(file)
... |
def get_debugger():
try:
from IPython.core.debugger import Pdb
pdb = Pdb()
except ImportError:
try:
from IPython.Debugger import Pdb
from IPython.Shell import IPShell
IPShell(argv=[''])
pdb = Pdb()
except ImportError:
wa... |
class CodeAssistInProjectsTest(unittest.TestCase):
def setUp(self):
super().setUp()
self.project = testutils.sample_project()
self.pycore = self.project.pycore
samplemod = testutils.create_module(self.project, 'samplemod')
code = dedent(' class SampleClass(object):... |
def test_kraus_map(dimensions, dtype):
if (isinstance(dimensions, list) and isinstance(dimensions[0], list)):
with pytest.raises(TypeError) as err:
kmap = rand_kraus_map(dimensions, dtype=dtype)
assert ('super operator' in str(err.value))
else:
kmap = rand_kraus_map(dimension... |
class ClassificationModel(object):
def __init__(self, K, is_test=False, seed=0):
if is_test:
class ARGS():
num_inducing = 2
iterations = 1
small_iterations = 1
adam_lr = 0.01
minibatch_size = 100
else:
... |
def main(_):
(model_config, train_config, input_config) = get_configs_from_pipeline_file()
model_fn = functools.partial(build_man_model, model_config=model_config, is_training=True)
create_input_dict_fn = functools.partial(input_reader.read_seq, input_config)
trainer_seq.train(model_fn, create_input_dic... |
def test_setup_cfg(testdir, xdist_args):
testdir.makefile('.cfg', setup='\n [mypy]\n disallow_untyped_defs = True\n ')
testdir.makepyfile(conftest='\n def pyfunc(x):\n return x * 2\n ')
result = testdir.runpytest_subprocess('--mypy', *xdist_args)... |
class Label(datatype('Label', ['key', 'value', 'uuid', 'source_type_name', 'media_type_name'])):
def for_label(cls, label):
if (label is None):
return None
return Label(db_id=label.id, key=label.key, value=label.value, uuid=label.uuid, media_type_name=model.label.get_media_types()[label.... |
def Fmt_test():
Print_Function()
e3d = Ga('e1 e2 e3', g=[1, 1, 1])
v = e3d.mv('v', 'vector')
B = e3d.mv('B', 'bivector')
M = e3d.mv('M', 'mv')
Fmt(2)
print('#Global $Fmt = 2$')
print('v =', v)
print('B =', B)
print('M =', M)
print('#Using $.Fmt()$ Function')
print('v.Fmt(... |
(dataset=dataset_utm_north_down())
def test_window_rt_north_down(dataset):
(left, top) = (dataset.transform * (0, 0))
(right, bottom) = (dataset.transform * (dataset.width, dataset.height))
assert_windows_almost_equal(dataset.window(left, bottom, right, top), windows.Window(0, 0, dataset.width, dataset.heig... |
def test_jsx():
assert (list(jslexer.tokenize('\n <option value="val1">{ i18n._(\'String1\') }</option>\n <option value="val2">{ i18n._(\'String 2\') }</option>\n <option value="val3">{ i18n._(\'String 3\') }</option>\n <component value={i18n._(\'String 4\')} />\n <comp2 prop... |
class Acquirer():
def __init__(self, size: int, init_size: Union[(int, float)]=0.01, batch_sizes: Iterable[Union[(int, float)]]=[0.01], metric: str='greedy', epsilon: float=0.0, beta: int=2, xi: float=0.01, threshold: float=float('-inf'), temp_i: Optional[float]=None, temp_f: Optional[float]=1.0, seed: Optional[int... |
class BaseDebugCommand(BaseCommand):
def __init__(self, *args, **kwargs):
if (not settings.DEBUG):
raise CommandError('This command is not allowed in production. Set DEBUG to False to use this command.')
super().__init__(*args, **kwargs)
def handle(self, *args, **options):
ra... |
class TestAsyncGenerator(TestNameCheckVisitorBase):
_passes()
def test_async_iterator(self):
import collections.abc
from typing import AsyncIterator
async def gen() -> AsyncIterator[int]:
(yield 3)
(yield 'not an int')
async def capybara() -> None:
... |
_vcs_handler('git', 'keywords')
def git_versions_from_keywords(keywords, tag_prefix, verbose):
if (not keywords):
raise NotThisMethod('no keywords at all, weird')
refnames = keywords['refnames'].strip()
if refnames.startswith('$Format'):
if verbose:
print('keywords are unexpanded... |
class wide_basic(nn.Module):
def __init__(self, in_channels, channels, dropout_rate, params, stride=1):
super(wide_basic, self).__init__()
add_output = params[0]
num_classes = params[1]
input_size = params[2]
self.output_id = params[3]
self.depth = 2
self.laye... |
class Migration(migrations.Migration):
dependencies = [('users', '0007_auto__1555')]
operations = [migrations.AlterField(model_name='user', name='email', field=models.EmailField(max_length=254, verbose_name='email address', blank=True)), migrations.AlterField(model_name='user', name='groups', field=models.ManyT... |
class Conv2dSame(nn.Conv2d):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True):
super(Conv2dSame, self).__init__(in_channels, out_channels, kernel_size, stride, 0, dilation, groups, bias)
def forward(self, x):
return conv2d_same(x, s... |
def render_event(events_definition, state, fn_prefix):
evname = state['evname']
ev_description = events_definition[evname]
parts = [fn_prefix(state)]
parts.append(ev_description['desc'])
for name in ev_description['update_names']:
if (name == 'evname'):
continue
parts.app... |
_api()
class buffer(Stream):
_graphviz_shape = 'diamond'
def __init__(self, upstream, n, **kwargs):
self.queue = Queue(maxsize=n)
kwargs['ensure_io_loop'] = True
Stream.__init__(self, upstream, **kwargs)
self.loop.add_callback(self.cb)
def update(self, x, who=None, metadata=N... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.