code stringlengths 281 23.7M |
|---|
class TestHandler():
def test_slot_behaviour(self):
class SubclassHandler(BaseHandler):
__slots__ = ()
def __init__(self):
super().__init__((lambda x: None))
def check_update(self, update: object):
pass
inst = SubclassHandler()
... |
def test_get_imgformat_png_when_setting_png(qapp, settings, item):
settings.setValue('Items/image_storage_format', 'png')
img = MagicMock(hasAlphaChannel=MagicMock(return_value=False), height=MagicMock(return_value=1600), width=MagicMock(return_value=1020))
assert (item.get_imgformat(img) == 'png') |
class EventLocation(models.Model):
calendar = models.ForeignKey(Calendar, related_name='locations', null=True, blank=True, on_delete=models.CASCADE)
name = models.CharField(max_length=255)
address = models.CharField(blank=True, null=True, max_length=255)
url = models.URLField('URL', blank=True, null=Tru... |
class Sup_MCL_Loss(nn.Module):
def __init__(self, args):
super(Sup_MCL_Loss, self).__init__()
self.embed_list = nn.ModuleList([])
self.args = args
for i in range(args.number_net):
self.embed_list.append(Embed(args.rep_dim[i], args.feat_dim))
self.contrast = SupMCL... |
.parametrize('improved_sampling', [True, False])
def test_super_H(improved_sampling):
size = 10
ntraj = 1000
a = qutip.destroy(size)
H = qutip.num(size)
state = qutip.basis(size, (size - 1))
times = np.linspace(0, 1.0, 100)
coupling = 0.5
n_th = 0.05
c_ops = (np.sqrt((coupling * (n_t... |
def _parse_path_args(path: str, llm_app_cls=LLMApp) -> List[LLMApp]:
assert os.path.exists(path), f'Could not load model from {path}, as it does not exist.'
if os.path.isfile(path):
with open(path, 'r') as f:
return [llm_app_cls.parse_yaml(f)]
elif os.path.isdir(path):
apps = []
... |
def spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax):
global mel_basis
dtype_device = ((str(spec.dtype) + '_') + str(spec.device))
fmax_dtype_device = ((str(fmax) + '_') + dtype_device)
if (fmax_dtype_device not in mel_basis):
mel = librosa_mel_fn(sampling_rate, n_fft, num_mel... |
.end_to_end()
def test_dry_run_w_subsequent_task(runner, tmp_path):
source = '\n import pytask\n\n .depends_on("out.txt")\n .produces("out_2.txt")\n def task_example(depends_on, produces):\n produces.touch()\n '
tmp_path.joinpath('task_example_second.py').write_text(textwrap.dedent(source)... |
def delete_sensor_from_config(sensor_mac):
global SENSORS
LOGGER.info(f'Deleting sensor from config: {sensor_mac}')
try:
del SENSORS[sensor_mac]
write_yaml_file(os.path.join(CONFIG_PATH, SENSORS_CONFIG_FILE), SENSORS)
except KeyError:
LOGGER.debug(f'{sensor_mac} not found in SENS... |
class TextItem():
def __init__(self, text, font_props=None, *, ws_before='', ws_after='', allow_break=True):
if (not isinstance(text, str)):
raise TypeError('TextItem text must be str.')
if (font_props is None):
font_props = textmodule.FontProps()
elif (not isinstance... |
def compute_rect_vertices(fromp, to, radius):
(x1, y1) = fromp
(x2, y2) = to
if (abs((y1 - y2)) < 1e-06):
dx = 0
dy = radius
else:
dx = ((radius * 1.0) / (((((x1 - x2) / (y1 - y2)) ** 2) + 1) ** 0.5))
dy = (((radius ** 2) - (dx ** 2)) ** 0.5)
dy *= ((- 1) if (((x1... |
def Print_info(fun):
def work(*args, **kwargs):
res = fun(*args, **kwargs)
if res:
if isinstance(res, str):
print(res)
elif isinstance(res, list):
for i in res:
print(i.replace('\n', ''))
else:
pa... |
def _remove_variable_info_from_output(data: str, path: Any) -> str:
lines = data.splitlines()
index_root = next((i for (i, line) in enumerate(lines) if line.startswith('Root:')))
new_info_line = ''.join(lines[1:index_root])
for platform in ('linux', 'win32', 'darwin'):
new_info_line = new_info_l... |
def test_naturaldelta() -> None:
seconds = ((((1234 * 365) * 24) * 60) * 60)
assert (humanize.naturaldelta(seconds) == '1,234 years')
try:
humanize.i18n.activate('fr_FR')
assert (humanize.naturaldelta(seconds) == '1 234 ans')
humanize.i18n.activate('es_ES')
assert (humanize.n... |
class TestRequestInterception(BaseTestCase):
async def test_request_interception(self):
(await self.page.setRequestInterception(True))
async def request_check(req):
self.assertIn('empty', req.url)
self.assertTrue(req.headers.get('user-agent'))
self.assertEqual(req... |
def _get_actual_assertions_names() -> list[str]:
from unittest import TestCase as DefaultTestCase
from django.test import TestCase as DjangoTestCase
obj = DjangoTestCase('run')
def is_assert(func) -> bool:
return (func.startswith('assert') and ('_' not in func))
base_methods = [name for (nam... |
def test_sparse_vs_pad():
node_feats = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9], [9, 10, 11], [11, 11.1, 12.4], [18, 11.1, 22.4], [24, 15.31, 18.4], [16, 10.1, 17.4]])
graph_ids = torch.tensor([0, 0, 0, 1, 1, 2, 2, 2])
edges = {'asingle': torch.tensor([[0, 1, 7, 6, 3, 4], [1, 2, 6, 5, 4, 3]]), 'bdouble... |
class PageRendererMixin():
def render_page(self, xml, page):
if (page['uri'] not in self.uris):
self.uris.add(page['uri'])
xml.startElement('page', {'dc:uri': page['uri']})
self.render_text_element(xml, 'uri_prefix', {}, page['uri_prefix'])
self.render_text_el... |
class TestBitrate(unittest.TestCase):
def test_wav(self):
actual = file_info.bitrate(INPUT_FILE)
expected = 706000.0
self.assertEqual(expected, actual)
def test_wav_pathlib(self):
actual = file_info.bitrate(Path(INPUT_FILE))
expected = 706000.0
self.assertEqual(ex... |
class _BaseHeaderFooter(BlockItemContainer):
def __init__(self, sectPr: CT_SectPr, document_part: DocumentPart, header_footer_index: WD_HEADER_FOOTER):
self._sectPr = sectPr
self._document_part = document_part
self._hdrftr_index = header_footer_index
def is_linked_to_previous(self) -> bo... |
class ResBottleneckBlock(nn.Module):
def __init__(self, w_in, w_out, stride, bn_norm, bm=1.0, gw=1, se_r=None):
super(ResBottleneckBlock, self).__init__()
self.construct(w_in, w_out, stride, bn_norm, bm, gw, se_r)
def _add_skip_proj(self, w_in, w_out, stride, bn_norm):
self.proj = nn.Con... |
class macros():
img_root = '${img_root}'
base_img_root = '${base_img_root}'
app_id = '${app_id}'
replica_id = '${replica_id}'
rank0_env = '${rank0_env}'
class Values():
img_root: str
app_id: str
replica_id: str
rank0_env: str
base_img_root: str = 'DEPRECAT... |
def test_sieve_band(tmpdir, runner):
outfile = str(tmpdir.join('out.tif'))
result = runner.invoke(main_group, (['calc'] + ['(sieve (band 1 1) 42)', 'tests/data/shade.tif', outfile]), catch_exceptions=False)
assert (result.exit_code == 0)
with rasterio.open(outfile) as src:
assert (src.count == 1... |
class TestLiterals(unittest.TestCase):
def test_format_str_literal(self) -> None:
assert (format_str_literal('') == b'\x00')
assert (format_str_literal('xyz') == b'\x03xyz')
assert (format_str_literal(('x' * 127)) == (b'\x7f' + (b'x' * 127)))
assert (format_str_literal(('x' * 128)) =... |
def select_2(train_embs, one_test_emb, downstream_train_examples, one_test_example, tag, given_context, phase2_selection):
cos = nn.CosineSimilarity(dim=1, eps=1e-06)
if (not os.path.isdir(f'{args.output_dir}/{tag}/prompts')):
os.makedirs(f'{args.output_dir}/{tag}/prompts', exist_ok=True)
prompt_str... |
class decoder(nn.Module):
def __init__(self, dim, nc=1):
super(decoder, self).__init__()
self.dim = dim
nf = 64
self.upc1 = nn.Sequential(nn.ConvTranspose2d(dim, (nf * 8), 4, 1, 0), nn.BatchNorm2d((nf * 8)), nn.LeakyReLU(0.2, inplace=True))
self.upc2 = dcgan_upconv(((nf * 8) ... |
def test_connection_create_table():
conn = Connection(REGION)
kwargs = {'read_capacity_units': 1, 'write_capacity_units': 1}
with pytest.raises(ValueError):
conn.create_table(TEST_TABLE_NAME, **kwargs)
kwargs['attribute_definitions'] = [{'attribute_name': 'key1', 'attribute_type': 'S'}, {'attrib... |
def gen_basic_test():
return '\n\n csrr x1, mngr2proc, < 5\n nop\n nop\n nop\n nop\n nop\n nop\n nop\n nop\n addi x3, x1, 0x0004\n nop\n nop\n nop\n nop\n nop\n nop\n nop\n nop\n csrw proc2mngr, x3 > 9\n nop\n nop\n nop\n nop\n nop\n nop\n ... |
class W_ImpPropertyAccessor(W_ImpPropertyFunction):
errorname = 'impersonator-property-accessor'
_call_method([values.W_Object, default(values.W_Object)])
def call(self, obj, fail):
v = lookup_property(obj, self.descriptor)
if v:
return v
if v:
return v
... |
.parametrize('access', [_access(actions=['pull', 'push']), _access(actions=['pull', '*']), _access(actions=['*', 'push']), _access(actions=['*']), _access(actions=['pull', '*', 'push'])])
def test_token_with_access(access, initialized_db):
token = _token(_token_data(access=access))
identity = _parse_token(token... |
class SearchEngineUrl(BaseType):
def to_py(self, value: _StrUnset) -> _StrUnsetNone:
self._basic_py_validation(value, str)
if isinstance(value, usertypes.Unset):
return value
elif (not value):
return None
if (not re.search('{(|0|semiquoted|unquoted|quoted)}', ... |
def test_widgetbox_start_opened(manager_nospawn, minimal_conf_noscreen):
config = minimal_conf_noscreen
tbox = TextBox(text='Text Box')
widget_box = WidgetBox(widgets=[tbox], start_opened=True)
config.screens = [libqtile.config.Screen(top=libqtile.bar.Bar([widget_box], 10))]
manager_nospawn.start(co... |
def main():
args = parser.parse_args()
sample = dict()
net_input = dict()
feature = get_feature(args.wav_path)
target_dict = Dictionary.load(args.target_dict_path)
model = load_model(args.w2v_path, target_dict)
model[0].eval()
generator = W2lViterbiDecoder(target_dict)
net_input['sou... |
class KnowValues(unittest.TestCase):
def xtest_gamma(self):
cell = make_primitive_cell(([17] * 3))
mf = pbcdft.RKS(cell)
mf.xc = 'lda,vwn'
e1 = mf.scf()
self.assertAlmostEqual(e1, (- 10.), 8)
def xtest_kpt_222(self):
cell = make_primitive_cell(([17] * 3))
... |
(frozen=True)
class AnnotatedTypesCheck(CustomCheck):
def can_assign(self, value: Value, ctx: CanAssignContext) -> CanAssign:
for subval in flatten_values(value):
original_subval = subval
if isinstance(subval, AnnotatedValue):
if any((((ext == self) or self.is_compati... |
class PathPlanner():
def __init__(self, app, planner_flag='rrt_dubins', show_planner=True):
self.waypoints = MsgWaypoints()
if (planner_flag == 'rrt_straight'):
self.rrt_straight_line = RRTStraightLine(app=app, show_planner=show_planner)
if (planner_flag == 'rrt_dubins'):
... |
class Volume(WorldObject):
def _wgpu_get_pick_info(self, pick_value):
tex = self.geometry.grid
if hasattr(tex, 'texture'):
tex = tex.texture
values = unpack_bitfield(pick_value, wobject_id=20, x=14, y=14, z=14)
texcoords_encoded = (values['x'], values['y'], values['z'])
... |
class TorchFM(nn.Module):
def __init__(self, config):
super().__init__()
self.gpu = config.use_gpu
self.n = config.FM_n
self.k = config.FM_k
self.V = nn.Parameter(torch.randn(self.n, self.k), requires_grad=True)
self.lin = nn.Linear(self.n, 1)
if self.gpu:
... |
def test_KanrenRelationSub_multiout():
class MyMultiOutOp(Op):
def make_node(self, *inputs):
outputs = [MyType()(), MyType()()]
return Apply(self, list(inputs), outputs)
def perform(self, node, inputs, outputs):
outputs[0] = np.array(inputs[0])
outputs... |
class MarkedIntensityHomogenuosPoisson(Intensity):
def __init__(self, dim=1):
self.dim = dim
self.lam = ([None] * dim)
def initialize(self, lam, dim=1):
self.lam[dim] = lam
def getValue(self, t, inds):
l = len(inds)
inten = ([0] * l)
for i in range(l):
... |
class TestCompositorNodeCopy(unittest.TestCase):
def setUp(self):
self.node = CompositorNode(MagicMock())
self.node.add_required_nodes([MagicMock(), MagicMock()])
self.node.add_optional_nodes([MagicMock()])
self.node_copy = self.node.copy()
def test_node_data_is_copied(self):
... |
class F31Handler(BaseHandler):
version = F31
commandMap = {'auth': commands.authconfig.F28_Authconfig, 'authconfig': commands.authconfig.F28_Authconfig, 'authselect': commands.authselect.F28_Authselect, 'autopart': commands.autopart.F29_AutoPart, 'autostep': commands.autostep.FC3_AutoStep, 'bootloader': command... |
class TestEPICL1bReader():
def _setup_h5(self, setup_hdf5_file):
from satpy.readers import load_reader
test_reader = load_reader(self.reader_configs)
loadables = test_reader.select_files_from_pathnames([setup_hdf5_file])
test_reader.create_filehandlers(loadables)
return test_... |
class ShellInfo_startupScript(QtWidgets.QVBoxLayout):
DISABLE_SYSTEM_DEFAULT = (sys.platform == 'darwin')
SYSTEM_VALUE = '$PYTHONSTARTUP'
RUN_AFTER_GUI_TEXT = '# AFTER_GUI - code below runs after integrating the GUI\n'
def __init__(self, parent):
QtWidgets.QVBoxLayout.__init__(self)
self... |
class _Commenter():
def __init__(self, code):
self.code = code
self.lines = self.code.split('\n')
self.lines.append('\n')
self.origs = list(range((len(self.lines) + 1)))
self.diffs = ([0] * (len(self.lines) + 1))
def comment(self, lineno):
start = (_logical_start(... |
class Solution(object):
def productExceptSelf(self, nums):
ans = ([1] * len(nums))
for i in range(1, len(nums)):
ans[i] = (ans[(i - 1)] * nums[(i - 1)])
right = 1
for i in range((len(nums) - 1), (- 1), (- 1)):
ans[i] *= right
right *= nums[i]
... |
class Effect5958(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Medium Hybrid Turret')), 'trackingSpeed', ship.getModifiedItemAttr('shipBonusGC'), skill='Gallente Cruiser', **kwargs) |
def test_extras_conflicts_all_extras(tester: CommandTester, mocker: MockerFixture) -> None:
assert isinstance(tester.command, InstallerCommand)
mocker.patch.object(tester.command.installer, 'run', return_value=0)
tester.execute('--extras foo --all-extras')
assert (tester.status_code == 1)
assert (te... |
class ScenarioWrapperParameter(Parameter):
def __init__(self, model, scenario, parameters, **kwargs):
super().__init__(model, **kwargs)
if (scenario.size != len(parameters)):
raise ValueError('The number of parameters must equal the size of the scenario.')
self.scenario = scenari... |
class Declaration(object):
def __init__(self):
self.declarator = None
self.type = Type()
self.storage = None
def __repr__(self):
d = {'declarator': self.declarator, 'type': self.type}
if self.storage:
d['storage'] = self.storage
l = [('%s=%r' % (k, v))... |
class ScopeSorter():
def __init__(self, settings: Settings, items: List[Item], rel_marks: List[RelativeMark[Item]], dep_marks: List[RelativeMark[Item]], session_scope: bool=False) -> None:
self.settings = settings
self.items = items
if session_scope:
self.rel_marks = rel_marks
... |
class TestBoolOp(TestNameCheckVisitorBase):
_passes()
def test(self):
def capybara(x):
if x:
cond = str(x)
cond2 = True
else:
cond = None
cond2 = None
assert_is_value(cond, MultiValuedValue([TypedValue(st... |
class Mark(object):
def __init__(self, name, index, line, column, buffer, pointer):
self.name = name
self.index = index
self.line = line
self.column = column
self.buffer = buffer
self.pointer = pointer
def get_snippet(self, indent=4, max_length=75):
if (se... |
class Migration(migrations.Migration):
dependencies = [('api', '0076_merge__1941')]
operations = [migrations.AlterField(model_name='botsetting', name='data', field=models.JSONField(help_text='The actual settings of this setting.')), migrations.AlterField(model_name='deletedmessage', name='embeds', field=django.... |
_criterion('latency_augmented_label_smoothed_cross_entropy')
class LatencyAugmentedLabelSmoothedCrossEntropyCriterion(LabelSmoothedCrossEntropyCriterion):
def __init__(self, args, task):
super().__init__(args, task)
self.eps = args.label_smoothing
self.latency_weight_avg = args.latency_weigh... |
def update_mopidy_config(output: str) -> None:
if settings.DOCKER:
return
if (output == 'pulse'):
if (storage.get('feed_cava') and shutil.which('cava')):
output = 'cava'
else:
output = 'regular'
spotify_username = storage.get('spotify_username')
spotify_pa... |
def simulation_ordered_grouped_low_depth_terms_with_info(hamiltonian, input_ordering=None, external_potential_at_end=False):
n_qubits = count_qubits(hamiltonian)
hamiltonian = normal_ordered(hamiltonian)
ordered_terms = []
ordered_indices = []
ordered_is_hopping_operator = []
try:
input_... |
class AssetFinder(object):
(engine=coerce_string_to_eng(require_exists=True))
def __init__(self, engine, future_chain_predicates=CHAIN_PREDICATES):
self.engine = engine
metadata = sa.MetaData(bind=engine)
metadata.reflect(only=asset_db_table_names)
for table_name in asset_db_tabl... |
def _projects_params(q: Optional[str]=None, id: Optional[MultiInt]=None, not_id: Optional[MultiInt]=None, lat: Optional[float]=None, lng: Optional[float]=None, radius: int=500, featured: Optional[bool]=None, noteworthy: Optional[bool]=None, place_id: Optional[MultiInt]=None, site_id: Optional[int]=None, rule_details: O... |
def resnet_v2_152(inputs, num_classes=None, is_training=True, global_pool=True, output_stride=None, reuse=None, scope='resnet_v2_152'):
blocks = [resnet_utils.Block('block1', bottleneck, (([(256, 64, 1)] * 2) + [(256, 64, 2)])), resnet_utils.Block('block2', bottleneck, (([(512, 128, 1)] * 7) + [(512, 128, 2)])), re... |
def write_fst(lexicon, silprobs, sil_phone, sil_disambig, nonterminals=None, left_context_phones=None):
(silbeginprob, silendcorrection, nonsilendcorrection, siloverallprob) = silprobs
initial_sil_cost = (- math.log(silbeginprob))
initial_non_sil_cost = (- math.log((1.0 - silbeginprob)))
sil_end_correct... |
def is_custom_op_loaded():
flag = False
try:
from ..tensorrt import is_tensorrt_plugin_loaded
flag = is_tensorrt_plugin_loaded()
except (ImportError, ModuleNotFoundError):
pass
if (not flag):
try:
from ..ops import get_onnxruntime_op_path
ort_lib_p... |
class XceptionFinalBlock(nn.Module):
def __init__(self):
super(XceptionFinalBlock, self).__init__()
self.conv1 = dws_conv3x3_block(in_channels=1024, out_channels=1536, activate=False)
self.conv2 = dws_conv3x3_block(in_channels=1536, out_channels=2048, activate=True)
self.activ = nn.R... |
def mn_decode(wlist):
out = ''
for i in range((len(wlist) // 3)):
(word1, word2, word3) = wlist[(3 * i):((3 * i) + 3)]
w1 = wordlist.index(word1)
w2 = (wordlist.index(word2) % n)
w3 = (wordlist.index(word3) % n)
x = ((w1 + (n * ((w2 - w1) % n))) + ((n * n) * ((w3 - w2) % ... |
def test_complete_multiline_on_single_line(cmd2_app):
text = ''
line = 'test_multiline {}'.format(text)
endidx = len(line)
begidx = (endidx - len(text))
expected = sorted(sport_item_strs, key=cmd2_app.default_sort_key)
first_match = complete_tester(text, line, begidx, endidx, cmd2_app)
asser... |
.cypress
def test_cypress():
pymedphys.zip_data_paths('metersetmap-gui-e2e-data.zip', extract_directory=utilities.HERE)
pymedphys.zip_data_paths('dummy-ct-and-struct.zip', extract_directory=utilities.HERE.joinpath('cypress', 'fixtures'))
utilities.run_test_commands_with_gui_process(['yarn', 'yarn cypress ru... |
def read_yaml(config_name, config_path):
if (config_name and config_path):
with open(config_path, 'r', encoding='utf-8') as f:
conf = yaml.safe_load(f.read())
if (config_name in conf.keys()):
return conf[config_name.upper()]
else:
raise KeyError('')
el... |
def test_version_writes_github_actions_output(repo_with_git_flow_angular_commits, cli_runner, monkeypatch, tmp_path):
mock_output_file = (tmp_path / 'action.out')
monkeypatch.setenv('GITHUB_OUTPUT', str(mock_output_file.resolve()))
result = cli_runner.invoke(main, [version.name, '--patch', '--no-push'])
... |
class ExceptionHandlerWidget(QtWidgets.QGroupBox):
sigStackItemClicked = QtCore.Signal(object, object)
sigStackItemDblClicked = QtCore.Signal(object, object)
_threadException = QtCore.Signal(object)
def __init__(self, parent=None):
super().__init__(parent)
self._setupUi()
self.fi... |
def get_activations(files, model, batch_size=50, dims=2048, cuda=False, verbose=False):
model.eval()
if ((len(files) % batch_size) != 0):
print('Warning: number of images is not a multiple of the batch size. Some samples are going to be ignored.')
if (batch_size > len(files)):
print('Warning... |
class BaseGlm(BaseEstimator):
def __init__(self, loss='lin_reg', penalty=None, constraint=None, standardize=True, fit_intercept=True, solver='default', lla=True, initializer='default', relaxed=False, inferencer=None):
pass
def _estimator_type(self):
loss_config = get_base_config(get_loss_config(... |
class _ParameterGuardMeta(type):
def __getitem__(self, params: Tuple[(str, object)]) -> Any:
if ((not isinstance(params, tuple)) or (len(params) != 2)):
raise TypeError(f'{self.__name__}[...] should be instantiated with two arguments (a variable name and a type).')
if (not isinstance(par... |
def _find_args_with_product_annotation(func: Callable[(..., Any)]) -> list[str]:
annotations = get_annotations(func, eval_str=True)
metas = {name: annotation.__metadata__ for (name, annotation) in annotations.items() if (get_origin(annotation) is Annotated)}
args_with_product_annot = []
for (name, meta)... |
class GetMessages():
async def get_messages(self: 'pyrogram.Client', chat_id: Union[(int, str)], message_ids: Union[(int, Iterable[int])]=None, reply_to_message_ids: Union[(int, Iterable[int])]=None, replies: int=1) -> Union[('types.Message', List['types.Message'])]:
(ids, ids_type) = ((message_ids, raw.typ... |
class DatasetFingerprintExtractor(object):
def __init__(self, dataset_name_or_id: Union[(str, int)], num_processes: int=8, verbose: bool=False):
dataset_name = maybe_convert_to_dataset_name(dataset_name_or_id)
self.verbose = verbose
self.dataset_name = dataset_name
self.input_folder ... |
def valid_sensor_mac(sensor_mac):
invalid_mac_list = ['', '\x00\x00\x00\x00\x00\x00\x00\x00', '\x00\x00\x00\x00\x00\x00\x00\x00']
if ((len(str(sensor_mac)) == 8) and (sensor_mac not in invalid_mac_list)):
return True
else:
LOGGER.warning(f'Unpairing bad MAC: {sensor_mac}')
try:
... |
_canonicalize
_rewriter([Sum, Prod])
def local_op_of_op(fgraph, node):
if (isinstance(node.op, Prod) or isinstance(node.op, Sum)):
op_type = (Sum if isinstance(node.op, Sum) else Prod)
(node_inps,) = node.inputs
out_dtype = node.op.dtype
if (len(fgraph.clients[node_inps]) == 1):
... |
class TextCapsBleu4Evaluator():
def __init__(self):
from pycocoevalcap.tokenizer.ptbtokenizer import PTBTokenizer
from pycocoevalcap.bleu.bleu import Bleu
self.tokenizer = PTBTokenizer()
self.scorer = Bleu(4)
def eval_pred_list(self, pred_list):
gts = {}
res = {}
... |
def get_loader(image_root, gt_root, batchsize, trainsize, shuffle=True, num_workers=4, pin_memory=True, augmentation=False):
dataset = PolypDataset(image_root, gt_root, trainsize, augmentation)
data_loader = data.DataLoader(dataset=dataset, batch_size=batchsize, shuffle=shuffle, num_workers=num_workers, pin_mem... |
class SqliteErrorCode(enum.Enum):
OK = 0
ERROR = 1
INTERNAL = 2
PERM = 3
ABORT = 4
BUSY = 5
LOCKED = 6
NOMEM = 7
READONLY = 8
INTERRUPT = 9
IOERR = 10
CORRUPT = 11
NOTFOUND = 12
FULL = 13
CANTOPEN = 14
PROTOCOL = 15
EMPTY = 16
SCHEMA = 17
TOOBI... |
def save_model(model, model_save_path, step):
if isinstance(model_save_path, Path):
model_path = str(model_save_path)
else:
model_path = model_save_path
model_state_dict = model.state_dict()
for key in model_state_dict:
model_state_dict[key] = model_state_dict[key].cpu()
torc... |
def scm(args):
if (args['toSystem'] == True):
printT('Try to spawn a system shell via scm & impersonation...')
esc = Escalation()
imp = Impersonate()
status = esc.namedPipeImpersonationSystemViaSCM(ps=True, debug=False)
imp.printCurrentThreadEffectiveToken()
if (statu... |
class AttrVI_ATTR_USB_BULK_IN_PIPE(RangeAttribute):
resources = [(constants.InterfaceType.usb, 'RAW')]
py_name = ''
visa_name = 'VI_ATTR_USB_BULK_IN_PIPE'
visa_type = 'ViInt16'
default = NotAvailable
(read, write, local) = (True, True, True)
(min_value, max_value, values) = (129, 143, [(- 1)... |
def _get_builtin_metadata():
id_to_name = {x['id']: x['name'] for x in categories}
thing_dataset_id_to_contiguous_id = {i: i for i in range(len(categories))}
thing_classes = [id_to_name[k] for k in sorted(id_to_name)]
return {'thing_dataset_id_to_contiguous_id': thing_dataset_id_to_contiguous_id, 'thing... |
def test_two_loop_vars_one_accumulator() -> None:
test_list = [10, 20, 30]
sum_so_far = 0
with AccumulationTable(['sum_so_far']) as table:
for (index, item) in enumerate(test_list):
sum_so_far = (sum_so_far + item)
assert (table.loop_variables == {'index': ['N/A', 0, 1, 2], 'item': [... |
class VanOverlappingPatchEmbedder(nn.Sequential):
def __init__(self, in_channels: int, hidden_size: int, patch_size: int=7, stride: int=4):
super().__init__()
self.convolution = nn.Conv2d(in_channels, hidden_size, kernel_size=patch_size, stride=stride, padding=(patch_size // 2))
self.normali... |
class CosLrWarmupScheduler():
def __init__(self, optimizer, total_iter):
assert (type(total_iter) is int)
self.optimizer = optimizer
self.total_iter = total_iter
self.base_lr = [group['lr'] for group in optimizer.param_groups]
self.current_iter = 0
def step(self):
... |
class EarlyStopping(Callback):
early_stopping_metric: str
is_maximize: bool
tol: float = 0.0
patience: int = 5
def __post_init__(self):
self.best_epoch = 0
self.stopped_epoch = 0
self.wait = 0
self.best_weights = None
self.best_loss = np.inf
if self.is... |
def main(args):
warpq = warpqMetric(args)
warpq_rawScore = []
warpq_mappedScore = []
if (args['mode'] == 'predict_csv'):
df = pd.read_csv(args['csv_input'], index_col=None)
for (index, row) in tqdm(df.iterrows(), total=df.shape[0], desc='Compute quality sores...'):
(rawScore,... |
class Config():
def _validate_py_syntax(filename):
with open(filename, 'r') as f:
content = f.read()
try:
ast.parse(content)
except SyntaxError as e:
raise SyntaxError(f'There are syntax errors in config file {filename}: {e}')
def _substitute_predefine... |
class TagModelToBaseTest(TestCase):
manage_models = [test_models.TagFieldOptionsModel]
def test_custom_base_used(self):
tag_model = test_models.CustomTagBaseTest.singletag.tag_model
self.assertTrue(issubclass(tag_model, test_models.CustomTagBase))
self.assertTrue(issubclass(tag_model, ta... |
def resolve_module_exports_from_url(url: str, max_depth: int, is_re_export: bool=False) -> set[str]:
if (max_depth == 0):
logger.warning(f'Did not resolve all exports for {url} - max depth reached')
return set()
try:
text = requests.get(url, timeout=5).text
except requests.exceptions... |
class Model2Model(PreTrainedEncoderDecoder):
def __init__(self, *args, **kwargs):
super(Model2Model, self).__init__(*args, **kwargs)
self.tie_weights()
def tie_weights(self):
pass
def from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs):
if (('bert' not in pre... |
class ShortReprMixin():
def __repr__(self):
return '{}{}({})'.format('{}.'.format(self.__class__.__module__), self.__class__.__name__, ', '.join((('{!r}'.format(value) if (not name.startswith('_')) else '{}={!r}'.format(name, value)) for (name, value) in self._repr_items)))
def print_nested(self, stream... |
class TestOCSPAcceptableResponses():
def test_invalid_types(self):
with pytest.raises(TypeError):
x509.OCSPAcceptableResponses(38)
with pytest.raises(TypeError):
x509.OCSPAcceptableResponses([38])
def test_eq(self):
acceptable_responses1 = x509.OCSPAcceptableRespo... |
class DTensorEntry(Entry):
shards: List[Shard]
mesh: NestedList
dim_map: List[List[int]]
def __init__(self, shards: List[Shard], mesh: NestedList, dim_map: List[List[int]]) -> None:
super().__init__(type='DTensor')
self.shards = shards
self.mesh = mesh
self.dim_map = dim_... |
def episodic_iterator(data, num_classes, transforms, forcecpu=False, use_hd=False):
if ((args.dataset_device == 'cpu') or forcecpu):
dataset = EpisodicCPUDataset(data, num_classes, transforms, use_hd=use_hd)
return torch.utils.data.DataLoader(dataset, batch_size=((args.batch_size // args.n_ways) * a... |
class DepositfilesComFolder(SimpleDecrypter):
__name__ = 'DepositfilesComFolder'
__type__ = 'decrypter'
__version__ = '0.07'
__status__ = 'testing'
__pattern__ = '
__config__ = [('enabled', 'bool', 'Activated', True), ('use_premium', 'bool', 'Use premium account if available', True), ('folder_pe... |
class XIQueryDevice(rq.ReplyRequest):
_request = rq.Struct(rq.Card8('opcode'), rq.Opcode(48), rq.RequestLength(), DEVICEID('deviceid'), rq.Pad(2))
_reply = rq.Struct(rq.ReplyCode(), rq.Pad(1), rq.Card16('sequence_number'), rq.ReplyLength(), rq.LengthOf('devices', 2), rq.Pad(22), rq.List('devices', DeviceInfo)) |
class StoppableProcess(context.Process):
def __init__(self):
super().__init__()
self._should_stop = context.Event()
self._should_stop.clear()
def join(self, timeout=0):
self._should_stop.wait(timeout)
if (not self.should_stop()):
self.stop()
return sup... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.