code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def remove_project(self, node): """ Removes the project associated with given node. :param node: Node. :type node: ProjectNode or DirectoryNode or FileNode :return: Method success. :rtype: bool """ if node.family == "Project": self.__script_e...
Removes the project associated with given node. :param node: Node. :type node: ProjectNode or DirectoryNode or FileNode :return: Method success. :rtype: bool
def get_setting(key, *default): """Return specific search setting from Django conf.""" if default: return get_settings().get(key, default[0]) else: return get_settings()[key]
Return specific search setting from Django conf.
def get_picture_elements(context, instance): """ Create a context, used to render a <picture> together with all its ``<source>`` elements: It returns a list of HTML elements, each containing the information to render a ``<source>`` element. The purpose of this HTML entity is to display images with a...
Create a context, used to render a <picture> together with all its ``<source>`` elements: It returns a list of HTML elements, each containing the information to render a ``<source>`` element. The purpose of this HTML entity is to display images with art directions. For normal images use the ``<img>`` el...
def populate_username(self, request, user): """ Fills in a valid username, if required and missing. If the username is already present it is assumed to be valid (unique). """ from .utils import user_username, user_email, user_field first_name = user_field(user, '...
Fills in a valid username, if required and missing. If the username is already present it is assumed to be valid (unique).
def reload(self, **params): """ Reloads the datatype from Riak. .. warning: This clears any local modifications you might have made. :param r: the read quorum :type r: integer, string, None :param pr: the primary read quorum :type pr: integer, string,...
Reloads the datatype from Riak. .. warning: This clears any local modifications you might have made. :param r: the read quorum :type r: integer, string, None :param pr: the primary read quorum :type pr: integer, string, None :param basic_quorum: whether to us...
def serialize(self, data): """ Determine & invoke the proper serializer method If data is a list then the serialize_datas method will be run otherwise serialize_data. """ super(Serializer, self).serialize(data) self.resp.content_type += '; header=present' impor...
Determine & invoke the proper serializer method If data is a list then the serialize_datas method will be run otherwise serialize_data.
def get_node_annotation_layers(docgraph): """ WARNING: this is higly inefficient! Fix this via Issue #36. Returns ------- all_layers : set or dict the set of all annotation layers used for annotating nodes in the given graph """ all_layers = set() for node_id, node_a...
WARNING: this is higly inefficient! Fix this via Issue #36. Returns ------- all_layers : set or dict the set of all annotation layers used for annotating nodes in the given graph
def is_group_or_super_group(cls, obj) -> bool: """ Check chat is group or super-group :param obj: :return: """ return cls._check(obj, [cls.GROUP, cls.SUPER_GROUP])
Check chat is group or super-group :param obj: :return:
def BGPSessionState_BGPPeerState(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") BGPSessionState = ET.SubElement(config, "BGPSessionState", xmlns="http://brocade.com/ns/brocade-notification-stream") BGPPeerState = ET.SubElement(BGPSessionState, "BGPPeerS...
Auto Generated Code
def subscribeToDeviceEvents(self, typeId="+", deviceId="+", eventId="+", msgFormat="+", qos=0): """ Subscribe to device event messages # Parameters typeId (string): typeId for the subscription, optional. Defaults to all device types (MQTT `+` wildcard) deviceId (string): device...
Subscribe to device event messages # Parameters typeId (string): typeId for the subscription, optional. Defaults to all device types (MQTT `+` wildcard) deviceId (string): deviceId for the subscription, optional. Defaults to all devices (MQTT `+` wildcard) eventId (string): eventId fo...
def init(self): """Init the connection to the CouchDB server.""" if not self.export_enable: return None server_uri = 'tcp://{}:{}'.format(self.host, self.port) try: self.context = zmq.Context() publisher = self.context.socket(zmq.PUB) pub...
Init the connection to the CouchDB server.
def compare_field_caches(self, replica, original): """Verify original is subset of replica""" if original is None: original = [] if replica is None: replica = [] self.pr_dbg("Comparing orig with %s fields to replica with %s fields" % (len(origi...
Verify original is subset of replica
def percent(args=None): ''' Return partition information for volumes mounted on this minion CLI Example: .. code-block:: bash salt '*' disk.percent /var ''' if __grains__['kernel'] == 'Linux': cmd = 'df -P' elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == ...
Return partition information for volumes mounted on this minion CLI Example: .. code-block:: bash salt '*' disk.percent /var
def is_cython(obj): """Check if an object is a Cython function or method""" # TODO(suo): We could split these into two functions, one for Cython # functions and another for Cython methods. # TODO(suo): There doesn't appear to be a Cython function 'type' we can # check against via isinstance. Please...
Check if an object is a Cython function or method
def trade_history( self, from_=None, count=None, from_id=None, end_id=None, order=None, since=None, end=None, pair=None ): """ Returns trade history. To use this method you need a privilege of the info key. :param int or None from_: trade ID, from which the display s...
Returns trade history. To use this method you need a privilege of the info key. :param int or None from_: trade ID, from which the display starts (default 0) :param int or None count: the number of trades for display (default 1000) :param int or None from_id: trade ID, from which the di...
def extract_rows(data, *rows): """Extract rows specified in the argument list. >>> chart_data.extract_rows([[10,20], [30,40], [50,60]], 1, 2) [[30,40],[50,60]] """ try: # for python 2.2 # return [data[r] for r in rows] out = [] for r in rows: out.append(data[r]) ...
Extract rows specified in the argument list. >>> chart_data.extract_rows([[10,20], [30,40], [50,60]], 1, 2) [[30,40],[50,60]]
def allocate(self, nodes, append=True): # TODO: check docstring """Allocates all nodes from `nodes` list in this route Parameters ---------- nodes : type Desc append : bool, defaults to True Desc """ nodes_demand ...
Allocates all nodes from `nodes` list in this route Parameters ---------- nodes : type Desc append : bool, defaults to True Desc
def create_position(self, params={}): """ Creates a position http://dev.wheniwork.com/#create-update-position """ url = "/2/positions/" body = params data = self._post_resource(url, body) return self.position_from_json(data["position"])
Creates a position http://dev.wheniwork.com/#create-update-position
def set_up_dirs(proc_name, output_dir=None, work_dir=None, log_dir=None): """ Creates output_dir, work_dir, and sets up log """ output_dir = safe_mkdir(adjust_path(output_dir or join(os.getcwd(), proc_name)), 'output_dir') debug('Saving results into ' + output_dir) work_dir = safe_mkdir(work_dir or...
Creates output_dir, work_dir, and sets up log
def _phi0(self, tau, delta): """Ideal gas Helmholtz free energy and derivatives Parameters ---------- tau : float Inverse reduced temperature Tc/T, [-] delta : float Reduced density rho/rhoc, [-] Returns ------- prop : dictionary ...
Ideal gas Helmholtz free energy and derivatives Parameters ---------- tau : float Inverse reduced temperature Tc/T, [-] delta : float Reduced density rho/rhoc, [-] Returns ------- prop : dictionary with ideal adimensional helmholtz energy...
def update_eol(self, os_name): """Update end of line status.""" os_name = to_text_string(os_name) value = {"nt": "CRLF", "posix": "LF"}.get(os_name, "CR") self.set_value(value)
Update end of line status.
def main(): """Main function""" # **** For Pytest **** # We need to create MainWindow **here** to avoid passing pytest # options to Spyder if running_under_pytest(): try: from unittest.mock import Mock except ImportError: from mock import Mock # Pyth...
Main function
def start_all_linking(self, mode, group): """Put the IM into All-Linking mode. Puts the IM into All-Linking mode for 4 minutes. Parameters: mode: 0 | 1 | 3 | 255 0 - PLM is responder 1 - PLM is controller 3 - Device that initiat...
Put the IM into All-Linking mode. Puts the IM into All-Linking mode for 4 minutes. Parameters: mode: 0 | 1 | 3 | 255 0 - PLM is responder 1 - PLM is controller 3 - Device that initiated All-Linking is Controller 255 = De...
def _set_wmi_setting(wmi_class_name, setting, value, server): ''' Set the value of the setting for the provided class. ''' with salt.utils.winapi.Com(): try: connection = wmi.WMI(namespace=_WMI_NAMESPACE) wmi_class = getattr(connection, wmi_class_name) objs =...
Set the value of the setting for the provided class.
def all(): """Returns all active registered goals, sorted alphabetically by name. :API: public """ return [goal for _, goal in sorted(Goal._goal_by_name.items()) if goal.active]
Returns all active registered goals, sorted alphabetically by name. :API: public
async def filter_by(cls, db, offset=None, limit=None, **kwargs): """Query by attributes iteratively. Ordering is not supported Example: User.get_by(db, age=[32, 54]) User.get_by(db, age=23, name="guido") """ if limit and type(limit) is not int: raise ...
Query by attributes iteratively. Ordering is not supported Example: User.get_by(db, age=[32, 54]) User.get_by(db, age=23, name="guido")
async def write(self, writer: Any, close_boundary: bool=True) -> None: """Write body.""" if not self._parts: return for part, encoding, te_encoding in self._parts: await writer.write(b'--' + self._boundary + b'\r\n') await writer.write(par...
Write body.
def main(args=None): """ Output information about `streamsx` and the environment. Useful for support to get key information for use of `streamsx` and Python in IBM Streams. """ _parse_args(args) streamsx._streams._version._mismatch_check('streamsx.topology.context') srp = pkg_res...
Output information about `streamsx` and the environment. Useful for support to get key information for use of `streamsx` and Python in IBM Streams.
def clean_ufo(path): """Make sure old UFO data is removed, as it may contain deleted glyphs.""" if path.endswith(".ufo") and os.path.exists(path): shutil.rmtree(path)
Make sure old UFO data is removed, as it may contain deleted glyphs.
def partial_derivative_scalar(self, U, V, y=0): """Compute partial derivative :math:`C(u|v)` of cumulative density of single values.""" self.check_fit() X = np.column_stack((U, V)) return self.partial_derivative(X, y)
Compute partial derivative :math:`C(u|v)` of cumulative density of single values.
def _bilinear_interp(xyref, zref, xi, yi): """ Perform bilinear interpolation of four 2D arrays located at points on a regular grid. Parameters ---------- xyref : list of 4 (x, y) pairs A list of 4 ``(x, y)`` pairs that form a rectangle. refdata : 3D...
Perform bilinear interpolation of four 2D arrays located at points on a regular grid. Parameters ---------- xyref : list of 4 (x, y) pairs A list of 4 ``(x, y)`` pairs that form a rectangle. refdata : 3D `~numpy.ndarray` A 3D `~numpy.ndarray` of shape ``...
def get_region_for_chip(x, y, level=3): """Get the region word for the given chip co-ordinates. Parameters ---------- x : int x co-ordinate y : int y co-ordinate level : int Level of region to build. 0 is the most coarse and 3 is the finest. When 3 is used the sp...
Get the region word for the given chip co-ordinates. Parameters ---------- x : int x co-ordinate y : int y co-ordinate level : int Level of region to build. 0 is the most coarse and 3 is the finest. When 3 is used the specified region will ONLY select the given chip,...
def divide(elements, by, translate=False, sep=' '): """Divide lists `elements` and `by`. All elements are grouped into N bins, where N denotes the elements in `by` list. Parameters ---------- elements: list of dict Elements to be grouped into bins. by: list of dict Elements defi...
Divide lists `elements` and `by`. All elements are grouped into N bins, where N denotes the elements in `by` list. Parameters ---------- elements: list of dict Elements to be grouped into bins. by: list of dict Elements defining the bins. translate: bool (default: False) ...
def addContentLen(self, content, len): """Append the extra substring to the node content. NOTE: In contrast to xmlNodeSetContentLen(), @content is supposed to be raw text, so unescaped XML special chars are allowed, entity references are not supported. """ libxml2mod.xmlNo...
Append the extra substring to the node content. NOTE: In contrast to xmlNodeSetContentLen(), @content is supposed to be raw text, so unescaped XML special chars are allowed, entity references are not supported.
def get_rules(self, optimized): """ Args: optimized (bool): Enable or Disable optimization - Do not produce O(n^3) Return: list: The CFG rules """ self.insert_start_to_accepting() # If CFG is not requested, avoid the following O(n^3) rule. ...
Args: optimized (bool): Enable or Disable optimization - Do not produce O(n^3) Return: list: The CFG rules
def run(self): """ Attmept to deliver the first outgoing L{QueuedMessage}; return a time to reschedule if there are still more retries or outgoing messages to send. """ delay = None router = self.siteRouter for qmsg in self.store.query(_QueuedMessage, ...
Attmept to deliver the first outgoing L{QueuedMessage}; return a time to reschedule if there are still more retries or outgoing messages to send.
def _readline(self): """Read exactly one line from the device, nonblocking. Returns: None on no data """ if len(self.lines) > 1: return self.lines.pop(0) tail = '' if len(self.lines): tail = self.lines.pop() try: ...
Read exactly one line from the device, nonblocking. Returns: None on no data
def _on_properties(self, properties): """ Callback if properties are changed. :param properties: (bool bold, bool italic, bool underline, bool overstrike) """ self._bold, self._italic, self._underline, self._overstrike = properties self._on_change()
Callback if properties are changed. :param properties: (bool bold, bool italic, bool underline, bool overstrike)
def debug_log_repo(repo): """Log to DEBUG level a Repo (or subclass) pretty-printed""" ds_str = juicer.utils.create_json_str(repo, indent=4, cls=juicer.common.Repo.RepoEncoder) juicer.utils.Log.log_debug(ds_str)
Log to DEBUG level a Repo (or subclass) pretty-printed
def check_pin_trust(self, environ): """Checks if the request passed the pin test. This returns `True` if the request is trusted on a pin/cookie basis and returns `False` if not. Additionally if the cookie's stored pin hash is wrong it will return `None` so that appropriate action can be...
Checks if the request passed the pin test. This returns `True` if the request is trusted on a pin/cookie basis and returns `False` if not. Additionally if the cookie's stored pin hash is wrong it will return `None` so that appropriate action can be taken.
def liftover(pass_pos, matures): """Make position at precursor scale""" fixed_pos = [] _print_header(pass_pos) for pos in pass_pos: mir = pos["mature"] db_pos = matures[pos["chrom"]] mut = _parse_mut(pos["sv"]) print([db_pos[mir], mut, pos["sv"]]) pos['pre_pos'] =...
Make position at precursor scale
def fetch(self, range_start, range_end): """ Fetches speeches from the ListarDiscursosPlenario endpoint of the SessoesReunioes (SessionsReunions) API. The date range provided should be specified as a string using the format supported by the API (%d/%m/%Y) """ ran...
Fetches speeches from the ListarDiscursosPlenario endpoint of the SessoesReunioes (SessionsReunions) API. The date range provided should be specified as a string using the format supported by the API (%d/%m/%Y)
def delete(self, image): """Delete the file of the given ``image``. :param image: the image to delete :type image: :class:`sqlalchemy_imageattach.entity.Image` """ from .entity import Image if not isinstance(image, Image): raise TypeError('image must be a sq...
Delete the file of the given ``image``. :param image: the image to delete :type image: :class:`sqlalchemy_imageattach.entity.Image`
def find_value_type(global_ns, value_type_str): """implementation details""" if not value_type_str.startswith('::'): value_type_str = '::' + value_type_str found = global_ns.decls( name=value_type_str, function=lambda decl: not isinstance(decl, calldef.calldef...
implementation details
def timestamp_feature(catalog, soup): """The datetime the xml file was last modified. """ # there's really no "time created", we're using the date the courses are listed for... epoch = 1318790434 catalog.timestamp = int(float(soup.title.text)) + epoch catalog.datetime = datetime.datetime.fromtim...
The datetime the xml file was last modified.
def plot_theta(self, colorbar=True, cb_orientation='vertical', cb_label='$g_\\theta$, m s$^{-2}$', ax=None, show=True, fname=None, **kwargs): """ Plot the theta component of the gravity field. Usage ----- x.plot_theta([tick_interval, xlabel,...
Plot the theta component of the gravity field. Usage ----- x.plot_theta([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname, **kwargs]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30...
def seek(self, position): """Seek to the specified position (byte offset) in the S3 key. :param int position: The byte offset from the beginning of the key. """ self._position = position range_string = make_range_string(self._position) logger.debug('content_length: %r ra...
Seek to the specified position (byte offset) in the S3 key. :param int position: The byte offset from the beginning of the key.
def load_module(ldr, fqname): '''Load `fqname` from under `ldr.fspath`. The `fqname` argument is the fully qualified module name, eg. "spam.eggs.ham". As explained above, when :: finder.find_module("spam.eggs.ham") is called, "spam.eggs" has already been imported and added t...
Load `fqname` from under `ldr.fspath`. The `fqname` argument is the fully qualified module name, eg. "spam.eggs.ham". As explained above, when :: finder.find_module("spam.eggs.ham") is called, "spam.eggs" has already been imported and added to `sys.modules`. However, the `find_...
def enable_secrets_engine(self, backend_type, path=None, description=None, config=None, plugin_name=None, options=None, local=False, seal_wrap=False): """Enable a new secrets engine at the given path. Supported methods: POST: /sys/mounts/{path}. Produces: 204 (...
Enable a new secrets engine at the given path. Supported methods: POST: /sys/mounts/{path}. Produces: 204 (empty body) :param backend_type: The name of the backend type, such as "github" or "token". :type backend_type: str | unicode :param path: The path to mount the method...
def get_00t_magmom_with_xyz_saxis(self): """ For internal implementation reasons, in non-collinear calculations VASP prefers: MAGMOM = 0 0 total_magnetic_moment SAXIS = x y z to an equivalent: MAGMOM = x y z SAXIS = 0 0 1 This method returns a ...
For internal implementation reasons, in non-collinear calculations VASP prefers: MAGMOM = 0 0 total_magnetic_moment SAXIS = x y z to an equivalent: MAGMOM = x y z SAXIS = 0 0 1 This method returns a Magmom object with magnetic moment [0, 0, t], where t...
def has_preview(self): """ Returns if the document has real merged data. When True, `topil()` returns pre-composed data. """ version_info = self.image_resources.get_data('version_info') if version_info: return version_info.has_composite return True
Returns if the document has real merged data. When True, `topil()` returns pre-composed data.
def iscm_md_append_array(self, arraypath, member): """ Append a member to a metadata array entry """ array_path = string.split(arraypath, ".") array_key = array_path.pop() current = self.metadata for k in array_path: if not current.has_key(k): ...
Append a member to a metadata array entry
def add_comment(self, line: str) -> None: '''Keeping track of "last comment" for section and parameter ''' # the rule is like # # # comment line --> add to last comment # blank line --> clears last comment # [ ] --> use last comment # parameter: --> use last comm...
Keeping track of "last comment" for section and parameter
def relative_abundance(coverage): """ cov = number of bases / length of genome relative abundance = [(cov) / sum(cov for all genomes)] * 100 """ relative = {} sums = [] for genome in coverage: for cov in coverage[genome]: sums.append(0) break for genome in coverage: index = 0 for cov in coverage[geno...
cov = number of bases / length of genome relative abundance = [(cov) / sum(cov for all genomes)] * 100
def create_scree_plot(data, o_filename, options): """Creates the scree plot. :param data: the eigenvalues. :param o_filename: the name of the output files. :param options: the options. :type data: numpy.ndarray :type o_filename: str :type options: argparse.Namespace """ # Importin...
Creates the scree plot. :param data: the eigenvalues. :param o_filename: the name of the output files. :param options: the options. :type data: numpy.ndarray :type o_filename: str :type options: argparse.Namespace
def convert_to_group_ids(groups, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a list of security groups and a vpc_id, convert_to_group_ids will convert all list items in the given list to security group ids. CLI example:: salt...
Given a list of security groups and a vpc_id, convert_to_group_ids will convert all list items in the given list to security group ids. CLI example:: salt myminion boto_secgroup.convert_to_group_ids mysecgroup vpc-89yhh7h
def set_context(self): """ Reads throught the namespaces in the RML and generates a context for json+ld output when compared to the RdfNsManager namespaces """ results = self.rml.query(""" SELECT ?o { { ?s rr:class ?o ...
Reads throught the namespaces in the RML and generates a context for json+ld output when compared to the RdfNsManager namespaces
def _insert(self, key, records, count): """ Insert records according to key """ if key not in self.records: assert key not in self.counts self.records[key] = records self.counts[key] = count else: self.records[key] = np.vstack((self.records[key], r...
Insert records according to key
def browse_httpauth_write_apis( request, database_name=None, collection_name=None): """Deprecated""" name = "Write APIs Using HTTPAuth Authentication" if database_name and collection_name: wapis = WriteAPIHTTPAuth.objects.filter( database_name=database_name, ...
Deprecated
def parse_time_derivative(self, node): """ Parses <TimeDerivative> @param node: Node containing the <TimeDerivative> element @type node: xml.etree.Element @raise ParseError: Raised when the time derivative does not hava a variable name of a value. """ i...
Parses <TimeDerivative> @param node: Node containing the <TimeDerivative> element @type node: xml.etree.Element @raise ParseError: Raised when the time derivative does not hava a variable name of a value.
def get_segment_effort(self, effort_id): """ Return a specific segment effort by ID. http://strava.github.io/api/v3/efforts/#retrieve :param effort_id: The id of associated effort to fetch. :type effort_id: int :return: The specified effort on a segment. :rtype...
Return a specific segment effort by ID. http://strava.github.io/api/v3/efforts/#retrieve :param effort_id: The id of associated effort to fetch. :type effort_id: int :return: The specified effort on a segment. :rtype: :class:`stravalib.model.SegmentEffort`
def skip_class_parameters(): """ Can be used with :meth:`add_parametric_object_params`, this removes duplicate variables cluttering the sphinx docs. This is only intended to be used with *sphinx autodoc* In your *sphinx* ``config.py`` file:: from cqparts.utils.sphinx import skip_class_par...
Can be used with :meth:`add_parametric_object_params`, this removes duplicate variables cluttering the sphinx docs. This is only intended to be used with *sphinx autodoc* In your *sphinx* ``config.py`` file:: from cqparts.utils.sphinx import skip_class_parameters def setup(app): ...
def search( self, id_list: List, negated_classes: List, limit: Optional[int] = 100, method: Optional[SimAlgorithm] = SimAlgorithm.PHENODIGM) -> SimResult: """ Owlsim2 search, calls search_by_attribute_set, and converts to SimResult object ...
Owlsim2 search, calls search_by_attribute_set, and converts to SimResult object :raises JSONDecodeError: If the owlsim response is not valid json.
def _extract_functions(resources): """ Extracts and returns function information from the given dictionary of SAM/CloudFormation resources. This method supports functions defined with AWS::Serverless::Function and AWS::Lambda::Function :param dict resources: Dictionary of SAM/CloudForma...
Extracts and returns function information from the given dictionary of SAM/CloudFormation resources. This method supports functions defined with AWS::Serverless::Function and AWS::Lambda::Function :param dict resources: Dictionary of SAM/CloudFormation resources :return dict(string : samcli.com...
def write_header(self): """Write the DNS message header. Writing the DNS message header is done asfter all sections have been rendered, but before the optional TSIG signature is added. """ self.output.seek(0) self.output.write(struct.pack('!HHHHHH', self.id, sel...
Write the DNS message header. Writing the DNS message header is done asfter all sections have been rendered, but before the optional TSIG signature is added.
def is_unit_upgrading_set(): """Return the state of the kv().get('unit-upgrading'). To help with units that don't have HookData() (testing) if it excepts, return False """ try: with unitdata.HookData()() as t: kv = t[0] # transform something truth-y into a Boolean. ...
Return the state of the kv().get('unit-upgrading'). To help with units that don't have HookData() (testing) if it excepts, return False
def get_subscription_attributes(SubscriptionArn, region=None, key=None, keyid=None, profile=None): ''' Returns all of the properties of a subscription. CLI example:: salt myminion boto3_sns.get_subscription_attributes somesubscription region=us-west-1 ''' conn = _get_conn(region=region, ke...
Returns all of the properties of a subscription. CLI example:: salt myminion boto3_sns.get_subscription_attributes somesubscription region=us-west-1
def create_task(self, task_name=None, script=None, hyper_parameters=None, saved_result_keys=None, **kwargs): """Uploads a task to the database, timestamp will be added automatically. Parameters ----------- task_name : str The task name. script : str File ...
Uploads a task to the database, timestamp will be added automatically. Parameters ----------- task_name : str The task name. script : str File name of the python script. hyper_parameters : dictionary The hyper parameters pass into the script. ...
def normalize_rrs(rrsets): """Lexically sort the order of every ResourceRecord in a ResourceRecords element so we don't generate spurious changes: ordering of e.g. NS records is irrelevant to the DNS line protocol, but XML sees it differently. Also rewrite any wildcard records to use the ascii hex code: somewh...
Lexically sort the order of every ResourceRecord in a ResourceRecords element so we don't generate spurious changes: ordering of e.g. NS records is irrelevant to the DNS line protocol, but XML sees it differently. Also rewrite any wildcard records to use the ascii hex code: somewhere deep inside route53 is som...
def writable(self): """True if the Slot is writable.""" return bool(lib.EnvSlotWritableP(self._env, self._cls, self._name))
True if the Slot is writable.
def load_drp(self, name, entry_point='numina.pipeline.1'): """Load all available DRPs in 'entry_point'.""" for drpins in self.iload(entry_point): if drpins.name == name: return drpins else: raise KeyError('{}'.format(name))
Load all available DRPs in 'entry_point'.
def send(self, request, stem=None): """Prepare and send a request Arguments: request: a Request object that is not yet prepared stem: a path to append to the root URL Returns: The response to the request """ if stem is not None: ...
Prepare and send a request Arguments: request: a Request object that is not yet prepared stem: a path to append to the root URL Returns: The response to the request
def squash_xml_to_text(elm, remove_namespaces=False): """Squash the given XML element (as `elm`) to a text containing XML. The outer most element/tag will be removed, but inner elements will remain. If `remove_namespaces` is specified, XML namespace declarations will be removed from the text. :para...
Squash the given XML element (as `elm`) to a text containing XML. The outer most element/tag will be removed, but inner elements will remain. If `remove_namespaces` is specified, XML namespace declarations will be removed from the text. :param elm: XML element :type elm: :class:`xml.etree.ElementTr...
def get_all_namespace_ids( self ): """ Get the set of all existing, READY namespace IDs. """ cur = self.db.cursor() namespace_ids = namedb_get_all_namespace_ids( cur ) return namespace_ids
Get the set of all existing, READY namespace IDs.
def _get_group_infos(self): """ Returns a (cached) list of group_info structures for the groups that our user is a member of. """ if self._group_infos is None: self._group_infos = self._group_type.user_groups( self._ldap_user, self._group_search ...
Returns a (cached) list of group_info structures for the groups that our user is a member of.
def update_source(ident, data): '''Update an harvest source''' source = get_source(ident) source.modify(**data) signals.harvest_source_updated.send(source) return source
Update an harvest source
def update_ports(self, ports, id_or_uri): """ Updates the switch ports. Only the ports under the management of OneView and those that are unlinked are supported for update. Note: This method is available for API version 300 or later. Args: ports: List of...
Updates the switch ports. Only the ports under the management of OneView and those that are unlinked are supported for update. Note: This method is available for API version 300 or later. Args: ports: List of Switch Ports. id_or_uri: Can be either the switch...
def wait_and_start_browser(host, port=None, cancel_event=None): """ Waits for the server to run and then opens the specified address in the browser. Set cancel_event to cancel the wait. """ if host == '0.0.0.0': host = 'localhost' if port is None: port = 80 if wait_for_serve...
Waits for the server to run and then opens the specified address in the browser. Set cancel_event to cancel the wait.
def transformToNative(obj): """ Turn obj.value into a list of dates, datetimes, or (datetime, timedelta) tuples. """ if obj.isNative: return obj obj.isNative = True if obj.value == '': obj.value = [] return obj tzinfo = ...
Turn obj.value into a list of dates, datetimes, or (datetime, timedelta) tuples.
def set_statements_pmid(self, pmid): """Set the evidence PMID of Statements that have been extracted. Parameters ---------- pmid : str or None The PMID to be used in the Evidence objects of the Statements that were extracted by the processor. """ ...
Set the evidence PMID of Statements that have been extracted. Parameters ---------- pmid : str or None The PMID to be used in the Evidence objects of the Statements that were extracted by the processor.
def json_output(cls, cs, score_dict, output_filename, ds_loc, limit, output_type='json'): ''' Generates JSON output for the ocmpliance score(s) @param cs Compliance Checker Suite @param score_groups List of results @param output_filename The fi...
Generates JSON output for the ocmpliance score(s) @param cs Compliance Checker Suite @param score_groups List of results @param output_filename The file path to output to @param ds_loc List of source datasets @param limit The degree of strictnes...
def get_lock(self, lockname, locktime=60, auto_renewal=False): ''' Gets a lock and returns if it can be stablished. Returns false otherwise ''' pid = os.getpid() caller = inspect.stack()[0][3] try: # rl = redlock.Redlock([{"host": settings.REDIS_SERVERS['std_redis']['hos...
Gets a lock and returns if it can be stablished. Returns false otherwise
def from_int(cls, retries, redirect=True, default=None): """ Backwards-compatibility for the old retries format.""" if retries is None: retries = default if default is not None else cls.DEFAULT if isinstance(retries, Retry): return retries redirect = bool(redire...
Backwards-compatibility for the old retries format.
def imrotate(img, angle, center=None, scale=1.0, border_value=0, auto_bound=False): """Rotate an image. Args: img (ndarray): Image to be rotated. angle (float): Rotation angle in degrees, positive values mean clockwise...
Rotate an image. Args: img (ndarray): Image to be rotated. angle (float): Rotation angle in degrees, positive values mean clockwise rotation. center (tuple): Center of the rotation in the source image, by default it is the center of the image. scale (float): ...
def construct(self, **bindings): """Constructs the graph and returns either a tensor or a sequence. Note: This method requires that this SequentialLayerBuilder holds a template. Args: **bindings: Arguments for every deferred parameter. Returns: The value that is placed into this. R...
Constructs the graph and returns either a tensor or a sequence. Note: This method requires that this SequentialLayerBuilder holds a template. Args: **bindings: Arguments for every deferred parameter. Returns: The value that is placed into this. Raises: ValueError: if this doesn't...
def update(self, scaling_group, name=None, cooldown=None, min_entities=None, max_entities=None, metadata=None): """ Updates an existing ScalingGroup. One or more of the attributes can be specified. NOTE: if you specify metadata, it will *replace* any existing metadata. ...
Updates an existing ScalingGroup. One or more of the attributes can be specified. NOTE: if you specify metadata, it will *replace* any existing metadata. If you want to add to it, you either need to pass the complete dict of metadata, or call the update_metadata() method.
def _get_struct_cxformwithalpha(self): """Get the values for the CXFORMWITHALPHA record.""" obj = _make_object("CXformWithAlpha") bc = BitConsumer(self._src) obj.HasAddTerms = bc.u_get(1) obj.HasMultTerms = bc.u_get(1) obj.NBits = nbits = bc.u_get(4) if obj.HasM...
Get the values for the CXFORMWITHALPHA record.
def get_msg_count_info(self, channel=Channel.CHANNEL_CH0): """ Reads the message counters of the specified CAN channel. :param int channel: CAN channel, which is to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :return: Tuple with number of CAN messag...
Reads the message counters of the specified CAN channel. :param int channel: CAN channel, which is to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :return: Tuple with number of CAN messages sent and received. :rtype: tuple(int, int)
def get_touch_dict(self, ind=None, out=bool): """ Get a dictionnary of Cls_Name struct with indices of Rays touching Only includes Struct object with compute = True (as returned by self.lStruct__computeInOut_computeInOut) Also return the associated colors If in is not None, ...
Get a dictionnary of Cls_Name struct with indices of Rays touching Only includes Struct object with compute = True (as returned by self.lStruct__computeInOut_computeInOut) Also return the associated colors If in is not None, the indices for each Struct are split between: ...
def parse_object_type_extension(lexer: Lexer) -> ObjectTypeExtensionNode: """ObjectTypeExtension""" start = lexer.token expect_keyword(lexer, "extend") expect_keyword(lexer, "type") name = parse_name(lexer) interfaces = parse_implements_interfaces(lexer) directives = parse_directives(lexer, ...
ObjectTypeExtension
def _resample_nu(self, tau, N_steps=100, prop_std=0.1, alpha=1, beta=1): """ Update the degree of freedom parameter with Metropolis-Hastings. Assume a prior nu ~ Ga(alpha, beta) and use a proposal nu' ~ N(nu, prop_std^2). If proposals are negative, reject automatically due to l...
Update the degree of freedom parameter with Metropolis-Hastings. Assume a prior nu ~ Ga(alpha, beta) and use a proposal nu' ~ N(nu, prop_std^2). If proposals are negative, reject automatically due to likelihood.
def _format_attrs(self): """ Formats the self.attrs #OrderedDict """ _bold = bold _colorize = colorize if not self.pretty: _bold = lambda x: x _colorize = lambda x, c: x attrs = [] add_attr = attrs.append if self.doc and hasattr(self.obj, "...
Formats the self.attrs #OrderedDict
def relativize(self, absolute_address, target_region_id=None): """ Convert an absolute address to the memory offset in a memory region. Note that if an address belongs to heap region is passed in to a stack region map, it will be converted to an offset included in the closest stack fram...
Convert an absolute address to the memory offset in a memory region. Note that if an address belongs to heap region is passed in to a stack region map, it will be converted to an offset included in the closest stack frame, and vice versa for passing a stack address to a heap region. Therefore y...
def lock(self, block=True): """ Lock connection from being used else where """ self._locked = True return self._lock.acquire(block)
Lock connection from being used else where
def download_files(file_list): """Download the latest data. """ for _, source_data_file in file_list: sql_gz_name = source_data_file['name'].split('/')[-1] msg = 'Downloading: %s' % (sql_gz_name) log.debug(msg) new_data = objectstore.get_object( handelsregister_conn,...
Download the latest data.
def update_fit_boxes(self, new_fit=False): """ alters fit_box and mean_fit_box lists to match with changes in specimen or new/removed interpretations Parameters ---------- new_fit : boolean representing if there is a new fit Alters ------ fit_box...
alters fit_box and mean_fit_box lists to match with changes in specimen or new/removed interpretations Parameters ---------- new_fit : boolean representing if there is a new fit Alters ------ fit_box selection, tmin_box selection, tmax_box selection, mea...
def _deftype_to_py_ast( # pylint: disable=too-many-branches ctx: GeneratorContext, node: DefType ) -> GeneratedPyAST: """Return a Python AST Node for a `deftype*` expression.""" assert node.op == NodeOp.DEFTYPE type_name = munge(node.name) ctx.symbol_table.new_symbol(sym.symbol(node.name), type_nam...
Return a Python AST Node for a `deftype*` expression.
def make_slow_waves(events, data, time, s_freq): """Create dict for each slow wave, based on events of time points. Parameters ---------- events : ndarray (dtype='int') N x 5 matrix with start, trough, zero, peak, end samples data : ndarray (dtype='float') vector with the data t...
Create dict for each slow wave, based on events of time points. Parameters ---------- events : ndarray (dtype='int') N x 5 matrix with start, trough, zero, peak, end samples data : ndarray (dtype='float') vector with the data time : ndarray (dtype='float') vector with time p...
def disable(states): ''' Disable state runs. CLI Example: .. code-block:: bash salt '*' state.disable highstate salt '*' state.disable highstate,test.succeed_without_changes .. note:: To disable a state file from running provide the same name that would be passed...
Disable state runs. CLI Example: .. code-block:: bash salt '*' state.disable highstate salt '*' state.disable highstate,test.succeed_without_changes .. note:: To disable a state file from running provide the same name that would be passed in a state.sls call. sa...
def run_command(self, data): """ check the given command and send to the correct dispatcher """ command = data.get("command") if self.debug: self.py3_wrapper.log("Running remote command %s" % command) if command == "refresh": self.refresh(data) ...
check the given command and send to the correct dispatcher