code
stringlengths
281
23.7M
class Plugin(plugin.PluginProto): PLUGIN_ID = 211 PLUGIN_NAME = 'RFID - RC522' PLUGIN_VALUENAME1 = 'Tag' def __init__(self, taskindex): plugin.PluginProto.__init__(self, taskindex) self.dtype = rpieGlobals.DEVICE_TYPE_SPI self.vtype = rpieGlobals.SENSOR_TYPE_TEXT self.val...
class OptionSeriesWaterfallSonificationContexttracksMappingNoteduration(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 OptionSeriesColumnrangeSonificationContexttracksMappingTime(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 TestUpdateOtherFieldHook(unittest.TestCase): def setUp(self) -> None: self.obj_1 = DummyInstance('01', '//fbsource', 'Meta', 'PCI', None, 'Seattle', 6, 7, 8) self.obj_2 = DummyInstance('02', '//fbsource', 'Meta', 'PCI', 'west-1', None, 6, 7, 8, 3) def test(self) -> None: self._init...
class LocalMemory(BaseMemory): def __init__(self, embedding_provider: callable): super(BaseMemory, self).__init__() self.docs: List[str] = [] self.embs: Optional[np.ndarray] = None self.embedding_provider = embedding_provider def __len__(self): return len(self.docs) d...
def extractJstranslations1Com(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 FilterPopup(QDialog): filterSettingsChanged = Signal(dict) def __init__(self, parent, key_defs): QDialog.__init__(self, parent, ((Qt.WindowStaysOnTopHint | Qt.X11BypassWindowManagerHint) | Qt.FramelessWindowHint)) self.setVisible(False) self.filter_items = {} layout = QVBox...
class OptionPlotoptionsPolygonZones(Options): def className(self): return self._config_get(None) def className(self, text: str): self._config(text, js_type=False) def color(self): return self._config_get(None) def color(self, text: str): self._config(text, js_type=False) ...
class Readonly(): def __raw_setattr(cls, self, name, value): object.__setattr__(self, name, value) def __raw_delattr(cls, self, name): object.__delattr__(self, name) def __setattr__(self, name, value): raise TypeError(f'{type(self).__name__} is readonly') def __delattr__(self, na...
def desenha_circulos_recursivos(x, y, raio): msp.add_circle(center=(x, y), radius=raio, dxfattribs={'layer': 'SCAN'}) if (raio > 2): desenha_circulos_recursivos((x + (raio / 2)), y, (raio / 2)) desenha_circulos_recursivos((x - (raio / 2)), y, (raio / 2)) desenha_circulos_recursivos(x, (y...
class Highlight(): NAME = 'highlight' MARGINS = 'margins' ALIGNMENT = 'alignment' ALIGN_CENTER = 'center' ALIGN_HCENTER = 'hcenter' ALIGN_VCENTER = 'vcenter' COLOR = 'color' BGCOLOR = 'bgcolor' FONT = 'font' CELLS = 'cells' ROWS = 'rows' COLS = 'cols' TEXT = 'text' ...
class Circle(Ellipse): def __init__(self, radius, colour=None, line_width=None, position=None, anti_aliasing=None): self._radius = radius if (position is None): position = defaults.circle_position if (colour is None): colour = defaults.circle_colour if (line_w...
def drives_for_iostandard(iostandard): if (iostandard in ['LVCMOS18', 'LVCMOS15']): drives = [2, 4, 6, 8, 12, 16] elif (iostandard == 'LVCMOS12'): drives = [2, 4, 6, 8] elif (iostandard in (SSTL + DIFF_SSTL)): return ['_FIXED'] else: assert False, 'this line should be unr...
def generate_mod(): if (not output_folder): status_label.config(text='Error: Please select the output folder.') return if blarc_file_path: script_dir = os.path.dirname(os.path.abspath(__file__)) extract_script_path = os.path.join(script_dir, 'extract.py') try: ...
class OptionPlotoptionsColumnDragdropDraghandle(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 OFVersions(): VERSION_1_0 = OFVersion('1.0', 1) VERSION_1_1 = OFVersion('1.1', 2) VERSION_1_2 = OFVersion('1.2', 3) VERSION_1_3 = OFVersion('1.3', 4) VERSION_1_4 = OFVersion('1.4', 5) VERSION_1_5 = OFVersion('1.5', 6) all_supported = (VERSION_1_0, VERSION_1_1, VERSION_1_2, VERSION_1_3,...
def get_ddr_phy_init_sequence(phy_settings, timing_settings): cl = phy_settings.cl bl = 4 mr = (log2_int(bl) + (cl << 4)) emr = 0 reset_dll = (1 << 8) init_sequence = [('Bring CKE high', 0, 0, cmds['CKE'], 20000), ('Precharge All', 1024, 0, cmds['PRECHARGE_ALL'], 0), ('Load Extended Mode Registe...
def get_observation_template_details(observation_template): obs_comp = frappe.qb.DocType('Observation Component') obs_temp = frappe.qb.DocType('Observation Template') from pypika import Case data = frappe.qb.from_(obs_comp).left_join(obs_temp).on((obs_comp.observation_template == obs_temp.name)).select(...
_metaclass(abc.ABCMeta) class _ZebraRedistribute(_ZebraMessageBody): _HEADER_FMT = '!B' HEADER_SIZE = struct.calcsize(_HEADER_FMT) _V4_HEADER_FMT = '!BBH' V4_HEADER_SIZE = struct.calcsize(_V4_HEADER_FMT) def __init__(self, route_type, afi=None, instance=None): super(_ZebraRedistribute, self)...
() ('--chroot', '-r', 'chroot_names', help='Chroot name, e.g. fedora-18-x86_64.', multiple=True) def drop_chroot(chroot_names): for chroot_name in chroot_names: try: coprs_logic.MockChrootsLogic.delete_by_name(chroot_name) db.session.commit() except exceptions.MalformedArgume...
def log_fortianalyzer_override_filter(data, fos): vdom = data['vdom'] log_fortianalyzer_override_filter_data = data['log_fortianalyzer_override_filter'] filtered_data = underscore_to_hyphen(filter_log_fortianalyzer_override_filter_data(log_fortianalyzer_override_filter_data)) return fos.set('log.fortian...
class TestLegalSearch(unittest.TestCase): def setUp(self): self.app = rest.app.test_client() ('webservices.rest.legal.es_client.search', legal_search_data) def test_default_search(self): response = self.app.get('/v1/legal/search/?&api_key=1234') assert (response.status_code == 200) ...
def download_test_data(): for js in JOB_STATUS: baker.make('download.JobStatus', job_status_id=js.id, name=js.name, description=js.desc) ata1 = baker.make('references.ToptierAgency', name='Bureau of Things', toptier_code='100', website=' mission='test', icon_filename='test') ata2 = baker.make('refer...
class CSVSourceFactory(HasTraits): def csv_loaded_callback(self, object): self.data_source_wizard = DataSourceWizardView(data_sources=self.csv_loader.data_dict) self.data_source_wizard.edit_traits() def __call__(self, fname): self.csv_loader = CSVLoader(filename=fname) self.csv_l...
def ExtractValue(message): if message.HasField('string_value'): return message.string_value elif message.HasField('long_value'): return message.long_value elif message.HasField('bool_value'): return message.bool_value elif message.HasField('double_value'): return message....
def test_snapshot_merge(snapshot: Snapshot): update_event = PartialSnapshot(snapshot) update_event.update_forward_model(real_id='1', forward_model_id='0', forward_model=ForwardModel(status='Finished', index='0', start_time=datetime(year=2020, month=10, day=27), end_time=datetime(year=2020, month=10, day=28))) ...
class ScheduleBFactory(BaseFactory): class Meta(): model = models.ScheduleB sub_id = factory.Sequence((lambda n: n)) report_year = 2016 two_year_transaction_period = 2016 _generation def update_fulltext(obj, create, extracted, **kwargs): obj.disbursement_description_text = sa.fun...
class InstantiateGvarTest(object): .parametrize('glyph_name', ['hyphen']) .parametrize('location, expected', [pytest.param({'wdth': (- 1.0)}, {'hyphen': [(27, 229), (27, 310), (247, 310), (247, 229), (0, 0), (274, 0), (0, 536), (0, 0)]}, id='wdth=-1.0'), pytest.param({'wdth': (- 0.5)}, {'hyphen': [(33.5, 229), ...
class EspEfuses(base_fields.EspEfusesBase): debug = False do_not_confirm = False def __init__(self, esp, skip_connect=False, debug=False, do_not_confirm=False): self.Blocks = EfuseDefineBlocks() self.Fields = EfuseDefineFields() self.REGS = EfuseDefineRegisters self.BURN_BLOC...
class dbus_polkit_require_auth(): _polkit_name = 'org.freedesktop.PolicyKit1' _polkit_path = '/org/freedesktop/PolicyKit1/Authority' _polkit_interface = 'org.freedesktop.PolicyKit1.Authority' _bus = None _bus_signal_receiver = None _interface_polkit = None def __init__(self, polkit_auth_requ...
class queue_op_failed_error_msg(error_msg): version = 6 type = 1 err_type = 9 def __init__(self, xid=None, code=None, data=None): if (xid != None): self.xid = xid else: self.xid = None if (code != None): self.code = code else: ...
def parse_args(argv=sys.argv[1:], prog=sys.argv[0]): import argparse parser = argparse.ArgumentParser() formats = ['summary', 'pairs', 'singles', 'simple', 'flat', 'json', 'raw'] parser.add_argument('--format', dest='fmt', choices=formats, default='summary') for fmt in formats: parser.add_ar...
def main(): build_dir = 'gateware' platform = Platform(toolchain='vivado') design = Tuto(platform) if ('load' in sys.argv[1:]): prog = platform.create_programmer() prog.load_bitstream((build_dir + '/top.bit')) exit() if ('sim' in sys.argv[1:]): ring = Blink(4) ...
class SectionContent(models.Model): feincms_item_editor_inline = SectionContentInline feincms_item_editor_context_processors = ((lambda x: settings.FEINCMS_RICHTEXT_INIT_CONTEXT),) feincms_item_editor_includes = {'head': [settings.FEINCMS_RICHTEXT_INIT_TEMPLATE]} title = models.CharField(_('title'), max...
def idx_ranges(table, starts, ends, mode: str): assert (mode in ('inner', 'outer')) if ((not len(table)) or ((starts is None) and (ends is None))): (yield (slice(None), None, None)) else: if ((((ends is not None) and len(ends)) and ((starts is not None) and len(starts))) and (not table.end.i...
def extractXianxiaheavenWordpressCom(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_t...
def test_mapping_saved_into_es_when_index_already_exists_closed(write_client): m = mapping.Mapping() m.field('name', 'text', analyzer=analysis.analyzer('my_analyzer', tokenizer='keyword')) write_client.indices.create(index='test-mapping') with raises(exceptions.IllegalOperation): m.save('test-ma...
('override,expected,space_after_sep', [param('key=value', 'value', False, id='str'), param("key='value'", "'value'", False, id='single_quoted'), param('key="value"', '"value"', False, id='double_quoted'), param("key=''", "''", False, id='quoted_unicode'), param('key=\\\\\\(\\)\\[\\]\\{\\}\\:\\=\\ \\\t\\,', '\\\\\\(\\)\...
def _host_is_trusted(hostname, trusted_list): if (not hostname): return False if isinstance(trusted_list, str): trusted_list = [trusted_list] def _normalize(hostname): if (':' in hostname): hostname = hostname.rsplit(':', 1)[0] return _encode_idna(hostname) tr...
def check_transaction(tx: Transaction, base_fee_per_gas: Uint, gas_available: Uint, chain_id: U64) -> Tuple[(Address, Uint)]: ensure((tx.gas <= gas_available), InvalidBlock) sender_address = recover_sender(chain_id, tx) if isinstance(tx, FeeMarketTransaction): ensure((tx.max_fee_per_gas >= tx.max_pr...
def test_schema_expansion(): ' sub_schema = {'name': 'Dependency', 'namespace': 'com.namespace.dependencies', 'type': 'record', 'fields': [{'name': 'sub_field_1', 'type': 'string'}]} outer_schema = {'name': 'MasterSchema', 'namespace': 'com.namespace.master', 'type': 'record', 'fields': [{'name': 'field_1',...
_dict def __init__(self, *args, **kwds): _auto_init_ = self._auto_init_ if (_auto_init_ is None): return if ('value' in _auto_init_): _auto_init_ = _auto_init_[1:] if _auto_init_: if (len(_auto_init_) < len(args)): raise TypeError(('%d arguments expected (%s), %d rece...
class OptionSeriesVennSonificationDefaultinstrumentoptionsPointgrouping(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 convertInfsToZeros_ArrayFloat(pArray, pToEpsilon=False): if (len(pArray) == 0): return pArray nan_elements = np.flatnonzero(np.isnan(pArray)) if (len(nan_elements) > 0): if pToEpsilon: pArray[nan_elements] = 1e-06 else: pArray[nan_elements] = 0.0 inf_e...
def get_kibana_client(cloud_id, kibana_url, kibana_user, kibana_password, kibana_cookie, space, ignore_ssl_errors, provider_type, provider_name, **kwargs): from requests import HTTPError from kibana import Kibana if (not (cloud_id or kibana_url)): client_error('Missing required --cloud-id or --kiban...
def test_split_coordinate_derivative(): mesh = UnitSquareMesh(1, 1) V = FunctionSpace(mesh, 'P', 1) Q = FunctionSpace(mesh, 'DP', 0) W = (V * Q) v = TestFunction(W) w = Function(W) x = SpatialCoordinate(mesh) J = derivative((inner(v, w) * dx), x) splitter = ExtractSubBlock() J00 ...
() def get_discussions(filters=None, order_by=None, limit_start=None, limit_page_length=None): if (not frappe.has_permission('GP Discussion', 'read')): frappe.throw('Insufficient Permission for GP Discussion', frappe.PermissionError) filters = (frappe.parse_json(filters) if filters else None) feed_t...
def _replace_pats(ir, fwd, c, pat, repl, only_replace_attrs=True, use_sym_id=True): cur_fwd = (lambda x: x) c = fwd(c) for rd in match_pattern(c, pat, use_sym_id=use_sym_id): rd = cur_fwd(rd) if (not (c_repl := repl(rd))): continue (ir, fwd_rd) = _replace_helper(rd, c_rep...
class DatasetNoReadAccessError(FoundryAPIError): def __init__(self, dataset_rid: str, response: (requests.Response | None)=None): super().__init__((f'''No read access to dataset {dataset_rid}. ''' + (response.text if (response is not None) else ''))) self.dataset_rid = dataset_rid self.respo...
class DataFormatSpec(): def __init__(self, attic): self.attic = attic self.default_index_mnem = 'DEPT' def __repr__(self): return 'DataFormatSpec()' def info(self): return self.attic.info def index_mnem(self): nspecs = len(self.specs) if ((self.depth_mode ...
(tags=['receipts'], description=docs.EFILING_TAG) class ScheduleAEfileView(views.ApiResource): model = models.ScheduleAEfile schema = schemas.ItemizedScheduleAfilingsSchema page_schema = schemas.ScheduleAEfilePageSchema filter_multi_fields = [('image_number', models.ScheduleAEfile.image_number), ('commi...
def generate_verify_code(*, length: int=settings.email_verification_code_length, secret: str=settings.secret.get_secret_value()) -> tuple[(str, str)]: code = ''.join((secrets.choice((string.ascii_uppercase + string.digits)) for _ in range(length))) return (code, get_verify_code_hash(code, secret=secret))
class TestInitializer(TestCase): def test_request_type(self): request = Request(factory.get('/')) message = 'The `request` argument must be an instance of `django. not `rest_framework.request.Request`.' with self.assertRaisesMessage(AssertionError, message): Request(request)
class OptionPlotoptionsXrangeSonificationContexttracksPointgrouping(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): ...
class Strategy(Protocol, Generic[(models.UP, models.ID)]): async def read_token(self, token: Optional[str], user_manager: BaseUserManager[(models.UP, models.ID)]) -> Optional[models.UP]: ... async def write_token(self, user: models.UP) -> str: ... async def destroy_token(self, token: str, us...
class CustomFormatter(logging.Formatter): grey = '\x1b[38;20m' green = '\x1b[1;32m' yellow = '\x1b[33;20m' red = '\x1b[31;20m' bold_red = '\x1b[31;1m' reset = '\x1b[0m' format_problem_str = '%(levelname)s - %(message)s' FORMATS = {logging.DEBUG: ((grey + '%(levelname)s - %(message)s') + ...
def get_db_engine(connection_string: str) -> Engine: connect_args = ({'connect_timeout': 10} if ('pymssql' not in connection_string) else {}) try: engine = sqlalchemy.create_engine(connection_string, connect_args=connect_args) except Exception as err: raise Exception('Failed to create engine...
def downgrade(): op.drop_column('user', 'password_hash') op.create_table('sessions', sa.Column('id', sa.INTEGER(), nullable=False), sa.Column('session_id', sa.VARCHAR(length=255), nullable=True), sa.Column('data', sa.BLOB(), nullable=True), sa.Column('expiry', sa.DATETIME(), nullable=True), sa.PrimaryKeyConstra...
(Book) class BookAdmin(CustomAdmin): autocomplete_fields = ['author', 'coll'] fields = ['isbn', 'title', 'author', 'coll'] inlines = [] list_display = ['isbn', 'title'] list_display_links = ['title'] list_filter = [AuthorFilter, CollectionFilter, PeopleWithFavBookFilter] list_filter_auto = [...
class OptionSeriesTreemapMarker(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, js_...
def update_node_packages(bench_path='.', apps=None, verbose=None): print('Updating node packages...') from distutils.version import LooseVersion from bench.utils.app import get_develop_version v = LooseVersion(get_develop_version('frappe', bench_path=bench_path)) if (v < LooseVersion('11.x.x-develop...
def get_place_trends(ids, exclude=None): twtr = Twython(**get_place_trends.get_auth_params()) trends_df = pd.DataFrame() if isinstance(ids, int): ids = [ids] for place_id in ids: place_trends = twtr.get_place_trends(id=place_id) trend_df = pd.DataFrame(place_trends[0]['trends']) ...
def test_mar_values(): current = pd.DataFrame(data=dict(user_id=['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'], prediction=[1, 2, 3, 1, 2, 3, 1, 2, 3], target=[1, 0, 0, 0, 0, 0, 0, 0, 1])) metric = MARKMetric(k=2) report = Report(metrics=[metric]) column_mapping = ColumnMapping(recommendations_type=Recom...
def try_load(path: Path, load=pickle.load, mode: str='rb'): try: return load(open(path, mode)) except (OSError, pickle.UnpicklingError, RuntimeError, EOFError) as exc: logger.warning('An error happened when trying to load from %s, this file will be ignored: %r', path, exc) return None
class StorageBucket(resource_class_factory('bucket', 'id')): ('iam_policy') def get_iam_policy(self, client=None): try: (data, _) = client.fetch_storage_bucket_iam_policy(self.key()) return data except (api_errors.ApiExecutionError, ResourceNotSupported) as e: ...
def test_save_string_model(mock_client): with mock.patch('foundry_dev_tools.cached_foundry_client.CachedFoundryClient.api', mock_client): cfc = CachedFoundryClient() model = 'simplestring' (rid, transaction) = cfc.save_model(model, dataset_path_or_rid='/Namespace1/project1/save_model_test', ...
class IntegrationManifestSchema(Schema): name = fields.Str(required=True) version = fields.Str(required=True) release = fields.Str(required=True) description = fields.Str(required=True) download = fields.Str(required=True) conditions = fields.Dict(required=True) policy_templates = fields.Lis...
def main(): args = parse_cmd_arguments() db_file = os.path.abspath(args.db) if (not os.path.exists(db_file)): raise RuntimeError(('database does not exist at: ' + db_file)) db_conn = sqlite3.connect(db_file) if (args.del_entry_by_id is not None): del_entry(db_conn=db_conn, table=args...
class OptionPlotoptionsFunnelSonificationTracksMapping(Options): def frequency(self) -> 'OptionPlotoptionsFunnelSonificationTracksMappingFrequency': return self._config_sub_data('frequency', OptionPlotoptionsFunnelSonificationTracksMappingFrequency) def gapBetweenNotes(self) -> 'OptionPlotoptionsFunnelS...
class RequestAccessPermissionButton(widgets.Button): name = 'plugin/lastfmlove/request_access_permission' def __init__(self, preferences, widget): widgets.Button.__init__(self, preferences, widget) self.message = dialogs.MessageBar(parent=preferences.builder.get_object('preferences_box'), button...
def test_comparison_refs(): def dummy_node(node_id) -> Node: n = Node(node_id, metadata=None, bindings=[], upstream_nodes=[], flyte_entity=SQLTask(name='x', query_template='x', inputs={})) n._id = node_id return n px = Promise('x', NodeOutput(var='x', node=dummy_node('n1'))) py = Pro...
def unsupported_feature(): print('Error: You have an unsupported version of Python interpreter dnspython library.') print(' Some features such as DoT and DoH are not available. You should upgrade') print(' the Python interpreter to at least 3.7 and reinstall dependencies.') sys.exit(127)
def gen_common_macros(out): out.write('\n/**\n * Macros for initializing and checking scalar types\n *\n * var The variable being initialized or checked\n * val The integer value to set/check against, see below\n *\n * Note that equality means something special for strings. Each byte\n * is initialized to an inc...
def Base(search_manager_regconfig): Base = declarative_base() make_searchable(Base.metadata) if search_manager_regconfig: search_manager.options['regconfig'] = search_manager_regconfig (yield Base) search_manager.options['regconfig'] = 'pg_catalog.english' search_manager.processed_column...
class Treemap(): def __init__(self, trees): self.done = False self.trees = trees self.hatches_gen = hatches() def compute(self): def new_size_method(): size_cache = {} def _size(thing): if isinstance(thing, int): return ...
def test_parse_arg_level_1(caplog): args = [path.relpath(__file__), '--debug', '--level', '1'] cis_audit.parse_arguments(argv=args) status = False for record in caplog.records: if (record.msg == 'Going to run Level 1 tests'): status = True break assert status
class TimeField(Field): default_error_messages = {'invalid': _('Time has wrong format. Use one of these formats instead: {format}.')} datetime_parser = datetime.datetime.strptime def __init__(self, format=empty, input_formats=None, **kwargs): if (format is not empty): self.format = forma...
class Solution(): def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: def find_combination(candidates, idx, target, curr, ret): if (target < 0): return if (target == 0): ret.append(list(curr)) return ...
class OptionNavigationBreadcrumbsSeparator(Options): def style(self) -> 'OptionNavigationBreadcrumbsSeparatorStyle': return self._config_sub_data('style', OptionNavigationBreadcrumbsSeparatorStyle) def text(self): return self._config_get('/') def text(self, text: str): self._config(t...
def fetch_consumption(zone_key: str='KW', session: (Session | None)=None, target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)): if target_datetime: raise NotImplementedError('This parser is not yet able to parse past dates') r = (session or Session()) url = ' response = r...
class InlineCKEditorWidget(forms.Textarea): def __init__(self, *args, **kwargs): self.ckeditor = (kwargs.pop('ckeditor') or _url()) self.config = (kwargs.pop('config') or _config()['default']) attrs = kwargs.setdefault('attrs', {}) attrs['data-inline-cke'] = id(self.config) i...
def gen_string(uni_str, exception=False): if (uni_str is None): if exception: raise TypeError('None not allowed') return b'' if (not hasattr(uni_str, 'encode')): if exception: raise TypeError('uni_str required function encode(format)') return b'' try: ...
class Javascript(Plugin): def language_init(self): self.update_actions({'render': {'call': 'inject', 'render': '%(code)s', 'header': "'%(header)s'+", 'trailer': "+'%(trailer)s'", 'test_render': ('typeof(%(r1)s)+%(r2)s' % {'r1': rand.randints[0], 'r2': rand.randints[1]}), 'test_render_expected': ('number%(r2...
def test_metadata(fx_asset): with Image(filename=str(fx_asset.joinpath('beach.jpg'))) as img: assert (len(img.metadata) > 0) for key in img.metadata: assert isinstance(key, string_type) assert ('exif:ApertureValue' in img.metadata) assert ('exif:UnknownValue' not in img.m...
class MainWindow(ApplicationWindow): data = List(Instance(Person)) row_info = Instance(AbstractRowInfo) data_view = Instance(IDataViewWidget) def _create_contents(self, parent): self.data_view.create(parent) return self.data_view.control def _data_default(self): logger.info('...
def get_fstring_from_call(ghidra_analysis, key_string, call_args, func, call, sources): if (call in call_args): arg_values = call_args[call] else: (_, arg_values) = get_call_site_args(ghidra_analysis, func, call, sources) call_args[call] = arg_values start = 1 for arg_value in ar...
def _coconut_iter_getitem(iterable, index): obj_iter_getitem = _coconut.getattr(iterable, '__iter_getitem__', None) if ((obj_iter_getitem is None) and _coconut.isinstance(iterable, _coconut.abc.Sequence)): obj_iter_getitem = _coconut.getattr(iterable, '__getitem__', None) if (obj_iter_getitem is not...
class OptionSeriesAreasplinerangeDataEvents(Options): def click(self): return self._config_get(None) def click(self, value: Any): self._config(value, js_type=False) def drag(self): return self._config_get(None) def drag(self, value: Any): self._config(value, js_type=False...
class OptionSeriesItemStatesHoverMarker(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(...
def import_symbol(symbol_path): if (':' in symbol_path): (module_name, symbol_name) = symbol_path.split(':') module = import_module(module_name) symbol = eval(symbol_name, module.__dict__) else: components = symbol_path.split('.') module_name = '.'.join(components[:(- 1)]...
def add_tags(ids: List[int], tags: List[str]): if ((tags is None) or (ids is None) or (len(ids) == 0)): return ids = ','.join([str(id) for id in ids]) conn = _get_connection() notes = conn.execute(f'select id, tags from notes where id in ({ids})').fetchall() updated = [] for (nid, tstr) ...
class stalkerForm(QDialog, Ui_StalkerDialog): def __init__(self, parent=None): super(stalkerForm, self).__init__(parent) self.setupUi(self) self.setWindowOpacity(0.93) self.btnSubmit.clicked.connect(self.submit) self.btnClear.clicked.connect(self.clearUi) self.clearUi...
def _on_monitor_change(**kwargs): fieldname = kwargs['fieldname'] obj = kwargs['obj'] name = kwargs['name'] session = kwargs['session'] outputfunc_name = kwargs['outputfunc_name'] category = None if (hasattr(obj, 'db_category') and (obj.db_category != None)): category = obj.db_catego...
class TestCategoryShare(BaseDataQualityCategoryMetricsTest): name: ClassVar = 'Share of category' alias: ClassVar = 'share_category' def get_condition_from_reference(self, reference: Optional[CategoryStat]) -> float: if (reference is not None): return reference.category_ratio rai...
(scope='package') def pysoa_client_json(): config = copy.deepcopy(_base_config) config['echo']['transport']['kwargs']['default_serializer_config'] = _json_serializer config['meta']['transport']['kwargs']['default_serializer_config'] = _json_serializer config['user']['transport']['kwargs']['default_seria...
class SizedArrayDecoder(BaseArrayDecoder): array_size = None def __init__(self, **kwargs): super().__init__(**kwargs) self.is_dynamic = self.item_decoder.is_dynamic _tuple def decode(self, stream): for _ in range(self.array_size): (yield self.item_decoder(stream))
_group.command('event-search') ('query') ('--index', '-i', multiple=True, help='Index patterns to search against') ('--eql/--lucene', '-e/-l', 'language', default=None, help='Query language used (default: kql)') ('--date-range', '-d', type=(str, str), default=('now-7d', 'now'), help='Date range to scope search') ('--co...
class OptionSeriesBoxplotSonificationDefaultinstrumentoptionsMappingTremoloSpeed(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 StalkerSceneAddAllShotPrevisOutputsOperator(bpy.types.Operator): bl_label = 'Add All Shot Previs Outputs' bl_idname = 'stalker.scene_add_all_shot_previs_outputs_op' stalker_entity_id = bpy.props.IntProperty(name='stalker_entity_id') stalker_entity_name = bpy.props.StringProperty(name='stalker_enti...
class Command(BaseCommand): help = 'Loads historical budget authority data from a CSV' DEFAULT_DIRECTORY_PATH = os.path.join('usaspending_api', 'data', 'budget_authority') def add_arguments(self, parser): parser.add_argument('-q', '--quarter', type=valid_quarter, help='Quarter to load from spreadshe...