code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def unzip(zip_file_path, output_dir, permission=None): """ Unzip the given file into the given directory while preserving file permissions in the process. Parameters ---------- zip_file_path : str Path to the zip file output_dir : str Path to the directory where the it should b...
Unzip the given file into the given directory while preserving file permissions in the process. Parameters ---------- zip_file_path : str Path to the zip file output_dir : str Path to the directory where the it should be unzipped to permission : octal int Permission to set
def isLocked(name): """Determine if the lock of the given name is held or not. @type name: C{str} @param name: The filesystem path to the lock to test @rtype: C{bool} @return: True if the lock is held, False otherwise. """ l = FilesystemLock(name) result = None try: ...
Determine if the lock of the given name is held or not. @type name: C{str} @param name: The filesystem path to the lock to test @rtype: C{bool} @return: True if the lock is held, False otherwise.
def UUIDField(default=NOTHING, required=False, repr=True, cmp=True, key=None): """ Create new UUID field on a model. :param default: any value :param bool required: whether or not the object is invalid if not provided. :param bool repr: include this field should appear in object's repr. :param ...
Create new UUID field on a model. :param default: any value :param bool required: whether or not the object is invalid if not provided. :param bool repr: include this field should appear in object's repr. :param bool cmp: include this field in generated comparison. :param string key: override name ...
def ProcessHttpRequest(self, http_request): """Hook for pre-processing of http requests.""" http_request.headers.update(self.additional_http_headers) if self.log_request: logging.info('Making http %s to %s', http_request.http_method, http_request.url) ...
Hook for pre-processing of http requests.
def _compile_bus_injection(self): """Impose injections on buses""" string = '"""\n' for device, series in zip(self.devices, self.series): if series: string += 'system.' + device + '.gcall(system.dae)\n' string += '\n' string += 'system.dae.reset_small_...
Impose injections on buses
def Write(self, packet): """See base class.""" if len(packet) != self.GetOutReportDataLength(): raise errors.HidError("Packet length must match report data length.") packet_data = [0] + packet # Prepend the zero-byte (report ID) out = bytes(bytearray(packet_data)) num_written = wintypes.DWOR...
See base class.
def _read(self, n): """Read (up to) 'n' bytes from the underlying file. If any bytes have been pushed in with _unread() those are returned first.""" if n <= len(self._prefix): # the read can be fulfilled entirely from the prefix result = self._prefix[:n] self...
Read (up to) 'n' bytes from the underlying file. If any bytes have been pushed in with _unread() those are returned first.
def merge(self, other): """ Merge another object as needed. """ other.qualify() for n in ('name', 'qname', 'min', 'max', 'default', 'type', 'nillable', 'f...
Merge another object as needed.
def add_tarball(self, tarball, package): """Add a tarball, possibly creating the directory if needed.""" if tarball is None: logger.error( "No tarball found for %s: probably a renamed project?", package) return target_dir = os.path.join(sel...
Add a tarball, possibly creating the directory if needed.
def get_machines_by_groups(self, groups): """Gets all machine references which are in one of the specified groups. in groups of type str What groups to match. The usual group list rules apply, i.e. passing an empty list will match VMs in the toplevel group, likewise ...
Gets all machine references which are in one of the specified groups. in groups of type str What groups to match. The usual group list rules apply, i.e. passing an empty list will match VMs in the toplevel group, likewise the empty string. return machines of type :c...
def _validate(self): """ Step 5 (1st flow) or Step 4 (2nd flow). Process contract for object. """ # disable methods matching before validation self._disable_patching = True # validation by Invariant.validate self._validate_base(self) # enable methods match...
Step 5 (1st flow) or Step 4 (2nd flow). Process contract for object.
def _parse_epsilon(line, lines): """Parse Energy [eV] Re_eps_xx Im_eps_xx Re_eps_zz Im_eps_zz""" split_line = line.split() energy = float(split_line[0]) re_eps_xx = float(split_line[1]) im_eps_xx = float(split_line[2]) re_eps_zz = float(split_line[3]) im_eps_zz = float(split_li...
Parse Energy [eV] Re_eps_xx Im_eps_xx Re_eps_zz Im_eps_zz
def from_metadata(cls, metadata: Dict[str, Any]) -> 'LogFields': """Initialize the log fields from the provided metadata The log fields are taken from the `LOG_FIELDS_KEY_META` key of the provided metadata. """ return cls(fields=json.loads(metadata.get(LOG_FIELDS_KEY_META, '{}'...
Initialize the log fields from the provided metadata The log fields are taken from the `LOG_FIELDS_KEY_META` key of the provided metadata.
def _extract_relations(self, attribute: str) -> Tuple[List[str], str]: """Split and return the list of relation(s) and the attribute. :param attribute: :type attribute: str :return: A tuple where the first element is the list of related entities and the second is the attrib...
Split and return the list of relation(s) and the attribute. :param attribute: :type attribute: str :return: A tuple where the first element is the list of related entities and the second is the attribute. :rtype: Tuple[List[str], str]
def divide_separate_words(string_matrix: List[List[str]]) -> List[List[str]]: """ As part of processing, some words obviously need to be separated. :param string_matrix: a data matrix: a list wrapping a list of strings, with each sublist being a sentence. :return: >>> divide_separate_words([['ita ve...
As part of processing, some words obviously need to be separated. :param string_matrix: a data matrix: a list wrapping a list of strings, with each sublist being a sentence. :return: >>> divide_separate_words([['ita vero'], ['quid', 'est', 'veritas']]) [['ita', 'vero'], ['quid', 'est', 'veritas']]
def PSHUFW(cpu, op0, op1, op3): """ Packed shuffle words. Copies doublewords from source operand (second operand) and inserts them in the destination operand (first operand) at locations selected with the order operand (third operand). :param cpu: current CPU. :param op...
Packed shuffle words. Copies doublewords from source operand (second operand) and inserts them in the destination operand (first operand) at locations selected with the order operand (third operand). :param cpu: current CPU. :param op0: destination operand. :param op1: source o...
def schedule_branches(b: bool, quoted_true, quoted_false): """ Helper function to choose which workflow to execute based on the boolean `b`. :param b: promised boolean value :param quoted_true: quoted workflow to eval if the boolean is true. :param quoted_true: quoted work...
Helper function to choose which workflow to execute based on the boolean `b`. :param b: promised boolean value :param quoted_true: quoted workflow to eval if the boolean is true. :param quoted_true: quoted workflow to eval if the boolean is false.
def mark_as_required(self): """Adds this loss to the MARKED_LOSSES collection.""" if self not in tf.get_collection(bookkeeper.GraphKeys.MARKED_LOSSES): tf.add_to_collection(bookkeeper.GraphKeys.MARKED_LOSSES, self)
Adds this loss to the MARKED_LOSSES collection.
def getarchive(project, user, format=None): """Generates and returns a download package (or 403 if one is already in the process of being prepared)""" if os.path.isfile(Project.path(project, user) + '.download'): #make sure we don't start two compression processes at the same time ...
Generates and returns a download package (or 403 if one is already in the process of being prepared)
def sort_rows(self, rows, section): """Sort the rows, as appropriate for the section. :param rows: List of tuples (all same length, same values in each position) :param section: Name of section, should match const in Differ class :return: None; rows are sorted in-place """ ...
Sort the rows, as appropriate for the section. :param rows: List of tuples (all same length, same values in each position) :param section: Name of section, should match const in Differ class :return: None; rows are sorted in-place
def pushover(message, token, user, title="JCVI: Job Monitor", \ priority=0, timestamp=None): """ pushover.net python API <https://pushover.net/faq#library-python> """ assert -1 <= priority <= 2, \ "Priority should be an int() between -1 and 2" if timestamp == None: ...
pushover.net python API <https://pushover.net/faq#library-python>
def netmiko_args(**kwargs): ''' .. versionadded:: 2019.2.0 Return the key-value arguments used for the authentication arguments for the netmiko module. When running in a non-native NAPALM driver (e.g., ``panos``, `f5``, ``mos`` - either from https://github.com/napalm-automation-community or de...
.. versionadded:: 2019.2.0 Return the key-value arguments used for the authentication arguments for the netmiko module. When running in a non-native NAPALM driver (e.g., ``panos``, `f5``, ``mos`` - either from https://github.com/napalm-automation-community or defined in user's own environment, one...
def kick(self, channel, target, reason=None): """kick target from channel""" if reason: target += ' :' + reason self.send_line('KICK %s %s' % (channel, target), nowait=True)
kick target from channel
def _ploadf(ins): """ Loads from stack pointer (SP) + X, being X 2st parameter. 1st operand must be a SIGNED integer. """ output = _pload(ins.quad[2], 5) output.extend(_fpush()) return output
Loads from stack pointer (SP) + X, being X 2st parameter. 1st operand must be a SIGNED integer.
def make_html_list(items, tag="ul"): # type: (Iterable[Any], str) -> str """ Makes a HTML list from the given iterable :param items: The items to list :param tag: The tag to use (ul or ol) :return: The HTML list code """ html_list = "\n".join( '<li><a href="{0}">{0}</a></li>'.fo...
Makes a HTML list from the given iterable :param items: The items to list :param tag: The tag to use (ul or ol) :return: The HTML list code
def read_icgem_gfc(filename, errors=None, lmax=None, epoch=None): """ Read spherical harmonic coefficients from an ICGEM GFC ascii-formatted file. This function only reads files with the gravity field spherical harmonic coefficients. Returns ------- cilm : array Array with the ...
Read spherical harmonic coefficients from an ICGEM GFC ascii-formatted file. This function only reads files with the gravity field spherical harmonic coefficients. Returns ------- cilm : array Array with the coefficients with the shape (2, lmax + 1, lmax + 1) for the given epoc...
def get_paths(self, key): "Like `gets`, but include the paths, like `get_path` for all matches." result_list = [] if key in self.keys(): result_list.append(((key,), self[key])) for sub_key, v in self.items(): if isinstance(v, self.__class__): sub_r...
Like `gets`, but include the paths, like `get_path` for all matches.
def build_client_schema( introspection: Dict, assume_valid: bool = False ) -> GraphQLSchema: """Build a GraphQLSchema for use by client tools. Given the result of a client running the introspection query, creates and returns a GraphQLSchema instance which can be then used with all GraphQL-core-next too...
Build a GraphQLSchema for use by client tools. Given the result of a client running the introspection query, creates and returns a GraphQLSchema instance which can be then used with all GraphQL-core-next tools, but cannot be used to execute a query, as introspection does not represent the "resolver", "...
def _hour_angle_to_hours(times, hourangle, longitude, equation_of_time): """converts hour angles in degrees to hours as a numpy array""" naive_times = times.tz_localize(None) # naive but still localized tzs = 1 / NS_PER_HR * ( naive_times.astype(np.int64) - times.astype(np.int64)) hours = (hour...
converts hour angles in degrees to hours as a numpy array
def bsn(self) -> str: """Generate a random, but valid ``Burgerservicenummer``. :returns: Random BSN. :Example: 255159705 """ def _is_valid_bsn(number: str) -> bool: total = 0 multiplier = 9 for char in number: mul...
Generate a random, but valid ``Burgerservicenummer``. :returns: Random BSN. :Example: 255159705
def make_pkh_output_script(pubkey, witness=False): ''' bytearray -> bytearray ''' if witness and not riemann.network.SEGWIT: raise ValueError( 'Network {} does not support witness scripts.' .format(riemann.get_current_network_name())) output_script = bytearray() ...
bytearray -> bytearray
def _proc_cyclic(self): """ Handles cyclic group molecules. """ main_axis, rot = max(self.rot_sym, key=lambda v: v[1]) self.sch_symbol = "C{}".format(rot) mirror_type = self._find_mirror(main_axis) if mirror_type == "h": self.sch_symbol += "h" ...
Handles cyclic group molecules.
def cut(args): """ %prog cut unitigfile fragID Cut the unitig at a given fragment. Run `%prog trace unitigfile` first to see which fragment breaks the unitig. """ from jcvi.formats.base import SetFile p = OptionParser(cut.__doc__) p.add_option("-s", dest="shredafter", default=False, ac...
%prog cut unitigfile fragID Cut the unitig at a given fragment. Run `%prog trace unitigfile` first to see which fragment breaks the unitig.
def all_as_list(): ''' returns a list of all defined containers ''' as_dict = all_as_dict() containers = as_dict['Running'] + as_dict['Frozen'] + as_dict['Stopped'] containers_list = [] for i in containers: i = i.replace(' (auto)', '') containers_list.append(i) ...
returns a list of all defined containers
def tree_node_to_xml(self, parent, item): """Converts a treeview item and children to xml nodes""" tree = self.treeview data = self.treedata[item] node = data.to_xml_node() children = tree.get_children(item) for child in children: cnode = ET.Element('child')...
Converts a treeview item and children to xml nodes
def _toUnicode(self, data, encoding): '''Given a string and its encoding, decodes the string into Unicode. %encoding is a string recognized by encodings.aliases''' # strip Byte Order Mark (if present) if (len(data) >= 4) and (data[:2] == '\xfe\xff') \ and (data[2:4] != '\...
Given a string and its encoding, decodes the string into Unicode. %encoding is a string recognized by encodings.aliases
def write(self): '''Write the job to the corresponding plist.''' with open(self.me, 'w') as f: f.write(self.printMe(self.tag, self.value))
Write the job to the corresponding plist.
def map_fit(interface, state, label, inp): """ Function calculates sigmoid function (g) for every sample. With g it calculates part of Hessian matrix and gradient, aggregates and output them. It also calculates J function which is needed for checking the convergence of parameters theta. """ import numpy...
Function calculates sigmoid function (g) for every sample. With g it calculates part of Hessian matrix and gradient, aggregates and output them. It also calculates J function which is needed for checking the convergence of parameters theta.
def query(self): """ Returns the full query for this widget. This will reflect the complete combined query for all containers within this widget. :return <orb.Query> """ if self._loadQuery is not None: return self._loadQuery ...
Returns the full query for this widget. This will reflect the complete combined query for all containers within this widget. :return <orb.Query>
def close(self): """Close the socket underlying this connection.""" self.rfile.close() if not self.linger: self._close_kernel_socket() self.socket.close() else: # On the other hand, sometimes we want to hang around for a bit # to make sure...
Close the socket underlying this connection.
def heatcapacity(ddtt): """ Heat capacity (kJ/m2-K) of a construction or material. thickness (m) * density (kg/m3) * specific heat (J/kg-K) * 0.001 """ object_type = ddtt.obj[0] if object_type == 'Construction': heatcapacity = 0 layers = ddtt.obj[2:] field_idd = ddtt.getf...
Heat capacity (kJ/m2-K) of a construction or material. thickness (m) * density (kg/m3) * specific heat (J/kg-K) * 0.001
def is_value_from_deprecated_setting(self, setting_name, deprecated_setting_name): """ Helps developers to determine where the settings helper got it's value from when dealing with settings that replace deprecated settings. Returns ``True`` when the new setting (with the name ``setting_...
Helps developers to determine where the settings helper got it's value from when dealing with settings that replace deprecated settings. Returns ``True`` when the new setting (with the name ``setting_name``) is a replacement for a deprecated setting (with the name ``deprecated_setting_n...
def del_register_user(self, register_user): """ Deletes registration object from database :param register_user: RegisterUser object to delete """ try: self.get_session.delete(register_user) self.get_session.commit() return True ...
Deletes registration object from database :param register_user: RegisterUser object to delete
def merge_versions(self, merge_id): """Get the merge versions from pagination""" payload = { 'order_by': 'updated_at', 'sort': 'asc', 'per_page': PER_PAGE } path = urijoin(GitLabClient.MERGES, str(merge_id), GitLabClient.VERSIONS) return self...
Get the merge versions from pagination
def _get_window_labels(self, window): """Returns the mapping between sliding window points and their contigs, and the x-axis position of contig Parameters ---------- window : int Size of the window. Returns ------- xbars : list Th...
Returns the mapping between sliding window points and their contigs, and the x-axis position of contig Parameters ---------- window : int Size of the window. Returns ------- xbars : list The x-axis position of the ending for each contig. ...
def run_mcl(matrix, expansion=2, inflation=2, loop_value=1, iterations=100, pruning_threshold=0.001, pruning_frequency=1, convergence_check_frequency=1, verbose=False): """ Perform MCL on the given similarity matrix :param matrix: The similarity matrix to cluster :param expa...
Perform MCL on the given similarity matrix :param matrix: The similarity matrix to cluster :param expansion: The cluster expansion factor :param inflation: The cluster inflation factor :param loop_value: Initialization value for self-loops :param iterations: Maximum number of iterations ...
def check_permission(self, permission_s, logical_operator=all): """ :param permission_s: a collection of 1..N permissions :type permission_s: List of authz_abcs.Permission objects or Strings :param logical_operator: indicates whether all or at least one ...
:param permission_s: a collection of 1..N permissions :type permission_s: List of authz_abcs.Permission objects or Strings :param logical_operator: indicates whether all or at least one permission check is true (any) :type: any OR all (from python stdlib) ...
def evolve(self, years): """ run the evolution of the planet to see how it looks after 'years' """ world_file = fldr + os.sep + self.name + '.txt' self.build_base() self.world.add_mountains() self.add_life() self.world.grd.save(world_file) ...
run the evolution of the planet to see how it looks after 'years'
def create_thumbnail(img, width, height): """ 创建缩略图 缩略图的意思就是缩小 :param img: 图片对象 :param width: 宽 :param height: 高 :return: """ size = (width, height) img.thumbnail(size) return img
创建缩略图 缩略图的意思就是缩小 :param img: 图片对象 :param width: 宽 :param height: 高 :return:
def _get_dbt_columns_from_bq_table(self, table): "Translates BQ SchemaField dicts into dbt BigQueryColumn objects" columns = [] for col in table.schema: # BigQuery returns type labels that are not valid type specifiers dtype = self.Column.translate_type(col.field_type) ...
Translates BQ SchemaField dicts into dbt BigQueryColumn objects
def get_authenticate_header(self, request): """ If a request is unauthenticated, determine the WWW-Authenticate header to use for 401 responses, if any. """ authenticators = self.get_authenticators() if authenticators: return authenticators[0].authenticate_hea...
If a request is unauthenticated, determine the WWW-Authenticate header to use for 401 responses, if any.
def show_preview(viewer_path, pdf_file_name): """Run the PDF viewer at the path viewer_path on the file pdf_file_name.""" try: cmd = [viewer_path, pdf_file_name] run_external_subprocess_in_background(cmd) except (subprocess.CalledProcessError, OSError, IOError) as e: print("\nWarning...
Run the PDF viewer at the path viewer_path on the file pdf_file_name.
def attach(session_type, address=None, port=None, path=None, argv=None, decode=None): """Provide a nicer interface to create python api sessions. Previous machinery to create python api sessions is still there. This only creates a facade function to make things easier for the most usual cases. ...
Provide a nicer interface to create python api sessions. Previous machinery to create python api sessions is still there. This only creates a facade function to make things easier for the most usual cases. Thus, instead of: from pynvim import socket_session, Nvim session = tcp_session(addre...
def salt_token_tool(): ''' If the custom authentication header is supplied, put it in the cookie dict so the rest of the session-based auth works as intended ''' x_auth = cherrypy.request.headers.get('X-Auth-Token', None) # X-Auth-Token header trumps session cookie if x_auth: cherry...
If the custom authentication header is supplied, put it in the cookie dict so the rest of the session-based auth works as intended
def update_json_file(filename, items): """Updates the json `filename` with a given dict. :param filename: path to json file (e.g. /etc/glance/policy.json) :param items: dict of items to update """ if not items: return with open(filename) as fd: policy = json.load(fd) # Comp...
Updates the json `filename` with a given dict. :param filename: path to json file (e.g. /etc/glance/policy.json) :param items: dict of items to update
def relate(self, part, id=None): """Relate this package component to the supplied part.""" assert part.name.startswith(self.base) name = part.name[len(self.base):].lstrip('/') rel = Relationship(self, name, part.rel_type, id=id) self.relationships.add(rel) return rel
Relate this package component to the supplied part.
def _compress(compress): ''' Resolve compression flags ''' if compress in ('bz2', 'bzip2', 'j'): compression = 'j' ext = 'bz2' elif compress in ('gz', 'gzip', 'z'): compression = 'z' ext = 'gz' elif compress in ('xz', 'a', 'J'): compression = 'J' e...
Resolve compression flags
def get_missing_deps(self, obj): ''' Returns missing dependencies for provider key. Missing meaning no instance can be provided at this time. :param key: Provider key :type key: object :return: Missing dependencies :rtype: list ''' deps = self.get...
Returns missing dependencies for provider key. Missing meaning no instance can be provided at this time. :param key: Provider key :type key: object :return: Missing dependencies :rtype: list
def whoarewe(self, shutit_pexpect_child=None, note=None, loglevel=logging.DEBUG): """Returns the current group. @param shutit_pexpect_child: See send() @param note: See send() @return: the first group found @rtype: string """ shutit_global.shutit_global_o...
Returns the current group. @param shutit_pexpect_child: See send() @param note: See send() @return: the first group found @rtype: string
def update_values(self): """ This method is for updating in the finite horizon case. It shifts the current value function .. math:: V_t(x) = x' P_t x + d_t and the optimal policy :math:`F_t` one step *back* in time, replacing the pair :math:`P_t` and :mat...
This method is for updating in the finite horizon case. It shifts the current value function .. math:: V_t(x) = x' P_t x + d_t and the optimal policy :math:`F_t` one step *back* in time, replacing the pair :math:`P_t` and :math:`d_t` with :math:`P_{t-1}` and :mat...
def get_field(self, offset, length, format): """Returns unpacked Python struct array. Args: offset (int): offset to byte array within structure length (int): how many bytes to unpack format (str): Python struct format string for unpacking See Also: ...
Returns unpacked Python struct array. Args: offset (int): offset to byte array within structure length (int): how many bytes to unpack format (str): Python struct format string for unpacking See Also: https://docs.python.org/2/library/struct.html#format-...
def save_response(self, service, operation, response_data, http_response=200): """ Store a response to the data directory. The ``operation`` should be the name of the operation in the service API (e.g. DescribeInstances), the ``response_data`` should a value you wa...
Store a response to the data directory. The ``operation`` should be the name of the operation in the service API (e.g. DescribeInstances), the ``response_data`` should a value you want to return from a placebo call and the ``http_response`` should be the HTTP status code returned from t...
def aggregate(self, q=None, scroll_size=SEARCH_LIMIT, reset_query=True, **kwargs): """Perform an advanced query, and return *all* matching results. Will automatically perform multiple queries in order to retrieve all results. Note: All ``aggregate`` queries run in advanced mode, and...
Perform an advanced query, and return *all* matching results. Will automatically perform multiple queries in order to retrieve all results. Note: All ``aggregate`` queries run in advanced mode, and ``info`` is not available. Arguments: q (str): The query to execute. **D...
def create(self, data, inlineparent = None): ''' Compatible to Parser.create() ''' if self.cstr: return _copy(data).rstrip(b'\x00') else: return _copy(data)
Compatible to Parser.create()
def triggerLogicToStr(self): """ Print all the trigger logic to a string and return it. """ try: import json except ImportError: return "Cannot dump triggers/dependencies/executes (need json)" retval = "TRIGGERS:\n"+json.dumps(self._allTriggers, indent=3) ...
Print all the trigger logic to a string and return it.
def get_chain(self, name, table="filter"): """ Get the list of rules for a particular chain. Chain order is kept intact. Args: name (str): chain name, e.g. `` table (str): table name, defaults to ``filter`` Returns: list: rules """ re...
Get the list of rules for a particular chain. Chain order is kept intact. Args: name (str): chain name, e.g. `` table (str): table name, defaults to ``filter`` Returns: list: rules
def robot_wireless(max_iters=100, kernel=None, optimize=True, plot=True): """Predict the location of a robot given wirelss signal strength readings.""" try:import pods except ImportError: print('pods unavailable, see https://github.com/sods/ods for example datasets') return data = pods.d...
Predict the location of a robot given wirelss signal strength readings.
def enable(name, **kwargs): ''' Enable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.enable <service name> ''' if _service_is_upstart(name): return _upstart_enable(name) executable = _get_service_exec() cmd = '{0} -f {1} defaults...
Enable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.enable <service name>
def pool(inputs, window_size, pooling_type, padding, strides=(1, 1)): """Pooling (supports "LEFT").""" with tf.name_scope("pool", values=[inputs]): static_shape = inputs.get_shape() if not static_shape or len(static_shape) != 4: raise ValueError("Inputs to conv must have statically known rank 4.") ...
Pooling (supports "LEFT").
def getSecret(self, *args, **kwargs): """ Get a Secret Retrieve a secret from storage. The result contains any passwords or other restricted information verbatim as well as a temporary credential based on the scopes specified when the secret was created. It is importan...
Get a Secret Retrieve a secret from storage. The result contains any passwords or other restricted information verbatim as well as a temporary credential based on the scopes specified when the secret was created. It is important that this secret is deleted by the consumer (`removeSecr...
def K(self, X, X2, target): """Return covariance between X and X2.""" self._K_computations(X, X2) target += self.variance*self._K_dvar
Return covariance between X and X2.
def _build_natgrad_step_op(self, model, q_mu_param, q_sqrt_param, xi_transform): """ Implements equation 10 from @inproceedings{salimbeni18, title={Natural Gradients in Practice: Non-Conjugate Variational Inference in Gaussian Process Models}, author={Salimbeni, Hugh an...
Implements equation 10 from @inproceedings{salimbeni18, title={Natural Gradients in Practice: Non-Conjugate Variational Inference in Gaussian Process Models}, author={Salimbeni, Hugh and Eleftheriadis, Stefanos and Hensman, James}, booktitle={AISTATS}, year={201...
def build_new_deep_neural_network_from_env_variables(): """build_new_deep_neural_network_from_env_variables Build a new deep neural network from environment variables: ``CSV_FILE`` - file to process created during prepare dataset ``CSV_META_FILE`` - metadata header file created during prepare dataset ...
build_new_deep_neural_network_from_env_variables Build a new deep neural network from environment variables: ``CSV_FILE`` - file to process created during prepare dataset ``CSV_META_FILE`` - metadata header file created during prepare dataset ``PREDICT_FEATURE`` - column to predict ``TEST_SIZE`` -...
def _unescape_math(xml): """Unescapes Math from Mathjax to MathML.""" xpath_math_script = etree.XPath( '//x:script[@type="math/mml"]', namespaces={'x': 'http://www.w3.org/1999/xhtml'}) math_script_list = xpath_math_script(xml) for mathscript in math_script_list: math = ma...
Unescapes Math from Mathjax to MathML.
def gravatar(self, size): """ Get url to gravatar """ hash = md5(self.email.encode('utf-8')).hexdigest() url = 'http://www.gravatar.com/avatar/{}?d=mm&s={}' return url.format(hash, size)
Get url to gravatar
def init(**config): """ Initialize the crypto backend. The backend can be one of two plugins: - 'x509' - Uses x509 certificates. - 'gpg' - Uses GnuPG keys. """ global _implementation global _validate_implementations if config.get('crypto_backend') == 'gpg': _implementa...
Initialize the crypto backend. The backend can be one of two plugins: - 'x509' - Uses x509 certificates. - 'gpg' - Uses GnuPG keys.
def rsquare(obsvalues, # type: Union[numpy.ndarray, List[Union[float, int]]] simvalues # type: Union[numpy.ndarray, List[Union[float, int]]] ): # type: (...) -> Union[float, numpy.ScalarType] """Calculate Coefficient of determination. Same as the square of the ...
Calculate Coefficient of determination. Same as the square of the Pearson correlation coefficient (r), and, the same as the built-in Excel function RSQ(). Programmed according to equation (1) in Legates, D.R. and G.J. McCabe, 1999. Evaluating the use of "goodness of fit" measu...
def p_const_vector_elem_list(p): """ const_number_list : expr """ if p[1] is None: return if not is_static(p[1]): if isinstance(p[1], symbols.UNARY): tmp = make_constexpr(p.lineno(1), p[1]) else: api.errmsg.syntax_error_not_constant(p.lexer.lineno) ...
const_number_list : expr
def connect(*args, **kwargs): """Create database connection, use TraceCursor as the cursor_factory.""" kwargs['cursor_factory'] = TraceCursor conn = pg_connect(*args, **kwargs) return conn
Create database connection, use TraceCursor as the cursor_factory.
def cancel_requests(self): """Cancels pending requests.""" self._timer.stop() self._job = None self._args = None self._kwargs = None
Cancels pending requests.
def center_crop(src, size, interp=2): """Crops the image `src` to the given `size` by trimming on all four sides and preserving the center of the image. Upsamples if `src` is smaller than `size`. .. note:: This requires MXNet to be compiled with USE_OPENCV. Parameters ---------- src : NDAr...
Crops the image `src` to the given `size` by trimming on all four sides and preserving the center of the image. Upsamples if `src` is smaller than `size`. .. note:: This requires MXNet to be compiled with USE_OPENCV. Parameters ---------- src : NDArray Binary source image data. siz...
def decode_iter_request(data: dict) -> Optional[Union[str, int]]: """ Decode incoming response from an iteration request Args: data: Response data Returns: Next itervalue """ if "response_metadata" in data: return data["response_metadata"].get("next_cursor") elif "p...
Decode incoming response from an iteration request Args: data: Response data Returns: Next itervalue
def add_latlon_metadata(lat_var, lon_var): """Adds latitude and longitude metadata""" lat_var.long_name = 'latitude' lat_var.standard_name = 'latitude' lat_var.units = 'degrees_north' lat_var.axis = 'Y' lon_var.long_name = 'longitude' lon_var.standard_name = 'longitude' lon_var.units = ...
Adds latitude and longitude metadata
def get_value(self, constraints, expression): """ Ask the solver for one possible result of given expression using given set of constraints. """ if not issymbolic(expression): return expression assert isinstance(expression, (Bool, BitVec, Array)) with constrai...
Ask the solver for one possible result of given expression using given set of constraints.
def addinnode(self, otherplus, node, objectname): """add an item to the node. example: add a new zone to the element 'ZONE' """ # do a test for unique object here newelement = otherplus.dt[node.upper()]
add an item to the node. example: add a new zone to the element 'ZONE'
def map_geometries(func, obj): """ Returns the result of passing every geometry in the given geojson object through func. :param func: Function to apply to tuples :type func: function :param obj: A geometry or feature to extract the coordinates from. :type obj: GeoJSON :return: The resu...
Returns the result of passing every geometry in the given geojson object through func. :param func: Function to apply to tuples :type func: function :param obj: A geometry or feature to extract the coordinates from. :type obj: GeoJSON :return: The result of applying the function to each geometr...
def throughput(sample, window=1, format='decimal'): ''' Return the throughput in (intelli)bytes per second. :param sample: number of samples sent :param window: default 1, sample window in seconds or :class:`datetime.timedelta` object :param format: default 'decimal', see :func:`...
Return the throughput in (intelli)bytes per second. :param sample: number of samples sent :param window: default 1, sample window in seconds or :class:`datetime.timedelta` object :param format: default 'decimal', see :func:`natural.size.filesize` >>> print(throughput(123456, 42)) ...
def delta_cdf(self, d_min, d_max, n=None): r'''Computes the difference in cumulative distribution function between two particle size diameters. .. math:: \Delta Q_n = Q_n(d_{max}) - Q_n(d_{min}) Parameters ---------- ...
r'''Computes the difference in cumulative distribution function between two particle size diameters. .. math:: \Delta Q_n = Q_n(d_{max}) - Q_n(d_{min}) Parameters ---------- d_min : float Lower particle size diame...
def encrypt(self, value): """Encrypt session data.""" timestamp = str(int(time.time())) value = base64.b64encode(value.encode(self.encoding)) signature = create_signature(self.secret, value + timestamp.encode(), encoding=self.encoding) return ...
Encrypt session data.
def combine_info(self, all_infos): """Combine metadata for multiple datasets. When loading data from multiple files it can be non-trivial to combine things like start_time, end_time, start_orbit, end_orbit, etc. By default this method will produce a dictionary containing all values ...
Combine metadata for multiple datasets. When loading data from multiple files it can be non-trivial to combine things like start_time, end_time, start_orbit, end_orbit, etc. By default this method will produce a dictionary containing all values that were equal across **all** provided i...
def run(): """ Generate TestCases from cmdfile according to the pattern in patternfile""" #Define the import statements impheader = """import sys import conv_base """ #Define the test case pattern pattern="""class Test%d(conv_base.%sCase): @classmethod def setUpClass(cls): cls.obsmo...
Generate TestCases from cmdfile according to the pattern in patternfile
def find(self, sym: sym.Symbol) -> Optional[Var]: """Find Vars mapped by the given Symbol input or None if no Vars are mapped by that Symbol.""" v = self.interns.entry(sym, None) if v is None: return self.refers.entry(sym, None) return v
Find Vars mapped by the given Symbol input or None if no Vars are mapped by that Symbol.
def related_archives(self): """ The pathnames of the source distribution(s) for this requirement (a list of strings). .. note:: This property is very new in pip-accel and its logic may need some time to mature. For now any misbehavior by this property shouldn...
The pathnames of the source distribution(s) for this requirement (a list of strings). .. note:: This property is very new in pip-accel and its logic may need some time to mature. For now any misbehavior by this property shouldn't be too much of a problem because the pathname...
def chi_a(mass1, mass2, spin1z, spin2z): """ Returns the aligned mass-weighted spin difference from mass1, mass2, spin1z, and spin2z. """ return (spin2z * mass2 - spin1z * mass1) / (mass2 + mass1)
Returns the aligned mass-weighted spin difference from mass1, mass2, spin1z, and spin2z.
def create_token(user): """ Create token. """ payload = jwt_payload_handler(user) if api_settings.JWT_ALLOW_REFRESH: payload['orig_iat'] = timegm( datetime.utcnow().utctimetuple() ) # Return values token = jwt_encode_handler(payload) return token
Create token.
def timeline_public(self, max_id=None, min_id=None, since_id=None, limit=None, only_media=False): """ Fetches the public / visible-network timeline, not including replies. Set `only_media` to True to retrieve only statuses with media attachments. Returns a list of `toot dicts`_. ...
Fetches the public / visible-network timeline, not including replies. Set `only_media` to True to retrieve only statuses with media attachments. Returns a list of `toot dicts`_.
def get_subject_with_remote_validation(jwt_bu64, base_url): """Same as get_subject_with_local_validation() except that the signing certificate is automatically downloaded from the CN. - Additional possible validations errors: - The certificate could not be retrieved from the root CN. """ ce...
Same as get_subject_with_local_validation() except that the signing certificate is automatically downloaded from the CN. - Additional possible validations errors: - The certificate could not be retrieved from the root CN.
def token_to_id(self, token): """Get the token_id of given token. Args: token (str): token from vocabulary. Returns: int: int id of token. """ token = self.process_token(token) return self._token2id.get(token, len(self._token2id) - 1)
Get the token_id of given token. Args: token (str): token from vocabulary. Returns: int: int id of token.
def serialize(self, data): ''' Serlialize the output based on the Accept header ''' self.set_header('Content-Type', self.content_type) return self.dumper(data)
Serlialize the output based on the Accept header
def serialize_comment(ctx, document, el, root): "Serializes comment." # Check if option is turned on if el.comment_type == 'end': ctx.opened_comments.remove(el.cid) else: if el.comment_type != 'reference': ctx.opened_comments.append(el.cid) if ctx.options['comment_...
Serializes comment.