positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def complete(self): """ Determine if the analyses of the strains are complete e.g. there are no missing GDCS genes, and the sample.general.bestassemblyfile != 'NA' """ # Boolean to store the completeness of the analyses allcomplete = True # Clear the list of samp...
Determine if the analyses of the strains are complete e.g. there are no missing GDCS genes, and the sample.general.bestassemblyfile != 'NA'
def browse(self, folder, levels=None, prefix=None): """ Returns the directory tree of the global model. Directories are always JSON objects (map/dictionary), and files are always arrays of modification time and size. The first integer is the files modification time, and the ...
Returns the directory tree of the global model. Directories are always JSON objects (map/dictionary), and files are always arrays of modification time and size. The first integer is the files modification time, and the second integer is the file size. Args: ...
def set_level(self, val): """Set the device ON LEVEL.""" if val == 0: self.off() elif val == 255: self.on() else: setlevel = 255 if val < 1: setlevel = val * 255 elif val <= 0xff: setlevel = val ...
Set the device ON LEVEL.
def bindToProperty(self,instance,propertyName,useGetter=False): """ 2-way binds to an instance property. Parameters: - instance -- the object instance - propertyName -- the name of the property to bind to - useGetter: when True, calls the getter method to obtain the valu...
2-way binds to an instance property. Parameters: - instance -- the object instance - propertyName -- the name of the property to bind to - useGetter: when True, calls the getter method to obtain the value. When False, the signal argument is used as input for the target setter. (default ...
def get_default_property_values(self, classname): """Return a dict with default values for all properties declared on this class.""" schema_element = self.get_element_by_class_name(classname) result = { property_name: property_descriptor.default for property_name, proper...
Return a dict with default values for all properties declared on this class.
def LayerNorm( x, epsilon=1e-5, use_bias=True, use_scale=True, gamma_init=None, data_format='channels_last'): """ Layer Normalization layer, as described in the paper: `Layer Normalization <https://arxiv.org/abs/1607.06450>`_. Args: x (tf.Tensor): a 4D or 2D tensor. When...
Layer Normalization layer, as described in the paper: `Layer Normalization <https://arxiv.org/abs/1607.06450>`_. Args: x (tf.Tensor): a 4D or 2D tensor. When 4D, the layout should match data_format. epsilon (float): epsilon to avoid divide-by-zero. use_scale, use_bias (bool): whether to...
def get_iso_time(): '''returns time as ISO string, mapping to and from datetime in ugly way convert to string with str() ''' t1 = time.time() t2 = datetime.datetime.fromtimestamp(t1) t4 = t2.__str__() try: t4a, t4b = t4.split(".", 1) except ValueError: t4a = t...
returns time as ISO string, mapping to and from datetime in ugly way convert to string with str()
def main(): """ NAME s_hext.py DESCRIPTION calculates Hext statistics for tensor data SYNTAX s_hext.py [-h][-i][-f file] [<filename] OPTIONS -h prints help message and quits -f file specifies filename on command line -l NMEAS do line by line instead of...
NAME s_hext.py DESCRIPTION calculates Hext statistics for tensor data SYNTAX s_hext.py [-h][-i][-f file] [<filename] OPTIONS -h prints help message and quits -f file specifies filename on command line -l NMEAS do line by line instead of whole file, use number ...
def summary(*samples): """Run SignatureCompareRelatedSimple module from qsignature tool. Creates a matrix of pairwise comparison among samples. The function will not run if the output exists :param samples: list with only one element containing all samples information :returns: (dict) with the pat...
Run SignatureCompareRelatedSimple module from qsignature tool. Creates a matrix of pairwise comparison among samples. The function will not run if the output exists :param samples: list with only one element containing all samples information :returns: (dict) with the path of the output to be joined t...
def _read(self, size): """Return size bytes from the stream. """ if self.comptype == "tar": return self.__read(size) c = len(self.dbuf) while c < size: buf = self.__read(self.bufsize) if not buf: break try: ...
Return size bytes from the stream.
def get_composition(self, composition_id): """Gets the ``Composition`` specified by its ``Id``. arg: composition_id (osid.id.Id): ``Id`` of the ``Composiiton`` return: (osid.repository.Composition) - the composition raise: NotFound - ``composition_id`` not found ...
Gets the ``Composition`` specified by its ``Id``. arg: composition_id (osid.id.Id): ``Id`` of the ``Composiiton`` return: (osid.repository.Composition) - the composition raise: NotFound - ``composition_id`` not found raise: NullArgument - ``composition_id`` is ``nul...
def _on_dirty_changed(self, dirty): """ Adds a star in front of a dirtt tab and emits dirty_changed. """ try: title = self._current._tab_name index = self.indexOf(self._current) if dirty: self.setTabText(index, "* " + title) ...
Adds a star in front of a dirtt tab and emits dirty_changed.
def yaml_force_unicode(): """ Force pyyaml to return unicode values. """ #/ ## modified from |http://stackoverflow.com/a/2967461| if sys.version_info[0] == 2: def construct_func(self, node): return self.construct_scalar(node) yaml.L...
Force pyyaml to return unicode values.
def columns(self, model=None): """ Returns any columns used within this query. :return [<orb.Column>, ..] """ for query in self.__queries: for column in query.columns(model=model): yield column
Returns any columns used within this query. :return [<orb.Column>, ..]
def feedforward(self): """ Soon to be depriciated. Needed to make the SP implementation compatible with some older code. """ m = self._numInputs n = self._numColumns W = np.zeros((n, m)) for i in range(self._numColumns): self.getPermanence(i, W[i, :]) return W
Soon to be depriciated. Needed to make the SP implementation compatible with some older code.
def mem_extend(self, start: int, size: int) -> None: """Extends the memory of this machine state. :param start: Start of memory extension :param size: Size of memory extension """ m_extend = self.calculate_extension_size(start, size) if m_extend: extend_gas =...
Extends the memory of this machine state. :param start: Start of memory extension :param size: Size of memory extension
def validate(self): """ validates the feature configuration, and returns a list of errors (empty list if no error) validate should: * required variables * warn on unused variables errors should either be reported via self._log_error(), or raise an exception """...
validates the feature configuration, and returns a list of errors (empty list if no error) validate should: * required variables * warn on unused variables errors should either be reported via self._log_error(), or raise an exception
def model(dropout, vocab, model_mode, output_size): """Construct the model.""" textCNN = SentimentNet(dropout=dropout, vocab_size=len(vocab), model_mode=model_mode,\ output_size=output_size) textCNN.hybridize() return textCNN
Construct the model.
def salt_api_acl_tool(username, request): ''' ..versionadded:: 2016.3.0 Verifies user requests against the API whitelist. (User/IP pair) in order to provide whitelisting for the API similar to the master, but over the API. ..code-block:: yaml rest_cherrypy: api_acl: ...
..versionadded:: 2016.3.0 Verifies user requests against the API whitelist. (User/IP pair) in order to provide whitelisting for the API similar to the master, but over the API. ..code-block:: yaml rest_cherrypy: api_acl: users: '*': ...
def _wait_for_token(self, ctx, wait_token_url): ''' Returns a token from a the wait token URL @param wait_token_url URL to wait for (string) :return DischargeToken ''' resp = requests.get(wait_token_url) if resp.status_code != 200: raise InteractionError('cann...
Returns a token from a the wait token URL @param wait_token_url URL to wait for (string) :return DischargeToken
def _build_kernel(self, kernel_source, compile_flags=()): """Convenience function for building the kernel for this worker. Args: kernel_source (str): the kernel source to use for building the kernel Returns: cl.Program: a compiled CL kernel """ return cl...
Convenience function for building the kernel for this worker. Args: kernel_source (str): the kernel source to use for building the kernel Returns: cl.Program: a compiled CL kernel
def _cfg_exists(self, cfg_str): """Check a partial config string exists in the running config. :param cfg_str: config string to check :return : True or False """ ios_cfg = self._get_running_config() parse = HTParser(ios_cfg) cfg_raw = parse.find_lines("^" + cfg_s...
Check a partial config string exists in the running config. :param cfg_str: config string to check :return : True or False
def draw_polygon( self, *pts, close_path=True, stroke=None, stroke_width=1, stroke_dash=None, fill=None ) -> None: """Draws the given polygon.""" c = self.c c.saveState() if stroke is not Non...
Draws the given polygon.
def _view_interval(self, queue_type, queue_id): """Updates the queue interval in SharQ.""" response = { 'status': 'failure' } try: request_data = json.loads(request.data) interval = request_data['interval'] except Exception, e: resp...
Updates the queue interval in SharQ.
def clean_and_split_sql(sql: str) -> List[str]: """ Cleans up and unifies a SQL query. This involves unifying quoted strings and splitting brackets which aren't formatted consistently in the data. """ sql_tokens: List[str] = [] for token in sql.strip().split(): token = token.replace('"',...
Cleans up and unifies a SQL query. This involves unifying quoted strings and splitting brackets which aren't formatted consistently in the data.
def lastmod(self, tag): """Return the last modification of the entry.""" lastitems = EntryModel.objects.published().order_by('-modification_date').filter(tags=tag).only('modification_date') return lastitems[0].modification_date
Return the last modification of the entry.
def _update_spec_config(self, document_name, spec): ''' Dynamo implementation of project specific metadata spec ''' # add the updated archive_metadata object to Dynamo self._spec_table.update_item( Key={'_id': '{}'.format(document_name)}, UpdateExpression...
Dynamo implementation of project specific metadata spec
def construct_vdp_dict(self, mode, mgrid, typeid, typeid_ver, vsiid_frmt, vsiid, filter_frmt, gid, mac, vlan, oui_id, oui_data): """Constructs the VDP Message. Please refer http://www.ieee802.org/1/pages/802.1bg.html VDP Section for more det...
Constructs the VDP Message. Please refer http://www.ieee802.org/1/pages/802.1bg.html VDP Section for more detailed information :param mode: Associate or De-associate :param mgrid: MGR ID :param typeid: Type ID :param typeid_ver: Version of the Type ID :param vsii...
def to_dataframe(self): """ Returns the entire dataset as a single pandas DataFrame. Returns ------- df : DataFrame with shape (n_instances, n_columns) A pandas DataFrame containing the complete original data table including all targets (specified by the ...
Returns the entire dataset as a single pandas DataFrame. Returns ------- df : DataFrame with shape (n_instances, n_columns) A pandas DataFrame containing the complete original data table including all targets (specified by the meta data) and all features (inc...
def static_uint8_variable_for_data(variable_name, data, max_line_length=120, comment="", indent=2): r""" >>> static_uint8_variable_for_data("v", "abc") 'static uint8_t v[3] = {\n 0x61, 0x62, 0x63,\n}; // v' >>> static_uint8_variable_for_data("v", "abc", comment="hi") 'static uint8_t v[3] = { // hi\...
r""" >>> static_uint8_variable_for_data("v", "abc") 'static uint8_t v[3] = {\n 0x61, 0x62, 0x63,\n}; // v' >>> static_uint8_variable_for_data("v", "abc", comment="hi") 'static uint8_t v[3] = { // hi\n 0x61, 0x62, 0x63,\n}; // v' >>> static_uint8_variable_for_data("v", "abc", indent=4) 'static ...
def set_config(self, **config): """Shadow all the current config.""" reinit = False if 'stdopt' in config: stdopt = config.pop('stdopt') reinit = (stdopt != self.stdopt) self.stdopt = stdopt if 'attachopt' in config: attachopt = config.pop(...
Shadow all the current config.
def ckgpav(inst, sclkdp, tol, ref): """ Get pointing (attitude) and angular velocity for a specified spacecraft clock time. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckgpav_c.html :param inst: NAIF ID of instrument, spacecraft, or structure. :type inst: int :param sclkdp: Enc...
Get pointing (attitude) and angular velocity for a specified spacecraft clock time. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckgpav_c.html :param inst: NAIF ID of instrument, spacecraft, or structure. :type inst: int :param sclkdp: Encoded spacecraft clock time. :type sclkdp: fl...
def credentials_required(method_func): """ Decorator for methods that checks that the client has credentials. Throws a CredentialsMissingError when they are absent. """ def _checkcredentials(self, *args, **kwargs): if self.username and self.password: return method_func(self, *ar...
Decorator for methods that checks that the client has credentials. Throws a CredentialsMissingError when they are absent.
def dimensions(self): """Returns terminal dimensions Don't save this information for long periods of time because the user might resize their terminal. :return: Returns ``(width, height)``. If there's no terminal to be found, we'll just return ``(79, 40)``. ""...
Returns terminal dimensions Don't save this information for long periods of time because the user might resize their terminal. :return: Returns ``(width, height)``. If there's no terminal to be found, we'll just return ``(79, 40)``.
def glue(self, pos): """Calculates the distance between the given position and the port :param (float, float) pos: Distance to this position is calculated :return: Distance to port :rtype: float """ # Distance between border of rectangle and point # Equation from...
Calculates the distance between the given position and the port :param (float, float) pos: Distance to this position is calculated :return: Distance to port :rtype: float
def infer_batch(self, dataloader): """ Description : inference for LipNet """ sum_losses = 0 len_losses = 0 for input_data, input_label in dataloader: data = gluon.utils.split_and_load(input_data, self.ctx, even_split=False) label = gluon.utils.spl...
Description : inference for LipNet
def get_upcoming_event_lists_for_the_remainder_of_the_month(self, year = None, month = None): '''Return the set of events as triple of (today's events, events for the remainder of the week, events for the remainder of the month).''' events = [] if year == None and month == None: now...
Return the set of events as triple of (today's events, events for the remainder of the week, events for the remainder of the month).
def distance_to_contact(D, alpha=1): """Compute contact matrix from input distance matrix. Distance values of zeroes are given the largest contact count otherwise inferred non-zero distance values. """ if callable(alpha): distance_function = alpha else: try: a = np.f...
Compute contact matrix from input distance matrix. Distance values of zeroes are given the largest contact count otherwise inferred non-zero distance values.
def delete(self, lookup): """ If exactly one quote matches, delete it. Otherwise, raise a ValueError. """ lookup, num = self.split_num(lookup) if num: result = self.find_matches(lookup)[num - 1] else: result, = self.find_matches(lookup) self.db.delete_one(result)
If exactly one quote matches, delete it. Otherwise, raise a ValueError.
def get_all(self): """ Gets all component references registered in this reference map. :return: a list with component references. """ components = [] self._lock.acquire() try: for reference in self._references: components.appe...
Gets all component references registered in this reference map. :return: a list with component references.
def _set_usb(self, v, load=False): """ Setter method for usb, mapped from YANG variable /brocade_firmware_rpc/firmware_download/input/usb (container) If this variable is read-only (config: false) in the source YANG file, then _set_usb is considered as a private method. Backends looking to populate t...
Setter method for usb, mapped from YANG variable /brocade_firmware_rpc/firmware_download/input/usb (container) If this variable is read-only (config: false) in the source YANG file, then _set_usb is considered as a private method. Backends looking to populate this variable should do so via calling thisO...
def assert_dict_equal( first, second, key_msg_fmt="{msg}", value_msg_fmt="{msg}" ): """Fail unless first dictionary equals second. The dictionaries are considered equal, if they both contain the same keys, and their respective values are also equal. >>> assert_dict_equal({"foo": 5}, {"foo": 5}) ...
Fail unless first dictionary equals second. The dictionaries are considered equal, if they both contain the same keys, and their respective values are also equal. >>> assert_dict_equal({"foo": 5}, {"foo": 5}) >>> assert_dict_equal({"foo": 5}, {}) Traceback (most recent call last): ... ...
def read_samples(self, parameters, array_class=None, **kwargs): """Reads samples for the given parameter(s). The ``parameters`` can be the name of any dataset in ``samples_group``, a virtual field or method of ``FieldArray`` (as long as the file contains the necessary fields to derive t...
Reads samples for the given parameter(s). The ``parameters`` can be the name of any dataset in ``samples_group``, a virtual field or method of ``FieldArray`` (as long as the file contains the necessary fields to derive the virtual field or method), and/or any numpy function of these. ...
def get_cluster(self, word): """ Returns the cluster number for a word in the vocabulary """ idx = self.ix(word) return self.clusters[idx]
Returns the cluster number for a word in the vocabulary
def angular_momentum(self): r""" Compute the angular momentum for the phase-space positions contained in this object:: .. math:: \boldsymbol{{L}} = \boldsymbol{{q}} \times \boldsymbol{{p}} See :ref:`shape-conventions` for more information about the shapes of ...
r""" Compute the angular momentum for the phase-space positions contained in this object:: .. math:: \boldsymbol{{L}} = \boldsymbol{{q}} \times \boldsymbol{{p}} See :ref:`shape-conventions` for more information about the shapes of input and output objects. ...
def create_subcommand_synopsis(self, parser): """ show usage with description for commands """ self.add_usage(parser.usage, parser._get_positional_actions(), None, prefix='') usage = self._format_usage(parser.usage, parser._get_positional_actions(), ...
show usage with description for commands
def blast(args): """ %prog blast <deltafile|coordsfile> Covert delta or coordsfile to BLAST tabular output. """ p = OptionParser(blast.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) deltafile, = args blastfile = deltafile.rsplit("....
%prog blast <deltafile|coordsfile> Covert delta or coordsfile to BLAST tabular output.
def interpreter_versions(self): """Python and IPython versions used by clients""" if CONF.get('main_interpreter', 'default'): from IPython.core import release versions = dict( python_version = sys.version.split("\n")[0].strip(), ipython_versi...
Python and IPython versions used by clients
def d3flare_json(metadata, file=None, **options): """ Converts the *metadata* dictionary of a container or field into a ``flare.json`` formatted string or formatted stream written to the *file* The ``flare.json`` format is defined by the `d3.js <https://d3js.org/>`_ graphic library. The ``flare.js...
Converts the *metadata* dictionary of a container or field into a ``flare.json`` formatted string or formatted stream written to the *file* The ``flare.json`` format is defined by the `d3.js <https://d3js.org/>`_ graphic library. The ``flare.json`` format looks like this: .. code-block:: JSON ...
def height(poly): """height""" num = len(poly) hgt = 0.0 for i in range(num): hgt += (poly[i][2]) return hgt/num
height
def recover_info_from_exception(err: Exception) -> Dict: """ Retrives the information added to an exception by :func:`add_info_to_exception`. """ if len(err.args) < 1: return {} info = err.args[-1] if not isinstance(info, dict): return {} return info
Retrives the information added to an exception by :func:`add_info_to_exception`.
def url_paths(self): """ A dictionary of the paths of the urls to be mocked with this service and the handlers that should be called in their place """ unformatted_paths = self._url_module.url_paths paths = {} for unformatted_path, handler in unformatted_paths.it...
A dictionary of the paths of the urls to be mocked with this service and the handlers that should be called in their place
def send_request_message(self, request_id, meta, body, _=None): """ Receives a request from the client and handles and dispatches in in-thread. `message_expiry_in_seconds` is not supported. Messages do not expire, as the server handles the request immediately in the same thread before th...
Receives a request from the client and handles and dispatches in in-thread. `message_expiry_in_seconds` is not supported. Messages do not expire, as the server handles the request immediately in the same thread before this method returns. This method blocks until the server has completed handling the re...
def addPartsToVSLC( self, vslc_id, allele1_id, allele2_id, zygosity_id=None, allele1_rel=None, allele2_rel=None): """ Here we add the parts to the VSLC. While traditionally alleles (reference or variant loci) are traditionally added, you can add any node (such as...
Here we add the parts to the VSLC. While traditionally alleles (reference or variant loci) are traditionally added, you can add any node (such as sequence_alterations for unlocated variations) to a vslc if they are known to be paired. However, if a sequence_alteration's loci is unknown...
def _to_corrected_pandas_type(dt): """ When converting Spark SQL records to Pandas DataFrame, the inferred data type may be wrong. This method gets the corrected data type for Pandas if that type may be inferred uncorrectly. """ import numpy as np if type(dt) == ByteType: return np.int8 ...
When converting Spark SQL records to Pandas DataFrame, the inferred data type may be wrong. This method gets the corrected data type for Pandas if that type may be inferred uncorrectly.
def on_return(self, node): # ('value',) """Return statement: look for None, return special sentinal.""" self.retval = self.run(node.value) if self.retval is None: self.retval = ReturnedNone return
Return statement: look for None, return special sentinal.
def parse_coverage(self, f): """ Parse the contents of the Qualimap BamQC Coverage Histogram file """ # Get the sample name from the parent parent directory # Typical path: <sample name>/raw_data_qualimapReport/coverage_histogram.txt s_name = self.get_s_name(f) d = dict() for l in f['f']: ...
Parse the contents of the Qualimap BamQC Coverage Histogram file
def mapPartitions(self, f, preservesPartitioning=False): """ Return a new RDD by applying a function to each partition of this RDD. >>> rdd = sc.parallelize([1, 2, 3, 4], 2) >>> def f(iterator): yield sum(iterator) >>> rdd.mapPartitions(f).collect() [3, 7] """ ...
Return a new RDD by applying a function to each partition of this RDD. >>> rdd = sc.parallelize([1, 2, 3, 4], 2) >>> def f(iterator): yield sum(iterator) >>> rdd.mapPartitions(f).collect() [3, 7]
def send(self, jsonstr): """ Send jsonstr to the UDP collector >>> logger = UDPLogger() >>> logger.send('{"key": "value"}') """ udp_sock = socket(AF_INET, SOCK_DGRAM) udp_sock.sendto(jsonstr.encode('utf-8'), self.addr)
Send jsonstr to the UDP collector >>> logger = UDPLogger() >>> logger.send('{"key": "value"}')
async def get_data(self): """Retrieve the data.""" url = '{}/{}'.format(self.url, 'all') try: with async_timeout.timeout(5, loop=self._loop): if self.password is None: response = await self._session.get(url) else: ...
Retrieve the data.
def get_route_name(resource_uri): """ Get route name from RAML resource URI. :param resource_uri: String representing RAML resource URI. :returns string: String with route name, which is :resource_uri: stripped of non-word characters. """ resource_uri = resource_uri.strip('/') resource_...
Get route name from RAML resource URI. :param resource_uri: String representing RAML resource URI. :returns string: String with route name, which is :resource_uri: stripped of non-word characters.
def _set_default_configuration_options(app): """ Sets the default configuration options used by this extension """ # Options for JWTs when the TOKEN_LOCATION is headers app.config.setdefault('JWT_HEADER_NAME', 'Authorization') app.config.setdefault('JWT_HEADER_TYPE', 'Bea...
Sets the default configuration options used by this extension
def parse_html(fileobj, encoding): """ Given a file object *fileobj*, get an ElementTree instance. The *encoding* is assumed to be utf8. """ parser = HTMLParser(encoding=encoding, remove_blank_text=True) return parse(fileobj, parser)
Given a file object *fileobj*, get an ElementTree instance. The *encoding* is assumed to be utf8.
def solve(self): ''' Solves the single period consumption-saving problem using the method of endogenous gridpoints. Solution includes a consumption function cFunc (using cubic or linear splines), a marginal value function vPfunc, a min- imum acceptable level of normalized market...
Solves the single period consumption-saving problem using the method of endogenous gridpoints. Solution includes a consumption function cFunc (using cubic or linear splines), a marginal value function vPfunc, a min- imum acceptable level of normalized market resources mNrmMin, normalized ...
def get_descriptions(self, description_type): """ Gets the descriptions for specified type. When complete the callback is called with a list of descriptions """ (desc_type, max_units) = description_type results = [None] * max_units self.elk._descriptions_in_progre...
Gets the descriptions for specified type. When complete the callback is called with a list of descriptions
def analysis(self): """Return an AnalysisPartition proxy, which wraps this partition to provide acess to dataframes, shapely shapes and other analysis services""" if isinstance(self, PartitionProxy): return AnalysisPartition(self._obj) else: return AnalysisPartiti...
Return an AnalysisPartition proxy, which wraps this partition to provide acess to dataframes, shapely shapes and other analysis services
def django_url(step, url=None): """ The URL for a page from the test server. :param step: A Gherkin step :param url: If specified, the relative URL to append. """ base_url = step.test.live_server_url if url: return urljoin(base_url, url) else: return base_url
The URL for a page from the test server. :param step: A Gherkin step :param url: If specified, the relative URL to append.
def combineIndepDstns(*distributions): ''' Given n lists (or tuples) whose elements represent n independent, discrete probability spaces (probabilities and values), construct a joint pmf over all combinations of these independent points. Can take multivariate discrete distributions as inputs. ...
Given n lists (or tuples) whose elements represent n independent, discrete probability spaces (probabilities and values), construct a joint pmf over all combinations of these independent points. Can take multivariate discrete distributions as inputs. Parameters ---------- distributions : [np.a...
def SendUcsFirmware(self, path=None, dumpXml=False): """ Uploads a specific CCO Image on UCS. - path specifies the path of the image to be uploaded. """ from UcsBase import WriteUcsWarning, UcsUtils, ManagedObject, WriteObject, UcsUtils, UcsValidationException, \ UcsException from Ucs import ConfigCon...
Uploads a specific CCO Image on UCS. - path specifies the path of the image to be uploaded.
def page(self, value): """ Set the page which will be returned. :param value: 'page' parameter value for the rest api call :type value: str Take a look at https://apihelp.surveygizmo.com/help/surveyresponse-sub-object """ instance = copy(self) ins...
Set the page which will be returned. :param value: 'page' parameter value for the rest api call :type value: str Take a look at https://apihelp.surveygizmo.com/help/surveyresponse-sub-object
def reg_add(self, reg, value): """ Add a value to a register. The value can be another :class:`Register`, an :class:`Offset`, a :class:`Buffer`, an integer or ``None``. Arguments: reg(pwnypack.shellcode.types.Register): The register to add the value to. ...
Add a value to a register. The value can be another :class:`Register`, an :class:`Offset`, a :class:`Buffer`, an integer or ``None``. Arguments: reg(pwnypack.shellcode.types.Register): The register to add the value to. value: The value to add to the register. ...
def edit(self, name, color, description=github.GithubObject.NotSet): """ :calls: `PATCH /repos/:owner/:repo/labels/:name <http://developer.github.com/v3/issues/labels>`_ :param name: string :param color: string :param description: string :rtype: None """ a...
:calls: `PATCH /repos/:owner/:repo/labels/:name <http://developer.github.com/v3/issues/labels>`_ :param name: string :param color: string :param description: string :rtype: None
def minimum_multivariate_ess(nmr_params, alpha=0.05, epsilon=0.05): r"""Calculate the minimum multivariate Effective Sample Size you will need to obtain the desired precision. This implements the inequality from Vats et al. (2016): .. math:: \widehat{ESS} \geq \frac{2^{2/p}\pi}{(p\Gamma(p/2))^{2/...
r"""Calculate the minimum multivariate Effective Sample Size you will need to obtain the desired precision. This implements the inequality from Vats et al. (2016): .. math:: \widehat{ESS} \geq \frac{2^{2/p}\pi}{(p\Gamma(p/2))^{2/p}} \frac{\chi^{2}_{1-\alpha,p}}{\epsilon^{2}} Where :math:`p` is t...
def getLogger(name): """Create logger with custom exception() method """ def exception(self, msg, *args, **kwargs): extra = kwargs.setdefault('extra', {}) extra['exc_fullstack'] = self.isEnabledFor(logging.DEBUG) kwargs['exc_info'] = True self.log(logging.ERROR, msg, *args, *...
Create logger with custom exception() method
def semimajor(P,mstar=1): """Returns semimajor axis in AU given P in days, mstar in solar masses. """ return ((P*DAY/2/np.pi)**2*G*mstar*MSUN)**(1./3)/AU
Returns semimajor axis in AU given P in days, mstar in solar masses.
def save_voxel_grid(voxel_grid, file_name): """ Saves binary voxel grid as a binary file. The binary file is structured in little-endian unsigned int format. :param voxel_grid: binary voxel grid :type voxel_grid: list, tuple :param file_name: file name to save :type file_name: str """ ...
Saves binary voxel grid as a binary file. The binary file is structured in little-endian unsigned int format. :param voxel_grid: binary voxel grid :type voxel_grid: list, tuple :param file_name: file name to save :type file_name: str
def find_annotations(data, retriever=None): """Find annotation configuration files for vcfanno, using pre-installed inputs. Creates absolute paths for user specified inputs and finds locally installed defaults. Default annotations: - gemini for variant pipelines - somatic for variant tumor...
Find annotation configuration files for vcfanno, using pre-installed inputs. Creates absolute paths for user specified inputs and finds locally installed defaults. Default annotations: - gemini for variant pipelines - somatic for variant tumor pipelines - rnaedit for RNA-seq variant call...
def get_ascii(pid=None, name=None, pokemons=None, return_pokemons=False, message=None): '''get_ascii will return ascii art for a pokemon based on a name or pid. :param pid: the pokemon ID to return :param name: the pokemon name to return :param return_pokemons: return catches (default False) :param ...
get_ascii will return ascii art for a pokemon based on a name or pid. :param pid: the pokemon ID to return :param name: the pokemon name to return :param return_pokemons: return catches (default False) :param message: add a message to the ascii
def decorate_function(self, name, decorator): """ Decorate function with given name with given decorator. :param str name: Name of the function. :param callable decorator: Decorator callback. """ self.functions[name] = decorator(self.functions[name])
Decorate function with given name with given decorator. :param str name: Name of the function. :param callable decorator: Decorator callback.
def get_occurrence_times_for_event(event): """ Return a tuple with two sets containing the (start, end) *naive* datetimes of an Event's Occurrences, or the original start datetime if an Occurrence's start was modified by a user. """ occurrences_starts = set() occurrences_ends = set() for...
Return a tuple with two sets containing the (start, end) *naive* datetimes of an Event's Occurrences, or the original start datetime if an Occurrence's start was modified by a user.
def _get_nest_stats(self): """Helper method to deal with nestedStats as json format changed in v12.x """ for x in self.rdict: check = urlparse(x) if check.scheme: nested_dict = self.rdict[x]['nestedStats'] tmp_dict = nested_dict['e...
Helper method to deal with nestedStats as json format changed in v12.x
def generate_rb_sequence(self, depth, gateset, seed=None, interleaver=None): """ Construct a randomized benchmarking experiment on the given qubits, decomposing into gateset. If interleaver is not provided, the returned sequence will have the form C_1 C_2 ... C_(depth-1) C_inv , ...
Construct a randomized benchmarking experiment on the given qubits, decomposing into gateset. If interleaver is not provided, the returned sequence will have the form C_1 C_2 ... C_(depth-1) C_inv , where each C is a Clifford element drawn from gateset, C_{< depth} are randomly selected, ...
def put_value(self, value, timeout=None): """Put a value to the Attribute and wait for completion""" self._context.put(self._data.path + ["value"], value, timeout=timeout)
Put a value to the Attribute and wait for completion
def duplicate(self): """Duplicates the matcher to others.""" other = Matcher(self.loc, self.check_var, self.checkdefs, self.names, self.var_index) other.insert_check(0, "not " + self.check_var) self.others.append(other) return other
Duplicates the matcher to others.
def main(): """ Computational Genomics Lab, Genomics Institute, UC Santa Cruz Toil BWA pipeline Alignment of fastq reads via BWA-kit General usage: 1. Type "toil-bwa generate" to create an editable manifest and config in the current working directory. 2. Parameterize the pipeline by editin...
Computational Genomics Lab, Genomics Institute, UC Santa Cruz Toil BWA pipeline Alignment of fastq reads via BWA-kit General usage: 1. Type "toil-bwa generate" to create an editable manifest and config in the current working directory. 2. Parameterize the pipeline by editing the config. 3. Fil...
def launch_host_event_handler(self, host): """Launch event handler for a service Format of the line that triggers function call:: LAUNCH_HOST_EVENT_HANDLER;<host_name> :param host: host to execute the event handler :type host: alignak.objects.host.Host :return: None ...
Launch event handler for a service Format of the line that triggers function call:: LAUNCH_HOST_EVENT_HANDLER;<host_name> :param host: host to execute the event handler :type host: alignak.objects.host.Host :return: None
def get_relationship_admin_session_for_family(self, family_id): """Gets the ``OsidSession`` associated with the relationship administration service for the given family. arg: family_id (osid.id.Id): the ``Id`` of the ``Family`` return: (osid.relationship.RelationshipAdminSession) - a ...
Gets the ``OsidSession`` associated with the relationship administration service for the given family. arg: family_id (osid.id.Id): the ``Id`` of the ``Family`` return: (osid.relationship.RelationshipAdminSession) - a ``RelationshipAdminSession`` raise: NotFound - no family ...
def get_single_group_membership_users(self, user_id, group_id): """ Get a single group membership. Returns the group membership with the given membership id or user id. """ path = {} data = {} params = {} # REQUIRED - PATH - group_id "...
Get a single group membership. Returns the group membership with the given membership id or user id.
def translate_to_international_phonetic_alphabet(self, hide_stress_mark=False): ''' θ½¬ζ’ζˆε›½ι™…ιŸ³ζ ‡γ€‚εͺ要一δΈͺε…ƒιŸ³ηš„ζ—Άε€™ιœ€θ¦ιšθ—ι‡ιŸ³ζ ‡θ―† :param hide_stress_mark: :return: ''' translations = self.stress.mark_ipa() if (not hide_stress_mark) and self.have_vowel else "" for phoneme in self._p...
θ½¬ζ’ζˆε›½ι™…ιŸ³ζ ‡γ€‚εͺ要一δΈͺε…ƒιŸ³ηš„ζ—Άε€™ιœ€θ¦ιšθ—ι‡ιŸ³ζ ‡θ―† :param hide_stress_mark: :return:
def _run_cwltool(args): """Run with cwltool -- reference implementation. """ main_file, json_file, project_name = _get_main_and_json(args.directory) work_dir = utils.safe_makedir(os.path.join(os.getcwd(), "cwltool_work")) tmp_dir = utils.safe_makedir(os.path.join(work_dir, "tmpcwl")) log_file = ...
Run with cwltool -- reference implementation.
def csl_styles(**kwargs): ''' Get list of styles from https://github.com/citation-style-language/styles :param kwargs: any additional arguments will be passed on to `requests.get` :return: list, of CSL styles Usage:: from habanero import cn cn.csl_styles() ''' base = "https://api.github.co...
Get list of styles from https://github.com/citation-style-language/styles :param kwargs: any additional arguments will be passed on to `requests.get` :return: list, of CSL styles Usage:: from habanero import cn cn.csl_styles()
def delete_instance(self, instance_id): ''' method for removing an instance from AWS EC2 :param instance_id: string of instance id on AWS :return: string reporting state of instance ''' title = '%s.delete_instance' % self.__class__.__name__ # validate inputs ...
method for removing an instance from AWS EC2 :param instance_id: string of instance id on AWS :return: string reporting state of instance
def date_to_timestamp(date): """ date to unix timestamp in milliseconds """ date_tuple = date.timetuple() timestamp = calendar.timegm(date_tuple) * 1000 return timestamp
date to unix timestamp in milliseconds
def _convert_string_array(data, encoding, errors, itemsize=None): """ we take a string-like that is object dtype and coerce to a fixed size string type Parameters ---------- data : a numpy array of object dtype encoding : None or string-encoding errors : handler for encoding errors ...
we take a string-like that is object dtype and coerce to a fixed size string type Parameters ---------- data : a numpy array of object dtype encoding : None or string-encoding errors : handler for encoding errors itemsize : integer, optional, defaults to the max length of the strings R...
def batting_avg(self, benchmark): """Percentage of periods when `self` outperformed `benchmark`. Parameters ---------- benchmark : {pd.Series, TSeries, 1d np.ndarray} The benchmark security to which `self` is compared. Returns ------- float "...
Percentage of periods when `self` outperformed `benchmark`. Parameters ---------- benchmark : {pd.Series, TSeries, 1d np.ndarray} The benchmark security to which `self` is compared. Returns ------- float
def parse(self, fd): """very simple parser - but why would we want it to be complex?""" def resolve_args(args): # FIXME break this out, it's in common with the templating stuff elsewhere root = self.sections[0] val_dict = dict(('<' + t + '>', u) for (t, u) in root.ge...
very simple parser - but why would we want it to be complex?
def process_services(self, device_ids=None, removed_devices_info=None): """Process services managed by this config agent. This method is invoked by any of three scenarios. 1. Invoked by a periodic task running every `RPC_LOOP_INTERVAL` seconds. This is the most common scenario. ...
Process services managed by this config agent. This method is invoked by any of three scenarios. 1. Invoked by a periodic task running every `RPC_LOOP_INTERVAL` seconds. This is the most common scenario. In this mode, the method is called without any arguments. 2. Called by th...
def request(self, method, path='/', url=None, ignore_codes=[], **kwargs): """ Wrapper for the ._request method that verifies if we're logged into RightScale before making a call, and sanity checks the oauth expiration time. :param str method: An HTTP method (e.g. 'get', 'post', ...
Wrapper for the ._request method that verifies if we're logged into RightScale before making a call, and sanity checks the oauth expiration time. :param str method: An HTTP method (e.g. 'get', 'post', 'PUT', etc...) :param str path: A path component of the target URL. This will be ...
def login(): """ This route has two purposes. First, it is used by the user to login. Second, it is used by the CAS to respond with the `ticket` after the user logs in successfully. When the user accesses this url, they are redirected to the CAS to login. If the login was successful, the CAS wi...
This route has two purposes. First, it is used by the user to login. Second, it is used by the CAS to respond with the `ticket` after the user logs in successfully. When the user accesses this url, they are redirected to the CAS to login. If the login was successful, the CAS will respond to this ro...
def get_multi_temperature_data(kt0=1.0, kt1=5.0, length0=10000, length1=10000, n0=10, n1=10): """ Continuous MCMC process in an asymmetric double well potential at multiple temperatures. Parameters ---------- kt0: double, optional, default=1.0 Temperature in kT for the first thermodynamic s...
Continuous MCMC process in an asymmetric double well potential at multiple temperatures. Parameters ---------- kt0: double, optional, default=1.0 Temperature in kT for the first thermodynamic state. kt1: double, optional, default=5.0 Temperature in kT for the second thermodynamic state....