code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def update_details(profile_tree, details): div = profile_tree.xpath("//div[@id = 'profile_details']")[0] for dl in div.iter('dl'): title = dl.find('dt').text item = dl.find('dd') if title == 'Last Online' and item.find('span') is not None: details[title.lower()] = item.find('span').text.strip() elif title.lower() in details and len(item.text): details[title.lower()] = item.text.strip() else: continue details[title.lower()] = replace_chars(details[title.lower()])
Update details attribute of a Profile.
def serialize(self): data = { 'type': self.__class__.__name__, 'caption': self.caption.serialize(), 'headings': [[cell.serialize() for cell in hrow] for hrow in self.headings], 'rows': [[cell.serialize() for cell in row] for row in self.rows], } return data
Convert Table element to python dictionary.
def a(self): a = Point(self.center) if self.xAxisIsMajor: a.x += self.majorRadius else: a.y += self.majorRadius return a
Positive antipodal point on the major axis, Point class.
def completenames(self, text, *ignored): return sorted(cmd.Cmd.completenames(self, text, *ignored) + self.argparse_names(text))
Patched to also return argparse commands
def _precedence_parens(self, node, child, is_left=True): if self._should_wrap(node, child, is_left): return "(%s)" % child.accept(self) return child.accept(self)
Wrap child in parens only if required to keep same semantics
def play(quiet, session_file, shell, speed, prompt, commentecho): run( session_file.readlines(), shell=shell, speed=speed, quiet=quiet, test_mode=TESTING, prompt_template=prompt, commentecho=commentecho, )
Play a session file.
def lnlike(self, theta): params,loglike = self.params,self.loglike kwargs = dict(list(zip(params,theta))) try: lnlike = loglike.value(**kwargs) except ValueError as AssertionError: lnlike = -np.inf return lnlike
Logarithm of the likelihood
def load_fits(self, filepath): image = AstroImage.AstroImage(logger=self.logger) image.load_file(filepath) self.set_image(image)
Load a FITS file into the viewer.
def slugify(text, sep='-'): text = stringify(text) if text is None: return None text = text.replace(sep, WS) text = normalize(text, ascii=True) if text is None: return None return text.replace(WS, sep)
A simple slug generator.
def other(wxcodes: typing.List[str]) -> str: ret = [] for code in wxcodes: item = translate.wxcode(code) if item.startswith('Vicinity'): item = item.lstrip('Vicinity ') + ' in the Vicinity' ret.append(item) return '. '.join(ret)
Format wx codes into a spoken word string
def visit_assign(self, node, parent): type_annotation = self.check_type_comment(node) newnode = nodes.Assign(node.lineno, node.col_offset, parent) newnode.postinit( targets=[self.visit(child, newnode) for child in node.targets], value=self.visit(node.value, newnode), type_annotation=type_annotation, ) return newnode
visit a Assign node by returning a fresh instance of it
def subscribe(self, topic, callback, qos): if topic in self.topics: return def _message_callback(mqttc, userdata, msg): callback(msg.topic, msg.payload.decode('utf-8'), msg.qos) self._mqttc.subscribe(topic, qos) self._mqttc.message_callback_add(topic, _message_callback) self.topics[topic] = callback
Subscribe to an MQTT topic.
def delegate(self, fn, *args, **kwargs): callback = functools.partial(fn, *args, **kwargs) coro = self.loop.run_in_executor(self.subexecutor, callback) return asyncio.ensure_future(coro)
Return the given operation as an asyncio future.
def visitTerminal(self, ctx): text = ctx.getText() return Terminal.from_text(text, ctx)
Converts case insensitive keywords and identifiers to lowercase
def _time_reduce(self, arr, reduction): if self.dtype_in_time == 'av' or not self.def_time: return arr reductions = { 'ts': lambda xarr: xarr, 'av': lambda xarr: xarr.mean(internal_names.YEAR_STR), 'std': lambda xarr: xarr.std(internal_names.YEAR_STR), } try: return reductions[reduction](arr) except KeyError: raise ValueError("Specified time-reduction method '{}' is not " "supported".format(reduction))
Perform the specified time reduction on a local time-series.
def reset(self): self.domain = \ dns.name.Name(dns.name.from_text(socket.gethostname())[1:]) if len(self.domain) == 0: self.domain = dns.name.root self.nameservers = [] self.localhosts = set([ 'localhost', 'loopback', '127.0.0.1', '0.0.0.0', '::1', 'ip6-localhost', 'ip6-loopback', ]) self.interfaces = set() self.search = set() self.search_patterns = ['www.%s.com', 'www.%s.org', 'www.%s.net', ] self.port = 53 self.timeout = 2.0 self.lifetime = 30.0 self.keyring = None self.keyname = None self.keyalgorithm = dns.tsig.default_algorithm self.edns = -1 self.ednsflags = 0 self.payload = 0 self.cache = None
Reset all resolver configuration to the defaults.
def update_last_sm_origin_meta_data(self): self.meta['last_saved']['time'] = self.state_machine_model.state_machine.last_update self.meta['last_saved']['file_system_path'] = self.state_machine_model.state_machine.file_system_path
Update the auto backup meta data with information of the state machine origin
def list_alarms(self, limit=None, marker=None, return_next=False): return self._alarm_manager.list(limit=limit, marker=marker, return_next=return_next)
Returns a list of all the alarms created on this entity.
def update(self, params=None, client=c): uri = self.parent.uri if not params or not self.res: self.get_params() return d = self.payload for k, v in params.items(): m = d["currentConfiguration"][self.parameter_map[k]]["message"] if isinstance(v, bool) or isinstance(v, str): m["value"] = v else: try: m["expression"] = str(v) except KeyError: m["value"] = str(v) res = client.update_configuration(uri.did, uri.wvm, uri.eid, json.dumps(d)) if res.status_code == 200: self.res = res
Push params to OnShape and synchronize the local copy
def wants(cls, *service_names): def _decorator(cls_): for service_name in service_names: cls_._services_requested[service_name] = "want" return cls_ return _decorator
A class decorator to indicate that an XBlock class wants particular services.
def coerce_to_decimal(value): if isinstance(value, decimal.Decimal): return value else: try: return decimal.Decimal(value) except decimal.InvalidOperation as e: raise GraphQLInvalidArgumentError(e)
Attempt to coerce the value to a Decimal, or raise an error if unable to do so.
def execute(self): r = self._s.execute() r._faceted_search = self return r
Execute the search and return the response.
def limit_gen(limit, iterable): limit = int(limit) assert limit >= 0, 'negative limit' for item in iterable: if limit <= 0: break yield item limit -= 1
A generator that applies a count `limit`.
def __install_eggs(self, config): egg_carton = (self.directory.install_directory(self.feature_name), 'requirements.txt') eggs = self.__gather_eggs(config) self.logger.debug("Installing eggs %s..." % eggs) self.__load_carton(egg_carton, eggs) self.__prepare_eggs(egg_carton, config)
Install eggs for a particular configuration
def shuffle(self, random=None): random_.shuffle(self._list, random=random) for i, elem in enumerate(self._list): self._dict[elem] = i
Shuffle all of the elements in self randomly.
def prepare_data(): ((x_train, y_train), (x_test, y_test)) = DATASET.load_data() x_train = x_train.astype("float32") x_test = x_test.astype("float32") x_train /= 255.0 x_test /= 255.0 return ((x_train, y_train), (x_test, y_test))
Load and normalize data.
def dump_model_data(request, app_label, model_label): return dump_to_response(request, '%s.%s' % (app_label, model_label), [], '-'.join((app_label, model_label)))
Exports data from a model.
def from_dict(cls, d): o = super(Signature, cls).from_dict(d) if 'content' in d: try: o._content = d['content']['_content'] o._contenttype = d['content']['type'] except TypeError: o._content = d['content'][-1]['_content'] o._contenttype = d['content'][-1]['type'] return o
Override default, adding the capture of content and contenttype.
def visit_ExtSlice(self, node: ast.ExtSlice) -> Tuple[Any, ...]: result = tuple(self.visit(node=dim) for dim in node.dims) self.recomputed_values[node] = result return result
Visit each dimension of the advanced slicing and assemble the dimensions in a tuple.
def append(self, row_dict): entry = self.client.InsertRow(row_dict, self.key, self.worksheet) self.feed.entry.append(entry) return GDataRow(entry, sheet=self, deferred_save=self.deferred_save)
Add a row to the spreadsheet, returns the new row
def check_signature(signature, *args, **kwargs): return hmac.compare_digest(signature, create_signature(*args, **kwargs))
Check for the signature is correct.
def output(self, stream, disabletransferencoding = None): if self._sendHeaders: raise HttpProtocolException('Cannot modify response, headers already sent') self.outputstream = stream try: content_length = len(stream) except Exception: pass else: self.header(b'Content-Length', str(content_length).encode('ascii')) if disabletransferencoding is not None: self.disabledeflate = disabletransferencoding self._startResponse()
Set output stream and send response immediately
def reorder_indices(self, indices_order): 'reorder all the indices' indices_order, single = convert_index_to_keys(self.indices, indices_order) old_indices = force_list(self.indices.keys()) if indices_order == old_indices: return if set(old_indices) != set(indices_order): raise KeyError('Keys in the new order do not match existing keys') new_idx = [old_indices.index(i) for i in indices_order] items = [map(i.__getitem__, new_idx) for i in self.items()] self.clear(True) _MI_init(self, items, indices_order)
reorder all the indices
def inject(*injections): def _decorate(func): def _decorated(*args, **kwargs): args = list(args) keys_to_inject = [name for name in injections if name not in kwargs] for key in keys_to_inject: kwargs[key] = get_current_scope().container.get(key) return func(*args, **kwargs) return _decorated return _decorate
Resolves dependencies using global container and passed it with optional parameters
def Y(self, value): if isinstance(value, (int, float, long, types.NoneType)): self._y = value
sets the Y coordinate
def __Finish(self, rootTable, sizePrefix): N.enforce_number(rootTable, N.UOffsetTFlags) prepSize = N.UOffsetTFlags.bytewidth if sizePrefix: prepSize += N.Int32Flags.bytewidth self.Prep(self.minalign, prepSize) self.PrependUOffsetTRelative(rootTable) if sizePrefix: size = len(self.Bytes) - self.Head() N.enforce_number(size, N.Int32Flags) self.PrependInt32(size) self.finished = True return self.Head()
Finish finalizes a buffer, pointing to the given `rootTable`.
def consume_keys_asynchronous_processes(self): print("\nLooking up " + self.input_queue.qsize().__str__() + " keys from " + self.source_name + "\n") jobs = multiprocessing.cpu_count()*4 if (multiprocessing.cpu_count()*4 < self.input_queue.qsize()) \ else self.input_queue.qsize() pool = multiprocessing.Pool(processes=jobs, maxtasksperchild=10) for x in range(jobs): pool.apply(self.data_worker, [], self.worker_args) pool.close() pool.join()
Work through the keys to look up asynchronously using multiple processes
def build_attrs(self, *args, **kwargs): attrs = super(HeavySelect2Mixin, self).build_attrs(*args, **kwargs) self.widget_id = signing.dumps(id(self)) attrs['data-field_id'] = self.widget_id attrs.setdefault('data-ajax--url', self.get_url()) attrs.setdefault('data-ajax--cache', "true") attrs.setdefault('data-ajax--type', "GET") attrs.setdefault('data-minimum-input-length', 2) if self.dependent_fields: attrs.setdefault('data-select2-dependent-fields', " ".join(self.dependent_fields)) attrs['class'] += ' django-select2-heavy' return attrs
Set select2's AJAX attributes.
def compress(func): def wrapper(*args, **kwargs): ret = func(*args, **kwargs) logger.debug('Receive {} {} request with header: {}'.format( request.method, request.url, ['{}: {}'.format(h, request.headers.get(h)) for h in request.headers.keys()] )) if 'deflate' in request.headers.get('Accept-Encoding', ''): response.headers['Content-Encoding'] = 'deflate' ret = deflate_compress(ret) else: response.headers['Content-Encoding'] = 'identity' return ret def deflate_compress(data, compress_level=6): zobj = zlib.compressobj(compress_level, zlib.DEFLATED, zlib.MAX_WBITS, zlib.DEF_MEM_LEVEL, zlib.Z_DEFAULT_STRATEGY) return zobj.compress(b(data)) + zobj.flush() return wrapper
Compress result with deflate algorithm if the client ask for it.
def suppress(self, email): body = { "EmailAddresses": [email] if isinstance(email, str) else email} response = self._post(self.uri_for("suppress"), json.dumps(body))
Adds email addresses to a client's suppression list
def maxCtxContextualRule(maxCtx, st, chain): if not chain: return max(maxCtx, st.GlyphCount) elif chain == 'Reverse': return max(maxCtx, st.GlyphCount + st.LookAheadGlyphCount) return max(maxCtx, st.InputGlyphCount + st.LookAheadGlyphCount)
Calculate usMaxContext based on a contextual feature rule.
def _from_string(cls, serialized): library_key = LibraryLocator._from_string(serialized) parsed_parts = LibraryLocator.parse_url(serialized) block_id = parsed_parts.get('block_id', None) if block_id is None: raise InvalidKeyError(cls, serialized) block_type = parsed_parts.get('block_type') if block_type is None: raise InvalidKeyError(cls, serialized) return cls(library_key, parsed_parts.get('block_type'), block_id)
Requests LibraryLocator to deserialize its part and then adds the local deserialization of block
def exclusions(self): exclusion_rules = [ r.strip() for r in self.config.get("browser_exclude_rule", "").split(",") if r.strip() ] return exclusion_rules
Return list of browser exclusion rules defined in the Configuration.
def verify(self, base_path, update=False): return self.project.verify_submission(base_path, self, update=update)
Verify the submission and return testables that can be executed.
def updateRouterStatus(self): print '%s call updateRouterStatus' % self.port cmd = 'state' while True: state = self.__sendCommand(cmd)[0] if state == 'detached': continue elif state == 'child': break else: return False cmd = 'state router' return self.__sendCommand(cmd)[0] == 'Done'
force update to router as if there is child id request
def _run_spellcheck_linter(matched_filenames, cache_dir, show_lint_files): from polysquarelinter import lint_spelling_only as lint from prospector.message import Message, Location for filename in matched_filenames: _debug_linter_status("spellcheck-linter", filename, show_lint_files) return_dict = dict() def _custom_reporter(error, file_path): line = error.line_offset + 1 key = _Key(file_path, line, "file/spelling_error") loc = Location(file_path, None, None, line, 0) desc = lint._SPELLCHECK_MESSAGES[error.error_type].format(error.word) return_dict[key] = Message("spellcheck-linter", "file/spelling_error", loc, desc) lint._report_spelling_error = _custom_reporter lint.main([ "--spellcheck-cache=" + os.path.join(cache_dir, "spelling"), "--stamp-file-path=" + os.path.join(cache_dir, "jobstamps", "polysquarelinter"), "--technical-terms=" + os.path.join(cache_dir, "technical-terms"), ] + matched_filenames) return return_dict
Run spellcheck-linter on matched_filenames.
def update_view_state(self, view, state): if view.name not in self: self[view.name] = Bunch() self[view.name].update(state)
Update the state of a view.
def _create_multi_buffer_action(self): icon = resources_path('img', 'icons', 'show-multi-buffer.svg') self.action_multi_buffer = QAction( QIcon(icon), self.tr('Multi Buffer'), self.iface.mainWindow()) self.action_multi_buffer.setStatusTip(self.tr( 'Open InaSAFE multi buffer')) self.action_multi_buffer.setWhatsThis(self.tr( 'Open InaSAFE multi buffer')) self.action_multi_buffer.triggered.connect(self.show_multi_buffer) self.add_action( self.action_multi_buffer, add_to_toolbar=self.full_toolbar)
Create action for multi buffer dialog.
def delete_intf_router(self, name, tenant_id, rout_id, subnet_lst): try: for subnet_id in subnet_lst: body = {'subnet_id': subnet_id} intf = self.neutronclient.remove_interface_router(rout_id, body=body) intf.get('id') except Exception as exc: LOG.error("Failed to delete router interface %(name)s, " " Exc %(exc)s", {'name': name, 'exc': str(exc)}) return False return True
Delete the openstack router and remove the interfaces attached.
def debug_callback(event, *args, **kwds): l = ['event %s' % (event.type,)] if args: l.extend(map(str, args)) if kwds: l.extend(sorted('%s=%s' % t for t in kwds.items())) print('Debug callback (%s)' % ', '.join(l))
Example callback, useful for debugging.
def increase_and_check_counter(self): self.counter += 1 self.counter %= self.period if not self.counter: return True else: return False
increase counter by one and check whether a period is end
def add_epoch_number(batch: Batch, epoch: int) -> Batch: for instance in batch.instances: instance.fields['epoch_num'] = MetadataField(epoch) return batch
Add the epoch number to the batch instances as a MetadataField.
def _unicode_decode_extracted_tb(extracted_tb): return [(_decode(file), line_number, _decode(function), _decode(text)) for file, line_number, function, text in extracted_tb]
Return a traceback with the string elements translated into Unicode.
def invert_node_predicate(node_predicate: NodePredicate) -> NodePredicate: def inverse_predicate(graph: BELGraph, node: BaseEntity) -> bool: return not node_predicate(graph, node) return inverse_predicate
Build a node predicate that is the inverse of the given node predicate.
def taxon_info(taxid, ncbi, outFH): taxid = int(taxid) tax_name = ncbi.get_taxid_translator([taxid])[taxid] rank = list(ncbi.get_rank([taxid]).values())[0] lineage = ncbi.get_taxid_translator(ncbi.get_lineage(taxid)) lineage = ['{}:{}'.format(k,v) for k,v in lineage.items()] lineage = ';'.join(lineage) x = [str(x) for x in [tax_name, taxid, rank, lineage]] outFH.write('\t'.join(x) + '\n')
Write info on taxid
def pause_resume(self): if self.is_paused(): urlopen(self.url + "&mode=resume") else: urlopen(self.url + "&mode=pause")
Toggle between pausing or resuming downloading.
def _DecodeUnrecognizedFields(message, pair_type): new_values = [] codec = _ProtoJsonApiTools.Get() for unknown_field in message.all_unrecognized_fields(): value, _ = message.get_unrecognized_field_info(unknown_field) value_type = pair_type.field_by_name('value') if isinstance(value_type, messages.MessageField): decoded_value = DictToMessage(value, pair_type.value.message_type) else: decoded_value = codec.decode_field( pair_type.value, value) try: new_pair_key = str(unknown_field) except UnicodeEncodeError: new_pair_key = protojson.ProtoJson().decode_field( pair_type.key, unknown_field) new_pair = pair_type(key=new_pair_key, value=decoded_value) new_values.append(new_pair) return new_values
Process unrecognized fields in message.
def update(self, cont): self.max_time = max(self.max_time, cont.max_time) if cont.items is not None: if self.items is None: self.items = cont.items else: self.items.update(cont.items)
Update this instance with the contextualize passed.
def repo(name: str, owner: str) -> snug.Query[dict]: return json.loads((yield f'/repos/{owner}/{name}').content)
a repository lookup by owner and name
def initStats(self): url = "%s://%s:%d/%s" % (self._proto, self._host, self._port, self._statuspath) response = util.get_url(url, self._user, self._password) self._statusDict = {} for line in response.splitlines(): mobj = re.match('\s*(\d+)\s+(\d+)\s+(\d+)\s*$', line) if mobj: idx = 0 for key in ('accepts','handled','requests'): idx += 1 self._statusDict[key] = util.parse_value(mobj.group(idx)) else: for (key,val) in re.findall('(\w+):\s*(\d+)', line): self._statusDict[key.lower()] = util.parse_value(val)
Query and parse Nginx Web Server Status Page.
def compare_config(self): if self.config_session is None: return '' else: commands = ['show session-config named %s diffs' % self.config_session] result = self.device.run_commands(commands, encoding='text')[0]['output'] result = '\n'.join(result.splitlines()[2:]) return result.strip()
Implementation of NAPALM method compare_config.
def rows(self): for t in self.terms: for row in t.rows: term, value = row if isinstance(value, dict): term, args, remain = self._args(term, value) yield term, args for k, v in remain.items(): yield term.split('.')[-1] + '.' + k, v else: yield row
Yield rows for the section
def rollback(self): commands = [] commands.append('configure replace flash:rollback-0') commands.append('write memory') self.device.run_commands(commands)
Implementation of NAPALM method rollback.
def ssh(cls, vm_id, login, identity, args=None): cmd = ['ssh'] if identity: cmd.extend(('-i', identity,)) version, ip_addr = cls.vm_ip(vm_id) if version == 6: cmd.append('-6') if not ip_addr: cls.echo('No IP address found for vm %s, aborting.' % vm_id) return cmd.append('%s@%s' % (login, ip_addr,)) if args: cmd.extend(args) cls.echo('Requesting access using: %s ...' % ' '.join(cmd)) return cls.execute(cmd, False)
Spawn an ssh session to virtual machine.
def create_signaling(args): if args.signaling == 'tcp-socket': return TcpSocketSignaling(args.signaling_host, args.signaling_port) elif args.signaling == 'unix-socket': return UnixSocketSignaling(args.signaling_path) else: return CopyAndPasteSignaling()
Create a signaling method based on command-line arguments.
def delete_port_postcommit(self, context): port = context.current log_context("delete_port_postcommit: port", port) self._delete_port_resources(port, context.host) self._try_to_release_dynamic_segment(context)
Delete the port from CVX
def exit_if_path_not_found(path): if not os.path.exists(path): ui.error(c.MESSAGES["path_missing"], path) sys.exit(1)
Exit if the path is not found.
def __update(self): width, height = self.size super(BaseWidget, self).__setattr__("width", width) super(BaseWidget, self).__setattr__("height", height) super(BaseWidget, self).__setattr__(self.anchor, self.pos)
This is called each time an attribute is asked, to be sure every params are updated, beceause of callbacks.
def conv1d_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs): return conv_block_internal(conv1d, inputs, filters, dilation_rates_and_kernel_sizes, **kwargs)
A block of standard 1d convolutions.
def load_registered_fixtures(context): runner = context._runner step_registry = getattr(runner, 'step_registry', None) if not step_registry: step_registry = module_step_registry.registry for step in context.scenario.all_steps: match = step_registry.find_match(step) if match and hasattr(match.func, 'registered_fixtures'): if not context.test.fixtures: context.test.fixtures = [] context.test.fixtures.extend(match.func.registered_fixtures)
Apply fixtures that are registered with the @fixtures decorator.
def citation_director(**kwargs): qualifier = kwargs.get('qualifier', '') content = kwargs.get('content', '') if qualifier == 'publicationTitle': return CitationJournalTitle(content=content) elif qualifier == 'volume': return CitationVolume(content=content) elif qualifier == 'issue': return CitationIssue(content=content) elif qualifier == 'pageStart': return CitationFirstpage(content=content) elif qualifier == 'pageEnd': return CitationLastpage(content=content) else: return None
Direct the citation elements based on their qualifier.
def filter_input(keys, raw): if len(keys) == 1: if keys[0] in UI.keys['up']: keys[0] = 'up' elif keys[0] in UI.keys['down']: keys[0] = 'down' elif len(keys[0]) == 4 and keys[0][0] == 'mouse press': if keys[0][1] == 4: keys[0] = 'up' elif keys[0][1] == 5: keys[0] = 'down' return keys
Adds fancy mouse wheel functionality and VI navigation to ListBox
def get(cls, object_version, key): return cls.query.filter_by( version_id=as_object_version_id(object_version), key=key, ).one_or_none()
Get the tag object.
def resume(self): with self._wake: self._paused = False self._wake.notifyAll()
Resumes the response stream.
def to_gpu(x, *args, **kwargs): return x.cuda(*args, **kwargs) if USE_GPU else x
puts pytorch variable to gpu, if cuda is available and USE_GPU is set to true.
def add_text(self, setting, width=300, height=100, multiline=False): tab = self.panel(setting.tab) if multiline: ctrl = wx.TextCtrl(tab, -1, "", size=(width,height), style=wx.TE_MULTILINE|wx.TE_PROCESS_ENTER) else: ctrl = wx.TextCtrl(tab, -1, "", size=(width,-1) ) self._add_input(setting, ctrl)
add a text input line
def read_ical(self, ical_file_location): with open(ical_file_location, 'r') as ical_file: data = ical_file.read() self.cal = Calendar.from_ical(data) return self.cal
Read the ical file
def asinh(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_asinh, (BigFloat._implicit_convert(x),), context, )
Return the inverse hyperbolic sine of x.
def visit_import(self, node, parent): names = [(alias.name, alias.asname) for alias in node.names] newnode = nodes.Import( names, getattr(node, "lineno", None), getattr(node, "col_offset", None), parent, ) for (name, asname) in newnode.names: name = asname or name parent.set_local(name.split(".")[0], newnode) return newnode
visit a Import node by returning a fresh instance of it
def _parse_complex_list(self, prop): xpath_root = self._get_xroot_for(prop) xpath_map = self._data_structures[prop] return parse_complex_list(self._xml_tree, xpath_root, xpath_map, prop)
Default parsing operation for lists of complex structs
def fetchone(self, sql: str, *args) -> Optional[Sequence[Any]]: self.ensure_db_open() cursor = self.db.cursor() self.db_exec_with_cursor(cursor, sql, *args) try: return cursor.fetchone() except: log.exception("fetchone: SQL was: " + sql) raise
Executes SQL; returns the first row, or None.
def dependencies(source): loader = ClassLoader(source, max_cache=-1) all_dependencies = set() for klass in loader.classes: new_dependencies = loader.dependencies(klass) - all_dependencies all_dependencies.update(new_dependencies) for new_dep in new_dependencies: click.echo(new_dep)
Output a list of all classes referenced by the given source.
def move(self, dst): if self.drive != dst.drive: raise NotImplementedError( "Moving between instances is not implemented yet") self._accessor.move(self, dst)
Move artifact from this path to destinaiton.
def copy(self): params = {} for key, val in self.__dict__.items(): if 'matrix' not in key: k = key[1:] if key[0] == '_' else key params[k] = val return self.__class__(**params)
Returns a copy of the projection matrix
def render(self, name, value, attrs=None, renderer=None): if django.VERSION >= (1, 11): return super(BetterFileInput, self).render(name, value, attrs) t = render_to_string( template_name=self.template_name, context=self.get_context(name, value, attrs), ) return mark_safe(t)
For django 1.10 compatibility
def app_stop(device_id, app_id): if not is_valid_app_id(app_id): abort(403) if not is_valid_device_id(device_id): abort(403) if device_id not in devices: abort(404) success = devices[device_id].stop_app(app_id) return jsonify(success=success)
stops an app with corresponding package name
async def read_frame(self, max_size: int) -> Frame: frame = await Frame.read( self.reader.readexactly, mask=not self.is_client, max_size=max_size, extensions=self.extensions, ) logger.debug("%s < %r", self.side, frame) return frame
Read a single frame from the connection.
def submit(self, *args, func=None, monitor=None): monitor = monitor or self.monitor func = func or self.task_func if not hasattr(self, 'socket'): self.__class__.running_tasks = self.tasks self.socket = Socket(self.receiver, zmq.PULL, 'bind').__enter__() monitor.backurl = 'tcp://%s:%s' % ( config.dbserver.host, self.socket.port) assert not isinstance(args[-1], Monitor) dist = 'no' if self.num_tasks == 1 else self.distribute if dist != 'no': args = pickle_sequence(args) self.sent += numpy.array([len(p) for p in args]) res = submit[dist](self, func, args, monitor) self.tasks.append(res)
Submit the given arguments to the underlying task
def visit_UnaryOperation(self, node): if node.op.nature == Nature.PLUS: return +self.visit(node.right) elif node.op.nature == Nature.MINUS: return -self.visit(node.right) elif node.op.nature == Nature.NOT: return Bool(not self.visit(node.right))
Visitor for `UnaryOperation` AST node.
def _chunk(self, response, size=4096): method = response.headers.get("content-encoding") if method == "gzip": d = zlib.decompressobj(16+zlib.MAX_WBITS) b = response.read(size) while b: data = d.decompress(b) yield data b = response.read(size) del data else: while True: chunk = response.read(size) if not chunk: break yield chunk
downloads a web response in pieces
def _get_metadata_model(name=None): if name is not None: try: return registry[name] except KeyError: if len(registry) == 1: valid_names = 'Try using the name "%s" or simply leaving it '\ 'out altogether.' % list(registry)[0] else: valid_names = "Valid names are " + ", ".join( '"%s"' % k for k in list(registry)) raise Exception( "Metadata definition with name \"%s\" does not exist.\n%s" % ( name, valid_names)) else: assert len(registry) == 1, \ "You must have exactly one Metadata class, if using " \ "get_metadata() without a 'name' parameter." return list(registry.values())[0]
Find registered Metadata object.
def linebreaks_safe(value, autoescape=True): if isinstance(value, string_types) and '\n' in value: return linebreaks_filter(value, autoescape=autoescape) return value
Adds linebreaks only for text that has a newline character.
def _handle_tag_defineshape4(self): obj = _make_object("DefineShape4") obj.ShapeId = unpack_ui16(self._src) obj.ShapeBounds = self._get_struct_rect() obj.EdgeBounds = self._get_struct_rect() bc = BitConsumer(self._src) bc.u_get(5) obj.UsesFillWindingRule = bc.u_get(1) obj.UsesNonScalingStrokes = bc.u_get(1) obj.UsesScalingStrokes = bc.u_get(1) obj.Shapes = self._get_struct_shapewithstyle(4) return obj
Handle the DefineShape4 tag.
def clear(self): self._config = configparser.RawConfigParser() self._override_config = {} self.read_config()
Restart with a clean config
def error_state(self): self.buildstate.state.lasttime = time() self.buildstate.commit() return self.buildstate.state.error
Set the error condition
def _parse_desc(node): desc = '' if len(node) == 0: return '<p>' + node.text + '</p>' for n in node: if n.tag == 'p': desc += '<p>' + _join_lines(n.text) + '</p>' elif n.tag == 'ol' or n.tag == 'ul': desc += '<ul>' for c in n: if c.tag == 'li': desc += '<li>' + _join_lines(c.text) + '</li>' else: raise ParseError('Expected <li> in <%s>, got <%s>' % (n.tag, c.tag)) desc += '</ul>' else: raise ParseError('Expected <p>, <ul>, <ol> in <%s>, got <%s>' % (node.tag, n.tag)) return desc
A quick'n'dirty description parser
def parseFeed(filename, yesterday): dom = xml.dom.minidom.parse(filename) getText = lambda node, tag: node.getElementsByTagName(tag)[0].childNodes[0].data getNode = lambda tag: dom.getElementsByTagName(tag) content = getNode('channel')[0] feedTitle = getText(content, 'title') feedLink = getText(content, 'link') feedDesc = getText(content, 'description') feed = Feed(feedTitle, feedLink, feedDesc) for item in getNode('item'): itemDate = time.strptime(getText(item, 'pubDate'), '%a, %d %b %Y %H:%M:%S GMT') if (itemDate > yesterday): feed.addItem(getText(item, 'title'), getText(item, 'link'), getText(item, 'description'), getText(item, 'pubDate')) return feed
Parse an RSS feed and filter only entries that are newer than yesterday.
def _set_allowed_services_and_actions(self, services): for service in services: self.services[service['name']] = {} for action in service['actions']: name = action.pop('name') self.services[service['name']][name] = action
Expect services to be a list of service dictionaries, each with `name` and `actions` keys.
async def update_trend_data(self, startdate, enddate): url = '{}/users/{}/trends'.format(API_URL, self.userid) params = { 'tz': self.device.tzone, 'from': startdate, 'to': enddate } trends = await self.device.api_get(url, params) if trends is None: _LOGGER.error('Unable to fetch eight trend data.') else: self.trends = trends['days']
Update trends data json for specified time period.
def extract_hosted_zip(data_url, save_dir, exclude_term=None): zip_name = os.path.join(save_dir, 'temp.zip') try: print('Downloading %r to %r' % (data_url, zip_name)) zip_name, hdrs = urllib.request.urlretrieve(url=data_url, filename=zip_name) print('Download successfully completed') except IOError as e: print("Could not successfully retrieve %r" % data_url) raise e extract_zip(zip_name=zip_name, exclude_term=exclude_term) os.unlink(zip_name) print("Extraction Complete")
Downloads, then extracts a zip file.