code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def no_company_with_insufficient_companies_house_data(value): """ Confirms that the company number is not for for a company that Companies House does not hold information on. Args: value (string): The company number to check. Raises: django.forms.ValidationError """ for p...
Confirms that the company number is not for for a company that Companies House does not hold information on. Args: value (string): The company number to check. Raises: django.forms.ValidationError
def isSuperTagSetOf(self, tagSet): """Test type relationship against given *TagSet* The callee is considered to be a supertype of given *TagSet* tag-wise if all tags in *TagSet* are present in the callee and they are in the same order. Parameters ---------- tagS...
Test type relationship against given *TagSet* The callee is considered to be a supertype of given *TagSet* tag-wise if all tags in *TagSet* are present in the callee and they are in the same order. Parameters ---------- tagSet: :class:`~pyasn1.type.tag.TagSet` ...
def _maybe_repeat(self, x): """Utility function for processing arguments that are singletons or lists. Args: x: either a list of self.n elements, or not a list. Returns: a list of self.n elements. """ if isinstance(x, list): assert len(x) == self.n return x else: ...
Utility function for processing arguments that are singletons or lists. Args: x: either a list of self.n elements, or not a list. Returns: a list of self.n elements.
def remove_object(self, name): """ Remove the object exposed under that name. If no object is registered under the supplied name, a RuntimeError is raised. :param name: Name of object to be removed. """ if name not in self._object_map: raise RuntimeError('No ...
Remove the object exposed under that name. If no object is registered under the supplied name, a RuntimeError is raised. :param name: Name of object to be removed.
def _base64_to_file(b64str, outfpath, writetostrio=False): '''This converts the base64 encoded string to a file. Parameters ---------- b64str : str A base64 encoded strin that is the output of `base64.b64encode`. outfpath : str The path to where the file will be written. This shou...
This converts the base64 encoded string to a file. Parameters ---------- b64str : str A base64 encoded strin that is the output of `base64.b64encode`. outfpath : str The path to where the file will be written. This should include an appropriate extension for the file (e.g. a b...
def get_userids_for_address(self, address: Address) -> Set[str]: """ Return all known user ids for the given ``address``. """ if not self.is_address_known(address): return set() return self._address_to_userids[address]
Return all known user ids for the given ``address``.
def rfc2426(self): """RFC2426-encode the field content. :return: the field in the RFC 2426 format. :returntype: `str`""" if self.type: p={"type":self.type} else: p={} return rfc2425encode(self.name,self.cred,p)
RFC2426-encode the field content. :return: the field in the RFC 2426 format. :returntype: `str`
def get_model(): """Get the NN model that's being analyzed from the request context. Put the model in the request context if it is not yet there. Returns: instance of :class:`.models.model.Model` or derived class """ if not hasattr(g, 'model'): g.model = load_model(current_...
Get the NN model that's being analyzed from the request context. Put the model in the request context if it is not yet there. Returns: instance of :class:`.models.model.Model` or derived class
def append_id(expr, id_col='append_id'): """ Append an ID column to current column to form a new DataFrame. :param str id_col: name of appended ID field. :return: DataFrame with ID field :rtype: DataFrame """ if hasattr(expr, '_xflow_append_id'): return expr._xflow_append_id(id_col...
Append an ID column to current column to form a new DataFrame. :param str id_col: name of appended ID field. :return: DataFrame with ID field :rtype: DataFrame
def refresh_token(): # noqa: E501 """Refreshes login token using refresh token Refreshes login token using refresh token # noqa: E501 :rtype: UserAuth """ current_user = get_jwt_identity() if not current_user: return ErrorResponse(status=401, message="Not logged in") access_token...
Refreshes login token using refresh token Refreshes login token using refresh token # noqa: E501 :rtype: UserAuth
def vMh2_to_m2Lambda(v, Mh2, C, scale_high): """Function to numerically determine the parameters of the Higgs potential given the physical Higgs VEV and mass.""" if C['phi'] == 0 and C['phiBox'] == 0 and C['phiD'] == 0: return _vMh2_to_m2Lambda_SM(v, Mh2) else: def f0(x): # we want the ...
Function to numerically determine the parameters of the Higgs potential given the physical Higgs VEV and mass.
def image_list(name=None, profile=None, **kwargs): ''' Return a list of available images (nova images-list + nova image-show) If a name is provided, only that image will be displayed. CLI Examples: .. code-block:: bash salt '*' nova.image_list salt '*' nova.image_list myimage ...
Return a list of available images (nova images-list + nova image-show) If a name is provided, only that image will be displayed. CLI Examples: .. code-block:: bash salt '*' nova.image_list salt '*' nova.image_list myimage
def check_datetime(method, dictionary, fields, label=None): """Checks if the specified fields are formatted correctly if they have a value. Throws an exception on incorrectly formatted fields. :param dict dictionary: Dictionary to check. :param typle fields: Fields to check. :param string label: Di...
Checks if the specified fields are formatted correctly if they have a value. Throws an exception on incorrectly formatted fields. :param dict dictionary: Dictionary to check. :param typle fields: Fields to check. :param string label: Dictionary name.
def do_fuzzy(self, word): """Compute fuzzy extensions of word. FUZZY lilas""" word = list(preprocess_query(word))[0] print(white(make_fuzzy(word)))
Compute fuzzy extensions of word. FUZZY lilas
def set_foreground(self, fg, isRGBA=None): """ Set the foreground color. fg can be a matlab format string, a html hex color string, an rgb unit tuple, or a float between 0 and 1. In the latter case, grayscale is used. """ # Implementation note: wxPython has a separate c...
Set the foreground color. fg can be a matlab format string, a html hex color string, an rgb unit tuple, or a float between 0 and 1. In the latter case, grayscale is used.
def expire(self, time=None): """Remove expired items from the cache.""" if time is None: time = self.__timer() root = self.__root curr = root.next links = self.__links cache_delitem = Cache.__delitem__ while curr is not root and curr.expire < time: ...
Remove expired items from the cache.
def weight_field(self, f): """ Select one field as the weight field. Note that this field will be exclude from feature fields. :param f: Selected weight field :type f: str :rtype: DataFrame """ if f is None: raise ValueError("Field name canno...
Select one field as the weight field. Note that this field will be exclude from feature fields. :param f: Selected weight field :type f: str :rtype: DataFrame
def validate_full_path(cls, full_path, **kwargs): """Helper method to return a full path from a full or partial path. If no domain, assumes user's account domain If the vault is "~", assumes personal vault. Valid vault paths include: domain:vault domain...
Helper method to return a full path from a full or partial path. If no domain, assumes user's account domain If the vault is "~", assumes personal vault. Valid vault paths include: domain:vault domain:vault:/path domain:vault/path vault:...
def ensure_dir(path): """Create all parent directories of path if they don't exist. Args: path. Path-like object. Create parent dirs to this path. Return: None. """ os.makedirs(os.path.abspath(os.path.dirname(path)), exist_ok=True)
Create all parent directories of path if they don't exist. Args: path. Path-like object. Create parent dirs to this path. Return: None.
def termination_check(self): # type: (Downloader) -> bool """Check if terminated :param Downloader self: this :rtype: bool :return: if terminated """ with self._transfer_lock: with self._disk_operation_lock: return (self._download_termi...
Check if terminated :param Downloader self: this :rtype: bool :return: if terminated
def Archimedes(L, rhof, rhop, mu, g=g): r'''Calculates Archimedes number, `Ar`, for a fluid and particle with the given densities, characteristic length, viscosity, and gravity (usually diameter of particle). .. math:: Ar = \frac{L^3 \rho_f(\rho_p-\rho_f)g}{\mu^2} Parameters ----------...
r'''Calculates Archimedes number, `Ar`, for a fluid and particle with the given densities, characteristic length, viscosity, and gravity (usually diameter of particle). .. math:: Ar = \frac{L^3 \rho_f(\rho_p-\rho_f)g}{\mu^2} Parameters ---------- L : float Characteristic length...
def chassis(name, chassis_name=None, password=None, datacenter=None, location=None, mode=None, idrac_launch=None, slot_names=None, blade_power_states=None): ''' Manage a Dell Chassis. chassis_name The name of the chassis. datacenter The datacenter in which the c...
Manage a Dell Chassis. chassis_name The name of the chassis. datacenter The datacenter in which the chassis is located location The location of the chassis. password Password for the chassis. Note: If this password is set for the chassis, the current implement...
def make_symmetric_matrix_from_upper_tri(val): """ Given a symmetric matrix in upper triangular matrix form as flat array indexes as: [A_xx,A_yy,A_zz,A_xy,A_xz,A_yz] This will generate the full matrix: [[A_xx,A_xy,A_xz],[A_xy,A_yy,A_yz],[A_xz,A_yz,A_zz] """ idx = [0,3,4,1,5,2] val = np.a...
Given a symmetric matrix in upper triangular matrix form as flat array indexes as: [A_xx,A_yy,A_zz,A_xy,A_xz,A_yz] This will generate the full matrix: [[A_xx,A_xy,A_xz],[A_xy,A_yy,A_yz],[A_xz,A_yz,A_zz]
def create_section( aggregation_summary, analysis_layer, postprocessor_fields, section_header, use_aggregation=True, units_label=None, use_rounding=True, extra_component_args=None): """Create demographic section context. :param aggregation_summary: Aggregation su...
Create demographic section context. :param aggregation_summary: Aggregation summary :type aggregation_summary: qgis.core.QgsVectorlayer :param analysis_layer: Analysis layer :type analysis_layer: qgis.core.QgsVectorLayer :param postprocessor_fields: Postprocessor fields to extract :type postp...
def searchResponse(self, queryType, query, vendorSpecific=None, **kwargs): """CNRead.search(session, queryType, query) → ObjectList https://releases.dataone.org/online/api- documentation-v2.0.1/apis/CN_APIs.html#CNRead.search. Args: queryType: query: vendor...
CNRead.search(session, queryType, query) → ObjectList https://releases.dataone.org/online/api- documentation-v2.0.1/apis/CN_APIs.html#CNRead.search. Args: queryType: query: vendorSpecific: **kwargs: Returns:
def available_services(): """ get the available services to be activated read the models dir to find the services installed to be added to the system by the administrator """ all_datas = () data = () for class_path in settings.TH_SERVICES: class_name = class_path.rs...
get the available services to be activated read the models dir to find the services installed to be added to the system by the administrator
def get(self, names_to_get, extract_numpy_scalars=True, on_new_output=None): """ Loads the requested variables from the matlab shell. names_to_get can be either a variable name, a list of variable names, or None. If it is a var...
Loads the requested variables from the matlab shell. names_to_get can be either a variable name, a list of variable names, or None. If it is a variable name, the values is returned. If it is a list, a dictionary of variable_name -> value is returned. If it is None, a dictionary ...
def __output_thread(self): "Output thread" while self.alive: instructions = self.__get_instructions() self.__process_instructions(instructions)
Output thread
def create_user(self, name, password, is_super=False): """ Create a new MapD user Parameters ---------- name : string User name password : string Password is_super : bool if user is a superuser """ statement = ddl.Cre...
Create a new MapD user Parameters ---------- name : string User name password : string Password is_super : bool if user is a superuser
def policy_net(rng_key, batch_observations_shape, num_actions, bottom_layers=None): """A policy net function.""" # Use the bottom_layers as the bottom part of the network and just add the # required layers on top of it. if bottom_layers is None: bottom_layers = [...
A policy net function.
def _all_unique_texts(text, final): """ Compute all the possible unique texts @type text: str @param text: Text written used spin syntax @type final: list @param final: An empty list where all the unique texts will be stored @return: Nothing. The result will be in the 'final' list """ ...
Compute all the possible unique texts @type text: str @param text: Text written used spin syntax @type final: list @param final: An empty list where all the unique texts will be stored @return: Nothing. The result will be in the 'final' list
def Marginal(self, i, name=''): """Gets the marginal distribution of the indicated variable. i: index of the variable we want Returns: Pmf """ pmf = Pmf(name=name) for vs, prob in self.Items(): pmf.Incr(vs[i], prob) return pmf
Gets the marginal distribution of the indicated variable. i: index of the variable we want Returns: Pmf
def _get_user_ns_object(shell, path): """Get object from the user namespace, given a path containing zero or more dots. Return None if the path is not valid. """ parts = path.split('.', 1) name, attr = parts[0], parts[1:] if name in shell.user_ns: if attr: try: ...
Get object from the user namespace, given a path containing zero or more dots. Return None if the path is not valid.
def get_types_by_attr(resource, template_id=None): """ Using the attributes of the resource, get all the types that this resource matches. @returns a dictionary, keyed on the template name, with the value being the list of type names which match the resources attributes. ...
Using the attributes of the resource, get all the types that this resource matches. @returns a dictionary, keyed on the template name, with the value being the list of type names which match the resources attributes.
def acquireConnection(self): """ Get a connection from the pool. Parameters: ---------------------------------------------------------------- retval: A ConnectionWrapper instance. NOTE: Caller is responsible for calling the ConnectionWrapper instance's rel...
Get a connection from the pool. Parameters: ---------------------------------------------------------------- retval: A ConnectionWrapper instance. NOTE: Caller is responsible for calling the ConnectionWrapper instance's release() method or use it in a context ...
def process(self): """! @brief Performs cluster analysis in line with rules of K-Medians algorithm. @return (kmedians) Returns itself (K-Medians instance). @remark Results of clustering can be obtained using corresponding get methods. @see get_clusters() ...
! @brief Performs cluster analysis in line with rules of K-Medians algorithm. @return (kmedians) Returns itself (K-Medians instance). @remark Results of clustering can be obtained using corresponding get methods. @see get_clusters() @see get_medians()
def mt_report(context, case_id, test, outpath=None): """Export all mitochondrial variants for each sample of a case and write them to an excel file Args: adapter(MongoAdapter) case_id(str) test(bool): True if the function is called for testing purposes ...
Export all mitochondrial variants for each sample of a case and write them to an excel file Args: adapter(MongoAdapter) case_id(str) test(bool): True if the function is called for testing purposes outpath(str): path to output file Returns: ...
def _fetch_result(self): """ Fetch the queried object. """ self._result = self.conn.query_single(self.object_type, self.url_params, self.query_params)
Fetch the queried object.
def parse(cls, msg): """Parse message string to request object.""" lines = msg.splitlines() method, uri, version = lines[0].split() headers = cls.parse_headers('\r\n'.join(lines[1:])) return cls(version=version, uri=uri, method=method, headers=headers)
Parse message string to request object.
def make_generic_validator(validator: AnyCallable) -> 'ValidatorCallable': """ Make a generic function which calls a validator with the right arguments. Unfortunately other approaches (eg. return a partial of a function that builds the arguments) is slow, hence this laborious way of doing things. ...
Make a generic function which calls a validator with the right arguments. Unfortunately other approaches (eg. return a partial of a function that builds the arguments) is slow, hence this laborious way of doing things. It's done like this so validators don't all need **kwargs in their signature, eg. any c...
def compliance_schedule(self, column=None, value=None, **kwargs): """ A sequence of activities with associated milestones which pertains to a given permit. >>> PCS().compliance_schedule('cmpl_schd_evt', '62099') """ return self._resolve_call('PCS_CMPL_SCHD', column, valu...
A sequence of activities with associated milestones which pertains to a given permit. >>> PCS().compliance_schedule('cmpl_schd_evt', '62099')
def receive_message(self, message, data): """ Called when a receiver-message has been received. """ if data[MESSAGE_TYPE] == TYPE_RECEIVER_STATUS: self._process_get_status(data) return True elif data[MESSAGE_TYPE] == TYPE_LAUNCH_ERROR: self._process_launch_e...
Called when a receiver-message has been received.
def lookup_providers(self, lookup): ''' Get a dict describing the configured providers ''' if lookup is None: lookup = 'all' if lookup == 'all': providers = set() for alias, drivers in six.iteritems(self.opts['providers']): for ...
Get a dict describing the configured providers
def _deserialize(self, value, attr, data): """Format and validate the phone number using libphonenumber.""" if value: value = self._format_phone_number(value, attr) return super(PhoneNumberField, self)._deserialize(value, attr, data)
Format and validate the phone number using libphonenumber.
def titleCounts(readsAlignments): """ Count the number of times each title in a readsAlignments instance is matched. This is useful for rapidly discovering what titles were matched and with what frequency. @param readsAlignments: A L{dark.alignments.ReadsAlignments} instance. @return: A C{dict}...
Count the number of times each title in a readsAlignments instance is matched. This is useful for rapidly discovering what titles were matched and with what frequency. @param readsAlignments: A L{dark.alignments.ReadsAlignments} instance. @return: A C{dict} whose keys are titles and whose values are th...
def _export_table(dataset, column_names=None, byteorder="=", shuffle=False, selection=False, progress=None, virtual=True, sort=None, ascending=True): """ :param DatasetLocal dataset: dataset to export :param str path: path for file :param lis[str] column_names: list of column names to export or None for...
:param DatasetLocal dataset: dataset to export :param str path: path for file :param lis[str] column_names: list of column names to export or None for all columns :param str byteorder: = for native, < for little endian and > for big endian :param bool shuffle: export rows in random order :param bool...
def regex(self, *pattern, **kwargs): """ Add re pattern :param pattern: :type pattern: :param kwargs: :type kwargs: :return: :rtype: """ set_defaults(self._kwargs, kwargs) set_defaults(self._regex_defaults, kwargs) set_defa...
Add re pattern :param pattern: :type pattern: :param kwargs: :type kwargs: :return: :rtype:
def record_big_endian(self): # type: () -> bytes ''' A method to generate a string representing the big endian version of this Path Table Record. Parameters: None. Returns: A string representing the big endian version of this Path Table Record. ...
A method to generate a string representing the big endian version of this Path Table Record. Parameters: None. Returns: A string representing the big endian version of this Path Table Record.
def find_route_functions_taint_args(self): """Find all route functions and taint all of their arguments. Yields: CFG of each route function, with args marked as tainted. """ for definition in _get_func_nodes(): if self.is_route_function(definition.node): ...
Find all route functions and taint all of their arguments. Yields: CFG of each route function, with args marked as tainted.
def to_text(self, line): """ Return the textual representation of the given `line`. """ return getattr(self, self.ENTRY_TRANSFORMERS[line.__class__])(line)
Return the textual representation of the given `line`.
def build_dataset(instruction_dicts, dataset_from_file_fn, shuffle_files=False, parallel_reads=64): """Constructs a `tf.data.Dataset` from TFRecord files. Args: instruction_dicts: `list` of {'filepath':, 'mask':, 'offset_mask':} containing the informa...
Constructs a `tf.data.Dataset` from TFRecord files. Args: instruction_dicts: `list` of {'filepath':, 'mask':, 'offset_mask':} containing the information about which files and which examples to use. The boolean mask will be repeated and zipped with the examples from filepath. dataset_from_fi...
def update(self, *args, **kwargs): ''' Updates the set to include all arguments passed in. If the keyword argument preprocess is passed, then each element is preprocessed before being added. ''' preprocess = kwargs.get('preprocess') for s in args: ...
Updates the set to include all arguments passed in. If the keyword argument preprocess is passed, then each element is preprocessed before being added.
def p0(self): """A dictionary of the initial position of the walkers. This is set by using ``set_p0``. If not set yet, a ``ValueError`` is raised when the attribute is accessed. """ if self._p0 is None: raise ValueError("initial positions not set; run set_p0") ...
A dictionary of the initial position of the walkers. This is set by using ``set_p0``. If not set yet, a ``ValueError`` is raised when the attribute is accessed.
def phrase_contains_special_keys(expansion: model.Expansion) -> bool: """ Determine if the expansion contains any special keys, including those resulting from any processed macros (<script>, <file>, etc). If any are found, the phrase cannot be undone. Python Zen: »In the face of ambigui...
Determine if the expansion contains any special keys, including those resulting from any processed macros (<script>, <file>, etc). If any are found, the phrase cannot be undone. Python Zen: »In the face of ambiguity, refuse the temptation to guess.« The question 'What does the phrase expansion ...
def html_to_cnxml(html_source, cnxml_source): """Transform the HTML to CNXML. We need the original CNXML content in order to preserve the metadata in the CNXML document. """ source = _string2io(html_source) xml = etree.parse(source) cnxml = etree.parse(_string2io(cnxml_source)) # Run the HTM...
Transform the HTML to CNXML. We need the original CNXML content in order to preserve the metadata in the CNXML document.
def canonical_value(self, query): """ Return the canonical value corresponding to the given query value. Return ``None`` if the query value is not present in any descriptor of the group. :param str query: the descriptor value to be checked against """ for d in self.desc...
Return the canonical value corresponding to the given query value. Return ``None`` if the query value is not present in any descriptor of the group. :param str query: the descriptor value to be checked against
def load_model(model_name, epoch_num, data_shapes, label_shapes, label_names, gpus=''): """Returns a module loaded with the provided model. Parameters ---------- model_name: str Prefix of the MXNet model name as stored on the local directory. epoch_num : int Epoch number of model w...
Returns a module loaded with the provided model. Parameters ---------- model_name: str Prefix of the MXNet model name as stored on the local directory. epoch_num : int Epoch number of model we would like to load. input_shape: tuple The shape of the input data in the form o...
def derive_key(self, master_password): """ Computes the key from the salt and the master password. """ encoder = encoding.Encoder(self.charset) bytes = ('%s:%s' % (master_password, self.name)).encode('utf8') start_time = time.clock() # we fix the scrypt parameters in case the d...
Computes the key from the salt and the master password.
def insert(self, before, name, attrs=None, data=None): """ Inserts a new element as a child of this element, before the specified index or sibling. :param before: An :class:`XmlElement` or a numeric index to insert the new node before :param name: The tag name to add :param attr...
Inserts a new element as a child of this element, before the specified index or sibling. :param before: An :class:`XmlElement` or a numeric index to insert the new node before :param name: The tag name to add :param attrs: Attributes for the new tag :param data: CDATA for the new tag ...
def _language_index_from_code(self, code, name_mode): """Return the index value for a language code. This returns l_any if more than one code is specified or the code is out of bounds. Parameters ---------- code : int The language code to interpret n...
Return the index value for a language code. This returns l_any if more than one code is specified or the code is out of bounds. Parameters ---------- code : int The language code to interpret name_mode : str The name mode of the algorithm: ``gen`...
def send_config_set( self, config_commands=None, exit_config_mode=True, delay_factor=1, max_loops=150, strip_prompt=False, strip_command=False, config_mode_command=None, ): """ Send configuration commands down the SSH channel. ...
Send configuration commands down the SSH channel. config_commands is an iterable containing all of the configuration commands. The commands will be executed one after the other. Automatically exits/enters configuration mode. :param config_commands: Multiple configuration commands to b...
def _translate_cond(self, c): #pylint:disable=no-self-use """ Checks whether this condition can be supported by FastMemory." """ if isinstance(c, claripy.ast.Base) and not c.singlevalued: raise SimFastMemoryError("size not supported") if c is None: return ...
Checks whether this condition can be supported by FastMemory."
def register_event(self, event): """Registers a new command line interface event hook as command""" self.log('Registering event hook:', event.cmd, event.thing, pretty=True, lvl=verbose) self.hooks[event.cmd] = event.thing
Registers a new command line interface event hook as command
def find_one(cls, *args, **kwargs): """Same as ``collection.find_one``, returns model object instead of dict.""" d = cls.collection.find_one(*args, **kwargs) if d: return cls(**d)
Same as ``collection.find_one``, returns model object instead of dict.
def _normalize_helper(number, replacements, remove_non_matches): """Normalizes a string of characters representing a phone number by replacing all characters found in the accompanying map with the values therein, and stripping all other characters if remove_non_matches is true. Arguments: number --...
Normalizes a string of characters representing a phone number by replacing all characters found in the accompanying map with the values therein, and stripping all other characters if remove_non_matches is true. Arguments: number -- a string representing a phone number replacements -- a mapping of c...
def univariate(self, data: ['SASdata', str] = None, by: [str, list] = None, cdfplot: str = None, cls: [str, list] = None, freq: str = None, histogram: str = None, id: [str, list] = None, ...
Python method to call the UNIVARIATE procedure Documentation link: https://go.documentation.sas.com/?cdcId=pgmsascdc&cdcVersion=9.4_3.4&docsetId=procstat&docsetTarget=procstat_univariate_syntax.htm&locale=en The PROC UNIVARIATE statement invokes the procedure. The VAR statement specifies the n...
def qos(self, prefetch_size=0, prefetch_count=0, is_global=False): ''' Set QoS on this channel. ''' args = Writer() args.write_long(prefetch_size).\ write_short(prefetch_count).\ write_bit(is_global) self.send_frame(MethodFrame(self.channel_id, 60,...
Set QoS on this channel.
def SNM0(T, Tc, Vc, omega, delta_SRK=None): r'''Calculates saturated liquid density using the Mchaweh, Moshfeghian model [1]_. Designed for simple calculations. .. math:: V_s = V_c/(1+1.169\tau^{1/3}+1.818\tau^{2/3}-2.658\tau+2.161\tau^{4/3} \tau = 1-\frac{(T/T_c)}{\alpha_{SRK}} \...
r'''Calculates saturated liquid density using the Mchaweh, Moshfeghian model [1]_. Designed for simple calculations. .. math:: V_s = V_c/(1+1.169\tau^{1/3}+1.818\tau^{2/3}-2.658\tau+2.161\tau^{4/3} \tau = 1-\frac{(T/T_c)}{\alpha_{SRK}} \alpha_{SRK} = [1 + m(1-\sqrt{T/T_C}]^2 ...
def get_folder(self, folder): """ Return the details for a folder :calls: `GET /api/v1/folders/:id \ <https://canvas.instructure.com/doc/api/files.html#method.folders.show>`_ :param folder: The object or ID of the folder to retrieve. :type folder: :class:`canvasapi.fold...
Return the details for a folder :calls: `GET /api/v1/folders/:id \ <https://canvas.instructure.com/doc/api/files.html#method.folders.show>`_ :param folder: The object or ID of the folder to retrieve. :type folder: :class:`canvasapi.folder.Folder` or int :rtype: :class:`canvasa...
async def api_request(self, url, params): """Make api fetch request.""" request = None try: with async_timeout.timeout(DEFAULT_TIMEOUT, loop=self._event_loop): request = await self._api_session.get( url, params=params) if request.status...
Make api fetch request.
def _get_column_ends(self): '''Guess where the ends of the columns lie. ''' ends = collections.Counter() for line in self.text.splitlines(): for matchobj in re.finditer('\s{2,}', line.lstrip()): ends[matchobj.end()] += 1 return ends
Guess where the ends of the columns lie.
def patch_namespaced_network_policy(self, name, namespace, body, **kwargs): """ partially update the specified NetworkPolicy This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced...
partially update the specified NetworkPolicy This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_network_policy(name, namespace, body, async_req=True) >>> result = thread.get() ...
def delete_os_dummy_rtr_nwk(self, rtr_id, net_id, subnet_id): """Delete the dummy interface to the router. """ subnet_lst = set() subnet_lst.add(subnet_id) ret = self.os_helper.delete_intf_router(None, None, rtr_id, subnet_lst) if not ret: return ret return s...
Delete the dummy interface to the router.
def _geom_series_uint32(r, n): """Unsigned integer calculation of sum of geometric series: 1 + r + r^2 + r^3 + ... r^(n-1) summed to n terms. Calculated modulo 2**32. Use the formula (r**n - 1) / (r - 1) """ if n == 0: return 0 if n == 1 or r == 0: return 1 m = 2**32 ...
Unsigned integer calculation of sum of geometric series: 1 + r + r^2 + r^3 + ... r^(n-1) summed to n terms. Calculated modulo 2**32. Use the formula (r**n - 1) / (r - 1)
def timeout_thread_handler(timeout, stop_event): """A background thread to kill the process if it takes too long. Args: timeout (float): The number of seconds to wait before killing the process. stop_event (Event): An optional event to cleanly stop the background thread ...
A background thread to kill the process if it takes too long. Args: timeout (float): The number of seconds to wait before killing the process. stop_event (Event): An optional event to cleanly stop the background thread if required during testing.
def _check_status(status): """Take a cairo status code and raise an exception if/as appropriate.""" if status != constants.STATUS_SUCCESS: exception = STATUS_TO_EXCEPTION.get(status, CairoError) status_name = ffi.string(ffi.cast("cairo_status_t", status)) message = 'cairo returned %s: %s...
Take a cairo status code and raise an exception if/as appropriate.
async def _chunked_upload(self, media, media_size, path=None, media_type=None, media_category=None, chunk_size=2**20, **params): """ upload media in c...
upload media in chunks Parameters ---------- media : file object a file object of the media media_size : int size of the media path : str, optional filename of the media media_type : str, optional mime type of the media ...
def get_wifi_packet(frame, no_rtap=False): """Discriminates Wi-Fi packet and creates packet object. :frame: ctypes.Structure :no_rtap: Bool :return: obj Wi-Fi packet """ _, packet = WiHelper._strip_rtap(frame) frame_control = struct.unpack('BB'...
Discriminates Wi-Fi packet and creates packet object. :frame: ctypes.Structure :no_rtap: Bool :return: obj Wi-Fi packet
def get_search_page(self, query): """Gets HTML source :param query: query to search engine :return: HTML source of search page of given query """ query_web_page = Webpage(self.url + self.parse_query(query)) query_web_page.get_html_source() # get html source retu...
Gets HTML source :param query: query to search engine :return: HTML source of search page of given query
def find_same_between_dicts(dict1, dict2): """ 查找两个字典中的相同点,包括键、值、项,仅支持 hashable 对象 :param: * dict1: (dict) 比较的字典 1 * dict2: (dict) 比较的字典 2 :return: * dup_info: (namedtuple) 返回两个字典中相同的信息组成的具名元组 举例如下:: print('--- find_same_between_dicts demo---') dict1 = {'x...
查找两个字典中的相同点,包括键、值、项,仅支持 hashable 对象 :param: * dict1: (dict) 比较的字典 1 * dict2: (dict) 比较的字典 2 :return: * dup_info: (namedtuple) 返回两个字典中相同的信息组成的具名元组 举例如下:: print('--- find_same_between_dicts demo---') dict1 = {'x':1, 'y':2, 'z':3} dict2 = {'w':10, 'x':1, 'y':...
def create_new(self, **kwargs): """ Creates a new License This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(respo...
Creates a new License This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> ...
def _parse_url_and_validate(cls, url): """ Recieves a URL string and validates it using urlparse. Args: url: A URL string Returns: parsed_url: A validated URL Raises: BadURLException """ parsed_url = urlparse(url) if pa...
Recieves a URL string and validates it using urlparse. Args: url: A URL string Returns: parsed_url: A validated URL Raises: BadURLException
def release(self, forceRelease=False): ''' release - Release the lock. @param forceRelease <bool> default False - If True, will release the lock even if we don't hold it. @return - True if lock is released, otherwise False ''' if not self.held: i...
release - Release the lock. @param forceRelease <bool> default False - If True, will release the lock even if we don't hold it. @return - True if lock is released, otherwise False
def arr_base10toN(anum10, aradix, *args): """ ARGS anum10 in number in base 10 aradix in convert <anum10> to number in base + <aradix> OPTIONAL forcelength in if nonzero, indicates the length ...
ARGS anum10 in number in base 10 aradix in convert <anum10> to number in base + <aradix> OPTIONAL forcelength in if nonzero, indicates the length + of the return array. Useful ...
def bulk_copy(self, ids): """Bulk copy a set of packages. :param ids: Int list of package IDs. :return: :class:`packages.Package <packages.Package>` list """ schema = PackageSchema() return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema)
Bulk copy a set of packages. :param ids: Int list of package IDs. :return: :class:`packages.Package <packages.Package>` list
def setup(self): """Setup.""" self.blocks = self.config['block_comments'] self.lines = self.config['line_comments'] self.group_comments = self.config['group_comments'] self.jsdocs = self.config['jsdocs'] self.decode_escapes = self.config['decode_escapes'] self.st...
Setup.
def size_to_content(self, horizontal_padding=None, vertical_padding=None): """ Size the canvas item to the text content. """ if horizontal_padding is None: horizontal_padding = 0 if vertical_padding is None: vertical_padding = 0 self.sizing.set_fixed_size(Geome...
Size the canvas item to the text content.
def bulkdownload(database, **kwargs): """Downloads an entire database. :param str database: The database code to download :param str filename: The filename for the download. \ If not specified, will download to the current working directory :param str api_key: Most databases require api_key for bulk...
Downloads an entire database. :param str database: The database code to download :param str filename: The filename for the download. \ If not specified, will download to the current working directory :param str api_key: Most databases require api_key for bulk download :param str download_type: 'part...
def sorted_exists(values, x): """ For list, values, returns the insert position for item x and whether the item already exists in the list. This allows one function call to return either the index to overwrite an existing value in the list, or the index to insert a new item in the list and keep the list...
For list, values, returns the insert position for item x and whether the item already exists in the list. This allows one function call to return either the index to overwrite an existing value in the list, or the index to insert a new item in the list and keep the list in sorted order. :param values: list...
def css(self): """Returns ------- str The CSS. """ css_list = [DEFAULT_MARK_CSS] for aes in self.aesthetics: css_list.extend(get_mark_css(aes, self.values[aes])) #print('\n'.join(css_list)) return '\n'.join(css_list)
Returns ------- str The CSS.
def coroutine( func: Callable[..., "Generator[Any, Any, _T]"] ) -> Callable[..., "Future[_T]"]: """Decorator for asynchronous generators. For compatibility with older versions of Python, coroutines may also "return" by raising the special exception `Return(value) <Return>`. Functions with this...
Decorator for asynchronous generators. For compatibility with older versions of Python, coroutines may also "return" by raising the special exception `Return(value) <Return>`. Functions with this decorator return a `.Future`. .. warning:: When exceptions occur inside a coroutine, the exce...
def stop(self): """Stop this gateway agent.""" if self._disconnector: self._disconnector.stop() self.client.disconnect()
Stop this gateway agent.
def extract_metric_name(self, metric_name): """ Method to extract SAR metric names from the section given in the config. The SARMetric class assumes that the section name will contain the SAR types listed in self.supported_sar_types tuple :param str metric_name: Section name from the config :return...
Method to extract SAR metric names from the section given in the config. The SARMetric class assumes that the section name will contain the SAR types listed in self.supported_sar_types tuple :param str metric_name: Section name from the config :return: str which identifies what kind of SAR metric the secti...
def dir(cls, label, children): """Return ``FSEntry`` directory object.""" return FSEntry(label=label, children=children, type=u"Directory", use=None)
Return ``FSEntry`` directory object.
def json(cls, message): """ Print a nice JSON output Args: message: the message to print """ if type(message) is OrderedDict: pprint(dict(message)) else: pprint(message)
Print a nice JSON output Args: message: the message to print
def change(script, layer_num=None): """ Change the current layer by specifying the new layer number. Args: script: the mlx.FilterScript object or script filename to write the filter to. layer_num (int): the number of the layer to change to. Default is the last layer if s...
Change the current layer by specifying the new layer number. Args: script: the mlx.FilterScript object or script filename to write the filter to. layer_num (int): the number of the layer to change to. Default is the last layer if script is a mlx.FilterScript object; if scrip...
def factory(cls, registry): """Returns a dynamic MetricsHandler class tied to the passed registry. """ # This implementation relies on MetricsHandler.registry # (defined above and defaulted to REGISTRY). # As we have unicode_literals, we need to create a str() ...
Returns a dynamic MetricsHandler class tied to the passed registry.
def put(self, item, *args, **kwargs): """Put an item into the cache, for this combination of args and kwargs. Args: *args: any arguments. **kwargs: any keyword arguments. If ``timeout`` is specified as one of the keyword arguments, the item will remain available...
Put an item into the cache, for this combination of args and kwargs. Args: *args: any arguments. **kwargs: any keyword arguments. If ``timeout`` is specified as one of the keyword arguments, the item will remain available for retrieval for ``timeout`` s...
def load_app(config, **kwargs): ''' Used to load a ``Pecan`` application and its environment based on passed configuration. :param config: Can be a dictionary containing configuration, a string which represents a (relative) configuration filename returns a pecan.Pecan object ...
Used to load a ``Pecan`` application and its environment based on passed configuration. :param config: Can be a dictionary containing configuration, a string which represents a (relative) configuration filename returns a pecan.Pecan object
def insertVariantSet(self, variantSet): """ Inserts a the specified variantSet into this repository. """ # We cheat a little here with the VariantSetMetadata, and encode these # within the table as a JSON dump. These should really be stored in # their own table me...
Inserts a the specified variantSet into this repository.