code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _get_batch_name(items, skip_jointcheck=False): """Retrieve the shared batch name for a group of items. """ batch_names = collections.defaultdict(int) has_joint = any([is_joint(d) for d in items]) for data in items: if has_joint and not skip_jointcheck: batches = dd.get_sample...
Retrieve the shared batch name for a group of items.
def _trychar(char, fallback, asciimode=None): # nocover """ Logic from IPython timeit to handle terminals that cant show mu Args: char (str): character, typically unicode, to try to use fallback (str): ascii character to use if stdout cannot encode char asciimode (bool): if True, a...
Logic from IPython timeit to handle terminals that cant show mu Args: char (str): character, typically unicode, to try to use fallback (str): ascii character to use if stdout cannot encode char asciimode (bool): if True, always use fallback Example: >>> char = _trychar('µs', 'u...
def build_date(self): """ get build date. :return: build date. None if not found """ # pylint: disable=len-as-condition if len(self.dutinformation) > 0 and (self.dutinformation.get(0).build is not None): return self.dutinformation.get(0).build.date re...
get build date. :return: build date. None if not found
def move_window(self, destination="", session=None): """ Move the current :class:`Window` object ``$ tmux move-window``. Parameters ---------- destination : str, optional the ``target window`` or index to move the window to, default: empty string ...
Move the current :class:`Window` object ``$ tmux move-window``. Parameters ---------- destination : str, optional the ``target window`` or index to move the window to, default: empty string session : str, optional the ``target session`` or index to mo...
def get_nearest_edges(G, X, Y, method=None, dist=0.0001): """ Return the graph edges nearest to a list of points. Pass in points as separate vectors of X and Y coordinates. The 'kdtree' method is by far the fastest with large data sets, but only finds approximate nearest edges if working in unprojec...
Return the graph edges nearest to a list of points. Pass in points as separate vectors of X and Y coordinates. The 'kdtree' method is by far the fastest with large data sets, but only finds approximate nearest edges if working in unprojected coordinates like lat-lng (it precisely finds the nearest edge ...
def _extract(self, identifier): ''' Extracts data from conjugation table. ''' conjugation = [] if self.tree.xpath('//p/b[normalize-space(text()) = "' + identifier.decode('utf-8') + '"]'): p = self.tree.xpath('//p/b[normalize-space(text()) = "' + identifier.decode('utf-8') + '"]')[0].getparent() for font in...
Extracts data from conjugation table.
def content_val(self, ymldata=None, messages=None): """Validates the Command Dictionary to ensure the contents for each of the fields meets specific criteria regarding the expected types, byte ranges, etc.""" self._ymlproc = YAMLProcessor(self._ymlfile, False) # Turn off the YAML Proce...
Validates the Command Dictionary to ensure the contents for each of the fields meets specific criteria regarding the expected types, byte ranges, etc.
def _parse_module_with_import(self, uri): """Look for functions and classes in an importable module. Parameters ---------- uri : str The name of the module to be parsed. This module needs to be importable. Returns ------- functions : list...
Look for functions and classes in an importable module. Parameters ---------- uri : str The name of the module to be parsed. This module needs to be importable. Returns ------- functions : list of str A list of (public) function names...
def _format_exitcodes(exitcodes): """Format a list of exit code with names of the signals if possible""" str_exitcodes = ["{}({})".format(_get_exitcode_name(e), e) for e in exitcodes if e is not None] return "{" + ", ".join(str_exitcodes) + "}"
Format a list of exit code with names of the signals if possible
def regex(self, *pattern, **kwargs): """ Add re pattern :param pattern: :type pattern: :return: self :rtype: Rebulk """ self.pattern(self.build_re(*pattern, **kwargs)) return self
Add re pattern :param pattern: :type pattern: :return: self :rtype: Rebulk
def _get_closest_ansi_color(r, g, b, exclude=()): """ Find closest ANSI color. Return it by name. :param r: Red (Between 0 and 255.) :param g: Green (Between 0 and 255.) :param b: Blue (Between 0 and 255.) :param exclude: A tuple of color names to exclude. (E.g. ``('ansired', )``.) """ ...
Find closest ANSI color. Return it by name. :param r: Red (Between 0 and 255.) :param g: Green (Between 0 and 255.) :param b: Blue (Between 0 and 255.) :param exclude: A tuple of color names to exclude. (E.g. ``('ansired', )``.)
def logger(self) -> Logger: """A :class:`logging.Logger` logger for the app. This can be used to log messages in a format as defined in the app configuration, for example, .. code-block:: python app.logger.debug("Request method %s", request.method) app.logger.e...
A :class:`logging.Logger` logger for the app. This can be used to log messages in a format as defined in the app configuration, for example, .. code-block:: python app.logger.debug("Request method %s", request.method) app.logger.error("Error, of some kind")
def _run_qmc(self, boot): """ runs quartet max-cut on a quartets file """ ## convert to txt file for wQMC self._tmp = os.path.join(self.dirs, ".tmpwtre") cmd = [ip.bins.qmc, "qrtt="+self.files.qdump, "otre="+self._tmp] ## run them proc = subprocess.Popen(cmd, stderr=su...
runs quartet max-cut on a quartets file
def get_push_commits(self, repository_id, push_id, project=None, top=None, skip=None, include_links=None): """GetPushCommits. Retrieve a list of commits associated with a particular push. :param str repository_id: The id or friendly name of the repository. To use the friendly name, projectId mus...
GetPushCommits. Retrieve a list of commits associated with a particular push. :param str repository_id: The id or friendly name of the repository. To use the friendly name, projectId must also be specified. :param int push_id: The id of the push. :param str project: Project ID or project...
def execute(self, query): """ Execute a query directly on the database. """ c = self.conn.cursor() result = c.execute(query) for i in result: yield i
Execute a query directly on the database.
def get_element_tree(parent_to_parse): """ :return: an ElementTree initialized with the parsed element. :see: get_element(parent_to_parse, element_path) """ if isinstance(parent_to_parse, ElementTree): return parent_to_parse element = get_element(parent_to_parse) return ElementTre...
:return: an ElementTree initialized with the parsed element. :see: get_element(parent_to_parse, element_path)
def next_address_avoid_collision(self, start_addr): """Finds the next address recursively which does not collide with any other address""" i = 1 while self.is_address_in_use(next_addr(start_addr, i)): i += 1 return next_addr(start_addr, i)
Finds the next address recursively which does not collide with any other address
def handle_POST(self, environ, start_response): """Handles the HTTP POST request. Attempts to interpret all HTTP POST requests as XML-RPC calls, which are forwarded to the server's _dispatch method for handling. Most code taken from SimpleXMLRPCServer with modifications for wsgi and my...
Handles the HTTP POST request. Attempts to interpret all HTTP POST requests as XML-RPC calls, which are forwarded to the server's _dispatch method for handling. Most code taken from SimpleXMLRPCServer with modifications for wsgi and my custom dispatcher.
def __on_message(self, ws, message): '''Handler for parsing WS messages.''' message = json.loads(message) self.logger.debug(json.dumps(message)) table = message['table'] if 'table' in message else None action = message['action'] if 'action' in message else None try: ...
Handler for parsing WS messages.
def is_number(obj): """ Helper function to determine numbers across Python 2.x and 3.x """ try: from numbers import Number except ImportError: from operator import isNumberType return isNumberType(obj) else: return isinstance(obj, Number)
Helper function to determine numbers across Python 2.x and 3.x
def update(self): """ Get the latest status information from device. Method executes the update method for the current receiver type. """ if self._receiver_type == AVR_X_2016.type: return self._update_avr_2016() else: return self._update_avr()
Get the latest status information from device. Method executes the update method for the current receiver type.
def dragMoveEvent( self, event ): """ Processes the drag drop event using the filter set by the \ setDragDropFilter :param event | <QDragEvent> """ filt = self.dragDropFilter() if not filt: super(XTreeWidget, self).dragMoveEvent(...
Processes the drag drop event using the filter set by the \ setDragDropFilter :param event | <QDragEvent>
def is_training(): """Get status on training/predicting. Returns ------- Current state of training/predicting. """ curr = ctypes.c_bool() check_call(_LIB.MXAutogradIsTraining(ctypes.byref(curr))) return curr.value
Get status on training/predicting. Returns ------- Current state of training/predicting.
def __parseParameters(self): """Parses the parameters of data.""" self.__parameters = [] for parameter in self.__data['parameters']: self.__parameters.append(Parameter(parameter))
Parses the parameters of data.
def _onLexerError(self, message): """Memorizes a lexer error message""" self.isOK = False if message.strip() != "": self.lexerErrors.append(message)
Memorizes a lexer error message
def toupper(self): """ Translate characters from lower to upper case for a particular column. :returns: new H2OFrame with all strings in the current frame converted to the uppercase. """ return H2OFrame._expr(expr=ExprNode("toupper", self), cache=self._ex._cache)
Translate characters from lower to upper case for a particular column. :returns: new H2OFrame with all strings in the current frame converted to the uppercase.
def modify_identity(self, identity, **kwargs): """ Modify some attributes of an identity or its name. :param: identity a zobjects.Identity with `id` set (mandatory). Also set items you want to modify/set and/or the `name` attribute to rename the identity. Ca...
Modify some attributes of an identity or its name. :param: identity a zobjects.Identity with `id` set (mandatory). Also set items you want to modify/set and/or the `name` attribute to rename the identity. Can also take the name in string and then attributes to modif...
def sub_menu(request, page_id): """Render the children of the requested page with the sub_menu template.""" page = Page.objects.get(id=page_id) pages = page.children.all() page_languages = settings.PAGE_LANGUAGES return render_to_response("admin/basic_cms/page/sub_menu.html", { 'page': p...
Render the children of the requested page with the sub_menu template.
def validateDocumentFinal(self, doc): """Does the final step for the document validation once all the incremental validation steps have been completed basically it does the following checks described by the XML Rec Check all the IDREF/IDREFS attributes definition for va...
Does the final step for the document validation once all the incremental validation steps have been completed basically it does the following checks described by the XML Rec Check all the IDREF/IDREFS attributes definition for validity
def get_objective_hierarchy_design_session_for_objective_bank(self, objective_bank_id, proxy): """Gets the ``OsidSession`` associated with the objective hierarchy design service for the given objective bank. arg: objective_bank_id (osid.id.Id): the ``Id`` of the objective bank ...
Gets the ``OsidSession`` associated with the objective hierarchy design service for the given objective bank. arg: objective_bank_id (osid.id.Id): the ``Id`` of the objective bank arg: proxy (osid.proxy.Proxy): a proxy return: (osid.learning.ObjectiveHierarchyDesignSession...
def only_horizon(meshes, xs, ys, zs, expose_horizon=False): """ Check all visible or partial triangles to see if they're behind the horizon, by checking the direction of the z-component of the normals (ie hidden if mu<0) """ # if visibility == 0, it should remain 0 # if visibility == 0.5, it sh...
Check all visible or partial triangles to see if they're behind the horizon, by checking the direction of the z-component of the normals (ie hidden if mu<0)
def DownloadData(name='all', data_dir=DataPath()): """ Downloads fit data to DataPath() diretory. If name='all', gets all fit data. """ if name == 'all': for tmp_name in fits_collection.keys(): DownloadData(name=tmp_name, data_dir=data_dir) return if name not in fits...
Downloads fit data to DataPath() diretory. If name='all', gets all fit data.
def p_file_cr_text_1(self, p): """file_cr_text : FILE_CR_TEXT file_cr_value""" try: self.builder.set_file_copyright(self.document, p[2]) except OrderError: self.order_error('FileCopyrightText', 'FileName', p.lineno(1)) except CardinalityError: self.mor...
file_cr_text : FILE_CR_TEXT file_cr_value
def _append_national_number(self, national_number): """Combines the national number with any prefix (IDD/+ and country code or national prefix) that was collected. A space will be inserted between them if the current formatting template indicates this to be suitable. """ ...
Combines the national number with any prefix (IDD/+ and country code or national prefix) that was collected. A space will be inserted between them if the current formatting template indicates this to be suitable.
def rebuild(self, scene=None): """ This method is where you will rebuild the geometry and \ data for a node. :param scene <QGraphicsScene> || None :return <bool> success """ rect = QRectF(0, 0, self.minimumWidth(), self.minimumHeig...
This method is where you will rebuild the geometry and \ data for a node. :param scene <QGraphicsScene> || None :return <bool> success
def definition_rst(self, definition, spec_path=None): ''' Prepare and write information about definition :param definition: --name of definition that would be prepared for render :type definition: str, unicode :param spec_path: --path to definitions :type spec_path: str, ...
Prepare and write information about definition :param definition: --name of definition that would be prepared for render :type definition: str, unicode :param spec_path: --path to definitions :type spec_path: str, unicode :return:
def Write(self, schedule, output_file): """Writes out a feed as KML. Args: schedule: A transitfeed.Schedule object containing the feed to write. output_file: The name of the output KML file, or file object to use. """ # Generate the DOM to write root = ET.Element('kml') root.attrib[...
Writes out a feed as KML. Args: schedule: A transitfeed.Schedule object containing the feed to write. output_file: The name of the output KML file, or file object to use.
def save_to_file(filename, content): """ Save content to file. Used by node initial contact but can be used anywhere. :param str filename: name of file to save to :param str content: content to save :return: None :raises IOError: permissions issue saving, invalid directory, etc """ ...
Save content to file. Used by node initial contact but can be used anywhere. :param str filename: name of file to save to :param str content: content to save :return: None :raises IOError: permissions issue saving, invalid directory, etc
def build_pydot(self, G=None): # pragma: no cover """ Build a pydot representation of this model. This needs pydot installed. Example Usage:: np.random.seed(1000) X = np.random.normal(0,1,(20,2)) beta = np.random.uniform(0,1,(2,1)) Y = X.dot(beta...
Build a pydot representation of this model. This needs pydot installed. Example Usage:: np.random.seed(1000) X = np.random.normal(0,1,(20,2)) beta = np.random.uniform(0,1,(2,1)) Y = X.dot(beta) m = RidgeRegression(X, Y) G = m.build_pydot(...
def peaking(GdB, fc, Q=3.5, fs=44100.): """ A second-order peaking filter having GdB gain at fc and approximately and 0 dB otherwise. The filter coefficients returns correspond to a biquadratic system function containing five parameters. Parameters ---------- GdB : Lowpass gain...
A second-order peaking filter having GdB gain at fc and approximately and 0 dB otherwise. The filter coefficients returns correspond to a biquadratic system function containing five parameters. Parameters ---------- GdB : Lowpass gain in dB fc : Center frequency in Hz Q : Filte...
def create_keypair(self, xml_bytes): """Parse the XML returned by the C{CreateKeyPair} function. @param xml_bytes: XML bytes with a C{CreateKeyPairResponse} root element. @return: The L{Keypair} instance created. """ keypair_data = XML(xml_bytes) key_name = k...
Parse the XML returned by the C{CreateKeyPair} function. @param xml_bytes: XML bytes with a C{CreateKeyPairResponse} root element. @return: The L{Keypair} instance created.
def signal_optimiser(d, analytes, min_points=5, threshold_mode='kde_first_max', threshold_mult=1., x_bias=0, weights=None, ind=None, mode='minimise'): """ Optimise data selection based on specified analytes. Identifies the longest possible cont...
Optimise data selection based on specified analytes. Identifies the longest possible contiguous data region in the signal where the relative standard deviation (std) and concentration of all analytes is minimised. Optimisation is performed via a grid search of all possible contiguous data regions...
def subnet2block(subnet): """Convert a dotted-quad ip address including a netmask into a tuple containing the network block start and end addresses. >>> subnet2block('127.0.0.1/255.255.255.255') ('127.0.0.1', '127.0.0.1') >>> subnet2block('127/255') ('127.0.0.0', '127.255.255.255') >>> sub...
Convert a dotted-quad ip address including a netmask into a tuple containing the network block start and end addresses. >>> subnet2block('127.0.0.1/255.255.255.255') ('127.0.0.1', '127.0.0.1') >>> subnet2block('127/255') ('127.0.0.0', '127.255.255.255') >>> subnet2block('127.0.1/255.255') ...
def process_action(self, raw_user, channel, raw_message): """Called when a message is received from a channel or user.""" log.info("%s %s %s", channel, raw_user, raw_message) if not raw_user: # ignore server messages return # This monster of a regex extracts msg...
Called when a message is received from a channel or user.
def get_pages(parser, token): """Add to context the list of page links. Usage: .. code-block:: html+django {% get_pages %} This is mostly used for Digg-style pagination. This call inserts in the template context a *pages* variable, as a sequence of page links. You can use *pages* in ...
Add to context the list of page links. Usage: .. code-block:: html+django {% get_pages %} This is mostly used for Digg-style pagination. This call inserts in the template context a *pages* variable, as a sequence of page links. You can use *pages* in different ways: - just print *pa...
def do_cleaning(self, arg): """Does the actual cleaning by using the delete methods above. :param arg: A string, the string which shell be cleaned. Or a list, in which case each of the strings within the list is cleaned. :return: A string, the cleaned string. Or a list with cleaned stri...
Does the actual cleaning by using the delete methods above. :param arg: A string, the string which shell be cleaned. Or a list, in which case each of the strings within the list is cleaned. :return: A string, the cleaned string. Or a list with cleaned string entries.
def plot_root_to_tip(self, add_internal=False, label=True, ax=None): """ Plot root-to-tip regression Parameters ---------- add_internal : bool If true, plot inte`rnal node positions label : bool If true, label the plots ax : matplotlib axe...
Plot root-to-tip regression Parameters ---------- add_internal : bool If true, plot inte`rnal node positions label : bool If true, label the plots ax : matplotlib axes If not None, use the provided matplotlib axes to plot the results
def restricted_cover(l, succsOf): """ Returns a restricted <succsOf> which only takes and yields values from <l> """ fzl = frozenset(l) lut = dict() for i in l: lut[i] = fzl.intersection(succsOf(i)) return lambda x: lut[x]
Returns a restricted <succsOf> which only takes and yields values from <l>
def execute(self, context): """ Uploads the file to Google cloud storage """ hook = GoogleCloudStorageHook( google_cloud_storage_conn_id=self.google_cloud_storage_conn_id, delegate_to=self.delegate_to) hook.upload( bucket_name=self.bucket, ...
Uploads the file to Google cloud storage
def lipd_read(path): """ Loads a LiPD file from local path. Unzip, read, and process data Steps: create tmp, unzip lipd, read files into memory, manipulate data, move to original dir, delete tmp. :param str path: Source path :return none: """ _j = {} dir_original = os.getcwd() # Im...
Loads a LiPD file from local path. Unzip, read, and process data Steps: create tmp, unzip lipd, read files into memory, manipulate data, move to original dir, delete tmp. :param str path: Source path :return none:
def get_seh_chain(self): """ @rtype: list of tuple( int, int ) @return: List of structured exception handlers. Each SEH is represented as a tuple of two addresses: - Address of this SEH block - Address of the SEH callback function Do not c...
@rtype: list of tuple( int, int ) @return: List of structured exception handlers. Each SEH is represented as a tuple of two addresses: - Address of this SEH block - Address of the SEH callback function Do not confuse this with the contents of the SEH bloc...
def memory(self): """ The maximum number of bytes of memory the job will require to run. """ if self._memory is not None: return self._memory elif self._config is not None: return self._config.defaultMemory else: raise AttributeError("D...
The maximum number of bytes of memory the job will require to run.
def _remove_attributes(attrs, remove_list): """ Removes attributes in the remove list from the input attribute dict :param attrs : Dict of operator attributes :param remove_list : list of attributes to be removed :return new_attr : Dict of operator attributes without the listed attributes. """ ...
Removes attributes in the remove list from the input attribute dict :param attrs : Dict of operator attributes :param remove_list : list of attributes to be removed :return new_attr : Dict of operator attributes without the listed attributes.
def children(self, unroll=False, skip_not_present=True): """ Returns an iterator that provides nodes for all immediate children of this component. Parameters ---------- unroll : bool If True, any children that are arrays are unrolled. skip_not_presen...
Returns an iterator that provides nodes for all immediate children of this component. Parameters ---------- unroll : bool If True, any children that are arrays are unrolled. skip_not_present : bool If True, skips children whose 'ispresent' property is se...
def _findSwipl(): """ This function makes a big effort to find the path to the SWI-Prolog shared library. Since this is both OS dependent and installation dependent, we may not aways succeed. If we do, we return a name/path that can be used by CDLL(). Otherwise we raise an exception. :return: T...
This function makes a big effort to find the path to the SWI-Prolog shared library. Since this is both OS dependent and installation dependent, we may not aways succeed. If we do, we return a name/path that can be used by CDLL(). Otherwise we raise an exception. :return: Tuple. Fist element is the name...
def trt_pmf(matrices): """ Fold full disaggregation matrix to tectonic region type PMF. :param matrices: a matrix with T submatrices :returns: an array of T probabilities one per each tectonic region type """ ntrts, nmags, ndists, nlons, nlats, neps = matrices.shape pmf = nu...
Fold full disaggregation matrix to tectonic region type PMF. :param matrices: a matrix with T submatrices :returns: an array of T probabilities one per each tectonic region type
def _get_consumption(self, url, start, end, aggregation): """ Request for both the get_consumption and get_sensor_consumption methods. Parameters ---------- url : str start : dt.datetime end : dt.datetime aggregation : int Returns ...
Request for both the get_consumption and get_sensor_consumption methods. Parameters ---------- url : str start : dt.datetime end : dt.datetime aggregation : int Returns ------- dict
def rankdata(inlist): """ Ranks the data in inlist, dealing with ties appropritely. Assumes a 1D inlist. Adapted from Gary Perlman's |Stat ranksort. Usage: rankdata(inlist) Returns: a list of length equal to inlist, containing rank scores """ n = len(inlist) svec, ivec = shellsort(inlist) sumranks ...
Ranks the data in inlist, dealing with ties appropritely. Assumes a 1D inlist. Adapted from Gary Perlman's |Stat ranksort. Usage: rankdata(inlist) Returns: a list of length equal to inlist, containing rank scores
def load_system_host_keys(self, filename=None): """ Load host keys from a system (read-only) file. Host keys read with this method will not be saved back by `save_host_keys`. This method can be called multiple times. Each new set of host keys will be merged with the existing s...
Load host keys from a system (read-only) file. Host keys read with this method will not be saved back by `save_host_keys`. This method can be called multiple times. Each new set of host keys will be merged with the existing set (new replacing old if there are conflicts). If `...
def pool_create_event(self, pool_info): """Process pool create event. Extract pool info and get listener info and call next listen_create_event """ pool_data = pool_info.get('pool') listeners = pool_data.get('listeners') for listener in listeners: l_i...
Process pool create event. Extract pool info and get listener info and call next listen_create_event
def set_config_defaults(args): """ Set configuration defaults :param args: a dict of arguments :type args: dict :return: a dict of arguments :rtype: dict """ defaults = { 'fail': 'fast', 'stdout': 'fail' } for key in defaults: if not args[k...
Set configuration defaults :param args: a dict of arguments :type args: dict :return: a dict of arguments :rtype: dict
def synchronize(self, func=None, wait=None, errors=()): """ This method is Capybara's primary defense against asynchronicity problems. It works by attempting to run a given decorated function until it succeeds. The exact behavior of this method depends on a number of factors. Basically t...
This method is Capybara's primary defense against asynchronicity problems. It works by attempting to run a given decorated function until it succeeds. The exact behavior of this method depends on a number of factors. Basically there are certain exceptions which, when raised from the decorated fu...
def p_select_related_where_statement(self, p): ''' statement : SELECT ONE variable_name RELATED BY navigation_hook navigation_chain WHERE expression | SELECT ANY variable_name RELATED BY navigation_hook navigation_chain WHERE expression | SELECT MANY variable_name R...
statement : SELECT ONE variable_name RELATED BY navigation_hook navigation_chain WHERE expression | SELECT ANY variable_name RELATED BY navigation_hook navigation_chain WHERE expression | SELECT MANY variable_name RELATED BY navigation_hook navigation_chain WHERE expression
def save_data(self, trigger_id, **data): """ let's save the data :param trigger_id: trigger ID from which to save data :param data: the data to check to be used and save :type trigger_id: int :type data: dict :return: the status of the sav...
let's save the data :param trigger_id: trigger ID from which to save data :param data: the data to check to be used and save :type trigger_id: int :type data: dict :return: the status of the save statement :rtype: boolean
def from_xml(cls, data, api=None, parser=None): """ Create a new instance and load data from xml data or object. .. note:: If parser is set to None, the functions tries to find the best parse. By default the SAX parser is chosen if a string is provided as data. ...
Create a new instance and load data from xml data or object. .. note:: If parser is set to None, the functions tries to find the best parse. By default the SAX parser is chosen if a string is provided as data. The parser is set to DOM if an xml.etree.ElementTree.Elem...
def get(self,request,*args,**kwargs): ''' Allow passing of basis and time limitations ''' try: year = int(self.kwargs.get('year')) except (ValueError, TypeError): year = getIntFromGet(request,'year') kwargs.update({ 'year': year, ...
Allow passing of basis and time limitations
def _sample_chain(args): """Sample a single chain for OptGPSampler. center and n_samples are updated locally and forgotten afterwards. """ n, idx = args # has to be this way to work in Python 2.7 center = sampler.center np.random.seed((sampler._seed + idx) % np.iinfo(np.int32).max) ...
Sample a single chain for OptGPSampler. center and n_samples are updated locally and forgotten afterwards.
def watch_log_for(self, exprs, from_mark=None, timeout=600, process=None, verbose=False, filename='system.log'): """ Watch the log until one or more (regular) expression are found. This methods when all the expressions have been found or the method timeouts (a TimeoutError is then raised...
Watch the log until one or more (regular) expression are found. This methods when all the expressions have been found or the method timeouts (a TimeoutError is then raised). On successful completion, a list of pair (line matched, match object) is returned.
def get_chain_details_by_related_pdb_chains(self, pdb_id, chain_id, pfam_accs): ''' Returns a dict of SCOPe details using info This returns Pfam-level information for a PDB chain i.e. no details on the protein, species, or domain will be returned. If there are SCOPe entries for the assoc...
Returns a dict of SCOPe details using info This returns Pfam-level information for a PDB chain i.e. no details on the protein, species, or domain will be returned. If there are SCOPe entries for the associated Pfam accession numbers which agree then this function returns pretty compl...
def conv_cy(self, cy_cl): """Convert cycles (cy/CL) to other units, such as FLOP/s or It/s.""" if not isinstance(cy_cl, PrefixedUnit): cy_cl = PrefixedUnit(cy_cl, '', 'cy/CL') clock = self.machine['clock'] element_size = self.kernel.datatypes_size[self.kernel.datatype] ...
Convert cycles (cy/CL) to other units, such as FLOP/s or It/s.
def by_interval_lookup(self, style_key, style_value): """Return a processor for an "interval" style value. Parameters ---------- style_key : str A style key. style_value : dict A dictionary with an "interval" key whose value consists of a sequ...
Return a processor for an "interval" style value. Parameters ---------- style_key : str A style key. style_value : dict A dictionary with an "interval" key whose value consists of a sequence of tuples where each tuple should have the form `(start, ...
def check_call(state, callstr, argstr=None, expand_msg=None): """When checking a function definition of lambda function, prepare has_equal_x for checking the call of a user-defined function. Args: callstr (str): call string that specifies how the function should be called, e.g. `f(1, a = 2)`. ...
When checking a function definition of lambda function, prepare has_equal_x for checking the call of a user-defined function. Args: callstr (str): call string that specifies how the function should be called, e.g. `f(1, a = 2)`. ``check_call()`` will replace ``f`` with the function/lambda yo...
def response(status, description, resource=DefaultResource): # type: (HTTPStatus, str, Optional[Resource]) -> Callable """ Define an expected response. The values are based off `Swagger <https://swagger.io/specification>`_. """ def inner(o): value = Response(status, description, resour...
Define an expected response. The values are based off `Swagger <https://swagger.io/specification>`_.
def parse_subscription(self, params, region, subscription): """ Parse a single subscription and reference it in its corresponding topic :param params: Global parameters (defaults to {}) :param subscription: SNS Subscription """ topic_arn = sub...
Parse a single subscription and reference it in its corresponding topic :param params: Global parameters (defaults to {}) :param subscription: SNS Subscription
def escape(s): """Convert the characters &, <, >, ' and " in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. Marks return value as markup string. """ if hasattr(s, '__html__'): return s.__html__() return Markup(text_type...
Convert the characters &, <, >, ' and " in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. Marks return value as markup string.
def openParametersDialog(params, title=None): ''' Opens a dialog to enter parameters. Parameters are passed as a list of Parameter objects Returns a dict with param names as keys and param values as values Returns None if the dialog was cancelled ''' QApplication.setOverrideCursor(QCursor(Qt...
Opens a dialog to enter parameters. Parameters are passed as a list of Parameter objects Returns a dict with param names as keys and param values as values Returns None if the dialog was cancelled
def _init_steps(self,): """ Given the flow config and everything else, create a list of steps to run, sorted by step number. :return: List[StepSpec] """ self._check_old_yaml_format() config_steps = self.flow_config.steps self._check_infinite_flows(config_steps) ...
Given the flow config and everything else, create a list of steps to run, sorted by step number. :return: List[StepSpec]
def cmd_export_all(*args): """ Arguments: <output folder> [-- [--quality <0-100>] [--page_format <page_format>]] Export all documents as PDF files. Default quality is 50. Default page format is A4. Possible JSON replies: -- { "status": "error", "exception":...
Arguments: <output folder> [-- [--quality <0-100>] [--page_format <page_format>]] Export all documents as PDF files. Default quality is 50. Default page format is A4. Possible JSON replies: -- { "status": "error", "exception": "yyy", "reason": "xxxx", "...
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the Locate request payload to a buffer. Args: output_buffer (stream): A data buffer in which to encode object data, supporting a write method. kmip_versio...
Write the data encoding the Locate request payload to a buffer. Args: output_buffer (stream): A data buffer in which to encode object data, supporting a write method. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the obje...
def clean_key(self): """ Validate the key contains an email address. """ key = self.cleaned_data["key"] gpg = get_gpg() result = gpg.import_keys(key) if result.count == 0: raise forms.ValidationError(_("Invalid Key")) return key
Validate the key contains an email address.
def subscribe(self, user_token, topic): """ Subscribe a user to the given topic. :param str user_token: The token of the user. :param str topic: The topic. :raises `requests.exceptions.HTTPError`: If an HTTP error occurred. """ response = _request('POST', ...
Subscribe a user to the given topic. :param str user_token: The token of the user. :param str topic: The topic. :raises `requests.exceptions.HTTPError`: If an HTTP error occurred.
def _compile(self, compile_request): """Perform the process of compilation, writing object files to the request's 'output_dir'. NB: This method must arrange the output files so that `collect_cached_objects()` can collect all of the results (or vice versa)! """ try: argv = self._make_compile_...
Perform the process of compilation, writing object files to the request's 'output_dir'. NB: This method must arrange the output files so that `collect_cached_objects()` can collect all of the results (or vice versa)!
def serialize_transaction(inputs, outputs, lock_time=0, version=1): """ Serializes a transaction. """ # add in the inputs serialized_inputs = ''.join([serialize_input(input) for input in inputs]) # add in the outputs serialized_outputs = ''.join([serialize_output(output) for output in outputs]...
Serializes a transaction.
def has_colors(stream): """ Determine if the terminal supports ansi colors. """ if not hasattr(stream, "isatty"): return False if not stream.isatty(): return False # auto color only on TTYs try: import curses curses.setupterm() return curses.tigetnum("col...
Determine if the terminal supports ansi colors.
def rnoncentral_t(mu, lam, nu, size=None): """ Non-central Student's t random variates. """ tau = rgamma(nu / 2., nu / (2. * lam), size) return rnormal(mu, tau)
Non-central Student's t random variates.
def show_stories(self, raw=False, limit=None): """Returns list of item ids of latest Show HN stories Args: limit (int): specifies the number of stories to be returned. raw (bool): Flag to indicate whether to transform all objects into raw json. Returns: ...
Returns list of item ids of latest Show HN stories Args: limit (int): specifies the number of stories to be returned. raw (bool): Flag to indicate whether to transform all objects into raw json. Returns: `list` object containing ids of Show HN storie...
def clean_video_data(_data): """ Clean video data: -> cleans title -> ... Args: _data (dict): Information about the video. Returns: dict: Refined video data. """ data = _data.copy() # TODO: fix this ugliness title = data.get('title') if title: ...
Clean video data: -> cleans title -> ... Args: _data (dict): Information about the video. Returns: dict: Refined video data.
def RemoveNIC(self,network_id): """Remove the NIC associated with the provided network from the server. https://www.ctl.io/api-docs/v2/#servers-remove-secondary-network network_id - ID associated with the network to remove >>> network = clc.v2.Networks(location="VA1").Get("10.128.166.0/24") >>>...
Remove the NIC associated with the provided network from the server. https://www.ctl.io/api-docs/v2/#servers-remove-secondary-network network_id - ID associated with the network to remove >>> network = clc.v2.Networks(location="VA1").Get("10.128.166.0/24") >>> clc.v2.Server(alias='BTDI',id='WA1BT...
def autosave(self, index): """ Autosave a file. Do nothing if the `changed_since_autosave` flag is not set or the file is newly created (and thus not named by the user). Otherwise, save a copy of the file with the name given by `self.get_autosave_filename()` and clear th...
Autosave a file. Do nothing if the `changed_since_autosave` flag is not set or the file is newly created (and thus not named by the user). Otherwise, save a copy of the file with the name given by `self.get_autosave_filename()` and clear the `changed_since_autosave` flag. Errors raised ...
def connect(self, nice_quit_ev): """Connect the server. We expect this to implement backoff and all connection logistics for servers that were discovered via a lookup node. """ _logger.debug("Connecting to discovered node: [%s]", self.server_host) stop_epoch = time.t...
Connect the server. We expect this to implement backoff and all connection logistics for servers that were discovered via a lookup node.
def docgraph2freqt(docgraph, root=None, include_pos=False, escape_func=FREQT_ESCAPE_FUNC): """convert a docgraph into a FREQT string.""" if root is None: return u"\n".join( sentence2freqt(docgraph, sentence, include_pos=include_pos, escape_func=e...
convert a docgraph into a FREQT string.
def runStickyEregressions(infile_name,interval_size,meas_err,sticky,all_specs): ''' Runs regressions for the main tables of the StickyC paper and produces a LaTeX table with results for one "panel". Parameters ---------- infile_name : str Name of tab-delimited text file with simulation ...
Runs regressions for the main tables of the StickyC paper and produces a LaTeX table with results for one "panel". Parameters ---------- infile_name : str Name of tab-delimited text file with simulation data. Assumed to be in the results directory, and was almost surely generated by ma...
def name(self): """Return the complete file and path name of the file.""" return str(conf.lib.clang_getCString(conf.lib.clang_getFileName(self)))
Return the complete file and path name of the file.
def _deprecated_kwargs(kwargs, arg_newarg): """ arg_newarg is a list of tuples, where each tuple has a pair of strings. ('old_arg', 'new_arg') A DeprecationWarning is raised for the arguments that need to be replaced. """ warn_for = [] for (arg, new_kw) in arg_newarg: if ...
arg_newarg is a list of tuples, where each tuple has a pair of strings. ('old_arg', 'new_arg') A DeprecationWarning is raised for the arguments that need to be replaced.
def load(self, languages=[]): """Loads the Duckling corpus. Languages can be specified, defaults to all. Args: languages: Optional parameter to specify languages, e.g. [Duckling.ENGLISH, Duckling.FRENCH] or supported ISO 639-1 Codes (e.g. ["en", "fr"]) """ ...
Loads the Duckling corpus. Languages can be specified, defaults to all. Args: languages: Optional parameter to specify languages, e.g. [Duckling.ENGLISH, Duckling.FRENCH] or supported ISO 639-1 Codes (e.g. ["en", "fr"])
def name(function): """ Retrieve a pretty name for the function :param function: function to get name from :return: pretty name """ if isinstance(function, types.FunctionType): return function.__name__ else: return str(function)
Retrieve a pretty name for the function :param function: function to get name from :return: pretty name
def list_nodes_select(call=None): ''' Return a list of the VMs that are on the provider, with select fields ''' if not call: call = 'select' if not get_configured_provider(): return info = ['id', 'name', 'image', 'size', 'state', 'public_ips', 'private_ips'] return salt.utils...
Return a list of the VMs that are on the provider, with select fields
def rating(self, value): """Set the rating parameter and regenerate the thumbnail link.""" self._rating = value self._thumb = self._link_to_img()
Set the rating parameter and regenerate the thumbnail link.
def get_default_params(type='BSPLINE'): """ get_default_params(type='BSPLINE') Get `Parameters` struct with parameters that users may want to tweak. The given `type` specifies the type of allowed transform, and can be 'RIGID', 'AFFINE', 'BSPLINE'. For detail on what parameters are availabl...
get_default_params(type='BSPLINE') Get `Parameters` struct with parameters that users may want to tweak. The given `type` specifies the type of allowed transform, and can be 'RIGID', 'AFFINE', 'BSPLINE'. For detail on what parameters are available and how they should be used, we refer to t...
def parse_delay_import_directory(self, rva, size): """Walk and parse the delay import directory.""" import_descs = [] while True: try: # If the RVA is invalid all would blow up. Some PEs seem to be # specially nasty and have an invalid RVA. ...
Walk and parse the delay import directory.