code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def transmit(self, payload, **kwargs): """ Send a completion status call to SAP SuccessFactors using the client. Args: payload: The learner completion data payload to send to SAP SuccessFactors """ kwargs['app_label'] = 'sap_success_factors' kwargs['model_nam...
Send a completion status call to SAP SuccessFactors using the client. Args: payload: The learner completion data payload to send to SAP SuccessFactors
def _actor_from_game_image(self, name, game_image): """Return an actor object matching the one in the game image. Note: Health and mana are based on measured percentage of a fixed maximum rather than the actual maximum in the game. Arguments: name: must be 'player' or '...
Return an actor object matching the one in the game image. Note: Health and mana are based on measured percentage of a fixed maximum rather than the actual maximum in the game. Arguments: name: must be 'player' or 'opponent' game_image: opencv image of the main game are...
def get_iterator(self, query, **options): """Returns an event iterator for the given query (and optional 'sync' token)""" return EventsPageIterator(self.client, '/events', query, options).items()
Returns an event iterator for the given query (and optional 'sync' token)
def fetch(self): """ Fetch a ExecutionContextInstance :returns: Fetched ExecutionContextInstance :rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextInstance """ params = values.of({}) payload = self._version.fetch( 'GET', ...
Fetch a ExecutionContextInstance :returns: Fetched ExecutionContextInstance :rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextInstance
def close_cursor(self, cursor_id, address=None): """DEPRECATED - Send a kill cursors message soon with the given id. Raises :class:`TypeError` if `cursor_id` is not an instance of ``(int, long)``. What closing the cursor actually means depends on this client's cursor manager. T...
DEPRECATED - Send a kill cursors message soon with the given id. Raises :class:`TypeError` if `cursor_id` is not an instance of ``(int, long)``. What closing the cursor actually means depends on this client's cursor manager. This method may be called from a :class:`~pymongo.cursor.Curs...
def output(self): """ Returns a ElasticsearchTarget representing the inserted dataset. Normally you don't override this. """ return ElasticsearchTarget( host=self.host, port=self.port, http_auth=self.http_auth, index=self.index, ...
Returns a ElasticsearchTarget representing the inserted dataset. Normally you don't override this.
def save(self, filename): """ Save host keys into a file, in the format used by openssh. The order of keys in the file will be preserved when possible (if these keys were loaded from a file originally). The single exception is that combined lines will be split into individual k...
Save host keys into a file, in the format used by openssh. The order of keys in the file will be preserved when possible (if these keys were loaded from a file originally). The single exception is that combined lines will be split into individual key lines, which is arguably a bug. @p...
def build_response(description, resource=None): """ Build a response definition. """ response = swagger.Response( description=description, ) if resource is not None: response.schema = swagger.JsonReference({ "$ref": "#/definitions/{}".format(type_name(name_for(resour...
Build a response definition.
def get_pid_from_file(self): """Get the pid from the pid file. If the pid file doesn't exist a :exc:`PIDFileError` is raised. """ pid_file = os.path.join(self.profile_dir.pid_dir, self.name + u'.pid') if os.path.isfile(pid_file): with open(pid_file, 'r') as f: ...
Get the pid from the pid file. If the pid file doesn't exist a :exc:`PIDFileError` is raised.
def add_signal_receiver(self, callback_fn, signal, user_arg): """ Add a signal receiver callback with user argument See also :py:meth:`remove_signal_receiver`, :py:exc:`.ConnSignalNameNotRecognisedException` :param func callback_fn: User-defined callback function to...
Add a signal receiver callback with user argument See also :py:meth:`remove_signal_receiver`, :py:exc:`.ConnSignalNameNotRecognisedException` :param func callback_fn: User-defined callback function to call when signal triggers :param str signal: Signal name e.g....
def cleanupmem(initial_memory): """ Cleans up initial memory. Each label must be ALONE. Each instruction must have an space, etc... """ i = 0 while i < len(initial_memory): tmp = initial_memory[i] match = RE_LABEL.match(tmp) if not match: i += 1 contin...
Cleans up initial memory. Each label must be ALONE. Each instruction must have an space, etc...
def cleanup_files(self): """Clean up files, remove builds.""" logger.debug('Cleaning up...') with indent_log(): for req in self.reqs_to_cleanup: req.remove_temporary_source() if self._pip_has_created_build_dir(): logger.debug('Removing tem...
Clean up files, remove builds.
def List(self): """ Lists the keys and values. """ print() for key in list(self.keys()): print(key,'=',self[key]) print()
Lists the keys and values.
def decimate(self, method, a, maxpoints=10000, **kwargs): """Decimate data *a* to *maxpoints* using *method*. If *a* is a 1D array then it is promoted to a (2, N) array where the first column simply contains the index. If the array contains fewer than *maxpoints* points or if *...
Decimate data *a* to *maxpoints* using *method*. If *a* is a 1D array then it is promoted to a (2, N) array where the first column simply contains the index. If the array contains fewer than *maxpoints* points or if *maxpoints* is ``None`` then it is returned as it is. The defa...
def attribute(self): """Set or reset attributes""" paint = { "bold": self.ESC + "1" + self.END, 1: self.ESC + "1" + self.END, "dim": self.ESC + "2" + self.END, 2: self.ESC + "2" + self.END, "underlined": self.ESC + "4" + self.END, ...
Set or reset attributes
def pos_tag( words: List[str], engine: str = "perceptron", corpus: str = "orchid" ) -> List[Tuple[str, str]]: """ Part of Speech tagging function. :param list words: a list of tokenized words :param str engine: * unigram - unigram tagger * perceptron - perceptron tagger (default) ...
Part of Speech tagging function. :param list words: a list of tokenized words :param str engine: * unigram - unigram tagger * perceptron - perceptron tagger (default) * artagger - RDR POS tagger :param str corpus: * orchid - annotated Thai academic articles (default) ...
def fastaReadHeaders(fasta): """Returns a list of fasta header lines, excluding """ headers = [] fileHandle = open(fasta, 'r') line = fileHandle.readline() while line != '': assert line[-1] == '\n' if line[0] == '>': headers.append(line[1:-1]) line = fileHandl...
Returns a list of fasta header lines, excluding
def do_dock6_flexible(self, ligand_path, force_rerun=False): """Dock a ligand to the protein. Args: ligand_path (str): Path to ligand (mol2 format) to dock to protein force_rerun (bool): If method should be rerun even if output file exists """ log.debug('{}: run...
Dock a ligand to the protein. Args: ligand_path (str): Path to ligand (mol2 format) to dock to protein force_rerun (bool): If method should be rerun even if output file exists
def get_tile_geometry(path, origin_espg, tolerance=500): """ Calculate the data and tile geometry for sentinel-2 tiles """ with rasterio.open(path) as src: # Get tile geometry b = src.bounds tile_shape = Polygon([(b[0], b[1]), (b[2], b[1]), (b[2], b[3]), (b[0], b[3]), (b[0], b[1])]) ...
Calculate the data and tile geometry for sentinel-2 tiles
def png_data_uri(self, **kw): """\ Converts the QR Code into a PNG data URI. Uses the same keyword parameters as the usual PNG serializer. :rtype: str """ return writers.as_png_data_uri(self.matrix, self._version, **kw)
\ Converts the QR Code into a PNG data URI. Uses the same keyword parameters as the usual PNG serializer. :rtype: str
def srbt(bt_address, pkts, inter=0.1, *args, **kargs): """send and receive using a bluetooth socket""" if "port" in kargs: s = conf.BTsocket(bt_address=bt_address, port=kargs.pop("port")) else: s = conf.BTsocket(bt_address=bt_address) a, b = sndrcv(s, pkts, inter=inter, *args, **kargs) ...
send and receive using a bluetooth socket
def paste(self, key, data): """Pastes data into grid Parameters ---------- key: 2-Tuple of Integer \tTop left cell data: String or wx.Bitmap \tTab separated string of paste data \tor paste data image """ data_gen = self._get_paste_data_g...
Pastes data into grid Parameters ---------- key: 2-Tuple of Integer \tTop left cell data: String or wx.Bitmap \tTab separated string of paste data \tor paste data image
def send_audio(self, url, name, **audioinfo): """Send a pre-uploaded audio to the room. See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-audio for audioinfo Args: url (str): The mxc url of the audio. name (str): The filename of the audio. ...
Send a pre-uploaded audio to the room. See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-audio for audioinfo Args: url (str): The mxc url of the audio. name (str): The filename of the audio. audioinfo (): Extra information about the audio.
def country_bank_code(self): """str or None: The country specific bank-code associated with the BIC.""" entry = registry.get('bic').get(self.compact) if entry: return entry.get('bank_code')
str or None: The country specific bank-code associated with the BIC.
def fromcols(selection, n_sessions, eqdata, **kwargs): """ Generate features from selected columns of a dataframe. Parameters ---------- selection : list or tuple of str Columns to be used as features. n_sessions : int Number of sessions over which to create features. eqda...
Generate features from selected columns of a dataframe. Parameters ---------- selection : list or tuple of str Columns to be used as features. n_sessions : int Number of sessions over which to create features. eqdata : DataFrame Data from which to generate feature set. Mus...
def intern(self, sym: sym.Symbol, var: Var, force: bool = False) -> Var: """Intern the Var given in this namespace mapped by the given Symbol. If the Symbol already maps to a Var, this method _will not overwrite_ the existing Var mapping unless the force keyword argument is given and is ...
Intern the Var given in this namespace mapped by the given Symbol. If the Symbol already maps to a Var, this method _will not overwrite_ the existing Var mapping unless the force keyword argument is given and is True.
def _reflect_table(self): """Load the tables definition from the database.""" with self.db.lock: try: self._table = SQLATable(self.name, self.db.metadata, schema=self.db.schema, ...
Load the tables definition from the database.
def get_fit_auto(self, CentralFreq, MaxWidth=15000, MinWidth=500, WidthIntervals=500, MakeFig=True, show_fig=True, silent=False): """ Tries a range of regions to search for peaks and runs the one with the least error and returns the parameters with the least errors. Parameters -...
Tries a range of regions to search for peaks and runs the one with the least error and returns the parameters with the least errors. Parameters ---------- CentralFreq : float The central frequency to use for the fittings. MaxWidth : float, optional The ma...
def Serialize(self, writer): """ Serialize object. Args: writer (neo.IO.BinaryWriter): """ writer.WriteUInt32(self.Version) writer.WriteUInt64(self.Services) writer.WriteUInt32(self.Timestamp) writer.WriteUInt16(self.Port) writer.Write...
Serialize object. Args: writer (neo.IO.BinaryWriter):
def set_ext_param(self, ext_key, param_key, val): ''' Set the provided parameter in a set of extension parameters. ''' if not self.extensions[ext_key]: self.extensions[ext_key] = defaultdict(lambda: None) self.extensions[ext_key][param_key] = val
Set the provided parameter in a set of extension parameters.
def post_message(name, channel, from_name, message, api_key=None, icon=None): ''' Send a message to a Slack channel. .. code-block:: yaml slack-message: slack.post_message: - channel: '#gener...
Send a message to a Slack channel. .. code-block:: yaml slack-message: slack.post_message: - channel: '#general' - from_name: SuperAdmin - message: 'This state was executed successfully.' - api_key: peWcBiMOS9HrZG15peWcBiMOS9HrZG15 The followi...
def managed(name, peers=None, servers=None): ''' Manages the configuration of NTP peers and servers on the device, as specified in the state SLS file. NTP entities not specified in these lists will be removed whilst entities not configured on the device will be set. SLS Example: .. code-block:: y...
Manages the configuration of NTP peers and servers on the device, as specified in the state SLS file. NTP entities not specified in these lists will be removed whilst entities not configured on the device will be set. SLS Example: .. code-block:: yaml netntp_example: netntp.managed: ...
def gauge(name, value, rate=1, tags=None): """Set the value for a gauge. >>> import statsdecor >>> statsdecor.gauge('my.metric', 10) """ client().gauge(name, value, rate, tags)
Set the value for a gauge. >>> import statsdecor >>> statsdecor.gauge('my.metric', 10)
def get_file(self, filename): """Get a file from the repo. Returns a file-like stream with the data. """ log.debug('[%s]: reading: //%s/%s', self.name, self.name, filename) try: blob = self.repo.head.commit.tree/filename return blob.data_stream ex...
Get a file from the repo. Returns a file-like stream with the data.
def process_reply(self, reply, status=None, description=None): """ Re-entry for processing a successful reply. Depending on how the ``retxml`` option is set, may return the SOAP reply XML or process it and return the Python object representing the returned value. @param...
Re-entry for processing a successful reply. Depending on how the ``retxml`` option is set, may return the SOAP reply XML or process it and return the Python object representing the returned value. @param reply: The SOAP reply envelope. @type reply: I{bytes} @param statu...
def _folder_get_content_iter(self, folder_key=None): """Iterator for api.folder_get_content""" lookup_params = [ {'content_type': 'folders', 'node': 'folders'}, {'content_type': 'files', 'node': 'files'} ] for param in lookup_params: more_chunks = Tr...
Iterator for api.folder_get_content
def notify_dispatch_request(self, request): # type: (Request) -> None """Will be called when a context passed to a hooked function is about to dispatch a request""" if isinstance(request, Put) and request.path[0] == self.mri: # This means the context we were passed has just m...
Will be called when a context passed to a hooked function is about to dispatch a request
def can_view(self, user=None, access_code=None): ''' Returns true if the accessing user is allowed to view this invoice, or if the given access code matches this invoice's user's access code. ''' if user == self.invoice.user: return True if user.is_staff: ...
Returns true if the accessing user is allowed to view this invoice, or if the given access code matches this invoice's user's access code.
def transfer(self, rights_assignment_data=None, *, from_user, to_user, rights_assignment_format='jsonld'): """Transfer this Right to another owner on the backing persistence layer. Args: rights_assignment_data (dict): Model data for the resulting :cl...
Transfer this Right to another owner on the backing persistence layer. Args: rights_assignment_data (dict): Model data for the resulting :class:`~.RightsAssignment` from_user (any, keyword): A user based on the model specified by the persistence l...
def _run_suite(self, test_suite): """ run tests in test_suite Args: test_suite: unittest.TestSuite() Returns: list: tests_results """ tests_results = [] for testcase in test_suite: testcase_name = testcase.config.get("name") ...
run tests in test_suite Args: test_suite: unittest.TestSuite() Returns: list: tests_results
def _open(self, filename): """ Open the input file. Set self._fp to point to it. Read the first line of parameters. @param filename: A C{str} filename containing JSON BLAST records. @raise ValueError: if the first line of the file isn't valid JSON, if the input file ...
Open the input file. Set self._fp to point to it. Read the first line of parameters. @param filename: A C{str} filename containing JSON BLAST records. @raise ValueError: if the first line of the file isn't valid JSON, if the input file is empty, or if the JSON does not contain an ...
def from_pint(cls, arr, unit_registry=None): """ Convert a Pint "Quantity" to a unyt_array or unyt_quantity. Parameters ---------- arr : Pint Quantity The Quantity to convert from. unit_registry : yt UnitRegistry, optional A yt unit registry to us...
Convert a Pint "Quantity" to a unyt_array or unyt_quantity. Parameters ---------- arr : Pint Quantity The Quantity to convert from. unit_registry : yt UnitRegistry, optional A yt unit registry to use in the conversion. If one is not supplied, the defa...
def iterable_validator(iterable_type, member_type): """Validator for ``attrs`` that performs deep type checking of iterables.""" def _validate_tuple(instance, attribute, value): # pylint: disable=unused-argument """Validate that a dictionary is structured as expected. :raises TypeError...
Validator for ``attrs`` that performs deep type checking of iterables.
def make_twitter_request(url, user_id, params={}, request_type='GET'): """ Generically make a request to twitter API using a particular user's authorization """ if request_type == "GET": return requests.get(url, auth=get_twitter_auth(user_id), params=params) elif request_type == "POST": retu...
Generically make a request to twitter API using a particular user's authorization
def append_child(self, name, child): # type: (str, typing.Any) -> ArTree """Append new child and return it.""" temp = ArTree(name, child) self._array.append(temp) return temp
Append new child and return it.
def clean_streak(image, stat="pmode1", maxiter=15, sigrej=2.0, lower=None, upper=None, binwidth=0.3, mask=None, rpt_clean=0, atol=0.01, verbose=True): """ Apply destriping algorithm to input array. Parameters ---------- image : `StripeArray` object Arrays a...
Apply destriping algorithm to input array. Parameters ---------- image : `StripeArray` object Arrays are modifed in-place. stat : str Statistics for background computations (see :py:func:`clean` for more details) mask : `numpy.ndarray` Mask array. Pixels with zero ...
def on_message(self, msg=None): """ Poll the websocket for a new packet. `Client.listen()` calls this. :param msg (string(byte array)): Optional. Parse the specified message instead of receiving a packet from the socket. """ if msg is None: try: ...
Poll the websocket for a new packet. `Client.listen()` calls this. :param msg (string(byte array)): Optional. Parse the specified message instead of receiving a packet from the socket.
def count(self): """ This method retrieve the total of records resulting from a given query. This attribute can be used compounded with query, filter, sort, order and facet methods. Examples: >>> from crossref.restful import Works >>> Works().query('zika...
This method retrieve the total of records resulting from a given query. This attribute can be used compounded with query, filter, sort, order and facet methods. Examples: >>> from crossref.restful import Works >>> Works().query('zika').count() 3597 ...
def font(self): """ The |Font| object that provides access to the text properties for these data labels, such as bold, italic, etc. """ defRPr = self._element.defRPr font = Font(defRPr) return font
The |Font| object that provides access to the text properties for these data labels, such as bold, italic, etc.
def convert_from_file(file): """ Reads the content of file in IDX format, converts it into numpy.ndarray and returns it. file is a file-like object (with read() method) or a file name. """ if isinstance(file, six_string_types): with open(file, 'rb') as f: return _internal_con...
Reads the content of file in IDX format, converts it into numpy.ndarray and returns it. file is a file-like object (with read() method) or a file name.
def _flatten_beam_dim(tensor): """Reshapes first two dimensions in to single dimension. Args: tensor: Tensor to reshape of shape [A, B, ...] Returns: Reshaped tensor of shape [A*B, ...] """ shape = _shape_list(tensor) shape[0] *= shape[1] shape.pop(1) # Remove beam dim return tf.reshape(tenso...
Reshapes first two dimensions in to single dimension. Args: tensor: Tensor to reshape of shape [A, B, ...] Returns: Reshaped tensor of shape [A*B, ...]
def _get_fault_type_dummy_variables(self, rup): """ The original classification considers four style of faulting categories (normal, strike-slip, reverse-oblique and reverse). """ Fn, Fr = 0, 0 if rup.rake >= -112.5 and rup.rake <= -67.5: # normal ...
The original classification considers four style of faulting categories (normal, strike-slip, reverse-oblique and reverse).
def _generate_ccitt_header(self, data): """Construct a CCITT G3 or G4 header from the PDF metadata""" # https://stackoverflow.com/questions/2641770/ # https://www.itu.int/itudoc/itu-t/com16/tiff-fx/docs/tiff6.pdf if not self.decode_parms: raise ValueError("/CCITTFaxDecode wi...
Construct a CCITT G3 or G4 header from the PDF metadata
def _ast_op_concat_to_code(self, opr, *, ignore_whitespace, **kwargs): """Convert an AST concatenate op to python source code.""" hoist_target = OP_CONCAT if ignore_whitespace else OP_WS_CONCAT operands = self._hoist_operands(opr.operands, lambda t: isinstance(t, OptreeNode) and t.opnode.operator is hoist_t...
Convert an AST concatenate op to python source code.
def copy_graph(subject, existing_graph): """Function takes a subject and an existing graph, returns a new graph with all predicate and objects of the existing graph copied to the new_graph with subject as the new subject Args: subject(rdflib.URIRef): A URIRef subject existing_graph(rdfl...
Function takes a subject and an existing graph, returns a new graph with all predicate and objects of the existing graph copied to the new_graph with subject as the new subject Args: subject(rdflib.URIRef): A URIRef subject existing_graph(rdflib.Graph): A rdflib.Graph Returns: ...
def check_visitors(cls): """Check that a checker's visitors are correctly named. A checker has methods named visit_NODETYPE, but it's easy to mis-name a visit method, and it will never be called. This decorator checks the class to see that all of its visitors are named after an existing node class...
Check that a checker's visitors are correctly named. A checker has methods named visit_NODETYPE, but it's easy to mis-name a visit method, and it will never be called. This decorator checks the class to see that all of its visitors are named after an existing node class.
def metricCompute(self, sensorToBody, bodyToSpecificObject): """ Compute the "sensor's location relative to a specific object" from the "body's location relative to a specific object" and the "sensor's location relative to body" @param sensorToBody (numpy array) Active cells o...
Compute the "sensor's location relative to a specific object" from the "body's location relative to a specific object" and the "sensor's location relative to body" @param sensorToBody (numpy array) Active cells of a single module that represents the sensor's location relative to t...
def drop_debug_privileges(cls, bIgnoreExceptions = False): """ Drops debug privileges. This may be needed to avoid being detected by certain anti-debug tricks. @type bIgnoreExceptions: bool @param bIgnoreExceptions: C{True} to ignore any exceptions that may be ...
Drops debug privileges. This may be needed to avoid being detected by certain anti-debug tricks. @type bIgnoreExceptions: bool @param bIgnoreExceptions: C{True} to ignore any exceptions that may be raised when dropping debug privileges. @rtype: bool @retu...
def _handle_magic_exception(self, mod, exc): """ Beginning with Ansible >2.6, some modules (file.py) install a sys.excepthook which is a closure over AnsibleModule, redirecting the magical exception to AnsibleModule.fail_json(). For extra special needs bonus points, the class is...
Beginning with Ansible >2.6, some modules (file.py) install a sys.excepthook which is a closure over AnsibleModule, redirecting the magical exception to AnsibleModule.fail_json(). For extra special needs bonus points, the class is not defined in module_utils, but is defined in the modul...
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_tx_ls_rjt(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") fcoe_get_interface = ET.Element("fcoe_get_interface") config = fcoe_get_interface output = ET.SubElement(fcoe_get_interface, "output"...
Auto Generated Code
def _process_data_var(string): """Transform datastring to key, values pair. All values are transformed to floating point values. Parameters ---------- string : str Returns ------- Tuple[Str, Str] key, values pair """ key, var = string.split("<-") if "structure" in ...
Transform datastring to key, values pair. All values are transformed to floating point values. Parameters ---------- string : str Returns ------- Tuple[Str, Str] key, values pair
def configure(self, options, config): """Configure the set of plugins with the given options and config instance. After configuration, disabled plugins are removed from the plugins list. """ log.debug("Configuring plugins") self.config = config cfg = PluginProxy('...
Configure the set of plugins with the given options and config instance. After configuration, disabled plugins are removed from the plugins list.
def total_reads_from_grabix(in_file): """Retrieve total reads in a fastq file from grabix index. """ gbi_file = _get_grabix_index(in_file) if gbi_file: with open(gbi_file) as in_handle: next(in_handle) # throw away num_lines = int(next(in_handle).strip()) assert ...
Retrieve total reads in a fastq file from grabix index.
def determine_min_cell(disordered_structure): """ Determine the smallest supercell that is able to enumerate the provided structure with the given order parameter """ def lcm(n1, n2): """ Find least common multiple of two numbers """ ...
Determine the smallest supercell that is able to enumerate the provided structure with the given order parameter
def defaultStorable(self, python_type=None, storable_type=None, version=None, **kwargs): """ Generate a default storable instance. Arguments: python_type (type): Python type of the object. storable_type (str): storable type name. version (tuple): version n...
Generate a default storable instance. Arguments: python_type (type): Python type of the object. storable_type (str): storable type name. version (tuple): version number of the storable handler. Returns: StorableHandler: storable instance. Ex...
def oauth_register(form): """Register user if possible. :param form: A form instance. :returns: A :class:`invenio_accounts.models.User` instance. """ if form.validate(): data = form.to_dict() if not data.get('password'): data['password'] = '' user = register_user...
Register user if possible. :param form: A form instance. :returns: A :class:`invenio_accounts.models.User` instance.
def concat_ws(sep, *cols): """ Concatenates multiple input string columns together into a single string column, using the given separator. >>> df = spark.createDataFrame([('abcd','123')], ['s', 'd']) >>> df.select(concat_ws('-', df.s, df.d).alias('s')).collect() [Row(s=u'abcd-123')] """ ...
Concatenates multiple input string columns together into a single string column, using the given separator. >>> df = spark.createDataFrame([('abcd','123')], ['s', 'd']) >>> df.select(concat_ws('-', df.s, df.d).alias('s')).collect() [Row(s=u'abcd-123')]
def sget_timestamp(self, cycle, step, dataset_number=None): """Returns timestamp for cycle, step. Convinience function; same as issuing dfdata[(dfdata[cycle_index_header] == cycle) & (dfdata[step_index_header] == step)][timestamp_header] Args: cycle: cyc...
Returns timestamp for cycle, step. Convinience function; same as issuing dfdata[(dfdata[cycle_index_header] == cycle) & (dfdata[step_index_header] == step)][timestamp_header] Args: cycle: cycle number step: step number dataset_number: the...
def update(self, *data, **kwargs) -> 'Entity': """Update a Record in the repository. Also performs unique validations before creating the entity. Supports both dictionary and keyword argument updates to the entity:: dog.update({'age': 10}) dog.update(age=10) ...
Update a Record in the repository. Also performs unique validations before creating the entity. Supports both dictionary and keyword argument updates to the entity:: dog.update({'age': 10}) dog.update(age=10) :param data: Dictionary of values to be updated for the en...
def _parse_json(self, doc, exactly_one): """ Parse JSON response body. """ places = doc.get('geonames', []) self._raise_for_error(doc) if not len(places): return None def parse_code(place): """ Parse each record. ""...
Parse JSON response body.
def is_integer(value, coerce_value = False, minimum = None, maximum = None, base = 10, **kwargs): """Indicate whether ``value`` contains a whole number. :param value: The value to evaluate. :param coerce_value: If ``True``, will re...
Indicate whether ``value`` contains a whole number. :param value: The value to evaluate. :param coerce_value: If ``True``, will return ``True`` if ``value`` can be coerced to whole number. If ``False``, will only return ``True`` if ``value`` is already a whole number (regardless of type). Defaults...
def add_incomplete_penetrance(genes, alias_genes, hpo_lines): """Add information of incomplete penetrance""" LOG.info("Add incomplete penetrance info") for hgnc_symbol in get_incomplete_penetrance_genes(hpo_lines): for hgnc_id in get_correct_ids(hgnc_symbol, alias_genes): genes[hgnc_id][...
Add information of incomplete penetrance
def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts): ''' Delete A record If the A record is used as a round robin you can set ``allow_array=True`` to delete all records for the hostname. CLI Examples: .. code-block:: bash salt-call infoblox.delete_a name=abc.example...
Delete A record If the A record is used as a round robin you can set ``allow_array=True`` to delete all records for the hostname. CLI Examples: .. code-block:: bash salt-call infoblox.delete_a name=abc.example.com salt-call infoblox.delete_a ipv4addr=192.168.3.5 salt-call inf...
def subdivide_with(self, branches, join_function, name='mixed'): """Branches this pretty tensor and uses an explicit join function. This should be used in a with statement, for example to fork and join with a sum: with pt.subdivide_with(2, tf.add_n) as [a, b]: a... b... Ar...
Branches this pretty tensor and uses an explicit join function. This should be used in a with statement, for example to fork and join with a sum: with pt.subdivide_with(2, tf.add_n) as [a, b]: a... b... Args: branches: The number of branches. join_function: A funct...
def initialize(): """ Method to parse and check configurations of FORD, get the project's global documentation, and create the Markdown reader. """ try: import multiprocessing ncpus = '{0}'.format(multiprocessing.cpu_count()) except (ImportError, NotImplementedError): nc...
Method to parse and check configurations of FORD, get the project's global documentation, and create the Markdown reader.
def sort(polylines): """ sort points within polyline p0-p1-p2... """ for n, c in enumerate(polylines): l = len(c) if l > 2: # DEFINE FIRST AND LAST INDEX A THOSE TWO POINTS THAT # HAVE THE BIGGEST DIFFERENCE FROM A MIDDLE: mid = c.mean(axis=0) ...
sort points within polyline p0-p1-p2...
def show(what='contents', calc_id=-1, extra=()): """ Show the content of a datastore (by default the last one). """ datadir = datastore.get_datadir() if what == 'all': # show all if not os.path.exists(datadir): return rows = [] for calc_id in datastore.get_calc_i...
Show the content of a datastore (by default the last one).
def is_module_has_decorated(path,decorator_module,decorator_name): ''' Finds out if a python module uses a given decorator. Args : loaded_module : The loaded module to be scanned. decorator_module : Then name of the module defining the decorator. decora...
Finds out if a python module uses a given decorator. Args : loaded_module : The loaded module to be scanned. decorator_module : Then name of the module defining the decorator. decorator_name : The name of the decorator.
def val_to_bin(edges, x): """Convert axis coordinate to bin index.""" ibin = np.digitize(np.array(x, ndmin=1), edges) - 1 return ibin
Convert axis coordinate to bin index.
def _gen_packet_setcolor(self, sequence, hue, sat, bri, kel, fade): """ Generate "setcolor" packet payload. """ hue = min(max(hue, HUE_MIN), HUE_MAX) sat = min(max(sat, SATURATION_MIN), SATURATION_MAX) bri = min(max(bri, BRIGHTNESS_MIN), BRIGHTNESS_MAX) kel = min(max(kel, TEMP_MI...
Generate "setcolor" packet payload.
def rename(self, old_key, new_key): """Rename a file. :param old_key: Old key that holds the object. :param new_key: New key that will hold the object. :returns: The object that has been renamed. """ assert new_key not in self assert old_key != new_key f...
Rename a file. :param old_key: Old key that holds the object. :param new_key: New key that will hold the object. :returns: The object that has been renamed.
def push(self): """ Pushes updated plot data via the Comm. """ if self.comm is None: raise Exception('Renderer does not have a comm.') diff = self.renderer.diff(self) self.comm.send(diff)
Pushes updated plot data via the Comm.
def generate_jobs_pending_widget(): """Generates a jobs_pending progress bar widget. """ pbar = widgets.IntProgress( value=0, min=0, max=50, description='', orientation='horizontal', layout=widgets.Layout(max_width='180px')) pbar.style.bar_color = '#71cddd' p...
Generates a jobs_pending progress bar widget.
def ngram_count(text,N=1,keep_punct=False): ''' if N=1, return a dict containing each letter along with how many times the letter occurred. if N=2, returns a dict containing counts of each bigram (pair of letters) etc. There is an option to remove all spaces and punctuation prior to processi...
if N=1, return a dict containing each letter along with how many times the letter occurred. if N=2, returns a dict containing counts of each bigram (pair of letters) etc. There is an option to remove all spaces and punctuation prior to processing
def add_files(self, files): """Add files and/or folders to transfer. If :class:`Transfer.compress` attribute is set to ``True``, files will get packed into a zip file before sending. :param files: Files or folders to send :type files: str, list """ if isinstance...
Add files and/or folders to transfer. If :class:`Transfer.compress` attribute is set to ``True``, files will get packed into a zip file before sending. :param files: Files or folders to send :type files: str, list
def multi_evaluate(self, x, out=None): """Evaluate log of the density to propose ``x``, namely log(q(x)) for each row in x. :param x: Matrix-like array; the proposed points. Expect i-th accessible as ``x[i]``. :param out: Vector-like array, length=...
Evaluate log of the density to propose ``x``, namely log(q(x)) for each row in x. :param x: Matrix-like array; the proposed points. Expect i-th accessible as ``x[i]``. :param out: Vector-like array, length==``len(x)``, optional; If provided, th...
def _get_netengine_backend(self): """ returns the netengine backend specified in self.backend for internal use only """ # extract backend class name, eg: AirOS or OpenWRT backend_class_name = self.backend.split('.')[-1] # convert to lowercase to get the path ...
returns the netengine backend specified in self.backend for internal use only
def visit_yieldfrom(self, node): """ Return an astroid.YieldFrom node as string. """ yi_val = (" " + node.value.accept(self)) if node.value else "" expr = "yield from" + yi_val if node.parent.is_statement: return expr return "(%s)" % (expr,)
Return an astroid.YieldFrom node as string.
def _reset_timeout(self): """Reset timeout for date keep alive.""" if self._timeout: self._timeout.cancel() self._timeout = self.loop.call_later(self.client.timeout, self.transport.close)
Reset timeout for date keep alive.
def _request(self, method, path, server=None, **kwargs): """Execute a request to the cluster A server is selected from the server pool. """ while True: next_server = server or self._get_server() try: response = self.server_pool[next_server].reques...
Execute a request to the cluster A server is selected from the server pool.
def stop(self): """ Stops the Dynamips hypervisor process. """ if self.is_running(): log.info("Stopping Dynamips process PID={}".format(self._process.pid)) yield from DynamipsHypervisor.stop(self) # give some time for the hypervisor to properly stop. ...
Stops the Dynamips hypervisor process.
def discover(self, start, top_level_directory=None, pattern='test*.py'): """Do test case discovery. This is the top-level entry-point for test discovery. If the ``start`` argument is a drectory, then ``haas`` will discover all tests in the package contained in that directory. ...
Do test case discovery. This is the top-level entry-point for test discovery. If the ``start`` argument is a drectory, then ``haas`` will discover all tests in the package contained in that directory. If the ``start`` argument is not a directory, it is assumed to be a package ...
def plot_bargraph (self, data, cats=None, pconfig=None): """ Depreciated function. Forwards to new location. """ from multiqc.plots import bargraph if pconfig is None: pconfig = {} return bargraph.plot(data, cats, pconfig)
Depreciated function. Forwards to new location.
def _ssl_PRF(secret, seed, req_len): """ Provides the implementation of SSLv3 PRF function: SSLv3-PRF(secret, seed) = MD5(secret || SHA-1("A" || secret || seed)) || MD5(secret || SHA-1("BB" || secret || seed)) || MD5(secret || SHA-1("CCC" || secret || seed)) || ... req_len sho...
Provides the implementation of SSLv3 PRF function: SSLv3-PRF(secret, seed) = MD5(secret || SHA-1("A" || secret || seed)) || MD5(secret || SHA-1("BB" || secret || seed)) || MD5(secret || SHA-1("CCC" || secret || seed)) || ... req_len should not be more than 26 x 16 = 416.
def feature_scaling(x, xmin, xmax, a=0, b=1): '''Generalized feature scaling (useful for variable error correction rate calculation)''' return a + float(x - xmin) * (b - a) / (xmax - xmin)
Generalized feature scaling (useful for variable error correction rate calculation)
def get_authenticated_subjects(cert_pem): """Return primary subject and set of equivalents authenticated by certificate. - ``cert_pem`` can be str or bytes """ if isinstance(cert_pem, str): cert_pem = cert_pem.encode('utf-8') return d1_common.cert.subjects.extract_subjects(cert_pem)
Return primary subject and set of equivalents authenticated by certificate. - ``cert_pem`` can be str or bytes
def run(self): """Call self._poll_for_update() in a loop and handle errors.""" while True: try: self._poll_for_update() except RuntimeError as error: # Note that because logging triggers a call to notify_update(), by # logging a message, we automatically retry publishing the ...
Call self._poll_for_update() in a loop and handle errors.
def atlasdb_get_zonefiles_by_name(name, max_index=None, con=None, path=None): """ Look up the sequence of zone file records by name, optionally up to a specific zonefile index Returns [{'zonefile_hash': ..., 'txid': ..., 'inv_index': ..., 'block_height': ..., 'present': ..., 'tried_storage': ...}], in block...
Look up the sequence of zone file records by name, optionally up to a specific zonefile index Returns [{'zonefile_hash': ..., 'txid': ..., 'inv_index': ..., 'block_height': ..., 'present': ..., 'tried_storage': ...}], in blockchain order
def _loadFromRow(self, result, fields, cursor): """Load from a database row, described by fields. ``fields`` should be the attribute names that will be set. Note that userclasses will be created (but not loaded). """ position = 0 for elem in fields: v...
Load from a database row, described by fields. ``fields`` should be the attribute names that will be set. Note that userclasses will be created (but not loaded).
def save(self): """ Persist changes on this Samples object back to the One Codex server along with any changes on its metadata (if it has any). """ super(Samples, self).save() if self.metadata is not None: self.metadata.save()
Persist changes on this Samples object back to the One Codex server along with any changes on its metadata (if it has any).