code
stringlengths
281
23.7M
class MenuButton(JsonDeserializable, JsonSerializable, Dictionaryable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) map = {'commands': MenuButtonCommands, 'web_app': MenuButtonWebApp, 'default': MenuButtonDefault} ...
class TestComparisons(unittest.TestCase): def test_instance(self): p1 = pathlib.Path('wcmatch') p2 = pypathlib.Path('wcmatch') self.assertTrue(isinstance(p1, pathlib.Path)) self.assertTrue(isinstance(p1, pypathlib.Path)) self.assertFalse(isinstance(p2, pathlib.Path)) ...
class OptionSeriesLollipopOnpoint(Options): def connectorOptions(self) -> 'OptionSeriesLollipopOnpointConnectoroptions': return self._config_sub_data('connectorOptions', OptionSeriesLollipopOnpointConnectoroptions) def id(self): return self._config_get(None) def id(self, text: str): ...
class TestOFPActionCopyTtlIn(unittest.TestCase): type_ = ofproto.OFPAT_COPY_TTL_IN len_ = ofproto.OFP_ACTION_HEADER_SIZE fmt = ofproto.OFP_ACTION_HEADER_PACK_STR buf = pack(fmt, type_, len_) c = OFPActionCopyTtlIn() def test_parser(self): res = self.c.parser(self.buf, 0) eq_(res....
def test_numbered_duplicates_returns_correct_items(): numbers = ['one', 'two', 'three', 'four'] for i in range(1000): sample = random.choices(numbers, k=7) result = _numbered_duplicates(sample) result_split = [num.rsplit('_', 1)[0] for num in result] assert (Counter(sample) == Co...
class stackoverflow_question__test_case(unittest.TestCase): def test_stackoverflow_question_(self): from benedict import benedict as bdict d = bdict({'ResponseMetadata': {'NOT IMPORTANT'}, 'hasMoreResults': True, 'marker': '{"NOT IMPORTANT"}', 'pipelineIdList': [{'id': 'df-0001', 'name': 'Blue'}, {'...
def parse_property_inetnum(block: str): match = re.findall(b'^inetnum:[\\s]*((?:\\d{1,3}\\.){3}\\d{1,3})[\\s]*-[\\s]*((?:\\d{1,3}\\.){3}\\d{1,3})', block, re.MULTILINE) if match: ip_start = match[0][0].decode('utf-8') ip_end = match[0][1].decode('utf-8') cidrs = iprange_to_cidrs(ip_start...
class Status(object): swagger_types = {'embedded': 'StatusEmbedded', 'links': 'StatusLinks', 'battery': 'Battery', 'doors_state': 'DoorsState', 'energy': 'list[Energy]', 'environment': 'Environment', 'ignition': 'Ignition', 'kinetic': 'Kinetic', 'last_position': 'Position', 'preconditionning': 'Preconditioning', 'p...
class TestSoupContains(util.TestCase): MARKUP = '\n <body>\n <div id="1">\n Testing\n <span id="2"> that </span>\n contains works.\n </div>\n </body>\n ' def test_contains(self): self.assert_selector(self.MARKUP, 'body span:-soup-contains(that)', ['2'], flags=util.HTML) def t...
def find_volume_mappers(): res = [] with suppress_vtk_warnings(): obj = tvtk.Object() obj.global_warning_display = False for name in dir(tvtk): if (('Volume' in name) and ('Mapper' in name)): try: klass = getattr(tvtk, name) ...
class SequenceTestCase(unittest.TestCase): def test_to_xml_method_is_working_properly(self): s = Sequence() s.duration = 109 s.name = 'previs_edit_v001' s.rate = Rate(timebase='24', ntsc=False) s.timecode = '00:00:00:00' m = Media() s.media = m v = Vid...
class OptionSeriesPolygonSonificationContexttracksMappingHighpassFrequency(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: str...
class Navigation(): def __init__(self, ui): self.page = ui.page def __format_text(self, text: Union[(str, dict)], size: str=None, italic: bool=True) -> str: if isinstance(text, dict): sub_title = self.page.ui.div(list(text.values())[0]) sub_title.options.managed = False ...
def test_traverse_attributes(): provider1 = providers.Object('bar') provider2 = providers.Object('baz') provider = providers.Factory(dict) provider.add_attributes(foo='foo', bar=provider1, baz=provider2) all_providers = list(provider.traverse()) assert (len(all_providers) == 2) assert (provi...
class OptionSeriesCylinderDataDatalabelsTextpath(Options): def attributes(self): return self._config_get(None) def attributes(self, value: Any): self._config(value, js_type=False) def enabled(self): return self._config_get(False) def enabled(self, flag: bool): self._confi...
def plot_lift_curve2(c_l_dict1, c_l_dict2, plot_range_deg=[(- 100), 100]): aoa_deg = np.linspace(plot_range_deg[0], plot_range_deg[1], num=((plot_range_deg[1] - plot_range_deg[0]) + 1)) aoa_rad = ((aoa_deg * math.pi) / 180) c_l_vec1 = np.zeros(aoa_deg.shape[0]) c_l_vec2 = np.zeros(aoa_deg.shape[0]) ...
def delete_saved_data(ctx, profile_id): files = list(ctx.obj.data_dir.rglob(f'{profile_id}*')) if (not files): click.echo('[*] No associated saved data found for configuration profile') elif click.confirm(f'[*] Do you want to delete the {len(files)} saved files associated with the configuration prof...
class TestNamedTraitObserverEqualHash(unittest.TestCase): def test_not_equal_notify(self): observer1 = NamedTraitObserver(name='foo', notify=True, optional=True) observer2 = NamedTraitObserver(name='foo', notify=False, optional=True) self.assertNotEqual(observer1, observer2) def test_not...
class TestPatchStorageConfig(): (scope='function') def url(self, oauth_client: ClientDetail) -> str: return (V1_URL_PREFIX + STORAGE_CONFIG) (scope='function') def payload(self): return [{'name': 'test destination', 'type': StorageType.s3.value, 'details': {'auth_method': S3AuthMethod.SE...
(EcsClient, '__init__') def test_is_deployed_if_no_tasks_should_be_running(client, service): client.list_tasks.return_value = RESPONSE_LIST_TASKS_0 action = EcsAction(client, CLUSTER_NAME, SERVICE_NAME) service[u'desiredCount'] = 0 is_deployed = action.is_deployed(service) assert (is_deployed is Tru...
class VLANHost(FaucetHost): intf_root_name = None vlans = None vlan_intfs = None def config(self, vlans=None, **params): super_config = super().config(**params) if (vlans is None): vlans = [100] self.vlans = vlans self.vlan_intfs = {} batch_cmds = [] ...
def test_adposition_complements(logfile): for (lemma, comps) in adposition_complements.items(): if (('left' not in comps) and ('right' not in comps) and ('poss' not in comps)): print_error_word_miss_context(lemma, '-1 / +1 COMP or 0 POSS', logfile) biggest = 0 total = 0 i...
class ModelAPITestCase(unittest.TestCase): def _get_simple_graph_and_output(self, test_name: str, dynamic_shape: bool=False, unsqueeze_output: bool=False) -> Tuple[(Model, Tuple[(torch.Tensor, torch.Tensor)], Tuple[(torch.Tensor, torch.Tensor)])]: target = detect_target() input_0 = Tensor(shape=[1],...
def get_capacity_dict_from_df(df_capacity: pd.DataFrame) -> dict[(str, Any)]: all_capacity = {} for zone in df_capacity.index.unique(): df_zone = df_capacity.loc[zone] zone_capacity = {} for (i, data) in df_zone.iterrows(): mode_capacity = {} mode_capacity['dateti...
class TestGraphInterface(): def nodes(self) -> List[BasicNode]: return [BasicNode(i) for i in range(10)] def test_equals(self, nodes): edges = [BasicEdge(nodes[0], nodes[1]), BasicEdge(nodes[1], nodes[2]), BasicEdge(nodes[2], nodes[3]), BasicEdge(nodes[2], nodes[1]), BasicEdge(nodes[1], nodes[4]...
def add_render_arguments(parser: argparse.ArgumentParser) -> None: parser.add_argument('-i', '--input', dest='input_file_names', metavar='<path>', nargs='*', help='input XML file name or names (if not specified, file will be downloaded using the OpenStreetMap API)') parser.add_argument('-o', '--output', dest='o...
def _upload(package_path: str, package_name: str, version: str) -> None: logger.info(f" Starting uploading package {package_name} at '{package_path}', version {version}...") logger.info(f'Uploading binary for package {package_name}: {version}') onedocker_repo_svc.upload(package_name, version, package_path) ...
def test_abi_deployment_enabled_by_default(network, build): network.connect('mainnet') address = '0x0bc529c00c6401aef6d220be8c6ea1667f6ad93e' Contract.from_abi('abiTester', address, build['abi']) assert (_get_deployment(address) != (None, None)) Contract.remove_deployment(address)
class Zones(SuperEnum): __keys__ = ['id', 'title', 'color', 'map_key', 'incr'] arctic_circle = (1, 'Artic Circle', (150, 150, 250), 'N', 0.6) northern_temperate = (2, 'Northern Temperate', (150, 250, 150), 'A', 0.9) northern_subtropics = (3, 'Nothern Subtropics', (150, 250, 200), 'B', 0.6) northern_...
.xfail(raises=ImageComparisonFailure, reason='Matplotlib plots for reasons a different image size.') def test_correlate_chromosomes(): outfile_heatmap = NamedTemporaryFile(suffix='heatmap.png', prefix='hicexplorer_test', delete=False) outfile_scatter = NamedTemporaryFile(suffix='scatter.png', prefix='hicexplore...
def _format_string_for_conversion(string_number: str) -> str: commas_occurences = [match.start() for match in re.finditer('\\,', string_number)] dot_occurences = [match.start() for match in re.finditer('\\.', string_number)] if ((len(commas_occurences) > 0) and (len(dot_occurences) > 0)): index_remo...
.asyncio .manager class TestVerifyUser(): async def test_invalid_token(self, user_manager: UserManagerMock[UserModel]): with pytest.raises(InvalidVerifyToken): (await user_manager.verify('foo')) async def test_token_expired(self, user_manager: UserManagerMock[UserModel], user: UserModel, ver...
def downgrade(): op.drop_column('users_events_roles', 'deleted_at') op.drop_column('user_permissions', 'deleted_at') op.drop_column('tickets', 'deleted_at') op.drop_column('ticket_tag', 'deleted_at') op.drop_column('ticket_holders', 'deleted_at') op.drop_column('sponsors', 'deleted_at') op.d...
class Invoice(DeleteMixin, QuickbooksPdfDownloadable, QuickbooksManagedObject, QuickbooksTransactionEntity, LinkedTxnMixin, SendMixin, VoidMixin): class_dict = {'DepartmentRef': Ref, 'CurrencyRef': Ref, 'CustomerRef': Ref, 'ClassRef': Ref, 'SalesTermRef': Ref, 'ShipMethodRef': Ref, 'DepositToAccountRef': Ref, 'Bill...
def test_delitem(fx_asset): with Image(filename=str(fx_asset.joinpath('apple.ico'))) as img: detached = img.sequence[0] del img.sequence[0] assert (len(img.sequence) == 3) assert (img.sequence[0] is not detached) assert (img.sequence[0].size == (16, 16)) expire(img) ...
def test_render_with_tooltips() -> None: run((COMMAND_LINES['render_with_tooltips'] + ['--cache', 'tests/data']), (LOG + b'INFO Writing output SVG to out/map.svg...\n')) with (OUTPUT_PATH / 'map.svg').open(encoding='utf-8') as output_file: root: Element = ElementTree.parse(output_file).getroot() ass...
def test_model_dialogues_keep_terminal_dialogues_option(): dialogues = DefaultDialogues(name='test', skill_context=Mock()) assert (DefaultDialogues._keep_terminal_state_dialogues == dialogues.is_keep_dialogues_in_terminal_state) dialogues = DefaultDialogues(name='test', skill_context=Mock(), keep_terminal_s...
def add_QueryServicer_to_server(servicer, server): rpc_method_handlers = {'Params': grpc.unary_unary_rpc_method_handler(servicer.Params, request_deserializer=cosmos_dot_mint_dot_v1beta1_dot_query__pb2.QueryParamsRequest.FromString, response_serializer=cosmos_dot_mint_dot_v1beta1_dot_query__pb2.QueryParamsResponse.S...
.django_db def test_award_endpoint_for_null_recipient_information(client, awards_and_transactions): resp = client.get('/api/v2/awards/3/', content_type='application/json') assert (resp.status_code == status.HTTP_200_OK) assert (json.loads(resp.content.decode('utf-8')).get('recipient') == recipient_without_i...
def parse_FMT21H(buffer, dex_object, pc_point, offset): (v,) = struct.unpack_from('H', buffer, 2) if (int(buffer[1]) == 25): arg1 = ('%d' % v) else: arg1 = ('%d0000' % v) return (dex_decode[int(buffer[0])][4], dex_decode[int(buffer[0])][1], ('v%d' % int(buffer[1])), arg1)
class ChatWithDbAutoExecute(BaseChat): chat_scene: str = ChatScene.ChatWithDbExecute.value() def __init__(self, chat_param: Dict): chat_mode = ChatScene.ChatWithDbExecute self.db_name = chat_param['select_param'] chat_param['chat_mode'] = chat_mode super().__init__(chat_param=cha...
def _start_local_worker(worker_manager: WorkerManagerAdapter, worker_params: ModelWorkerParameters): with root_tracer.start_span('WorkerManager._start_local_worker', span_type=SpanType.RUN, metadata={'run_service': SpanTypeRunName.WORKER_MANAGER, 'params': _get_dict_from_obj(worker_params), 'sys_infos': _get_dict_f...
.usefixtures('use_tmpdir', 'init_eclrun_config') .requires_eclipse def test_run(source_root): shutil.copy(os.path.join(source_root, 'test-data/eclipse/SPE1.DATA'), 'SPE1.DATA') econfig = ecl_config.Ecl100Config() erun = ecl_run.EclRun('SPE1.DATA', None) erun.runEclipse(eclrun_config=ecl_config.EclrunCon...
def typeof(data: Union[(primitives.JsDataModel, str)], type: Optional[Union[(primitives.JsDataModel, str)]]=None): if (type is None): return JsObjects.JsBoolean.JsBoolean(('typeof %s' % JsUtils.jsConvertData(data, None))) return JsObjects.JsVoid(('typeof %s === %s' % (JsUtils.jsConvertData(data, None), ...
class OptionSeriesStreamgraphDataDragdropGuideboxDefault(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 colo...
def test_create_load_object(monkeypatch): columns = {'input_field_1': 'output_field_1', 'input_field_2': 'output_field_2'} bools = {'input_field_3': 'output_field_3', 'input_field_4': 'output_field_4', 'input_field_5': 'output_field_5'} functions = {'output_field_6': (lambda t: (t['input_field_6'] * 2)), 'o...
class Geometric(Harmony): def __init__(self) -> None: self.count = 12 def harmonize(self, color: 'Color', space: str) -> List['Color']: color1 = self.get_cylinder(color, space) output = space space = color1.space() name = color1._space.hue_name() degree = current ...
def test_update_instructions_with_redundant(variable_x, variable_v, aliased_variable_y, variable): binary_operation = BinaryOperation(OperationType.plus, [aliased_variable_y[2], aliased_variable_y[3]]) instructions = [Assignment(ListOperation([]), Call(imp_function_symbol('printf'), [Constant()])), Assignment(v...
class BaseSQLAFilter(filters.BaseFilter): def __init__(self, column, name, options=None, data_type=None): super(BaseSQLAFilter, self).__init__(name, options, data_type) self.column = column def get_column(self, alias): return (self.column if (alias is None) else getattr(alias, self.colum...
class OptionsWidget(Gtk.Widget): def __init__(self, *args, **kwargs): super(OptionsWidget, self).__init__(*args, **kwargs) self._controller = None def controller(self): return self._controller def controller(self, controller): if self._controller: self._controller...
.asyncio .manager class TestCreateUser(): .parametrize('email', ['king.', 'King.']) async def test_existing_user(self, email: str, user_manager: UserManagerMock[UserModel]): user = UserCreate(email=email, password='guinevere') with pytest.raises(UserAlreadyExists): (await user_manage...
class ethernet(packet_base.PacketBase): _PACK_STR = '!6s6sH' _MIN_LEN = struct.calcsize(_PACK_STR) _MIN_PAYLOAD_LEN = 46 _TYPE = {'ascii': ['src', 'dst']} def __init__(self, dst='ff:ff:ff:ff:ff:ff', src='00:00:00:00:00:00', ethertype=ether.ETH_TYPE_IP): super(ethernet, self).__init__() ...
class _MethodProxy(): def __init__(self, value: Any, callable_value: Optional[Callable]=None) -> None: self.__dict__['_value'] = value self.__dict__['_callable_value'] = (callable_value or value) def __get__(self, instance: 'StrictMock', owner: Optional[Type['StrictMock']]=None) -> Union[(object...
class HTTPException(Exception): def __init__(self, status_code: int, detail: typing.Optional[str]=None, headers: typing.Optional[typing.Dict[(str, str)]]=None) -> None: if (detail is None): detail = self.status_code = status_code self.detail = detail self.headers = heade...
def handle_uploaded_file(import_file, request): logger.info('Uploaded file: %s', import_file) logger.info('File content type is: %s', import_file.content_type) if (import_file.content_type == 'text/csv'): return process_csv(import_file) elif ((import_file.content_type == 'application/vnd.openxml...
class EquilateralTriangleTest(unittest.TestCase): def test_all_sides_are_equal(self): self.assertIs(equilateral([2, 2, 2]), True) def test_any_side_is_unequal(self): self.assertIs(equilateral([2, 3, 2]), False) def test_no_sides_are_equal(self): self.assertIs(equilateral([5, 4, 6]), ...
class SubDecl(Decl): block: Block var: str def new(self): return (self.var, 'void()') def ok(self, block): return block.ok def block_same(self) -> (Block.same block): return [] def block_env(self, block) -> (Block.env block): return {**self.env, **block.procs} ...
def planSlantAxis(glyphSetFunc, axisLimits, slants=None, samples=None, glyphs=None, designLimits=None, pins=None, sanitize=False): if (slants is None): slants = SLANTS return planAxis(measureSlant, normalizeDegrees, interpolateLinear, glyphSetFunc, 'slnt', axisLimits, values=slants, samples=samples, gly...
def test_multiple_register_pairs_are_handled_correctly(): cfg = ControlFlowGraph() (eax, ebx, a, b) = ((lambda x, name=name: Variable(name, Integer.int32_t(), ssa_label=x)) for name in ['eax', 'ebx', 'a', 'b']) (v0, v1) = ((lambda name=name: Variable(name, Integer.int64_t(), ssa_label=0)) for name in ['loc_...
class LaunchChannel(ChannelInterface): mtimes = Signal(str, float, dict) changed_binaries = Signal(str, dict) launch_nodes = Signal(str, list) def __init__(self): ChannelInterface.__init__(self) self._args_lock = threading.RLock() self._cache_file_includes = {} self._cach...
def metadata_manager_with_teardown(jp_environ): metadata_manager = MetadataManager(schemaspace=ComponentCatalogs.COMPONENT_CATALOGS_SCHEMASPACE_ID) (yield metadata_manager) try: if metadata_manager.get(TEST_CATALOG_NAME): metadata_manager.remove(TEST_CATALOG_NAME) except Exception: ...
class ConnectionPool(): _shared_state = {} _db_max_connections = 50 def __init__(self): self.__dict__ = self._shared_state if (not hasattr(self, 'connected')): print('Database connection pool init!') try: self.dbPool = psycopg2.pool.ThreadedConnectionP...
def test_get_local_addr_with_socket(): transport = MockTransport({'socket': MockSocket(family=socket.AF_IPX)}) assert (get_local_addr(transport) is None) transport = MockTransport({'socket': MockSocket(family=socket.AF_INET6, sockname=('::1', 123))}) assert (get_local_addr(transport) == ('::1', 123)) ...
def get_link_tag(box): shift = (box[2] / 8) shift_box = ((box[0] + shift), (box[1] + shift), (box[2] - (shift * 2)), (box[3] - (shift * 2))) square_left = np.array((shift_box[0], (shift_box[1] + ((shift_box[3] - (shift_box[2] / 2)) / 2)), (shift_box[2] / 2), (shift_box[2] / 2))) square_right = np.array(...
def _clean_header(header: HeaderType) -> Dict[(str, Any)]: if isinstance(header, str): header = {'description': header} typedef = header.get('type', 'string') if (typedef in PY_TYPES): header['type'] = PY_TYPES[typedef] elif (isinstance(typedef, (list, tuple)) and (len(typedef) == 1) and...
class OptionSeriesBubbleLabelStyle(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(text, js_...
class FileThread(Thread): def __init__(self): super().__init__() def run(self): while 1: if record.namelist: pross = record.namelist.pop(0) img2 = cv2.imread(pross) record.videoWriter.write(img2) os.remove(pross) ...
def _date_fix(tags): tags = copy.deepcopy(tags) for t in ['__date_added', '__last_played', '__modified']: if (t in tags): try: dt = datetime.datetime.fromtimestamp(tags[t]) tags[t] = dt.strftime('%Y-%m-%d %H:%M:%S') except: pass ...
.parametrize('type_str, encoder_class, decoder_class', (('address', encoding.AddressEncoder, decoding.AddressDecoder), ('bool', encoding.BooleanEncoder, decoding.BooleanDecoder), ('bytes12', encoding.BytesEncoder, decoding.BytesDecoder), ('function', encoding.BytesEncoder, decoding.BytesDecoder), ('bytes', encoding.Byt...
def get_ec2_ondemand_instances_prices(filter_region=None, filter_instance_type=None, filter_instance_type_pattern=None, filter_os_type=None, use_cache=False, cache_class=SimpleResultsCache): urls = [INSTANCES_ON_DEMAND_LINUX_URL, INSTANCES_ON_DEMAND_RHEL_URL, INSTANCES_ON_DEMAND_SLES_URL, INSTANCES_ON_DEMAND_WINDOW...
class DomoTestClient(): def __init__(self, domo_token, domo_connection_config: ConnectionConfig): self.domo_secrets = domo_connection_config.secrets self.headers = {'Content-Type': 'application/json', 'Authorization': f'Bearer {domo_token}'} self.base_url = f" def create_user(self, email...
class WebDavXmlUtils(): def __init__(self): pass def parse_get_list_info_response(content): try: tree = etree.fromstring(content) infos = [] for response in tree.findall('.//{DAV:}response'): href_el = next(iter(response.findall('.//{DAV:}href'...
(help=dict(clean='clear the doc output; start fresh', build='build html docs', show='show the docs in the browser.')) def docs(ctx, clean=False, build=False, show=False, **kwargs): if (not (clean or build or show)): sys.exit('Task "docs" must be called with --clean, --build or --show') if clean: ...
(params=['foo', '$key', '$value']) def initquery(request): ref = db.Reference(path='foo') if (request.param == '$key'): return (ref.order_by_key(), request.param) if (request.param == '$value'): return (ref.order_by_value(), request.param) return (ref.order_by_child(request.param), reque...
class OSDisplay(BaseDisplay): def __init__(self, **args): try: copy_docstr(BaseDisplay, OSDisplay) except: pass self.experiment = settings.osexperiment self.canvas = canvas(self.experiment) self.dispsize = self.experiment.resolution() def show(self...
class MedicationRequest(ServiceRequestController): def on_update_after_submit(self): self.validate_invoiced_qty() def set_title(self): if (frappe.flags.in_import and self.title): return self.title = f'{self.patient_name} - {self.medication}' def before_insert(self): ...
def _fullscreen_to_file(filename: Union[(os.PathLike, str)]) -> None: if (not QtDBus): raise ModuleNotFoundError('QtDBUS not available.') screenshot_interface = _get_screenshot_interface() if screenshot_interface.isValid(): result = screenshot_interface.call('Screenshot', True, False, filena...
def post_upgrade(from_ver, to_ver, bench_path='.'): from bench.bench import Bench from bench.config import redis from bench.config.nginx import make_nginx_conf from bench.config.supervisor import generate_supervisor_config conf = Bench(bench_path).conf print((('-' * 80) + f'Your bench was upgrad...
class DataCandle(DataChart): def close(self): return self._attrs['close'] def close(self, val): self._attrs['close'] = val def high(self): return self._attrs['high'] def high(self, val): self._attrs['high'] = val def low(self): return self._attrs['low'] de...
def usage(): print('usage: vthunting.py [OPTION]') print(' -h, --help Print this help\n -r, --report Print the VT hunting report\n -s, --slack_report Send the report to a Slack channel\n -e, --email_report Send the report by email\n -t, --telegram_report Send t...
class SnmpSecurityLevel(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec subtypeSpec += ConstraintsUnion(SingleValueConstraint(*(1, 2, 3))) namedValues = NamedValues(*(('authNoPriv', 2), ('authPriv', 3), ('noAuthNoPriv', 1))) if mibBuilder.loadTexts: desc...
class CombineTest(unittest.TestCase): def test_merge(self): e1 = Event.sequence(array1, interval=0.01) e2 = Event.sequence(array2, interval=0.01).delay(0.001) event = e1.merge(e2) self.assertEqual(event.run(), [i for j in zip(array1, array2) for i in j]) def test_switch(self): ...
def extractUnderworldtranslateWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, name...
class TestSeriesFrameHist(TestData): def test_flight_delay_min_hist(self): pd_flights = self.pd_flights() ed_flights = self.ed_flights() num_bins = 10 pd_flightdelaymin = np.histogram(pd_flights['FlightDelayMin'], num_bins) pd_bins = pd.DataFrame({'FlightDelayMin': pd_flightd...
def check_old_links(app): usual_sites = ['github.com', 'gitlab.com', 'bitbucket.org'] old_sites = ['gitorious.org', 'code.google.com'] if any(((s in app.Repo) for s in usual_sites)): for f in ['WebSite', 'SourceCode', 'IssueTracker', 'Changelog']: v = app.get(f) if any(((s in...
def test_version_parsing(): for (pe_export_stamp, version_string) in version.PE_EXPORT_STAMP_TO_VERSION.items(): bversion = version.BeaconVersion(version_string) assert int(pe_export_stamp) assert bversion.date assert bversion.tuple assert bversion.version
def test_get_contract_factory_with_valid_escrow_manifest(w3): escrow_manifest = get_ethpm_spec_manifest('escrow', 'v3.json') escrow_package = w3.pm.get_package_from_manifest(escrow_manifest) escrow_factory = escrow_package.get_contract_factory('Escrow') assert escrow_factory.needs_bytecode_linking s...
def test_nl_tagger_return_char(NLP): text = 'hi Aaron,\r\n\r\nHow is your schedule today, I was wondering if you had time for a phone\r\ncall this afternoon?\r\n\r\n\r\n' doc = NLP(text) for token in doc: if token.is_space: assert (token.pos == SPACE) assert (doc[3].text == '\r\n\r\n...
def test_chat(browser, clear_log): browser.slow_click('#button1') browser.assert_text('Hello, WS1!', 'div.ws1', timeout=5) browser.assert_text('WS1 CONNECTED', 'div.sse', timeout=5) clear_log() browser.slow_click('#button2') browser.assert_text('Hello, WS2!', 'div.ws2', timeout=5) browser.as...
def test_feeder_set_hopper(client: TestClient, with_stored_recipe: None): from tests.test_database_models import SAMPLE_DEVICE_HID response = client.post(f'/api/v1/feeder/{SAMPLE_DEVICE_HID}/hopper', json={'level': 100}) assert (response.status_code == 200) response = client.get(f'/api/v1/feeder/{SAMPLE...
class CabinetHingeEdge(BaseEdge): char = 'u' description = 'Edge with cabinet hinges' def __init__(self, boxes, settings=None, top: bool=False, angled: bool=False) -> None: super().__init__(boxes, settings) self.top = top self.angled = angled self.char = 'uUvV'[(bool(top) + (...
def IKTargetDoRotateQuaternion(kwargs: dict) -> OutgoingMessage: compulsory_params = ['id', 'quaternion', 'duration'] optional_params = ['speed_based', 'relative'] utility.CheckKwargs(kwargs, compulsory_params) if ('speed_based' not in kwargs): kwargs['speed_based'] = True if ('relative' not...
def _CopyDebugger(target_dir, target_cpu): win_sdk_dir = SetEnvironmentAndGetSDKDir() if (not win_sdk_dir): return debug_files = [('dbghelp.dll', False), ('dbgcore.dll', True)] for (debug_file, is_optional) in debug_files: full_path = os.path.join(win_sdk_dir, 'Debuggers', target_cpu, de...
class OptionPlotoptionsScatter3dSonificationTracks(Options): def activeWhen(self) -> 'OptionPlotoptionsScatter3dSonificationTracksActivewhen': return self._config_sub_data('activeWhen', OptionPlotoptionsScatter3dSonificationTracksActivewhen) def instrument(self): return self._config_get('piano')...
def look_up_cognito_id(event_body): print('looking up cognito id...', event_body) try: response = cognito_client.admin_get_user(UserPoolId=os.environ['USER_POOL_ID'], Username=event_body['email']) except Exception as e: if (e.response['Error']['Code'] == 'UserNotFoundException'): ...
class PreviewWindow(HasTraits): _engine = Instance(Engine) _scene = Instance(SceneModel, ()) view = View(Item('_scene', editor=SceneEditor(scene_class=Scene), show_label=False), width=500, height=500) def add_source(self, src): self._engine.add_source(src) def add_module(self, module): ...
class Polynomial_GF256_int(Polynomial_GF256_base): def to_exp(self): return Polynomial_GF256_exp([(LOG[x] if x else None) for x in self]) def get_str(self): return ' + '.join((f'{n}x**{(len(self) - i)}' for (i, n) in enumerate(self, 1))) def copy_with_increased_degree(self, n): retur...
def writeSignificantHDF(pOutFileName, pSignificantDataList, pSignificantKeyList, pViewpointObj, pReferencePointsList, pArgs): significantFileH5Object = h5py.File(pOutFileName, 'w') significantFileH5Object.attrs['type'] = 'significant' significantFileH5Object.attrs['version'] = __version__ significantFil...
class TestsInit(unittest.TestCase): def setUpClass(cls): cls.path_for_test = (mpi.Path(__file__).parent / '../_transonic_testing/src/_transonic_testing/for_test_init.py') assert cls.path_for_test.exists() cls.path_backend = path_backend = ((cls.path_for_test.parent / f'__{backend_default}__'...
def get_unit_type(): if frappe.db.exists('Healthcare Service Unit Type', 'Inpatient Rooms'): return frappe.get_doc('Healthcare Service Unit Type', 'Inpatient Rooms') unit_type = frappe.new_doc('Healthcare Service Unit Type') unit_type.service_unit_type = 'Inpatient Rooms' unit_type.inpatient_occ...