code
stringlengths
281
23.7M
class ForwardingRule(object): def __init__(self, project_id, resource_id, full_name, creation_timestamp, name, description, region, ip_address, ip_protocol, port_range, ports, target, self_link, load_balancing_scheme, subnetwork, network, backend_service, raw_json): self.project_id = project_id self...
class TestLCh(util.ColorAssertsPyTest): COLORS = [('red', 'color(--lch 54.291 106.84 40.858)'), ('orange', 'color(--lch 75.59 83.769 70.824)'), ('yellow', 'color(--lch 97.607 94.712 99.572)'), ('green', 'color(--lch 46.278 67.984 134.38)'), ('blue', 'color(--lch 29.568 131.2 301.36)'), ('indigo', 'color(--lch 19.71...
class Neighbor(Command): help_msg = 'show neighbor information' command = 'neighbor' subcommands = {'summary': NeighborSummary, 'sent-routes': SentRoutes, 'received-routes': ReceivedRoutes} fmtstr = ' {0:<12s} {1:<12s} {2:<}\n' def action(self, params): core_service = self.api.get_core_servi...
class TaxService(QuickbooksBaseObject, UpdateMixin): list_dict = {'TaxRateDetails': TaxRateDetails} qbo_object_name = 'TaxService/Taxcode' def __init__(self): super(TaxService, self).__init__() self.TaxCode = None self.TaxCodeId = None self.Id = 0 self.TaxRateDetails ...
class OptionPlotoptionsErrorbarSonificationContexttracksMappingHighpassResonance(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, tex...
class WafTagsResponseAllOf(ModelNormal): allowed_values = {} validations = {} _property def additional_properties_type(): lazy_import() return (bool, date, datetime, dict, float, int, list, str, none_type) _nullable = False _property def openapi_types(): lazy_import()...
class Solution(): def rotate(self, matrix: List[List[int]]) -> None: if (not matrix): return (start, end) = (0, (len(matrix[0]) - 1)) while (start <= end): for index in range(start, end): index2 = ((end - index) + start) tmp = matrix[st...
def load_sonar_dataset(data_dir='data/'): url = ' data_path = os.path.join(data_dir, 'sonar.csv') if (not os.path.exists(data_dir)): os.makedirs(data_dir) if (not os.path.exists(data_path)): urllib.request.urlretrieve(url, data_path) df = pandas.read_csv(data_path, header=None) a...
(cls=ClickAliasedCommand, help=cmd_help, short_help=cmd_short_help, alias='u') ('-n', '--no-interaction', help='Do not ask any interactive question.', is_flag=True) ('-p', '--pretend', help='Run but do not make any changes.', is_flag=True) ('--use-version', help='The branch, tag or commit ID to checkout after clone.', ...
(malformed_type_strs) ('address20') def test_get_abi_strategy_returns_no_strategy_for_invalid_type_strs(malformed_type_str): try: get_abi_strategy(malformed_type_str) except (ParseError, NoEntriesFound, ValueError): pass else: raise AssertionError('Expected ParseError or NoEntriesFou...
def init(saved_lang): locale = QtCore.QLocale.system() lang = locale.name() if saved_lang: lang = saved_lang i18n_path = __get_i18n_path() print('Loading translations:', i18n_path, 'locale:', lang) translator = QtCore.QTranslator() translator.load((((((i18n_path + '/') + lang) + '/op...
class TestStringEval(unittest.TestCase): def test_eval_strings(self): input_data = ['this string is useful', 'garbage n$%Schtz', '/an/interesting/directory'] result = eval_strings(input_data) assert (result == ['/an/interesting/directory', 'this string is useful', 'garbage n$%Schtz']) de...
def test_check_or_select_variables(): input_df = pd.DataFrame({'words': ['dog', 'dig', 'cat'], 'animals': [1, 2, np.nan]}) enc = MockClassFit(ignore_format=False) assert (enc._check_or_select_variables(input_df) == ['words']) enc = MockClassFit(ignore_format=True) assert (enc._check_or_select_variab...
class ToMini(): _node_to_mini_node: Dict[(bn.BMGNode, MiniNode)] _observed_constants: int _queries: int _mini_nodes: List[MiniNode] def __init__(self) -> None: self._node_to_mini_node = {} self._observed_constants = 0 self._queries = 0 self._mini_nodes = [] def to...
def extractMxnhwuWordpressCom(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, tl_type) in...
class AgencyBase(APIView): params_to_validate: List[str] additional_models: dict def _validate_params(self, param_values, params_to_validate=None): params_to_validate = (params_to_validate or getattr(self, 'params_to_validate', [])) additional_models = getattr(self, 'additional_models', []) ...
class OptionSeriesErrorbarSonificationDefaultinstrumentoptionsMappingVolume(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: st...
class ColourList(): values = None python_type = 'List[str]' yaml_type = 'ColourList' json_schema = {'type': 'array', 'items': {'$ref': 'definitions.json#/definitions/colour'}} def __init__(self, param): self._param = param assert (param._defs.get('default') == 'stringarray()'), param...
class ModuleList(Module): _modules: Dict[(str, Module)] def __init__(self, modules: Optional[Iterable[Module]]=None) -> None: super(ModuleList, self).__init__() if (modules is not None): self += modules def _get_abs_string_index(self, idx): idx = operator.index(idx) ...
class IsolateLogPrinter(): debug: bool def __init__(self, debug: bool=False) -> None: self.debug = debug def print(self, log: Log): if ((log.level < LogLevel.INFO) and (not self.debug)): return level = str(log.level) if hasattr(log, 'timestamp'): times...
class CodeNodeSerializer(AbstractSyntaxTreeNodeSerializer): def serialize(self, node: CodeNode) -> Dict: data = super().serialize(node) data.update({'instructions': [self._pseudo.serialize(instruction) for instruction in node.instructions]}) return data def deserialize(self, data: dict) ...
def get_compare_questions(a_questions, b_questions): a_questions = {a['id']: a for a in a_questions} b_questions = {b['id']: b for b in b_questions} for (id_, a) in a_questions.items(): if (id_ not in b_questions): continue question = {**a['input'], 'id': id_, 'A': a['output'], '...
class ExperimentConfig(): builder: builders.ActorLearnerBuilder network_factory: NetworkFactory environment_factory: types.EnvironmentFactory max_num_actor_steps: int seed: int policy_network_factory: Optional[DeprecatedPolicyFactory] = None evaluator_factories: Optional[Sequence[EvaluatorFa...
class BaseFatetell(GenericAction): type: str def __init__(self, target, cond): self.source = target self.target = target self.cond = cond self.initiator = self.game.hybrid_stack[(- 1)] self.card_manipulator = self def apply_action(self): g = self.game ...
def parse_oozie_default_args(): return Namespace(cluster_base_name=None, cluster_depends_on_past=False, cluster_name_suffix=None, cluster_num_workers=128, cluster_project_id='my-project', cluster_region='us-central1', cluster_wait_for_downstream=False, dag_concurrency=16, dag_disable_catchup=False, dag_max_active_r...
class StatusPayloadFactory(factory.Factory): class Meta(): model = StatusPayload version = LESProtocolV2.version network_id = MAINNET_NETWORK_ID head_td = GENESIS_DIFFICULTY head_hash = MAINNET_GENESIS_HASH head_number = GENESIS_BLOCK_NUMBER genesis_hash = MAINNET_GENESIS_HASH se...
class ReadFontInfoVersion1TestCase(unittest.TestCase): def setUp(self): self.dstDir = tempfile.mktemp() os.mkdir(self.dstDir) metaInfo = {'creator': 'test', 'formatVersion': 1} path = os.path.join(self.dstDir, 'metainfo.plist') with open(path, 'wb') as f: plistlib...
def test_new_file_dir(): fd = FlyteDirectory(path='s3://my-bucket') assert (fd.sep == '/') inner_dir = fd.new_dir('test') assert (inner_dir.path == 's3://my-bucket/test') fd = FlyteDirectory(path='s3://my-bucket/') inner_dir = fd.new_dir('test') assert (inner_dir.path == 's3://my-bucket/test...
.parametrize('name, content_var', FILES.items()) def test_python_virtualenv(tmpdir, name, content_var): if nodeenv.is_WIN: bin_dir = tmpdir.join('Scripts') else: bin_dir = tmpdir.join('bin') bin_dir.mkdir() for n in FILES: bin_dir.join(n).write(n) with mock.patch.object(sys, ...
(IPythonShell) class PythonShell(MPythonShell, LayoutWidget): command_executed = Event() key_pressed = Event(KeyPressedEvent) def __init__(self, parent=None, **traits): create = traits.pop('create', None) super().__init__(parent=parent, **traits) if create: self.create() ...
class OptionPlotoptionsPyramidSonificationDefaultinstrumentoptionsMappingTime(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 ViewAction(): inline_actions: Optional[List[Union[(str, Callable)]]] = ['view_action'] def view_action(self, request, obj, parent_obj=None): url = reverse('admin:{}_{}_change'.format(obj._meta.app_label, obj._meta.model_name), args=(obj.pk,)) return redirect(url) view_action.short_desc...
class WebhookLogRepository(BaseRepository[WebhookLog], UUIDRepositoryMixin[WebhookLog]): model = WebhookLog async def get_by_id_and_webhook(self, id: uuid.UUID, webhook: uuid.UUID) -> (WebhookLog | None): statement = select(WebhookLog).where((WebhookLog.id == id), (WebhookLog.webhook_id == webhook)) ...
class Migration(migrations.Migration): dependencies = [('objects', '0010_auto__1820')] operations = [migrations.AlterField(model_name='objectdb', name='db_sessid', field=models.CharField(help_text='csv list of session ids of connected Account, if any.', max_length=32, null=True, validators=[django.core.validato...
class TestAxInvalidCastChoice(): def test_invalid_cast_choice(self, monkeypatch): with monkeypatch.context() as m: m.setattr(sys, 'argv', ['', '--config', './tests/conf/yaml/test_hp_cast.yaml']) ax_config = AxTunerConfig(name='Basic Test', minimize=False, objective_name='None', verbo...
class TransferModel(Base): __tablename__ = 'transfers' block_number = Column(Numeric, nullable=False) transaction_hash = Column(String, primary_key=True) trace_address = Column(ARRAY(Integer), nullable=False) protocol = Column(String, nullable=True) from_address = Column(String, nullable=False) ...
def test(): n = Network((LATENCY * 2)) nodes = [Node(n, i, ((i % 4) == 0)) for i in range(20)] for i in range(30): for _ in range(2): z = random.randrange(20) n.send_to([(1000 + i)], z, at=(5 + (i * 2))) for i in range((21 * LATENCY)): n.tick() if ((i % 10...
class TaskCollection(object): task_type_to_cls = {'manual_fetch': ManualFetchTask, 'manual_fetch_skip_for_now': ManualFetchTask, 'auto_fetch': AutoFetchTask, 'convert': ConvertTask, 'import': ImportTask, 'post_process': PostProcessTask} def __init__(self, task_data=None, ordered=False, task_type=None): ...
class StepStatsRenderer(): def render_stats(episode_event_log: EpisodeEventLog, event_name: str='BaseEnvEvents.reward', group_by: Optional[str]=None, aggregation_func: Optional[Callable]=None, metric: str='value', cumulative: bool=True): events = defaultdict(list) group_by_values = set() for...
class XCalExporter(): def __init__(self): pass def export(event_id): event = Event.query.get(event_id) i_calendar_node = Element('iCalendar') i_calendar_node.set('xmlns:xCal', 'urn:ietf:params:xml:ns:xcal') v_calendar_node = SubElement(i_calendar_node, 'vcalendar') ...
class TestURLFuzzer(unittest.TestCase): def setUp(self): self.TestHost = Host self.TestHost.create_host_dir_and_set_file_logger = (lambda _: None) self.TestFuzzer = URLFuzzer self.TestFuzzer.get_log_file_path = (lambda _, __: SystemOutLogger()) self.loop = asyncio.get_event_l...
def latest_review_time(): if ah.user_settings['keep_log']: ah.log.debug('Begin function') out = mw.col.db.scalar('select max(id/1000) from revlog') if (out is None): out = intTime() if ah.user_settings['keep_log']: ah.log.debug(('End function returning: %s (%s)' % (out, prettyTim...
def search_view(request): if ('q' in request.GET): form = SearchForm(request.GET) if form.is_valid(): search_params = form.cleaned_data max_results_per_obj_type = (search_params.pop('max_results_per_obj_type') or 10) results = search(**search_params) _...
class OptionSeriesHistogramSonificationContexttracksMappingHighpass(Options): def frequency(self) -> 'OptionSeriesHistogramSonificationContexttracksMappingHighpassFrequency': return self._config_sub_data('frequency', OptionSeriesHistogramSonificationContexttracksMappingHighpassFrequency) def resonance(s...
def extractEvelantranslationsWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('God of Thunder', 'God of Thunder', 'translated')] for (tagname, name, tl_type) in ...
class TlsBulkCertificatesResponse(ModelComposed): allowed_values = {} validations = {} _property def additional_properties_type(): lazy_import() return (bool, date, datetime, dict, float, int, list, str, none_type) _nullable = False _property def openapi_types(): lazy...
class LinuxFirewall(Firewall): def __init__(self, device, config): super().__init__(device, config) self._connector_helper = ConnectorHelper(self._device) self._testing_chain_name = ('xv_leak_testing_' + ''.join((random.choice(string.ascii_uppercase) for _ in range(8)))) self._create...
class TestDataMapperRegistryPopulation(unittest.TestCase, BaseRegistryPopulationTests): def get_registered_items(self): from d2go.data.dataset_mappers import D2GO_DATA_MAPPER_REGISTRY return [k for (k, v) in D2GO_DATA_MAPPER_REGISTRY] def import_all_modules(self): import d2go.data.datase...
def get_control_tabs(config): tabs = [] for car in config.myp.vehicles_list: if (car.label is None): label = car.vin else: label = car.label myp: PSAClient = config.myp el = [] buttons_row = [] if (car.status is not None): cards...
class AsyncCursorProxy(wrapt.ObjectProxy): provider_name = None DML_QUERIES = ('INSERT', 'DELETE', 'UPDATE') def __init__(self, wrapped, destination_info=None): super(AsyncCursorProxy, self).__init__(wrapped) self._self_destination_info = (destination_info or {}) async def callproc(self,...
class BaseProxyPeer(Service): def __init__(self, session: SessionAPI, event_bus: EndpointAPI) -> None: self.logger = get_logger('trinity.protocol.common.BaseProxyPeer') self.event_bus = event_bus self.session = session def __str__(self) -> str: return f'{self.__class__.__name__} ...
def validate_rlp_equal(obj_a: BaseBlock, obj_b: BaseBlock, obj_a_name: str=None, obj_b_name: str=None) -> None: if (obj_a == obj_b): return if (obj_a_name is None): obj_a_name = (obj_a.__class__.__name__ + '_a') if (obj_b_name is None): obj_b_name = (obj_b.__class__.__name__ + '_b') ...
(schema=bodhi.server.schemas.SaveReleaseSchema(), permission='admin', renderer='json', error_handler=bodhi.server.services.errors.json_handler, validators=(colander_body_validator, validate_tags, validate_enums, validate_eol_date)) def save_release(request): data = request.validated edited = data.pop('edited', ...
class FaucetUntaggedNSLoopTest(FaucetUntaggedTest): CONFIG_GLOBAL = ('\nacls:\n nsonly:\n - rule:\n dl_type: %u\n ip_proto: 58\n icmpv6_type: 135\n actions:\n allow: 1\n - rule:\n actions:\n allow: 0\nvlans:\n 1...
class SparkChiSquare(SparkStatTestImpl): base_stat_test = chi_stat_test def __call__(self, data: SpartStatTestData, feature_type: ColumnType, threshold: float) -> StatTestFuncReturns: cur = data.current_data ref = data.reference_data column_name = data.column_name from scipy.stat...
def extractBruinTranslation(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())): return None if (not item['title']): return False if ((item['tags'] == ['Uncategorized']) and item['title...
.usefixtures('use_tmpdir') def test_that_spaces_in_forward_model_args_are_dropped(): test_config_file_name = 'test.ert' test_config_contents = dedent('\n NUM_REALIZATIONS 1\n FORWARD_MODEL ECLIPSE100(<VERSION>=smersion , <NUM_CPU>=42)\n ') with open(test_config_file_...
() ('--reloader/--no-reloader', default=None) ('--debug/--no-debug', default=None) ('--host', default=None) ('--port', default=None) _app def runserver(app=None, reloader=None, debug=None, host=None, port=None): debug = (debug or app.config.get('DEBUG', False)) reloader = (reloader or app.config.get('RELOADER',...
class TestDisabledLinenums(util.MdCase): extension = ['pymdownx.highlight', 'pymdownx.superfences'] extension_configs = {'pymdownx.highlight': {'linenums': False}} def test_global_disable(self): self.check_markdown('\n ```python linenums="1"\n import test\n test.test...
class IntegratedHingeBox(Boxes): ui_group = 'Box' def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings) self.addSettingsArgs(edges.ChestHingeSettings) self.buildArgParser('x', 'y', 'h', 'outside') self.argparser.add_argument('--l...
def choice(values, weights=None, _randomstate_lambda=None): def decorator(func): (func) _synthetic() def decorator_inner(self, *args, **kw): randomstate = __get_random_state(self, _randomstate_lambda) value = randomstate.choice(values, p=weights) return fu...
def _load_config(project_path: Path) -> Dict: path = _get_project_config_path(project_path) if (path is None): return {} with path.open() as fp: if (path.suffix in ('.yaml', '.yml')): return (yaml.safe_load(fp) or {}) raw_json = fp.read() valid_json = re.sub('\\/\\/[^...
('pyscf') .parametrize('precon_update, ref_cycles', [(1, 14), (5, 15), (10, 19)]) def test_precon_update(precon_update, ref_cycles): geom = geom_loader('lib:h2o_shaken.xyz') calc = PySCF(basis='sto3g') geom.set_calculator(calc) opt_kwargs = {'thresh': 'gau_tight', 'max_cycles': 100, 'precon_update': pre...
class Brightness(Filter): NAME = 'brightness' ALLOWED_SPACES = ('srgb-linear', 'srgb') def filter(self, color: Color, amount: (float | None), **kwargs: Any) -> None: amount = alg.clamp((1 if (amount is None) else amount), 0) for (e, c) in enumerate(color[:(- 1)]): color[e] = line...
def writeSave(): startData = 'True' save = open('chess.save', 'w') save.write(startData) save.write('\n') writeBoard(save) writeGlobal(save) writePiecesArrays(save) write_r_PiecesArrays(save) write_p_moves(save) write_firstPawns(save) save.write('\n') save.close()
.parametrize('calc_cls, calc_kwargs, ref_energy, ref_charges', [pytest.param(Gaussian16, {'route': 'BP86 def2SVP'}, (- 40.), ((- 0.195353), 0.048838, 0.048838, 0.048838, 0.048838), marks=using('gaussian16'))]) def test_parse_charges(calc_cls, calc_kwargs, ref_energy, ref_charges): geom = geom_loader('lib:methane_bp...
def test_livefootballscores_deprecated_font_colour(caplog): widget = qtile_extras.widget.LiveFootballScores(font_colour='ffffff') assert (caplog.record_tuples[0] == ('libqtile', logging.WARNING, 'The use of `font_colour` is deprecated. Please update your config to use `foreground` instead.')) assert (widget...
def _register_types(TYPE_REGISTER, component, cnames, func, space_only=True): name_split = func.__qualname__.split('.') cls_name = name_split[0] fn_name = name_split[1] entity_id = ((func.__module__ + '/') + cls_name) entry = ((func.__module__ + '/') + func.__qualname__) if space_only: f...
class OptionPlotoptionsAreaDatasorting(Options): def enabled(self): return self._config_get(None) def enabled(self, flag: bool): self._config(flag, js_type=False) def matchByName(self): return self._config_get(None) def matchByName(self, flag: bool): self._config(flag, js...
class King(Piece): def __init__(self, x, y, c): super().__init__(x, y, c) self.set_letter('K') def drag(self, new_p, pieces): if self.grabbed: (path, dist) = self.select_path((self.start_x, self.start_y), [[1, 1], [(- 1), 1], [1, 0], [0, 1]], new_p) path_len = mat...
_os(*metadata.platforms) def main(): masquerade = '/tmp/openssl' common.create_macos_masquerade(masquerade) common.log('Launching fake openssl commands to decode payload') common.execute([masquerade, '-out', '/tmp/test', 'enc', '-d'], timeout=10, kill=True) common.remove_file(masquerade)
def get_queue_stats(dp, waiters, port_no=None, queue_id=None, to_user=True): if (port_no is None): port_no = dp.ofproto.OFPP_ANY else: port_no = UTIL.ofp_port_from_user(port_no) if (queue_id is None): queue_id = dp.ofproto.OFPQ_ALL else: queue_id = UTIL.ofp_queue_from_use...
def extractWwwFringecapybaraCom(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, tl_type) ...
('prefix,override_type', [param('', OverrideType.CHANGE, id='change'), param('+', OverrideType.ADD, id='add'), param('++', OverrideType.FORCE_ADD, id='force_add'), param('~', OverrideType.DEL, id='del')]) ('value,expected_key,expected_value,expected_value_type', [param('key=value', 'key', 'value', ValueType.ELEMENT, id...
def setup_vertigo(camera): global vertigo_attr_name global vertigo_global_attr_name vertigo_loc = camera.attr(vertigo_attr_name).inputs()[0] z1 = vertigo_loc.tz.get() f1 = camera.focalLength.get() world_loc = pm.spaceLocator(n=(camera.name() + 'vertigo_space_loc#')) if (not camera.hasAttr(ve...
def run_reproducible_rollout(env: MazeEnv, pick_action: Callable, n_steps: int=100) -> List[ObservationType]: env.seed(1234) act_conv_spaces = dict() for (policy_id, policy_act_conv) in env.action_conversion_dict.items(): policy_space = policy_act_conv.space() policy_space.seed(1234) ...
class RMSPropGrafting(AdagradGrafting): def __init__(self, param, beta2: float=0.99, epsilon: float=1e-08, group: Optional[dist.ProcessGroup]=None, group_source_rank: int=0, dist_buffer: Optional[Tensor]=None, use_dtensor: bool=True, communication_dtype: CommunicationDType=CommunicationDType.DEFAULT): super...
def test_issue_26_v0_4_0(): sig = np.array(['0xff864d8f', '0xff86b76d', '0xff880f87']) fxp_sig = Fxp(sig) assert (fxp_sig[0] == (- 7975537)) assert (fxp_sig[1] == (- 7948435)) assert (fxp_sig[2] == (- 7860345)) fxp_sig = Fxp(sig, signed=False) assert (fxp_sig[0] == int('0xff864d8f', 16)) ...
def suppress(signal): def wrapper(function): def wrapped_function(self, *args, **kwargs): def on_event(sender, *args): sender.stop_emission_by_name(signal) return True handler_id = self.connect(signal, on_event) function(self, *args, **kwar...
class TestHostsResolver(tests.LimitedTestCase): def test_default_fname(self): hr = greendns.HostsResolver() assert os.path.exists(hr.fname) def test_readlines_lines(self): hr = _make_host_resolver() hr.hosts.write(b'line0\n') hr.hosts.flush() assert (list(hr._read...
class CmdWriteAsm(Cmd): keywords = ['writeasm', 'asm'] description = 'Writes assembler instructions to a specified memory address.' parser = argparse.ArgumentParser(prog=keywords[0], description=description, epilog=('Aliases: ' + ', '.join(keywords))) parser.add_argument('--dry', '-d', action='store_tru...
def convert_input_media_array(array): media = [] files = {} for input_media in array: if isinstance(input_media, types.InputMedia): media_dict = input_media.to_dict() if media_dict['media'].startswith('attach://'): key = media_dict['media'].replace('attach://'...
class version1(StdOutputParams, ExecutorTopicContinuum, CreateMakeDependencies): def __init__(self, oconfig): tracer.debug('Called.') StdOutputParams.__init__(self, oconfig) CreateMakeDependencies.__init__(self) self.__used_vcs_id = None def cmad_topic_continuum_pre(self, _): ...
def _resolve_model(obj): if (isinstance(obj, six.string_types) and (len(obj.split('.')) == 2)): (app_name, model_name) = obj.split('.') return apps.get_model(app_name, model_name) elif (inspect.isclass(obj) and issubclass(obj, models.Model)): return obj else: raise ValueError...
.django_db def test_messages_not_nested(client, monkeypatch, elasticsearch_award_index, awards_over_different_date_ranges): setup_elasticsearch_test(monkeypatch, elasticsearch_award_index) contract_type_list = all_award_types_mappings['contracts'] request_for_2015 = {'subawards': False, 'fields': ['Award ID...
def hc_worker(crack=None, hash_file=None, session=None, wordlist=None, outfile=None, hash_mode=1000, attack_mode=None, mask=None, rules=None, name=None, username=False, pot_path=None, restore=None, brain=True, mask_file=False, increment=False, increment_min=None, increment_max=None, speed=True, benchmark=False, benchma...
class TestAddCliOption(object): def cli(self): cli = argparse.ArgumentParser() rgbgradientv2.add_cli_option(cli, 'color0', {'label': 'Logo LED colors and effects', 'description': 'Set the colors and the effects of the logo LED', 'cli': ['-c', '--logo-color', '--foobar'], 'report_type': 3, 'command':...
def extractScarletMadness(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())): return None tagmap = [('Kanna The Godless; The Summoned Heretic Is A Scenario Breaker', 'Kanna no Kanna Itanshoukansha...
class TestDemoImageFile(unittest.TestCase): def test_description_contains_file_uri(self): with tempfile.NamedTemporaryFile() as file_obj: (dirname, basename) = os.path.split(file_obj.name) parent = DemoPath(name=dirname) image_node = DemoImageFile(parent=parent, name=base...
def send_recognized_voice(user_id, file, duration): if (duration <= 60): recognized_text = recognize(file.read()) subject = ('Voice: {}'.format(get_subject(recognized_text)) if recognized_text else 'Voice note to self') else: recognized_text = '' subject = 'Voice note to self' ...
class VariantTestCase(unittest.TestCase): ('This fails with a memory leak. Figure out if false positive.') def test_VARIANT_array(self): v = VARIANT() v.value = ((1, 2, 3), ('foo', 'bar', None)) self.assertEqual(v.vt, (VT_ARRAY | VT_VARIANT)) self.assertEqual(v.value, ((1, 2, 3)...
def set_chatroom_name(self, chatroomUserName, name): url = ('%s/webwxupdatechatroom?fun=modtopic&pass_ticket=%s' % (self.loginInfo['url'], self.loginInfo['pass_ticket'])) data = {'BaseRequest': self.loginInfo['BaseRequest'], 'ChatRoomName': chatroomUserName, 'NewTopic': name} headers = {'content-type': 'app...
class SimpleEditor(CustomEditor): orientation = wx.HORIZONTAL extra = 2 _dialog_ui = Instance('traitsui.ui.UI') def create_editor(self, parent, sizer): self._button = button = wx.Button(parent, (- 1), '') sizer.Add(button, 1, (wx.EXPAND | wx.LEFT), 5) button.Bind(wx.EVT_BUTTON, s...
class ColumnDriftParameter(ExcludeNoneMixin, TestParameters): stattest: str score: float threshold: float detected: bool column_name: Optional[str] = None def from_metric(cls, data: ColumnDataDriftMetrics, column_name: str=None): return ColumnDriftParameter(stattest=data.stattest_name, s...
.parametrize('python_version_enum, expected_image_string', [(PythonVersion.PYTHON_3_8, 'cr.flyte.org/flyteorg/flytekit:py3.8-latest'), (PythonVersion.PYTHON_3_9, 'cr.flyte.org/flyteorg/flytekit:py3.9-latest'), (PythonVersion.PYTHON_3_10, 'cr.flyte.org/flyteorg/flytekit:py3.10-latest')]) def test_defaults(python_version...
def send_email_ticket_sales_end_next_week(event, emails): action = MailType.TICKET_SALES_END_NEXT_WEEK mail = MAILS[action] settings = get_settings() tickets = [] for ticket in event.tickets: if (ticket.sales_ends_at.date() == (datetime.date.today() - datetime.timedelta(days=(- 7)))): ...
class Definition(Node): def __init__(self): super().__init__() self.n_docstring = None def set_docstring(self, n_docstring): assert isinstance(n_docstring, Docstring) self.n_docstring = n_docstring self.n_docstring.set_parent(self) def get_local_name(self): ra...
class ExportPanel(QWidget): updateExportButton = Signal(str, bool) runExport = Signal(dict) def __init__(self, parent=None): QWidget.__init__(self, parent) self.setMinimumWidth(500) self.setMinimumHeight(200) self._dynamic = False self.setWindowTitle('Export data') ...
class SocketCalc(Calculator): valid_requests = ('energy', 'forces', 'hessian') def __init__(self, *args, host='localhost', port=8080, **kwargs): super().__init__(*args, **kwargs) self.port = port self.host = host def listen_for(self, atoms, coords, request): request = request...
def all_platforms_message(): message = messaging.Message(notification=messaging.Notification(title='$GOOG up 1.43% on the day', body='$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.'), android=messaging.AndroidConfig(ttl=datetime.timedelta(seconds=3600), priority='normal', notification=messaging....