code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'): ''' Insert a rule into the specified table/chain, at the specified position. This function accepts a rule in a standard iptables command format, starting with the chain. Trying to force users to adapt to a new ...
Insert a rule into the specified table/chain, at the specified position. This function accepts a rule in a standard iptables command format, starting with the chain. Trying to force users to adapt to a new method of creating rules would be irritating at best, and we already have a parser th...
def dfs_iterative(graph, start, seen): """DFS, detect connected component, iterative implementation :param graph: directed graph in listlist or listdict format :param int node: to start graph exploration :param boolean-table seen: will be set true for the connected component containing node. ...
DFS, detect connected component, iterative implementation :param graph: directed graph in listlist or listdict format :param int node: to start graph exploration :param boolean-table seen: will be set true for the connected component containing node. :complexity: `O(|V|+|E|)`
def intinlist(lst): """test if int in list""" for item in lst: try: item = int(item) return True except ValueError: pass return False
test if int in list
def set_target(self, target): '''Set the target to use (one of buildozer.targets, such as "android") ''' self.targetname = target m = __import__('buildozer.targets.{0}'.format(target), fromlist=['buildozer']) self.target = m.get_target(self) self.ch...
Set the target to use (one of buildozer.targets, such as "android")
def top_i_answer(self, i): """获取排名某一位的答案. :param int i: 要获取的答案的排名 :return: 答案对象,能直接获取的属性参见answers方法 :rtype: Answer """ for j, a in enumerate(self.answers): if j == i - 1: return a
获取排名某一位的答案. :param int i: 要获取的答案的排名 :return: 答案对象,能直接获取的属性参见answers方法 :rtype: Answer
def parse_date(my_date): """Parse a date into canonical format of datetime.dateime. :param my_date: Either datetime.datetime or string in '%Y-%m-%dT%H:%M:%SZ' format. ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- :return: A datetime.datetime. ...
Parse a date into canonical format of datetime.dateime. :param my_date: Either datetime.datetime or string in '%Y-%m-%dT%H:%M:%SZ' format. ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- :return: A datetime.datetime. ~-~-~-~-~-~-~-~-~-~-~-~-~-~-...
def guess_type_tag(self, input_bytes, filename): """ Try to guess the type_tag for this sample """ mime_to_type = {'application/jar': 'jar', 'application/java-archive': 'jar', 'application/octet-stream': 'data', 'application/pdf': '...
Try to guess the type_tag for this sample
def get_var(var): ''' Get the value of a variable in make.conf Return the value of the variable or None if the variable is not in make.conf CLI Example: .. code-block:: bash salt '*' makeconf.get_var 'LINGUAS' ''' makeconf = _get_makeconf() # Open makeconf with salt.u...
Get the value of a variable in make.conf Return the value of the variable or None if the variable is not in make.conf CLI Example: .. code-block:: bash salt '*' makeconf.get_var 'LINGUAS'
def error(self): if self._error is None: try: #__init is renamed to the class with an _ init = getattr(self, "_" + self.__class__.__name__ + "__init", None) if init is not None and callable(init): init() except Exception...
gets the error
def percent_encode_non_ascii_headers(self, encoding='UTF-8'): """ Encode any headers that are not plain ascii as UTF-8 as per: https://tools.ietf.org/html/rfc8187#section-3.2.3 https://tools.ietf.org/html/rfc5987#section-3.2.2 """ def do_encode(m): ...
Encode any headers that are not plain ascii as UTF-8 as per: https://tools.ietf.org/html/rfc8187#section-3.2.3 https://tools.ietf.org/html/rfc5987#section-3.2.2
def getatom(self, atomends=None): """Parse an RFC 2822 atom. Optional atomends specifies a different set of end token delimiters (the default is to use self.atomends). This is used e.g. in getphraselist() since phrase endings must not include the `.' (which is legal in phrases)...
Parse an RFC 2822 atom. Optional atomends specifies a different set of end token delimiters (the default is to use self.atomends). This is used e.g. in getphraselist() since phrase endings must not include the `.' (which is legal in phrases).
def get_nowait_from_queue(queue): """ Collect all immediately available items from a queue """ data = [] for _ in range(queue.qsize()): try: data.append(queue.get_nowait()) except q.Empty: break return data
Collect all immediately available items from a queue
def encipher(self,message): """Encipher string using M209 cipher according to initialised key. Punctuation and whitespace are removed from the input. Example (continuing from the example above):: ciphertext = m.encipher(plaintext) :param string: The str...
Encipher string using M209 cipher according to initialised key. Punctuation and whitespace are removed from the input. Example (continuing from the example above):: ciphertext = m.encipher(plaintext) :param string: The string to encipher. :returns: The ...
def circuit_to_latex_using_qcircuit( circuit: circuits.Circuit, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT) -> str: """Returns a QCircuit-based latex diagram of the given circuit. Args: circuit: The circuit to represent in latex. qubit_order: Determines the order...
Returns a QCircuit-based latex diagram of the given circuit. Args: circuit: The circuit to represent in latex. qubit_order: Determines the order of qubit wires in the diagram. Returns: Latex code for the diagram.
def translate(self, closed_regex=True): u""" Returns a Python regular expression allowing to match :return: """ if closed_regex: return self.regex else: return translate(self.pattern, closed_regex=False, **self.flags)
u""" Returns a Python regular expression allowing to match :return:
def correct_pairs(p, pf, tag): """ Take one pair of reads and correct to generate *.corr.fastq. """ from jcvi.assembly.preprocess import correct as cr logging.debug("Work on {0} ({1})".format(pf, ','.join(p))) itag = tag[0] cm = ".".join((pf, itag)) targets = (cm + ".1.corr.fastq", cm +...
Take one pair of reads and correct to generate *.corr.fastq.
def show_version(a_device): """Execute show version command using Netmiko.""" remote_conn = ConnectHandler(**a_device) print() print("#" * 80) print(remote_conn.send_command("show version")) print("#" * 80) print()
Execute show version command using Netmiko.
def sign(s, passphrase, sig_format=SER_COMPACT, curve='secp160r1'): """ Signs `s' with passphrase `passphrase' """ if isinstance(s, six.text_type): raise ValueError("Encode `s` to a bytestring yourself to" + " prevent problems with different default encodings") curve = Curve...
Signs `s' with passphrase `passphrase'
def add_template_events(self, columns, vectors): """ Add a vector indexed """ # initialize with zeros - since vectors can be None, look for the # longest one that isn't new_events = None for v in vectors: if v is not None: new_events = numpy.zeros(len(...
Add a vector indexed
def flat_map(self, flatmap_fn): """Applies a flatmap operator to the stream. Attributes: flatmap_fn (function): The user-defined logic of the flatmap (e.g. split()). """ op = Operator( _generate_uuid(), OpType.FlatMap, "FlatM...
Applies a flatmap operator to the stream. Attributes: flatmap_fn (function): The user-defined logic of the flatmap (e.g. split()).
def _reset_values(self, instance): """Reset all associated values and clean up dictionary items""" self.value = None self.reference.value = None instance.__dict__.pop(self.field_name, None) instance.__dict__.pop(self.reference.field_name, None) self.reference.delete_cache...
Reset all associated values and clean up dictionary items
def to_networkx(self): r"""Export the graph to NetworkX. Edge weights are stored as an edge attribute, under the name "weight". Signals are stored as node attributes, under their name in the :attr:`signals` dictionary. `N`-dimensional signals are broken into `N` 1-dimen...
r"""Export the graph to NetworkX. Edge weights are stored as an edge attribute, under the name "weight". Signals are stored as node attributes, under their name in the :attr:`signals` dictionary. `N`-dimensional signals are broken into `N` 1-dimensional signals. They wi...
def write(self, *messages): """ Push a message list to this context's input queue. :param mixed value: message """ for message in messages: if not isinstance(message, Token): message = ensure_tuple(message, cls=self._input_type, length=self._input_len...
Push a message list to this context's input queue. :param mixed value: message
def get_chunk_meta(self, meta_file): """Get chunk meta table""" chunks = self.envs["CHUNKS"] if cij.nvme.get_meta(0, chunks * self.envs["CHUNK_META_SIZEOF"], meta_file): raise RuntimeError("cij.liblight.get_chunk_meta: fail") chunk_meta = cij.bin.Buffer(types=self.envs["CHUN...
Get chunk meta table
def deposit_links_factory(pid): """Factory for record links generation. The dictionary is formed as: .. code-block:: python { 'files': '/url/to/files', 'publish': '/url/to/publish', 'edit': '/url/to/edit', 'discard': '/url/to/discard', ....
Factory for record links generation. The dictionary is formed as: .. code-block:: python { 'files': '/url/to/files', 'publish': '/url/to/publish', 'edit': '/url/to/edit', 'discard': '/url/to/discard', ... } :param pid: The recor...
def instance(self, skip_exist_test=False): """ Returns the instance of the related object linked by the field. """ model = self.database._models[self.related_to] meth = model.lazy_connect if skip_exist_test else model return meth(self.proxy_get())
Returns the instance of the related object linked by the field.
def genesis_signing_lockset(genesis, privkey): """ in order to avoid a complicated bootstrapping, we define the genesis_signing_lockset as a lockset with one vote by any validator. """ v = VoteBlock(0, 0, genesis.hash) v.sign(privkey) ls = LockSet(num_eligible_votes=1) ls.add(v) asse...
in order to avoid a complicated bootstrapping, we define the genesis_signing_lockset as a lockset with one vote by any validator.
def reporter(self): """ Creates a report of the results """ # Create a set of all the gene names without alleles or accessions e.g. sul1_18_AY260546 becomes sul1 genedict = dict() # Load the notes file to a dictionary notefile = os.path.join(self.targetpath, 'note...
Creates a report of the results
def get_page(self, form): '''Get the requested page''' page_size = form.cleaned_data['iDisplayLength'] start_index = form.cleaned_data['iDisplayStart'] paginator = Paginator(self.object_list, page_size) num_page = (start_index / page_size) + 1 return paginator.page(num_pa...
Get the requested page
def summary(args): """ %prog summary gffile Print summary stats for features of different types. """ from jcvi.formats.base import SetFile from jcvi.formats.bed import BedSummary from jcvi.utils.table import tabulate p = OptionParser(summary.__doc__) p.add_option("--isoform", defau...
%prog summary gffile Print summary stats for features of different types.
def build_views(self): """ Bake out specified buildable views. """ # Then loop through and run them all for view_str in self.view_list: logger.debug("Building %s" % view_str) if self.verbosity > 1: self.stdout.write("Building %s" % view_str...
Bake out specified buildable views.
def uri_from_fields(prefix, *fields): """Construct a URI out of the fields, concatenating them after removing offensive characters. When all the fields are empty, return empty""" string = '_'.join(AlignmentHelper.alpha_numeric(f.strip().lower(), '') for f in fields) if len(string) == le...
Construct a URI out of the fields, concatenating them after removing offensive characters. When all the fields are empty, return empty
def resize(self, nrows, front=False): """ Resize the table to the given size, removing or adding rows as necessary. Note if expanding the table at the end, it is more efficient to use the append function than resizing and then writing. New added rows are zerod, except f...
Resize the table to the given size, removing or adding rows as necessary. Note if expanding the table at the end, it is more efficient to use the append function than resizing and then writing. New added rows are zerod, except for 'i1', 'u2' and 'u4' data types which get -128,3...
def close_stream(self): """ Closes the stream. Performs cleanup. """ self.keep_listening = False self.stream.stop_stream() self.stream.close() self.pa.terminate()
Closes the stream. Performs cleanup.
def unban_chat_member(self, *args, **kwargs): """See :func:`unban_chat_member`""" return unban_chat_member(*args, **self._merge_overrides(**kwargs)).run()
See :func:`unban_chat_member`
def _MergeIdentical(self, a, b): """Tries to merge two values. The values are required to be identical. Args: a: The first value. b: The second value. Returns: The trivially merged value. Raises: MergeError: The values were not identical. """ if a != b: raise Mer...
Tries to merge two values. The values are required to be identical. Args: a: The first value. b: The second value. Returns: The trivially merged value. Raises: MergeError: The values were not identical.
def encode_abi(self, types: Iterable[TypeStr], args: Iterable[Any]) -> bytes: """ Encodes the python values in ``args`` as a sequence of binary values of the ABI types in ``types`` via the head-tail mechanism. :param types: An iterable of string representations of the ABI types ...
Encodes the python values in ``args`` as a sequence of binary values of the ABI types in ``types`` via the head-tail mechanism. :param types: An iterable of string representations of the ABI types that will be used for encoding e.g. ``('uint256', 'bytes[]', '(int,int)')`` ...
def convert(fname,saveAs=True,showToo=False): """ Convert weird TIF files into web-friendly versions. Auto contrast is applied (saturating lower and upper 0.1%). make saveAs True to save as .TIF.png make saveAs False and it won't save at all make saveAs "someFile.jpg" to save it as a...
Convert weird TIF files into web-friendly versions. Auto contrast is applied (saturating lower and upper 0.1%). make saveAs True to save as .TIF.png make saveAs False and it won't save at all make saveAs "someFile.jpg" to save it as a different path/format
def create_connection(cls, address, timeout=None, source_address=None): """Create a SlipSocket connection. This convenience method creates a connection to the the specified address using the :func:`socket.create_connection` function. The socket that is returned from that call is automat...
Create a SlipSocket connection. This convenience method creates a connection to the the specified address using the :func:`socket.create_connection` function. The socket that is returned from that call is automatically wrapped in a :class:`SlipSocket` object. .. note:: ...
def cmd(name, options=''): """ Decorator for all commands. Commands will receive (pymux, variables) as input. Commands can raise CommandException. """ # Validate options. if options: try: docopt.docopt('Usage:\n %s %s' % (name, options, ), []) except SystemExi...
Decorator for all commands. Commands will receive (pymux, variables) as input. Commands can raise CommandException.
def manangeRecurringPaymentsProfileStatus(self, params, fail_silently=False): """ Requires `profileid` and `action` params. Action must be either "Cancel", "Suspend", or "Reactivate". """ defaults = {"method": "ManageRecurringPaymentsProfileStatus"} required = ["profileid...
Requires `profileid` and `action` params. Action must be either "Cancel", "Suspend", or "Reactivate".
def translate(self): """ Will look at the `Content-type` sent by the client, and maybe deserialize the contents into the format they sent. This will work for JSON, YAML, XML and Pickle. Since the data is not just key-value (and maybe just a list), the data will be placed on ...
Will look at the `Content-type` sent by the client, and maybe deserialize the contents into the format they sent. This will work for JSON, YAML, XML and Pickle. Since the data is not just key-value (and maybe just a list), the data will be placed on `request.data` instead, and the handle...
def show(self, id, detailed=None): """ This API endpoint returns a single Key transaction, identified its ID. :type id: int :param id: Key transaction ID :type detailed: bool :param detailed: :rtype: dict :return: The JSON response of the API :...
This API endpoint returns a single Key transaction, identified its ID. :type id: int :param id: Key transaction ID :type detailed: bool :param detailed: :rtype: dict :return: The JSON response of the API :: { "plugin": { ...
def _start_new_episode(self): """ Bookkeeping to do at the start of each new episode. """ # flush any data left over from the previous episode if any interactions have happened if self.has_interaction: self._flush() # timesteps in current episode sel...
Bookkeeping to do at the start of each new episode.
async def main(): """ Main code """ # Create Client from endpoint string in Duniter format client = Client(BMAS_ENDPOINT) # Get the node summary infos to test the connection response = await client(bma.node.summary) print(response) # prompt hidden user entry salt = getpass.getp...
Main code
def _check_image(self, X): """ Checks the image size and its compatibility with classifier's receptive field. At this moment it is required that image size = K * receptive_field. This will be relaxed in future with the introduction of padding. """ if (len(X.shap...
Checks the image size and its compatibility with classifier's receptive field. At this moment it is required that image size = K * receptive_field. This will be relaxed in future with the introduction of padding.
def seeds(args): """ %prog seeds [pngfile|jpgfile] Extract seed metrics from [pngfile|jpgfile]. Use --rows and --cols to crop image. """ p = OptionParser(seeds.__doc__) p.set_outfile() opts, args, iopts = add_seeds_options(p, args) if len(args) != 1: sys.exit(not p.print_help()...
%prog seeds [pngfile|jpgfile] Extract seed metrics from [pngfile|jpgfile]. Use --rows and --cols to crop image.
def source(self, format='xml', accessible=False): """ Args: format (str): only 'xml' and 'json' source types are supported accessible (bool): when set to true, format is always 'json' """ if accessible: return self.http.get('/wda/accessibleSource').val...
Args: format (str): only 'xml' and 'json' source types are supported accessible (bool): when set to true, format is always 'json'
def append(self, *args): """ add arguments to the set """ self.args.append(args) if self.started: self.started = False return self.length()
add arguments to the set
def pad_z(pts, value=0.0): """Adds a Z component from `pts` if it is missing. The value defaults to `value` (0.0)""" pts = np.asarray(pts) if pts.shape[-1] < 3: if len(pts.shape) < 2: return np.asarray((pts[0], pts[1], value), dtype=pts.dtype) pad_col = np.full(len(pts), valu...
Adds a Z component from `pts` if it is missing. The value defaults to `value` (0.0)
def distance(self, other): """ Distance between the center of this region and another. Parameters ---------- other : one region, or array-like Either another region, or the center of another region. """ from numpy.linalg import norm if isinsta...
Distance between the center of this region and another. Parameters ---------- other : one region, or array-like Either another region, or the center of another region.
def footprints_from_place(place, footprint_type='building', retain_invalid=False): """ Get footprints within the boundaries of some place. The query must be geocodable and OSM must have polygon boundaries for the geocode result. If OSM does not have a polygon for this place, you can instead get its...
Get footprints within the boundaries of some place. The query must be geocodable and OSM must have polygon boundaries for the geocode result. If OSM does not have a polygon for this place, you can instead get its footprints using the footprints_from_address function, which geocodes the place name to a ...
def _bp_static_url(blueprint): """ builds the absolute url path for a blueprint's static folder """ u = six.u('%s%s' % (blueprint.url_prefix or '', blueprint.static_url_path or '')) return u
builds the absolute url path for a blueprint's static folder
def extraction_data_statistics(path): """ Generates data statistics for the given data extraction setup stored in Xcessiv notebook. This is in rqtasks.py but not as a job yet. Temporarily call this directly while I'm figuring out Javascript lel. Args: path (str, unicode): Path to xcessiv n...
Generates data statistics for the given data extraction setup stored in Xcessiv notebook. This is in rqtasks.py but not as a job yet. Temporarily call this directly while I'm figuring out Javascript lel. Args: path (str, unicode): Path to xcessiv notebook
def _sending_task(self, backend): """ Used internally to safely increment `backend`s task count. Returns the overall count of tasks for `backend`. """ with self.backend_mutex: self.backends[backend] += 1 self.task_counter[backend] += 1 this_ta...
Used internally to safely increment `backend`s task count. Returns the overall count of tasks for `backend`.
def get_objs_from_record(self, record, key): """Returns a mapping of UID -> object """ uids = self.get_uids_from_record(record, key) objs = map(self.get_object_by_uid, uids) return dict(zip(uids, objs))
Returns a mapping of UID -> object
def _checkpoint(self, stage): """ Decide whether to stop processing of a pipeline. This is the hook A pipeline can report various "checkpoints" as sort of status markers that designate the logical processing phase that's just been completed. The initiation of a pipeline can preo...
Decide whether to stop processing of a pipeline. This is the hook A pipeline can report various "checkpoints" as sort of status markers that designate the logical processing phase that's just been completed. The initiation of a pipeline can preordain one of those as a "stopping point" t...
def readline(self, size=None): """Reads a single line of text. The functions reads one entire line from the file-like object. A trailing end-of-line indicator (newline by default) is kept in the string (but may be absent when a file ends with an incomplete line). An empty string is returned only wh...
Reads a single line of text. The functions reads one entire line from the file-like object. A trailing end-of-line indicator (newline by default) is kept in the string (but may be absent when a file ends with an incomplete line). An empty string is returned only when end-of-file is encountered immediat...
def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default...
.. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be ...
def path_to(self, p): """Returns the absolute path to a given relative path.""" if os.path.isabs(p): return p return os.sep.join([self._original_dir, p])
Returns the absolute path to a given relative path.
def record_drop_duplicate_fields(record): """ Return a record where all the duplicate fields have been removed. Fields are considered identical considering also the order of their subfields. """ out = {} position = 0 tags = sorted(record.keys()) for tag in tags: fields = rec...
Return a record where all the duplicate fields have been removed. Fields are considered identical considering also the order of their subfields.
def plot_colormap_components(cmap): """Plot the components of a given colormap.""" from ._helpers import set_ax_labels # recursive import protection plt.figure(figsize=[8, 4]) gs = grd.GridSpec(3, 1, height_ratios=[1, 10, 1], hspace=0.05) # colorbar ax = plt.subplot(gs[0]) gradient = np.li...
Plot the components of a given colormap.
def _search(mapping, filename): """Search a Loader data structure for a filename.""" result = mapping.get(filename) if result is not None: return result name, ext = os.path.splitext(filename) result = mapping.get(ext) if result is not None: for pattern, result2 in result: ...
Search a Loader data structure for a filename.
def abbreviate_list(items, max_items=10, item_max_len=40, joiner=", ", indicator="..."): """ Abbreviate a list, truncating each element and adding an indicator at the end if the whole list was truncated. Set item_max_len to None or 0 not to truncate items. """ if not items: return items else: shorte...
Abbreviate a list, truncating each element and adding an indicator at the end if the whole list was truncated. Set item_max_len to None or 0 not to truncate items.
def sudoers(self, enable): """ This method is used to enable/disable bash sudo commands running through the guestshell virtual service. By default sudo access is prevented due to the setting in the 'sudoers' file. Therefore the setting must be disabled in the file to enable sud...
This method is used to enable/disable bash sudo commands running through the guestshell virtual service. By default sudo access is prevented due to the setting in the 'sudoers' file. Therefore the setting must be disabled in the file to enable sudo commands. This method assumes that t...
async def list_pools() -> None: """ Lists names of created pool ledgers :return: Error code """ logger = logging.getLogger(__name__) logger.debug("list_pools: >>> ") if not hasattr(list_pools, "cb"): logger.debug("list_pools: Creating callback") list_pools.cb = create_cb(CF...
Lists names of created pool ledgers :return: Error code
def rewrite(self, source_bucket, source_object, destination_bucket, destination_object=None): """ Has the same functionality as copy, except that will work on files over 5 TB, as well as when copying between locations and/or storage classes. destination_object ca...
Has the same functionality as copy, except that will work on files over 5 TB, as well as when copying between locations and/or storage classes. destination_object can be omitted, in which case source_object is used. :param source_bucket: The bucket of the object to copy from. :...
def get_html(self): """Method to convert the repository list to a search results page.""" here = path.abspath(path.dirname(__file__)) env = Environment(loader=FileSystemLoader(path.join(here, "res/"))) suggest = env.get_template("suggest.htm.j2") return suggest.render( ...
Method to convert the repository list to a search results page.
def compile_file(source, globals_=None): """Compile by saving to file and importing that. Compiling the AST/source code this way ensures that the source code is readable by e.g. `pdb` or `inspect`. Args: source: The code to compile, either as a string or as an AST. globals_: A dictionary of variables ...
Compile by saving to file and importing that. Compiling the AST/source code this way ensures that the source code is readable by e.g. `pdb` or `inspect`. Args: source: The code to compile, either as a string or as an AST. globals_: A dictionary of variables that should be available as globals in ...
def check(text): """Suggest the preferred forms.""" err = "spelling.athletes" msg = "Misspelling of athlete's name. '{}' is the preferred form." misspellings = [ ["Dwyane Wade", ["Dwayne Wade"]], ["Miikka Kiprusoff", ["Mikka Kiprusoff"]], ["Mark Buehrle", ["Mar...
Suggest the preferred forms.
def get_dict_registry_services(registry, template_files, warn_missing_files=True): """ Return a dict mapping service name to a dict containing the service's type ('fixtures', 'platform_services', 'application_services', 'internal_services'), the template file's absolute path, and a list of environments ...
Return a dict mapping service name to a dict containing the service's type ('fixtures', 'platform_services', 'application_services', 'internal_services'), the template file's absolute path, and a list of environments to which the service is intended to deploy. Service names that appear twice in the out...
def _unpack_truisms(self, c): """ Given a constraint, _unpack_truisms() returns a set of constraints that must be True this constraint to be True. """ try: op = getattr(self, '_unpack_truisms_'+c.op) except AttributeError: return set() ret...
Given a constraint, _unpack_truisms() returns a set of constraints that must be True this constraint to be True.
def get_instance(self, payload): """ Build an instance of UserChannelInstance :param dict payload: Payload response from the API :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance...
Build an instance of UserChannelInstance :param dict payload: Payload response from the API :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance
def editpermissions_anonymous_user_view(self, request, forum_id=None): """ Allows to edit anonymous user permissions for the considered forum. The view displays a form to define which permissions are granted for the anonymous user for the considered forum. """ forum = get_objec...
Allows to edit anonymous user permissions for the considered forum. The view displays a form to define which permissions are granted for the anonymous user for the considered forum.
def _get_gather_offset(self, size): """Calculate the offset for gather result from this process Parameters ---------- size : int The total number of process. Returns ------- tuple_size : tuple_int Number of elements to send from each pr...
Calculate the offset for gather result from this process Parameters ---------- size : int The total number of process. Returns ------- tuple_size : tuple_int Number of elements to send from each process (one integer for each process...
def member_del(self, cluster_id, member_id): """remove member from cluster cluster""" cluster = self._storage[cluster_id] result = cluster.member_remove(member_id) self._storage[cluster_id] = cluster return result
remove member from cluster cluster
def step_a_file_named_filename_with(context, filename): """Creates a textual file with the content provided as docstring.""" step_a_file_named_filename_and_encoding_with(context, filename, "UTF-8") # -- SPECIAL CASE: For usage with behave steps. if filename.endswith(".feature"): command_util.en...
Creates a textual file with the content provided as docstring.
def get_feedback_from_submission(self, submission, only_feedback=False, show_everything=False, translation=gettext.NullTranslations()): """ Get the input of a submission. If only_input is False, returns the full submissions with a dictionnary object at the key "input". Else, returns only...
Get the input of a submission. If only_input is False, returns the full submissions with a dictionnary object at the key "input". Else, returns only the dictionnary. If show_everything is True, feedback normally hidden is shown.
def rename_bika_setup(): """ Rename Bika Setup to just Setup to avoid naming confusions for new users """ logger.info("Renaming Bika Setup...") bika_setup = api.get_bika_setup() bika_setup.setTitle("Setup") bika_setup.reindexObject() setup = api.get_portal().portal_setup setup.runImp...
Rename Bika Setup to just Setup to avoid naming confusions for new users
def post(self, document): """Send to API a document or a list of document. :param document: a document or a list of document. :type document: dict or list :return: Message with location of job :rtype: dict :raises ValidationError: if API returns status 400 :raise...
Send to API a document or a list of document. :param document: a document or a list of document. :type document: dict or list :return: Message with location of job :rtype: dict :raises ValidationError: if API returns status 400 :raises Unauthorized: if API returns status...
def insertLink(page, lnk, mark = True): """ Insert a new link for the current page. """ CheckParent(page) annot = getLinkText(page, lnk) if annot == "": raise ValueError("link kind not supported") page._addAnnot_FromString([annot]) return
Insert a new link for the current page.
def main(self,argv=None): """Run as a command-line script.""" parser = optparse.OptionParser(usage=USAGE % self.__class__.__name__) newopt = parser.add_option newopt('-i','--interact',action='store_true',default=False, help='Interact with the program after the script is r...
Run as a command-line script.
def valid_kdf(self, kdf): """Determine whether a KDFSuite can be used with this EncryptionSuite. :param kdf: KDFSuite to evaluate :type kdf: aws_encryption_sdk.identifiers.KDFSuite :rtype: bool """ if kdf.input_length is None: return True if self.dat...
Determine whether a KDFSuite can be used with this EncryptionSuite. :param kdf: KDFSuite to evaluate :type kdf: aws_encryption_sdk.identifiers.KDFSuite :rtype: bool
async def inspect(self, *, node_id: str) -> Mapping[str, Any]: """ Inspect a node Args: node_id: The ID or name of the node """ response = await self.docker._query_json( "nodes/{node_id}".format(node_id=node_id), method="GET" ) return res...
Inspect a node Args: node_id: The ID or name of the node
def system_config_dir(): r"""Return the system-wide config dir (full path). - Linux, SunOS: /etc/glances - *BSD, macOS: /usr/local/etc/glances - Windows: %APPDATA%\glances """ if LINUX or SUNOS: path = '/etc' elif BSD or MACOS: path = '/usr/local/etc' else: path ...
r"""Return the system-wide config dir (full path). - Linux, SunOS: /etc/glances - *BSD, macOS: /usr/local/etc/glances - Windows: %APPDATA%\glances
def get_properties(properties, identifier, namespace='cid', searchtype=None, as_dataframe=False, **kwargs): """Retrieve the specified properties from PubChem. :param identifier: The compound, substance or assay identifier to use as a search query. :param namespace: (optional) The identifier type. :para...
Retrieve the specified properties from PubChem. :param identifier: The compound, substance or assay identifier to use as a search query. :param namespace: (optional) The identifier type. :param searchtype: (optional) The advanced search type, one of substructure, superstructure or similarity. :param as...
def buildErrorResponse(self, request, error=None): """ Builds an error response. @param request: The AMF request @type request: L{Request<pyamf.remoting.Request>} @return: The AMF response @rtype: L{Response<pyamf.remoting.Response>} """ if error is not N...
Builds an error response. @param request: The AMF request @type request: L{Request<pyamf.remoting.Request>} @return: The AMF response @rtype: L{Response<pyamf.remoting.Response>}
def max_interval_intersec(S): """determine a value that is contained in a largest number of given intervals :param S: list of half open intervals :complexity: O(n log n), where n = len(S) """ B = ([(left, +1) for left, right in S] + [(right, -1) for left, right in S]) B.sort() c =...
determine a value that is contained in a largest number of given intervals :param S: list of half open intervals :complexity: O(n log n), where n = len(S)
def add_sun_flare(img, flare_center_x, flare_center_y, src_radius, src_color, circles): """Add sun flare. From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library Args: img (np.array): flare_center_x (float): flare_center_y (float): src_radius: src_c...
Add sun flare. From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library Args: img (np.array): flare_center_x (float): flare_center_y (float): src_radius: src_color (int, int, int): circles (list): Returns:
def post(self, url, entity): """ To make a POST request to Falkonry API server :param url: string :param entity: Instantiated class object """ try: if entity is None or entity == "": jsonData = "" else: jsonData = e...
To make a POST request to Falkonry API server :param url: string :param entity: Instantiated class object
def getSpecialPrice(self, product, store_view=None, identifierType=None): """ Get product special price data :param product: ID or SKU of product :param store_view: ID or Code of Store view :param identifierType: Defines whether the product or SKU value is ...
Get product special price data :param product: ID or SKU of product :param store_view: ID or Code of Store view :param identifierType: Defines whether the product or SKU value is passed in the "product" parameter. :return: Dictionary
def parse_scwrl_out(scwrl_std_out, scwrl_pdb): """Parses SCWRL output and returns PDB and SCWRL score. Parameters ---------- scwrl_std_out : str Std out from SCWRL. scwrl_pdb : str String of packed SCWRL PDB. Returns ------- fixed_scwrl_str : str String of packe...
Parses SCWRL output and returns PDB and SCWRL score. Parameters ---------- scwrl_std_out : str Std out from SCWRL. scwrl_pdb : str String of packed SCWRL PDB. Returns ------- fixed_scwrl_str : str String of packed SCWRL PDB, with correct PDB format. score : floa...
def move(self, d_xyz, inplace=False): """ Translate the whole Space in x, y and z coordinates. :param d_xyz: displacement in x, y(, and z). :type d_xyz: tuple (len=2 or 3) :param inplace: If True, the moved ``pyny.Space`` is copied and added to the cu...
Translate the whole Space in x, y and z coordinates. :param d_xyz: displacement in x, y(, and z). :type d_xyz: tuple (len=2 or 3) :param inplace: If True, the moved ``pyny.Space`` is copied and added to the current ``pyny.Space``. If False, it returns the...
def enter(clsQname): """ Delegate a rule to another class which instantiates a Klein app This also memoizes the resource instance on the handler function itself """ def wrapper(routeHandler): @functools.wraps(routeHandler) def inner(self, request, *a, **kw): if getattr(i...
Delegate a rule to another class which instantiates a Klein app This also memoizes the resource instance on the handler function itself
def delete_record(self, record): """ Permanently removes record from table. """ try: self.session.delete(record) self.session.commit() except Exception as e: self.session.rollback() raise ProgrammingError(e) finally: ...
Permanently removes record from table.
def get_linked(self): """Get a list of currently linked devices from the hub""" linked_devices = {} self.logger.info("\nget_linked") #todo instead of sleep, create loop to keep checking buffer self.direct_command_hub('0269') sleep(1) self.get_buffer_status() ...
Get a list of currently linked devices from the hub
def reveal(input_image_file): """Find a message in an image. """ from base64 import b64decode from zlib import decompress img = tools.open_image(input_image_file) try: if img.format in ["JPEG", "TIFF"]: if "exif" in img.info: exif_dict = piexif.load(img.info...
Find a message in an image.
def check_child_friendly(self, name): """ Check if a module is a container and so can have children """ name = name.split()[0] if name in self.container_modules: return root = os.path.dirname(os.path.realpath(__file__)) module_path = os.path.join(root,...
Check if a module is a container and so can have children
def get_plot(self, units='THz', ymin=None, ymax=None, width=None, height=None, dpi=None, plt=None, fonts=None, dos=None, dos_aspect=3, color=None, style=None, no_base_style=False): """Get a :obj:`matplotlib.pyplot` object of the phonon band structure. Args: ...
Get a :obj:`matplotlib.pyplot` object of the phonon band structure. Args: units (:obj:`str`, optional): Units of phonon frequency. Accepted (case-insensitive) values are Thz, cm-1, eV, meV. ymin (:obj:`float`, optional): The minimum energy on the y-axis. ymax...
def _initialize_cfg(self): """ Re-create the DiGraph """ self.kb.functions = FunctionManager(self.kb) self._jobs_to_analyze_per_function = defaultdict(set) self._completed_functions = set()
Re-create the DiGraph