code stringlengths 281 23.7M |
|---|
.skipif((not has_cupy_gpu), reason='needs CuPy GPU')
def test_model_gpu():
pytest.importorskip('ml_datasets')
import ml_datasets
with use_ops('cupy'):
n_hidden = 32
dropout = 0.2
((train_X, train_Y), (dev_X, dev_Y)) = ml_datasets.mnist()
model = chain(Relu(nO=n_hidden, dropou... |
class ParallelPreprocessor(Preprocessor):
def __init__(self, *args, **kwargs):
self.tasks = mp.cpu_count()
super(ParallelPreprocessor, self).__init__(*args, **kwargs)
def on_result(self, result):
self.results.append(result)
def transform(self, fileids=None, categories=None):
... |
def test_ordered_set():
ordered_set = OrderedSet([1, 3, 1, 2])
assert (list(ordered_set) == [1, 3, 2])
assert (1 in ordered_set)
assert bool(ordered_set)
ordered_set.add(1)
assert (1 in ordered_set)
ordered_set.remove(1)
assert (1 not in ordered_set)
for i in range(4):
ordere... |
class UnsignedShortType(Type):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.name = UNSIGNED_SHORT
self.byte_size = 2
def debug_info(self):
bs = bytearray()
bs.append(ENUM_ABBREV_CODE['BASE_TYPE_WITH_ENCODING'])
bs.append(self.byte_si... |
(urls.PRIVACY_NOTICE, status_code=HTTP_200_OK, response_model=Page[schemas.PrivacyNoticeResponse], dependencies=[Security(verify_oauth_client, scopes=[scope_registry.PRIVACY_NOTICE_READ])])
def get_privacy_notice_list(*, db: Session=Depends(deps.get_db), params: Params=Depends(), show_disabled: Optional[bool]=True, reg... |
class OptionPlotoptionsArcdiagramSonificationTracksMapping(Options):
def frequency(self) -> 'OptionPlotoptionsArcdiagramSonificationTracksMappingFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsArcdiagramSonificationTracksMappingFrequency)
def gapBetweenNotes(self) -> 'OptionPlotop... |
_api.route('/v1/check/images/<path:image_name>', methods=['POST'])
def check_docker_by_image_name(image_name):
if (not image_name):
return (json.dumps({'err': 400, 'msg': 'Bad image name'}, sort_keys=True), 400)
try:
pulled = False
if (not InternalServer.get_docker_driver().is_docker_ima... |
class TestTransformerModelConverter(AITTestCase):
def test_transformer_encoder(self):
torch.manual_seed(0)
class EncoderBlock(torch.nn.Module):
def __init__(self, input_dim, num_heads, dim_feedforward, dropout=0.0):
super().__init__()
self.attn = torch.nn.... |
class UserSettingsHandler(BaseHandler):
def initialize(self, app):
self.user_settings = app.user_settings
def get(self, path):
if (path == 'style.css'):
self.set_status(200)
self.set_header('Content-type', 'text/css')
self.write(self.user_settings['user_css']) |
class ConnectorRunner():
def __init__(self, db, cache: FidesopsRedis, connector_type: str, secrets: Dict[(str, Any)], external_references: Optional[Dict[(str, Any)]]=None, erasure_external_references: Optional[Dict[(str, Any)]]=None):
self.db = db
self.cache = cache
self.connector_type = con... |
def freq_from_hps(signal, fs):
signal = (asarray(signal) + 0.0)
N = len(signal)
signal -= mean(signal)
windowed = (signal * kaiser(N, 100))
X = log(abs(rfft(windowed)))
X -= mean(X)
hps = copy(X)
for h in range(2, 9):
dec = decimate(X, h, zero_phase=True)
hps[:len(dec)] +... |
_routes.route('/<int:stream_id>/join')
_required
def join_stream(stream_id: int):
stream = VideoStream.query.get_or_404(stream_id)
if (not stream.user_can_access):
raise NotFoundError({'source': ''}, 'Video Stream Not Found')
if ((not stream.channel) or (stream.channel.provider != 'bbb')):
r... |
class OptionPlotoptionsBubbleTooltip(Options):
def clusterFormat(self):
return self._config_get('Clustered points: {point.clusterPointsAmount}')
def clusterFormat(self, text: str):
self._config(text, js_type=False)
def dateTimeLabelFormats(self) -> 'OptionPlotoptionsBubbleTooltipDatetimelabe... |
class OptionSeriesBubbleSonificationDefaultinstrumentoptionsMappingTremoloDepth(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text... |
class OptionPlotoptionsDumbbellSonificationContexttracksMapping(Options):
def frequency(self) -> 'OptionPlotoptionsDumbbellSonificationContexttracksMappingFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsDumbbellSonificationContexttracksMappingFrequency)
def gapBetweenNotes(self) -... |
class FromCrypto():
env_int_def_from_crypto: int = '${spock.crypto:gAAAAABigpYHrKffEQ203V6L5YEikgAfuzOU6i0xigLinKlXeR7seWHji4aHyoQ-H9IGaXcCns65AZq-cSyXcUFtQ_9w43RUraUM-tqDdCXeiDygeA_BEC0=}'
env_float_def_from_crypto: float = '${spock.crypto:gAAAAABigpYHuJndgXM8wQ17uDblBfgm256VzXNjCiblpPfL08LndRWSG4E8v7rSPB7Amfo... |
def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str):
state_dict = trainer.model.state_dict()
if trainer.args.should_save:
cpu_state_dict = {}
for key in state_dict.keys():
if ('teacher' in key):
continue
cpu_state_dict[key] =... |
def get(obj):
if (not isinstance(obj, bytes)):
raise TypeError('object type must be bytes')
info = {'type': dict(), 'extension': dict(), 'mime': dict()}
stream = ' '.join(['{:02}'.format(byte) for byte in obj])
for element in data:
for signature in element['signature']:
offse... |
def test_grid_from_hdf_warns(tmp_path, any_grid):
if (version.parse(xtgeo_version) < version.parse('2.16')):
pytest.skip()
any_grid.to_hdf((tmp_path / 'grid.hdf'))
with pytest.warns(DeprecationWarning, match='from_hdf is deprecated'):
any_grid.from_hdf((tmp_path / 'grid.hdf')) |
_routes.route('/<int:stream_id>/chat-token')
_required
def get_chat_token(stream_id: int):
stream = VideoStream.query.get_or_404(stream_id)
event = stream.event
if (not stream.user_can_access):
raise NotFoundError({'source': ''}, 'Video Stream Not Found')
if (not event.is_chat_enabled):
... |
class MockTaskExecutor(TaskExecutorBase):
def __init__(self):
self.command_queue: PersistentQueue = None
self.started_task = []
self.stopped_task = []
def start_task_execution(self, key: TaskExecutionKey):
self.started_task.append(key)
def stop_task_execution(self, key: TaskE... |
class Thunderbird(Backend):
_unread = set()
def init(self):
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()
bus.add_signal_receiver(self.new_msg, dbus_interface='org.mozilla.thunderbird.DBus', signal_name='NewMessageSignal')
bus.add_signal_receiver(s... |
def downgrade():
op.drop_column('ctl_data_uses', 'replaced_by')
op.drop_column('ctl_data_uses', 'version_deprecated')
op.drop_column('ctl_data_uses', 'version_added')
op.drop_column('ctl_data_subjects', 'replaced_by')
op.drop_column('ctl_data_subjects', 'version_deprecated')
op.drop_column('ctl_... |
class UserProfileView(APIView):
serializer = UserProfileSerializer
dc_bound = False
order_by_default = ('user__username',)
order_by_field_map = {'created': 'user_id', 'username': 'user__username'}
def __init__(self, request, username, data, many=False):
super(UserProfileView, self).__init__(... |
def prepare_df_for_time_index_plot(df: DataFrame, column_name: str, datetime_name: Optional[str]) -> Tuple[(pd.DataFrame, Optional[str])]:
if (datetime_name is not None):
(prefix, pattern, freq) = choose_agg_period(df, None, datetime_name)
date_col = sf.col(datetime_name)
if (pattern == 'wee... |
def LMQLOp(name):
def class_transformer(cls):
cls_name = cls.__name__
if (cls.__module__ != 'lmql.ops.ops'):
cls_name = cls
if (type(name) is list):
for n in name:
lmql_operation_registry[n] = cls_name
return cls
lmql_operation_regi... |
(nopython=True)
def kernel_g_z_spherical(longitude, cosphi, sinphi, radius, longitude_p, cosphi_p, sinphi_p, radius_p):
(distance, cospsi, _) = distance_spherical_core(longitude, cosphi, sinphi, radius, longitude_p, cosphi_p, sinphi_p, radius_p)
delta_z = (radius - (radius_p * cospsi))
return (delta_z / (di... |
class TestEmailLogin(BaseEvenniaCommandTest):
def test_connect(self):
self.call(email_login.CmdUnconnectedConnect(), ' test', "The email '' does not match any accounts.", inputs=['Y'])
self.call(email_login.CmdUnconnectedCreate(), '"mytest" test11111', "A new account 'mytest' was created. Welcome!"... |
class PParallelInpOut32(object):
def __init__(self, address=888):
from ctypes import windll
if (isinstance(address, str) and address.startswith('0x')):
self.base = int(address, 16)
else:
self.base = address
try:
self.port = windll.inpout32
... |
def get_releases(metadata: DictConfig) -> List[Version]:
ret: List[Version] = []
for (ver, files) in metadata.releases.items():
for file in files:
if ((file.packagetype == 'bdist_wheel') and (file.yanked is not True)):
v = parse_version(ver)
ret.append(v)
... |
class BlockUidHistory(ReprMixIn):
def __init__(self) -> None:
self._history: Dict[(int, Dict[(int, SparseBitfield)])] = {}
def add(self, storage_id: int, block_uid: BlockUid) -> None:
assert ((block_uid.left is not None) and (block_uid.right is not None))
history = self._history
... |
class LondonVM(BerlinVM):
fork = 'london'
block_class: Type[BaseBlock] = LondonBlock
_state_class: Type[BaseState] = LondonState
create_header_from_parent = staticmethod(create_london_header_from_parent(compute_london_difficulty))
compute_difficulty = staticmethod(compute_london_difficulty)
conf... |
.django_db
def test_alternate_agency(client, monkeypatch, transaction_search_1, elasticsearch_transaction_index):
setup_elasticsearch_test(monkeypatch, elasticsearch_transaction_index)
resp = client.get(url.format(toptier_code='002', filter='?fiscal_year=2021'))
assert (resp.status_code == status.HTTP_200_O... |
class CyclicBehaviour(SimpleBehaviour, ABC):
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
self._number_of_executions = 0
def number_of_executions(self) -> int:
return self._number_of_executions
def act_wrapper(self) -> None:
if (not self.is_done()):
... |
def fetch_production(zone_key: str='PE', session: (Session | None)=None, target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)) -> list:
if target_datetime:
raise NotImplementedError('This parser is not yet able to parse past dates')
r = (session or Session())
url = '
curre... |
def test_transition_enum():
r = ft.AnimatedSwitcher()
assert (r.transition is None)
assert (r._get_attr('transition') is None)
r = ft.AnimatedSwitcher(transition=ft.AnimatedSwitcherTransition.FADE)
assert isinstance(r.transition, ft.AnimatedSwitcherTransition)
assert (r.transition == ft.Animated... |
def set_t_ids_val(unit_drops_stats: list[int], data: dict[(str, Any)], user_t_ids: list[int]) -> list[int]:
for t_id in user_t_ids:
if (t_id in data['t_ids']):
index = data['t_ids'].index(t_id)
save_index = data['indexes'][index]
unit_drops_stats[save_index] = 1
retur... |
def attach_modules(parent_module: Union[('BaseWeb3', 'Module')], module_definitions: Dict[(str, Any)], w3: Optional[Union[('BaseWeb3', 'Module')]]=None) -> None:
for (module_name, module_info) in module_definitions.items():
module_info_is_list_like = isinstance(module_info, Sequence)
module_class = ... |
def transform_interface_to_typed_interface(interface: typing.Optional[Interface]) -> typing.Optional[_interface_models.TypedInterface]:
if (interface is None):
return None
if (interface.docstring is None):
input_descriptions = output_descriptions = {}
else:
input_descriptions = inter... |
_bad_request
def ghost_generics_for_entity(request, code, entity_type):
date = _specified_or_last_date(request, 'prescribing')
entity = _get_entity(entity_type, code)
measure_for_entity_url = reverse('measure_for_one_{}'.format(entity_type.lower()), kwargs={'measure': 'ghost_generic_measure', 'entity_code':... |
class Migration(migrations.Migration):
dependencies = [('home', '0002_create_homepage')]
operations = [migrations.AddField(model_name='homepage', name='how_body', field=wagtail.core.fields.RichTextField(default='Blah blah')), migrations.AddField(model_name='homepage', name='how_header', field=models.CharField(d... |
class OptionSeriesLollipopAccessibility(Options):
def description(self):
return self._config_get(None)
def description(self, text: str):
self._config(text, js_type=False)
def descriptionFormat(self):
return self._config_get(None)
def descriptionFormat(self, text: str):
se... |
class TwigSecuredTest(unittest.TestCase, BaseTest):
expected_data = {'language': 'php', 'engine': 'twig', 'trailer': '{{%(trailer)s}}', 'header': '{{%(header)s}}', 'render': '{{%(code)s}}', 'prefix': '', 'suffix': ''}
url = '
url_blind = ''
plugin = Twig
blind_tests = []
reflection_tests = [(0, ... |
def create_sdm_item_selection(item_count, *items):
ret = b''
if (item_count == 255):
return b'\xff'
elif (item_count == 0):
return b'\x00'
ret += struct.pack('<B', item_count)
for item in items:
ret += struct.pack('<BB', item[0], (1 if item[1] else 0))
return ret |
.skipif(('pandas' not in sys.modules), reason='Pandas is not installed.')
def test_pass_annotated_to_downstream_tasks():
import pandas as pd
def hash_pandas_dataframe(df: pd.DataFrame) -> str:
return str(pd.util.hash_pandas_object(df))
def t0(a: int) -> Annotated[(int, HashMethod(function=str))]:
... |
def _get_resources(resources: List[Type[Resource]]):
ret = []
for resource in resources:
item = {'icon': resource.icon, 'label': resource.label}
if issubclass(resource, Link):
item['type'] = 'link'
item['url'] = resource.url
item['target'] = resource.target
... |
def inject_attrs(cls, base, names=None, *, exclude=None, fail=True):
if (not isinstance(cls, type)):
raise TypeError(f'cls must be a type, got {cls!r}')
ns = _resolve_base_namespace(base, names, exclude)
if (not _check_matching_attrs(cls, ns, base, fail)):
return None
vars(cls).update(ns... |
class SGDGraftingTest(unittest.TestCase):
def _setup_test(self) -> Tuple[(SGDGrafting, torch.Tensor)]:
param = torch.tensor([1.0, 2.0])
return (SGDGrafting(param), param)
def test_init(self):
(grafting, _) = self._setup_test()
self.assertEqual(grafting.parameter_count, 0)
def... |
.parametrize('contents, expected_errors', [(dedent('\n INCLUDE does_not_exist0\n NUM_REALIZATIONS 1\n INCLUDE does_not_exist1\n INCLUDE does_not_exist2\n INCLUDE does_not_exist3\n JOBNAME my_name%d\n INCLUDE does_no... |
def get_latest_anomaly_test_metrics(dbt_project: DbtProject, test_id: str):
results = dbt_project.run_query(ANOMALY_TEST_POINTS_QUERY.format(test_id=test_id))
result_rows = [json.loads(result['result_row']) for result in results]
return {(dateutil.parser.parse(result['bucket_start']).replace(tzinfo=None), d... |
class PlayerRole(Generic[T], GameViralContext):
_role: T
def __init__(self, typ: Type[T]):
self._typ = typ
self._role = typ(0)
def __str__(self) -> str:
return self._role.name
def __eq__(self, other: object) -> bool:
if (not isinstance(other, self._typ)):
retu... |
def _start():
global patch, name, path, monitor
global list_input, list_output, list1, list2, list3, i, j, lock, trigger, key1, key2, key3, this, thread, context, socket
list_input = patch.config.items('input')
list_output = patch.config.items('output')
list1 = []
list2 = []
list3 = []
f... |
class TaskModelOutputMetaData(TaskOutputMetaData):
def __init__(self, o_sequence, o_label, model_md):
super(TaskModelOutputMetaData, self).__init__(o_sequence, o_label, elmdpenum.TaskOutputMetaDataTypes.MODEL_OUTPUT.value)
self.model_md = model_md
def to_dict(self):
meta_data = super(Tas... |
class _IndexedRadioEditor(BaseSourceWithLocation):
source_class = RadioEditor
locator_class = Index
handlers = [(MouseClick, (lambda wrapper, _: _interaction_helpers.mouse_click_radiobutton_child_in_panel(control=wrapper._target.source.control, index=convert_index(source=wrapper._target.source, index=wrappe... |
def test_firedrake_integral_sphere_high_order_netgen():
try:
from netgen.csg import CSGeometry, Pnt, Sphere
import netgen
except ImportError:
pytest.skip(reason='Netgen unavailable, skipping Netgen test.')
comm = COMM_WORLD
if (comm.Get_rank() == 0):
geo = CSGeometry()
... |
class Test(unittest.TestCase):
def tearDown(self):
if hasattr(self, 'ie'):
self.ie.Quit()
del self.ie
def test_mycomobject(self):
o = MyComObject()
p = comtypes2pywin(o, IDispatch)
disp = win32com.client.Dispatch(p)
self.assertEqual(repr(disp), '<C... |
class TestPackageModel(BasePyTestCase):
def test_two_package_different_types(self):
package1 = model.Package(name='python-requests')
package2 = model.RpmPackage(name='python-requests')
self.db.add(package1)
self.db.add(package2)
self.db.flush()
def test_two_package_same_t... |
def is_directly_connected(node, node_tree, wire1, wire2):
if ('wires' in node_tree):
node_tree_wires = node_tree['wires']
elif ((len(node_tree['edges']) == 1) and (len(node_tree['joins']) == 0)):
node_tree_wires = node_tree['edges'][0]
else:
return None
if (wire1 not in node_tree... |
class OptionPlotoptionsNetworkgraphOnpointPosition(Options):
def offsetX(self):
return self._config_get(None)
def offsetX(self, num: float):
self._config(num, js_type=False)
def offsetY(self):
return self._config_get(None)
def offsetY(self, num: float):
self._config(num, ... |
class JaggedDim(Node):
def __init__(self, min_value: IntVar, max_value: IntVar):
if isinstance(min_value, int):
min_value = IntImm(min_value)
if isinstance(max_value, int):
max_value = IntImm(max_value)
if (min_value.lower_bound() < 0):
raise ValueError(f'... |
_processor
def inject_variables():
if get_authed():
mod_links = [('boards', ['mod.mod_boards', 'mod.mod_board_log']), ('reports', ['mod.mod_report'])]
if request_has_role(roles.ROLE_ADMIN):
mod_links += [('bans', ['mod.mod_bans']), ('moderators', ['mod.mod_moderators']), ('pages', ['mod.... |
class Restore(object):
_MODULE_NAME = 'fledge_restore_common'
SCHEDULE_RESTORE_ON_DEMAND = '8d4d3ca0-de80-11e7-80c1-9a214cf093ae'
_MESSAGES_LIST = {'i000000': 'general information', 'i000001': 'On demand restore successfully launched.', 'e000000': 'general error', 'e000001': 'cannot launch on demand restore... |
class OtherVarNode(GivElm):
total = 0
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.name = kwargs['name']
def __repr__(self):
return self.name
def __str__(self):
return repr(self)
def str_noindex(self):
return self.name
def st... |
class Core(core.Core):
core_type = 'S'
def __init__(self, **options: Dict[(str, Any)]) -> None:
super().__init__()
self.options = Options(options)
self.events = Events(self)
disables = self.options.disables
if ('serve' not in disables):
self.serve = parts.serv... |
('build', 'build a given project')
class BuildCmd(ProjectCmdBase):
def run_project_cmd(self, args, loader, manifest):
if args.clean:
clean_dirs(loader.build_opts)
print(('Building on %s' % loader.ctx_gen.get_context(args.project)))
projects = loader.manifests_in_dependency_order(... |
def _get_file_kind(filename):
try:
st = os.lstat(filename)
except FileNotFoundError:
return None
kinds = []
if _stat.S_ISDIR(st.st_mode):
kinds.append('dir')
elif _stat.S_ISREG(st.st_mode):
kinds.append('file')
else:
kinds.append('other')
if _stat.S_IS... |
def test_dependency_getter(tmp_path: Path) -> None:
fake_pyproject_toml = '[project]\n# PEP 621 project metadata\n# See = [\n "qux",\n "bar>=20.9",\n "optional-foo[option]>=0.12.11",\n "conditional-bar>=1.1.0; python_version < 3.11",\n "fox-python", # top level module is called "fox"\n]\n\n[project... |
def rewrite_nn_resize_op(is_quantized=False):
input_pattern = graph_matcher.OpTypePattern(('FakeQuantWithMinMaxVars' if is_quantized else '*'))
reshape_1_pattern = graph_matcher.OpTypePattern('Reshape', inputs=[input_pattern, 'Const'], ordered_inputs=False)
mul_pattern = graph_matcher.OpTypePattern('Mul', i... |
class OptionPlotoptionsVariablepieSonificationContexttracksMappingLowpassFrequency(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, t... |
.parametrize('elasticapm_client', [{'breakdown_metrics': False}], indirect=True)
def test_disable_breakdowns(elasticapm_client):
with pytest.raises(LookupError):
elasticapm_client.metrics.get_metricset('elasticapm.metrics.sets.breakdown.BreakdownMetricSet')
with mock.patch('elasticapm.traces.BaseSpan.ch... |
class AbstractWhoosheer(object):
auto_update = True
def search(cls, search_string, values_of='', group=whoosh.qparser.OrGroup, match_substrings=True, limit=None):
index = Whooshee.get_or_create_index(_get_app(cls), cls)
prepped_string = cls.prep_search_string(search_string, match_substrings)
... |
def test_named_schema_with_logical_type_in_union():
schema = [{'name': 'named_schema_with_logical_type', 'namespace': 'com.example', 'type': 'record', 'fields': [{'name': 'item', 'type': {'type': 'int', 'logicalType': 'date'}}]}, {'type': 'record', 'name': 'test_named_schema_with_logical_type', 'fields': [{'name': ... |
def _create_firmware_directory():
logging.info('Creating firmware directory')
data_dir_name = config.backend.firmware_file_storage_directory
mkdir_process = subprocess.run(f'sudo mkdir -p --mode=0744 {data_dir_name}', shell=True, stdout=PIPE, stderr=STDOUT, text=True)
chown_process = subprocess.run(f'su... |
(type_strs)
def test_has_arrlist_has_expected_behavior_for_parsable_types(type_str):
if type_str.startswith('('):
assert (not has_arrlist(type_str))
event('No match for tuple type')
elif ARRAY_RE.search(type_str):
assert has_arrlist(type_str)
event('Match for array type')
els... |
def test_arbitrary_encoding_automatically_find_variables_ignore_format(df_enc_numeric):
encoder = OrdinalEncoder(encoding_method='arbitrary', variables=None, ignore_format=True)
X = encoder.fit_transform(df_enc_numeric[['var_A', 'var_B']])
transf_df = df_enc_numeric[['var_A', 'var_B']].copy()
transf_df[... |
class TestOneDockerServiceAsync(IsolatedAsyncioTestCase):
('fbpcp.service.container.ContainerService')
def setUp(self, MockContainerService):
self.container_svc = MockContainerService()
self.insights = AsyncMock()
self.onedocker_svc = OneDockerService(container_svc=self.container_svc, ta... |
class ArgmaxTestCase(unittest.TestCase):
def _test_argmax(self, batch_size=1, shape=(2, 6), dim=0, test_name='argmax', copy_op=False, dtype='float16'):
o_shape = list(shape)[:(- 1)]
X1 = Tensor(shape=shape, dtype=dtype, name='X', is_input=True)
X4_op = ops.argmax(dim=dim)
if copy_op:... |
_ns.route('/bitbucket/<int:copr_id>/<uuid>/', methods=['POST'])
_ns.route('/bitbucket/<int:copr_id>/<uuid>/<string:pkg_name>/', methods=['POST'])
def webhooks_bitbucket_push(copr_id, uuid, pkg_name: Optional[str]=None):
copr = ComplexLogic.get_copr_by_id(copr_id)
if (copr.webhook_secret != uuid):
raise ... |
def test_default_param_filler():
generator_config = {'name': 'do_snapshot_copiers', 'type': 'requests_json_generator', 'target': 'do_something_with_items', 'requires_resources': ['dataproc-cluster'], 'properties': {'url': ' 'list_json_key': 'my-key'}}
g = plugins.manager.generators(generator_config)
assert ... |
class DummyObserver():
def __init__(self, notify=True, observables=(), next_objects=(), notifier=None, maintainer=None, extra_graphs=()):
if (notifier is None):
notifier = DummyNotifier()
if (maintainer is None):
maintainer = DummyNotifier()
self.notify = notify
... |
def from_csv(file, name='name', id_ft='id_ft', id_fld='id_fld', name_fld=None):
sites = []
with open(file) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
params = [row[name], row[id_ft], row[id_fld]]
params = (params.append(row[name_fld]) if name_fld else... |
('ciftify.bidsapp.fmriprep_ciftify.run')
def test_ux21_synth_will_run_from_derivatives(mock_run):
uargs = [synth_bids, os.path.join(synth_bids, 'derivatives'), 'participant', '--participant_label=02', '--task=nback', '--surf-reg', 'FS']
ret = simple_main_run(uargs)
call_list = parse_call_list_into_strings(m... |
def format_continuation_lexicon_xml(tsvparts):
xmlstring = ' <e>'
if (tsvparts[1] != ''):
xmlstring += '<a>'
for anal in tsvparts[1].split('|'):
if (anal in Ftb3Formatter.stuff2ftb3):
anal = make_xmlid(anal)
xmlstring += (('<s mcs="' + anal) + '"/>'... |
def get_otp_url(kp_entry):
otp_url = ''
if hasattr(kp_entry, 'otp'):
otp_url = kp_entry.deref('otp')
else:
otp_url = kp_entry.get_custom_property('otp')
if otp_url:
return otp_url
otp_url_format = 'otpauth://totp/Entry?secret={}&period={}&digits={}&algorithm={}'
(digits, ... |
class TestPyQtFont(unittest.TestCase):
def test_create_traitsfont(self):
expected_outcomes = {}
expected_outcomes[''] = TraitsFont()
for (weight, qt_weight) in font_weights.items():
expected_outcomes[weight] = TraitsFont()
expected_outcomes[weight].setWeight(qt_weight... |
class TestOldAPI():
.skipif((sys.version_info >= (3, 0)), reason='ok on Py3')
def test_duplicate_keys_02(self):
from srsly.ruamel_yaml import safe_load
from srsly.ruamel_yaml.constructor import DuplicateKeyError
with pytest.raises(DuplicateKeyError):
safe_load('type: Domestic... |
def heading(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
LOGGER.debug('entering heading: %s, %s, %s, %s', state, startLine, endLine, silent)
pos = (state.bMarks[startLine] + state.tShift[startLine])
maximum = state.eMarks[startLine]
if state.is_code_block(startLine):
r... |
('/api/user/create', methods=['POST'])
_secure
def user_create():
username = request.form['username']
password = request.form['password']
password2 = request.form['password2']
is_admin = (request.form['is_admin'] == 'true')
if (password != password2):
return (jsonify({'message': "Passwords d... |
class AccountTable(BaseWalletStore):
LOGGER_NAME = 'db-table-account'
CREATE_SQL = 'INSERT INTO Accounts (account_id, default_masterkey_id, default_script_type, account_name, date_created, date_updated) VALUES (?, ?, ?, ?, ?, ?)'
READ_SQL = 'SELECT account_id, default_masterkey_id, default_script_type, acco... |
class _ContainerProjectsLocationsRepository(_base_repository.GCPRepository):
def __init__(self, **kwargs):
super(_ContainerProjectsLocationsRepository, self).__init__(component='projects.locations', **kwargs)
def get_serverconfig(self, project_id, location, fields=None, **kwargs):
name = 'projec... |
def long_field(data):
str_or_bytes = (str(data) if (not isinstance(data, (str, bytes))) else data)
if (len(str_or_bytes) > LONG_FIELD_MAX_LENGTH):
if isinstance(str_or_bytes, bytes):
return (str_or_bytes[:(LONG_FIELD_MAX_LENGTH - 3)] + b'...')
else:
return (str_or_bytes[:... |
_ns.route('/<username>/new-fedora-review/', methods=['GET', 'POST'])
_required
def copr_add_fedora_review(username):
delete_after_days = app.config['DELETE_AFTER_DAYS']
if (username != flask.g.user.username):
flask.flash("You can not add projects for '{}' user".format(username), 'error')
return ... |
class ElasticsearchAccountDisasterBase(DisasterBase):
agg_group_name: str = 'group_by_agg_key'
agg_key: str
bucket_count: int
filter_query: ES_Q
has_children: bool = False
nested_nonzero_fields: Dict[(str, str)] = []
query_fields: List[str]
sub_agg_group_name: str = 'sub_group_by_sub_agg... |
class OptionPlotoptionsVectorOnpoint(Options):
def connectorOptions(self) -> 'OptionPlotoptionsVectorOnpointConnectoroptions':
return self._config_sub_data('connectorOptions', OptionPlotoptionsVectorOnpointConnectoroptions)
def id(self):
return self._config_get(None)
def id(self, text: str):... |
class TopicSetWCI(object):
def __init__(self, topic_set, commit_info):
self.__topic_set = topic_set
self.__commit_info = commit_info
def get_topic_set(self):
return self.__topic_set
def get_commit_info(self):
return self.__commit_info
def execute(self, executor, func_pref... |
class _TabWidget(QtGui.QTabWidget):
_active_icon = None
_spinner_data = None
def __init__(self, root, *args):
QtGui.QTabWidget.__init__(self, *args)
if (sys.platform == 'darwin'):
self.setDocumentMode(True)
self._root = root
self.setTabBar(_DragableTabBar(self._ro... |
def test_append_to_recent_files_working_properly(test_data):
test_data['version'].id = 234
test_data['external_env'].append_to_recent_files(test_data['version'])
path = test_data['external_env'].get_settings_file_path()
with open(path, 'r') as f:
vid = f.read()
assert (vid == str(234)) |
class RegisterWithArgChecks(object):
def __init__(self, name, req_args=None, opt_args=None):
self._name = name
if (not req_args):
req_args = []
self._req_args = req_args
if (not opt_args):
opt_args = []
self._opt_args = opt_args
self._all_args ... |
class RepresentationTests(TestCase):
def test_unicode_crash(self):
grammar = Grammar('string = ~r"\\S+"u')
str(grammar.parse(''))
def test_unicode(self):
str(rule_grammar)
def test_unicode_keep_parens(self):
self.assertEqual(str(Grammar('foo = "bar" ("baz" "eggs")* "spam"')),... |
.usefixtures('use_tmpdir')
def test_rms_job_script_parser(monkeypatch, source_root):
with open('rms_config.yml', 'w', encoding='utf-8') as f:
json.dump({'executable': os.path.realpath('bin/rms'), 'env': {'10.1.3': {'PATH': ''}}}, f)
monkeypatch.setenv('RMS_TEST_VAR', 'fdsgfdgfdsgfds')
os.mkdir('run_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.