code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def to_html( self, suppress_newlines=False, in_div_flag=False): # pylint: disable=W0221 """Render a MessageElement as html. :param suppress_newlines: Whether to suppress any newlines in the output. If this option is enabled, the entire html output will b...
Render a MessageElement as html. :param suppress_newlines: Whether to suppress any newlines in the output. If this option is enabled, the entire html output will be rendered on a single line. :type suppress_newlines: bool :param in_div_flag: Whether the message should b...
def xyz2lonlat(x, y, z): """Convert cartesian to lon lat.""" lon = xu.rad2deg(xu.arctan2(y, x)) lat = xu.rad2deg(xu.arctan2(z, xu.sqrt(x**2 + y**2))) return lon, lat
Convert cartesian to lon lat.
def authenticate(self, username=None, password=None, actions=None, response=None, authorization=None): # pylint: disable=too-many-arguments,too-many-locals """ Authenticate to the registry using a username and password, an au...
Authenticate to the registry using a username and password, an authorization header or otherwise as the anonymous user. :param username: User name to authenticate as. :type username: str :param password: User's password. :type password: str :param actions: If you know ...
def dataReceived(self, data): """ Takes "data" which we assume is json encoded If data has a subject_id attribute, we pass that to the dispatcher as the subject_id so it will get carried through into any return communications and be identifiable to the client ...
Takes "data" which we assume is json encoded If data has a subject_id attribute, we pass that to the dispatcher as the subject_id so it will get carried through into any return communications and be identifiable to the client falls back to just passing the message along....
def stem(self, word, alternate_vowels=False): """Return Snowball German stem. Parameters ---------- word : str The word to stem alternate_vowels : bool Composes ae as ä, oe as ö, and ue as ü before running the algorithm Returns ------- ...
Return Snowball German stem. Parameters ---------- word : str The word to stem alternate_vowels : bool Composes ae as ä, oe as ö, and ue as ü before running the algorithm Returns ------- str Word stem Examples ...
def set_shape(self, id, new_shape): """Copies the turtle data from the old shape buffer to the new""" old_shape = self.id_to_shape[id] old_buffer = self.get_buffer(old_shape) model, color = old_buffer.get(id) new_data = self._create_turtle(id, new_shape, model, color) old...
Copies the turtle data from the old shape buffer to the new
def _Initialize(self, http, url): """Initialize this download by setting self.http and self.url. We want the user to be able to override self.http by having set the value in the constructor; in that case, we ignore the provided http. Args: http: An httplib2.Http insta...
Initialize this download by setting self.http and self.url. We want the user to be able to override self.http by having set the value in the constructor; in that case, we ignore the provided http. Args: http: An httplib2.Http instance or None. url: The url for this ...
def offer(self, item): """Offer to the buffer It is a non-blocking operation, and when the buffer is full, it raises Queue.Full exception """ try: # non-blocking self._buffer.put(item, block=False) if self._consumer_callback is not None: self._consumer_callback() return ...
Offer to the buffer It is a non-blocking operation, and when the buffer is full, it raises Queue.Full exception
def _clean_up_gene_id(geneid, sp, curie_map): """ A series of identifier rewriting to conform with standard gene identifiers. :param geneid: :param sp: :return: """ # special case for MGI geneid = re.sub(r'MGI:MGI:', 'MGI:', geneid) # rewr...
A series of identifier rewriting to conform with standard gene identifiers. :param geneid: :param sp: :return:
def do_mumble(self, args): """Mumbles what you tell me to.""" repetitions = args.repeat or 1 for i in range(min(repetitions, self.maxrepeats)): output = [] if random.random() < .33: output.append(random.choice(self.MUMBLE_FIRST)) for word in ar...
Mumbles what you tell me to.
def MergeData(self, merge_data, raw_data=None): """Merges data read from a config file into the current config.""" self.FlushCache() if raw_data is None: raw_data = self.raw_data for k, v in iteritems(merge_data): # A context clause. if isinstance(v, dict) and k not in self.type_infos...
Merges data read from a config file into the current config.
def printDuplicatedTPEDandTFAM(tped, tfam, samples, oldSamples, prefix): """Print the TPED and TFAM of the duplicated samples. :param tped: the ``tped`` containing duplicated samples. :param tfam: the ``tfam`` containing duplicated samples. :param samples: the updated position of the samples in the tpe...
Print the TPED and TFAM of the duplicated samples. :param tped: the ``tped`` containing duplicated samples. :param tfam: the ``tfam`` containing duplicated samples. :param samples: the updated position of the samples in the tped containing only duplicated samples. :param oldSamples:...
def increment(self, delta=1, text=None): """Redraw the progress bar, incrementing the value by delta (default=1) and optionally changing the text. Returns the ProgressBar's new value. See also .update().""" return self.update(value=min(self.max, self.value + delta), text=text)
Redraw the progress bar, incrementing the value by delta (default=1) and optionally changing the text. Returns the ProgressBar's new value. See also .update().
def _proc_member(self, tarfile): """Choose the right processing method depending on the type and call it. """ if self.type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK): return self._proc_gnulong(tarfile) elif self.type == GNUTYPE_SPARSE: return self._proc_sp...
Choose the right processing method depending on the type and call it.
def attach_tracker(self, stanza, tracker=None): """ Return a new tracker or modify one to track the stanza. :param stanza: Stanza to track. :type stanza: :class:`aioxmpp.Message` :param tracker: Existing tracker to attach to. :type tracker: :class:`.tracking.MessageTrack...
Return a new tracker or modify one to track the stanza. :param stanza: Stanza to track. :type stanza: :class:`aioxmpp.Message` :param tracker: Existing tracker to attach to. :type tracker: :class:`.tracking.MessageTracker` :raises ValueError: if the stanza is of type ...
def remove(self, elem): """Removes an item from the list. Similar to list.remove().""" self._values.remove(elem) self._message_listener.Modified()
Removes an item from the list. Similar to list.remove().
def _lstrip_word(word, prefix): ''' Return a copy of the string after the specified prefix was removed from the beginning of the string ''' if six.text_type(word).startswith(prefix): return six.text_type(word)[len(prefix):] return word
Return a copy of the string after the specified prefix was removed from the beginning of the string
def stat(filename, retry_params=None, _account_id=None): """Get GCSFileStat of a Google Cloud storage file. Args: filename: A Google Cloud Storage filename of form '/bucket/filename'. retry_params: An api_utils.RetryParams for this call to GCS. If None, the default one is used. _account_id: Inter...
Get GCSFileStat of a Google Cloud storage file. Args: filename: A Google Cloud Storage filename of form '/bucket/filename'. retry_params: An api_utils.RetryParams for this call to GCS. If None, the default one is used. _account_id: Internal-use only. Returns: a GCSFileStat object containing ...
def get_heat_capacity(self, temperature, structure, n, u, cutoff=1e2): """ Gets the directional heat capacity for a higher order tensor expansion as a function of direction and polarization. Args: temperature (float): Temperature in kelvin structure (float): Stru...
Gets the directional heat capacity for a higher order tensor expansion as a function of direction and polarization. Args: temperature (float): Temperature in kelvin structure (float): Structure to be used in directional heat capacity determination n (...
def nodeprep(string, allow_unassigned=False): """ Process the given `string` using the Nodeprep (`RFC 6122`_) profile. In the error cases defined in `RFC 3454`_ (stringprep), a :class:`ValueError` is raised. """ chars = list(string) _nodeprep_do_mapping(chars) do_normalization(chars) ...
Process the given `string` using the Nodeprep (`RFC 6122`_) profile. In the error cases defined in `RFC 3454`_ (stringprep), a :class:`ValueError` is raised.
def parse(self): """Parse and return an nbt literal from the token stream.""" token_type = self.current_token.type.lower() handler = getattr(self, f'parse_{token_type}', None) if handler is None: raise self.error(f'Invalid literal {self.current_token.value!r}') return...
Parse and return an nbt literal from the token stream.
def get_queue_info(self, instance, cursor): """Collects metrics for all queues on the connected database.""" cursor.execute(self.QUEUE_INFO_STATEMENT) for queue_name, ticker_lag, ev_per_sec in cursor: yield queue_name, { 'ticker_lag': ticker_lag, 'ev_p...
Collects metrics for all queues on the connected database.
def _check_valid_translation(self, translation): """Checks that the translation vector is valid. """ if not isinstance(translation, np.ndarray) or not np.issubdtype(translation.dtype, np.number): raise ValueError('Translation must be specified as numeric numpy array') t = tr...
Checks that the translation vector is valid.
def merge_requests(self, **kwargs): """List the merge requests related to this milestone. Args: all (bool): If True, return all the items, without pagination per_page (int): Number of items to retrieve per request page (int): ID of the page to return (starts with pag...
List the merge requests related to this milestone. Args: all (bool): If True, return all the items, without pagination per_page (int): Number of items to retrieve per request page (int): ID of the page to return (starts with page 1) as_list (bool): If set to Fals...
def retrieve(self, cursor): """ Retrieve items from query """ assert isinstance(cursor, dict), "expected cursor type 'dict'" # look for record in query query = self.get_query() assert isinstance(query, peewee.Query) query return query.get(**curso...
Retrieve items from query
def listurl_get(self, q, **kwargs): '''taobao.taobaoke.listurl.get 淘宝客关键词搜索URL 淘宝客关键词搜索URL''' request = TOPRequest('taobao.taobaoke.listurl.get') request['q'] = q for k, v in kwargs.iteritems(): if k not in ('nick', 'outer_code', 'pid') and v==None: continue ...
taobao.taobaoke.listurl.get 淘宝客关键词搜索URL 淘宝客关键词搜索URL
def request(self, location, fragment_enc=False): """ Given a URL this method will add a fragment, a query part or extend a query part if it already exists with the information in this instance. :param location: A URL :param fragment_enc: Whether the information should b...
Given a URL this method will add a fragment, a query part or extend a query part if it already exists with the information in this instance. :param location: A URL :param fragment_enc: Whether the information should be placed in a fragment (True) or in a query part (False) ...
def fetch(self): """ Fetch a VariableInstance :returns: Fetched VariableInstance :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance """ params = values.of({}) payload = self._version.fetch( 'GET', self._uri, ...
Fetch a VariableInstance :returns: Fetched VariableInstance :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance
def size(config, accounts=(), day=None, group=None, human=True, region=None): """size of exported records for a given day.""" config = validate.callback(config) destination = config.get('destination') client = boto3.Session().client('s3') day = parse(day) def export_size(client, account): ...
size of exported records for a given day.
def request(self, url, method='GET', params=None, data=None, expected_response_code=200): """Make a http request to API.""" url = "{0}/{1}".format(self._baseurl, url) if params is None: params = {} auth = { 'u': self._username, 'p': s...
Make a http request to API.
def get_parent_tag(mention): """Return the HTML tag of the Mention's parent. These may be tags such as 'p', 'h2', 'table', 'div', etc. If a candidate is passed in, only the tag of its first Mention is returned. :param mention: The Mention to evaluate :rtype: string """ span = _to_span(ment...
Return the HTML tag of the Mention's parent. These may be tags such as 'p', 'h2', 'table', 'div', etc. If a candidate is passed in, only the tag of its first Mention is returned. :param mention: The Mention to evaluate :rtype: string
def _item_list(profile=None, **connection_args): ''' Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list ''' kstone = auth(profile, **connection_args) ret = [] for item in ...
Template for writing list functions Return a list of available items (keystone items-list) CLI Example: .. code-block:: bash salt '*' keystone.item_list
def endswith(self, name: str) -> List[str]: """Return a list of all keywords ending with the given string. >>> from hydpy.core.devicetools import Keywords >>> keywords = Keywords('first_keyword', 'second_keyword', ... 'keyword_3', 'keyword_4', ... ...
Return a list of all keywords ending with the given string. >>> from hydpy.core.devicetools import Keywords >>> keywords = Keywords('first_keyword', 'second_keyword', ... 'keyword_3', 'keyword_4', ... 'keyboard') >>> keywords.endswith('key...
def parse_clubs(self, clubs_page): """Parses the DOM and returns character clubs attributes. :type clubs_page: :class:`bs4.BeautifulSoup` :param clubs_page: MAL character clubs page's DOM :rtype: dict :return: character clubs attributes. """ character_info = self.parse_sidebar(clubs_page)...
Parses the DOM and returns character clubs attributes. :type clubs_page: :class:`bs4.BeautifulSoup` :param clubs_page: MAL character clubs page's DOM :rtype: dict :return: character clubs attributes.
def deserialize(self, node: SchemaNode, cstruct: Union[str, ColanderNullType]) \ -> Optional[Pendulum]: """ Deserializes string representation to Python object. """ if not cstruct: return colander.null try: ...
Deserializes string representation to Python object.
def content_recommendations(access_token, content_item_id): ''' Name: content_recommendations Parameters: access_token, content_item_id Return: dictionary ''' headers = {'Authorization': 'Bearer ' + str(access_token)} recommendations_url =\ construct_content_recommendations_url(enrichment_url, content_item_id...
Name: content_recommendations Parameters: access_token, content_item_id Return: dictionary
def restore(self, value, context=None): """ Restores the value from a table cache for usage. :param value | <variant> context | <orb.Context> || None """ value = super(DatetimeWithTimezoneColumn, self).restore(value, context) if value in ('tod...
Restores the value from a table cache for usage. :param value | <variant> context | <orb.Context> || None
def v_unique_name_children(ctx, stmt): """Make sure that each child of stmt has a unique name""" def sort_pos(p1, p2): if p1.line < p2.line: return (p1,p2) else: return (p2,p1) dict = {} chs = stmt.i_children def check(c): key = (c.i_module.i_module...
Make sure that each child of stmt has a unique name
def print_partlist(input, timeout=20, showgui=False): '''print partlist text delivered by eagle :param input: .sch or .brd file name :param timeout: int :param showgui: Bool, True -> do not hide eagle GUI :rtype: None ''' print raw_partlist(input=input, timeout=timeout, showgui=showgui)
print partlist text delivered by eagle :param input: .sch or .brd file name :param timeout: int :param showgui: Bool, True -> do not hide eagle GUI :rtype: None
def c_join(self, other, psi=-40.76, omega=-178.25, phi=-65.07, o_c_n_angle=None, c_n_ca_angle=None, c_n_length=None, relabel=True): """Joins other to self at the C-terminus via a peptide bond. Notes ----- This function directly modifies self. It does not re...
Joins other to self at the C-terminus via a peptide bond. Notes ----- This function directly modifies self. It does not return a new object. Parameters ---------- other: Residue or Polypeptide psi: float, optional Psi torsion angle (degrees) between ...
def initializeSessionAsBob(sessionState, sessionVersion, parameters): """ :type sessionState: SessionState :type sessionVersion: int :type parameters: BobAxolotlParameters """ sessionState.setSessionVersion(sessionVersion) sessionState.setRemoteIdentityKey(paramet...
:type sessionState: SessionState :type sessionVersion: int :type parameters: BobAxolotlParameters
def a_alpha_and_derivatives(self, T, full=True, quick=True): r'''Method to calculate `a_alpha` and its first and second derivatives for this EOS. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. Uses the set values of `a...
r'''Method to calculate `a_alpha` and its first and second derivatives for this EOS. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. Uses the set values of `a`. .. math:: a\alpha = a ...
def team(self): """Team to which the scope is assigned.""" team_dict = self._json_data.get('team') if team_dict and team_dict.get('id'): return self._client.team(id=team_dict.get('id')) else: return None
Team to which the scope is assigned.
def doc2md(docstr, title, min_level=1, more_info=False, toc=True, maxdepth=0): """ Convert a docstring to a markdown text. """ text = doctrim(docstr) lines = text.split('\n') sections = find_sections(lines) if sections: level = min(n for n,t in sections) - 1 else: level ...
Convert a docstring to a markdown text.
def getTableMisnestedNodePosition(self): """Get the foster parent element, and sibling to insert before (or None) when inserting a misnested table node""" # The foster parent element is the one which comes before the most # recently opened table element # XXX - this is really ine...
Get the foster parent element, and sibling to insert before (or None) when inserting a misnested table node
def _ParseValueData(self, knowledge_base, value_data): """Parses Windows Registry value data for a preprocessing attribute. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. value_data (object): Windows Registry value data. Raises: errors.PreProcessFail: if th...
Parses Windows Registry value data for a preprocessing attribute. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. value_data (object): Windows Registry value data. Raises: errors.PreProcessFail: if the preprocessing fails.
def remove_request(self, uuid): """Remove any RPC request(s) using this uuid. :param str uuid: Rpc Identifier. :return: """ for key in list(self._request): if self._request[key] == uuid: del self._request[key]
Remove any RPC request(s) using this uuid. :param str uuid: Rpc Identifier. :return:
def fix(self, *args, **kwargs): """ Turns parameters to constants. As arguments, parameters must be strings. As keyword arguments, they can be set at the same time. Note this will NOT work when specifying a non-string fit function, because there is no flexibility in the...
Turns parameters to constants. As arguments, parameters must be strings. As keyword arguments, they can be set at the same time. Note this will NOT work when specifying a non-string fit function, because there is no flexibility in the number of arguments. To get around this, su...
def parent_link_record_exists(self): # type: () -> bool ''' Determine whether this Rock Ridge entry has a parent link record (used for relocating deep directory records). Parameters: None: Returns: True if this Rock Ridge entry has a parent link record,...
Determine whether this Rock Ridge entry has a parent link record (used for relocating deep directory records). Parameters: None: Returns: True if this Rock Ridge entry has a parent link record, False otherwise.
def monitor_experiment(args): '''monitor the experiment''' if args.time <= 0: print_error('please input a positive integer as time interval, the unit is second.') exit(1) while True: try: os.system('clear') update_experiment() show_experiment_info(...
monitor the experiment
def to_cartesian(r, theta, theta_units="radians"): """ Converts polar r, theta to cartesian x, y. """ assert theta_units in ['radians', 'degrees'],\ "kwarg theta_units must specified in radians or degrees" # Convert to radians if theta_units == "degrees": theta = to_radians(thet...
Converts polar r, theta to cartesian x, y.
def cpp_app_builder(build_context, target): """Pack a C++ binary as a Docker image with its runtime dependencies. TODO(itamar): Dynamically analyze the binary and copy shared objects from its buildenv image to the runtime image, unless they're installed. """ yprint(build_context.conf, 'Build CppApp...
Pack a C++ binary as a Docker image with its runtime dependencies. TODO(itamar): Dynamically analyze the binary and copy shared objects from its buildenv image to the runtime image, unless they're installed.
def _carregar(self): """Carrega (ou recarrega) a biblioteca SAT. Se a convenção de chamada ainda não tiver sido definida, será determinada pela extensão do arquivo da biblioteca. :raises ValueError: Se a convenção de chamada não puder ser determinada ou se não for um valor v...
Carrega (ou recarrega) a biblioteca SAT. Se a convenção de chamada ainda não tiver sido definida, será determinada pela extensão do arquivo da biblioteca. :raises ValueError: Se a convenção de chamada não puder ser determinada ou se não for um valor válido.
def fa(a, b, alpha=2): """Returns the factor of 'alpha' (2 or 5 normally) """ return np.sum((a > b / alpha) & (a < b * alpha), dtype=float) / len(a) * 100
Returns the factor of 'alpha' (2 or 5 normally)
def map(self, f_list: List[Callable[[np.ndarray], int]], *, axis: int = 0, chunksize: int = 1000, selection: np.ndarray = None) -> List[np.ndarray]: """ Apply a function along an axis without loading the entire dataset in memory. Args: f: Function(s) that takes a numpy ndarray as argument axis: Axis alo...
Apply a function along an axis without loading the entire dataset in memory. Args: f: Function(s) that takes a numpy ndarray as argument axis: Axis along which to apply the function (0 = rows, 1 = columns) chunksize: Number of rows (columns) to load per chunk selection: Columns (rows) to include ...
async def close(self): """Stop serving the :attr:`.Server.sockets` and close all concurrent connections. """ if self._server: self._server.close() self._server = None self.event('stop').fire()
Stop serving the :attr:`.Server.sockets` and close all concurrent connections.
def unzip(self, directory): """ Write contents of zipfile to directory """ if not os.path.exists(directory): os.makedirs(directory) shutil.copytree(self.src_dir, directory)
Write contents of zipfile to directory
def get_all_item_data(items, conn, graph=None, output='json', **kwargs): """ queries a triplestore with the provided template or uses a generic template that returns triples 3 edges out in either direction from the provided item_uri args: items: the starting uri or list of uris to the query ...
queries a triplestore with the provided template or uses a generic template that returns triples 3 edges out in either direction from the provided item_uri args: items: the starting uri or list of uris to the query conn: the rdfframework triplestore connection to query against outpu...
def _worker_fn(samples, batchify_fn, dataset=None): """Function for processing data in worker process.""" # pylint: disable=unused-argument # it is required that each worker process has to fork a new MXIndexedRecordIO handle # preserving dataset as global variable can save tons of overhead and is safe i...
Function for processing data in worker process.
def is_up(coordinate, current_time): """ Given the position and time determin if the given target is up. @param coordinate: the J2000 location of the source @param current_time: The time of the observations @return: True/False """ cfht.date = current_time.iso.replace('-', '/') cfht.hori...
Given the position and time determin if the given target is up. @param coordinate: the J2000 location of the source @param current_time: The time of the observations @return: True/False
def create_comment_commit(self, body, commit_id, path, position, pr_id): """ Posts a comment to a given commit at a certain pull request. Check https://developer.github.com/v3/pulls/comments/#create-a-comment param body: str -> Comment text param commit_id: str -> SHA of the com...
Posts a comment to a given commit at a certain pull request. Check https://developer.github.com/v3/pulls/comments/#create-a-comment param body: str -> Comment text param commit_id: str -> SHA of the commit param path: str -> Relative path of the file to be commented param positi...
def library(self): """ Library to browse or search your media. """ if not self._library: try: data = self.query(Library.key) self._library = Library(self, data) except BadRequest: data = self.query('/library/sections/') ...
Library to browse or search your media.
def is_consonant(note1, note2, include_fourths=True): """Return True if the interval is consonant. A consonance is a harmony, chord, or interval considered stable, as opposed to a dissonance. This function tests whether the given interval is consonant. This basically means that it checks whether t...
Return True if the interval is consonant. A consonance is a harmony, chord, or interval considered stable, as opposed to a dissonance. This function tests whether the given interval is consonant. This basically means that it checks whether the interval is (or sounds like) a unison, third, sixth, p...
def unique_items(seq): """Return the unique items from iterable *seq* (in order).""" seen = set() return [x for x in seq if not (x in seen or seen.add(x))]
Return the unique items from iterable *seq* (in order).
def remote_image_request(self, image_url, params=None): """ Send an image for classification. The imagewill be retrieved from the URL specified. The params parameter is optional. On success this method will immediately return a job information. Its status will initially ...
Send an image for classification. The imagewill be retrieved from the URL specified. The params parameter is optional. On success this method will immediately return a job information. Its status will initially be :py:data:`cloudsight.STATUS_NOT_COMPLETED` as it usually takes 6-...
def doi_input(doi_string, download=True): """ This method accepts a DOI string and attempts to download the appropriate xml file. If successful, it returns a path to that file. As with all URL input types, the success of this method depends on supporting per-publisher conventions and will fail on un...
This method accepts a DOI string and attempts to download the appropriate xml file. If successful, it returns a path to that file. As with all URL input types, the success of this method depends on supporting per-publisher conventions and will fail on unsupported publishers
def check_folder_exists(project, path, folder_name): ''' :param project: project id :type project: string :param path: path to where we should look for the folder in question :type path: string :param folder_name: name of the folder in question :type folder_name: string :returns: A boole...
:param project: project id :type project: string :param path: path to where we should look for the folder in question :type path: string :param folder_name: name of the folder in question :type folder_name: string :returns: A boolean True or False whether the folder exists at the specified path ...
def apply(self, builder): """Apply the Slide Configuration to a Builder.""" if 'theme' in self.attributes: builder.apply_theme( self.attributes['theme'], builder.theme_options, )
Apply the Slide Configuration to a Builder.
def write(self, buf, url): """Write buffer to storage at a given url""" (store_name, path) = self._split_url(url) adapter = self._create_adapter(store_name) with adapter.open(path, 'wb') as f: f.write(buf.encode())
Write buffer to storage at a given url
def __extract_tags(self): """ Extract tags from the DocBlock. """ tags = list() current = None for line in self._comment: parts = re.match(r'^@(\w+)', line) if parts: current = (parts.group(1), list()) tags.append(cu...
Extract tags from the DocBlock.
def subroutine(*effects): """ Returns an effect performing a list of effects. The value passed to each effect is a result of the previous effect. """ def subroutine(value, context, *args, **kwargs): d = defer.succeed(value) for effect in effects: d.addCallback(effect, co...
Returns an effect performing a list of effects. The value passed to each effect is a result of the previous effect.
def scatter_plot(data, index_x, index_y, percent=100.0, seed=1, size=50, title=None, outfile=None, wait=True): """ Plots two attributes against each other. TODO: click events http://matplotlib.org/examples/event_handling/data_browser.html :param data: the dataset :type data: Instances :param i...
Plots two attributes against each other. TODO: click events http://matplotlib.org/examples/event_handling/data_browser.html :param data: the dataset :type data: Instances :param index_x: the 0-based index of the attribute on the x axis :type index_x: int :param index_y: the 0-based index of th...
def in_template_path(fn): """ Return `fn` in template context, or in other words add `fn` to template path, so you don't need to write absolute path of `fn` in template directory manually. Args: fn (str): Name of the file in template dir. Return: str: Absolute path to the file....
Return `fn` in template context, or in other words add `fn` to template path, so you don't need to write absolute path of `fn` in template directory manually. Args: fn (str): Name of the file in template dir. Return: str: Absolute path to the file.
def validatefeatures(self,features): """Returns features in validated form, or raises an Exception. Mostly for internal use""" validatedfeatures = [] for feature in features: if isinstance(feature, int) or isinstance(feature, float): validatedfeatures.append( str(feat...
Returns features in validated form, or raises an Exception. Mostly for internal use
def _CompileTemplate( template_str, builder, meta='{}', format_char='|', default_formatter='str', whitespace='smart'): """Compile the template string, calling methods on the 'program builder'. Args: template_str: The template string. It should not have any compilation options in the ...
Compile the template string, calling methods on the 'program builder'. Args: template_str: The template string. It should not have any compilation options in the header -- those are parsed by FromString/FromFile builder: The interface of _ProgramBuilder isn't fixed. Use at your own risk. ...
def color(self): """Get light color.""" return (self.get_value(CONST.STATUSES_KEY).get('hue'), self.get_value(CONST.STATUSES_KEY).get('saturation'))
Get light color.
def resolve_metric_as_tuple(metric): """ Resolve metric key to a given target. :param metric: the metric name. :type metric: ``str`` :rtype: :class:`Metric` """ if "." in metric: _, metric = metric.split(".") r = [ (operator, match) for operator, match in ALL_METRICS ...
Resolve metric key to a given target. :param metric: the metric name. :type metric: ``str`` :rtype: :class:`Metric`
def fingerprint(self, word, n_bits=16, most_common=MOST_COMMON_LETTERS_CG): """Return the occurrence halved fingerprint. Based on the occurrence halved fingerprint from :cite:`Cislak:2017`. Parameters ---------- word : str The word to fingerprint n_bits : in...
Return the occurrence halved fingerprint. Based on the occurrence halved fingerprint from :cite:`Cislak:2017`. Parameters ---------- word : str The word to fingerprint n_bits : int Number of bits in the fingerprint returned most_common : list ...
def coerce(self, value): """Coerce a cleaned value.""" if self._coerce is not None: value = self._coerce(value) return value
Coerce a cleaned value.
def _install_one( repo_url, branch, destination, commit='', patches=None, exclude_modules=None, include_modules=None, base=False, work_directory='' ): """ Install a third party odoo add-on :param string repo_url: url of the repo that contains the patch. :param string branch: name of the branch to c...
Install a third party odoo add-on :param string repo_url: url of the repo that contains the patch. :param string branch: name of the branch to checkout. :param string destination: the folder where the add-on should end up at. :param string commit: Optional commit rev to checkout to. If mentioned, that ...
def identical_signature_wrapper(original_function, wrapped_function): ''' Return a function with identical signature as ``original_function``'s which will call the ``wrapped_function``. ''' context = {'__wrapped__': wrapped_function} function_def = compile( 'def {0}({1}):\n' ' ...
Return a function with identical signature as ``original_function``'s which will call the ``wrapped_function``.
def mount(directory, lower_dir, upper_dir, mount_table=None): """Creates a mount""" return OverlayFS.mount(directory, lower_dir, upper_dir, mount_table=mount_table)
Creates a mount
def aget(dct, key): r"""Allow to get values deep in a dict with iterable keys Accessing leaf values is quite straightforward: >>> dct = {'a': {'x': 1, 'b': {'c': 2}}} >>> aget(dct, ('a', 'x')) 1 >>> aget(dct, ('a', 'b', 'c')) 2 If key is empty, it returns unchanged...
r"""Allow to get values deep in a dict with iterable keys Accessing leaf values is quite straightforward: >>> dct = {'a': {'x': 1, 'b': {'c': 2}}} >>> aget(dct, ('a', 'x')) 1 >>> aget(dct, ('a', 'b', 'c')) 2 If key is empty, it returns unchanged the ``dct`` value. ...
def env(var_name, default=False): """ Get the environment variable. If not found use a default or False, but print to stderr a warning about the missing env variable.""" try: value = os.environ[var_name] if str(value).strip().lower() in ['false', 'f', 'no', 'off' '0', 'none', 'null', '', ]: ...
Get the environment variable. If not found use a default or False, but print to stderr a warning about the missing env variable.
def parse_template(self, tmp, reset=False, only_body=False): """parses a template or user edited string to fills this envelope. :param tmp: the string to parse. :type tmp: str :param reset: remove previous envelope content :type reset: bool """ logging.debug('GoT...
parses a template or user edited string to fills this envelope. :param tmp: the string to parse. :type tmp: str :param reset: remove previous envelope content :type reset: bool
def _dcm_array_to_matrix3(self, dcm): """ Converts dcm array into Matrix3 :param dcm: 3x3 dcm array :returns: Matrix3 """ assert(dcm.shape == (3, 3)) a = Vector3(dcm[0][0], dcm[0][1], dcm[0][2]) b = Vector3(dcm[1][0], dcm[1][1], dcm[1][2]) c = Vect...
Converts dcm array into Matrix3 :param dcm: 3x3 dcm array :returns: Matrix3
def update_by_example(cls, collection, example_data, new_value, keep_null=False, wait_for_sync=None, limit=None): """ This will find all documents in the collection that match the specified example object, and partially update the document body with the new value specified. Note that doc...
This will find all documents in the collection that match the specified example object, and partially update the document body with the new value specified. Note that document meta-attributes such as _id, _key, _from, _to etc. cannot be replaced. Note: the limit attribute is not sup...
async def websocket_disconnect(self, message): """ Handle the disconnect message. This is propagated to all upstream applications. """ # set this flag so as to ensure we don't send a downstream `websocket.close` message due to all # child applications closing. se...
Handle the disconnect message. This is propagated to all upstream applications.
def commit(func): '''Used as a decorator for automatically making session commits''' def wrap(**kwarg): with session_withcommit() as session: a = func(**kwarg) session.add(a) return session.query(songs).order_by( songs.song_id.desc()).first().song_id retur...
Used as a decorator for automatically making session commits
def utterances_from_tier(eafob: Eaf, tier_name: str) -> List[Utterance]: """ Returns utterances found in the given Eaf object in the given tier.""" try: speaker = eafob.tiers[tier_name][2]["PARTICIPANT"] except KeyError: speaker = None # We don't know the name of the speaker. tier_utte...
Returns utterances found in the given Eaf object in the given tier.
def Dirname(self): """Get a new copied object with only the directory path.""" result = self.Copy() while 1: last_directory = posixpath.dirname(result.last.path) if last_directory != "/" or len(result) <= 1: result.last.path = last_directory # Make sure to clear the inode inform...
Get a new copied object with only the directory path.
def fetchone(self, query, *args): """ Returns the first result of the given query. :param query: The query to be executed as a `str`. :param params: A `tuple` of parameters that will be replaced for placeholders in the query. :return: The retrieved row wit...
Returns the first result of the given query. :param query: The query to be executed as a `str`. :param params: A `tuple` of parameters that will be replaced for placeholders in the query. :return: The retrieved row with each field being one element in a `...
def writelines_nl(fileobj: TextIO, lines: Iterable[str]) -> None: """ Writes lines, plus terminating newline characters, to the file. (Since :func:`fileobj.writelines` doesn't add newlines... http://stackoverflow.com/questions/13730107/writelines-writes-lines-without-newline-just-fills-the-file) ""...
Writes lines, plus terminating newline characters, to the file. (Since :func:`fileobj.writelines` doesn't add newlines... http://stackoverflow.com/questions/13730107/writelines-writes-lines-without-newline-just-fills-the-file)
def load_file(self, app, pathname, relpath, pypath): """Loads a file and creates a View from it. Files are split between a YAML front-matter and the content (unless it is a .yml file). """ try: view_class = self.get_file_view_cls(relpath) return create_view_from_f...
Loads a file and creates a View from it. Files are split between a YAML front-matter and the content (unless it is a .yml file).
def _ensure_frames(cls, documents): """ Ensure all items in a list are frames by converting those that aren't. """ frames = [] for document in documents: if not isinstance(document, Frame): frames.append(cls(document)) else: ...
Ensure all items in a list are frames by converting those that aren't.
def ParseMessage(descriptor, byte_str): """Generate a new Message instance from this Descriptor and a byte string. Args: descriptor: Protobuf Descriptor object byte_str: Serialized protocol buffer byte string Returns: Newly created protobuf Message object. """ result_class = MakeClass(descriptor...
Generate a new Message instance from this Descriptor and a byte string. Args: descriptor: Protobuf Descriptor object byte_str: Serialized protocol buffer byte string Returns: Newly created protobuf Message object.
def infer_datetime_units(dates): """Given an array of datetimes, returns a CF compatible time-unit string of the form "{time_unit} since {date[0]}", where `time_unit` is 'days', 'hours', 'minutes' or 'seconds' (the first one that can evenly divide all unique time deltas in `dates`) """ dates = n...
Given an array of datetimes, returns a CF compatible time-unit string of the form "{time_unit} since {date[0]}", where `time_unit` is 'days', 'hours', 'minutes' or 'seconds' (the first one that can evenly divide all unique time deltas in `dates`)
def flush_stream_threads(process, out_formatter=None, err_formatter=terminal.fg.red, size=1): """ Context manager that creates 2 threads, one for each standard stream (stdout/stderr), updating in realtime the piped data. The formatters are callables that receives manipu...
Context manager that creates 2 threads, one for each standard stream (stdout/stderr), updating in realtime the piped data. The formatters are callables that receives manipulates the data, e.g. coloring it before writing to a ``sys`` stream. See ``FlushStreamThread`` for more information.
def get_item_query_session(self): """Gets the ``OsidSession`` associated with the item query service. return: (osid.assessment.ItemQuerySession) - an ``ItemQuerySession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_item_query()...
Gets the ``OsidSession`` associated with the item query service. return: (osid.assessment.ItemQuerySession) - an ``ItemQuerySession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_item_query()`` is ``false`` *compliance: optional...
def prepare_inputs(self, times=None, weather=None): """ Prepare the solar position, irradiance, and weather inputs to the model. Parameters ---------- times : None or DatetimeIndex, default None Times at which to evaluate the model. Can be None if ...
Prepare the solar position, irradiance, and weather inputs to the model. Parameters ---------- times : None or DatetimeIndex, default None Times at which to evaluate the model. Can be None if attribute `times` is already set. weather : None or DataFrame, ...