code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _parseSpec(values): """ Split the argument string. Example: --arg name:value0,value1,key2=value2,key3=value3 gets split into name, args, kwargs = ( "name", (value0, value1), {"key2":value2, "key3":value3}, ) """ split = values.split(":", 1) name = split[0].strip() rest = split[1]...
Split the argument string. Example: --arg name:value0,value1,key2=value2,key3=value3 gets split into name, args, kwargs = ( "name", (value0, value1), {"key2":value2, "key3":value3}, )
def _build_compatibility_members(binding, decorators=None): """Apply `binding` to QtCompat Arguments: binding (str): Top level binding in _compatibility_members. decorators (dict, optional): Provides the ability to decorate the original Qt methods when needed by a binding. This can ...
Apply `binding` to QtCompat Arguments: binding (str): Top level binding in _compatibility_members. decorators (dict, optional): Provides the ability to decorate the original Qt methods when needed by a binding. This can be used to change the returned value to a standard valu...
def load_stencil_set(self, stencilset_name): """Return the Stencil Set from this template pack.""" if stencilset_name not in self._stencil_sets: if stencilset_name not in self.manifest['stencil_sets'].keys(): raise exc.FastfoodStencilSetNotListed( "Stencil...
Return the Stencil Set from this template pack.
def eflux(self, emin, emax, params=None): """Evaluate the integral energy flux.""" params = self.params if params is None else params return np.squeeze(self.eval_eflux(emin, emax, params, self.scale, self.extra_params))
Evaluate the integral energy flux.
def correlation(self, n, k, error=False): r""" Calculate `\langle k \rangle_n`, the `k`-particle correlation function for `n`\ th-order anisotropy. :param int n: Anisotropy order. :param int k: Correlation order. :param bool error: Whether to calculate stati...
r""" Calculate `\langle k \rangle_n`, the `k`-particle correlation function for `n`\ th-order anisotropy. :param int n: Anisotropy order. :param int k: Correlation order. :param bool error: Whether to calculate statistical error (for `\langle 2 \rangle` ...
def register(self, new_calc, *args, **kwargs): """ Register calculations and meta data. * ``dependencies`` - list of prerequisite calculations * ``always_calc`` - ``True`` if calculation ignores thresholds * ``frequency`` - frequency of calculation in intervals or units of time ...
Register calculations and meta data. * ``dependencies`` - list of prerequisite calculations * ``always_calc`` - ``True`` if calculation ignores thresholds * ``frequency`` - frequency of calculation in intervals or units of time :param new_calc: register new calculation
def create(self): """ create a SNAP7 client. """ logger.info("creating snap7 client") self.library.Cli_Create.restype = c_void_p self.pointer = S7Object(self.library.Cli_Create())
create a SNAP7 client.
def define_association(self, rel_id, source_kind, source_keys, source_many, source_conditional, source_phrase, target_kind, target_keys, target_many, target_conditional, target_phrase): ''' Define and return an associatio...
Define and return an association from one kind of class (the source kind) to some other kind of class (the target kind).
def b1_theory(N, mu): """ Expected B1 ratio for given time-series length N and exponent mu FIXME: add reference (paper & link) The exponents are defined as S_y(f) = h_a f^alpha (power spectrum of y) S_x(f) = g_b f^b (power spectrum of x) bias = const *...
Expected B1 ratio for given time-series length N and exponent mu FIXME: add reference (paper & link) The exponents are defined as S_y(f) = h_a f^alpha (power spectrum of y) S_x(f) = g_b f^b (power spectrum of x) bias = const * tau^mu and (...
def add_link(dataset, source, target, count=1): """Add a link. Parameters ---------- dataset : `dict` of ([`int`, `str`] or [`list` of `int`, `list` of `str`]) Dataset. source : `iterable` of `str` Link source. target : `str` Link targ...
Add a link. Parameters ---------- dataset : `dict` of ([`int`, `str`] or [`list` of `int`, `list` of `str`]) Dataset. source : `iterable` of `str` Link source. target : `str` Link target. count : `int`, optional Link count ...
def get_anchor_contents(markup): """ Given HTML markup, return a list of href inner html for each anchor tag. """ soup = BeautifulSoup(markup, 'lxml') return ['%s' % link.contents[0] for link in soup.find_all('a')]
Given HTML markup, return a list of href inner html for each anchor tag.
def to_python(fname, converter): """ Convert a source model .hdf5 file into a :class:`SourceModel` object """ with hdf5.File(fname, 'r') as f: source_model = f['/'] for sg in source_model: for src in sg: if hasattr(src, 'mfd'): # multipoint source ...
Convert a source model .hdf5 file into a :class:`SourceModel` object
def _get_op_name(op, special): """ Find the name to attach to this method according to conventions for special and non-special methods. Parameters ---------- op : binary operator special : bool Returns ------- op_name : str """ opname = op.__name__.strip('_') if spe...
Find the name to attach to this method according to conventions for special and non-special methods. Parameters ---------- op : binary operator special : bool Returns ------- op_name : str
def sub(self, topics=(b'',)): """ Returns an iterable that can be used to iterate over incoming messages, that were published with one of the topics specified in ``topics``. Note that the iterable returns as many parts as sent by subscribed publishers. :param topics: a list of t...
Returns an iterable that can be used to iterate over incoming messages, that were published with one of the topics specified in ``topics``. Note that the iterable returns as many parts as sent by subscribed publishers. :param topics: a list of topics to subscribe to (default=b'') :type ...
def get_output_from_steps(stmt, last_step): ''' Extract output_from(1), output_from('step_1'), and output_from([1, 2]) to determine dependent steps ''' opt_values = get_param_of_function( 'output_from', stmt, extra_dict=env.sos_dict.dict()) def step_name(val): if isinstance(val,...
Extract output_from(1), output_from('step_1'), and output_from([1, 2]) to determine dependent steps
def generate (self, ps): """ Determines final build properties, generates sources, and calls 'construct'. This method should not be overridden. """ assert isinstance(ps, property_set.PropertySet) self.manager_.errors().push_user_context( "Generating target " +...
Determines final build properties, generates sources, and calls 'construct'. This method should not be overridden.
def download_metadata_tar(self,download_dir): """ Downloads the ${run_name}.metadata.tar file from the DNAnexus sequencing results project. Args: download_dir: `str` - The local directory path to download the QC report to. Returns: `str`: The filepath to t...
Downloads the ${run_name}.metadata.tar file from the DNAnexus sequencing results project. Args: download_dir: `str` - The local directory path to download the QC report to. Returns: `str`: The filepath to the downloaded metadata tarball.
def get_data_path(self, filename, env_prefix=None): """ Get data path. Args: filename (string) : Name of file inside of /data folder to retrieve. Kwargs: env_prefix (string) : Name of subfolder, ex: 'qa' will find files in /data/qa Returns: ...
Get data path. Args: filename (string) : Name of file inside of /data folder to retrieve. Kwargs: env_prefix (string) : Name of subfolder, ex: 'qa' will find files in /data/qa Returns: String - path to file. Usage:: open(WTF_DATA_MANAG...
def nominate(self, owner_id, player_idx, bid): """ Nominates the player for auctioning. :param int owner_id: index of the owner who is nominating :param int player_idx: index of the player to nominate in the players list :param int bid: starting bid :raise InvalidAction...
Nominates the player for auctioning. :param int owner_id: index of the owner who is nominating :param int player_idx: index of the player to nominate in the players list :param int bid: starting bid :raise InvalidActionError: if the action is not allowed according to the rules. See the...
def _add_op_node(self, op, qargs, cargs, condition=None): """Add a new operation node to the graph and assign properties. Args: op (Instruction): the operation associated with the DAG node qargs (list): list of quantum wires to attach to. cargs (list): list of classi...
Add a new operation node to the graph and assign properties. Args: op (Instruction): the operation associated with the DAG node qargs (list): list of quantum wires to attach to. cargs (list): list of classical wires to attach to. condition (tuple or None): option...
def update_identity_pool(IdentityPoolId, IdentityPoolName=None, AllowUnauthenticatedIdentities=False, SupportedLoginProviders=None, DeveloperProviderName=None, OpenIdConnectProviderARNs=None, ...
Updates the given IdentityPoolId's properties. All parameters except for IdentityPoolId, is optional. SupportedLoginProviders should be a dictionary mapping provider names to provider app IDs. OpenIdConnectProviderARNs should be a list of OpenID Connect provider ARNs. To clear SupportedLoginProvider...
def GET_subdomains( self, path_info ): """ Get all subdomains in existence. Requires page={int} Returns the list on success Returns 400 on invalid arguments Returns 502 on failure to get names """ qs_values = path_info['qs_values'] page = qs_values...
Get all subdomains in existence. Requires page={int} Returns the list on success Returns 400 on invalid arguments Returns 502 on failure to get names
def is_null(value): """ Check if the scalar value or tuple/list value is NULL. :param value: Value to check. :type value: a scalar or tuple or list :return: Returns ``True`` if and only if the value is NULL (scalar value is None or _any_ tuple/list elements are None). :rtype: bool ...
Check if the scalar value or tuple/list value is NULL. :param value: Value to check. :type value: a scalar or tuple or list :return: Returns ``True`` if and only if the value is NULL (scalar value is None or _any_ tuple/list elements are None). :rtype: bool
def current_time_is_in_interval(start, end): """ Determine whether the current time is on the interval [start, end]. """ interval_start = parse_lms_api_datetime(start or UNIX_MIN_DATE_STRING) interval_end = parse_lms_api_datetime(end or UNIX_MAX_DATE_STRING) return interval_start <= timezone.now...
Determine whether the current time is on the interval [start, end].
def __schema_descriptor(self, services): """Descriptor for the all the JSON Schema used. Args: services: List of protorpc.remote.Service instances implementing an api/version. Returns: Dictionary containing all the JSON Schema used in the service. """ methods_desc = {} for...
Descriptor for the all the JSON Schema used. Args: services: List of protorpc.remote.Service instances implementing an api/version. Returns: Dictionary containing all the JSON Schema used in the service.
def _base_placeholder(self): """ Return the layout placeholder this slide placeholder inherits from. Not to be confused with an instance of |BasePlaceholder| (necessarily). """ layout, idx = self.part.slide_layout, self._element.ph_idx return layout.placeholders.g...
Return the layout placeholder this slide placeholder inherits from. Not to be confused with an instance of |BasePlaceholder| (necessarily).
async def get_image( self, input_source: str, output_format: str = IMAGE_JPEG, extra_cmd: Optional[str] = None, timeout: int = 15, ) -> Optional[bytes]: """Open FFmpeg process as capture 1 frame.""" command = ["-an", "-frames:v", "1", "-c:v", output_format] ...
Open FFmpeg process as capture 1 frame.
def get_own_ip(): """ Gets the IP from the inet interfaces. """ own_ip = None interfaces = psutil.net_if_addrs() for _, details in interfaces.items(): for detail in details: if detail.family == socket.AF_INET: ip_address = ipaddress.ip_address(detail.addre...
Gets the IP from the inet interfaces.
def has_successor(self, graph, orig, dest, branch, turn, tick, *, forward=None): """Return whether an edge connects the origin to the destination at the given time. Doesn't require the edge's index, which makes it slower than retrieving a particular edge. """ if forward is None...
Return whether an edge connects the origin to the destination at the given time. Doesn't require the edge's index, which makes it slower than retrieving a particular edge.
def start(self, trunk_type): """Type of internal network trunk. in trunk_type of type str Type of internal network trunk. """ if not isinstance(trunk_type, basestring): raise TypeError("trunk_type can only be an instance of type basestring") self._call("...
Type of internal network trunk. in trunk_type of type str Type of internal network trunk.
def get_negative_cycle(self): ''' API: get_negative_cycle(self) Description: Finds and returns negative cost cycle using 'cost' attribute of arcs. Return value is a list of nodes representing cycle it is in the following form; n_1-n_2-...-n_k, when...
API: get_negative_cycle(self) Description: Finds and returns negative cost cycle using 'cost' attribute of arcs. Return value is a list of nodes representing cycle it is in the following form; n_1-n_2-...-n_k, when the cycle has k nodes. Pre: A...
def discard(self, msg, reason, logMethod=logging.error, cliOutput=False): """ Discard a message and log a reason using the specified `logMethod`. :param msg: the message to discard :param reason: the reason why this message is being discarded :param logMethod: the logging functi...
Discard a message and log a reason using the specified `logMethod`. :param msg: the message to discard :param reason: the reason why this message is being discarded :param logMethod: the logging function to be used :param cliOutput: if truthy, informs a CLI that the logged msg should ...
def _get_reference(self): """:return: Reference Object we point to :raise TypeError: If this symbolic reference is detached, hence it doesn't point to a reference, but to a commit""" sha, target_ref_path = self._get_ref_info(self.repo, self.path) if target_ref_path is None: ...
:return: Reference Object we point to :raise TypeError: If this symbolic reference is detached, hence it doesn't point to a reference, but to a commit
def _value_from_label(self, label): '''Convert a label into a kvl value. ''' unser_val = (label.rel_strength.value, label.meta) return cbor.dumps(unser_val)
Convert a label into a kvl value.
def _extract_local_histogram(image, mask=slice(None), bins=19, rang="image", cutoffp=(0.0, 100.0), size=None, footprint=None, output=None, mode="ignore", origin=0): """ Internal, single-image version of @see local_histogram Note: Values outside of the histograms range are not considered. Note: Mode...
Internal, single-image version of @see local_histogram Note: Values outside of the histograms range are not considered. Note: Mode constant is not available, instead a mode "ignore" is provided. Note: Default dtype of returned values is float.
def configure_logging(level=logging.DEBUG): '''Configures the root logger for command line applications. A stream handler will be added to the logger that directs messages to the standard error stream. By default, *no* messages will be filtered out: set a higher level on derived/child loggers to a...
Configures the root logger for command line applications. A stream handler will be added to the logger that directs messages to the standard error stream. By default, *no* messages will be filtered out: set a higher level on derived/child loggers to achieve filtering. Warning ------- Logg...
def _SerializeAttributeContainer(self, attribute_container): """Serializes an attribute container. Args: attribute_container (AttributeContainer): attribute container. Returns: bytes: serialized attribute container. Raises: IOError: if the attribute container cannot be serialized. ...
Serializes an attribute container. Args: attribute_container (AttributeContainer): attribute container. Returns: bytes: serialized attribute container. Raises: IOError: if the attribute container cannot be serialized. OSError: if the attribute container cannot be serialized.
def _exec_eval(data, expr): """ Internal function to isolate an exec. Executes ``data`` and returns the ``expr`` evaluation afterwards. """ ns = {} exec(data, ns) return eval(expr, ns)
Internal function to isolate an exec. Executes ``data`` and returns the ``expr`` evaluation afterwards.
def update_instance( self, update_mask, instance, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates the metadata and configuration of a specific Redis instance. Comple...
Updates the metadata and configuration of a specific Redis instance. Completed longrunning.Operation will contain the new instance object in the response field. The returned operation is automatically deleted after a few hours, so there is no need to call DeleteOperation. Example: ...
def ingest(self): """Import the ned_d catalogue into the catalogues database The method first generates a list of python dictionaries from the ned_d datafile, imports this list of dictionaries into a database table and then generates the HTMIDs for that table. **Usage:** See clas...
Import the ned_d catalogue into the catalogues database The method first generates a list of python dictionaries from the ned_d datafile, imports this list of dictionaries into a database table and then generates the HTMIDs for that table. **Usage:** See class docstring for usage ...
def add_password_arg(cmd, psw, ___required=False): """Append password switch to commandline. """ if UNRAR_TOOL == ALT_TOOL: return if psw is not None: cmd.append('-p' + psw) else: cmd.append('-p-')
Append password switch to commandline.
def convert_to_experiment_list(experiments): """Produces a list of Experiment objects. Converts input from dict, single experiment, or list of experiments to list of experiments. If input is None, will return an empty list. Arguments: experiments (Experiment | list | dict): Experiments to ...
Produces a list of Experiment objects. Converts input from dict, single experiment, or list of experiments to list of experiments. If input is None, will return an empty list. Arguments: experiments (Experiment | list | dict): Experiments to run. Returns: List of experiments.
def onPersonRemoved( self, mid=None, removed_id=None, author_id=None, thread_id=None, ts=None, msg=None, ): """ Called when the client is listening, and somebody removes a person from a group thread :param mid: The action ID :p...
Called when the client is listening, and somebody removes a person from a group thread :param mid: The action ID :param removed_id: The ID of the person who got removed :param author_id: The ID of the person who removed the person :param thread_id: Thread ID that the action was sent to....
def parse_init_dat(infile): """Parse the main init.dat file which contains the modeling results The first line of the file init.dat contains stuff like:: "120 easy 40 8" The other lines look like this:: " 161 11.051 1 1guqA MUSTER" and getting the first 1...
Parse the main init.dat file which contains the modeling results The first line of the file init.dat contains stuff like:: "120 easy 40 8" The other lines look like this:: " 161 11.051 1 1guqA MUSTER" and getting the first 10 gives you the top 10 templates us...
def keyval_typ2str(var, val): """Convert a variable to a string Parameters ---------- var: str The variable name val: any type The value of the variable Returns ------- varout: str Stripped lowercase `var` valout: any type The value converted to a us...
Convert a variable to a string Parameters ---------- var: str The variable name val: any type The value of the variable Returns ------- varout: str Stripped lowercase `var` valout: any type The value converted to a useful string representation See A...
def values(self, multi=False): # type: (bool) -> Iterator[Any] """ Yield the last value on every key list. :param multi: If set to `True` the iterator returned will have a pair for each value of each key. Otherwise it will only contain pairs ...
Yield the last value on every key list. :param multi: If set to `True` the iterator returned will have a pair for each value of each key. Otherwise it will only contain pairs for the lasted added of each key.
def command_loop(self, run_script_event): """ This is the debugger command loop that processes (protocol) client requests. """ while True: obj = remote_client.receive(self) command = obj["command"] # TODO: ensure we always have a command if receive r...
This is the debugger command loop that processes (protocol) client requests.
def on_session_destroyed(self, *callbacks): ''' Provide callbacks to invoke when the session serving the Document is destroyed ''' for callback in callbacks: _check_callback(callback, ('session_context',)) self._session_destroyed_callbacks.add(callback)
Provide callbacks to invoke when the session serving the Document is destroyed
def color_hex(self): """Node color as Hex Triplet https://en.wikipedia.org/wiki/Web_colors#Hex_triplet""" def clamp(x): return max(0, min(int(x), 255)) r, g, b = np.trunc(self.color_rgb * 255) return "#{0:02x}{1:02x}{2:02x}".format(clamp(r), clamp(g), clamp(b))
Node color as Hex Triplet https://en.wikipedia.org/wiki/Web_colors#Hex_triplet
def add_default(self, key: str, value: Optional[str], default_type: type = str) -> None: """ Adds a default value and a default type for a key. :param key: Key :param value: *Serialized* default value, i.e. a string or ``None``. :param default_type: The type to unserialize value...
Adds a default value and a default type for a key. :param key: Key :param value: *Serialized* default value, i.e. a string or ``None``. :param default_type: The type to unserialize values for this key to, defaults to ``str``.
def main(): """ Main function for command line usage """ usage = "usage: %(prog)s [options] " description = "Gather source maps from Fermi-LAT files." parser = argparse.ArgumentParser(usage=usage, description=description) parser.add_argument('-o', '--output', default=None, type=str, ...
Main function for command line usage
def recursive_exclude(self, dir, pattern): """ Exclude any file anywhere in 'dir/' that match the pattern. """ match = translate_pattern(os.path.join(dir, '**', pattern)) return self._remove_files(match.match)
Exclude any file anywhere in 'dir/' that match the pattern.
def latsrf(method, target, et, fixref, lonlat): """ Map array of planetocentric longitude/latitude coordinate pairs to surface points on a specified target body. The surface of the target body may be represented by a triaxial ellipsoid or by topographic data provided by DSK files. http...
Map array of planetocentric longitude/latitude coordinate pairs to surface points on a specified target body. The surface of the target body may be represented by a triaxial ellipsoid or by topographic data provided by DSK files. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/latsrf_...
def new_ele_description(**kwargs): ''' from elist.elist import * from elist.jprint import pobj root_desc = new_ele_description(leaf=False,depth=0,breadth_path=[],path=[],parent_path=[],parent_breadth_path=[]) pobj(root_desc) #None means not handled ''' desc = { ...
from elist.elist import * from elist.jprint import pobj root_desc = new_ele_description(leaf=False,depth=0,breadth_path=[],path=[],parent_path=[],parent_breadth_path=[]) pobj(root_desc) #None means not handled
def wrongstatus(data, sb, msb, lsb): """Check if the status bit and field bits are consistency. This Function is used for checking BDS code versions. """ # status bit, most significant bit, least significant bit status = int(data[sb-1]) value = bin2int(data[msb-1:lsb]) if not status: ...
Check if the status bit and field bits are consistency. This Function is used for checking BDS code versions.
def load_unicode(self, resource_path): """ Gets the content of a resource """ resource_content = pkg_resources.resource_string(self.module_name, resource_path) return resource_content.decode('utf-8')
Gets the content of a resource
def send_item(self, destination, item_id, force_send): """ Run send method for item_id at destination. :param destination: str which type of operation are we doing (SHARE_DESTINATION or DELIVER_DESTINATION) :param item_id: str D4S2 service id representing the item we want to send ...
Run send method for item_id at destination. :param destination: str which type of operation are we doing (SHARE_DESTINATION or DELIVER_DESTINATION) :param item_id: str D4S2 service id representing the item we want to send :param force_send: bool it's ok to email the item again :return: r...
def post_resource(url, body): """ Post resource with the given json body :returns: http response data """ response = Bridge_DAO().postURL(url, PHEADER, body) log_data = "POST %s %s ==status==> %s" % (url, body, response.status) if response.status != 200 and response.status != 201: #...
Post resource with the given json body :returns: http response data
def results(self, Pc): r""" Places the results of the IP simulation into the Phase object. Parameters ---------- Pc : float Capillary Pressure at which phase configuration was reached """ phase = self.project.find_phase(self) net = self.proj...
r""" Places the results of the IP simulation into the Phase object. Parameters ---------- Pc : float Capillary Pressure at which phase configuration was reached
def unicode_urlencode(obj, charset='utf-8', for_qs=False): """URL escapes a single bytestring or unicode string with the given charset if applicable to URL safe quoting under all rules that need to be considered under all supported Python versions. If non strings are provided they are converted to thei...
URL escapes a single bytestring or unicode string with the given charset if applicable to URL safe quoting under all rules that need to be considered under all supported Python versions. If non strings are provided they are converted to their unicode representation first.
def data_groups(self, groups, entity_count): """Process Group data. Args: groups (list): The list of groups to process. Returns: list: A list of groups including associations """ data = [] # process group objects for xid in groups.keys():...
Process Group data. Args: groups (list): The list of groups to process. Returns: list: A list of groups including associations
def to_csv(self, path_or_buf=None, sep=",", na_rep='', float_format=None, columns=None, header=True, index=True, index_label=None, mode='w', encoding=None, compression='infer', quoting=None, quotechar='"', line_terminator=None, chunksize=None, tupleize_cols=No...
r""" Write object to a comma-separated values (csv) file. .. versionchanged:: 0.24.0 The order of arguments for Series was changed. Parameters ---------- path_or_buf : str or file handle, default None File path or object, if None is provided the result i...
def peekView(self, newLength): """ Return a view of the next newLength bytes. """ # Note: In Python 2.7, memoryviews can't be written to # by the struct module. (BUG) return memoryview(self.buf)[self.offset:self.offset + newLength]
Return a view of the next newLength bytes.
def get_logger(process_name, append_to_console=None, redirect_stdstream=None): """ method returns initiated logger""" if append_to_console is None: append_to_console = settings.settings['under_test'] if redirect_stdstream is None: redirect_stdstream=not settings.settings['under_test'] i...
method returns initiated logger
def listar_por_ambiente(self, id_ambiente): """List all VLANs from an environment. ** The itens returning from network is there to be compatible with other system ** :param id_ambiente: Environment identifier. :return: Following dictionary: :: {'vlan': [{'id': < id_v...
List all VLANs from an environment. ** The itens returning from network is there to be compatible with other system ** :param id_ambiente: Environment identifier. :return: Following dictionary: :: {'vlan': [{'id': < id_vlan >, 'nome': < nome_vlan >, 'num_...
def iterate(self, func, args=None, filter=[]): '''Call a function on this node, and recursively all its children. This is a depth-first iteration. @param func The function to call. Its declaration must be 'def blag(node, args)', where 'node' is the current node ...
Call a function on this node, and recursively all its children. This is a depth-first iteration. @param func The function to call. Its declaration must be 'def blag(node, args)', where 'node' is the current node in the iteration and args is the value of @ref arg...
def update_function( cfg, path_to_zip_file, existing_cfg, use_s3=False, s3_file=None, preserve_vpc=False ): """Updates the code of an existing Lambda function""" print('Updating your Lambda function') byte_stream = read(path_to_zip_file, binary_file=True) profile_name = cfg.get('profile') a...
Updates the code of an existing Lambda function
def show(fig=None, path='_map.html', **kwargs): """ Convert a Matplotlib Figure to a Leaflet map. Open in a browser Parameters ---------- fig : figure, default gcf() Figure used to convert to map path : string, default '_map.html' Filename where output html will be saved Se...
Convert a Matplotlib Figure to a Leaflet map. Open in a browser Parameters ---------- fig : figure, default gcf() Figure used to convert to map path : string, default '_map.html' Filename where output html will be saved See fig_to_html() for description of keyword args.
def get_qrcode_url(self, shop_id, img_id): """ 获取物料二维码图片网址 详情请参考 http://mp.weixin.qq.com/wiki/7/fcd0378ef00617fc276be2b3baa80973.html :param shop_id: 门店 ID :param img_id: 物料样式编号:0-二维码,可用于自由设计宣传材料; 1-桌贴(二维码),100mm×100mm(宽×高),可直接张贴 :return: ...
获取物料二维码图片网址 详情请参考 http://mp.weixin.qq.com/wiki/7/fcd0378ef00617fc276be2b3baa80973.html :param shop_id: 门店 ID :param img_id: 物料样式编号:0-二维码,可用于自由设计宣传材料; 1-桌贴(二维码),100mm×100mm(宽×高),可直接张贴 :return: 二维码图片网址
def geometric_fba(model, epsilon=1E-06, max_tries=200, processes=None): """ Perform geometric FBA to obtain a unique, centered flux distribution. Geometric FBA [1]_ formulates the problem as a polyhedron and then solves it by bounding the convex hull of the polyhedron. The bounding forms a box arou...
Perform geometric FBA to obtain a unique, centered flux distribution. Geometric FBA [1]_ formulates the problem as a polyhedron and then solves it by bounding the convex hull of the polyhedron. The bounding forms a box around the convex hull which reduces with every iteration and extracts a unique solu...
def optimize(model,cand,obj): """optimize: function for solving the model, updating candidate solutions' list Parameters: - model: Gurobi model object - cand: list of pairs of objective functions (for appending more solutions) - obj: name of a model's variable to setup as objective R...
optimize: function for solving the model, updating candidate solutions' list Parameters: - model: Gurobi model object - cand: list of pairs of objective functions (for appending more solutions) - obj: name of a model's variable to setup as objective Returns the solver's exit status
def listscripts(self): """List available scripts. See MANAGESIEVE specifications, section 2.7 :returns: a 2-uple (active script, [script1, ...]) """ code, data, listing = self.__send_command( "LISTSCRIPTS", withcontent=True) if code == "NO": retu...
List available scripts. See MANAGESIEVE specifications, section 2.7 :returns: a 2-uple (active script, [script1, ...])
def aggregate(self, rankings, breaking="full", k=None): """ Description: Takes in a set of rankings and computes the Plackett-Luce model aggregate ranking. Parameters: rankings: set of rankings to aggregate breaking: type of breaking to use ...
Description: Takes in a set of rankings and computes the Plackett-Luce model aggregate ranking. Parameters: rankings: set of rankings to aggregate breaking: type of breaking to use k: number to be used for top, bottom, and position breakin...
def edit(self, title=github.GithubObject.NotSet, body=github.GithubObject.NotSet, assignee=github.GithubObject.NotSet, state=github.GithubObject.NotSet, milestone=github.GithubObject.NotSet, labels=github.GithubObject.NotSet, assignees=github.GithubObject.NotSet): """ :calls: `PATCH /repos/:owner/:repo/...
:calls: `PATCH /repos/:owner/:repo/issues/:number <http://developer.github.com/v3/issues>`_ :param title: string :param body: string :param assignee: string or :class:`github.NamedUser.NamedUser` or None :param assignees: list (of string or :class:`github.NamedUser.NamedUser`) :p...
def reset_dq_bits(input,bits,extver=None,extname='dq'): """ This function resets bits in the integer array(s) of a FITS file. Parameters ---------- filename : str full filename with path bits : str sum or list of integers corresponding to all the bits to be reset extver : int,...
This function resets bits in the integer array(s) of a FITS file. Parameters ---------- filename : str full filename with path bits : str sum or list of integers corresponding to all the bits to be reset extver : int, optional List of version numbers of the DQ arrays ...
def start_output (self): """Write start of checking info as DOT comment.""" super(DOTLogger, self).start_output() if self.has_part("intro"): self.write_intro() self.writeln() self.writeln(u"digraph G {") self.writeln(u" graph [") self.writeln(u" ...
Write start of checking info as DOT comment.
def unpack(self, data, namedstruct): ''' Unpack the struct from specified bytes. If the struct is sub-classed, definitions from the sub type is not unpacked. :param data: bytes of the struct, including fields of sub type and "extra" data. :param namedstruct: a N...
Unpack the struct from specified bytes. If the struct is sub-classed, definitions from the sub type is not unpacked. :param data: bytes of the struct, including fields of sub type and "extra" data. :param namedstruct: a NamedStruct object of this type :returns:...
def save_policy(self, path): """Pickles the current policy for later inspection. """ with open(path, 'wb') as f: pickle.dump(self.policy, f)
Pickles the current policy for later inspection.
def convert_from_eclipse(self, eclipse_projects): """ Convert from eclipse projects format to grimoire projects json format """ projects = {} # We need the global project for downloading the full Bugzilla and Gerrit projects['unknown'] = { "gerrit": ["git.eclipse.org"], ...
Convert from eclipse projects format to grimoire projects json format
def get_target_state(): """SDP target State. Returns the target state; allowed target states and time updated """ sdp_state = SDPState() errval, errdict = _check_status(sdp_state) if errval == "error": LOG.debug(errdict['reason']) return dict( current_target_state="u...
SDP target State. Returns the target state; allowed target states and time updated
def name(self, filetype, **kwargs): """Return the directory containing a file of a given type. Parameters ---------- filetype : str File type parameter. Returns ------- name : str Name of a file with no directory information. """ ...
Return the directory containing a file of a given type. Parameters ---------- filetype : str File type parameter. Returns ------- name : str Name of a file with no directory information.
def copy(self): """ Return a new :class:`~pywbem.CIMQualifierDeclaration` object that is a copy of this CIM qualifier type. Objects of this class have no mutable types in any attributes, so modifications of the original object will not affect the returned copy, and vice ...
Return a new :class:`~pywbem.CIMQualifierDeclaration` object that is a copy of this CIM qualifier type. Objects of this class have no mutable types in any attributes, so modifications of the original object will not affect the returned copy, and vice versa. Note that the Python...
def knot_removal(degree, knotvector, ctrlpts, u, **kwargs): """ Computes the control points of the rational/non-rational spline after knot removal. Implementation based on Algorithm A5.8 and Equation 5.28 of The NURBS Book by Piegl & Tiller Keyword Arguments: * ``num``: number of knot removals ...
Computes the control points of the rational/non-rational spline after knot removal. Implementation based on Algorithm A5.8 and Equation 5.28 of The NURBS Book by Piegl & Tiller Keyword Arguments: * ``num``: number of knot removals :param degree: degree :type degree: int :param knotvector:...
def _processValueItem(element, reg_key, reg_valuename, policy, parent_element, check_deleted=False, this_element_value=None): ''' helper function to process a value type item and generate the expected string in the Registry.pol file element - the element to process reg_key - t...
helper function to process a value type item and generate the expected string in the Registry.pol file element - the element to process reg_key - the registry key associated with the element (some inherit from their parent policy) reg_valuename - the registry valueName associated with the...
def make_figs(dcfg,dp='figs',force=False): """ 'figi','plotp' """ doutp=abspath(dp) if isinstance(dcfg,str): dcfg=pd.read_table(dcfg, error_bad_lines=False, comment='#',) # .dropna(subset=['figi','fign','plotn','plotp']) dc...
'figi','plotp'
def parse(self, scope): """Parse node args: scope (Scope): current scope raises: SyntaxError returns: self """ self.name, args, self.guards = self.tokens[0] self.args = [a for a in utility.flatten(args) if a] self.body =...
Parse node args: scope (Scope): current scope raises: SyntaxError returns: self
def parser_factory(lang): """Returns a Parser object specific to the language specified by :param:`lang`. :param lang: A string naming the desired parser. See the keys in :var:`class_` for valid strings. :Example: >>> chinese_parser = parser_factory('zh-Hans') >>> isinstance(chinese_parser, ...
Returns a Parser object specific to the language specified by :param:`lang`. :param lang: A string naming the desired parser. See the keys in :var:`class_` for valid strings. :Example: >>> chinese_parser = parser_factory('zh-Hans') >>> isinstance(chinese_parser, ChineseSimplifiedParser) True...
def set_fetcher(self, fetcher_class): """Set the fetcher class. :Parameters: - `fetcher_class`: the fetcher class. :Types: - `fetcher_class`: `CacheFetcher` based class """ self._lock.acquire() try: self._fetcher = fetcher_class ...
Set the fetcher class. :Parameters: - `fetcher_class`: the fetcher class. :Types: - `fetcher_class`: `CacheFetcher` based class
def get_age_info(self, filename=None): """ Read er_ages.txt file. Parse information into dictionaries for each site/sample. Then add it to the site/sample object as site/sample.age_data. """ # use filename if provided, otherwise find er_ages.txt in WD if not filen...
Read er_ages.txt file. Parse information into dictionaries for each site/sample. Then add it to the site/sample object as site/sample.age_data.
def factory(opts, **kwargs): ''' If we have additional IPC transports other than UXD and TCP, add them here ''' import salt.transport.ipc return salt.transport.ipc.IPCMessageServer(opts, **kwargs)
If we have additional IPC transports other than UXD and TCP, add them here
def returner(load): ''' Return data to a postgres server ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''INSERT INTO salt_returns (fun, jid, return, id, success) VALUES (%s, %s, %s, %s, %s)''' try: ret = six.text_ty...
Return data to a postgres server
def add_to_file_links(self): # type: () -> None ''' Increment the number of POSIX file links on this entry by one. Parameters: None. Returns: Nothing. ''' if not self._initialized: raise pycdlibexception.PyCdlibInternalError('Rock Ri...
Increment the number of POSIX file links on this entry by one. Parameters: None. Returns: Nothing.
def log(self, *lines): """will print out the lines in console if debug is enabled for the specific sprite""" if getattr(self, "debug", False): print(dt.datetime.now().time(), end=' ') for line in lines: print(line, end=' ') print()
will print out the lines in console if debug is enabled for the specific sprite
def compute_key_composite(password=None, keyfile=None): """Compute composite key. Used in header verification and payload decryption.""" # hash the password if password: password_composite = hashlib.sha256(password.encode('utf-8')).digest() else: password_composite = b'' # hash ...
Compute composite key. Used in header verification and payload decryption.
def oldest_frame(self, raw=False): """ Get the oldest frame in the panel. """ if raw: return self.buffer.values[:, self._oldest_frame_idx(), :] return self.buffer.iloc[:, self._oldest_frame_idx(), :]
Get the oldest frame in the panel.
def load(self, key): """ Given a bucket key, load the corresponding bucket. :param key: The bucket key. This may be either a string or a BucketKey object. :returns: A Bucket object. """ # Turn the key into a BucketKey if isinstance(key, bas...
Given a bucket key, load the corresponding bucket. :param key: The bucket key. This may be either a string or a BucketKey object. :returns: A Bucket object.
def init_layout(self): """ Create the widget in the layout pass after the child widget has been created and intialized. We do this so the child widget does not attempt to use this proxy widget as its parent and because repositioning must be done after the widget is set. """ ...
Create the widget in the layout pass after the child widget has been created and intialized. We do this so the child widget does not attempt to use this proxy widget as its parent and because repositioning must be done after the widget is set.
def raise_exception(entity_type, entity, exception): """ Exception helper """ raise exception( u'The {} you have provided is not valid: {}'.format(entity_type, entity).encode('utf-8') )
Exception helper
def getApplicationsThatSupportMimeType(self, pchMimeType, pchAppKeysThatSupportBuffer, unAppKeysThatSupportBuffer): """Get the list of app-keys that support this mime type, comma-delimited, the return value is number of bytes you need to return the full string""" fn = self.function_table.getApplication...
Get the list of app-keys that support this mime type, comma-delimited, the return value is number of bytes you need to return the full string
def append(*vectors): r""" Takes an arbitrary number of vectors containing features and append them (horizontally). E.g. taking a 100 and a 200 sample vector with 7 features each, a 300x7 vector is returned. The vectors are expected to have the form samples*features i.e.:: ...
r""" Takes an arbitrary number of vectors containing features and append them (horizontally). E.g. taking a 100 and a 200 sample vector with 7 features each, a 300x7 vector is returned. The vectors are expected to have the form samples*features i.e.:: s1 s2 s3 [.....