code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def get_pager(self, *path, **kwargs): """ A generator for all the results a resource can provide. The pages are lazily loaded. """ page_arg = kwargs.pop('page_size', None) limit_arg = kwargs.pop('limit', None) kwargs['limit'] = page_arg or limit_arg or self.default_page_size ...
A generator for all the results a resource can provide. The pages are lazily loaded.
def modflow_hob_to_instruction_file(hob_file): """write an instruction file for a modflow head observation file Parameters ---------- hob_file : str modflow hob file Returns ------- df : pandas.DataFrame pandas DataFrame with control file observation information """ ...
write an instruction file for a modflow head observation file Parameters ---------- hob_file : str modflow hob file Returns ------- df : pandas.DataFrame pandas DataFrame with control file observation information
def copy( self ): """ Returns a new copy of a C{ParseResults} object. """ ret = ParseResults( self.__toklist ) ret.__tokdict = self.__tokdict.copy() ret.__parent = self.__parent ret.__accumNames.update( self.__accumNames ) ret.__name = self.__name ...
Returns a new copy of a C{ParseResults} object.
def set_to_numa_nodemask(mask): """ Conver Python set to NUMA nodemask. """ result = nodemask_t() __nodemask_zero(result) for i in range(0, get_max_node() + 1): if i in mask: __nodemask_set(result, i) return result
Conver Python set to NUMA nodemask.
def send_async(self, msg, persist=False): """ Arrange for `msg` to be delivered to this context, with replies directed to a newly constructed receiver. :attr:`dst_id <Message.dst_id>` is set to the target context ID, and :attr:`reply_to <Message.reply_to>` is set to the newly con...
Arrange for `msg` to be delivered to this context, with replies directed to a newly constructed receiver. :attr:`dst_id <Message.dst_id>` is set to the target context ID, and :attr:`reply_to <Message.reply_to>` is set to the newly constructed receiver's handle. :param bool persist: ...
def explanation(self, index, extra): """ >>> d = DistanceAlphabet('D', NPOSTFIX=2, NDIRECT=10) >>> d[55].explanation(13) '11[1101]01-5: [0]+240' """ extraBits = self.extraBits(index) extraString = '[{:0{}b}]'.format(extra, extraBits) return '{0}: [{1[0]}]{...
>>> d = DistanceAlphabet('D', NPOSTFIX=2, NDIRECT=10) >>> d[55].explanation(13) '11[1101]01-5: [0]+240'
def get_payment_card_by_id(cls, payment_card_id, **kwargs): """Find PaymentCard Return single instance of PaymentCard by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_payment_car...
Find PaymentCard Return single instance of PaymentCard by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_payment_card_by_id(payment_card_id, async=True) >>> result = thread.get() ...
def reseed_random(seed): """Reseed factory.fuzzy's random generator.""" r = random.Random(seed) random_internal_state = r.getstate() set_random_state(random_internal_state)
Reseed factory.fuzzy's random generator.
def set_border_style(self, border_style): """ Set the border style using the specified MenuBorderStyle instance. :param border_style: the instance of MenuBorderStyle to use for border style formatting. """ if not isinstance(border_style, MenuBorderStyle): raise TypeEr...
Set the border style using the specified MenuBorderStyle instance. :param border_style: the instance of MenuBorderStyle to use for border style formatting.
def param_fetch_all(self): '''initiate fetch of all parameters''' if time.time() - getattr(self, 'param_fetch_start', 0) < 2.0: # don't fetch too often return self.param_fetch_start = time.time() self.param_fetch_in_progress = True self.mav.param_request_l...
initiate fetch of all parameters
def rand_phone(): """Random US phone number. (10 digits) Example:: >>> rand_phone() (306)-746-6690 """ return "(%s)-%s-%s" % (rand_str(3, string.digits), rand_str(3, string.digits), rand_str(3, string.digits))
Random US phone number. (10 digits) Example:: >>> rand_phone() (306)-746-6690
def stop(self): """Shut down transport.""" self.reconnect = False self.logger.debug("Shutting down.") if self.transport: self.transport.close()
Shut down transport.
def get_complete(command): """ Get the Cmd complete function for the click command :param command: The click Command object :return: the complete_* method for Cmd :rtype: function """ assert isinstance(command, click.Command) def complete_(self, text, line, begidx, endidx): # pylint: ...
Get the Cmd complete function for the click command :param command: The click Command object :return: the complete_* method for Cmd :rtype: function
def apply_with(self, obj, val, ctx): """ recursively apply Schema object :param obj.Model obj: model object to instruct how to create this model :param dict val: things used to construct this model """ for k, v in six.iteritems(val): if k in obj.properties: ...
recursively apply Schema object :param obj.Model obj: model object to instruct how to create this model :param dict val: things used to construct this model
def set_license(self, license_): """Sets the license. arg: license (string): the new license raise: InvalidArgument - ``license`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` raise: NullArgument - ``license`` is ``null`` *compliance: mandatory...
Sets the license. arg: license (string): the new license raise: InvalidArgument - ``license`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` raise: NullArgument - ``license`` is ``null`` *compliance: mandatory -- This method must be implemented.*
def append(self, val): """Connect any new items to the scraper.""" val.scraper = self.scraper val._collection_path = copy(self.collection._collection_path) val._collection_path.append(val) super(ItemList, self).append(val)
Connect any new items to the scraper.
def _values(self): """Getter for series values (flattened)""" return [ val for serie in self.series for val in serie.values if val is not None ]
Getter for series values (flattened)
def tail(self, lines=10): """\ Return the last lines of the file. """ self.seek_end() end_pos = self.file.tell() for i in range(lines): if not self.seek_line(): break data = self.file.read(end_pos - self.file.tell() - 1) if da...
\ Return the last lines of the file.
def mergeSplitsOnInterfaces(root: LNode): """ collect all split/concatenation nodes and group them by target interface """ for ch in root.children: if ch.children: mergeSplitsOnInterfaces(ch) ctx = MergeSplitsOnInterfacesCtx() for ch in root.children: srcPorts = None...
collect all split/concatenation nodes and group them by target interface
def validate(mcs, bases, attributes): """Check attributes.""" if bases[0] is object: return None mcs.check_model_cls(attributes) mcs.check_include_exclude(attributes) mcs.check_properties(attributes)
Check attributes.
def Serialize(self, writer): """ Serialize object. Args: writer (neo.IO.BinaryWriter): """ writer.WriteUInt256(self.AssetId) writer.WriteFixed8(self.Value) writer.WriteUInt160(self.ScriptHash)
Serialize object. Args: writer (neo.IO.BinaryWriter):
def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if...
Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt mym...
def get_system_uptime_output_show_system_uptime_hours(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_system_uptime = ET.Element("get_system_uptime") config = get_system_uptime output = ET.SubElement(get_system_uptime, "output") show_...
Auto Generated Code
def pop(self, groupName, default=None): """ Removes the **groupName** from the Groups and returns the list of group members. If no group is found, **default** is returned. **groupName** is a :ref:`type-string`. This must return either **default** or a :ref:`type-immutable-list` o...
Removes the **groupName** from the Groups and returns the list of group members. If no group is found, **default** is returned. **groupName** is a :ref:`type-string`. This must return either **default** or a :ref:`type-immutable-list` of glyph names as :ref:`type-string`. >>...
def object_from_string(name): """Creates a Python class or function from its fully qualified name. :param name: A fully qualified name of a class or a function. In Python 3 this is only allowed to be of text type (unicode). In Python 2, both bytes and unicode are allowed. :return: A functio...
Creates a Python class or function from its fully qualified name. :param name: A fully qualified name of a class or a function. In Python 3 this is only allowed to be of text type (unicode). In Python 2, both bytes and unicode are allowed. :return: A function or class object. This method i...
def get_last_pos_of_char(char, string): ''' :param char: The character to find :type char: string :param string: The string in which to search for *char* :type string: string :returns: Index in *string* where *char* last appears (unescaped by a preceding "\\"), -1 if not found :rtype: int ...
:param char: The character to find :type char: string :param string: The string in which to search for *char* :type string: string :returns: Index in *string* where *char* last appears (unescaped by a preceding "\\"), -1 if not found :rtype: int Finds the last occurrence of *char* in *string* i...
def _send(self, data): """ Send data to statsite. Data that can not be sent will be queued. """ retry = self.RETRY # Attempt to send any data in the queue while retry > 0: # Check socket if not self.socket: # Log Error ...
Send data to statsite. Data that can not be sent will be queued.
def weight_unit(self, weight_unit): """Sets the weight_unit of this MeasurementSettings. :param weight_unit: The weight_unit of this MeasurementSettings. :type: str """ allowed_values = ["pound", "kilogram"] # noqa: E501 if weight_unit is not None and weight_unit not i...
Sets the weight_unit of this MeasurementSettings. :param weight_unit: The weight_unit of this MeasurementSettings. :type: str
def _check_data_flow_validity(self, check_data_flow): """Checks the validity of a data flow Calls further checks to inspect the id, ports and data types. :param rafcon.core.data_flow.DataFlow check_data_flow: The data flow to be checked :return bool validity, str message: validity is T...
Checks the validity of a data flow Calls further checks to inspect the id, ports and data types. :param rafcon.core.data_flow.DataFlow check_data_flow: The data flow to be checked :return bool validity, str message: validity is True, when the data flow is valid, False else. message gives ...
def active_devices(self, active_devices): """ Sets the active_devices of this ReportBillingData. :param active_devices: The active_devices of this ReportBillingData. :type: int """ if active_devices is None: raise ValueError("Invalid value for `active_devices...
Sets the active_devices of this ReportBillingData. :param active_devices: The active_devices of this ReportBillingData. :type: int
def dump(self, file, sort_keys: bool = True, **kwargs) -> None: """Dump this seeding container to a file as JSON.""" json.dump(self.to_json(), file, sort_keys=sort_keys, **kwargs)
Dump this seeding container to a file as JSON.
def hello_command(name, print_counter=False, repeat=10): """Print nice greetings.""" for i in range(repeat): if print_counter: print i+1, print 'Hello, %s!' % name
Print nice greetings.
def add_basemap(ax, zoom=12): """ Adds map to a plot. """ url = ctx.sources.ST_TONER_LITE xmin, xmax, ymin, ymax = ax.axis() basemap, extent = ctx.bounds2img(xmin, ymin, xmax, ymax, zoom=zoom, url=url) ax.imshow(basemap, extent=extent, interpolati...
Adds map to a plot.
def _bivariate_handler(df, x, y=None, w=None, inplace=True, pvalue='sim', outvals=None, **kwargs): """ Compute a descriptive bivariate statistic over two sets of columns, `x` and `y`, contained in `df`. Parameters ---------- df : pandas.DataFrame ...
Compute a descriptive bivariate statistic over two sets of columns, `x` and `y`, contained in `df`. Parameters ---------- df : pandas.DataFrame dataframe in which columns `x` and `y` are contained x : string or list of strings one or more colum...
def predict(model, X, joint_contribution=False): """ Returns a triple (prediction, bias, feature_contributions), such that prediction ≈ bias + feature_contributions. Parameters ---------- model : DecisionTreeRegressor, DecisionTreeClassifier, ExtraTreeRegressor, ExtraTreeClassifier, ...
Returns a triple (prediction, bias, feature_contributions), such that prediction ≈ bias + feature_contributions. Parameters ---------- model : DecisionTreeRegressor, DecisionTreeClassifier, ExtraTreeRegressor, ExtraTreeClassifier, RandomForestRegressor, RandomForestClassifier, Ex...
def library_exists(self, library): """ Check whether a given library exists. Parameters ---------- library : `str` The name of the library. e.g. 'library' or 'user.library' Returns ------- `bool` True if the library with the given...
Check whether a given library exists. Parameters ---------- library : `str` The name of the library. e.g. 'library' or 'user.library' Returns ------- `bool` True if the library with the given name already exists, False otherwise
def create_from_sedfile(cls, fitsfile, norm_type='eflux'): """Create a CastroData object from an SED fits file Parameters ---------- fitsfile : str Name of the fits file norm_type : str Type of normalization to use, options are: * norm : N...
Create a CastroData object from an SED fits file Parameters ---------- fitsfile : str Name of the fits file norm_type : str Type of normalization to use, options are: * norm : Normalization w.r.t. to test source * flux : Flux of the te...
def _translateMetricsToJSON(self, metrics, label): """ Translates the given metrics value to JSON string metrics: A list of dictionaries per OPFTaskDriver.getMetrics(): Returns: JSON string representing the given metrics object. """ # Transcode the MetricValueElement values into JSO...
Translates the given metrics value to JSON string metrics: A list of dictionaries per OPFTaskDriver.getMetrics(): Returns: JSON string representing the given metrics object.
def list(self, id=None): """ List all running processes :param id: optional PID for the process to list """ args = {'pid': id} self._process_chk.check(args) return self._client.json('process.list', args)
List all running processes :param id: optional PID for the process to list
def prior_groups(self): """get the prior info groups Returns ------- prior_groups : list a list of prior information groups """ og = list(self.prior_information.groupby("obgnme").groups.keys()) #og = list(map(pst_utils.SFMT, og)) return og
get the prior info groups Returns ------- prior_groups : list a list of prior information groups
def get_environ_vars(self, prefix='VIRTUALENV_'): """ Returns a generator with all environmental vars with prefix VIRTUALENV """ for key, val in os.environ.items(): if key.startswith(prefix): yield (key.replace(prefix, '').lower(), val)
Returns a generator with all environmental vars with prefix VIRTUALENV
def get(self, *args, **kwargs): """ Returns a single instance matching this query, optionally with additional filter kwargs. A DoesNotExistError will be raised if there are no rows matching the query A MultipleObjectsFoundError will be raised if there is more than one row matching the q...
Returns a single instance matching this query, optionally with additional filter kwargs. A DoesNotExistError will be raised if there are no rows matching the query A MultipleObjectsFoundError will be raised if there is more than one row matching the queyr
def validate_unique(self): '''This clean method will check for unique_together condition''' # Collect unique_checks and to run from all the forms. all_unique_checks = set() all_date_checks = set() forms_to_delete = self.deleted_forms valid_forms = [form for form in self.f...
This clean method will check for unique_together condition
def get_mask_from_sequence_lengths(sequence_lengths: torch.Tensor, max_length: int) -> torch.Tensor: """ Given a variable of shape ``(batch_size,)`` that represents the sequence lengths of each batch element, this function returns a ``(batch_size, max_length)`` mask variable. For example, if our input ...
Given a variable of shape ``(batch_size,)`` that represents the sequence lengths of each batch element, this function returns a ``(batch_size, max_length)`` mask variable. For example, if our input was ``[2, 2, 3]``, with a ``max_length`` of 4, we'd return ``[[1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 1, 0]]``. ...
def view_elt(token, dstore): """ Display the event loss table averaged by event """ oq = dstore['oqparam'] R = len(dstore['csm_info'].rlzs) dic = group_array(dstore['losses_by_event'].value, 'rlzi') header = oq.loss_dt().names tbl = [] for rlzi in range(R): if rlzi in dic: ...
Display the event loss table averaged by event
def follow_shortlinks(shortlinks): """Follow redirects in list of shortlinks, return dict of resulting URLs""" links_followed = {} for shortlink in shortlinks: url = shortlink request_result = requests.get(url) redirect_history = request_result.history # history might look li...
Follow redirects in list of shortlinks, return dict of resulting URLs
def create_random_context(dialog, rng, minimum_context_length=2, max_context_length=20): """ Samples random context from a dialog. Contexts are uniformly sampled from the whole dialog. :param dialog: :param rng: :return: context, index of next utterance that follows the context """ # sample ...
Samples random context from a dialog. Contexts are uniformly sampled from the whole dialog. :param dialog: :param rng: :return: context, index of next utterance that follows the context
def _get_assignment_target_end(self, ast_module): """Returns position of 1st char after assignment traget. If there is no assignment, -1 is returned If there are more than one of any ( expressions or assigments) then a ValueError is raised. """ if len(ast_module.body)...
Returns position of 1st char after assignment traget. If there is no assignment, -1 is returned If there are more than one of any ( expressions or assigments) then a ValueError is raised.
def cut_video(in_file, out_file, start=None, end=None, vcodec=None, acodec=None, log_level='info', print_cmd=False, **kwargs): """Cut a clip from a video. Args: in_file (str): Input video fil...
Cut a clip from a video. Args: in_file (str): Input video filename. out_file (str): Output video filename. start (None or float): Start time (in seconds). end (None or float): End time (in seconds). vcodec (None or str): Output video codec, None for unchanged. acodec...
def md2pypi(filename): ''' Load .md (markdown) file and sanitize it for PyPI. Remove unsupported github tags: - code-block directive - travis ci build badges ''' content = io.open(filename).read() for match in RE_MD_CODE_BLOCK.finditer(content): rst_block = '\n'.join( ...
Load .md (markdown) file and sanitize it for PyPI. Remove unsupported github tags: - code-block directive - travis ci build badges
def do_escape(source, n): """Its actually quite complicated to cover every case :) http://www.javascriptkit.com/jsref/escapesequence.shtml""" if not n + 1 < len(source): return '' # not possible here but can be possible in general case. if source[n + 1] in LINE_TERMINATOR: if source[...
Its actually quite complicated to cover every case :) http://www.javascriptkit.com/jsref/escapesequence.shtml
def inflate_plugin_dict(plugin_dict, inflate_plugin): """ Inflate a list of strings/dictionaries to a list of plugin instances. Args: plugin_dict (dict): a dict of dict. inflate_plugin (method): the method to inflate the plugin. Returns: list: a plug...
Inflate a list of strings/dictionaries to a list of plugin instances. Args: plugin_dict (dict): a dict of dict. inflate_plugin (method): the method to inflate the plugin. Returns: list: a plugin instances list.
def cree_ws_lecture(self, champs_ligne): """Alternative to create read only widgets. They should be set after.""" for c in champs_ligne: label = ASSOCIATION[c][0] w = ASSOCIATION[c][3](self.acces[c], False) w.setObjectName("champ-lecture-seule-details") se...
Alternative to create read only widgets. They should be set after.
def list_users(self, pattern=None): """ List all users registered on this Pagure instance. :param pattern: filters the starting letters of the return value :return: """ request_url = "{}/api/0/users".format(self.instance) params = None if pattern: ...
List all users registered on this Pagure instance. :param pattern: filters the starting letters of the return value :return:
def generate_error_message(tag, err_uniq, err_appl, err_mult): """ Generate the error message for an object. """ err = [] if err_uniq: err.append('Uniqueness restriction: item type %s' % tag.item_type) if err_appl: err.append('Applicability restriction: field %s' % tag.field) ...
Generate the error message for an object.
def delete_pod(name, namespace='default', **kwargs): ''' Deletes the kubernetes pod defined by name and namespace CLI Examples:: salt '*' kubernetes.delete_pod guestbook-708336848-5nl8c default salt '*' kubernetes.delete_pod name=guestbook-708336848-5nl8c namespace=default ''' cfg ...
Deletes the kubernetes pod defined by name and namespace CLI Examples:: salt '*' kubernetes.delete_pod guestbook-708336848-5nl8c default salt '*' kubernetes.delete_pod name=guestbook-708336848-5nl8c namespace=default
def _create_os_nwk(self, tenant_id, tenant_name, direc, is_fw_virt=False): """Function to create Openstack network. This function does the following: 1. Allocate an IP address with the net_id/subnet_id not filled in the DB. 2. Fill network parameters w/o vlan, segmentation_id...
Function to create Openstack network. This function does the following: 1. Allocate an IP address with the net_id/subnet_id not filled in the DB. 2. Fill network parameters w/o vlan, segmentation_id, because we don't have net_id to store in DB. 3. Create a Openstac...
def set_tiepoints(self, lon, lat): """Defines the lon,lat tie points. """ self.lon_tiepoint = lon self.lat_tiepoint = lat
Defines the lon,lat tie points.
def align_check(device, part_type, partition): ''' Check if partition satisfies the alignment constraint of part_type. Type must be "minimal" or "optimal". CLI Example: .. code-block:: bash salt '*' partition.align_check /dev/sda minimal 1 ''' _validate_device(device) if part...
Check if partition satisfies the alignment constraint of part_type. Type must be "minimal" or "optimal". CLI Example: .. code-block:: bash salt '*' partition.align_check /dev/sda minimal 1
def wrap(self, text): """wrap(text : string) -> [string] Reformat the multiple paragraphs in 'text' so they fit in lines of no more than 'self.width' columns, and return a list of wrapped lines. Tabs in 'text' are expanded with string.expandtabs(), and all other whitespace char...
wrap(text : string) -> [string] Reformat the multiple paragraphs in 'text' so they fit in lines of no more than 'self.width' columns, and return a list of wrapped lines. Tabs in 'text' are expanded with string.expandtabs(), and all other whitespace characters (including newline) are ...
def change_ref(self, gm=None, r0=None, lmax=None): """ Return a new SHGravCoeffs class instance with a different reference gm or r0. Usage ----- clm = x.change_ref([gm, r0, lmax]) Returns ------- clm : SHGravCoeffs class instance. Parame...
Return a new SHGravCoeffs class instance with a different reference gm or r0. Usage ----- clm = x.change_ref([gm, r0, lmax]) Returns ------- clm : SHGravCoeffs class instance. Parameters ---------- gm : float, optional, default = self.gm...
def x(self, x): """Project x as y""" if x is None: return None if self._force_vertical: return super(HorizontalView, self).x(x) return super(HorizontalView, self).y(x)
Project x as y
def escape_regex_special_chars(api_path): """ Turns the non prametrized path components into strings subtable for using as a regex pattern. This primarily involves escaping special characters so that the actual character is matched in the regex. """ def substitute(string, replacements): ...
Turns the non prametrized path components into strings subtable for using as a regex pattern. This primarily involves escaping special characters so that the actual character is matched in the regex.
def find_image(self, image, configuration): """Complain if we don't have an image""" images = configuration["images"] available = list(images.keys()) if not image: info = {} if available: info["available"] = available raise BadOption("...
Complain if we don't have an image
def from_file(filename, serverEndpoint=ServerEndpoint): ''' Parse from file :param filename: file :param serverEndpoint: Tika server end point (optional) :return: ''' tarOutput = parse1('unpack', filename, serverEndpoint, responseMimeType='application/x-tar', ...
Parse from file :param filename: file :param serverEndpoint: Tika server end point (optional) :return:
async def byte_order(self): """Get the byte order used when communicating (should only ever be little endian using this library). """ return await asyncio.wait_for( self._protocol.send_command("byteorder"), timeout=self._timeout )
Get the byte order used when communicating (should only ever be little endian using this library).
def get_volume_by_id(self, id): """ Get ScaleIO Volume object by its ID :param name: ID of volume :return: ScaleIO Volume object :raise KeyError: No Volume with specified ID found :rtype: ScaleIO Volume object """ for vol in self.conn.volumes: ...
Get ScaleIO Volume object by its ID :param name: ID of volume :return: ScaleIO Volume object :raise KeyError: No Volume with specified ID found :rtype: ScaleIO Volume object
def calc_PSD_welch(x, fs, nperseg): '''Caclulate power spectral density with Welch's method Args ---- x: ndarray sample array fs: float sampling frequency (1/dt) Returns ------- f_welch: ndarray Discrete frequencies S_xx_welch: ndarray Estimated PSD ...
Caclulate power spectral density with Welch's method Args ---- x: ndarray sample array fs: float sampling frequency (1/dt) Returns ------- f_welch: ndarray Discrete frequencies S_xx_welch: ndarray Estimated PSD at discrete frequencies `f_welch` P_wel...
def discover(interface=None): """Print help and scan devices on screen. :return: None """ click.secho(HELP, fg='yellow') scan_devices(discovery_print, lfilter=lambda d: d.src not in mac_id_list, iface=interface)
Print help and scan devices on screen. :return: None
def _update_simulation_end_from_lsm(self): """ Update simulation end time from LSM """ te = self.l2g.xd.lsm.datetime[-1] simulation_end = te.replace(tzinfo=utc) \ .astimezone(tz=self.tz) \ .replace(tzinfo=None) if sel...
Update simulation end time from LSM
def run_cna(graph, root, targets, relationship_dict=None): """ Returns the effect from the root to the target nodes represented as {-1,1} :param pybel.BELGraph graph: A BEL graph :param BaseEntity root: The root node :param iter targets: The targets nodes :param dict relationship_dict: dictionary w...
Returns the effect from the root to the target nodes represented as {-1,1} :param pybel.BELGraph graph: A BEL graph :param BaseEntity root: The root node :param iter targets: The targets nodes :param dict relationship_dict: dictionary with relationship effects :return list[tuple]:
def get_assets_by_genus_type(self, asset_genus_type=None): """Gets an ``AssetList`` corresponding to the given asset genus ``Type`` which does not include assets of types derived from the specified ``Type``. In plenary mode, the returned list contains all known assets or an error result...
Gets an ``AssetList`` corresponding to the given asset genus ``Type`` which does not include assets of types derived from the specified ``Type``. In plenary mode, the returned list contains all known assets or an error results. Otherwise, the returned list may contain only those assets ...
def get_topic(self): """ Returns the topic to consider. """ if not hasattr(self, 'topic'): self.topic = get_object_or_404( Topic.objects.select_related('forum').all(), pk=self.kwargs['pk'], ) return self.topic
Returns the topic to consider.
def yieldable(self): """Return True if there is a line that the buffer can return, False otherwise.""" if self.read_buffer is None: return False t = _remove_trailing_new_line(self.read_buffer) n = _find_furthest_new_line(t) if n >= 0: return True ...
Return True if there is a line that the buffer can return, False otherwise.
def restoreSettings(self, settings): """ Restores properties for this tree widget from the inputed XML. :param xml | <xml.etree.ElementTree.Element> :return <bool> success """ self.setUpdatesEnabled(False) self.blockSignals(True...
Restores properties for this tree widget from the inputed XML. :param xml | <xml.etree.ElementTree.Element> :return <bool> success
def parse_content_type(headers: MutableMapping) -> Tuple[Optional[str], str]: """ Find content-type and encoding of the response Args: headers: Response headers Returns: :py:class:`tuple` (content-type, encoding) """ content_type = headers.get("content-type") if not content...
Find content-type and encoding of the response Args: headers: Response headers Returns: :py:class:`tuple` (content-type, encoding)
def set_meta_all(self, props): """Set metadata values for collection. ``props`` a dict with values for properties. """ delta_props = self.get_meta() for key in delta_props.keys(): if key not in props: delta_props[key] = None delta_props.updat...
Set metadata values for collection. ``props`` a dict with values for properties.
def is_kinematic(self, is_kinematic): '''Set the kinematic/dynamic attribute for this body. In pagoda, kinematic bodies have infinite mass and do interact with other bodies via collisions. Parameters ---------- is_kinematic : bool If True, this body will be ...
Set the kinematic/dynamic attribute for this body. In pagoda, kinematic bodies have infinite mass and do interact with other bodies via collisions. Parameters ---------- is_kinematic : bool If True, this body will be set to kinematic. If False, it will be ...
def show_scan_report(audio_filepaths, album_dir, r128_data): """ Display loudness scan results. """ # track loudness/peak for audio_filepath in audio_filepaths: try: loudness, peak = r128_data[audio_filepath] except KeyError: loudness, peak = "SKIPPED", "SKIPPED" else: loudness = "%....
Display loudness scan results.
def parse_data_line(self, sline): """ Parses the data line and builds the dictionary. :param sline: a split data line to parse :returns: the number of rows to jump and parse the next data line or return the code error -1 """ # if there are less values founded than headers...
Parses the data line and builds the dictionary. :param sline: a split data line to parse :returns: the number of rows to jump and parse the next data line or return the code error -1
def copy(configfile='', destpath='', overwrite=False, sub_node=''): """Copies the files in the built file tree map to despath. :param configfile: string Path to the FileTreeMap config file :param destpath: string Path to the files destination :param overwrite: bool Overwrite files ...
Copies the files in the built file tree map to despath. :param configfile: string Path to the FileTreeMap config file :param destpath: string Path to the files destination :param overwrite: bool Overwrite files if they already exist. :param sub_node: string Tree map configura...
def get_children(self): """:returns: A queryset of all the node's children""" if self.is_leaf(): return get_result_class(self.__class__).objects.none() return get_result_class(self.__class__).objects.filter( depth=self.depth + 1, path__range=self._get_children...
:returns: A queryset of all the node's children
def get_lib_and_tag_name(tag): """ Takes a tag string and returns the tag library and tag name. For example, "app_tags.tag_name" is returned as "app_tags", "tag_name" and "app_tags.sub.tag_name" is returned as "app_tags.sub", "tag_name" """ if '.' not in tag: raise ValueError('Tag string...
Takes a tag string and returns the tag library and tag name. For example, "app_tags.tag_name" is returned as "app_tags", "tag_name" and "app_tags.sub.tag_name" is returned as "app_tags.sub", "tag_name"
def obj_ref(obj): """Returns a tuple identifying a category/event/contrib/subcontrib""" from indico_livesync.models.queue import EntryType if isinstance(obj, Category): ref = {'type': EntryType.category, 'category_id': obj.id} elif isinstance(obj, Event): ref = {'type': EntryType.event, ...
Returns a tuple identifying a category/event/contrib/subcontrib
def parsers(self): """Metadata item name to parser function mapping.""" parse_list = self._parse_list parse_file = self._parse_file parse_dict = self._parse_dict exclude_files_parser = self._exclude_files_parser return { 'platforms': parse_list, '...
Metadata item name to parser function mapping.
def rectified(self): """ Fixes swaped min-max pairs. """ return Rect(np.minimum(self.mins, self.maxes), np.maximum(self.maxes, self.mins))
Fixes swaped min-max pairs.
def get_batched(portal_type=None, uid=None, endpoint=None, **kw): """Get batched results """ # fetch the catalog results results = get_search_results(portal_type=portal_type, uid=uid, **kw) # fetch the batch params from the request size = req.get_batch_size() start = req.get_batch_start() ...
Get batched results
def percentOverlap(x1, x2, size): """ Computes the percentage of overlap between vectors x1 and x2. @param x1 (array) binary vector @param x2 (array) binary vector @param size (int) length of binary vectors @return percentOverlap (float) percentage overlap between x1 and x2 """ nonZeroX1 = np.co...
Computes the percentage of overlap between vectors x1 and x2. @param x1 (array) binary vector @param x2 (array) binary vector @param size (int) length of binary vectors @return percentOverlap (float) percentage overlap between x1 and x2
def execute(self, *args, **kwargs): """ Fill all variables from *args and **kwargs, build the request, and send it. If we set the _verbose kwarg to true, then we'll get a Response object back instead of loaded data. """ _verbose = kwargs.pop('_verbose', False) ret...
Fill all variables from *args and **kwargs, build the request, and send it. If we set the _verbose kwarg to true, then we'll get a Response object back instead of loaded data.
def from_bytearray(self, stream): """ Constructs this frame from input data stream, consuming as many bytes as necessary from the beginning of the stream. If stream does not contain enough data to construct a complete modbus frame, an EOFError is raised and no data is consumed. ...
Constructs this frame from input data stream, consuming as many bytes as necessary from the beginning of the stream. If stream does not contain enough data to construct a complete modbus frame, an EOFError is raised and no data is consumed. :param stream: bytearray to consume data from...
def v_multiply(scalar, v1): """ Multiply vector by scalar""" vector = [] for i, x in enumerate(v1): vector.append('(({})*({}))'.format(scalar, v1[i])) return vector
Multiply vector by scalar
def _index_into(self, idx, data): """ Attempts to get the column from the data using the specified index, raises an exception if this is not possible from this point in the stack. """ try: if is_dataframe(data): # Assume column indexing ...
Attempts to get the column from the data using the specified index, raises an exception if this is not possible from this point in the stack.
def normalize_url(url: 'Union[URL, str]') -> 'URL': """Normalize url to make comparisons.""" url = URL(url) return url.with_query(urlencode(sorted(parse_qsl(url.query_string))))
Normalize url to make comparisons.
def determine_progression(self, shorthand=False): """Return a list of lists [place_in_beat, possible_progressions].""" res = [] for x in self.bar: res.append([x[0], progressions.determine(x[2].get_note_names(), self.key.key, shorthand)]) return res
Return a list of lists [place_in_beat, possible_progressions].
def Operate(self, command, index, op_type): """ The Master sent an Operate command to the Outstation. Handle it. :param command: ControlRelayOutputBlock, AnalogOutputInt16, AnalogOutputInt32, AnalogOutputFloat32, or AnalogOutputDouble64. :param index: int ...
The Master sent an Operate command to the Outstation. Handle it. :param command: ControlRelayOutputBlock, AnalogOutputInt16, AnalogOutputInt32, AnalogOutputFloat32, or AnalogOutputDouble64. :param index: int :param op_type: OperateType :return: CommandStatus
def _remove_layer_clicked(self): """Remove layer clicked.""" layer = self.list_layers_in_map_report.selectedItems()[0] origin = layer.data(LAYER_ORIGIN_ROLE) if origin == FROM_ANALYSIS['key']: key = layer.data(LAYER_PURPOSE_KEY_OR_ID_ROLE) parent = layer.data(LAYE...
Remove layer clicked.
def add_systemnumber(self, source, recid=None): """Add 035 number from 001 recid with given source.""" if not recid: recid = self.get_recid() if not self.hidden and recid: record_add_field( self.record, tag='035', subfields=...
Add 035 number from 001 recid with given source.
def f_to_dict(self, copy=True): """Returns annotations as dictionary. :param copy: Whether to return a shallow copy or the real thing (aka _dict). """ if copy: return self._dict.copy() else: return self._dict
Returns annotations as dictionary. :param copy: Whether to return a shallow copy or the real thing (aka _dict).
def _load_profile(self, profile_name): """Load a profile by name Called by load_user_options """ # find the profile default_profile = self._profile_list[0] for profile in self._profile_list: if profile.get('default', False): # explicit defaul...
Load a profile by name Called by load_user_options
def _get_package_name(prefix=settings.TEMP_DIR, book_id=None): """ Return package path. Use uuid to generate package's directory name. Args: book_id (str, default None): UUID of the book. prefix (str, default settings.TEMP_DIR): Where the package will be stored. Default :attr...
Return package path. Use uuid to generate package's directory name. Args: book_id (str, default None): UUID of the book. prefix (str, default settings.TEMP_DIR): Where the package will be stored. Default :attr:`settings.TEMP_DIR`. Returns: str: Path to the root directory...