code
stringlengths
281
23.7M
class OptionSeriesHistogramDragdropGuideboxDefault(Options): def className(self): return self._config_get('highcharts-drag-box-default') def className(self, text: str): self._config(text, js_type=False) def color(self): return self._config_get('rgba(0, 0, 0, 0.1)') def color(self...
def extractTranslatingboredomWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('rcfn chapters', 'Rebirth of a Cannon Fodder in a Novel', 'translated'), ('rcfn', 'Rebi...
_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestCustomImageEnumEditor(BaseTestMixin, unittest.TestCase): def setUp(self): BaseTestMixin.setUp(self) def tearDown(self): BaseTestMixin.tearDown(self) def setup_gui(self, model, view): with create_ui(model, dict(view=view)) as ui: ...
def generate_test_paths(n_samples, dq_H_E, dq_B_W, paths_start_at_origin=True, include_outliers_B_H=False, outlier_probability_B_H=0.1, include_noise_B_H=False, noise_sigma_trans_B_H=0.01, noise_sigma_rot_B_H=0.1, include_outliers_W_E=False, outlier_probability_W_E=0.1, include_noise_W_E=False, noise_sigma_trans_W_E=0....
def test_warn_if_transform_df_contains_categories_not_seen_in_fit(df_enc, df_enc_rare): msg = 'During the encoding, NaN values were introduced in the feature(s) var_A.' with pytest.warns(UserWarning) as record: encoder = WoEEncoder(unseen='ignore') encoder.fit(df_enc[['var_A', 'var_B']], df_enc[...
def _validate_rule(action_type: Optional[str], storage_destination_id: Optional[str], masking_strategy: Optional[Dict[(str, Union[(str, Dict[(str, str)])])]]) -> None: if (not action_type): raise common_exceptions.RuleValidationError('action_type is required.') if (action_type == ActionType.erasure.valu...
def test_request_stream(test_client_factory): async def app(scope, receive, send): request = Request(scope, receive) body = b'' async for chunk in request.stream(): body += chunk response = JSONResponse({'body': body.decode()}) (await response(scope, receive, send...
class LoggingFormatVersionInteger(ModelNormal): allowed_values = {('format_version',): {'v1': 1, 'v2': 2}} validations = {} _property def additional_properties_type(): return (bool, date, datetime, dict, float, int, list, str, none_type) _nullable = False _property def openapi_types(...
def eval_function_completions(responses: List[str], definition: str, test: Optional[str]=None, entry_point: Optional[str]=None, assertions: Optional[Union[(str, Callable[([str], Tuple[(str, float)])])]]=None, timeout: Optional[float]=3, use_docker: Optional[bool]=True) -> Dict: n = len(responses) if (assertions...
class BeaconConfig(): def __init__(self, config_block: bytes) -> None: self.config_block: bytes = config_block self.settings_tuple = tuple(iter_settings(config_block)) self.xorkey: Optional[bytes] = None self.xorencoded: bool = False self.pe_export_stamp: Optional[int] = None...
class SubclassDefaultsSuper(HasTraits): a_str = Str() an_expr = Expression('[]') a_list = List() an_instance = Instance(Wrapper) a_wrapper_1 = WrapperTrait('bar') a_wrapper_2 = WrapperTrait() clone_wrapper_1 = CloneWrapperTrait('bar') clone_wrapper_2 = CloneWrapperTrait() disallow_de...
def fill_axis(xs: List[int], values: List[Bytes32], length: int) -> List[Bytes32]: data = [[bytes_to_int(a[i:(i + (FIELD_ELEMENT_BITS // 8))]) for a in values] for i in range(0, 32, (FIELD_ELEMENT_BITS // 8))] newdata = [fill(xs, d, length) for d in data] return [b''.join([int_to_bytes(n[i], (FIELD_ELEMENT_...
_register_make _set_nxm_headers([ofproto_v1_0.NXM_OF_IP_DST, ofproto_v1_0.NXM_OF_IP_DST_W]) _field_header([ofproto_v1_0.NXM_OF_IP_DST, ofproto_v1_0.NXM_OF_IP_DST_W]) class MFIPDst(MFField): pack_str = MF_PACK_STRING_BE32 def __init__(self, header, value, mask=None): super(MFIPDst, self).__init__(header,...
class sdict(Dict[(KT, VT)]): __slots__ = () __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ __getitem__ = dict.get def __getattr__(self, key: str) -> Optional[VT]: if key.startswith('__'): raise AttributeError return self.get(key, None) __repr__ = (lambd...
def tickets_view(page, is_my_view=False, subscribed=False): form = SearchTicketForm() status = request.args.get('status') department = request.args.get('department') category = request.args.get('category') content = request.args.get('content') user_id = request.args.get('user_id') assigned_i...
def validate_bls_withdrawal_credentials(bls_withdrawal_credentials: str) -> bytes: bls_withdrawal_credentials_bytes = normalize_bls_withdrawal_credentials_to_bytes(bls_withdrawal_credentials) if is_eth1_address_withdrawal_credentials(bls_withdrawal_credentials_bytes): raise ValidationError((load_text(['...
(np.multiply) def mul(x, y, out=None, out_like=None, sizing='optimal', method='raw', **kwargs): def _mul_raw(x, y, n_frac): precision_cast = ((lambda m: np.array(m, dtype=object)) if (n_frac >= _n_word_max) else (lambda m: m)) raw_cast = ((lambda m: np.array(m, dtype=object)) if ((x.n_word + y.n_wor...
def _check_surfer_integrity(field, shape, data_range): if (field.shape != shape): raise IOError("Grid shape {} doesn't match shape read from header {}.".format(field.shape, shape)) field_range = [field.min(), field.max()] if (not np.allclose(field_range, data_range)): raise IOError("Grid dat...
def ModelFactory(name, RangeFactory): class ModelWithRanges(HasTraits): percentage = RangeFactory(0.0, 100.0) open_closed = RangeFactory(0.0, 100.0, exclude_low=True) closed_open = RangeFactory(0.0, 100.0, exclude_high=True) open = RangeFactory(0.0, 100.0, exclude_low=True, exclude_h...
def _leaf_detail_kind(kind: str) -> SharedTextKind: text_kind = SharedTextKind.from_string(kind) if (text_kind is None): raise UserError(f'Invalid kind {kind}') if (text_kind == SharedTextKind.source): text_kind = SharedTextKind.source_detail elif (text_kind == SharedTextKind.sink): ...
class IPv6TransportEndpoints(TransportEndpointsBase): def _addEndpoint(self, addr): if (not udp6): raise SnmpsimError('This system does not support UDP/IP6') if ((addr.find(']:') != (- 1)) and (addr[0] == '[')): (h, p) = addr.split(']:') try: (h, p...
class TestWorkflowUtils(unittest.TestCase): def setUp(self) -> None: if (not os.path.exists(BLOB_DIR)): os.mkdir(BLOB_DIR) def tearDown(self) -> None: if os.path.exists(BLOB_DIR): shutil.rmtree(BLOB_DIR) def test_extract_workflows_from_file(self): workflows = ...
def start_client(): body_snsr_loc_chrc[0].ReadValue({}, reply_handler=body_sensor_val_cb, error_handler=generic_error_cb, dbus_interface=GATT_CHRC_IFACE) hr_msrmt_prop_iface = dbus.Interface(hr_msrmt_chrc[0], DBUS_PROP_IFACE) hr_msrmt_prop_iface.connect_to_signal('PropertiesChanged', hr_msrmt_changed_cb) ...
class OptionPlotoptionsPyramidSonificationPointgrouping(Options): def algorithm(self): return self._config_get('minmax') def algorithm(self, text: str): self._config(text, js_type=False) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): self....
def generate_graph(workflow_meta: WorkflowMeta): workflow_graph: AIGraph = extract_graph(workflow_meta) (workflow_nodes, id_nodes, name_nodes) = build_nodes(workflow_graph) (parent_edges, children_edges) = build_edges(workflow_graph, workflow_nodes, id_nodes, name_nodes) return build_graph(name_nodes, p...
class EfuseDefineRegisters(EfuseRegistersBase): EFUSE_MEM_SIZE = (508 + 4) DR_REG_EFUSE_BASE = EFUSE_PGM_DATA0_REG = DR_REG_EFUSE_BASE EFUSE_CHECK_VALUE0_REG = (DR_REG_EFUSE_BASE + 32) EFUSE_CLK_REG = (DR_REG_EFUSE_BASE + 456) EFUSE_CONF_REG = (DR_REG_EFUSE_BASE + 460) EFUSE_STATUS_REG = (D...
def test_default_keyword_in_message_and_keyword_only_in_message() -> None: def f(a: int, *, b: bool, c: float=0.0) -> str: pass assert (parse_function_annotations(f, default_keyword_in_message=False, keyword_only_in_message=False) == ({'a': int}, {'sample': str}, False)) assert (parse_function_annot...
class InstallWithCompile(install): def run(self): from babel.messages.frontend import compile_catalog compiler = compile_catalog(self.distribution) option_dict = self.distribution.get_option_dict('compile_catalog') compiler.domain = [option_dict['domain'][1]] compiler.directo...
class MySink(Node): TOPIC = Topic(ZMQMessage) config: MySinkConfig def setup(self) -> None: self.output_file = open(self.config.output_filename, 'wb') self.num_received = 0 (TOPIC) async def sink(self, message: ZMQMessage) -> None: self.output_file.write(message.data) ...
class Wildcard(FunctionSignature): name = 'wildcard' argument_types = [TypeHint.String, TypeHint.String.require_literal()] return_value = TypeHint.Boolean additional_types = TypeHint.String.require_literal() def to_regex(cls, *wildcards): expressions = [] head = '^' tail = '$...
class OnEmailVerificationRequestedTask(TaskBase): __name__ = 'on_email_verification_requested' async def run(self, email_verification_id: str, workspace_id: str, code: str): workspace = (await self._get_workspace(uuid.UUID(workspace_id))) async with self.get_workspace_session(workspace) as sessi...
_bp.route((app.config['FLICKET'] + 'ticket_create/'), methods=['GET', 'POST']) _required def ticket_create(): last_category = session.get('ticket_create_last_category') form = CreateTicketForm(category=last_category) if form.validate_on_submit(): new_ticket = FlicketTicketExt.create_ticket(title=for...
def psc_test_data(db): baker.make('search.AwardSearch', award_id=1, latest_transaction_id=1) baker.make('search.AwardSearch', award_id=2, latest_transaction_id=2) baker.make('search.AwardSearch', award_id=3, latest_transaction_id=3) baker.make('search.AwardSearch', award_id=4, latest_transaction_id=4) ...
class RoundedTriangleEdgeSettings(Settings): absolute_params = {'height': 50.0, 'radius': 30.0, 'r_hole': 2.0} relative_params = {'outset': 0.0} def edgeObjects(self, boxes, chars: str='t', add: bool=True): edges = [RoundedTriangleEdge(boxes, self), RoundedTriangleFingerHolesEdge(boxes, self)] ...
def create_pixbuf_from_file_at_size(filename, width, height): pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(filename, width, height) if ((pixbuf.get_width() != width) or (pixbuf.get_height() != height)): pixbuf = pixbuf.scale_simple(width, height, GdkPixbuf.InterpType.BILINEAR) return pixbuf
class Listener(object): uri = 'tcp://eddn-relay.elite-markets.net:9500' supportedSchema = ' def __init__(self, zmqContext=None, minBatchTime=5.0, maxBatchTime=10.0, reconnectTimeout=180.0, burstLimit=200): assert (burstLimit > 0) if (not zmqContext): zmqContext = zmq.Context() ...
_converter(torch.ops.aten.avg_pool2d.default) def aten_ops_avg_pool2d(target: Target, args: Tuple[(Argument, ...)], kwargs: Dict[(str, Argument)], name: str) -> ConverterOutput: input_val = args[0] if (not isinstance(input_val, AITTensor)): raise RuntimeError(f'Non-tensor inputs for {name}: {input_val}'...
def test_data_quality_test_conflict_prediction() -> None: test_dataset = pd.DataFrame({'category_feature': ['n', 'n', 'p', 'n'], 'numerical_feature': [0, 0, 2, 5], 'prediction': [0, 1, 0, 1]}) mapping = ColumnMapping(categorical_features=['category_feature'], numerical_features=['numerical_feature']) suite ...
class FBCopyCommand(fb.FBCommand): def name(self): return 'copy' def description(self): return 'Copy data to your Mac.' def options(self): return [fb.FBCommandArgument(short='-f', long='--filename', arg='filename', help='The output filename.'), fb.FBCommandArgument(short='-n', long='...
class Test_Core_Treeview(unittest.TestCase): def test_renderer(self): main_tree = Tree() main_tree.dist = 0 (t, ts) = face_grid.get_example_tree() t_grid = TreeFace(t, ts) n = main_tree.add_child() n.add_face(t_grid, 0, 'aligned') (t, ts) = bubble_map.get_exam...
class KiwoomOpenApiPlusManagerApplication(QObjectLogging): class ConnectionStatus(Enum): DISCONNECTED = 1 CONNECTED = 2 class ServerType(Enum): SIMULATION = 1 REAL = 2 UNKNOWN = 3 class RestartType(Enum): NO_RESTART = 1 RESTART_ONLY = 2 RESTART...
class SourceMockup(Source): def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs print(f'Climetlab SourceMockup : args={args}, kwargs={kwargs}') super(SourceMockup, self).__init__(**kwargs) def to_xarray(self, *args, **kwargs): return TestingDatasetA...
class LegacyWafUpdateStatus(ModelNormal): allowed_values = {} validations = {} _property def additional_properties_type(): return (bool, date, datetime, dict, float, int, list, str, none_type) _nullable = False _property def openapi_types(): return {'completed_at': (str,), 'c...
class TestMimeClient(ClientTestBase): def test_reload_server_state(self): data = self._fake_data(num_batches=1, batch_size=10) clnt = self._get_mime_client(data) self._test_reload_server_state(clnt) def test_mime_generate_local_update(self): data = self._fake_data(num_batches=5, ...
class EmissionFactorTestCase(unittest.TestCase): def test_emission_factors(self): expected = {'battery charge': 0, 'battery discharge': 490., 'biomass': 230, 'coal': 820, 'gas': 490, 'geothermal': 38, 'hydro': 24, 'hydro charge': 0, 'hydro discharge': 490., 'nuclear': 12, 'oil': 650, 'solar': 45, 'unknown':...
class WindllHandler(ClipboardHandlerBase): def _copy(text: str) -> None: from ctypes.wintypes import BOOL, DWORD, HANDLE, HGLOBAL, HINSTANCE, HMENU, HWND, INT, LPCSTR, LPVOID, UINT windll = ctypes.windll msvcrt = ctypes.CDLL('msvcrt') safeCreateWindowExA = CheckedCall(windll.user32.C...
(params=[('CG', 2, TensorFunctionSpace), ('BDM', 2, VectorFunctionSpace), ('Regge', 2, FunctionSpace)], ids=(lambda x: f'{x[2].__name__}({x[0]}{x[1]})')) def tfs(request, parentmesh): family = request.param[0] if ((family != 'CG') and (parentmesh.ufl_cell().cellname() != 'triangle') and (parentmesh.ufl_cell().c...
class scan(_coconut_has_iter): __slots__ = ('func', 'initial') def __new__(cls, function, iterable, initial=_coconut_sentinel): self = _coconut.super(scan, cls).__new__(cls, iterable) self.func = function self.initial = initial return self def __repr__(self): return (...
.parametrize(('degree', 'family', 'tdim'), [(1, 'Lagrange', 3), (2, 'Lagrange', 3), (3, 'Lagrange', 3), (0, 'Quadrature', 2), (1, 'Quadrature', 2), (2, 'Quadrature', 2)]) def test_projection_symmetric_tensor(mesh, degree, family, tdim): shape = (tdim, tdim) remove = (2 if (tdim == 2) else [3, 6, 7]) if (fam...
def print_result(data): _table = '| %-4s | %-4s | %-30s | %-29s |' print('\n* Found mice:') print(('-' * 80)) print((_table % ('VID', 'PID', 'NAME', 'FULL NAME'))) print(('-' * 80)) for (pid, vid, name, full_name, _) in data: print((_table % (pid, vid, name, full_name))) print(('-' *...
def _tf_odapi_client(image, ip, port, model_name, signature_name='detection_signature', input_name='inputs', timeout=300): start_time = time() result = _generic_tf_serving_client(image, ip, port, model_name, signature_name, input_name, timeout) log('time taken for image shape {} is {} secs'.format(image.sha...
class OptionPlotoptionsErrorbarSonificationContexttracksPointgrouping(Options): def algorithm(self): return self._config_get('minmax') def algorithm(self, text: str): self._config(text, js_type=False) def enabled(self): return self._config_get(True) def enabled(self, flag: bool):...
def youtube_recon(user_name): if (not user_name): return None url = ' r = requests.get(url) if (b'This channel does not exist.' in r.content): return None soup = BeautifulSoup(r.content, 'lxml') avatar = soup.find('img', class_='channel-header-profile-image').get('src') try: ...
def test_file_format_getting_python_value(): transformer = TypeEngine.get_transformer(FlyteFile) ctx = FlyteContext.current_context() lv = Literal(scalar=Scalar(blob=Blob(metadata=BlobMetadata(type=BlobType(format='txt', dimensionality=0)), uri='file:///tmp/test'))) pv = transformer.to_python_value(ctx,...
class TestMyRLAgent(GymTestCase): def test_fit(self): step_result = ('obs', 'reward', 'done', 'info') with patch.object(ProxyEnv, 'reset') as mocked_reset: with patch.object(ProxyEnv, 'step', return_value=step_result) as mocked_step: with patch.object(ProxyEnv, 'close') a...
class CancelCollection(View): def post(self, request): nid_list = request.POST.getlist('nid') request.user.collects.remove(*nid_list) article_query: QuerySet = Articles.objects.filter(nid__in=nid_list) article_query.update(collects_count=(F('collects_count') - 1)) return redi...
.benchmark def test_birkholz_set_synthesis(fixture_store): for (i, fix) in enumerate(fixture_store): print(i, fix) tot_cycles = 0 converged = 0 bags = fixture_store['results_bag'] for (k, v) in bags.items(): if (not k.startswith('test_birkholz_set')): continue pri...
class OptionSeriesTreemapBreadcrumbsPosition(Options): def align(self): return self._config_get('left') def align(self, text: str): self._config(text, js_type=False) def verticalAlign(self): return self._config_get('top') def verticalAlign(self, text: str): self._config(t...
def main(): rule_set = mh_style.get_rules() rules = [rule() for rules in rule_set.values() for rule in rules] mandatory_rules = [rule for rule in rules if rule.mandatory] autofix_rules = [rule for rule in rules if ((not rule.mandatory) and rule.autofix)] other_rules = [rule for rule in rules if ((no...
class TestDescriptor(Descriptor): TEST_DESC_UUID = '-1234-5678-1234-56789abcdef2' def __init__(self, bus, index, characteristic): Descriptor.__init__(self, bus, index, self.TEST_DESC_UUID, ['read', 'write'], characteristic) def ReadValue(self, options): return [dbus.Byte('T'), dbus.Byte('e')...
class KeyBindingCtrl(QtGui.QLineEdit): def __init__(self, editor, parent=None): super().__init__(parent) self.setFocusPolicy(QtCore.Qt.FocusPolicy.StrongFocus) self.setMinimumWidth(160) self.setMaximumWidth(160) self.setReadOnly(True) self.editor = editor edit...
class NamespaceVersioning(BaseVersioning): invalid_version_message = _('Invalid version in URL path. Does not match any version namespace.') def determine_version(self, request, *args, **kwargs): resolver_match = getattr(request, 'resolver_match', None) if ((resolver_match is not None) and resol...
def clean_title(title) -> str: ostype = platform.system() if (ostype == 'Linux'): title = title.replace('/', '_') elif (ostype == 'Darwin'): title = title.replace(':', ' ') title = title.replace('\\', '_').replace('/', '_').replace('|', '_') elif (ostype == 'Windows'): ti...
class OptionSeriesPictorialSonificationPointgrouping(Options): def algorithm(self): return self._config_get('minmax') def algorithm(self, text: str): self._config(text, js_type=False) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): self._co...
class OptionSeriesDependencywheelLabelStyle(Options): def fontSize(self): return self._config_get('0.8em') def fontSize(self, num: float): self._config(num, js_type=False) def fontWeight(self): return self._config_get('bold') def fontWeight(self, text: str): self._config(...
def get_registry_event_details(io, metadata, event, extra_detail_io): path_info = read_detail_string_info(io) details_info = dict() if (event.operation in [RegistryOperation.RegLoadKey.name, RegistryOperation.RegRenameKey.name]): details_info['new_path_info'] = read_detail_string_info(io) ex...
class OptionSeriesScatter3dDataDragdropDraghandle(Options): def className(self): return self._config_get('highcharts-drag-handle') def className(self, text: str): self._config(text, js_type=False) def color(self): return self._config_get('#fff') def color(self, text: str): ...
class OptionSeriesTreemapSonificationContexttracksPointgrouping(Options): def algorithm(self): return self._config_get('minmax') def algorithm(self, text: str): self._config(text, js_type=False) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): ...
def benchmark(): collect_statistics(True) baseurls = [CML_BASEURL_S3, CML_BASEURL_CDS] requests = [{'param': 'r', 'time': '1000', 'step': '0'}, {'param': 'r', 'time': '1000'}, {'param': 'r', 'time': ['1100', '1200', '1300', '1400']}, {'param': ['r', 'z'], 'time': ['0200', '1000', '1800', '2300'], 'levelist'...
def draw_scipy_ui(context: bpy.types.Context, layout: bpy.types.UILayout): numpy_is_installed = moduleutil.is_installed('numpy') scipy_is_installed = moduleutil.is_installed('scipy') col = layout.column(align=True) if scipy_is_installed: col.label(text='SciPy is already installed', icon='INFO') ...
class LevelModel(proteus.Transport.OneLevelTransport): nCalls = 0 def __init__(self, uDict, phiDict, testSpaceDict, matType, dofBoundaryConditionsDict, dofBoundaryConditionsSetterDict, coefficients, elementQuadrature, elementBoundaryQuadrature, fluxBoundaryConditionsDict=None, advectiveFluxBoundaryConditionsSet...
def anonymize_field(field: Dict[(str, Any)], named_schemas: NamedSchemas) -> Dict[(str, Any)]: parsed_field: Dict[(str, Any)] = {} if ('doc' in field): parsed_field['doc'] = _md5(field['doc']) if ('aliases' in field): parsed_field['aliases'] = [_md5(alias) for alias in field['aliases']] ...
class Conv2dBiasAct(Module): def __init__(self, op_name, in_channels, out_channels, kernel_size, stride, padding=0, dilation=1, groups=1, dtype='float16'): super().__init__() self.weight = Parameter(shape=[out_channels, kernel_size, kernel_size, (in_channels // groups)], dtype=dtype) self.bi...
def force_print(is_distributed: bool, *args, **kwargs) -> None: if is_distributed: try: device_info = f' [device:{torch.cuda.current_device()}]' print(*args, device_info, **kwargs, force=True) except TypeError: pass else: print(*args, **kwargs)
def to_rnn_dict_space_environment(env: str, rnn_steps: int) -> GymMazeEnv: env = GymMazeEnv(env=env) if (rnn_steps > 1): stack_config = [{'observation': 'observation', 'keep_original': False, 'tag': None, 'delta': False, 'stack_steps': rnn_steps}] env = ObservationStackWrapper.wrap(env, stack_co...
def test_perturbation_medium(): pp_real = td.ParameterPerturbation(heat=td.LinearHeatPerturbation(coeff=(- 0.01), temperature_ref=300, temperature_range=(200, 500))) pp_complex = td.ParameterPerturbation(heat=td.LinearHeatPerturbation(coeff=0.01j, temperature_ref=300, temperature_range=(200, 500)), charge=td.Li...
def _validate_wh_allocation(warehouse_allocation: WHAllocation): if (not warehouse_allocation): return so_codes = list(warehouse_allocation.keys()) so_item_data = frappe.db.sql('\n\t\t\tselect item_code, sum(qty) as qty, parent as sales_order\n\t\t\tfrom `tabSales Order Item`\n\t\t\twhere\n\t\t\t\tp...
def parse_args(cli_args): parser = argparse.ArgumentParser(description='Running sagemaker task') (args, unknowns) = parser.parse_known_args(cli_args) flyte_cmd = [] env_vars = {} i = 0 while (i < len(unknowns)): unknown = unknowns[i] logging.info(f'Processing argument {unknown}')...
class RealSupportDist(dist.Distribution): has_enumerate_support = False support = dist.constraints.real has_rsample = True arg_constraints = {} def rsample(self, sample_shape): return torch.zeros(sample_shape) def log_prob(self, value): return torch.zeros(value.shape)
def miller_loop(Q: Point2D[FQ12], P: Point2D[FQ12]) -> FQ12: if ((Q is None) or (P is None)): return FQ12.one() R = Q f = FQ12.one() for i in range(log_ate_loop_count, (- 1), (- 1)): f = ((f * f) * linefunc(R, R, P)) R = double(R) if (ate_loop_count & (2 ** i)): ...
class ComponentTestB(Component): name = 'test_b' my_int = DBField(default=1) my_list = DBField(default=[]) default_tag = TagField(default='initial_value') single_tag = TagField(enforce_single=True) multiple_tags = TagField() default_single_tag = TagField(default='initial_value', enforce_sing...
class SetVlanPcp(BaseModifyPacketTest): def runTest(self): actions = [ofp.action.set_field(ofp.oxm.vlan_pcp(2))] pkt = simple_tcp_packet(dl_vlan_enable=True, vlan_pcp=1) exp_pkt = simple_tcp_packet(dl_vlan_enable=True, vlan_pcp=2) self.verify_modify(actions, pkt, exp_pkt)
def plot_roc_auc(*, curr_roc_curve: dict, ref_roc_curve: Optional[dict], color_options: ColorOptions) -> List[Tuple[(str, BaseWidgetInfo)]]: additional_plots = [] cols = 1 subplot_titles = [''] current_color = color_options.get_current_data_color() reference_color = color_options.get_reference_data_...
def test_optional_prefix_re_cmd(testbot): testbot.bot_config.BOT_PREFIX_OPTIONAL_ON_CHAT = False assert ('bar' in testbot.exec_command('!plz dont match this')) testbot.bot_config.BOT_PREFIX_OPTIONAL_ON_CHAT = True assert ('bar' in testbot.exec_command('!plz dont match this')) assert ('bar' in testbo...
def record(oid, tag, value, **context): if ('dbConn' in moduleContext): db_conn = moduleContext['dbConn'] else: raise error.SnmpsimError('variation module not initialized') db_table = moduleContext['dbTable'] if context['stopFlag']: raise error.NoDataNotification() sql_oid = ...
() class _LiteDRAMPatternChecker(Module, AutoCSR): def __init__(self, dram_port, init=[]): (ashift, awidth) = get_ashift_awidth(dram_port) self.start = Signal() self.done = Signal() self.ticks = Signal(32) self.errors = Signal(32) self.run_cascade_in = Signal(reset=1)...
class OperatorListView(OperatorAbstractView): def __init__(self, obj, filter_func=None): assert isinstance(obj, list) obj = RdyToFlattenList(obj) super(OperatorListView, self).__init__(obj, filter_func) def combine_related(self, field_name): f = self._fields[field_name] r...
class UtilityFuncs(): def selHierarchy(root): pm.select(root, hi=1) return pm.ls(sl=1) def renameHierarchy(hierarchy, name): for s in hierarchy: pm.rename(s, (name + '#')) return hierarchy def duplicateObject(object): dup = pm.duplicate(object) ret...
class LeadGenPostSubmissionCheckResult(AbstractObject): def __init__(self, api=None): super(LeadGenPostSubmissionCheckResult, self).__init__() self._isLeadGenPostSubmissionCheckResult = True self._api = api class Field(AbstractObject.Field): api_call_result = 'api_call_result' ...
class DualQuaternionOperations(unittest.TestCase): def test_addition(self): qr_1 = Quaternion(1.0, 2.0, 3.0, 4.0) qt_1 = Quaternion(1.0, 3.0, 3.0, 0.0) dq_1 = DualQuaternion(qr_1, qt_1) qr_2 = Quaternion(3.0, 5.0, 3.0, 2.0) qt_2 = Quaternion((- 4.0), 2.0, 3.0, 0.0) dq...
class OptionSeriesPyramid3dMarker(Options): def enabled(self): return self._config_get(None) def enabled(self, flag: bool): self._config(flag, js_type=False) def enabledThreshold(self): return self._config_get(2) def enabledThreshold(self, num: float): self._config(num, j...
_init.register_param_type class param_supported_addr(param): _VALUE_STR = '!H' _VALUE_LEN = struct.calcsize(_VALUE_STR) def param_type(cls): return PTYPE_SUPPORTED_ADDR def __init__(self, value=None, length=0): if (not isinstance(value, list)): value = [value] for one...
class OptionSeriesPolygonStatesSelectHalo(Options): def attributes(self): return self._config_get(None) def attributes(self, value: Any): self._config(value, js_type=False) def opacity(self): return self._config_get(0.25) def opacity(self, num: float): self._config(num, j...
class OptionSeriesOrganizationStatesSelect(Options): def animation(self) -> 'OptionSeriesOrganizationStatesSelectAnimation': return self._config_sub_data('animation', OptionSeriesOrganizationStatesSelectAnimation) def borderColor(self): return self._config_get('#000000') def borderColor(self...
def get_segment_vafs(variants, segments): if segments: chunks = variants.by_ranges(segments) else: chunks = [(None, variants)] for (seg, seg_snvs) in chunks: freqs = seg_snvs['alt_freq'].values idx_above_mid = (freqs > 0.5) for idx_vaf in (idx_above_mid, (~ idx_above_...
_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestCustomCheckListEditor(BaseTestMixin, unittest.TestCase): def setUp(self): BaseTestMixin.setUp(self) def tearDown(self): BaseTestMixin.tearDown(self) def setup_gui(self, model, view): with create_ui(model, dict(view=view)) as ui: ...
def check_heading_slug_func(inst: 'MdParserConfig', field: dc.Field, value: Any) -> None: if (value is None): return if isinstance(value, str): try: (module_path, function_name) = value.rsplit('.', 1) mod = import_module(module_path) value = getattr(mod, funct...
class _DummyService(BaseService): service_name = 'dummy' def __init__(self, exec_args, *args, **kwargs): super().__init__(*args, exec_args=exec_args, timeout=10, **kwargs) def start(self): assert (self._proc is not None) self._proc.start() def join(self): self.wait()
def test_session_edit_locked_allow_organizer(db, client, user, jwt): session = get_session(db, user, event_owner=True, is_locked=True) data = json.dumps({'data': {'type': 'session', 'id': str(session.id), 'attributes': {'title': 'Sheesha'}}}) response = client.patch(f'/v1/sessions/{session.id}', content_typ...
('config_type', ['strict']) def test_missing_envs_not_required_in_strict_mode(config, json_config_file_3): with open(json_config_file_3, 'w') as file: file.write(json.dumps({'section': {'undefined': '${UNDEFINED}'}})) config.from_json(json_config_file_3, envs_required=False) assert (config.section.u...