code stringlengths 281 23.7M |
|---|
class Mpd2(base.ThreadPoolText):
defaults = [('update_interval', 1, 'Interval of update widget'), ('host', 'localhost', 'Host of mpd server'), ('port', 6600, 'Port of mpd server'), ('password', None, 'Password for auth on mpd server'), ('mouse_buttons', keys, 'b_num -> action.'), ('play_states', play_states, 'Play ... |
def _check_mopidy_extensions_user() -> Dict[(str, Tuple[(bool, str)])]:
config = subprocess.run(['mopidy', 'config'], stdout=subprocess.PIPE, universal_newlines=True, check=True).stdout
parser = configparser.ConfigParser()
parser.read_string(config)
extensions = {}
for extension in ['spotify', 'soun... |
class Window(Gtk.Window):
windows: list[Gtk.Window] = []
_preven_inital_show = False
def __init__(self, *args, **kwargs):
self._header_bar = None
dialog = kwargs.pop('dialog', True)
super().__init__(*args, **kwargs)
type(self).windows.append(self)
if dialog:
... |
class RoutingTotals(ctypes.Structure):
_fields_ = [('dwInflow', ctypes.c_double), ('wwInflow', ctypes.c_double), ('gwInflow', ctypes.c_double), ('iiInflow', ctypes.c_double), ('exInflow', ctypes.c_double), ('flooding', ctypes.c_double), ('outflow', ctypes.c_double), ('evapLoss', ctypes.c_double), ('seepLoss', ctype... |
class Effect3962(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Repair Systems')), 'armorDamageAmount', src.getModifiedItemAttr('subsystemBonusMinmatarDefensive'), skill='Minmatar Defensive Syste... |
class WindowSetFullScreenEventSequenceTest(EventSequenceTest, unittest.TestCase):
last_sequence = 2
def on_resize(self, width, height):
self.check_sequence(1, 'on_resize')
def on_expose(self):
self.check_sequence(2, 'on_expose')
def test_method(self):
window.Window._enable_event_... |
class ModalEmbeddings(nn.Module):
def __init__(self, config, encoder, embeddings):
super().__init__()
self.config = config
self.encoder = encoder
self.proj_embeddings = nn.Linear(config.modal_hidden_size, config.hidden_size)
self.position_embeddings = embeddings.position_embe... |
def optimize_one_inter_rep(inter_rep, layer_name, target, probe, lr=0.001, max_epoch=256, loss_func=nn.CrossEntropyLoss(), verbose=False):
with autocast('cuda', enabled=False):
target_clone = torch.Tensor(target).to(torch.long).to(torch_device).unsqueeze(0)
tensor = inter_rep.clone().to(torch_device... |
class PAZ2(Stage):
_format = {None: [E(1, 4, x_fixed(b'PAZ2'), dummy=True), E(6, 7, 'i2'), E(9, 9, 'a1'), E(11, 25, 'e15.8'), E(27, 30, 'i4'), E(32, 39, 'f8.3'), E(41, 43, 'i3'), E(45, 47, 'i3'), E(49, None, 'a25+')], ('IMS1.0', 'USA_DMC'): [E(1, 4, x_fixed(b'PAZ2'), dummy=True), E(6, 7, 'i2'), E(9, 9, 'a1'), E(11,... |
def split(k, port, should_fail=False):
cmd = ('devlink port split %s count %s' % (port.bus_info, k))
(stdout, stderr) = run_command(cmd, should_fail=should_fail)
if should_fail:
if (not test((stderr != ''), ('%s is unsplittable' % port.name))):
print(('split an unsplittable port %s' % po... |
('satpy.readers.electrol_hrit.HRITGOMSFileHandler.__init__', return_value=None)
('satpy.readers.electrol_hrit.HRITFileHandler.get_dataset', return_value={})
class TestHRITGOMSFileHandler(unittest.TestCase):
('satpy.readers.electrol_hrit.HRITGOMSFileHandler.calibrate')
def test_get_dataset(self, calibrate_mock, ... |
def test_gitlab_webhook_payload_known_issue():
expected = {'commit': '770830e7cae6db4f7fc0f4dbe20bd5f', 'ref': 'refs/tags/fourthtag', 'git_url': ':someuser/some-test-project.git', 'commit_info': {'url': ' 'date': '2019-10-17T18:07:48Z', 'message': 'Update Dockerfile'}}
def lookup_commit(repo_id, commit_sha):
... |
def test_unexpected_kwarg_node():
model = Model()
with pytest.raises(TypeError):
node = Node(model, 'test_node', invalid=True)
with pytest.raises(TypeError):
inpt = Input(model, 'test_input', invalid=True)
with pytest.raises(TypeError):
storage = Storage(model, 'test_storage', in... |
def sample_min_with_randFeatures(num_features, d, nObservations, value_of_nObservations, alpha, l, noise, initial_point, optimize_method='L-BFGS-B', maximize=False, bnds=None):
l = np.array(([l] * num_features))
W = np.divide(npr.randn(num_features, d), l)
b = ((2 * np.pi) * npr.uniform(0, 1, num_features))... |
class Migration(migrations.Migration):
dependencies = [('sponsors', '0073_auto__1906')]
operations = [migrations.AddField(model_name='providedtextasset', name='shared_text', field=models.TextField(blank=True, null=True)), migrations.AddField(model_name='providedtextassetconfiguration', name='shared_text', field... |
def prune_non_overlapping_boxes(boxlist1, boxlist2, min_overlap=0.0, scope=None):
with tf.name_scope(scope, 'PruneNonOverlappingBoxes'):
ioa_ = ioa(boxlist2, boxlist1)
ioa_ = tf.reduce_max(ioa_, reduction_indices=[0])
keep_bool = tf.greater_equal(ioa_, tf.constant(min_overlap))
keep_... |
class XLMRobertaConfig(PretrainedConfig):
model_type = 'xlm-roberta'
def __init__(self, vocab_size=30522, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_s... |
def recursive_find_python_class(folder, trainer_name, current_module):
tr = None
for (importer, modname, ispkg) in pkgutil.iter_modules(folder):
if (not ispkg):
m = importlib.import_module(((current_module + '.') + modname))
if hasattr(m, trainer_name):
tr = getat... |
def calculate_curtailment(n, label, curtailment):
avail = n.generators_t.p_max_pu.multiply(n.generators.p_nom_opt).sum().groupby(n.generators.carrier).sum()
used = n.generators_t.p.sum().groupby(n.generators.carrier).sum()
curtailment[label] = (((avail - used) / avail) * 100).round(3)
return curtailment |
_tf
class TFDeiTRobertaModelTest(TFVisionTextDualEncoderMixin, unittest.TestCase):
def get_pretrained_model_and_inputs(self):
model = TFVisionTextDualEncoderModel.from_vision_text_pretrained('Rocketknight1/tiny-random-deit-tf', 'hf-internal-testing/tiny-random-roberta')
batch_size = 13
pixel... |
class TransformerEncoderBase(nn.Module):
def __init__(self, cfg, embed_tokens):
self.cfg = cfg
super(TransformerEncoderBase, self).__init__()
self.register_buffer('version', torch.Tensor([3]))
self.dropout_module = nn.Dropout(cfg.dropout)
self.encoder_layerdrop = cfg.encoder_... |
def test_float32():
Format = QtGui.QImage.Format
dtype = np.float32
(w, h) = (192, 108)
(lo, hi) = ((- 1), 1)
lut_none = None
lut_mono1 = np.random.randint(256, size=256, dtype=np.uint8)
lut_mono2 = np.random.randint(256, size=(256, 1), dtype=np.uint8)
lut_rgb = np.random.randint(256, si... |
def _test_roialign_allclose(device, dtype):
if ((not torch.cuda.is_available()) and (device == 'cuda')):
pytest.skip('test requires GPU')
try:
from mmcv.ops import roi_align
except ModuleNotFoundError:
pytest.skip('test requires compilation')
pool_h = 2
pool_w = 2
spatial... |
def parse_string_date(obj_datetime):
try:
logging.info(('Obj_date time ' + str(obj_datetime)))
obj_datetime = re.sub('\\s\\s+', ' ', obj_datetime).strip()
logging.info(('Obj_date sub time ' + str(obj_datetime)))
date_line = re.match('[\\s\\S\\n]*\\w{3} \\w{3} \\d{1,} \\d{2}:\\d{2}:\\... |
def fit_model(model, train_data, test_data):
weights_dir = 'RNN_weights.h5'
try:
if os.path.exists(weights_dir):
model.load_weights(weights_dir)
print('Load weights')
train_generator = util.video_generator(train_data, BatchSize, SequenceLength, CNN_output, N_CLASSES)
... |
def load_arguments(argument_class, json_file_path=None):
parser = HfArgumentParser(argument_class)
if (json_file_path is not None):
(args,) = parser.parse_json_file(json_file=json_file_path)
elif ((len(sys.argv) == 2) and sys.argv[1].endswith('.json')):
(args,) = parser.parse_json_file(json_... |
class TestTravelTimeMatrixComputer():
def test_travel_time_matrix_initialization(self, transport_network, population_grid_points, origin_point, departure_datetime):
travel_time_matrix_computer = r5py.TravelTimeMatrixComputer(transport_network, origins=origin_point, destinations=population_grid_points, depar... |
class GroupSong(AudioFile):
def __init__(self, can_multiple: bool=True, can_change: bool=True, cant_change: (list[str] | None)=None):
self._can_multiple = can_multiple
self._can_change = can_change
self._cant_change = (cant_change or [])
def can_multiple_values(self, key=None):
i... |
def _topk_py_impl(op, x, k, axis, idx_dtype):
ndim = x.ndim
assert ((- ndim) <= axis < ndim)
axis %= ndim
if (k == 0):
raise ValueError('topk: kth cannot be zero')
elif (k > x.shape[axis]):
raise ValueError(f'topk: kth cannot be larger than the size of specified axis {int(axis)}')
... |
def get_segment_dataset(config, use_gt_inssem=False):
if (config.dataset_class == 'panopli'):
if use_gt_inssem:
(instance_dir, semantics_dir, instance_to_semantic_key) = ('rs_instance', 'rs_semantics', 'rs_instance_to_semantic')
else:
(instance_dir, semantics_dir, instance_to... |
class TestDecodeHexRecords(TestIntelHexBase):
def setUp(self):
self.ih = IntelHex()
self.decode_record = self.ih._decode_record
def tearDown(self):
del self.ih
def test_empty_line(self):
self.decode_record('')
def test_non_empty_line(self):
self.assertRaisesMsg(He... |
class Poll():
_EVENT_TO_MASK = {'r': select.POLLIN, 'w': select.POLLOUT}
def _has_event(events, event):
return ((events & event) != 0)
def for_events(cls, *events):
notifier = eintr_retry_call(select.poll)
for (fd, event) in events:
mask = cls._EVENT_TO_MASK.get(event)
... |
class FrameCounter(QtCore.QObject):
sigFpsUpdate = QtCore.Signal(object)
def __init__(self, interval=1000):
super().__init__()
self.count = 0
self.last_update = 0
self.interval = interval
def update(self):
self.count += 1
if (self.last_update == 0):
... |
class AssignResult(util_mixins.NiceRepr):
def __init__(self, num_gts, gt_inds, max_overlaps, labels=None):
self.num_gts = num_gts
self.gt_inds = gt_inds
self.max_overlaps = max_overlaps
self.labels = labels
self._extra_properties = {}
def num_preds(self):
return l... |
def Branin_Hoo(X):
x1 = X[0]
x2 = X[1]
x1bar = ((15 * x1) - 5)
x2bar = (15 * x2)
term1 = (((x2bar - ((5.1 * (x1bar ** 2)) / (4 * (np.pi ** 2)))) + ((5 * x1bar) / np.pi)) - 6)
term2 = ((10 - (10 / (8 * np.pi))) * np.cos(x1bar))
ret = (((((term1 ** 2) + term2) - 44.81) / 51.95) + ((10 ** (- 3)... |
class BubbleManager():
def __init__(self, sprite):
self.sprite = sprite
self.flipped = False
self.bubble = None
def say(self, text: str, border=Bubble.SAY):
if isinstance(text, (int, float)):
text = str((round(text, 2) if ((text % 1) > 0) else int(text)))
if s... |
class Migration(migrations.Migration):
dependencies = [migrations.swappable_dependency(settings.AUTH_USER_MODEL)]
operations = [migrations.CreateModel(name='Profile', fields=[('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created_at', models.DateTimeField(au... |
def inference_tip(infer_function: InferFn[_NodesT], raise_on_overwrite: bool=False) -> TransformFn[_NodesT]:
def transform(node: _NodesT, infer_function: InferFn[_NodesT]=infer_function) -> _NodesT:
if (raise_on_overwrite and (node._explicit_inference is not None) and (node._explicit_inference is not infer_... |
class TestBaseHandler(RapidTest):
def setUp(self):
self.connection = self.create_connection()
def test_dispatch(self):
msg = IncomingMessage(self.connection, 'hello')
retVal = BaseHandler.dispatch(self.router, msg)
self.assertFalse(retVal)
self.assertEqual(len(msg.respons... |
class MADDPGCritic(nn.Module):
def __init__(self, scheme, args):
super(MADDPGCritic, self).__init__()
self.args = args
self.n_actions = args.n_actions
self.n_agents = args.n_agents
self.input_shape = (self._get_input_shape(scheme) + (self.n_actions * self.n_agents))
i... |
def test_update_all_packages(monkeypatch):
public_pkg_1 = PkgFile('Flask', '1.0')
public_pkg_2 = PkgFile('requests', '1.0')
private_pkg_1 = PkgFile('my_private_pkg', '1.0')
private_pkg_2 = PkgFile('my_other_private_pkg', '1.0')
roots_mock = {Path('/opt/pypi'): [public_pkg_1, private_pkg_1], Path('/d... |
class Effect1046(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Remote Armor Repair Systems')), 'maxRange', src.getModifiedItemAttr('shipBonusGC'), skill='Gallente Cruiser', **kwargs) |
.unit()
def test_insert_missing_modules(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
monkeypatch.chdir(tmp_path)
modules = {'xxx.project.foo': ModuleType('xxx.project.foo')}
_insert_missing_modules(modules, 'xxx.project.foo')
assert (sorted(modules) == ['xxx', 'xxx.project', 'xxx.project.fo... |
class WaypointService(object):
def __init__(self, data_path=None, parent=None):
logging.debug('>>')
self.parent = parent
self.pytrainer_main = parent
self.data_path = data_path
logging.debug('<<')
def removeWaypoint(self, id_waypoint):
logging.debug('>>')
... |
class FortBlackCommand(models.Model):
black_commands = models.TextField(verbose_name='', default='/bin/rm, /sbin/reboot, /sbin/halt, /sbin/shutdown, /usr/bin/passwd, /bin/su, /sbin/init, /bin/chmod, /bin/chown, /usr/sbin/visudo')
class Meta():
db_table = 'ops_fort_black_command'
verbose_name = '... |
class TypeObject():
typ: Union[(type, super, str)]
base_classes: Set[Union[(type, str)]] = field(default_factory=set)
is_protocol: bool = False
protocol_members: Set[str] = field(default_factory=set)
is_thrift_enum: bool = field(init=False)
is_universally_assignable: bool = field(init=False)
... |
class nnUNetTrainer_50epochs(nnUNetTrainer):
def __init__(self, plans: dict, configuration: str, fold: int, dataset_json: dict, unpack_dataset: bool=True, device: torch.device=torch.device('cuda')):
super().__init__(plans, configuration, fold, dataset_json, unpack_dataset, device)
self.num_epochs = ... |
def is_valid_unlock(unlock: ReceiveUnlock, channel_state: NettingChannelState, sender_state: NettingChannelEndState) -> PendingLocksStateOrError:
received_balance_proof = unlock.balance_proof
current_balance_proof = get_current_balanceproof(sender_state)
lock = get_lock(sender_state, unlock.secrethash)
... |
_tf
class TFMT5ModelTest(unittest.TestCase):
def test_resize_embeddings(self):
model = TFMT5ForConditionalGeneration.from_pretrained('google/mt5-small')
original_vocab_size = model.get_input_embeddings().weight.shape[0]
self.assertEqual(original_vocab_size, model.config.vocab_size)
t... |
def temp_filename(*args, as_path=False, **kwargs):
from tests import mkstemp
try:
del kwargs['as_path']
except KeyError:
pass
(fd, filename) = mkstemp(*args, **kwargs)
os.close(fd)
normalized = normalize_path(filename)
(yield (Path(normalized) if as_path else normalized))
... |
.skipif((not PY311_PLUS), reason='Requires Python 3.11 or higher')
def test_star_exceptions() -> None:
code = textwrap.dedent('\n try:\n raise ExceptionGroup("group", [ValueError(654)])\n except* ValueError:\n print("Handling ValueError")\n except* TypeError:\n print("Handling TypeErro... |
class CosFace(torch.nn.Module):
def __init__(self, s=64.0, m=0.4):
super(CosFace, self).__init__()
self.s = s
self.m = m
def forward(self, logits: torch.Tensor, labels: torch.Tensor):
index = torch.where((labels != (- 1)))[0]
target_logit = logits[(index, labels[index].vi... |
class Question(Model, TranslationMixin):
prefetch_lookups = ('conditions', 'optionsets')
uri = models.URLField(max_length=800, blank=True, default='', verbose_name=_('URI'), help_text=_('The Uniform Resource Identifier of this question (auto-generated).'))
uri_prefix = models.URLField(max_length=256, verbos... |
class Inhibitor():
def __init__(self, source: InhibitorSource):
self.source = source
self.inhibited = False
def inhibit(self):
if (not self.inhibited):
self.source.inhibit()
self.inhibited = True
def uninhibit(self):
if self.inhibited:
self... |
class Behavior():
def __init__(self, quarkResultInstance: 'QuarkResult', methodCaller: Method, firstAPI: Method, secondAPI: Method) -> None:
self.quarkResult = quarkResultInstance
self.methodCaller = methodCaller
self.firstAPI = firstAPI
self.secondAPI = secondAPI
self.method... |
def AddOraclePath(train_info, valid_info, test_info, info_dict):
orc_meta_dict = defaultdict(list)
for i in train_info:
(spk, wav_path, txt) = (i['speaker'], i['wav_path'], i['text'])
orc_meta_dict[spk].append([txt, wav_path])
for i in valid_info:
(spk, wav_path, txt) = (i['speaker']... |
def install_hatch_project(context: Context, path: Path) -> None:
py_proj_toml = toml.load((path / 'pyproject.toml'))
hatch_default_env = py_proj_toml['tool']['hatch']['envs'].get('default', {})
hatch_default_features = hatch_default_env.get('features', [])
hatch_default_deps = hatch_default_env.get('dep... |
def test_spatialdropout1d_legacy_interface():
old_layer = keras.layers.SpatialDropout1D(p=0.6, name='sd1d')
new_layer_1 = keras.layers.SpatialDropout1D(rate=0.6, name='sd1d')
new_layer_2 = keras.layers.SpatialDropout1D(0.6, name='sd1d')
assert (json.dumps(old_layer.get_config()) == json.dumps(new_layer_... |
class CompatibilityFilesTests(unittest.TestCase):
def package(self):
bytes_data = io.BytesIO(b'Hello, world!')
return util.create_package(file=bytes_data, path='some_path', contents=('a', 'b', 'c'))
def files(self):
return resources.files(self.package)
def test_spec_path_iter(self):
... |
def evaluate(dataloader, model, criterion, postprocessors, confusion, config, args, thresh):
model.eval()
criterion.eval()
logging.error('VALIDATION')
for (i, batch) in enumerate(tqdm(dataloader)):
(seq_images, targets, _) = batch
if (seq_images == None):
continue
seq... |
class IntegrationMultiModule(xt.EditableModule):
def __init__(self, a, b):
self.a = a
self.b = b
def forward(self, x, c):
return (torch.cos(((self.a * x) + (self.b * c))), torch.sin(((self.a * x) + (self.b * c))))
def getparamnames(self, methodname, prefix=''):
return [(prefi... |
class Plugin():
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.reset_counters()
def reset_counters(self):
self.called_preparse = 0
self.called_postparsing = 0
self.called_precmd = 0
self.called_postcmd = 0
self.called_cmdfinali... |
def gather_experiment_predss(experiment) -> List[np.ndarray]:
chkpts_dir = (Path(experiment) / 'chkpts')
chkpt_iter_dirs = sorted(chkpts_dir.iterdir(), key=(lambda p: int(p.stem.split('_')[(- 1)])))[1:]
try:
preds_npzs = [np.load((chkpt_iter_dir / 'preds.npz')) for chkpt_iter_dir in chkpt_iter_dirs]... |
def make_canonical_identifier(chain_identifier=EMPTY, token_network_address=EMPTY, channel_identifier=EMPTY) -> CanonicalIdentifier:
return create(CanonicalIdentifierProperties(chain_identifier=chain_identifier, token_network_address=token_network_address, channel_identifier=(channel_identifier or make_channel_iden... |
(everythings(min_int=(- ), max_int=, allow_inf=False))
def test_ujson_converter_unstruct_collection_overrides(everything: Everything):
converter = ujson_make_converter(unstruct_collection_overrides={AbstractSet: sorted})
raw = converter.unstructure(everything)
assert (raw['a_set'] == sorted(raw['a_set']))
... |
def test_single(hatch, helpers, temp_dir_data, config_file):
config_file.model.template.plugins['default']['tests'] = False
config_file.save()
project_name = 'My.App'
with temp_dir_data.as_cwd():
result = hatch('new', project_name)
assert (result.exit_code == 0), result.output
project_pa... |
def load_json_info(gt_file, img_info):
annotation = mmcv.load(gt_file)
anno_info = []
for line in annotation['lines']:
segmentation = line['points']
x = max(0, min(segmentation[0::2]))
y = max(0, min(segmentation[1::2]))
w = abs((max(segmentation[0::2]) - x))
h = abs(... |
def setup_resolver(configuration: BaseConfiguration, patches: GamePatches) -> tuple[(State, Logic)]:
game = filtered_database.game_description_for_layout(configuration).get_mutable()
bootstrap = game.game.generator.bootstrap
game.resource_database = bootstrap.patch_resource_database(game.resource_database, ... |
def test_ScanArgs_remove_nonseq_outer_input():
hmm_model_env = create_test_hmm()
scan_args = hmm_model_env['scan_args']
hmm_model_env['scan_op']
Y_t = hmm_model_env['Y_t']
Y_rv = hmm_model_env['Y_rv']
mus_in = hmm_model_env['mus_in']
mus_t = hmm_model_env['mus_t']
sigmas_in = hmm_model_e... |
def evaluate(model, data, epoch, args, tb_writer=None):
metrics = {}
if (not is_master(args)):
return metrics
device = torch.device(args.device)
model.eval()
zero_shot_metrics = zero_shot_eval(model, data, epoch, args)
metrics.update(zero_shot_metrics)
autocast = get_autocast(args.pr... |
class JPEG2000(BinaryCodec):
fmt = '.jp2'
def name(self):
return 'JPEG2000'
def description(self):
return f'JPEG2000. ffmpeg version {_get_ffmpeg_version()}'
def _get_encode_cmd(self, in_filepath, quality, out_filepath):
cmd = ['ffmpeg', '-loglevel', 'panic', '-y', '-i', in_filep... |
class ErrorHandlingTestCases(unittest.TestCase):
def test_catch_catches(self):
(exception=BlockingIOError)
def f():
raise BlockingIOError
f()
self.assertTrue(True)
def test_catch_doesnt_catch_unspecified(self):
(exception=BlockingIOError)
def f():
... |
def build_context_and_subject(auth_context=None, tuf_roots=None):
context = (auth_context.to_signed_dict() if auth_context else {})
single_root = (list(tuf_roots.values())[0] if ((tuf_roots is not None) and (len(tuf_roots) == 1)) else DISABLED_TUF_ROOT)
context.update({CLAIM_TUF_ROOTS: tuf_roots, CLAIM_TUF_... |
class TestTrainingExtensionsQcQuantizeRecurrentParamOp():
def test_qc_quantize_recurrent_param_op(self):
graph = tf.Graph()
config = tf.compat.v1.ConfigProto(log_device_placement=False)
sess = tf.compat.v1.Session(graph=graph, config=config)
bitwidth = 8
use_symm_encoding = T... |
def test_repr_pyobjectsdef_pyclass_without_associated_resource(project):
code = 'class MyClass: pass'
mod = libutils.get_string_module(project, code)
obj = mod.get_attribute('MyClass').pyobject
assert isinstance(obj, pyobjectsdef.PyClass)
assert repr(obj).startswith('<rope.base.pyobjectsdef.PyClass ... |
def download_and_unzip(url, root, dataset):
folder = os.path.join(root, dataset)
folder_zips = os.path.join(folder, 'zips')
if (not os.path.exists(folder_zips)):
os.makedirs(folder_zips)
filename_zip = os.path.join(folder_zips, url.split('/')[(- 1)])
download_from_url(url, filename_zip)
... |
def test_run_script_with_binary_file(base_app, request):
test_dir = os.path.dirname(request.module.__file__)
filename = os.path.join(test_dir, 'scripts', 'binary.bin')
(out, err) = run_cmd(base_app, 'run_script {}'.format(filename))
assert ('is not an ASCII or UTF-8 encoded text file' in err[0])
ass... |
def delete_bytes(fobj, size: int, offset: int, BUFFER_SIZE: int=_DEFAULT_BUFFER_SIZE) -> None:
if ((size < 0) or (offset < 0)):
raise ValueError
fobj.seek(0, 2)
filesize = fobj.tell()
movesize = ((filesize - offset) - size)
if (movesize < 0):
raise ValueError
move_bytes(fobj, off... |
def test_ignore_form_by_class(app, client):
selectors_to_ignore = ['form.form-get-class']
crawler = Crawler(client=client, initial_paths=['/'], rules=(PERMISSIVE_HYPERLINKS_ONLY_RULE_SET + SUBMIT_GET_FORMS_RULE_SET), ignore_css_selectors=selectors_to_ignore)
crawler.crawl()
submitted_forms = [form for f... |
def repo_result_view(repo, username, last_modified=None, stars=None, popularity=None):
kind = ('application' if (Repository.kind.get_name(repo.kind_id) == 'application') else 'repository')
view = {'kind': kind, 'title': ('app' if (kind == 'application') else 'repo'), 'namespace': search_entity_view(username, re... |
def convert_data(apps, schema_editor):
Keynote = apps.get_model('conferences', 'Keynote')
for keynote in Keynote.objects.all():
keynote.description = json.dumps({'en': keynote.description})
keynote.title = json.dumps({'en': keynote.title})
for speaker in keynote.speakers.all():
... |
class AltCLIPProcessor(ProcessorMixin):
attributes = ['image_processor', 'tokenizer']
image_processor_class = 'CLIPImageProcessor'
tokenizer_class = ('XLMRobertaTokenizer', 'XLMRobertaTokenizerFast')
def __init__(self, image_processor=None, tokenizer=None, **kwargs):
if ('feature_extractor' in k... |
class WindowOptions():
arch: ArchOptions = ArchOptions()
array: ArrayOptions = ArrayOptions()
size_offset: SizeOffsetOptions = SizeOffsetOptions()
bar_fill: FillBarOptions = FillBarOptions()
louver_fill: FillLouverOptions = FillLouverOptions()
glass_fill: FillGlassPaneOptions = FillGlassPaneOpti... |
class MobileViTAttention(nn.Module):
def __init__(self, in_channel=3, dim=512, kernel_size=3, patch_size=7, depth=3, mlp_dim=1024):
super().__init__()
(self.ph, self.pw) = (patch_size, patch_size)
self.conv1 = nn.Conv2d(in_channel, in_channel, kernel_size=kernel_size, padding=(kernel_size //... |
class SparseTransformerSentenceEncoderLayer(TransformerSentenceEncoderLayer):
def __init__(self, embedding_dim: int=768, ffn_embedding_dim: int=3072, num_attention_heads: int=8, dropout: float=0.1, attention_dropout: float=0.1, activation_dropout: float=0.1, activation_fn: str='relu', export: bool=False, is_bidirec... |
class numeric_grad():
type_eps = {'float64': 1e-07, 'float32': 0.0003, 'float16': 0.1, np.dtype('float64'): 1e-07, np.dtype('float32'): 0.0003, np.dtype('float16'): 0.1}
def __init__(self, f, pt, eps=None, out_type=None):
def prod(inputs):
rval = 1
for i in inputs:
... |
def load_results(n_demo):
expert_results = glob.glob(f'{data_dir}/expert/expert_{args.env}_seed=*.perf')
(expert_reward, _, _, _) = get_results(expert_results)
bc_mse_results = glob.glob(f'{data_dir}/bc/bc_{args.env}_policy_ntrajs={n_demo}_seed=*.perf')
(bc_mse_reward, _, _, _) = get_results(bc_mse_resu... |
class BanSelector(discord.ui.Select):
view: QuotientView
def __init__(self, ctx: Context, teams: T.List[BannedTeam]):
_options = []
for _ in teams:
_options.append(discord.SelectOption(label=f"{getattr(ctx.bot.get_user(_.user_id), 'name', 'unknown-user')} [{_.user_id}]", description=... |
_on_failure
.parametrize('number_of_nodes', [1])
.parametrize('channels_per_node', [0])
.parametrize('enable_rest_api', [True])
def test_payload_with_address_not_eip55(api_server_test_instance: APIServer):
invalid_address = '0xf696209d2ca35e6c88e5b99b7cda3abf316bed69'
channel_data_obj = {'partner_address': inva... |
def bootstrap(field):
if (hasattr(field, 'field') and hasattr(field.field, 'widget') and field.field.widget):
widget = field.field.widget.__class__.__name__.lower()
if (widget in ['passwordinput', 'textinput', 'textarea', 'select', 'numberinput', 'emailinput']):
return add_class(field, '... |
def testParameterAddActions():
pa = OSC.ParameterAddAction('Myparam', 3)
pa.setVersion(minor=1)
prettyprint(pa.get_element())
pa2 = OSC.ParameterAddAction('Myparam', 3)
pa3 = OSC.ParameterAddAction('Myparam', 2)
assert (pa == pa2)
assert (pa != pa3)
pa4 = OSC.ParameterAddAction.parse(pa.... |
class TestAttributes(EvenniaTest):
def test_attrhandler(self):
key = 'testattr'
value = 'test attr value '
self.obj1.attributes.add(key, value)
self.assertEqual(self.obj1.attributes.get(key), value)
self.obj1.db.testattr = value
self.assertEqual(self.obj1.db.testattr,... |
_dataframe_method
_function(message='This function will be deprecated in a 1.x release. Please use `pd.DataFrame.assign` instead.')
def add_columns(df: pd.DataFrame, fill_remaining: bool=False, **kwargs: Any) -> pd.DataFrame:
for (col_name, values) in kwargs.items():
df = df.add_column(col_name, values, fil... |
def get_estimation(idx, target_name, estimation_dict):
estimated = estimation_dict[target_name][idx]
if (len(estimated) == 0):
warn('TODO: zero estimation, caused by ddp')
return None
estimated = np.concatenate([estimated[key] for key in sorted(estimated.keys())], axis=0)
return estimate... |
class RemoveEvent():
def __init__(self, itype, iid, destination):
assert ((itype == 'pack') or (itype == 'file'))
assert ((destination == 'queue') or (destination == 'collector'))
self.type = itype
self.id = iid
self.destination = destination
def to_list(self):
re... |
class TestProcessParameterData(TestCase):
def test_process_1D_data(self):
name = 'lico2_ocv_example'
path = os.path.join(pybamm.root_dir(), 'tests', 'unit', 'test_parameters')
processed = pybamm.parameters.process_1D_data(name, path)
self.assertEqual(processed[0], name)
self.... |
_layer('exampleconv1')
class ExampleConv1(MessagePassing):
def __init__(self, in_channels, out_channels, bias=True, **kwargs):
super().__init__(aggr=cfg.gnn.agg, **kwargs)
self.in_channels = in_channels
self.out_channels = out_channels
self.weight = Parameter(torch.Tensor(in_channels... |
def _init_env_vars(use_gpu: bool):
if (('WORLD_SIZE' not in os.environ) or ('RANK' not in os.environ)):
os.environ['WORLD_SIZE'] = '1'
os.environ['RANK'] = '0'
os.environ['LOCAL_RANK'] = '0'
if (('MASTER_ADDR' not in os.environ) or ('MASTER_PORT' not in os.environ)):
os.environ['... |
def get_basic_announcements(announcements, include_local: bool=True):
return [announcement for announcement in announcements if (((announcement.get('type', '').lower() != 'primary_announcement') and (not announcement.get('local', False))) or (announcement.get('local', False) and include_local))] |
def handle_action_transfer_reroute(chain_state: ChainState, state_change: ActionTransferReroute) -> TransitionResult[ChainState]:
new_secrethash = state_change.secrethash
current_payment_task = chain_state.payment_mapping.secrethashes_to_task[state_change.transfer.lock.secrethash]
chain_state.payment_mappin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.