positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def init_app(self, app, report_exceptions=False, reset_context_after_request=False): """ Initialize honeybadger and listen for errors. :param Flask app: the Flask application object. :param bool report_exceptions: whether to automatically report exceptions raised by Flask on requests ...
Initialize honeybadger and listen for errors. :param Flask app: the Flask application object. :param bool report_exceptions: whether to automatically report exceptions raised by Flask on requests (i.e. by calling abort) or not. :param bool reset_context_after_request: whether to reset ...
def norm_2l2(x, axis=None): r"""Compute the squared :math:`\ell_2` norm .. math:: \| \mathbf{x} \|_2^2 = \sum_i x_i^2 where :math:`x_i` is element :math:`i` of vector :math:`\mathbf{x}`. Parameters ---------- x : array_like Input array :math:`\mathbf{x}` axis : `None` or int o...
r"""Compute the squared :math:`\ell_2` norm .. math:: \| \mathbf{x} \|_2^2 = \sum_i x_i^2 where :math:`x_i` is element :math:`i` of vector :math:`\mathbf{x}`. Parameters ---------- x : array_like Input array :math:`\mathbf{x}` axis : `None` or int or tuple of ints, optional (defau...
def validate(self, value): """ Validates that the input is a list or tuple. """ if self.required and not value: raise OAuthValidationError({'error': 'invalid_request'}) # Validate that each value in the value list is in self.choices. for val in value: ...
Validates that the input is a list or tuple.
def bling(self, target, sender): "will print yo" if target.startswith("#"): self.message(target, "%s: yo" % sender) else: self.message(sender, "yo")
will print yo
def _validate_number(self, input_number, path_to_root, object_title=''): ''' a helper method for validating properties of a number :return: input_number ''' rules_path_to_root = re.sub('\[\d+\]', '[0]', path_to_root) input_criteria = self.keyMap[rules_path_to_root]...
a helper method for validating properties of a number :return: input_number
def gather_named_configs(self, ingredient): """Collect all named configs from this ingredient and its sub-ingredients. Yields ------ config_name: str The full (dotted) name of the named config. config: ConfigScope or ConfigDict or basestring The c...
Collect all named configs from this ingredient and its sub-ingredients. Yields ------ config_name: str The full (dotted) name of the named config. config: ConfigScope or ConfigDict or basestring The corresponding named config.
def MessageToString(message, as_utf8=False, as_one_line=False, pointy_brackets=False, use_index_order=False, float_format=None, use_field_number=False, descriptor_pool=None, ...
Convert protobuf message to text format. Floating point values can be formatted compactly with 15 digits of precision (which is the most that IEEE 754 "double" can guarantee) using float_format='.15g'. To ensure that converting to text and back to a proto will result in an identical value, float_format='.17g' ...
def iuwt_recomposition(in1, scale_adjust=0, mode='ser', core_count=1, store_on_gpu=False, smoothed_array=None): """ This function serves as a handler for the different implementations of the IUWT recomposition. It allows the different methods to be used almost interchangeably. INPUTS: in1 ...
This function serves as a handler for the different implementations of the IUWT recomposition. It allows the different methods to be used almost interchangeably. INPUTS: in1 (no default): Array on which the decomposition is to be performed. scale_adjust (no default): ...
def start(args): """ %prog start Launch ec2 instance through command line. """ p = OptionParser(start.__doc__) p.add_option("--ondemand", default=False, action="store_true", help="Do we want a more expensive on-demand instance") p.add_option("--profile", default="mvrad-data...
%prog start Launch ec2 instance through command line.
def add_argument(self, *args, **kwargs): """ Add a parameter to this app. """ if not (('action' in kwargs) and (kwargs['action'] == 'help')): # make sure required parameter options were defined try: name = kwargs['dest'] param_type ...
Add a parameter to this app.
def by_ldap_credentials(cls, session, login, password, settings): """if possible try to contact the LDAP for authentification if success and login don't exist localy create one and return it :param session: SQLAlchemy session :type session: :class:`sqlalchemy.Session` :param lo...
if possible try to contact the LDAP for authentification if success and login don't exist localy create one and return it :param session: SQLAlchemy session :type session: :class:`sqlalchemy.Session` :param login: username :type login: unicode :param password: user pas...
def p_common_scalar_magic_method(p): 'common_scalar : METHOD_C' p[0] = ast.MagicConstant(p[1].upper(), None, lineno=p.lineno(1))
common_scalar : METHOD_C
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = GridLayout(self.get_context(), None, d.style)
Create the underlying widget.
def param_describe(params, quant=95, axis=0): """Get mean + quantile range from bootstrapped params.""" par = np.mean(params, axis=axis) lo, up = perc(quant) p_up = np.percentile(params, up, axis=axis) p_lo = np.percentile(params, lo, axis=axis) return par, p_lo, p_up
Get mean + quantile range from bootstrapped params.
def find_poor_default_arg(node): """Finds poor default args""" poor_defaults = [ ast.Call, ast.Dict, ast.DictComp, ast.GeneratorExp, ast.List, ast.ListComp, ast.Set, ast.SetComp, ] # pylint: disable=unidiomatic-typecheck return ( ...
Finds poor default args
def sessioninfo(self): ''' session info ''' response, status_code = self.__pod__.Session.get_v2_sessioninfo( sessionToken=self.__session__ ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
session info
def _set_weight(self, v, load=False): """ Setter method for weight, mapped from YANG variable /routing_system/route_map/content/set/weight (container) If this variable is read-only (config: false) in the source YANG file, then _set_weight is considered as a private method. Backends looking to popula...
Setter method for weight, mapped from YANG variable /routing_system/route_map/content/set/weight (container) If this variable is read-only (config: false) in the source YANG file, then _set_weight is considered as a private method. Backends looking to populate this variable should do so via calling this...
def DeleteConflict(self, conflict_link, options=None): """Deletes a conflict. :param str conflict_link: The link to the conflict. :param dict options: The request options for the request. :return: The deleted Conflict. :rtype: dic...
Deletes a conflict. :param str conflict_link: The link to the conflict. :param dict options: The request options for the request. :return: The deleted Conflict. :rtype: dict
def gelman_rubin(self, chain=None, threshold=0.05): r""" Runs the Gelman Rubin diagnostic on the supplied chains. Parameters ---------- chain : int|str, optional Which chain to run the diagnostic on. By default, this is `None`, which will run the diagnostic on al...
r""" Runs the Gelman Rubin diagnostic on the supplied chains. Parameters ---------- chain : int|str, optional Which chain to run the diagnostic on. By default, this is `None`, which will run the diagnostic on all chains. You can also supply and integer (the c...
def separator_width(self, value): """ Setter for **self.__separator_width** attribute. :param value: Attribute value. :type value: int """ if value is not None: assert type(value) is int, "'{0}' attribute: '{1}' type is not 'int'!".format("separator_width", ...
Setter for **self.__separator_width** attribute. :param value: Attribute value. :type value: int
def _get_event_id(object_type: str) -> str: """Return an event key for the event on the object type. This must be a unique event id for the object. Args: object_type (str): Type of object Returns: str, event id """ key = _keys.event_counter(object_type) DB.watch(key, pipe...
Return an event key for the event on the object type. This must be a unique event id for the object. Args: object_type (str): Type of object Returns: str, event id
def feature_names(self, feature_names): """Set feature names (column labels). Parameters ---------- feature_names : list or None Labels for features. None will reset existing feature names """ if feature_names is not None: # validate feature name ...
Set feature names (column labels). Parameters ---------- feature_names : list or None Labels for features. None will reset existing feature names
def validate_jhove(filename, jhove=None, ignore=None): """Validate TIFF file using jhove -m TIFF-hul. Raise ValueError if jhove outputs an error message unless the message contains one of the strings in 'ignore'. JHOVE does not support bigtiff or more than 50 IFDs. See `JHOVE TIFF-hul Module <htt...
Validate TIFF file using jhove -m TIFF-hul. Raise ValueError if jhove outputs an error message unless the message contains one of the strings in 'ignore'. JHOVE does not support bigtiff or more than 50 IFDs. See `JHOVE TIFF-hul Module <http://jhove.sourceforge.net/tiff-hul.html>`_
def scale(self, scale_xy): "Returns the pix object rescaled according to the proportions given." with _LeptonicaErrorTrap(): return Pix(lept.pixScale(self._cdata, scale_xy[0], scale_xy[1]))
Returns the pix object rescaled according to the proportions given.
def switch_into_lazy_mode(self, affect_master=None): """Load apps in workers instead of master. This option may have memory usage implications as Copy-on-Write semantics can not be used. .. note:: Consider using ``touch_chain_reload`` option in ``workers`` basic params for ...
Load apps in workers instead of master. This option may have memory usage implications as Copy-on-Write semantics can not be used. .. note:: Consider using ``touch_chain_reload`` option in ``workers`` basic params for lazy apps reloading. :param bool affect_master: If **Tr...
def _write_act_files(self, ref_fasta, qry_fasta, coords_file, outprefix): '''Writes crunch file and shell script to start up ACT, showing comparison of ref and qry''' if self.verbose: print('Making ACT files from', ref_fasta, qry_fasta, coords_file) ref_fasta = os.path.relpath(ref_fa...
Writes crunch file and shell script to start up ACT, showing comparison of ref and qry
def scp(self, local_file, remote_path=''): """Copy a local file to the given remote path.""" if self.args.user: upload_spec = '{0}@{1}:{2}'.format(self.args.user, self.args.server, remote_path) ...
Copy a local file to the given remote path.
def release_key(self, character=''): """ Release a given character key. """ try: shifted = self.is_char_shifted(character) except AttributeError: win32api.keybd_event(character, 0, KEYEVENTF_KEYUP, 0) else: if shifted: w...
Release a given character key.
def _randomSO3(): """Return random rotatation matrix, algo by James Arvo.""" u1 = np.random.random() u2 = np.random.random() u3 = np.random.random() R = np.array( [ [np.cos(2 * np.pi * u1), np.sin(2 * np.pi * u1), 0], [-np.sin(2 * np.pi * u1), np.cos(2 * np.pi * u1), ...
Return random rotatation matrix, algo by James Arvo.
def transform(self, config): """ :param config: :type config: dict :return: :rtype: yowsup.config.config.Config """ out = {} for prop in vars(config): out[prop] = getattr(config, prop) return out
:param config: :type config: dict :return: :rtype: yowsup.config.config.Config
def delete_driver_script(driver, script_delete=None): # noqa: E501 """Delete a script Delete a script # noqa: E501 :param driver: The driver to use for the request. ie. github :type driver: str :param script_delete: The data needed to delete this script :type script_delete: dict | bytes ...
Delete a script Delete a script # noqa: E501 :param driver: The driver to use for the request. ie. github :type driver: str :param script_delete: The data needed to delete this script :type script_delete: dict | bytes :rtype: Response
def ast_from_file(self, filepath, modname=None, fallback=True, source=False): """given a module name, return the astroid object""" try: filepath = modutils.get_source_file(filepath, include_no_ext=True) source = True except modutils.NoSourceFile: pass ...
given a module name, return the astroid object
def overlap(args): """ %prog overlap ctgfasta poolfasta Fish out the sequences in `poolfasta` that overlap with `ctgfasta`. Mix and combine using `minimus2`. """ p = OptionParser(overlap.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) ...
%prog overlap ctgfasta poolfasta Fish out the sequences in `poolfasta` that overlap with `ctgfasta`. Mix and combine using `minimus2`.
def _set_rcv_queue(self, v, load=False): """ Setter method for rcv_queue, mapped from YANG variable /rbridge_id/qos/rcv_queue (container) If this variable is read-only (config: false) in the source YANG file, then _set_rcv_queue is considered as a private method. Backends looking to populate this va...
Setter method for rcv_queue, mapped from YANG variable /rbridge_id/qos/rcv_queue (container) If this variable is read-only (config: false) in the source YANG file, then _set_rcv_queue is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_rcv_...
def clean_stacks(self, stacks: List[List[BaseLayer]]) \ -> List[List[BaseLayer]]: """ Two cases: if a stack finishes by a sleep then let's keep it (it means that there was nothing after the text). However if the stack finishes with something else (like a quick reply) then we ...
Two cases: if a stack finishes by a sleep then let's keep it (it means that there was nothing after the text). However if the stack finishes with something else (like a quick reply) then we don't risk an is preserved.
def from_euler(self, roll, pitch, yaw): '''fill the matrix from Euler angles in radians''' cp = cos(pitch) sp = sin(pitch) sr = sin(roll) cr = cos(roll) sy = sin(yaw) cy = cos(yaw) self.a.x = cp * cy self.a.y = (sr * sp * cy) - (cr * sy) s...
fill the matrix from Euler angles in radians
def get_user_events(self, id, **data): """ GET /users/:id/events/ Returns a :ref:`paginated <pagination>` response of :format:`events <event>`, under the key ``events``, of all events the user has access to """ return self.get("/users/{0}/events/".format(id), data=data)
GET /users/:id/events/ Returns a :ref:`paginated <pagination>` response of :format:`events <event>`, under the key ``events``, of all events the user has access to
def close(self): """ Mark the latch as closed, and cause every sleeping thread to be woken, with :class:`mitogen.core.LatchError` raised in each thread. """ self._lock.acquire() try: self.closed = True while self._waking < len(self._sleeping): ...
Mark the latch as closed, and cause every sleeping thread to be woken, with :class:`mitogen.core.LatchError` raised in each thread.
def remove_redundant_verts(self, eps=1e-10): """Given verts and faces, this remove colocated vertices""" import numpy as np from scipy.spatial import cKDTree # FIXME pylint: disable=no-name-in-module fshape = self.f.shape tree = cKDTree(self.v) close_pairs = list(tree.que...
Given verts and faces, this remove colocated vertices
def _db_pre_transform(self, train_tfm:List[Callable], valid_tfm:List[Callable]): "Call `train_tfm` and `valid_tfm` after opening image, before converting from `PIL.Image`" self.train_ds.x.after_open = compose(train_tfm) self.valid_ds.x.after_open = compose(valid_tfm) return self
Call `train_tfm` and `valid_tfm` after opening image, before converting from `PIL.Image`
def numeric_function_clean_dataframe(self, axis): """Preprocesses numeric functions to clean dataframe and pick numeric indices. Args: axis: '0' if columns and '1' if rows. Returns: Tuple with return value(if any), indices to apply func to & cleaned Manager. """...
Preprocesses numeric functions to clean dataframe and pick numeric indices. Args: axis: '0' if columns and '1' if rows. Returns: Tuple with return value(if any), indices to apply func to & cleaned Manager.
def isreal(obj): """ Test if the argument is a real number (float or integer). :param obj: Object :type obj: any :rtype: boolean """ return ( (obj is not None) and (not isinstance(obj, bool)) and isinstance(obj, (int, float)) )
Test if the argument is a real number (float or integer). :param obj: Object :type obj: any :rtype: boolean
def new_keys(self): """ Access the new_keys :returns: twilio.rest.api.v2010.account.new_key.NewKeyList :rtype: twilio.rest.api.v2010.account.new_key.NewKeyList """ if self._new_keys is None: self._new_keys = NewKeyList(self._version, account_sid=self._solutio...
Access the new_keys :returns: twilio.rest.api.v2010.account.new_key.NewKeyList :rtype: twilio.rest.api.v2010.account.new_key.NewKeyList
def make_basic_table(self, file_type): """ Create table of key-value items in 'file_type'. """ table_data = {sample: items['kv'] for sample, items in self.mod_data[file_type].items() } table_headers = {} for column_header, (description, h...
Create table of key-value items in 'file_type'.
def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root)
Common code for conditionally removing masks before making changes to a service's state.
def minutes_back(self, date): ''' Gives a number (integer) of days since a given date ''' elapsed = (datetime.utcnow() - datetime.strptime(date,'%Y-%m-%dT%H:%M:%S')) if elapsed.days > 0: secondsback = (elapsed.days * 24 * 60 * 60) + elapsed.seconds else: ...
Gives a number (integer) of days since a given date
def refresh_if_needed(self): """ Refresh the status of the task from server if required. """ if self.state in (self.PENDING, self.STARTED): try: response, = self._fetch_result()['tasks'] except (KeyError, ValueError): raise Exceptio...
Refresh the status of the task from server if required.
def eformat(format_str,lst,dct,defvalue='-'): """ Formats a list and a dictionary, manages unkown keys It works like :meth:`string.Formatter.vformat` except that it accepts a defvalue for not matching keys. Defvalue can be a callable that will receive the requested key as argument and return a string ...
Formats a list and a dictionary, manages unkown keys It works like :meth:`string.Formatter.vformat` except that it accepts a defvalue for not matching keys. Defvalue can be a callable that will receive the requested key as argument and return a string Args: format_string (str): Same format string ...
def verify_login(user, password=None, **connection_args): ''' Attempt to login using the provided credentials. If successful, return true. Otherwise, return False. CLI Example: .. code-block:: bash salt '*' mysql.verify_login root password ''' # Override the connection args for u...
Attempt to login using the provided credentials. If successful, return true. Otherwise, return False. CLI Example: .. code-block:: bash salt '*' mysql.verify_login root password
def config(remote_base= 'https://raw.githubusercontent.com/SciCrunch/NIF-Ontology/', local_base= None, # devconfig.ontology_local_repo by default branch= devconfig.neurons_branch, core_graph_paths= ['ttl/phenotype-core.ttl', 'ttl/ph...
Wraps graphBase.configGraphIO to provide a set of sane defaults for input ontologies and output files.
def filter(self, *filter, **kw): # @ReservedAssignment """ Filter results for specific element type. keyword arguments can be used to specify a match against the elements attribute directly. It's important to note that if the search filter contains a / or -, the SMC...
Filter results for specific element type. keyword arguments can be used to specify a match against the elements attribute directly. It's important to note that if the search filter contains a / or -, the SMC will only search the name and comment fields. Otherwise other key f...
def stop(self): """Stops the reader an writes all remaining messages to the database. Thus, this might take a while and block. """ BufferedReader.stop(self) self._stop_running_event.set() self._writer_thread.join() BaseIOHandler.stop(self)
Stops the reader an writes all remaining messages to the database. Thus, this might take a while and block.
def get_form(): """ Return the form to use for commenting. """ global form_class from fluent_comments import appsettings if form_class is None: if appsettings.FLUENT_COMMENTS_FORM_CLASS: from django.utils.module_loading import import_string form_class = import_str...
Return the form to use for commenting.
def get_magicc6_to_magicc7_variable_mapping(inverse=False): """Get the mappings from MAGICC6 to MAGICC7 variables. Note that this mapping is not one to one. For example, "HFC4310", "HFC43-10" and "HFC-43-10" in MAGICC6 both map to "HFC4310" in MAGICC7 but "HFC4310" in MAGICC7 maps back to "HFC4310". ...
Get the mappings from MAGICC6 to MAGICC7 variables. Note that this mapping is not one to one. For example, "HFC4310", "HFC43-10" and "HFC-43-10" in MAGICC6 both map to "HFC4310" in MAGICC7 but "HFC4310" in MAGICC7 maps back to "HFC4310". Note that HFC-245fa was mistakenly labelled as HFC-245ca in MAGI...
def show_fabric_trunk_info_output_show_trunk_list_trunk_list_groups_trunk_list_member_trunk_list_nbr_interface_type(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_fabric_trunk_info = ET.Element("show_fabric_trunk_info") config = show_fabric_trunk_i...
Auto Generated Code
def python_2_unicode_compatible(cls): """Taken from Django project (django/utils/encoding.py) & modified a bit to always have __unicode__ method available. """ if '__str__' not in cls.__dict__: raise ValueError("@python_2_unicode_compatible cannot be applied " "to %s bec...
Taken from Django project (django/utils/encoding.py) & modified a bit to always have __unicode__ method available.
def select_dict(coll, key, value): """ Given an iterable of dictionaries, return the dictionaries where the values at a given key match the given value. If the value is an iterable of objects, the function will consider any to be a match. This is especially useful when calling REST APIs which ...
Given an iterable of dictionaries, return the dictionaries where the values at a given key match the given value. If the value is an iterable of objects, the function will consider any to be a match. This is especially useful when calling REST APIs which return arrays of JSON objects. When such a r...
def get_entity(api, entity_id): """ Generic "getSpecific" call that calls get_specific with the given id :param api: api to call get_specific on :param id: id of the entity to retrieve :return: REST entity """ response = utils.checked_api_call(api, 'get_specific', id=entity_id) if respon...
Generic "getSpecific" call that calls get_specific with the given id :param api: api to call get_specific on :param id: id of the entity to retrieve :return: REST entity
def mean(data, n=3, **kwargs): """The mean forecast for the next point is the mean value of the previous ``n`` points in the series. Args: data (np.array): Observed data, presumed to be ordered in time. n (int): period over which to calculate the mean Returns: float: a single...
The mean forecast for the next point is the mean value of the previous ``n`` points in the series. Args: data (np.array): Observed data, presumed to be ordered in time. n (int): period over which to calculate the mean Returns: float: a single-valued forecast for the next value in...
def stop_timer(self, request_len, reply_len, server_time=None, exception=False): """ This is a low-level method is called by pywbem at the end of an operation. It completes the measurement for that operation by capturing the needed data, and updates the statistics data...
This is a low-level method is called by pywbem at the end of an operation. It completes the measurement for that operation by capturing the needed data, and updates the statistics data, if statistics is enabled for the connection. Parameters: request_len (:term:`integer`) ...
def get_1D_overlap(eclusters, depth=1): """ Find blocks that are 1D overlapping, returns cliques of block ids that are in conflict """ overlap_set = set() active = set() ends = [] for i, (chr, left, right) in enumerate(eclusters): ends.append((chr, left, 0, i)) # 0/1 for left/r...
Find blocks that are 1D overlapping, returns cliques of block ids that are in conflict
def eventFilter(self, widget, event): """ A filter that is used to send a signal when the figure canvas is clicked. """ if event.type() == QEvent.MouseButtonPress: if event.button() == Qt.LeftButton: self.sig_canvas_clicked.emit(self) return su...
A filter that is used to send a signal when the figure canvas is clicked.
def convert_odt_to_text(filename: str = None, blob: bytes = None, config: TextProcessingConfig = _DEFAULT_CONFIG) -> str: """ Converts an OpenOffice ODT file to text. Pass either a filename or a binary object. """ # We can't use exactly the same metho...
Converts an OpenOffice ODT file to text. Pass either a filename or a binary object.
def element_count(self): """Retrieve the number of elements in this type. Returns an int. If the Type is not an array or vector, this raises. """ result = conf.lib.clang_getNumElements(self) if result < 0: raise Exception('Type does not have elements.') ...
Retrieve the number of elements in this type. Returns an int. If the Type is not an array or vector, this raises.
def stop(self, timeout=1.0): """Stop the handler thread (from another thread). Parameters ---------- timeout : float, optional Seconds to wait for server to have *started*. """ if timeout: self._running.wait(timeout) self._running.clear()...
Stop the handler thread (from another thread). Parameters ---------- timeout : float, optional Seconds to wait for server to have *started*.
def create_sources_field(self, sources, sources_rel_path, key_arg=None): """Factory method to create a SourcesField appropriate for the type of the sources object. Note that this method is called before the call to Target.__init__ so don't expect fields to be populated! :API: public :return: a pa...
Factory method to create a SourcesField appropriate for the type of the sources object. Note that this method is called before the call to Target.__init__ so don't expect fields to be populated! :API: public :return: a payload field object representing the sources parameter :rtype: SourcesField
def surfnm(a, b, c, point): """ This routine computes the outward-pointing, unit normal vector from a point on the surface of an ellipsoid. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/surfnm_c.html :param a: Length of the ellisoid semi-axis along the x-axis. :type a: float :par...
This routine computes the outward-pointing, unit normal vector from a point on the surface of an ellipsoid. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/surfnm_c.html :param a: Length of the ellisoid semi-axis along the x-axis. :type a: float :param b: Length of the ellisoid semi-axis a...
def masked_local_attention_2d(q, k, v, query_shape=(8, 16), memory_flange=(8, 16), name=None): """Strided block local self-attention. Each position in a query block ...
Strided block local self-attention. Each position in a query block can attend to all the generated queries in the query block, which are generated in raster scan, and positions that are generated to the left and top. The shapes are specified by query shape and memory flange. Note that if you're using this func...
def load_json_from_file(file_path): """Load schema from a JSON file""" try: with open(file_path) as f: json_data = json.load(f) except ValueError as e: raise ValueError('Given file {} is not a valid JSON file: {}'.format(file_path, e)) else: return json_data
Load schema from a JSON file
def _ExtractHuntIdFromPath(entry, event): """Extracts a Hunt ID from an APIAuditEntry's HTTP request path.""" match = re.match(r".*hunt/([^/]+).*", entry.http_request_path) if match: event.urn = "aff4:/hunts/{}".format(match.group(1))
Extracts a Hunt ID from an APIAuditEntry's HTTP request path.
def slice_begin(self, tensor_shape, pnum): """Begin position for the tensor slice for the given processor. Args: tensor_shape: Shape. pnum: int <= self.size. Returns: list of integers with length tensor_shape.ndims. """ tensor_layout = self.tensor_layout(tensor_shape) coordin...
Begin position for the tensor slice for the given processor. Args: tensor_shape: Shape. pnum: int <= self.size. Returns: list of integers with length tensor_shape.ndims.
def ls(*topic, **kwargs): """List topic from external datastore Arguments: topic (str): One or more topics, e.g. ("project", "item", "task") root (str, optional): Absolute path to where projects reside, defaults to os.getcwd() backend (callable, optional): Function to call w...
List topic from external datastore Arguments: topic (str): One or more topics, e.g. ("project", "item", "task") root (str, optional): Absolute path to where projects reside, defaults to os.getcwd() backend (callable, optional): Function to call with absolute path as ...
def set_channel_access(self, channel=None, access_update_mode='non_volatile', alerting=False, per_msg_auth=False, user_level_auth=False, access_mode='always', privilege_update_mode='non_volatile', ...
Set channel access :param channel: number [1:7] :param access_update_mode: dont_change = don't set or change Channel Access non_volatile = set non-volatile Channel Access volatile = set volatile (active) setting of Channel Access :param alerting: PEF A...
def do_add_device_override(self, args): """Add a device override to the IM. Usage: add_device_override address cat subcat [firmware] Arguments: address: Insteon address of the device to override cat: Device category subcat: Device subcategory ...
Add a device override to the IM. Usage: add_device_override address cat subcat [firmware] Arguments: address: Insteon address of the device to override cat: Device category subcat: Device subcategory firmware: Optional - Device firmware ...
def _traverse_repos(self, callback, repo_name=None): ''' Traverse through all repo files and apply the functionality provided in the callback to them ''' repo_files = [] if os.path.exists(self.opts['spm_repos_config']): repo_files.append(self.opts['spm_repos_c...
Traverse through all repo files and apply the functionality provided in the callback to them
def get_swagger_objects(settings, route_info, registry): """Returns appropriate swagger handler and swagger spec schema. Swagger Handler contains callables that isolate implementation differences in the tween to handle both Swagger 1.2 and Swagger 2.0. Exception is made when `settings.prefer_20_routes...
Returns appropriate swagger handler and swagger spec schema. Swagger Handler contains callables that isolate implementation differences in the tween to handle both Swagger 1.2 and Swagger 2.0. Exception is made when `settings.prefer_20_routes` are non-empty and ['1.2', '2.0'] both are present in avail...
def perform(self, cfg): """ Performs transformation according to configuration :param cfg: transformation configuration """ self.__src = self._load(cfg[Transformation.__CFG_KEY_LOAD]) self.__transform(cfg[Transformation.__CFG_KEY_TRANSFORM]) self.__cleanup(cfg[Tra...
Performs transformation according to configuration :param cfg: transformation configuration
def extra_info(port): """Collects the serial nunber and manufacturer into a string, if the fields are available.""" extra_items = [] if port.manufacturer: extra_items.append("vendor '{}'".format(port.manufacturer)) if port.serial_number: extra_items.append("serial '{}'".format(por...
Collects the serial nunber and manufacturer into a string, if the fields are available.
def colorize(lead, num, color): """ Print 'lead' = 'num' in 'color' """ if num != 0 and ANSIBLE_COLOR and color is not None: return "%s%s%-15s" % (stringc(lead, color), stringc("=", color), stringc(str(num), color)) else: return "%s=%-4s" % (lead, str(num))
Print 'lead' = 'num' in 'color'
def angle(v1, v2): """Return the angle in radians between vectors 'v1' and 'v2'.""" v1_u = unit_vector(v1) v2_u = unit_vector(v2) return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
Return the angle in radians between vectors 'v1' and 'v2'.
def points_to_barycentric(triangles, points, method='cramer'): """ Find the barycentric coordinates of points relative to triangles. The Cramer's rule solution implements: http://blackpawn.com/texts/pointinpoly The cross product solution impl...
Find the barycentric coordinates of points relative to triangles. The Cramer's rule solution implements: http://blackpawn.com/texts/pointinpoly The cross product solution implements: https://www.cs.ubc.ca/~heidrich/Papers/JGT.05.pdf Parameters ----------- triangles : (n, 3, 3) fl...
def terminate(self): """ Terminate Qutepart instance. This method MUST be called before application stop to avoid crashes and some other interesting effects Call it on close to free memory and stop background highlighting """ self.text = '' self._completer.termina...
Terminate Qutepart instance. This method MUST be called before application stop to avoid crashes and some other interesting effects Call it on close to free memory and stop background highlighting
def dumps(data, escape=False, **kwargs): """A wrapper around `json.dumps` that can handle objects that json module is not aware. This function is aware of a list of custom serializers that can be registered by the API user, making it possible to convert any kind of object to types that the json lib...
A wrapper around `json.dumps` that can handle objects that json module is not aware. This function is aware of a list of custom serializers that can be registered by the API user, making it possible to convert any kind of object to types that the json library can handle.
def list_ext(self, collection, path, retrieve_all, **_params): """Client extension hook for list.""" return self.list(collection, path, retrieve_all, **_params)
Client extension hook for list.
def string_to_run(self, qad, executable, stdin=None, stdout=None, stderr=None, exec_args=None): """ Build and return a string with the command required to launch `executable` with the qadapter `qad`. Args qad: Qadapter instance. executable (str): Executable name or path ...
Build and return a string with the command required to launch `executable` with the qadapter `qad`. Args qad: Qadapter instance. executable (str): Executable name or path stdin (str): Name of the file to be used as standard input. None means no redirection. stdou...
def update_roles(self, roles='view'): """ Updates the roles of this permission :return: Success / Failure :rtype: bool """ if not self.object_id: return False url = self.build_url(self._endpoints.get('permission').format( driveitem_id=self.drivei...
Updates the roles of this permission :return: Success / Failure :rtype: bool
def bounce(sequence): ''' Return a driver function that can advance a "bounced" sequence of values. .. code-block:: none seq = [0, 1, 2, 3] # bounce(seq) => [0, 1, 2, 3, 3, 2, 1, 0, 0, 1, 2, ...] Args: sequence (seq) : a sequence of values for the driver to bounce ''' ...
Return a driver function that can advance a "bounced" sequence of values. .. code-block:: none seq = [0, 1, 2, 3] # bounce(seq) => [0, 1, 2, 3, 3, 2, 1, 0, 0, 1, 2, ...] Args: sequence (seq) : a sequence of values for the driver to bounce
def genl_ctrl_grp_by_name(family, grp_name): """https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/ctrl.c#L446. Positional arguments: family -- genl_family class instance. grp_name -- bytes. Returns: group ID or negative error code. """ for grp in nl_list_for_each_entry(genl_fa...
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/ctrl.c#L446. Positional arguments: family -- genl_family class instance. grp_name -- bytes. Returns: group ID or negative error code.
def make_classify_tab(self): """ initial set up of classification tab""" self.pick_frame = tk.Frame(self.tab_classify) self.pick_frame2 = tk.Frame(self.tab_classify) self.solar_class_var = tk.IntVar() self.solar_class_var.set(0) # initialize to unlabeled buttonnum = 0 ...
initial set up of classification tab
def autopep8_diff(fpath): r""" Args: fpath (str): file path string CommandLine: python -m utool.util_dev --test-autopep8_diff --fpath ingest_data.py Example: >>> # DISABLE_DOCTEST >>> from utool.util_dev import * # NOQA >>> fpath = ut.get_argval('--fpath', typ...
r""" Args: fpath (str): file path string CommandLine: python -m utool.util_dev --test-autopep8_diff --fpath ingest_data.py Example: >>> # DISABLE_DOCTEST >>> from utool.util_dev import * # NOQA >>> fpath = ut.get_argval('--fpath', type_=str, default='ingest_data.p...
def wrap(self, encoding, **textio_args): """Return a :class:`io.TextIOWrapper` that wraps the stream. The wrapper provides text IO on top of the byte stream, using the specified *encoding*. The *textio_args* keyword arguments are additional keyword arguments passed to the :class:`~io.Te...
Return a :class:`io.TextIOWrapper` that wraps the stream. The wrapper provides text IO on top of the byte stream, using the specified *encoding*. The *textio_args* keyword arguments are additional keyword arguments passed to the :class:`~io.TextIOWrapper` constructor. Unless another buf...
def yum_update(self, allow_reboot=False): """Do a yum update on the system. :param allow_reboot: If True and if a new kernel has been installed, the system will be rebooted """ self.run('yum clean all') self.run('test -f /usr/bin/subscription-manager && subscription-mana...
Do a yum update on the system. :param allow_reboot: If True and if a new kernel has been installed, the system will be rebooted
def _run_titancna(cn_file, het_file, ploidy, num_clusters, work_dir, data): """Run titanCNA wrapper script on given ploidy and clusters. """ sample = dd.get_sample_name(data) cores = dd.get_num_cores(data) export_cmd = utils.get_R_exports() ploidy_dir = utils.safe_makedir(os.path.join(work_dir, ...
Run titanCNA wrapper script on given ploidy and clusters.
def ensure_user_profile(user_profile=None): r""" Args: user_profile (UserProfile): (default = None) Returns: UserProfile: user_profile CommandLine: python -m utool.util_project --exec-ensure_user_profile --show Example: >>> # DISABLE_DOCTEST >>> from utool....
r""" Args: user_profile (UserProfile): (default = None) Returns: UserProfile: user_profile CommandLine: python -m utool.util_project --exec-ensure_user_profile --show Example: >>> # DISABLE_DOCTEST >>> from utool.util_project import * # NOQA >>> import...
def Skip(self: Iterable, n): """ [ { 'self': [1, 2, 3, 4, 5], 'n': 3, 'assert': lambda ret: list(ret) == [4, 5] } ] """ con = iter(self) for i, _ in enumerate(con): if i == n: break retur...
[ { 'self': [1, 2, 3, 4, 5], 'n': 3, 'assert': lambda ret: list(ret) == [4, 5] } ]
def get_authorize_url(self, redirect_uri=None, **kw): ''' return the authorization url that the user should be redirected to. ''' redirect = redirect_uri if redirect_uri else self.redirect_uri if not redirect: raise APIError('21305', 'Parameter absent: redirect_uri', ...
return the authorization url that the user should be redirected to.
def get_database_users(self): """Get list of database users.""" url = "db/{0}/users".format(self._database) response = self.request( url=url, method='GET', expected_response_code=200 ) return response.json()
Get list of database users.
def find_matching_link(self, mode, group, addr): """Find a matching link in the current device. Mode: r | c is the mode of the link in the linked device This method will search for a corresponding link in the reverse direction. group: All-Link group number ad...
Find a matching link in the current device. Mode: r | c is the mode of the link in the linked device This method will search for a corresponding link in the reverse direction. group: All-Link group number addr: Inteon address of the linked device
def _ReadEncodedData(self, read_size): """Reads encoded data from the file-like object. Args: read_size (int): number of bytes of encoded data to read. Returns: int: number of bytes of encoded data read. """ encoded_data = self._file_object.read(read_size) read_count = len(encoded...
Reads encoded data from the file-like object. Args: read_size (int): number of bytes of encoded data to read. Returns: int: number of bytes of encoded data read.
def add_language_to_project(self, project_id, language_code): """ Adds a new language to project """ self._run( url_path="languages/add", id=project_id, language=language_code ) return True
Adds a new language to project