code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _ParseFileEntry(self, knowledge_base, file_entry): """Parses a file entry for a preprocessing attribute. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. file_entry (dfvfs.FileEntry): file entry that contains the artifact value data. Raises: Pre...
Parses a file entry for a preprocessing attribute. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. file_entry (dfvfs.FileEntry): file entry that contains the artifact value data. Raises: PreProcessFail: if the preprocessing fails.
def isnumber(self, string, *args): """Is number args: string (str): match returns: bool """ try: n, u = utility.analyze_number(string) except SyntaxError: return False return True
Is number args: string (str): match returns: bool
def begin_run_group(project): """ Begin a run_group in the database. A run_group groups a set of runs for a given project. This models a series of runs that form a complete binary runtime test. Args: project: The project we begin a new run_group for. Returns: ``(group, session...
Begin a run_group in the database. A run_group groups a set of runs for a given project. This models a series of runs that form a complete binary runtime test. Args: project: The project we begin a new run_group for. Returns: ``(group, session)`` where group is the created group in th...
def get_choices(timezones, grouped=False): """Retrieves timezone choices from any iterable (normally pytz).""" # Created a namedtuple to store the "key" for the choices_dict TZOffset = namedtuple('TZOffset', 'value offset_string') choices_dict = defaultdict(list) # Iterate through the timezones a...
Retrieves timezone choices from any iterable (normally pytz).
def handle_task(self, uuid_task, worker=None): """Handle snapshotted event.""" uuid, task = uuid_task if task.worker and task.worker.hostname: worker = self.handle_worker( (task.worker.hostname, task.worker), ) defaults = { 'name': tas...
Handle snapshotted event.
def parse(self, text): """Parses and renders a text as HTML regarding current format. """ if self.format == 'markdown': try: import markdown except ImportError: raise RuntimeError(u"Looks like markdown is not installed") if tex...
Parses and renders a text as HTML regarding current format.
def import_rsa_key(pem_data): """ Extract an RSA key from a PEM-encoded X.509 certificate :param pem_data: RSA key encoded in standard form :return: rsa.RSAPublicKey instance """ if not pem_data.startswith(PREFIX): pem_data = bytes('{}\n{}\n{}'.format(PREFIX, pem_data, POSTFIX), ...
Extract an RSA key from a PEM-encoded X.509 certificate :param pem_data: RSA key encoded in standard form :return: rsa.RSAPublicKey instance
def _get_base(role, **conn): """ Determine whether the boto get_role call needs to be made or if we already have all that data in the role object. :param role: dict containing (at the very least) role_name and/or arn. :param conn: dict containing enough information to make a connection to the desire...
Determine whether the boto get_role call needs to be made or if we already have all that data in the role object. :param role: dict containing (at the very least) role_name and/or arn. :param conn: dict containing enough information to make a connection to the desired account. :return: Camelized dict de...
def stop(self): """ Stop services and requestors and then connection. :return: self """ LOGGER.debug("natsd.Driver.stop") for requester in self.requester_registry: requester.stop() self.requester_registry.clear() for service in self.services_r...
Stop services and requestors and then connection. :return: self
def get_active_choices(self, language_code=None, site_id=None): """ Find out which translations should be visible in the site. It returns a list with either a single choice (the current language), or a list with the current language + fallback language. """ if language_co...
Find out which translations should be visible in the site. It returns a list with either a single choice (the current language), or a list with the current language + fallback language.
def refresh_jwt_token(self, token, override_access_lifespan=None): """ Creates a new token for a user if and only if the old token's access permission is expired but its refresh permission is not yet expired. The new token's refresh expiration moment is the same as the old token'...
Creates a new token for a user if and only if the old token's access permission is expired but its refresh permission is not yet expired. The new token's refresh expiration moment is the same as the old token's, but the new token's access expiration is refreshed :param: token: ...
def remove(self): """ remove this endpoint from Ariane server :return: """ LOGGER.debug("Endpoint.remove - " + self.id + " - " + self.url) if self.id is None: return None else: if self.id in EndpointService.local_cache_by_id: ...
remove this endpoint from Ariane server :return:
def sub_array_2d_from_sub_array_1d(self, sub_array_1d): """ Map a 1D sub-array the same dimension as the sub-grid (e.g. including sub-pixels) to its original masked 2D sub array. Parameters ----------- sub_array_1d : ndarray The 1D sub_array which is mapped to its ma...
Map a 1D sub-array the same dimension as the sub-grid (e.g. including sub-pixels) to its original masked 2D sub array. Parameters ----------- sub_array_1d : ndarray The 1D sub_array which is mapped to its masked 2D sub-array.
def str2url(str): """ Takes a UTF-8 string and replaces all characters with the equivalent in 7-bit ASCII. It returns a plain ASCII string usable in URLs. """ try: str = str.encode('utf-8') except: pass mfrom = "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîï" to = "AAAAAAECEEEEIIIIDNOOOOOOUUUUYSaaaaaaaceee...
Takes a UTF-8 string and replaces all characters with the equivalent in 7-bit ASCII. It returns a plain ASCII string usable in URLs.
def valuefrompostdata(self, postdata): """This parameter method searches the POST data and retrieves the values it needs. It does not set the value yet though, but simply returns it. Needs to be explicitly passed to parameter.set()""" if self.id in postdata and postdata[self.id] != '': retur...
This parameter method searches the POST data and retrieves the values it needs. It does not set the value yet though, but simply returns it. Needs to be explicitly passed to parameter.set()
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: SyncListItemContext for this SyncListItemInstance :rtype: twilio.rest.preview.sync.service.sync_l...
Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: SyncListItemContext for this SyncListItemInstance :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemContext
def toVName(name, stripNum=0, upper=False): """ Turn a Python name into an iCalendar style name, optionally uppercase and with characters stripped off. """ if upper: name = name.upper() if stripNum != 0: name = name[:-stripNum] return name.replace('_', '-')
Turn a Python name into an iCalendar style name, optionally uppercase and with characters stripped off.
def delete(self, subnet_id): """ This is bad delete function because one vpc can have more than one subnet. It is Ok if user only use CAL for manage cloud resource We will update ASAP. """ # 1 : show subnet subnet = self.client.describe_subnets( ...
This is bad delete function because one vpc can have more than one subnet. It is Ok if user only use CAL for manage cloud resource We will update ASAP.
def getSkeletalSummaryData(self, action): """Reads summary information about the current pose of the skeleton associated with the given action.""" fn = self.function_table.getSkeletalSummaryData pSkeletalSummaryData = VRSkeletalSummaryData_t() result = fn(action, byref(pSkeletalSummaryD...
Reads summary information about the current pose of the skeleton associated with the given action.
def _get_namespace2go2term(go2terms): """Group GO IDs by namespace.""" namespace2go2term = cx.defaultdict(dict) for goid, goterm in go2terms.items(): namespace2go2term[goterm.namespace][goid] = goterm return namespace2go2term
Group GO IDs by namespace.
def agreement_weighted(ci, wts): ''' D = AGREEMENT_WEIGHTED(CI,WTS) is identical to AGREEMENT, with the exception that each partitions contribution is weighted according to the corresponding scalar value stored in the vector WTS. As an example, suppose CI contained partitions obtained using some heu...
D = AGREEMENT_WEIGHTED(CI,WTS) is identical to AGREEMENT, with the exception that each partitions contribution is weighted according to the corresponding scalar value stored in the vector WTS. As an example, suppose CI contained partitions obtained using some heuristic for maximizing modularity. A possi...
def birth(self): ''' Create the individual (compute the spline curve) ''' splineReal = scipy.interpolate.splrep(self.x, self.y.real) self.y_int.real = scipy.interpolate.splev(self.x_int,splineReal) splineImag = scipy.interpolate.splrep(self.x, self.y.imag) self.y_int.imag = scipy.interpolate.splev(self.x_...
Create the individual (compute the spline curve)
def create(cls, interface_id, logical_interface_ref, **kw): """ :param int interface_id: the interface id :param str logical_ref: logical interface reference, must be unique from inline intfs :rtype: dict """ data = {'inspect_unspecified_vlans': True, ...
:param int interface_id: the interface id :param str logical_ref: logical interface reference, must be unique from inline intfs :rtype: dict
def _validate_data(dataset, target, features=None, validation_set='auto'): """ Validate and canonicalize training and validation data. Parameters ---------- dataset : SFrame Dataset for training the model. target : string Name of the column containing the target variable. ...
Validate and canonicalize training and validation data. Parameters ---------- dataset : SFrame Dataset for training the model. target : string Name of the column containing the target variable. features : list[string], optional List of feature names used. validation_s...
def complete(self, text, state): """Return the next possible completion for 'text'. This is called successively with state == 0, 1, 2, ... until it returns None. The completion should begin with 'text'. """ if self.use_main_ns: self.namespace = __main__.__dict__ ...
Return the next possible completion for 'text'. This is called successively with state == 0, 1, 2, ... until it returns None. The completion should begin with 'text'.
def gamma(self, gamma=1.0): """Apply gamma correction to the channels of the image. If *gamma* is a tuple, then it should have as many elements as the channels of the image, and the gamma correction is applied elementwise. If *gamma* is a number, the same gamma correction is applied on e...
Apply gamma correction to the channels of the image. If *gamma* is a tuple, then it should have as many elements as the channels of the image, and the gamma correction is applied elementwise. If *gamma* is a number, the same gamma correction is applied on every channel, if there are seve...
def normalize_map_between(dictionary, norm_min, norm_max): """ Performs linear normalization of all values in Map between normMin and normMax :param: map Map to normalize values for :param: normMin Smallest normalized value :param: normMax Largest normalized value :return: A new map with do...
Performs linear normalization of all values in Map between normMin and normMax :param: map Map to normalize values for :param: normMin Smallest normalized value :param: normMax Largest normalized value :return: A new map with double values within [normMin, normMax]
def _autobox(content, format): ''' Autobox response content. :param content: Response content :type content: str :param format: Format to return :type format: `yaxil.Format` :returns: Autoboxed content :rtype: dict|xml.etree.ElementTree.Element|csvreader ''' if format == Format....
Autobox response content. :param content: Response content :type content: str :param format: Format to return :type format: `yaxil.Format` :returns: Autoboxed content :rtype: dict|xml.etree.ElementTree.Element|csvreader
def check_error(model, path, shapes, output = 'softmax_output', verbose = True): """ Check the difference between predictions from MXNet and CoreML. """ coreml_model = _coremltools.models.MLModel(path) input_data = {} input_data_copy = {} for ip in shapes: input_data[ip] = _np.random...
Check the difference between predictions from MXNet and CoreML.
def _fchown(self, real, fileno, uid, gid): """Run fake fchown code if fileno points to a sub-path of our tree. The ownership set with this fake fchown can be inspected by looking at the self.uid/self.gid dictionaries. """ path = self._fake_path(self._path_from_fd(fileno)) ...
Run fake fchown code if fileno points to a sub-path of our tree. The ownership set with this fake fchown can be inspected by looking at the self.uid/self.gid dictionaries.
def _args_from_dict(ddata: Mapping[str, Any]): """Allows to construct an instance of AnnData from a dictionary. Acts as interface for the communication with the hdf5 file. In particular, from a dict that has been written using ``AnnData._to_dict_fixed_width_arrays``. """ ...
Allows to construct an instance of AnnData from a dictionary. Acts as interface for the communication with the hdf5 file. In particular, from a dict that has been written using ``AnnData._to_dict_fixed_width_arrays``.
def copy(self, new_name=None): """ Returns a deep copy of the system Parameters ----------- new_name: str, optional Set a new meta name parameter. Default: <old_name>_copy """ _tmp = copy.deepcopy(self) if not new_name: new_na...
Returns a deep copy of the system Parameters ----------- new_name: str, optional Set a new meta name parameter. Default: <old_name>_copy
def add(self, key, value, time, compress_level=-1): """ Add a key/value to server ony if it does not exist. :param key: Key's name :type key: six.string_types :param value: A value to be stored on server. :type value: object :param time: Time in seconds that your...
Add a key/value to server ony if it does not exist. :param key: Key's name :type key: six.string_types :param value: A value to be stored on server. :type value: object :param time: Time in seconds that your key will expire. :type time: int :param compress_level:...
def convert_to_str(d): """ Recursively convert all values in a dictionary to strings This is required because setup() does not like unicode in the values it is supplied. """ d2 = {} for k, v in d.items(): k = str(k) if type(v) in [list, tuple]: d2[k] = [str(a) fo...
Recursively convert all values in a dictionary to strings This is required because setup() does not like unicode in the values it is supplied.
def evaluate_binop_logical(self, operation, left, right, **kwargs): """ Evaluate given logical binary operation with given operands. """ if not operation in self.binops_logical: raise ValueError("Invalid logical binary operation '{}'".format(operation)) result = self....
Evaluate given logical binary operation with given operands.
def fail_remaining(self): """ Mark all unfinished tasks (including currently running ones) as failed. """ self._failed.update(self._graph.nodes) self._graph = Graph() self._running = set()
Mark all unfinished tasks (including currently running ones) as failed.
def boxcox_trans(p, **kwargs): """ Boxcox Transformation Parameters ---------- p : float Power parameter, commonly denoted by lower-case lambda in formulae kwargs : dict Keyword arguments passed onto :func:`trans_new`. Should not include the `transform` o...
Boxcox Transformation Parameters ---------- p : float Power parameter, commonly denoted by lower-case lambda in formulae kwargs : dict Keyword arguments passed onto :func:`trans_new`. Should not include the `transform` or `inverse`.
def process_data(key, data_list, result_info_key, identifier_keys): """ Given a key as the endpoint name, pulls the data for that endpoint out of the data_list for each address, processes the data into a more excel-friendly format and returns that data. Args: key: the endpoint n...
Given a key as the endpoint name, pulls the data for that endpoint out of the data_list for each address, processes the data into a more excel-friendly format and returns that data. Args: key: the endpoint name of the data to process data_list: the main data list to take...
async def add(self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None): """ Stores the value in the given key with ttl if specified. Raises an error if the key already exists. :param key: str :param value: obj :param ttl: int the expiration time in seco...
Stores the value in the given key with ttl if specified. Raises an error if the key already exists. :param key: str :param value: obj :param ttl: int the expiration time in seconds. Due to memcached restrictions if you want compatibility use int. In case you need...
def describe_enum_value(enum_value): """Build descriptor for Enum instance. Args: enum_value: Enum value to provide descriptor for. Returns: Initialized EnumValueDescriptor instance describing the Enum instance. """ enum_value_descriptor = EnumValueDescriptor() enum_value_descripto...
Build descriptor for Enum instance. Args: enum_value: Enum value to provide descriptor for. Returns: Initialized EnumValueDescriptor instance describing the Enum instance.
def set_description(self, vrf_name, description=None, default=False, disable=False): """ Configures the VRF description Args: vrf_name (str): The VRF name to configure description(str): The string to set the vrf description to default (bool): ...
Configures the VRF description Args: vrf_name (str): The VRF name to configure description(str): The string to set the vrf description to default (bool): Configures the vrf description to its default value disable (bool): Negates the vrf description Retu...
def register_custom_adapter(cls, target_class, adapter): """ :type target_class: type :type adapter: JsonAdapter|type :rtype: None """ class_name = target_class.__name__ if adapter.can_serialize(): cls._custom_serializers[class_name] = adapter ...
:type target_class: type :type adapter: JsonAdapter|type :rtype: None
def sample(self, num_rows=1): """Creates sintentic values stadistically similar to the original dataset. Args: num_rows: `int` amount of samples to generate. Returns: np.ndarray: Sampled data. """ self.check_fit() res = {} means = np.ze...
Creates sintentic values stadistically similar to the original dataset. Args: num_rows: `int` amount of samples to generate. Returns: np.ndarray: Sampled data.
def create_panel_of_normals(items, group_id, work_dir): """Create a panel of normals from one or more background read counts. """ out_file = os.path.join(work_dir, "%s-%s-pon.hdf5" % (dd.get_sample_name(items[0]), group_id)) if not utils.file_exists(out_file): with file_transaction(items[0], out...
Create a panel of normals from one or more background read counts.
def restore(self): """Restore the saved value for the attribute of the object.""" if self.proxy_object is None: if self.getter: setattr(self.getter_class, self.attr_name, self.getter) elif self.is_local: setattr(self.orig_object, self.attr_name, se...
Restore the saved value for the attribute of the object.
def render(self, size): """ render identicon to PIL.Image @param size identicon patchsize. (image size is 3 * [size]) @return PIL.Image """ # decode the code middle, corner, side, foreColor, backColor = self.decode(self.code) size = int(size) # m...
render identicon to PIL.Image @param size identicon patchsize. (image size is 3 * [size]) @return PIL.Image
def average(var, key, N): '''average over N points''' global average_data if not key in average_data: average_data[key] = [var]*N return var average_data[key].pop(0) average_data[key].append(var) return sum(average_data[key])/N
average over N points
def get_comments(self, project, work_item_id, top=None, continuation_token=None, include_deleted=None, expand=None, order=None): """GetComments. [Preview API] Returns a list of work item comments, pageable. :param str project: Project ID or project name :param int work_item_id: Id of a w...
GetComments. [Preview API] Returns a list of work item comments, pageable. :param str project: Project ID or project name :param int work_item_id: Id of a work item to get comments for. :param int top: Max number of comments to return. :param str continuation_token: Used to query...
def get_small_image_url(self, page=1): """ Returns the URL for the small sized image of a single page. The page kwarg specifies which page to return. One is the default. """ template = self.resources.page.get('image') return template.replace( "{page}", ...
Returns the URL for the small sized image of a single page. The page kwarg specifies which page to return. One is the default.
def make_relationship_aggregate(self, relationship): """ Returns a new relationship aggregate for the given relationship. :param relationship: Instance of :class:`everest.entities.relationship.DomainRelationship`. """ if not self._session.IS_MANAGING_BACKREFERENCES: ...
Returns a new relationship aggregate for the given relationship. :param relationship: Instance of :class:`everest.entities.relationship.DomainRelationship`.
def put_account(self, headers=None, query=None, cdn=False, body=None): """ PUTs the account and returns the results. This is usually done with the extract-archive bulk upload request and has no other use I know of (but the call is left open in case there ever is). :param...
PUTs the account and returns the results. This is usually done with the extract-archive bulk upload request and has no other use I know of (but the call is left open in case there ever is). :param headers: Additional headers to send with the request. :param query: Set to a dict ...
def PC_AC1_calc(P, TOP, POP): """ Calculate percent chance agreement for Gwet's AC1. :param P: condition positive :type P : dict :param TOP: test outcome positive :type TOP : dict :param POP: population :type POP:dict :return: percent chance agreement as float """ try: ...
Calculate percent chance agreement for Gwet's AC1. :param P: condition positive :type P : dict :param TOP: test outcome positive :type TOP : dict :param POP: population :type POP:dict :return: percent chance agreement as float
def get_template(cls, message, messenger): """Get a template path to compile a message. 1. `tpl` field of message context; 2. `template` field of message class; 3. deduced from message, messenger data and `template_ext` message type field (e.g. `sitemessage/messages/plain__sm...
Get a template path to compile a message. 1. `tpl` field of message context; 2. `template` field of message class; 3. deduced from message, messenger data and `template_ext` message type field (e.g. `sitemessage/messages/plain__smtp.txt` for `plain` message type). :param Mes...
def remove_temp_copy(self): """ Removes a temporary copy of the MAGICC version shipped with Pymagicc. """ if self.is_temp and self.root_dir is not None: shutil.rmtree(self.root_dir) self.root_dir = None
Removes a temporary copy of the MAGICC version shipped with Pymagicc.
def decipher(self,string): """Decipher string using Foursquare cipher according to initialised key. Punctuation and whitespace are removed from the input. The ciphertext should be an even number of characters. If the input ciphertext is not an even number of characters, an 'X' will be appended. ...
Decipher string using Foursquare cipher according to initialised key. Punctuation and whitespace are removed from the input. The ciphertext should be an even number of characters. If the input ciphertext is not an even number of characters, an 'X' will be appended. Example:: plaintext = Fo...
def linkify(self): """ Check exclusion for each timeperiod :return: None """ for t_id in self.items: timeperiod = self.items[t_id] timeperiod.linkify(self)
Check exclusion for each timeperiod :return: None
def push(self, kv): """ Adds a new item from the given (key, value)-tuple. If the key exists, pushes the updated item to the head of the dict. """ if kv[0] in self: self.__delitem__(kv[0]) self.__setitem__(kv[0], kv[1])
Adds a new item from the given (key, value)-tuple. If the key exists, pushes the updated item to the head of the dict.
def run_command_on_marathon_leader( command, username=None, key_path=None, noisy=True ): """ Run a command on the Marathon leader """ return run_command(shakedown.marathon_leader_ip(), command, username, key_path, noisy)
Run a command on the Marathon leader
def ToByteArray(self): """ Serialize self and get the byte stream. Returns: bytes: serialized object. """ ms = StreamManager.GetStream() writer = BinaryWriter(ms) self.Serialize(writer) retval = ms.ToArray() StreamManager.ReleaseStrea...
Serialize self and get the byte stream. Returns: bytes: serialized object.
def parse_sentence(self, string): """ Parses the given sentence. BASIC commands must be types UPPERCASE and as SEEN in ZX BASIC. e.g. GO SUB for gosub, etc... """ result = [] def shift(string_): """ Returns first word of a string, and remaining """ ...
Parses the given sentence. BASIC commands must be types UPPERCASE and as SEEN in ZX BASIC. e.g. GO SUB for gosub, etc...
def enterEvent( self, event ): """ Toggles the display for the tracker item. """ item = self.trackerItem() if ( item ): item.setVisible(True)
Toggles the display for the tracker item.
def _check_std(self, paths, cmd_pieces): """ Run `cmd` as a check on `paths`. """ cmd_pieces.extend(paths) process = Popen(cmd_pieces, stdout=PIPE, stderr=PIPE) out, err = process.communicate() lines = out.strip().splitlines() + err.strip().splitlines() re...
Run `cmd` as a check on `paths`.
def _get_pydot(self): """Return pydot package. Load pydot, if necessary.""" if self.pydot: return self.pydot self.pydot = __import__("pydot") return self.pydot
Return pydot package. Load pydot, if necessary.
def add_response_headers(h): """ Add HTTP-headers to response. Example: @add_response_headers({'Refresh': '10', 'X-Powered-By': 'Django'}) def view(request): .... """ def headers_wrapper(fun): def wrapped_function(*args, **kwargs): response = fun(*args...
Add HTTP-headers to response. Example: @add_response_headers({'Refresh': '10', 'X-Powered-By': 'Django'}) def view(request): ....
def clear_jobs(): '''Clear old jobs :param days: Jobs for how many days should be kept (default: 10) :type days: integer :statuscode 200: no error :statuscode 403: not authorized to delete jobs :statuscode 409: an error occurred ''' if not is_authorized(): return json.dumps({'e...
Clear old jobs :param days: Jobs for how many days should be kept (default: 10) :type days: integer :statuscode 200: no error :statuscode 403: not authorized to delete jobs :statuscode 409: an error occurred
def bootstrap_app(): ''' Grab the opts dict of the master config by trying to import Salt ''' from salt.netapi.rest_cherrypy import app import salt.config __opts__ = salt.config.client_config( os.environ.get('SALT_MASTER_CONFIG', '/etc/salt/master')) return app.get_app(__opts__)
Grab the opts dict of the master config by trying to import Salt
def show_text_glyphs(self, text, glyphs, clusters, cluster_flags=0): """This operation has rendering effects similar to :meth:`show_glyphs` but, if the target surface supports it (see :meth:`Surface.has_show_text_glyphs`), uses the provided text and cluster mapping to embed the t...
This operation has rendering effects similar to :meth:`show_glyphs` but, if the target surface supports it (see :meth:`Surface.has_show_text_glyphs`), uses the provided text and cluster mapping to embed the text for the glyphs shown in the output. If the target does not support t...
def orthogonal_basis(self): """Return an orthogonal basis to this direction. Note ---- Only implemented in 3D. Returns ------- :obj:`tuple` of :obj:`Direction` The pair of normalized Direction vectors that form a basis of this directi...
Return an orthogonal basis to this direction. Note ---- Only implemented in 3D. Returns ------- :obj:`tuple` of :obj:`Direction` The pair of normalized Direction vectors that form a basis of this direction's orthogonal complement. Ra...
def get_name_addr(value): """ name-addr = [display-name] angle-addr """ name_addr = NameAddr() # Both the optional display name and the angle-addr can start with cfws. leader = None if value[0] in CFWS_LEADER: leader, value = get_cfws(value) if not value: raise error...
name-addr = [display-name] angle-addr
def fill_auth_list(self, auth_provider, name, groups, auth_list=None, permissive=None): ''' Returns a list of authorisation matchers that a user is eligible for. This list is a combination of the provided personal matchers plus the matchers of any group the user is in. ''' ...
Returns a list of authorisation matchers that a user is eligible for. This list is a combination of the provided personal matchers plus the matchers of any group the user is in.
def conformPadding(cls, chars): """ Ensure alternate input padding formats are conformed to formats defined in PAD_MAP If chars is already a format defined in PAD_MAP, then it is returned unmodified. Example:: '#' -> '#' '@@@@' -> '@@@@' ...
Ensure alternate input padding formats are conformed to formats defined in PAD_MAP If chars is already a format defined in PAD_MAP, then it is returned unmodified. Example:: '#' -> '#' '@@@@' -> '@@@@' '%04d' -> '#' Args: char...
def port_create(request, network_id, **kwargs): """Create a port on a specified network. :param request: request context :param network_id: network id a subnet is created on :param device_id: (optional) device id attached to the port :param tenant_id: (optional) tenant id of the port created :p...
Create a port on a specified network. :param request: request context :param network_id: network id a subnet is created on :param device_id: (optional) device id attached to the port :param tenant_id: (optional) tenant id of the port created :param name: (optional) name of the port created :ret...
def snapshot(self): """ Return a nested dictionary snapshot of all metrics and their values at this time. Example: { 'category': { 'metric1_name': 42.0, 'metric2_name': 'foo' } } """ return dict((category, di...
Return a nested dictionary snapshot of all metrics and their values at this time. Example: { 'category': { 'metric1_name': 42.0, 'metric2_name': 'foo' } }
def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gathe...
Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``n...
def _render_headers(self): """ Write the headers row """ headers = getattr(self, 'headers', ()) for index, col in enumerate(headers): # We write the headers cell = self.worksheet.cell(row=1, column=index + 1) cell.value = col['label'] ...
Write the headers row
async def close(self) -> None: """Close underlying connector. Release all acquired resources. """ if not self.closed: if self._connector is not None and self._connector_owner: await self._connector.close() self._connector = None
Close underlying connector. Release all acquired resources.
def write(self, obj): """Writes the given object to the cache file as pickle. The cache file with its path is created if needed. """ if self.verbose: self._warnings("cache miss for {0}", self._cache_id_desc()) if self._start_time is not None: elapsed = ...
Writes the given object to the cache file as pickle. The cache file with its path is created if needed.
def get_clan_tracking(self, *tags: crtag, **params: keys): """Returns if the clan is currently being tracked by the API by having either cr-api.com or royaleapi.com in the clan description Parameters ---------- \*tags: str Valid clan tags. Minimum length: 3 ...
Returns if the clan is currently being tracked by the API by having either cr-api.com or royaleapi.com in the clan description Parameters ---------- \*tags: str Valid clan tags. Minimum length: 3 Valid characters: 0289PYLQGRJCUV \*\*keys: Optional...
def timed_rotating_file_handler(name, logname, filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False): """ A Bark logging handler logging output to a named file. At intervals specified by the 'when', the file wil...
A Bark logging handler logging output to a named file. At intervals specified by the 'when', the file will be rotated, under control of 'backupCount'. Similar to logging.handlers.TimedRotatingFileHandler.
def designator(self): """\ Returns the version and error correction level as string `V-E` where `V` represents the version number and `E` the error level. """ version = str(self.version) return '-'.join((version, self.error) if self.error else (version,))
\ Returns the version and error correction level as string `V-E` where `V` represents the version number and `E` the error level.
def dump_yaml(data, Dumper=_Dumper, default_flow_style=False): """Returns data as yaml-formatted string.""" content = yaml.dump(data, default_flow_style=default_flow_style, Dumper=Dumper) return content.strip()
Returns data as yaml-formatted string.
def delete_refresh_token(self, refresh_token): """ Deletes a refresh token after use :param refresh_token: The refresh token to delete. """ access_token = self.fetch_by_refresh_token(refresh_token) self.delete(access_token.token)
Deletes a refresh token after use :param refresh_token: The refresh token to delete.
def is_none_or(self): """ Ensures :attr:`subject` is either ``None``, or satisfies subsequent (chained) conditions:: Ensure(None).is_none_or.is_an(int) """ if self._subject is None: return NoOpInspector(subject=self._subject, error_factory=self._error_factory) ...
Ensures :attr:`subject` is either ``None``, or satisfies subsequent (chained) conditions:: Ensure(None).is_none_or.is_an(int)
def parse_signature(signature): """Parse a signature into its input and return parameter types. This will also collect the types that are required by any of the input and return types. :sig: (str) -> Tuple[List[str], str, Set[str]] :param signature: Signature to parse. :return: Input parameter...
Parse a signature into its input and return parameter types. This will also collect the types that are required by any of the input and return types. :sig: (str) -> Tuple[List[str], str, Set[str]] :param signature: Signature to parse. :return: Input parameter types, return type, and all required t...
def listar_por_equipamento(self, id_equipment): """List all Script related Equipment. :param id_equipment: Identifier of the Equipment. Integer value and greater than zero. :return: Dictionary with the following structure: :: {script': [{‘id’: < id >, ‘nome’: ...
List all Script related Equipment. :param id_equipment: Identifier of the Equipment. Integer value and greater than zero. :return: Dictionary with the following structure: :: {script': [{‘id’: < id >, ‘nome’: < nome >, ‘descricao’: < descricao >, ...
def prev_img_ws(self, ws, loop=True): """Go to the previous image in the focused channel in the workspace. """ channel = self.get_active_channel_ws(ws) if channel is None: return channel.prev_image() return True
Go to the previous image in the focused channel in the workspace.
def visualize_cloud_of_words(dictionary, image_path=None): """ Renders the cloud of words representation for a given dictionary of frequencies :param dictionary: the dictionary object that contains key-frequency pairs :param image_path: the path to the image mask, None if no masking is ...
Renders the cloud of words representation for a given dictionary of frequencies :param dictionary: the dictionary object that contains key-frequency pairs :param image_path: the path to the image mask, None if no masking is needed
def cause_effect_info(self, mechanism, purview): """Return the cause-effect information for a mechanism over a purview. This is the minimum of the cause and effect information. """ return min(self.cause_info(mechanism, purview), self.effect_info(mechanism, purview))
Return the cause-effect information for a mechanism over a purview. This is the minimum of the cause and effect information.
def combs(a, r): """NumPy implementation of ``itertools.combinations``. Return successive ``r``-length combinations of elements in the array ``a``. Args: a (np.ndarray): The array from which to get combinations. r (int): The length of the combinations. Returns: np.ndarray: An ...
NumPy implementation of ``itertools.combinations``. Return successive ``r``-length combinations of elements in the array ``a``. Args: a (np.ndarray): The array from which to get combinations. r (int): The length of the combinations. Returns: np.ndarray: An array of combinations.
def fit_linear(X, y): """ Uses OLS to fit the regression. """ model = linear_model.LinearRegression() model.fit(X, y) return model
Uses OLS to fit the regression.
def unpack_4to8(data): """ Promote 2-bit unisgned data into 8-bit unsigned data. Args: data: Numpy array with dtype == uint8 Notes: # The process is this: # ABCDEFGH [Bits of one 4+4-bit value] # 00000000ABCDEFGH [astype(uint16)] # 0000ABCDEFGH0000 [<< 4] # ...
Promote 2-bit unisgned data into 8-bit unsigned data. Args: data: Numpy array with dtype == uint8 Notes: # The process is this: # ABCDEFGH [Bits of one 4+4-bit value] # 00000000ABCDEFGH [astype(uint16)] # 0000ABCDEFGH0000 [<< 4] # 0000ABCDXXXXEFGH [bitwise 'or' ...
def evert(iterable: Iterable[Dict[str, Tuple]]) -> Iterable[Iterable[Dict[str, Any]]]: '''Evert dictionaries with tuples. Iterates over the list of dictionaries and everts them with their tuple values. For example: ``[ { 'a': ( 1, 2, ), }, ]`` becomes ``[ ( { 'a': 1, }, ), ( { 'a', 2, }, ) ...
Evert dictionaries with tuples. Iterates over the list of dictionaries and everts them with their tuple values. For example: ``[ { 'a': ( 1, 2, ), }, ]`` becomes ``[ ( { 'a': 1, }, ), ( { 'a', 2, }, ) ]`` The resulting iterable contains the same number of tuples as the initial iterable...
def plot(self, entity): """ Basic plot of a single binary sensor data. Parameters ---------- entity : string The entity to plot """ df = self._binary_df[[entity]] resampled = df.resample("s").ffill() # Sample at seconds and ffill resa...
Basic plot of a single binary sensor data. Parameters ---------- entity : string The entity to plot
def execute_command(working_dir, cmd, env_dict): """ execute_command: run the command provided in the working dir specified adding the env_dict settings to the execution environment :param working_dir: path to directory to execute command also gets added to the PATH :param cmd: Shell com...
execute_command: run the command provided in the working dir specified adding the env_dict settings to the execution environment :param working_dir: path to directory to execute command also gets added to the PATH :param cmd: Shell command to execute :param env_dict: dictionary of additional...
def add_proxy_to(self, parent, name, multiplicity=Multiplicity.ONE_MANY, **kwargs): # type: (Any, AnyStr, Any, **Any) -> Part """Add this model as a proxy to another parent model. This will add the current model as a proxy model to another parent model. It ensure that it will copy the w...
Add this model as a proxy to another parent model. This will add the current model as a proxy model to another parent model. It ensure that it will copy the whole subassembly to the 'parent' model. In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` a...
def p_arglist(p): ''' arglist : arg | arglist COMMA arg ''' if len(p) == 2: p[0] = [p[1]] else: p[0] = p[1] p[0].append(p[3])
arglist : arg | arglist COMMA arg
def _defaultdict(dct, fallback=_illegal_character): """Wraps the given dictionary such that the given fallback function will be called when a nonexistent key is accessed. """ out = defaultdict(lambda: fallback) for k, v in six.iteritems(dct): out[k] = v return out
Wraps the given dictionary such that the given fallback function will be called when a nonexistent key is accessed.
def merge(self, commit_message='', sha=None): """Merge this pull request. :param str commit_message: (optional), message to be used for the merge commit :returns: bool """ parameters = {'commit_message': commit_message} if sha: parameters['sha'] =...
Merge this pull request. :param str commit_message: (optional), message to be used for the merge commit :returns: bool
def parse_type(defn, preprocess=True): """ Parse a simple type expression into a SimType >>> parse_type('int *') """ if pycparser is None: raise ImportError("Please install pycparser in order to parse C definitions") defn = 'typedef ' + defn.strip('; \n\t\r') + ' QQQQ;' if preproc...
Parse a simple type expression into a SimType >>> parse_type('int *')
def classify_harmonic(self, partial_labels, use_CMN=True): '''Harmonic function method for semi-supervised classification, also known as the Gaussian Mean Fields algorithm. partial_labels: (n,) array of integer labels, -1 for unlabeled. use_CMN : when True, apply Class Mass Normalization From "Sem...
Harmonic function method for semi-supervised classification, also known as the Gaussian Mean Fields algorithm. partial_labels: (n,) array of integer labels, -1 for unlabeled. use_CMN : when True, apply Class Mass Normalization From "Semi-Supervised Learning Using Gaussian Fields and Harmonic Functions...