code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def add_with_properties(self, model, name=None, update_dict=None, bulk=True, **kwargs): """ Add a part and update its properties in one go. In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as additional keyword=value argument to this method....
Add a part and update its properties in one go. In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as additional keyword=value argument to this method. This will improve performance of the backend against a trade-off that someone looking at the fronte...
def get_event(self, client, check): """ Returns an event for a given client & check name. """ data = self._request('GET', '/events/{}/{}'.format(client, check)) return data.json()
Returns an event for a given client & check name.
def stop_server(self): """ Stop serving. Also stops the thread. """ if self.rpc_server is not None: try: self.rpc_server.socket.shutdown(socket.SHUT_RDWR) except: log.warning("Failed to shut down server socket") self.r...
Stop serving. Also stops the thread.
def _any_bound_condition_fails_criterion(agent, criterion): """Returns True if any bound condition fails to meet the specified criterion. Parameters ---------- agent: Agent The agent whose bound conditions we evaluate criterion: function Evaluates criterion(a) for each a in a bo...
Returns True if any bound condition fails to meet the specified criterion. Parameters ---------- agent: Agent The agent whose bound conditions we evaluate criterion: function Evaluates criterion(a) for each a in a bound condition and returns True if any agents fail to meet t...
def delete(self, request, bot_id, hook_id, id, format=None): """ Delete an existing telegram recipient --- responseMessages: - code: 401 message: Not authenticated """ bot = self.get_bot(bot_id, request.user) hook = self.get_hook(hook_...
Delete an existing telegram recipient --- responseMessages: - code: 401 message: Not authenticated
def from_json(cls, service_dict): """Create a service object from a JSON string.""" sd = service_dict.copy() service_endpoint = sd.get(cls.SERVICE_ENDPOINT) if not service_endpoint: logger.error( 'Service definition in DDO document is missing the "serviceEndpo...
Create a service object from a JSON string.
def clone(self, document): ''' Serialize a document, remove its _id, and deserialize as a new object ''' wrapped = document.wrap() if '_id' in wrapped: del wrapped['_id'] return type(document).unwrap(wrapped, session=self)
Serialize a document, remove its _id, and deserialize as a new object
def tt_qr(X, left_to_right=True): """ Orthogonalizes a TT tensor from left to right or from right to left. :param: X - thensor to orthogonalise :param: direction - direction. May be 'lr/LR' or 'rl/RL' for left/right orthogonalization :return: X_orth, R - orthogonal tensor and right (...
Orthogonalizes a TT tensor from left to right or from right to left. :param: X - thensor to orthogonalise :param: direction - direction. May be 'lr/LR' or 'rl/RL' for left/right orthogonalization :return: X_orth, R - orthogonal tensor and right (left) upper (lower) triangular mat...
def remove_breakpoint(self, event_type, bp=None, filter_func=None): """ Removes a breakpoint. :param bp: The breakpoint to remove. :param filter_func: A filter function to specify whether each breakpoint should be removed or not. """ if bp is None and filter_func is No...
Removes a breakpoint. :param bp: The breakpoint to remove. :param filter_func: A filter function to specify whether each breakpoint should be removed or not.
def add(self, album, objects, object_type=None, **kwds): """ Endpoint: /album/<id>/<type>/add.json Add objects (eg. Photos) to an album. The objects are a list of either IDs or Trovebox objects. If Trovebox objects are used, the object type is inferred automatically. ...
Endpoint: /album/<id>/<type>/add.json Add objects (eg. Photos) to an album. The objects are a list of either IDs or Trovebox objects. If Trovebox objects are used, the object type is inferred automatically. Returns the updated album object.
def docs(root_url, path): """Generate URL for path in the Taskcluster docs.""" root_url = root_url.rstrip('/') path = path.lstrip('/') if root_url == OLD_ROOT_URL: return 'https://docs.taskcluster.net/{}'.format(path) else: return '{}/docs/{}'.format(root_url, path)
Generate URL for path in the Taskcluster docs.
def normal(self): ''' :return: Line Returns a Line normal (perpendicular) to this Line. ''' d = self.B - self.A return Line([-d.y, d.x], [d.y, -d.x])
:return: Line Returns a Line normal (perpendicular) to this Line.
def write(url, content, **args): """Put the object/collection into a file URL.""" with HTTPResource(url, **args) as resource: resource.write(content)
Put the object/collection into a file URL.
def resort_client_actions(portal): """Resorts client action views """ sorted_actions = [ "edit", "contacts", "view", # this redirects to analysisrequests "analysisrequests", "batches", "samplepoints", "profiles", "templates", "specs", ...
Resorts client action views
def multiCall(*commands, dependent=True, bundle=False, print_result=False, print_commands=False): """ Calls the function 'call' multiple times, given sets of commands """ results = [] dependent_failed = False for command in commands: if not dependent_failed: re...
Calls the function 'call' multiple times, given sets of commands
def ensure_mingw_drive(win32_path): r""" replaces windows drives with mingw style drives Args: win32_path (str): CommandLine: python -m utool.util_path --test-ensure_mingw_drive Example: >>> # DISABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> win32_...
r""" replaces windows drives with mingw style drives Args: win32_path (str): CommandLine: python -m utool.util_path --test-ensure_mingw_drive Example: >>> # DISABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> win32_path = r'C:/Program Files/Foobar' ...
def getFactors(self, aLocation, axisOnly=False, allFactors=False): """ Return a list of all factors and math items at aLocation. factor, mathItem, deltaName all = True: include factors that are zero or near-zero """ deltas = [] aLocation.expand(self.ge...
Return a list of all factors and math items at aLocation. factor, mathItem, deltaName all = True: include factors that are zero or near-zero
def reprString(self, string, length): """ Output a string of length tokens in the original form. If string is an integer, it is considered as an offset in the text. Otherwise string is considered as a sequence of ids (see voc and tokId). >>> SA=SuffixArray('mississippi',...
Output a string of length tokens in the original form. If string is an integer, it is considered as an offset in the text. Otherwise string is considered as a sequence of ids (see voc and tokId). >>> SA=SuffixArray('mississippi', UNIT_BYTE) >>> SA.reprString(0, 3) 'mis' ...
def clear_caches(delete_all=False): """Fortpy caches many things, that should be completed after each completion finishes. :param delete_all: Deletes also the cache that is normally not deleted, like parser cache, which is important for faster parsing. """ global _time_caches if delete...
Fortpy caches many things, that should be completed after each completion finishes. :param delete_all: Deletes also the cache that is normally not deleted, like parser cache, which is important for faster parsing.
def save_model(self, request, obj, form, change): """ Saves the message for the recipient and looks in the form instance for other possible recipients. Prevents duplication by excludin the original recipient from the list of optional recipients. When changing an existing message...
Saves the message for the recipient and looks in the form instance for other possible recipients. Prevents duplication by excludin the original recipient from the list of optional recipients. When changing an existing message and choosing optional recipients, the message is effectively ...
def add_requirements(self, metadata_path): """Add additional requirements from setup.cfg to file metadata_path""" additional = list(self.setupcfg_requirements()) if not additional: return pkg_info = read_pkg_info(metadata_path) if 'Provides-Extra' in pkg_info or 'Requires-Dist' i...
Add additional requirements from setup.cfg to file metadata_path
def copy(self): """ Creates copy of the digest CTX to allow to compute digest while being able to hash more data """ new_digest = Digest(self.digest_type) libcrypto.EVP_MD_CTX_copy(new_digest.ctx, self.ctx) return new_digest
Creates copy of the digest CTX to allow to compute digest while being able to hash more data
def fill_triangle(setter, x0, y0, x1, y1, x2, y2, color=None, aa=False): """Draw solid triangle with points x0,y0 - x1,y1 - x2,y2""" a = b = y = last = 0 if y0 > y1: y0, y1 = y1, y0 x0, x1 = x1, x0 if y1 > y2: y2, y1 = y1, y2 x2, x1 = x1, x2 if y0 > y1: y0, y...
Draw solid triangle with points x0,y0 - x1,y1 - x2,y2
def is_all_field_none(self): """ :rtype: bool """ if self._id_ is not None: return False if self._created is not None: return False if self._updated is not None: return False if self._type_ is not None: return Fa...
:rtype: bool
def key_81_CosSin_2009(): r"""Key 81 pt CosSin filter, as published in [Key09]_. Taken from file ``FilterModules.f90`` provided with 1DCSEM_. License: `Apache License, Version 2.0, <http://www.apache.org/licenses/LICENSE-2.0>`_. """ dlf = DigitalFilter('Key 81 CosSin (2009)', 'key_81_CosSin_...
r"""Key 81 pt CosSin filter, as published in [Key09]_. Taken from file ``FilterModules.f90`` provided with 1DCSEM_. License: `Apache License, Version 2.0, <http://www.apache.org/licenses/LICENSE-2.0>`_.
def _close(self, args): """Request a connection close This method indicates that the sender wants to close the connection. This may be due to internal conditions (e.g. a forced shut-down) or due to an error handling a specific method, i.e. an exception. When a close is due to a...
Request a connection close This method indicates that the sender wants to close the connection. This may be due to internal conditions (e.g. a forced shut-down) or due to an error handling a specific method, i.e. an exception. When a close is due to an exception, the sender pro...
def add_line(self, line='', *, empty=False): """Adds a line to the current page. If the line exceeds the :attr:`max_size` then an exception is raised. Parameters ----------- line: :class:`str` The line to add. empty: :class:`bool` Indicat...
Adds a line to the current page. If the line exceeds the :attr:`max_size` then an exception is raised. Parameters ----------- line: :class:`str` The line to add. empty: :class:`bool` Indicates if another empty line should be added. Raise...
def _create_arg_dict(self, tenant_id, data, in_sub, out_sub): """Create the argument dictionary. """ in_seg, in_vlan = self.get_in_seg_vlan(tenant_id) out_seg, out_vlan = self.get_out_seg_vlan(tenant_id) in_ip_dict = self.get_in_ip_addr(tenant_id) out_ip_dict = self.get_out_ip_ad...
Create the argument dictionary.
def fetch_json(self, uri_path, http_method='GET', query_params=None, body=None, headers=None): ''' Make a call to Trello API and capture JSON response. Raises an error when it fails. Returns: dict: Dictionary with the JSON data ''' query_pa...
Make a call to Trello API and capture JSON response. Raises an error when it fails. Returns: dict: Dictionary with the JSON data
def use_setuptools( version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15 ): """Automatically find/download setuptools and make it available on sys.path `version` should be a valid setuptools version number that is available as an egg for download under the `downlo...
Automatically find/download setuptools and make it available on sys.path `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where setuptools will be downloaded, if it is n...
def infer_format(filename:str) -> str: """Return extension identifying format of given filename""" _, ext = os.path.splitext(filename) return ext
Return extension identifying format of given filename
def client_for(service, service_module, thrift_service_name=None): """Build a synchronous client class for the given Thrift service. The generated class accepts a TChannelSyncClient and an optional hostport as initialization arguments. Given ``CommentService`` defined in ``comment.thrift`` and registe...
Build a synchronous client class for the given Thrift service. The generated class accepts a TChannelSyncClient and an optional hostport as initialization arguments. Given ``CommentService`` defined in ``comment.thrift`` and registered with Hyperbahn under the name "comment", here's how this might be ...
def _bse_cli_list_ref_formats(args): '''Handles the list-ref-formats subcommand''' all_refformats = api.get_reference_formats() if args.no_description: liststr = all_refformats.keys() else: liststr = format_columns(all_refformats.items()) return '\n'.join(liststr)
Handles the list-ref-formats subcommand
async def notifications(dev: Device, notification: str, listen_all: bool): """List available notifications and listen to them. Using --listen-all [notification] allows to listen to all notifications from the given subsystem. If the subsystem is omited, notifications from all subsystems are request...
List available notifications and listen to them. Using --listen-all [notification] allows to listen to all notifications from the given subsystem. If the subsystem is omited, notifications from all subsystems are requested.
def get(self, request): """Handle HTTP GET request. Returns template and context from generate_page_title and generate_sections to populate template. """ sections_list = self.generate_sections() p = Paginator(sections_list, 25) page = request.GET.get('page') ...
Handle HTTP GET request. Returns template and context from generate_page_title and generate_sections to populate template.
def __check_prefix_conflict(self, existing_ni_or_ns_uri, incoming_prefix): """If existing_ni_or_ns_uri is a _NamespaceInfo object (which must be in this set), then caller wants to map incoming_prefix to that namespace. This function verifies that the prefix isn't already mapped to a dif...
If existing_ni_or_ns_uri is a _NamespaceInfo object (which must be in this set), then caller wants to map incoming_prefix to that namespace. This function verifies that the prefix isn't already mapped to a different namespace URI. If it is, an exception is raised. Otherwise, existing_...
def encode(self, payload): """ Returns an encoded token for the given payload dictionary. """ token = jwt.encode(payload, self.signing_key, algorithm=self.algorithm) return token.decode('utf-8')
Returns an encoded token for the given payload dictionary.
def pkg(pkg_path, pkg_sum, hash_type, test=None, **kwargs): ''' Execute a packaged state run, the packaged state run will exist in a tarball available locally. This packaged state can be generated using salt-ssh. CLI Example: .. code-block:: bash salt '...
Execute a packaged state run, the packaged state run will exist in a tarball available locally. This packaged state can be generated using salt-ssh. CLI Example: .. code-block:: bash salt '*' state.pkg /tmp/salt_state.tgz 760a9353810e36f6d81416366fc426dc md5
def exclude(prop): '''Don't replicate property that is normally replicated: ordering column, many-to-one relation that is marked for replication from other side.''' if isinstance(prop, QueryableAttribute): prop = prop.property assert isinstance(prop, (Column, ColumnProperty, RelationshipProperty...
Don't replicate property that is normally replicated: ordering column, many-to-one relation that is marked for replication from other side.
def apply_dict_of_variables_vfunc( func, *args, signature, join='inner', fill_value=None ): """Apply a variable level function over dicts of DataArray, DataArray, Variable and ndarray objects. """ args = [_as_variables_or_variable(arg) for arg in args] names = join_dict_keys(args, how=join) ...
Apply a variable level function over dicts of DataArray, DataArray, Variable and ndarray objects.
def create_transient(self, input_stream, original_name, length=None): '''Create TransientFile and file on FS from given input stream and original file name.''' ext = os.path.splitext(original_name)[1] transient = self.new_transient(ext) if not os.path.isdir(self.transient_root):...
Create TransientFile and file on FS from given input stream and original file name.
def LEA(cpu, dest, src): """ Loads effective address. Computes the effective address of the second operand (the source operand) and stores it in the first operand (destination operand). The source operand is a memory address (offset part) specified with one of the processors add...
Loads effective address. Computes the effective address of the second operand (the source operand) and stores it in the first operand (destination operand). The source operand is a memory address (offset part) specified with one of the processors addressing modes; the destination operand is a g...
def analyze_beam_spot(scan_base, combine_n_readouts=1000, chunk_size=10000000, plot_occupancy_hists=False, output_pdf=None, output_file=None): ''' Determines the mean x and y beam spot position as a function of time. Therefore the data of a fixed number of read outs are combined ('combine_n_readouts'). The occupanc...
Determines the mean x and y beam spot position as a function of time. Therefore the data of a fixed number of read outs are combined ('combine_n_readouts'). The occupancy is determined for the given combined events and stored into a pdf file. At the end the beam x and y is plotted into a scatter plot with absolute ...
def update_project(id, **kwargs): """ Update an existing Project with new information """ content = update_project_raw(id, **kwargs) if content: return utils.format_json(content)
Update an existing Project with new information
def clean(args): """ %prog clean Removes all symlinks from current folder """ p = OptionParser(clean.__doc__) opts, args = p.parse_args(args) for link_name in os.listdir(os.getcwd()): if not op.islink(link_name): continue logging.debug("remove symlink `{0}`".for...
%prog clean Removes all symlinks from current folder
def mailto_to_envelope(mailto_str): """ Interpret mailto-string into a :class:`alot.db.envelope.Envelope` """ from alot.db.envelope import Envelope headers, body = parse_mailto(mailto_str) return Envelope(bodytext=body, headers=headers)
Interpret mailto-string into a :class:`alot.db.envelope.Envelope`
def procrustes(anchors, X, scale=True, print_out=False): """ Fit X to anchors by applying optimal translation, rotation and reflection. Given m >= d anchor nodes (anchors in R^(m x d)), return transformation of coordinates X (output of EDM algorithm) optimally matching anchors in least squares sense. ...
Fit X to anchors by applying optimal translation, rotation and reflection. Given m >= d anchor nodes (anchors in R^(m x d)), return transformation of coordinates X (output of EDM algorithm) optimally matching anchors in least squares sense. :param anchors: Matrix of shape m x d, where m is number of ancho...
def infer_type(self, in_type): """infer_type interface. override to create new operators Parameters ---------- in_type : list of np.dtype list of argument types in the same order as declared in list_arguments. Returns ------- in_type : li...
infer_type interface. override to create new operators Parameters ---------- in_type : list of np.dtype list of argument types in the same order as declared in list_arguments. Returns ------- in_type : list list of argument types. Can...
def animate(self, **kwargs): """ Animates the surface. This function only animates the triangulated surface. There will be no other elements, such as control points grid or bounding box. Keyword arguments: * ``colormap``: applies colormap to the surface Colormaps a...
Animates the surface. This function only animates the triangulated surface. There will be no other elements, such as control points grid or bounding box. Keyword arguments: * ``colormap``: applies colormap to the surface Colormaps are a visualization feature of Matplotlib....
def get_failed_jobs(self, fail_running=False, fail_pending=False): """Return a dictionary with the subset of jobs that are marked as failed Parameters ---------- fail_running : `bool` If True, consider running jobs as failed fail_pending : `bool` If True...
Return a dictionary with the subset of jobs that are marked as failed Parameters ---------- fail_running : `bool` If True, consider running jobs as failed fail_pending : `bool` If True, consider pending jobs as failed Returns ------- fai...
def set_subcommands(func, parser): """ Set subcommands. """ if hasattr(func, '__subcommands__') and func.__subcommands__: sub_parser = parser.add_subparsers( title=SUBCOMMANDS_LIST_TITLE, dest='subcommand', description=SUBCOMMANDS_LIST_DESCRIPTION.format( ...
Set subcommands.
def set_memory(self, total=None, static=None): """ Set the maxium allowed memory. Args: total: The total memory. Integer. Unit: MBytes. If set to None, this parameter will be neglected. static: The static memory. Integer. Unit MBytes. If set to None, ...
Set the maxium allowed memory. Args: total: The total memory. Integer. Unit: MBytes. If set to None, this parameter will be neglected. static: The static memory. Integer. Unit MBytes. If set to None, this parameterwill be neglected.
def download_sysdig_capture(self, capture_id): '''**Description** Download a sysdig capture by id. **Arguments** - **capture_id**: the capture id to download. **Success Return Value** The bytes of the scap ''' url = '{url}/api/sysdig/{id}/dow...
**Description** Download a sysdig capture by id. **Arguments** - **capture_id**: the capture id to download. **Success Return Value** The bytes of the scap
def gaussian_prior_model_for_arguments(self, arguments): """ Parameters ---------- arguments: {Prior: float} A dictionary of arguments Returns ------- prior_models: [PriorModel] A new list of prior models with gaussian priors """ ...
Parameters ---------- arguments: {Prior: float} A dictionary of arguments Returns ------- prior_models: [PriorModel] A new list of prior models with gaussian priors
def _check_seismogenic_depths(self, upper_depth, lower_depth): ''' Checks the seismic depths for physical consistency :param float upper_depth: Upper seismogenic depth (km) :param float lower_depth: Lower seismogenic depth (km) ''' # Simple check ...
Checks the seismic depths for physical consistency :param float upper_depth: Upper seismogenic depth (km) :param float lower_depth: Lower seismogenic depth (km)
def directionaldiff(f, x0, vec, **options): """ Return directional derivative of a function of n variables Parameters ---------- fun: callable analytical function to differentiate. x0: array vector location at which to differentiate fun. If x0 is an nxm array, then fun i...
Return directional derivative of a function of n variables Parameters ---------- fun: callable analytical function to differentiate. x0: array vector location at which to differentiate fun. If x0 is an nxm array, then fun is assumed to be a function of n*m variables. vec: ar...
def write_chisq(page, injList, grbtag): """ Write injection chisq plots to markup.page object page """ if injList: th = ['']+injList + ['OFFSOURCE'] else: th= ['','OFFSOURCE'] injList = ['OFFSOURCE'] td = [] plots = ['bank_veto','auto_veto','chi_square', 'mchir...
Write injection chisq plots to markup.page object page
def make_url(*args, **kwargs): """Makes a URL from component parts""" base = "/".join(args) if kwargs: return "%s?%s" % (base, urlencode(kwargs)) else: return base
Makes a URL from component parts
def _check_for_answers(self, pk): """ Callback called for every packet received to check if we are waiting for an answer on this port. If so, then cancel the retry timer. """ longest_match = () if len(self._answer_patterns) > 0: data = (pk.header,) + t...
Callback called for every packet received to check if we are waiting for an answer on this port. If so, then cancel the retry timer.
def _pnorm_default(x, p): """Default p-norm implementation.""" return np.linalg.norm(x.data.ravel(), ord=p)
Default p-norm implementation.
def calculate_md5(filename, length): """Calculate the MD5 hash of a file, up to length bytes. Returns the MD5 in its binary form, as an 8-byte string. Raises IOError or OSError in case of error. """ assert length >= 0 # shortcut: MD5 of an empty string is 'd41d8cd98f00b204e9800998ecf8427e', ...
Calculate the MD5 hash of a file, up to length bytes. Returns the MD5 in its binary form, as an 8-byte string. Raises IOError or OSError in case of error.
def get_docker_tag(platform: str, registry: str) -> str: """:return: docker tag to be used for the container""" platform = platform if any(x in platform for x in ['build.', 'publish.']) else 'build.{}'.format(platform) if not registry: registry = "mxnet_local" return "{0}/{1}".format(registry, p...
:return: docker tag to be used for the container
async def _get_popular_people_page(self, page=1): """Get a specific page of popular person data. Arguments: page (:py:class:`int`, optional): The page to get. Returns: :py:class:`dict`: The page data. """ return await self.get_data(self.url_builder( ...
Get a specific page of popular person data. Arguments: page (:py:class:`int`, optional): The page to get. Returns: :py:class:`dict`: The page data.
def to_bytes(self, frame, state): """ Convert a single frame into bytes that can be transmitted on the stream. :param frame: The frame to convert. Should be the same type of object returned by ``to_frame()``. :param state: An instance of ``FramerState``. ...
Convert a single frame into bytes that can be transmitted on the stream. :param frame: The frame to convert. Should be the same type of object returned by ``to_frame()``. :param state: An instance of ``FramerState``. This object may be used to track...
def get_search_result(self, ddoc_id, index_name, **query_params): """ Retrieves the raw JSON content from the remote database based on the search index on the server, using the query_params provided as query parameters. A ``query`` parameter containing the Lucene query syntax is ...
Retrieves the raw JSON content from the remote database based on the search index on the server, using the query_params provided as query parameters. A ``query`` parameter containing the Lucene query syntax is mandatory. Example for search queries: .. code-block:: python ...
def _preprocess_and_rename_grid_attrs(func, grid_attrs=None, **kwargs): """Call a custom preprocessing method first then rename grid attrs. This wrapper is needed to generate a single function to pass to the ``preprocesss`` of xr.open_mfdataset. It makes sure that the user-specified preprocess functio...
Call a custom preprocessing method first then rename grid attrs. This wrapper is needed to generate a single function to pass to the ``preprocesss`` of xr.open_mfdataset. It makes sure that the user-specified preprocess function is called on the loaded Dataset before aospy's is applied. An example fo...
def update(self, instance): """ method finds unit_of_work record and change its status""" assert isinstance(instance, UnitOfWork) if instance.db_id: query = {'_id': ObjectId(instance.db_id)} else: query = {unit_of_work.PROCESS_NAME: instance.process_name, ...
method finds unit_of_work record and change its status
def inverse(self): """return index array that maps unique values back to original space. unique[inverse]==keys""" inv = np.empty(self.size, np.int) inv[self.sorter] = self.sorted_group_rank_per_key return inv
return index array that maps unique values back to original space. unique[inverse]==keys
def _check_subject_identifier_matches_requested(self, authentication_request, sub): # type (oic.message.AuthorizationRequest, str) -> None """ Verifies the subject identifier against any requested subject identifier using the claims request parameter. :param authentication_request: authe...
Verifies the subject identifier against any requested subject identifier using the claims request parameter. :param authentication_request: authentication request :param sub: subject identifier :raise AuthorizationError: if the subject identifier does not match the requested one
def setupTable_VORG(self): """ Make the VORG table. **This should not be called externally.** Subclasses may override or supplement this method to handle the table creation in a different way if desired. """ if "VORG" not in self.tables: return ...
Make the VORG table. **This should not be called externally.** Subclasses may override or supplement this method to handle the table creation in a different way if desired.
def logs(self, prefix='worker'): """Generates a dictionary that contains all collected statistics. """ logs = [] logs += [('success_rate', np.mean(self.success_history))] if self.compute_Q: logs += [('mean_Q', np.mean(self.Q_history))] logs += [('episode', sel...
Generates a dictionary that contains all collected statistics.
def get_path(self, dir=None): """Return path relative to the current working directory of the Node.FS.Base object that owns us.""" if not dir: dir = self.fs.getcwd() if self == dir: return '.' path_elems = self.get_path_elements() pathname = '' ...
Return path relative to the current working directory of the Node.FS.Base object that owns us.
def documentation(self): """ Get the documentation that the server sends for the API. """ newclient = self.__class__(self.session, self.root_url) return newclient.get_raw('/')
Get the documentation that the server sends for the API.
def bbduk_trim(forward_in, forward_out, reverse_in='NA', reverse_out='NA', trimq=20, k=25, minlength=50, forcetrimleft=15, hdist=1, returncmd=False, **kwargs): """ Wrapper for using bbduk to quality trim reads. Contains arguments used in OLC Assembly Pipeline, but these can be overwritten by ...
Wrapper for using bbduk to quality trim reads. Contains arguments used in OLC Assembly Pipeline, but these can be overwritten by using keyword parameters. :param forward_in: Forward reads you want to quality trim. :param returncmd: If set to true, function will return the cmd string passed to subprocess as ...
def find_application(app_id=None, app_name=None): """ find the application according application id (prioritary) or application name :param app_id: the application id :param app_name: the application name :return: found application or None if not found """ LOGGER....
find the application according application id (prioritary) or application name :param app_id: the application id :param app_name: the application name :return: found application or None if not found
def parse_definition_expr(expr, default_value=None): """ Parses a definition expression and returns a key-value pair as a tuple. Each definition expression should be in one of these two formats: * <variable>=<value> * <variable> :param expr: String expression to be parsed....
Parses a definition expression and returns a key-value pair as a tuple. Each definition expression should be in one of these two formats: * <variable>=<value> * <variable> :param expr: String expression to be parsed. :param default_value: (Default None) When a definiti...
def _calculate(self): self.logpriors = np.zeros_like(self.rad) for i in range(self.N-1): o = np.arange(i+1, self.N) dist = ((self.zscale*(self.pos[i] - self.pos[o]))**2).sum(axis=-1) dist0 = (self.rad[i] + self.rad[o])**2 update = self.prior_func(dist -...
# This is equivalent for i in range(self.N-1): for j in range(i+1, self.N): d = ((self.zscale*(self.pos[i] - self.pos[j]))**2).sum(axis=-1) r = (self.rad[i] + self.rad[j])**2 cost = self.prior_func(d - r) self.logpriors[i] += cost ...
def nonoverlap(item_a, time_a, item_b, time_b, max_value): """ Percentage of pixels in each object that do not overlap with the other object Args: item_a: STObject from the first set in ObjectMatcher time_a: Time integer being evaluated item_b: STObject from the second set in Object...
Percentage of pixels in each object that do not overlap with the other object Args: item_a: STObject from the first set in ObjectMatcher time_a: Time integer being evaluated item_b: STObject from the second set in ObjectMatcher time_b: Time integer being evaluated max_value:...
def _compute_anelastic_attenuation_term(self, C, rrup, mag): """ Compute magnitude-distance scaling term as defined in equation 21, page 2291 (Tavakoli and Pezeshk, 2005) """ r = (rrup**2. + (C['c5'] * np.exp(C['c6'] * mag + C['c7'] * (8....
Compute magnitude-distance scaling term as defined in equation 21, page 2291 (Tavakoli and Pezeshk, 2005)
def query_fetch_all(self, query, values): """ Executes a db query, gets all the values, and closes the connection. """ self.cursor.execute(query, values) retval = self.cursor.fetchall() self.__close_db() return retval
Executes a db query, gets all the values, and closes the connection.
def info(self): """return information about replica set""" hosts = ','.join(x['host'] for x in self.members()) mongodb_uri = 'mongodb://' + hosts + '/?replicaSet=' + self.repl_id result = {"id": self.repl_id, "auth_key": self.auth_key, "members": self....
return information about replica set
def _parse_routes(iface, opts): ''' Filters given options and outputs valid settings for the route settings file. ''' # Normalize keys opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts)) result = {} if 'routes' not in opts: _raise_error_routes(iface, 'routes', 'List of ...
Filters given options and outputs valid settings for the route settings file.
def discover_settings(conf_base=None): """ Discover custom settings for ZMQ path""" settings = { 'zmq_prefix': '', 'libzmq_extension': False, 'no_libzmq_extension': False, 'skip_check_zmq': False, 'build_ext': {}, 'bdist_egg': {}, } if sys.platform.startsw...
Discover custom settings for ZMQ path
def Load(self): """Loads all new events from disk. Calling Load multiple times in a row will not 'drop' events as long as the return value is not iterated over. Yields: All events in the file that have not been yielded yet. """ for record in super(EventFileLoader, self).Load(): yie...
Loads all new events from disk. Calling Load multiple times in a row will not 'drop' events as long as the return value is not iterated over. Yields: All events in the file that have not been yielded yet.
def setup_panel_params(self, scale_x, scale_y): """ Compute the range and break information for the panel """ def train(scale, limits, trans, name): """ Train a single coordinate axis """ if limits is None: rangee = scale.d...
Compute the range and break information for the panel
def to_capabilities(self): """ Creates a capabilities with all the options that have been set and returns a dictionary with everything """ capabilities = ChromeOptions.to_capabilities(self) capabilities.update(self._caps) opera_options = capabilities[self.KEY] ...
Creates a capabilities with all the options that have been set and returns a dictionary with everything
def acquire(self, key): """Return the known information about the device and mark the record as being used by a segmenation state machine.""" if _debug: DeviceInfoCache._debug("acquire %r", key) if isinstance(key, int): device_info = self.cache.get(key, None) elif n...
Return the known information about the device and mark the record as being used by a segmenation state machine.
def on_backward_end(self, iteration:int, **kwargs)->None: "Callback function that writes backward end appropriate data to Tensorboard." if iteration == 0: return self._update_batches_if_needed() #TODO: This could perhaps be implemented as queues of requests instead but that seemed like ...
Callback function that writes backward end appropriate data to Tensorboard.
def _find_all_versions(self, project_name): """Find all available versions for project_name This checks index_urls, find_links and dependency_links All versions found are returned See _link_package_versions for details on which files are accepted """ index_locations = s...
Find all available versions for project_name This checks index_urls, find_links and dependency_links All versions found are returned See _link_package_versions for details on which files are accepted
def _check_stations_csv(self, usr, root): ''' Reclocate a stations.csv copy in user home for easy manage. E.g. not need sudo when you add new station, etc ''' if path.exists(path.join(usr, 'stations.csv')): return else: copyfile(root, path.join(usr, 'stations...
Reclocate a stations.csv copy in user home for easy manage. E.g. not need sudo when you add new station, etc
def resize_image(fullfile,fullfile_resized,_megapixels): """Resizes image (fullfile), saves to fullfile_resized. Image aspect ratio is conserved, will be scaled to be close to _megapixels in size. Eg if _megapixels=2, will resize 2560x1920 so each dimension is scaled by ((2**(20+1*MP))/float(2560*1920)...
Resizes image (fullfile), saves to fullfile_resized. Image aspect ratio is conserved, will be scaled to be close to _megapixels in size. Eg if _megapixels=2, will resize 2560x1920 so each dimension is scaled by ((2**(20+1*MP))/float(2560*1920))**2
def _convert_to_ndarray(self, data): """Converts data from dataframe to ndarray format. Assumption: df-columns are ndarray-layers (3rd dim.)""" if data.__class__.__name__ != "DataFrame": raise Exception(f"data is not a DataFrame but {data.__class__.__name__}.") shape_ndarray = (self....
Converts data from dataframe to ndarray format. Assumption: df-columns are ndarray-layers (3rd dim.)
def process_bytecode(link_refs: Dict[str, Any], bytecode: bytes) -> str: """ Replace link_refs in bytecode with 0's. """ all_offsets = [y for x in link_refs.values() for y in x.values()] # Link ref validation. validate_link_ref_fns = ( validate_link_ref(ref["start"] * 2, ref["length"] * ...
Replace link_refs in bytecode with 0's.
def delete_chat_sticker_set(self, chat_id): """ Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set optionally returned in getChat requ...
Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on su...
def get(self): '''Get a task from queue when bucket available''' if self.bucket.get() < 1: return None now = time.time() self.mutex.acquire() try: task = self.priority_queue.get_nowait() self.bucket.desc() except Queue.Empty: ...
Get a task from queue when bucket available
def format_option(self, ohi): """Format the help output for a single option. :param OptionHelpInfo ohi: Extracted information for option to print :return: Formatted help text for this option :rtype: list of string """ lines = [] choices = 'one of: [{}] '.format(ohi.choices) if ohi.choices e...
Format the help output for a single option. :param OptionHelpInfo ohi: Extracted information for option to print :return: Formatted help text for this option :rtype: list of string
def make_clean_visible_file(i_chunk, clean_visible_path): '''make a temp file of clean_visible text''' _clean = open(clean_visible_path, 'wb') _clean.write('<?xml version="1.0" encoding="UTF-8"?>') _clean.write('<root>') for idx, si in enumerate(i_chunk): if si.stream_id is None: ...
make a temp file of clean_visible text
def add(self, pattern, method=None, call=None, name=None): """Add a url pattern. Args: pattern (:obj:`str`): URL pattern to add. This is usually '/' separated path. Parts of the URL can be parameterised using curly braces. Examples: "/", "/pat...
Add a url pattern. Args: pattern (:obj:`str`): URL pattern to add. This is usually '/' separated path. Parts of the URL can be parameterised using curly braces. Examples: "/", "/path/to/resource", "/resoures/{param}" method (:obj:`str`, :o...
def start_sctp_server(self, ip, port, name=None, timeout=None, protocol=None, family='ipv4'): """Starts a new STCP server to given `ip` and `port`. `family` can be either ipv4 (default) or ipv6. pysctp (https://github.com/philpraxis/pysctp) need to be installed your system. Server can ...
Starts a new STCP server to given `ip` and `port`. `family` can be either ipv4 (default) or ipv6. pysctp (https://github.com/philpraxis/pysctp) need to be installed your system. Server can be given a `name`, default `timeout` and a `protocol`. Notice that you have to use `Accept Connec...
def _GetDirectory(self): """Retrieves a directory. Returns: CPIODirectory: a directory or None if not available. """ if self.entry_type != definitions.FILE_ENTRY_TYPE_DIRECTORY: return None return CPIODirectory(self._file_system, self.path_spec)
Retrieves a directory. Returns: CPIODirectory: a directory or None if not available.