code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def get_taker_id(self): """Gets the ``Id`` of the resource who took or is taking this assessment. return: (osid.id.Id) - the resource ``Id`` *compliance: mandatory -- This method must be implemented.* """ if self._my_map['takerId']: return Id(self._my_map['takerId']...
Gets the ``Id`` of the resource who took or is taking this assessment. return: (osid.id.Id) - the resource ``Id`` *compliance: mandatory -- This method must be implemented.*
Below is the the instruction that describes the task: ### Input: Gets the ``Id`` of the resource who took or is taking this assessment. return: (osid.id.Id) - the resource ``Id`` *compliance: mandatory -- This method must be implemented.* ### Response: def get_taker_id(self): """Gets the `...
def human_xor_01(X, y, model_generator, method_name): """ XOR (false/true) This tests how well a feature attribution method agrees with human intuition for an eXclusive OR operation combined with linear effects. This metric deals specifically with the question of credit allocation for the following fun...
XOR (false/true) This tests how well a feature attribution method agrees with human intuition for an eXclusive OR operation combined with linear effects. This metric deals specifically with the question of credit allocation for the following function when all three inputs are true: if fever: +2 poi...
Below is the the instruction that describes the task: ### Input: XOR (false/true) This tests how well a feature attribution method agrees with human intuition for an eXclusive OR operation combined with linear effects. This metric deals specifically with the question of credit allocation for the follow...
def deco_optional(decorator): """ optional argument 를 포함하는 decorator를 만드는 decorator """ @functools.wraps(decorator) def dispatcher(*args, **kwargs): one_arg = len(args) == 1 and not kwargs if one_arg and inspect.isfunction(args[0]): decor_obj = decorator() re...
optional argument 를 포함하는 decorator를 만드는 decorator
Below is the the instruction that describes the task: ### Input: optional argument 를 포함하는 decorator를 만드는 decorator ### Response: def deco_optional(decorator): """ optional argument 를 포함하는 decorator를 만드는 decorator """ @functools.wraps(decorator) def dispatcher(*args, **kwargs): one_arg ...
def image_by_id(self, id): """ Return image with given Id """ if not id: return None return next((image for image in self.images() if image['Id'] == id), None)
Return image with given Id
Below is the the instruction that describes the task: ### Input: Return image with given Id ### Response: def image_by_id(self, id): """ Return image with given Id """ if not id: return None return next((image for image in self.images() if image['Id'] == id), ...
def p_block(p): """block : '{' commands '}' """ # section 3.2: REQUIRE command must come before any other commands, # which means it can't be in the block of another command if any(command.RULE_IDENTIFIER == 'REQUIRE' for command in p[2].commands): print("REQUIRE command not allowed i...
block : '{' commands '}'
Below is the the instruction that describes the task: ### Input: block : '{' commands '}' ### Response: def p_block(p): """block : '{' commands '}' """ # section 3.2: REQUIRE command must come before any other commands, # which means it can't be in the block of another command if any(command.RULE_I...
def set_qualifier(self, value): """Set the qualifier for the element. Verifies the element is allowed to have a qualifier, and throws an exception if not. """ if self.allows_qualifier: self.qualifier = value.strip() else: raise UNTLStructureExcept...
Set the qualifier for the element. Verifies the element is allowed to have a qualifier, and throws an exception if not.
Below is the the instruction that describes the task: ### Input: Set the qualifier for the element. Verifies the element is allowed to have a qualifier, and throws an exception if not. ### Response: def set_qualifier(self, value): """Set the qualifier for the element. Verifies the...
def read_pyproject_conf(data: str) -> dict: """We expect to have a section in pyproject looking like ``` [tool.commitizen] name = "cz_conventional_commits" ``` """ doc = parse(data) try: return doc["tool"]["commitizen"] except exceptions.NonExistentKey: return {}
We expect to have a section in pyproject looking like ``` [tool.commitizen] name = "cz_conventional_commits" ```
Below is the the instruction that describes the task: ### Input: We expect to have a section in pyproject looking like ``` [tool.commitizen] name = "cz_conventional_commits" ``` ### Response: def read_pyproject_conf(data: str) -> dict: """We expect to have a section in pyproject looking like ...
def hset(self, key, value): """Create key/value pair in Redis. Args: key (string): The key to create in Redis. value (any): The value to store in Redis. Returns: (string): The response from Redis. """ return self.r.hset(self.hash, key, value)
Create key/value pair in Redis. Args: key (string): The key to create in Redis. value (any): The value to store in Redis. Returns: (string): The response from Redis.
Below is the the instruction that describes the task: ### Input: Create key/value pair in Redis. Args: key (string): The key to create in Redis. value (any): The value to store in Redis. Returns: (string): The response from Redis. ### Response: def hset(self, k...
def _get_dS2S(self, imt_per): """ Table 4 of 2013 report """ if imt_per == 0: dS2S = 0.05 elif 0 < imt_per < 0.15: dS2S = self._interp_function(-0.15, 0.05, 0.15, 0, imt_per) elif 0.15 <= imt_per < 0.45: dS2S = self._interp_function(0.4...
Table 4 of 2013 report
Below is the the instruction that describes the task: ### Input: Table 4 of 2013 report ### Response: def _get_dS2S(self, imt_per): """ Table 4 of 2013 report """ if imt_per == 0: dS2S = 0.05 elif 0 < imt_per < 0.15: dS2S = self._interp_function(-0.15...
def search_auth(self, list_or_file_path, source): """ Looking for auth in env, cmdline, str :param list_or_file_path: :param source: """ _auth = source.args['auth'] if isinstance(_auth, str): if ':' in _auth: _auth = _auth.split(':') ...
Looking for auth in env, cmdline, str :param list_or_file_path: :param source:
Below is the the instruction that describes the task: ### Input: Looking for auth in env, cmdline, str :param list_or_file_path: :param source: ### Response: def search_auth(self, list_or_file_path, source): """ Looking for auth in env, cmdline, str :param list_or_file_path:...
def store(auth, provider, config_location=DEFAULT_CONFIG_DIR): """Store auth info in file for specified provider """ auth_file = None try: # only for custom locations _create_config_dir(config_location, "Creating custom config directory [%s]... ") config_...
Store auth info in file for specified provider
Below is the the instruction that describes the task: ### Input: Store auth info in file for specified provider ### Response: def store(auth, provider, config_location=DEFAULT_CONFIG_DIR): """Store auth info in file for specified provider """ auth_file = None try: # only for custom locations ...
def gamma(arr, g): r""" Gamma correction is a nonlinear operation that adjusts the image's channel values pixel-by-pixel according to a power-law: .. math:: pixel_{out} = pixel_{in} ^ {\gamma} Setting gamma (:math:`\gamma`) to be less than 1.0 darkens the image and setting gamma to be grea...
r""" Gamma correction is a nonlinear operation that adjusts the image's channel values pixel-by-pixel according to a power-law: .. math:: pixel_{out} = pixel_{in} ^ {\gamma} Setting gamma (:math:`\gamma`) to be less than 1.0 darkens the image and setting gamma to be greater than 1.0 lightens i...
Below is the the instruction that describes the task: ### Input: r""" Gamma correction is a nonlinear operation that adjusts the image's channel values pixel-by-pixel according to a power-law: .. math:: pixel_{out} = pixel_{in} ^ {\gamma} Setting gamma (:math:`\gamma`) to be less than 1.0 dark...
def _known_populations(row, pops): """Find variants present in substantial frequency in population databases. """ cutoff = 0.01 out = set([]) for pop, base in [("esp", "af_esp_all"), ("1000g", "af_1kg_all"), ("exac", "af_exac_all"), ("anypop", "max_aaf_all")]: for key i...
Find variants present in substantial frequency in population databases.
Below is the the instruction that describes the task: ### Input: Find variants present in substantial frequency in population databases. ### Response: def _known_populations(row, pops): """Find variants present in substantial frequency in population databases. """ cutoff = 0.01 out = set([]) fo...
def list_tags(Name, region=None, key=None, keyid=None, profile=None): ''' List tags of a trail Returns: tags: - {...} - {...} CLI Example: .. code-block:: bash salt myminion boto_cloudtrail.list_tags my_trail ''' try: conn = _get_c...
List tags of a trail Returns: tags: - {...} - {...} CLI Example: .. code-block:: bash salt myminion boto_cloudtrail.list_tags my_trail
Below is the the instruction that describes the task: ### Input: List tags of a trail Returns: tags: - {...} - {...} CLI Example: .. code-block:: bash salt myminion boto_cloudtrail.list_tags my_trail ### Response: def list_tags(Name, region=None, key=N...
def is_public(self): """``True`` if this is a public key, otherwise ``False``""" return isinstance(self._key, Public) and not isinstance(self._key, Private)
``True`` if this is a public key, otherwise ``False``
Below is the the instruction that describes the task: ### Input: ``True`` if this is a public key, otherwise ``False`` ### Response: def is_public(self): """``True`` if this is a public key, otherwise ``False``""" return isinstance(self._key, Public) and not isinstance(self._key, Private)
def _augment_observation(self, ob, reward, cumulative_reward): """"Expand observation array with additional information header (top rows). Args: ob: observation reward: reward to be included in header. cumulative_reward: total cumulated reward to be included in header. Returns: Exp...
Expand observation array with additional information header (top rows). Args: ob: observation reward: reward to be included in header. cumulative_reward: total cumulated reward to be included in header. Returns: Expanded observation array.
Below is the the instruction that describes the task: ### Input: Expand observation array with additional information header (top rows). Args: ob: observation reward: reward to be included in header. cumulative_reward: total cumulated reward to be included in header. Returns: Expan...
def makePlot(gmag, pdf=False, png=False, rvs=False): """ Make a plot of a Mv vs (V-I) colour magnitude diagram containing lines of constant distance for stars at G=20. This will give an idea of the reach of Gaia. Parameters ---------- args - command line arguments """ vmini = np.linspace(-0.5,4.0,100)...
Make a plot of a Mv vs (V-I) colour magnitude diagram containing lines of constant distance for stars at G=20. This will give an idea of the reach of Gaia. Parameters ---------- args - command line arguments
Below is the the instruction that describes the task: ### Input: Make a plot of a Mv vs (V-I) colour magnitude diagram containing lines of constant distance for stars at G=20. This will give an idea of the reach of Gaia. Parameters ---------- args - command line arguments ### Response: def makePlot(gmag,...
def _marker_line(self): # type: () -> str """Generate a correctly sized marker line. e.g. '+------------------+---------+----------+---------+' :return: str """ output = '' for col in sorted(self.col_widths): line = self.COLUMN_MARK + (self....
Generate a correctly sized marker line. e.g. '+------------------+---------+----------+---------+' :return: str
Below is the the instruction that describes the task: ### Input: Generate a correctly sized marker line. e.g. '+------------------+---------+----------+---------+' :return: str ### Response: def _marker_line(self): # type: () -> str """Generate a correctly sized marker li...
def create_table(self, model): """Create model and table in database. >> migrator.create_table(model) """ self.orm[model._meta.table_name] = model model._meta.database = self.database self.ops.append(model.create_table) return model
Create model and table in database. >> migrator.create_table(model)
Below is the the instruction that describes the task: ### Input: Create model and table in database. >> migrator.create_table(model) ### Response: def create_table(self, model): """Create model and table in database. >> migrator.create_table(model) """ self.orm[model._meta...
def imagenet_model_fn(features, labels, mode, params): """Our model_fn for ResNet to be used with our Estimator.""" # Warmup and higher lr may not be valid for fine tuning with small batches # and smaller numbers of training images. if params['fine_tune']: base_lr = .1 else: base_lr = .128 learnin...
Our model_fn for ResNet to be used with our Estimator.
Below is the the instruction that describes the task: ### Input: Our model_fn for ResNet to be used with our Estimator. ### Response: def imagenet_model_fn(features, labels, mode, params): """Our model_fn for ResNet to be used with our Estimator.""" # Warmup and higher lr may not be valid for fine tuning with...
def install_reactor(explicitReactor=None, verbose=False): """ Install Twisted reactor. :param explicitReactor: If provided, install this reactor. Else, install optimal reactor. :type explicitReactor: obj :param verbose: If ``True``, print what happens. :type verbose: bool """ import sys...
Install Twisted reactor. :param explicitReactor: If provided, install this reactor. Else, install optimal reactor. :type explicitReactor: obj :param verbose: If ``True``, print what happens. :type verbose: bool
Below is the the instruction that describes the task: ### Input: Install Twisted reactor. :param explicitReactor: If provided, install this reactor. Else, install optimal reactor. :type explicitReactor: obj :param verbose: If ``True``, print what happens. :type verbose: bool ### Response: def inst...
def find(self, path, all=False): """ Looks for files in the app directories. """ matches = [] for app in self.apps: app_location = self.storages[app].location if app_location not in searched_locations: searched_locations.append(app_location...
Looks for files in the app directories.
Below is the the instruction that describes the task: ### Input: Looks for files in the app directories. ### Response: def find(self, path, all=False): """ Looks for files in the app directories. """ matches = [] for app in self.apps: app_location = self.storages...
def add_view(self, view): """ Add a ViewTrack object to this composite. :param view: A ViewTrack object. """ self.add_child(view) self.views.append(view)
Add a ViewTrack object to this composite. :param view: A ViewTrack object.
Below is the the instruction that describes the task: ### Input: Add a ViewTrack object to this composite. :param view: A ViewTrack object. ### Response: def add_view(self, view): """ Add a ViewTrack object to this composite. :param view: A ViewTrack object...
def entry_point(args=None, configuration=None): """ Standard entry point for the docker interface CLI. Parameters ---------- args : list or None list of command line arguments or `None` to use `sys.argv` configuration : dict parsed configuration or `None` to load and build a con...
Standard entry point for the docker interface CLI. Parameters ---------- args : list or None list of command line arguments or `None` to use `sys.argv` configuration : dict parsed configuration or `None` to load and build a configuration given the command line arguments Rai...
Below is the the instruction that describes the task: ### Input: Standard entry point for the docker interface CLI. Parameters ---------- args : list or None list of command line arguments or `None` to use `sys.argv` configuration : dict parsed configuration or `None` to load and bu...
def get_InsideConvexPoly(self, RelOff=_def.TorRelOff, ZLim='Def', Spline=True, Splprms=_def.TorSplprms, NP=_def.TorInsideNP, Plot=False, Test=True): """ Return a polygon that is a smaller and smoothed approximation of Ves.Poly, useful for excluding the d...
Return a polygon that is a smaller and smoothed approximation of Ves.Poly, useful for excluding the divertor region in a Tokamak For some uses, it can be practical to approximate the polygon defining the Ves object (which can be non-convex, like with a divertor), by a simpler, sligthly smaller and convex polyg...
Below is the the instruction that describes the task: ### Input: Return a polygon that is a smaller and smoothed approximation of Ves.Poly, useful for excluding the divertor region in a Tokamak For some uses, it can be practical to approximate the polygon defining the Ves object (which can be non-convex, l...
def _mesh_values(data, box_size): """ Extract all the data values in boxes of size ``box_size``. Values from incomplete boxes, either because of the image edges or masked pixels, are not returned. Parameters ---------- data : 2D `~numpy.ma.MaskedArray` The input masked array. ...
Extract all the data values in boxes of size ``box_size``. Values from incomplete boxes, either because of the image edges or masked pixels, are not returned. Parameters ---------- data : 2D `~numpy.ma.MaskedArray` The input masked array. box_size : int The box size. Retu...
Below is the the instruction that describes the task: ### Input: Extract all the data values in boxes of size ``box_size``. Values from incomplete boxes, either because of the image edges or masked pixels, are not returned. Parameters ---------- data : 2D `~numpy.ma.MaskedArray` The in...
def compressBWT(inputFN, outputFN, numProcs, logger): ''' Current encoding scheme uses 3 LSB for the letter and 5 MSB for a count, note that consecutive ones of the same character combine to create one large count. So to represent 34A, you would have 00010|001 followed by 00001|001 which can be though of ...
Current encoding scheme uses 3 LSB for the letter and 5 MSB for a count, note that consecutive ones of the same character combine to create one large count. So to represent 34A, you would have 00010|001 followed by 00001|001 which can be though of as 2*1 + 32*1 = 34 @param inputFN - the filename of the BWT...
Below is the the instruction that describes the task: ### Input: Current encoding scheme uses 3 LSB for the letter and 5 MSB for a count, note that consecutive ones of the same character combine to create one large count. So to represent 34A, you would have 00010|001 followed by 00001|001 which can be though o...
def getmlsthelper(referencefilepath, start, organism, update): """Prepares to run the getmlst.py script provided in SRST2""" from accessoryFunctions.accessoryFunctions import GenObject # Initialise a set to for the organism(s) for which new alleles and profiles are desired organismset = set() # Allo...
Prepares to run the getmlst.py script provided in SRST2
Below is the the instruction that describes the task: ### Input: Prepares to run the getmlst.py script provided in SRST2 ### Response: def getmlsthelper(referencefilepath, start, organism, update): """Prepares to run the getmlst.py script provided in SRST2""" from accessoryFunctions.accessoryFunctions impo...
def delete_contact(self, contact_id): """ Delete single contact """ url = self.CONTACTS_ID_URL % contact_id connection = Connection(self.token) connection.set_url(self.production, url) return connection.delete_request()
Delete single contact
Below is the the instruction that describes the task: ### Input: Delete single contact ### Response: def delete_contact(self, contact_id): """ Delete single contact """ url = self.CONTACTS_ID_URL % contact_id connection = Connection(self.token) connection.set_url(se...
def get_email_link(email, value=None): """ Returns a well-formed link to an email address. If email is None/empty, returns an empty string :param email: email address :param link_text: text to be displayed. If None, the email itself is used :return: a well-formatted html anchor """ if no...
Returns a well-formed link to an email address. If email is None/empty, returns an empty string :param email: email address :param link_text: text to be displayed. If None, the email itself is used :return: a well-formatted html anchor
Below is the the instruction that describes the task: ### Input: Returns a well-formed link to an email address. If email is None/empty, returns an empty string :param email: email address :param link_text: text to be displayed. If None, the email itself is used :return: a well-formatted html anchor...
def _remove_trustee(self, device): '''Remove a trustee from the trust domain. :param device: MangementRoot object -- device to remove ''' trustee_name = get_device_info(device).name name_object_map = get_device_names_to_objects(self.devices) delete_func = self._get_dele...
Remove a trustee from the trust domain. :param device: MangementRoot object -- device to remove
Below is the the instruction that describes the task: ### Input: Remove a trustee from the trust domain. :param device: MangementRoot object -- device to remove ### Response: def _remove_trustee(self, device): '''Remove a trustee from the trust domain. :param device: MangementRoot object ...
def _match_state(self, state): """Checks whether a given State matches self.names.""" return (self.names == '*' or state in self.names or state.name in self.names)
Checks whether a given State matches self.names.
Below is the the instruction that describes the task: ### Input: Checks whether a given State matches self.names. ### Response: def _match_state(self, state): """Checks whether a given State matches self.names.""" return (self.names == '*' or state in self.names or s...
def ReadStoredProcedure(self, sproc_link, options=None): """Reads a stored procedure. :param str sproc_link: The link to the stored procedure. :param dict options: The request options for the request. :return: The read Stored Procedure. :rtyp...
Reads a stored procedure. :param str sproc_link: The link to the stored procedure. :param dict options: The request options for the request. :return: The read Stored Procedure. :rtype: dict
Below is the the instruction that describes the task: ### Input: Reads a stored procedure. :param str sproc_link: The link to the stored procedure. :param dict options: The request options for the request. :return: The read Stored Procedure. :rty...
def _lookup_field(self, path): """ Searches for a field as defined by path. This method is used by the ``dependency`` evaluation logic. :param path: Path elements are separated by a ``.``. A leading ``^`` indicates that the path relates to the document root, ...
Searches for a field as defined by path. This method is used by the ``dependency`` evaluation logic. :param path: Path elements are separated by a ``.``. A leading ``^`` indicates that the path relates to the document root, otherwise it relates to the curre...
Below is the the instruction that describes the task: ### Input: Searches for a field as defined by path. This method is used by the ``dependency`` evaluation logic. :param path: Path elements are separated by a ``.``. A leading ``^`` indicates that the path relates to the ...
def evaluate(self, verbose=False, decode=True, passes=None, num_threads=1, apply_experimental_transforms=True): """Evaluate the stored expression. Parameters ---------- verbose : bool, optional Whether to print output for each Weld compilation step. ...
Evaluate the stored expression. Parameters ---------- verbose : bool, optional Whether to print output for each Weld compilation step. decode : bool, optional Whether to decode the result passes : list, optional Which Weld optimization passes ...
Below is the the instruction that describes the task: ### Input: Evaluate the stored expression. Parameters ---------- verbose : bool, optional Whether to print output for each Weld compilation step. decode : bool, optional Whether to decode the result ...
def cos_distance(t1, t2, epsilon=1e-12, name=None): """Cos distance between t1 and t2 and caps the gradient of the Square Root. Args: t1: A tensor t2: A tensor that can be multiplied by t1. epsilon: A lower bound value for the distance. The square root is used as the normalizer. name: Optiona...
Cos distance between t1 and t2 and caps the gradient of the Square Root. Args: t1: A tensor t2: A tensor that can be multiplied by t1. epsilon: A lower bound value for the distance. The square root is used as the normalizer. name: Optional name for this op. Returns: The cos distance betwe...
Below is the the instruction that describes the task: ### Input: Cos distance between t1 and t2 and caps the gradient of the Square Root. Args: t1: A tensor t2: A tensor that can be multiplied by t1. epsilon: A lower bound value for the distance. The square root is used as the normalizer. n...
def run_analysis( named_analysis, prepared_analyses=None,log_dir=default_log_dir): """ Runs just the named analysis. Otherwise just like run_analyses """ if prepared_analyses == None: prepared_analyses = prepare_analyses() state_collection = funtool.state_collection.StateCollection([],{}) ...
Runs just the named analysis. Otherwise just like run_analyses
Below is the the instruction that describes the task: ### Input: Runs just the named analysis. Otherwise just like run_analyses ### Response: def run_analysis( named_analysis, prepared_analyses=None,log_dir=default_log_dir): """ Runs just the named analysis. Otherwise just like run_analyses """ if ...
def write(self, cull=False): """ Serialize self.g and write to self.filename, set cull to true to remove unwanted prefixes """ if cull: cull_prefixes(self).write() else: ser = self.g.serialize(format='nifttl') with open(self.filename, 'wb') as f: ...
Serialize self.g and write to self.filename, set cull to true to remove unwanted prefixes
Below is the the instruction that describes the task: ### Input: Serialize self.g and write to self.filename, set cull to true to remove unwanted prefixes ### Response: def write(self, cull=False): """ Serialize self.g and write to self.filename, set cull to true to remove unwanted prefixes """ if ...
def to_hdf5(self, f): """ Serialize this object to an HDF5 file. Requires ``h5py``. Parameters ---------- f : str, :class:`h5py.File` Either the filename or an open HDF5 file. """ if isinstance(f, str): import h5py f ...
Serialize this object to an HDF5 file. Requires ``h5py``. Parameters ---------- f : str, :class:`h5py.File` Either the filename or an open HDF5 file.
Below is the the instruction that describes the task: ### Input: Serialize this object to an HDF5 file. Requires ``h5py``. Parameters ---------- f : str, :class:`h5py.File` Either the filename or an open HDF5 file. ### Response: def to_hdf5(self, f): """ ...
def setup_a_alpha_and_derivatives(self, i, T=None): r'''Sets `a`, `kappa0`, `kappa1`, and `Tc` for a specific component before the pure-species EOS's `a_alpha_and_derivatives` method is called. Both are called by `GCEOSMIX.a_alpha_and_derivatives` for every component.''' if not hasattr...
r'''Sets `a`, `kappa0`, `kappa1`, and `Tc` for a specific component before the pure-species EOS's `a_alpha_and_derivatives` method is called. Both are called by `GCEOSMIX.a_alpha_and_derivatives` for every component.
Below is the the instruction that describes the task: ### Input: r'''Sets `a`, `kappa0`, `kappa1`, and `Tc` for a specific component before the pure-species EOS's `a_alpha_and_derivatives` method is called. Both are called by `GCEOSMIX.a_alpha_and_derivatives` for every component. ### Response: d...
def add_virtual_loss(self, up_to): """Propagate a virtual loss up to the root node. Args: up_to: The node to propagate until. (Keep track of this! You'll need it to reverse the virtual loss later.) """ self.losses_applied += 1 # This is a "win" for th...
Propagate a virtual loss up to the root node. Args: up_to: The node to propagate until. (Keep track of this! You'll need it to reverse the virtual loss later.)
Below is the the instruction that describes the task: ### Input: Propagate a virtual loss up to the root node. Args: up_to: The node to propagate until. (Keep track of this! You'll need it to reverse the virtual loss later.) ### Response: def add_virtual_loss(self, up_to): ...
def _find_xinput(self): """Find most recent xinput library.""" for dll in XINPUT_DLL_NAMES: try: self.xinput = getattr(ctypes.windll, dll) except OSError: pass else: # We found an xinput driver self.xinpu...
Find most recent xinput library.
Below is the the instruction that describes the task: ### Input: Find most recent xinput library. ### Response: def _find_xinput(self): """Find most recent xinput library.""" for dll in XINPUT_DLL_NAMES: try: self.xinput = getattr(ctypes.windll, dll) except O...
def friedman(dv=None, within=None, subject=None, data=None, export_filename=None): """Friedman test for repeated measurements. Parameters ---------- dv : string Name of column containing the dependant variable. within : string Name of column containing the within-subjec...
Friedman test for repeated measurements. Parameters ---------- dv : string Name of column containing the dependant variable. within : string Name of column containing the within-subject factor. subject : string Name of column containing the subject identifier. data : pan...
Below is the the instruction that describes the task: ### Input: Friedman test for repeated measurements. Parameters ---------- dv : string Name of column containing the dependant variable. within : string Name of column containing the within-subject factor. subject : string ...
def run(self, rs, overwrite=True, skip_existing=False, path=None, chunksize=None): """Compute timestamps for current populations.""" if path is None: path = str(self.S.store.filepath.parent) kwargs = dict(rs=rs, overwrite=overwrite, path=path, timesl...
Compute timestamps for current populations.
Below is the the instruction that describes the task: ### Input: Compute timestamps for current populations. ### Response: def run(self, rs, overwrite=True, skip_existing=False, path=None, chunksize=None): """Compute timestamps for current populations.""" if path is None: pa...
def get_all_dbsecurity_groups(self, groupname=None, max_records=None, marker=None): """ Get all security groups associated with your account in a region. :type groupnames: list :param groupnames: A list of the names of security groups to retrieve. ...
Get all security groups associated with your account in a region. :type groupnames: list :param groupnames: A list of the names of security groups to retrieve. If not provided, all security groups will be returned. :type max_records: int ...
Below is the the instruction that describes the task: ### Input: Get all security groups associated with your account in a region. :type groupnames: list :param groupnames: A list of the names of security groups to retrieve. If not provided, all security groups will ...
def _all(confs=None, **kwargs): """ True iif all input confs are True. :param confs: confs to check. :type confs: list or dict or str :param kwargs: additional task kwargs. :return: True if all conditions are checked. False otherwise. :rtype: bool """ result = False if confs ...
True iif all input confs are True. :param confs: confs to check. :type confs: list or dict or str :param kwargs: additional task kwargs. :return: True if all conditions are checked. False otherwise. :rtype: bool
Below is the the instruction that describes the task: ### Input: True iif all input confs are True. :param confs: confs to check. :type confs: list or dict or str :param kwargs: additional task kwargs. :return: True if all conditions are checked. False otherwise. :rtype: bool ### Response: de...
def _synthesize_multiple_c_extension(self, text_file, output_file_path, quit_after=None, backwards=False): """ Synthesize multiple text fragments, using the cew extension. Return a tuple (anchors, total_time, num_chars). :rtype: (bool, (list, :class:`~aeneas.exacttiming.TimeValue`, int...
Synthesize multiple text fragments, using the cew extension. Return a tuple (anchors, total_time, num_chars). :rtype: (bool, (list, :class:`~aeneas.exacttiming.TimeValue`, int))
Below is the the instruction that describes the task: ### Input: Synthesize multiple text fragments, using the cew extension. Return a tuple (anchors, total_time, num_chars). :rtype: (bool, (list, :class:`~aeneas.exacttiming.TimeValue`, int)) ### Response: def _synthesize_multiple_c_extension(sel...
def copy(self, source, dest): """Implementation of :meth:`~simplekv.CopyMixin.copy`. Copies the data in the backing store and removes the destination key from the cache, in case it was already populated. Does not work when the backing store does not implement copy. ""...
Implementation of :meth:`~simplekv.CopyMixin.copy`. Copies the data in the backing store and removes the destination key from the cache, in case it was already populated. Does not work when the backing store does not implement copy.
Below is the the instruction that describes the task: ### Input: Implementation of :meth:`~simplekv.CopyMixin.copy`. Copies the data in the backing store and removes the destination key from the cache, in case it was already populated. Does not work when the backing store does not...
def spread_money(money: Money, spread_p: Decimal) -> Tuple[Money, Money]: """Returns a lower and upper money amount separated by a spread percentage""" upper, lower = spread_value(money.amount, spread_p) return Money(upper, money.currency), Money(lower, money.currency)
Returns a lower and upper money amount separated by a spread percentage
Below is the the instruction that describes the task: ### Input: Returns a lower and upper money amount separated by a spread percentage ### Response: def spread_money(money: Money, spread_p: Decimal) -> Tuple[Money, Money]: """Returns a lower and upper money amount separated by a spread percentage""" uppe...
def setCurrentSchemaPath(self, path): """ Sets the current item based on the inputed column. :param path | <str> """ if not path: return False parts = path.split('.') name = parts[0] next = parts[1:] ...
Sets the current item based on the inputed column. :param path | <str>
Below is the the instruction that describes the task: ### Input: Sets the current item based on the inputed column. :param path | <str> ### Response: def setCurrentSchemaPath(self, path): """ Sets the current item based on the inputed column. :param ...
def get_servers(self, topic): """We're assuming that the static list of servers can serve the given topic, since we have to preexisting knowledge about them. """ return (nsq.node.ServerNode(sh) for sh in self.__server_hosts)
We're assuming that the static list of servers can serve the given topic, since we have to preexisting knowledge about them.
Below is the the instruction that describes the task: ### Input: We're assuming that the static list of servers can serve the given topic, since we have to preexisting knowledge about them. ### Response: def get_servers(self, topic): """We're assuming that the static list of servers can serve the ...
def from_filename(cls, filename): """ Class constructor using the path to the corresponding mp3 file. The metadata will be read from this file to create the song object, so it must at least contain valid ID3 tags for artist and title. """ if not filename: logg...
Class constructor using the path to the corresponding mp3 file. The metadata will be read from this file to create the song object, so it must at least contain valid ID3 tags for artist and title.
Below is the the instruction that describes the task: ### Input: Class constructor using the path to the corresponding mp3 file. The metadata will be read from this file to create the song object, so it must at least contain valid ID3 tags for artist and title. ### Response: def from_filename(cls, ...
def get_installation_order(self, req_set): # type: (RequirementSet) -> List[InstallRequirement] """Create the installation order. The installation order is topological - requirements are installed before the requiring thing. We break cycles at an arbitrary point, and make no oth...
Create the installation order. The installation order is topological - requirements are installed before the requiring thing. We break cycles at an arbitrary point, and make no other guarantees.
Below is the the instruction that describes the task: ### Input: Create the installation order. The installation order is topological - requirements are installed before the requiring thing. We break cycles at an arbitrary point, and make no other guarantees. ### Response: def get_installa...
def balance_get(self, nick): '''xxxxx.xxxxx.account.balance.get =================================== 取得当前登录用户的授权账户列表''' request = TOPRequest('xxxxx.xxxxx.account.balance.get') request['nick'] = nick self.create(self.execute(request)) return self.result
xxxxx.xxxxx.account.balance.get =================================== 取得当前登录用户的授权账户列表
Below is the the instruction that describes the task: ### Input: xxxxx.xxxxx.account.balance.get =================================== 取得当前登录用户的授权账户列表 ### Response: def balance_get(self, nick): '''xxxxx.xxxxx.account.balance.get =================================== 取得当前登录用户的授权账...
def image_url(self, width=None, height=None): """ Returns URL to placeholder image Example: http://placehold.it/640x480 """ width_ = width or self.random_int(max=1024) height_ = height or self.random_int(max=1024) placeholder_url = self.random_element(self.image_p...
Returns URL to placeholder image Example: http://placehold.it/640x480
Below is the the instruction that describes the task: ### Input: Returns URL to placeholder image Example: http://placehold.it/640x480 ### Response: def image_url(self, width=None, height=None): """ Returns URL to placeholder image Example: http://placehold.it/640x480 """ ...
def delete_folder(self, folder): '''Delete a folder. It will recursively delete all the content. Args: folder_id (str): The UUID of the folder to be deleted. Returns: None Raises: StorageArgumentException: Invalid arguments StorageForbid...
Delete a folder. It will recursively delete all the content. Args: folder_id (str): The UUID of the folder to be deleted. Returns: None Raises: StorageArgumentException: Invalid arguments StorageForbiddenException: 403 StorageNotFoun...
Below is the the instruction that describes the task: ### Input: Delete a folder. It will recursively delete all the content. Args: folder_id (str): The UUID of the folder to be deleted. Returns: None Raises: StorageArgumentException: Invalid arguments ...
def sort_meta_elements(blob): """For v0.0 (which has meta values in a list), this function recursively walks through the object and sorts each meta by @property or @rel values. """ v = detect_nexson_version(blob) if _is_badgerfish_version(v): _recursive_sort_meta(blob, '') return blo...
For v0.0 (which has meta values in a list), this function recursively walks through the object and sorts each meta by @property or @rel values.
Below is the the instruction that describes the task: ### Input: For v0.0 (which has meta values in a list), this function recursively walks through the object and sorts each meta by @property or @rel values. ### Response: def sort_meta_elements(blob): """For v0.0 (which has meta values in a list), thi...
def var(self, ddof=1, *args, **kwargs): """ Compute variance of groups, excluding missing values. Parameters ---------- ddof : integer, default 1 degrees of freedom """ nv.validate_resampler_func('var', args, kwargs) return self._downsample('v...
Compute variance of groups, excluding missing values. Parameters ---------- ddof : integer, default 1 degrees of freedom
Below is the the instruction that describes the task: ### Input: Compute variance of groups, excluding missing values. Parameters ---------- ddof : integer, default 1 degrees of freedom ### Response: def var(self, ddof=1, *args, **kwargs): """ Compute variance o...
def get_string_module(project, code, resource=None, force_errors=False): """Returns a `PyObject` object for the given code If `force_errors` is `True`, `exceptions.ModuleSyntaxError` is raised if module has syntax errors. This overrides ``ignore_syntax_errors`` project config. """ return pyob...
Returns a `PyObject` object for the given code If `force_errors` is `True`, `exceptions.ModuleSyntaxError` is raised if module has syntax errors. This overrides ``ignore_syntax_errors`` project config.
Below is the the instruction that describes the task: ### Input: Returns a `PyObject` object for the given code If `force_errors` is `True`, `exceptions.ModuleSyntaxError` is raised if module has syntax errors. This overrides ``ignore_syntax_errors`` project config. ### Response: def get_string_modul...
def format_number(x): """Format number to string Function converts a number to string. For numbers of class :class:`float`, up to 17 digits will be used to print the entire floating point number. Any padding zeros will be removed at the end of the number. See :ref:`user-guide:int` and :ref:`user-guide...
Format number to string Function converts a number to string. For numbers of class :class:`float`, up to 17 digits will be used to print the entire floating point number. Any padding zeros will be removed at the end of the number. See :ref:`user-guide:int` and :ref:`user-guide:double` for more information...
Below is the the instruction that describes the task: ### Input: Format number to string Function converts a number to string. For numbers of class :class:`float`, up to 17 digits will be used to print the entire floating point number. Any padding zeros will be removed at the end of the number. See :r...
def _require_host_parameter(args, to): """ Make sure, that user specified --host argument. """ if not args.host: sys.stderr.write("--host is required parameter to --%s\n" % to) sys.exit(1)
Make sure, that user specified --host argument.
Below is the the instruction that describes the task: ### Input: Make sure, that user specified --host argument. ### Response: def _require_host_parameter(args, to): """ Make sure, that user specified --host argument. """ if not args.host: sys.stderr.write("--host is required parameter to -...
def _sorted_keys(self): """ Return list of keys sorted by version Sorting is done based on :py:func:`pkg_resources.parse_version` """ try: keys = self._cache['sorted_keys'] except KeyError: keys = self._cache['sorted_keys'] = sorted(self.keys(), ...
Return list of keys sorted by version Sorting is done based on :py:func:`pkg_resources.parse_version`
Below is the the instruction that describes the task: ### Input: Return list of keys sorted by version Sorting is done based on :py:func:`pkg_resources.parse_version` ### Response: def _sorted_keys(self): """ Return list of keys sorted by version Sorting is done based on :py:func:...
def Cpl(self): r'''Liquid-phase heat capacity of the mixture at its current temperature and composition, in units of [J/kg/K]. For calculation of this property at other temperatures or compositions, or specifying manually the method used to calculate it, and more - see the object ...
r'''Liquid-phase heat capacity of the mixture at its current temperature and composition, in units of [J/kg/K]. For calculation of this property at other temperatures or compositions, or specifying manually the method used to calculate it, and more - see the object oriented interface :ob...
Below is the the instruction that describes the task: ### Input: r'''Liquid-phase heat capacity of the mixture at its current temperature and composition, in units of [J/kg/K]. For calculation of this property at other temperatures or compositions, or specifying manually the method used to c...
def create_external_feed_courses(self, url, course_id, header_match=None, verbosity=None): """ Create an external feed. Create a new external feed for the course or group. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id ...
Create an external feed. Create a new external feed for the course or group.
Below is the the instruction that describes the task: ### Input: Create an external feed. Create a new external feed for the course or group. ### Response: def create_external_feed_courses(self, url, course_id, header_match=None, verbosity=None): """ Create an external feed. ...
def create_cursor(self, name=None): """ Returns an active connection cursor to the database. """ return Cursor(self.client_connection, self.connection, self.djongo_connection)
Returns an active connection cursor to the database.
Below is the the instruction that describes the task: ### Input: Returns an active connection cursor to the database. ### Response: def create_cursor(self, name=None): """ Returns an active connection cursor to the database. """ return Cursor(self.client_connection, self.connection,...
def decrypt(self, ciphertext, nonce=None, encoder=encoding.RawEncoder): """ Decrypts the ciphertext using the `nonce` (explicitly, when passed as a parameter or implicitly, when omitted, as part of the ciphertext) and returns the plaintext message. :param ciphertext: [:class:`by...
Decrypts the ciphertext using the `nonce` (explicitly, when passed as a parameter or implicitly, when omitted, as part of the ciphertext) and returns the plaintext message. :param ciphertext: [:class:`bytes`] The encrypted message to decrypt :param nonce: [:class:`bytes`] The nonce used...
Below is the the instruction that describes the task: ### Input: Decrypts the ciphertext using the `nonce` (explicitly, when passed as a parameter or implicitly, when omitted, as part of the ciphertext) and returns the plaintext message. :param ciphertext: [:class:`bytes`] The encrypted mes...
def read_file(self, mesh_spacing=1.0): ''' Reads the file and returns an instance of the FaultSource class. :param float mesh_spacing: Fault mesh spacing (km) ''' # Process the tectonic regionalisation tectonic_reg = self.process_tectonic_regionalisation() ...
Reads the file and returns an instance of the FaultSource class. :param float mesh_spacing: Fault mesh spacing (km)
Below is the the instruction that describes the task: ### Input: Reads the file and returns an instance of the FaultSource class. :param float mesh_spacing: Fault mesh spacing (km) ### Response: def read_file(self, mesh_spacing=1.0): ''' Reads the file and returns an instance o...
def upload(identifier, files, metadata=None, headers=None, access_key=None, secret_key=None, queue_derive=None, verbose=None, verify=None, checksum=None, delete=None, retries=None, retries_sleep=None...
Upload files to an item. The item will be created if it does not exist. :type identifier: str :param identifier: The globally unique Archive.org identifier for a given item. :param files: The filepaths or file-like objects to upload. This value can be an iterable or a single file-like ob...
Below is the the instruction that describes the task: ### Input: Upload files to an item. The item will be created if it does not exist. :type identifier: str :param identifier: The globally unique Archive.org identifier for a given item. :param files: The filepaths or file-like objects to upload. Thi...
def abilities(api_key=None, add_headers=None): """Fetch a list of permission-like strings for this account.""" client = ClientMixin(api_key=api_key) result = client.request('GET', endpoint='abilities', add_headers=add_headers,) return result['abilities']
Fetch a list of permission-like strings for this account.
Below is the the instruction that describes the task: ### Input: Fetch a list of permission-like strings for this account. ### Response: def abilities(api_key=None, add_headers=None): """Fetch a list of permission-like strings for this account.""" client = ClientMixin(api_key=api_key) result = client.r...
def dtype(self, value): """Gets the datatype for the given `value` (description). Args: value (str): A text description for any datatype. Returns: numpy.dtype: The matching datatype for the given text. None: If no match can be found, `None` will be returned....
Gets the datatype for the given `value` (description). Args: value (str): A text description for any datatype. Returns: numpy.dtype: The matching datatype for the given text. None: If no match can be found, `None` will be returned.
Below is the the instruction that describes the task: ### Input: Gets the datatype for the given `value` (description). Args: value (str): A text description for any datatype. Returns: numpy.dtype: The matching datatype for the given text. None: If no match can ...
def get_versions(reporev=True): """Get version information for components used by Spyder""" import sys import platform import qtpy import qtpy.QtCore revision = None if reporev: from spyder.utils import vcs revision, branch = vcs.get_git_revision(os.path.dirname(__dir__)) ...
Get version information for components used by Spyder
Below is the the instruction that describes the task: ### Input: Get version information for components used by Spyder ### Response: def get_versions(reporev=True): """Get version information for components used by Spyder""" import sys import platform import qtpy import qtpy.QtCore revisi...
def Clean(self): """Clean the build environment.""" # os.unlink doesn't work effectively, use the shell to delete. if os.path.exists(args.build_dir): subprocess.call("rd /s /q %s" % args.build_dir, shell=True) if os.path.exists(args.output_dir): subprocess.call("rd /s /q %s" % args.output_di...
Clean the build environment.
Below is the the instruction that describes the task: ### Input: Clean the build environment. ### Response: def Clean(self): """Clean the build environment.""" # os.unlink doesn't work effectively, use the shell to delete. if os.path.exists(args.build_dir): subprocess.call("rd /s /q %s" % args.bu...
def start_worker(self): """Trigger new process as a RQ worker.""" if not self.include_rq: return None worker = Worker(queues=self.queues, connection=self.connection) worker_pid_path = current_app.config.get( "{}_WORKER_PID".format(self.con...
Trigger new process as a RQ worker.
Below is the the instruction that describes the task: ### Input: Trigger new process as a RQ worker. ### Response: def start_worker(self): """Trigger new process as a RQ worker.""" if not self.include_rq: return None worker = Worker(queues=self.queues, c...
def main(): """The main function of the module. These are the steps: 1. Reads the population file (:py:func:`readPopulations`). 2. Extracts the MDS values (:py:func:`extractData`). 3. Plots the MDS values (:py:func:`plotMDS`). """ # Getting and checking the options args = parseArgs() ...
The main function of the module. These are the steps: 1. Reads the population file (:py:func:`readPopulations`). 2. Extracts the MDS values (:py:func:`extractData`). 3. Plots the MDS values (:py:func:`plotMDS`).
Below is the the instruction that describes the task: ### Input: The main function of the module. These are the steps: 1. Reads the population file (:py:func:`readPopulations`). 2. Extracts the MDS values (:py:func:`extractData`). 3. Plots the MDS values (:py:func:`plotMDS`). ### Response: def ma...
def _convert_eta_to_c(eta, ref_position): """ Parameters ---------- eta : 1D or 2D ndarray. The elements of the array should be this model's 'transformed' shape parameters, i.e. the natural log of (the corresponding shape parameter divided by the reference shape parameter). This ...
Parameters ---------- eta : 1D or 2D ndarray. The elements of the array should be this model's 'transformed' shape parameters, i.e. the natural log of (the corresponding shape parameter divided by the reference shape parameter). This array's elements will be real valued. If `eta`...
Below is the the instruction that describes the task: ### Input: Parameters ---------- eta : 1D or 2D ndarray. The elements of the array should be this model's 'transformed' shape parameters, i.e. the natural log of (the corresponding shape parameter divided by the reference shape pa...
def update_property(tree_to_update, xpath_root, xpaths, prop, values, supported=None): """ Either update the tree the default way, or call the custom updater Default Way: Existing values in the tree are overwritten. If xpaths contains a single path, then each value is written to the tree at that path. ...
Either update the tree the default way, or call the custom updater Default Way: Existing values in the tree are overwritten. If xpaths contains a single path, then each value is written to the tree at that path. If xpaths contains a list of xpaths, then the values corresponding to each xpath index are writ...
Below is the the instruction that describes the task: ### Input: Either update the tree the default way, or call the custom updater Default Way: Existing values in the tree are overwritten. If xpaths contains a single path, then each value is written to the tree at that path. If xpaths contains a list of x...
def archive_done( self): """*move done tasks from the document's 'Archive' project into an adjacent markdown tasklog file* **Usage:** To move the archived tasks within a workspace's taskpaper docs into ``-tasklog.md`` files use the ``archive_done()`` method: .. cod...
*move done tasks from the document's 'Archive' project into an adjacent markdown tasklog file* **Usage:** To move the archived tasks within a workspace's taskpaper docs into ``-tasklog.md`` files use the ``archive_done()`` method: .. code-block:: python ws.archive_do...
Below is the the instruction that describes the task: ### Input: *move done tasks from the document's 'Archive' project into an adjacent markdown tasklog file* **Usage:** To move the archived tasks within a workspace's taskpaper docs into ``-tasklog.md`` files use the ``archive_done()`` method...
def status_bar(python_input): """ Create the `Layout` for the status bar. """ TB = 'class:status-toolbar' @if_mousedown def toggle_paste_mode(mouse_event): python_input.paste_mode = not python_input.paste_mode @if_mousedown def enter_history(mouse_event): python_input.e...
Create the `Layout` for the status bar.
Below is the the instruction that describes the task: ### Input: Create the `Layout` for the status bar. ### Response: def status_bar(python_input): """ Create the `Layout` for the status bar. """ TB = 'class:status-toolbar' @if_mousedown def toggle_paste_mode(mouse_event): python_...
def _get_model_parameters_estimations(self, error_model): """ Infer model estimation method from the 'error_model'. Return an object of type ModelParametersEstimation. """ if error_model.dependance == NIDM_INDEPEDENT_ERROR: if error_model.variance_homo: ...
Infer model estimation method from the 'error_model'. Return an object of type ModelParametersEstimation.
Below is the the instruction that describes the task: ### Input: Infer model estimation method from the 'error_model'. Return an object of type ModelParametersEstimation. ### Response: def _get_model_parameters_estimations(self, error_model): """ Infer model estimation method from the 'erro...
def evaluate(): """Evaluate the model on validation dataset. """ log.info('Loader dev data...') if version_2: dev_data = SQuAD('dev', version='2.0') else: dev_data = SQuAD('dev', version='1.1') log.info('Number of records in Train data:{}'.format(len(dev_data))) dev_dataset ...
Evaluate the model on validation dataset.
Below is the the instruction that describes the task: ### Input: Evaluate the model on validation dataset. ### Response: def evaluate(): """Evaluate the model on validation dataset. """ log.info('Loader dev data...') if version_2: dev_data = SQuAD('dev', version='2.0') else: dev...
def handle_error(self, error=None): """Trap for TCPServer errors, otherwise continue.""" if _debug: TCPServer._debug("handle_error %r", error) # core does not take parameters asyncore.dispatcher.handle_error(self)
Trap for TCPServer errors, otherwise continue.
Below is the the instruction that describes the task: ### Input: Trap for TCPServer errors, otherwise continue. ### Response: def handle_error(self, error=None): """Trap for TCPServer errors, otherwise continue.""" if _debug: TCPServer._debug("handle_error %r", error) # core does not take ...
def decodeIlxResp(resp): """ We need this until we can get json back directly and this is SUPER nasty""" lines = [_ for _ in resp.text.split('\n') if _] # strip empties if 'successfull' in lines[0]: return [(_.split('"')[1], ilxIdFix(_.split(': ')[-1])) for _ in li...
We need this until we can get json back directly and this is SUPER nasty
Below is the the instruction that describes the task: ### Input: We need this until we can get json back directly and this is SUPER nasty ### Response: def decodeIlxResp(resp): """ We need this until we can get json back directly and this is SUPER nasty""" lines = [_ for _ in resp.text.split('\n') if _] #...
def get_changelog_file_for_database(database=DEFAULT_DB_ALIAS): """get changelog filename for given `database` DB alias""" from django.conf import settings try: return settings.LIQUIMIGRATE_CHANGELOG_FILES[database] except AttributeError: if database == DEFAULT_DB_ALIAS: tr...
get changelog filename for given `database` DB alias
Below is the the instruction that describes the task: ### Input: get changelog filename for given `database` DB alias ### Response: def get_changelog_file_for_database(database=DEFAULT_DB_ALIAS): """get changelog filename for given `database` DB alias""" from django.conf import settings try: ...
def discover(self, topic): '''Run the discovery mechanism''' logger.info('Discovering on topic %s', topic) producers = [] for lookupd in self._lookupd: logger.info('Discovering on %s', lookupd) try: # Find all the current producers on this instance...
Run the discovery mechanism
Below is the the instruction that describes the task: ### Input: Run the discovery mechanism ### Response: def discover(self, topic): '''Run the discovery mechanism''' logger.info('Discovering on topic %s', topic) producers = [] for lookupd in self._lookupd: logger.info(...
def PhyDMSLogoPlotParser(): """Returns `argparse.ArgumentParser` for ``phydms_logoplot``.""" parser = ArgumentParserNoArgHelp(description= "Make logo plot of preferences or differential preferences. " "Uses weblogo (http://weblogo.threeplusone.com/). " "{0} Version {1}. Full ...
Returns `argparse.ArgumentParser` for ``phydms_logoplot``.
Below is the the instruction that describes the task: ### Input: Returns `argparse.ArgumentParser` for ``phydms_logoplot``. ### Response: def PhyDMSLogoPlotParser(): """Returns `argparse.ArgumentParser` for ``phydms_logoplot``.""" parser = ArgumentParserNoArgHelp(description= "Make logo plot of...
def oversample1d(sp, crval1, cdelt1, oversampling=1, debugplot=0): """Oversample spectrum. Parameters ---------- sp : numpy array Spectrum to be oversampled. crval1 : float Abscissae of the center of the first pixel in the original spectrum 'sp'. cdelt1 : float A...
Oversample spectrum. Parameters ---------- sp : numpy array Spectrum to be oversampled. crval1 : float Abscissae of the center of the first pixel in the original spectrum 'sp'. cdelt1 : float Abscissae increment corresponding to 1 pixel in the original spectr...
Below is the the instruction that describes the task: ### Input: Oversample spectrum. Parameters ---------- sp : numpy array Spectrum to be oversampled. crval1 : float Abscissae of the center of the first pixel in the original spectrum 'sp'. cdelt1 : float Abscis...
def get_max_size(pool, num_option, item_length): """ Calculate the max number of item that an option can stored in the pool at give time. This is to limit the pool size to POOL_SIZE Args: option_index (int): the index of the option to calculate the size for pool (dict): answer pool ...
Calculate the max number of item that an option can stored in the pool at give time. This is to limit the pool size to POOL_SIZE Args: option_index (int): the index of the option to calculate the size for pool (dict): answer pool num_option (int): total number of options available for ...
Below is the the instruction that describes the task: ### Input: Calculate the max number of item that an option can stored in the pool at give time. This is to limit the pool size to POOL_SIZE Args: option_index (int): the index of the option to calculate the size for pool (dict): answer ...
def update_device(name, **kwargs): ''' .. versionadded:: 2019.2.0 Add attributes to an existing device, identified by name. name The name of the device, e.g., ``edge_router`` kwargs Arguments to change in device, e.g., ``serial=JN2932930`` CLI Example: .. code-block:: bash...
.. versionadded:: 2019.2.0 Add attributes to an existing device, identified by name. name The name of the device, e.g., ``edge_router`` kwargs Arguments to change in device, e.g., ``serial=JN2932930`` CLI Example: .. code-block:: bash salt myminion netbox.update_device ed...
Below is the the instruction that describes the task: ### Input: .. versionadded:: 2019.2.0 Add attributes to an existing device, identified by name. name The name of the device, e.g., ``edge_router`` kwargs Arguments to change in device, e.g., ``serial=JN2932930`` CLI Example: ...
def query(self, url, method="GET", params=dict(), headers=dict()): """ Request a API endpoint at ``url`` with ``params`` being either the POST or GET data. """ access_token = self._get_at_from_session() oauth = OAuth1( self.consumer_key, client_sec...
Request a API endpoint at ``url`` with ``params`` being either the POST or GET data.
Below is the the instruction that describes the task: ### Input: Request a API endpoint at ``url`` with ``params`` being either the POST or GET data. ### Response: def query(self, url, method="GET", params=dict(), headers=dict()): """ Request a API endpoint at ``url`` with ``params`` being ...
def add_constraints(self): """ Set the base constraints of the relation query """ if self._constraints: super(MorphOneOrMany, self).add_constraints() self._query.where(self._morph_type, self._morph_name)
Set the base constraints of the relation query
Below is the the instruction that describes the task: ### Input: Set the base constraints of the relation query ### Response: def add_constraints(self): """ Set the base constraints of the relation query """ if self._constraints: super(MorphOneOrMany, self).add_constrain...
def templates_in(path): """Enumerate the templates found in path""" ext = '.cpp' return ( Template(f[0:-len(ext)], load_file(os.path.join(path, f))) for f in os.listdir(path) if f.endswith(ext) )
Enumerate the templates found in path
Below is the the instruction that describes the task: ### Input: Enumerate the templates found in path ### Response: def templates_in(path): """Enumerate the templates found in path""" ext = '.cpp' return ( Template(f[0:-len(ext)], load_file(os.path.join(path, f))) for f in os.listdir(p...
def dont_cache(): """ Set Cache-Control headers for no caching Will generate proxy-revalidate, no-cache, no-store, must-revalidate, max-age=0. """ def decorate_func(func): @wraps(func) def decorate_func_call(*a, **kw): callback = SetCacheControlHeadersForNoCachingCal...
Set Cache-Control headers for no caching Will generate proxy-revalidate, no-cache, no-store, must-revalidate, max-age=0.
Below is the the instruction that describes the task: ### Input: Set Cache-Control headers for no caching Will generate proxy-revalidate, no-cache, no-store, must-revalidate, max-age=0. ### Response: def dont_cache(): """ Set Cache-Control headers for no caching Will generate proxy-revalidate...
def get_brace_style_log_with_null_handler(name: str) -> BraceStyleAdapter: """ For use by library functions. Returns a log with the specifed name that has a null handler attached, and a :class:`BraceStyleAdapter`. """ log = logging.getLogger(name) log.addHandler(logging.NullHandler()) return...
For use by library functions. Returns a log with the specifed name that has a null handler attached, and a :class:`BraceStyleAdapter`.
Below is the the instruction that describes the task: ### Input: For use by library functions. Returns a log with the specifed name that has a null handler attached, and a :class:`BraceStyleAdapter`. ### Response: def get_brace_style_log_with_null_handler(name: str) -> BraceStyleAdapter: """ For use by...
def direct_view(self, targets='all'): """construct a DirectView object. If no targets are specified, create a DirectView using all engines. rc.direct_view('all') is distinguished from rc[:] in that 'all' will evaluate the target engines at each execution, whereas rc[:] will con...
construct a DirectView object. If no targets are specified, create a DirectView using all engines. rc.direct_view('all') is distinguished from rc[:] in that 'all' will evaluate the target engines at each execution, whereas rc[:] will connect to all *current* engines, and that l...
Below is the the instruction that describes the task: ### Input: construct a DirectView object. If no targets are specified, create a DirectView using all engines. rc.direct_view('all') is distinguished from rc[:] in that 'all' will evaluate the target engines at each execution, wh...
def _key_deploy_run(self, host, target, re_run=True): ''' The ssh-copy-id routine ''' argv = [ 'ssh.set_auth_key', target.get('user', 'root'), self.get_pubkey(), ] single = Single( self.opts, argv, ...
The ssh-copy-id routine
Below is the the instruction that describes the task: ### Input: The ssh-copy-id routine ### Response: def _key_deploy_run(self, host, target, re_run=True): ''' The ssh-copy-id routine ''' argv = [ 'ssh.set_auth_key', target.get('user', 'root'), s...
def process_IN_CREATE(self, raw_event): """ If the event affects a directory and the auto_add flag of the targetted watch is set to True, a new watch is added on this new directory, with the same attribute values than those of this watch. """ if raw_event.mask & I...
If the event affects a directory and the auto_add flag of the targetted watch is set to True, a new watch is added on this new directory, with the same attribute values than those of this watch.
Below is the the instruction that describes the task: ### Input: If the event affects a directory and the auto_add flag of the targetted watch is set to True, a new watch is added on this new directory, with the same attribute values than those of this watch. ### Response: def process_IN_CR...
def login(self, username=None, password=None): """Explicit Abode login.""" if username is not None: self._cache[CONST.ID] = username if password is not None: self._cache[CONST.PASSWORD] = password if (self._cache[CONST.ID] is None or not isinstanc...
Explicit Abode login.
Below is the the instruction that describes the task: ### Input: Explicit Abode login. ### Response: def login(self, username=None, password=None): """Explicit Abode login.""" if username is not None: self._cache[CONST.ID] = username if password is not None: self._ca...
def input(self, **kwargs): """ Specify temporary input file extension. Browserify requires explicit file extension (".js" or ".json" by default). https://github.com/substack/node-browserify/issues/1469 """ if self.infile is None and "{infile}" in self.command: ...
Specify temporary input file extension. Browserify requires explicit file extension (".js" or ".json" by default). https://github.com/substack/node-browserify/issues/1469
Below is the the instruction that describes the task: ### Input: Specify temporary input file extension. Browserify requires explicit file extension (".js" or ".json" by default). https://github.com/substack/node-browserify/issues/1469 ### Response: def input(self, **kwargs): """ S...
def _ExtractMetadataFromFileEntry(self, mediator, file_entry, data_stream): """Extracts metadata from a file entry. Args: mediator (ParserMediator): mediates the interactions between parsers and other components, such as storage and abort signals. file_entry (dfvfs.FileEntry): file entry ...
Extracts metadata from a file entry. Args: mediator (ParserMediator): mediates the interactions between parsers and other components, such as storage and abort signals. file_entry (dfvfs.FileEntry): file entry to extract metadata from. data_stream (dfvfs.DataStream): data stream or None...
Below is the the instruction that describes the task: ### Input: Extracts metadata from a file entry. Args: mediator (ParserMediator): mediates the interactions between parsers and other components, such as storage and abort signals. file_entry (dfvfs.FileEntry): file entry to extract met...
def read_file_chunk(self, source, pos, chunk): '''Read local file chunk''' if chunk==0: return StringIO() data = None with open(source, 'rb') as f: f.seek(pos) data = f.read(chunk) if not data: raise Failure('Unable to read data from source: %s' % source) return StringI...
Read local file chunk
Below is the the instruction that describes the task: ### Input: Read local file chunk ### Response: def read_file_chunk(self, source, pos, chunk): '''Read local file chunk''' if chunk==0: return StringIO() data = None with open(source, 'rb') as f: f.seek(pos) data = f.read(chun...