code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def strel_pair(x, y): """Create a structing element composed of the origin and another pixel x, y - x and y offsets of the other pixel returns a structuring element """ x_center = int(np.abs(x)) y_center = int(np.abs(y)) result = np.zeros((y_center * 2 + 1, x_center * 2 + 1), bool...
Create a structing element composed of the origin and another pixel x, y - x and y offsets of the other pixel returns a structuring element
def MSTORE(self, address, value): """Save word to memory""" if istainted(self.pc): for taint in get_taints(self.pc): value = taint_with(value, taint) self._allocate(address, 32) self._store(address, value, 32)
Save word to memory
def authenticate(url, account, key, by='name', expires=0, timestamp=None, timeout=None, request_type="xml", admin_auth=False, use_password=False, raise_on_error=False): """ Authenticate to the Zimbra server :param url: URL of Zimbra SOAP service :param account: The accoun...
Authenticate to the Zimbra server :param url: URL of Zimbra SOAP service :param account: The account to be authenticated against :param key: The preauth key of the domain of the account or a password (if admin_auth or use_password is True) :param by: If the account is specified as a name, an ID o...
def close(self): """End the report.""" endpoint = self.endpoint.replace("/api/v1/spans", "") logger.debug("Zipkin trace may be located at this URL {}/traces/{}".format(endpoint, self.trace_id))
End the report.
def lpad(col, len, pad): """ Left-pad the string column to width `len` with `pad`. >>> df = spark.createDataFrame([('abcd',)], ['s',]) >>> df.select(lpad(df.s, 6, '#').alias('s')).collect() [Row(s=u'##abcd')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.lp...
Left-pad the string column to width `len` with `pad`. >>> df = spark.createDataFrame([('abcd',)], ['s',]) >>> df.select(lpad(df.s, 6, '#').alias('s')).collect() [Row(s=u'##abcd')]
def _get_string_match_value(self, string, string_match_type): """Gets the match value""" if string_match_type == Type(**get_type_data('EXACT')): return string elif string_match_type == Type(**get_type_data('IGNORECASE')): return re.compile('^' + string, re.I) elif...
Gets the match value
def find_by_reference_ids(reference_ids, _connection=None, page_size=100, page_number=0, sort_by=enums.DEFAULT_SORT_BY, sort_order=enums.DEFAULT_SORT_ORDER): """ List all videos identified by a list of reference ids """ if not isinstance(reference_ids, (list, tuple)): ...
List all videos identified by a list of reference ids
def serialize_dictionary(dictionary): """Function to stringify a dictionary recursively. :param dictionary: The dictionary. :type dictionary: dict :return: The string. :rtype: basestring """ string_value = {} for k, v in list(dictionary.items()): if isinstance(v, QUrl): ...
Function to stringify a dictionary recursively. :param dictionary: The dictionary. :type dictionary: dict :return: The string. :rtype: basestring
def clean_item_no_list(i): """ Return a json-clean item or None. Will log info message for failure. """ itype = type(i) if itype == dict: return clean_dict(i, clean_item_no_list) elif itype == list: return clean_tuple(i, clean_item_no_list) elif itype == tuple: re...
Return a json-clean item or None. Will log info message for failure.
def load_features(self, features, image_type=None, from_array=False, threshold=0.001): """ Load features from current Dataset instance or a list of files. Args: features: List containing paths to, or names of, features to extract. Each element in the lis...
Load features from current Dataset instance or a list of files. Args: features: List containing paths to, or names of, features to extract. Each element in the list must be a string containing either a path to an image, or the name of a feature (as named ...
def autoconfig_url_from_registry(): """ Get the PAC ``AutoConfigURL`` value from the Windows Registry. This setting is visible as the "use automatic configuration script" field in Internet Options > Connection > LAN Settings. :return: The value from the registry, or None if the value isn't co...
Get the PAC ``AutoConfigURL`` value from the Windows Registry. This setting is visible as the "use automatic configuration script" field in Internet Options > Connection > LAN Settings. :return: The value from the registry, or None if the value isn't configured or available. Note that it may b...
def query_all(self): """ Query all records without limit and offset. """ return self.query_model(self.model, self.condition, order_by=self.order_by, group_by=self.group_by, having=self.having)
Query all records without limit and offset.
def get_comments_of_delivery_note_per_page(self, delivery_note_id, per_page=1000, page=1): """ Get comments of delivery note per page :param delivery_note_id: the delivery note :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 ...
Get comments of delivery note per page :param delivery_note_id: the delivery note :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :return: list
def to_config(self, k, v): """ Hook method that allows conversion of individual options. :param k: the key of the option :type k: str :param v: the value :type v: object :return: the potentially processed value :rtype: object """ if k == "...
Hook method that allows conversion of individual options. :param k: the key of the option :type k: str :param v: the value :type v: object :return: the potentially processed value :rtype: object
def annotate(args): """ %prog annotate new.bed old.bed 2> log Annotate the `new.bed` with features from `old.bed` for the purpose of gene numbering. Ambiguity in ID assignment can be resolved by either of the following 2 methods: - `alignment`: make use of global sequence alignment score (calc...
%prog annotate new.bed old.bed 2> log Annotate the `new.bed` with features from `old.bed` for the purpose of gene numbering. Ambiguity in ID assignment can be resolved by either of the following 2 methods: - `alignment`: make use of global sequence alignment score (calculated by `needle`) - `overl...
def raw_from_delimited(msgs: DelimitedMsg) -> RawMsgs: """\ From a message consisting of header frames, delimiter frame, and payload frames, return a tuple `(header, payload)`. The payload frames may be returned as sequences of bytes (raw) or as `Message`s. """ delim = _rindex(msgs, b'') return ...
\ From a message consisting of header frames, delimiter frame, and payload frames, return a tuple `(header, payload)`. The payload frames may be returned as sequences of bytes (raw) or as `Message`s.
def fix_spelling(words, join=True, joinstring=' '): """Simple function for quickly correcting misspelled words. Parameters ---------- words: list of str or str Either a list of pretokenized words or a string. In case of a string, it will be splitted using default behaviour of string.spl...
Simple function for quickly correcting misspelled words. Parameters ---------- words: list of str or str Either a list of pretokenized words or a string. In case of a string, it will be splitted using default behaviour of string.split() function. join: boolean (default: True) Sh...
def similarity(w1, w2, threshold=0.5): """compare two strings 'words', and return ratio of smiliarity, be it larger than the threshold, or 0 otherwise. NOTE: if the result more like junk, increase the threshold value. """ ratio = SM(None, str(w1).lower(), str(w2).lower()).ratio() return rat...
compare two strings 'words', and return ratio of smiliarity, be it larger than the threshold, or 0 otherwise. NOTE: if the result more like junk, increase the threshold value.
def getKnownPlayers(reset=False): """identify all of the currently defined players""" global playerCache if not playerCache or reset: jsonFiles = os.path.join(c.PLAYERS_FOLDER, "*.json") for playerFilepath in glob.glob(jsonFiles): filename = os.path.basename(playerFilepath) ...
identify all of the currently defined players
def get_disparity(self, pair): """ Compute disparity from image pair (left, right). First, convert images to grayscale if needed. Then pass to the ``_block_matcher`` for stereo matching. """ gray = [] if pair[0].ndim == 3: for side in pair: ...
Compute disparity from image pair (left, right). First, convert images to grayscale if needed. Then pass to the ``_block_matcher`` for stereo matching.
def resume(profile_process='worker'): """ Resume paused profiling. Parameters ---------- profile_process : string whether to profile kvstore `server` or `worker`. server can only be profiled when kvstore is of type dist. if this is not passed, defaults to `worker` """ ...
Resume paused profiling. Parameters ---------- profile_process : string whether to profile kvstore `server` or `worker`. server can only be profiled when kvstore is of type dist. if this is not passed, defaults to `worker`
def choice_SlackBuild(self): """View .SlackBuild file """ SlackBuild = ReadSBo(self.sbo_url).slackbuild(self.name, ".SlackBuild") fill = self.fill_pager(SlackBuild) self.pager(SlackBuild + fill)
View .SlackBuild file
def _insert_update(self, index: int, length: int) -> None: """Update self._type_to_spans according to the added length.""" ss, se = self._span for spans in self._type_to_spans.values(): for span in spans: if index < span[1] or span[1] == index == se: ...
Update self._type_to_spans according to the added length.
def get_text(self): ''' ::returns: a rendered string representation of the given row ''' row_lines = [] for line in zip_longest(*[column.get_cell_lines() for column in self.columns], fillvalue=' '): row_lines.append(' '.join(line)) return '\n'...
::returns: a rendered string representation of the given row
def download_url(url, filename=None, spoof=False, iri_fallback=True, verbose=True, new=False, chunk_size=None): r""" downloads a url to a filename. Args: url (str): url to download filename (str): path to download to. Defaults to basename of url spoof (bool): if True pr...
r""" downloads a url to a filename. Args: url (str): url to download filename (str): path to download to. Defaults to basename of url spoof (bool): if True pretends to by Firefox iri_fallback : falls back to requests get call if there is a UnicodeError References: http:...
def generate_evenly_distributed_data(dim = 2000, num_active = 40, num_samples = 1000, num_negatives = 500): """ Generates a set of data drawn from a uniform distribution. The binning structure from Poir...
Generates a set of data drawn from a uniform distribution. The binning structure from Poirazi & Mel is ignored, and all (dim choose num_active) arrangements are possible. num_negatives samples are put into a separate negatives category for output compatibility with generate_data, but are otherwise identical.
def data_find_text(data, path): """Return the text value of the element-as-tuple in tuple ``data`` using simplified XPath ``path``. """ el = data_find(data, path) if not isinstance(el, (list, tuple)): return None texts = [child for child in el[1:] if not isinstance(child, (tuple, list, d...
Return the text value of the element-as-tuple in tuple ``data`` using simplified XPath ``path``.
def getPhysicalMaximum(self,chn=None): """ Returns the maximum physical value of signal edfsignal. Parameters ---------- chn : int channel number Examples -------- >>> import pyedflib >>> f = pyedflib.data.test_generator() >>>...
Returns the maximum physical value of signal edfsignal. Parameters ---------- chn : int channel number Examples -------- >>> import pyedflib >>> f = pyedflib.data.test_generator() >>> f.getPhysicalMaximum(0)==1000.0 True >>> f...
def error(request, message, extra_tags='', fail_silently=False, async=False): """Adds a message with the ``ERROR`` level.""" if ASYNC and async: messages.debug(_get_user(request), message) else: add_message(request, constants.ERROR, message, extra_tags=extra_tags, fail_si...
Adds a message with the ``ERROR`` level.
def serialize(ty, *values, **kwargs): """ Serialize value using type specification in ty. ABI.serialize('int256', 1000) ABI.serialize('(int, int256)', 1000, 2000) """ try: parsed_ty = abitypes.parse(ty) except Exception as e: # Catch and re...
Serialize value using type specification in ty. ABI.serialize('int256', 1000) ABI.serialize('(int, int256)', 1000, 2000)
def getFunc(self, o: Any) -> Callable: """ Get the next function from the list of routes that is capable of processing o's type. :param o: the object to process :return: the next function """ for cls, func in self.routes.items(): if isinstance(o, cls)...
Get the next function from the list of routes that is capable of processing o's type. :param o: the object to process :return: the next function
def removeGaps(self) : """Remove all gaps between regions""" for i in range(1, len(self.children)) : if self.children[i].x1 > self.children[i-1].x2: aux_moveTree(self.children[i-1].x2-self.children[i].x1, self.children[i])
Remove all gaps between regions
def stopdocs(): "stop Sphinx watchdog" for i in range(4): pid = watchdog_pid() if pid: if not i: sh('ps {}'.format(pid)) sh('kill {}'.format(pid)) time.sleep(.5) else: break
stop Sphinx watchdog
def updateColumnValue(self, column, value, index=None): """ Assigns the value for the column of this record to the inputed value. :param index | <int> value | <variant> """ if index is None: index = self.treeWidget().column(co...
Assigns the value for the column of this record to the inputed value. :param index | <int> value | <variant>
def editpropset(self): ''' :foo=10 ''' self.ignore(whitespace) if not self.nextstr(':'): self._raiseSyntaxExpects(':') relp = self.relprop() self.ignore(whitespace) self.nextmust('=') self.ignore(whitespace) valu = self.va...
:foo=10
def length(self): """Return the length of this response. We expose this as an attribute since using len() directly can fail for responses larger than sys.maxint. Returns: Response length (as int or long) """ def ProcessContentRange(content_range): ...
Return the length of this response. We expose this as an attribute since using len() directly can fail for responses larger than sys.maxint. Returns: Response length (as int or long)
def alignment_a(self): """Computes the rotation matrix that aligns the unit cell with the Cartesian axes, starting with cell vector a. * a parallel to x * b in xy-plane with b_y positive * c with c_z positive """ from molmod.transformations import Rot...
Computes the rotation matrix that aligns the unit cell with the Cartesian axes, starting with cell vector a. * a parallel to x * b in xy-plane with b_y positive * c with c_z positive
def RegisterArtifact(self, artifact_rdfvalue, source="datastore", overwrite_if_exists=False, overwrite_system_artifacts=False): """Registers a new artifact.""" artifact_name = artifact_rdfvalue.name if artifact_name ...
Registers a new artifact.
def _check_allowed_values(self, parameters): """ Check whether the given parameter value is allowed. Log messages into ``self.result``. :param dict parameters: the given parameters """ for key, allowed_values in self.ALLOWED_VALUES: self.log([u"Checking allow...
Check whether the given parameter value is allowed. Log messages into ``self.result``. :param dict parameters: the given parameters
def _body(self, paragraphs): """Generate a body of text""" body = [] for i in range(paragraphs): paragraph = self._paragraph(random.randint(1, 10)) body.append(paragraph) return '\n'.join(body)
Generate a body of text
def load_feedback(): """ Open existing feedback file """ result = {} if os.path.exists(_feedback_file): f = open(_feedback_file, 'r') cont = f.read() f.close() else: cont = '{}' try: result = json.loads(cont) if cont else {} except ValueError as e: ...
Open existing feedback file
def initialize(self, *args): """Initialize a recommender by resetting stored users and items. """ # number of observed users self.n_user = 0 # store user data self.users = {} # number of observed items self.n_item = 0 # store item data s...
Initialize a recommender by resetting stored users and items.
def dir(): """Return the list of patched function names. Used for patching functions imported from the module. """ dir = [ 'abspath', 'dirname', 'exists', 'expanduser', 'getatime', 'getctime', 'getmtime', 'getsize', 'isabs', 'isdir', 'isfile', 'islink'...
Return the list of patched function names. Used for patching functions imported from the module.
def is_string_dtype(arr_or_dtype): """ Check whether the provided array or dtype is of the string dtype. Parameters ---------- arr_or_dtype : array-like The array or dtype to check. Returns ------- boolean Whether or not the array or dtype is of the string dtype. E...
Check whether the provided array or dtype is of the string dtype. Parameters ---------- arr_or_dtype : array-like The array or dtype to check. Returns ------- boolean Whether or not the array or dtype is of the string dtype. Examples -------- >>> is_string_dtype(st...
def step(self, batch_size, ignore_stale_grad=False): """Makes one step of parameter update. Should be called after `autograd.backward()` and outside of `record()` scope. For normal parameter updates, `step()` should be used, which internally calls `allreduce_grads()` and then `update()`...
Makes one step of parameter update. Should be called after `autograd.backward()` and outside of `record()` scope. For normal parameter updates, `step()` should be used, which internally calls `allreduce_grads()` and then `update()`. However, if you need to get the reduced gradients to p...
def build_paths(self, end_entity_cert): """ Builds a list of ValidationPath objects from a certificate in the operating system trust store to the end-entity certificate :param end_entity_cert: A byte string of a DER or PEM-encoded X.509 certificate, or an instanc...
Builds a list of ValidationPath objects from a certificate in the operating system trust store to the end-entity certificate :param end_entity_cert: A byte string of a DER or PEM-encoded X.509 certificate, or an instance of asn1crypto.x509.Certificate :return: ...
def connect(host='localhost', port=21050, database=None, timeout=None, use_ssl=False, ca_cert=None, auth_mechanism='NOSASL', user=None, password=None, kerberos_service_name='impala', use_ldap=None, ldap_user=None, ldap_password=None, use_kerberos=None, protocol=None, krb_...
Get a connection to HiveServer2 (HS2). These options are largely compatible with the impala-shell command line arguments. See those docs for more information. Parameters ---------- host : str The hostname for HS2. For Impala, this can be any of the `impalad`s. port : int, optional ...
def _jar_paths(): """Produce potential paths for an h2o.jar executable.""" # PUBDEV-3534 hook to use arbitrary h2o.jar own_jar = os.getenv("H2O_JAR_PATH", "") if own_jar != "": if not os.path.isfile(own_jar): raise H2OStartupError("Environment variable H2O_JA...
Produce potential paths for an h2o.jar executable.
def getUserInfo(self): """ Returns a dictionary of user info that google stores. """ userJson = self.httpGet(ReaderUrl.USER_INFO_URL) result = json.loads(userJson, strict=False) self.userId = result['userId'] return result
Returns a dictionary of user info that google stores.
def harmonic(y, **kwargs): '''Extract harmonic elements from an audio time-series. Parameters ---------- y : np.ndarray [shape=(n,)] audio time series kwargs : additional keyword arguments. See `librosa.decompose.hpss` for details. Returns ------- y_harmonic : np.ndarra...
Extract harmonic elements from an audio time-series. Parameters ---------- y : np.ndarray [shape=(n,)] audio time series kwargs : additional keyword arguments. See `librosa.decompose.hpss` for details. Returns ------- y_harmonic : np.ndarray [shape=(n,)] audio time ...
def parse_changelog(path, **kwargs): """ Load and parse changelog file from ``path``, returning data structures. This function does not alter any files on disk; it is solely for introspecting a Releases ``changelog.rst`` and programmatically answering questions like "are there any unreleased bugfix...
Load and parse changelog file from ``path``, returning data structures. This function does not alter any files on disk; it is solely for introspecting a Releases ``changelog.rst`` and programmatically answering questions like "are there any unreleased bugfixes for the 2.3 line?" or "what was included i...
def add_sender_info( self, sender_txhash, nulldata_vin_outpoint, sender_out_data ): """ Record sender information in our block info. @sender_txhash: txid of the sender @nulldata_vin_outpoint: the 'vout' index from the nulldata tx input that this transaction funded """ ass...
Record sender information in our block info. @sender_txhash: txid of the sender @nulldata_vin_outpoint: the 'vout' index from the nulldata tx input that this transaction funded
def distance(p_a, p_b): """ Euclidean distance, between two points Args: p_a (:obj:`Point`) p_b (:obj:`Point`) Returns: float: distance, in degrees """ return sqrt((p_a.lat - p_b.lat) ** 2 + (p_a.lon - p_b.lon) ** 2)
Euclidean distance, between two points Args: p_a (:obj:`Point`) p_b (:obj:`Point`) Returns: float: distance, in degrees
def latexsnippet(code, kvs, staffsize=17, initiallines=1): """Take in account key/values""" snippet = '' staffsize = int(kvs['staffsize']) if 'staffsize' in kvs \ else staffsize initiallines = int(kvs['initiallines']) if 'initiallines' in kvs \ else initiallines annotationsize = .5 *...
Take in account key/values
def isotime(at=None, subsecond=False): """Stringify time in ISO 8601 format.""" if not at: at = utcnow() st = at.strftime(_ISO8601_TIME_FORMAT if not subsecond else _ISO8601_TIME_FORMAT_SUBSECOND) tz = at.tzinfo.tzname(None) if at.tzinfo else 'UTC' s...
Stringify time in ISO 8601 format.
def save_form(self, request, form, change): """Here we pluck out the data to create a new cloned repo. Form is an instance of NewRepoForm. """ name = form.cleaned_data['name'] origin_url = form.cleaned_data['origin_url'] res = ClonedRepo(name=name, origin=origin_url) ...
Here we pluck out the data to create a new cloned repo. Form is an instance of NewRepoForm.
def loglike(self, endog, mu, freq_weights=1., scale=1.): """ The log-likelihood in terms of the fitted mean response. Parameters ---------- endog : array-like Endogenous response variable mu : array-like Fitted mean response variable freq_...
The log-likelihood in terms of the fitted mean response. Parameters ---------- endog : array-like Endogenous response variable mu : array-like Fitted mean response variable freq_weights : array-like 1d array of frequency weights. The default i...
def _create_subplots(self, fig, layout): """ Create suplots and return axs """ num_panels = len(layout) axsarr = np.empty((self.nrow, self.ncol), dtype=object) # Create axes i = 1 for row in range(self.nrow): for col in range(self.ncol): ...
Create suplots and return axs
def compile_template(instance, template, additionnal_context=None): """ Fill the given template with the instance's datas and return the odt file For every instance class, common values are also inserted in the context dict (and so can be used) : * config values :param obj instance: the i...
Fill the given template with the instance's datas and return the odt file For every instance class, common values are also inserted in the context dict (and so can be used) : * config values :param obj instance: the instance of a model (like Userdatas, Company) :param template: the template o...
def get_dbcollection_with_es(self, **kwargs): """ Get DB objects collection by first querying ES. """ es_objects = self.get_collection_es() db_objects = self.Model.filter_objects(es_objects) return db_objects
Get DB objects collection by first querying ES.
def _get_kwargs(profile=None, **connection_args): ''' get connection args ''' if profile: prefix = profile + ":keystone." else: prefix = "keystone." def get(key, default=None): ''' look in connection_args first, then default to config file ''' ret...
get connection args
def get_url(cls, url, uid, **kwargs): """ Construct the URL for talking to an individual resource. http://myapi.com/api/resource/1 Args: url: The url for this resource uid: The unique identifier for an individual resource kwargs: Additional keyword a...
Construct the URL for talking to an individual resource. http://myapi.com/api/resource/1 Args: url: The url for this resource uid: The unique identifier for an individual resource kwargs: Additional keyword argueents returns: final_url: The URL f...
def wr_txt(self, fout_txt): """Write to a file GOEA results in an ASCII text format.""" with open(fout_txt, 'w') as prt: for line in self.ver_list: prt.write("{LINE}\n".format(LINE=line)) self.prt_txt(prt) print(" WROTE: {TXT}".format(TXT=fout_txt))
Write to a file GOEA results in an ASCII text format.
def _find_cellid(self, code): """Determines the most similar cell (if any) to the specified code. It must have at least 50% overlap ratio and have been a loop-intercepted cell previously. Args: code (str): contents of the code cell that were executed. """ fro...
Determines the most similar cell (if any) to the specified code. It must have at least 50% overlap ratio and have been a loop-intercepted cell previously. Args: code (str): contents of the code cell that were executed.
def updates(self): ''' Get the contents of ``_updates`` (all updates) and puts them in an Updates class to expose the list and summary functions. Returns: Updates: An instance of the Updates class with all updates for the system. .. code-block:: python ...
Get the contents of ``_updates`` (all updates) and puts them in an Updates class to expose the list and summary functions. Returns: Updates: An instance of the Updates class with all updates for the system. .. code-block:: python import salt.utils.win_updat...
def getDefaultItems(self): """ Returns a list with the default plugins in the repo tree item registry. """ return [ RtiRegItem('HDF-5 file', 'argos.repo.rtiplugins.hdf5.H5pyFileRti', extensions=['hdf5', 'h5', 'h5e', 'he5', 'nc']), # hdf e...
Returns a list with the default plugins in the repo tree item registry.
def unregister_provider(self, provider): """ Unregister a provider. Blocks until this RpcConsumer is unregistered from its QueueConsumer, which only happens when all providers have asked to unregister. """ self._unregistering_providers.add(provider) remaining_providers =...
Unregister a provider. Blocks until this RpcConsumer is unregistered from its QueueConsumer, which only happens when all providers have asked to unregister.
def load(dbname, dbmode='a'): """Load an existing hdf5 database. Return a Database instance. :Parameters: filename : string Name of the hdf5 database to open. mode : 'a', 'r' File mode : 'a': append, 'r': read-only. """ if dbmode == 'w': raise AttributeError("db...
Load an existing hdf5 database. Return a Database instance. :Parameters: filename : string Name of the hdf5 database to open. mode : 'a', 'r' File mode : 'a': append, 'r': read-only.
def remove_negativescores_nodes(self): """\ if there are elements inside our top node that have a negative gravity score, let's give em the boot """ gravity_items = self.parser.css_select(self.top_node, "*[gravityScore]") for item in gravity_items: sco...
\ if there are elements inside our top node that have a negative gravity score, let's give em the boot
def _parse_01(ofiles, individual=False): """ a subfunction for summarizing results """ ## parse results from outfiles cols = [] dats = [] for ofile in ofiles: ## parse file with open(ofile) as infile: dat = infile.read() lastbits = dat.split(".mcmc.txt...
a subfunction for summarizing results
def post(self, request, *args, **kwargs): """ Returns a token identifying the user in Centrifugo. """ current_timestamp = "%.0f" % time.time() user_id_str = u"{0}".format(request.user.id) token = generate_token(settings.CENTRIFUGE_SECRET, user_id_str, "{0}".format(curren...
Returns a token identifying the user in Centrifugo.
def _unique_by_email(users_and_watches): """Given a sequence of (User/EmailUser, [Watch, ...]) pairs clustered by email address (which is never ''), yield from each cluster a single pair like this:: (User/EmailUser, [Watch, Watch, ...]). The User/Email is that of... (1) the first incoming pa...
Given a sequence of (User/EmailUser, [Watch, ...]) pairs clustered by email address (which is never ''), yield from each cluster a single pair like this:: (User/EmailUser, [Watch, Watch, ...]). The User/Email is that of... (1) the first incoming pair where the User has an email and is not ...
def adjustMask(self): """ Updates the alpha mask for this popup widget. """ if self.currentMode() == XPopupWidget.Mode.Dialog: self.clearMask() return path = self.borderPath() bitmap = QBitmap(self.width(), self.height()) ...
Updates the alpha mask for this popup widget.
def create_cherry_pick(self, cherry_pick_to_create, project, repository_id): """CreateCherryPick. [Preview API] Cherry pick a specific commit or commits that are associated to a pull request into a new branch. :param :class:`<GitAsyncRefOperationParameters> <azure.devops.v5_0.git.models.GitAsync...
CreateCherryPick. [Preview API] Cherry pick a specific commit or commits that are associated to a pull request into a new branch. :param :class:`<GitAsyncRefOperationParameters> <azure.devops.v5_0.git.models.GitAsyncRefOperationParameters>` cherry_pick_to_create: :param str project: Project ID o...
def delete(self, upload_id): """ Deletes an upload by ID. """ return super(UploadsProxy, self).delete(upload_id, file_upload=True)
Deletes an upload by ID.
def read_data(self, size): """Receive data from the device. If the read fails for any reason, an :obj:`IOError` exception is raised. :param size: the number of bytes to read. :type size: int :return: the data received. :rtype: list(int) """ r...
Receive data from the device. If the read fails for any reason, an :obj:`IOError` exception is raised. :param size: the number of bytes to read. :type size: int :return: the data received. :rtype: list(int)
def dereference_object(object_type, object_uuid, status): """Show linked persistent identifier(s).""" from .models import PersistentIdentifier pids = PersistentIdentifier.query.filter_by( object_type=object_type, object_uuid=object_uuid ) if status: pids = pids.filter_by(status=stat...
Show linked persistent identifier(s).
def descriptionHtml(self): """ HTML help describing the class. For use in the detail editor. """ if self.cls is None: return None elif hasattr(self.cls, 'descriptionHtml'): return self.cls.descriptionHtml() else: return ''
HTML help describing the class. For use in the detail editor.
def search_process_log(self, pid, filter={}, start=0, limit=1000): ''' search_process_log(self, pid, filter={}, start=0, limit=1000) Search in process logs :Parameters: * *pid* (`string`) -- Identifier of an existing process * *start* (`int`) -- start index to retrieve ...
search_process_log(self, pid, filter={}, start=0, limit=1000) Search in process logs :Parameters: * *pid* (`string`) -- Identifier of an existing process * *start* (`int`) -- start index to retrieve from. Default is 0 * *limit* (`int`) -- maximum number of entities to retrieve....
def get_player(self, *tags: crtag, **params: keys): """Get a player information Parameters ---------- \*tags: str Valid player tags. Minimum length: 3 Valid characters: 0289PYLQGRJCUV \*\*keys: Optional[list] = None Filter which keys should be...
Get a player information Parameters ---------- \*tags: str Valid player tags. Minimum length: 3 Valid characters: 0289PYLQGRJCUV \*\*keys: Optional[list] = None Filter which keys should be included in the response \*\*exclude: Opti...
def string_chain(text, filters): """ Chain several filters after each other, applies the filter on the entire string :param text: String to format :param filters: Sequence of filters to apply on String :return: The formatted String """ if filters is None: ...
Chain several filters after each other, applies the filter on the entire string :param text: String to format :param filters: Sequence of filters to apply on String :return: The formatted String
def read_file(self): """ Open the file and assiging the permission to read/write and return the content in json formate. Return : json data """ file_obj = open(self.file, 'r') content = file_obj.read() file_obj.close() if content: cont...
Open the file and assiging the permission to read/write and return the content in json formate. Return : json data
def get_default_config(self): """ Returns the default collector settings """ default_config = super(FlumeCollector, self).get_default_config() default_config['path'] = 'flume' default_config['req_host'] = 'localhost' default_config['req_port'] = 41414 defa...
Returns the default collector settings
def get_application(*args): ''' Returns a WSGI application function. If you supply the WSGI app and config it will use that, otherwise it will try to obtain them from a local Salt installation ''' opts_tuple = args def wsgi_app(environ, start_response): root, _, conf = opts_tuple or...
Returns a WSGI application function. If you supply the WSGI app and config it will use that, otherwise it will try to obtain them from a local Salt installation
def loop_exit_label(self, loop_type): """ Returns the label for the given loop type which exits the loop. loop_type must be one of 'FOR', 'WHILE', 'DO' """ for i in range(len(self.LOOPS) - 1, -1, -1): if loop_type == self.LOOPS[i][0]: return self.LOOPS[i][1] ...
Returns the label for the given loop type which exits the loop. loop_type must be one of 'FOR', 'WHILE', 'DO'
def process_create_ex(self, executable, arguments, environment_changes, flags, timeout_ms, priority, affinity): """Creates a new process running in the guest with the extended options for setting the process priority and affinity. See :py:func:`IGuestSession.process_create` for more in...
Creates a new process running in the guest with the extended options for setting the process priority and affinity. See :py:func:`IGuestSession.process_create` for more information. in executable of type str Full path to the file to execute in the guest. The file has to ...
def search_dashboard_for_facets(self, **kwargs): # noqa: E501 """Lists the values of one or more facets over the customer's non-deleted dashboards # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asy...
Lists the values of one or more facets over the customer's non-deleted dashboards # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.search_dashboard_for_facets(async_req...
def agg(self, func, *fields, **name): """ Calls the aggregation function `func` on each group in the GroubyTable, and leaves the results in a new column with the name of the aggregation function. Call `.agg` with `name='desired_column_name' to choose a column name for th...
Calls the aggregation function `func` on each group in the GroubyTable, and leaves the results in a new column with the name of the aggregation function. Call `.agg` with `name='desired_column_name' to choose a column name for this aggregation.
def write_serializable_array(self, array): """ Write an array of serializable objects to the stream. Args: array(list): a list of serializable objects. i.e. extending neo.IO.Mixins.SerializableMixin """ if array is None: self.write_byte(0) else: ...
Write an array of serializable objects to the stream. Args: array(list): a list of serializable objects. i.e. extending neo.IO.Mixins.SerializableMixin
def _read_structure_attributes(f): """ function to read information from a PEST-style structure file Parameters ---------- f : (file handle) file handle open for reading Returns ------- nugget : float the GeoStruct nugget transform : str the GeoStruct transforma...
function to read information from a PEST-style structure file Parameters ---------- f : (file handle) file handle open for reading Returns ------- nugget : float the GeoStruct nugget transform : str the GeoStruct transformation variogram_info : dict dict...
def create_metric(metric_type, metric_id, data): """ Create Hawkular-Metrics' submittable structure. :param metric_type: MetricType to be matched (required) :param metric_id: Exact string matching metric id :param data: A datapoint or a list of datapoints created with create_datapoint(value, timest...
Create Hawkular-Metrics' submittable structure. :param metric_type: MetricType to be matched (required) :param metric_id: Exact string matching metric id :param data: A datapoint or a list of datapoints created with create_datapoint(value, timestamp, tags)
def unseal(self, data, return_options=False): '''Unseal data''' data = self._remove_magic(data) data = urlsafe_nopadding_b64decode(data) options = self._read_header(data) data = self._add_magic(data) data = self._unsign_data(data, options) data = self._remove_mag...
Unseal data
def open(filepath, edit_local=False): """Open any wt5 file, returning the top-level object (data or collection). Parameters ---------- filepath : path-like Path to file. Can be either a local or remote file (http/ftp). Can be compressed with gz/bz2, decompression based on file n...
Open any wt5 file, returning the top-level object (data or collection). Parameters ---------- filepath : path-like Path to file. Can be either a local or remote file (http/ftp). Can be compressed with gz/bz2, decompression based on file name. edit_local : boolean (optional) ...
def info_community(self,teamid): '''Get comunity info using a ID''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/standings.phtml',"User-Agent": user_agent} req = self.session.get('http://'+self.domain+'/teamInfo.phtml?ti...
Get comunity info using a ID
def validate_image_size(image): """ Validate that a particular image size. """ config = get_app_config() valid_max_image_size_in_bytes = config.valid_max_image_size * 1024 if config and not image.size <= valid_max_image_size_in_bytes: raise ValidationError( _("The logo image ...
Validate that a particular image size.
def parse_manifest(self, manifest_xml): """ Parse manifest xml file :type manifest_xml: str :param manifest_xml: raw xml content of manifest file """ manifest = dict() try: mdata = xmltodict.parse(manifest_xml)['modules']['module'] for mo...
Parse manifest xml file :type manifest_xml: str :param manifest_xml: raw xml content of manifest file
def _initialize_plugin_system(self) -> None: """Initialize the plugin system""" self._preloop_hooks = [] self._postloop_hooks = [] self._postparsing_hooks = [] self._precmd_hooks = [] self._postcmd_hooks = [] self._cmdfinalization_hooks = []
Initialize the plugin system
def delete_ip_address(context, id): """Delete an ip address. : param context: neutron api request context : param id: UUID representing the ip address to delete. """ LOG.info("delete_ip_address %s for tenant %s" % (id, context.tenant_id)) with context.session.begin(): ip_address = db_ap...
Delete an ip address. : param context: neutron api request context : param id: UUID representing the ip address to delete.
def renders(self, template_content, context=None, at_paths=None, at_encoding=anytemplate.compat.ENCODING, **kwargs): """ :param template_content: Template content :param context: A dict or dict-like object to instantiate given template file or None :param at_p...
:param template_content: Template content :param context: A dict or dict-like object to instantiate given template file or None :param at_paths: Template search paths :param at_encoding: Template encoding :param kwargs: Keyword arguments passed to the template engine to ...
def p_version_def(t): """version_def : VERSION ID LBRACE procedure_def procedure_def_list RBRACE EQUALS constant SEMI""" global name_dict id = t[2] value = t[8] lineno = t.lineno(1) if id_unique(id, 'version', lineno): name_dict[id] = const_info(id, value, lineno)
version_def : VERSION ID LBRACE procedure_def procedure_def_list RBRACE EQUALS constant SEMI