Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
364,600
def required_get_and_update(self, name, default=None): setting = self._get_and_update_setting(name, default=None) if setting in [None, ""]: bot.exit( % name) return setting
a wrapper to get_and_update, but if not successful, will print an error and exit.
364,601
def parse_rest_doc(doc): class Section(object): def __init__(self, header=None, body=None): self.header = header self.body = body doc_sections = OrderedDict([(, Section(header=))]) if not doc: return doc_sections doc = cleandoc(doc) lines = iter(do...
Extract the headers, delimiters, and text from reST-formatted docstrings. Parameters ---------- doc: Union[str, None] Returns ------- Dict[str, Section]
364,602
def get_translation_objects(self, request, language_code, obj=None, inlines=True): if obj is not None: for translations_model in obj._parler_meta.get_all_models(): try: translation = translations_model.objects.get(master=obj, lan...
Return all objects that should be deleted when a translation is deleted. This method can yield all QuerySet objects or lists for the objects.
364,603
def convert_http_request(request, referrer_host=None): new_request = urllib.request.Request( request.url_info.url, origin_req_host=referrer_host, ) for name, value in request.fields.get_all(): new_request.add_header(name, value) return new_request
Convert a HTTP request. Args: request: An instance of :class:`.http.request.Request`. referrer_host (str): The referrering hostname or IP address. Returns: Request: An instance of :class:`urllib.request.Request`
364,604
def create_scratch_org(self, org_name, config_name, days=None, set_password=True): scratch_config = getattr( self.project_config, "orgs__scratch__{}".format(config_name) ) if days is not None: scratch_config["days"] = days else: ...
Adds/Updates a scratch org config to the keychain from a named config
364,605
def cli( paths, dbname, separator, quoting, skip_errors, replace_tables, table, extract_column, date, datetime, datetime_format, primary_key, fts, index, shape, filename_column, no_index_fks, no_fulltext_fks, ): extract_columns = extr...
PATHS: paths to individual .csv files or to directories containing .csvs DBNAME: name of the SQLite database file to create
364,606
def get_xritdecompress_outfile(stdout): outfile = b for line in stdout: try: k, v = [x.strip() for x in line.split(b, 1)] except ValueError: break if k == b: outfile = v break return outfile
Analyse the output of the xRITDecompress command call and return the file.
364,607
def profile_detail( request, username, template_name=accounts_settings.ACCOUNTS_PROFILE_DETAIL_TEMPLATE, extra_context=None, **kwargs): user = get_object_or_404(get_user_model(), username__iexact=username) profile_model = get_profile_model() try: profile...
Detailed view of an user. :param username: String of the username of which the profile should be viewed. :param template_name: String representing the template name that should be used to display the profile. :param extra_context: Dictionary of variables which should be su...
364,608
def get_datetime(self, timestamp: str, unix=True): time = datetime.strptime(timestamp, ) if unix: return int(time.timestamp()) else: return time
Converts a %Y%m%dT%H%M%S.%fZ to a UNIX timestamp or a datetime.datetime object Parameters --------- timestamp: str A timstamp in the %Y%m%dT%H%M%S.%fZ format, usually returned by the API in the ``created_time`` field for example (eg. 20180718T145906.000Z) ...
364,609
def generate_index(self, schemas): params = {: sorted(schemas, key=lambda x: x.object_name), : self.project_name, : \ .format(self.project_name)} template = self.lookup.get_template() html = template.render_unicode(**params) ...
Generates html for an index file
364,610
def trigger(self, events, *args, **kwargs): if not hasattr(self, ): self._on_off_events = {} if not hasattr(self, ): self.exc_info = None logging.debug("OnOffMixin triggering event(s): %s" % events) if isinstance(events, (str, unicode)): ...
Fires the given *events* (string or list of strings). All callbacks associated with these *events* will be called and if their respective objects have a *times* value set it will be used to determine when to remove the associated callback from the event. If given, callbacks associated ...
364,611
def Bankoff(m, x, rhol, rhog, mul, mug, D, roughness=0, L=1): r v_lo = m/rhol/(pi/4*D**2) Re_lo = Reynolds(V=v_lo, rho=rhol, mu=mul, D=D) fd_lo = friction_factor(Re=Re_lo, eD=roughness/D) dP_lo = fd_lo*L/D*(0.5*rhol*v_lo**2) gamma = (0.71 + 2.35*rhog/rhol)/(1. + (1.-x)/x*rhog/rhol) phi...
r'''Calculates two-phase pressure drop with the Bankoff (1960) correlation, as shown in [2]_, [3]_, and [4]_. .. math:: \Delta P_{tp} = \phi_{l}^{7/4} \Delta P_{l} .. math:: \phi_l = \frac{1}{1-x}\left[1 - \gamma\left(1 - \frac{\rho_g}{\rho_l} \right)\right]^{3/7}\left[1 + x\left(\...
364,612
def get_file_uuid(fpath, hasher=None, stride=1): if hasher is None: hasher = hashlib.sha1() hashbytes_20 = get_file_hash(fpath, hasher=hasher, stride=stride) hashbytes_16 = hashbytes_20[0:16] uuid_ = uuid.UUID(bytes=hashbytes_16) return uuid_
Creates a uuid from the hash of a file
364,613
def transform(self, X, perplexity=5, initialization="median", k=25, learning_rate=1, n_iter=100, exaggeration=2, momentum=0): affinity_signature = inspect.signature(self.affinities.to_new) if "perplexity" not in affinity_signature....
Embed new points into the existing embedding. This procedure optimizes each point only with respect to the existing embedding i.e. it ignores any interactions between the points in ``X`` among themselves. Please see the :ref:`parameter-guide` for more information. Parameters ...
364,614
def draw_beam(ax, p1, p2, width=0, beta1=None, beta2=None, format=None, **kwds): r if format is None: format = if width == 0: x0 = [p1[0], p2[0]] y0 = [p1[1], p2[1]] ax.plot(x0, y0, format, **kwds) else: a = width/2 x1, y1 = p1 ...
r"""Draw a laser beam.
364,615
def use_comparative_sequence_rule_enabler_rule_view(self): self._object_views[] = COMPARATIVE for session in self._get_provider_sessions(): try: session.use_comparative_sequence_rule_enabler_rule_view() except AttributeError: pass
Pass through to provider SequenceRuleEnablerRuleLookupSession.use_comparative_sequence_rule_enabler_rule_view
364,616
def from_gps(cls, gps, Name = None): self = cls(AttributesImpl({u"Type": u"GPS"})) if Name is not None: self.Name = Name self.pcdata = gps return self
Instantiate a Time element initialized to the value of the given GPS time. The Name attribute will be set to the value of the Name parameter if given. Note: the new Time element holds a reference to the GPS time, not a copy of it. Subsequent modification of the GPS time object will be reflected in what ge...
364,617
def heightmap_get_interpolated_value( hm: np.ndarray, x: float, y: float ) -> float: return float( lib.TCOD_heightmap_get_interpolated_value(_heightmap_cdata(hm), x, y) )
Return the interpolated height at non integer coordinates. Args: hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions. x (float): A floating point x coordinate. y (float): A floating point y coordinate. Returns: float: The value at ``x``, ``y``.
364,618
def wait_for_keys_modified(self, *keys, modifiers_to_check=_mod_keys, timeout=0): set_mods = pygame.key.get_mods() return frozenset.union( frozenset([self.wait_for_keys(*keys, timeout=timeout)]), EventListener._contained_modifiers(set_mods...
The same as wait_for_keys, but returns a frozen_set which contains the pressed key, and the modifier keys. :param modifiers_to_check: iterable of modifiers for which the function will check whether they are pressed :type modifiers: Iterable[int]
364,619
def basename(path): base_path = path.strip(SEP) sep_ind = base_path.rfind(SEP) if sep_ind < 0: return path return base_path[sep_ind + 1:]
Rightmost part of path after separator.
364,620
async def api_bikes(request): postcode: Optional[str] = request.match_info.get(, None) try: radius = int(request.match_info.get(, 10)) except ValueError: raise web.HTTPBadRequest(text="Invalid Radius") try: postcode = (await get_postcode_random()) if postcode == "random" e...
Gets stolen bikes within a radius of a given postcode. :param request: The aiohttp request. :return: The bikes stolen with the given range from a postcode.
364,621
def purchase_time(self): ts = self._iface.get_purchase_time(self.app_id) return datetime.utcfromtimestamp(ts)
Date and time of app purchase. :rtype: datetime
364,622
def get_participants(self, namespace, room): for sid, active in six.iteritems(self.rooms[namespace][room].copy()): yield sid
Return an iterable with the active participants in a room.
364,623
def monitor(self): if self._monitor is None: from twilio.rest.monitor import Monitor self._monitor = Monitor(self) return self._monitor
Access the Monitor Twilio Domain :returns: Monitor Twilio Domain :rtype: twilio.rest.monitor.Monitor
364,624
def async_make_reply(msgname, types, arguments_future, major): arguments = yield arguments_future raise gen.Return(make_reply(msgname, types, arguments, major))
Wrap future that will resolve with arguments needed by make_reply().
364,625
def delete(self): try: self.revert() except errors.ChangelistError: pass self._connection.run([, , str(self._change)])
Reverts all files in this changelist then deletes the changelist from perforce
364,626
def visit_For(self, node): assert isinstance(node.target, ast.Name), "For apply on variables." self.visit(node.iter) if isinstance(node.iter, ast.Call): for alias in self.aliases[node.iter.func]: if isinstance(alias, Intrinsic): self.add(n...
Handle iterate variable in for loops. >>> import gast as ast >>> from pythran import passmanager, backend >>> node = ast.parse(''' ... def foo(): ... a = b = c = 2 ... for i in __builtin__.range(1): ... a -= 1 ... b += 1''') ...
364,627
def _split(string, splitters): part = for character in string: if character in splitters: yield part part = else: part += character yield part
Splits a string into parts at multiple characters
364,628
def noise_op(latents, hparams): if hparams.latent_noise == 0 or hparams.mode != tf.estimator.ModeKeys.TRAIN: return latents latent_shape = common_layers.shape_list(latents) return latents + tf.random_normal(latent_shape, stddev=hparams.latent_noise)
Adds isotropic gaussian-noise to each latent. Args: latents: 4-D or 5-D tensor, shape=(NTHWC) or (NHWC). hparams: HParams. Returns: latents: latents with isotropic gaussian noise appended.
364,629
def parallel_assimilate(self, rootpath): logger.info() valid_paths = [] for (parent, subdirs, files) in os.walk(rootpath): valid_paths.extend(self._drone.get_valid_paths((parent, subdirs, files))) manager = ...
Assimilate the entire subdirectory structure in rootpath.
364,630
def start(self): pipers = self.postorder() for piper in pipers: piper.start(stages=(0, 1)) for piper in pipers: piper.start(stages=(2,))
Given the pipeline topology starts ``Pipers`` in the order input -> output. See ``Piper.start``. ``Pipers`` instances are started in two stages, which allows them to share ``NuMaps``.
364,631
def patch(self, overrides): overrides = overrides or {} for key, value in iteritems(overrides): current = self.get(key) if isinstance(value, dict) and isinstance(current, dict): current.patch(value) else: self[key] = value
Patches the config with the given overrides. Example: If the current dictionary looks like this: a: 1, b: { c: 3, d: 4 } and `patch` is called with the following overrides: b: { d: 2, e: 4 }, c: 5 ...
364,632
def main(): import jsonschema parser = argparse.ArgumentParser(version=__version__) parser.add_argument( , action=, default=False, help=) parser.add_argument( , action=, default=False, help=) parser.add_argument( , metavar=, type=str, nargs=, help...
Main entry point.
364,633
def join_syllables_spaces(syllables: List[str], spaces: List[int]) -> str: syllable_line = list("".join(syllables)) for space in spaces: syllable_line.insert(space, " ") return "".join(flatten(syllable_line))
Given a list of syllables, and a list of integers indicating the position of spaces, return a string that has a space inserted at the designated points. :param syllables: :param spaces: :return: >>> join_syllables_spaces(["won", "to", "tree", "dun"], [3, 6, 11]) 'won to tree dun'
364,634
def lookup(self, domain_name, validate=True): try: domain = self.get_domain(domain_name, validate) except: domain = None return domain
Lookup an existing SimpleDB domain. This differs from :py:meth:`get_domain` in that ``None`` is returned if ``validate`` is ``True`` and no match was found (instead of raising an exception). :param str domain_name: The name of the domain to retrieve :param bool validate: If ``...
364,635
def load_all_csvs_to_model(path, model, field_names=None, delimiter=None, batch_len=10000, dialect=None, num_header_rows=1, mode=, strip=True, clear=False, dry_run=True, ignore_errors=True, sort_files=True, recursive=False, ext=, ...
Bulk create database records from all csv files found within a directory.
364,636
def create_cells(self, blocks): cells = [] for block in blocks: if (block[] == self.code) and (block[] == ): code_cell = self.create_code_cell(block) cells.append(code_cell) elif (block[] == self.code and block[] == and...
Turn the list of blocks into a list of notebook cells.
364,637
def _elapsed(self): self.last_time = time.time() return self.last_time - self.start
Returns elapsed time at update.
364,638
def add_done_callback(self, fn): if self._result_set: _helpers.safe_invoke_callback(fn, self) return self._done_callbacks.append(fn) if self._polling_thread is None: self._polling_thread = _helpers.start_daemon_thread( ...
Add a callback to be executed when the operation is complete. If the operation is not already complete, this will start a helper thread to poll for the status of the operation in the background. Args: fn (Callable[Future]): The callback to execute when the operation ...
364,639
def blast_representative_sequence_to_pdb(self, seq_ident_cutoff=0, evalue=0.0001, display_link=False, outdir=None, force_rerun=False): if not self.representative_sequence: log.warning(.format(self.id)) return None ...
BLAST the representative protein sequence to the PDB. Saves a raw BLAST result file (XML file). Args: seq_ident_cutoff (float, optional): Cutoff results based on percent coverage (in decimal form) evalue (float, optional): Cutoff for the E-value - filters for significant hits. 0.001 is ...
364,640
def is_installable_file(path): from packaging import specifiers if isinstance(path, Mapping): path = convert_entry_to_path(path) if any(path.startswith(spec) for spec in "!=<>~"): try: specifiers.SpecifierSet(path) except specifiers.InvalidS...
Determine if a path can potentially be installed
364,641
def _send_command(self, cmd, expect=None): if not self.is_alive: raise NotPlayingError() logger.debug("Send command to mplayer: " + cmd) cmd = cmd + "\n" try: self.sub_proc.stdin.write(cmd) except (TypeError, Un...
Send a command to MPlayer. cmd: the command string expect: expect the output starts with a certain string The result, if any, is returned as a string.
364,642
def assign_value(rs, data_type, val, unit_id, name, metadata={}, data_hash=None, user_id=None, source=None): log.debug("Assigning value %s to rs %s in scenario %s", name, rs.resource_attr_id, rs.scenario_id) if rs.scenario.locked == : raise PermissionError("Cannot a...
Insert or update a piece of data in a scenario. If the dataset is being shared by other resource scenarios, a new dataset is inserted. If the dataset is ONLY being used by the resource scenario in question, the dataset is updated to avoid unnecessary duplication.
364,643
def get_supplier_properties_per_page(self, per_page=1000, page=1, params=None): return self._get_resource_per_page(resource=SUPPLIER_PROPERTIES, per_page=per_page, page=page, params=params)
Get supplier properties per page :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :param params: Search parameters. Default: {} :return: list
364,644
def ekf_ok(self): if self.armed: return self._ekf_poshorizabs and not self._ekf_constposmode else: return self._ekf_poshorizabs or self._ekf_predposhorizabs
``True`` if the EKF status is considered acceptable, ``False`` otherwise (``boolean``).
364,645
def send(self, s): m = Message() m.add_byte(cMSG_CHANNEL_DATA) m.add_int(self.remote_chanid) return self._send(s, m)
Send data to the channel. Returns the number of bytes sent, or 0 if the channel stream is closed. Applications are responsible for checking that all data has been sent: if only some of the data was transmitted, the application needs to attempt delivery of the remaining data. :...
364,646
def resort(self, attributeID, isAscending=None): if isAscending is None: isAscending = self.defaultSortAscending newSortColumn = self.columns[attributeID] if newSortColumn.sortAttribute() is None: raise Unsortable( % (attributeID,)) if self.currentSortCo...
Sort by one of my specified columns, identified by attributeID
364,647
def replace_namespaced_limit_range(self, name, namespace, body, **kwargs): kwargs[] = True if kwargs.get(): return self.replace_namespaced_limit_range_with_http_info(name, namespace, body, **kwargs) else: (data) = self.replace_namespaced_limit_range_with_http_inf...
replace the specified LimitRange This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_limit_range(name, namespace, body, async_req=True) >>> result = thread.get() :param asyn...
364,648
def jira_connection(config): global _jira_connection if _jira_connection: return _jira_connection else: jira_options = {: config.get().get()} cookies = configuration._get_cookies_as_dict() jira_connection = jira_ext.JIRA(options=jira_options) session = jira_conn...
Gets a JIRA API connection. If a connection has already been created the existing connection will be returned.
364,649
def is_empty(self): return ( self._lower > self._upper or (self._lower == self._upper and (self._left == OPEN or self._right == OPEN)) )
Test interval emptiness. :return: True if interval is empty, False otherwise.
364,650
def split(self, text): import re if re.search(, text): return text.split() elif re.search(, text): return text.split() else: LOGGER.error(" does not appear to be a subtitle file", self.filename) sys.exit(...
Split text into a list of cells.
364,651
def reporter(self): with open(os.path.join(self.reportpath, ), ) as report: data = for sample in self.runmetadata.samples: sample[self.analysistype].coreset = list(sample[self.analysistype].coreset) sample[self.analysistype].core...
Create a .csv file with the strain name, and the number of core genes present/the total number of core genes
364,652
def value(source, key, ext=COMPLETE): _MMD_LIB.extract_metadata_value.restype = ctypes.c_char_p _MMD_LIB.extract_metadata_value.argtypes = [ctypes.c_char_p, ctypes.c_ulong, ctypes.c_char_p] src = source.encode() dkey = key.encode() value = _MMD_LIB.extract_metadata_value(src, ext, dkey) r...
Extracts value for the specified metadata key from the given extension set. Keyword arguments: source -- string containing MultiMarkdown text ext -- extension bitfield for processing text key -- key to extract
364,653
def wysiwyg_setup(protocol="http", editor_override=None): ctx = { "protocol": protocol, } ctx.update(get_settings(editor_override=editor_override)) return render_to_string( "django_wysiwyg/%s/includes.html" % ctx[], ctx )
Create the <style> and <script> tags needed to initialize the rich text editor. Create a local django_wysiwyg/includes.html template if you don't want to use Yahoo's CDN
364,654
def add_update_resources(self, resources, ignore_datasetid=False): if not isinstance(resources, list): raise HDXError() for resource in resources: self.add_update_resource(resource, ignore_datasetid)
Add new or update existing resources with new metadata to the dataset Args: resources (List[Union[hdx.data.resource.Resource,Dict,str]]): A list of either resource ids or resources metadata from either Resource objects or dictionaries ignore_datasetid (bool): Whether to ignore dataset i...
364,655
def _init_objgoea(self, pop, assoc): propagate_counts = not self.args.no_propagate_counts return GOEnrichmentStudy(pop, assoc, self.godag, propagate_counts=propagate_counts, relationships=False, a...
Run gene ontology enrichment analysis (GOEA).
364,656
def evaluate(self, dataset, metric="auto", missing_value_action=, with_predictions=False, options={}, **kwargs): if missing_value_action == : missing_value_action = select_default_missing_value_policy( self, ) ...
Evaluate the model by making predictions of target values and comparing these to actual values. Parameters ---------- dataset : SFrame Dataset in the same format used for training. The columns names and types of the dataset must be the same as that used in traini...
364,657
def _clean_features(struct): struct = dict(struct) ptypes = [, , , , , , , , , , ] for pt in ptypes: struct[pt] = struct[pt] if pd.notnull(struct.get(pt)) else False struct[] = struct.get() == struct[] = struct.get() == struct[] = struct.get()...
Cleans up the features collected in parse_play_details. :struct: Pandas Series of features parsed from details string. :returns: the same dict, but with cleaner features (e.g., convert bools, ints, etc.)
364,658
def retry(n, errors, wait=0.0, logger_name=None): def wrapper(func): @functools.wraps(func) def new_func(*args, **kwargs): retries = 0 while True: try: result = func(*args, **kwargs) if retries and logger_name: ...
This is a decorator that retries a function. Tries `n` times and catches a given tuple of `errors`. If the `n` retries are not enough, the error is reraised. If desired `waits` some seconds. Optionally takes a 'logger_name' of a given logger to print the caught error.
364,659
def deploy_func_between_two_axis_partitions( cls, axis, func, num_splits, len_of_left, kwargs, *partitions ): lt_frame = pandas.concat(list(partitions[:len_of_left]), axis=axis, copy=False) rt_frame = pandas.concat(list(partitions[len_of_left:]), axis=axis, copy=False) resu...
Deploy a function along a full axis between two data sets in Ray. Args: axis: The axis to perform the function along. func: The function to perform. num_splits: The number of splits to return (see `split_result_of_axis_func_pandas`). len_of_left: ...
364,660
def _realToVisibleColumn(self, text, realColumn): generator = self._visibleCharPositionGenerator(text) for i in range(realColumn): val = next(generator) val = next(generator) return val
If \t is used, real position of symbol in block and visible position differs This function converts real to visible
364,661
def flushTable(self, login, tableName, startRow, endRow, wait): self.send_flushTable(login, tableName, startRow, endRow, wait) self.recv_flushTable()
Parameters: - login - tableName - startRow - endRow - wait
364,662
def xml2dict(root): output = {} if root.items(): output.update(dict(root.items())) for element in root: if element: if len(element) == 1 or element[0].tag != element[1].tag: one_dict = xml2dict(element) else: one_dict = {ns(elemen...
Use functions instead of Class and remove namespace based on: http://stackoverflow.com/questions/2148119
364,663
def run_script(scriptfile): try: f = open(scriptfile, mode=) except Exception: return mpstate.console.writeln("Running script %s" % scriptfile) sub = mp_substitute.MAVSubstitute() for line in f: line = line.strip() if line == "" or line.startswith(): ...
run a script file
364,664
def _bss_image_crit(s_true, e_spat, e_interf, e_artif): sdr = _safe_db(np.sum(s_true**2), np.sum((e_spat+e_interf+e_artif)**2)) isr = _safe_db(np.sum(s_true**2), np.sum(e_spat**2)) sir = _safe_db(np.sum((s_true+e_spat)**2), np.sum(e_interf**2)) sar = _safe_db(np.sum((s_true+e_spat+e_interf)**2...
Measurement of the separation quality for a given image in terms of filtered true source, spatial error, interference and artifacts.
364,665
def pending_batch_info(self): c_length = ctypes.c_int(0) c_limit = ctypes.c_int(0) self._call( , ctypes.byref(c_length), ctypes.byref(c_limit)) return (c_length.value, c_limit.value)
Returns a tuple of the current size of the pending batch queue and the current queue limit.
364,666
def Cpu(): cpu = try: cpu = str(multiprocessing.cpu_count()) except Exception as e: logger.error("Can " + str(e)) return cpu
Get number of available CPUs
364,667
def _mudraw(buffer, fmt): with NamedTemporaryFile(suffix=) as tmp_in: tmp_in.write(buffer) tmp_in.seek(0) tmp_in.flush() proc = run( [, , fmt, , , tmp_in.name], stdout=PIPE, stderr=PIPE ) if proc.stderr: raise RuntimeError(proc.stderr.dec...
Use mupdf draw to rasterize the PDF in the memory buffer
364,668
def encode_varint(value, write): value = (value << 1) ^ (value >> 63) if value <= 0x7f: write(value) return 1 if value <= 0x3fff: write(0x80 | (value & 0x7f)) write(value >> 7) return 2 if value <= 0x1fffff: write(0x80 | (value & 0x7f)) ...
Encode an integer to a varint presentation. See https://developers.google.com/protocol-buffers/docs/encoding?csw=1#varints on how those can be produced. Arguments: value (int): Value to encode write (function): Called per byte that needs to be writen Returns: ...
364,669
def load_site_config(name): return _load_config_json( os.path.join( CONFIG_PATH, CONFIG_SITES_PATH, name + CONFIG_EXT ) )
Load and return site configuration as a dict.
364,670
def _add_scope_decorations(self, block, start, end): try: parent = FoldScope(block).parent() except ValueError: parent = None if TextBlockHelper.is_fold_trigger(block): base_color = self._get_scope_highlight_color() factor_step = 5 ...
Show a scope decoration on the editor widget :param start: Start line :param end: End line
364,671
def importpath(path, error_text=None): result = None attrs = [] parts = path.split() exception = None while parts: try: result = __import__(.join(parts), {}, {}, []) except ImportError as e: if exception is None: exception = e ...
Import value by specified ``path``. Value can represent module, class, object, attribute or method. If ``error_text`` is not None and import will raise ImproperlyConfigured with user friendly text.
364,672
def _show_prompt(self, prompt=None, html=False, newline=True): cursor = self._get_end_cursor() self._append_before_prompt_pos = cursor.position() if newline and cursor.position() > 0: cursor.movePosition(QtGui.QTextCursor.Left, ...
Writes a new prompt at the end of the buffer. Parameters ---------- prompt : str, optional The prompt to show. If not specified, the previous prompt is used. html : bool, optional (default False) Only relevant when a prompt is specified. If set, the prompt will ...
364,673
def send_frame(self, frame): if self.closed: if self.close_info and len(self.close_info[]) > 0: raise ChannelClosed( "channel %d is closed: %s : %s", self.channel_id, self.close_info[], self.clos...
Queue a frame for sending. Will send immediately if there are no pending synchronous transactions on this connection.
364,674
def vertex_colors(self, values): if values is None: if in self._data: self._data.data.pop() return values = np.asanyarray(values) if (self.mesh is not None and not (values.shape == (len(self.mesh.vertices), 3) o...
Set the colors for each vertex of a mesh This will apply these colors and delete any previously specified color information. Parameters ------------ colors: (len(mesh.vertices), 3), set each face to the color (len(mesh.vertices), 4), set each face to the color ...
364,675
def _irc_upper(self, in_string): conv_string = self._translate(in_string) if self._upper_trans is not None: conv_string = in_string.translate(self._upper_trans) return str.upper(conv_string)
Convert us to our upper-case equivalent, given our std.
364,676
def inject_closure_values(func, **kwargs): wrapped_by = None if isinstance(func, property): fget, fset, fdel = func.fget, func.fset, func.fdel if fget: fget = fix_func(fget, **kwargs) if fset: fset = fix_func(fset, **kwargs) if fdel: fdel = fix_func(fdel, **kwargs) ...
Returns a new function identical to the previous one except that it acts as though global variables named in `kwargs` have been closed over with the values specified in the `kwargs` dictionary. Works on properties, class/static methods and functions. This can be useful for mocking and other nefarious ...
364,677
async def on_raw_329(self, message): target, channel, timestamp = message.params if not self.in_channel(channel): return self.channels[channel][] = datetime.datetime.fromtimestamp(int(timestamp))
Channel creation time.
364,678
def fast_int( x, key=lambda x: x, _uni=unicodedata.digit, _first_char=POTENTIAL_FIRST_CHAR, ): if x[0] in _first_char: try: return long(x) except ValueError: try: return _uni(x, key(x)) if len(x) == 1 else key(x) except TypeErr...
Convert a string to a int quickly, return input as-is if not possible. We don't need to accept all input that the real fast_int accepts because natsort is controlling what is passed to this function. Parameters ---------- x : str String to attempt to convert to an int. key : callable ...
364,679
def max_freq(self, tech_in_nm=130, ffoverhead=None): cp_length = self.max_length() scale_factor = 130.0 / tech_in_nm if ffoverhead is None: clock_period_in_ps = scale_factor * (cp_length + 189 + 194) else: clock_period_in_ps = (scale_factor * cp_length) +...
Estimates the max frequency of a block in MHz. :param tech_in_nm: the size of the circuit technology to be estimated (for example, 65 is 65nm and 250 is 0.25um) :param ffoverhead: setup and ff propagation delay in picoseconds :return: a number representing an estimate of the max fre...
364,680
def get_subject_with_file_validation(jwt_bu64, cert_path): cert_obj = d1_common.cert.x509.deserialize_pem_file(cert_path) return get_subject_with_local_validation(jwt_bu64, cert_obj)
Same as get_subject_with_local_validation() except that the signing certificate is read from a local PEM file.
364,681
def decode_index_value(self, index, value): if index.endswith("_int"): return int(value) else: return bytes_to_str(value)
Decodes a secondary index value into the correct Python type. :param index: the name of the index :type index: str :param value: the value of the index entry :type value: str :rtype str or int
364,682
def _add(self, hostport): peer = self.peer_class( tchannel=self.tchannel, hostport=hostport, on_conn_change=self._update_heap, ) peer.rank = self.rank_calculator.get_rank(peer) self._peers[peer.hostport] = peer self.peer_heap.add_and_...
Creates a peer from the hostport and adds it to the peer heap
364,683
def getSkeletalBoneDataCompressed(self, action, eMotionRange, pvCompressedData, unCompressedSize): fn = self.function_table.getSkeletalBoneDataCompressed punRequiredCompressedSize = c_uint32() result = fn(action, eMotionRange, pvCompressedData, unCompressedSize, byref(punRequiredCompre...
Reads the state of the skeletal bone data in a compressed form that is suitable for sending over the network. The required buffer size will never exceed ( sizeof(VR_BoneTransform_t)*boneCount + 2). Usually the size will be much smaller.
364,684
def search(self, q, **kw): url = .format(**vars(self)) params = { : q, } params.update(self.params) params.update(kw) response = self.session.get(url, params=params) response.raise_for_status() return response.json()
Search Gnip for given query, returning deserialized response.
364,685
def http_post(url, data=None, opt=opt_default): return _http_request(url, method=, data=_marshalled(data), opt=opt)
Shortcut for urlopen (POST) + read. We'll probably want to add a nice timeout here later too.
364,686
def _get_error_values(self, startingPercentage, endPercentage, startDate, endDate): if startDate is not None: possibleDates = filter(lambda date: date >= startDate, self._errorDates) if 0 == len(possibleDates): raise ValueError("%s does not represent a valid star...
Gets the defined subset of self._errorValues. Both parameters will be correct at this time. :param float startingPercentage: Defines the start of the interval. This has to be a value in [0.0, 100.0]. It represents the value, where the error calculation should be started. 25.0 f...
364,687
def utc_datetime(dt=None, local_value=True): if dt is None: return datetime.now(tz=timezone.utc) result = dt if result.utcoffset() is None: if local_value is False: return result.replace(tzinfo=timezone.utc) else: result = result.replace(tzinfo=local_tz()) return result.astimezone(timezone.utc)
Convert local datetime and/or datetime without timezone information to UTC datetime with timezone information. :param dt: local datetime to convert. If is None, then system datetime value is used :param local_value: whether dt is a datetime in system timezone or UTC datetime without timezone information :return: d...
364,688
def _preflight_check(desired, fromrepo, **kwargs): if not in __salt__: return {} ret = {: {}, : []} pkginfo = __salt__[]( *list(desired.keys()), fromrepo=fromrepo, **kwargs ) for pkgname in pkginfo: if pkginfo[pkgname][] is False: if pkginfo[pkgname][]: ...
Perform platform-specific checks on desired packages
364,689
def bulk_upsert(self, docs, namespace, timestamp): if self.auto_commit_interval is not None: add_kwargs = { "commit": (self.auto_commit_interval == 0), "commitWithin": str(self.auto_commit_interval) } else: add_kwargs = {"commi...
Update or insert multiple documents into Solr docs may be any iterable
364,690
def get_processors(processor_cat, prop_defs, data_attr=None): processor_defs = prop_defs.get(processor_cat,[]) processor_list = [] for processor in processor_defs: proc_class = PropertyProcessor[processor[][0]] processor_list.append(proc_class(processor.get(, [{}]), ...
reads the prop defs and adds applicable processors for the property Args: processor_cat(str): The category of processors to retreive prop_defs: property defintions as defined by the rdf defintions data_attr: the attr to manipulate during processing. Returns: list: a list of pro...
364,691
def delete_table_rate_rule_by_id(cls, table_rate_rule_id, **kwargs): kwargs[] = True if kwargs.get(): return cls._delete_table_rate_rule_by_id_with_http_info(table_rate_rule_id, **kwargs) else: (data) = cls._delete_table_rate_rule_by_id_with_http_info(table_rate_...
Delete TableRateRule Delete an instance of TableRateRule by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_table_rate_rule_by_id(table_rate_rule_id, async=True) >>> result = th...
364,692
def load_dsdl(*paths, **args): global DATATYPES, TYPENAMES paths = list(paths) try: if not args.get("exclude_dist", None): dsdl_path = pkg_resources.resource_filename(__name__, "dsdl_files") paths = [os.path.join(dsdl_path, "uavcan")] + paths ...
Loads the DSDL files under the given directory/directories, and creates types for each of them in the current module's namespace. If the exclude_dist argument is not present, or False, the DSDL definitions installed with this package will be loaded first. Also adds entries for all datatype (ID, kind)s...
364,693
def acquireConnection(self): self._logger.debug("Acquiring connection") self._conn._ping_check() connWrap = ConnectionWrapper(dbConn=self._conn, cursor=self._conn.cursor(), releaser=self._releaseConnection, ...
Get a Connection instance. Parameters: ---------------------------------------------------------------- retval: A ConnectionWrapper instance. NOTE: Caller is responsible for calling the ConnectionWrapper instance's release() method or use it in a context manag...
364,694
def run_example(example_coroutine, *extra_args): args = _get_parser(extra_args).parse_args() logging.basicConfig(level=logging.DEBUG if args.debug else logging.WARNING) cookies = hangups.auth.get_auth_stdin(args.token_path) client = hangups.Client(cookies) loop = asyncio.get_event_loo...
Run a hangups example coroutine. Args: example_coroutine (coroutine): Coroutine to run with a connected hangups client and arguments namespace as arguments. extra_args (str): Any extra command line arguments required by the example.
364,695
def end(self): if self._duration: return self.begin + self._duration elif self._end_time: if self.all_day: return self._end_time else: return self._end_time elif self._begin: if self.all_...
Get or set the end of the event. | Will return an :class:`Arrow` object. | May be set to anything that :func:`Arrow.get` understands. | If set to a non null value, removes any already existing duration. | Setting to None will have unexpected behavior if begin...
364,696
def _rectangles_to_polygons(df): n = len(df) xmin_idx = np.tile([True, True, False, False], n) xmax_idx = ~xmin_idx ymin_idx = np.tile([True, False, False, True], n) ymax_idx = ~ymin_idx x = np.empty(n*4) y = np.empty(n*4) x[xmin_idx] = df[].repeat(2) x[xma...
Convert rect data to polygons Paramters --------- df : dataframe Dataframe with *xmin*, *xmax*, *ymin* and *ymax* columns, plus others for aesthetics ... Returns ------- data : dataframe Dataframe with *x* and *y* columns, plus others for aesthetics ...
364,697
def _hook_xfer_mem(self, uc, access, address, size, value, data): assert access in (UC_MEM_WRITE, UC_MEM_READ, UC_MEM_FETCH) if access == UC_MEM_WRITE: self._cpu.write_int(address, value, size * 8) elif access == UC_MEM_READ: ...
Handle memory operations from unicorn.
364,698
def delete_collection_namespaced_service_account(self, namespace, **kwargs): kwargs[] = True if kwargs.get(): return self.delete_collection_namespaced_service_account_with_http_info(namespace, **kwargs) else: (data) = self.delete_collection_namespaced_service_acc...
delete collection of ServiceAccount This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_service_account(namespace, async_req=True) >>> result = thread.get() :param...
364,699
def do_random(context, seq): try: return random.choice(seq) except IndexError: return context.environment.undefined()
Return a random item from the sequence.