code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def _spot_check_that_elements_produced_by_this_generator_have_attribute(self, name): g_tmp = self.values_gen.spawn() sample_element = next(g_tmp)[0] try: getattr(sample_element, name) except AttributeError: raise AttributeError(f"Items produced by {self} do not ha...
Helper function to spot-check that the items produces by this generator have the attribute `name`.
def flush(self): for name in self.item_names: item = self[name] item.flush() self.file.flush()
Ensure contents are written to file.
def result(self, value): if self._process_result: self._result = self._process_result(value) self._raw_result = value
The result of the command.
def register(self, entity): response = self.api.post_entity(entity.serialize) print(response) print() if response['status']['code'] == 200: entity.id = response['id'] if response['status']['code'] == 409: entity.id = next(i.id for i in self.api.agent_entit...
Registers a new entity and returns the entity object with an ID
def as_dict(self): result = {} for key in self._valid_properties: val = getattr(self, key) if isinstance(val, datetime): val = val.isoformat() elif val and not Model._is_builtin(val): val = val.as_dict() elif isinstance(val,...
Returns a dict representation of the resource
def render(self, model, color, num_turtles): self.program.bind() glBindVertexArray(self.vao) self.model_buffer.load(model.data, model.byte_size) self.color_buffer.load(color.data, color.byte_size) glDrawArraysInstanced( GL_TRIANGLES, 0, len(sel...
Renders all turtles of a given shape
async def _execute(self, appt): user = self.core.auth.user(appt.useriden) if user is None: logger.warning('Unknown user %s in stored appointment', appt.useriden) await self._markfailed(appt) return await self.core.boss.execute(self._runJob(user, appt), f'Agend...
Fire off the task to make the storm query
def tags_context(self, worker_ctx, exc_info): tags = { 'call_id': worker_ctx.call_id, 'parent_call_id': worker_ctx.immediate_parent_call_id, 'service_name': worker_ctx.container.service_name, 'method_name': worker_ctx.entrypoint.method_name } for k...
Merge any tags to include in the sentry payload.
def delete(self, uid): if self.check_post_role()['DELETE']: pass else: return False histinfo = MWikiHist.get_by_uid(uid) if histinfo: pass else: return False postinfo = MWiki.get_by_uid(histinfo.wiki_id) MWikiHist.de...
Delete the history of certain ID.
def ReadCronJobs(self, cronjob_ids=None): if cronjob_ids is None: res = [job.Copy() for job in itervalues(self.cronjobs)] else: res = [] for job_id in cronjob_ids: try: res.append(self.cronjobs[job_id].Copy()) except KeyError: raise db.UnknownCronJobError("C...
Reads a cronjob from the database.
def draw(self): cell_background_renderer = GridCellBackgroundCairoRenderer( self.context, self.code_array, self.key, self.rect, self.view_frozen) cell_content_renderer = GridCellContentCairoRenderer( self.context, self.c...
Draws cell to context
def register_master(): tango_db = Database() device = "sip_sdp/elt/master" device_info = DbDevInfo() device_info._class = "SDPMasterDevice" device_info.server = "sdp_master_ds/1" device_info.name = device devices = tango_db.get_device_name(device_info.server, device_info._class) if devic...
Register the SDP Master device.
def _set_spyder_breakpoints(self, breakpoints): if not self._pdb_obj: return serialized_breakpoints = breakpoints[0] breakpoints = pickle.loads(serialized_breakpoints) self._pdb_obj.set_spyder_breakpoints(breakpoints)
Set all Spyder breakpoints in an active pdb session
def read_profiles(profiles_dir=None): if profiles_dir is None: profiles_dir = PROFILES_DIR raw_profiles = read_profile(profiles_dir) if raw_profiles is None: profiles = {} else: profiles = {k: v for (k, v) in raw_profiles.items() if k != 'config'} return profiles
This is only used for some error handling
def commit(self, callback=None): if self.executed: raise InvalidTransaction('Invalid operation. ' 'Transaction already executed.') session = self.session self.session = None self.on_result = self._commit(session, callback) r...
Close the transaction and commit session to the backend.
def __flushLevel(self, level): objectsCount = len(self.objectsStack) while objectsCount > level: lastIndex = objectsCount - 1 if lastIndex == 0: if self.objectsStack[0].__class__.__name__ == "Class": self.classes.append(self.objectsStack[0]) ...
Merge the found objects to the required level
def clear_dir(self): self.stdout.write("Deleting contents of '{}'.".format(self.destination_path)) for filename in os.listdir(self.destination_path): if os.path.isfile(filename) or os.path.islink(filename): os.remove(filename) elif os.path.isdir(filename): ...
Delete contents of the directory on the given path.
def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri })
Domain metadata change events handler
def _handle_actionpush(self, length): init_pos = self._src.tell() while self._src.tell() < init_pos + length: obj = _make_object("ActionPush") obj.Type = unpack_ui8(self._src) push_types = { 0: ("String", self._get_struct_string), 1: ("...
Handle the ActionPush action.
def reject(self, reason): if self._state != 'pending': raise RuntimeError('Promise is no longer pending.') self.reason = reason self._state = 'rejected' errbacks = self._errbacks self._errbacks = None for errback in errbacks: errback(reason)
Rejects the promise with the given reason.
def find_loci(self): session = OAuth1Session(self.consumer_key, self.consumer_secret, access_token=self.session_token, access_token_secret=self.session_secret) r = session.get(self.loci) if r.status_c...
Finds the URLs for all allele files
def to_feature_reports(self, debug=False): rest = self.to_string() seq = 0 out = [] while rest: this, rest = rest[:7], rest[7:] if seq > 0 and rest: if this != b'\x00\x00\x00\x00\x00\x00\x00': this += yubico_util.chr_byte(yubike...
Return the frame as an array of 8-byte parts, ready to be sent to a YubiKey.
def status(self): status_request = etcdrpc.StatusRequest() status_response = self.maintenancestub.Status( status_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata ) for m in self.members: if m.id =...
Get the status of the responding member.
def check_link(self, link): r = requests.get(CHECK_LINK_ENDPOINT + link) if r.status_code != 200: raise GfycatClientError('Unable to check the link', r.status_code) return r.json()
Check if a link has been already converted.
def make_video_cache(self, days=None): if days is None: days = self._min_days_vdo_cache self._cached_videos = self.videos(days)
Save videos on _cache_videos to avoid dups.
def delete_lbaas_member(self, lbaas_member, lbaas_pool): return self.delete(self.lbaas_member_path % (lbaas_pool, lbaas_member))
Deletes the specified lbaas_member.
def namedb_get_num_names( cur, current_block, include_expired=False ): unexpired_query = "" unexpired_args = () if not include_expired: unexpired_query, unexpired_args = namedb_select_where_unexpired_names( current_block ) unexpired_query = 'WHERE {}'.format(unexpired_query) query = "SEL...
Get the number of names that exist at the current block
def create_client_for_file(self, filename, is_cython=False): self.create_new_client(filename=filename, is_cython=is_cython) self.master_clients -= 1 client = self.get_current_client() client.allow_rename = False tab_text = self.disambiguate_fname(filename) self.rena...
Create a client to execute code related to a file.
def create_toolbar_tokens_func(get_is_refreshing, show_fish_help): token = Token.Toolbar def get_toolbar_tokens(cli): result = [] result.append((token, ' ')) if cli.buffers[DEFAULT_BUFFER].always_multiline: result.append((token.On, '[F3] Multiline: ON ')) else: ...
Return a function that generates the toolbar tokens.
def _remove_bcbiovm_path(): cur_path = os.path.dirname(os.path.realpath(sys.executable)) paths = os.environ["PATH"].split(":") if cur_path in paths: paths.remove(cur_path) os.environ["PATH"] = ":".join(paths)
Avoid referencing minimal bcbio_nextgen in bcbio_vm installation.
def getobject_use_prevfield(idf, idfobject, fieldname): if not fieldname.endswith("Name"): return None fdnames = idfobject.fieldnames ifieldname = fdnames.index(fieldname) prevfdname = fdnames[ifieldname - 1] if not prevfdname.endswith("Object_Type"): return None objkey = idfobje...
field=object_name, prev_field=object_type. Return the object
def _request_titles_xml() -> ET.ElementTree: response = api.titles_request() return api.unpack_xml(response.text)
Request AniDB titles file.
def Negation(expr: Expression) -> Expression: expr = Expression(_negate(expr.body)) return ast.fix_missing_locations(expr)
Return expression which is the negation of `expr`.
def __get_tokens(self, row): row_tokenizer = RowTokenizer(row, self.config) line = row_tokenizer.next() while line: yield line line = row_tokenizer.next()
Row should be a single string
def add_current_vrf(self): vrf_id = request.json['vrf_id'] if vrf_id is not None: if vrf_id == 'null': vrf = VRF() else: vrf_id = int(vrf_id) vrf = VRF.get(vrf_id) session['current_vrfs'][vrf_id] = { 'id': vrf.id, 'rt': ...
Add VRF to filter list session variable
def OnTimerToggle(self, event): if self.grid.timer_running: self.grid.timer_running = False self.grid.timer.Stop() del self.grid.timer else: self.grid.timer_running = True self.grid.timer = wx.Timer(self.grid) self.grid.timer.Start(...
Toggles the timer for updating frozen cells
def keys(self): keys = Struct.keys(self) for key in ( '_cloud_provider', '_naming_policy', '_setup_provider', 'known_hosts_file', 'repository', ): if key in keys: keys.remove(key) ...
Only expose some of the attributes when using as a dictionary
def expr_to_json(expr): if isinstance(expr, symbolics.Mul): return {"type": "Mul", "args": [expr_to_json(arg) for arg in expr.args]} elif isinstance(expr, symbolics.Add): return {"type": "Add", "args": [expr_to_json(arg) for arg in expr.args]} elif isinstance(expr, symbolics.Symbol): ...
Converts a Sympy expression to a json-compatible tree-structure.
def do_function(self, prov, func, kwargs): matches = self.lookup_providers(prov) if len(matches) > 1: raise SaltCloudSystemExit( 'More than one results matched \'{0}\'. Please specify ' 'one of: {1}'.format( prov, ', '.j...
Perform a function against a cloud provider
def pan_cb(self, setting, value): pan_x, pan_y = value[:2] self.logger.debug("pan set to %.2f,%.2f" % (pan_x, pan_y)) self.redraw(whence=0)
Handle callback related to changes in pan.
def GetPythonLibraryDirectoryPath(): path = sysconfig.get_python_lib(True) _, _, path = path.rpartition(sysconfig.PREFIX) if path.startswith(os.sep): path = path[1:] return path
Retrieves the Python library directory path.
def to_bool(text): downcased_text = six.text_type(text).strip().lower() if downcased_text == 'false': return False elif downcased_text == 'true': return True return text
Convert the string name of a boolean to that boolean value.
def _ndefs(f): if isinstance(f, Function): return f.ndefs spec = inspect.getfullargspec(f) if spec.defaults is None: return 0 return len(spec.defaults)
number of any default values for positional or keyword parameters
async def _send_packet(self, pkt): if self.state != 'connected': return await self.queue.put(pkt) self.logger.info( 'Sending packet %s data %s', packet.packet_names[pkt.packet_type], pkt.data if not isinstance(pkt.data, bytes) else '<binary>')
Queue a packet to be sent to the server.
def getbyteslice(self, start, end): c = self._rawarray[start:end] return c
Direct access to byte data.
def upload_vcl(self, service_id, version_number, name, content, main=None, comment=None): body = self._formdata({ "name": name, "content": content, "comment": comment, "main": main, }, FastlyVCL.FIELDS) content = self._fetch("/service/%s/version/%d/vcl" % (service_id, version_number), method="POST", b...
Upload a VCL for a particular service and version.
def data_url_scheme(self): encoded = base64.b64encode(self.contents().encode()) return "data:image/svg+xml;base64," + encoded.decode()
Get svg in Data URL Scheme format.
def links(self, base_link, current_page) -> dict: max_pages = self.max_pages - 1 if \ self.max_pages > 0 else self.max_pages base_link = '/%s' % (base_link.strip("/")) self_page = current_page prev = current_page - 1 if current_page is not 0 else None prev_link ...
Return JSON paginate links
def _parse_return_code_powershell(string): regex = re.search(r'ReturnValue\s*: (\d*)', string) if not regex: return (False, 'Could not parse PowerShell return code.') else: return int(regex.group(1))
return from the input string the return code of the powershell command
def wrap_text(paragraph, line_count, min_char_per_line=0): one_string = strip_all_white_space(paragraph) if min_char_per_line: lines = wrap(one_string, width=min_char_per_line) try: return lines[:line_count] except IndexError: return lines else: return wrap(one_string, len(one_string)/line_count)
Wraps the given text to the specified number of lines.
def render_node(_node_id, value=None, noderequest={}, **kw): "Recursively render a node's value" if value == None: kw.update( noderequest ) results = _query(_node_id, **kw) current_app.logger.debug("results: %s", results) if results: values = [] for (resul...
Recursively render a node's value
def session_state_view(request, template_name, **kwargs): 'Example view that exhibits the use of sessions to store state' session = request.session demo_count = session.get('django_plotly_dash', {}) ind_use = demo_count.get('ind_use', 0) ind_use += 1 demo_count['ind_use'] = ind_use context =...
Example view that exhibits the use of sessions to store state
def function(self,p): generators = self._advance_pattern_generators(p) assert hasattr(p.operator,'reduce'),repr(p.operator)+" does not support 'reduce'." patterns = [pg(xdensity=p.xdensity,ydensity=p.ydensity, bounds=p.bounds,mask=p.mask, x=p.x+p.siz...
Constructs combined pattern out of the individual ones.
def from_name(cls, name): return Author(name=name, sha512=cls.hash_name(name))
Create an author by name, automatically populating the hash.
def generate_wakeword_pieces(self, volume): while True: target = 1 if random() > 0.5 else 0 it = self.pos_files_it if target else self.neg_files_it sample_file = next(it) yield self.layer_with(self.normalize_volume_to(load_audio(sample_file), volume), target) ...
Generates chunks of audio that represent the wakeword stream
def _yarn_scheduler_metrics(self, rm_address, instance, addl_tags, queue_blacklist): metrics_json = self._rest_request_to_json(rm_address, instance, YARN_SCHEDULER_PATH, addl_tags) try: metrics_json = metrics_json['scheduler']['schedulerInfo'] if metrics_json['type'] == 'capacity...
Get metrics from YARN scheduler
def query_ids(self, ids): results = self._get_repo_filter(Layer.objects).filter(uuid__in=ids).all() if len(results) == 0: results = self._get_repo_filter(Service.objects).filter(uuid__in=ids).all() return results
Query by list of identifiers
def send(self, auth_header=None, callback=None, **data): message = self.encode(data) return self.send_encoded(message, auth_header=auth_header, callback=callback)
Serializes the message and passes the payload onto ``send_encoded``.
def _get_serv(ret): _options = _get_options(ret) host = _options.get('host') port = _options.get('port') log.debug('memcache server: %s:%s', host, port) if not host or not port: log.error('Host or port not defined in salt config') return memcacheoptions = (host, port) return ...
Return a memcache server object
def mdata(): grains = {} mdata_list = salt.utils.path.which('mdata-list') mdata_get = salt.utils.path.which('mdata-get') grains = salt.utils.dictupdate.update(grains, _user_mdata(mdata_list, mdata_get), merge_lists=True) grains = salt.utils.dictupdate.update(grains, _sdc_mdata(mdata_list, mdata_get)...
Provide grains from the SmartOS metadata
def parse_PRIK(chunk, encryption_key): decrypted = decode_aes256('cbc', encryption_key[:16], decode_hex(chunk.payload), encryption_key) hex_key = re.match(br'^LastPassPrivateKey<(?P<hex_key>.*)>LastPassPrivateKey$', decryp...
Parse PRIK chunk which contains private RSA key
def _is_undefok(arg, undefok_names): if not arg.startswith('-'): return False if arg.startswith('--'): arg_without_dash = arg[2:] else: arg_without_dash = arg[1:] if '=' in arg_without_dash: name, _ = arg_without_dash.split('=', 1) else: name = arg_without_dash if name in undefok_names: ...
Returns whether we can ignore arg based on a set of undefok flag names.
def _check_success(self): cube_height = self.sim.data.body_xpos[self.cube_body_id][2] table_height = self.table_full_size[2] return cube_height > table_height + 0.10
Returns True if task is successfully completed
def text(self): text = [] rows = self.rowCount() cols = self.columnCount() if rows == 2 and cols == 2: item = self.item(0, 0) if item is None: return '' for r in range(rows - 1): for c in range(cols - 1): ...
Return the entered array in a parseable form.
def OnWidget(self, event): self.choice_dialects.SetValue(len(self.choices['dialects']) - 1) event.Skip()
Update the dialect widget to 'user
def calculate_normals(vertices): verts = np.array(vertices, dtype=float) normals = np.zeros_like(verts) for start, end in pairwise(np.arange(0, verts.shape[0] + 1, 3)): vecs = np.vstack((verts[start + 1] - verts[start], verts[start + 2] - verts[start])) vecs /= np.linalg.norm(vecs, axis=1, k...
Return Nx3 normal array from Nx3 vertex array.
def min_pos(self): if self.__len__() == 0: return ArgumentError('empty set has no minimum positive value.') if self.contains(0): return None positive = [interval for interval in self.intervals if interval.left > 0] if len(positive) == 0: ...
Returns minimal positive value or None.
def check_duplicate_filenames(files): used_names = set() dup_names = list() for this_file in files: this_fname = os.path.basename(this_file) if this_fname in used_names: dup_names.append(this_file) else: used_names.add(this_fname) if len(dup_names) > 0: ...
Check for duplicate filenames across gallery directories.
def run_notebook(self, nb, f): if PYTHON_MAJOR_VERSION == 3: kernel_name = 'python3' elif PYTHON_MAJOR_VERSION == 2: kernel_name = 'python2' else: raise Exception('Only Python 2 and 3 are supported') ep = ExecutePreprocessor(timeout=600, kernel_name=ke...
Runs a loaded notebook file.
def do_install(ctx, verbose, fake): click.echo('The following git aliases will be installed:\n') aliases = cli.list_commands(ctx) output_aliases(aliases) if click.confirm('\n{}Install aliases above?'.format('FAKE ' if fake else ''), default=fake): for alias in aliases: cmd = '!legit ...
Installs legit git aliases.
def update(self): self.idx_chan.clear() for chan_name in self.parent.traces.chan: self.idx_chan.addItem(chan_name) if self.selected_chan is not None: self.idx_chan.setCurrentIndex(self.selected_chan) self.selected_chan = None
Add channel names to the combobox.
def trigger(self, identifier, force=True): self.debug(identifier) url = "{base}/{identifier}".format( base=self.local_base_url, identifier=identifier ) param = {} if force: param['force'] = force encode = urllib.urlencode(param) ...
Trigger an upgrade task.
def renamed_class(cls): class DeprecationWrapper(cls): def __init__(self, config=None, env=None, logger_creator=None): old_name = cls.__name__.replace("Trainer", "Agent") new_name = cls.__name__ logger.warn("DeprecationWarning: {} has been renamed to {}. ". ...
Helper class for renaming Agent => Trainer with a warning.
def to_dict(self): return { 'current': self.current, 'first': self.first, 'last': self.last, 'next': self.more, 'prev': self.prev, }
Convert the Paginator into a dict
def suspend_queues(self, active_queues, sleep_time=10.0): for queue in active_queues: self.disable_queue(queue) while self.get_active_tasks(): time.sleep(sleep_time)
Suspend Celery queues and wait for running tasks to complete.
def abstract(cls): if not issubclass(cls, HasProps): raise TypeError("%s is not a subclass of HasProps" % cls.__name__) if cls.__doc__ is not None: cls.__doc__ += _ABSTRACT_ADMONITION return cls
A decorator to mark abstract base classes derived from |HasProps|.
def _generate_alphabet_dict(iterable, reserved_tokens=None): if reserved_tokens is None: reserved_tokens = RESERVED_TOKENS alphabet = {c for token in iterable for c in token} alphabet |= {c for token in reserved_tokens for c in token} alphabet |= _ESCAPE_CHARS return alphabet
Create set of characters that appear in any element in the iterable.
def update_params(self, token, match): for k, v in self.params.items(): if isinstance(v, MatchGroup): self.params[k] = v.get_group_value(token, match)
Update dict of params from results of regex match
def _is_number_matching_desc(national_number, number_desc): if number_desc is None: return False actual_length = len(national_number) possible_lengths = number_desc.possible_length if len(possible_lengths) > 0 and actual_length not in possible_lengths: return False return _match_nati...
Determine if the number matches the given PhoneNumberDesc
def _close_stdio(): for fd in (sys.stdin, sys.stdout, sys.stderr): file_no = fd.fileno() fd.flush() fd.close() os.close(file_no)
Close stdio streams to avoid output in the tty that launched pantsd.
def isPIDValid(self, pid): class ExitCodeProcess(ctypes.Structure): _fields_ = [('hProcess', ctypes.c_void_p), ('lpExitCode', ctypes.POINTER(ctypes.c_ulong))] SYNCHRONIZE = 0x100000 PROCESS_QUERY_LIMITED_INFORMATION = 0x1000 process = self._kernel32.Op...
Checks if a PID is associated with a running process
def process(self): self.modules.sort(key=lambda x: x.priority) for module in self.modules: transforms = module.transform(self.data) transforms.sort(key=lambda x: x.linenum, reverse=True) for transform in transforms: linenum = transform.linenum ...
This method handles the actual processing of Modules and Transforms
def add_layer_item(self, layer): if not layer.is_draft_version: raise ValueError("Layer isn't a draft version") self.items.append(layer.latest_version)
Adds a Layer to the publish group.
def via_nupnp(): bridges_from_portal = parse_portal_json() logger.info('Portal returned %d Hue bridges(s).', len(bridges_from_portal)) found_bridges = {} for bridge in bridges_from_portal: serial, bridge_info = parse_description_xml(bridge[1]) if serial: foun...
Use method 2 as described by the Philips guide
def retrieve_and_parse_profile(fid: str) -> Optional[ActivitypubProfile]: profile = retrieve_and_parse_document(fid) if not profile: return try: profile.validate() except ValueError as ex: logger.warning("retrieve_and_parse_profile - found profile %s but it didn't validate: %s", ...
Retrieve the remote fid and return a Profile object.
def diff_files(left, right, diff_options=None, formatter=None): return _diff(etree.parse, left, right, diff_options=diff_options, formatter=formatter)
Takes two filenames or streams, and diffs the XML in those files
def _create_gitlab_runner_prometheus_instance(self, instance, init_config): allowed_metrics = init_config.get('allowed_metrics') if allowed_metrics is None: raise CheckException("At least one metric must be whitelisted in `allowed_metrics`.") gitlab_runner_instance = deepcopy(instanc...
Set up the gitlab_runner instance so it can be used in OpenMetricsBaseCheck
def _call_command(self, name, *args, **kwargs): meth = super(RedisField, self)._call_command if self.indexable and name in self.available_modifiers: with FieldLock(self): try: result = meth(name, *args, **kwargs) except: ...
Add lock management and call parent.
def flush_queue(self): records = [] while not self.queue.empty() and len(records) < self.batch_size: records.append(self.queue.get()) if records: self.send_records(records) self.last_flush = time.time()
Grab all the current records in the queue and send them.
def replace_graph(cls, response, serialized): if cls.is_graph(response): return serialized if hasattr(response, '__getitem__'): if len(response) > 0 and \ cls.is_graph(response[0]): return (serialized,) + response[1:] return response
Replace the rdflib Graph in a Flask response
def stop(self): with self.lock: self._message_received(ConnectionClosed(self._file, self))
Stop the communication with the shield.
def generate(self): t = (self.context.identifier, RDF.type, META.Provenance) if t not in self.context.graph: self.context.graph.add(t) for name, value in self.data.items(): pat = (self.context.identifier, META[name], None) if pat in self.context.graph: ...
Add provenance info to the context graph.
def import_related_module(package, pkg_path, related_name, ignore_exceptions=False): try: imp.find_module(related_name, pkg_path) except ImportError: return try: return getattr( __import__('%s' % (package), globals(), locals(), [related_name]), ...
Import module from given path.
def rounding(price, currency): currency = validate_currency(currency) price = validate_price(price) if decimals(currency) == 0: return round(int(price), decimals(currency)) return round(price, decimals(currency))
rounding currency value based on its max decimal digits
def _container_attrib_builder(name, container, mapper): context = {'@container': '@{0}'.format(name)} def _attrib(type, **kwargs): kwargs.setdefault('metadata', {}) kwargs['metadata'][KEY_CLS] = type kwargs['default'] = Factory(container) def _converter(value): if isi...
Builder for container attributes.
def model_resources(self): response = jsonify({ 'apiVersion': '0.1', 'swaggerVersion': '1.1', 'basePath': '%s%s' % (self.base_uri(), self.api.url_prefix), 'apis': self.get_model_resources() }) response.headers.add('Cache-Control', 'max-age=0') ...
Listing of all supported resources.
def model_ext_functions(vk, model): model['ext_functions'] = {'instance': {}, 'device': {}} alias = {v: k for k, v in model['alias'].items()} for extension in get_extensions_filtered(vk): for req in extension['require']: if not req.get('command'): continue ext...
Fill the model with extensions functions
def time_delay_from_earth_center(self, right_ascension, declination, t_gps): return self.time_delay_from_location(np.array([0, 0, 0]), right_ascension, declination, t_gps)
Return the time delay from the earth center
def dragLeaveEvent(self, event): super(AbstractDragView, self).dragLeaveEvent(event) self.dragline = None self.viewport().update() event.accept()
Clears drop cursor line
def _graphql_query_waittime(self, query_hash: str, current_time: float, untracked_queries: bool = False) -> int: sliding_window = 660 if query_hash not in self._graphql_query_timestamps: self._graphql_query_timestamps[query_hash] = [] self._graphql_query_timestamps[query_hash] = list...
Calculate time needed to wait before GraphQL query can be executed.