Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
342,900
def source(self): if self._source is not None: return self._source elif self.parent is not None: return self.parent.source else: return Location(self)
The source element this document element was created from.
342,901
def from_json(json): points = [] for point in json[]: points.append(Point.from_json(point)) return Segment(points)
Creates a segment from a JSON file. No preprocessing is done. Arguments: json (:obj:`dict`): JSON representation. See to_json. Return: :obj:`Segment`
342,902
def on_close_grid(self, event): if self.parent.grid_frame: self.parent.grid_frame.onSave(None) self.parent.grid_frame.Destroy()
If there is an open grid, save its data and close it.
342,903
def to_json(value, **kwargs): def _recurse_list(val): if val and isinstance(val[0], list): return [_recurse_list(v) for v in val] return [str(v) if np.isnan(v) or np.isinf(v) else v for v in val] return _recurse_list(value.tolist())
Convert array to JSON list nan values are converted to string 'nan', inf values to 'inf'.
342,904
def _coral_to_seqfeature(feature): bio_strand = 1 if feature.strand == 1 else -1 ftype = _process_feature_type(feature.feature_type, bio_to_coral=False) sublocations = [] if feature.gaps: location_operator = location = FeatureLocation(ExactPosition(0), Ex...
Convert a coral.Feature to a Biopython SeqFeature. :param feature: coral Feature. :type feature: coral.Feature
342,905
def fitter(self, n=0, ftype="real", colfac=1.0e-8, lmfac=1.0e-3): fid = self._fitproxy.getid() ftype = self._gettype(ftype) n = len(self._fitids) if 0 <= fid < n: self._fitids[fid] = {} elif fid == n: self._fitids.append({}) else: ...
Create a sub-fitter. The created sub-fitter can be used in the same way as a fitter default fitter. This function returns an identification, which has to be used in the `fid` argument of subsequent calls. The call can specify the standard constructor arguments (`n`, `type`, `colfac`, ...
342,906
def _merge_by_keys(cls, session, items, hash_item, *attrs): items_iter1, items_iter2 = tee(items) keys = {} for i in items_iter1: item_hash = hash_item(i) keys[item_hash] = {attr.key: getattr(i, attr...
An object can have multiple attributes as its key. This merges the items to be added with existing items in the database based on their key(s). session: Session object for querying the DB. items: Iterator of items to be added to the DB. hash_item: Function that takes as in put t...
342,907
def create_many(self, statements): Statement = self.get_model() Tag = self.get_model() session = self.Session() create_statements = [] create_tags = {} for statement in statements: statement_data = statement.serialize() tag_data = stat...
Creates multiple statement entries.
342,908
def from_stanford_dependencies(this_class, stream, tree, include_erased=False, include_punct=True): stream = iter(stream) sentence = this_class() covered_indices = set() tags_and_words = ptb_tags_and_words_re.findall(tree) tags...
Construct a Sentence. stream is an iterable over strings where each string is a line representing a Stanford Dependency as in the output of the command line Stanford Dependency tool: deprel(gov-index, dep-depindex) The corresponding Penn Treebank formatted tree must be provided ...
342,909
def _read_config(self): this_dir = os.path.dirname(__file__) config_file = os.path.abspath(os.path.join(this_dir, "..", "config", "config.json")) self.generic_enum_attrs = [] self.base_attrs = [] self.generic_enums = [] self.named_entity_attrs =...
This method reads provided json config file.
342,910
def archive_compile(filename, command="make"): if not tarfile.is_tarfile(filename): print("Cannot extract archive") return False if command == "": return True with tempfile.TemporaryDirectory(suffix="prof") as tmpdir: with tarfile.open(filename) as tararchive: ...
Returns if the given archive properly compile. Extract it in a temporary directory, run the given command, and return True it's result is 0
342,911
def posterior_step(logposts, dim): if logposts.ndim > 1: raise ValueError("logposts must be a 1D array") criteria = dim/2. dp = numpy.diff(logposts) indices = numpy.where(dp >= criteria)[0] if indices.size > 0: idx = indices[-1] + 1 else: idx = 0 return idx
Finds the last time a chain made a jump > dim/2. Parameters ---------- logposts : array 1D array of values that are proportional to the log posterior values. dim : int The dimension of the parameter space. Returns ------- int The index of the last time the logpost m...
342,912
def _address_rxp(self, addr): try: addr = to_checksum_address(addr) rxp = + pex(address_checksum_and_decode(addr)) + f self._extra_keys[pex(address_checksum_and_decode(addr))] = addr.lower() self._extra_keys[addr[2:].lower()] = addr.lower() excep...
Create a regex string for addresses, that matches several representations: - with(out) '0x' prefix - `pex` version This function takes care of maintaining additional lookup keys for substring matches. In case the given string is no address, it returns the original string.
342,913
def then_by_descending(self, func): if func is None: raise NullArgumentError( u"then_by_descending requires a lambda function arg") self._key_funcs.append(OrderingDirection(key=func, reverse=True)) return SortedEnumerable(self._key_funcs, self._data)
Subsequent sorting function in descending order :param func: lambda function for secondary sort key :return: SortedEnumerable instance
342,914
def configure(cls, host_name: str = , service_name: str = , service_version=, http_host: str = , http_port: int = 8000, tcp_host: str = , tcp_port: int = 8001, ssl_context=None, registry_host: str = "0.0.0.0", registry_port: int = 4500, pubsub_host...
A convenience method for providing registry and pubsub(redis) endpoints :param host_name: Used for process name :param registry_host: IP Address for trellio-registry; default = 0.0.0.0 :param registry_port: Port for trellio-registry; default = 4500 :param pubsub_host: IP Address for pub...
342,915
def masked_middle_map(self): begin, end = self._masked_middle_begin_end() return self.__mfcc_mask_map[begin:end]
Return the map from the MFCC speech frame indices in the MIDDLE portion of the wave to the MFCC FULL frame indices. :rtype: :class:`numpy.ndarray` (1D)
342,916
def referencesFinder(text): references = referencesRegEx.finditer(text) count = 0 refs = [] spans = [] for i in references: refs.append(i.group()) spans.append(i.span()) count += 1 done = set() nameRegEx = re.compile(r) for index, obj in enumerate(refs): ...
:param text: takes the whole text of an article, searches for references, cleans the text, marks the reference indeces from zero inside the text. :return: the tagged text and a tag:reference dictionary to be used in sectionParser
342,917
def get_notes(self): self.owner.sync() notes = self.owner.notes.values() return [n for n in notes if n.project_id == self.id]
Return a list of all of the project's notes. :return: A list of notes. :rtype: list of :class:`pytodoist.todoist.Note` >>> from pytodoist import todoist >>> user = todoist.login('john.doe@gmail.com', 'password') >>> project = user.get_project('PyTodoist') >>> notes = pr...
342,918
def k_small(self): return self.k * _np.sqrt(2/_np.pi) / self.sig_y
Small-angle driving force term: :math:`r'' = -k_{small} r`. Note: :math:`k_{small} = \\frac{k}{2{\\sigma_r^2}}`
342,919
def feed_packet(self, binary_packet, linktype=LinkTypes.ETHERNET): warnings.warn("Deprecated method. Use InMemCapture.parse_packet() instead.") self._current_linktype = linktype pkt = self.parse_packet(binary_packet) self.close() self._packets.append(pkt) return ...
DEPRECATED. Use parse_packet instead. This function adds the packet to the packets list, and also closes and reopens tshark for each packet. ============== Gets a binary (string) packet and parses & adds it to this capture. Returns the added packet. Use feed_packets if ...
342,920
def parse_line(self, line): if line[0].isspace(): new_part = + line.lstrip() self._as_list[self._last_key][-1] += new_part dict.__setitem__(self, self._last_key, self[self._last_key] + new_part) else: nam...
Updates the dictionary with a single header line. >>> h = HTTPHeaders() >>> h.parse_line("Content-Type: text/html") >>> h.get('content-type') 'text/html'
342,921
def disco(self, code, lasti=-1, file=None): return _disco(self.python_version, code, timestamp=0, out=file, is_pypy=self.is_pypy, header=False)
Disassemble a code object.
342,922
def post(method, hmc, uri, uri_parms, body, logon_required, wait_for_completion): assert wait_for_completion is True storage_group_oid = uri_parms[0] storage_group_uri = + storage_group_oid try: storage_group = hmc.lookup_by_uri(storage_group...
Operation: Modify Storage Group Properties.
342,923
def process_import_request(username, path, timestamp, logger_handler): items = [] error_protocol = [] global logger logger = logger_handler user_conf = passwd_reader.read_user_config(username) logger.info("Locking user´s directory.") recursive_chmod(path, 0555) tr...
React to import request. Look into user's directory and react to files user uploaded there. Behavior of this function can be set by setting variables in :mod:`ftp.settings`. Args: username (str): Name of the user who triggered the import request. path (str): Path to the file, which tri...
342,924
def _log_loss(y, y_pred, w): eps = 1e-15 inv_y_pred = np.clip(1 - y_pred, eps, 1 - eps) y_pred = np.clip(y_pred, eps, 1 - eps) score = y * np.log(y_pred) + (1 - y) * np.log(inv_y_pred) return np.average(-score, weights=w)
Calculate the log loss.
342,925
def main(): conn = symphony.Config() agent, pod, symphony_sid = conn.connect() agent.test_echo() msgFormat = message = agent.send_message(symphony_sid, msgFormat, message)
main program loop
342,926
def _load_nnp(self, rel_name, rel_url): from nnabla.utils.download import download path_nnp = os.path.join( get_model_home(), .format(rel_name)) url = os.path.join(get_model_url_base(), .format(rel_url)) logger.info(.format(rel_name, ur...
Args: rel_name: relative path to where donwloaded nnp is saved. rel_url: relative url path to where nnp is downloaded from.
342,927
def summary(self): if self.hasSummary: return BisectingKMeansSummary(super(BisectingKMeansModel, self).summary) else: raise RuntimeError("No training summary available for this %s" % self.__class__.__name__)
Gets summary (e.g. cluster assignments, cluster sizes) of the model trained on the training set. An exception is thrown if no summary exists.
342,928
def combine_express(samples, combined): if not combined: return None to_combine = [dd.get_express_counts(x) for x in dd.sample_data_iterator(samples) if dd.get_express_counts(x)] gtf_file = dd.get_gtf_file(samples[0][0]) isoform_to_gene_file = os.path.join(os.path.dirname(...
Combine tpm, effective counts and fpkm from express results
342,929
def _apply_hard_disk(unit_number, key, operation, disk_label=None, size=None, unit=, controller_key=None, thin_provision=None, eagerly_scrub=None, datastore=None, filename=None): log.trace( , disk_label, size, unit, controller_key, thin_prov...
Returns a vim.vm.device.VirtualDeviceSpec object specifying to add/edit a virtual disk device unit_number Add network adapter to this address key Device key number operation Action which should be done on the device add or edit disk_label Label of the new disk, ca...
342,930
def _shutdown_broker(self): if self.broker: self.broker.shutdown() self.broker.join() self.broker = None self.router = None mitogen.fork.on_fork()
Shutdown the broker thread during :meth:`close` or :meth:`reset`.
342,931
def _check_structure(self): unused_variables = set() unused_operators = set() for variable in self.unordered_variable_iterator(): unused_variables.add(variable.full_name) for operator in self.unordered_operator_iterator(): unused_operators.add(op...
This function applies some rules to check if the parsed model is proper. Currently, it only checks if isolated variable and isolated operator exists.
342,932
def export(self, metadata, **kwargs): "Turn metadata into JSON" kwargs.setdefault(, 4) metadata = json.dumps(metadata, **kwargs) return u(metadata)
Turn metadata into JSON
342,933
def n_weekends(self) -> int: saturdays = set() for interval in self.intervals: saturdays.update(interval.saturdays_of_weekends()) return len(saturdays)
Returns the number of weekends that the intervals collectively touch (where "touching a weekend" means "including time on a Saturday or a Sunday").
342,934
def users_autocomplete(self, name=None, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/users api_path = "/api/v2/users/autocomplete.json" api_query = {} if "query" in kwargs.keys(): api_query.update(kwargs["query"]) del kwargs["query"] if nam...
https://developer.zendesk.com/rest_api/docs/core/users#autocomplete-users
342,935
def _unset_annotation_to_str(keys: List[str]) -> str: if len(keys) == 1: return .format(list(keys)[0]) return .format(.join(.format(key) for key in keys))
Return an unset annotation string.
342,936
def rmsd(self, other): if self.numbers.shape != other.numbers.shape or \ (self.numbers != other.numbers).all(): raise ValueError("The other molecule does not have the same numbers as this molecule.") return fit_rmsd(self.coordinates, other.coordinates)
Compute the RMSD between two molecules. Arguments: | ``other`` -- Another molecule with the same atom numbers Return values: | ``transformation`` -- the transformation that brings 'self' into overlap with 'other' | ``other...
342,937
def _install_gatk_jar(name, fname, manifest, system_config, toolplus_dir): if not fname.endswith(".jar"): raise ValueError("--toolplus argument for %s expects a jar file: %s" % (name, fname)) version = get_gatk_jar_version(name, fname) store_dir = utils.safe_makedir(os.path.join(toolplus_dir, n...
Install a jar for GATK or associated tools like MuTect.
342,938
def _setup_listener(self): listener_class = get_listener(self._listener_type) self.address = self.listener_opts.pop(, self.address) self.port = self.listener_opts.pop(, self.port) self.listener = listener_class(self.address, self.port, ...
Setup the transport.
342,939
def dimensions(self): if self.scraper.current_item is not self: self._move_here() if self._dimensions is None: self._dimensions = DimensionList() for d in self.scraper._fetch_dimensions(self): d.dataset = self d.scrap...
Available dimensions, if defined.
342,940
def setCellUser(self, iden): if not self.user.admin: mesg = raise s_exc.AuthDeny(mesg=mesg) user = self.cell.auth.user(iden) if user is None: raise s_exc.NoSuchUser(iden=iden) self.user = user return True
Switch to another user (admin only). This API allows remote admin/service accounts to impersonate a user. Used mostly by services that manage their own authentication/sessions.
342,941
def _create_historical_estimates(resource, configuration): today = timezone.now() month_start = core_utils.month_start(today) while month_start > resource.created: month_start -= relativedelta(months=1) models.PriceEstimate.create_historical(resource, configuration, max(month_start, res...
Create consumption details and price estimates for past months. Usually we need to update historical values on resource import.
342,942
def for_me(conditions, myself): if not conditions.audience_restriction: return True for restriction in conditions.audience_restriction: if not restriction.audience: continue for audience in restriction.audience: if audience.text.strip() == myself: ...
Am I among the intended audiences
342,943
def wait(self, timeout_s: float = None) -> int: if not self.running: return 0 retcode = self.process.wait(timeout=timeout_s) elif retcode == 0: self.info("Subprocess finished cleanly (return code 0).") else: self.error( ...
Wait for up to ``timeout_s`` for the child process to finish. Args: timeout_s: maximum time to wait or ``None`` to wait forever Returns: process return code; or ``0`` if it wasn't running, or ``1`` if it managed to exit without a return code Raises: ...
342,944
def properties(self): resource = "basestation" basestn_event = self.publish_and_get_event(resource) if basestn_event: return basestn_event.get() return None
Return the base station info.
342,945
def _as_tensor(x, name, dtype): return None if x is None else tf.convert_to_tensor( value=x, name=name, dtype=dtype)
Convenience to convert to `Tensor` or leave as `None`.
342,946
def resolve_requirements(self, interpreter, req_libs): with self.invalidated(req_libs) as invalidation_check: if invalidation_check.all_vts: target_set_id = VersionedTargetSet.from_versioned_targets( invalidation_check.all_vts).cache_key.hash else: t...
Requirements resolution for PEX files. :param interpreter: Resolve against this :class:`PythonInterpreter`. :param req_libs: A list of :class:`PythonRequirementLibrary` targets to resolve. :returns: a PEX containing target requirements and any specified python dist targets.
342,947
def get_vnetwork_vms_output_vnetwork_vms_datacenter(self, **kwargs): config = ET.Element("config") get_vnetwork_vms = ET.Element("get_vnetwork_vms") config = get_vnetwork_vms output = ET.SubElement(get_vnetwork_vms, "output") vnetwork_vms = ET.SubElement(output, "vnetwor...
Auto Generated Code
342,948
def set(self, obj, value): assert self.setter is not None, "Setter accessor is not specified." if callable(self.setter): return self.setter(obj, value) assert isinstance(self.setter, string_types), "Accessor must be a function or a dot-separated string." def _set(o...
Set value for obj's attribute. :param obj: Result object or dict to assign the attribute to. :param value: Value to be assigned.
342,949
def term_doc_lists(self): doc_ids = self._X.transpose().tolil().rows terms = self._term_idx_store.values() return dict(zip(terms, doc_ids))
Returns ------- dict
342,950
def get_connected_components(graph): list_of_components = [] component = [] unreached = set(graph.get_all_node_ids()) to_explore = deque() while len(unreached) > 0: if len(to_explore) == 0: n = unreached.pop() unreached.add(n) to_ex...
Finds all connected components of the graph. Returns a list of lists, each containing the nodes that form a connected component. Returns an empty list for an empty graph.
342,951
def alias_exists(alias, keystore_path=None, keystore_password=): log = logging.getLogger(mod_logger + ) if not isinstance(alias, basestring): msg = log.error(msg) raise OSError(msg) log.debug() try: java_home = os.environ[] except KeyError: msg = ...
Checks if an alias already exists in a keystore :param alias: :param keystore_path: :param keystore_password: :return: (bool) True when the alias already exists in the keystore :raises: OSError
342,952
def get_bound_method(self, instruction): try: return self._bound_instructions[type(instruction)] except KeyError: raise PulseError( % instruction)
Get conversion method for instruction.
342,953
def http_exception(channel, title): gui = ui_embed.UI( channel, "Too much help", "{} is too helpful! Try trimming some of the help messages.".format(title), modulename=modulename ) return gui
Creates an embed UI containing the 'too long' error message Args: channel (discord.Channel): The Discord channel to bind the embed to title (str): The title of the embed Returns: ui (ui_embed.UI): The embed UI object
342,954
def on_message(self, msg): if self not in clients: return try: payload = json_decode(msg) except ValueError: return if in payload: self.close() return for verb, args in payload.items(): ...
Accept a message that was published, process and forward Parameters ---------- msg : str The message sent over the line Notes ----- This method only handles messages where `message_type` is "message".
342,955
def _update_internal_nodes(self, index, delta): while index > 0: index = (index - 1) // 2 self._memory[index] += delta
Update internal priority sums when leaf priority has been changed. Args: index: leaf node index delta: change in priority
342,956
def _import_gns3_gui_conf(self): config_file = os.path.join(os.path.dirname(self._config_file), "gns3_gui.conf") if os.path.exists(config_file): with open(config_file) as f: data = json.load(f) server_settings = data.get("Servers", {}) ...
Import old config from GNS3 GUI
342,957
def articles(self): if self._articles is None: self._articles = [] for doc in self.docs: for k in set(self.fl).difference(doc.keys()): doc[k] = None self._articles.append(Article(**doc)) ...
articles getter
342,958
def removeAttribute(self, attrName): attrName = attrName.lower() try: del self._attributes[attrName] except KeyError: pass
removeAttribute - Removes an attribute, by name. @param attrName <str> - The attribute name
342,959
def set_digit(self, pos, digit, decimal=False): if self.invert: self.set_digit_raw(pos, IDIGIT_VALUES.get(str(digit).upper(), 0x00)) else: self.set_digit_raw(pos, DIGIT_VALUES.get(str(digit).upper(), 0x00)) if decimal: self.set_decimal(pos, True)
Set digit at position to provided value. Position should be a value of 0 to 3 with 0 being the left most digit on the display. Digit should be a number 0-9, character A-F, space (all LEDs off), or dash (-).
342,960
def diseases(context, api_key): adapter = context.obj[] api_key = api_key or context.obj.get() if not api_key: LOG.warning("Please provide a omim api key to load the omim gene panel") context.abort() try: mim_files = fetch_mim_files(api_key, genemap2=True) exc...
Update disease terms in mongo database.
342,961
def add_data(self, data): df = pd.DataFrame(data) name, dtype = self.get_singular_and_plural_dtype(self.dtype) if name in df.columns: df.index = df[name] df.index.name = name + " name" self.df = df
Add df to a MagicDataFrame using a data list. Parameters ---------- data : list of dicts data list with format [{'key1': 'val1', ...}, {'key1': 'val2', ...}, ... }] dtype : str MagIC table type
342,962
def connect(self, ctx): if hasattr(ctx,"conn") or "host" not in ctx.params: return ctx.conn = conn = connect(ctx.params["host"]) lnk = link.Link() lnk.wire("main", receive=conn, send=conn) ctx.client = api.Client(link=lnk) ctx.widget = ClientWidget...
establish xbahn connection and store on click context
342,963
def update_options(self, **options): _check_options(options) if in options: options[] = reference_to_path( options[]) if in options: self._id = options[] self._options.update(options)
Safely update this async job's configuration options.
342,964
def get_keys(self, lst): pk_name = self.get_pk_name() if self.is_pk_composite(): return [[getattr(item, pk) for pk in pk_name] for item in lst] else: return [getattr(item, pk_name) for item in lst]
return a list of pk values from object list
342,965
def _init(board, project_dir): project_dir = os.path.abspath(project_dir) pio_config_path = os.path.join(project_dir, "platformio.ini") if not os.path.isfile(pio_config_path): click.echo("Initializing PlatformIO project") with open("/dev/null", "wb") as null: try: ...
Initialize an OpenAg-based project. Internal function we use for both init and flash commands.
342,966
def verify_certificate_chain(cert_str, trusted_certs, ignore_self_signed=True): certificate = crypto.load_certificate(crypto.FILETYPE_ASN1, cert_str) try: store = crypto.X509Store() if ignore_self_signed: store.add_cert(certificate) for _cert in tr...
Verify a given certificate against a trust store
342,967
def rollback(self, transaction = None): if not self.in_transaction: raise NotInTransaction for collection, store in self.stores.items(): store.rollback() indexes = self.indexes[collection] indexes_to_rebuild = [] for key, index in inde...
Roll back a transaction.
342,968
def create_inputhook_qt4(mgr, app=None): if app is None: app = QtCore.QCoreApplication.instance() if app is None: app = QtGui.QApplication([" "]) ip = InteractiveShell.instance() if hasattr(ip, ): return app, ip._inputhook_qt4 got_kbdint = [Fal...
Create an input hook for running the Qt4 application event loop. Parameters ---------- mgr : an InputHookManager app : Qt Application, optional. Running application to use. If not given, we probe Qt for an existing application object, and create a new one if none is found. Return...
342,969
def get_outliers(campaign, pipeline=, sigma=5): from .utils import GetK2Campaign client = k2plr.API() assert pipeline.lower() in Pipelines, % pipeline with warnings.catch_warnings(): warnings.simplefilter("ignore") done = np.loadtxt(file, dtype=float) if len(d...
Computes the number of outliers for a given `campaign` and a given `pipeline`. Stores the results in a file under "/missions/k2/tables/". :param int sigma: The sigma level at which to clip outliers. Default 5
342,970
def recent_photos(request): imgs = [] for obj in Image_File.objects.filter(is_image=True).order_by("-date_created"): upurl = "/" + obj.upload.url thumburl = "" if obj.thumbnail: thumburl = "/" + obj.thumbnail.url imgs.append({: upurl, : thumburl, : True}) ret...
returns all the images from the data base
342,971
def plot_route_network_from_gtfs(g, ax=None, spatial_bounds=None, map_alpha=0.8, scalebar=True, legend=True, return_smopy_map=False, map_style=None): assert(isinstance(g, GTFS)) route_shapes = g.get_all_route_shapes() if spatial_bounds is None: spatial_bounds =...
Parameters ---------- g: A gtfspy.gtfs.GTFS object Where to get the data from? ax: matplotlib.Axes object, optional If None, a new figure and an axis is created spatial_bounds: dict, optional with str keys: lon_min, lon_max, lat_min, lat_max return_smopy_map: bool, optional ...
342,972
def visit_Call(self, node): if node in self.potential_iterator: matched_path = self.find_matching_builtin(node) if matched_path is None: return self.generic_visit(node) else: node = node.args[0] self.update =...
Replace function call by its correct iterator if it is possible.
342,973
def send_rally_point(self, i): p = self.rallyloader.rally_point(i) p.target_system = self.target_system p.target_component = self.target_component self.master.mav.send(p)
send rally points from fenceloader
342,974
def get_defaults_str(raw=None, after=): if raw is None: raw = __doc__ return unicode(textwrap.dedent(raw.split(after)[-1]).strip())
Get the string YAML representation of configuration defaults.
342,975
def app_url_value_preprocessor(self, f): self.record_once(lambda s: s.app.url_value_preprocessors .setdefault(None, []).append(f)) return f
Same as :meth:`url_value_preprocessor` but application wide.
342,976
def update_environment(lib_directory): lib_path = os.path.join(os.getcwd(), lib_directory) if in os.environ: os.environ[] = .format( lib_path, os.pathsep, os.environ[] ) else: os.environ[] ...
Run the App as a subprocess.
342,977
def seed_url(self): url = self.base_url if self.URL_TEMPLATE is not None: url = urlparse.urljoin( self.base_url, self.URL_TEMPLATE.format(**self.url_kwargs) ) if not url: return None url_parts = list(urlparse.urlparse(url)) ...
A URL that can be used to open the page. The URL is formatted from :py:attr:`URL_TEMPLATE`, which is then appended to :py:attr:`base_url` unless the template results in an absolute URL. :return: URL that can be used to open the page. :rtype: str
342,978
def consolidate_output(job, job_vars, output_ids): input_args, ids = job_vars work_dir = job.fileStore.getLocalTempDir() uuid = input_args[] rseq_id, exon_id, rsem_id = flatten(output_ids) qc_tar = job.fileStore.readGlobalFile(rseq_id, os.path.join(work_dir, )) exon_tar = job...
Combine the contents of separate zipped outputs into one via streaming job_vars: tuple Tuple of dictionaries: input_args and ids output_ids: tuple Nested tuple of all the output fileStore IDs
342,979
def bin_to_mac(bin, size=6): if len(bin) != size: raise Exception("Invalid MAC address: %s" % (bin)) return .join([binascii.hexlify(o) for o in bin])
Convert 6 bytes into a MAC string. Args: bin (str): hex string of lenth 6. Returns: str: String representation of the MAC address in lower case. Raises: Exception: if ``len(bin)`` is not 6.
342,980
def waitForAllConnectionsToClose(self): if not self._connections: return self._stop() return self._allConnectionsClosed.deferred().addBoth(self._stop)
Wait for all currently-open connections to enter the 'CLOSED' state. Currently this is only usable from test fixtures.
342,981
def request_raw(self, method, url, params=None, supplied_headers=None): if self.api_key: my_api_key = self.api_key else: from stripe import api_key my_api_key = api_key if my_api_key is None: raise error.AuthenticationError( ...
Mechanism for issuing an API call
342,982
def export_ruptures_xml(ekey, dstore): fmt = ekey[-1] oq = dstore[] num_ses = oq.ses_per_logic_tree_path mesh = get_mesh(dstore[]) ruptures_by_grp = {} for rgetter in gen_rupture_getters(dstore): ebrs = [ebr.export(mesh, rgetter.rlzs_by_gsim, num_ses) for ebr in rget...
:param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object
342,983
def make_local_settings(argv=None): description = textwrap.dedent( % make_local_settings.__doc__) parser = ArgParser( description=description, formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.add_argument(, nargs=, help=) parser.add_argument(, , default=) par...
Generate a local settings file. The most common usage is: make-local-settings <env> where env is replaced with and environment name such as stage or prod. For example: make-local-settings prod This will create a local settings file named local.prod.cfg with a prod section if loc...
342,984
def sampleLocationFromFeature(self, feature): if feature == "surface": return self.sampleLocationFromFeature() elif feature=="face": indx = self.rng.choice(range(self.faces.count)) rndFace = self.faces[indx] return self._sampleLocationOnFace(rndFace) elif feature == "edge": ...
Samples a location from the provided specific feature. TODO surface feature is not handled correctly. forwarded to sample from face instead.
342,985
def en020(self, value=None): if value is not None: try: value = float(value) except ValueError: raise ValueError( .format(value)) self._en020 = value
Corresponds to IDD Field `en020` mean coincident dry-bulb temperature to Enthalpy corresponding to 2.0% annual cumulative frequency of occurrence Args: value (float): value for IDD Field `en020` Unit: kJ/kg if `value` is None it will not be checked ag...
342,986
def get_version_from_module(module): if module is not None: module = str(module).split(, 1)[0] try: package = pkg_resources.get_distribution(module) return package.version except pkg_resources.DistributionNotFound: pass
Use pkg_resources to get version of installed module by name.
342,987
def set_output(self, output_names, output_dims): spec = self.spec nn_spec = self.nn_spec for idx, dim in enumerate(output_dims): spec.description.output[idx].type.multiArrayType.ClearField("shape") spec.description.output[idx].type.multiArrayType.shape.extend(dim...
Set the outputs of the network spec. Parameters ---------- output_names: [str] List of output names of the network. output_dims: [tuple] List of output dimensions of the network. The ordering of output_dims is the same as output_names. Examp...
342,988
def _preset(self, name, args, kwargs): if self.f_contains(name, shortcuts=False): raise ValueError( % name) else: self._changed_default_parameters[name] = (args, kwargs)
Generic preset function, marks a parameter or config for presetting.
342,989
async def run_jog(data): axis = data.get() direction = data.get() step = data.get() if axis not in (, , ): message = status = 400 elif direction not in (-1, 1): message = status = 400 elif step is None: message = status = 400 else: ...
Allow the user to jog the selected pipette around the deck map :param data: Information obtained from a POST request. The content type is application/json The correct packet form should be as follows: { 'token': UUID token from current session start 'command': 'jog' 'axis': The curren...
342,990
def remove(self, obj): activity = { "verb": "remove", "object": { "objectType": obj.object_type, "id": obj.id }, "target": { "objectType": self.object_type, "id": self.id } ...
Removes a member from the collection. :param obj: Object to remove. Example: >>> mycollection.remove(pump.Person('bob@example.org'))
342,991
def get_rmsd(self, mol1, mol2): label1, label2 = self._mapper.uniform_labels(mol1, mol2) if label1 is None or label2 is None: return float("Inf") return self._calc_rms(mol1, mol2, label1, label2)
Get RMSD between two molecule with arbitrary atom order. Returns: RMSD if topology of the two molecules are the same Infinite if the topology is different
342,992
def read(self): for line in self.io.read(): with self.parse_line(line) as j: yield j
Iterate over all JSON input (Generator)
342,993
def status(self): status = c_long() _WinHttpRequest._Status(self, byref(status)) return int(status.value)
Gets status of response.
342,994
def absent(name=None, canonical=None, **api_opts): ret = {: name, : False, : , : {}} obj = __salt__[](name=name, canonical=canonical, **api_opts) if not obj: ret[] = True ret[] = return ret if __opts__[]: ret[] = None ret[] = {: obj, : } return ret...
Ensure the CNAME with the given name or canonical name is removed
342,995
def _parse_signed_int_components(buf): sign_bit = 0 value = 0 first = True while True: ch = buf.read(1) if ch == b: break octet = ord(ch) if first: if octet & _SIGNED_INT_SIGN_MASK: sign_bit = 1 value = octet & _SI...
Parses the remainder of a file-like object as a signed magnitude value. Returns: Returns a pair of the sign bit and the unsigned magnitude.
342,996
def remover(self, id_tipo_acesso, id_equipamento): if not is_valid_int_param(id_tipo_acesso): raise InvalidParameterError(u) if not is_valid_int_param(id_equipamento): raise InvalidParameterError(u) url = + \ str(id_equipamento) + + str(id_tipo_a...
Removes relationship between equipment and access type. :param id_equipamento: Equipment identifier. :param id_tipo_acesso: Access type identifier. :return: None :raise EquipamentoNaoExisteError: Equipment doesn't exist. :raise EquipamentoAcessoNaoExisteError: Relationship bet...
342,997
def vn(x): if x == []: return None if isinstance(x, list): return .join(x) if isinstance(x, datetime): return x.isoformat() return x
value or none, returns none if x is an empty list
342,998
def write_membership(filename,config,srcfile,section=None): source = Source() source.load(srcfile,section=section) loglike = createLoglike(config,source) loglike.write_membership(filename)
Top level interface to write the membership from a config and source model.
342,999
def GetFileEntryByPathSpec(self, path_spec): return fvde_file_entry.FVDEFileEntry( self._resolver_context, self, path_spec, is_root=True, is_virtual=True)
Retrieves a file entry for a path specification. Args: path_spec (PathSpec): path specification. Returns: FVDEFileEntry: file entry or None.