text
stringlengths
78
104k
score
float64
0
0.18
def copyVarStatesFrom(self, particleState, varNames): """Copy specific variables from particleState into this particle. Parameters: -------------------------------------------------------------- particleState: dict produced by a particle's getState() method varNames: which variab...
0.006056
def human_readable_size(num, suffix='B'): """ FROM http://stackoverflow.com/a/1094933/1958900 """ for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix)
0.025723
def generation_dispatchable(self): """ Get generation time series of dispatchable generators (only active power) Returns ------- :pandas:`pandas.DataFrame<dataframe>` See class definition for details. """ try: return self._generat...
0.006682
def _fromJSON(cls, jsonobject): """Generates a new instance of :class:`maspy.core.Sai` from a decoded JSON object (as generated by :func:`maspy.core.Sai._reprJSON()`). :param jsonobject: decoded JSON object :returns: a new instance of :class:`Sai` """ newInstance = cls(...
0.002941
async def replace_local_did_metadata(self, loc_did: str, metadata: dict) -> DIDInfo: """ Replace the metadata associated with a local DID. Raise WalletState if wallet is closed, AbsentRecord for no such local DID. :param loc_did: local DID of interest :param metadata: new metad...
0.007965
def get_queryset(self, **options): """ Filters the list of log objects to display """ days = options.get('days') queryset = TimelineLog.objects.order_by('-timestamp') if days: try: start = timezone.now() - timedelta(days=days) excep...
0.005607
def login(session): """Login to Voobly.""" if not session.auth.username or not session.auth.password: raise VooblyError('must supply username and password') _LOGGER.info("logging in (no valid cookie found)") session.cookies.clear() try: session.get(session.auth.base_url + LOGIN_PAGE)...
0.001393
def _ReadData(self, file_object, file_offset, data_size): """Reads data. Args: file_object (dvfvs.FileIO): a file-like object to read. file_offset (int): offset of the data relative to the start of the file-like object. data_size (int): size of the data. The resulting data size much...
0.00519
def racks(self): """ Gets the Racks API client. Returns: Racks: """ if not self.__racks: self.__racks = Racks(self.__connection) return self.__racks
0.00905
def claim_new(self) -> Iterable[str]: """Checks for messages in the ``new`` subdirectory, moving them to ``cur`` and returning their keys. """ new_subdir = self._paths['new'] cur_subdir = self._paths['cur'] for name in os.listdir(new_subdir): new_path = os.pa...
0.003384
def u2opener(self): """ Create a urllib opener. @return: An opener. @rtype: I{OpenerDirector} """ if self.urlopener is None: return urllib2.build_opener(*self.u2handlers()) return self.urlopener
0.007576
def expr_to_str(n, l=None): """ construct SQL string from expression node """ op = n[0] if op.startswith('_') and op.endswith('_'): op = op.strip('_') if op == 'var': return n[1] elif op == 'literal': if isinstance(n[1], basestring): re...
0.002714
def _build_filters(_filters): """Builds filters using the filter options passed into the CLI. This only supports the equals keyword at the moment. """ root = utils.NestedDict({}) for _filter in _filters: operation = None for operation, token in SPLIT_TOKENS: # split "som...
0.000781
def get_objective_ids_by_objective_bank(self, objective_bank_id): """Gets the list of ``Objective`` ``Ids`` associated with an ``ObjectiveBank``. arg: objective_bank_id (osid.id.Id): ``Id`` of the ``ObjectiveBank`` return: (osid.id.IdList) - list of related objectives ...
0.00431
def _update_length(self): """Update the length field of the struct.""" action_length = 4 + len(self.field.pack()) overflow = action_length % 8 self.length = action_length if overflow: self.length = action_length + 8 - overflow
0.007194
def norm(x, encoding="latin1"): "Convertir acentos codificados en ISO 8859-1 u otro, a ASCII regular" if not isinstance(x, basestring): x = unicode(x) elif isinstance(x, str): x = x.decode(encoding, 'ignore') return unicodedata.normalize('NFKD', x).encode('ASCII', 'ignore')
0.003268
def Nu(L: float, h: float, k: float) -> float: """ Calculate the Nusselt number. :param L: [m] heat transfer surface characteristic length. :param h: [W/K/m2] convective heat transfer coefficient. :param k: [W/K/m] fluid thermal conductivity. :returns: float """ return h * L / k
0.003185
def add_federation(self, provider, federated_id): """ Add federated login to the current user :param provider: :param federated_id: :return: """ models.AuthUserFederation.new(user=self, provider=provider, ...
0.00551
def validate_instance_id(self, instid): ''' Validate instance ID ''' # 1-63 alphanumeric characters, first must be a letter. if re.match('[\w-]+$', instid) is not None: if len(instid) <= 63 and len(instid) >= 1: if instid[0].isalpha(): return True ...
0.009281
def start_process(self, program, arguments=None, working_dir=None, print_command=True, use_pseudo_terminal=True, env=None): """ Starts the child process. :param program: program to start :param arguments: list of program arguments :param working_dir: workin...
0.006471
def useThis(self, *args, **kwargs): """ Change parameter of the callback function. :param *args, **kwargs: parameter(s) to use when executing the callback function. """ self._callback = functools.partial(self._callback, *args, **kwargs)
0.006993
def event_date(self, event_date): """Set the Events "event date" value.""" self._group_data['eventDate'] = self._utils.format_datetime( event_date, date_format='%Y-%m-%dT%H:%M:%SZ' )
0.009174
def draw_circuit(circuit, filename, direction = 'lr', hunit = HUNIT, vunit = VUNIT, rhmargin = RHMARGIN, rvmargin = RVMARGIN, rpermutation_length = RPLENGTH, draw_boxes = True, permutation_arrows = False): """ Generate a graphic representation of circu...
0.017857
def zone_schedules_backup(self, filename): """Backup all zones on control system to the given file.""" _LOGGER.info("Backing up schedules from ControlSystem: %s (%s)...", self.systemId, self.location.name) schedules = {} if self.hotwater: _LOGGER.info("...
0.001786
def resolution_profile(self, graph, partition_type, resolution_range, weights=None, bisect_func=lambda p: p.bisect_value(), min_diff_bisect_value=1, min_diff_resolution=1e-3, linear_bisection=False, number_iterations=1, **kwargs ): ...
0.009026
def _query_dns(self, host: str, family: int=socket.AF_INET) \ -> dns.resolver.Answer: '''Query DNS using Python. Coroutine. ''' record_type = {socket.AF_INET: 'A', socket.AF_INET6: 'AAAA'}[family] event_loop = asyncio.get_event_loop() query = functools.parti...
0.003534
def reload_scoped_variables_list_store(self): """Reloads the scoped variable list store from the data port models""" if isinstance(self.model, ContainerStateModel): tmp = self.get_new_list_store() for sv_model in self.model.scoped_variables: data_type = sv_model....
0.003281
def _remove_some_work_units(self, work_spec_name, work_unit_names, suffix='', priority_min='-inf', priority_max='+inf'): '''Remove some units from somewhere.''' now = time.time() if work_unit_names is None: count = 0 ...
0.004072
def stack_reparameterization_layer(self, layer_size): """ Perform reparameterization trick for latent variables. :param layer_size: the size of latent variable """ self.rep_layer = ReparameterizationLayer(layer_size, sample=self.sample) self.stack_encoders(self.rep_layer)
0.009375
def library_specs(self): """Lists of specs to resolve to jar_libraries containing more jars.""" return [Address.parse(spec, relative_to=self.address.spec_path).spec for spec in self.payload.library_specs]
0.004464
def order(self, asset, amount, limit_price=None, stop_price=None, style=None): """Place an order. Parameters ---------- asset : Asset The asset that this order is for. amount : int The ...
0.003706
def fetchall_sp(s,p): """ fetch all triples for a property """ query = """ SELECT * WHERE {{ <{s}> <{p}> ?x }} """.format(s=s, p=prefixmap[p]) bindings = run_sparql(query) rows = [r['x']['value'] for r in bindings] return rows
0.007407
def get_error_page(self): """ Method returning error page. Should return string. By default it find element with class ``error-page`` and returns text of ``h1`` header. You can change this method accordingly to your app. Error page returned from this method is used in decorator...
0.003115
def match_description(self, description, string_match_type=DEFAULT_STRING_MATCH_TYPE, match=True): """Adds a description name to match. Multiple description matches can be added to perform a boolean ``OR`` among them. arg: description (string): description to match arg: s...
0.004024
def get_host_uuid(self): """Request host UUID of the server. :returns: the host UUID of the server :raises: IloConnectionError if failed connecting to the iLO. """ xml = self._request_host() root = etree.fromstring(xml) data = self._elementtree_to_dict(root) ...
0.005168
def sensor_offsets_send(self, mag_ofs_x, mag_ofs_y, mag_ofs_z, mag_declination, raw_press, raw_temp, gyro_cal_x, gyro_cal_y, gyro_cal_z, accel_cal_x, accel_cal_y, accel_cal_z, force_mavlink1=False): ''' Offsets and calibrations values for hardware sensors. This makes it e...
0.005242
def _ordered_node_addrs(self, function_address): """ For a given function, return all nodes in an optimal traversal order. If the function does not exist, return an empty list. :param int function_address: Address of the function. :return: A ordered list of the nodes. :r...
0.01
def GetInput(self): """Yield client urns.""" clients = GetAllClients(token=self.token) logging.debug("Got %d clients", len(clients)) return clients
0.006135
def process_request(self, request): """ Redirects the current request if there is a matching Redirect model with the current request URL as the old_path field. """ site = request.site cache_key = '{prefix}-{site}'.format(prefix=settings.REDIRECT_CACHE_KEY_PREFIX, site=sit...
0.00554
def invoke(cls, ns, banner): # pragma: nocover """ :param ns: local namespace :param banner: interactive shell startup banner Embed an interactive native python shell. """ import code py_prefix = sys.platform.startswith('java') and 'J' or 'P' shell_banne...
0.00335
def call(self, action_name, arg_in=None, http_auth=None, http_headers=None): """ Construct the XML and make the call to the device. Parse the response values into a dict. """ if arg_in is None: arg_in = {} soap_env = '{%s}' % NS_SOAP_ENV m = '{%s}' % self.ser...
0.004627
def save_dataset(self, dataset_id, filename=None, writer=None, overlay=None, compute=True, **kwargs): """Save the *dataset_id* to file using *writer* (default: geotiff).""" if writer is None and filename is None: writer = 'geotiff' elif writer is None: writer = self.get_w...
0.003861
def _phiforce(self,R,z,phi=0.,t=0.): """ NAME: _phiforce PURPOSE: evaluate the azimuthal force for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: ...
0.01848
def save(self, filename, garbage=0, clean=0, deflate=0, incremental=0, ascii=0, expand=0, linear=0, pretty=0, decrypt=1): """save(self, filename, garbage=0, clean=0, deflate=0, incremental=0, ascii=0, expand=0, linear=0, pretty=0, decrypt=1) -> PyObject *""" if self.isClosed or self.isEncrypted: ...
0.00551
def transformer_ada_lmpackedbase_dialog(): """Set of hyperparameters.""" hparams = transformer_base_vq_ada_32ex_packed() hparams.max_length = 1024 hparams.ffn_layer = "dense_relu_dense" hparams.batch_size = 4096 return hparams
0.029412
def enhance(self): """ Function enhance Enhance the object with new item or enhanced items """ self.update({'images': SubDict(self.api, self.objName, self.payloadObj, self.key, SubItemImages)})
0.006579
def _set_folium_map(self): """A map containing only the feature.""" m = Map(features=[self], width=self._width, height=self._height) self._folium_map = m.draw()
0.01087
def _read_conf_file(path): ''' Read in a config file from a given path and process it into a dictionary ''' log.debug('Reading configuration from %s', path) with salt.utils.files.fopen(path, 'r') as conf_file: try: conf_opts = salt.utils.yaml.safe_load(conf_file) or {} ex...
0.002281
def estimate_tau_exp(chains, **kwargs): """ Estimate the exponential auto-correlation time for all parameters in a chain. """ # Calculate the normalised autocorrelation function in each parameter. rho = np.nan * np.ones(chains.shape[1:]) for i in range(chains.shape[2]): try: ...
0.007991
def start(self, stats): """Start the bottle.""" # Init stats self.stats = stats # Init plugin list self.plugins_list = self.stats.getPluginsList() # Bind the Bottle TCP address/port if self.args.open_web_browser: # Implementation of the issue #946 ...
0.002587
def main(): parser = getparser() args = parser.parse_args() fn = args.fn sitename = args.sitename #User-specified output extent #Note: not checked, untested if args.extent is not None: extent = (args.extent).split() else: extent = (geolib.site_dict[sitename]).extent ...
0.010312
def _EntriesGenerator(self): """Retrieves directory entries. Since a directory can contain a vast number of entries using a generator is more memory efficient. Yields: APFSContainerPathSpec: a path specification. """ # Only the virtual root file has directory entries. volume_index = ...
0.004454
def Clone(self): """ Clone self. Returns: AccountState: """ return AccountState(self.ScriptHash, self.IsFrozen, self.Votes, self.Balances)
0.015707
def get_pdf_response(self, context, **response_kwargs): """ Renders PDF document and prepares response. :returns: Django HTTP response :rtype: :class:`django.http.HttpResponse` """ return render_to_pdf_response( request=self.request, template=self...
0.003976
def worker(data, json_file): """ Handle parameter substitution and execute command as child process. """ # PERHAPS TODO: Support either full or relative paths. with open(json_file) as fp: d = json.load(fp) json_directory = os.path.dirname(json_file) def p(*parts): return os.p...
0.001531
def column_widths(self, size, focus=False): """ Return a list of column widths. 0 values in the list mean hide corresponding column completely """ maxcol = size[0] self._cache_maxcol = maxcol widths = [width for i, (w, (t, width, b)) in enumerate(self.contents)] ...
0.005195
def parse(self, text): """Parse self.text. Args: text (str): the text to lex Returns: object: a node representing the current rule. """ tokens = self.lex(text) parser = Parser(tokens) return parser.parse()
0.006969
def cumulative_distribution(self, X): """Computes the cumulative distribution function for the copula, :math:`C(u, v)` Args: X: `np.ndarray` Returns: np.array: cumulative distribution """ self.check_fit() U, V = self.split_matrix(X) num...
0.005495
def load_rsa_public_key_file(rsakeyfile): # type: (str, str) -> # cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey """Load an RSA Public key PEM file :param str rsakeyfile: RSA public key PEM file to load :rtype: cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey :return...
0.001515
def supervise(self): """If not in a hot_loop, call supervise() to start the tasks""" self.retval = set([]) stats = TaskMgrStats( worker_count=self.worker_count, log_interval=self.log_interval, hot_loop=self.hot_loop, ) hot_loop = self.hot_loop...
0.002298
def install_deps(pkgpath): """Install plugin dependencies using pip. We import pip here to reduce load time for when its not needed. """ if os.path.exists(os.path.join(pkgpath, "requirements.txt")): logger.debug("installing dependencies") click.secho("[*] Installing dependencies") ...
0.00321
def get_config(self, retrieve='all'): """Implementation of get_config for IOS. Returns the startup or/and running configuration as dictionary. The keys of the dictionary represent the type of configuration (startup or running). The candidate is always empty string, since IOS doe...
0.00232
def open(self, create_if_not_found=True): """Open a kube config file. If the file does not exist, it creates a new file. """ try: self.data = self._read() # If the file does except FileNotFoundError as e: if create_if_not_found is True: ...
0.003887
def get(self, name, start, end, resolution, window): """ :param name: :param start: :param end: :param resolution: :param window: :return: an analysed file. """ logger.info( 'Analysing ' + name + ' from ' + start + ' to ' + end + ' at '...
0.005216
def wait(self): """ waits for the running command to finish. this is called on all running commands, eventually, except for ones that run in the background """ if not self._process_completed: self._process_completed = True exit_code = self.process.wait() ...
0.005998
def run_command(self, args: List[str], max_num_processes: int=None, max_stack_size: int=None, max_virtual_memory: int=None, as_root: bool=False, stdin: FileIO=None, timeout: int=No...
0.008241
def prior_tuples(self): """ Returns ------- prior_tuple_dict: [(Prior, PriorTuple)] The set of all priors associated with this mapper """ return {prior_tuple.prior: prior_tuple for name, prior_model in self.prior_model_tuples fo...
0.005391
def bind(self, field_name, parent): """ Create translation serializer dynamically. Takes translatable model class (shared_model) from parent serializer and it may create a serializer class on the fly if no custom class was specified. """ super(TranslatedFieldsField, self...
0.004182
def _permute_two_sample_iscs(iscs, group_parameters, i, pairwise=False, summary_statistic='median', exact_permutations=None, prng=None): """Applies two-sample permutations to ISC data Input ISCs should be n_subjects (leave-one-out approach) or n_pa...
0.000316
def calculate_parameters_with_confidence(self, independentTs, dependentTs, confidenceLevel, samplePercentage=.1): """Same functionality as calculate_parameters, just that additionally the confidence interval for a given confidenceLevel is calculated. This is done based on a sample of the depende...
0.005745
def _get_11paths_serialized_headers(x_headers): """ Prepares and returns a string ready to be signed from the 11-paths specific HTTP headers received. :param x_headers: a non necessarily ordered map (array without duplicates) of the HTTP headers to be ordered. :return: string The serialized headers, an...
0.005353
def send_single_value(self, channel: int, value: int) -> int: """ Send a single value to the uDMX :param channel: DMX channel number, 1-512 :param value: Value to be sent to channel, 0-255 :return: number of bytes actually sent """ SetSingleChannel = 1 n =...
0.006818
def get_proficiency_objective_bank_assignment_session(self, proxy): """Gets the ``OsidSession`` associated with assigning proficiencies to objective banks. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.learning.ProficiencyObjectiveBankAssignmentSession ...
0.003891
def _detectPossibleKsubcatRelsFromSent( sentence, kSubCatRelsLexicon, reverseMapping = False ): ''' Attempts to detect all possible K subcategorization relations from given sentence, using the heuristic method _detectKsubcatRelType(); Returns a dictionary of relations where the key correspo...
0.018298
def touch(self, connection=None): """ Mark this update as complete. IMPORTANT, If the marker table doesn't exist, the connection transaction will be aborted and the connection reset. Then the marker table will be created. """ self.create_marker_table() i...
0.003394
def register(self, command: str, handler: Any): """ Register a new handler for a specific slash command Args: command: Slash command handler: Callback """ if not command.startswith("/"): command = f"/{command}" LOG.info("Registering ...
0.005076
def CloseCHM(self): '''Closes the CHM archive. This function will close the CHM file, if it is open. All variables are also reset. ''' if self.filename is not None: chmlib.chm_close(self.file) self.file = None self.filename = '' sel...
0.004405
def echo_html_fenye_str(rec_num, fenye_num): ''' 生成分页的导航 ''' pagination_num = int(math.ceil(rec_num * 1.0 / 10)) if pagination_num == 1 or pagination_num == 0: fenye_str = '' elif pagination_num > 1: pager_mid, pager_pre, pager_next, pager_last, pager_home = '', '', '', '', ''...
0.004918
def save(self, segids, filepath=None, file_format='ply'): """ Save one or more segids into a common mesh format as a single file. segids: int, string, or list thereof filepath: string or None (optional) file_format: string (optional) Supported Formats: 'obj', 'ply' """ if type(segids) ...
0.010604
def list_namespaced_service_account(self, namespace, **kwargs): """ list or watch objects of kind ServiceAccount This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_service_acco...
0.002751
def float_input(message, low, high): ''' Ask a user for a float input between two values args: message (str): Prompt for user low (float): Low value, user entered value must be > this value to be accepted high (float): High value, user entered value must be < this value to be accept...
0.005305
def receive(xpub, callback, api_key): """Call the '/v2/receive' endpoint and create a forwarding address. :param str xpub: extended public key to generate payment address :param str callback: callback URI that will be called upon payment :param str api_key: Blockchain.info API V2 key :return: a...
0.002463
def hicpro_mapping_chart (self): """ Generate the HiC-Pro Aligned reads plot """ # Specify the order of the different possible categories keys = OrderedDict() keys['Full_Alignments_Read'] = { 'color': '#005ce6', 'name': 'Full reads Alignments' } keys['Trimmed_Alignments_Read']...
0.01418
def rfc1123_date(timestamp=None): """Create a RFC1123 style Date header for *timestamp*.""" if timestamp is None: timestamp = time.time() timestamp = int(timestamp) global _cached_timestamp, _cached_datestring if timestamp != _cached_timestamp: # The time stamp must be GMT, and canno...
0.001639
def read_arg(src, c): """Read the argument from buffer. Advances buffer until right before the end of the argument. :param Buffer src: a buffer of tokens :param str c: argument token (starting token) :return: the parsed argument :rtype: Arg """ content = [c] while src.hasNext(): ...
0.002
def _get_ssl_opts(): ''' Parse out ssl_options for Cassandra cluster connection. Make sure that the ssl_version (if any specified) is valid. ''' sslopts = __salt__['config.option']('cassandra').get('ssl_options', None) ssl_opts = {} if sslopts: ssl_opts['ca_certs'] = sslopts['ca_cer...
0.000801
def load_module(self, name): """ Only lets modules in allowed_modules be loaded, others will get an ImportError """ # Get the name relative to SITEDIR .. filepath = self.module_info[1] fullname = splitext( \ relpath(filepath, self.sitedir) \ ...
0.003571
def check(self, value, namespace): """ Attribute _field_types is a dict from field name to type. """ if (not issubclass(type(value), self._cls) or len(value) != len(self._cls._fields)): return False for i, check in enumerate(self._checks): if n...
0.007519
def quarantineWorker(self, *args, **kwargs): """ Quarantine a worker Quarantine a worker This method takes input: ``v1/quarantine-worker-request.json#`` This method gives output: ``v1/worker-response.json#`` This method is ``experimental`` """ return ...
0.007712
def vis_splitting(Verts, splitting, output='vtk', fname='output.vtu'): """Coarse grid visualization for C/F splittings. Parameters ---------- Verts : {array} coordinate array (N x D) splitting : {array} coarse(1)/fine(0) flags fname : {string, file object} file to be wri...
0.000313
def clipRegionToScreen(self): """ Returns the part of the region that is visible on a screen If the region equals to all visible screens, returns Screen(-1). If the region is visible on multiple screens, returns the screen with the smallest ID. Returns None if the region is outside the ...
0.004107
def intersect(self, range_): self.solver.intersection_broad_tests_count += 1 """Remove variants whose version fall outside of the given range.""" if range_.is_any(): return self if self.solver.optimised: if range_ in self.been_intersected_with: r...
0.002055
def get_term_config(platform, filter_name, term_name, filter_options=None, pillar_key='acl', pillarenv=None, saltenv=None, merge_pillar=True, revision_id=None, ...
0.002261
def process_climis_crop_production_data(data_dir: str): """ Process CliMIS crop production data """ climis_crop_production_csvs = glob( "{data_dir}/Climis South Sudan Crop Production Data/" "Crops_EstimatedProductionConsumptionBalance*.csv" ) state_county_df = pd.read_csv( f"{da...
0.000527
def _metadata_from_video(self, video): '''Generate the searchable metadata that we'll store in the bundle for the video''' long_desc = video['long_description'] if long_desc is not None: long_desc = long_desc[:MAX_METADATA_STRING_LEN] tags = video.get('tags') metada...
0.003916
def post(self, request, bot_id, format=None): """ Add a new chat state --- serializer: KikChatStateSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request """ re...
0.005208
def check_rights(self, resources, request=None): """ Check rights for resources. :return bool: True if operation is success else HTTP_403_FORBIDDEN """ if not self.auth: return True try: if not self.auth.test_rights(resources, request=request): ...
0.006237
def _srads2bt(self, data, channel_name): """Computation based on spectral radiance.""" a__, b__, c__ = BTFIT[channel_name] wavenumber = CALIB[self.platform_id][channel_name]["VC"] temp = self._tl15(data, wavenumber) return a__ * temp * temp + b__ * temp + c__
0.006667
def get_toplevel_parent(self, treeitem): """Returns the top level parent for treeitem.""" tv = self.treeview toplevel_items = tv.get_children() item = treeitem while not (item in toplevel_items): item = tv.parent(item) return item
0.006849
def qn(self, namespace): """Connect tag prefix to longer namespace""" nsmap = { 'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0', } spl = namespace.split(':') return '{{{}}}{}'.format(nsmap[spl[0]], spl[1])
0.007519