positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def uuid(self, type, val): """Return the item-uuid for a identifier""" picker = lambda x: x.get('uuid', x) return self._get((type, val), picker)
Return the item-uuid for a identifier
def _build_reflash_script_action(target, source, env): """Create a TRUB script containing tile and controller reflashes and/or sensorgraph If the app_info is provided, then the final source file will be a sensorgraph. All subsequent files in source must be in intel hex format. This is guaranteed by the...
Create a TRUB script containing tile and controller reflashes and/or sensorgraph If the app_info is provided, then the final source file will be a sensorgraph. All subsequent files in source must be in intel hex format. This is guaranteed by the ensure_image_is_hex call in build_update_script.
def create_pie_chart(self, snapshot, filename=''): """ Create a pie chart that depicts the distribution of the allocated memory for a given `snapshot`. The chart is saved to `filename`. """ try: from pylab import figure, title, pie, axes, savefig from pyla...
Create a pie chart that depicts the distribution of the allocated memory for a given `snapshot`. The chart is saved to `filename`.
def compile_cc(build_context, compiler_config, buildenv, sources, workspace_dir, buildenv_workspace, cmd_env): """Compile list of C++ source files in a buildenv image and return list of generated object file. """ objects = [] for src in sources: obj_rel_path = '{}.o'.format...
Compile list of C++ source files in a buildenv image and return list of generated object file.
def __start_command_queue_listener(self): """Start the function __command_queue_listener in a separate thread. This function continuously listens to the pipe connected to the frontend. """ thread_function = self.__command_queue_listener class QueueListenerThread(threading.Thread...
Start the function __command_queue_listener in a separate thread. This function continuously listens to the pipe connected to the frontend.
def subplots(scale_x=None, scale_y=None, scale=None, **kwargs): r''' Run ``matplotlib.pyplot.subplots`` with ``figsize`` set to the correct multiple of the default. :additional options: **scale, scale_x, scale_y** (``<float>``) Scale the figure-size (along one of the dimensions). ''' if 'figsize' in kwar...
r''' Run ``matplotlib.pyplot.subplots`` with ``figsize`` set to the correct multiple of the default. :additional options: **scale, scale_x, scale_y** (``<float>``) Scale the figure-size (along one of the dimensions).
def fast_forward(self, start_dt): """ Fast-forward file to given start_dt datetime obj using binary search. Only fast for files. Streams need to be forwarded manually, and it will miss the first line that would otherwise match (as it consumes the log line). """ i...
Fast-forward file to given start_dt datetime obj using binary search. Only fast for files. Streams need to be forwarded manually, and it will miss the first line that would otherwise match (as it consumes the log line).
def play_random(env, steps): """ Play the environment making uniformly random decisions. Args: env (gym.Env): the initialized gym environment to play steps (int): the number of random steps to take Returns: None """ try: done = True progress = tqdm(rang...
Play the environment making uniformly random decisions. Args: env (gym.Env): the initialized gym environment to play steps (int): the number of random steps to take Returns: None
def post_multipart(self, url, params, files): """ Generates and issues a multipart request for data files :param url: a string, the url you are requesting :param params: a dict, a key-value of all the parameters :param files: a dict, matching the form '{name: file descriptor}' ...
Generates and issues a multipart request for data files :param url: a string, the url you are requesting :param params: a dict, a key-value of all the parameters :param files: a dict, matching the form '{name: file descriptor}' :returns: a dict parsed from the JSON response
def update_configuration(self, **kwargs): """ Update the SNMP configuration using any kwargs supported in the `enable` constructor. Return whether a change was made. You must call update on the engine to commit any changes. :param dict kwargs: keyword arguments supported...
Update the SNMP configuration using any kwargs supported in the `enable` constructor. Return whether a change was made. You must call update on the engine to commit any changes. :param dict kwargs: keyword arguments supported by enable constructor :rtype: bool
def _region_from_key_id(key_id, default_region=None): """Determine the target region from a key ID, falling back to a default region if provided. :param str key_id: AWS KMS key ID :param str default_region: Region to use if no region found in key_id :returns: region name :rtype: str :raises Unk...
Determine the target region from a key ID, falling back to a default region if provided. :param str key_id: AWS KMS key ID :param str default_region: Region to use if no region found in key_id :returns: region name :rtype: str :raises UnknownRegionError: if no region found in key_id and no default_...
def regroup_vectorized(srccat, eps, far=None, dist=norm_dist): """ Regroup the islands of a catalog according to their normalised distance. Assumes srccat is recarray-like for efficiency. Return a list of island groups. Parameters ---------- srccat : np.rec.arry or pd.DataFrame Sho...
Regroup the islands of a catalog according to their normalised distance. Assumes srccat is recarray-like for efficiency. Return a list of island groups. Parameters ---------- srccat : np.rec.arry or pd.DataFrame Should have the following fields[units]: ra[deg],dec[deg], a[arcsec],b...
def get_message_type_by_id(self, message_type_id): """ Get a message type by message type ID :param message_type_id: is the message type that the client wants to retrieve """ self._validate_uuid(message_type_id) url = "/notification/v1/mes...
Get a message type by message type ID :param message_type_id: is the message type that the client wants to retrieve
def xmoe_2d(): """Two-dimensional hierarchical mixture of 16 experts.""" hparams = xmoe_top_2() hparams.decoder_layers = ["att", "hmoe"] * 4 hparams.mesh_shape = "b0:2;b1:4" hparams.outer_batch_size = 4 hparams.layout = "outer_batch:b0;inner_batch:b1,expert_x:b1,expert_y:b0" hparams.moe_num_experts = [4, ...
Two-dimensional hierarchical mixture of 16 experts.
def requires(self, i=0, end_=None): """ Returns a list of registers and variables this block requires. By default checks from the beginning (i = 0). :param i: initial position of the block to examine :param end_: final position to examine :returns: registers safe to write ...
Returns a list of registers and variables this block requires. By default checks from the beginning (i = 0). :param i: initial position of the block to examine :param end_: final position to examine :returns: registers safe to write
def _GetPrimitiveEncoder(self): """Finds the primitive encoder according to the type's data_store_type.""" # Decide what should the primitive type be for packing the target rdfvalue # into the protobuf and create a delegate descriptor to control that. primitive_cls = self._PROTO_DATA_STORE_LOOKUP[self.t...
Finds the primitive encoder according to the type's data_store_type.
def Parse(self, value): """Parse a 'Value' declaration. Args: value: String line from a template file, must begin with 'Value '. Raises: TextFSMTemplateError: Value declaration contains an error. """ value_line = value.split(' ') if len(value_line) < 3: raise TextFSMTemplat...
Parse a 'Value' declaration. Args: value: String line from a template file, must begin with 'Value '. Raises: TextFSMTemplateError: Value declaration contains an error.
def make_multi_qq_plots(arrays, key_text): """Make a quantile-quantile plot comparing multiple sets of events and models. *arrays* X. *key_text* Text describing the quantile-quantile comparison quantity; will be shown on the plot legend. Returns: An :class:`omega.RectPlot` insta...
Make a quantile-quantile plot comparing multiple sets of events and models. *arrays* X. *key_text* Text describing the quantile-quantile comparison quantity; will be shown on the plot legend. Returns: An :class:`omega.RectPlot` instance. *TODO*: nothing about this is Sherpa-spe...
def reqTickByTickData( self, contract: Contract, tickType: str, numberOfTicks: int = 0, ignoreSize: bool = False) -> Ticker: """ Subscribe to tick-by-tick data and return the Ticker that holds the ticks in ticker.tickByTicks. https://interactivebrokers.github.io/...
Subscribe to tick-by-tick data and return the Ticker that holds the ticks in ticker.tickByTicks. https://interactivebrokers.github.io/tws-api/tick_data.html Args: contract: Contract of interest. tickType: One of 'Last', 'AllLast', 'BidAsk' or 'MidPoint'. nu...
def normalize_operations(self, operations): """ Removes redundant SQL operations - e.g. a CREATE X followed by a DROP X """ normalized = OrderedDict() for operation in operations: op_key = (operation.sql_type, operation.obj_name) # do we already have an ...
Removes redundant SQL operations - e.g. a CREATE X followed by a DROP X
def playlist_song_delete(self, playlist_song): """Delete song from playlist. Parameters: playlist_song (str): A playlist song dict. Returns: dict: Playlist dict including songs. """ self.playlist_songs_delete([playlist_song]) return self.playlist(playlist_song['playlistId'], include_songs=True)
Delete song from playlist. Parameters: playlist_song (str): A playlist song dict. Returns: dict: Playlist dict including songs.
def command(self, group=None, help="", name=None): """Decorator for adding a command to this manager.""" def decorator(func): return self.add_command(func, group=group, help=help, name=name) return decorator
Decorator for adding a command to this manager.
def create_deepcopied_groupby_dict(orig_df, obs_id_col): """ Will create a dictionary where each key corresponds to a unique value in `orig_df[obs_id_col]` and each value corresponds to all of the rows of `orig_df` where `orig_df[obs_id_col] == key`. Parameters ---------- orig_df : pandas D...
Will create a dictionary where each key corresponds to a unique value in `orig_df[obs_id_col]` and each value corresponds to all of the rows of `orig_df` where `orig_df[obs_id_col] == key`. Parameters ---------- orig_df : pandas DataFrame. Should be long-format dataframe containing the data...
def add_tags(self, tags, **kwargs): """ :param tags: Tags to add to the analysis :type tags: list of strings Adds each of the specified tags to the analysis. Takes no action for tags that are already listed for the analysis. """ dxpy.api.analysis_add_tags(self....
:param tags: Tags to add to the analysis :type tags: list of strings Adds each of the specified tags to the analysis. Takes no action for tags that are already listed for the analysis.
def file_handles(self) -> Iterable[IO[str]]: """Generates all file handles represented by the analysis. Callee owns file handle and closes it when the next is yielded or the generator ends. """ if self.file_handle: yield self.file_handle self.file_handle.c...
Generates all file handles represented by the analysis. Callee owns file handle and closes it when the next is yielded or the generator ends.
def insert_param(self, param): """ Insert a parameter at the front of the parameter list. """ self._current_params = tuple([param] + list(self._current_params))
Insert a parameter at the front of the parameter list.
def to_utf8(str_or_unicode): """ Safely returns a UTF-8 version of a given string >>> utils.to_utf8(u'hi') 'hi' """ if not isinstance(str_or_unicode, six.text_type): return str_or_unicode.encode("utf-8", "ignore") return str(str_or_unicode)
Safely returns a UTF-8 version of a given string >>> utils.to_utf8(u'hi') 'hi'
def _extract_secrets_from_patch(self, f, plugin, filename): """Extract secrets from a given patch file object. Note that we only want to capture incoming secrets (so added lines). :type f: unidiff.patch.PatchedFile :type plugin: detect_secrets.plugins.base.BasePlugin :type file...
Extract secrets from a given patch file object. Note that we only want to capture incoming secrets (so added lines). :type f: unidiff.patch.PatchedFile :type plugin: detect_secrets.plugins.base.BasePlugin :type filename: str
def search_groups(self, args): """ Executes a search flickr:(credsfile),search,(arg1)=(val1),(arg2)=(val2)... """ kwargs = {'text': args[0]} return self._paged_api_call(self.flickr.groups_search, kwargs, 'group')
Executes a search flickr:(credsfile),search,(arg1)=(val1),(arg2)=(val2)...
def get_messages(self, *args, **kwargs): """Return a get_content generator for inbox (messages only). The additional parameters are passed directly into :meth:`.get_content`. Note: the `url` parameter cannot be altered. """ return self.get_content(self.config['messages'], *args...
Return a get_content generator for inbox (messages only). The additional parameters are passed directly into :meth:`.get_content`. Note: the `url` parameter cannot be altered.
def as_unicode(obj, encoding=convert.LOCALE, pretty=False): """ Representing any object to <unicode> string (python2.7) or <str> string (python3.0). :param obj: any object :type encoding: str :param encoding: codec for encoding unicode strings (locale.getpreferredencoding() by ...
Representing any object to <unicode> string (python2.7) or <str> string (python3.0). :param obj: any object :type encoding: str :param encoding: codec for encoding unicode strings (locale.getpreferredencoding() by default) :type pretty: bool :param pretty: pretty print :rt...
def reverse(self, point, language=None, sensor=False): '''Reverse geocode a point. Pls refer to the Google Maps Web API for the details of the parameters ''' params = { 'latlng': point, 'sensor': str(sensor).lower() } if language: ...
Reverse geocode a point. Pls refer to the Google Maps Web API for the details of the parameters
def add_child(self, value): """ Add a node as a child node. """ child = FPNode(value, 1, self) self.children.append(child) return child
Add a node as a child node.
def drop_columns(records, slices): """ Drop all columns present in ``slices`` from records """ for record in records: # Generate a set of indices to remove drop = set(i for slice in slices for i in range(*slice.indices(len(record)))) keep = [i not in drop for i...
Drop all columns present in ``slices`` from records
def get_container_metadata(self, container, prefix=None): """ Returns a dictionary containing the metadata for the container. """ return self._manager.get_metadata(container, prefix=prefix)
Returns a dictionary containing the metadata for the container.
def xml(self, indent=4, **kwargs): """ :return: this node as XML text. Delegates to :meth:`write` """ writer = StringIO() self.write(writer, indent=indent, **kwargs) return writer.getvalue()
:return: this node as XML text. Delegates to :meth:`write`
def render_output_pygraphviz(self, dotdata, **kwargs): """Render model data as image using pygraphviz""" if not HAS_PYGRAPHVIZ: raise CommandError("You need to install pygraphviz python module") version = pygraphviz.__version__.rstrip("-svn") try: if tuple(int(v)...
Render model data as image using pygraphviz
def from_csv(cls, path, folder, csv_fname, bs=64, tfms=(None,None), val_idxs=None, suffix='', test_name=None, continuous=False, skip_header=True, num_workers=8, cat_separator=' '): """ Read in images and their labels given as a CSV file. This method should be used when training image lab...
Read in images and their labels given as a CSV file. This method should be used when training image labels are given in an CSV file as opposed to sub-directories with label names. Arguments: path: a root path of the data (used for storing trained models, precomputed values, etc) ...
def select_action(self, nb_actions, probs): """Return the selected action # Arguments probs (np.ndarray) : Probabilty for each action # Returns action """ action = np.random.choice(range(nb_actions), p=probs) return action
Return the selected action # Arguments probs (np.ndarray) : Probabilty for each action # Returns action
def path_segments(self, value=None): """ Return the path segments :param list value: the new path segments to use """ if value is not None: encoded_values = map(unicode_quote_path_segment, value) new_path = '/' + '/'.join(encoded_values) retur...
Return the path segments :param list value: the new path segments to use
def encode_safely(self, data): """Encode the data. """ encoder = self.base_encoder result = settings.null try: result = encoder(pickle.dumps(data)) except: warnings.warn("Data could not be serialized.", RuntimeWarning) return resu...
Encode the data.
def olindex(order, dim): """ Create an lexiographical sorted basis for a given order. Examples -------- >>> chaospy.bertran.olindex(3, 2) array([[0, 3], [1, 2], [2, 1], [3, 0]]) """ idxm = [0]*dim out = [] def _olindex(idx): """Recursive...
Create an lexiographical sorted basis for a given order. Examples -------- >>> chaospy.bertran.olindex(3, 2) array([[0, 3], [1, 2], [2, 1], [3, 0]])
def login_required(function=None): """ Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary. """ def check_perms(user): # if user not logged in, show login form if not user.is_authenticated: return False # if this...
Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary.
def get_corner(hdr, rsize=1): """Obtain bin and corner information for a subarray. ``LTV1``, ``LTV2``, ``LTM1_1``, and ``LTM2_2`` keywords are extracted from the given extension header and converted to bin and corner values (0-indexed). ``LTV1`` for the CCD uses the beginning of the illuminated ...
Obtain bin and corner information for a subarray. ``LTV1``, ``LTV2``, ``LTM1_1``, and ``LTM2_2`` keywords are extracted from the given extension header and converted to bin and corner values (0-indexed). ``LTV1`` for the CCD uses the beginning of the illuminated portion as the origin, not the begi...
def setStimDuration(self): """Sets the duration of the StimulusModel from values pulled from this widget""" duration = self.ui.durSpnbx.value() self.tone.setDuration(duration)
Sets the duration of the StimulusModel from values pulled from this widget
def print_peer(self, peer, show_id=True, id_prefix="", reply=True): """ :param id_prefix: Prefix of the #id thing. Set a string, or true to have it generated. :type id_prefix: str|bool """ if isinstance(id_prefix, bool): if id_prefix: # True if isins...
:param id_prefix: Prefix of the #id thing. Set a string, or true to have it generated. :type id_prefix: str|bool
def update_resource(zone, resource_type, resource_selector, **kwargs): ''' Add a resource zone : string name of zone resource_type : string type of resource resource_selector : string unique resource identifier kwargs : string|int|... resource properties .. ...
Add a resource zone : string name of zone resource_type : string type of resource resource_selector : string unique resource identifier kwargs : string|int|... resource properties .. note:: Set resource_selector to None for resource that do not require one. ...
def get_state_actions(self, state, **kwargs): """ For dependent items, inherits the behavior from :class:`dockermap.map.action.resume.ResumeActionGenerator`. For other the main container, checks if containers exist, and depending on the ``remove_existing_before`` option either fails or r...
For dependent items, inherits the behavior from :class:`dockermap.map.action.resume.ResumeActionGenerator`. For other the main container, checks if containers exist, and depending on the ``remove_existing_before`` option either fails or removes them. Otherwise runs the script. :param state: Con...
def copy( ctx, opts, owner_repo_package, destination, skip_errors, wait_interval, no_wait_for_sync, sync_attempts, ): """ Copy a package to another repository. This requires appropriate permissions for both the source repository/package and the destination repository. ...
Copy a package to another repository. This requires appropriate permissions for both the source repository/package and the destination repository. - OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the REPO name where the package is stored, and the PACKAGE name (slug) of the pac...
def checkArgs(args): """Checks the arguments and options. :param args: an object containing the options of the program. :type args: argparse.Namespace :returns: ``True`` if everything was OK. If there is a problem with an option, an exception is raised using the :py:class:`ProgramError` clas...
Checks the arguments and options. :param args: an object containing the options of the program. :type args: argparse.Namespace :returns: ``True`` if everything was OK. If there is a problem with an option, an exception is raised using the :py:class:`ProgramError` class, a message is printed to t...
def _transform(self, X): """Asssume X contains only categorical features. Parameters ---------- X : array-like or sparse matrix, shape=(n_samples, n_features) Dense array or sparse matrix. """ X = self._matrix_adjust(X) X = check_array(X, accept_spar...
Asssume X contains only categorical features. Parameters ---------- X : array-like or sparse matrix, shape=(n_samples, n_features) Dense array or sparse matrix.
def unpack(self, buff, offset=0): """Unpack a binary message into this object's attributes. Unpack the binary value *buff* and update this object attributes based on the results. Ethernet headers may have VLAN tags. If no VLAN tag is found, a 'wildcard VLAN tag' is inserted to ...
Unpack a binary message into this object's attributes. Unpack the binary value *buff* and update this object attributes based on the results. Ethernet headers may have VLAN tags. If no VLAN tag is found, a 'wildcard VLAN tag' is inserted to assure correct unpacking. Args: ...
def _instruction_getter(self, name, env_replace): """ Get LABEL or ENV instructions with environment replacement :param name: e.g. 'LABEL' or 'ENV' :param env_replace: bool, whether to perform ENV substitution :return: Labels instance or Envs instance """ if name...
Get LABEL or ENV instructions with environment replacement :param name: e.g. 'LABEL' or 'ENV' :param env_replace: bool, whether to perform ENV substitution :return: Labels instance or Envs instance
def op(name, data, bucket_count=None, display_name=None, description=None, collections=None): """Create a legacy histogram summary op. Arguments: name: A unique name for the generated summary node. data: A `Tensor` of any shape. Must be castable to `float64`. bucket_c...
Create a legacy histogram summary op. Arguments: name: A unique name for the generated summary node. data: A `Tensor` of any shape. Must be castable to `float64`. bucket_count: Optional positive `int`. The output will have this many buckets, except in two edge cases. If there is no data, then ...
def to_deeper_graph(graph): ''' deeper graph ''' weighted_layer_ids = graph.deep_layer_ids() if len(weighted_layer_ids) >= Constant.MAX_LAYERS: return None deeper_layer_ids = sample(weighted_layer_ids, 1) for layer_id in deeper_layer_ids: layer = graph.layer_list[layer_id] ...
deeper graph
def to_(self, attrvals): """ Create a list of Attribute instances. :param attrvals: A dictionary of attributes and values :return: A list of Attribute instances """ attributes = [] for key, value in attrvals.items(): name = self._to.get(key.lower()) ...
Create a list of Attribute instances. :param attrvals: A dictionary of attributes and values :return: A list of Attribute instances
def add_page(self, title=None, content=None, old_url=None, tags=None, old_id=None, old_parent_id=None): """ Adds a page to the list of pages to be imported - used by the Wordpress importer. """ if not title: text = decode_entities(strip_tags(content))...
Adds a page to the list of pages to be imported - used by the Wordpress importer.
def set_alphabet(self, alphabet): """Set the alphabet to be used for new UUIDs.""" # Turn the alphabet into a set and sort it to prevent duplicates # and ensure reproducibility. new_alphabet = list(sorted(set(alphabet))) if len(new_alphabet) > 1: self._alphabet = new...
Set the alphabet to be used for new UUIDs.
def add_simmanager_api(self, mock): '''Add org.ofono.SimManager API to a mock''' iface = 'org.ofono.SimManager' mock.AddProperties(iface, { 'BarredDialing': _parameters.get('BarredDialing', False), 'CardIdentifier': _parameters.get('CardIdentifier', new_iccid(self)), 'FixedDialing':...
Add org.ofono.SimManager API to a mock
def do_search(self, arg): """ [~process] s [address-address] <search string> [~process] search [address-address] <search string> """ token_list = self.split_tokens(arg, 1, 3) pid, tid = self.get_process_and_thread_ids_from_prefix() process = self.get_process(...
[~process] s [address-address] <search string> [~process] search [address-address] <search string>
def get_newest_commit_date(self): ''' Get datetime of newest commit involving this file :returns: Datetime of newest commit ''' newest_commit = self.get_newest_commit() return self.git.get_commit_date(newest_commit, self.tz_name)
Get datetime of newest commit involving this file :returns: Datetime of newest commit
def hacking_python3x_print_function(logical_line, noqa): r"""Check that all print occurrences look like print functions. Check that all occurrences of print look like functions, not print operator. As of Python 3.x, the print operator has been removed. Okay: print(msg) Okay: print (msg) O...
r"""Check that all print occurrences look like print functions. Check that all occurrences of print look like functions, not print operator. As of Python 3.x, the print operator has been removed. Okay: print(msg) Okay: print (msg) Okay: print msg # noqa Okay: print() H233: print msg ...
def runPlink(options): """Run Plink with the ``mind`` option. :param options: the options. :type options: argparse.Namespace """ # The plink command plinkCommand = [ "plink", "--noweb", "--bfile" if options.is_bfile else "--tfile", options.ifile, "--min...
Run Plink with the ``mind`` option. :param options: the options. :type options: argparse.Namespace
def get_child_repository_ids(self, repository_id): """Gets the ``Ids`` of the children of the given repository. arg: repository_id (osid.id.Id): the ``Id`` to query return: (osid.id.IdList) - the children of the repository raise: NotFound - ``repository_id`` not found raise:...
Gets the ``Ids`` of the children of the given repository. arg: repository_id (osid.id.Id): the ``Id`` to query return: (osid.id.IdList) - the children of the repository raise: NotFound - ``repository_id`` not found raise: NullArgument - ``repository_id`` is ``null`` raise: ...
def ua_string(praw_info): """Return the user-agent string. The user-agent string contains PRAW version and platform version info. """ if os.environ.get('SERVER_SOFTWARE') is not None: # Google App Engine information # https://developers.google.com/appengine/docs...
Return the user-agent string. The user-agent string contains PRAW version and platform version info.
def from_database(cls, database): """Initialize migrator by db.""" if isinstance(database, PostgresqlDatabase): return PostgresqlMigrator(database) if isinstance(database, SqliteDatabase): return SqliteMigrator(database) if isinstance(database, MySQLDatabase): ...
Initialize migrator by db.
def getlines(fname): """ Returns iterator of whitespace-stripped lines in file, omitting blank lines, lines beginning with '#', and line contents following the first '#' character. """ with open(fname, 'rU') as f: for line in f: if line.strip() and not line.startswith('#'): ...
Returns iterator of whitespace-stripped lines in file, omitting blank lines, lines beginning with '#', and line contents following the first '#' character.
async def pfmerge(self, dest, *sources): """ Merge N different HyperLogLogs into a single one. Cluster impl: Very special implementation is required to make pfmerge() work But it works :] It works by first fetching all HLL objects that should be merged and ...
Merge N different HyperLogLogs into a single one. Cluster impl: Very special implementation is required to make pfmerge() work But it works :] It works by first fetching all HLL objects that should be merged and move them to one hashslot so that pfmerge operation...
def list_tables(self): ''' Load existing tables and their descriptions. :return: ''' if not self._tables: for table_name in os.listdir(self.db_path): self._tables[table_name] = self._load_table(table_name) return self._tables.keys()
Load existing tables and their descriptions. :return:
def get_attributes(self): """ Returns the Node attributes. Usage:: >>> node_a = AbstractNode("MyNodeA", attributeA=Attribute(value="A"), attributeB=Attribute(value="B")) >>> node_a.get_attributes() [<Attribute object at 0x7fa471d3b5e0>, <Attribute object at ...
Returns the Node attributes. Usage:: >>> node_a = AbstractNode("MyNodeA", attributeA=Attribute(value="A"), attributeB=Attribute(value="B")) >>> node_a.get_attributes() [<Attribute object at 0x7fa471d3b5e0>, <Attribute object at 0x101e6c4a0>] :return: Attributes. ...
def get_xy_simple_dipole_dipole(dataframe, spacing=1, indices=None): """For each configuration indicated by the numerical index array, compute (x,z) pseudo locations based on the paper from XX. All positions are computed for indices=None. """ if indices is None: indices = slice(None) ab...
For each configuration indicated by the numerical index array, compute (x,z) pseudo locations based on the paper from XX. All positions are computed for indices=None.
def load_all_available_checkers(cls): """ Helper method to retrieve all sub checker classes derived from various base classes. """ for x in working_set.iter_entry_points('compliance_checker.suites'): try: xl = x.resolve() cls.checkers['...
Helper method to retrieve all sub checker classes derived from various base classes.
def geo_point_n(arg, n): """Return the Nth point in a single linestring in the geometry. Negative values are counted backwards from the end of the LineString, so that -1 is the last point. Returns NULL if there is no linestring in the geometry Parameters ---------- arg : geometry n : in...
Return the Nth point in a single linestring in the geometry. Negative values are counted backwards from the end of the LineString, so that -1 is the last point. Returns NULL if there is no linestring in the geometry Parameters ---------- arg : geometry n : integer Returns ------- ...
def extract_spectra_from_file( log, pathToSpectrum, convertLumToFlux=False): """ *Given a spectrum file this function shall convert the two columns (wavelength and luminosity) to a wavelegnth (wavelengthArray) and flux (fluxArray) array* **Key Arguments:** - ``log`` -- logge...
*Given a spectrum file this function shall convert the two columns (wavelength and luminosity) to a wavelegnth (wavelengthArray) and flux (fluxArray) array* **Key Arguments:** - ``log`` -- logger - ``pathToSpectrum`` -- absolute path the the spectrum file **Return:** - None
def replace_gist_tags(generator): """Replace gist tags in the article content.""" from jinja2 import Template template = Template(gist_template) should_cache = generator.context.get('GIST_CACHE_ENABLED') cache_location = generator.context.get('GIST_CACHE_LOCATION') pygments_style = generator.co...
Replace gist tags in the article content.
def compare_hexdigests( digest1, digest2 ): """Compute difference in bits between digest1 and digest2 returns -127 to 128; 128 is the same, -127 is different""" # convert to 32-tuple of unsighed two-byte INTs digest1 = tuple([int(digest1[i:i+2],16) for i in range(0,63,2)]) digest2 = tuple([int(di...
Compute difference in bits between digest1 and digest2 returns -127 to 128; 128 is the same, -127 is different
def index_objects(mapping_type, ids, chunk_size=100, es=None, index=None): """Index documents of a specified mapping type. This allows for asynchronous indexing. If a mapping_type extends Indexable, you can add a ``post_save`` hook for the model that it's based on like this:: @receiver(dbsign...
Index documents of a specified mapping type. This allows for asynchronous indexing. If a mapping_type extends Indexable, you can add a ``post_save`` hook for the model that it's based on like this:: @receiver(dbsignals.post_save, sender=MyModel) def update_in_index(sender, instance, **kw)...
def bias_ratio(self, positive_or_negative=False): """ 判斷乖離 :param bool positive_or_negative: 正乖離 為 True,負乖離 為 False """ return self.data.check_moving_average_bias_ratio( self.data.moving_average_bias_ratio(3, 6)[0], posit...
判斷乖離 :param bool positive_or_negative: 正乖離 為 True,負乖離 為 False
def validate_locked(self, authc_token, failed_attempts): """ :param failed_attempts: the failed attempts for this type of credential """ if self.locking_limit and len(failed_attempts) > self.locking_limit: msg = ('Authentication attempts breached threshold. Account' ...
:param failed_attempts: the failed attempts for this type of credential
def parse_out(self, fo): """ Convert MotifSampler output to motifs Parameters ---------- fo : file-like File object containing MotifSampler output. Returns ------- motifs : list List of Motif instances. """ ...
Convert MotifSampler output to motifs Parameters ---------- fo : file-like File object containing MotifSampler output. Returns ------- motifs : list List of Motif instances.
def run_preassembly_duplicate(preassembler, beliefengine, **kwargs): """Run deduplication stage of preassembly on a list of statements. Parameters ---------- preassembler : indra.preassembler.Preassembler A Preassembler instance beliefengine : indra.belief.BeliefEngine A BeliefEngin...
Run deduplication stage of preassembly on a list of statements. Parameters ---------- preassembler : indra.preassembler.Preassembler A Preassembler instance beliefengine : indra.belief.BeliefEngine A BeliefEngine instance. save : Optional[str] The name of a pickle file to sa...
def _get_arch(): """ Determines the current processor architecture. @rtype: str @return: On error, returns: - L{ARCH_UNKNOWN} (C{"unknown"}) meaning the architecture could not be detected or is not known to WinAppDbg. On success, returns one of the following values: ...
Determines the current processor architecture. @rtype: str @return: On error, returns: - L{ARCH_UNKNOWN} (C{"unknown"}) meaning the architecture could not be detected or is not known to WinAppDbg. On success, returns one of the following values: - L{ARCH_I386} (C{"i386"}) f...
def get_qualification_score(self, qualification_type_id, worker_id): """TODO: Document.""" params = {'QualificationTypeId' : qualification_type_id, 'SubjectId' : worker_id} return self._process_request('GetQualificationScore', params, [('Qualification', Qual...
TODO: Document.
def fix_lockfile(self): """Run each line of outfile through fix_pin""" with open(self.outfile, 'rt') as fp: lines = [ self.fix_pin(line) for line in self.concatenated(fp) ] with open(self.outfile, 'wt') as fp: fp.writelines([ ...
Run each line of outfile through fix_pin
def _writeImage(dataArray=None, inputHeader=None): """ Writes out the result of the combination step. The header of the first 'outsingle' file in the association parlist is used as the header of the new image. Parameters ---------- dataArray : arr Array o...
Writes out the result of the combination step. The header of the first 'outsingle' file in the association parlist is used as the header of the new image. Parameters ---------- dataArray : arr Array of data to be written to a fits.PrimaryHDU object i...
def convert_unicode(value): """Resolves python 2 issue with json loading in unicode instead of string Args: value (str): Unicode value to be converted Returns: (str): converted string """ if isinstance(value, dict): return {convert_unicode(key): convert_unicode(value) ...
Resolves python 2 issue with json loading in unicode instead of string Args: value (str): Unicode value to be converted Returns: (str): converted string
def block(bdaddr): ''' Block a specific bluetooth device by BD Address CLI Example: .. code-block:: bash salt '*' bluetooth.block DE:AD:BE:EF:CA:FE ''' if not salt.utils.validate.net.mac(bdaddr): raise CommandExecutionError( 'Invalid BD address passed to bluetooth....
Block a specific bluetooth device by BD Address CLI Example: .. code-block:: bash salt '*' bluetooth.block DE:AD:BE:EF:CA:FE
def hide_ticks(plot, min_tick_value=None, max_tick_value=None): """Hide tick values that are outside of [min_tick_value, max_tick_value]""" for tick, tick_value in zip(plot.get_yticklabels(), plot.get_yticks()): tick_label = as_numeric(tick_value) if tick_label: if (min_tick_value is...
Hide tick values that are outside of [min_tick_value, max_tick_value]
def _build_search_query(self, from_date): """Build an ElasticSearch search query to retrieve items for read methods. :param from_date: date to start retrieving items from. :return: JSON query in dict format """ sort = [{self._sort_on_field: {"order": "asc"}}] filters =...
Build an ElasticSearch search query to retrieve items for read methods. :param from_date: date to start retrieving items from. :return: JSON query in dict format
def get_toc(self, subchapters=False): """ Returns table-of-contents information extracted from the PDF doc. When `subchapters=False`, the output is a list of this form .. code-block:: python [ {'title': 'First chapter', 'page_start': 0, 'page_end': 10}, ...
Returns table-of-contents information extracted from the PDF doc. When `subchapters=False`, the output is a list of this form .. code-block:: python [ {'title': 'First chapter', 'page_start': 0, 'page_end': 10}, {'title': 'Second chapter', 'page_start': 10...
def _cov_for(self, imls): """ Clip `imls` to the range associated with the support of the vulnerability function and returns the corresponding covariance values by linear interpolation. For instance if the range is [0.005, 0.0269] and the imls are [0.0049, 0.006, 0.027], ...
Clip `imls` to the range associated with the support of the vulnerability function and returns the corresponding covariance values by linear interpolation. For instance if the range is [0.005, 0.0269] and the imls are [0.0049, 0.006, 0.027], the clipped imls are [0.005, 0.006, 0...
def delete(self, request, uri): """ Delete versioned uri and return empty text response on success. """ uri = self.decode_uri(uri) uris = cio.delete(uri) if uri not in uris: raise Http404 return self.render_to_response()
Delete versioned uri and return empty text response on success.
def _rows_from_json(values, schema): """Convert JSON row data to rows with appropriate types.""" from google.cloud.bigquery import Row field_to_index = _field_to_index_mapping(schema) return [Row(_row_tuple_from_json(r, schema), field_to_index) for r in values]
Convert JSON row data to rows with appropriate types.
def get_account_certificate(self, account_id, cert_id, **kwargs): # noqa: E501 """Get trusted certificate by ID. # noqa: E501 An endpoint for retrieving a trusted certificate by ID. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/trusted-certificates/{cert-id} -...
Get trusted certificate by ID. # noqa: E501 An endpoint for retrieving a trusted certificate by ID. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/trusted-certificates/{cert-id} -H 'Authorization: Bearer API_KEY'` # noqa: E501 This method makes a synchronous HT...
def queue_push(self, key, value, create=False, **kwargs): """ Add an item to the end of a queue. :param key: The document ID of the queue :param value: The item to add to the queue :param create: Whether the queue should be created if it does not exist :param kwargs: Arg...
Add an item to the end of a queue. :param key: The document ID of the queue :param value: The item to add to the queue :param create: Whether the queue should be created if it does not exist :param kwargs: Arguments to pass to :meth:`mutate_in` :return: :class:`OperationResult` ...
def generate_transpose(node_name, in_name, out_name, axes, base_name, func_counter): """Generate a Transpose operator to transpose the specified buffer. """ trans = nnabla_pb2.Function() trans.type = "Transpose" set_function_name(trans, node_name, base_name, func_counter) trans.input.extend([in_...
Generate a Transpose operator to transpose the specified buffer.
def collect_impl(self): """ overrides DistJarChange and DistClassChange from the underlying DistChange with DistJarReport and DistClassReport instances """ for c in DistChange.collect_impl(self): if isinstance(c, DistJarChange): if c.is_change(): ...
overrides DistJarChange and DistClassChange from the underlying DistChange with DistJarReport and DistClassReport instances
def _get_jvm_opts(config, tmp_dir): """Retrieve common options for running VarScan. Handles jvm_opts, setting user and country to English to avoid issues with different locales producing non-compliant VCF. """ resources = config_utils.get_resources("varscan", config) jvm_opts = resources.get("jv...
Retrieve common options for running VarScan. Handles jvm_opts, setting user and country to English to avoid issues with different locales producing non-compliant VCF.
def draw_points(self, *points): """Draw multiple points on the current rendering target. Args: *points (Point): The points to draw. Raises: SDLError: If an error is encountered. """ point_array = ffi.new('SDL_Point[]', len(points)) for i, p in en...
Draw multiple points on the current rendering target. Args: *points (Point): The points to draw. Raises: SDLError: If an error is encountered.
def from_json(cls, json): """Deserialize from json. Args: json: a dict of json compatible fields. Returns: a KeyRanges object. Raises: ValueError: if the json is invalid. """ if json["name"] in _KEYRANGES_CLASSES: return _KEYRANGES_CLASSES[json["name"]].from_json(json)...
Deserialize from json. Args: json: a dict of json compatible fields. Returns: a KeyRanges object. Raises: ValueError: if the json is invalid.