code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _get_path(name, settings, mkdir=True): """ Generate a project path. """ default_projects_path = settings.config.get("projects_path") path = None if default_projects_path: path = raw_input("\nWhere would you like to create this project? [{0}/{1}] ".format(default_projects_path, name)...
Generate a project path.
Below is the the instruction that describes the task: ### Input: Generate a project path. ### Response: def _get_path(name, settings, mkdir=True): """ Generate a project path. """ default_projects_path = settings.config.get("projects_path") path = None if default_projects_path: pat...
def _cdist(x, y, exponent=1): """ Pairwise distance between points in two sets. As Scipy converts every value to double, this wrapper uses a less efficient implementation if the original dtype can not be converted to double. """ if _can_be_double(x) and _can_be_double(y): return _c...
Pairwise distance between points in two sets. As Scipy converts every value to double, this wrapper uses a less efficient implementation if the original dtype can not be converted to double.
Below is the the instruction that describes the task: ### Input: Pairwise distance between points in two sets. As Scipy converts every value to double, this wrapper uses a less efficient implementation if the original dtype can not be converted to double. ### Response: def _cdist(x, y, exponent=1): ...
def _StartDebugger(): """Configures and starts the debugger.""" global _hub_client global _breakpoints_manager cdbg_native.InitializeModule(_flags) _hub_client = gcp_hub_client.GcpHubClient() visibility_policy = _GetVisibilityPolicy() _breakpoints_manager = breakpoints_manager.BreakpointsManager( ...
Configures and starts the debugger.
Below is the the instruction that describes the task: ### Input: Configures and starts the debugger. ### Response: def _StartDebugger(): """Configures and starts the debugger.""" global _hub_client global _breakpoints_manager cdbg_native.InitializeModule(_flags) _hub_client = gcp_hub_client.GcpHubClien...
def schedule_transfer_runs( self, parent, start_time, end_time, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates transfer runs for a time range [start\_time, end\_time...
Creates transfer runs for a time range [start\_time, end\_time]. For each date - or whatever granularity the data source supports - in the range, one transfer run is created. Note that runs are created per UTC time in the time range. Example: >>> from google.cloud import big...
Below is the the instruction that describes the task: ### Input: Creates transfer runs for a time range [start\_time, end\_time]. For each date - or whatever granularity the data source supports - in the range, one transfer run is created. Note that runs are created per UTC time in the time ...
def rmi(self, force=False, via_name=False): """ remove this image :param force: bool, force removal of the image :param via_name: bool, refer to the image via name, if false, refer via ID, not used now :return: None """ return os.remove(self.local_location)
remove this image :param force: bool, force removal of the image :param via_name: bool, refer to the image via name, if false, refer via ID, not used now :return: None
Below is the the instruction that describes the task: ### Input: remove this image :param force: bool, force removal of the image :param via_name: bool, refer to the image via name, if false, refer via ID, not used now :return: None ### Response: def rmi(self, force=False, via_name=False):...
def handle_services(changeset): """Populate the change set with addCharm and deploy changes.""" charms = {} for service_name, service in sorted(changeset.bundle['services'].items()): # Add the addCharm record if one hasn't been added yet. if service['charm'] not in charms: record...
Populate the change set with addCharm and deploy changes.
Below is the the instruction that describes the task: ### Input: Populate the change set with addCharm and deploy changes. ### Response: def handle_services(changeset): """Populate the change set with addCharm and deploy changes.""" charms = {} for service_name, service in sorted(changeset.bundle['serv...
def load_path(self, path): ''' Load and return a given import path to a module or class ''' containing_module, _, last_item = path.rpartition('.') if last_item[0].isupper(): # Is a class definition, should do an "import from" path = containing_module ...
Load and return a given import path to a module or class
Below is the the instruction that describes the task: ### Input: Load and return a given import path to a module or class ### Response: def load_path(self, path): ''' Load and return a given import path to a module or class ''' containing_module, _, last_item = path.rpartition('.') ...
def connect(self): """Connect to the host and port specified in __init__.""" self.sock = socket_create_connection((self.host,self.port), self.timeout, self.source_address) if self._tunnel_host: self._tunnel()
Connect to the host and port specified in __init__.
Below is the the instruction that describes the task: ### Input: Connect to the host and port specified in __init__. ### Response: def connect(self): """Connect to the host and port specified in __init__.""" self.sock = socket_create_connection((self.host,self.port), ...
def _cmd_exists(cmd): """ check if dependency program is there """ return _subprocess.call("type " + cmd, shell=True, stdout=_subprocess.PIPE, stderr=_subprocess.PIPE) == 0
check if dependency program is there
Below is the the instruction that describes the task: ### Input: check if dependency program is there ### Response: def _cmd_exists(cmd): """ check if dependency program is there """ return _subprocess.call("type " + cmd, shell=True, stdout=_subprocess....
def get_perceel_by_capakey(self, capakey): ''' Get a `perceel`. :param capakey: An capakey for a `perceel`. :rtype: :class:`Perceel` ''' def creator(): url = self.base_url + '/parcel/%s' % capakey h = self.base_headers p = { ...
Get a `perceel`. :param capakey: An capakey for a `perceel`. :rtype: :class:`Perceel`
Below is the the instruction that describes the task: ### Input: Get a `perceel`. :param capakey: An capakey for a `perceel`. :rtype: :class:`Perceel` ### Response: def get_perceel_by_capakey(self, capakey): ''' Get a `perceel`. :param capakey: An capakey for a `perceel`. ...
def from_chunks(cls, chunks): """Construct PNG from raw chunks. :arg chunks: A list of ``(chunk_type, chunk_raw_data)``. Also see :func:`chunks`. :type chunks: list[tuple(str, bytes)] """ im = cls() im.chunks = chunks im.init() return im
Construct PNG from raw chunks. :arg chunks: A list of ``(chunk_type, chunk_raw_data)``. Also see :func:`chunks`. :type chunks: list[tuple(str, bytes)]
Below is the the instruction that describes the task: ### Input: Construct PNG from raw chunks. :arg chunks: A list of ``(chunk_type, chunk_raw_data)``. Also see :func:`chunks`. :type chunks: list[tuple(str, bytes)] ### Response: def from_chunks(cls, chunks): """Construct PNG from raw chunks. :arg...
def gff(args): """ %prog gff btabfile Convert btab file generated by AAT to gff3 format. """ from jcvi.utils.range import range_minmax from jcvi.formats.gff import valid_gff_parent_child, valid_gff_type p = OptionParser(gff.__doc__) p.add_option("--source", default=None, help="Specify ...
%prog gff btabfile Convert btab file generated by AAT to gff3 format.
Below is the the instruction that describes the task: ### Input: %prog gff btabfile Convert btab file generated by AAT to gff3 format. ### Response: def gff(args): """ %prog gff btabfile Convert btab file generated by AAT to gff3 format. """ from jcvi.utils.range import range_minmax f...
def build_license_file(directory, spec): """ Creates a License.rtf file with the content of "X_MSI_LICENSE_TEXT" in the given directory """ name, text = '', '' try: name = spec['LICENSE'] text = spec['X_MSI_LICENSE_TEXT'] except KeyError: pass # ignore this as X_MSI_LICE...
Creates a License.rtf file with the content of "X_MSI_LICENSE_TEXT" in the given directory
Below is the the instruction that describes the task: ### Input: Creates a License.rtf file with the content of "X_MSI_LICENSE_TEXT" in the given directory ### Response: def build_license_file(directory, spec): """ Creates a License.rtf file with the content of "X_MSI_LICENSE_TEXT" in the given directo...
def _simple_dispatch(self, name, params): """ Dispatch method """ # Normalize parameters if params: if isinstance(params, (list, tuple)): params = [jabsorb.from_jabsorb(param) for param in params] else: params = {key: jabsor...
Dispatch method
Below is the the instruction that describes the task: ### Input: Dispatch method ### Response: def _simple_dispatch(self, name, params): """ Dispatch method """ # Normalize parameters if params: if isinstance(params, (list, tuple)): params = [jabs...
def cases(store, case_query, limit=100): """Preprocess case objects. Add the necessary information to display the 'cases' view Args: store(adapter.MongoAdapter) case_query(pymongo.Cursor) limit(int): Maximum number of cases to display Returns: data(dict): includes the ...
Preprocess case objects. Add the necessary information to display the 'cases' view Args: store(adapter.MongoAdapter) case_query(pymongo.Cursor) limit(int): Maximum number of cases to display Returns: data(dict): includes the cases, how many there are and the limit.
Below is the the instruction that describes the task: ### Input: Preprocess case objects. Add the necessary information to display the 'cases' view Args: store(adapter.MongoAdapter) case_query(pymongo.Cursor) limit(int): Maximum number of cases to display Returns: data...
def _get_geometry(self): """ Creates a multipolygon of bounding box polygons """ return shapely.geometry.MultiPolygon([bbox.geometry for bbox in self.bbox_list])
Creates a multipolygon of bounding box polygons
Below is the the instruction that describes the task: ### Input: Creates a multipolygon of bounding box polygons ### Response: def _get_geometry(self): """ Creates a multipolygon of bounding box polygons """ return shapely.geometry.MultiPolygon([bbox.geometry for bbox in self.bbox_list])
def _try_coerce_result(self, result): """ reverse of try_coerce_args """ if isinstance(result, np.ndarray): if result.dtype.kind in ['i', 'f']: result = result.astype('M8[ns]') elif isinstance(result, (np.integer, np.float, np.datetime64)): result = self....
reverse of try_coerce_args
Below is the the instruction that describes the task: ### Input: reverse of try_coerce_args ### Response: def _try_coerce_result(self, result): """ reverse of try_coerce_args """ if isinstance(result, np.ndarray): if result.dtype.kind in ['i', 'f']: result = result.astyp...
def message_interval_send(self, message_id, interval_us, force_mavlink1=False): ''' This interface replaces DATA_STREAM message_id : The ID of the requested MAVLink message. v1.0 is limited to 254 messages. (uint16_t) interval_us ...
This interface replaces DATA_STREAM message_id : The ID of the requested MAVLink message. v1.0 is limited to 254 messages. (uint16_t) interval_us : The interval between two messages, in microseconds. A value of -1 indicates this stream is disabled, 0 indicat...
Below is the the instruction that describes the task: ### Input: This interface replaces DATA_STREAM message_id : The ID of the requested MAVLink message. v1.0 is limited to 254 messages. (uint16_t) interval_us : The interval between two messages, in mic...
def clone(self, data=None, shared_data=True, new_type=None, link=True, *args, **overrides): """ Returns a clone of the object with matching parameter values containing the specified args and kwargs. If shared_data is set to True and no data explicitly supplied, the...
Returns a clone of the object with matching parameter values containing the specified args and kwargs. If shared_data is set to True and no data explicitly supplied, the clone will share data with the original. May also supply a new_type, which will inherit all shared parameters.
Below is the the instruction that describes the task: ### Input: Returns a clone of the object with matching parameter values containing the specified args and kwargs. If shared_data is set to True and no data explicitly supplied, the clone will share data with the original. May also supply...
def pose_from_oxts_packet(packet, scale): """Helper method to compute a SE(3) pose matrix from an OXTS packet. """ er = 6378137. # earth radius (approx.) in meters # Use a Mercator projection to get the translation vector tx = scale * packet.lon * np.pi * er / 180. ty = scale * er * \ ...
Helper method to compute a SE(3) pose matrix from an OXTS packet.
Below is the the instruction that describes the task: ### Input: Helper method to compute a SE(3) pose matrix from an OXTS packet. ### Response: def pose_from_oxts_packet(packet, scale): """Helper method to compute a SE(3) pose matrix from an OXTS packet. """ er = 6378137. # earth radius (approx.) in ...
def parse_python(classifiers): """Parse out the versions of python supported a/c classifiers.""" prefix = 'Programming Language :: Python ::' python_classifiers = [c.split('::')[2].strip() for c in classifiers if c.startswith(prefix)] return ', '.join([c for c in python_classifiers if parse_version(c)])
Parse out the versions of python supported a/c classifiers.
Below is the the instruction that describes the task: ### Input: Parse out the versions of python supported a/c classifiers. ### Response: def parse_python(classifiers): """Parse out the versions of python supported a/c classifiers.""" prefix = 'Programming Language :: Python ::' python_classifiers = [...
def norm(self): """:obj:`tuple` of :obj:`numpy.ndarray`: The normalized vectors for qr and qd, respectively. """ qr_c = quaternion_conjugate(self._qr) qd_c = quaternion_conjugate(self._qd) qr_norm = np.linalg.norm(quaternion_multiply(self._qr, qr_c)) qd_norm = np.linalg....
:obj:`tuple` of :obj:`numpy.ndarray`: The normalized vectors for qr and qd, respectively.
Below is the the instruction that describes the task: ### Input: :obj:`tuple` of :obj:`numpy.ndarray`: The normalized vectors for qr and qd, respectively. ### Response: def norm(self): """:obj:`tuple` of :obj:`numpy.ndarray`: The normalized vectors for qr and qd, respectively. """ qr_c = qu...
def _filter_releases(self): """ Run the release filtering plugins """ global display_filter_log filter_plugins = filter_release_plugins() if not filter_plugins: if display_filter_log: logger.info("No release filters are enabled. Skipping filter...
Run the release filtering plugins
Below is the the instruction that describes the task: ### Input: Run the release filtering plugins ### Response: def _filter_releases(self): """ Run the release filtering plugins """ global display_filter_log filter_plugins = filter_release_plugins() if not filter_pl...
def install_database(name, owner, template='template0', encoding='UTF8', locale='en_US.UTF-8'): """ Require a PostgreSQL database. :: from fabtools import require require.postgres.database('myapp', owner='dbuser') """ create_database(name, owner, template=template, encoding=enc...
Require a PostgreSQL database. :: from fabtools import require require.postgres.database('myapp', owner='dbuser')
Below is the the instruction that describes the task: ### Input: Require a PostgreSQL database. :: from fabtools import require require.postgres.database('myapp', owner='dbuser') ### Response: def install_database(name, owner, template='template0', encoding='UTF8', locale='en_US.UTF-8'): ...
def _fix_score_column(cov_file): """ Move counts to score columns in bed file """ new_cov = utils.splitext_plus(cov_file)[0] + '_fix.cov' with open(cov_file) as in_handle: with open(new_cov, 'w') as out_handle: for line in in_handle: cols = line.strip().split("\t"...
Move counts to score columns in bed file
Below is the the instruction that describes the task: ### Input: Move counts to score columns in bed file ### Response: def _fix_score_column(cov_file): """ Move counts to score columns in bed file """ new_cov = utils.splitext_plus(cov_file)[0] + '_fix.cov' with open(cov_file) as in_handle: ...
def normalize(dt, tz=UTC): """ Convert date or datetime to datetime with timezone. :param dt: date to normalize :param tz: the normalized date's timezone :return: date as datetime with timezone """ if type(dt) is date: dt = dt + relativedelta(hour=0) elif type(dt) is datetime: ...
Convert date or datetime to datetime with timezone. :param dt: date to normalize :param tz: the normalized date's timezone :return: date as datetime with timezone
Below is the the instruction that describes the task: ### Input: Convert date or datetime to datetime with timezone. :param dt: date to normalize :param tz: the normalized date's timezone :return: date as datetime with timezone ### Response: def normalize(dt, tz=UTC): """ Convert date or datet...
def clear_cached_realms(self, realms, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-clear-cache.html>`_ :arg realms: Comma-separated list of realms to clear :arg usernames: Comma-separated list of usernames to clear from the ...
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-clear-cache.html>`_ :arg realms: Comma-separated list of realms to clear :arg usernames: Comma-separated list of usernames to clear from the cache
Below is the the instruction that describes the task: ### Input: `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-clear-cache.html>`_ :arg realms: Comma-separated list of realms to clear :arg usernames: Comma-separated list of usernames to clear from the ca...
def runExperiment5B(dirName): """ This runs the second experiment in the section "Simulations with Sensorimotor Sequences". It averages over many parameter combinations. This experiment could take several hours. You can run faster versions by reducing the number of trials. """ # Results are put into a pk...
This runs the second experiment in the section "Simulations with Sensorimotor Sequences". It averages over many parameter combinations. This experiment could take several hours. You can run faster versions by reducing the number of trials.
Below is the the instruction that describes the task: ### Input: This runs the second experiment in the section "Simulations with Sensorimotor Sequences". It averages over many parameter combinations. This experiment could take several hours. You can run faster versions by reducing the number of trials. ### ...
def get_mchirp(h5group): """Calculate the chipr mass column for this PyCBC HDF5 table group """ mass1 = h5group['mass1'][:] mass2 = h5group['mass2'][:] return (mass1 * mass2) ** (3/5.) / (mass1 + mass2) ** (1/5.)
Calculate the chipr mass column for this PyCBC HDF5 table group
Below is the the instruction that describes the task: ### Input: Calculate the chipr mass column for this PyCBC HDF5 table group ### Response: def get_mchirp(h5group): """Calculate the chipr mass column for this PyCBC HDF5 table group """ mass1 = h5group['mass1'][:] mass2 = h5group['mass2'][:] ...
def get_already_awarded_user_ids(self, db_read=None, show_log=True): """ Returns already awarded user ids and the count. """ db_read = db_read or self.db_read already_awarded_ids = self.badge.users.using(db_read).values_list('id', flat=True) already_awarded_ids_count = ...
Returns already awarded user ids and the count.
Below is the the instruction that describes the task: ### Input: Returns already awarded user ids and the count. ### Response: def get_already_awarded_user_ids(self, db_read=None, show_log=True): """ Returns already awarded user ids and the count. """ db_read = db_read or self.db_r...
def importFile(self, srcUrl, sharedFileName=None, hardlink=False): """ Imports the file at the given URL into job store. The ID of the newly imported file is returned. If the name of a shared file name is provided, the file will be imported as such and None is returned. Currentl...
Imports the file at the given URL into job store. The ID of the newly imported file is returned. If the name of a shared file name is provided, the file will be imported as such and None is returned. Currently supported schemes are: - 's3' for objects in Amazon S3 e...
Below is the the instruction that describes the task: ### Input: Imports the file at the given URL into job store. The ID of the newly imported file is returned. If the name of a shared file name is provided, the file will be imported as such and None is returned. Currently supported scheme...
def equal(self, cwd): """ Returns True if left and right are equal """ cmd = ["diff"] cmd.append("-q") cmd.append(self.left.get_name()) cmd.append(self.right.get_name()) try: Process(cmd).run(cwd=cwd, suppress_output=True) except SubprocessErr...
Returns True if left and right are equal
Below is the the instruction that describes the task: ### Input: Returns True if left and right are equal ### Response: def equal(self, cwd): """ Returns True if left and right are equal """ cmd = ["diff"] cmd.append("-q") cmd.append(self.left.get_name()) cmd.append(...
def _copy(self, other, copy_func): """ Copies the contents of another Choice object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and obje...
Copies the contents of another Choice object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects
Below is the the instruction that describes the task: ### Input: Copies the contents of another Choice object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, ...
def nodes(self): """ Return the nodes for this VSS Container :rtype: SubElementCollection(VSSContainerNode) """ resource = sub_collection( self.get_relation('vss_container_node'), VSSContainerNode) resource._load_from_engine(self, 'nodes...
Return the nodes for this VSS Container :rtype: SubElementCollection(VSSContainerNode)
Below is the the instruction that describes the task: ### Input: Return the nodes for this VSS Container :rtype: SubElementCollection(VSSContainerNode) ### Response: def nodes(self): """ Return the nodes for this VSS Container :rtype: SubElementCollection(VSSContai...
def _set_edge_loop_detection_native(self, v, load=False): """ Setter method for edge_loop_detection_native, mapped from YANG variable /interface/ethernet/edge_loop_detection_native (container) If this variable is read-only (config: false) in the source YANG file, then _set_edge_loop_detection_native is ...
Setter method for edge_loop_detection_native, mapped from YANG variable /interface/ethernet/edge_loop_detection_native (container) If this variable is read-only (config: false) in the source YANG file, then _set_edge_loop_detection_native is considered as a private method. Backends looking to populate this ...
Below is the the instruction that describes the task: ### Input: Setter method for edge_loop_detection_native, mapped from YANG variable /interface/ethernet/edge_loop_detection_native (container) If this variable is read-only (config: false) in the source YANG file, then _set_edge_loop_detection_native is c...
def setCurrentRecord(self, record): """ Sets the current record for this tree to the inputed record. :param record | <orb.Table> """ if self.isLoading(): self._tempCurrentRecord = record return for i in range(self.t...
Sets the current record for this tree to the inputed record. :param record | <orb.Table>
Below is the the instruction that describes the task: ### Input: Sets the current record for this tree to the inputed record. :param record | <orb.Table> ### Response: def setCurrentRecord(self, record): """ Sets the current record for this tree to the inputed record. ...
def contracts_derived(self): """list(Contract): List of contracts that are derived and not inherited.""" inheritance = (x.inheritance for x in self.contracts) inheritance = [item for sublist in inheritance for item in sublist] return [c for c in self._contracts.values() if c not in inher...
list(Contract): List of contracts that are derived and not inherited.
Below is the the instruction that describes the task: ### Input: list(Contract): List of contracts that are derived and not inherited. ### Response: def contracts_derived(self): """list(Contract): List of contracts that are derived and not inherited.""" inheritance = (x.inheritance for x in self.co...
def addItem(self, itemType, itemContents, itemID=None): """ :param str itemType: The type of the item, note, place, todo :param dict itemContents: A dictionary of the item contents :param int itemID: When editing a note, send the ID along with it """ if itemT...
:param str itemType: The type of the item, note, place, todo :param dict itemContents: A dictionary of the item contents :param int itemID: When editing a note, send the ID along with it
Below is the the instruction that describes the task: ### Input: :param str itemType: The type of the item, note, place, todo :param dict itemContents: A dictionary of the item contents :param int itemID: When editing a note, send the ID along with it ### Response: def addItem(self, itemTyp...
def save_config(self, cmd="save", confirm=False, confirm_response=""): """ Save Config for HuaweiSSH""" return super(HuaweiBase, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
Save Config for HuaweiSSH
Below is the the instruction that describes the task: ### Input: Save Config for HuaweiSSH ### Response: def save_config(self, cmd="save", confirm=False, confirm_response=""): """ Save Config for HuaweiSSH""" return super(HuaweiBase, self).save_config( cmd=cmd, confirm=confirm, confirm_...
def get_auto_follow_pattern(self, name=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/ccr-get-auto-follow-pattern.html>`_ :arg name: The name of the auto follow pattern. """ return self.transport.perform_request( "GET", _mak...
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/ccr-get-auto-follow-pattern.html>`_ :arg name: The name of the auto follow pattern.
Below is the the instruction that describes the task: ### Input: `<https://www.elastic.co/guide/en/elasticsearch/reference/current/ccr-get-auto-follow-pattern.html>`_ :arg name: The name of the auto follow pattern. ### Response: def get_auto_follow_pattern(self, name=None, params=None): """ ...
def save(self): """Persist config changes""" with open(self._config_file_path, 'w') as file: self._config_parser.write(file)
Persist config changes
Below is the the instruction that describes the task: ### Input: Persist config changes ### Response: def save(self): """Persist config changes""" with open(self._config_file_path, 'w') as file: self._config_parser.write(file)
def install_backport_hook(api): """ Install a backport import hook for Qt4 api Parameters ---------- api : str The Qt4 api whose structure should be intercepted ('pyqt4' or 'pyside'). Example ------- >>> install_backport_hook("pyqt4") >>> import PyQt4 Loaded mod...
Install a backport import hook for Qt4 api Parameters ---------- api : str The Qt4 api whose structure should be intercepted ('pyqt4' or 'pyside'). Example ------- >>> install_backport_hook("pyqt4") >>> import PyQt4 Loaded module AnyQt._backport as a substitute for PyQt...
Below is the the instruction that describes the task: ### Input: Install a backport import hook for Qt4 api Parameters ---------- api : str The Qt4 api whose structure should be intercepted ('pyqt4' or 'pyside'). Example ------- >>> install_backport_hook("pyqt4") >>> im...
def is_parent_of_gradebook(self, id_, gradebook_id): """Tests if an ``Id`` is a direct parent of a gradebook. arg: id (osid.id.Id): an ``Id`` arg: gradebook_id (osid.id.Id): the ``Id`` of a gradebook return: (boolean) - ``true`` if this ``id`` is a parent of ``grad...
Tests if an ``Id`` is a direct parent of a gradebook. arg: id (osid.id.Id): an ``Id`` arg: gradebook_id (osid.id.Id): the ``Id`` of a gradebook return: (boolean) - ``true`` if this ``id`` is a parent of ``gradebook_id,`` ``false`` otherwise raise: NotFound - ``gr...
Below is the the instruction that describes the task: ### Input: Tests if an ``Id`` is a direct parent of a gradebook. arg: id (osid.id.Id): an ``Id`` arg: gradebook_id (osid.id.Id): the ``Id`` of a gradebook return: (boolean) - ``true`` if this ``id`` is a parent of `...
def approximate_gradient(decision_function, sample, num_evals, delta, constraint, shape, clip_min, clip_max): """ Gradient direction estimation """ # Generate random vectors. noise_shape = [num_evals] + list(shape) if constraint == 'l2': rv = np.random.randn(*noise_shape) elif con...
Gradient direction estimation
Below is the the instruction that describes the task: ### Input: Gradient direction estimation ### Response: def approximate_gradient(decision_function, sample, num_evals, delta, constraint, shape, clip_min, clip_max): """ Gradient direction estimation """ # Generate random vectors. ...
def cvss_base_v2_value(cls, cvss_base_vector): """ Calculate the cvss base score from a cvss base vector for cvss version 2. Arguments: cvss_base_vector (str) Cvss base vector v2. Return the calculated score """ if not cvss_base_vector: return Non...
Calculate the cvss base score from a cvss base vector for cvss version 2. Arguments: cvss_base_vector (str) Cvss base vector v2. Return the calculated score
Below is the the instruction that describes the task: ### Input: Calculate the cvss base score from a cvss base vector for cvss version 2. Arguments: cvss_base_vector (str) Cvss base vector v2. Return the calculated score ### Response: def cvss_base_v2_value(cls, cvss_base_vect...
def is_username_available(self, username): """Return True if username is valid and available, otherwise False.""" params = {'user': username} try: result = self.request_json(self.config['username_available'], params=params) except errors...
Return True if username is valid and available, otherwise False.
Below is the the instruction that describes the task: ### Input: Return True if username is valid and available, otherwise False. ### Response: def is_username_available(self, username): """Return True if username is valid and available, otherwise False.""" params = {'user': username} try: ...
async def rcpt(self, recipient, options=None): """ Sends a SMTP 'RCPT' command. - Indicates a recipient for the e-mail. For further details, please check out `RFC 5321 § 4.1.1.3`_ and `§ 3.3`_. Args: recipient (str): E-mail address of one recipient. opti...
Sends a SMTP 'RCPT' command. - Indicates a recipient for the e-mail. For further details, please check out `RFC 5321 § 4.1.1.3`_ and `§ 3.3`_. Args: recipient (str): E-mail address of one recipient. options (list of str or None, optional): Additional options to send ...
Below is the the instruction that describes the task: ### Input: Sends a SMTP 'RCPT' command. - Indicates a recipient for the e-mail. For further details, please check out `RFC 5321 § 4.1.1.3`_ and `§ 3.3`_. Args: recipient (str): E-mail address of one recipient. op...
def start_to(self, local_ip, remote_ip, local_tsap, remote_tsap): """ Starts the Partner and binds it to the specified IP address and the IsoTCP port. :param local_ip: PC host IPV4 Address. "0.0.0.0" is the default adapter :param remote_ip: PLC IPV4 Address :param local_...
Starts the Partner and binds it to the specified IP address and the IsoTCP port. :param local_ip: PC host IPV4 Address. "0.0.0.0" is the default adapter :param remote_ip: PLC IPV4 Address :param local_tsap: Local TSAP :param remote_tsap: PLC TSAP
Below is the the instruction that describes the task: ### Input: Starts the Partner and binds it to the specified IP address and the IsoTCP port. :param local_ip: PC host IPV4 Address. "0.0.0.0" is the default adapter :param remote_ip: PLC IPV4 Address :param local_tsap: Local TSAP ...
def save(self, commit=True): """save the instance or create a new one..""" # walk through the document fields for field_name, field in iter_valid_fields(self._meta): setattr(self.instance, field_name, self.cleaned_data.get(field_name)) if commit: self.instance.s...
save the instance or create a new one..
Below is the the instruction that describes the task: ### Input: save the instance or create a new one.. ### Response: def save(self, commit=True): """save the instance or create a new one..""" # walk through the document fields for field_name, field in iter_valid_fields(self._meta): ...
def face_and_energy_detector(image_path, detect_faces=True): """ Finds faces and energy in an image """ source = Image.open(image_path) work_width = 800 if source.mode != 'RGB' or source.bits != 8: source24 = source.convert('RGB') else: source24 = source.copy() grayscale...
Finds faces and energy in an image
Below is the the instruction that describes the task: ### Input: Finds faces and energy in an image ### Response: def face_and_energy_detector(image_path, detect_faces=True): """ Finds faces and energy in an image """ source = Image.open(image_path) work_width = 800 if source.mode != 'RGB' ...
def config(remote_base= 'https://raw.githubusercontent.com/SciCrunch/NIF-Ontology/', local_base= None, # devconfig.ontology_local_repo by default branch= devconfig.neurons_branch, core_graph_paths= ['ttl/phenotype-core.ttl', 'ttl/ph...
Wraps graphBase.configGraphIO to provide a set of sane defaults for input ontologies and output files.
Below is the the instruction that describes the task: ### Input: Wraps graphBase.configGraphIO to provide a set of sane defaults for input ontologies and output files. ### Response: def config(remote_base= 'https://raw.githubusercontent.com/SciCrunch/NIF-Ontology/', local_base= None...
def selection(self): """ Selection property. :return: None if no font is selected and font family name if one is selected. :rtype: None or str """ if self._font.get() is "" or self._font.get() not in self._fonts: return None else: ...
Selection property. :return: None if no font is selected and font family name if one is selected. :rtype: None or str
Below is the the instruction that describes the task: ### Input: Selection property. :return: None if no font is selected and font family name if one is selected. :rtype: None or str ### Response: def selection(self): """ Selection property. :return: None i...
def p0f_impersonate(pkt, osgenre=None, osdetails=None, signature=None, extrahops=0, mtu=1500, uptime=None): """Modifies pkt so that p0f will think it has been sent by a specific OS. If osdetails is None, then we randomly pick up a personality matching osgenre. If osgenre and signature are also ...
Modifies pkt so that p0f will think it has been sent by a specific OS. If osdetails is None, then we randomly pick up a personality matching osgenre. If osgenre and signature are also None, we use a local signature (using p0f_getlocalsigs). If signature is specified (as a tuple), we use the signature. For now, only T...
Below is the the instruction that describes the task: ### Input: Modifies pkt so that p0f will think it has been sent by a specific OS. If osdetails is None, then we randomly pick up a personality matching osgenre. If osgenre and signature are also None, we use a local signature (using p0f_getlocalsigs). If signat...
def disassociate_address(self, public_ip=None, association_id=None): """ Disassociate an Elastic IP address from a currently running instance. :type public_ip: string :param public_ip: The public IP address for EC2 elastic IPs. :type association_id: string :param associ...
Disassociate an Elastic IP address from a currently running instance. :type public_ip: string :param public_ip: The public IP address for EC2 elastic IPs. :type association_id: string :param association_id: The association ID for a VPC based elastic ip. :rtype: bool :r...
Below is the the instruction that describes the task: ### Input: Disassociate an Elastic IP address from a currently running instance. :type public_ip: string :param public_ip: The public IP address for EC2 elastic IPs. :type association_id: string :param association_id: The associ...
def from_dict(data, ctx): """ Instantiate a new PriceBucket from a dict (generally from loading a JSON response). The data used to instantiate the PriceBucket is a shallow copy of the dict passed in, with any complex child types instantiated appropriately. """ da...
Instantiate a new PriceBucket from a dict (generally from loading a JSON response). The data used to instantiate the PriceBucket is a shallow copy of the dict passed in, with any complex child types instantiated appropriately.
Below is the the instruction that describes the task: ### Input: Instantiate a new PriceBucket from a dict (generally from loading a JSON response). The data used to instantiate the PriceBucket is a shallow copy of the dict passed in, with any complex child types instantiated appropriately. ...
async def add_recipients(self, *recipients): r"""|coro| Adds recipients to this group. A group can only have a maximum of 10 members. Attempting to add more ends up in an exception. To add a recipient to the group, you must have a relationship with the user of type :att...
r"""|coro| Adds recipients to this group. A group can only have a maximum of 10 members. Attempting to add more ends up in an exception. To add a recipient to the group, you must have a relationship with the user of type :attr:`RelationshipType.friend`. Parameters ...
Below is the the instruction that describes the task: ### Input: r"""|coro| Adds recipients to this group. A group can only have a maximum of 10 members. Attempting to add more ends up in an exception. To add a recipient to the group, you must have a relationship with the u...
def rowgroupmap(table, key, mapper, header=None, presorted=False, buffersize=None, tempdir=None, cache=True): """ Group rows under the given key then apply `mapper` to yield zero or more output rows for each input group of rows. """ return RowGroupMapView(table, key, mapper, header...
Group rows under the given key then apply `mapper` to yield zero or more output rows for each input group of rows.
Below is the the instruction that describes the task: ### Input: Group rows under the given key then apply `mapper` to yield zero or more output rows for each input group of rows. ### Response: def rowgroupmap(table, key, mapper, header=None, presorted=False, buffersize=None, tempdir=None, cach...
def _similar_names(owner, attrname, distance_threshold, max_choices): """Given an owner and a name, try to find similar names The similar names are searched given a distance metric and only a given number of choices will be returned. """ possible_names = [] names = _node_names(owner) for n...
Given an owner and a name, try to find similar names The similar names are searched given a distance metric and only a given number of choices will be returned.
Below is the the instruction that describes the task: ### Input: Given an owner and a name, try to find similar names The similar names are searched given a distance metric and only a given number of choices will be returned. ### Response: def _similar_names(owner, attrname, distance_threshold, max_choice...
def _video_part_rIds(self): """Return the rIds for relationships to media part for video. This is where the media part and its relationships to the slide are actually created. """ media_rId, video_rId = self._slide_part.get_or_add_video_media_part( self._video ...
Return the rIds for relationships to media part for video. This is where the media part and its relationships to the slide are actually created.
Below is the the instruction that describes the task: ### Input: Return the rIds for relationships to media part for video. This is where the media part and its relationships to the slide are actually created. ### Response: def _video_part_rIds(self): """Return the rIds for relationships t...
def filter_composite_from_subgroups(s): """ Given a sorted list of subgroups, return a string appropriate to provide as the a composite track's `filterComposite` argument >>> import trackhub >>> trackhub.helpers.filter_composite_from_subgroups(['cell', 'ab', 'lab', 'knockdown']) 'dimA dimB' ...
Given a sorted list of subgroups, return a string appropriate to provide as the a composite track's `filterComposite` argument >>> import trackhub >>> trackhub.helpers.filter_composite_from_subgroups(['cell', 'ab', 'lab', 'knockdown']) 'dimA dimB' Parameters ---------- s : list A l...
Below is the the instruction that describes the task: ### Input: Given a sorted list of subgroups, return a string appropriate to provide as the a composite track's `filterComposite` argument >>> import trackhub >>> trackhub.helpers.filter_composite_from_subgroups(['cell', 'ab', 'lab', 'knockdown']) ...
def position_sp(self): """ Writing specifies the target position for the `run-to-abs-pos` and `run-to-rel-pos` commands. Reading returns the current value. Units are in tacho counts. You can use the value returned by `count_per_rot` to convert tacho counts to/from rotations or de...
Writing specifies the target position for the `run-to-abs-pos` and `run-to-rel-pos` commands. Reading returns the current value. Units are in tacho counts. You can use the value returned by `count_per_rot` to convert tacho counts to/from rotations or degrees.
Below is the the instruction that describes the task: ### Input: Writing specifies the target position for the `run-to-abs-pos` and `run-to-rel-pos` commands. Reading returns the current value. Units are in tacho counts. You can use the value returned by `count_per_rot` to convert tacho counts to/fr...
def draw_lines(self, lines, x=0, y=0): '''Write a collection of lines to the terminal stream at the given location. The lines are written as one 'block' (i.e. each new line starts one line down from the previous, but each starts *at the given x coordinate*). :parameter lines: An...
Write a collection of lines to the terminal stream at the given location. The lines are written as one 'block' (i.e. each new line starts one line down from the previous, but each starts *at the given x coordinate*). :parameter lines: An iterable of strings that should be written to the...
Below is the the instruction that describes the task: ### Input: Write a collection of lines to the terminal stream at the given location. The lines are written as one 'block' (i.e. each new line starts one line down from the previous, but each starts *at the given x coordinate*). :...
def parse(self, configManager, config): """ Parses commandline arguments, given a series of configuration options. Inputs: configManager - Our parent ConfigManager instance which is constructing the Config object. config - The _Config object containing configuration optio...
Parses commandline arguments, given a series of configuration options. Inputs: configManager - Our parent ConfigManager instance which is constructing the Config object. config - The _Config object containing configuration options populated thus far. Outputs: A dictionary of new...
Below is the the instruction that describes the task: ### Input: Parses commandline arguments, given a series of configuration options. Inputs: configManager - Our parent ConfigManager instance which is constructing the Config object. config - The _Config object containing configurat...
def newEmailReport(self, name, **kwargs): """Creates a new email report Returns status message for operation Optional parameters: * checkid -- Check identifier. If omitted, this will be an overview report Type: Integer * frequency -...
Creates a new email report Returns status message for operation Optional parameters: * checkid -- Check identifier. If omitted, this will be an overview report Type: Integer * frequency -- Report frequency Type: String [...
Below is the the instruction that describes the task: ### Input: Creates a new email report Returns status message for operation Optional parameters: * checkid -- Check identifier. If omitted, this will be an overview report Type: Integer ...
def divisors(n): """ From a given natural integer, returns the list of divisors in ascending order :param n: Natural integer :return: List of divisors of n in ascending order """ factors = _factor_generator(n) _divisors = [] listexponents = [[k**x for x in range(0, factors[k]+1)] for k i...
From a given natural integer, returns the list of divisors in ascending order :param n: Natural integer :return: List of divisors of n in ascending order
Below is the the instruction that describes the task: ### Input: From a given natural integer, returns the list of divisors in ascending order :param n: Natural integer :return: List of divisors of n in ascending order ### Response: def divisors(n): """ From a given natural integer, returns the lis...
def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: -...
Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - host...
Below is the the instruction that describes the task: ### Input: Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted...
def _validate_alias_file_content(alias_file_path, url=''): """ Make sure the alias name and alias command in the alias file is in valid format. Args: The alias file path to import aliases from. """ alias_table = get_config_parser() try: alias_table.read(alias_file_path) ...
Make sure the alias name and alias command in the alias file is in valid format. Args: The alias file path to import aliases from.
Below is the the instruction that describes the task: ### Input: Make sure the alias name and alias command in the alias file is in valid format. Args: The alias file path to import aliases from. ### Response: def _validate_alias_file_content(alias_file_path, url=''): """ Make sure the alias n...
def _get_phantom_root_catalog(self, cat_name, cat_class): """Get's the catalog id corresponding to the root of all implementation catalogs.""" catalog_map = make_catalog_map(cat_name, identifier=PHANTOM_ROOT_IDENTIFIER) return cat_class(osid_object_map=catalog_map, runtime=self._runtime, proxy=s...
Get's the catalog id corresponding to the root of all implementation catalogs.
Below is the the instruction that describes the task: ### Input: Get's the catalog id corresponding to the root of all implementation catalogs. ### Response: def _get_phantom_root_catalog(self, cat_name, cat_class): """Get's the catalog id corresponding to the root of all implementation catalogs.""" ...
def file_uptodate(fname, cmp_fname): """Check if a file exists, is non-empty and is more recent than cmp_fname. """ try: return (file_exists(fname) and file_exists(cmp_fname) and os.path.getmtime(fname) >= os.path.getmtime(cmp_fname)) except OSError: return False
Check if a file exists, is non-empty and is more recent than cmp_fname.
Below is the the instruction that describes the task: ### Input: Check if a file exists, is non-empty and is more recent than cmp_fname. ### Response: def file_uptodate(fname, cmp_fname): """Check if a file exists, is non-empty and is more recent than cmp_fname. """ try: return (file_exists(fna...
def f_add_leaf(self, *args, **kwargs): """Adds an empty generic leaf under the current node. You can add to a generic leaves anywhere you want. So you are free to build your trajectory tree with any structure. You do not necessarily have to follow the four subtrees `config`, `parameters...
Adds an empty generic leaf under the current node. You can add to a generic leaves anywhere you want. So you are free to build your trajectory tree with any structure. You do not necessarily have to follow the four subtrees `config`, `parameters`, `derived_parameters`, `results`. If yo...
Below is the the instruction that describes the task: ### Input: Adds an empty generic leaf under the current node. You can add to a generic leaves anywhere you want. So you are free to build your trajectory tree with any structure. You do not necessarily have to follow the four subtrees `c...
def check_existing(package, pkg_files, formula_def, conn=None): ''' Check the filesystem for existing files ''' if conn is None: conn = init() node_type = six.text_type(__opts__.get('spm_node_type')) existing_files = [] for member in pkg_files: if member.isdir(): ...
Check the filesystem for existing files
Below is the the instruction that describes the task: ### Input: Check the filesystem for existing files ### Response: def check_existing(package, pkg_files, formula_def, conn=None): ''' Check the filesystem for existing files ''' if conn is None: conn = init() node_type = six.text_typ...
async def bootstrap(self, addrs): """ Bootstrap the server by connecting to other known nodes in the network. Args: addrs: A `list` of (ip, port) `tuple` pairs. Note that only IP addresses are acceptable - hostnames will cause an error. """ log.de...
Bootstrap the server by connecting to other known nodes in the network. Args: addrs: A `list` of (ip, port) `tuple` pairs. Note that only IP addresses are acceptable - hostnames will cause an error.
Below is the the instruction that describes the task: ### Input: Bootstrap the server by connecting to other known nodes in the network. Args: addrs: A `list` of (ip, port) `tuple` pairs. Note that only IP addresses are acceptable - hostnames will cause an error. ### Respons...
def dump_process_memory(self, pid, working_dir="c:\\windows\\carbonblack\\", path_to_procdump=None): """Use sysinternals procdump to dump process memory on a specific process. If only the pid is specified, the default behavior is to use the version of ProcDump supplied with cbinterface's pip3 installer....
Use sysinternals procdump to dump process memory on a specific process. If only the pid is specified, the default behavior is to use the version of ProcDump supplied with cbinterface's pip3 installer. :requires: SysInternals ProcDump v9.0 included with cbinterface==1.1.0 :arguments pid: Process...
Below is the the instruction that describes the task: ### Input: Use sysinternals procdump to dump process memory on a specific process. If only the pid is specified, the default behavior is to use the version of ProcDump supplied with cbinterface's pip3 installer. :requires: SysInternals ProcDump ...
def nvmlDeviceGetComputeMode(handle): r""" /** * Retrieves the current compute mode for the device. * * For all products. * * See \ref nvmlComputeMode_t for details on allowed compute modes. * * @param device The identifier of the target device ...
r""" /** * Retrieves the current compute mode for the device. * * For all products. * * See \ref nvmlComputeMode_t for details on allowed compute modes. * * @param device The identifier of the target device * @param mode ...
Below is the the instruction that describes the task: ### Input: r""" /** * Retrieves the current compute mode for the device. * * For all products. * * See \ref nvmlComputeMode_t for details on allowed compute modes. * * @param device The identif...
def get_lldp_neighbor_detail_output_has_more(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_lldp_neighbor_detail = ET.Element("get_lldp_neighbor_detail") config = get_lldp_neighbor_detail output = ET.SubElement(get_lldp_neighbor_detail, "out...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def get_lldp_neighbor_detail_output_has_more(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_lldp_neighbor_detail = ET.Element("get_lldp_neighbor_detail")...
def inband_solarirradiance(self, rsr, scale=1.0, **options): """Derive the inband solar irradiance for a given instrument relative spectral response valid for an earth-sun distance of one AU.""" return self._band_calculations(rsr, False, scale, **options)
Derive the inband solar irradiance for a given instrument relative spectral response valid for an earth-sun distance of one AU.
Below is the the instruction that describes the task: ### Input: Derive the inband solar irradiance for a given instrument relative spectral response valid for an earth-sun distance of one AU. ### Response: def inband_solarirradiance(self, rsr, scale=1.0, **options): """Derive the inband solar irra...
def is_safe_url(url, host=None): """Return ``True`` if the url is a safe redirection. The safe redirection means that it doesn't point to a different host. Always returns ``False`` on an empty url. """ if not url: return False netloc = urlparse.urlparse(url)[1] return not netloc or ...
Return ``True`` if the url is a safe redirection. The safe redirection means that it doesn't point to a different host. Always returns ``False`` on an empty url.
Below is the the instruction that describes the task: ### Input: Return ``True`` if the url is a safe redirection. The safe redirection means that it doesn't point to a different host. Always returns ``False`` on an empty url. ### Response: def is_safe_url(url, host=None): """Return ``True`` if the ur...
def syllable_tokenize(text: str) -> List[str]: """ :param str text: input string to be tokenized :return: list of syllables """ if not text or not isinstance(text, str): return [] tokens = [] if text: words = word_tokenize(text) trie = dict_trie(dict_source=thai_syl...
:param str text: input string to be tokenized :return: list of syllables
Below is the the instruction that describes the task: ### Input: :param str text: input string to be tokenized :return: list of syllables ### Response: def syllable_tokenize(text: str) -> List[str]: """ :param str text: input string to be tokenized :return: list of syllables """ if not tex...
def change_password(self, username, newpassword, raise_on_error=False): """Change new password for a user Args: username: The account username. newpassword: The account new password. raise_on_error: optional (default: False) Returns: True: Succ...
Change new password for a user Args: username: The account username. newpassword: The account new password. raise_on_error: optional (default: False) Returns: True: Succeeded False: If unsuccessful
Below is the the instruction that describes the task: ### Input: Change new password for a user Args: username: The account username. newpassword: The account new password. raise_on_error: optional (default: False) Returns: True: Succeeded ...
async def joinTeleLayer(self, url, indx=None): ''' Convenience function to join a remote telepath layer into this cortex and default view. ''' info = { 'type': 'remote', 'owner': 'root', 'config': { 'url': url } ...
Convenience function to join a remote telepath layer into this cortex and default view.
Below is the the instruction that describes the task: ### Input: Convenience function to join a remote telepath layer into this cortex and default view. ### Response: async def joinTeleLayer(self, url, indx=None): ''' Convenience function to join a remote telepath layer into this co...
def export(self, queryset=None, *args, **kwargs): """ Exports a resource. """ self.before_export(queryset, *args, **kwargs) if queryset is None: queryset = self.get_queryset() headers = self.get_export_headers() data = tablib.Dataset(headers=headers)...
Exports a resource.
Below is the the instruction that describes the task: ### Input: Exports a resource. ### Response: def export(self, queryset=None, *args, **kwargs): """ Exports a resource. """ self.before_export(queryset, *args, **kwargs) if queryset is None: queryset = self.g...
def CreateItem(self, database_or_Container_link, document, options=None): """Creates a document in a collection. :param str database_or_Container_link: The link to the database when using partitioning, otherwise link to the document collection. :param dict document: The ...
Creates a document in a collection. :param str database_or_Container_link: The link to the database when using partitioning, otherwise link to the document collection. :param dict document: The Azure Cosmos document to create. :param dict options: The request...
Below is the the instruction that describes the task: ### Input: Creates a document in a collection. :param str database_or_Container_link: The link to the database when using partitioning, otherwise link to the document collection. :param dict document: The Azure Cosmos doc...
def on_exchange_declareok(self, unused_frame): """ Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC command. :param pika.Frame.Method unused_frame: Exchange.DeclareOk response frame """ self._logger.debug('Exchange declared') self.setup_queue(s...
Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC command. :param pika.Frame.Method unused_frame: Exchange.DeclareOk response frame
Below is the the instruction that describes the task: ### Input: Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC command. :param pika.Frame.Method unused_frame: Exchange.DeclareOk response frame ### Response: def on_exchange_declareok(self, unused_frame): """ In...
async def stop(self): """Stop heartbeat.""" self.stopped = True self.loop_event.set() # Waiting for shutdown of loop() await self.stopped_event.wait()
Stop heartbeat.
Below is the the instruction that describes the task: ### Input: Stop heartbeat. ### Response: async def stop(self): """Stop heartbeat.""" self.stopped = True self.loop_event.set() # Waiting for shutdown of loop() await self.stopped_event.wait()
def avhrr(scans_nb, scan_points, scan_angle=55.37, frequency=1 / 6.0, apply_offset=True): """Definition of the avhrr instrument. Source: NOAA KLM User's Guide, Appendix J http://www.ncdc.noaa.gov/oa/pod-guide/ncdc/docs/klm/html/j/app-j.htm """ # build the avhrr instrument (scan angles) ...
Definition of the avhrr instrument. Source: NOAA KLM User's Guide, Appendix J http://www.ncdc.noaa.gov/oa/pod-guide/ncdc/docs/klm/html/j/app-j.htm
Below is the the instruction that describes the task: ### Input: Definition of the avhrr instrument. Source: NOAA KLM User's Guide, Appendix J http://www.ncdc.noaa.gov/oa/pod-guide/ncdc/docs/klm/html/j/app-j.htm ### Response: def avhrr(scans_nb, scan_points, scan_angle=55.37, frequency=1 / 6.0, ...
def get_trilegal(filename,ra,dec,folder='.', galactic=False, filterset='kepler_2mass',area=1,maglim=27,binaries=False, trilegal_version='1.6',sigma_AV=0.1,convert_h5=True): """Runs get_trilegal perl script; optionally saves output into .h5 file Depends on a perl script provide...
Runs get_trilegal perl script; optionally saves output into .h5 file Depends on a perl script provided by L. Girardi; calls the web form simulation, downloads the file, and (optionally) converts to HDF format. Uses A_V at infinity from :func:`utils.get_AV_infinity`. .. note:: Would be de...
Below is the the instruction that describes the task: ### Input: Runs get_trilegal perl script; optionally saves output into .h5 file Depends on a perl script provided by L. Girardi; calls the web form simulation, downloads the file, and (optionally) converts to HDF format. Uses A_V at infinity fr...
def path(self, args, kw): """Builds the URL path fragment for this route.""" params = self._pop_params(args, kw) if args or kw: raise InvalidArgumentError("Extra parameters (%s, %s) when building path for %s" % (args, kw, self.template)) return self.build_url(**params)
Builds the URL path fragment for this route.
Below is the the instruction that describes the task: ### Input: Builds the URL path fragment for this route. ### Response: def path(self, args, kw): """Builds the URL path fragment for this route.""" params = self._pop_params(args, kw) if args or kw: raise InvalidArgumentError(...
def reset_input_generators(self, seed): """ Helper method which explicitly resets all input generators to the derived generator. This should only ever be called for testing or debugging. """ seed_generator = SeedGenerator().reset(seed=seed) for gen in self.input_...
Helper method which explicitly resets all input generators to the derived generator. This should only ever be called for testing or debugging.
Below is the the instruction that describes the task: ### Input: Helper method which explicitly resets all input generators to the derived generator. This should only ever be called for testing or debugging. ### Response: def reset_input_generators(self, seed): """ Helper method whi...
def sync_and_deploy_gateway(collector): """Do a sync followed by deploying the gateway""" configuration = collector.configuration aws_syncr = configuration['aws_syncr'] find_gateway(aws_syncr, configuration) artifact = aws_syncr.artifact aws_syncr.artifact = "" sync(collector) aws_sync...
Do a sync followed by deploying the gateway
Below is the the instruction that describes the task: ### Input: Do a sync followed by deploying the gateway ### Response: def sync_and_deploy_gateway(collector): """Do a sync followed by deploying the gateway""" configuration = collector.configuration aws_syncr = configuration['aws_syncr'] find_ga...
def split(self, amt): """ return 2 trades, 1 with specific amt and the other with self.quantity - amt """ ratio = abs(amt / self.qty) t1 = Trade(self.tid, self.ts, amt, self.px, fees=ratio * self.fees, **self.kwargs) t2 = Trade(self.tid, self.ts, self.qty - amt, self.px, fees=(1. - ratio...
return 2 trades, 1 with specific amt and the other with self.quantity - amt
Below is the the instruction that describes the task: ### Input: return 2 trades, 1 with specific amt and the other with self.quantity - amt ### Response: def split(self, amt): """ return 2 trades, 1 with specific amt and the other with self.quantity - amt """ ratio = abs(amt / self.qty) t1...
def dump(cfg, f): '''Serialize ``cfg`` as a libconfig-formatted stream into ``f`` ``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values (numbers, strings, booleans, possibly nested dicts, lists, and tuples). ``f`` must be a ``file``-like object with a ``write()`` method. ''' ...
Serialize ``cfg`` as a libconfig-formatted stream into ``f`` ``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values (numbers, strings, booleans, possibly nested dicts, lists, and tuples). ``f`` must be a ``file``-like object with a ``write()`` method.
Below is the the instruction that describes the task: ### Input: Serialize ``cfg`` as a libconfig-formatted stream into ``f`` ``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values (numbers, strings, booleans, possibly nested dicts, lists, and tuples). ``f`` must be a ``file``-like ...
def connect_combo_text(instance, prop, widget): """ Connect a callback property with a QComboBox widget based on the text. Parameters ---------- instance : object The class instance that the callback property is attached to prop : str The name of the callback property widget...
Connect a callback property with a QComboBox widget based on the text. Parameters ---------- instance : object The class instance that the callback property is attached to prop : str The name of the callback property widget : QComboBox The combo box to connect. See Also...
Below is the the instruction that describes the task: ### Input: Connect a callback property with a QComboBox widget based on the text. Parameters ---------- instance : object The class instance that the callback property is attached to prop : str The name of the callback property ...
def setProperty(self, name, value): ''' Sets one of the supported property values of the speech engine listed above. If a value is invalid, attempts to clip it / coerce so it is valid before giving up and firing an exception. @param name: Property name @type name: str ...
Sets one of the supported property values of the speech engine listed above. If a value is invalid, attempts to clip it / coerce so it is valid before giving up and firing an exception. @param name: Property name @type name: str @param value: Property value @type value: ...
Below is the the instruction that describes the task: ### Input: Sets one of the supported property values of the speech engine listed above. If a value is invalid, attempts to clip it / coerce so it is valid before giving up and firing an exception. @param name: Property name @type...
def main(): # type: () -> typing.Any """Parse the command line options and launch the requested command. If the command is 'help' then print the help message for the subcommand; if no subcommand is given, print the standard help message. """ colorama.init(wrap=six.PY3) doc = usage.get_prima...
Parse the command line options and launch the requested command. If the command is 'help' then print the help message for the subcommand; if no subcommand is given, print the standard help message.
Below is the the instruction that describes the task: ### Input: Parse the command line options and launch the requested command. If the command is 'help' then print the help message for the subcommand; if no subcommand is given, print the standard help message. ### Response: def main(): # type: () ->...
def _relativeize(self, filename): """Return the portion of a filename that is 'relative' to the directories in this lookup. """ filename = posixpath.normpath(filename) for dir in self.directories: if filename[0:len(dir)] == dir: return filename[le...
Return the portion of a filename that is 'relative' to the directories in this lookup.
Below is the the instruction that describes the task: ### Input: Return the portion of a filename that is 'relative' to the directories in this lookup. ### Response: def _relativeize(self, filename): """Return the portion of a filename that is 'relative' to the directories in this loo...
def getWeights(self, term_i=None): """ Return weights for fixed effect term term_i Args: term_i: fixed effect term index Returns: weights of the spefied fixed effect term. The output will be a KxL matrix of weights will be returned, wh...
Return weights for fixed effect term term_i Args: term_i: fixed effect term index Returns: weights of the spefied fixed effect term. The output will be a KxL matrix of weights will be returned, where K is F.shape[1] and L is A.shape[1] of the correspo...
Below is the the instruction that describes the task: ### Input: Return weights for fixed effect term term_i Args: term_i: fixed effect term index Returns: weights of the spefied fixed effect term. The output will be a KxL matrix of weights will be returned, ...
def predict_survival_function(self, X, times=None): """ Predict the survival function for individuals, given their covariates. This assumes that the individual just entered the study (that is, we do not condition on how long they have already lived for.) Parameters ---------- ...
Predict the survival function for individuals, given their covariates. This assumes that the individual just entered the study (that is, we do not condition on how long they have already lived for.) Parameters ---------- X: numpy array or DataFrame a (n,d) covariate numpy a...
Below is the the instruction that describes the task: ### Input: Predict the survival function for individuals, given their covariates. This assumes that the individual just entered the study (that is, we do not condition on how long they have already lived for.) Parameters ---------- ...
def get_stacks(self): """Get the stacks for the current action. Handles configuring the :class:`stacker.stack.Stack` objects that will be used in the current action. Returns: list: a list of :class:`stacker.stack.Stack` objects """ if not hasattr(self, "_st...
Get the stacks for the current action. Handles configuring the :class:`stacker.stack.Stack` objects that will be used in the current action. Returns: list: a list of :class:`stacker.stack.Stack` objects
Below is the the instruction that describes the task: ### Input: Get the stacks for the current action. Handles configuring the :class:`stacker.stack.Stack` objects that will be used in the current action. Returns: list: a list of :class:`stacker.stack.Stack` objects ### Respon...
def get_zeta_i_j(self, X): ''' Parameters ---------- X : np.array Array of word counts, shape (N, 2) where N is the vocab size. X[:,0] is the positive class, while X[:,1] is the negative class. None by default Returns ------- np.array of z-scores ''' y_i, y_j = X.T[0], X.T[1] return self.get...
Parameters ---------- X : np.array Array of word counts, shape (N, 2) where N is the vocab size. X[:,0] is the positive class, while X[:,1] is the negative class. None by default Returns ------- np.array of z-scores
Below is the the instruction that describes the task: ### Input: Parameters ---------- X : np.array Array of word counts, shape (N, 2) where N is the vocab size. X[:,0] is the positive class, while X[:,1] is the negative class. None by default Returns ------- np.array of z-scores ### Response: de...
def getResultsRange(self): """Returns the valid result range for this reference analysis based on the results ranges defined in the Reference Sample from which this analysis has been created. A Reference Analysis (control or blank) will be considered out of range if its results ...
Returns the valid result range for this reference analysis based on the results ranges defined in the Reference Sample from which this analysis has been created. A Reference Analysis (control or blank) will be considered out of range if its results does not match with the result defined...
Below is the the instruction that describes the task: ### Input: Returns the valid result range for this reference analysis based on the results ranges defined in the Reference Sample from which this analysis has been created. A Reference Analysis (control or blank) will be considered out o...