code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def handle_put_user(self, req): """Handles the PUT v2/<account>/<user> call for adding a user to an account. X-Auth-User-Key represents the user's key (url encoded), - OR - X-Auth-User-Key-Hash represents the user's hashed key (url encoded), X-Auth-User-Admin may be set ...
Handles the PUT v2/<account>/<user> call for adding a user to an account. X-Auth-User-Key represents the user's key (url encoded), - OR - X-Auth-User-Key-Hash represents the user's hashed key (url encoded), X-Auth-User-Admin may be set to `true` to create an account .admin, and ...
def asr_breaking(self, tol_eigendisplacements=1e-5): """ Returns the breaking of the acoustic sum rule for the three acoustic modes, if Gamma is present. None otherwise. If eigendisplacements are available they are used to determine the acoustic modes: selects the bands correspon...
Returns the breaking of the acoustic sum rule for the three acoustic modes, if Gamma is present. None otherwise. If eigendisplacements are available they are used to determine the acoustic modes: selects the bands corresponding to the eigendisplacements that represent to a translation w...
def rename(self, old_fieldname, new_fieldname): """ Renames a specific field, and preserves the underlying order. """ if old_fieldname not in self: raise Exception("DataTable does not have field `%s`" % old_fieldname) if not isinstance(new...
Renames a specific field, and preserves the underlying order.
def _post_fork_init(self): ''' Some things need to be init'd after the fork has completed The easiest example is that one of these module types creates a thread in the parent process, then once the fork happens you'll start getting errors like "WARNING: Mixing fork() and threads ...
Some things need to be init'd after the fork has completed The easiest example is that one of these module types creates a thread in the parent process, then once the fork happens you'll start getting errors like "WARNING: Mixing fork() and threads detected; memory leaked."
def price_diff(self): '返回DataStruct.price的一阶差分' res = self.price.groupby(level=1).apply(lambda x: x.diff(1)) res.name = 'price_diff' return res
返回DataStruct.price的一阶差分
def _offset_setup(self,sigangle,leading,deltaAngleTrack): """The part of the setup related to calculating the stream/progenitor offset""" #From the progenitor orbit, determine the sigmas in J and angle self._sigjr= (self._progenitor.rap()-self._progenitor.rperi())/numpy.pi*self._sigv sel...
The part of the setup related to calculating the stream/progenitor offset
def download(url, filename=None, print_progress=0, delete_fail=True, **kwargs): """ Download a file, optionally printing a simple progress bar url: The URL to download filename: The filename to save to, default is to use the URL basename print_progress: The length of the progress bar, u...
Download a file, optionally printing a simple progress bar url: The URL to download filename: The filename to save to, default is to use the URL basename print_progress: The length of the progress bar, use 0 to disable delete_fail: If True delete the file if the download was not successful, defaul...
def gpg_decrypt( fd_in, path_out, sender_key_info, my_key_info, passphrase=None, config_dir=None ): """ Decrypt a stream of data using key info for a private key we own. @my_key_info and @sender_key_info should be data returned by gpg_app_get_key { 'key_id': ... 'key_data': ... ...
Decrypt a stream of data using key info for a private key we own. @my_key_info and @sender_key_info should be data returned by gpg_app_get_key { 'key_id': ... 'key_data': ... 'app_name': ... } Return {'status': True, 'sig': ...} on success Return {'status': True} on succ...
def on_connect(client): """ Sample on_connect function. Handles new connections. """ print "++ Opened connection to %s" % client.addrport() broadcast('%s joins the conversation.\n' % client.addrport() ) CLIENT_LIST.append(client) client.send("Welcome to the Chat Server, %s.\n" % client.a...
Sample on_connect function. Handles new connections.
def shrank(self, block=None, percent_diff=0, abs_diff=1): """ Returns whether a block has less nets than before :param Block block: block to check (if changed) :param Number percent_diff: percentage difference threshold :param int abs_diff: absolute difference threshold ...
Returns whether a block has less nets than before :param Block block: block to check (if changed) :param Number percent_diff: percentage difference threshold :param int abs_diff: absolute difference threshold :return: boolean This function checks whether the change in the numbe...
def dictToFile(dictionary,replicateKey,outFileName): ''' Function to write dictionary data, from subsampleReplicates, to file an hdf5 file. :param dictionary: nested dictionary returned by subsampleReplicates :param replicateKey: string designating the replicate written to file :param outFileName: ...
Function to write dictionary data, from subsampleReplicates, to file an hdf5 file. :param dictionary: nested dictionary returned by subsampleReplicates :param replicateKey: string designating the replicate written to file :param outFileName: string defining the hdf5 filename
def delete_model(self, meta: dict): """Delete the model from GCS.""" bucket = self.connect() if bucket is None: raise BackendRequiredError blob_name = "models/%s/%s.asdf" % (meta["model"], meta["uuid"]) self._log.info(blob_name) try: self._log.info...
Delete the model from GCS.
def diffmap(adata, n_comps=15, copy=False): """Diffusion Maps [Coifman05]_ [Haghverdi15]_ [Wolf18]_. Diffusion maps [Coifman05]_ has been proposed for visualizing single-cell data by [Haghverdi15]_. The tool uses the adapted Gaussian kernel suggested by [Haghverdi16]_ in the implementation of [Wolf18]_...
Diffusion Maps [Coifman05]_ [Haghverdi15]_ [Wolf18]_. Diffusion maps [Coifman05]_ has been proposed for visualizing single-cell data by [Haghverdi15]_. The tool uses the adapted Gaussian kernel suggested by [Haghverdi16]_ in the implementation of [Wolf18]_. The width ("sigma") of the connectivity kern...
def _wait_until(obj, att, desired, callback, interval, attempts, verbose, verbose_atts): """ Loops until either the desired value of the attribute is reached, or the number of attempts is exceeded. """ if not isinstance(desired, (list, tuple)): desired = [desired] if verbose_atts...
Loops until either the desired value of the attribute is reached, or the number of attempts is exceeded.
def get_user_for_membersuite_entity(membersuite_entity): """Returns a User for `membersuite_entity`. membersuite_entity is any MemberSuite object that has the fields membersuite_id, email_address, first_name, and last_name, e.g., PortalUser or Individual. """ user = None user_created = Fal...
Returns a User for `membersuite_entity`. membersuite_entity is any MemberSuite object that has the fields membersuite_id, email_address, first_name, and last_name, e.g., PortalUser or Individual.
def _raise_error_if_not_of_type(arg, expected_type, arg_name=None): """ Check if the input is of expected type. Parameters ---------- arg : Input argument. expected_type : A type OR a list of types that the argument is expected to be. arg_name : The n...
Check if the input is of expected type. Parameters ---------- arg : Input argument. expected_type : A type OR a list of types that the argument is expected to be. arg_name : The name of the variable in the function being used. No name is a...
def _add_new_items(self, config, seen): '''Add new (unseen) items to the config.''' for (key, value) in self.items(): if key not in seen: self._set_value(config, key, value)
Add new (unseen) items to the config.
def _check_series_localize_timestamps(s, timezone): """ Convert timezone aware timestamps to timezone-naive in the specified timezone or local timezone. If the input series is not a timestamp series, then the same series is returned. If the input series is a timestamp series, then a converted series is...
Convert timezone aware timestamps to timezone-naive in the specified timezone or local timezone. If the input series is not a timestamp series, then the same series is returned. If the input series is a timestamp series, then a converted series is returned. :param s: pandas.Series :param timezone: the...
def getStats(self): """ TODO: This method needs to be enhanced to get the stats on the *aggregated* records. :returns: stats (like min and max values of the fields). """ # The record store returns a dict of stats, each value in this dict is # a list with one item per field of the record s...
TODO: This method needs to be enhanced to get the stats on the *aggregated* records. :returns: stats (like min and max values of the fields).
def _process_state_embryo(self, job_record): """ method that takes care of processing job records in STATE_EMBRYO state""" start_timeperiod = self.compute_start_timeperiod(job_record.process_name, job_record.timeperiod) end_timeperiod = self.compute_end_timeperiod(job_record.process_name, job_re...
method that takes care of processing job records in STATE_EMBRYO state
def channels(self): """Output channels""" try: return self._channels except AttributeError: logger.debug("initialize output channels ...") channels = self.args.channels config_channels = [sec.rpartition('_')[0] for sec in self.config.sections(suffix='_cha...
Output channels
def _set_auth_type(self, v, load=False): """ Setter method for auth_type, mapped from YANG variable /routing_system/interface/ve/ipv6/ipv6_vrrp_extended/auth_type (container) If this variable is read-only (config: false) in the source YANG file, then _set_auth_type is considered as a private method....
Setter method for auth_type, mapped from YANG variable /routing_system/interface/ve/ipv6/ipv6_vrrp_extended/auth_type (container) If this variable is read-only (config: false) in the source YANG file, then _set_auth_type is considered as a private method. Backends looking to populate this variable should ...
def _parallel_exec(self, hosts): ''' handles mulitprocessing when more than 1 fork is required ''' if not hosts: return p = multiprocessing.Pool(self.forks) results = [] #results = p.map(multiprocessing_runner, hosts) # can't handle keyboard interrupt results ...
handles mulitprocessing when more than 1 fork is required
def _proc_gnusparse_01(self, next, pax_headers): """Process a GNU tar extended sparse header, version 0.1. """ sparse = [int(x) for x in pax_headers["GNU.sparse.map"].split(",")] next.sparse = list(zip(sparse[::2], sparse[1::2]))
Process a GNU tar extended sparse header, version 0.1.
def pin_ls(self, type="all", **kwargs): """Lists objects pinned to local storage. By default, all pinned objects are returned, but the ``type`` flag or arguments can restrict that to a specific pin type or to some specific objects respectively. .. code-block:: python ...
Lists objects pinned to local storage. By default, all pinned objects are returned, but the ``type`` flag or arguments can restrict that to a specific pin type or to some specific objects respectively. .. code-block:: python >>> c.pin_ls() {'Keys': { ...
def configure_logging(args): """Logging to console""" log_format = logging.Formatter('%(levelname)s:%(name)s:line %(lineno)s:%(message)s') log_level = logging.INFO if args.verbose else logging.WARN log_level = logging.DEBUG if args.debug else log_level console = logging.StreamHandler() console.s...
Logging to console
def copy(self): "Return a clone of this hash object." other = _ChainedHashAlgorithm(self._algorithms) other._hobj = deepcopy(self._hobj) other._fobj = deepcopy(self._fobj) return other
Return a clone of this hash object.
def token(self): " Get token when needed." if hasattr(self, '_token'): return getattr(self, '_token') # Json formatted auth. data = json.dumps({'customer_name': self.customer, 'user_name': self.username, 'password': self...
Get token when needed.
def get_grade_systems_by_genus_type(self, grade_system_genus_type): """Gets a ``GradeSystemList`` corresponding to the given grade system genus ``Type`` which does not include systems of genus types derived from the specified ``Type``. In plenary mode, the returned list contains all known systems or ...
Gets a ``GradeSystemList`` corresponding to the given grade system genus ``Type`` which does not include systems of genus types derived from the specified ``Type``. In plenary mode, the returned list contains all known systems or an error results. Otherwise, the returned list may contain only t...
def list_logs(args, container_name=None): '''list a specific log for a builder, or the latest log if none provided Parameters ========== args: the argparse object to look for a container name container_name: a default container name set to be None (show latest log) ''' from sre...
list a specific log for a builder, or the latest log if none provided Parameters ========== args: the argparse object to look for a container name container_name: a default container name set to be None (show latest log)
def print_commands(self, out=sys.stdout): ''' utility method to print commands and descriptions for @BotFather ''' cmds = self.list_commands() for ck in cmds: if ck.printable: out.write('%s\n' % ck)
utility method to print commands and descriptions for @BotFather
def build_common_all_meta_df(common_meta_dfs, fields_to_remove, remove_all_metadata_fields): """ concatenate the entries in common_meta_dfs, removing columns selectively (fields_to_remove) or entirely ( remove_all_metadata_fields=True; in this case, effectively just merges all the indexes in common_meta...
concatenate the entries in common_meta_dfs, removing columns selectively (fields_to_remove) or entirely ( remove_all_metadata_fields=True; in this case, effectively just merges all the indexes in common_meta_dfs). Returns 2 dataframes (in a tuple): the first has duplicates removed, the second does not...
def _ls_print_summary(all_trainings: List[Tuple[str, dict, TrainingTrace]]) -> None: """ Print trainings summary. In particular print tables summarizing the number of trainings with - particular model names - particular combinations of models and datasets :param all_trainings: a list of...
Print trainings summary. In particular print tables summarizing the number of trainings with - particular model names - particular combinations of models and datasets :param all_trainings: a list of training tuples (train_dir, configuration dict, trace)
def collect(nested_nodes, transform=None): ''' Return list containing the result of the `transform` function applied to each item in the supplied list of nested nodes. A custom transform function may be applied to each entry during the flattening by specifying a function through the `transform` key...
Return list containing the result of the `transform` function applied to each item in the supplied list of nested nodes. A custom transform function may be applied to each entry during the flattening by specifying a function through the `transform` keyword argument. The `transform` function will be pa...
def task_done(self, **kw): """ Marks a pending task as done, optionally specifying a completion date with the 'end' argument. """ def validate(task): if not Status.is_pending(task['status']): raise ValueError("Task is not pending.") return sel...
Marks a pending task as done, optionally specifying a completion date with the 'end' argument.
def comment(self, text): """ Make a top-level comment to this. :param text: The comment text. """ url = self._imgur._base_url + "/3/comment" payload = {'image_id': self.id, 'comment': text} resp = self._imgur._send_request(url, params=payload, needs_auth=True, ...
Make a top-level comment to this. :param text: The comment text.
def get_imports(self, option): """ See if we have been passed a set of currencies or a setting variable or look for settings CURRENCIES or SHOP_CURRENCIES. """ if option: if len(option) == 1 and option[0].isupper() and len(option[0]) > 3: return getatt...
See if we have been passed a set of currencies or a setting variable or look for settings CURRENCIES or SHOP_CURRENCIES.
def attach_volume(self, xml_bytes): """Parse the XML returned by the C{AttachVolume} function. @param xml_bytes: XML bytes with a C{AttachVolumeResponse} root element. @return: a C{dict} with status and attach_time keys. TODO: volumeId, instanceId, device """ ...
Parse the XML returned by the C{AttachVolume} function. @param xml_bytes: XML bytes with a C{AttachVolumeResponse} root element. @return: a C{dict} with status and attach_time keys. TODO: volumeId, instanceId, device
def to_xml(self): """Spit this resource record set out as XML""" if self.alias_hosted_zone_id != None and self.alias_dns_name != None: # Use alias body = self.AliasBody % (self.alias_hosted_zone_id, self.alias_dns_name) else: # Use resource record(s) ...
Spit this resource record set out as XML
def register_dimensions(self, dims): """ Register multiple dimensions on the cube. .. code-block:: python cube.register_dimensions([ {'name' : 'ntime', 'global_size' : 10, 'lower_extent' : 2, 'upper_extent' : 7 }, {'name' : 'na', 'glo...
Register multiple dimensions on the cube. .. code-block:: python cube.register_dimensions([ {'name' : 'ntime', 'global_size' : 10, 'lower_extent' : 2, 'upper_extent' : 7 }, {'name' : 'na', 'global_size' : 3, 'lower_extent' : 2, 'upper...
def from_unidiff(cls, diff: str) -> 'Patch': """ Constructs a Patch from a provided unified format diff. """ lines = diff.split('\n') file_patches = [] while lines: if lines[0] == '' or lines[0].isspace(): lines.pop(0) continue ...
Constructs a Patch from a provided unified format diff.
def restore_review_history_for_affected_objects(portal): """Applies the review history for objects that are bound to new senaite_* workflows """ logger.info("Restoring review_history ...") query = dict(portal_type=NEW_SENAITE_WORKFLOW_BINDINGS) brains = api.search(query, UID_CATALOG) total =...
Applies the review history for objects that are bound to new senaite_* workflows
def LOS_CrossProj(VType, Ds, us, kPIns, kPOuts, kRMins, Lplot='In', proj='All', multi=False): """ Compute the parameters to plot the poloidal projection of the LOS """ assert type(VType) is str and VType.lower() in ['tor','lin'] assert Lplot.lower() in ['tot','in'] assert type(proj) i...
Compute the parameters to plot the poloidal projection of the LOS
def get_cfgdict_list_subset(cfgdict_list, keys): r""" returns list of unique dictionaries only with keys specified in keys Args: cfgdict_list (list): keys (list): Returns: list: cfglbl_list CommandLine: python -m utool.util_gridsearch --test-get_cfgdict_list_subset...
r""" returns list of unique dictionaries only with keys specified in keys Args: cfgdict_list (list): keys (list): Returns: list: cfglbl_list CommandLine: python -m utool.util_gridsearch --test-get_cfgdict_list_subset Example: >>> # ENABLE_DOCTEST >...
def diropenbox(msg=None , title=None , default=None ): """ A dialog to get a directory name. Note that the msg argument, if specified, is ignored. Returns the name of a directory, or None if user chose to cancel. If the "default" argument specifies a directory name, and that direct...
A dialog to get a directory name. Note that the msg argument, if specified, is ignored. Returns the name of a directory, or None if user chose to cancel. If the "default" argument specifies a directory name, and that directory exists, then the dialog box will start with that directory.
def dumps(obj, big_endian=True): """ Dump a GeoJSON-like `dict` to a WKB string. .. note:: The dimensions of the generated WKB will be inferred from the first vertex in the GeoJSON `coordinates`. It will be assumed that all vertices are uniform. There are 4 types: - 2D (X, ...
Dump a GeoJSON-like `dict` to a WKB string. .. note:: The dimensions of the generated WKB will be inferred from the first vertex in the GeoJSON `coordinates`. It will be assumed that all vertices are uniform. There are 4 types: - 2D (X, Y): 2-dimensional geometry - Z (X, Y,...
def download(url, path, kind='file', progressbar=True, replace=False, timeout=10., verbose=True): """Download a URL. This will download a file and store it in a '~/data/` folder, creating directories if need be. It will also work for zip files, in which case it will unzip all of the files ...
Download a URL. This will download a file and store it in a '~/data/` folder, creating directories if need be. It will also work for zip files, in which case it will unzip all of the files to the desired location. Parameters ---------- url : string The url of the file to download. ...
def find_by_id(self, team, params={}, **options): """Returns the full record for a single team. Parameters ---------- team : {Id} Globally unique identifier for the team. [params] : {Object} Parameters for the request """ path = "/teams/%s" % (team) retu...
Returns the full record for a single team. Parameters ---------- team : {Id} Globally unique identifier for the team. [params] : {Object} Parameters for the request
def size(self): """Get the number of elements in the DataFrame. Returns: The number of elements in the DataFrame. """ return len(self._query_compiler.index) * len(self._query_compiler.columns)
Get the number of elements in the DataFrame. Returns: The number of elements in the DataFrame.
def __value_compare(self, target): """ Comparing result based on expectation if arg_type is "VALUE" Args: Anything Return: Boolean """ if self.expectation == "__ANY__": return True elif self.expectation == "__DEFINED__": return True if targ...
Comparing result based on expectation if arg_type is "VALUE" Args: Anything Return: Boolean
def generate(organization, package, destination): """Generates the Sphinx configuration and Makefile. Args: organization (str): the organization name. package (str): the package to be documented. destination (str): the destination directory. """ gen = ResourceGenerator(organizat...
Generates the Sphinx configuration and Makefile. Args: organization (str): the organization name. package (str): the package to be documented. destination (str): the destination directory.
def get_random_service( service_registry: ServiceRegistry, block_identifier: BlockSpecification, ) -> Tuple[Optional[str], Optional[str]]: """Selects a random PFS from service_registry. Returns a tuple of the chosen services url and eth address. If there are no PFS in the given registry, it...
Selects a random PFS from service_registry. Returns a tuple of the chosen services url and eth address. If there are no PFS in the given registry, it returns (None, None).
def sm_dict2lha(d): """Convert a a dictionary of SM parameters into a dictionary that pylha can convert into a DSixTools SM output file.""" blocks = OrderedDict([ ('GAUGE', {'values': [[1, d['g'].real], [2, d['gp'].real], [3, d['gs'].real]]}), ('SCALAR', {'values': [[1, d['Lambda'].real], [2...
Convert a a dictionary of SM parameters into a dictionary that pylha can convert into a DSixTools SM output file.
def flush(self, timeout=60): """ Sends a ping to the server expecting a pong back ensuring what we have written so far has made it to the server and also enabling measuring of roundtrip time. In case a pong is not returned within the allowed timeout, then it will raise Er...
Sends a ping to the server expecting a pong back ensuring what we have written so far has made it to the server and also enabling measuring of roundtrip time. In case a pong is not returned within the allowed timeout, then it will raise ErrTimeout.
def coerce(cls, key, value): """Convert plain dictionaries to MutationDict.""" if not isinstance(value, MutationDict): if isinstance(value, dict): return MutationDict(value) # this call will raise ValueError return Mutable.coerce(key, value) e...
Convert plain dictionaries to MutationDict.
def open(self): """Open an existing database""" if self._table_exists(): self.mode = "open" # get table info self._get_table_info() return self else: # table not found raise IOError,"Table %s doesn't exist" %self.na...
Open an existing database
def check_all_permissions(sender, **kwargs): """ This syncdb checks our PERMISSIONS setting in settings.py and makes sure all those permissions actually exit. """ if not is_permissions_app(sender): return config = getattr(settings, 'PERMISSIONS', dict()) # for each of our items ...
This syncdb checks our PERMISSIONS setting in settings.py and makes sure all those permissions actually exit.
def _run_operation_with_response(self, operation, unpack_res, exhaust=False, address=None): """Run a _Query/_GetMore operation and return a Response. :Parameters: - `operation`: a _Query or _GetMore object. - `unpack_res`: A callable that decodes...
Run a _Query/_GetMore operation and return a Response. :Parameters: - `operation`: a _Query or _GetMore object. - `unpack_res`: A callable that decodes the wire protocol response. - `exhaust` (optional): If True, the socket used stays checked out. It is returned along ...
def mach2cas(M, h): """ Mach to CAS conversion """ tas = mach2tas(M, h) cas = tas2cas(tas, h) return cas
Mach to CAS conversion
def reset_db(): """ drops the *scheduler* database, resets schema """ logger = get_logger(PROCESS_SCHEDULER) logger.info('Starting *scheduler* DB reset') ds = ds_manager.ds_factory(logger) ds._db_client.drop_database(settings.settings['mongo_db_name']) logger.info('*scheduler* db has been dropp...
drops the *scheduler* database, resets schema
def _set_exp_traffic_class(self, v, load=False): """ Setter method for exp_traffic_class, mapped from YANG variable /qos_mpls/map/exp_traffic_class (list) If this variable is read-only (config: false) in the source YANG file, then _set_exp_traffic_class is considered as a private method. Backends lo...
Setter method for exp_traffic_class, mapped from YANG variable /qos_mpls/map/exp_traffic_class (list) If this variable is read-only (config: false) in the source YANG file, then _set_exp_traffic_class is considered as a private method. Backends looking to populate this variable should do so via calling ...
def resource_type_type(loader): """ Returns a function which validates that resource types string contains only a combination of service, container, and object. Their shorthand representations are s, c, and o. """ def impl(string): t_resources = loader.get_models('common.models#ResourceTypes') ...
Returns a function which validates that resource types string contains only a combination of service, container, and object. Their shorthand representations are s, c, and o.
def textContent(self, text: str) -> None: # type: ignore """Set text content to inner node.""" if self._inner_element: self._inner_element.textContent = text else: # Need a trick to call property of super-class super().textContent = text
Set text content to inner node.
def select_window(pymux, variables): """ Select a window. E.g: select-window -t :3 """ window_id = variables['<target-window>'] def invalid_window(): raise CommandException('Invalid window: %s' % window_id) if window_id.startswith(':'): try: number = int(window_id[...
Select a window. E.g: select-window -t :3
def save(self, filename, clobber=True, **kwargs): """ Save the `Spectrum1D` object to the specified filename. :param filename: The filename to save the Spectrum1D object to. :type filename: str :param clobber: [optional] Whether to o...
Save the `Spectrum1D` object to the specified filename. :param filename: The filename to save the Spectrum1D object to. :type filename: str :param clobber: [optional] Whether to overwrite the `filename` if it already exists. :type clobber: ...
def SETB(cpu, dest): """ Sets byte if below. :param cpu: current CPU. :param dest: destination operand. """ dest.write(Operators.ITEBV(dest.size, cpu.CF, 1, 0))
Sets byte if below. :param cpu: current CPU. :param dest: destination operand.
def clear_threads(self): """ Clears the threads snapshot. """ for aThread in compat.itervalues(self.__threadDict): aThread.clear() self.__threadDict = dict()
Clears the threads snapshot.
def prt_txt(prt, data_nts, prtfmt=None, nt_fields=None, **kws): """Print list of namedtuples into a table using prtfmt.""" lines = get_lines(data_nts, prtfmt, nt_fields, **kws) if lines: for line in lines: prt.write(line) else: sys.stdout.write(" 0 items. NOT WRITING\n")
Print list of namedtuples into a table using prtfmt.
def cmServiceRequest(PriorityLevel_presence=0): """CM SERVICE REQUEST Section 9.2.9""" a = TpPd(pd=0x5) b = MessageType(mesType=0x24) # 00100100 c = CmServiceTypeAndCiphKeySeqNr() e = MobileStationClassmark2() f = MobileId() packet = a / b / c / e / f if PriorityLevel_presence is 1: ...
CM SERVICE REQUEST Section 9.2.9
def validNormalizeAttributeValue(self, doc, 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 leading an...
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 has_equal_value(state, ordered=False, ndigits=None, incorrect_msg=None): """Verify if a student and solution query result match up. This function must always be used after 'zooming' in on certain columns or records (check_column, check_row or check_result). ``has_equal_value`` then goes over all column...
Verify if a student and solution query result match up. This function must always be used after 'zooming' in on certain columns or records (check_column, check_row or check_result). ``has_equal_value`` then goes over all columns that are still left in the solution query result, and compares each column with th...
def string_to_tokentype(s): """ Convert a string into a token type:: >>> string_to_token('String.Double') Token.Literal.String.Double >>> string_to_token('Token.Literal.Number') Token.Literal.Number >>> string_to_token('') Token Tokens that are already token...
Convert a string into a token type:: >>> string_to_token('String.Double') Token.Literal.String.Double >>> string_to_token('Token.Literal.Number') Token.Literal.Number >>> string_to_token('') Token Tokens that are already tokens are returned unchanged: >>> s...
def get_nested_val(key_tuple, dict_obj): """Return a value from nested dicts by the order of the given keys tuple. Parameters ---------- key_tuple : tuple The keys to use for extraction, in order. dict_obj : dict The outer-most dict to extract from. Returns ------- valu...
Return a value from nested dicts by the order of the given keys tuple. Parameters ---------- key_tuple : tuple The keys to use for extraction, in order. dict_obj : dict The outer-most dict to extract from. Returns ------- value : object The extracted value, if exist...
def validate(self, instance, value): """Checks that value is a float and in min/max bounds Non-float numbers are coerced to floats """ try: floatval = float(value) if not self.cast and abs(value - floatval) > TOL: self.error( i...
Checks that value is a float and in min/max bounds Non-float numbers are coerced to floats
def list_controller_revision_for_all_namespaces(self, **kwargs): # noqa: E501 """list_controller_revision_for_all_namespaces # noqa: E501 list or watch objects of kind ControllerRevision # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTT...
list_controller_revision_for_all_namespaces # noqa: E501 list or watch objects of kind ControllerRevision # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_controller_revision_fo...
def hog(image, orientations=8, ksize=(5, 5)): ''' returns the Histogram of Oriented Gradients :param ksize: convolution kernel size as (y,x) - needs to be odd :param orientations: number of orientations in between rad=0 and rad=pi similar to http://scikit-image.org/docs/dev/auto_examples/pl...
returns the Histogram of Oriented Gradients :param ksize: convolution kernel size as (y,x) - needs to be odd :param orientations: number of orientations in between rad=0 and rad=pi similar to http://scikit-image.org/docs/dev/auto_examples/plot_hog.html but faster and with less options
def subprocess_check_output(*args, cwd=None, env=None, stderr=False): """ Run a command and capture output :param *args: List of command arguments :param cwd: Current working directory :param env: Command environment :param stderr: Read on stderr :returns: Command output """ if std...
Run a command and capture output :param *args: List of command arguments :param cwd: Current working directory :param env: Command environment :param stderr: Read on stderr :returns: Command output
def cleanup(self, force=False): """Clean up Yadis-related services in the session and return the most-recently-attempted service from the manager, if one exists. @param force: True if the manager should be deleted regardless of whether it's a manager for self.url. @retu...
Clean up Yadis-related services in the session and return the most-recently-attempted service from the manager, if one exists. @param force: True if the manager should be deleted regardless of whether it's a manager for self.url. @return: current service endpoint object or None...
def tocimxml(value): # pylint: disable=line-too-long """ Return the CIM-XML representation of the input object, as an object of an appropriate subclass of :term:`Element`. The returned CIM-XML representation is consistent with :term:`DSP0201`. Parameters: value (:term:`CIM object`, :ter...
Return the CIM-XML representation of the input object, as an object of an appropriate subclass of :term:`Element`. The returned CIM-XML representation is consistent with :term:`DSP0201`. Parameters: value (:term:`CIM object`, :term:`CIM data type`, :term:`number`, :class:`py:datetime.datetime`, or ...
def create_geometry(self, input_geometry, dip, upper_depth, lower_depth, mesh_spacing=1.0): ''' If geometry is defined as a numpy array then create instance of nhlib.geo.line.Line class, otherwise if already instance of class accept class :param input_geo...
If geometry is defined as a numpy array then create instance of nhlib.geo.line.Line class, otherwise if already instance of class accept class :param input_geometry: Trace (line) of the fault source as either i) instance of nhlib.geo.line.Line class ii) numpy...
def create_widget(self): """ Create the underlying widget. """ context = self.get_context() d = self.declaration style = d.style or '@attr/autoCompleteTextViewStyle' self.widget = AutoCompleteTextView(context, None, style) self.adapter = ArrayAdapter(context, '@l...
Create the underlying widget.
def channels_rename(self, *, channel: str, name: str, **kwargs) -> SlackResponse: """Renames a channel. Args: channel (str): The channel id. e.g. 'C1234567890' name (str): The new channel name. e.g. 'newchannel' """ self._validate_xoxp_token() kwargs.upda...
Renames a channel. Args: channel (str): The channel id. e.g. 'C1234567890' name (str): The new channel name. e.g. 'newchannel'
def hierarchyLookup(self, record): """ Looks up additional hierarchy information for the inputed record. :param record | <orb.Table> :return (<subclass of orb.Table> || None, <str> column) """ def _get_lookup(cls): if cls in...
Looks up additional hierarchy information for the inputed record. :param record | <orb.Table> :return (<subclass of orb.Table> || None, <str> column)
def _certificate_required(cls, hostname, port=XCLI_DEFAULT_PORT, ca_certs=None, validate=None): ''' returns true if connection should verify certificate ''' if not ca_certs: return False xlog.debug("CONNECT SSL %s:%s, cert_file=%s", ...
returns true if connection should verify certificate
def enqueue_conversion_path(url_string, to_type, enqueue_convert): ''' Given a URL string that has already been downloaded, enqueue necessary conversion to get to target type ''' target_ts = TypeString(to_type) foreign_res = ForeignResource(url_string) # Determine the file type of the forei...
Given a URL string that has already been downloaded, enqueue necessary conversion to get to target type
def _update_key(self, mask, key): """ Mask the value contained in the DataStore at a specified key. Parameters ----------- mask: (n,) int (n,) bool key: hashable object, in self._data """ mask = np.asanyarray(mask) if key in self._da...
Mask the value contained in the DataStore at a specified key. Parameters ----------- mask: (n,) int (n,) bool key: hashable object, in self._data
def rows2skip(self, decdel): """ Return the number of rows to skip based on the decimal delimiter decdel. When each record start to have the same number of matches, this is where the data starts. This is the idea. And the number of consecutive records to have the same nu...
Return the number of rows to skip based on the decimal delimiter decdel. When each record start to have the same number of matches, this is where the data starts. This is the idea. And the number of consecutive records to have the same number of matches is to be EQUAL_CNT_REQ.
def json_item(model, target=None, theme=FromCurdoc): ''' Return a JSON block that can be used to embed standalone Bokeh content. Args: model (Model) : The Bokeh object to embed target (string, optional) A div id to embed the model into. If None, the target id must ...
Return a JSON block that can be used to embed standalone Bokeh content. Args: model (Model) : The Bokeh object to embed target (string, optional) A div id to embed the model into. If None, the target id must be supplied in the JavaScript call. theme (Th...
def normalize(self, decl_string, arg_separator=None): """implementation details""" if not self.has_pattern(decl_string): return decl_string name, args = self.split(decl_string) for i, arg in enumerate(args): args[i] = self.normalize(arg) return self.join(n...
implementation details
def execute(self): """ Executes the command. """ from vsgen.util.logger import VSGLogger VSGLogger.info(self._logname, self._message) start = time.clock() VSGWriter.write(self._writables, self._parallel) end = time.clock() VSGLogger.info(self._log...
Executes the command.
def hacking_docstring_start_space(physical_line, previous_logical, tokens): r"""Check for docstring not starting with space. OpenStack HACKING guide recommendation for docstring: Docstring should not start with space Okay: def foo():\n '''This is good.''' Okay: def foo():\n r'''This is good....
r"""Check for docstring not starting with space. OpenStack HACKING guide recommendation for docstring: Docstring should not start with space Okay: def foo():\n '''This is good.''' Okay: def foo():\n r'''This is good.''' Okay: def foo():\n a = ''' This is not a docstring.''' Okay: def ...
def dot_product_batched_head(q, k, v, gates_q, gates_k, mask_right=False): """Perform a dot product attention on a single sequence on a single head. This function dispatch the q, k, v and loop over the buckets to compute the attention dot product on each subsequences. Args: q (tf.Tensor): [batch*heads, le...
Perform a dot product attention on a single sequence on a single head. This function dispatch the q, k, v and loop over the buckets to compute the attention dot product on each subsequences. Args: q (tf.Tensor): [batch*heads, length_q, depth_q] k (tf.Tensor): [batch*heads, length_k, depth_q] v (tf.T...
def visit_FormattedValue(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s value formatted according to its format spec.""" format_spec = node.format_spec return f"{{{self.visit(node.value)}" \ f"{self.CONV_MAP.get(node.conversion, ...
Return `node`s value formatted according to its format spec.
def _recurse(self, matrix, m_list, indices, output_m_list=[]): """ This method recursively finds the minimal permutations using a binary tree search strategy. Args: matrix: The current matrix (with some permutations already performed). m_list: The...
This method recursively finds the minimal permutations using a binary tree search strategy. Args: matrix: The current matrix (with some permutations already performed). m_list: The list of permutations still to be performed indices: Set of indices whi...
def setImagePlotAutoRangeOn(self, axisNumber): """ Sets the image plot's auto-range on for the axis with number axisNumber. :param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes). """ setXYAxesAutoRangeOn(self, self.xAxisRangeCti, self.yAxisRangeCti, axisNumber)
Sets the image plot's auto-range on for the axis with number axisNumber. :param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes).
def isPositiveStrand(self): """ Check if this genomic region is on the positive strand. :return: True if this element is on the positive strand """ if self.strand is None and self.DEFAULT_STRAND == self.POSITIVE_STRAND: return True return self.strand == self.POSITIVE_STRAND
Check if this genomic region is on the positive strand. :return: True if this element is on the positive strand
def to_text_diagram_drawer( self, *, use_unicode_characters: bool = True, qubit_namer: Optional[Callable[[ops.Qid], str]] = None, transpose: bool = False, precision: Optional[int] = 3, qubit_order: ops.QubitOrderOrList = ops.QubitOrder....
Returns a TextDiagramDrawer with the circuit drawn into it. Args: use_unicode_characters: Determines if unicode characters are allowed (as opposed to ascii-only diagrams). qubit_namer: Names qubits in diagram. Defaults to str. transpose: Arranges qubit wires ...
def _generate_corpus_table(self, labels, ngrams): """Returns an HTML table containing data on each corpus' n-grams.""" html = [] for label in labels: html.append(self._render_corpus_row(label, ngrams)) return '\n'.join(html)
Returns an HTML table containing data on each corpus' n-grams.
def _prefix_from_ip_int(self, ip_int): """Return prefix length from the bitwise netmask. Args: ip_int: An integer, the netmask in expanded bitwise format Returns: An integer, the prefix length. Raises: ValueError: If the input intermingles zeroes & ...
Return prefix length from the bitwise netmask. Args: ip_int: An integer, the netmask in expanded bitwise format Returns: An integer, the prefix length. Raises: ValueError: If the input intermingles zeroes & ones
def pattern_for_view(self, view, action): """ Returns the URL pattern for the passed in action. """ # if this view knows how to define a URL pattern, call that if getattr(view, 'derive_url_pattern', None): return view.derive_url_pattern(self.path, action) # o...
Returns the URL pattern for the passed in action.