code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _updateEmissionProbabilities(self): """Sample a new set of emission probabilites from the conditional distribution P(E | S, O) """ observations_by_state = [self.model.collect_observations_in_state(self.observations, state) for state in range(self.model.nstat...
Sample a new set of emission probabilites from the conditional distribution P(E | S, O)
Below is the the instruction that describes the task: ### Input: Sample a new set of emission probabilites from the conditional distribution P(E | S, O) ### Response: def _updateEmissionProbabilities(self): """Sample a new set of emission probabilites from the conditional distribution P(E | S, O) ...
def extend_substation(grid, critical_stations, grid_level): """ Reinforce MV or LV substation by exchanging the existing trafo and installing a parallel one if necessary. First, all available transformers in a `critical_stations` are extended to maximum power. If this does not solve all present iss...
Reinforce MV or LV substation by exchanging the existing trafo and installing a parallel one if necessary. First, all available transformers in a `critical_stations` are extended to maximum power. If this does not solve all present issues, additional transformers are build. Parameters --------...
Below is the the instruction that describes the task: ### Input: Reinforce MV or LV substation by exchanging the existing trafo and installing a parallel one if necessary. First, all available transformers in a `critical_stations` are extended to maximum power. If this does not solve all present issues...
def format_servers(servers): """ :param servers: server list, element in it can have two kinds of format. - dict servers = [ {'name':'node1','host':'127.0.0.1','port':10000,'db':0}, {'name':'node2','host':'127.0.0.1','port':11000,'db':0}, {'name':'node3','host':'127.0.0.1','por...
:param servers: server list, element in it can have two kinds of format. - dict servers = [ {'name':'node1','host':'127.0.0.1','port':10000,'db':0}, {'name':'node2','host':'127.0.0.1','port':11000,'db':0}, {'name':'node3','host':'127.0.0.1','port':12000,'db':0}, ] - url_s...
Below is the the instruction that describes the task: ### Input: :param servers: server list, element in it can have two kinds of format. - dict servers = [ {'name':'node1','host':'127.0.0.1','port':10000,'db':0}, {'name':'node2','host':'127.0.0.1','port':11000,'db':0}, {'name':'no...
def tree2text(tree_obj, indent=4): # type: (TreeInfo, int) -> str """ Return text representation of a decision tree. """ parts = [] def _format_node(node, depth=0): # type: (NodeInfo, int) -> None def p(*args): # type: (*str) -> None parts.append(" " * de...
Return text representation of a decision tree.
Below is the the instruction that describes the task: ### Input: Return text representation of a decision tree. ### Response: def tree2text(tree_obj, indent=4): # type: (TreeInfo, int) -> str """ Return text representation of a decision tree. """ parts = [] def _format_node(node, depth=0):...
def _aload16(ins): ''' Loads a 16 bit value from a memory address If 2nd arg. start with '*', it is always treated as an indirect value. ''' output = _addr(ins.quad[2]) output.append('ld e, (hl)') output.append('inc hl') output.append('ld d, (hl)') output.append('ex de, hl') out...
Loads a 16 bit value from a memory address If 2nd arg. start with '*', it is always treated as an indirect value.
Below is the the instruction that describes the task: ### Input: Loads a 16 bit value from a memory address If 2nd arg. start with '*', it is always treated as an indirect value. ### Response: def _aload16(ins): ''' Loads a 16 bit value from a memory address If 2nd arg. start with '*', it is always...
def do_clustering(types, max_clust): """ Helper method for clustering that takes a list of all of the things being clustered (which are assumed to be binary numbers represented as strings), and an int representing the maximum number of clusters that are allowed. Returns: A dictionary mapping cluste...
Helper method for clustering that takes a list of all of the things being clustered (which are assumed to be binary numbers represented as strings), and an int representing the maximum number of clusters that are allowed. Returns: A dictionary mapping cluster ids to lists of numbers that are part of th...
Below is the the instruction that describes the task: ### Input: Helper method for clustering that takes a list of all of the things being clustered (which are assumed to be binary numbers represented as strings), and an int representing the maximum number of clusters that are allowed. Returns: A dicti...
def numberofnetworks(self): """The number of distinct networks defined by the|Node| and |Element| objects currently handled by the |HydPy| object.""" sels1 = selectiontools.Selections() sels2 = selectiontools.Selections() complete = selectiontools.Selection('complete', ...
The number of distinct networks defined by the|Node| and |Element| objects currently handled by the |HydPy| object.
Below is the the instruction that describes the task: ### Input: The number of distinct networks defined by the|Node| and |Element| objects currently handled by the |HydPy| object. ### Response: def numberofnetworks(self): """The number of distinct networks defined by the|Node| and |Element...
def check_arguments_compatibility(the_callable, argd): """ Check if calling the_callable with the given arguments would be correct or not. >>> def foo(arg1, arg2, arg3='val1', arg4='val2', *args, **argd): ... pass >>> try: check_arguments_compatibility(foo, {'arg1': 'bla', 'arg2': 'blo'}) ...
Check if calling the_callable with the given arguments would be correct or not. >>> def foo(arg1, arg2, arg3='val1', arg4='val2', *args, **argd): ... pass >>> try: check_arguments_compatibility(foo, {'arg1': 'bla', 'arg2': 'blo'}) ... except ValueError as err: print 'failed' ... else: print...
Below is the the instruction that describes the task: ### Input: Check if calling the_callable with the given arguments would be correct or not. >>> def foo(arg1, arg2, arg3='val1', arg4='val2', *args, **argd): ... pass >>> try: check_arguments_compatibility(foo, {'arg1': 'bla', 'arg2': 'blo'})...
def keys_delete(gandi, fqdn, key, force): """Delete a key for a domain.""" if not force: proceed = click.confirm('Are you sure you want to delete key %s on ' 'domain %s?' % (key, fqdn)) if not proceed: return result = gandi.dns.keys_delete(fqdn, ...
Delete a key for a domain.
Below is the the instruction that describes the task: ### Input: Delete a key for a domain. ### Response: def keys_delete(gandi, fqdn, key, force): """Delete a key for a domain.""" if not force: proceed = click.confirm('Are you sure you want to delete key %s on ' 'do...
async def spawn(self, agent_cls, *args, addr=None, **kwargs): """Spawn a new agent in a slave environment. :param str agent_cls: `qualname`` of the agent class. That is, the name should be in the form ``pkg.mod:cls``, e.g. ``creamas.core.agent:CreativeAgent``. ...
Spawn a new agent in a slave environment. :param str agent_cls: `qualname`` of the agent class. That is, the name should be in the form ``pkg.mod:cls``, e.g. ``creamas.core.agent:CreativeAgent``. :param str addr: Optional. Address for the slave enviroment...
Below is the the instruction that describes the task: ### Input: Spawn a new agent in a slave environment. :param str agent_cls: `qualname`` of the agent class. That is, the name should be in the form ``pkg.mod:cls``, e.g. ``creamas.core.agent:CreativeAgent``. :p...
def _contained_parameters(expression): """ Determine which parameters are contained in this expression. :param Expression expression: expression involving parameters :return: set of parameters contained in this expression :rtype: set """ if isinstance(expression, BinaryExp): return ...
Determine which parameters are contained in this expression. :param Expression expression: expression involving parameters :return: set of parameters contained in this expression :rtype: set
Below is the the instruction that describes the task: ### Input: Determine which parameters are contained in this expression. :param Expression expression: expression involving parameters :return: set of parameters contained in this expression :rtype: set ### Response: def _contained_parameters(expres...
def bulk_get_or_create(self, data_list): """ data_list is the data to get or create We generate the query and set all the record keys based on passed in queryset Then we loop over each item in the data_list, which has the keys already! No need to generate them. Should save a lot of time...
data_list is the data to get or create We generate the query and set all the record keys based on passed in queryset Then we loop over each item in the data_list, which has the keys already! No need to generate them. Should save a lot of time Use values instead of the whole object, much faster ...
Below is the the instruction that describes the task: ### Input: data_list is the data to get or create We generate the query and set all the record keys based on passed in queryset Then we loop over each item in the data_list, which has the keys already! No need to generate them. Should save a lot...
def ecdsa_sign_compact(msg32, seckey): """ Takes the same message and seckey as _ecdsa_sign_recoverable Returns an unsigned char array of length 65 containing the signed message """ # Assign 65 bytes to output output64 = ffi.new("unsigned char[65]") # ffi definition of recid reci...
Takes the same message and seckey as _ecdsa_sign_recoverable Returns an unsigned char array of length 65 containing the signed message
Below is the the instruction that describes the task: ### Input: Takes the same message and seckey as _ecdsa_sign_recoverable Returns an unsigned char array of length 65 containing the signed message ### Response: def ecdsa_sign_compact(msg32, seckey): """ Takes the same message and seckey as _...
def _stderr_raw(self, s): """Writes the string to stdout""" print(s, end='', file=sys.stderr) sys.stderr.flush()
Writes the string to stdout
Below is the the instruction that describes the task: ### Input: Writes the string to stdout ### Response: def _stderr_raw(self, s): """Writes the string to stdout""" print(s, end='', file=sys.stderr) sys.stderr.flush()
def create_description(self, complib=None, complevel=None, fletcher32=False, expectedrows=None): """ create the description of the table from the axes & values """ # provided expected rows if its passed if expectedrows is None: expectedrows = max(self.nrow...
create the description of the table from the axes & values
Below is the the instruction that describes the task: ### Input: create the description of the table from the axes & values ### Response: def create_description(self, complib=None, complevel=None, fletcher32=False, expectedrows=None): """ create the description of the table from ...
def propagate_event_to_delegate(self, event, eventhandler): """Propagate the given Mouse event to the widgetdelegate Enter edit mode, get the editor widget and issue an event on that widget. :param event: the mouse event :type event: :class:`QtGui.QMouseEvent` :param eventhandl...
Propagate the given Mouse event to the widgetdelegate Enter edit mode, get the editor widget and issue an event on that widget. :param event: the mouse event :type event: :class:`QtGui.QMouseEvent` :param eventhandler: the eventhandler to use. E.g. ``"mousePressEvent"`` :type e...
Below is the the instruction that describes the task: ### Input: Propagate the given Mouse event to the widgetdelegate Enter edit mode, get the editor widget and issue an event on that widget. :param event: the mouse event :type event: :class:`QtGui.QMouseEvent` :param eventhandler...
def get_sgburst_waveform(template=None, **kwargs): """Return the plus and cross polarizations of a time domain sine-Gaussian burst waveform. Parameters ---------- template: object An object that has attached properties. This can be used to subsitute for keyword arguments. A common e...
Return the plus and cross polarizations of a time domain sine-Gaussian burst waveform. Parameters ---------- template: object An object that has attached properties. This can be used to subsitute for keyword arguments. A common example would be a row in an xml table. approximant : s...
Below is the the instruction that describes the task: ### Input: Return the plus and cross polarizations of a time domain sine-Gaussian burst waveform. Parameters ---------- template: object An object that has attached properties. This can be used to subsitute for keyword arguments....
def conspectus_api(): """ Virtual ``conspectus.py`` file for brython. This file contains following variables: Attributes: consp_dict (dict): Dictionary with conspects. cosp_id_pairs (list): List of tuples ``(name, id)`` for conspectus. subs_by_mdt (dict): Dictionary containing `...
Virtual ``conspectus.py`` file for brython. This file contains following variables: Attributes: consp_dict (dict): Dictionary with conspects. cosp_id_pairs (list): List of tuples ``(name, id)`` for conspectus. subs_by_mdt (dict): Dictionary containing ``mdt: sub_dict``. mdt_by_n...
Below is the the instruction that describes the task: ### Input: Virtual ``conspectus.py`` file for brython. This file contains following variables: Attributes: consp_dict (dict): Dictionary with conspects. cosp_id_pairs (list): List of tuples ``(name, id)`` for conspectus. subs_by_...
def start(self, n): """Start n copies of the process using a batch system.""" self.log.debug("Starting %s: %r", self.__class__.__name__, self.args) # Here we save profile_dir in the context so they # can be used in the batch script template as {profile_dir} self.write_batch_scrip...
Start n copies of the process using a batch system.
Below is the the instruction that describes the task: ### Input: Start n copies of the process using a batch system. ### Response: def start(self, n): """Start n copies of the process using a batch system.""" self.log.debug("Starting %s: %r", self.__class__.__name__, self.args) # Here we sa...
def iter_penalty_model_from_specification(cur, specification): """Iterate through all penalty models in the cache matching the given specification. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. specificat...
Iterate through all penalty models in the cache matching the given specification. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. specification (:class:`penaltymodel.Specification`): A specification ...
Below is the the instruction that describes the task: ### Input: Iterate through all penalty models in the cache matching the given specification. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. specificati...
def build_query(self, **filters): """ Build queries for geo spatial filtering. Expected query parameters are: - a `unit=value` parameter where the unit is a valid UNIT in the `django.contrib.gis.measure.Distance` class. - `from` which must be a comma separated latit...
Build queries for geo spatial filtering. Expected query parameters are: - a `unit=value` parameter where the unit is a valid UNIT in the `django.contrib.gis.measure.Distance` class. - `from` which must be a comma separated latitude and longitude. Example query: ...
Below is the the instruction that describes the task: ### Input: Build queries for geo spatial filtering. Expected query parameters are: - a `unit=value` parameter where the unit is a valid UNIT in the `django.contrib.gis.measure.Distance` class. - `from` which must be a comma ...
def encryptfile(filename, key=None, outfile=None, chunk=64 * 1024): """ Encrypts a file using AES (CBC mode) with the given key. If no file is supplied, then the inputted file will be modified in place. The chunk value will be the size with which the function uses to read and encrypt the file. Lar...
Encrypts a file using AES (CBC mode) with the given key. If no file is supplied, then the inputted file will be modified in place. The chunk value will be the size with which the function uses to read and encrypt the file. Larger chunks can be faster for some files and machines. The chunk MUST be div...
Below is the the instruction that describes the task: ### Input: Encrypts a file using AES (CBC mode) with the given key. If no file is supplied, then the inputted file will be modified in place. The chunk value will be the size with which the function uses to read and encrypt the file. Larger chunks ...
def __assert_less(expected, returned): ''' Test if a value is less than the returned value ''' result = "Pass" try: assert (expected < returned), "{0} not False".format(returned) except AssertionError as err: result = "Fail: " + six.text_type(err) ...
Test if a value is less than the returned value
Below is the the instruction that describes the task: ### Input: Test if a value is less than the returned value ### Response: def __assert_less(expected, returned): ''' Test if a value is less than the returned value ''' result = "Pass" try: assert (expected < r...
def params(self): """ Read self params from configuration. """ parser = JinjaInterpolationNamespace() parser.read(self.configuration) return dict(parser['params'] or {})
Read self params from configuration.
Below is the the instruction that describes the task: ### Input: Read self params from configuration. ### Response: def params(self): """ Read self params from configuration. """ parser = JinjaInterpolationNamespace() parser.read(self.configuration) return dict(parser['params'] or {...
def serialize_b58(self, private=True): """Encode the serialized node in base58.""" return ensure_str( base58.b58encode_check(unhexlify(self.serialize(private))))
Encode the serialized node in base58.
Below is the the instruction that describes the task: ### Input: Encode the serialized node in base58. ### Response: def serialize_b58(self, private=True): """Encode the serialized node in base58.""" return ensure_str( base58.b58encode_check(unhexlify(self.serialize(private))))
def all_as_list(): ''' returns a list of all defined containers ''' as_dict = all_as_dict() containers = as_dict['Running'] + as_dict['Frozen'] + as_dict['Stopped'] containers_list = [] for i in containers: i = i.replace(' (auto)', '') containers_list.append(i) ...
returns a list of all defined containers
Below is the the instruction that describes the task: ### Input: returns a list of all defined containers ### Response: def all_as_list(): ''' returns a list of all defined containers ''' as_dict = all_as_dict() containers = as_dict['Running'] + as_dict['Frozen'] + as_dict['Stopped'] ...
def _confirm_dialog(self, prompt): ''' Prompts for a 'yes' or 'no' to given prompt. ''' response = raw_input(prompt).strip().lower() valid = {'y': True, 'ye': True, 'yes': True, 'n': False, 'no': False} while True: try: return valid[response] excep...
Prompts for a 'yes' or 'no' to given prompt.
Below is the the instruction that describes the task: ### Input: Prompts for a 'yes' or 'no' to given prompt. ### Response: def _confirm_dialog(self, prompt): ''' Prompts for a 'yes' or 'no' to given prompt. ''' response = raw_input(prompt).strip().lower() valid = {'y': True, 'ye': True, 'y...
def remote_write(self, data): """ Called from remote worker to write L{data} to L{fp} within boundaries of L{maxsize} @type data: C{string} @param data: String of data to write """ data = unicode2bytes(data) if self.remaining is not None: if ...
Called from remote worker to write L{data} to L{fp} within boundaries of L{maxsize} @type data: C{string} @param data: String of data to write
Below is the the instruction that describes the task: ### Input: Called from remote worker to write L{data} to L{fp} within boundaries of L{maxsize} @type data: C{string} @param data: String of data to write ### Response: def remote_write(self, data): """ Called from remot...
def set_trace(): """Call pdb.set_trace in the calling frame, first restoring sys.stdout to the real output stream. Note that sys.stdout is NOT reset to whatever it was before the call once pdb is done! """ import pdb import sys stdout = sys.stdout sys.stdout = sys.__stdout__ pdb.Pdb(...
Call pdb.set_trace in the calling frame, first restoring sys.stdout to the real output stream. Note that sys.stdout is NOT reset to whatever it was before the call once pdb is done!
Below is the the instruction that describes the task: ### Input: Call pdb.set_trace in the calling frame, first restoring sys.stdout to the real output stream. Note that sys.stdout is NOT reset to whatever it was before the call once pdb is done! ### Response: def set_trace(): """Call pdb.set_trace in ...
def stop_service(self, instance, service): """ Stops a single service. :param str instance: A Yamcs instance name. :param str service: The name of the service. """ req = rest_pb2.EditServiceRequest() req.state = 'stopped' url = '/services/{}/{}'.format(in...
Stops a single service. :param str instance: A Yamcs instance name. :param str service: The name of the service.
Below is the the instruction that describes the task: ### Input: Stops a single service. :param str instance: A Yamcs instance name. :param str service: The name of the service. ### Response: def stop_service(self, instance, service): """ Stops a single service. :param str...
def plot_isotherm(self, T, zs, ws, Pmin=None, Pmax=None, methods=[], pts=50, only_valid=True): # pragma: no cover r'''Method to create a plot of the property vs pressure at a specified temperature and composition according to either a specified list of methods, or the us...
r'''Method to create a plot of the property vs pressure at a specified temperature and composition according to either a specified list of methods, or the user methods (if set), or all methods. User-selectable number of points, and pressure range. If only_valid is set, `test_method_v...
Below is the the instruction that describes the task: ### Input: r'''Method to create a plot of the property vs pressure at a specified temperature and composition according to either a specified list of methods, or the user methods (if set), or all methods. User-selectable number of poi...
def is_tainted(variable, context, only_unprotected=False, ignore_generic_taint=False): ''' Args: variable context (Contract|Function) only_unprotected (bool): True only unprotected function are considered Returns: bool ''' assert isinstance(context, (Contract, Fun...
Args: variable context (Contract|Function) only_unprotected (bool): True only unprotected function are considered Returns: bool
Below is the the instruction that describes the task: ### Input: Args: variable context (Contract|Function) only_unprotected (bool): True only unprotected function are considered Returns: bool ### Response: def is_tainted(variable, context, only_unprotected=False, ignore_generic...
def parse_ls_date(self, s, *, now=None): """ Parsing dates from the ls unix utility. For example, "Nov 18 1958" and "Nov 18 12:29". :param s: ls date :type s: :py:class:`str` :rtype: :py:class:`str` """ with setlocale("C"): try: ...
Parsing dates from the ls unix utility. For example, "Nov 18 1958" and "Nov 18 12:29". :param s: ls date :type s: :py:class:`str` :rtype: :py:class:`str`
Below is the the instruction that describes the task: ### Input: Parsing dates from the ls unix utility. For example, "Nov 18 1958" and "Nov 18 12:29". :param s: ls date :type s: :py:class:`str` :rtype: :py:class:`str` ### Response: def parse_ls_date(self, s, *, now=None): ...
def gen_random_string(str_len): """ generate random string with specified length """ return ''.join( random.choice(string.ascii_letters + string.digits) for _ in range(str_len))
generate random string with specified length
Below is the the instruction that describes the task: ### Input: generate random string with specified length ### Response: def gen_random_string(str_len): """ generate random string with specified length """ return ''.join( random.choice(string.ascii_letters + string.digits) for _ in range(str...
def _initEphemerals(self): """ Initialize all ephemeral members after being restored to a pickled state. """ BacktrackingTM._initEphemerals(self) #--------------------------------------------------------------------------------- # cells4 specific initialization # If True, let C++ allocate m...
Initialize all ephemeral members after being restored to a pickled state.
Below is the the instruction that describes the task: ### Input: Initialize all ephemeral members after being restored to a pickled state. ### Response: def _initEphemerals(self): """ Initialize all ephemeral members after being restored to a pickled state. """ BacktrackingTM._initEphemerals(self) ...
def alignTwoAlignments(aln1,aln2,outfile,WorkingDir=None,SuppressStderr=None,\ SuppressStdout=None): """Aligns two alignments. Individual sequences are not realigned aln1: string, name of file containing the first alignment aln2: string, name of file containing the second alignment outfile: you're ...
Aligns two alignments. Individual sequences are not realigned aln1: string, name of file containing the first alignment aln2: string, name of file containing the second alignment outfile: you're forced to specify an outfile name, because if you don't aln1 will be overwritten. So, if you want aln1 t...
Below is the the instruction that describes the task: ### Input: Aligns two alignments. Individual sequences are not realigned aln1: string, name of file containing the first alignment aln2: string, name of file containing the second alignment outfile: you're forced to specify an outfile name, because ...
def animate_2Dscatter(x, y, NumAnimatedPoints=50, NTrailPoints=20, xlabel="", ylabel="", xlims=None, ylims=None, filename="testAnim.mp4", bitrate=1e5, dpi=5e2, fps=30, figsize = [6, 6]): """ Animates x and y - where x and y are 1d arrays of x and y positions and it plots x[i:i+NTrailPoints] a...
Animates x and y - where x and y are 1d arrays of x and y positions and it plots x[i:i+NTrailPoints] and y[i:i+NTrailPoints] against each other and iterates through i.
Below is the the instruction that describes the task: ### Input: Animates x and y - where x and y are 1d arrays of x and y positions and it plots x[i:i+NTrailPoints] and y[i:i+NTrailPoints] against each other and iterates through i. ### Response: def animate_2Dscatter(x, y, NumAnimatedPoints=50, NTrailPoi...
def __query(p, k, v, accepted_keys=None, required_values=None, path=None, exact=True): """ Query function given to visit method :param p: visited path in tuple form :param k: visited key :param v: visited value :param accepted_keys: list of keys where one must match k to satisfy query. :par...
Query function given to visit method :param p: visited path in tuple form :param k: visited key :param v: visited value :param accepted_keys: list of keys where one must match k to satisfy query. :param required_values: list of values where one must match v to satisfy query :param path: exact p...
Below is the the instruction that describes the task: ### Input: Query function given to visit method :param p: visited path in tuple form :param k: visited key :param v: visited value :param accepted_keys: list of keys where one must match k to satisfy query. :param required_values: list of va...
def available(self, skip_hidden=True, skip_installed=True, skip_mandatory=False, skip_reboot=False, software=True, drivers=True, categories=None, severities=None): ''' ...
Gets a list of all updates available on the system that match the passed criteria. Args: skip_hidden (bool): Skip hidden updates. Default is True skip_installed (bool): Skip installed updates. Default is True skip_mandatory (bool): Skip mandatory updates. Default ...
Below is the the instruction that describes the task: ### Input: Gets a list of all updates available on the system that match the passed criteria. Args: skip_hidden (bool): Skip hidden updates. Default is True skip_installed (bool): Skip installed updates. Default is True...
def earliest_possible_date(): """ The earliest date for which we can load data from this module. """ today = pd.Timestamp('now', tz='UTC').normalize() # Bank of Canada only has the last 10 years of data at any given time. return today.replace(year=today.year - 10)
The earliest date for which we can load data from this module.
Below is the the instruction that describes the task: ### Input: The earliest date for which we can load data from this module. ### Response: def earliest_possible_date(): """ The earliest date for which we can load data from this module. """ today = pd.Timestamp('now', tz='UTC').normalize() # ...
def findfileindirs(filename, dirs=None, use_pythonpath=True, use_searchpath=True, notfound_is_fatal=True, notfound_val=None): """Find file in multiple directories. Inputs: filename: the file name to be searched for. dirs: list of folders or None use_pythonpath: use the Python module sea...
Find file in multiple directories. Inputs: filename: the file name to be searched for. dirs: list of folders or None use_pythonpath: use the Python module search path use_searchpath: use the sastool search path. notfound_is_fatal: if an exception is to be raised if the file ...
Below is the the instruction that describes the task: ### Input: Find file in multiple directories. Inputs: filename: the file name to be searched for. dirs: list of folders or None use_pythonpath: use the Python module search path use_searchpath: use the sastool search path. ...
def validate(reference_tempi, reference_weight, estimated_tempi): """Checks that the input annotations to a metric look like valid tempo annotations. Parameters ---------- reference_tempi : np.ndarray reference tempo values, in bpm reference_weight : float perceptual weight of ...
Checks that the input annotations to a metric look like valid tempo annotations. Parameters ---------- reference_tempi : np.ndarray reference tempo values, in bpm reference_weight : float perceptual weight of slow vs fast in reference estimated_tempi : np.ndarray estim...
Below is the the instruction that describes the task: ### Input: Checks that the input annotations to a metric look like valid tempo annotations. Parameters ---------- reference_tempi : np.ndarray reference tempo values, in bpm reference_weight : float perceptual weight of slow...
def get_extr_lics_xref(self, extr_lic): """ Return a list of cross references. """ xrefs = list(self.graph.triples((extr_lic, RDFS.seeAlso, None))) return map(lambda xref_triple: xref_triple[2], xrefs)
Return a list of cross references.
Below is the the instruction that describes the task: ### Input: Return a list of cross references. ### Response: def get_extr_lics_xref(self, extr_lic): """ Return a list of cross references. """ xrefs = list(self.graph.triples((extr_lic, RDFS.seeAlso, None))) return map(la...
def configure_s3_resources(self, config): """ Extract the S3 operations from the configuration and execute them. :param config: config of SageMaker operation :type config: dict :rtype: dict """ s3_operations = config.pop('S3Operations', None) if s3_opera...
Extract the S3 operations from the configuration and execute them. :param config: config of SageMaker operation :type config: dict :rtype: dict
Below is the the instruction that describes the task: ### Input: Extract the S3 operations from the configuration and execute them. :param config: config of SageMaker operation :type config: dict :rtype: dict ### Response: def configure_s3_resources(self, config): """ Extra...
def set_training(train_mode): #pylint: disable=redefined-outer-name """Set status to training/predicting. This affects ctx.is_train in operator running context. For example, Dropout will drop inputs randomly when train_mode=True while simply passing through if train_mode=False. Parameters ---------...
Set status to training/predicting. This affects ctx.is_train in operator running context. For example, Dropout will drop inputs randomly when train_mode=True while simply passing through if train_mode=False. Parameters ---------- train_mode: bool Returns ------- previous state before t...
Below is the the instruction that describes the task: ### Input: Set status to training/predicting. This affects ctx.is_train in operator running context. For example, Dropout will drop inputs randomly when train_mode=True while simply passing through if train_mode=False. Parameters ---------- ...
def writeString(self, str): """Write the content of the string in the output I/O buffer This routine handle the I18N transcoding from internal UTF-8 The buffer is lossless, i.e. will store in case of partial or delayed writes. """ ret = libxml2mod.xmlOutputBufferWriteStrin...
Write the content of the string in the output I/O buffer This routine handle the I18N transcoding from internal UTF-8 The buffer is lossless, i.e. will store in case of partial or delayed writes.
Below is the the instruction that describes the task: ### Input: Write the content of the string in the output I/O buffer This routine handle the I18N transcoding from internal UTF-8 The buffer is lossless, i.e. will store in case of partial or delayed writes. ### Response: def write...
def setup_signing_encode(self, target_system, target_component, secret_key, initial_timestamp): ''' Setup a MAVLink2 signing key. If called with secret_key of all zero and zero initial_timestamp will disable signing target_system : system id o...
Setup a MAVLink2 signing key. If called with secret_key of all zero and zero initial_timestamp will disable signing target_system : system id of the target (uint8_t) target_component : component ID of the target (uint8_t) secret_key ...
Below is the the instruction that describes the task: ### Input: Setup a MAVLink2 signing key. If called with secret_key of all zero and zero initial_timestamp will disable signing target_system : system id of the target (uint8_t) target_component ...
def close(self): """Cleanup client resources and disconnect from MongoDB. On MongoDB >= 3.6, end all server sessions created by this client by sending one or more endSessions commands. Close all sockets in the connection pools and stop the monitor threads. If this instance is u...
Cleanup client resources and disconnect from MongoDB. On MongoDB >= 3.6, end all server sessions created by this client by sending one or more endSessions commands. Close all sockets in the connection pools and stop the monitor threads. If this instance is used again it will be automat...
Below is the the instruction that describes the task: ### Input: Cleanup client resources and disconnect from MongoDB. On MongoDB >= 3.6, end all server sessions created by this client by sending one or more endSessions commands. Close all sockets in the connection pools and stop the monit...
def rename_item_list(self, item_list_url, new_name): """ Rename an Item List on the server :type item_list_url: String or ItemList :param item_list_url: the URL of the list to which to add the items, or an ItemList object :type new_name: String :param new_name: the n...
Rename an Item List on the server :type item_list_url: String or ItemList :param item_list_url: the URL of the list to which to add the items, or an ItemList object :type new_name: String :param new_name: the new name to give the Item List :rtype: ItemList :...
Below is the the instruction that describes the task: ### Input: Rename an Item List on the server :type item_list_url: String or ItemList :param item_list_url: the URL of the list to which to add the items, or an ItemList object :type new_name: String :param new_name: t...
def update_mute(self, data): """Update mute.""" self._group['muted'] = data['mute'] self.callback() _LOGGER.info('updated mute on %s', self.friendly_name)
Update mute.
Below is the the instruction that describes the task: ### Input: Update mute. ### Response: def update_mute(self, data): """Update mute.""" self._group['muted'] = data['mute'] self.callback() _LOGGER.info('updated mute on %s', self.friendly_name)
def project(self, point_cloud, round_px=True): """Projects a point cloud onto the camera image plane. Parameters ---------- point_cloud : :obj:`autolab_core.PointCloud` or :obj:`autolab_core.Point` A PointCloud or Point to project onto the camera image plane. round_...
Projects a point cloud onto the camera image plane. Parameters ---------- point_cloud : :obj:`autolab_core.PointCloud` or :obj:`autolab_core.Point` A PointCloud or Point to project onto the camera image plane. round_px : bool If True, projections are rounded to ...
Below is the the instruction that describes the task: ### Input: Projects a point cloud onto the camera image plane. Parameters ---------- point_cloud : :obj:`autolab_core.PointCloud` or :obj:`autolab_core.Point` A PointCloud or Point to project onto the camera image plane. ...
def create(self, parameters={}, create_keys=True, **kwargs): """ Create the service. """ # Create the service cs = self._create_service(parameters=parameters, **kwargs) # Create the service key to get config details and # store in local cache file. if cre...
Create the service.
Below is the the instruction that describes the task: ### Input: Create the service. ### Response: def create(self, parameters={}, create_keys=True, **kwargs): """ Create the service. """ # Create the service cs = self._create_service(parameters=parameters, **kwargs) ...
def action(self, target, message, formatted=True, tags=None): """Send an action to the given target.""" if formatted: message = unescape(message) self.ctcp(target, 'ACTION', message)
Send an action to the given target.
Below is the the instruction that describes the task: ### Input: Send an action to the given target. ### Response: def action(self, target, message, formatted=True, tags=None): """Send an action to the given target.""" if formatted: message = unescape(message) self.ctcp(target,...
def generate_reset_password_token(user): # type: (User) -> Any """Generate a unique reset password token for the specified user. :param user: The user to work with """ data = [str(user.id), md5(user.password)] return get_serializer("reset").dumps(data)
Generate a unique reset password token for the specified user. :param user: The user to work with
Below is the the instruction that describes the task: ### Input: Generate a unique reset password token for the specified user. :param user: The user to work with ### Response: def generate_reset_password_token(user): # type: (User) -> Any """Generate a unique reset password token for the specified us...
def next(self): """ Returns new CharacterDataWrapper TODO: Don't raise offset past count - limit """ self.params['offset'] = str(int(self.params['offset']) + int(self.params['limit'])) return self.marvel.get_characters(self.marvel, (), **self.params)
Returns new CharacterDataWrapper TODO: Don't raise offset past count - limit
Below is the the instruction that describes the task: ### Input: Returns new CharacterDataWrapper TODO: Don't raise offset past count - limit ### Response: def next(self): """ Returns new CharacterDataWrapper TODO: Don't raise offset past count - limit """ self.param...
def get_asset_content_lookup_session_for_repository(self, repository_id): """Pass through to provider get_asset_content_lookup_session_for_repository""" return getattr(sessions, 'AssetContentLookupSession')( provider_session=self._provider_manager.get_asset_content_lookup_session_for_reposit...
Pass through to provider get_asset_content_lookup_session_for_repository
Below is the the instruction that describes the task: ### Input: Pass through to provider get_asset_content_lookup_session_for_repository ### Response: def get_asset_content_lookup_session_for_repository(self, repository_id): """Pass through to provider get_asset_content_lookup_session_for_repository""" ...
def within_set(df, items=None): """ Assert that df is a subset of items Parameters ========== df : DataFrame items : dict mapping of columns (k) to array-like of values (v) that ``df[k]`` is expected to be a subset of """ for k, v in items.items(): if not df[k]....
Assert that df is a subset of items Parameters ========== df : DataFrame items : dict mapping of columns (k) to array-like of values (v) that ``df[k]`` is expected to be a subset of
Below is the the instruction that describes the task: ### Input: Assert that df is a subset of items Parameters ========== df : DataFrame items : dict mapping of columns (k) to array-like of values (v) that ``df[k]`` is expected to be a subset of ### Response: def within_set(df, i...
def _get_args_name_from_parser(parser): """Retrieve the name of the function argument linked to the given parser. Args: parser: a function parser """ # Retrieve the 'action' destination of the method parser i.e. its # argument name. The HelpAction is ignored. return [action.dest for act...
Retrieve the name of the function argument linked to the given parser. Args: parser: a function parser
Below is the the instruction that describes the task: ### Input: Retrieve the name of the function argument linked to the given parser. Args: parser: a function parser ### Response: def _get_args_name_from_parser(parser): """Retrieve the name of the function argument linked to the given parser. ...
def __install_eggs(self, config): """ Install eggs for a particular configuration """ egg_carton = (self.directory.install_directory(self.feature_name), 'requirements.txt') eggs = self.__gather_eggs(config) self.logger.debug("Installing eggs %s..." % eggs) ...
Install eggs for a particular configuration
Below is the the instruction that describes the task: ### Input: Install eggs for a particular configuration ### Response: def __install_eggs(self, config): """ Install eggs for a particular configuration """ egg_carton = (self.directory.install_directory(self.feature_name), '...
def V_horiz_guppy(D, L, a, h, headonly=False): r'''Calculates volume of a tank with guppy heads, according to [1]_. .. math:: V_f = A_fL + \frac{2aR^2}{3}\cos^{-1}\left(1 - \frac{h}{R}\right) +\frac{2a}{9R}\sqrt{2Rh - h^2}(2h-3R)(h+R) .. math:: Af = R^2\cos^{-1}\frac{R-h}{R} - (R-h...
r'''Calculates volume of a tank with guppy heads, according to [1]_. .. math:: V_f = A_fL + \frac{2aR^2}{3}\cos^{-1}\left(1 - \frac{h}{R}\right) +\frac{2a}{9R}\sqrt{2Rh - h^2}(2h-3R)(h+R) .. math:: Af = R^2\cos^{-1}\frac{R-h}{R} - (R-h)\sqrt{2Rh - h^2} Parameters ---------- ...
Below is the the instruction that describes the task: ### Input: r'''Calculates volume of a tank with guppy heads, according to [1]_. .. math:: V_f = A_fL + \frac{2aR^2}{3}\cos^{-1}\left(1 - \frac{h}{R}\right) +\frac{2a}{9R}\sqrt{2Rh - h^2}(2h-3R)(h+R) .. math:: Af = R^2\cos^{-1}\f...
def compute_position_log(self, td=None, method='mc', update_deviation=True): """ Args: deviation (ndarray): A deviation survey with rows like MD, INC, AZI td (Number): The TD of the well, if no...
Args: deviation (ndarray): A deviation survey with rows like MD, INC, AZI td (Number): The TD of the well, if not the end of the deviation survey you're passing. method (str): 'aa': average angle 'bt': balanced tangential ...
Below is the the instruction that describes the task: ### Input: Args: deviation (ndarray): A deviation survey with rows like MD, INC, AZI td (Number): The TD of the well, if not the end of the deviation survey you're passing. method (str): 'aa': a...
def format_table(rows, sep=' '): """Format table :param sep: separator between columns :type sep: unicode on python2 | str on python3 Given the table:: table = [ ['foo', 'bar', 'foo'], [1, 2, 3], ['54a5a05d-c83b-4bb5-bd95-d90d6ea4a878'], ['foo'...
Format table :param sep: separator between columns :type sep: unicode on python2 | str on python3 Given the table:: table = [ ['foo', 'bar', 'foo'], [1, 2, 3], ['54a5a05d-c83b-4bb5-bd95-d90d6ea4a878'], ['foo', 45, 'bar', 2345] ] `format...
Below is the the instruction that describes the task: ### Input: Format table :param sep: separator between columns :type sep: unicode on python2 | str on python3 Given the table:: table = [ ['foo', 'bar', 'foo'], [1, 2, 3], ['54a5a05d-c83b-4bb5-bd95-d90d6e...
def get_publication_date(self, xml_doc): """Return the best effort start_date.""" start_date = get_value_in_tag(xml_doc, "prism:coverDate") if not start_date: start_date = get_value_in_tag(xml_doc, "prism:coverDisplayDate") if not start_date: start_date = ...
Return the best effort start_date.
Below is the the instruction that describes the task: ### Input: Return the best effort start_date. ### Response: def get_publication_date(self, xml_doc): """Return the best effort start_date.""" start_date = get_value_in_tag(xml_doc, "prism:coverDate") if not start_date: start_...
def _is_raising(body: typing.List) -> bool: """Return true if the given statement node raise an exception""" for node in body: if isinstance(node, astroid.Raise): return True return False
Return true if the given statement node raise an exception
Below is the the instruction that describes the task: ### Input: Return true if the given statement node raise an exception ### Response: def _is_raising(body: typing.List) -> bool: """Return true if the given statement node raise an exception""" for node in body: if isinstance(node, astroid.Raise)...
def get_index_text(self, modname, name_cls): """Return text for index entry based on object type.""" if self.objtype.endswith('function'): if not modname: return _('%s() (built-in %s)') % \ (name_cls[0], self.chpl_type_name) return _('%s() (in ...
Return text for index entry based on object type.
Below is the the instruction that describes the task: ### Input: Return text for index entry based on object type. ### Response: def get_index_text(self, modname, name_cls): """Return text for index entry based on object type.""" if self.objtype.endswith('function'): if not modname: ...
def get_weather_code(self, ip): ''' Get weather_code ''' rec = self.get_all(ip) return rec and rec.weather_code
Get weather_code
Below is the the instruction that describes the task: ### Input: Get weather_code ### Response: def get_weather_code(self, ip): ''' Get weather_code ''' rec = self.get_all(ip) return rec and rec.weather_code
def get_nodes(api_url=None, verify=False, cert=list()): """ Returns info for all Nodes :param api_url: Base PuppetDB API url """ return utils._make_api_request(api_url, '/nodes', verify, cert)
Returns info for all Nodes :param api_url: Base PuppetDB API url
Below is the the instruction that describes the task: ### Input: Returns info for all Nodes :param api_url: Base PuppetDB API url ### Response: def get_nodes(api_url=None, verify=False, cert=list()): """ Returns info for all Nodes :param api_url: Base PuppetDB API url """ return utils._m...
def init_session(self, get_token=True): """ init a new oauth2 session that is required to access the cloud :param bool get_token: if True, a token will be obtained, after the session has been created """ if (self._client_id is None) or (self._clien...
init a new oauth2 session that is required to access the cloud :param bool get_token: if True, a token will be obtained, after the session has been created
Below is the the instruction that describes the task: ### Input: init a new oauth2 session that is required to access the cloud :param bool get_token: if True, a token will be obtained, after the session has been created ### Response: def init_session(self, get_token=True): ...
def trocar_codigo_de_ativacao(self, novo_codigo_ativacao, opcao=constantes.CODIGO_ATIVACAO_REGULAR, codigo_emergencia=None): """Sobrepõe :meth:`~satcfe.base.FuncoesSAT.trocar_codigo_de_ativacao`. :return: Uma resposta SAT padrão. :rtype: satcfe.resposta.padrao.RespostaSA...
Sobrepõe :meth:`~satcfe.base.FuncoesSAT.trocar_codigo_de_ativacao`. :return: Uma resposta SAT padrão. :rtype: satcfe.resposta.padrao.RespostaSAT
Below is the the instruction that describes the task: ### Input: Sobrepõe :meth:`~satcfe.base.FuncoesSAT.trocar_codigo_de_ativacao`. :return: Uma resposta SAT padrão. :rtype: satcfe.resposta.padrao.RespostaSAT ### Response: def trocar_codigo_de_ativacao(self, novo_codigo_ativacao, opca...
def check(self, version): """Check that a version is inside this SemanticVersionRange Args: version (SemanticVersion): The version to check Returns: bool: True if the version is included in the range, False if not """ for disjunct in self._disjuncts: ...
Check that a version is inside this SemanticVersionRange Args: version (SemanticVersion): The version to check Returns: bool: True if the version is included in the range, False if not
Below is the the instruction that describes the task: ### Input: Check that a version is inside this SemanticVersionRange Args: version (SemanticVersion): The version to check Returns: bool: True if the version is included in the range, False if not ### Response: def check...
def robust_std(x, debug=False): """Compute a robust estimator of the standard deviation See Eq. 3.36 (page 84) in Statistics, Data Mining, and Machine in Astronomy, by Ivezic, Connolly, VanderPlas & Gray Parameters ---------- x : 1d numpy array, float Array of input values which standa...
Compute a robust estimator of the standard deviation See Eq. 3.36 (page 84) in Statistics, Data Mining, and Machine in Astronomy, by Ivezic, Connolly, VanderPlas & Gray Parameters ---------- x : 1d numpy array, float Array of input values which standard deviation is requested. debug : ...
Below is the the instruction that describes the task: ### Input: Compute a robust estimator of the standard deviation See Eq. 3.36 (page 84) in Statistics, Data Mining, and Machine in Astronomy, by Ivezic, Connolly, VanderPlas & Gray Parameters ---------- x : 1d numpy array, float Arra...
def _find_im_paths(self, subj_mp, obs_name, target_polarity, max_paths=1, max_path_length=5): """Check for a source/target path in the influence map. Parameters ---------- subj_mp : pysb.MonomerPattern MonomerPattern corresponding to the subject of the...
Check for a source/target path in the influence map. Parameters ---------- subj_mp : pysb.MonomerPattern MonomerPattern corresponding to the subject of the Statement being checked. obs_name : str Name of the PySB model Observable corresponding to the ...
Below is the the instruction that describes the task: ### Input: Check for a source/target path in the influence map. Parameters ---------- subj_mp : pysb.MonomerPattern MonomerPattern corresponding to the subject of the Statement being checked. obs_name : st...
def _add_spanning_relation(self, source, target): """add a spanning relation to this docgraph""" self.add_edge(source, target, layers={self.ns, self.ns+':unit'}, edge_type=EdgeTypes.spanning_relation)
add a spanning relation to this docgraph
Below is the the instruction that describes the task: ### Input: add a spanning relation to this docgraph ### Response: def _add_spanning_relation(self, source, target): """add a spanning relation to this docgraph""" self.add_edge(source, target, layers={self.ns, self.ns+':unit'}, ...
def Prl(self): r'''Prandtl number of the liquid phase of the chemical at its current temperature and pressure, [dimensionless]. .. math:: Pr = \frac{C_p \mu}{k} Utilizes the temperature and pressure dependent object oriented interfaces :obj:`thermo.viscosity.Viscosi...
r'''Prandtl number of the liquid phase of the chemical at its current temperature and pressure, [dimensionless]. .. math:: Pr = \frac{C_p \mu}{k} Utilizes the temperature and pressure dependent object oriented interfaces :obj:`thermo.viscosity.ViscosityLiquid`, :obj...
Below is the the instruction that describes the task: ### Input: r'''Prandtl number of the liquid phase of the chemical at its current temperature and pressure, [dimensionless]. .. math:: Pr = \frac{C_p \mu}{k} Utilizes the temperature and pressure dependent object oriented ...
def process_nxml_str(nxml_str, citation=None, offline=False, output_fname=default_output_fname): """Return a ReachProcessor by processing the given NXML string. NXML is the format used by PubmedCentral for papers in the open access subset. Parameters ---------- nxml_str : ...
Return a ReachProcessor by processing the given NXML string. NXML is the format used by PubmedCentral for papers in the open access subset. Parameters ---------- nxml_str : str The NXML string to be processed. citation : Optional[str] A PubMed ID passed to be used in the eviden...
Below is the the instruction that describes the task: ### Input: Return a ReachProcessor by processing the given NXML string. NXML is the format used by PubmedCentral for papers in the open access subset. Parameters ---------- nxml_str : str The NXML string to be processed. citatio...
def connect(self, app_id, wait=True, security=None): """Connect to a running application. Parameters ---------- app_id : str The id of the application. wait : bool, optional If true [default], blocks until the application starts. If False, wil...
Connect to a running application. Parameters ---------- app_id : str The id of the application. wait : bool, optional If true [default], blocks until the application starts. If False, will raise a ``ApplicationNotRunningError`` immediately if the ...
Below is the the instruction that describes the task: ### Input: Connect to a running application. Parameters ---------- app_id : str The id of the application. wait : bool, optional If true [default], blocks until the application starts. If False, ...
def save(self): """Update the infoblox with new values for the specified object, or add the values if it's a new object all together. :raises: AssertionError :raises: infoblox.exceptions.ProtocolError """ if 'save' not in self._supports: raise AssertionError...
Update the infoblox with new values for the specified object, or add the values if it's a new object all together. :raises: AssertionError :raises: infoblox.exceptions.ProtocolError
Below is the the instruction that describes the task: ### Input: Update the infoblox with new values for the specified object, or add the values if it's a new object all together. :raises: AssertionError :raises: infoblox.exceptions.ProtocolError ### Response: def save(self): """Up...
def bank_account_query(self, number, date, account_type, bank_id): """Bank account statement request""" return self.authenticated_query( self._bareq(number, date, account_type, bank_id) )
Bank account statement request
Below is the the instruction that describes the task: ### Input: Bank account statement request ### Response: def bank_account_query(self, number, date, account_type, bank_id): """Bank account statement request""" return self.authenticated_query( self._bareq(number, date, account_type, ...
def _download_progress_cb(blocknum, blocksize, totalsize): """Banana Banana""" readsofar = blocknum * blocksize if totalsize > 0: percent = readsofar * 1e2 / totalsize msg = "\r%5.1f%% %*d / %d" % ( percent, len(str(totalsize)), readsofar, totalsize) print(msg) if...
Banana Banana
Below is the the instruction that describes the task: ### Input: Banana Banana ### Response: def _download_progress_cb(blocknum, blocksize, totalsize): """Banana Banana""" readsofar = blocknum * blocksize if totalsize > 0: percent = readsofar * 1e2 / totalsize msg = "\r%5.1f%% %*d / %d"...
def _Fgamma(self, x, Ep): """ KAB06 Eq.58 Note: Quantities are not used in this function Parameters ---------- x : float Egamma/Eprot Ep : float Eprot [TeV] """ L = np.log(Ep) B = 1.30 + 0.14 * L + 0.011 * L ** 2 ...
KAB06 Eq.58 Note: Quantities are not used in this function Parameters ---------- x : float Egamma/Eprot Ep : float Eprot [TeV]
Below is the the instruction that describes the task: ### Input: KAB06 Eq.58 Note: Quantities are not used in this function Parameters ---------- x : float Egamma/Eprot Ep : float Eprot [TeV] ### Response: def _Fgamma(self, x, Ep): """ ...
def get_extra_functions(self) -> Dict[str, Callable]: """Get a list of additional features Returns: Dict[str, Callable]: A dict of methods marked as additional features. Method can be called with ``get_extra_functions()["methodName"]()``. """ if self.channel_type...
Get a list of additional features Returns: Dict[str, Callable]: A dict of methods marked as additional features. Method can be called with ``get_extra_functions()["methodName"]()``.
Below is the the instruction that describes the task: ### Input: Get a list of additional features Returns: Dict[str, Callable]: A dict of methods marked as additional features. Method can be called with ``get_extra_functions()["methodName"]()``. ### Response: def get_extra_functio...
def extract(self, obj, bypass_ref=False): """ Extract parent of obj, according to current token. :param obj: the object source :param bypass_ref: not used """ for i in range(0, self.stages): try: obj = obj.parent_obj except Attribu...
Extract parent of obj, according to current token. :param obj: the object source :param bypass_ref: not used
Below is the the instruction that describes the task: ### Input: Extract parent of obj, according to current token. :param obj: the object source :param bypass_ref: not used ### Response: def extract(self, obj, bypass_ref=False): """ Extract parent of obj, according to current toke...
def get_package_formats(): """Get the list of available package formats and parameters.""" # pylint: disable=fixme # HACK: This obviously isn't great, and it is subject to change as # the API changes, but it'll do for now as a interim method of # introspection to get the parameters we need. def ...
Get the list of available package formats and parameters.
Below is the the instruction that describes the task: ### Input: Get the list of available package formats and parameters. ### Response: def get_package_formats(): """Get the list of available package formats and parameters.""" # pylint: disable=fixme # HACK: This obviously isn't great, and it is subje...
def auto_convert_string_cell(flagable, cell_str, position, worksheet, flags, units, parens_as_neg=True): ''' Handles the string case of cell and attempts auto-conversion for auto_convert_cell. Args: parens_as_neg: Converts numerics surrounded by parens to negative v...
Handles the string case of cell and attempts auto-conversion for auto_convert_cell. Args: parens_as_neg: Converts numerics surrounded by parens to negative values
Below is the the instruction that describes the task: ### Input: Handles the string case of cell and attempts auto-conversion for auto_convert_cell. Args: parens_as_neg: Converts numerics surrounded by parens to negative values ### Response: def auto_convert_string_cell(flagable, cell_str, positio...
def url_to_query(url): """ Given a big huge bugzilla query URL, returns a query dict that can be passed along to the Bugzilla.query() method. """ q = {} # pylint: disable=unpacking-non-sequence (ignore, ignore, path, ignore, query, ignore) = urlparse(url...
Given a big huge bugzilla query URL, returns a query dict that can be passed along to the Bugzilla.query() method.
Below is the the instruction that describes the task: ### Input: Given a big huge bugzilla query URL, returns a query dict that can be passed along to the Bugzilla.query() method. ### Response: def url_to_query(url): """ Given a big huge bugzilla query URL, returns a query dict that can ...
def _componentSortKey(componentAndType): """Sort SET components by tag Sort regardless of the Choice value (static sort) """ component, asn1Spec = componentAndType if asn1Spec is None: asn1Spec = component if asn1Spec.typeId == univ.Choice.typeId and not as...
Sort SET components by tag Sort regardless of the Choice value (static sort)
Below is the the instruction that describes the task: ### Input: Sort SET components by tag Sort regardless of the Choice value (static sort) ### Response: def _componentSortKey(componentAndType): """Sort SET components by tag Sort regardless of the Choice value (static sort) """ ...
def get_string_list(self, key): """Get a list of strings.""" strings = [] size = self.beginReadArray(key) for i in range(size): self.setArrayIndex(i) entry = str(self._value("entry")) strings.append(entry) self.endArray() return strings
Get a list of strings.
Below is the the instruction that describes the task: ### Input: Get a list of strings. ### Response: def get_string_list(self, key): """Get a list of strings.""" strings = [] size = self.beginReadArray(key) for i in range(size): self.setArrayIndex(i) entry =...
def scoped_session_decorator(func): """Manage contexts and add debugging to db sessions.""" @wraps(func) def wrapper(*args, **kwargs): with sessions_scope(session): # The session used in func comes from the funcs globals, but # it will be a proxied thread local var from the ...
Manage contexts and add debugging to db sessions.
Below is the the instruction that describes the task: ### Input: Manage contexts and add debugging to db sessions. ### Response: def scoped_session_decorator(func): """Manage contexts and add debugging to db sessions.""" @wraps(func) def wrapper(*args, **kwargs): with sessions_scope(session): ...
def FindRegex(self, regex, data): """Search the data for a hit.""" for match in re.finditer(regex, data, flags=re.I | re.S | re.M): yield (match.start(), match.end())
Search the data for a hit.
Below is the the instruction that describes the task: ### Input: Search the data for a hit. ### Response: def FindRegex(self, regex, data): """Search the data for a hit.""" for match in re.finditer(regex, data, flags=re.I | re.S | re.M): yield (match.start(), match.end())
def Clift(Re): r'''Calculates drag coefficient of a smooth sphere using the method in [1]_ as described in [2]_. .. math:: C_D = \left\{ \begin{array}{ll} \frac{24}{Re} + \frac{3}{16} & \mbox{if $Re < 0.01$}\\ \frac{24}{Re}(1 + 0.1315Re^{0.82 - 0.05\log Re}) & \mbox{if $0.01 < Re < ...
r'''Calculates drag coefficient of a smooth sphere using the method in [1]_ as described in [2]_. .. math:: C_D = \left\{ \begin{array}{ll} \frac{24}{Re} + \frac{3}{16} & \mbox{if $Re < 0.01$}\\ \frac{24}{Re}(1 + 0.1315Re^{0.82 - 0.05\log Re}) & \mbox{if $0.01 < Re < 20$}\\ \fra...
Below is the the instruction that describes the task: ### Input: r'''Calculates drag coefficient of a smooth sphere using the method in [1]_ as described in [2]_. .. math:: C_D = \left\{ \begin{array}{ll} \frac{24}{Re} + \frac{3}{16} & \mbox{if $Re < 0.01$}\\ \frac{24}{Re}(1 + 0.131...
def _update_limits_from_api(self): """ Call :py:meth:`~.connect` and then check what region we're running in; adjust default limits as required for regions that differ (us-east-1). """ region_limits = { 'us-east-1': 70 } self.connect() rname = ...
Call :py:meth:`~.connect` and then check what region we're running in; adjust default limits as required for regions that differ (us-east-1).
Below is the the instruction that describes the task: ### Input: Call :py:meth:`~.connect` and then check what region we're running in; adjust default limits as required for regions that differ (us-east-1). ### Response: def _update_limits_from_api(self): """ Call :py:meth:`~.connect` and t...
def igphyml(input_file=None, tree_file=None, root=None, verbose=False): ''' Computes a phylogenetic tree using IgPhyML. .. note:: IgPhyML must be installed. It can be downloaded from https://github.com/kbhoehn/IgPhyML. Args: input_file (str): Path to a Phylip-formatted multip...
Computes a phylogenetic tree using IgPhyML. .. note:: IgPhyML must be installed. It can be downloaded from https://github.com/kbhoehn/IgPhyML. Args: input_file (str): Path to a Phylip-formatted multiple sequence alignment. Required. tree_file (str): Path to the output tree f...
Below is the the instruction that describes the task: ### Input: Computes a phylogenetic tree using IgPhyML. .. note:: IgPhyML must be installed. It can be downloaded from https://github.com/kbhoehn/IgPhyML. Args: input_file (str): Path to a Phylip-formatted multiple sequence ali...
def project_run_path(cls, project, transfer_config, run): """Return a fully-qualified project_run string.""" return google.api_core.path_template.expand( "projects/{project}/transferConfigs/{transfer_config}/runs/{run}", project=project, transfer_config=transfer_confi...
Return a fully-qualified project_run string.
Below is the the instruction that describes the task: ### Input: Return a fully-qualified project_run string. ### Response: def project_run_path(cls, project, transfer_config, run): """Return a fully-qualified project_run string.""" return google.api_core.path_template.expand( "projects...
def node_from_elem(elem, nodefactory=Node, lazy=()): """ Convert (recursively) an ElementTree object into a Node object. """ children = list(elem) lineno = getattr(elem, 'lineno', None) if not children: return nodefactory(elem.tag, dict(elem.attrib), elem.text, ...
Convert (recursively) an ElementTree object into a Node object.
Below is the the instruction that describes the task: ### Input: Convert (recursively) an ElementTree object into a Node object. ### Response: def node_from_elem(elem, nodefactory=Node, lazy=()): """ Convert (recursively) an ElementTree object into a Node object. """ children = list(elem) linen...
def _formatters_default(self): """Activate the default formatters.""" formatter_classes = [ PlainTextFormatter, HTMLFormatter, SVGFormatter, PNGFormatter, JPEGFormatter, LatexFormatter, JSONFormatter, Javascr...
Activate the default formatters.
Below is the the instruction that describes the task: ### Input: Activate the default formatters. ### Response: def _formatters_default(self): """Activate the default formatters.""" formatter_classes = [ PlainTextFormatter, HTMLFormatter, SVGFormatter, ...
def get_uri_obj(uri, storage_args={}): """ Retrieve the underlying storage object based on the URI (i.e., scheme). :param str uri: URI to get storage object for :param dict storage_args: Keyword arguments to pass to the underlying storage object """ if isinstance(uri, BaseURI): return uri ...
Retrieve the underlying storage object based on the URI (i.e., scheme). :param str uri: URI to get storage object for :param dict storage_args: Keyword arguments to pass to the underlying storage object
Below is the the instruction that describes the task: ### Input: Retrieve the underlying storage object based on the URI (i.e., scheme). :param str uri: URI to get storage object for :param dict storage_args: Keyword arguments to pass to the underlying storage object ### Response: def get_uri_obj(uri, sto...
def author(self, value): """ Setter for **self.__author** attribute. :param value: Attribute value. :type value: unicode """ if value is not None: assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format( "author"...
Setter for **self.__author** attribute. :param value: Attribute value. :type value: unicode
Below is the the instruction that describes the task: ### Input: Setter for **self.__author** attribute. :param value: Attribute value. :type value: unicode ### Response: def author(self, value): """ Setter for **self.__author** attribute. :param value: Attribute value. ...
def _collect_args(args) -> ISeq: """Collect Python starred arguments into a Basilisp list.""" if isinstance(args, tuple): return llist.list(args) raise TypeError("Python variadic arguments should always be a tuple")
Collect Python starred arguments into a Basilisp list.
Below is the the instruction that describes the task: ### Input: Collect Python starred arguments into a Basilisp list. ### Response: def _collect_args(args) -> ISeq: """Collect Python starred arguments into a Basilisp list.""" if isinstance(args, tuple): return llist.list(args) raise TypeError...
def get_descendants(self): """ :returns: A queryset of all the node's descendants as DFS, doesn't include the node itself """ return self.__class__.get_tree(self).exclude(pk=self.pk)
:returns: A queryset of all the node's descendants as DFS, doesn't include the node itself
Below is the the instruction that describes the task: ### Input: :returns: A queryset of all the node's descendants as DFS, doesn't include the node itself ### Response: def get_descendants(self): """ :returns: A queryset of all the node's descendants as DFS, doesn't include...
def moments(self): """The first two time delay weighted statistical moments of the ARMA response.""" timepoints = self.ma.delays response = self.response moment1 = statstools.calc_mean_time(timepoints, response) moment2 = statstools.calc_mean_time_deviation( t...
The first two time delay weighted statistical moments of the ARMA response.
Below is the the instruction that describes the task: ### Input: The first two time delay weighted statistical moments of the ARMA response. ### Response: def moments(self): """The first two time delay weighted statistical moments of the ARMA response.""" timepoints = self.ma.delays...