code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def from_json(json): """Creates a Track from a JSON file. No preprocessing is done. Arguments: json: map with the keys: name (optional) and segments. Return: A track instance """ segments = [Segment.from_json(s) for s in json['segments']] ...
Creates a Track from a JSON file. No preprocessing is done. Arguments: json: map with the keys: name (optional) and segments. Return: A track instance
def create_connection(self, from_obj, to_obj): """ Creates and returns a connection between the given objects. If a connection already exists, that connection will be returned instead. """ self._validate_ctypes(from_obj, to_obj) return Connection.objects.get_or_create(rel...
Creates and returns a connection between the given objects. If a connection already exists, that connection will be returned instead.
def get_pandas_series(self): """The function creates pandas series based on index and values""" return pandas.Series(self.values, self.index, name=self.name)
The function creates pandas series based on index and values
def badges(request): ''' Either displays a form containing a list of users with badges to render, or returns a .zip file containing their badges. ''' category = request.GET.getlist("category", []) product = request.GET.getlist("product", []) status = request.GET.get("status") form = forms.Invo...
Either displays a form containing a list of users with badges to render, or returns a .zip file containing their badges.
def _create_skt(self): ''' Create the authentication socket. ''' log.debug('Creating the auth socket') if ':' in self.auth_address: self.socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) else: self.socket = socket.socket(socket.AF_INET, s...
Create the authentication socket.
def keypress(self, size, key): """allow subclasses to intercept keystrokes""" key = self.__super.keypress(size, key) if key: key = self.unhandled_keys(size, key) return key
allow subclasses to intercept keystrokes
def find_hwpack_dir(root): """search for hwpack dir under root.""" root = path(root) log.debug('files in dir: %s', root) for x in root.walkfiles(): log.debug(' %s', x) hwpack_dir = None for h in (root.walkfiles('boards.txt')): assert not hwpack_dir hwpack_dir = h.parent...
search for hwpack dir under root.
def convolve_image(image, kernel_image, crop=True): """ Convolve one image with another ANTsR function: `convolveImage` Arguments --------- image : ANTsImage image to convolve kernel_image : ANTsImage image acting as kernel crop : boolean whether to automatica...
Convolve one image with another ANTsR function: `convolveImage` Arguments --------- image : ANTsImage image to convolve kernel_image : ANTsImage image acting as kernel crop : boolean whether to automatically crop kernel_image Returns ------- ANTsImage ...
def rawDataReceived(self, data): """ Process data. Args: data (str): Incoming data """ if self._len_expected is not None: data, extra = data[:self._len_expected], data[self._len_expected:] self._len_expected -= len(data) else: extr...
Process data. Args: data (str): Incoming data
def init_app(self, app): """Initializes Journey extension :param app: App passed from constructor or directly to init_app :raises: - NoBundlesAttached if no bundles has been attached attached """ if len(self._attached_bundles) == 0: raise NoBundlesAttac...
Initializes Journey extension :param app: App passed from constructor or directly to init_app :raises: - NoBundlesAttached if no bundles has been attached attached
def visibleRows(self): # onscreen rows 'List of rows onscreen. ' return self.rows[self.topRowIndex:self.topRowIndex+self.nVisibleRows]
List of rows onscreen.
def protocol_authenticate(self, account=None): """ Low-level API to perform protocol-level authentication on protocols that support it. .. HINT:: In most cases, you want to use the login() method instead, as it automatically chooses the best login method for each p...
Low-level API to perform protocol-level authentication on protocols that support it. .. HINT:: In most cases, you want to use the login() method instead, as it automatically chooses the best login method for each protocol. :type account: Account :param account: A...
def _generate_examples(self, data_path): """Generate MovingMnist sequences. Args: data_path (str): Path to the data file Yields: 20 x 64 x 64 x 1 uint8 numpy arrays """ with tf.io.gfile.GFile(data_path, "rb") as fp: images = np.load(fp) images = np.transpose(images, (1, 0, 2,...
Generate MovingMnist sequences. Args: data_path (str): Path to the data file Yields: 20 x 64 x 64 x 1 uint8 numpy arrays
def upload_receipt(self, url, data): """Upload a receipt to the give url :param url: :param data: :return: """ return self.upload_attachment(url=url, data=data, mime_type='application/vnd.mcash.receipt.v1+json')
Upload a receipt to the give url :param url: :param data: :return:
def add_token(self, token_identifier, delegation_token): """ Parameters: - token_identifier - delegation_token """ self.send_add_token(token_identifier, delegation_token) return self.recv_add_token()
Parameters: - token_identifier - delegation_token
def InitializeContext(self, args): """Initializes the context of this flow.""" if args is None: args = rdf_flow_runner.FlowRunnerArgs() output_plugins_states = [] for plugin_descriptor in args.output_plugins: if not args.client_id: self.Log( "Not initializing output plug...
Initializes the context of this flow.
def load(self): """ Loads the shop details and current inventory Raises parseException """ pg = self.usr.getPage("http://www.neopets.com/market.phtml?type=your") try: self.name = pg.find_all(text = "Shop Till")[1].parent.parent.parent.p...
Loads the shop details and current inventory Raises parseException
def getusers(self, search=None, page=1, per_page=20, **kwargs): """ Returns a list of users from the Gitlab server .. warning:: Warning this is being deprecated please use :func:`gitlab.Gitlab.get_users` :param search: Optional search query :param page: Page number (default: 1)...
Returns a list of users from the Gitlab server .. warning:: Warning this is being deprecated please use :func:`gitlab.Gitlab.get_users` :param search: Optional search query :param page: Page number (default: 1) :param per_page: Number of items to list per page (default: 20, max: 100) ...
def remove_header(self, header_name): """Remove ``header_name`` from this request. """ val1 = self.headers.pop(header_name, None) val2 = self.unredirected_headers.pop(header_name, None) return val1 or val2
Remove ``header_name`` from this request.
def get_object(self): """ Returns the object the view is displaying. You may want to override this if you need to provide non-standard queryset lookups. Eg if objects are referenced using multiple keyword arguments in the url conf. :return: An instance of the view's model. ...
Returns the object the view is displaying. You may want to override this if you need to provide non-standard queryset lookups. Eg if objects are referenced using multiple keyword arguments in the url conf. :return: An instance of the view's model.
def hacking_todo_format(physical_line, tokens): """Check for 'TODO()'. OpenStack HACKING guide recommendation for TODO: Include your name with TODOs as in "# TODO(termie)" Okay: # TODO(sdague) H101: # TODO fail H101: # TODO H101: # TODO (jogo) fail Okay: TODO = 5 """ # TODO(jog...
Check for 'TODO()'. OpenStack HACKING guide recommendation for TODO: Include your name with TODOs as in "# TODO(termie)" Okay: # TODO(sdague) H101: # TODO fail H101: # TODO H101: # TODO (jogo) fail Okay: TODO = 5
def check_errors(self): ''' Check if errors occured during a latex run by scanning the output. ''' errors = ERROR_PATTTERN.findall(self.out) # "errors" is a list of tuples if errors: self.log.error('! Errors occurred:') self.log.error('\n'...
Check if errors occured during a latex run by scanning the output.
def start(self): """ Start database worker threads """ # give a nice name to the process w.setproctitle('oq-dbserver') dworkers = [] for _ in range(self.num_workers): sock = z.Socket(self.backend, z.zmq.REP, 'connect') threading.Thread(tar...
Start database worker threads
def loads(json_data, encoding="utf-8", **kwargs): """ Custom loads function with an object_hook and automatic decoding Parameters ---------- json_data : str The JSON data to decode *args Positional arguments, passed to :func:`json.loads` encoding : :obj:`str`, optional ...
Custom loads function with an object_hook and automatic decoding Parameters ---------- json_data : str The JSON data to decode *args Positional arguments, passed to :func:`json.loads` encoding : :obj:`str`, optional The encoding of the bytestring **kwargs Keyword...
def owner(self, owner): """ Sets the owner of this LinkedDatasetCreateOrUpdateRequest. User name and unique identifier of the creator of the dataset. :param owner: The owner of this LinkedDatasetCreateOrUpdateRequest. :type: str """ if owner is None: ...
Sets the owner of this LinkedDatasetCreateOrUpdateRequest. User name and unique identifier of the creator of the dataset. :param owner: The owner of this LinkedDatasetCreateOrUpdateRequest. :type: str
def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname ...
Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf...
def count(self): "Return how many nodes this contains, including self." if self._nodes is None: return 1 return sum(i.count() for i in self._nodes)
Return how many nodes this contains, including self.
def set_focus(self, position): """Set the focus to position or raise IndexError.""" self._focus_position = position self._modified() # If we set focus to anywhere but the last position, the user if # scrolling up: try: self.next_position(position) exce...
Set the focus to position or raise IndexError.
def get_keycode(conn, keysym): """ Given a keysym, find the keycode mapped to it in the current X environment. It is necessary to search the keysym table in order to do this, including all columns. :param keysym: An X keysym. :return: A keycode or None if one could not be found. :rtype: int...
Given a keysym, find the keycode mapped to it in the current X environment. It is necessary to search the keysym table in order to do this, including all columns. :param keysym: An X keysym. :return: A keycode or None if one could not be found. :rtype: int
def rpc_get_namespace_blockchain_record( self, namespace_id, **con_info ): """ Return the namespace with the given namespace_id Return {'status': True, 'record': ...} on success Return {'error': ...} on error """ if not check_namespace(namespace_id): return {...
Return the namespace with the given namespace_id Return {'status': True, 'record': ...} on success Return {'error': ...} on error
def _federation_indicators(catalog, central_catalog, identifier_search=False): """Cuenta la cantidad de datasets incluídos tanto en la lista 'catalogs' como en el catálogo central, y genera indicadores a partir de esa información. Args: catalog (dict): catálogo ya par...
Cuenta la cantidad de datasets incluídos tanto en la lista 'catalogs' como en el catálogo central, y genera indicadores a partir de esa información. Args: catalog (dict): catálogo ya parseado central_catalog (str o dict): ruta a catálogo central, o un dict con el catálogo ya par...
def TimeToSecondsSinceMidnight(time_string): """Convert HHH:MM:SS into seconds since midnight. For example "01:02:03" returns 3723. The leading zero of the hours may be omitted. HH may be more than 23 if the time is on the following day.""" m = re.match(r'(\d{1,3}):([0-5]\d):([0-5]\d)$', time_string) # ignor...
Convert HHH:MM:SS into seconds since midnight. For example "01:02:03" returns 3723. The leading zero of the hours may be omitted. HH may be more than 23 if the time is on the following day.
def project(self, projected_meta=None, new_attr_dict=None, all_but_meta=None, projected_regs=None, new_field_dict=None, all_but_regs=None): """ *Wrapper of* ``PROJECT`` The PROJECT operator creates, from an existing dataset, a new dataset with all the samples (with their...
*Wrapper of* ``PROJECT`` The PROJECT operator creates, from an existing dataset, a new dataset with all the samples (with their regions and region values) in the input one, but keeping for each sample in the input dataset only those metadata and/or region attributes expressed in the operator pa...
def listsdelete(x, xs): """Return a new list with x removed from xs""" i = xs.index(x) return xs[:i] + xs[(i+1):]
Return a new list with x removed from xs
def make_map(declarations): """Process route declarations to create a Route Mapper.""" mapper = routes.Mapper() for route, methods in ROUTE_LIST: allowed_methods = [] for method, func in methods.items(): mapper.connect(route, action=func, conditions=dic...
Process route declarations to create a Route Mapper.
def execute(self, input_data): """This worker puts the output of pe_features into a dictionary of dataframes""" if 'sample' in input_data: print 'Warning: PEFeaturesDF is supposed to be called on a sample_set' self.samples.append(input_data['sample']['md5']) else: ...
This worker puts the output of pe_features into a dictionary of dataframes
def monochrome(clr): """ Returns colors in the same hue with varying brightness/saturation. """ def _wrap(x, min, threshold, plus): if x - min < threshold: return x + plus else: return x - min colors = colorlist(clr) c = clr.copy() c.brightness = _wr...
Returns colors in the same hue with varying brightness/saturation.
def get_parser(): """Argument specifier. """ parser = argparse.ArgumentParser(prog='pyradigm') parser.add_argument('path_list', nargs='*', action='store', default=None, help='List of paths to display info about.') parser.add_argument('-m', '--meta', action='store_true', d...
Argument specifier.
def import_image(self, name, tags=None): """ Import image tags from a Docker registry into an ImageStream :return: bool, whether tags were imported """ stream_import_file = os.path.join(self.os_conf.get_build_json_store(), 'image_stream_...
Import image tags from a Docker registry into an ImageStream :return: bool, whether tags were imported
def host(self, hostname, owner=None, **kwargs): """ Create the Host TI object. Args: owner: hostname: **kwargs: Return: """ return Host(self.tcex, hostname, owner=owner, **kwargs)
Create the Host TI object. Args: owner: hostname: **kwargs: Return:
def _rfind(expr, sub, start=0, end=None): """ Return highest indexes in each strings in the sequence or scalar where the substring is fully contained between [start:end]. Return -1 on failure. Equivalent to standard str.rfind(). :param expr: :param sub: :param start: :param end: :re...
Return highest indexes in each strings in the sequence or scalar where the substring is fully contained between [start:end]. Return -1 on failure. Equivalent to standard str.rfind(). :param expr: :param sub: :param start: :param end: :return: sequence or scalar
def remote_delete(self, remote_path, r_st): """Remove the remote directory node.""" # If it's a directory, then delete content and directory if S_ISDIR(r_st.st_mode): for item in self.sftp.listdir_attr(remote_path): full_path = path_join(remote_path, item.filename) ...
Remove the remote directory node.
def _safe_unicode(o): """ Returns an equivalent unicode object, trying harder to avoid dependencies on the Python default encoding. """ def clean(s): return u''.join([c if c in ASCII_PRINTABLE else '?' for c in s]) if USING_PYTHON2: try: return unicode(o) exce...
Returns an equivalent unicode object, trying harder to avoid dependencies on the Python default encoding.
def process_request(self, request): """ Gets the current user from the request and prepares and connects a signal receiver with the user already attached to it. """ # Initialize thread local storage threadlocal.auditlog = { 'signal_duid': (self.__class__, time...
Gets the current user from the request and prepares and connects a signal receiver with the user already attached to it.
def _validate_dtype(self, dtype): """ validate the passed dtype """ if dtype is not None: dtype = pandas_dtype(dtype) # a compound dtype if dtype.kind == 'V': raise NotImplementedError("compound dtypes are not implemented" ...
validate the passed dtype
def wrap_kwargs_to_initdict(init_kwargs_fn: InitKwargsFnType, typename: str, check_result: bool = True) \ -> InstanceToInitDictFnType: """ Wraps a function producing a ``KwargsDict``, making it into a function producing an ``InitDict``. """...
Wraps a function producing a ``KwargsDict``, making it into a function producing an ``InitDict``.
def child_regions(self): """This generator generates the list of direct child regions.""" start, end = self.get_range() block = self._trigger.next() ref_lvl = self.scope_level while block.blockNumber() <= end and block.isValid(): lvl = TextBlockHelper.get_fold_lvl(blo...
This generator generates the list of direct child regions.
def is_skipped_module(self, module_name): """Backport for https://bugs.python.org/issue36130. Fixed in Python 3.8+. """ if module_name is None: return False return super(Pdb, self).is_skipped_module(module_name)
Backport for https://bugs.python.org/issue36130. Fixed in Python 3.8+.
def find_seqs(ol,seqs,test_func,*args): ''' from elist.elist import * def test_func(ele,x): cond = (ele > x) return(cond) ol = [1,2,3,4,5,6,7] some = find_seqs(ol,[0,3],test_func,3) some some = find_some(ol,[0,1,2],test_func,3) ...
from elist.elist import * def test_func(ele,x): cond = (ele > x) return(cond) ol = [1,2,3,4,5,6,7] some = find_seqs(ol,[0,3],test_func,3) some some = find_some(ol,[0,1,2],test_func,3) some #find_some is the same as find_seqs
def all_state_variables_read(self): ''' list(StateVariable): List all of the state variables read ''' all_state_variables_read = [f.all_state_variables_read() for f in self.functions + self.modifiers] all_state_variables_read = [item for sublist in all_state_variables_read fo...
list(StateVariable): List all of the state variables read
def describe_partitioner(self, ): """ returns the partitioner used by this cluster """ self._seqid += 1 d = self._reqs[self._seqid] = defer.Deferred() self.send_describe_partitioner() return d
returns the partitioner used by this cluster
def split_sentences(text): """ Utility function to return a list of sentences. @param text The text that must be split in to sentences. """ sentence_delimiters = re.compile(u'[\\[\\]\n.!?,;:\t\\-\\"\\(\\)\\\'\u2019\u2013]') sentences = sentence_delimiters.split(text) return sentences
Utility function to return a list of sentences. @param text The text that must be split in to sentences.
def make_dash_table(df): ''' Return a dash definitio of an HTML table for a Pandas dataframe ''' table = [] for index, row in df.iterrows(): html_row = [] for i in range(len(row)): html_row.append(html.Td([row[i]])) table.append(html.Tr(html_row)) return table
Return a dash definitio of an HTML table for a Pandas dataframe
def parse_description(markdown=True): """ Parse the description in the README file """ if markdown: return parse_markdown() try: from pypandoc import convert readme_file = f'{PACKAGE_ROOT}/docs/index.rst' if not path.exists(readme_file): raise ImportError ...
Parse the description in the README file
def store(self, data, key="id"): """ Cache the list :param list data: List of objects to cache """ dict.__init__(self, data) self._store_item(key)
Cache the list :param list data: List of objects to cache
def get_blocks(self, chrom, start, end): """ Get any blocks in this alignment that overlap the given location. :return: the alignment blocks that overlap a given genomic interval; potentially none, in which case the empty list is returned. """ blocks = [] for k in self.__get_keys(c...
Get any blocks in this alignment that overlap the given location. :return: the alignment blocks that overlap a given genomic interval; potentially none, in which case the empty list is returned.
def F(self, value): """State Transition matrix""" self._F = value self._F_inv = self.inv(self._F)
State Transition matrix
def _add_match(self, match_key, match_value): """Adds a match key/value""" if match_key is None: raise errors.NullArgument() self._query_terms[match_key] = str(match_key) + '=' + str(match_value)
Adds a match key/value
def add_dependencies(self, task, params={}, **options): """Marks a set of tasks as dependencies of this task, if they are not already dependencies. *A task can have at most 15 dependencies.* Parameters ---------- task : {Id} The task to add dependencies to. [data] : {Ob...
Marks a set of tasks as dependencies of this task, if they are not already dependencies. *A task can have at most 15 dependencies.* Parameters ---------- task : {Id} The task to add dependencies to. [data] : {Object} Data for the request - dependencies : {Array} An arr...
def isotime(s): "Convert timestamps in ISO8661 format to and from Unix time." if type(s) == type(1): return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(s)) elif type(s) == type(1.0): date = int(s) msec = s - date date = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(s)) ...
Convert timestamps in ISO8661 format to and from Unix time.
def build_query(self, **filters): """ Creates a single SQ filter from querystring parameters that correspond to the SearchIndex fields that have been "registered" in `view.fields`. Default behavior is to `OR` terms for the same parameters, and `AND` between parameters. Any query...
Creates a single SQ filter from querystring parameters that correspond to the SearchIndex fields that have been "registered" in `view.fields`. Default behavior is to `OR` terms for the same parameters, and `AND` between parameters. Any querystring parameters that are not registered in `view.fie...
def column(self): """The column where the definition occurs (starting with 0).""" line = self.line return self._element.start - self._element.module.charindex(line, 0)
The column where the definition occurs (starting with 0).
def handle_set_command_list(self, line: str, position: int, tokens: ParseResults) -> ParseResults: """Handle a ``SET X = {"Y", "Z", ...}`` statement.""" key, values = tokens['key'], tokens['values'] for value in values: self.raise_for_invalid_annotation_value(line, position, key, val...
Handle a ``SET X = {"Y", "Z", ...}`` statement.
def _asDict(self): """ Returns all configuration values as a dictionary. """ config = defaultdict(dict) for section in self._sections: for name, value in self._sections[section].items(): if name != '__name__': config[section.lower()][name.lower()] ...
Returns all configuration values as a dictionary.
def _score(self, state, score_movement=True): """Score a state based on how balanced it is. A higher score represents a more balanced state. :param state: The state to score. """ score = 0 max_score = 0 if state.total_weight: # Coefficient of variance...
Score a state based on how balanced it is. A higher score represents a more balanced state. :param state: The state to score.
def ttl(self, steps, relative_time=None): ''' Return the ttl given the number of steps, None if steps is not defined or we're otherwise unable to calculate one. If relative_time is defined, then return a ttl that is the number of seconds from now that the record should be expired. ''' if ste...
Return the ttl given the number of steps, None if steps is not defined or we're otherwise unable to calculate one. If relative_time is defined, then return a ttl that is the number of seconds from now that the record should be expired.
def unique(iterable): """ Returns an iterator that yields the first occurence of a hashable item in `iterable`. """ seen = set() for obj in iterable: if obj not in seen: yield obj seen.add(obj)
Returns an iterator that yields the first occurence of a hashable item in `iterable`.
def cmdify(self): """Encode into a cmd-executable string. This re-implements CreateProcess's quoting logic to turn a list of arguments into one single string for the shell to interpret. * All double quotes are escaped with a backslash. * Existing backslashes before a quote are ...
Encode into a cmd-executable string. This re-implements CreateProcess's quoting logic to turn a list of arguments into one single string for the shell to interpret. * All double quotes are escaped with a backslash. * Existing backslashes before a quote are doubled, so they are all ...
def new_profile(self): """Create a new profile by name. """ # noinspection PyCallByClass,PyTypeChecker dir = os.path.join(QgsApplication.qgisSettingsDirPath(), 'inasafe', 'minimum_needs') file_name, __ = QFileDialog.getSaveFileName( self, ...
Create a new profile by name.
def _smooth_fragment_list(self, real_wave_mfcc_audio_length, ns_string): """ Remove NONSPEECH fragments from list if needed, and set HEAD/TAIL begin/end. """ self.log(u"Called _smooth_fragment_list") self.smflist[0].begin = TimeValue("0.000") self.smflist[-1].end ...
Remove NONSPEECH fragments from list if needed, and set HEAD/TAIL begin/end.
def api_doc(full_version, resource, method='GET', **kwargs): ''' >>> # Wrap api endpoints with more details >>> api_doc('/resource', secure=True, key='value') GET /resource?secure=true&key=value ''' doc = '{} {}'.format(method, api_url(full_version, resource)) params = '&'.join(['{}={}'.form...
>>> # Wrap api endpoints with more details >>> api_doc('/resource', secure=True, key='value') GET /resource?secure=true&key=value
def append(self, item): """ Adds @item to the end of the list -> #int length of list after operation """ return self._client.rpush(self.key_prefix, self._dumps(item))
Adds @item to the end of the list -> #int length of list after operation
def select_warp_gates(action, action_space, select_add): """Select all warp gates.""" del action_space action.action_ui.select_warp_gates.selection_add = select_add
Select all warp gates.
def flatten(iterable): """Fully flattens an iterable: In: flatten([1,2,3,4,[5,6,[7,8]]]) Out: [1,2,3,4,5,6,7,8] """ container = iterable.__class__ placeholder = [] for item in iterable: try: placeholder.extend(flatten(item)) except TypeError: placehol...
Fully flattens an iterable: In: flatten([1,2,3,4,[5,6,[7,8]]]) Out: [1,2,3,4,5,6,7,8]
def _normalize_purge_unknown(mapping, schema): """ {'type': 'boolean'} """ for field in [x for x in mapping if x not in schema]: mapping.pop(field) return mapping
{'type': 'boolean'}
def make_tarball(self, app_folder, build_data): """ Following a successful build, create a tarball and build result. """ # slugignore clean_slug_dir(app_folder) # tar up the result with tarfile.open('build.tar.gz', 'w:gz') as tar: tar.add(app_folder, ...
Following a successful build, create a tarball and build result.
def print_ldamodel_distribution(distrib, row_labels, val_labels, top_n=10): """ Print `n_top` top values from a LDA model's distribution `distrib`. Can be used for topic-word distributions and document-topic distributions. """ df_values = top_n_from_distribution(distrib, top_n=top_n, row_labels=row...
Print `n_top` top values from a LDA model's distribution `distrib`. Can be used for topic-word distributions and document-topic distributions.
def assert_type(lst_or_dct, keys, exp_types, must_exist=True, check=None): """ Raise MetainfoError is not of a particular type lst_or_dct: list or dict instance keys: Sequence of keys so that `lst_or_dct[key[0]][key[1]]...` resolves to a value exp_types: Sequence of types that the value s...
Raise MetainfoError is not of a particular type lst_or_dct: list or dict instance keys: Sequence of keys so that `lst_or_dct[key[0]][key[1]]...` resolves to a value exp_types: Sequence of types that the value specified by `keys` must be an instance of must_exist: Whether to rai...
def diag(image, mask=None, iterations=1): '''4-connect pixels that are 8-connected 0 0 0 0 0 ? 0 0 1 -> 0 1 1 0 1 0 ? 1 ? ''' global diag_table if mask is None: masked_image = image else: masked_image = image.astype(bool).copy() masked_image[~ma...
4-connect pixels that are 8-connected 0 0 0 0 0 ? 0 0 1 -> 0 1 1 0 1 0 ? 1 ?
def add(self, row): """Add a row to the table. Args: row: A dict whose keys match the keys added in set_columns, and whose values can be cast to the types added in set_columns. """ if not self._types: raise wandb.Error( 'TypedTable...
Add a row to the table. Args: row: A dict whose keys match the keys added in set_columns, and whose values can be cast to the types added in set_columns.
def get_hashes_from_search(self, query, page=None): """ Get the scan results for a file. Even if you do not have a Private Mass API key that you can use, you can still automate VirusTotal Intelligence searches pretty much in the same way that the searching for files api call works. :pa...
Get the scan results for a file. Even if you do not have a Private Mass API key that you can use, you can still automate VirusTotal Intelligence searches pretty much in the same way that the searching for files api call works. :param query: a VirusTotal Intelligence search string in accordance...
def gen(function, io_loop=None): """Allows using a generator to chain together reversible actions. This function is very similar to :py:func:`reversible.gen` except that it may be used with actions whose ``forwards`` and/or ``backwards`` methods are couroutines. Specifically, if either of those methods...
Allows using a generator to chain together reversible actions. This function is very similar to :py:func:`reversible.gen` except that it may be used with actions whose ``forwards`` and/or ``backwards`` methods are couroutines. Specifically, if either of those methods return futures the generated action...
def trigger_show_by_trigger_name(self, trigger_name, **kwargs): "https://developer.zendesk.com/rest_api/docs/chat/triggers#get-a-trigger" api_path = "/api/v2/triggers/{trigger_name}" api_path = api_path.format(trigger_name=trigger_name) return self.call(api_path, **kwargs)
https://developer.zendesk.com/rest_api/docs/chat/triggers#get-a-trigger
def minimize(self, bAsync = True): """ Minimize the window. @see: L{maximize}, L{restore} @type bAsync: bool @param bAsync: Perform the request asynchronously. @raise WindowsError: An error occured while processing this request. """ if bAsync: ...
Minimize the window. @see: L{maximize}, L{restore} @type bAsync: bool @param bAsync: Perform the request asynchronously. @raise WindowsError: An error occured while processing this request.
def get_html_row_count(spans): """Get the number of rows""" if spans == []: return 0 row_counts = {} for span in spans: span = sorted(span) try: row_counts[str(span[0][1])] += get_span_row_count(span) except KeyError: row_counts[str(span[0][1])] =...
Get the number of rows
def autoconf(self): """Implements Munin Plugin Auto-Configuration Option. @return: True if plugin can be auto-configured, False otherwise. """ nginxInfo = NginxInfo(self._host, self._port, self._user, self._password, ...
Implements Munin Plugin Auto-Configuration Option. @return: True if plugin can be auto-configured, False otherwise.
def parse_or_die(self, args=None): """Like :meth:`ParseKeywords.parse`, but calls :func:`pkwit.cli.die` if a :exc:`KwargvError` is raised, printing the exception text. Returns *self* for convenience. """ from .cli import die try: return self.parse(args) ...
Like :meth:`ParseKeywords.parse`, but calls :func:`pkwit.cli.die` if a :exc:`KwargvError` is raised, printing the exception text. Returns *self* for convenience.
def bds(tickers, flds, **kwargs): """ Bloomberg block data Args: tickers: ticker(s) flds: field(s) **kwargs: other overrides for query -> raw: raw output from `pdbdp` library, default False Returns: pd.DataFrame: block data Examples: >>> import os...
Bloomberg block data Args: tickers: ticker(s) flds: field(s) **kwargs: other overrides for query -> raw: raw output from `pdbdp` library, default False Returns: pd.DataFrame: block data Examples: >>> import os >>> >>> pd.options.display.wi...
def retrieve_mail_attachments(self, name, mail_folder='INBOX', check_regex=False, latest_only=False, not_found_mode='raise'): """ Retr...
Retrieves mail's attachments in the mail folder by its name. :param name: The name of the attachment that will be downloaded. :type name: str :param mail_folder: The mail folder where to look at. :type mail_folder: str :param check_regex: Checks the name for a regular expression...
def build(self, mode='debug'): """ Builds the app project after the execution of validate and prepare. This is the third and last step in the build process. Needs to be implemented by the subclass. """ self.ensure_cache_folder() ref = { 'debug': 'assembleDebug', 'release': 'ass...
Builds the app project after the execution of validate and prepare. This is the third and last step in the build process. Needs to be implemented by the subclass.
def create_coreference(self, coref_type, term_ids, id=None): """ Create a new coreference object and add it to the coreferences layer @type coref_type: string @param coref_type: type of the coreference object @type term_ids: list @param term_ids: list of term ids ...
Create a new coreference object and add it to the coreferences layer @type coref_type: string @param coref_type: type of the coreference object @type term_ids: list @param term_ids: list of term ids @type id: string @param id: optional id of the entity
def merge_configs(to_be_merged, default): """Merges two configuration dictionaries by overwriting values with same keys, with the priority on values given on the 'left' side, so the to_be_merged dict. Notice that with lists in the configuration, it skips from the default (right side) the tuples in t...
Merges two configuration dictionaries by overwriting values with same keys, with the priority on values given on the 'left' side, so the to_be_merged dict. Notice that with lists in the configuration, it skips from the default (right side) the tuples in that which already exist in the left side to_b...
def _gen_helper_dict(filtered_inputs): ''' Create a dict of values for the downloaded files. This is similar to the variables created when running a bash app. ''' file_key_descs, _ignore = file_load_utils.analyze_bash_vars( file_load_utils.get_input_json_file(), None) flattened_dict = ...
Create a dict of values for the downloaded files. This is similar to the variables created when running a bash app.
def _mean_prediction(self, sigma2, Y, scores, h, t_params): """ Creates a h-step ahead mean prediction Parameters ---------- sigma2 : np.array The past predicted values Y : np.array The past data scores : np.array The past scores ...
Creates a h-step ahead mean prediction Parameters ---------- sigma2 : np.array The past predicted values Y : np.array The past data scores : np.array The past scores h : int How many steps ahead for the prediction ...
def _FindInFileEntry(self, file_entry, find_specs, search_depth): """Searches for matching file entries within the file entry. Args: file_entry (FileEntry): file entry. find_specs (list[FindSpec]): find specifications. search_depth (int): number of location path segments to compare. Yiel...
Searches for matching file entries within the file entry. Args: file_entry (FileEntry): file entry. find_specs (list[FindSpec]): find specifications. search_depth (int): number of location path segments to compare. Yields: PathSpec: path specification of a matching file entry.
def run(self): "Run each middleware function on files" # load files from source directory files = self.get_files() # loop through each middleware for func in self.middleware: # call each one, ignoring return value func(files, self) # store and r...
Run each middleware function on files
def update(self, cont): """Update this instance with the contextualize passed.""" self.max_time = max(self.max_time, cont.max_time) if cont.items is not None: if self.items is None: self.items = cont.items else: self.items.update(cont.item...
Update this instance with the contextualize passed.
def _read_preference(self, allow_secondary): """ Return the mongo read preference given an 'allow_secondary' argument """ allow_secondary = self._allow_secondary if allow_secondary is None else allow_secondary return ReadPreference.NEAREST if allow_secondary else ReadPreference.PRIMARY
Return the mongo read preference given an 'allow_secondary' argument
def send_preview(self, recipients, personalize="fallback"): """Sends a preview of this campaign.""" body = { "PreviewRecipients": [recipients] if isinstance(recipients, str) else recipients, "Personalize": personalize} response = self._post(self.uri_for("sendpreview"), js...
Sends a preview of this campaign.
def jsonld(client, records): """Format dataset files as JSON-LD. :param client: LocalClient instance. :param records: Filtered collection. """ from renku.models._json import dumps from renku.models._jsonld import asjsonld data = [asjsonld(record) for record in records] echo_via_pager(d...
Format dataset files as JSON-LD. :param client: LocalClient instance. :param records: Filtered collection.