code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def server_info(self): """ Query information about the server. """ response = self._post(self.apiurl + "/v2/server/info", data={'apikey': self.apikey}) return self._raise_or_extract(response)
Query information about the server.
def get_by_index(self, index): """Returns a Volume or Disk by its index.""" try: return self[index] except KeyError: for v in self.get_volumes(): if v.index == str(index): return v raise KeyError(index)
Returns a Volume or Disk by its index.
def run_subprocess(executable_command, command_arguments = [], timeout=None, print_process_output=True, stdout_file=None, stderr_file=None, poll_seconds=.100, buffer_size=-1, ...
Create and run a subprocess and return the process and execution time after it has completed. The execution time does not include the time taken for file i/o when logging the output if stdout_file and stderr_file arguments are given. Positional arguments: executable_command (str) -- executable com...
def main(): """ Main entry point - used for command line call """ args = _parse_arg(CountryConverter().valid_class) coco = CountryConverter(additional_data=args.additional_data) converted_names = coco.convert( names=args.names, src=args.src, to=args.to, enforce_list=F...
Main entry point - used for command line call
def mkdir(dir_path): # type: (AnyStr) -> None """Make directory if not existed""" if not os.path.isdir(dir_path) or not os.path.exists(dir_path): os.makedirs(dir_path)
Make directory if not existed
async def genSchema(self, name, version, attrNames) -> Schema: """ Generates and submits Schema. :param name: schema name :param version: schema version :param attrNames: a list of attributes the schema contains :return: submitted Schema """ schema = Sche...
Generates and submits Schema. :param name: schema name :param version: schema version :param attrNames: a list of attributes the schema contains :return: submitted Schema
def _clean_rule(self, rule): """ Cleans a css Rule by removing Selectors without matches on the tree Returns None if the whole rule do not match :param rule: CSS Rule to check :type rule: A tinycss Rule object :returns: A cleaned tinycss Rule with only Selectors matching...
Cleans a css Rule by removing Selectors without matches on the tree Returns None if the whole rule do not match :param rule: CSS Rule to check :type rule: A tinycss Rule object :returns: A cleaned tinycss Rule with only Selectors matching the tree or None :rtype: tinycss Rule or...
def GeneratePassphrase(length=20): """Create a 20 char passphrase with easily typeable chars.""" valid_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" valid_chars += "0123456789 ,-_&$#" return "".join(random.choice(valid_chars) for i in range(length))
Create a 20 char passphrase with easily typeable chars.
def element_to_objects(payload: Dict) -> List: """ Transform an Element to a list of entities recursively. """ entities = [] cls = MAPPINGS.get(payload.get('type')) if not cls: return [] transformed = transform_attributes(payload, cls) entity = cls(**transformed) if hasattr...
Transform an Element to a list of entities recursively.
def last_modified(self): """ Gets the most recent modification time for all entries in the view """ if self.entries: latest = max(self.entries, key=lambda x: x.last_modified) return arrow.get(latest.last_modified) return arrow.get()
Gets the most recent modification time for all entries in the view
def natsorted(seq, key=None, reverse=False, alg=ns.DEFAULT): """ Sorts an iterable naturally. Parameters ---------- seq : iterable The input to sort. key : callable, optional A key used to determine how to sort each element of the iterable. It is **not** applied recursi...
Sorts an iterable naturally. Parameters ---------- seq : iterable The input to sort. key : callable, optional A key used to determine how to sort each element of the iterable. It is **not** applied recursively. It should accept a single argument and return a single valu...
def triggerid_get(hostid=None, trigger_desc=None, priority=4, **kwargs): ''' .. versionadded:: Fluorine Retrieve trigger ID and description based in host ID and trigger description. .. note:: https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get :param hostid: ID of th...
.. versionadded:: Fluorine Retrieve trigger ID and description based in host ID and trigger description. .. note:: https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get :param hostid: ID of the host whose trigger we want to find :param trigger_desc: Description of trigger ...
def remove_hyperedge(self, hyperedge_id): """Removes a hyperedge and its attributes from the hypergraph. :param hyperedge_id: ID of the hyperedge to be removed. :raises: ValueError -- No such hyperedge exists. Examples: :: >>> H = DirectedHypergraph() >...
Removes a hyperedge and its attributes from the hypergraph. :param hyperedge_id: ID of the hyperedge to be removed. :raises: ValueError -- No such hyperedge exists. Examples: :: >>> H = DirectedHypergraph() >>> xyz = hyperedge_list = ((["A"], ["B", "C"]), ...
def pipeline(self, config, request): """ The pipeline() function handles authentication and invocation of the correct consumer based on the server configuration, that is provided at initialization time. When authentication is performed all the authenticators are executed...
The pipeline() function handles authentication and invocation of the correct consumer based on the server configuration, that is provided at initialization time. When authentication is performed all the authenticators are executed. If any returns False, authentication fails and a 403 ...
def execute(self, context): """ Publish the message to SQS queue :param context: the context object :type context: dict :return: dict with information about the message sent For details of the returned dict see :py:meth:`botocore.client.SQS.send_message` :rty...
Publish the message to SQS queue :param context: the context object :type context: dict :return: dict with information about the message sent For details of the returned dict see :py:meth:`botocore.client.SQS.send_message` :rtype: dict
def is_me(self): # pragma: no cover, seems not to be used anywhere """Check if parameter name if same than name of this object TODO: is it useful? :return: true if parameter name if same than this name :rtype: bool """ logger.info("And arbiter is launched with the host...
Check if parameter name if same than name of this object TODO: is it useful? :return: true if parameter name if same than this name :rtype: bool
def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for...
Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss.
def write_hdf5_segmentlist(seglist, output, path=None, **kwargs): """Write a `SegmentList` to an HDF5 file/group Parameters ---------- seglist : :class:`~ligo.segments.segmentlist` data to write output : `str`, `h5py.File`, `h5py.Group` filename or HDF5 object to write to path...
Write a `SegmentList` to an HDF5 file/group Parameters ---------- seglist : :class:`~ligo.segments.segmentlist` data to write output : `str`, `h5py.File`, `h5py.Group` filename or HDF5 object to write to path : `str` path to which to write inside the HDF5 file, relative to...
def unary_from_softmax(sm, scale=None, clip=1e-5): """Converts softmax class-probabilities to unary potentials (NLL per node). Parameters ---------- sm: numpy.array Output of a softmax where the first dimension is the classes, all others will be flattend. This means `sm.shape[0] == n_cl...
Converts softmax class-probabilities to unary potentials (NLL per node). Parameters ---------- sm: numpy.array Output of a softmax where the first dimension is the classes, all others will be flattend. This means `sm.shape[0] == n_classes`. scale: float The certainty of the soft...
def init_app(self, app): """Flask application initialization. Initialize the REST endpoints. Connect all signals if `DEPOSIT_REGISTER_SIGNALS` is True. :param app: An instance of :class:`flask.Flask`. """ self.init_config(app) blueprint = rest.create_blueprint(...
Flask application initialization. Initialize the REST endpoints. Connect all signals if `DEPOSIT_REGISTER_SIGNALS` is True. :param app: An instance of :class:`flask.Flask`.
def range(self, channels=None): """ Get the range of the specified channel(s). The range is a two-element list specifying the smallest and largest values that an event in a channel should have. Note that with floating point data, some events could have values outside the ...
Get the range of the specified channel(s). The range is a two-element list specifying the smallest and largest values that an event in a channel should have. Note that with floating point data, some events could have values outside the range in either direction due to instrument compens...
def feature_match(template, image, options=None): """ Match template and image by extracting specified feature :param template: Template image :param image: Search image :param options: Options include - feature: Feature extractor to use. Default is 'rgb'. Available options are: ...
Match template and image by extracting specified feature :param template: Template image :param image: Search image :param options: Options include - feature: Feature extractor to use. Default is 'rgb'. Available options are: 'hog', 'lab', 'rgb', 'gray' :return: Heatmap
def redirects(self): """ list: List of all redirects to this page; **i.e.,** the titles \ listed here will redirect to this page title Note: Not settable """ if self._redirects is None: self._redirects = list() self.__pull_combined_propert...
list: List of all redirects to this page; **i.e.,** the titles \ listed here will redirect to this page title Note: Not settable
def _configure_device(commands, **kwargs): ''' Helper function to send configuration commands to the device over a proxy minion or native minion using NX-API or SSH. ''' if salt.utils.platform.is_proxy(): return __proxy__['nxos.proxy_config'](commands, **kwargs) else: return _nxa...
Helper function to send configuration commands to the device over a proxy minion or native minion using NX-API or SSH.
def fanout(self, hosts=None, timeout=None, max_concurrency=64, auto_batch=None): """Returns a context manager for a map operation that fans out to manually specified hosts instead of using the routing system. This can for instance be used to empty the database on all hosts. The ...
Returns a context manager for a map operation that fans out to manually specified hosts instead of using the routing system. This can for instance be used to empty the database on all hosts. The context manager returns a :class:`FanoutClient`. Example usage:: with cluster.fanout(...
def meta_changed_notify_after(self, state_machine_m, _, info): """Handle notification about the change of a state's meta data The meta data of the affected state(s) are read and the view updated accordingly. :param StateMachineModel state_machine_m: Always the state machine model belonging to t...
Handle notification about the change of a state's meta data The meta data of the affected state(s) are read and the view updated accordingly. :param StateMachineModel state_machine_m: Always the state machine model belonging to this editor :param str _: Always "state_meta_signal" :param...
def _handle_auth(self, dtype, data, ts): """Handles authentication responses. :param dtype: :param data: :param ts: :return: """ # Contains keys status, chanId, userId, caps if dtype == 'unauth': raise NotImplementedError channel_id = ...
Handles authentication responses. :param dtype: :param data: :param ts: :return:
def addItem(self, item): """Adds an item if the tree is mutable""" try: self.tree.addItem(item) except AttributeError, e: raise VersionError('Saved versions are immutable')
Adds an item if the tree is mutable
def _iter_rawterms(cls, tree): """Iterate through the raw terms (Classes) in the ontology. """ for elem in tree.iterfind(OWL_CLASS): if RDF_ABOUT not in elem.keys(): # This avoids parsing a class continue # created by restriction ra...
Iterate through the raw terms (Classes) in the ontology.
def _split_line_with_offsets(line): """Split a line by delimiter, but yield tuples of word and offset. This function works by dropping all the english-like punctuation from a line (so parenthesis preceded or succeeded by spaces, periods, etc) and then splitting on spaces. """ for delimiter in r...
Split a line by delimiter, but yield tuples of word and offset. This function works by dropping all the english-like punctuation from a line (so parenthesis preceded or succeeded by spaces, periods, etc) and then splitting on spaces.
def find_id_in_folder(self, name, parent_folder_id=0): """Find a folder or a file ID from its name, inside a given folder. Args: name (str): Name of the folder or the file to find. parent_folder_id (int): ID of the folder where to search. Returns: int. ID o...
Find a folder or a file ID from its name, inside a given folder. Args: name (str): Name of the folder or the file to find. parent_folder_id (int): ID of the folder where to search. Returns: int. ID of the file or folder found. None if not found. Raises: ...
def get_section(self, section_id, params={}): """ Return section resource for given canvas section id. https://canvas.instructure.com/doc/api/sections.html#method.sections.show """ url = SECTIONS_API.format(section_id) return CanvasSection(data=self._get_resource(url, pa...
Return section resource for given canvas section id. https://canvas.instructure.com/doc/api/sections.html#method.sections.show
def dump(self): """Print a formatted summary of the current solve state.""" from rez.utils.formatting import columnise rows = [] for i, phase in enumerate(self.phase_stack): rows.append((self._depth_label(i), phase.status, str(phase))) print "status: %s (%s)" % (sel...
Print a formatted summary of the current solve state.
def load(self, config): """Load the web list from the configuration file.""" web_list = [] if config is None: logger.debug("No configuration file available. Cannot load ports list.") elif not config.has_section(self._section): logger.debug("No [%s] section in the...
Load the web list from the configuration file.
def absent(name, **connection_args): ''' Ensure that the named database is absent name The name of the database to remove ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} #check if db exists and remove it if __salt__['mysql.db_...
Ensure that the named database is absent name The name of the database to remove
def main(): # type: () -> typing.Any """Parse the command line options and launch the requested command. If the command is 'help' then print the help message for the subcommand; if no subcommand is given, print the standard help message. """ colorama.init(wrap=six.PY3) doc = usage.get_prima...
Parse the command line options and launch the requested command. If the command is 'help' then print the help message for the subcommand; if no subcommand is given, print the standard help message.
def handleMatch(self, m): """ Handles user input into [magic] tag, processes it, and inserts the returned URL into an <img> tag through a Python ElementTree <img> Element. """ userStr = m.group(3) # print(userStr) imgURL = processString(userStr) # ...
Handles user input into [magic] tag, processes it, and inserts the returned URL into an <img> tag through a Python ElementTree <img> Element.
def run(data): """Quantitaive isoforms expression by eXpress""" name = dd.get_sample_name(data) in_bam = dd.get_transcriptome_bam(data) config = data['config'] if not in_bam: logger.info("Transcriptome-mapped BAM file not found, skipping eXpress.") return data out_dir = os.path.j...
Quantitaive isoforms expression by eXpress
def idle_task(self): '''called on idle''' for r in self.repeats: if r.event.trigger(): self.mpstate.functions.process_stdin(r.cmd, immediate=True)
called on idle
def task(name, deps = None, fn = None): """Define a new task.""" if callable(deps): fn = deps deps = None if not deps and not fn: logger.log(logger.red("The task '%s' is empty" % name)) else: tasks[name] = [fn, deps]
Define a new task.
def paginate(self): """Make folders where we would like to put results etc.""" project_dir = self.project_dir raw_dir = self.raw_dir batch_dir = self.batch_dir if project_dir is None: raise UnderDefined("no project directory defined") if raw_dir is None: ...
Make folders where we would like to put results etc.
def detect_direct_function_shadowing(contract): """ Detects and obtains functions which are shadowed immediately by the provided ancestor contract. :param contract: The ancestor contract which we check for function shadowing within. :return: A list of tuples (overshadowing_function, overshadowed_immedia...
Detects and obtains functions which are shadowed immediately by the provided ancestor contract. :param contract: The ancestor contract which we check for function shadowing within. :return: A list of tuples (overshadowing_function, overshadowed_immediate_base_contract, overshadowed_function) -overshadowing_...
def _factory(cls, constraints, op): """ Factory for joining constraints with a single conjunction """ pieces = [] for i, constraint in enumerate(constraints): pieces.append(constraint) if i != len(constraints) - 1: pieces.append(op) return cls(piec...
Factory for joining constraints with a single conjunction
def _handle_chat(self, data): """Handle chat messages""" self.conn.enqueue_data( "chat", ChatMessage.from_data(self.room, self.conn, data) )
Handle chat messages
def search_upwards(self, fpath=None, repodirname='.svn', upwards={}): """ Traverse filesystem upwards, searching for .svn directories with matching UUIDs (Recursive) Args: fpath (str): file path to search upwards from repodirname (str): directory name to search f...
Traverse filesystem upwards, searching for .svn directories with matching UUIDs (Recursive) Args: fpath (str): file path to search upwards from repodirname (str): directory name to search for (``.svn``) upwards (dict): dict of already-searched directories ex...
def pretty_time(timestamp: str): """Format timestamp for human consumption.""" try: parsed = iso_8601.parse_datetime(timestamp) except ValueError: now = datetime.utcnow().replace(tzinfo=timezone.utc) try: delta = iso_8601.parse_delta(timestamp) except ValueError: ...
Format timestamp for human consumption.
def _sync_io(self): """Update the stream with changes to the file object contents.""" if self._file_epoch == self.file_object.epoch: return if self._io.binary: contents = self.file_object.byte_contents else: contents = self.file_object.contents ...
Update the stream with changes to the file object contents.
def find_bidi(self, el): """Get directionality from element text.""" for node in self.get_children(el, tags=False): # Analyze child text nodes if self.is_tag(node): # Avoid analyzing certain elements specified in the specification. direction = D...
Get directionality from element text.
def filter_missing(self): """Filter out individuals and SNPs that have too many missing to be considered""" missing = None locus_count = 0 # Filter out individuals according to missingness self.genotype_file.seek(0) for genotypes in self.genotype_fil...
Filter out individuals and SNPs that have too many missing to be considered
def add_cmds_cpdir(cpdir, cmdpkl, cpfileglob='checkplot*.pkl*', require_cmd_magcolor=True, save_cmd_pngs=False): '''This adds CMDs for each object in cpdir. Parameters ---------- cpdir : list of str This is the directo...
This adds CMDs for each object in cpdir. Parameters ---------- cpdir : list of str This is the directory to search for checkplot pickles. cmdpkl : str This is the filename of the CMD pickle created previously. cpfileglob : str The UNIX fileglob to use when searching for c...
def datapoint_indices_for_tensor(self, tensor_index): """ Returns the indices for all datapoints in the given tensor. """ if tensor_index >= self._num_tensors: raise ValueError('Tensor index %d is greater than the number of tensors (%d)' %(tensor_index, self._num_tensors)) return sel...
Returns the indices for all datapoints in the given tensor.
def marshal(self, values): """ Turn a list of entities into a list of dictionaries. :param values: The entities to serialize. :type values: List[stravalib.model.BaseEntity] :return: List of dictionaries of attributes :rtype: List[Dict[str, Any]] """ if va...
Turn a list of entities into a list of dictionaries. :param values: The entities to serialize. :type values: List[stravalib.model.BaseEntity] :return: List of dictionaries of attributes :rtype: List[Dict[str, Any]]
def _search(self, limit, format): ''' Returns a list of result objects, with the url for the next page MsCognitive search url. ''' limit = min(limit, self.MAX_SEARCH_PER_QUERY) payload = { 'q' : self.query, 'count' : limit, #currently 50 is max per search. ...
Returns a list of result objects, with the url for the next page MsCognitive search url.
def boggle_hill_climbing(board=None, ntimes=100, verbose=True): """Solve inverse Boggle by hill-climbing: find a high-scoring board by starting with a random one and changing it.""" finder = BoggleFinder() if board is None: board = random_boggle() best = len(finder.set_board(board)) for ...
Solve inverse Boggle by hill-climbing: find a high-scoring board by starting with a random one and changing it.
def proc_collector(process_map, args, pipeline_string): """ Function that collects all processes available and stores a dictionary of the required arguments of each process class to be passed to procs_dict_parser Parameters ---------- process_map: dict The dictionary with the Proces...
Function that collects all processes available and stores a dictionary of the required arguments of each process class to be passed to procs_dict_parser Parameters ---------- process_map: dict The dictionary with the Processes currently available in flowcraft and their corresponding...
def _set_interface_brief(self, v, load=False): """ Setter method for interface_brief, mapped from YANG variable /isis_state/interface_brief (container) If this variable is read-only (config: false) in the source YANG file, then _set_interface_brief is considered as a private method. Backends looking...
Setter method for interface_brief, mapped from YANG variable /isis_state/interface_brief (container) If this variable is read-only (config: false) in the source YANG file, then _set_interface_brief is considered as a private method. Backends looking to populate this variable should do so via calling thi...
def clear_all_events(self): """Clear all event queues and their cached events.""" self.lock.acquire() self.event_dict.clear() self.lock.release()
Clear all event queues and their cached events.
def loadPng(varNumVol, tplPngSize, strPathPng): """Load PNG files. Parameters ---------- varNumVol : float Number of volumes, i.e. number of time points in all runs. tplPngSize : tuple Shape of the stimulus image (i.e. png). strPathPng: str Path to the folder cointaining...
Load PNG files. Parameters ---------- varNumVol : float Number of volumes, i.e. number of time points in all runs. tplPngSize : tuple Shape of the stimulus image (i.e. png). strPathPng: str Path to the folder cointaining the png files. Returns ------- aryPngData ...
def new_transaction( vm: VM, from_: Address, to: Address, amount: int=0, private_key: PrivateKey=None, gas_price: int=10, gas: int=100000, data: bytes=b'') -> BaseTransaction: """ Create and return a transaction sending amount from <from_> to <to>....
Create and return a transaction sending amount from <from_> to <to>. The transaction will be signed with the given private key.
def decorator(directname=None): """ Attach a class to a parsing decorator and register it to the global decorator list. The class is registered with its name unless directname is provided """ global _decorators class_deco_list = _decorators def wrapper(f): nonlocal d...
Attach a class to a parsing decorator and register it to the global decorator list. The class is registered with its name unless directname is provided
def query_by_user(cls, user, **kwargs): """Get a user's memberships.""" return cls._filter( cls.query.filter_by(user_id=user.get_id()), **kwargs )
Get a user's memberships.
def _prepare_transformation_recipe(pattern: str, reduction: str, axes_lengths: Tuple) -> TransformRecipe: """ Perform initial parsing of pattern and provided supplementary info axes_lengths is a tuple of tuples (axis_name, axis_length) """ left, right = pattern.split('->') identifiers_left, composit...
Perform initial parsing of pattern and provided supplementary info axes_lengths is a tuple of tuples (axis_name, axis_length)
def merge_items(from_id, to_id, login_obj, mediawiki_api_url='https://www.wikidata.org/w/api.php', ignore_conflicts='', user_agent=config['USER_AGENT_DEFAULT']): """ A static method to merge two Wikidata items :param from_id: The QID which should be merged into another item ...
A static method to merge two Wikidata items :param from_id: The QID which should be merged into another item :type from_id: string with 'Q' prefix :param to_id: The QID into which another item should be merged :type to_id: string with 'Q' prefix :param login_obj: The object conta...
def check_config_mode(self, check_string=")#", pattern=""): """ Checks if the device is in configuration mode or not. Cisco IOS devices abbreviate the prompt at 20 chars in config mode """ return super(CiscoBaseConnection, self).check_config_mode( check_string=check_...
Checks if the device is in configuration mode or not. Cisco IOS devices abbreviate the prompt at 20 chars in config mode
def compose_object(self, file_list, destination_file, content_type): """COMPOSE multiple objects together. Using the given list of files, calls the put object with the compose flag. This call merges all the files into the destination file. Args: file_list: list of dicts with the file name. ...
COMPOSE multiple objects together. Using the given list of files, calls the put object with the compose flag. This call merges all the files into the destination file. Args: file_list: list of dicts with the file name. destination_file: Path to the destination file. content_type: Content...
def get_east_asian_width_property(value, is_bytes=False): """Get `EAST ASIAN WIDTH` property.""" obj = unidata.ascii_east_asian_width if is_bytes else unidata.unicode_east_asian_width if value.startswith('^'): negated = value[1:] value = '^' + unidata.unicode_alias['eastasianwidth'].get(ne...
Get `EAST ASIAN WIDTH` property.
def setup_multiprocessing_logging(queue=None): ''' This code should be called from within a running multiprocessing process instance. ''' from salt.utils.platform import is_windows global __MP_LOGGING_CONFIGURED global __MP_LOGGING_QUEUE_HANDLER if __MP_IN_MAINPROCESS is True and not i...
This code should be called from within a running multiprocessing process instance.
def process(self, formdata=None, obj=None, data=None, **kwargs): '''Wrap the process method to store the current object instance''' self._obj = obj super(CommonFormMixin, self).process(formdata, obj, data, **kwargs)
Wrap the process method to store the current object instance
def url(self): """ The URL present in this inline results. If you want to "click" this URL to open it in your browser, you should use Python's `webbrowser.open(url)` for such task. """ if isinstance(self.result, types.BotInlineResult): return self.result.url
The URL present in this inline results. If you want to "click" this URL to open it in your browser, you should use Python's `webbrowser.open(url)` for such task.
def _prm_write_shared_array(self, key, data, hdf5_group, full_name, flag, **kwargs): """Creates and array that can be used with an HDF5 array object""" if flag == HDF5StorageService.ARRAY: self._prm_write_into_array(key, data, hdf5_group, full_name, **kwargs) elif flag in (HDF5Stora...
Creates and array that can be used with an HDF5 array object
def map_components(notsplit_packages, components): """ Returns a list of packages to install based on component names This is done by checking if a component is in notsplit_packages, if it is, we know we need to install 'ceph' instead of the raw component name. Essentially, this component hasn't b...
Returns a list of packages to install based on component names This is done by checking if a component is in notsplit_packages, if it is, we know we need to install 'ceph' instead of the raw component name. Essentially, this component hasn't been 'split' from the master 'ceph' package yet.
def _dict_to_map_str_str(self, d): """ Thrift requires the params and headers dict values to only contain str values. """ return dict(map( lambda (k, v): (k, str(v).lower() if isinstance(v, bool) else str(v)), d.iteritems() ))
Thrift requires the params and headers dict values to only contain str values.
def configure_retrieve(self, ns, definition): """ Register a retrieve endpoint. The definition's func should be a retrieve function, which must: - accept kwargs for path data - return an item or falsey :param ns: the namespace :param definition: the endpoint def...
Register a retrieve endpoint. The definition's func should be a retrieve function, which must: - accept kwargs for path data - return an item or falsey :param ns: the namespace :param definition: the endpoint definition
def save_history(self, f): """Saves the history of ``NeuralNet`` as a json file. In order to use this feature, the history must only contain JSON encodable Python data structures. Numpy and PyTorch types should not be in the history. Parameters ---------- f : fil...
Saves the history of ``NeuralNet`` as a json file. In order to use this feature, the history must only contain JSON encodable Python data structures. Numpy and PyTorch types should not be in the history. Parameters ---------- f : file-like object or str Examples...
def lessThan(self, leftIndex, rightIndex): """ Returns true if the value of the item referred to by the given index left is less than the value of the item referred to by the given index right, otherwise returns false. """ leftData = self.sourceModel().data(leftIndex, RegistryTable...
Returns true if the value of the item referred to by the given index left is less than the value of the item referred to by the given index right, otherwise returns false.
def convert_representation(self, i): """ Return the proper representation for the given integer """ if self.number_representation == 'unsigned': return i elif self.number_representation == 'signed': if i & (1 << self.interpreter._bit_width - 1): ...
Return the proper representation for the given integer
def rescale_gradients(model: Model, grad_norm: Optional[float] = None) -> Optional[float]: """ Performs gradient rescaling. Is a no-op if gradient rescaling is not enabled. """ if grad_norm: parameters_to_clip = [p for p in model.parameters() if p.grad is not None] ...
Performs gradient rescaling. Is a no-op if gradient rescaling is not enabled.
def solution(self, expr, v, extra_constraints=(), solver=None, model_callback=None): """ Return True if `v` is a solution of `expr` with the extra constraints, False otherwise. :param expr: An expression (an AST) to evaluate :param v: The proposed soluti...
Return True if `v` is a solution of `expr` with the extra constraints, False otherwise. :param expr: An expression (an AST) to evaluate :param v: The proposed solution (an AST) :param solver: A solver object, native to the backend, to assist in the ...
def get_bios_firmware_version(snmp_client): """Get bios firmware version of the node. :param snmp_client: an SNMP client object. :raises: SNMPFailure if SNMP operation failed. :returns: a string of bios firmware version. """ try: bios_firmware_version = snmp_client.get(BIOS_FW_VERSION_...
Get bios firmware version of the node. :param snmp_client: an SNMP client object. :raises: SNMPFailure if SNMP operation failed. :returns: a string of bios firmware version.
def _get_path_pattern_tornado45(self, router=None): """Return the path pattern used when routing a request. (Tornado>=4.5) :param tornado.routing.Router router: (Optional) The router to scan. Defaults to the application's router. :rtype: str """ if router is None: ...
Return the path pattern used when routing a request. (Tornado>=4.5) :param tornado.routing.Router router: (Optional) The router to scan. Defaults to the application's router. :rtype: str
def print_trace(self, file=sys.stdout, base=10, compact=False): """ Prints a list of wires and their current values. :param int base: the base the values are to be printed in :param bool compact: whether to omit spaces in output lines """ if len(self.trace) == 0: ...
Prints a list of wires and their current values. :param int base: the base the values are to be printed in :param bool compact: whether to omit spaces in output lines
def insert(self, song): """在当前歌曲后插入一首歌曲""" if song in self._songs: return if self._current_song is None: self._songs.append(song) else: index = self._songs.index(self._current_song) self._songs.insert(index + 1, song)
在当前歌曲后插入一首歌曲
def start(workflow_name, data=None, object_id=None, **kwargs): """Start a workflow by given name for specified data. The name of the workflow to start is considered unique and it is equal to the name of a file containing the workflow definition. The data passed could be a list of Python standard data ...
Start a workflow by given name for specified data. The name of the workflow to start is considered unique and it is equal to the name of a file containing the workflow definition. The data passed could be a list of Python standard data types such as strings, dict, integers etc. to run through the work...
def _netbsd_gpu_data(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed'] gpus = [] try: pcictl_out = __salt__['cmd.run']('pcictl pci0 list') f...
num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string
def is_ancestor(self, commit1, commit2, patch=False): """Returns True if commit1 is a direct ancestor of commit2, or False otherwise. This method considers a commit to be a direct ancestor of itself""" result = self.hg("log", "-r", "first(%s::%s)" % (commit1, commit2), ...
Returns True if commit1 is a direct ancestor of commit2, or False otherwise. This method considers a commit to be a direct ancestor of itself
async def update(self, obj, only=None): """Update the object in the database. Optionally, update only the specified fields. For creating a new object use :meth:`.create()` :param only: (optional) the list/tuple of fields or field names to update """ field_di...
Update the object in the database. Optionally, update only the specified fields. For creating a new object use :meth:`.create()` :param only: (optional) the list/tuple of fields or field names to update
def file_content(self, value): """The Base64 encoded content of the attachment :param value: The Base64 encoded content of the attachment :type value: FileContent, string """ if isinstance(value, FileContent): self._file_content = value else: self...
The Base64 encoded content of the attachment :param value: The Base64 encoded content of the attachment :type value: FileContent, string
def parse_element(raw_element: str) -> List[Element]: """ Parse a raw element into text and indices (integers). """ elements = [regex.match("^(([a-zA-Z]+)\(([^;]+),List\(([^;]*)\)\))$", elem.lstrip().rstrip()) for elem in raw_element.split(';')...
Parse a raw element into text and indices (integers).
def list_services(request, step): """ get the activated services added from the administrator :param request: request object :param step: the step which is proceeded :type request: HttpRequest object :type step: string :return the activated services added from the adm...
get the activated services added from the administrator :param request: request object :param step: the step which is proceeded :type request: HttpRequest object :type step: string :return the activated services added from the administrator
def cd_to(path, mkdir=False): """make a generator like cd, but use it for function Usage:: >>> @cd_to("/") ... def say_where(): ... print(os.getcwd()) ... >>> say_where() / """ def cd_to_decorator(func): @functools.wraps(func) def _c...
make a generator like cd, but use it for function Usage:: >>> @cd_to("/") ... def say_where(): ... print(os.getcwd()) ... >>> say_where() /
def to_python(self, value): """Convert value if needed.""" if isinstance(value, DirDescriptor): return value elif isinstance(value, str): return DirDescriptor(value) elif isinstance(value, dict): try: path = value['dir'] exc...
Convert value if needed.
def _get_content_type(url, session): """Get the Content-Type of the given url, using a HEAD request""" scheme, netloc, path, query, fragment = urllib_parse.urlsplit(url) if scheme not in ('http', 'https'): # FIXME: some warning or something? # assertion error? ...
Get the Content-Type of the given url, using a HEAD request
def getFieldMax(self, fieldName): """ If underlying implementation does not support min/max stats collection, or if a field type does not support min/max (non scalars), the return value will be None. :param fieldName: (string) name of field to get max :returns: current maximum value for the fie...
If underlying implementation does not support min/max stats collection, or if a field type does not support min/max (non scalars), the return value will be None. :param fieldName: (string) name of field to get max :returns: current maximum value for the field ``fieldName``.
def create_dialog_node(self, workspace_id, dialog_node, description=None, conditions=None, parent=None, previous_sibling=None, outp...
Create dialog node. Create a new dialog node. This operation is limited to 500 requests per 30 minutes. For more information, see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str dialog_node: The dialog node ID. This string must conform...
def match(self, search, **kwargs): """ Searches for Repository Configurations based on internal or external url, ignoring the protocol and \".git\" suffix. Only exact matches are returned. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP requ...
Searches for Repository Configurations based on internal or external url, ignoring the protocol and \".git\" suffix. Only exact matches are returned. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be ...
def v1_folder_rename(request, response, kvlclient, fid_src, fid_dest, sfid_src=None, sfid_dest=None): '''Rename a folder or a subfolder. The routes for this endpoint are: * ``POST /dossier/v1/<fid_src>/rename/<fid_dest>`` * ``POST /dossier/v1/<fid_src>/subfolder/<sfid_src>/rename/...
Rename a folder or a subfolder. The routes for this endpoint are: * ``POST /dossier/v1/<fid_src>/rename/<fid_dest>`` * ``POST /dossier/v1/<fid_src>/subfolder/<sfid_src>/rename/ <fid_dest>/subfolder/<sfid_dest>``
def _bld_pnab_generic(self, funcname, **kwargs): """ implement's a generic version of a non-attribute based pandas function """ margs = {'mtype': pnab, 'kwargs': kwargs} setattr(self, funcname, margs)
implement's a generic version of a non-attribute based pandas function
def _doc2vec_doc_stream(paths, n, tokenizer=word_tokenize, sentences=True): """ Generator to feed sentences to the dov2vec model. """ i = 0 p = Progress() for path in paths: with open(path, 'r') as f: for line in f: i += 1 p.print_progress(i/n)...
Generator to feed sentences to the dov2vec model.
def pbkdf2(digestmod, password, salt, count, dk_length): """ PBKDF2, from PKCS #5 v2.0[1]. [1]: http://tools.ietf.org/html/rfc2898 For proper usage, see NIST Special Publication 800-132: http://csrc.nist.gov/publications/PubsSPs.html The arguments for this function are: digestmod...
PBKDF2, from PKCS #5 v2.0[1]. [1]: http://tools.ietf.org/html/rfc2898 For proper usage, see NIST Special Publication 800-132: http://csrc.nist.gov/publications/PubsSPs.html The arguments for this function are: digestmod a crypographic hash constructor, such as hashlib.sha256 ...
def find_unpaired_ligand(self): """Identify unpaired functional in groups in ligands, involving H-Bond donors, acceptors, halogen bond donors. """ unpaired_hba, unpaired_hbd, unpaired_hal = [], [], [] # Unpaired hydrogen bond acceptors/donors in ligand (not used for hydrogen bonds/water,...
Identify unpaired functional in groups in ligands, involving H-Bond donors, acceptors, halogen bond donors.