code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def setPluginSetting(name, value, namespace = None): ''' Sets the value of a plugin setting. :param name: the name of the setting. It is not the full path, but just the last name of it :param value: the value to set for the plugin setting :param namespace: The namespace. If not passed or None, the ...
Sets the value of a plugin setting. :param name: the name of the setting. It is not the full path, but just the last name of it :param value: the value to set for the plugin setting :param namespace: The namespace. If not passed or None, the namespace will be inferred from the caller method. Normally, ...
Below is the the instruction that describes the task: ### Input: Sets the value of a plugin setting. :param name: the name of the setting. It is not the full path, but just the last name of it :param value: the value to set for the plugin setting :param namespace: The namespace. If not passed or None, ...
def u_base(self, theta, phi, lam, q): """Apply U to q.""" return self.append(UBase(theta, phi, lam), [q], [])
Apply U to q.
Below is the the instruction that describes the task: ### Input: Apply U to q. ### Response: def u_base(self, theta, phi, lam, q): """Apply U to q.""" return self.append(UBase(theta, phi, lam), [q], [])
def _has_vowel(self, term): """Return Porter helper function _has_vowel value. Parameters ---------- term : str The word to scan for vowels Returns ------- bool True iff a vowel exists in the term (as defined in the Porter ste...
Return Porter helper function _has_vowel value. Parameters ---------- term : str The word to scan for vowels Returns ------- bool True iff a vowel exists in the term (as defined in the Porter stemmer definition)
Below is the the instruction that describes the task: ### Input: Return Porter helper function _has_vowel value. Parameters ---------- term : str The word to scan for vowels Returns ------- bool True iff a vowel exists in the term (as defined...
def list(self, before_id=None, since_id=None, **kwargs): """Return a page of direct messages. The messages come in reversed order (newest first). Note you can only provide _one_ of ``before_id``, ``since_id``. :param str before_id: message ID for paging backwards :param str sin...
Return a page of direct messages. The messages come in reversed order (newest first). Note you can only provide _one_ of ``before_id``, ``since_id``. :param str before_id: message ID for paging backwards :param str since_id: message ID for most recent messages since :return: di...
Below is the the instruction that describes the task: ### Input: Return a page of direct messages. The messages come in reversed order (newest first). Note you can only provide _one_ of ``before_id``, ``since_id``. :param str before_id: message ID for paging backwards :param str si...
def debug_storage(storage, base_info=False, chars=True, runs=False): "Display debug information for the storage" import codecs import locale import sys if six.PY2: stderr = codecs.getwriter(locale.getpreferredencoding())(sys.stderr) else: stderr = sys.stderr caller = inspe...
Display debug information for the storage
Below is the the instruction that describes the task: ### Input: Display debug information for the storage ### Response: def debug_storage(storage, base_info=False, chars=True, runs=False): "Display debug information for the storage" import codecs import locale import sys if six.PY2: ...
def format(self, indent_level, indent_size=4): """Format this verifier Returns: string: A formatted string """ name = self.format_name('Bytes', indent_size) return self.wrap_lines(name, indent_level, indent_size)
Format this verifier Returns: string: A formatted string
Below is the the instruction that describes the task: ### Input: Format this verifier Returns: string: A formatted string ### Response: def format(self, indent_level, indent_size=4): """Format this verifier Returns: string: A formatted string """ n...
async def StorageAttachmentLife(self, ids): ''' ids : typing.Sequence[~StorageAttachmentId] Returns -> typing.Sequence[~LifeResult] ''' # map input types to rpc msg _params = dict() msg = dict(type='Uniter', request='StorageAttachmentLife', ...
ids : typing.Sequence[~StorageAttachmentId] Returns -> typing.Sequence[~LifeResult]
Below is the the instruction that describes the task: ### Input: ids : typing.Sequence[~StorageAttachmentId] Returns -> typing.Sequence[~LifeResult] ### Response: async def StorageAttachmentLife(self, ids): ''' ids : typing.Sequence[~StorageAttachmentId] Returns -> typing.Sequence[~...
async def _send_scan_event(self, device): """Send a scan event from a device.""" conn_string = str(device.iotile_id) info = { 'connection_string': conn_string, 'uuid': device.iotile_id, 'signal_strength': 100, 'validity_period': self.ExpirationTim...
Send a scan event from a device.
Below is the the instruction that describes the task: ### Input: Send a scan event from a device. ### Response: async def _send_scan_event(self, device): """Send a scan event from a device.""" conn_string = str(device.iotile_id) info = { 'connection_string': conn_string, ...
def _put_on_queue(self, to_put): """Puts data on queue""" old = self.pickle_queue self.pickle_queue = False try: self.queue.put(to_put, block=True) finally: self.pickle_queue = old
Puts data on queue
Below is the the instruction that describes the task: ### Input: Puts data on queue ### Response: def _put_on_queue(self, to_put): """Puts data on queue""" old = self.pickle_queue self.pickle_queue = False try: self.queue.put(to_put, block=True) finally: ...
def format_error(self, error, args=None): """ Format error with positional or named arguments (if any) """ if type(args) is dict: return error.format(**args) if type(args) is list or type(args) is tuple: return error.format(*args) return error
Format error with positional or named arguments (if any)
Below is the the instruction that describes the task: ### Input: Format error with positional or named arguments (if any) ### Response: def format_error(self, error, args=None): """ Format error with positional or named arguments (if any) """ if type(args) is dict: return error.format(*...
def put_mouse_event(self, dx, dy, dz, dw, button_state): """Initiates a mouse event using relative pointer movements along x and y axis. in dx of type int Amount of pixels the mouse should move to the right. Negative values move the mouse to the left. in dy of t...
Initiates a mouse event using relative pointer movements along x and y axis. in dx of type int Amount of pixels the mouse should move to the right. Negative values move the mouse to the left. in dy of type int Amount of pixels the mouse should move downwards...
Below is the the instruction that describes the task: ### Input: Initiates a mouse event using relative pointer movements along x and y axis. in dx of type int Amount of pixels the mouse should move to the right. Negative values move the mouse to the left. in dy of ...
def loadIntoTextureD3D11_Async(self, textureId, pDstTexture): """Helper function to copy the bits into an existing texture.""" fn = self.function_table.loadIntoTextureD3D11_Async result = fn(textureId, pDstTexture) return result
Helper function to copy the bits into an existing texture.
Below is the the instruction that describes the task: ### Input: Helper function to copy the bits into an existing texture. ### Response: def loadIntoTextureD3D11_Async(self, textureId, pDstTexture): """Helper function to copy the bits into an existing texture.""" fn = self.function_table.loadInto...
def qos_map_cos_traffic_class_cos0(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos") map = ET.SubElement(qos, "map") cos_traffic_class = ET.SubElement(map, "cos-traffic-cl...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def qos_map_cos_traffic_class_cos0(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos"...
def delete_old_host(self, hostname): """Remove all records for the host. :param str hostname: Hostname to remove :rtype: bool """ host = Host(self.session, name=hostname) return host.delete()
Remove all records for the host. :param str hostname: Hostname to remove :rtype: bool
Below is the the instruction that describes the task: ### Input: Remove all records for the host. :param str hostname: Hostname to remove :rtype: bool ### Response: def delete_old_host(self, hostname): """Remove all records for the host. :param str hostname: Hostname to remove ...
def _control_sample(self, sample): ''' Control the asked sample is ok ''' if sample > float(self.SAMPLE_LAST_PIXEL): return int(self.SAMPLE_LAST_PIXEL) elif sample < float(self.SAMPLE_FIRST_PIXEL): return int(self.SAMPLE_FIRST_PIXEL) else: return sampl...
Control the asked sample is ok
Below is the the instruction that describes the task: ### Input: Control the asked sample is ok ### Response: def _control_sample(self, sample): ''' Control the asked sample is ok ''' if sample > float(self.SAMPLE_LAST_PIXEL): return int(self.SAMPLE_LAST_PIXEL) elif sample < flo...
def combine_uuids(uuids, ordered=True, salt=''): """ Creates a uuid that specifies a group of UUIDS Args: uuids (list): list of uuid objects ordered (bool): if False uuid order changes the resulting combined uuid otherwise the uuids are considered an orderless set salt (...
Creates a uuid that specifies a group of UUIDS Args: uuids (list): list of uuid objects ordered (bool): if False uuid order changes the resulting combined uuid otherwise the uuids are considered an orderless set salt (str): salts the resulting hash Returns: uuid.UUI...
Below is the the instruction that describes the task: ### Input: Creates a uuid that specifies a group of UUIDS Args: uuids (list): list of uuid objects ordered (bool): if False uuid order changes the resulting combined uuid otherwise the uuids are considered an orderless set ...
def revoke_user_access(self, user, db_names, strict=True): """ Revokes access to the databases listed in `db_names` for the user. If any of the databases do not exist, a NoSuchDatabase exception will be raised, unless you specify `strict=False` in the call. """ user = ut...
Revokes access to the databases listed in `db_names` for the user. If any of the databases do not exist, a NoSuchDatabase exception will be raised, unless you specify `strict=False` in the call.
Below is the the instruction that describes the task: ### Input: Revokes access to the databases listed in `db_names` for the user. If any of the databases do not exist, a NoSuchDatabase exception will be raised, unless you specify `strict=False` in the call. ### Response: def revoke_user_access(s...
def thresholds(self): """Threshold values of the response functions.""" return numpy.array( sorted(self._key2float(key) for key in self._coefs), dtype=float)
Threshold values of the response functions.
Below is the the instruction that describes the task: ### Input: Threshold values of the response functions. ### Response: def thresholds(self): """Threshold values of the response functions.""" return numpy.array( sorted(self._key2float(key) for key in self._coefs), dtype=float)
def get_provisioning_configuration( self, provisioning_configuration_id, custom_headers=None, raw=False, **operation_config): """GetContinuousDeploymentOperation. :param provisioning_configuration_id: :type provisioning_configuration_id: str :param dict custom_headers: heade...
GetContinuousDeploymentOperation. :param provisioning_configuration_id: :type provisioning_configuration_id: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param...
Below is the the instruction that describes the task: ### Input: GetContinuousDeploymentOperation. :param provisioning_configuration_id: :type provisioning_configuration_id: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct...
def BaseShapeFactory(shape_elm, parent): """ Return an instance of the appropriate shape proxy class for *shape_elm*. """ tag = shape_elm.tag if tag == qn('p:pic'): videoFiles = shape_elm.xpath('./p:nvPicPr/p:nvPr/a:videoFile') if videoFiles: return Movie(shape_elm, pare...
Return an instance of the appropriate shape proxy class for *shape_elm*.
Below is the the instruction that describes the task: ### Input: Return an instance of the appropriate shape proxy class for *shape_elm*. ### Response: def BaseShapeFactory(shape_elm, parent): """ Return an instance of the appropriate shape proxy class for *shape_elm*. """ tag = shape_elm.tag ...
def text_uk_extremes(self, request): """ Return textual data of UK extremes. request: metoffer.CAPABILITIES Returns available extreme date and issue time metoffer.LATEST Returns data of late...
Return textual data of UK extremes. request: metoffer.CAPABILITIES Returns available extreme date and issue time metoffer.LATEST Returns data of latest extremes ...
Below is the the instruction that describes the task: ### Input: Return textual data of UK extremes. request: metoffer.CAPABILITIES Returns available extreme date and issue time metoffer.LATEST Returns ...
def memory_order(self, pattern): """! @brief Calculates function of the memorized pattern. @details Throws exception if length of pattern is not equal to size of the network or if it consists feature with value that are not equal to [-1; 1]. @param[in] pattern (list): Pattern fo...
! @brief Calculates function of the memorized pattern. @details Throws exception if length of pattern is not equal to size of the network or if it consists feature with value that are not equal to [-1; 1]. @param[in] pattern (list): Pattern for recognition represented by list of feature...
Below is the the instruction that describes the task: ### Input: ! @brief Calculates function of the memorized pattern. @details Throws exception if length of pattern is not equal to size of the network or if it consists feature with value that are not equal to [-1; 1]. @param[in] p...
def masked_dense(inputs, units, num_blocks=None, exclusive=False, kernel_initializer=None, reuse=None, name=None, *args, # pylint: disable=keyword-arg-before-vararg **kwargs): """A ...
A autoregressively masked dense layer. Analogous to `tf.layers.dense`. See [Germain et al. (2015)][1] for detailed explanation. Arguments: inputs: Tensor input. units: Python `int` scalar representing the dimensionality of the output space. num_blocks: Python `int` scalar representing the number...
Below is the the instruction that describes the task: ### Input: A autoregressively masked dense layer. Analogous to `tf.layers.dense`. See [Germain et al. (2015)][1] for detailed explanation. Arguments: inputs: Tensor input. units: Python `int` scalar representing the dimensionality of the output ...
def query(self, where="1=1", out_fields="*", timeFilter=None, geometryFilter=None, returnGeometry=True, returnIDsOnly=False, returnCountOnly=False, pixelSize=None, orderByFields=None, ...
queries a feature service based on a sql statement Inputs: where - the selection sql statement out_fields - the attribute fields to return timeFilter - a TimeFilter object where either the start time or start and end time are defined t...
Below is the the instruction that describes the task: ### Input: queries a feature service based on a sql statement Inputs: where - the selection sql statement out_fields - the attribute fields to return timeFilter - a TimeFilter object where either the start...
def _user_thread_main(self, target): """Main entry point for the thread that will run user's code.""" try: # Wait for GLib main loop to start running before starting user code. while True: if self._gobject_mainloop is not None and self._gobject_mainloop.is_running...
Main entry point for the thread that will run user's code.
Below is the the instruction that describes the task: ### Input: Main entry point for the thread that will run user's code. ### Response: def _user_thread_main(self, target): """Main entry point for the thread that will run user's code.""" try: # Wait for GLib main loop to start running...
def available_backups(self): """ The backups response contains what backups are available to be restored. """ if not hasattr(self, '_avail_backups'): result = self._client.get("{}/backups".format(Instance.api_endpoint), model=self) if not 'automatic' in result: ...
The backups response contains what backups are available to be restored.
Below is the the instruction that describes the task: ### Input: The backups response contains what backups are available to be restored. ### Response: def available_backups(self): """ The backups response contains what backups are available to be restored. """ if not hasattr(self, ...
def _npcap_set(self, key, val): """Internal function. Set a [key] parameter to [value]""" res, code = _exec_cmd(_encapsulate_admin( " ".join([_WlanHelper, self.guid[1:-1], key, val]) )) _windows_title() # Reset title of the window if code != 0: raise OSEr...
Internal function. Set a [key] parameter to [value]
Below is the the instruction that describes the task: ### Input: Internal function. Set a [key] parameter to [value] ### Response: def _npcap_set(self, key, val): """Internal function. Set a [key] parameter to [value]""" res, code = _exec_cmd(_encapsulate_admin( " ".join([_WlanHelper, s...
def get_pending_plan(self): """Read the currently running plan on reassign_partitions node.""" reassignment_path = '{admin}/{reassignment_node}'\ .format(admin=ADMIN_PATH, reassignment_node=REASSIGNMENT_NODE) try: result = self.get(reassignment_path) return lo...
Read the currently running plan on reassign_partitions node.
Below is the the instruction that describes the task: ### Input: Read the currently running plan on reassign_partitions node. ### Response: def get_pending_plan(self): """Read the currently running plan on reassign_partitions node.""" reassignment_path = '{admin}/{reassignment_node}'\ ....
def target_in_range(self, target: "Unit", bonus_distance: Union[int, float] = 0) -> bool: """ Includes the target's radius when calculating distance to target """ if self.can_attack_ground and not target.is_flying: unit_attack_range = self.ground_range elif self.can_attack_air and (t...
Includes the target's radius when calculating distance to target
Below is the the instruction that describes the task: ### Input: Includes the target's radius when calculating distance to target ### Response: def target_in_range(self, target: "Unit", bonus_distance: Union[int, float] = 0) -> bool: """ Includes the target's radius when calculating distance to target """ ...
def ensure_float_vector_or_None(F, require_order = False): """Ensures that F is either None, or a numpy array of floats If F is already either None or a numpy array of floats, F is returned (no copied!) Otherwise, checks if the argument can be converted to an array of floats and does that. Parameters ...
Ensures that F is either None, or a numpy array of floats If F is already either None or a numpy array of floats, F is returned (no copied!) Otherwise, checks if the argument can be converted to an array of floats and does that. Parameters ---------- F: float, list of float or 1D-ndarray of float ...
Below is the the instruction that describes the task: ### Input: Ensures that F is either None, or a numpy array of floats If F is already either None or a numpy array of floats, F is returned (no copied!) Otherwise, checks if the argument can be converted to an array of floats and does that. Paramete...
def write(self, data): """ Write the given data to the file. """ # Do the write self.backingStream.write(data) for listener in self.writeListeners: # Send out notifications listener(len(data))
Write the given data to the file.
Below is the the instruction that describes the task: ### Input: Write the given data to the file. ### Response: def write(self, data): """ Write the given data to the file. """ # Do the write self.backingStream.write(data) for listener in self.writ...
def CreateGRRTempFileVFS(filename=None, lifetime=0, mode="w+b", suffix=""): """Creates a GRR VFS temp file. This function is analogous to CreateGRRTempFile but returns an open VFS handle to the newly created file. Arguments are the same as for CreateGRRTempFile: Args: filename: The name of the file to use...
Creates a GRR VFS temp file. This function is analogous to CreateGRRTempFile but returns an open VFS handle to the newly created file. Arguments are the same as for CreateGRRTempFile: Args: filename: The name of the file to use. Note that setting both filename and directory name is not allowed. ...
Below is the the instruction that describes the task: ### Input: Creates a GRR VFS temp file. This function is analogous to CreateGRRTempFile but returns an open VFS handle to the newly created file. Arguments are the same as for CreateGRRTempFile: Args: filename: The name of the file to use. Note that ...
def send(self, me, to, subject, msg): """ Send Message """ msg = MIMEText(msg) msg['Subject'] = subject msg['From'] = me msg['To'] = to server = smtplib.SMTP(self.host, self.port) server.starttls() # Check if user and password defined if self._usr ...
Send Message
Below is the the instruction that describes the task: ### Input: Send Message ### Response: def send(self, me, to, subject, msg): """ Send Message """ msg = MIMEText(msg) msg['Subject'] = subject msg['From'] = me msg['To'] = to server = smtplib.SMTP(self.host, self.p...
def friendly_number(self, value: int) -> str: """Returns a comma-separated number for the given integer.""" if self.code not in ("en", "en_US"): return str(value) s = str(value) parts = [] while s: parts.append(s[-3:]) s = s[:-3] return...
Returns a comma-separated number for the given integer.
Below is the the instruction that describes the task: ### Input: Returns a comma-separated number for the given integer. ### Response: def friendly_number(self, value: int) -> str: """Returns a comma-separated number for the given integer.""" if self.code not in ("en", "en_US"): return ...
def group_keys_by_values(d): """ Take a dict (A -> B( and return another one (B -> [A]). It groups keys from the original dict by their values. .. testsetup:: from proso.dict import group_keys_by_values from pprint import pprint .. doctest:: >>> pprint(group_keys_by_value...
Take a dict (A -> B( and return another one (B -> [A]). It groups keys from the original dict by their values. .. testsetup:: from proso.dict import group_keys_by_values from pprint import pprint .. doctest:: >>> pprint(group_keys_by_values({1: True, 2: False, 3: True, 4: True}))...
Below is the the instruction that describes the task: ### Input: Take a dict (A -> B( and return another one (B -> [A]). It groups keys from the original dict by their values. .. testsetup:: from proso.dict import group_keys_by_values from pprint import pprint .. doctest:: >>...
def zipWithIndex(self): """ Zips this RDD with its element indices. The ordering is first based on the partition index and then the ordering of items within each partition. So the first item in the first partition gets index 0, and the last item in the last partition rec...
Zips this RDD with its element indices. The ordering is first based on the partition index and then the ordering of items within each partition. So the first item in the first partition gets index 0, and the last item in the last partition receives the largest index. This metho...
Below is the the instruction that describes the task: ### Input: Zips this RDD with its element indices. The ordering is first based on the partition index and then the ordering of items within each partition. So the first item in the first partition gets index 0, and the last item in the l...
def cc(self, chan, ctrl, val): """Send control change value. The controls that are recognized are dependent on the SoundFont. Values are always 0 to 127. Typical controls include: 1: vibrato 7: volume 10: pan (left to right) 11: expression (soft...
Send control change value. The controls that are recognized are dependent on the SoundFont. Values are always 0 to 127. Typical controls include: 1: vibrato 7: volume 10: pan (left to right) 11: expression (soft to loud) 64: sustain ...
Below is the the instruction that describes the task: ### Input: Send control change value. The controls that are recognized are dependent on the SoundFont. Values are always 0 to 127. Typical controls include: 1: vibrato 7: volume 10: pan (left to right) ...
def initialize(name='', pool_size=10, host='localhost', password='', port=5432, user=''): """Initialize a new database connection and return the pool object. Saves a reference to that instance in a module-level variable, so applications with only one database can just call this function and not worry about...
Initialize a new database connection and return the pool object. Saves a reference to that instance in a module-level variable, so applications with only one database can just call this function and not worry about pool objects.
Below is the the instruction that describes the task: ### Input: Initialize a new database connection and return the pool object. Saves a reference to that instance in a module-level variable, so applications with only one database can just call this function and not worry about pool objects. ### Response:...
def get_proc_dir(cachedir, **kwargs): ''' Given the cache directory, return the directory that process data is stored in, creating it if it doesn't exist. The following optional Keyword Arguments are handled: mode: which is anything os.makedir would accept as mode. uid: the uid to set, if not ...
Given the cache directory, return the directory that process data is stored in, creating it if it doesn't exist. The following optional Keyword Arguments are handled: mode: which is anything os.makedir would accept as mode. uid: the uid to set, if not set, or it is None or -1 no changes are m...
Below is the the instruction that describes the task: ### Input: Given the cache directory, return the directory that process data is stored in, creating it if it doesn't exist. The following optional Keyword Arguments are handled: mode: which is anything os.makedir would accept as mode. uid: the ...
def is_ancestor_of(self, other, inclusive=False): """ class or instance level method which returns True if self is ancestor (closer to root) of other else False. Optional flag `inclusive` on whether or not to treat self as ancestor of self. For example see: * :mod:`sqlalchemy_m...
class or instance level method which returns True if self is ancestor (closer to root) of other else False. Optional flag `inclusive` on whether or not to treat self as ancestor of self. For example see: * :mod:`sqlalchemy_mptt.tests.cases.integrity.test_hierarchy_structure`
Below is the the instruction that describes the task: ### Input: class or instance level method which returns True if self is ancestor (closer to root) of other else False. Optional flag `inclusive` on whether or not to treat self as ancestor of self. For example see: * :mod:`sqlal...
def rot(inputArray, theta=0, pc=(0, 0)): """ rotate input array with angle of theta :param inputArray: input array or list, e.g. np.array([[0,0],[0,1],[0,2]]) or [[0,0],[0,1],[0,2]] :param theta: rotation angle in degree :param pc: central point coords (x,y) r...
rotate input array with angle of theta :param inputArray: input array or list, e.g. np.array([[0,0],[0,1],[0,2]]) or [[0,0],[0,1],[0,2]] :param theta: rotation angle in degree :param pc: central point coords (x,y) regarding to rotation :return: rotated numpy a...
Below is the the instruction that describes the task: ### Input: rotate input array with angle of theta :param inputArray: input array or list, e.g. np.array([[0,0],[0,1],[0,2]]) or [[0,0],[0,1],[0,2]] :param theta: rotation angle in degree :param pc: central poin...
def get_resource_agent_session_for_bin(self, bin_id, proxy): """Gets a resource agent session for the given bin. arg: bin_id (osid.id.Id): the ``Id`` of the bin arg: proxy (osid.proxy.Proxy): a proxy return: (osid.resource.ResourceAgentSession) - a ``ResourceAgentS...
Gets a resource agent session for the given bin. arg: bin_id (osid.id.Id): the ``Id`` of the bin arg: proxy (osid.proxy.Proxy): a proxy return: (osid.resource.ResourceAgentSession) - a ``ResourceAgentSession`` raise: NotFound - ``bin_id`` not found raise: ...
Below is the the instruction that describes the task: ### Input: Gets a resource agent session for the given bin. arg: bin_id (osid.id.Id): the ``Id`` of the bin arg: proxy (osid.proxy.Proxy): a proxy return: (osid.resource.ResourceAgentSession) - a ``ResourceAgentSess...
def send(self, obj): """ Send an object to the remote server; block and return the reply if the socket type is REQ. :param obj: the Python object to send """ self.zsocket.send_pyobj(obj) self.num_sent += 1 if self.socket_type == zmq.REQ: ...
Send an object to the remote server; block and return the reply if the socket type is REQ. :param obj: the Python object to send
Below is the the instruction that describes the task: ### Input: Send an object to the remote server; block and return the reply if the socket type is REQ. :param obj: the Python object to send ### Response: def send(self, obj): """ Send an object to the remote server; ...
def _disambiguate_doc(self, tagged_tokens): """ Takes a list of tagged tokens, representing a document, in the form: [(token, tag), ...] And returns a mapping of terms to their disambiguated concepts (synsets). """ # Group tokens by PoS pos_groups =...
Takes a list of tagged tokens, representing a document, in the form: [(token, tag), ...] And returns a mapping of terms to their disambiguated concepts (synsets).
Below is the the instruction that describes the task: ### Input: Takes a list of tagged tokens, representing a document, in the form: [(token, tag), ...] And returns a mapping of terms to their disambiguated concepts (synsets). ### Response: def _disambiguate_doc(self, tagged_tokens):...
def parse_extended_entities(extended_entities_dict): """Parse media file URL:s form tweet data :extended_entities_dict: :returns: list of media file urls """ urls = [] if "media" in extended_entities_dict.keys(): for item in extended_entities_dict["media"]: # add static i...
Parse media file URL:s form tweet data :extended_entities_dict: :returns: list of media file urls
Below is the the instruction that describes the task: ### Input: Parse media file URL:s form tweet data :extended_entities_dict: :returns: list of media file urls ### Response: def parse_extended_entities(extended_entities_dict): """Parse media file URL:s form tweet data :extended_entities_dict: ...
def lovasz_hinge(logits, labels, per_image=True, ignore=None): """ Binary Lovasz hinge loss logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty) labels: [B, H, W] Tensor, binary ground truth masks (0 or 1) per_image: compute the loss per image instead of per batch ...
Binary Lovasz hinge loss logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty) labels: [B, H, W] Tensor, binary ground truth masks (0 or 1) per_image: compute the loss per image instead of per batch ignore: void class id
Below is the the instruction that describes the task: ### Input: Binary Lovasz hinge loss logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty) labels: [B, H, W] Tensor, binary ground truth masks (0 or 1) per_image: compute the loss per image instead of per batch ign...
def contract(s): """ >>> assert contract("1 1 1 2 2 3") == "3*1 2*2 1*3" >>> assert contract("1 1 3 2 3") == "2*1 1*3 1*2 1*3" """ if not s: return s tokens = s.split() old = tokens[0] count = [[1, old]] for t in tokens[1:]: if t == old: count[-1][0] += 1 ...
>>> assert contract("1 1 1 2 2 3") == "3*1 2*2 1*3" >>> assert contract("1 1 3 2 3") == "2*1 1*3 1*2 1*3"
Below is the the instruction that describes the task: ### Input: >>> assert contract("1 1 1 2 2 3") == "3*1 2*2 1*3" >>> assert contract("1 1 3 2 3") == "2*1 1*3 1*2 1*3" ### Response: def contract(s): """ >>> assert contract("1 1 1 2 2 3") == "3*1 2*2 1*3" >>> assert contract("1 1 3 2 3") == "2*1 ...
def pairwise_reproducibility(df, plot=False): """ Calculate the reproducibility of LA-ICPMS based on unique pairs of repeat analyses. Pairwise differences are fit with a half-Cauchy distribution, and the median and 95% confidence limits are returned for each analyte. Parameters ------...
Calculate the reproducibility of LA-ICPMS based on unique pairs of repeat analyses. Pairwise differences are fit with a half-Cauchy distribution, and the median and 95% confidence limits are returned for each analyte. Parameters ---------- df : pandas.DataFrame A dataset ...
Below is the the instruction that describes the task: ### Input: Calculate the reproducibility of LA-ICPMS based on unique pairs of repeat analyses. Pairwise differences are fit with a half-Cauchy distribution, and the median and 95% confidence limits are returned for each analyte. Parameters...
def serializable(wrapped): """ If a keyword argument 'serialize' with a True value is passed to the Wrapped function, the return of the wrapped function will be serialized. Nothing happens if the argument is not passed or the value is not True """ @wraps(wrapped) def wrapper(*args, **kwargs...
If a keyword argument 'serialize' with a True value is passed to the Wrapped function, the return of the wrapped function will be serialized. Nothing happens if the argument is not passed or the value is not True
Below is the the instruction that describes the task: ### Input: If a keyword argument 'serialize' with a True value is passed to the Wrapped function, the return of the wrapped function will be serialized. Nothing happens if the argument is not passed or the value is not True ### Response: def serializabl...
def overlay_gateway_map_vlan_vni_mapping_vni(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels") name_key = ET.SubElement(overlay_gateway, "name") ...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def overlay_gateway_map_vlan_vni_mapping_vni(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns=...
def _draw_mainlayer(self, gc, view_bounds=None, mode="default"): """ Draws the component """ gc.save_state() try: # Specify the font font = str_to_font(str(self.pen.font)) gc.set_font(font) gc.set_fill_color(self.pen.color_) x = self...
Draws the component
Below is the the instruction that describes the task: ### Input: Draws the component ### Response: def _draw_mainlayer(self, gc, view_bounds=None, mode="default"): """ Draws the component """ gc.save_state() try: # Specify the font font = str_to_font(str(self.pen.fo...
def CreateMock(self, class_to_mock): """Create a new mock object. Args: # class_to_mock: the class to be mocked class_to_mock: class Returns: MockObject that can be used as the class_to_mock would be. """ new_mock = MockObject(class_to_mock) self._mock_objects.append(new_moc...
Create a new mock object. Args: # class_to_mock: the class to be mocked class_to_mock: class Returns: MockObject that can be used as the class_to_mock would be.
Below is the the instruction that describes the task: ### Input: Create a new mock object. Args: # class_to_mock: the class to be mocked class_to_mock: class Returns: MockObject that can be used as the class_to_mock would be. ### Response: def CreateMock(self, class_to_mock): """Cre...
def duration(self): """The duration of this stimulus :returns: float -- duration in seconds """ durs = [] for track in self._segments: durs.append(sum([comp.duration() for comp in track])) return max(durs)
The duration of this stimulus :returns: float -- duration in seconds
Below is the the instruction that describes the task: ### Input: The duration of this stimulus :returns: float -- duration in seconds ### Response: def duration(self): """The duration of this stimulus :returns: float -- duration in seconds """ durs = [] for track i...
def QA_fetch_stock_day_full_adv(date): ''' '返回全市场某一天的数据' :param date: :return: QA_DataStruct_Stock_day类 型数据 ''' # 🛠 todo 检查日期data参数 res = QA_fetch_stock_full(date, 'pd') if res is None: print("QA Error QA_fetch_stock_day_full_adv parameter date=%s call QA_fetch_stock_full return...
'返回全市场某一天的数据' :param date: :return: QA_DataStruct_Stock_day类 型数据
Below is the the instruction that describes the task: ### Input: '返回全市场某一天的数据' :param date: :return: QA_DataStruct_Stock_day类 型数据 ### Response: def QA_fetch_stock_day_full_adv(date): ''' '返回全市场某一天的数据' :param date: :return: QA_DataStruct_Stock_day类 型数据 ''' # 🛠 todo 检查日期data参数 re...
def modified(self): 'return datetime.datetime' return dateutil.parser.parse(str(self.f.currentRevision.modified))
return datetime.datetime
Below is the the instruction that describes the task: ### Input: return datetime.datetime ### Response: def modified(self): 'return datetime.datetime' return dateutil.parser.parse(str(self.f.currentRevision.modified))
def __openDatafile(self, modelResult): """Open the data file and write the header row""" # Write reset bit resetFieldMeta = FieldMetaInfo( name="reset", type=FieldMetaType.integer, special = FieldMetaSpecial.reset) self.__outputFieldsMeta.append(resetFieldMeta) # --------------...
Open the data file and write the header row
Below is the the instruction that describes the task: ### Input: Open the data file and write the header row ### Response: def __openDatafile(self, modelResult): """Open the data file and write the header row""" # Write reset bit resetFieldMeta = FieldMetaInfo( name="reset", type=FieldMeta...
def produce(txt,img,ver=5,err_crt = qrcode.constants.ERROR_CORRECT_H,bri = 1.0, cont = 1.0,\ colourful = False, rgba = (0,0,0,255),pixelate = False): """Produce QR code :txt: QR text :img: Image path / Image object :ver: QR version :err_crt: QR error correct :bri: Brightness enhance ...
Produce QR code :txt: QR text :img: Image path / Image object :ver: QR version :err_crt: QR error correct :bri: Brightness enhance :cont: Contrast enhance :colourful: If colourful mode :rgba: color to replace black :pixelate: pixelate :returns: list of produced image
Below is the the instruction that describes the task: ### Input: Produce QR code :txt: QR text :img: Image path / Image object :ver: QR version :err_crt: QR error correct :bri: Brightness enhance :cont: Contrast enhance :colourful: If colourful mode :rgba: color to replace black ...
def find_additional_rels(self, all_models): """Attempts to scan for additional relationship fields for this model based on all of the other models' structures and relationships. """ for model_name, model in iteritems(all_models): if model_name != self.name: fo...
Attempts to scan for additional relationship fields for this model based on all of the other models' structures and relationships.
Below is the the instruction that describes the task: ### Input: Attempts to scan for additional relationship fields for this model based on all of the other models' structures and relationships. ### Response: def find_additional_rels(self, all_models): """Attempts to scan for additional relationsh...
def node_get(self, arch=None, ver=None, flavor=None, count=1, retry_count=1, retry_interval=10): """ Requests specified number of nodes with the provided parameters. :param arch: Server architecture (ex: x86_64) :param ver: CentOS version (ex: 7) :param count: N...
Requests specified number of nodes with the provided parameters. :param arch: Server architecture (ex: x86_64) :param ver: CentOS version (ex: 7) :param count: Number of servers (ex: 2) :parma flavor: The flavor of machine to use (multi-arch only) :param retry_count: Number of t...
Below is the the instruction that describes the task: ### Input: Requests specified number of nodes with the provided parameters. :param arch: Server architecture (ex: x86_64) :param ver: CentOS version (ex: 7) :param count: Number of servers (ex: 2) :parma flavor: The flavor of mac...
def smart_insert(df, table, engine, minimal_size=5): """An optimized Insert strategy. **中文文档** 一种优化的将大型DataFrame中的数据, 在有IntegrityError的情况下将所有 好数据存入数据库的方法。 """ from sqlalchemy.exc import IntegrityError try: table_name = table.name except: table_name = table # 首先进行尝...
An optimized Insert strategy. **中文文档** 一种优化的将大型DataFrame中的数据, 在有IntegrityError的情况下将所有 好数据存入数据库的方法。
Below is the the instruction that describes the task: ### Input: An optimized Insert strategy. **中文文档** 一种优化的将大型DataFrame中的数据, 在有IntegrityError的情况下将所有 好数据存入数据库的方法。 ### Response: def smart_insert(df, table, engine, minimal_size=5): """An optimized Insert strategy. **中文文档** 一种优化的将大型DataFr...
def _cost_method(self, *args, **kwargs): """Calculate sparsity component of the cost This method returns the l1 norm error of the weighted wavelet coefficients Returns ------- float sparsity cost component """ cost_val = np.sum(np.abs(self.weights * se...
Calculate sparsity component of the cost This method returns the l1 norm error of the weighted wavelet coefficients Returns ------- float sparsity cost component
Below is the the instruction that describes the task: ### Input: Calculate sparsity component of the cost This method returns the l1 norm error of the weighted wavelet coefficients Returns ------- float sparsity cost component ### Response: def _cost_method(self, *args, **...
def move(self, path, raise_if_exists=False): """ Alias for ``rename()`` """ self.rename(path, raise_if_exists=raise_if_exists)
Alias for ``rename()``
Below is the the instruction that describes the task: ### Input: Alias for ``rename()`` ### Response: def move(self, path, raise_if_exists=False): """ Alias for ``rename()`` """ self.rename(path, raise_if_exists=raise_if_exists)
def create_broadcast(src_atr_name, dest_processors, dest_atr_name=None, transform_function=lambda x: x): """ This method creates a function, intended to be called as a Processor posthook, that copies some of the processor's attributes to other processors """ from functools import partial if ...
This method creates a function, intended to be called as a Processor posthook, that copies some of the processor's attributes to other processors
Below is the the instruction that describes the task: ### Input: This method creates a function, intended to be called as a Processor posthook, that copies some of the processor's attributes to other processors ### Response: def create_broadcast(src_atr_name, dest_processors, dest_atr_name=None, transform_...
def generate_api_gateway(): """Create the Blockade API Gateway REST service.""" logger.debug("[#] Setting up the API Gateway") client = boto3.client('apigateway', region_name=PRIMARY_REGION) matches = [x for x in client.get_rest_apis().get('items', list()) if x['name'] == API_GATEWAY] ...
Create the Blockade API Gateway REST service.
Below is the the instruction that describes the task: ### Input: Create the Blockade API Gateway REST service. ### Response: def generate_api_gateway(): """Create the Blockade API Gateway REST service.""" logger.debug("[#] Setting up the API Gateway") client = boto3.client('apigateway', region_name=PRI...
def cancel(self): """attempt to prevent the timer from ever running its function :returns: ``True`` if it was successful, ``False`` if the timer had already run or been cancelled """ done = self.finished.is_set() self.finished.set() return not don...
attempt to prevent the timer from ever running its function :returns: ``True`` if it was successful, ``False`` if the timer had already run or been cancelled
Below is the the instruction that describes the task: ### Input: attempt to prevent the timer from ever running its function :returns: ``True`` if it was successful, ``False`` if the timer had already run or been cancelled ### Response: def cancel(self): """attempt to preve...
def detect_worktree(cls, binary='git', subdir=None): """Detect the git working tree above cwd and return it; else, return None. :param string binary: The path to the git binary to use, 'git' by default. :param string subdir: The path to start searching for a git repo. :returns: path to the directory wh...
Detect the git working tree above cwd and return it; else, return None. :param string binary: The path to the git binary to use, 'git' by default. :param string subdir: The path to start searching for a git repo. :returns: path to the directory where the git working tree is rooted. :rtype: string
Below is the the instruction that describes the task: ### Input: Detect the git working tree above cwd and return it; else, return None. :param string binary: The path to the git binary to use, 'git' by default. :param string subdir: The path to start searching for a git repo. :returns: path to the dir...
def query(self, sql=None, filename=None, **kwargs): """ run raw sql from sql or file against. :param sql: Raw SQL query to pass directly to the connection. :type sql: string :param filename: Path to a file containing a SQL query. The path should be relative to CWD. :type filenam...
run raw sql from sql or file against. :param sql: Raw SQL query to pass directly to the connection. :type sql: string :param filename: Path to a file containing a SQL query. The path should be relative to CWD. :type filename: string :param db: `optional` Database name from your ...
Below is the the instruction that describes the task: ### Input: run raw sql from sql or file against. :param sql: Raw SQL query to pass directly to the connection. :type sql: string :param filename: Path to a file containing a SQL query. The path should be relative to CWD. :type fi...
def get_model_path(self, name): """Infer the path to the XML model name.""" name, ext = os.path.splitext(name) ext = '.xml' xmlfile = name + self.config['file_suffix'] + ext xmlfile = utils.resolve_path(xmlfile, workdir=self.config['fileio'][...
Infer the path to the XML model name.
Below is the the instruction that describes the task: ### Input: Infer the path to the XML model name. ### Response: def get_model_path(self, name): """Infer the path to the XML model name.""" name, ext = os.path.splitext(name) ext = '.xml' xmlfile = name + self.config['file_suffix...
def _combine_season_stats(self, table_rows, career_stats, all_stats_dict): """ Combine all stats for each season. Since all of the stats are spread across multiple tables, they should be combined into a single field which can be used to easily query stats at once. Param...
Combine all stats for each season. Since all of the stats are spread across multiple tables, they should be combined into a single field which can be used to easily query stats at once. Parameters ---------- table_rows : generator A generator where each elem...
Below is the the instruction that describes the task: ### Input: Combine all stats for each season. Since all of the stats are spread across multiple tables, they should be combined into a single field which can be used to easily query stats at once. Parameters ---------- ...
def add_member(self, urls): """ Add a member into the cluster. :returns: new member :rtype: :class:`.Member` """ member_add_request = etcdrpc.MemberAddRequest(peerURLs=urls) member_add_response = self.clusterstub.MemberAdd( member_add_request, ...
Add a member into the cluster. :returns: new member :rtype: :class:`.Member`
Below is the the instruction that describes the task: ### Input: Add a member into the cluster. :returns: new member :rtype: :class:`.Member` ### Response: def add_member(self, urls): """ Add a member into the cluster. :returns: new member :rtype: :class:`.Member` ...
def elasticsearch_ispartial_log(line): ''' >>> line1 = ' [2018-04-03T00:22:38,048][DEBUG][o.e.c.u.c.QueueResizingEsThreadPoolExecutor] [search17/search]: there were [2000] tasks in [809ms], avg task time [28.4micros], EWMA task execution [790nanos], [35165.36 tasks/s], optimal queue is [35165], current capacit...
>>> line1 = ' [2018-04-03T00:22:38,048][DEBUG][o.e.c.u.c.QueueResizingEsThreadPoolExecutor] [search17/search]: there were [2000] tasks in [809ms], avg task time [28.4micros], EWMA task execution [790nanos], [35165.36 tasks/s], optimal queue is [35165], current capacity [1000]' >>> line2 = ' org.elasticsearch.Reso...
Below is the the instruction that describes the task: ### Input: >>> line1 = ' [2018-04-03T00:22:38,048][DEBUG][o.e.c.u.c.QueueResizingEsThreadPoolExecutor] [search17/search]: there were [2000] tasks in [809ms], avg task time [28.4micros], EWMA task execution [790nanos], [35165.36 tasks/s], optimal queue is [35165...
def find_cycles(self): """Find cycles using Tarjan's strongly connected components algorithm.""" # Apply the Tarjan's algorithm successively until all functions are visited stack = [] data = {} order = 0 for function in compat_itervalues(self.functions): orde...
Find cycles using Tarjan's strongly connected components algorithm.
Below is the the instruction that describes the task: ### Input: Find cycles using Tarjan's strongly connected components algorithm. ### Response: def find_cycles(self): """Find cycles using Tarjan's strongly connected components algorithm.""" # Apply the Tarjan's algorithm successively until all ...
def _parse_guild_homepage(self, info_container): """ Parses the guild's homepage info. Parameters ---------- info_container: :class:`bs4.Tag` The parsed content of the information container. """ m = homepage_regex.search(info_container.text) i...
Parses the guild's homepage info. Parameters ---------- info_container: :class:`bs4.Tag` The parsed content of the information container.
Below is the the instruction that describes the task: ### Input: Parses the guild's homepage info. Parameters ---------- info_container: :class:`bs4.Tag` The parsed content of the information container. ### Response: def _parse_guild_homepage(self, info_container): """ ...
def create(cls, infile, config=None, params=None, mask=None): """Create a new instance of GTAnalysis from an analysis output file generated with `~fermipy.GTAnalysis.write_roi`. By default the new instance will inherit the configuration of the saved analysis instance. The configuration...
Create a new instance of GTAnalysis from an analysis output file generated with `~fermipy.GTAnalysis.write_roi`. By default the new instance will inherit the configuration of the saved analysis instance. The configuration may be overriden by passing a configuration file path with the `...
Below is the the instruction that describes the task: ### Input: Create a new instance of GTAnalysis from an analysis output file generated with `~fermipy.GTAnalysis.write_roi`. By default the new instance will inherit the configuration of the saved analysis instance. The configuration may...
def needs_ext(self): """ Check whether `self.app` is missing the '.js' extension and if it needs it. """ if settings.SYSTEMJS_DEFAULT_JS_EXTENSIONS: name, ext = posixpath.splitext(self.app) if not ext: return True return False
Check whether `self.app` is missing the '.js' extension and if it needs it.
Below is the the instruction that describes the task: ### Input: Check whether `self.app` is missing the '.js' extension and if it needs it. ### Response: def needs_ext(self): """ Check whether `self.app` is missing the '.js' extension and if it needs it. """ if settings.SYSTEMJS_DE...
def addProxyObject(self, obj, proxied): """ Stores a reference to the unproxied and proxied versions of C{obj} for later retrieval. @since: 0.6 """ self.proxied_objects[id(obj)] = proxied self.proxied_objects[id(proxied)] = obj
Stores a reference to the unproxied and proxied versions of C{obj} for later retrieval. @since: 0.6
Below is the the instruction that describes the task: ### Input: Stores a reference to the unproxied and proxied versions of C{obj} for later retrieval. @since: 0.6 ### Response: def addProxyObject(self, obj, proxied): """ Stores a reference to the unproxied and proxied versions of...
def get_member_details(self, username): """Returns the HPEAccount object :param username: username of account :returns: HPEAccount object if criterion matches, None otherwise """ members = self.get_members() for member in members: if member.username == userna...
Returns the HPEAccount object :param username: username of account :returns: HPEAccount object if criterion matches, None otherwise
Below is the the instruction that describes the task: ### Input: Returns the HPEAccount object :param username: username of account :returns: HPEAccount object if criterion matches, None otherwise ### Response: def get_member_details(self, username): """Returns the HPEAccount object ...
def clear_marking(self): """Clear marking from image. This does not clear loaded coordinates from memory.""" if self.marktag: try: self.canvas.delete_object_by_tag(self.marktag, redraw=False) except Exception: pass if self.markhlta...
Clear marking from image. This does not clear loaded coordinates from memory.
Below is the the instruction that describes the task: ### Input: Clear marking from image. This does not clear loaded coordinates from memory. ### Response: def clear_marking(self): """Clear marking from image. This does not clear loaded coordinates from memory.""" if self.marktag: ...
def mean_squared_error(true, pred): """L2 distance between tensors true and pred. Args: true: the ground truth image. pred: the predicted image. Returns: mean squared error between ground truth and predicted image. """ result = tf.reduce_sum( tf.squared_difference(true, pred)) / tf.to_float...
L2 distance between tensors true and pred. Args: true: the ground truth image. pred: the predicted image. Returns: mean squared error between ground truth and predicted image.
Below is the the instruction that describes the task: ### Input: L2 distance between tensors true and pred. Args: true: the ground truth image. pred: the predicted image. Returns: mean squared error between ground truth and predicted image. ### Response: def mean_squared_error(true, pred): """L2...
def wait_for_and_switch_to_alert(driver, timeout=settings.LARGE_TIMEOUT): """ Wait for a browser alert to appear, and switch to it. This should be usable as a drop-in replacement for driver.switch_to.alert when the alert box may not exist yet. @Params driver - the webdriver object (required) ...
Wait for a browser alert to appear, and switch to it. This should be usable as a drop-in replacement for driver.switch_to.alert when the alert box may not exist yet. @Params driver - the webdriver object (required) timeout - the time to wait for the alert in seconds
Below is the the instruction that describes the task: ### Input: Wait for a browser alert to appear, and switch to it. This should be usable as a drop-in replacement for driver.switch_to.alert when the alert box may not exist yet. @Params driver - the webdriver object (required) timeout - the ti...
def recursive_glob(base_directory, regex=''): """ Uses glob to find all files or folders that match the regex starting from the base_directory. Parameters ---------- base_directory: str regex: str Returns ------- files: list """ files = glob(op.join(base_directory, re...
Uses glob to find all files or folders that match the regex starting from the base_directory. Parameters ---------- base_directory: str regex: str Returns ------- files: list
Below is the the instruction that describes the task: ### Input: Uses glob to find all files or folders that match the regex starting from the base_directory. Parameters ---------- base_directory: str regex: str Returns ------- files: list ### Response: def recursive_glob(base_di...
def __int(value): '''validate an integer''' valid, _value = False, value try: _value = int(value) valid = True except ValueError: pass return (valid, _value, 'integer')
validate an integer
Below is the the instruction that describes the task: ### Input: validate an integer ### Response: def __int(value): '''validate an integer''' valid, _value = False, value try: _value = int(value) valid = True except ValueError: pass return (valid, _value, 'integer')
def patch_vary_headers(response, newheaders): """Adds (or updates) the "Vary" header in the given HttpResponse object. newheaders is a list of header names that should be in "Vary". Existing headers in "Vary" aren't removed. For information on the Vary header, see: http://www.w3.org/Protocols...
Adds (or updates) the "Vary" header in the given HttpResponse object. newheaders is a list of header names that should be in "Vary". Existing headers in "Vary" aren't removed. For information on the Vary header, see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.44
Below is the the instruction that describes the task: ### Input: Adds (or updates) the "Vary" header in the given HttpResponse object. newheaders is a list of header names that should be in "Vary". Existing headers in "Vary" aren't removed. For information on the Vary header, see: http://www....
def associate_hosting_device_with_config_agent( self, client, config_agent_id, body): """Associates a hosting_device with a config agent.""" return client.post((ConfigAgentHandlingHostingDevice.resource_path + CFG_AGENT_HOSTING_DEVICES) % config_agent_id, ...
Associates a hosting_device with a config agent.
Below is the the instruction that describes the task: ### Input: Associates a hosting_device with a config agent. ### Response: def associate_hosting_device_with_config_agent( self, client, config_agent_id, body): """Associates a hosting_device with a config agent.""" return client.post...
def security_cleanup(app, appbuilder): """ Cleanup unused permissions from views and roles. """ _appbuilder = import_application(app, appbuilder) _appbuilder.security_cleanup() click.echo(click.style("Finished security cleanup", fg="green"))
Cleanup unused permissions from views and roles.
Below is the the instruction that describes the task: ### Input: Cleanup unused permissions from views and roles. ### Response: def security_cleanup(app, appbuilder): """ Cleanup unused permissions from views and roles. """ _appbuilder = import_application(app, appbuilder) _appbuilder.secur...
def format_options(self, ctx, formatter): """Monkey-patch click's format_options method to support option categorization. """ field_opts = [] global_opts = [] local_opts = [] other_opts = [] for param in self.params: if param.name in SETTINGS_PARMS: ...
Monkey-patch click's format_options method to support option categorization.
Below is the the instruction that describes the task: ### Input: Monkey-patch click's format_options method to support option categorization. ### Response: def format_options(self, ctx, formatter): """Monkey-patch click's format_options method to support option categorization. """ field_opt...
def del_option_by_number(self, number): """ Delete an option from the message by number :type number: Integer :param number: option naumber """ for o in list(self._options): assert isinstance(o, Option) if o.number == number: self....
Delete an option from the message by number :type number: Integer :param number: option naumber
Below is the the instruction that describes the task: ### Input: Delete an option from the message by number :type number: Integer :param number: option naumber ### Response: def del_option_by_number(self, number): """ Delete an option from the message by number :type numb...
def is_done(self): """ Returns True if the read stream is done (either it's returned EOF or the pump doesn't have wait_for_output set), and the write side does not have pending bytes to send. """ return (not self.wait_for_output or self.eof) and \ not (ha...
Returns True if the read stream is done (either it's returned EOF or the pump doesn't have wait_for_output set), and the write side does not have pending bytes to send.
Below is the the instruction that describes the task: ### Input: Returns True if the read stream is done (either it's returned EOF or the pump doesn't have wait_for_output set), and the write side does not have pending bytes to send. ### Response: def is_done(self): """ Returns True...
def clean_weights(self, cutoff=1e-4, rounding=5): """ Helper method to clean the raw weights, setting any weights whose absolute values are below the cutoff to zero, and rounding the rest. :param cutoff: the lower bound, defaults to 1e-4 :type cutoff: float, optional :pa...
Helper method to clean the raw weights, setting any weights whose absolute values are below the cutoff to zero, and rounding the rest. :param cutoff: the lower bound, defaults to 1e-4 :type cutoff: float, optional :param rounding: number of decimal places to round the weights, defaults ...
Below is the the instruction that describes the task: ### Input: Helper method to clean the raw weights, setting any weights whose absolute values are below the cutoff to zero, and rounding the rest. :param cutoff: the lower bound, defaults to 1e-4 :type cutoff: float, optional :par...
def on_data(self, data): """ This is the function called by the handler object upon receipt of incoming client data. The data is passed to the responder's parser class (via the :method:`consume` method), which digests and stores the HTTP data. Upon completion of ...
This is the function called by the handler object upon receipt of incoming client data. The data is passed to the responder's parser class (via the :method:`consume` method), which digests and stores the HTTP data. Upon completion of parsing the HTTP headers, the responder ...
Below is the the instruction that describes the task: ### Input: This is the function called by the handler object upon receipt of incoming client data. The data is passed to the responder's parser class (via the :method:`consume` method), which digests and stores the HTTP data. ...
def _setTaskParsObj(self, theTask): """ Overridden version for ConfigObj. theTask can be either a .cfg file name or a ConfigObjPars object. """ # Create the ConfigObjPars obj self._taskParsObj = cfgpars.getObjectFromTaskArg(theTask, self._strict, F...
Overridden version for ConfigObj. theTask can be either a .cfg file name or a ConfigObjPars object.
Below is the the instruction that describes the task: ### Input: Overridden version for ConfigObj. theTask can be either a .cfg file name or a ConfigObjPars object. ### Response: def _setTaskParsObj(self, theTask): """ Overridden version for ConfigObj. theTask can be either a .cfg f...
def render(self, obj, opt=None): """ render a Schema/Parameter :param obj Schema/Parameter: the swagger spec object :param opt dict: render option :return: values that can be passed to Operation.__call__ :rtype: depends on type of 'obj' """ opt = self.default() i...
render a Schema/Parameter :param obj Schema/Parameter: the swagger spec object :param opt dict: render option :return: values that can be passed to Operation.__call__ :rtype: depends on type of 'obj'
Below is the the instruction that describes the task: ### Input: render a Schema/Parameter :param obj Schema/Parameter: the swagger spec object :param opt dict: render option :return: values that can be passed to Operation.__call__ :rtype: depends on type of 'obj' ### Response: def...
def tracker_print(msg): """Print message to the tracker. This function can be used to communicate the information of the progress to the tracker Parameters ---------- msg : str The message to be printed to tracker. """ if not isinstance(msg, str): msg = str(msg) _LI...
Print message to the tracker. This function can be used to communicate the information of the progress to the tracker Parameters ---------- msg : str The message to be printed to tracker.
Below is the the instruction that describes the task: ### Input: Print message to the tracker. This function can be used to communicate the information of the progress to the tracker Parameters ---------- msg : str The message to be printed to tracker. ### Response: def tracker_print(...
def createEditor(self, delegate, parent, option): """ Creates a ColorCtiEditor. For the parameters see the AbstractCti constructor documentation. """ return ColorCtiEditor(self, delegate, parent=parent)
Creates a ColorCtiEditor. For the parameters see the AbstractCti constructor documentation.
Below is the the instruction that describes the task: ### Input: Creates a ColorCtiEditor. For the parameters see the AbstractCti constructor documentation. ### Response: def createEditor(self, delegate, parent, option): """ Creates a ColorCtiEditor. For the parameters see the Abstr...
def phase_progeny_by_transmission(g): """Phase progeny genotypes from a trio or cross using Mendelian transmission. Parameters ---------- g : array_like, int, shape (n_variants, n_samples, 2) Genotype array, with parents as first two columns and progeny as remaining columns. Re...
Phase progeny genotypes from a trio or cross using Mendelian transmission. Parameters ---------- g : array_like, int, shape (n_variants, n_samples, 2) Genotype array, with parents as first two columns and progeny as remaining columns. Returns ------- g : ndarray, int8, shap...
Below is the the instruction that describes the task: ### Input: Phase progeny genotypes from a trio or cross using Mendelian transmission. Parameters ---------- g : array_like, int, shape (n_variants, n_samples, 2) Genotype array, with parents as first two columns and progeny as re...
def get_dataframe_row(self, dataset_cases, predicted_data, pdb_data, record_id, additional_prediction_data_columns): '''Create a dataframe row for a prediction.''' # Ignore derived mutations if appropriate record = dataset_cases[record_id] if self.is_this_record_a_derived_mutation(recor...
Create a dataframe row for a prediction.
Below is the the instruction that describes the task: ### Input: Create a dataframe row for a prediction. ### Response: def get_dataframe_row(self, dataset_cases, predicted_data, pdb_data, record_id, additional_prediction_data_columns): '''Create a dataframe row for a prediction.''' # Ignore deriv...
def render_pep440(vcs): """Convert git release tag into a form that is PEP440 compliant.""" if vcs is None: return None tags = vcs.split('-') # Bare version number if len(tags) == 1: return tags[0] else: return tags[0] + '+' + '.'.join(tags[1:])
Convert git release tag into a form that is PEP440 compliant.
Below is the the instruction that describes the task: ### Input: Convert git release tag into a form that is PEP440 compliant. ### Response: def render_pep440(vcs): """Convert git release tag into a form that is PEP440 compliant.""" if vcs is None: return None tags = vcs.split('-') # Bar...
def delete_fw(self, tenant_id, data): """Top level routine called when a FW is deleted. """ try: ret = self._delete_fw(tenant_id, data) return ret except Exception as exc: LOG.error("Failed to delete FW for device native, tenant " "%(tena...
Top level routine called when a FW is deleted.
Below is the the instruction that describes the task: ### Input: Top level routine called when a FW is deleted. ### Response: def delete_fw(self, tenant_id, data): """Top level routine called when a FW is deleted. """ try: ret = self._delete_fw(tenant_id, data) return ret ...
def run(self): """ This function executes planarRad using the batch file. """ """ Error when planarRad start : /bin/sh: 1: ../planarrad.py: not found """ print('Executing planarrad') # If we are not in the reverse_mode : if self.ui.tabWidget.curre...
This function executes planarRad using the batch file.
Below is the the instruction that describes the task: ### Input: This function executes planarRad using the batch file. ### Response: def run(self): """ This function executes planarRad using the batch file. """ """ Error when planarRad start : /bin/sh: 1: ../planarrad.py: ...
def next_time(self, asc=False): """Get the local time of the next schedule time this job will run. :param bool asc: Format the result with ``time.asctime()`` :returns: The epoch time or string representation of the epoch time that the job should be run next """ _time ...
Get the local time of the next schedule time this job will run. :param bool asc: Format the result with ``time.asctime()`` :returns: The epoch time or string representation of the epoch time that the job should be run next
Below is the the instruction that describes the task: ### Input: Get the local time of the next schedule time this job will run. :param bool asc: Format the result with ``time.asctime()`` :returns: The epoch time or string representation of the epoch time that the job should be run next ...