code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def build_css_class(localized_fieldname, prefix=''): """ Returns a css class based on ``localized_fieldname`` which is easily splitable and capable of regionalized language codes. Takes an optional ``prefix`` which is prepended to the returned string. """ bits = localized_fieldname.split('_') ...
Returns a css class based on ``localized_fieldname`` which is easily splitable and capable of regionalized language codes. Takes an optional ``prefix`` which is prepended to the returned string.
def connection_factory(self, endpoint, *args, **kwargs): """ Called to create a new connection with proper configuration. Intended for internal use only. """ kwargs = self._make_connection_kwargs(endpoint, kwargs) return self.connection_class.factory(endpoint, self.connec...
Called to create a new connection with proper configuration. Intended for internal use only.
def symbols(): """Return a list of symbols.""" symbols = [] for line in symbols_stream(): symbols.append(line.decode('utf-8').strip()) return symbols
Return a list of symbols.
def languages(self): """ A list of strings describing the user's languages. """ languages = [] for language in self.cache['languages']: language = Structure( id = language['id'], name = language['name'] ) langu...
A list of strings describing the user's languages.
def fetch(self): """ Fetch a CompositionSettingsInstance :returns: Fetched CompositionSettingsInstance :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsInstance """ params = values.of({}) payload = self._version.fetch( 'GET', ...
Fetch a CompositionSettingsInstance :returns: Fetched CompositionSettingsInstance :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsInstance
def strip_transcript_versions(fasta, out_file): """ strip transcript versions from a FASTA file. these appear like this: >ENST00000434970.2 cdna chromosome:GRCh38:14:22439007:22439015:1 etc """ if file_exists(out_file): return out_file with file_transaction(out_file) as tx_out_file: ...
strip transcript versions from a FASTA file. these appear like this: >ENST00000434970.2 cdna chromosome:GRCh38:14:22439007:22439015:1 etc
def _dihedral_affine(k:partial(uniform_int,0,7)): "Randomly flip `x` image based on `k`." x = -1 if k&1 else 1 y = -1 if k&2 else 1 if k&4: return [[0, x, 0.], [y, 0, 0], [0, 0, 1.]] return [[x, 0, 0.], [0, y, 0], [0, 0, 1.]]
Randomly flip `x` image based on `k`.
def check_minions(self, expr, tgt_type='glob', delimiter=DEFAULT_TARGET_DELIM, greedy=True): ''' Check the passed regex against the available minions' public keys stored for authentication. This should return...
Check the passed regex against the available minions' public keys stored for authentication. This should return a set of ids which match the regex, this will then be used to parse the returns to make sure everyone has checked back in.
def bilinear(x, W, y, input_size, seq_len, batch_size, num_outputs=1, bias_x=False, bias_y=False): """Do xWy Parameters ---------- x : NDArray (input_size x seq_len) x batch_size W : NDArray (num_outputs x ny) x nx y : NDArray (input_size x seq_len) x batch_size inpu...
Do xWy Parameters ---------- x : NDArray (input_size x seq_len) x batch_size W : NDArray (num_outputs x ny) x nx y : NDArray (input_size x seq_len) x batch_size input_size : int input dimension seq_len : int sequence length batch_size : int ...
def add_page(self, pattern, classname): """ Add a new page to the web application. Only available after that the Plugin Manager is loaded """ if not self._loaded: raise PluginManagerNotLoadedException() self._app.add_mapping(pattern, classname)
Add a new page to the web application. Only available after that the Plugin Manager is loaded
def _request_delete(self, path, params=None, url=BASE_URL): """Perform a HTTP DELETE request.""" url = urljoin(url, path) headers = self._get_request_headers() response = requests.delete( url, params=params, headers=headers, timeout=DEFAULT_TIMEOUT) response.raise_f...
Perform a HTTP DELETE request.
def copy(self): """Return a shallow copy of a RangeSet.""" cpy = self.__class__() cpy._autostep = self._autostep cpy.padding = self.padding cpy.update(self) return cpy
Return a shallow copy of a RangeSet.
def remove_objects(self, bucket_name, objects_iter): """ Removes multiple objects from a bucket. :param bucket_name: Bucket from which to remove objects :param objects_iter: A list, tuple or iterator that provides objects names to delete. :return: An iterator of MultiD...
Removes multiple objects from a bucket. :param bucket_name: Bucket from which to remove objects :param objects_iter: A list, tuple or iterator that provides objects names to delete. :return: An iterator of MultiDeleteError instances for each object that had a delete error.
def get_collection(cls): """Return a reference to the database collection for the class""" # By default the collection returned will be the published collection, # however if the `draft` flag has been set against the global context # (e.g `g`) then the collection returned will contain d...
Return a reference to the database collection for the class
def _dep_map(self): """ A map of extra to its list of (direct) requirements for this distribution, including the null extra. """ try: return self.__dep_map except AttributeError: self.__dep_map = self._filter_extras(self._build_dep_map()) r...
A map of extra to its list of (direct) requirements for this distribution, including the null extra.
def upload(self, f): """Upload a file to the Puush account. Parameters: * f: The file. Either a path to a file or a file-like object. """ if hasattr(f, 'read'): needs_closing = False else: f = open(f, 'rb') needs_closing = ...
Upload a file to the Puush account. Parameters: * f: The file. Either a path to a file or a file-like object.
def _distance_matrix_generic(x, centering, exponent=1): """Compute a centered distance matrix given a matrix.""" _check_valid_dcov_exponent(exponent) x = _transform_to_2d(x) # Calculate distance matrices a = distances.pairwise_distances(x, exponent=exponent) # Double centering a = centeri...
Compute a centered distance matrix given a matrix.
def BE64(value, min_value=None, max_value=None, fuzzable=True, name=None, full_range=False): '''64-bit field, Big endian encoded''' return UInt64(value, min_value=min_value, max_value=max_value, encoder=ENC_INT_BE, fuzzable=fuzzable, name=name, full_range=full_range)
64-bit field, Big endian encoded
def save(self, filename, binary=True): """ Writes a surface mesh to disk. Written file may be an ASCII or binary ply, stl, or vtk mesh file. Parameters ---------- filename : str Filename of mesh to be written. File type is inferred from the exte...
Writes a surface mesh to disk. Written file may be an ASCII or binary ply, stl, or vtk mesh file. Parameters ---------- filename : str Filename of mesh to be written. File type is inferred from the extension of the filename unless overridden with ft...
def temporal_louvain(tnet, resolution=1, intersliceweight=1, n_iter=100, negativeedge='ignore', randomseed=None, consensus_threshold=0.5, temporal_consensus=True, njobs=1): r""" Louvain clustering for a temporal network. Parameters ----------- tnet : array, dict, TemporalNetwork Input netwo...
r""" Louvain clustering for a temporal network. Parameters ----------- tnet : array, dict, TemporalNetwork Input network resolution : int resolution of Louvain clustering ($\gamma$) intersliceweight : int interslice weight of multilayer clustering ($\omega$). Must be pos...
def get_size(self, value=None): """Return the size in bytes. Args: value: In structs, the user can assign other value instead of this class' instance. Here, in such cases, ``self`` is a class attribute of the struct. Returns: int: The siz...
Return the size in bytes. Args: value: In structs, the user can assign other value instead of this class' instance. Here, in such cases, ``self`` is a class attribute of the struct. Returns: int: The size in bytes.
def kruskal_mst(graph): """Implements Kruskal's Algorithm for finding minimum spanning trees. Assumes a non-empty, connected graph. """ edges_accepted = 0 ds = DisjointSet() pq = PriorityQueue() accepted_edges = [] label_lookup = {} nodes = graph.get_all_node_ids() num_vertices ...
Implements Kruskal's Algorithm for finding minimum spanning trees. Assumes a non-empty, connected graph.
def multicategory_scatterplot(output_directory, file_prefix, df, x_series_index, y_series_index, category_series_index, series_color, plot_title = '', x_axis_label = '', y_axis_label = '', min_predict...
This function was adapted from the covariation benchmark.
def send(self, to, subject, body, reply_to=None, **kwargs): """ Send email via AWS SES. :returns string: message id *** Composes an email message based on input data, and then immediately queues the message for sending. :type to: list of strings or string ...
Send email via AWS SES. :returns string: message id *** Composes an email message based on input data, and then immediately queues the message for sending. :type to: list of strings or string :param to: The To: field(s) of the message. :type subject: string ...
def command_clean(string, vargs): """ Remove characters that are not IPA valid from the given string, and print the remaining string. :param str string: the string to act upon :param dict vargs: the command line arguments """ valid_chars, invalid_chars = remove_invalid_ipa_characters( ...
Remove characters that are not IPA valid from the given string, and print the remaining string. :param str string: the string to act upon :param dict vargs: the command line arguments
def ls_command( endpoint_plus_path, recursive_depth_limit, recursive, long_output, show_hidden, filter_val, ): """ Executor for `globus ls` """ endpoint_id, path = endpoint_plus_path # do autoactivation before the `ls` call so that recursive invocations # won't do this r...
Executor for `globus ls`
def _get_footer_size(file_obj): """Read the footer size in bytes, which is serialized as little endian.""" file_obj.seek(-8, 2) tup = struct.unpack(b"<i", file_obj.read(4)) return tup[0]
Read the footer size in bytes, which is serialized as little endian.
def fit(self, X, y, n_iter=None): """w = w + α * δ * X""" self.n_iter = self.n_iter if n_iter is None else n_iter X = getattr(X, 'values', X).reshape(len(X), 1) X_1 = self.homogenize(X) for i in range(self.n_iter): for i in range(0, len(X), 10): # minibatch learning ...
w = w + α * δ * X
def set_line_width(self, width): """Sets the current line width within the cairo context. The line width value specifies the diameter of a pen that is circular in user space, (though device-space pen may be an ellipse in general due to scaling / shear / rotation of the CTM). ...
Sets the current line width within the cairo context. The line width value specifies the diameter of a pen that is circular in user space, (though device-space pen may be an ellipse in general due to scaling / shear / rotation of the CTM). .. note:: When the descript...
def _init_level_set(init_level_set, image_shape): """Auxiliary function for initializing level sets with a string. If `init_level_set` is not a string, it is returned as is. """ if isinstance(init_level_set, str): if init_level_set == 'checkerboard': res = checkerboard_level_set(ima...
Auxiliary function for initializing level sets with a string. If `init_level_set` is not a string, it is returned as is.
def write_bytes(self, where, data, force=False): """ Write a concrete or symbolic (or mixed) buffer to memory :param int where: address to write to :param data: data to write :type data: str or list :param force: whether to ignore memory permissions """ ...
Write a concrete or symbolic (or mixed) buffer to memory :param int where: address to write to :param data: data to write :type data: str or list :param force: whether to ignore memory permissions
def t_BIN(self, t): r'(%[01]+)|([01]+[bB])' # A Binary integer # Note 00B is a 0 binary, but # 00Bh is a 12 in hex. So this pattern must come # after HEXA if t.value[0] == '%': t.value = t.value[1:] # Remove initial % else: t.value = t.value[:-1...
r'(%[01]+)|([01]+[bB])
def save(name, data, rc_file='~/.odoorpcrc'): """Save the `data` session configuration under the name `name` in the `rc_file` file. >>> import odoorpc >>> odoorpc.session.save( ... 'foo', ... {'type': 'ODOO', 'host': 'localhost', 'protocol': 'jsonrpc', ... 'port': 8069, 'timeou...
Save the `data` session configuration under the name `name` in the `rc_file` file. >>> import odoorpc >>> odoorpc.session.save( ... 'foo', ... {'type': 'ODOO', 'host': 'localhost', 'protocol': 'jsonrpc', ... 'port': 8069, 'timeout': 120, 'database': 'db_name' ... 'user': '...
def add_vertex(self, vertex, **attr): """ Add vertex and update vertex attributes """ self.vertices[vertex] = [] if attr: self.nodes[vertex] = attr
Add vertex and update vertex attributes
def add_chart(self, component): """Add a chart to the layout.""" if getattr(component, "name") != "Chart": raise Exception("Component is not an instance of Chart") self.charts.append(component)
Add a chart to the layout.
def build_module(name, doc=None): """create and initialize an astroid Module node""" node = nodes.Module(name, doc, pure_python=False) node.package = False node.parent = None return node
create and initialize an astroid Module node
def preorder(self, skip_seed=False): """ Return a generator that yields the nodes of the tree in preorder. If skip_seed=True then the root node is not included. """ for node in self._tree.preorder_node_iter(): if skip_seed and node is self._tree.seed_node: ...
Return a generator that yields the nodes of the tree in preorder. If skip_seed=True then the root node is not included.
def delete_volume(target, stop=True): ''' Deletes a gluster volume target Volume to delete stop : True If ``True``, stop volume before delete CLI Example: .. code-block:: bash salt '*' glusterfs.delete_volume <volume> ''' volinfo = info() if target not in...
Deletes a gluster volume target Volume to delete stop : True If ``True``, stop volume before delete CLI Example: .. code-block:: bash salt '*' glusterfs.delete_volume <volume>
def set_setting(name, value): ''' Set the configuration for the named audit setting Args: name (str): The name of the setting to configure value (str): The configuration for the named value. Valid options are: - No Auditing - Success ...
Set the configuration for the named audit setting Args: name (str): The name of the setting to configure value (str): The configuration for the named value. Valid options are: - No Auditing - Success - Failure - Success and ...
def _make_value(self, value): """ Constructs a _child_spec value from a native Python data type, or an appropriate Asn1Value object :param value: A native Python value, or some child of Asn1Value :return: An object of type _child_spec """ ...
Constructs a _child_spec value from a native Python data type, or an appropriate Asn1Value object :param value: A native Python value, or some child of Asn1Value :return: An object of type _child_spec
def create_application(self): """Create and return a new instance of tinman.application.Application""" return application.Application(self.settings, self.namespace.routes, self.port)
Create and return a new instance of tinman.application.Application
def update_value_from_mapping(source_resource_attr_id, target_resource_attr_id, source_scenario_id, target_scenario_id, **kwargs): """ Using a resource attribute mapping, take the value from the source and apply it to the target. Both source and target scenarios must be specified (and therefor ...
Using a resource attribute mapping, take the value from the source and apply it to the target. Both source and target scenarios must be specified (and therefor must exist).
def _initialise(self, feed_type="linear"): """ Initialise the object by generating appropriate filenames, opening associated file handles and inspecting the FITS axes of these files. """ self._filenames = filenames = _create_filenames(self._filename_schema, ...
Initialise the object by generating appropriate filenames, opening associated file handles and inspecting the FITS axes of these files.
def uniqid(iface='wlan0', is_hex=True): """ 使用网卡的物理地址 ``默认wlan0`` 来作为标识 - 置位 ``is_hex``, 来确定返回 ``16进制/10进制格式`` :param iface: ``网络接口(默认wlan0)`` :type iface: str :param is_hex: ``True(返回16进制)/False(10进制)`` :type is_hex: bool :return: ``mac地址/空`` :rtype: str """ # return s...
使用网卡的物理地址 ``默认wlan0`` 来作为标识 - 置位 ``is_hex``, 来确定返回 ``16进制/10进制格式`` :param iface: ``网络接口(默认wlan0)`` :type iface: str :param is_hex: ``True(返回16进制)/False(10进制)`` :type is_hex: bool :return: ``mac地址/空`` :rtype: str
def add_reader(self, fd, callback): " Start watching the file descriptor for read availability. " h = msvcrt.get_osfhandle(fd) self._read_fds[h] = callback
Start watching the file descriptor for read availability.
def get_shape_str(tensors): """ Internally used by layer registry, to print shapes of inputs/outputs of layers. Args: tensors (list or tf.Tensor): a tensor or a list of tensors Returns: str: a string to describe the shape """ if isinstance(tensors, (list, tuple)): for v ...
Internally used by layer registry, to print shapes of inputs/outputs of layers. Args: tensors (list or tf.Tensor): a tensor or a list of tensors Returns: str: a string to describe the shape
def get_parameter(self): """Obtain the parameter object from the current widget state. :returns: A BooleanParameter from the current state of widget """ self._parameter.value = self._input.value() return self._parameter
Obtain the parameter object from the current widget state. :returns: A BooleanParameter from the current state of widget
def refreshUi( self ): """ Refreshes the interface based on the current settings. """ widget = self.uiContentsTAB.currentWidget() is_content = isinstance(widget, QWebView) if is_content: self._currentContentsIndex = self.uiContentsTAB.currentInd...
Refreshes the interface based on the current settings.
def serialize_to_file(obj, file_name, append=False): """Pickle obj to file_name.""" logging.info("Serializing to file %s.", file_name) with tf.gfile.Open(file_name, "a+" if append else "wb") as output_file: pickle.dump(obj, output_file) logging.info("Done serializing to file %s.", file_name)
Pickle obj to file_name.
def NormalizePath(path, sep="/"): """A sane implementation of os.path.normpath. The standard implementation treats leading / and // as different leading to incorrect normal forms. NOTE: Its ok to use a relative path here (without leading /) but any /../ will still be removed anchoring the path at the top le...
A sane implementation of os.path.normpath. The standard implementation treats leading / and // as different leading to incorrect normal forms. NOTE: Its ok to use a relative path here (without leading /) but any /../ will still be removed anchoring the path at the top level (e.g. foo/../../../../bar => bar)...
def __track_vars(self, command_result): """ Check if there are any tracked variable inside the result. And keep them for future use. :param command_result: command result tot check :return: """ command_env = command_result.environment() for var_name in self.tracked_vars(): if var_name in command_env.ke...
Check if there are any tracked variable inside the result. And keep them for future use. :param command_result: command result tot check :return:
def unicode_wrapper(self, property, default=ugettext('Untitled')): """ Wrapper to allow for easy unicode representation of an object by the specified property. If this wrapper is not able to find the right translation of the specified property, it will return the default value in...
Wrapper to allow for easy unicode representation of an object by the specified property. If this wrapper is not able to find the right translation of the specified property, it will return the default value instead. Example:: def __unicode__(self): return uni...
def print_markdown(data, title=None): """Print data in GitHub-flavoured Markdown format for issues etc. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be rendered as headline 2. """ def excl_value(value): # contains path, i.e. personal info re...
Print data in GitHub-flavoured Markdown format for issues etc. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be rendered as headline 2.
def suggest(self, index=None, body=None, params=None): """ The suggest feature suggests similar looking terms based on a provided text by using a suggester. `<http://elasticsearch.org/guide/reference/api/search/suggest/>`_ :arg index: A comma-separated list of index names to res...
The suggest feature suggests similar looking terms based on a provided text by using a suggester. `<http://elasticsearch.org/guide/reference/api/search/suggest/>`_ :arg index: A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the ...
def convert_value(v): """ 默认使用Json转化数据,凡以[或{开始的,均载入json :param v: :return: """ if v and isinstance(v, six.string_types): v = v.strip() if (v.startswith('{') and v.endswith('}')) or (v.startswith('[') and v.endswith(']')): try: return json.loads(v) ...
默认使用Json转化数据,凡以[或{开始的,均载入json :param v: :return:
def course_feature(catalog, soup): """Parses all the courses (AKA, the most important part). """ courses = {} course_crns = {} for course in soup.findAll('course'): c = Course.from_soup_tag(course) courses[str(c)] = c catalog.courses = courses catalog.courses logger.info(...
Parses all the courses (AKA, the most important part).
def subscribe(self, channel_name): """Subscribe to a channel :param channel_name: The name of the channel to subscribe to. :type channel_name: str :rtype : Channel """ data = {'channel': channel_name} if channel_name.startswith('presence-'): data['a...
Subscribe to a channel :param channel_name: The name of the channel to subscribe to. :type channel_name: str :rtype : Channel
def _write(self, command, future): """Write a command to the socket :param Command command: the Command data structure """ def on_written(): self._on_written(command, future) try: self._stream.write(command.command, callback=on_written) except ...
Write a command to the socket :param Command command: the Command data structure
def _get_key_from_raw_synset(raw_synset): """Derives synset key in the form of `lemma.pos.sense_no` from the provided eurown.py Synset class, Notes ----- Internal function. Do not call directly. Parameters ---------- raw_synset : eurown.Synset Synset representation from which lemma,...
Derives synset key in the form of `lemma.pos.sense_no` from the provided eurown.py Synset class, Notes ----- Internal function. Do not call directly. Parameters ---------- raw_synset : eurown.Synset Synset representation from which lemma, part-of-speech and sense is derived. Return...
def API_GET(self, courseid, taskid, submissionid): # pylint: disable=arguments-differ """ List all the submissions that the connected user made. Returns list of the form :: [ { "id": "submission_id1", ...
List all the submissions that the connected user made. Returns list of the form :: [ { "id": "submission_id1", "submitted_on": "date", "status" : "done", #can be "done", "waiting", "error" ...
def get_possible_combos_for_transition(trans, model, self_model, is_external=False): """ The function provides combos for a transition and its respective :param trans: :param model: :param self_model: :param is_external: :return: """ from_state_combo = Gt...
The function provides combos for a transition and its respective :param trans: :param model: :param self_model: :param is_external: :return:
def do_videoplaceholder(parser, token): """ Method that parse the imageplaceholder template tag. """ name, params = parse_placeholder(parser, token) return VideoPlaceholderNode(name, **params)
Method that parse the imageplaceholder template tag.
def build_dependencies(self) -> "Dependencies": """ Return `Dependencies` instance containing the build dependencies available on this Package. The ``Package`` class should provide access to the full dependency tree. .. code:: python >>> owned_package.build_dependencies['zep...
Return `Dependencies` instance containing the build dependencies available on this Package. The ``Package`` class should provide access to the full dependency tree. .. code:: python >>> owned_package.build_dependencies['zeppelin'] <ZeppelinPackage>
def capability(cap, *wrap_exceptions): """ Return a decorator, that registers function as capability. Also, all specified exceptions are caught and instead of them the :class:`.WClientCapabilityError` exception is raised :param cap: target function capability (may be a str or :class:`.WNetworkClientCapabilities`...
Return a decorator, that registers function as capability. Also, all specified exceptions are caught and instead of them the :class:`.WClientCapabilityError` exception is raised :param cap: target function capability (may be a str or :class:`.WNetworkClientCapabilities` class ) :param wrap_exceptions: exceptions...
def on_success(self, retval, task_id, args, kwargs): """on_success http://docs.celeryproject.org/en/latest/reference/celery.app.task.html :param retval: return value :param task_id: celery task id :param args: arguments passed into task :param kwargs: keyword arguments ...
on_success http://docs.celeryproject.org/en/latest/reference/celery.app.task.html :param retval: return value :param task_id: celery task id :param args: arguments passed into task :param kwargs: keyword arguments passed into task
def complete_set_acls(self, cmd_param_text, full_cmd, *rest): """ FIXME: complete inside a quoted param is broken """ possible_acl = [ "digest:", "username_password:", "world:anyone:c", "world:anyone:cd", "world:anyone:cdr", "world:...
FIXME: complete inside a quoted param is broken
def get_config_node(self): '''get_config_node High-level api: get_config_node returns an Element node in the config tree, which is corresponding to the URL in the Restconf GET reply. Returns ------- Element A config node. ''' default_ns = '...
get_config_node High-level api: get_config_node returns an Element node in the config tree, which is corresponding to the URL in the Restconf GET reply. Returns ------- Element A config node.
def _get_chat(self) -> Dict: """ As Telegram changes where the chat object is located in the response, this method tries to be smart about finding it in the right place. """ if 'callback_query' in self._update: query = self._update['callback_query'] if 'm...
As Telegram changes where the chat object is located in the response, this method tries to be smart about finding it in the right place.
def _serialiseServices(self, jobStore, jobGraph, rootJobGraph): """ Serialises the services for a job. """ def processService(serviceJob, depth): # Extend the depth of the services if necessary if depth == len(jobGraph.services): jobGraph.services....
Serialises the services for a job.
def regressfile(filename): """ Run all stories in filename 'filename' in python 2 and 3. Rewrite stories if appropriate. """ _storybook().in_filename(filename).with_params( **{"python version": "2.7.14"} ).ordered_by_name().play() _storybook().with_params(**{"python version": "3.7.0...
Run all stories in filename 'filename' in python 2 and 3. Rewrite stories if appropriate.
def is_temple_project(): """Raises `InvalidTempleProjectError` if repository is not a temple project""" if not os.path.exists(temple.constants.TEMPLE_CONFIG_FILE): msg = 'No {} file found in repository.'.format(temple.constants.TEMPLE_CONFIG_FILE) raise temple.exceptions.InvalidTempleProjectErro...
Raises `InvalidTempleProjectError` if repository is not a temple project
def copy_module(target_path, my_directory_full_path, my_module): ''' Helper function for copy_module_to_local(). Provides the actual copy functionality, with highly cautious safeguards against copying over important things. Parameters ---------- target_path : string String, file pat...
Helper function for copy_module_to_local(). Provides the actual copy functionality, with highly cautious safeguards against copying over important things. Parameters ---------- target_path : string String, file path to target location my_directory_full_path: string String, full...
def _fn_with_diet_vars(fn, args, params): """Call function with args; use diet variables according to params.""" vs_ctr = [] def grad_fn(inputs, variables, outputs, output_grads): """Custom gradient function.""" del outputs # recomputing below with common_layers.fn_device_dependency("diet_grad", ...
Call function with args; use diet variables according to params.
def create_chunked_body_end(trailers=None): """Create the ending that terminates a chunked body.""" chunk = [] chunk.append('0\r\n') if trailers: for name, value in trailers: chunk.append(name) chunk.append(': ') chunk.append(value) chunk.append('\...
Create the ending that terminates a chunked body.
def sg_rnn_layer_func(func): r"""Decorates function as sg_rnn_layer functions. Args: func: function to decorate """ @wraps(func) def wrapper(tensor, **kwargs): r"""Manages arguments of `tf.sg_opt`. Args: tensor: automatically passed by decorator kwargs: ...
r"""Decorates function as sg_rnn_layer functions. Args: func: function to decorate
def parse(self, text, html=True): '''Parse the text and return a ParseResult instance.''' self._urls = [] self._users = [] self._lists = [] self._tags = [] reply = REPLY_REGEX.match(text) reply = reply.groups(0)[0] if reply is not None else None parsed_h...
Parse the text and return a ParseResult instance.
def add(self, node): """Register a top level node (and its children) for syncing up to the server. There's no need to call this for nodes created by :py:meth:`createNote` or :py:meth:`createList` as they are automatically added. LoginException: If :py:meth:`login` has not been called. ...
Register a top level node (and its children) for syncing up to the server. There's no need to call this for nodes created by :py:meth:`createNote` or :py:meth:`createList` as they are automatically added. LoginException: If :py:meth:`login` has not been called. Args: node (gkeep...
def read_config(self): """ Read credentials from the config file """ with open(self.config_file) as cfg: try: self.config.read_file(cfg) except AttributeError: self.config.readfp(cfg) self.client_id = self.config.get('exist', 'client_id') ...
Read credentials from the config file
def call_openssl(cmd, message, silent=False): """ call openssl :param cmd: a string of command send to openssl :param message: a string to print out if not silent :param silent: a boolean for whether to suppress output from openssl """ if silent: with open(os.devnull, 'w') as devnull...
call openssl :param cmd: a string of command send to openssl :param message: a string to print out if not silent :param silent: a boolean for whether to suppress output from openssl
def custom_size(self, minimum: int = 40, maximum: int = 62) -> int: """Generate clothing size using custom format. :param minimum: Minimum value. :param maximum: Maximum value. :return: Clothing size. """ return self.random.randint(minimum, maximum)
Generate clothing size using custom format. :param minimum: Minimum value. :param maximum: Maximum value. :return: Clothing size.
def guard_handler(instance, transition_id): """Generic workflow guard handler that returns true if the transition_id passed in can be performed to the instance passed in. This function is called automatically by a Script (Python) located at bika/lims/skins/guard_handler.py, which in turn is fired by Zo...
Generic workflow guard handler that returns true if the transition_id passed in can be performed to the instance passed in. This function is called automatically by a Script (Python) located at bika/lims/skins/guard_handler.py, which in turn is fired by Zope when an expression like "python:here.guard_h...
def _maintain_parent(self, request, response): """ Maintain the parent ID in the querystring for response_add and response_change. """ location = response._headers.get("location") parent = request.GET.get("parent") if parent and location and "?" not in location[1]...
Maintain the parent ID in the querystring for response_add and response_change.
def unlock(self): """ Releases the lock. """ return self._encode_invoke(lock_unlock_codec, thread_id=thread_id(), reference_id=self.reference_id_generator.get_and_increment())
Releases the lock.
def delete_data(self, url, *args, **kwargs): """Deletes data under provided url Returns status as boolean. Args: **url**: address of file to be deleted .. versionadded:: 0.3.2 **additional_headers**: (optional) Additional headers to be u...
Deletes data under provided url Returns status as boolean. Args: **url**: address of file to be deleted .. versionadded:: 0.3.2 **additional_headers**: (optional) Additional headers to be used with request Returns: Boolean. ...
def send(self, stanza, *, timeout=None, cb=None): """ Send a stanza. :param stanza: Stanza to send :type stanza: :class:`~.IQ`, :class:`~.Presence` or :class:`~.Message` :param timeout: Maximum time in seconds to wait for an IQ response, or :data:`None` t...
Send a stanza. :param stanza: Stanza to send :type stanza: :class:`~.IQ`, :class:`~.Presence` or :class:`~.Message` :param timeout: Maximum time in seconds to wait for an IQ response, or :data:`None` to disable the timeout. :type timeout: :class:`~numbers.Real` o...
def generate_VJ_junction_transfer_matrices(self): """Compute the transfer matrices for the VJ junction. Sets the attributes Tvj, Svj, Dvj, lTvj, and lDvj. """ nt2num = {'A': 0, 'C': 1, 'G': 2, 'T': 3} #Compute Tvj Tv...
Compute the transfer matrices for the VJ junction. Sets the attributes Tvj, Svj, Dvj, lTvj, and lDvj.
def create_graph(grid): """ This function creates a graph of vertices and edges from segments returned by SLIC. :param array grid: A grid of segments as returned by the slic function defined in skimage library :return: A graph as [vertices, edges] """ try: import numpy as np except I...
This function creates a graph of vertices and edges from segments returned by SLIC. :param array grid: A grid of segments as returned by the slic function defined in skimage library :return: A graph as [vertices, edges]
def decorate_event_js(js_code): """setup a method as an event, adding also javascript code to generate Args: js_code (str): javascript code to generate the event client-side. js_code is added to the widget html as widget.attributes['onclick'] = js_code%{'emitter_identifier':wid...
setup a method as an event, adding also javascript code to generate Args: js_code (str): javascript code to generate the event client-side. js_code is added to the widget html as widget.attributes['onclick'] = js_code%{'emitter_identifier':widget.identifier, 'event_name':'onclick'}
def getWorkersName(data): """Returns the list of the names of the workers sorted alphabetically""" names = [fichier for fichier in data.keys()] names.sort() try: names.remove("broker") except ValueError: pass return names
Returns the list of the names of the workers sorted alphabetically
def validate(schema, data, owner=None): """Validate input data with input schema. :param Schema schema: schema able to validate input data. :param data: data to validate. :param Schema owner: input schema parent schema. :raises: Exception if the data is not validated. """ schema._validate(d...
Validate input data with input schema. :param Schema schema: schema able to validate input data. :param data: data to validate. :param Schema owner: input schema parent schema. :raises: Exception if the data is not validated.
def solve_resolve(expr, vars): """Use IStructured.resolve to get member (rhs) from the object (lhs). This operation supports both scalars and repeated values on the LHS - resolving from a repeated value implies a map-like operation and returns a new repeated values. """ objs, _ = __solve_for_re...
Use IStructured.resolve to get member (rhs) from the object (lhs). This operation supports both scalars and repeated values on the LHS - resolving from a repeated value implies a map-like operation and returns a new repeated values.
def set_title(self, title, subtitle=''): """Set the title and the subtitle of the suite.""" self.title = title self.subtitle = subtitle
Set the title and the subtitle of the suite.
def pole_error(ax, fit, **kwargs): """ Plot the error to the pole to a plane on a `mplstereonet` axis object. """ ell = normal_errors(fit.axes, fit.covariance_matrix) lonlat = -N.array(ell) n = len(lonlat) codes = [Path.MOVETO] codes += [Path.LINETO]*(n-1) vertices = list(lonlat)...
Plot the error to the pole to a plane on a `mplstereonet` axis object.
def stop(self): """Stop the name server. """ self.listener.setsockopt(LINGER, 1) self.loop = False with nslock: self.listener.close()
Stop the name server.
def pyeapi_nxos_api_args(**prev_kwargs): ''' .. versionadded:: 2019.2.0 Return the key-value arguments used for the authentication arguments for the :mod:`pyeapi execution module <salt.module.arista_pyeapi>`. CLI Example: .. code-block:: bash salt '*' napalm.pyeapi_nxos_api_args ...
.. versionadded:: 2019.2.0 Return the key-value arguments used for the authentication arguments for the :mod:`pyeapi execution module <salt.module.arista_pyeapi>`. CLI Example: .. code-block:: bash salt '*' napalm.pyeapi_nxos_api_args
def constcase(text, acronyms=None): """Return text in CONST_CASE style (aka SCREAMING_SNAKE_CASE). Args: text: input string to convert case detect_acronyms: should attempt to detect acronyms acronyms: a list of acronyms to detect >>> constcase("hello world") 'HELLO_WORLD' >...
Return text in CONST_CASE style (aka SCREAMING_SNAKE_CASE). Args: text: input string to convert case detect_acronyms: should attempt to detect acronyms acronyms: a list of acronyms to detect >>> constcase("hello world") 'HELLO_WORLD' >>> constcase("helloHTMLWorld", True, ["HTML...
def to_string_with_default(value, default_value): """ Converts value into string or returns default when value is None. :param value: the value to convert. :param default_value: the default value. :return: string value or default when value is null. """ result ...
Converts value into string or returns default when value is None. :param value: the value to convert. :param default_value: the default value. :return: string value or default when value is null.
def best(cls): """ Select the best ScriptWriter suitable for Windows """ writer_lookup = dict( executable=WindowsExecutableLauncherWriter, natural=cls, ) # for compatibility, use the executable launcher by default launcher = os.environ.get(...
Select the best ScriptWriter suitable for Windows
def _inject_specs(self, specs): """Injects targets into the graph for the given `Specs` object. Yields the resulting addresses. """ if not specs: return logger.debug('Injecting specs to %s: %s', self, specs) with self._resolve_context(): thts, = self._scheduler.product_request(Tran...
Injects targets into the graph for the given `Specs` object. Yields the resulting addresses.
def multivariate_normality(X, alpha=.05): """Henze-Zirkler multivariate normality test. Parameters ---------- X : np.array Data matrix of shape (n_samples, n_features). alpha : float Significance level. Returns ------- normal : boolean True if X comes from a mul...
Henze-Zirkler multivariate normality test. Parameters ---------- X : np.array Data matrix of shape (n_samples, n_features). alpha : float Significance level. Returns ------- normal : boolean True if X comes from a multivariate normal distribution. p : float ...