code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def get_image_path(repo_url, trailing_path): '''get_image_path will determine an image path based on a repo url, removing any token, and taking into account urls that end with .git. :param repo_url: the repo url to parse: :param trailing_path: the trailing path (commit then hash is common) ''' r...
get_image_path will determine an image path based on a repo url, removing any token, and taking into account urls that end with .git. :param repo_url: the repo url to parse: :param trailing_path: the trailing path (commit then hash is common)
def add_deploy(state, deploy_func, *args, **kwargs): ''' Prepare & add an deploy to pyinfra.state by executing it on all hosts. Args: state (``pyinfra.api.State`` obj): the deploy state to add the operation deploy_func (function): the operation function from one of the modules, ie `...
Prepare & add an deploy to pyinfra.state by executing it on all hosts. Args: state (``pyinfra.api.State`` obj): the deploy state to add the operation deploy_func (function): the operation function from one of the modules, ie ``server.user`` args/kwargs: passed to the operation funct...
def _init_cycle_dict(self): """ Populate a cycle dict """ dict_arr = np.zeros(self.epochs, dtype=int) length_arr = np.zeros(self.epochs, dtype=int) start_arr = np.zeros(self.epochs, dtype=int) c_len = self.cycle_len idx = 0 for i in range(self.cycles): ...
Populate a cycle dict
def contributions_from_model_image_and_galaxy_image(self, model_image, galaxy_image, minimum_value=0.0): """Compute the contribution map of a galaxy, which represents the fraction of flux in each pixel that the \ galaxy is attributed to contain, scaled to the *contribution_factor* hyper-parameter. ...
Compute the contribution map of a galaxy, which represents the fraction of flux in each pixel that the \ galaxy is attributed to contain, scaled to the *contribution_factor* hyper-parameter. This is computed by dividing that galaxy's flux by the total flux in that pixel, and then scaling by the \ ...
def intersect(a, b): """ Check if two rectangles intersect """ if a[x0] == a[x1] or a[y0] == a[y1]: return False if b[x0] == b[x1] or b[y0] == b[y1]: return False return a[x0] <= b[x1] and b[x0] <= a[x1] and a[y0] <= b[y1] and b[y0] <= a[y1]
Check if two rectangles intersect
def _set_bfd_static_route(self, v, load=False): """ Setter method for bfd_static_route, mapped from YANG variable /rbridge_id/vrf/address_family/ip/unicast/ip/route/static/bfd/bfd_static_route (list) If this variable is read-only (config: false) in the source YANG file, then _set_bfd_static_route is con...
Setter method for bfd_static_route, mapped from YANG variable /rbridge_id/vrf/address_family/ip/unicast/ip/route/static/bfd/bfd_static_route (list) If this variable is read-only (config: false) in the source YANG file, then _set_bfd_static_route is considered as a private method. Backends looking to populat...
def info(self): """get information about the terms in the term list Parameters ---------- Returns ------- dict containing information to duplicate the term list """ info = {'term_type': 'term_list', 'verbose': self.verbose} info.update({'terms':[...
get information about the terms in the term list Parameters ---------- Returns ------- dict containing information to duplicate the term list
def RunMetadata(self, run, tag): """Get the session.run() metadata associated with a TensorFlow run and tag. Args: run: A string name of a TensorFlow run. tag: A string name of the tag associated with a particular session.run(). Raises: KeyError: If the run is not found, or the tag is no...
Get the session.run() metadata associated with a TensorFlow run and tag. Args: run: A string name of a TensorFlow run. tag: A string name of the tag associated with a particular session.run(). Raises: KeyError: If the run is not found, or the tag is not available for the given run. ...
def close(self, status=1000, reason=u''): """ Send Close frame to the client. The underlying socket is only closed when the client acknowledges the Close frame. status is the closing identifier. reason is the reason for the close. """ try: ...
Send Close frame to the client. The underlying socket is only closed when the client acknowledges the Close frame. status is the closing identifier. reason is the reason for the close.
def _check_valid_condition(self, get_params): """ Check if the condition has been met. We need to make sure that we are of the correct type. """ try: variable = get_params(self.variable) except: # noqa e722 variable = None value = self.val...
Check if the condition has been met. We need to make sure that we are of the correct type.
def query(self, tableClass, comparison=None, limit=None, offset=None, sort=None): """ Return a generator of instances of C{tableClass}, or tuples of instances if C{tableClass} is a tuple of classes. Examples:: fastCars = s.query(Vehicle, ...
Return a generator of instances of C{tableClass}, or tuples of instances if C{tableClass} is a tuple of classes. Examples:: fastCars = s.query(Vehicle, axiom.attributes.AND( Vehicle.wheels == 4, Vehicle.maxKPH > 200), ...
def import_module(self, name): """Import a module into the bridge.""" if name not in self._objects: module = _import_module(name) self._objects[name] = module self._object_references[id(module)] = name return self._objects[name]
Import a module into the bridge.
def get_raw(self, url: str, _attempt=1) -> requests.Response: """Downloads a file anonymously. :raises QueryReturnedNotFoundException: When the server responds with a 404. :raises QueryReturnedForbiddenException: When the server responds with a 403. :raises ConnectionException: When dow...
Downloads a file anonymously. :raises QueryReturnedNotFoundException: When the server responds with a 404. :raises QueryReturnedForbiddenException: When the server responds with a 403. :raises ConnectionException: When download failed. .. versionadded:: 4.2.1
def check_file(self, filename): # type: (str) -> bool """ Check if ``filename`` can be read. Will return boolean which is True if the file can be read, False otherwise. """ if not exists(filename): return False # Check if the file is version-compatibl...
Check if ``filename`` can be read. Will return boolean which is True if the file can be read, False otherwise.
def to_dict(self): """ Convert the object into a json serializable dictionary. Note: It uses the private method _save_to_input_dict of the parent. :return dict: json serializable dictionary containing the needed information to instantiate the object """ #TODO: Implemen...
Convert the object into a json serializable dictionary. Note: It uses the private method _save_to_input_dict of the parent. :return dict: json serializable dictionary containing the needed information to instantiate the object
def coerce_author(value): """ Coerce strings to :class:`Author` objects. :param value: A string or :class:`Author` object. :returns: An :class:`Author` object. :raises: :exc:`~exceptions.ValueError` when `value` isn't a string or :class:`Author` object. """ # Author objects pas...
Coerce strings to :class:`Author` objects. :param value: A string or :class:`Author` object. :returns: An :class:`Author` object. :raises: :exc:`~exceptions.ValueError` when `value` isn't a string or :class:`Author` object.
def word_groups_for_language(language_code): """ Return the math word groups for a language code. The language_code should be an ISO 639-2 language code. https://www.loc.gov/standards/iso639-2/php/code_list.php """ if language_code not in LANGUAGE_CODES: message = '{} is not an availabl...
Return the math word groups for a language code. The language_code should be an ISO 639-2 language code. https://www.loc.gov/standards/iso639-2/php/code_list.php
def signMessage(self, message): """Add a signature (and a signed list) to a message. @return: a new Message object with a signature @rtype: L{openid.message.Message} """ if (message.hasKey(OPENID_NS, 'sig') or message.hasKey(OPENID_NS, 'signed')): raise V...
Add a signature (and a signed list) to a message. @return: a new Message object with a signature @rtype: L{openid.message.Message}
def extend_env(extra_env): """ Copies and extends the current environment with the values present in `extra_env`. """ env = os.environ.copy() env.update(extra_env) return env
Copies and extends the current environment with the values present in `extra_env`.
def eval_grad(self): """Compute gradient in Fourier domain.""" # Compute X D - S Ryf = self.eval_Rf(self.Yf) gradf = sl.inner(np.conj(self.Zf), Ryf, axis=self.cri.axisK) # Multiple channel signal, single channel dictionary if self.cri.C > 1 and self.cri.Cd == 1: ...
Compute gradient in Fourier domain.
def newbie(cls, *args, **kwargs): """ Create a newbie class, with all the skills needed """ parser = cls(*args, **kwargs) subparser = parser.add_subparsers(dest='command') parents = [parser.pparser, parser.output_parser] sparser = subparser.add_parser('search', help='Perform new...
Create a newbie class, with all the skills needed
def form_field_definitions(self): """Hook optional_login extractor if necessary for form defaults. """ schema = copy.deepcopy(form_field_definitions.user) uid, login = self._get_auth_attrs() if uid != login: field = schema.get(login, schema['default']) if ...
Hook optional_login extractor if necessary for form defaults.
def read_adc_difference(self, differential): """Read the difference between two channels. Differential should be a value of: - 0: Return channel 0 minus channel 1 - 1: Return channel 1 minus channel 0 - 2: Return channel 2 minus channel 3 - 3: Return channel 3 mi...
Read the difference between two channels. Differential should be a value of: - 0: Return channel 0 minus channel 1 - 1: Return channel 1 minus channel 0 - 2: Return channel 2 minus channel 3 - 3: Return channel 3 minus channel 2 - 4: Return channel 4 minus chan...
def getRenderers(filename): """For a given DP, returns a list of renderer ids giving the renderers that support the source file type""" global available_renderers renderers = [] for rdrid, (renderer, module) in available_renderers.items(): try: priority = renderer.canRender(filen...
For a given DP, returns a list of renderer ids giving the renderers that support the source file type
def product_name(self): """Returns the product name of the connected J-Link. Args: self (JLink): the ``JLink`` instance Returns: Product name. """ buf = (ctypes.c_char * self.MAX_BUF_SIZE)() self._dll.JLINKARM_EMU_GetProductName(buf, self.MAX_BUF_SIZ...
Returns the product name of the connected J-Link. Args: self (JLink): the ``JLink`` instance Returns: Product name.
def set_chat_photo( self, chat_id: Union[int, str], photo: str ) -> bool: """Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. You must be an administrator in the chat for this to work and must have the appropriate adm...
Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. You must be an administrator in the chat for this to work and must have the appropriate admin rights. Note: In regular groups (non-supergroups), this method will only work if the "All...
def notification_message(cls, item): '''Convert an RPCRequest item to a message.''' assert isinstance(item, Notification) return cls.encode_payload(cls.request_payload(item, None))
Convert an RPCRequest item to a message.
def mmGetCellTracePlot(self, cellTrace, cellCount, activityType, title="", showReset=False, resetShading=0.25): """ Returns plot of the cell activity. Note that if many timesteps of activities are input, matplotlib's image interpolation may omit activities (columns in the image)...
Returns plot of the cell activity. Note that if many timesteps of activities are input, matplotlib's image interpolation may omit activities (columns in the image). @param cellTrace (list) a temporally ordered list of sets of cell activities @param cellCount (i...
def features(self): """ lazy fetch and cache features """ if self._features is None: metadata = self.metadata() if "features" in metadata: self._features = metadata["features"] else: self._features = [] return se...
lazy fetch and cache features
def to_keypoints(self): """ Convert the line string points to keypoints. Returns ------- list of imgaug.augmentables.kps.Keypoint Points of the line string as keypoints. """ # TODO get rid of this deferred import from imgaug.augmentables.kps ...
Convert the line string points to keypoints. Returns ------- list of imgaug.augmentables.kps.Keypoint Points of the line string as keypoints.
def read_data_sets(train_dir, data_type="train"): """ Parse or download mnist data if train_dir is empty. :param: train_dir: The directory storing the mnist data :param: data_type: Reading training set or testing set.It can be either "train" or "test" :return: ``` (ndarray, ndarray) repr...
Parse or download mnist data if train_dir is empty. :param: train_dir: The directory storing the mnist data :param: data_type: Reading training set or testing set.It can be either "train" or "test" :return: ``` (ndarray, ndarray) representing (features, labels) features is a 4D unit8 numpy a...
def get_folder_details(self, folder): '''Get information on a given folder. Args: folder (str): The UUID of the requested folder. Returns: A dictionary of the folder details if found:: { u'created_by': u'303447', ...
Get information on a given folder. Args: folder (str): The UUID of the requested folder. Returns: A dictionary of the folder details if found:: { u'created_by': u'303447', u'created_on': u'2017-03-21T14:06:32.293902Z', ...
def in_filter_get(self, address): """This method gets in-bound filters of the specified neighbor. ``address`` specifies the IP address of the neighbor. Returns a list object containing an instance of Filter sub-class """ func_name = 'neighbor.in_filter.get' param = { ...
This method gets in-bound filters of the specified neighbor. ``address`` specifies the IP address of the neighbor. Returns a list object containing an instance of Filter sub-class
def list_containers_info(self, limit=None, marker=None): """Returns a list of info on Containers. For each container, a dict containing the following keys is returned: \code name - the name of the container count - the number of objects in the container bytes...
Returns a list of info on Containers. For each container, a dict containing the following keys is returned: \code name - the name of the container count - the number of objects in the container bytes - the total bytes in the container
def mget(self, keys, *args): """ Returns a list of values ordered identically to ``keys`` """ args = list_or_args(keys, args) options = {} if not args: options[EMPTY_RESPONSE] = [] return self.execute_command('MGET', *args, **options)
Returns a list of values ordered identically to ``keys``
def set(self, section, key, value): ''' Set the value for a key in the given section. It will check the type of the value if it is available. If the value is not from the given type it will be transformed to the type. An exception will be thrown if there is a problem with the...
Set the value for a key in the given section. It will check the type of the value if it is available. If the value is not from the given type it will be transformed to the type. An exception will be thrown if there is a problem with the conversion. @param sec...
def launch_subshell(self, shell_cls, cmd, args, *, prompt = None, context = {}): """Launch a subshell. The doc string of the cmdloop() method explains how shell histories and history files are saved and restored. The design of the _ShellBase class encourage launching of sub...
Launch a subshell. The doc string of the cmdloop() method explains how shell histories and history files are saved and restored. The design of the _ShellBase class encourage launching of subshells through the subshell() decorator function. Nonetheless, the user has the option o...
def handle_error(self, message: str, e: mastodon.MastodonError) -> OutputRecord: """Handle error while trying to do something.""" self.lerror(f"Got an error! {e}") # Handle errors if we know how. try: code = e[0]["code"] if code in self.handled_errors: ...
Handle error while trying to do something.
def get_child(self, child_name): # pylint: disable=no-self-use """ returns the object with the name supplied """ child = self.children.get(child_name, None) if child: return child raise ValueError("Value {} not in this tree".format(child_name))
returns the object with the name supplied
def update_configurable(self, configurable_class, name, config): """ Callback fired when a configurable instance is updated. Looks up the existing configurable in the proper "registry" and `apply_config()` is called on it. If a method named "on_<configurable classname>_update" ...
Callback fired when a configurable instance is updated. Looks up the existing configurable in the proper "registry" and `apply_config()` is called on it. If a method named "on_<configurable classname>_update" is defined it is called in the work pool and passed the configurable's name, ...
def get_stream(self, bucket, label, as_stream=True): '''Get a bitstream for the given bucket:label combination. :param bucket: the bucket to use. :return: bitstream as a file-like object ''' if self.mode == "w": raise OFSException("Cannot read from archive in 'w' mod...
Get a bitstream for the given bucket:label combination. :param bucket: the bucket to use. :return: bitstream as a file-like object
def _set_suffix_links(self): ''' Sets all suffix links in all nodes in this trie. ''' self._suffix_links_set = True for current, parent in self.bfs(): # skip the root node if parent is None: continue current.longest_prefix = par...
Sets all suffix links in all nodes in this trie.
def add_tunnel_port(self, name, tunnel_type, remote_ip, local_ip=None, key=None, ofport=None): """ Creates a tunnel port. :param name: Port name to be created :param tunnel_type: Type of tunnel (gre or vxlan) :param remote_ip: Remote IP address of tunnel ...
Creates a tunnel port. :param name: Port name to be created :param tunnel_type: Type of tunnel (gre or vxlan) :param remote_ip: Remote IP address of tunnel :param local_ip: Local IP address of tunnel :param key: Key of GRE or VNI of VxLAN :param ofport: Requested OpenFlo...
def _unicode(p): """ Used when force_unicode is True (default), the tags and values in the dict will be coerced as 'str' (or 'unicode' with Python2). In Python3 they can otherwise end up as a mixtures of 'str' and 'bytes'. """ q = {} for tag in p: vals = [] for v in p[tag]: ...
Used when force_unicode is True (default), the tags and values in the dict will be coerced as 'str' (or 'unicode' with Python2). In Python3 they can otherwise end up as a mixtures of 'str' and 'bytes'.
def enumerate(self, **kwargs): '''Iterate through all possible sequences (lists). By default, will stop after 50 items have been yielded. This value can be change by supplying a different value via the max_enumerate kwarg. ''' for item in self.set.enumerate(**kwargs): ...
Iterate through all possible sequences (lists). By default, will stop after 50 items have been yielded. This value can be change by supplying a different value via the max_enumerate kwarg.
def _fetch_AlignmentMapper(self, tx_ac, alt_ac=None, alt_aln_method=None): """convenience version of VariantMapper._fetch_AlignmentMapper that derives alt_ac from transcript, assembly, and alt_aln_method used to instantiate the AssemblyMapper instance """ if alt_ac is None: ...
convenience version of VariantMapper._fetch_AlignmentMapper that derives alt_ac from transcript, assembly, and alt_aln_method used to instantiate the AssemblyMapper instance
def retrieve_tmpl(args): """Retrieve template. Argument: args: arguments object """ password = get_password(args) token = connect.get_token(args.username, password, args.server) if args.__dict__.get('template'): # When specified template identifier template = args.temp...
Retrieve template. Argument: args: arguments object
def server_rules(self): """ Reads the server rules from the client and returns it. """ sftp = self.client.open_sftp() try: rule_path = self.rule_location try: stat_entry = sftp.stat(rule_path) if stat.S_ISDIR(stat_en...
Reads the server rules from the client and returns it.
def render_services_ctrl(self, request): """ Example for rendering the service control panel row You can override the default template and create a custom one if you wish. :param request: :return: """ urls = self.Urls() urls.auth_activate = 'auth_e...
Example for rendering the service control panel row You can override the default template and create a custom one if you wish. :param request: :return:
def _move_to_top(self, pos): """Move element at given position to top of queue.""" if pos > 0: self.queue.rotate(-pos) item = self.queue.popleft() self.queue.rotate(pos) self.queue.appendleft(item)
Move element at given position to top of queue.
def _do(self, cmd, *args, **kwargs): """Semi-raw execution of a matlab command. Smartly handle calls to matlab, figure out what to do with `args`, and when to use function call syntax and not. If no `args` are specified, the ``cmd`` not ``result = cmd()`` form is used in Matlab...
Semi-raw execution of a matlab command. Smartly handle calls to matlab, figure out what to do with `args`, and when to use function call syntax and not. If no `args` are specified, the ``cmd`` not ``result = cmd()`` form is used in Matlab -- this also makes literal Matlab commands lega...
def speech_src(self): """Retrieves the URL/filename of the audio or video file associated with the element. The source is inherited from ancestor elements if none is specified. For this reason, always use this method rather than access the ``src`` attribute directly. Returns: str o...
Retrieves the URL/filename of the audio or video file associated with the element. The source is inherited from ancestor elements if none is specified. For this reason, always use this method rather than access the ``src`` attribute directly. Returns: str or None if not found
def orchestration_save(self, mode="shallow", custom_params=None): """Orchestration Save command :param mode: :param custom_params: json with all required action to configure or remove vlans from certain port :return Serialized OrchestrationSavedArtifact to json :rtype json ...
Orchestration Save command :param mode: :param custom_params: json with all required action to configure or remove vlans from certain port :return Serialized OrchestrationSavedArtifact to json :rtype json
def start_exp(): """ Serves up the experiment applet. """ if not (('hitId' in request.args) and ('assignmentId' in request.args) and ('workerId' in request.args) and ('mode' in request.args)): raise ExperimentError('hit_assign_worker_id_not_set_in_exp') hit_id = request.args['hitId'] ...
Serves up the experiment applet.
def build_block(self): """ Assembles the candidate block into it's finalized form for broadcast. """ header_bytes = self.block_header.SerializeToString() block = Block(header=header_bytes, header_signature=self._header_signature) block.batches.extend...
Assembles the candidate block into it's finalized form for broadcast.
def _discover_ontology(ontology_path): """Look for the file in known places. :param ontology: path name or url :type ontology: str :return: absolute path of a file if found, or None """ last_part = os.path.split(os.path.abspath(ontology_path))[1] possible_patterns = [last_part, last_part.l...
Look for the file in known places. :param ontology: path name or url :type ontology: str :return: absolute path of a file if found, or None
def compute_chunksize(df, num_splits, default_block_size=32, axis=None): """Computes the number of rows and/or columns to include in each partition. Args: df: The DataFrame to split. num_splits: The maximum number of splits to separate the DataFrame into. default_block_size: Minimum num...
Computes the number of rows and/or columns to include in each partition. Args: df: The DataFrame to split. num_splits: The maximum number of splits to separate the DataFrame into. default_block_size: Minimum number of rows/columns (default set to 32x32). axis: The axis to split. (0:...
def get_devices(self, refresh=False): """Get all devices from Abode.""" if refresh or self._devices is None: if self._devices is None: self._devices = {} _LOGGER.info("Updating all devices...") response = self.send_request("get", CONST.DEVICES_URL) ...
Get all devices from Abode.
def get_vowel(syll): '''Return the firstmost vowel in 'syll'.''' return re.search(r'([ieaouäöy]{1})', syll, flags=FLAGS).group(1).upper()
Return the firstmost vowel in 'syll'.
def _chunk(self, size): """ Chunk the underlying collection. :param size: The chunk size :type size: int :rtype: Collection """ items = self.items return [items[i:i + size] for i in range(0, len(items), size)]
Chunk the underlying collection. :param size: The chunk size :type size: int :rtype: Collection
def kernel(x1, x2, method='gaussian', sigma=1, **kwargs): """Compute kernel matrix""" if method.lower() in ['gaussian', 'gauss', 'rbf']: K = np.exp(-dist(x1, x2) / (2 * sigma**2)) return K
Compute kernel matrix
def register(self, command: str, handler: Any): """ Register a new handler for a specific slash command Args: command: Slash command handler: Callback """ if not command.startswith("/"): command = f"/{command}" LOG.info("Registering ...
Register a new handler for a specific slash command Args: command: Slash command handler: Callback
def _add_default_source(self): """Add the package's default configuration settings. This looks for a YAML file located inside the package for the module `modname` if it was given. """ if self.modname: if self._package_path: filename = os.path.join(self...
Add the package's default configuration settings. This looks for a YAML file located inside the package for the module `modname` if it was given.
def get_log_entry_log_session(self, proxy): """Gets the session for retrieving log entry to log mappings. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.logging.LogEntryLogSession) - a ``LogEntryLogSession`` raise: NullArgument - ``proxy`` is ``null`` r...
Gets the session for retrieving log entry to log mappings. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.logging.LogEntryLogSession) - a ``LogEntryLogSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to complete request ...
def _decrypt(self, rj, token): """ Decrypt an encrypted JsonWebToken :param rj: :py:class:`cryptojwt.jwe.JWE` instance :param token: The encrypted JsonWebToken :return: """ if self.iss: keys = self.key_jar.get_jwt_decrypt_keys(rj.jwt, aud=self.iss) ...
Decrypt an encrypted JsonWebToken :param rj: :py:class:`cryptojwt.jwe.JWE` instance :param token: The encrypted JsonWebToken :return:
def get_value(self, tau): """ Compute the value of the term for an array of lags Args: tau (array[...]): An array of lags where the term should be evaluated. Returns: The value of the term for each ``tau``. This will have the same sha...
Compute the value of the term for an array of lags Args: tau (array[...]): An array of lags where the term should be evaluated. Returns: The value of the term for each ``tau``. This will have the same shape as ``tau``.
def pick_input_v1(self): """Updates |Input| based on |Total|.""" flu = self.sequences.fluxes.fastaccess inl = self.sequences.inlets.fastaccess flu.input = 0. for idx in range(inl.len_total): flu.input += inl.total[idx][0]
Updates |Input| based on |Total|.
def setMaximumHeight(self, height): """ Sets the maximum height value to the inputed height and emits the \ sizeConstraintChanged signal. :param height | <int> """ super(XView, self).setMaximumHeight(height) if ( not self.signalsBlocked() ):...
Sets the maximum height value to the inputed height and emits the \ sizeConstraintChanged signal. :param height | <int>
def encapsulate_processing(object): """ Encapsulates a processing operation. :param object: Object to decorate. :type object: object :return: Object. :rtype: object """ @functools.wraps(object) def encapsulate_processing_wrapper(*args, **kwargs): """ Encapsulates a ...
Encapsulates a processing operation. :param object: Object to decorate. :type object: object :return: Object. :rtype: object
def set_stream(self, stream_id): """Set group stream.""" self._group['stream_id'] = stream_id yield from self._server.group_stream(self.identifier, stream_id) _LOGGER.info('set stream to %s on %s', stream_id, self.friendly_name)
Set group stream.
def list_queues(region, opts=None, user=None): ''' List the queues in the selected region. region Region to list SQS queues for opts : None Any additional options to add to the command line user : None Run hg as a user other than what the minion runs as CLI Example: ...
List the queues in the selected region. region Region to list SQS queues for opts : None Any additional options to add to the command line user : None Run hg as a user other than what the minion runs as CLI Example: salt '*' aws_sqs.list_queues <region>
def get_works(self): """Return the author's works. :return: a list of `HucitWork` instances. """ Work = self._session.get_class(surf.ns.EFRBROO['F1_Work']) return list(Work.all())
Return the author's works. :return: a list of `HucitWork` instances.
def load_url(self, url, force=False, reload_seconds=0, callback_function=None): """ Starts loading a URL with an optional reload time in seconds. Setting force to True may load pages which block iframe embedding, but will prevent reload from working and ...
Starts loading a URL with an optional reload time in seconds. Setting force to True may load pages which block iframe embedding, but will prevent reload from working and will cause calls to load_url() to reload the app.
def end_node(self): """ Get end node :return: StructuredNode """ return db.cypher_query("MATCH (aNode) " "WHERE id(aNode)={nodeid} " "RETURN aNode".format(nodeid=self._end_node_id), reso...
Get end node :return: StructuredNode
def concat(self, to_concat, new_axis): """ Concatenate a list of SingleBlockManagers into a single SingleBlockManager. Used for pd.concat of Series objects with axis=0. Parameters ---------- to_concat : list of SingleBlockManagers new_axis : Index of the...
Concatenate a list of SingleBlockManagers into a single SingleBlockManager. Used for pd.concat of Series objects with axis=0. Parameters ---------- to_concat : list of SingleBlockManagers new_axis : Index of the result Returns ------- SingleBloc...
def _recordAndPrintHeadline(self, test, error_class, artifact): """Record that an error-like thing occurred, and print a summary. Store ``artifact`` with the record. Return whether the test result is any sort of failure. """ # We duplicate the errorclass handling from super ra...
Record that an error-like thing occurred, and print a summary. Store ``artifact`` with the record. Return whether the test result is any sort of failure.
def matchingfiles(self, projectpath): """Checks if the input conditions are satisfied, i.e the required input files are present. We use the symbolic links .*.INPUTTEMPLATE.id.seqnr to determine this. Returns a list of matching results (seqnr, filename, inputtemplate).""" results = [] if project...
Checks if the input conditions are satisfied, i.e the required input files are present. We use the symbolic links .*.INPUTTEMPLATE.id.seqnr to determine this. Returns a list of matching results (seqnr, filename, inputtemplate).
def register(self, app, options, first_registration=False): """Called by :meth:`Flask.register_blueprint` to register a blueprint on the application. This can be overridden to customize the register behavior. Keyword arguments from :func:`~flask.Flask.register_blueprint` are directly for...
Called by :meth:`Flask.register_blueprint` to register a blueprint on the application. This can be overridden to customize the register behavior. Keyword arguments from :func:`~flask.Flask.register_blueprint` are directly forwarded to this method in the `options` dictionary.
def create(cls, name, ncpus=None): """Create a Moap instance based on the predictor name. Parameters ---------- name : str Name of the predictor (eg. Xgboost, BayesianRidge, ...) ncpus : int, optional Number of threads. Default is the number spec...
Create a Moap instance based on the predictor name. Parameters ---------- name : str Name of the predictor (eg. Xgboost, BayesianRidge, ...) ncpus : int, optional Number of threads. Default is the number specified in the config. Returns ...
def is_sufficient(self, device): """ Returns whether the device is sufficient for this requirement. :param device: A GPUDevice instance. :type device: GPUDevice :return: True if the requirement is fulfilled otherwise False """ sufficient = True if (self....
Returns whether the device is sufficient for this requirement. :param device: A GPUDevice instance. :type device: GPUDevice :return: True if the requirement is fulfilled otherwise False
def to_unicode(value): """ Converts a string argument to a unicode string. If the argument is already a unicode string or None, it is returned unchanged. Otherwise it must be a byte string and is decoded as utf8. """ if isinstance(value, _TO_UNICODE_TYPES): return value if not isins...
Converts a string argument to a unicode string. If the argument is already a unicode string or None, it is returned unchanged. Otherwise it must be a byte string and is decoded as utf8.
def state_set(self, state, use_active_range=False): """Sets the internal state of the df Example: >>> import vaex >>> df = vaex.from_scalars(x=1, y=2) >>> df # x y r 0 1 2 2.23607 >>> df['r'] = (df.x**2 + df.y**2)**0.5 >>>...
Sets the internal state of the df Example: >>> import vaex >>> df = vaex.from_scalars(x=1, y=2) >>> df # x y r 0 1 2 2.23607 >>> df['r'] = (df.x**2 + df.y**2)**0.5 >>> state = df.state_get() >>> state {'active_rang...
def _clean_frequency(frequency): """Converts a frequency value to an integer. Raises an error if an invalid type is given. :param frequency: A frequency :type frequency: int or datetime.timedelta :rtype: int """ if isinstance(frequency, int): return frequency elif isinstance(fre...
Converts a frequency value to an integer. Raises an error if an invalid type is given. :param frequency: A frequency :type frequency: int or datetime.timedelta :rtype: int
def get_encoding_from_headers(headers): """Returns encodings from given HTTP Header Dict. :param headers: dictionary to extract encoding from. """ content_type = headers.get('content-type') if not content_type: return None content_type, params = cgi.parse_header(content_type) if...
Returns encodings from given HTTP Header Dict. :param headers: dictionary to extract encoding from.
def warn(self, collection): """Checks the module for documentation and best-practice warnings.""" super(CodeElement, self).warn(collection) if not "implicit none" in self.modifiers: collection.append("WARNING: implicit none not set in {}".format(self.name))
Checks the module for documentation and best-practice warnings.
def with_tz(request): """ Get the time with TZ enabled """ dt = datetime.now() t = Template('{% load tz %}{% localtime on %}{% get_current_timezone as TIME_ZONE %}{{ TIME_ZONE }}{% endlocaltime %}') c = RequestContext(request) response = t.render(c) return HttpResponse(response)
Get the time with TZ enabled
def json(self): """ Return a JSON-serializable representation of this result. The output of this function can be converted to a serialized string with :any:`json.dumps`. """ data = { "segment_name": self.segment_name, "formula": self.formula, ...
Return a JSON-serializable representation of this result. The output of this function can be converted to a serialized string with :any:`json.dumps`.
def convert_nsarg( nsarg: str, api_url: str = None, namespace_targets: Mapping[str, List[str]] = None, canonicalize: bool = False, decanonicalize: bool = False, ) -> str: """[De]Canonicalize NSArg Args: nsarg (str): bel statement string or partial string (e.g. subject or object) ...
[De]Canonicalize NSArg Args: nsarg (str): bel statement string or partial string (e.g. subject or object) api_url (str): BEL.bio api url to use, e.g. https://api.bel.bio/v1 namespace_targets (Mapping[str, List[str]]): formatted as in configuration file example canonicalize (bool): u...
def _dist_obs_oracle(oracle, query, trn_list): """A helper function calculating distances between a feature and frames in oracle.""" a = np.subtract(query, [oracle.f_array[t] for t in trn_list]) return (a * a).sum(axis=1)
A helper function calculating distances between a feature and frames in oracle.
def set_speech_ssml(self, ssml): """Set response output speech as SSML type. Args: ssml: str. Response speech used when type is 'SSML', should be formatted with Speech Synthesis Markup Language. Cannot exceed 8,000 characters. """ self.respons...
Set response output speech as SSML type. Args: ssml: str. Response speech used when type is 'SSML', should be formatted with Speech Synthesis Markup Language. Cannot exceed 8,000 characters.
def _fake_enumerateclassnames(self, namespace, **params): """ Implements a mock server responder for :meth:`~pywbem.WBEMConnection.EnumerateClassNames`. Enumerates the classnames of the classname in the 'classname' parameter or from the top of the tree if 'classname is None. ...
Implements a mock server responder for :meth:`~pywbem.WBEMConnection.EnumerateClassNames`. Enumerates the classnames of the classname in the 'classname' parameter or from the top of the tree if 'classname is None. Returns: return tuple including list of classnames ...
def file_code(function_index=1, function_name=None): """ This will return the code of the calling function function_index of 2 will give the parent of the caller function_name should not be used with function_index :param function_index: int of how many frames back the program should look :para...
This will return the code of the calling function function_index of 2 will give the parent of the caller function_name should not be used with function_index :param function_index: int of how many frames back the program should look :param function_name: str of what function to look for :return: st...
def read_word(self, offset): """ .. _read_word: Read one word from a device. The offset is ``device_addr + device_offset``, e.g.:: offset = 3 # third word of the device offset += addr2 b.read_word(offset) # reads third word of d2. Truncates the value according to ``width``. May raise BUSErro...
.. _read_word: Read one word from a device. The offset is ``device_addr + device_offset``, e.g.:: offset = 3 # third word of the device offset += addr2 b.read_word(offset) # reads third word of d2. Truncates the value according to ``width``. May raise BUSError_, if the offset exceeds the address...
def load_np(self, imname, data_np, imtype, header): """Display a numpy image buffer in a remote Ginga reference viewer. Parameters ---------- imname : str A name to use for the image in the reference viewer. data_np : ndarray This should be at least a 2D...
Display a numpy image buffer in a remote Ginga reference viewer. Parameters ---------- imname : str A name to use for the image in the reference viewer. data_np : ndarray This should be at least a 2D Numpy array. imtype : str Image type--cur...
def _cutout_psf(self, image, subgrid_res): """ cutout the part of the image relevant for the psf convolution :param image: :return: """ self._init_mask_psf() return image[self._x_min_psf*subgrid_res:(self._x_max_psf+1)*subgrid_res, self._y_min_psf*subgrid_res:(sel...
cutout the part of the image relevant for the psf convolution :param image: :return:
def new_db_from_pandas(self, frame, table=None, data=None, load=True, **kwargs): """Create a new db partition from a pandas data frame. If the table does not exist, it will be created """ from ..orm import Column # from dbexceptions import ConfigurationError # Create ...
Create a new db partition from a pandas data frame. If the table does not exist, it will be created
def create(self, campaign_id, data, **queryparams): """ Add feedback on a specific campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { ...
Add feedback on a specific campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "message": string* } :param queryparams: The que...
def list_instances(self, hourly=True, monthly=True, tags=None, cpus=None, memory=None, hostname=None, domain=None, local_disk=None, datacenter=None, nic_speed=None, public_ip=None, private_ip=None, **kwargs): """Retrieve a list of all virtual ...
Retrieve a list of all virtual servers on the account. Example:: # Print out a list of hourly instances in the DAL05 data center. for vsi in mgr.list_instances(hourly=True, datacenter='dal05'): print vsi['fullyQualifiedDomainName'], vsi['primaryIpAddress'] ...
def describe_batch_predictions(FilterVariable=None, EQ=None, GT=None, LT=None, GE=None, LE=None, NE=None, Prefix=None, SortOrder=None, NextToken=None, Limit=None): """ Returns a list of BatchPrediction operations that match the search criteria in the request. See also: AWS API Documentation :e...
Returns a list of BatchPrediction operations that match the search criteria in the request. See also: AWS API Documentation :example: response = client.describe_batch_predictions( FilterVariable='CreatedAt'|'LastUpdatedAt'|'Status'|'Name'|'IAMUser'|'MLModelId'|'DataSourceId'|'DataURI', ...
def lsb_release(self, loglevel=logging.DEBUG): """Get distro information from lsb_release. """ # v the space is intentional, to avoid polluting bash history. shutit = self.shutit d = {} self.send(ShutItSendSpec(self, send=' command lsb_release -a', ...
Get distro information from lsb_release.