code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def check_periodrec_alias(actualperiod, recoveredperiod, tolerance=1.0e-3): '''This determines what kind of aliasing (if any) exists between `recoveredperiod` and `actualperiod`. Parameters ---------- actualperiod : float The actual perio...
This determines what kind of aliasing (if any) exists between `recoveredperiod` and `actualperiod`. Parameters ---------- actualperiod : float The actual period of the object. recoveredperiod : float The recovered period of the object. tolerance : float The absolute d...
def set_dvs_network_resource_management_enabled(dvs_ref, enabled): ''' Sets whether NIOC is enabled on a DVS. dvs_ref The DVS reference. enabled Flag specifying whether NIOC is enabled. ''' dvs_name = get_managed_object_name(dvs_ref) log.trace('Setting network resource mana...
Sets whether NIOC is enabled on a DVS. dvs_ref The DVS reference. enabled Flag specifying whether NIOC is enabled.
def receive(self, max_batch_size=None, timeout=None): """ Receive events from the EventHub. :param max_batch_size: Receive a batch of events. Batch size will be up to the maximum specified, but will return as soon as service returns no new events. If combined with a timeout an...
Receive events from the EventHub. :param max_batch_size: Receive a batch of events. Batch size will be up to the maximum specified, but will return as soon as service returns no new events. If combined with a timeout and no events are retrieve before the time, the result will be empt...
def _integrateLinearOrbit(vxvv,pot,t,method,dt): """ NAME: integrateLinearOrbit PURPOSE: integrate a one-dimensional orbit INPUT: vxvv - initial condition [x,vx] pot - linearPotential or list of linearPotentials t - list of times at which to output (0 has to be in this...
NAME: integrateLinearOrbit PURPOSE: integrate a one-dimensional orbit INPUT: vxvv - initial condition [x,vx] pot - linearPotential or list of linearPotentials t - list of times at which to output (0 has to be in this!) method - 'odeint' or 'leapfrog' OUTPUT: ...
def weighted(weights, sample_size, with_replacement=False): """ Return a set of random integers 0 <= N <= len(weights) - 1, where the weights determine the probability of each possible integer in the set. """ assert sample_size <= len(weights), "The sample size must be smaller \ ...
Return a set of random integers 0 <= N <= len(weights) - 1, where the weights determine the probability of each possible integer in the set.
def safe_date(self, x): """Transform x[self.col_name] into a date string. Args: x(dict like / pandas.Series): Row containing data to cast safely. Returns: str """ t = x[self.col_name] if np.isnan(t): return t elif np.isposin...
Transform x[self.col_name] into a date string. Args: x(dict like / pandas.Series): Row containing data to cast safely. Returns: str
def printInput(self, x): """ TODO: document :param x: :return: """ print "Input" for c in xrange(self.numberOfCols): print int(x[c]), print
TODO: document :param x: :return:
def from_jsonf(cls, fpath: str, encoding: str='utf8', force_snake_case=True, force_cast: bool=False, restrict: bool=False) -> T: """From json file path to instance :param fpath: Json file path :param encoding: Json file encoding :param force_snake_case: Keys are trans...
From json file path to instance :param fpath: Json file path :param encoding: Json file encoding :param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True :param force_cast: Cast forcibly if True :param restrict: Prohibit extra parameters if ...
def publishTemplate(self, templateMessage): """ 发送单聊模板消息方法(一个用户向多个用户发送不同消息内容,单条消息最大 128k。每分钟最多发送 6000 条信息,每次发送用户上限为 1000 人。) 方法 @param templateMessage:单聊模版消息。 @return code:返回码,200 为正常。 @return errorMessage:错误信息。 """ desc = { "name": "CodeSuccessReslu...
发送单聊模板消息方法(一个用户向多个用户发送不同消息内容,单条消息最大 128k。每分钟最多发送 6000 条信息,每次发送用户上限为 1000 人。) 方法 @param templateMessage:单聊模版消息。 @return code:返回码,200 为正常。 @return errorMessage:错误信息。
def set_object_info(self): """ set my pandas type & version """ self.attrs.pandas_type = str(self.pandas_kind) self.attrs.pandas_version = str(_version) self.set_version()
set my pandas type & version
def openWith(self, accel = True, gyro = True, temp = True, cycle = False, cycleFreq = 0x00): """! Trun on device with configurable sensors into wake up mode @param accel: True - Enable accelerometer @param gyro: True - Enable gyroscope @param temp: True - Enable Thermome...
! Trun on device with configurable sensors into wake up mode @param accel: True - Enable accelerometer @param gyro: True - Enable gyroscope @param temp: True - Enable Thermometer @param cycle: True - Enable cycle wake-up mode @param cycleFreq: Cycle wake-up frequ...
def utf8(value): """Converts a string argument to a byte string. If the argument is already a byte string or None, it is returned unchanged. Otherwise it must be a unicode string and is encoded as utf8. """ if isinstance(value, _UTF8_TYPES): return value if not isinstance(value, unicode...
Converts a string argument to a byte string. If the argument is already a byte string or None, it is returned unchanged. Otherwise it must be a unicode string and is encoded as utf8.
def logWrite(self, string): """Only write text to the log file, do not print""" logFile = open(self.logFile, 'at') logFile.write(string + '\n') logFile.close()
Only write text to the log file, do not print
def detect_vec(df, max_anoms=0.10, direction='pos', alpha=0.05, period=None, only_last=False, threshold=None, e_value=False, longterm_period=None, plot=False, y_log=False, xlabel='', ylabel='count', title=None, verbose=False): """ Anomaly Detection Usi...
Anomaly Detection Using Seasonal Hybrid ESD Test A technique for detecting anomalies in seasonal univariate time series where the input is a series of observations. Args: x: Time series as a column data frame, list, or vector, where the column consists of the observations. max_anoms: Maximum ...
def array_remove(col, element): """ Collection function: Remove all elements that equal to element from the given array. :param col: name of column containing array :param element: element to be removed from the array >>> df = spark.createDataFrame([([1, 2, 3, 1, 1],), ([],)], ['data']) >>> df...
Collection function: Remove all elements that equal to element from the given array. :param col: name of column containing array :param element: element to be removed from the array >>> df = spark.createDataFrame([([1, 2, 3, 1, 1],), ([],)], ['data']) >>> df.select(array_remove(df.data, 1)).collect() ...
def logo_path(instance, filename): """ Delete the file if it already exist and returns the enterprise customer logo image path. Arguments: instance (:class:`.EnterpriseCustomerBrandingConfiguration`): EnterpriseCustomerBrandingConfiguration object filename (str): file to upload Returns...
Delete the file if it already exist and returns the enterprise customer logo image path. Arguments: instance (:class:`.EnterpriseCustomerBrandingConfiguration`): EnterpriseCustomerBrandingConfiguration object filename (str): file to upload Returns: path: path of image file e.g. enterpr...
def script_repr(self,imports=[],prefix=" "): """ Same as Parameterized.script_repr, except that X.classname(Y is replaced with X.classname.instance(Y """ return self.pprint(imports,prefix,unknown_value='',qualify=True, separator="\n")
Same as Parameterized.script_repr, except that X.classname(Y is replaced with X.classname.instance(Y
def remove_date(self, file_path='', date=str(datetime.date.today())): """ Removes all rows of the associated date from the given csv file. Defaults to today. """ languages_exists = os.path.isfile(file_path) if languages_exists: with open(file_path, 'rb') as in...
Removes all rows of the associated date from the given csv file. Defaults to today.
def cell_ends_with_code(lines): """Is the last line of the cell a line with code?""" if not lines: return False if not lines[-1].strip(): return False if lines[-1].startswith('#'): return False return True
Is the last line of the cell a line with code?
def delete(self): # type () -> () """Delete this property. :return: None :raises APIError: if delete was not successful """ r = self._client._request('DELETE', self._client._build_url('property', property_id=self.id)) if r.status_code != requests.codes.no_conten...
Delete this property. :return: None :raises APIError: if delete was not successful
def collect_and_zip_files(dir_list, output_dir, zip_file_name, file_extension_list=None, file_name_list=None): """ Function to collect files and make a zip file :param dir_list: A list of directories :param output_dir: The output directory :param zip_file_name: Zip file name :param file_extensio...
Function to collect files and make a zip file :param dir_list: A list of directories :param output_dir: The output directory :param zip_file_name: Zip file name :param file_extension_list: A list of extensions of files to find :param file_name_list: A list of file names to find :return: ...
def get_all_regions_with_tiles(self): """ Generator which yields a set of (rx, ry) tuples which describe all regions for which the world has tile data """ for key in self.get_all_keys(): (layer, rx, ry) = struct.unpack('>BHH', key) if layer == 1: ...
Generator which yields a set of (rx, ry) tuples which describe all regions for which the world has tile data
def gen_mu(K, delta, c): """The Robust Soliton Distribution on the degree of transmitted blocks """ S = c * log(K/delta) * sqrt(K) tau = gen_tau(S, K, delta) rho = gen_rho(K) normalizer = sum(rho) + sum(tau) return [(rho[d] + tau[d])/normalizer for d in range(K)]
The Robust Soliton Distribution on the degree of transmitted blocks
def __calculate_bu_dfs(dfs_data): """Calculates the b(u) lookup table.""" u = dfs_data['ordering'][0] b = {} b[u] = D(u, dfs_data) __calculate_bu_dfs_recursively(u, b, dfs_data) return b
Calculates the b(u) lookup table.
def rootChild_resetPassword(self, req, webViewer): """ Return a page which will allow the user to re-set their password. """ from xmantissa.signup import PasswordResetResource return PasswordResetResource(self.store)
Return a page which will allow the user to re-set their password.
def set_target_ref(self, value): """ Setter for 'target_ref' field. :param value - a new value of 'target_ref' field. Required field. Must be a String type. """ if value is None or not isinstance(value, str): raise TypeError("TargetRef is required and must be set to a...
Setter for 'target_ref' field. :param value - a new value of 'target_ref' field. Required field. Must be a String type.
def _build_pcollection(self, pipeline, filepaths, language): """Build PCollection of examples in the raw (text) form.""" beam = tfds.core.lazy_imports.apache_beam def _extract_content(filepath): """Extracts article content from a single WikiMedia XML file.""" logging.info("generating examples ...
Build PCollection of examples in the raw (text) form.
def slamdunkGeneralStatsTable(self): """ Take the parsed summary stats from Slamdunk and add it to the basic stats table at the top of the report """ headers = OrderedDict() headers['counted'] = { 'title': '{} Counted'.format(config.read_count_prefix), 'descript...
Take the parsed summary stats from Slamdunk and add it to the basic stats table at the top of the report
def apply_update(self, value, index): """ Record an opendnp3 data value (Analog, Binary, etc.) in the outstation's database. The data value gets sent to the Master as a side-effect. :param value: An instance of Analog, Binary, or another opendnp3 data value. :param inde...
Record an opendnp3 data value (Analog, Binary, etc.) in the outstation's database. The data value gets sent to the Master as a side-effect. :param value: An instance of Analog, Binary, or another opendnp3 data value. :param index: (integer) Index of the data definition in the opendnp3 data...
def syncdb(self, site=None, all=0, database=None, ignore_errors=1): # pylint: disable=redefined-builtin """ Runs the standard Django syncdb command for one or more sites. """ r = self.local_renderer ignore_errors = int(ignore_errors) post_south = self.version_tuple >= (...
Runs the standard Django syncdb command for one or more sites.
def datasets(self): """List of datasets in this mart.""" if self._datasets is None: self._datasets = self._fetch_datasets() return self._datasets
List of datasets in this mart.
def softmask(X, X_ref, power=1, split_zeros=False): '''Robustly compute a softmask operation. `M = X**power / (X**power + X_ref**power)` Parameters ---------- X : np.ndarray The (non-negative) input array corresponding to the positive mask elements X_ref : np.ndarray The ...
Robustly compute a softmask operation. `M = X**power / (X**power + X_ref**power)` Parameters ---------- X : np.ndarray The (non-negative) input array corresponding to the positive mask elements X_ref : np.ndarray The (non-negative) array of reference or background elements. ...
def init(self): "Initialize the message-digest and set all fields to zero." self.length = 0 self.input = [] # Initial 160 bit message digest (5 times 32 bit). self.H0 = 0x67452301 self.H1 = 0xEFCDAB89 self.H2 = 0x98BADCFE self.H3 = 0x10325476 sel...
Initialize the message-digest and set all fields to zero.
def build_type_dict(converters): """ Builds type dictionary for user-defined type converters, used by :mod:`parse` module. This requires that each type converter has a "name" attribute. :param converters: List of type converters (parse_types) :return: Type converter dictionary """ more_...
Builds type dictionary for user-defined type converters, used by :mod:`parse` module. This requires that each type converter has a "name" attribute. :param converters: List of type converters (parse_types) :return: Type converter dictionary
def density_water(temp): """Return the density of water at a given temperature. If given units, the function will automatically convert to Kelvin. If not given units, the function will assume Kelvin. """ ut.check_range([temp, ">0", "Temperature in Kelvin"]) rhointerpolated = interpolate.CubicSp...
Return the density of water at a given temperature. If given units, the function will automatically convert to Kelvin. If not given units, the function will assume Kelvin.
def handle(self, *args, **options): """Run do_index_command on each specified index and log the output.""" for index in options.pop("indexes"): data = {} try: data = self.do_index_command(index, **options) except TransportError as ex: l...
Run do_index_command on each specified index and log the output.
def ppiece(self, content): ''' Process a piece that we've received from a peer, writing it out to one or more files ''' piece_index, byte_begin = struct.unpack('!ii', content[0:8]) # TODO -- figure out a better way to catch this error. # How is piece_index gettin...
Process a piece that we've received from a peer, writing it out to one or more files
def xirr(values, dates, guess=0): """ Function to calculate the internal rate of return (IRR) using payments and non-periodic dates. It resembles the excel function XIRR(). Excel reference: https://support.office.com/en-ie/article/xirr-function-de1242ec-6477-445b-b11b-a303ad9adc9d :param values: t...
Function to calculate the internal rate of return (IRR) using payments and non-periodic dates. It resembles the excel function XIRR(). Excel reference: https://support.office.com/en-ie/article/xirr-function-de1242ec-6477-445b-b11b-a303ad9adc9d :param values: the payments of which at least one has to be ne...
def print_dictionary(self, d, h, n, nl=False): """Print complex using the specified indent (n) and newline (nl).""" if d in h: return "{}..." h.append(d) s = [] if nl: s.append("\n") s.append(self.indent(n)) s.append("{") for it...
Print complex using the specified indent (n) and newline (nl).
def interpolate_colors(array: numpy.ndarray, x: int) -> numpy.ndarray: """ Creates a color map for values in array :param array: color map to interpolate :param x: number of colors :return: interpolated color map """ out_array = [] for i in range(x): if i % (x / (len(array) - 1))...
Creates a color map for values in array :param array: color map to interpolate :param x: number of colors :return: interpolated color map
def get_key(key_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if a key exists. Returns fingerprint and name if it does and False if it doesn't CLI Example: .. code-block:: bash salt myminion boto_ec2.get_key mykey ''' conn = _get_conn(region=region, key=k...
Check to see if a key exists. Returns fingerprint and name if it does and False if it doesn't CLI Example: .. code-block:: bash salt myminion boto_ec2.get_key mykey
def country(anon, obj, field, val): """ Returns a randomly selected country. """ return anon.faker.country(field=field)
Returns a randomly selected country.
def set_top_bar_color(self, index): """Set the color of the upper frame to the background color of the reftrack status :param index: the index :type index: :class:`QtGui.QModelIndex` :returns: None :rtype: None :raises: None """ dr = QtCore.Qt.ForegroundR...
Set the color of the upper frame to the background color of the reftrack status :param index: the index :type index: :class:`QtGui.QModelIndex` :returns: None :rtype: None :raises: None
def create_ssh_pub_key(self, name, key): """ Installs the public SSH key under the name :attr:`name`. Once installed, the key can be referenced when creating new server instances. """ self.nova.keypairs.create(name, key)
Installs the public SSH key under the name :attr:`name`. Once installed, the key can be referenced when creating new server instances.
async def end_takeout(self, success): """ Finishes a takeout, with specified result sent back to Telegram. Returns: ``True`` if the operation was successful, ``False`` otherwise. """ try: async with _TakeoutClient(True, self, None) as takeout: ...
Finishes a takeout, with specified result sent back to Telegram. Returns: ``True`` if the operation was successful, ``False`` otherwise.
def handle_job_exception(self, exception, variables=None): """ Makes and returns a last-ditch error response. :param exception: The exception that happened :type exception: Exception :param variables: A dictionary of context-relevant variables to include in the error response ...
Makes and returns a last-ditch error response. :param exception: The exception that happened :type exception: Exception :param variables: A dictionary of context-relevant variables to include in the error response :type variables: dict :return: A `JobResponse` object :r...
def update_image(self, ami_id, instance_id): """Replaces an existing AMI ID with an image created from the provided instance ID :param ami_id: (str) ID of the AMI to delete and replace :param instance_id: (str) ID of the instance ID to create an image from :return: None...
Replaces an existing AMI ID with an image created from the provided instance ID :param ami_id: (str) ID of the AMI to delete and replace :param instance_id: (str) ID of the instance ID to create an image from :return: None
def pdchAssignmentCommand(ChannelDescription_presence=0, CellChannelDescription_presence=0, MobileAllocation_presence=0, StartingTime_presence=0, FrequencyList_presence=0, ChannelDescription_presence1=0, ...
PDCH ASSIGNMENT COMMAND Section 9.1.13a
def _handle_pyout(self, msg): """ Handle display hook output. """ self.log.debug("pyout: %s", msg.get('content', '')) if not self._hidden and self._is_from_this_session(msg): text = msg['content']['data'] self._append_plain_text(text + '\n', before_prompt=True)
Handle display hook output.
def format_table(table, align='<', format='{:.3g}', colwidth=None, maxwidth=None, spacing=2, truncate=0, suffix="..." ): """ Formats a table represented as an iterable of iterab...
Formats a table represented as an iterable of iterable into a nice big string suitable for printing. Parameters: ----------- align : string or list of strings Alignment of cell contents. Each character in a string specifies the alignment of one column. * ``<`` - Le...
def gmm_cause(points, k=4, p1=2, p2=2): """Init a root cause with a Gaussian Mixture Model w/ a spherical covariance type.""" g = GMM(k, covariance_type="spherical") g.fit(np.random.randn(300, 1)) g.means_ = p1 * np.random.randn(k, 1) g.covars_ = np.power(abs(p2 * np.random.randn(k, 1) + 1), 2) ...
Init a root cause with a Gaussian Mixture Model w/ a spherical covariance type.
def _zoom_rows(self, zoom): """Zooms grid rows""" self.grid.SetDefaultRowSize(self.grid.std_row_size * zoom, resizeExistingRows=True) self.grid.SetRowLabelSize(self.grid.row_label_size * zoom) for row, tab in self.code_array.row_heights: ...
Zooms grid rows
def get_cached_item(cache_key, alternative_cache_key, *func_args, **func_kwargs): """Not a decorator, but a helper function to retrieve the cached item for a key created via get_cache_key. Args: - cache_key: if there was a specific cache key used to cache the function, it should be provided ...
Not a decorator, but a helper function to retrieve the cached item for a key created via get_cache_key. Args: - cache_key: if there was a specific cache key used to cache the function, it should be provided here. If not this should be None - func: the function which was cache - *...
def field(*, default=MISSING, default_factory=MISSING, init=True, repr=True, hash=None, compare=True, metadata=None): """Return an object to identify dataclass fields. default is the default value of the field. default_factory is a 0-argument function called to initialize a field's value. If in...
Return an object to identify dataclass fields. default is the default value of the field. default_factory is a 0-argument function called to initialize a field's value. If init is True, the field will be a parameter to the class's __init__() function. If repr is True, the field will be included in t...
def save_yaml_file(file, val): """ Save data to yaml file :param file: Writable object or path to file :type file: FileIO | str | unicode :param val: Value or struct to save :type val: None | int | float | str | unicode | list | dict """ opened = False if not hasattr(file, "write")...
Save data to yaml file :param file: Writable object or path to file :type file: FileIO | str | unicode :param val: Value or struct to save :type val: None | int | float | str | unicode | list | dict
def submatrix(matrix,i1,i2,j1,j2): """ returns the submatrix defined by the index bounds i1-i2 and j1-j2 Endpoints included! """ new = [] for i in range(i1,i2+1): new.append(matrix[i][j1:j2+1]) return _n.array(new)
returns the submatrix defined by the index bounds i1-i2 and j1-j2 Endpoints included!
def _unassembled_reads2_out_file_name(self): """Checks if file name is set for reads2 output. Returns absolute path.""" if self.Parameters['-2'].isOn(): unassembled_reads2 = self._absolute( str(self.Parameters['-2'].Value)) else: raise ValueErro...
Checks if file name is set for reads2 output. Returns absolute path.
def add_legend(self): """Add or update Cuts plot legend.""" cuts = [tag for tag in self.tags if tag is not self._new_cut] self.cuts_plot.ax.legend(cuts, loc='best', shadow=True, fancybox=True, prop={'size': 8}, labelspacing=0.2)
Add or update Cuts plot legend.
def build_url(self, data): """This method occurs after dumping the data into the class. Args: data (dict): dictionary of all the query values Returns: data (dict): ordered dict of all the values """ query_part_one = [] query_part_two = [] ...
This method occurs after dumping the data into the class. Args: data (dict): dictionary of all the query values Returns: data (dict): ordered dict of all the values
def get_content_size(self, path): "Return size of files/dirs contents excluding parent node." node = self._get_node(path) return self._get_content_size(node) - node.size
Return size of files/dirs contents excluding parent node.
def list_sub_commmands(self, cmd_name, cmd): """Return all commands for a group""" ret = {} if isinstance(cmd, click.core.Group): for sub_cmd_name in cmd.commands: sub_cmd = cmd.commands[sub_cmd_name] sub = self.list_sub_commmands(sub_cmd_name, sub_cmd...
Return all commands for a group
def detect_emg_activations(emg_signal, sample_rate, smooth_level=20, threshold_level=10, time_units=False, volts=False, resolution=None, device="biosignalsplux", plot_result=False): """ ----- Brief ----- Python implementation of Burst detection a...
----- Brief ----- Python implementation of Burst detection algorithm using Teager Kaiser Energy Operator. ----------- Description ----------- Activation events in EMG readings correspond to an increase of muscular activity, namely, from inaction to action. These events are characterised...
def _get_private_room(self, invitees: List[User]): """ Create an anonymous, private room and invite peers """ return self._client.create_room( None, invitees=[user.user_id for user in invitees], is_public=False, )
Create an anonymous, private room and invite peers
def import_object(name): """ Import module and return object from it. *name* is :class:`str` in format ``module.path.ObjectClass``. :: >>> import_command('module.path.ObjectClass') <class 'module.path.ObjectClass'> """ parts = name.split('.') if len(parts) < 2: raise...
Import module and return object from it. *name* is :class:`str` in format ``module.path.ObjectClass``. :: >>> import_command('module.path.ObjectClass') <class 'module.path.ObjectClass'>
def get_p2o_params_from_url(cls, url): """ Get the p2o params given a URL for the data source """ # if the url doesn't contain a filter separator, return it if PRJ_JSON_FILTER_SEPARATOR not in url: return {"url": url} # otherwise, add the url to the params params = ...
Get the p2o params given a URL for the data source
def on_ok(self, sender): """ This callback is called when one task reaches status S_OK. If sender == self.ion_task, we update the initial structure used by self.ioncell_task and we unlock it so that the job can be submitted. """ logger.debug("in on_ok with sender %s" % se...
This callback is called when one task reaches status S_OK. If sender == self.ion_task, we update the initial structure used by self.ioncell_task and we unlock it so that the job can be submitted.
def process_tag(self, tag): """Processes tag and detects which function to use""" try: if not self._is_function(tag): self._tag_type_processor[tag.data_type](tag) except KeyError as ex: raise Exception('Tag type {0} not recognized for tag {1}' ...
Processes tag and detects which function to use
def _datetime_to_stata_elapsed_vec(dates, fmt): """ Convert from datetime to SIF. http://www.stata.com/help.cgi?datetime Parameters ---------- dates : Series Series or array containing datetime.datetime or datetime64[ns] to convert to the Stata Internal Format given by fmt fmt :...
Convert from datetime to SIF. http://www.stata.com/help.cgi?datetime Parameters ---------- dates : Series Series or array containing datetime.datetime or datetime64[ns] to convert to the Stata Internal Format given by fmt fmt : str The format to convert to. Can be, tc, td, tw, t...
def run(self, *args): """Merge unique identities using a matching algorithm.""" params = self.parser.parse_args(args) code = self.unify(params.matching, params.sources, params.fast_matching, params.no_strict, params.interactive, params.recove...
Merge unique identities using a matching algorithm.
def add_affiliation(self, value, curated_relation=None, record=None): """Add an affiliation. Args: value (string): affiliation value curated_relation (bool): is relation curated record (dict): affiliation JSON reference """ if value: affil...
Add an affiliation. Args: value (string): affiliation value curated_relation (bool): is relation curated record (dict): affiliation JSON reference
def step(self, state, clamping): """ Performs a simulation step from the given state and with respect to the given clamping Parameters ---------- state : dict The key-value mapping describing the current state of the logical network clamping : caspo.core.cla...
Performs a simulation step from the given state and with respect to the given clamping Parameters ---------- state : dict The key-value mapping describing the current state of the logical network clamping : caspo.core.clamping.Clamping A clamping over variables ...
def export_default_instruments(target_folder, source_folder = None, raise_errors = False, verbose=True): """ tries to instantiate all the instruments that are imported in /instruments/__init__.py and saves instruments that could be instantiate into a .b2 file in the folder path Args: target_fold...
tries to instantiate all the instruments that are imported in /instruments/__init__.py and saves instruments that could be instantiate into a .b2 file in the folder path Args: target_folder: target path for .b26 files
def overview(name, server): """ Overview of the server as seen through the properties of the server class. """ print('%s OVERVIEW' % name) print(" Interop namespace: %s" % server.interop_ns) print(" Brand: %s" % server.brand) print(" Version: %s" % server.version) print(" Namespa...
Overview of the server as seen through the properties of the server class.
def edge_label(self, edge): """ Get the label of an edge. @type edge: edge @param edge: One edge. @rtype: string @return: Edge label """ return self.get_edge_properties( edge ).setdefault( self.LABEL_ATTRIBUTE_NAME, self.DEFAULT_LABEL )
Get the label of an edge. @type edge: edge @param edge: One edge. @rtype: string @return: Edge label
def secret_loader(self, callback): """ Decorate a method that receives a key id and returns a secret key """ if not callback or not callable(callback): raise Exception("Please pass in a callable that loads secret keys") self.secret_loader_callback = callback r...
Decorate a method that receives a key id and returns a secret key
def close(self): """ Close and upload local log file to remote storage Wasb. """ # When application exit, system shuts down all handlers by # calling close method. Here we check if logger is already # closed to prevent uploading the log to remote storage multiple ...
Close and upload local log file to remote storage Wasb.
def discard_logcat_logs(self): """Discard previous logcat logs""" if self.driver_wrapper.is_android_test(): try: self.driver_wrapper.driver.get_log('logcat') except Exception: pass
Discard previous logcat logs
def weighted_n(self): """float count of returned rows adjusted for weighting.""" if not self.is_weighted: return float(self.unweighted_n) return float(sum(self._cube_dict["result"]["measures"]["count"]["data"]))
float count of returned rows adjusted for weighting.
def is_stop_here(self, frame, event, arg): """ Does the magic to determine if we stop here and run a command processor or not. If so, return True and set self.stop_reason; if not, return False. Determining factors can be whether a breakpoint was encountered, whether we are stepp...
Does the magic to determine if we stop here and run a command processor or not. If so, return True and set self.stop_reason; if not, return False. Determining factors can be whether a breakpoint was encountered, whether we are stepping, next'ing, finish'ing, and, if so, whether ...
def add_user_to_allow(self, name, user): """Add a user to the given acl allow block.""" # Clear user from both allow and deny before adding if not self.remove_user_from_acl(name, user): return False if name not in self._acl: return False self._acl[name]...
Add a user to the given acl allow block.
def stream(self, amt=2**16, decode_content=None): """ A generator wrapper for the read() method. A call will block until ``amt`` bytes have been read from the connection or until the connection is closed. :param amt: How much of the content to read. The generator wil...
A generator wrapper for the read() method. A call will block until ``amt`` bytes have been read from the connection or until the connection is closed. :param amt: How much of the content to read. The generator will return up to much data per iteration, but may return les...
def setting(self, name_hyphen): """ Retrieves the setting value whose name is indicated by name_hyphen. Values starting with $ are assumed to reference environment variables, and the value stored in environment variables is retrieved. It's an error if thes corresponding environm...
Retrieves the setting value whose name is indicated by name_hyphen. Values starting with $ are assumed to reference environment variables, and the value stored in environment variables is retrieved. It's an error if thes corresponding environment variable it not set.
def delete_ip4(self, id_ip): """ Delete an IP4 :param id_ip: Ipv4 identifier. Integer value and greater than zero. :return: None :raise IpNotFoundError: IP is not registered. :raise DataBaseError: Networkapi failed to access the database. """ if not i...
Delete an IP4 :param id_ip: Ipv4 identifier. Integer value and greater than zero. :return: None :raise IpNotFoundError: IP is not registered. :raise DataBaseError: Networkapi failed to access the database.
def rel_curve_to(self, dx1, dy1, dx2, dy2, dx3, dy3): """ Relative-coordinate version of :meth:`curve_to`. All offsets are relative to the current point. Adds a cubic Bézier spline to the path from the current point to a point offset from the current point by ``(dx3, dy3)``, usin...
Relative-coordinate version of :meth:`curve_to`. All offsets are relative to the current point. Adds a cubic Bézier spline to the path from the current point to a point offset from the current point by ``(dx3, dy3)``, using points offset by ``(dx1, dy1)`` and ``(dx2, dy2)`` as th...
def interpolate(self, year): """Interpolate missing values in timeseries (linear interpolation) Parameters ---------- year: int year to be interpolated """ df = self.pivot_table(index=IAMC_IDX, columns=['year'], values='value', ...
Interpolate missing values in timeseries (linear interpolation) Parameters ---------- year: int year to be interpolated
def serialize(self): """ Get the collection of items as a serialized object (ready to be json encoded). :rtype: dict or list """ def _serialize(value): if hasattr(value, 'serialize'): return value.serialize() elif hasattr(value, 'to_dict'...
Get the collection of items as a serialized object (ready to be json encoded). :rtype: dict or list
def add_note(self, body): """ Create a Note to current object :param body: the body of the note :type body: str :return: newly created Note :rtype: Tag """ from highton.models.note import Note created_id = self._post_request( endpoint=...
Create a Note to current object :param body: the body of the note :type body: str :return: newly created Note :rtype: Tag
def process(self): """Run the analysis across all files found in the given paths. Each file is loaded once and all plugins are run against it before loading the next file. """ for filename in self.hairball_files(self.paths, self.extensions): if not self.options.quie...
Run the analysis across all files found in the given paths. Each file is loaded once and all plugins are run against it before loading the next file.
def define_trajectory(self, trajectory_id, offset, n_pieces): """ Define a trajectory that has previously been uploaded to memory. :param trajectory_id: The id of the trajectory :param offset: offset in uploaded memory :param n_pieces: Nr of pieces in the trajectory :ret...
Define a trajectory that has previously been uploaded to memory. :param trajectory_id: The id of the trajectory :param offset: offset in uploaded memory :param n_pieces: Nr of pieces in the trajectory :return:
def format(self, pattern='{head}{padding}{tail} [{ranges}]'): '''Return string representation as specified by *pattern*. Pattern can be any format accepted by Python's standard format function and will receive the following keyword arguments as context: * *head* - Common leading pa...
Return string representation as specified by *pattern*. Pattern can be any format accepted by Python's standard format function and will receive the following keyword arguments as context: * *head* - Common leading part of the collection. * *tail* - Common trailing part of the ...
def basic_auth_handler(url, method, timeout, headers, data, username=None, password=None): """Handler that implements HTTP/HTTPS connections with Basic Auth. Sets auth headers using supplied 'username' and 'password', if set. Used by the push_to_gateway functions. Can be re-used by other handlers.""" ...
Handler that implements HTTP/HTTPS connections with Basic Auth. Sets auth headers using supplied 'username' and 'password', if set. Used by the push_to_gateway functions. Can be re-used by other handlers.
def frequency_cutoff_from_name(name, m1, m2, s1z, s2z): """ Returns the result of evaluating the frequency cutoff function specified by 'name' on a template with given parameters. Parameters ---------- name : string Name of the cutoff function m1 : float or numpy.array First...
Returns the result of evaluating the frequency cutoff function specified by 'name' on a template with given parameters. Parameters ---------- name : string Name of the cutoff function m1 : float or numpy.array First component mass in solar masses m2 : float or numpy.array ...
def commitreturn(self,qstring,vals=()): "commit and return result. This is intended for sql UPDATE ... RETURNING" with self.withcur() as cur: cur.execute(qstring,vals) return cur.fetchone()
commit and return result. This is intended for sql UPDATE ... RETURNING
def reserve_ipblock(self, ipblock): """ Reserves an IP block within your account. """ properties = { "name": ipblock.name } if ipblock.location: properties['location'] = ipblock.location if ipblock.size: properties['size'] = ...
Reserves an IP block within your account.
def from_json(cls, data): """Return object based on JSON / dict input Args: data (dict): Dictionary containing a serialized Role object Returns: :obj:`Role`: Role object representing the data """ role = cls() role.role_id = data['roleId'] ...
Return object based on JSON / dict input Args: data (dict): Dictionary containing a serialized Role object Returns: :obj:`Role`: Role object representing the data
def delete_beacon(self, name): ''' Delete a beacon item ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot delete beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: ...
Delete a beacon item
def str_rate(self): """Returns the rate with formatting. If done, returns the overall rate instead.""" # Handle special cases. if not self._eta.started or self._eta.stalled or not self.rate: return '--.-KiB/s' unit_rate, unit = UnitByte(self._eta.rate_overall if self.done el...
Returns the rate with formatting. If done, returns the overall rate instead.
def search_videos_by_tag(self, tag, category=None, period='today', orderby='relevance', page=1, count=20): """doc: http://open.youku.com/docs/doc?id=80 """ url = 'https://openapi.youku.com/v2/searches/video/by...
doc: http://open.youku.com/docs/doc?id=80
def alias_get(indices=None, aliases=None, hosts=None, profile=None): ''' Check for the existence of an alias and if it exists, return it indices Single or multiple indices separated by comma, use _all to perform the operation on all indices. aliases Alias names separated by comma C...
Check for the existence of an alias and if it exists, return it indices Single or multiple indices separated by comma, use _all to perform the operation on all indices. aliases Alias names separated by comma CLI example:: salt myminion elasticsearch.alias_get testindex
def mdf_path(self): """Absolute path of the MDF file. Empty string if file is not present.""" # Lazy property to avoid multiple calls to has_abiext. try: return self._mdf_path except AttributeError: path = self.outdir.has_abiext("MDF.nc") if path: self...
Absolute path of the MDF file. Empty string if file is not present.