code stringlengths 281 23.7M |
|---|
def animate():
rot = la.quat_from_euler((0.005, 0.01), order='xy')
cube1.local.rotation = la.quat_mul(rot, cube1.local.rotation)
cube2.local.rotation = la.quat_mul(rot, cube2.local.rotation)
renderer1.render(scene1, camera1)
renderer2.render(scene2, camera2)
renderer2.request_draw() |
(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = (yield)
result = outcome.get_result()
if (result.when == 'setup'):
setattr(item, '_test_failed_statuses', {})
_test_failed_statuses = getattr(item, '_test_failed_statuses', {})
_test_failed_statuses[result.when] = result... |
class CommandGraphNode(metaclass=abc.ABCMeta):
def selector(self) -> ((str | int) | None):
def selectors(self) -> list[SelectorType]:
def parent(self) -> (CommandGraphNode | None):
def children(self) -> list[str]:
def navigate(self, name: str, selector: ((str | int) | None)) -> CommandGraphNode:
... |
.parametrize('username,password', users)
.parametrize('project_id', projects)
def test_project_export_xml(db, client, files, username, password, project_id):
client.login(username=username, password=password)
url = reverse('project_export', args=[project_id, 'xml'])
response = client.get(url)
if (projec... |
class TASFSave(TestCase):
original = os.path.join(DATA_DIR, 'silence-1.wma')
def setUp(self):
self.filename = get_temp_copy(self.original)
self.audio = ASF(self.filename)
def tearDown(self):
os.unlink(self.filename)
def test_save_filename(self):
self.audio.save(self.audio... |
class NodeScenarioSuccessOutput():
nodes: typing.Dict[(int, Node)] = field(metadata={'name': 'Nodes started/stopped/terminated/rebooted', 'description': 'Map between timestamps and the pods started/stopped/terminated/rebooted.\n The timestamp is provided in nanoseconds'})
action: kube_hel... |
class BaseDriver(ABC):
def __init__(self, molecule: Optional[Molecule]=None, basis: str='sto3g', hf_method: str='rhf', supports_molecule: bool=False) -> None:
if ((molecule is not None) and (not supports_molecule)):
raise QiskitChemistryError("Driver doesn't support molecule.")
self._mol... |
def _show_files_win32(dirname, entries):
if (not is_windows()):
raise BrowseError('windows only')
if (not entries):
try:
if (subprocess.call(['explorer', dirname]) != 0):
raise OSError('explorer error return status')
except OSError as e:
raise Brow... |
class EPICSBooleanButton(gui.Container, EPICSWidget):
icon = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC4AAAAuCAYAAABXuSs3AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAOxAAADsQBlSsOGwAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAKMSURBVGiB7ZqxaxNRGMB/9+7uXZK2aaMVEUWEKNSh4CQIrhWnujiIQqGig7gXF/+B7tLNbp2KQyfBwcVdsdhW... |
def filter_available_models(model_dict: Union[(List[dict], Tuple[(dict, ...)])], dataset_name_or_id: Union[(str, int)]):
valid = []
for trained_model in model_dict:
plans_manager = PlansManager(join(nnUNet_preprocessed, maybe_convert_to_dataset_name(dataset_name_or_id), (trained_model['plans'] + '.json'... |
def download_subprocess(dii, save_dir):
for image in tqdm(dii):
(key, value) = image.popitem()
try:
img_data = requests.get(value).content
img = Image.open(BytesIO(img_data)).convert('RGB')
h = img.size[0]
w = img.size[1]
if (min(h, w) > 51... |
class ChannelTest(unittest.TestCase):
def setUp(self):
zero_state = np.array([[1], [0]], dtype=complex)
one_state = np.array([[0], [1]], dtype=complex)
one_one_state = np.kron(one_state, one_state)
zero_zero_state = np.kron(zero_state, zero_state)
cat_state = ((1.0 / np.sqrt(... |
class AverageMeter():
def __init__(self, num=100):
self.num = num
self.reset()
def reset(self):
self.val = {}
self.sum = {}
self.count = {}
self.history = {}
def update(self, batch=1, **kwargs):
val = {}
for k in kwargs:
val[k] = (k... |
def test_specifying_process_covariance_Q_motion_model():
with open(CONFIG_FILE, 'r') as config_file:
config = json.load(config_file)['TrackerConfig']
assert ('G' in config['MotionModel'])
assert ('Q' not in config['MotionModel'])
model = utils.read_motion_model(config)
test_config = dict(con... |
_param_scheduler('composite')
class CompositeParamScheduler(param_scheduler.CompositeParamScheduler):
__doc__ = param_scheduler.CompositeParamScheduler.__doc__
def __init__(self, schedulers: Sequence[param_scheduler.ParamScheduler], lengths: Sequence[float], interval_scaling: Sequence[Union[(IntervalScaling, st... |
class TestDataset(Dataset):
def __init__(self, args, raw_datasets, cache_root):
self.args = args
self.raw_datasets = raw_datasets
cache_path = os.path.join(cache_root, 'e2e_nlg_cleaned_test.cache')
if (os.path.exists(cache_path) and args.dataset.use_cache):
(self.full_src... |
.parametrize('input_value, clean, alias', [({'type': 'null', 'alias': None, 'doc': None, 'logical': None}, False, False), ('null', True, False), ('bool', True, False), ({'type': 'int', 'bits': 32, 'signed': True, 'alias': None, 'doc': None, 'logical': None}, False, False), ({'type': 'int', 'bits': 32}, True, False), ({... |
class InceptionResNetV2(nn.Module):
def __init__(self, dropout_rate=0.0, in_channels=3, in_size=(299, 299), num_classes=1000):
super(InceptionResNetV2, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
layers = [10, 21, 11]
normal_units = [InceptionAUnit,... |
class CmdOpenLid(Command):
key = 'open lid'
aliases = ['open button', 'open']
locks = 'cmd:all()'
def func(self):
if self.obj.db.lid_locked:
self.caller.msg('This lid seems locked in place for the moment.')
return
string = '\nA ticking sound is heard, like a windi... |
((not DASK_INSTALLED), reason='Dask is not installed in a supported version.')
class DaskDataSourceTest(_DistributedDataSourceTest, unittest.TestCase):
def _testAssignPartitions(self, part_nodes, actor_nodes, expected_actor_parts):
partitions = list(range(len(part_nodes)))
part_to_node = dict(zip(ra... |
class RegRst(Component):
def construct(s, Type, reset_value=0):
s.out = OutPort(Type)
s.in_ = InPort(Type)
_ff
def up_regrst():
if s.reset:
s.out <<= reset_value
else:
s.out <<= s.in_
def line_trace(s):
return f"[{('... |
class TMP4Chapters(TMP4):
original = os.path.join(DATA_DIR, 'nero-chapters.m4b')
def test_has_chapters(self):
self.failUnless(hasattr(self.audio, 'chapters'))
chapters = self.audio.chapters
self.failUnlessEqual(len(chapters), 112)
for (i, c) in enumerate(chapters):
se... |
def compute_average_flops_cost(self, bw_weight=4, bw_act=4, strategy=(None, None), print_layerwise=False):
quant_idx = 0
(w_str, a_str) = (strategy[0], strategy[1])
batches_count = self.__batch_counter__
flops_sum = 0
for (name, module) in self.named_modules():
if is_supported_instance(modul... |
class RpmPackage(Package):
def is_installed(self):
return (self.run_test('rpm -q %s', self.name).rc == 0)
def version(self):
return self.check_output('rpm -q --queryformat="%%{VERSION}" %s', self.name)
def release(self):
return self.check_output('rpm -q --queryformat="%%{RELEASE}" %s... |
def test_binary_ssvm_repellent_potentials():
(X, Y) = generate_checker()
crf = GridCRF(inference_method=inference_method)
clf = NSlackSSVM(model=crf, max_iter=10, C=100, check_constraints=True)
clf.fit(X, Y)
Y_pred = clf.predict(X)
assert_array_equal(Y, Y_pred)
submodular_clf = NSlackSSVM(mo... |
class Effect4974(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Shield Operation')), 'shieldBonus', ship.getModifiedItemAttr('eliteBonusViolators2'), skill='Marauders', **kwargs) |
def _run_crefl_abi(refl, mus, muv, phi, solar_zenith, sensor_zenith, height, *coeffs):
a_O3 = [268.45, 0.5, 115.42, (- 3.2922)]
a_H2O = [0.0311, 0.1, 92.471, (- 1.3814)]
a_O2 = [0.4567, 0.007, 96.4884, (- 1.697)]
G_O3 = (_G_calc(solar_zenith, a_O3) + _G_calc(sensor_zenith, a_O3))
G_H2O = (_G_calc(so... |
def unary_union(shapes):
if (shapely_version < '1.2.16'):
raise Exception('shapely 1.2.16 or higher needed for unary_union; upgrade shapely or try cascade_union instead')
o = []
for shape in shapes:
if (not hasattr(shape, GEO_INTERFACE_ATTR)):
raise TypeError((SHAPE_TYPE_ERR % sh... |
def test_optimizer():
nan_detected = [False]
def detect_nan(fgraph, i, node, fn):
for output in fn.outputs:
if np.isnan(output[0]).any():
print('*** NaN detected ***')
debugprint(node)
print(('Inputs : %s' % [input[0] for input in fn.inputs]))
... |
def pad_if_smaller(img, size, fill=0):
min_size = min(img.size)
if (min_size < size):
(original_width, original_height) = img.size
pad_height = ((size - original_height) if (original_height < size) else 0)
pad_width = ((size - original_width) if (original_width < size) else 0)
im... |
class F28_TestCase(F20_TestCase):
def runTest(self):
F20_TestCase.runTest(self)
self.assert_parse('firewall --use-system-defaults', 'firewall --use-system-defaults\n')
self.assert_parse('firewall --enabled --service=ssh --use-system-defaults', 'firewall --use-system-defaults\n') |
def partition_data(dataset, datadir, logdir, partition, n_parties, labeled_num, beta=0.4):
if (dataset == 'cifar10'):
(X_train, y_train, X_test, y_test) = load_cifar10_data(datadir)
state = np.random.get_state()
np.random.shuffle(X_train)
np.random.set_state(state)
np.random.shuffle(y_train)... |
class GaussianProcessLayer(gpytorch.models.ApproximateGP):
def __init__(self, num_dim, grid_bounds=((- 10.0), 10.0), grid_size=64):
variational_distribution = gpytorch.variational.CholeskyVariationalDistribution(num_inducing_points=grid_size, batch_shape=torch.Size([num_dim]))
variational_strategy =... |
def _get_help_record(opt):
def _write_opts(opts):
(rv, _) = click.formatting.join_options(opts)
if ((not opt.is_flag) and (not opt.count)):
rv += ' <{}>'.format(opt.name)
return rv
rv = [_write_opts(opt.opts)]
if opt.secondary_opts:
rv.append(_write_opts(opt.secon... |
def change_coordinate_frame(boxlist, window, scope=None):
with tf.name_scope(scope, 'ChangeCoordinateFrame'):
win_height = (window[2] - window[0])
win_width = (window[3] - window[1])
boxlist_new = scale(box_list.BoxList((boxlist.get() - [window[0], window[1], window[0], window[1]])), (1.0 / ... |
class RequestTests(GeneratorTestCase):
def setUp(self):
super().setUp()
self.reader = StreamReader()
def parse(self):
return Request.parse(self.reader.read_line)
def test_parse(self):
self.reader.feed_data(b'GET /chat HTTP/1.1\r\nHost: server.example.com\r\nUpgrade: websocket... |
class RankRounder(CompRatioRounder):
def __init__(self, multiplicity: int, cost_calculator):
self._multiplicity = multiplicity
self._cost_calculator = cost_calculator
def round(self, layer: Layer, comp_ratio: Decimal, cost_metric: CostMetric) -> Decimal:
if (self._multiplicity == 1):
... |
def main():
datapipes_folder = os.path.join('torchdata', 'datapipes')
init_file = '__init__.py'
docs_source_folder = os.path.join('docs', 'source')
exit_code = 0
for (target, ignore_set) in zip(['iter', 'map', 'utils'], [{'IterDataPipe', 'Extractor'}, {'MapDataPipe'}, {}]):
init_path = os.pa... |
class Color(VersionBase):
def __init__(self, color_type, color_definition):
self.color_type = convert_enum(color_type, ColorType, False)
if (not isinstance(color_definition, _ColorDefinition)):
raise TypeError('input is not a color definition')
self.color_definition = color_defin... |
def test_get_bindings():
def function1(a: int) -> None:
pass
assert (get_bindings(function1) == {})
def function2(a: int) -> None:
pass
assert (get_bindings(function2) == {'a': int})
('b')
def function3(a: int, b: str) -> None:
pass
assert (get_bindings(function3) == ... |
class TBEArmor(DefaultObject):
def at_object_creation(self):
self.db.damage_reduction = 4
self.db.defense_modifier = (- 4)
def at_before_drop(self, dropper):
if is_in_combat(dropper):
dropper.msg("You can't doff armor in a fight!")
return False
return True... |
def test_primitive_types(client):
client = BigQueryClient(client)
recap_schema = client.schema('test_project', 'test_dataset', 'test_table')
recap_fields = recap_schema.fields
assert (recap_fields[0] == UnionType(types=[NullType(), StringType()], default=None, name='test_string'))
assert (recap_fiel... |
def sample_and_group_all(xyz, points, use_xyz=True):
batch_size = xyz.get_shape()[0].value
nsample = xyz.get_shape()[1].value
new_xyz = tf.constant(np.tile(np.array([0, 0, 0]).reshape((1, 1, 3)), (batch_size, 1, 1)), dtype=tf.float32)
idx = tf.constant(np.tile(np.array(range(nsample)).reshape((1, 1, nsa... |
.skipif((sys.version_info < (3, 11)), reason='Native ExceptionGroup not implemented')
.parametrize('outer_chain', ['none', 'from', 'another'])
.parametrize('inner_chain', ['none', 'from', 'another'])
def test_native_exceptiongroup(pytester: Pytester, outer_chain, inner_chain) -> None:
_exceptiongroup_common(pyteste... |
def markup_bbcMicro_word(pronunc):
global bbc_partsSoFar, bbc_charsSoFar
thisPartCount = bbcMicro_partPhonemeCount(pronunc)
if (((not bbc_partsSoFar) or ((bbc_partsSoFar + thisPartCount) > 115)) or ((not bbc_charsSoFar) or ((bbc_charsSoFar + len(pronunc)) > 238))):
if bbc_charsSoFar:
r =... |
def test_directionoftraveldistribution():
dotd = OSC.DirectionOfTravelDistribution(1, 2)
dotd2 = OSC.DirectionOfTravelDistribution(1, 2)
prettyprint(dotd.get_element())
dotd3 = OSC.DirectionOfTravelDistribution(1, 1)
assert (dotd == dotd2)
assert (dotd != dotd3)
dotd4 = OSC.DirectionOfTravel... |
class Formatter(metaclass=ClassRegistry):
subclasses = []
def __init__(self):
pass
def formatters(cls, filename):
for formatter in cls.subclasses:
if formatter.supports(filename):
(yield formatter)
def supports(cls, filename):
for pattern in cls.patter... |
class STM32F4xxRccV1(STM32F4xxRcc):
class Type(ctypes.Structure):
_fields_ = [('CR', ctypes.c_uint32), ('PLLCFGR', ctypes.c_uint32), ('CFGR', ctypes.c_uint32), ('CIR', ctypes.c_uint32), ('AHB1RSTR', ctypes.c_uint32), ('AHB2RSTR', ctypes.c_uint32), ('AHB3RSTR', ctypes.c_uint32), ('RESERVED0', ctypes.c_uint32... |
def test_get_ref_lat_1(ntg1, ntg2, ntg3, ntg_weird, ntg_latlon):
rl1 = ntg1.get_ref_lat_1()
assert isinstance(rl1, float)
np.testing.assert_allclose(rl1, 0.0)
np.testing.assert_allclose(ntg2.get_ref_lat_1(), 2.5)
np.testing.assert_allclose(ntg3.get_ref_lat_1(), 75)
with pytest.raises(ValueError,... |
def _modexp(data: bytes) -> int:
(base_length, exponent_length, modulus_length) = _extract_lengths(data)
if (base_length == 0):
return 0
elif (modulus_length == 0):
return 0
base_end_idx = (96 + base_length)
exponent_end_idx = (base_end_idx + exponent_length)
modulus_end_dx = (ex... |
def test_shifted_qr_np():
np.set_printoptions(formatter={'float': '{:0.2f}'.format})
np_dtype = np.float64
N = 10
diag = generate_spectrum(coeff=0.5, scale=1.0, size=N, dtype=np_dtype)
A = generate_pd_from_diag(diag, dtype=diag.dtype, seed=21)
(A_new, _) = shifted_qr_np(A, shifts=np.zeros((50,))... |
def event_input_bert_mrc_fn(input_Xs, start_Ys, end_Ys, token_type_ids, query_lens, is_training, is_testing, args):
_shapes = (([None], (), (), [None]), ([None], [None]))
_types = ((tf.int32, tf.int32, tf.int32, tf.int32), (tf.int32, tf.int32))
_pads = ((0, 0, 0, 0), (0, 0))
ds = tf.data.Dataset.from_ge... |
def add_content_to_text(text: str, content: str, add_after: Optional[Union[(str, Pattern)]]=None, add_before: Optional[Union[(str, Pattern)]]=None, exact_match: bool=False) -> str:
if ((add_after is None) and (add_before is None)):
raise ValueError('You need to pass either `add_after` or `add_before`')
... |
class CoSQL(datasets.GeneratorBasedBuilder):
VERSION = datasets.Version('1.0.0')
BUILDER_CONFIGS = [datasets.BuilderConfig(name='cosql', version=VERSION, description='A Conversational Text-to-SQL Challenge Towards Cross-Domain Natural Language Interfaces to Databases')]
def __init__(self, *args, writer_batc... |
class GPint(object):
def __init__(self, x_init, model):
self.model = model
self.x = x_init
self.y = model.predict(np.array(x_init, ndmin=2))
def getState(self):
return (self.x, self.model.predict(np.array(self.x, ndmin=2))[0])
def setX(self, x_new):
self.x = x_new |
_images
def test_package(host, docker_image):
assert (not host.package('zsh').is_installed)
ssh = host.package('openssh-server')
version = {'rockylinux9': '8.', 'debian_bookworm': '1:9.2'}[docker_image]
assert ssh.is_installed
assert ssh.version.startswith(version)
release = {'rockylinux9': '.el... |
def test_read_setup_py_empty(tmp_path):
with open((tmp_path / 'setup.py'), 'w') as f:
f.write(dedent('\n from setuptools import setup\n\n REQUIRES = "3.21"\n\n setuptools.setup(\n name = "hello",\n other = 23,\n ... |
def skip_reverse_union_constraints(cs: list[Constraint]) -> list[Constraint]:
reverse_union_cs = set()
for c in cs:
p_target = get_proper_type(c.target)
if isinstance(p_target, UnionType):
for item in p_target.items:
if isinstance(item, TypeVarType):
... |
class MetaConvModel(MetaModule):
def __init__(self, in_channels, out_features, hidden_size=64, feature_size=64):
super(MetaConvModel, self).__init__()
self.in_channels = in_channels
self.out_features = out_features
self.hidden_size = hidden_size
self.feature_size = feature_si... |
def test_sky_temple_key_distribution_logic_all_guardians_valid(echoes_game_description):
results = sky_temple_keys.add_sky_temple_key_distribution_logic(echoes_game_description, LayoutSkyTempleKeyMode.ALL_GUARDIANS)
assert (results == _create_pool_with(3, echoes_game_description.resource_database)) |
class Connect():
MAX_REDIRECTS_ALLOWED = 10
def __init__(self, uri: str, *, create_protocol: Optional[Callable[(..., WebSocketClientProtocol)]]=None, logger: Optional[LoggerLike]=None, compression: Optional[str]='deflate', origin: Optional[Origin]=None, extensions: Optional[Sequence[ClientExtensionFactory]]=Non... |
def process_dir(query_path, gallery_path):
query_img_paths = glob.glob(os.path.join(query_path, '*.jpg'))
gallery_img_paths = glob.glob(os.path.join(gallery_path, '*.jpg'))
query_paths = []
pattern = re.compile('([-\\d]+)_c(\\d)')
for img_path in query_img_paths:
(pid, camid) = map(int, patt... |
_specialize('shape_unsafe')
_rewriter([Elemwise])
def local_elemwise_alloc(fgraph, node):
if (len(node.inputs) == 1):
return None
def dimshuffled_alloc(i):
return (isinstance(i.owner.op, DimShuffle) and i.owner.inputs[0].owner and isinstance(i.owner.inputs[0].owner.op, Alloc))
alloc_idxs = [... |
def create_temporary_tag_if_necessary(manifest, expiration_sec):
tag_name = ('$temp-%s' % str(uuid.uuid4()))
now_ms = get_epoch_timestamp_ms()
end_ms = (now_ms + (expiration_sec * 1000))
with db_transaction():
try:
Tag.select().where((Tag.manifest == manifest), ((Tag.lifetime_end_ms ... |
_sentencepiece
_tokenizers
class DebertaV2TokenizationTest(TokenizerTesterMixin, unittest.TestCase):
tokenizer_class = DebertaV2Tokenizer
rust_tokenizer_class = None
test_rust_tokenizer = False
test_sentencepiece = True
test_sentencepiece_ignore_case = True
def setUp(self):
super().setUp... |
def _numerator(z_slice_shape, precision, unroll=1):
def fwd(qs, ks, vs):
def body(p, qkv):
(q, k, v) = qkv
p += jnp.einsum('...m,...d->...md', k, v, precision=precision)
X_slice = jnp.einsum('...m,...md->...d', q, p, precision=precision)
return (p, X_slice)
... |
class Transformer(nn.Module):
def __init__(self, dim, proj_kernel, kv_proj_stride, depth, heads, dim_head=64, mlp_mult=4, dropout=0.0):
super().__init__()
self.layers = nn.ModuleList([])
for _ in range(depth):
self.layers.append(nn.ModuleList([PreNorm(dim, Attention(dim, proj_ker... |
class PreferencesButton(Gtk.HBox):
def __init__(self, browser):
super().__init__()
self._menu = menu = Gtk.Menu()
pref_item = MenuItem(_('_Preferences'), Icons.PREFERENCES_SYSTEM)
def preferences_cb(menu_item):
window = Preferences(browser)
window.show()
... |
def satisfy_filter(finds_address, is_order):
def inner(x):
order = []
for address in finds_address:
if (address not in x):
return False
else:
order.append(x.find(address))
else:
if is_order:
return (True if (... |
class UserScriptsCollector(diamond.collector.Collector):
def get_default_config_help(self):
config_help = super(UserScriptsCollector, self).get_default_config_help()
config_help.update({'scripts_path': 'Path to find the scripts to run'})
return config_help
def get_default_config(self):
... |
def _decode_headers(decoder, encoded_header_block):
try:
return decoder.decode(encoded_header_block, raw=True)
except OversizedHeaderListError as e:
raise DenialOfServiceError(('Oversized header block: %s' % e))
except (HPACKError, IndexError, TypeError, UnicodeDecodeError) as e:
rai... |
class MpiAdam(object):
def __init__(self, var_list, *, beta1=0.9, beta2=0.999, epsilon=1e-08, scale_grad_by_procs=True, comm=None):
self.var_list = var_list
self.beta1 = beta1
self.beta2 = beta2
self.epsilon = epsilon
self.scale_grad_by_procs = scale_grad_by_procs
siz... |
class ResultCollection():
def load(cls, directory):
if (not os.path.isdir(directory)):
raise ValueError(f"Given filepath '{directory}' is not a directory")
order_fp = os.path.join(directory, '.order')
if os.path.isfile(order_fp):
collection = cls._load_ordered(directo... |
def get_polarity_form_result(score_dict):
extracted_meta = {}
for (source, score) in score_dict.items():
source = source.lower().strip()
if (source != ''):
if (score['PosScore'] < score['NegScore']):
extracted_meta[source] = 'negative'
else:
... |
class RandomHierarchicalPolicy(object):
def __init__(self, base_policy, num_skills, steps_per_option):
self._steps_per_option = steps_per_option
self._base_policy = base_policy
self._num_skills = num_skills
self.reset()
def reset(self):
self._t = 0
self._z = None
... |
class RenderedObservation(ObservationWrapper):
def __init__(self, env, observation_type, image_size, render_kwargs, crop=None):
super(RenderedObservation, self).__init__(env)
self._type = observation_type
self._size = image_size
if (observation_type == 'rgb_image'):
last_... |
class SOTLAgent(Agent):
def __init__(self, dic_agent_conf, dic_traffic_env_conf, dic_path, cnt_round):
super(SOTLAgent, self).__init__(dic_agent_conf, dic_traffic_env_conf, dic_path)
self.current_phase_time = 0
if (self.dic_traffic_env_conf['SIMULATOR_TYPE'] == 'anon'):
self.DIC_... |
def get_material_parameters(mat: material):
try:
bulk_recombination_energy = (mat.bulk_recombination_energy / q)
except ValueError:
bulk_recombination_energy = 0
try:
auger_electron = (mat.electron_auger_recombination * .0)
except ValueError:
auger_electron = 0
try:
... |
def train(epochs, decay=0, threshold=0.0):
model.train()
pbar = tqdm(range(epochs), total=epochs)
curves = np.zeros((epochs, 14))
for epoch in pbar:
for (batch_idx, (data, target)) in enumerate(train_loader):
(data, target) = (data.to(device), target.to(device))
optimizer... |
(scope='module')
def survey_project(project_urls, project_token, mocked_responses) -> Project:
def request_callback_survey(req):
(request_data, request_headers, request_type) = parse_request(req)
request_handler = get_survey_project_request_handler(request_type)
response = request_handler(da... |
class Effect5673(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Small Projectile Turret')), 'damageMultiplier', ship.getModifiedItemAttr('eliteBonusInterceptor2'), skill='Interceptors', **kwargs... |
class NestedDictionaryDataset(FairseqDataset):
def __init__(self, defn, sizes=None):
super().__init__()
self.defn = _flatten(defn)
self.sizes = ([sizes] if (not isinstance(sizes, (list, tuple))) else sizes)
first = None
for v in self.defn.values():
if (not isinsta... |
class ScoreEvaluator():
def __init__(self, scores_file='cos_eor/scripts/orm/mlm_scores.npy', splits_file='cos_eor/scripts/orm/amt_data/splits.yaml', matching='obj_room_recep', random=False, seed=0) -> None:
self.splits_file = splits_file
self.scores_file = scores_file
self.get_scores(matchin... |
def test_upper_lower_index_size_check():
n_tensor = numpy.zeros((2, 2, 2))
m_tensor = numpy.zeros((2, 2))
with pytest.raises(IndexError):
wedge(n_tensor, m_tensor, (3, 1), (1, 1))
with pytest.raises(IndexError):
wedge(n_tensor, m_tensor, (4, 0), (1, 2))
with pytest.raises(IndexError)... |
class LabelItem(GraphicsWidgetAnchor, GraphicsWidget):
def __init__(self, text=' ', parent=None, angle=0, **args):
GraphicsWidget.__init__(self, parent)
GraphicsWidgetAnchor.__init__(self)
self.item = QtWidgets.QGraphicsTextItem(self)
self.opts = {'color': None, 'justify': 'center'}
... |
def guess_terminal(preference: ((str | Sequence) | None)=None) -> (str | None):
test_terminals = []
if isinstance(preference, str):
test_terminals += [preference]
elif isinstance(preference, Sequence):
test_terminals += list(preference)
if ('WAYLAND_DISPLAY' in os.environ):
test_... |
class EmbeddingTowerCollectionSharder(BaseEmbeddingSharder[EmbeddingTowerCollection]):
def __init__(self, fused_params: Optional[Dict[(str, Any)]]=None, qcomm_codecs_registry: Optional[Dict[(str, QuantizedCommCodecs)]]=None) -> None:
super().__init__(fused_params=fused_params, qcomm_codecs_registry=qcomm_co... |
def parse_condition(toks, start_idx, tables_with_alias, schema, default_tables=None):
idx = start_idx
len_ = len(toks)
isBlock = False
if (toks[idx] == '('):
isBlock = True
idx += 1
conds = []
while (idx < len_):
(idx, val_unit) = parse_val_unit(toks, idx, tables_with_ali... |
def generate(args):
constants.DATA_SAVE_PATH = args.save_path
print(('Force Unsave Data: %s' % str(args.force_unsave)))
if isinstance(args.x_display, (list, tuple)):
args.x_display = random.choice(args.x_display)
succ_traj = pd.DataFrame(columns=['goal', 'pickup', 'movable', 'receptacle', 'scene... |
def select_by_keyword(session: Session, dag: nx.DiGraph) -> set[str]:
keywordexpr = session.config['expression']
if (not keywordexpr):
return None
try:
expression = Expression.compile_(keywordexpr)
except ParseError as e:
msg = f"Wrong expression passed to '-k': {keywordexpr}: {e... |
def get_data():
((x_train, y_train), (x_test, y_test)) = test_utils.get_test_data(num_train=batch_size, num_test=batch_size, input_shape=(data_dim,), classification=True, num_classes=num_classes)
y_train = np_utils.to_categorical(y_train, num_classes)
y_test = np_utils.to_categorical(y_test, num_classes)
... |
def encoder_rgcn(inputs, units, training, dropout_rate=0.0):
(graph_convolution_units, auxiliary_units) = units
with tf.variable_scope('graph_convolutions'):
output = multi_graph_convolution_layers(inputs, graph_convolution_units, activation=tf.nn.tanh, dropout_rate=dropout_rate, training=training)
... |
class HashChecker(ContentChecker):
pattern = re.compile('(?P<hash_name>sha1|sha224|sha384|sha256|sha512|md5)=(?P<expected>[a-f0-9]+)')
def __init__(self, hash_name, expected):
self.hash_name = hash_name
self.hash = hashlib.new(hash_name)
self.expected = expected
def from_url(cls, url... |
def get_test_attrs():
attrs = {'name': 'IR_108', 'start_time': datetime.datetime(2018, 1, 1, 0), 'end_time': datetime.datetime(2018, 1, 1, 0, 15), 'int': 1, 'float': 1.0, 'none': None, 'numpy_int': np.uint8(1), 'numpy_float': np.float32(1), 'numpy_bool': True, 'numpy_void': np.void(0), 'numpy_bytes': np.bytes_('tes... |
def conv1x1(in_channels, out_channels, module_name, postfix, stride=1, groups=1, kernel_size=1, padding=0):
return [(f'{module_name}_{postfix}/conv', nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, groups=groups, bias=False)), (f'{module_name}_{postfix}/norm', nn.BatchN... |
_2_unicode_compatible
class ConferenceVenue(AuditModel):
name = models.CharField(max_length=100)
address = models.TextField()
latitude = models.DecimalField(max_digits=17, decimal_places=15)
longitudes = models.DecimalField(max_digits=19, decimal_places=16)
def __str__(self):
return self.nam... |
.parametrize('rho_type, args', [('oper', {}), ('ket', {}), ('oper', {'fock_numbers': [0, 1, 2, 3]}), ('oper', {'unit_y_range': False})])
def test_plot_fock_distribution(rho_type, args):
if (rho_type == 'oper'):
rho = qutip.rand_dm(4)
else:
rho = qutip.basis(2, 0)
(fig, ax) = qutip.plot_fock_... |
def getCharactersForUser(lookfor, eager=None):
if isinstance(lookfor, int):
eager = processEager(eager)
with sd_lock:
characters = saveddata_session.query(Character).options(*eager).filter((Character.ownerID == lookfor)).all()
else:
raise TypeError('Need integer as argument')... |
class RootComponentFinder():
def run(self):
paths = self.get_paths()
templates = self.get_templates(paths)
components = self.get_components(templates)
self.register_components(components)
def get_loaders(self):
template_source_loaders = []
for e in engines.all():
... |
def test_set_progress_bar_enabled():
TINY_MODEL = 'hf-internal-testing/tiny-random-distilbert'
with patch('tqdm.auto.tqdm') as mock_tqdm:
disable_progress_bar()
_ = AutoConfig.from_pretrained(TINY_MODEL, force_download=True)
mock_tqdm.assert_not_called()
mock_tqdm.reset_mock()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.