code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def xception_exit(inputs): """Xception exit flow.""" with tf.variable_scope("xception_exit"): x = inputs x_shape = x.get_shape().as_list() if x_shape[1] is None or x_shape[2] is None: length_float = tf.to_float(tf.shape(x)[1]) length_float *= tf.to_float(tf.shape(x)[2]) spatial_dim_flo...
Xception exit flow.
Below is the the instruction that describes the task: ### Input: Xception exit flow. ### Response: def xception_exit(inputs): """Xception exit flow.""" with tf.variable_scope("xception_exit"): x = inputs x_shape = x.get_shape().as_list() if x_shape[1] is None or x_shape[2] is None: length_flo...
def _convert_eq(self, eq): """WORKS INPLACE on eq """ rename = dict(enumerate(self.index)) eq['eq_sets'] = {rename[k]: {rename[x] for x in v} for k, v in eq['eq_sets'].items()} eq['sym_ops'] = {rename[k]: {rename[x]: v[x] for x in v} ...
WORKS INPLACE on eq
Below is the the instruction that describes the task: ### Input: WORKS INPLACE on eq ### Response: def _convert_eq(self, eq): """WORKS INPLACE on eq """ rename = dict(enumerate(self.index)) eq['eq_sets'] = {rename[k]: {rename[x] for x in v} for k, v in eq['e...
def load(self, specfiles=None): """Imports the specified ``fic`` files from the hard disk. :param specfiles: the name of an ms-run file or a list of names. If None all specfiles are selected. :type specfiles: None, str, [str, str] """ if specfiles is None: ...
Imports the specified ``fic`` files from the hard disk. :param specfiles: the name of an ms-run file or a list of names. If None all specfiles are selected. :type specfiles: None, str, [str, str]
Below is the the instruction that describes the task: ### Input: Imports the specified ``fic`` files from the hard disk. :param specfiles: the name of an ms-run file or a list of names. If None all specfiles are selected. :type specfiles: None, str, [str, str] ### Response: def load(se...
def printAllColorsToConsole(cls): ''' A simple enumeration of the colors to the console to help decide :) ''' for elem in cls.__dict__: # ignore specials such as __class__ or __module__ if not elem.startswith("__"): color_fmt = cls.__dict__[elem] i...
A simple enumeration of the colors to the console to help decide :)
Below is the the instruction that describes the task: ### Input: A simple enumeration of the colors to the console to help decide :) ### Response: def printAllColorsToConsole(cls): ''' A simple enumeration of the colors to the console to help decide :) ''' for elem in cls.__dict__: # ig...
def get_widget_for(self, fieldname): """Lookup the widget """ field = self.context.getField(fieldname) if not field: return None return field.widget
Lookup the widget
Below is the the instruction that describes the task: ### Input: Lookup the widget ### Response: def get_widget_for(self, fieldname): """Lookup the widget """ field = self.context.getField(fieldname) if not field: return None return field.widget
def mavgen(opts, args): """Generate mavlink message formatters and parsers (C and Python ) using options and args where args are a list of xml files. This function allows python scripts under Windows to control mavgen using the same interface as shell scripts under Unix""" xml = [] # Enable va...
Generate mavlink message formatters and parsers (C and Python ) using options and args where args are a list of xml files. This function allows python scripts under Windows to control mavgen using the same interface as shell scripts under Unix
Below is the the instruction that describes the task: ### Input: Generate mavlink message formatters and parsers (C and Python ) using options and args where args are a list of xml files. This function allows python scripts under Windows to control mavgen using the same interface as shell scripts under ...
def get_features(self, organism=None, sequence=None): """ Get the features for an organism / sequence :type organism: str :param organism: Organism Common Name :type sequence: str :param sequence: Sequence Name :rtype: dict :return: A standard apollo fe...
Get the features for an organism / sequence :type organism: str :param organism: Organism Common Name :type sequence: str :param sequence: Sequence Name :rtype: dict :return: A standard apollo feature dictionary ({"features": [{...}]})
Below is the the instruction that describes the task: ### Input: Get the features for an organism / sequence :type organism: str :param organism: Organism Common Name :type sequence: str :param sequence: Sequence Name :rtype: dict :return: A standard apollo feature...
def textrank(self, sentence, topK=20, withWeight=False, allowPOS=('ns', 'n', 'vn', 'v'), withFlag=False): """ Extract keywords from sentence using TextRank algorithm. Parameter: - topK: return how many top keywords. `None` for all possible words. - withWeight: if True, re...
Extract keywords from sentence using TextRank algorithm. Parameter: - topK: return how many top keywords. `None` for all possible words. - withWeight: if True, return a list of (word, weight); if False, return a list of words. - allowPOS: the allowed...
Below is the the instruction that describes the task: ### Input: Extract keywords from sentence using TextRank algorithm. Parameter: - topK: return how many top keywords. `None` for all possible words. - withWeight: if True, return a list of (word, weight); ...
def process_value_pairs(self, tokens, type_): """ Metadata, Values, and Validation blocks can either have string pairs or attributes Attributes will already be processed """ key, body = self.check_composite_tokens(type_, tokens) key_name = self.key_name(key) ...
Metadata, Values, and Validation blocks can either have string pairs or attributes Attributes will already be processed
Below is the the instruction that describes the task: ### Input: Metadata, Values, and Validation blocks can either have string pairs or attributes Attributes will already be processed ### Response: def process_value_pairs(self, tokens, type_): """ Metadata, Values, and Validation b...
def bottom(self, features): """Transforms features to feed into body. Args: features: dict of str to Tensor. Typically it is the preprocessed data batch after Problem's preprocess_example(). Returns: transformed_features: dict of same key-value pairs as features. The value Tens...
Transforms features to feed into body. Args: features: dict of str to Tensor. Typically it is the preprocessed data batch after Problem's preprocess_example(). Returns: transformed_features: dict of same key-value pairs as features. The value Tensors are newly transformed.
Below is the the instruction that describes the task: ### Input: Transforms features to feed into body. Args: features: dict of str to Tensor. Typically it is the preprocessed data batch after Problem's preprocess_example(). Returns: transformed_features: dict of same key-value pairs a...
def post_public(self, path, data, is_json=True): '''Make a post request requiring no auth.''' return self._post(path, data, is_json)
Make a post request requiring no auth.
Below is the the instruction that describes the task: ### Input: Make a post request requiring no auth. ### Response: def post_public(self, path, data, is_json=True): '''Make a post request requiring no auth.''' return self._post(path, data, is_json)
def get_available_references(self, datas): """ Get available manifest reference names. Every rules starting with prefix from ``nomenclature.RULE_REFERENCE`` are available references. Only name validation is performed on these references. Arguments: datas (d...
Get available manifest reference names. Every rules starting with prefix from ``nomenclature.RULE_REFERENCE`` are available references. Only name validation is performed on these references. Arguments: datas (dict): Data where to search for reference declarations. ...
Below is the the instruction that describes the task: ### Input: Get available manifest reference names. Every rules starting with prefix from ``nomenclature.RULE_REFERENCE`` are available references. Only name validation is performed on these references. Arguments: da...
def moses_multi_bleu(hypotheses, references, lowercase=False): """Calculate the bleu score for hypotheses and references using the MOSES ulti-bleu.perl script. Parameters ------------ hypotheses : numpy.array.string A numpy array of strings where each string is a single example. referen...
Calculate the bleu score for hypotheses and references using the MOSES ulti-bleu.perl script. Parameters ------------ hypotheses : numpy.array.string A numpy array of strings where each string is a single example. references : numpy.array.string A numpy array of strings where each s...
Below is the the instruction that describes the task: ### Input: Calculate the bleu score for hypotheses and references using the MOSES ulti-bleu.perl script. Parameters ------------ hypotheses : numpy.array.string A numpy array of strings where each string is a single example. referenc...
def add_query(self, name, filter, **kwargs): """Add a new query to device query service. .. code-block:: python f = api.add_query( name = "Query name", filter = { "device_id": {"$eq": "01234"}, custom_attributes = { ...
Add a new query to device query service. .. code-block:: python f = api.add_query( name = "Query name", filter = { "device_id": {"$eq": "01234"}, custom_attributes = { "foo": {"$eq": "bar"} ...
Below is the the instruction that describes the task: ### Input: Add a new query to device query service. .. code-block:: python f = api.add_query( name = "Query name", filter = { "device_id": {"$eq": "01234"}, custom_attr...
def get_dashboard_history(self, id, **kwargs): # noqa: E501 """Get the version history of a specific dashboard # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api...
Get the version history of a specific dashboard # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_dashboard_history(id, async_req=True) >>> result = thread.g...
Below is the the instruction that describes the task: ### Input: Get the version history of a specific dashboard # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.ge...
def get_hash(name, password=None): ''' Returns the hash of a certificate in the keychain. name The name of the certificate (which you can get from keychain.get_friendly_name) or the location of a p12 file. password The password that is used in the certificate. Only required if ...
Returns the hash of a certificate in the keychain. name The name of the certificate (which you can get from keychain.get_friendly_name) or the location of a p12 file. password The password that is used in the certificate. Only required if your passing a p12 file. Note: This wil...
Below is the the instruction that describes the task: ### Input: Returns the hash of a certificate in the keychain. name The name of the certificate (which you can get from keychain.get_friendly_name) or the location of a p12 file. password The password that is used in the certific...
def contains(self, time: datetime.datetime, inclusive: bool = True) -> bool: """ Does the interval contain a momentary time? Args: time: the ``datetime.datetime`` to check inclusive: use inclusive rather than exclusive range checks? """ i...
Does the interval contain a momentary time? Args: time: the ``datetime.datetime`` to check inclusive: use inclusive rather than exclusive range checks?
Below is the the instruction that describes the task: ### Input: Does the interval contain a momentary time? Args: time: the ``datetime.datetime`` to check inclusive: use inclusive rather than exclusive range checks? ### Response: def contains(self, time: datetime.datetime, ...
def set_client_cert(self, cert): """*Sets the client cert for the requests.* The cert is either a path to a .pem file, or a JSON array, or a list having the cert path and the key path. Values ``null`` and ``${None}`` can be used for clearing the cert. *Examples* | `Se...
*Sets the client cert for the requests.* The cert is either a path to a .pem file, or a JSON array, or a list having the cert path and the key path. Values ``null`` and ``${None}`` can be used for clearing the cert. *Examples* | `Set Client Cert` | ${CURDIR}/client.pem | ...
Below is the the instruction that describes the task: ### Input: *Sets the client cert for the requests.* The cert is either a path to a .pem file, or a JSON array, or a list having the cert path and the key path. Values ``null`` and ``${None}`` can be used for clearing the cert. ...
def fetch_items(self, category, **kwargs): """Fetch the bugs :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ from_date = kwargs['from_date'] logger.info("Looking for bugs: '%s' updated from '%...
Fetch the bugs :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items
Below is the the instruction that describes the task: ### Input: Fetch the bugs :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items ### Response: def fetch_items(self, category, **kwargs): """Fetch the bugs :para...
def _disable(name, started, result=True, skip_verify=False, **kwargs): ''' Disable the service ''' ret = {} if not skip_verify: # is service available? try: if not _available(name, ret): ret['result'] = True return ret except Comma...
Disable the service
Below is the the instruction that describes the task: ### Input: Disable the service ### Response: def _disable(name, started, result=True, skip_verify=False, **kwargs): ''' Disable the service ''' ret = {} if not skip_verify: # is service available? try: if not _av...
def position(self): """ Returns the current position of the motor in pulses of the rotary encoder. When the motor rotates clockwise, the position will increase. Likewise, rotating counter-clockwise causes the position to decrease. Writing will set the position to that value. ...
Returns the current position of the motor in pulses of the rotary encoder. When the motor rotates clockwise, the position will increase. Likewise, rotating counter-clockwise causes the position to decrease. Writing will set the position to that value.
Below is the the instruction that describes the task: ### Input: Returns the current position of the motor in pulses of the rotary encoder. When the motor rotates clockwise, the position will increase. Likewise, rotating counter-clockwise causes the position to decrease. Writing will set the...
def setup_icons(self, ): """Set all icons on buttons :returns: None :rtype: None :raises: None """ folder_icon = get_icon('glyphicons_144_folder_open.png', asicon=True) self.asset_open_path_tb.setIcon(folder_icon) self.shot_open_path_tb.setIcon(folder_ico...
Set all icons on buttons :returns: None :rtype: None :raises: None
Below is the the instruction that describes the task: ### Input: Set all icons on buttons :returns: None :rtype: None :raises: None ### Response: def setup_icons(self, ): """Set all icons on buttons :returns: None :rtype: None :raises: None """ ...
def epsilon_crit(self): """ returns the critical projected mass density in units of M_sun/Mpc^2 (physical units) :return: critical projected mass density """ if not hasattr(self, '_Epsilon_Crit'): const_SI = const.c ** 2 / (4 * np.pi * const.G) #c^2/(4*pi*G) in units...
returns the critical projected mass density in units of M_sun/Mpc^2 (physical units) :return: critical projected mass density
Below is the the instruction that describes the task: ### Input: returns the critical projected mass density in units of M_sun/Mpc^2 (physical units) :return: critical projected mass density ### Response: def epsilon_crit(self): """ returns the critical projected mass density in units of M_...
def assert_any_call(self, *args, **kwargs): """assert the mock has been called with the specified arguments. The assert passes if the mock has *ever* been called, unlike `assert_called_with` and `assert_called_once_with` that only pass if the call is the most recent one.""" expe...
assert the mock has been called with the specified arguments. The assert passes if the mock has *ever* been called, unlike `assert_called_with` and `assert_called_once_with` that only pass if the call is the most recent one.
Below is the the instruction that describes the task: ### Input: assert the mock has been called with the specified arguments. The assert passes if the mock has *ever* been called, unlike `assert_called_with` and `assert_called_once_with` that only pass if the call is the most recent one. #...
def calc_significand(prefix, dpd_bits, num_bits): """ prefix: High bits integer value dpd_bits: dpd encoded bits num_bits: bit length of dpd_bits """ # https://en.wikipedia.org/wiki/Decimal128_floating-point_format#Densely_packed_decimal_significand_field num_segments = num_bits // 10 se...
prefix: High bits integer value dpd_bits: dpd encoded bits num_bits: bit length of dpd_bits
Below is the the instruction that describes the task: ### Input: prefix: High bits integer value dpd_bits: dpd encoded bits num_bits: bit length of dpd_bits ### Response: def calc_significand(prefix, dpd_bits, num_bits): """ prefix: High bits integer value dpd_bits: dpd encoded bits num_bit...
def on_message(self, ws, message): """Websocket on_message event handler Saves message as RTMMessage in self._inbox """ try: data = json.loads(message) except Exception: self._set_error(message, "decode message failed") else: self._inb...
Websocket on_message event handler Saves message as RTMMessage in self._inbox
Below is the the instruction that describes the task: ### Input: Websocket on_message event handler Saves message as RTMMessage in self._inbox ### Response: def on_message(self, ws, message): """Websocket on_message event handler Saves message as RTMMessage in self._inbox """ ...
def set_link(self, link,y=0,page=-1): "Set destination of internal link" if(y==-1): y=self.y if(page==-1): page=self.page self.links[link]=[page,y]
Set destination of internal link
Below is the the instruction that describes the task: ### Input: Set destination of internal link ### Response: def set_link(self, link,y=0,page=-1): "Set destination of internal link" if(y==-1): y=self.y if(page==-1): page=self.page self.links[link]=[page,y]
def await_flush_completion(self, timeout=None): """ Mark all partitions as ready to send and block until the send is complete """ try: for batch in self._incomplete.all(): log.debug('Waiting on produce to %s', batch.produce_future.top...
Mark all partitions as ready to send and block until the send is complete
Below is the the instruction that describes the task: ### Input: Mark all partitions as ready to send and block until the send is complete ### Response: def await_flush_completion(self, timeout=None): """ Mark all partitions as ready to send and block until the send is complete """ ...
def autodiscover(): """ Auto-discover INSTALLED_APPS backbone_api.py modules. """ # This code is based off django.contrib.admin.__init__ from django.conf import settings try: # Django versions >= 1.9 from django.utils.module_loading import import_module except ImportError: ...
Auto-discover INSTALLED_APPS backbone_api.py modules.
Below is the the instruction that describes the task: ### Input: Auto-discover INSTALLED_APPS backbone_api.py modules. ### Response: def autodiscover(): """ Auto-discover INSTALLED_APPS backbone_api.py modules. """ # This code is based off django.contrib.admin.__init__ from django.conf import s...
def DeleteUser(self, user_link, options=None): """Deletes a user. :param str user_link: The link to the user entity. :param dict options: The request options for the request. :return: The deleted user. :rtype: dict """ ...
Deletes a user. :param str user_link: The link to the user entity. :param dict options: The request options for the request. :return: The deleted user. :rtype: dict
Below is the the instruction that describes the task: ### Input: Deletes a user. :param str user_link: The link to the user entity. :param dict options: The request options for the request. :return: The deleted user. :rtype: dict ### ...
def visit_image(self, node): """ Image directive """ uri = node.attributes['uri'] doc_folder = os.path.dirname(self.builder.current_docname) if uri.startswith(doc_folder): # drop docname prefix uri = uri[len(doc_folder):] if uri.startsw...
Image directive
Below is the the instruction that describes the task: ### Input: Image directive ### Response: def visit_image(self, node): """ Image directive """ uri = node.attributes['uri'] doc_folder = os.path.dirname(self.builder.current_docname) if uri.startswith(doc_folder): ...
def push_broks_to_broker(self): # pragma: no cover - not used! """Send all broks from arbiter internal list to broker The arbiter get some broks and then pushes them to all the brokers. :return: None """ someone_is_concerned = False sent = False for broker_link...
Send all broks from arbiter internal list to broker The arbiter get some broks and then pushes them to all the brokers. :return: None
Below is the the instruction that describes the task: ### Input: Send all broks from arbiter internal list to broker The arbiter get some broks and then pushes them to all the brokers. :return: None ### Response: def push_broks_to_broker(self): # pragma: no cover - not used! """Send all ...
def absent(name, force=False): ''' Ensure that a container is absent name Name of the container force : False Set to ``True`` to remove the container even if it is running Usage Examples: .. code-block:: yaml mycontainer: docker_container.absent mu...
Ensure that a container is absent name Name of the container force : False Set to ``True`` to remove the container even if it is running Usage Examples: .. code-block:: yaml mycontainer: docker_container.absent multiple_containers: docker_contain...
Below is the the instruction that describes the task: ### Input: Ensure that a container is absent name Name of the container force : False Set to ``True`` to remove the container even if it is running Usage Examples: .. code-block:: yaml mycontainer: docker_co...
def write_training_data(self, features, targets): """ Writes data dictionary to filename """ assert len(features) == len(targets) data = dict(zip(features, targets)) with open(os.path.join(self.repopath, 'training.pkl'), 'w') as fp: pickle.dump(data, fp)
Writes data dictionary to filename
Below is the the instruction that describes the task: ### Input: Writes data dictionary to filename ### Response: def write_training_data(self, features, targets): """ Writes data dictionary to filename """ assert len(features) == len(targets) data = dict(zip(features, targets)) ...
def prediction_model_dict(self): """ Converts the list of prediction_models passed in into properly formatted dictionaries :return: formatted prediction model dict """ models = {} for model in self.predictions_models: models[model.name] = model.keywords ...
Converts the list of prediction_models passed in into properly formatted dictionaries :return: formatted prediction model dict
Below is the the instruction that describes the task: ### Input: Converts the list of prediction_models passed in into properly formatted dictionaries :return: formatted prediction model dict ### Response: def prediction_model_dict(self): """ Converts the list of prediction_models passed in...
def basicauthfail(self, realm = b'all'): """ Return 401 for authentication failure. This will end the handler. """ if not isinstance(realm, bytes): realm = realm.encode('ascii') self.start_response(401, [(b'WWW-Authenticate', b'Basic realm="' + realm + b'"')]) ...
Return 401 for authentication failure. This will end the handler.
Below is the the instruction that describes the task: ### Input: Return 401 for authentication failure. This will end the handler. ### Response: def basicauthfail(self, realm = b'all'): """ Return 401 for authentication failure. This will end the handler. """ if not isinstance(realm...
def check_throttles(self, request): """ Check if request should be throttled. Raises an appropriate exception if the request is throttled. """ for throttle in self.get_throttles(): if not throttle.allow_request(request, self): self.throttled(request, t...
Check if request should be throttled. Raises an appropriate exception if the request is throttled.
Below is the the instruction that describes the task: ### Input: Check if request should be throttled. Raises an appropriate exception if the request is throttled. ### Response: def check_throttles(self, request): """ Check if request should be throttled. Raises an appropriate excep...
def video_category(self): """doc: http://open.youku.com/docs/doc?id=90 """ url = 'https://openapi.youku.com/v2/schemas/video/category.json' r = requests.get(url) check_error(r) return r.json()
doc: http://open.youku.com/docs/doc?id=90
Below is the the instruction that describes the task: ### Input: doc: http://open.youku.com/docs/doc?id=90 ### Response: def video_category(self): """doc: http://open.youku.com/docs/doc?id=90 """ url = 'https://openapi.youku.com/v2/schemas/video/category.json' r = requests.get(url) ...
def add_code_cell(work_notebook, code): """Add a code cell to the notebook Parameters ---------- code : str Cell content """ code_cell = { "cell_type": "code", "execution_count": None, "metadata": {"collapsed": False}, "outputs": [], "source": [c...
Add a code cell to the notebook Parameters ---------- code : str Cell content
Below is the the instruction that describes the task: ### Input: Add a code cell to the notebook Parameters ---------- code : str Cell content ### Response: def add_code_cell(work_notebook, code): """Add a code cell to the notebook Parameters ---------- code : str Cell...
def _get_acceleration(self, data): '''Return acceleration mG''' if (data[7:8] == 0x7FFF or data[9:10] == 0x7FFF or data[11:12] == 0x7FFF): return (None, None, None) acc_x = twos_complement((data[7] << 8) + data[8], 16) acc_y = twos_complement(...
Return acceleration mG
Below is the the instruction that describes the task: ### Input: Return acceleration mG ### Response: def _get_acceleration(self, data): '''Return acceleration mG''' if (data[7:8] == 0x7FFF or data[9:10] == 0x7FFF or data[11:12] == 0x7FFF): return (None, ...
def start(self): """ start """ def main_thread(): # create resp, req thread pool self._create_thread_pool() # start connection, this will block until stop() self.conn_thread = Thread(target=self._conn.connect) self.conn_thread.d...
start
Below is the the instruction that describes the task: ### Input: start ### Response: def start(self): """ start """ def main_thread(): # create resp, req thread pool self._create_thread_pool() # start connection, this will block until stop() ...
def calc_fracrain_v1(self): """Determine the temperature-dependent fraction of (liquid) rainfall and (total) precipitation. Required control parameters: |NmbZones| |TT|, |TTInt| Required flux sequence: |TC| Calculated flux sequences: |FracRain| Basic equation: ...
Determine the temperature-dependent fraction of (liquid) rainfall and (total) precipitation. Required control parameters: |NmbZones| |TT|, |TTInt| Required flux sequence: |TC| Calculated flux sequences: |FracRain| Basic equation: :math:`FracRain = \\frac{TC-(T...
Below is the the instruction that describes the task: ### Input: Determine the temperature-dependent fraction of (liquid) rainfall and (total) precipitation. Required control parameters: |NmbZones| |TT|, |TTInt| Required flux sequence: |TC| Calculated flux sequences: ...
def _raise_error(self, status_code, raw_data): """ Locate appropriate exception and raise it. """ error_message = raw_data additional_info = None try: additional_info = json.loads(raw_data) error_message = additional_info.get('error', error_message...
Locate appropriate exception and raise it.
Below is the the instruction that describes the task: ### Input: Locate appropriate exception and raise it. ### Response: def _raise_error(self, status_code, raw_data): """ Locate appropriate exception and raise it. """ error_message = raw_data additional_info = None ...
def extend(self, table, keys=None): """Extends all rows in the texttable. The rows are extended with the new columns from the table. Args: table: A texttable, the table to extend this table by. keys: A set, the set of columns to use as the key. If None, the row index is used. ...
Extends all rows in the texttable. The rows are extended with the new columns from the table. Args: table: A texttable, the table to extend this table by. keys: A set, the set of columns to use as the key. If None, the row index is used. Raises: IndexError: If key is not a valid...
Below is the the instruction that describes the task: ### Input: Extends all rows in the texttable. The rows are extended with the new columns from the table. Args: table: A texttable, the table to extend this table by. keys: A set, the set of columns to use as the key. If None, the ro...
def color_scale_HSV(c: Color, scoef: float, vcoef: float) -> None: """Scale a color's saturation and value. Does not return a new Color. ``c`` is modified inplace. Args: c (Union[Color, List[int]]): A Color instance, or an [r, g, b] list. scoef (float): Saturation multiplier, from 0 to 1....
Scale a color's saturation and value. Does not return a new Color. ``c`` is modified inplace. Args: c (Union[Color, List[int]]): A Color instance, or an [r, g, b] list. scoef (float): Saturation multiplier, from 0 to 1. Use 1 to keep current saturation. vcoef (f...
Below is the the instruction that describes the task: ### Input: Scale a color's saturation and value. Does not return a new Color. ``c`` is modified inplace. Args: c (Union[Color, List[int]]): A Color instance, or an [r, g, b] list. scoef (float): Saturation multiplier, from 0 to 1. ...
def write_file(path, content, mode='w'): # type: (Text, Union[Text,bytes], Text) -> None """ --pretend aware file writing. You can always write files manually but you should always handle the --pretend case. Args: path (str): content (str): mode (str): """ from pelt...
--pretend aware file writing. You can always write files manually but you should always handle the --pretend case. Args: path (str): content (str): mode (str):
Below is the the instruction that describes the task: ### Input: --pretend aware file writing. You can always write files manually but you should always handle the --pretend case. Args: path (str): content (str): mode (str): ### Response: def write_file(path, content, mode='w'...
def decode(tokens): """Decode a list of tokens to a unicode string. Args: tokens: a list of Unicode strings Returns: a unicode string """ token_is_alnum = [t[0] in _ALPHANUMERIC_CHAR_SET for t in tokens] ret = [] for i, token in enumerate(tokens): if i > 0 and token_is_alnum[i - 1] and token_...
Decode a list of tokens to a unicode string. Args: tokens: a list of Unicode strings Returns: a unicode string
Below is the the instruction that describes the task: ### Input: Decode a list of tokens to a unicode string. Args: tokens: a list of Unicode strings Returns: a unicode string ### Response: def decode(tokens): """Decode a list of tokens to a unicode string. Args: tokens: a list of Unicode str...
def parse_classname(self, tup_tree): """ Parse a CLASSNAME element and return the class path it represents as a CIMClassName object. :: <!ELEMENT CLASSNAME EMPTY> <!ATTLIST CLASSNAME %CIMName;> Returns: CIMClassName object ...
Parse a CLASSNAME element and return the class path it represents as a CIMClassName object. :: <!ELEMENT CLASSNAME EMPTY> <!ATTLIST CLASSNAME %CIMName;> Returns: CIMClassName object (without namespace or host)
Below is the the instruction that describes the task: ### Input: Parse a CLASSNAME element and return the class path it represents as a CIMClassName object. :: <!ELEMENT CLASSNAME EMPTY> <!ATTLIST CLASSNAME %CIMName;> Returns: CIMClass...
def start_kline_socket(self, symbol, callback, interval=Client.KLINE_INTERVAL_1MINUTE): """Start a websocket for symbol kline data https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#klinecandlestick-streams :param symbol: required :type symb...
Start a websocket for symbol kline data https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#klinecandlestick-streams :param symbol: required :type symbol: str :param callback: callback function to handle messages :type callback: funct...
Below is the the instruction that describes the task: ### Input: Start a websocket for symbol kline data https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#klinecandlestick-streams :param symbol: required :type symbol: str :param callbac...
def _set_vcs_cluster_type_info(self, v, load=False): """ Setter method for vcs_cluster_type_info, mapped from YANG variable /brocade_vcs_rpc/show_vcs/output/vcs_cluster_type_info (vcs-cluster-type) If this variable is read-only (config: false) in the source YANG file, then _set_vcs_cluster_type_info is ...
Setter method for vcs_cluster_type_info, mapped from YANG variable /brocade_vcs_rpc/show_vcs/output/vcs_cluster_type_info (vcs-cluster-type) If this variable is read-only (config: false) in the source YANG file, then _set_vcs_cluster_type_info is considered as a private method. Backends looking to populate ...
Below is the the instruction that describes the task: ### Input: Setter method for vcs_cluster_type_info, mapped from YANG variable /brocade_vcs_rpc/show_vcs/output/vcs_cluster_type_info (vcs-cluster-type) If this variable is read-only (config: false) in the source YANG file, then _set_vcs_cluster_type_info...
def check(self, check_all=True, do_reload=True): """Check whether some modules need to be reloaded.""" with enaml.imports(): super(EnamlReloader, self).check(check_all=check_all, do_reload=do_reload)
Check whether some modules need to be reloaded.
Below is the the instruction that describes the task: ### Input: Check whether some modules need to be reloaded. ### Response: def check(self, check_all=True, do_reload=True): """Check whether some modules need to be reloaded.""" with enaml.imports(): super(EnamlReloader, self).check(ch...
def convert_choices_to_dict(choices): """ Takes a list of tuples and converts it to a list of dictionaries of where each dictionary has a value and text key. This is the expected format of question choices to be returned by self.ask() :param convert_choices_to_dict: :type conver...
Takes a list of tuples and converts it to a list of dictionaries of where each dictionary has a value and text key. This is the expected format of question choices to be returned by self.ask() :param convert_choices_to_dict: :type convert_choices_to_dict: list :return: ...
Below is the the instruction that describes the task: ### Input: Takes a list of tuples and converts it to a list of dictionaries of where each dictionary has a value and text key. This is the expected format of question choices to be returned by self.ask() :param convert_choices_to_dict: ...
def partial_fit(self, X): """Train model based on mini-batch of input data. Return cost of mini-batch. """ opt, cost = self.sess.run((self.optimizer, self.cost), feed_dict={self.x: X}) return cost
Train model based on mini-batch of input data. Return cost of mini-batch.
Below is the the instruction that describes the task: ### Input: Train model based on mini-batch of input data. Return cost of mini-batch. ### Response: def partial_fit(self, X): """Train model based on mini-batch of input data. Return cost of mini-batch. """ ...
def update_observation(observation_id: int, params: Dict[str, Any], access_token: str) -> List[Dict[str, Any]]: """ Update a single observation. See https://www.inaturalist.org/pages/api+reference#put-observations-id :param observation_id: the ID of the observation to update :param params: to be passed...
Update a single observation. See https://www.inaturalist.org/pages/api+reference#put-observations-id :param observation_id: the ID of the observation to update :param params: to be passed to iNaturalist API :param access_token: the access token, as returned by :func:`get_access_token()` :return: iNatu...
Below is the the instruction that describes the task: ### Input: Update a single observation. See https://www.inaturalist.org/pages/api+reference#put-observations-id :param observation_id: the ID of the observation to update :param params: to be passed to iNaturalist API :param access_token: the access...
def resample(grid, wl, flux): """ Resample spectrum onto desired grid """ flux_rs = (interpolate.interp1d(wl, flux))(grid) return flux_rs
Resample spectrum onto desired grid
Below is the the instruction that describes the task: ### Input: Resample spectrum onto desired grid ### Response: def resample(grid, wl, flux): """ Resample spectrum onto desired grid """ flux_rs = (interpolate.interp1d(wl, flux))(grid) return flux_rs
def data_nodes(self): """ Returns all data nodes of the dispatcher. :return: All data nodes of the dispatcher. :rtype: dict[str, dict] """ return {k: v for k, v in self.nodes.items() if v['type'] == 'data'}
Returns all data nodes of the dispatcher. :return: All data nodes of the dispatcher. :rtype: dict[str, dict]
Below is the the instruction that describes the task: ### Input: Returns all data nodes of the dispatcher. :return: All data nodes of the dispatcher. :rtype: dict[str, dict] ### Response: def data_nodes(self): """ Returns all data nodes of the dispatcher. :retu...
def unpack_results( data: bytes, repetitions: int, key_sizes: Sequence[Tuple[str, int]] ) -> Dict[str, np.ndarray]: """Unpack data from a bitstring into individual measurement results. Args: data: Packed measurement results, in the form <rep0><rep1>... where each rep...
Unpack data from a bitstring into individual measurement results. Args: data: Packed measurement results, in the form <rep0><rep1>... where each repetition is <key0_0>..<key0_{size0-1}><key1_0>... with bits packed in little-endian order in each byte. repetitions: number of r...
Below is the the instruction that describes the task: ### Input: Unpack data from a bitstring into individual measurement results. Args: data: Packed measurement results, in the form <rep0><rep1>... where each repetition is <key0_0>..<key0_{size0-1}><key1_0>... with bits packed ...
def find_faces(self, image, draw_box=False): """Uses a haarcascade to detect faces inside an image. Args: image: The image. draw_box: If True, the image will be marked with a rectangle. Return: The faces as returned by OpenCV's detectMultiScale method for ...
Uses a haarcascade to detect faces inside an image. Args: image: The image. draw_box: If True, the image will be marked with a rectangle. Return: The faces as returned by OpenCV's detectMultiScale method for cascades.
Below is the the instruction that describes the task: ### Input: Uses a haarcascade to detect faces inside an image. Args: image: The image. draw_box: If True, the image will be marked with a rectangle. Return: The faces as returned by OpenCV's detectMultiScale ...
def init_default_config(self, path): ''' Initialize the config object and load the default configuration. The path to the config file must be provided. The name of the application is read from the config file. The config file stores the description and the default values for ...
Initialize the config object and load the default configuration. The path to the config file must be provided. The name of the application is read from the config file. The config file stores the description and the default values for all configurations including the appl...
Below is the the instruction that describes the task: ### Input: Initialize the config object and load the default configuration. The path to the config file must be provided. The name of the application is read from the config file. The config file stores the description and the...
def set_style(self): """ Set font style with the following attributes: 'foreground_color', 'background_color', 'italic', 'bold' and 'underline' """ if self.current_format is None: assert self.base_format is not None self.current_format = QTextCharF...
Set font style with the following attributes: 'foreground_color', 'background_color', 'italic', 'bold' and 'underline'
Below is the the instruction that describes the task: ### Input: Set font style with the following attributes: 'foreground_color', 'background_color', 'italic', 'bold' and 'underline' ### Response: def set_style(self): """ Set font style with the following attributes: 'foreg...
def normalize(body_part_tup,): """Normalize a tuple of BodyPart objects to a string. Normalization is done by sorting the body_parts by the Content- Disposition headers, which is typically on the form, ``form-data; name="name_of_part``. """ return '\n\n'.join( [ '{}\n\n{}'.form...
Normalize a tuple of BodyPart objects to a string. Normalization is done by sorting the body_parts by the Content- Disposition headers, which is typically on the form, ``form-data; name="name_of_part``.
Below is the the instruction that describes the task: ### Input: Normalize a tuple of BodyPart objects to a string. Normalization is done by sorting the body_parts by the Content- Disposition headers, which is typically on the form, ``form-data; name="name_of_part``. ### Response: def normalize(body_part_...
def run_subprocess(command, cwd=None, stdout=None, stderr=None, shell=False, beat_freq=None): """ Parameters ---------- command: command cwd: current working directory stdout: output info stream (must have 'write' method) stderr: output error stream (must have 'write' method) shell: see ...
Parameters ---------- command: command cwd: current working directory stdout: output info stream (must have 'write' method) stderr: output error stream (must have 'write' method) shell: see subprocess.Popen beat_freq: if not none, stdout will be used at least every beat_freq (in seconds)
Below is the the instruction that describes the task: ### Input: Parameters ---------- command: command cwd: current working directory stdout: output info stream (must have 'write' method) stderr: output error stream (must have 'write' method) shell: see subprocess.Popen beat_freq: if no...
def _shares_exec_prefix(basedir): ''' Whether a give base directory is on the system exex prefix ''' import sys prefix = sys.exec_prefix return (prefix is not None and basedir.startswith(prefix))
Whether a give base directory is on the system exex prefix
Below is the the instruction that describes the task: ### Input: Whether a give base directory is on the system exex prefix ### Response: def _shares_exec_prefix(basedir): ''' Whether a give base directory is on the system exex prefix ''' import sys prefix = sys.exec_prefix return (prefix is n...
def create(self, email, device_name, passphrase=None, api_token=None, redirect_uri=None, **kwargs): """Create a new User object and add it to this Users collection. In addition to creating a user, this call will create a device for that user, whose device_token will be returned f...
Create a new User object and add it to this Users collection. In addition to creating a user, this call will create a device for that user, whose device_token will be returned from this call. Store the device_token, as it's required to complete Gem-Device authentication after the user a...
Below is the the instruction that describes the task: ### Input: Create a new User object and add it to this Users collection. In addition to creating a user, this call will create a device for that user, whose device_token will be returned from this call. Store the device_token, as it's re...
def spia_matrices_to_excel(spia_matrices: Mapping[str, pd.DataFrame], path: str) -> None: """Export a SPIA data dictionary into an Excel sheet at the given path. .. note:: # The R import should add the values: # ["nodes"] from the columns # ["title"] from the name of the file #...
Export a SPIA data dictionary into an Excel sheet at the given path. .. note:: # The R import should add the values: # ["nodes"] from the columns # ["title"] from the name of the file # ["NumberOfReactions"] set to "0"
Below is the the instruction that describes the task: ### Input: Export a SPIA data dictionary into an Excel sheet at the given path. .. note:: # The R import should add the values: # ["nodes"] from the columns # ["title"] from the name of the file # ["NumberOfReactions"] set t...
def _run_env(self): """ Augment the current environment providing the PYTHONUSERBASE. """ env = dict(os.environ) env.update( getattr(self, 'env', {}), PYTHONUSERBASE=self.env_path, PIP_USER="1", ) self._disable_venv(env) ...
Augment the current environment providing the PYTHONUSERBASE.
Below is the the instruction that describes the task: ### Input: Augment the current environment providing the PYTHONUSERBASE. ### Response: def _run_env(self): """ Augment the current environment providing the PYTHONUSERBASE. """ env = dict(os.environ) env.update( ...
def p_casecontent_statement(self, p): 'casecontent_statement : casecontent_condition COLON basic_statement' p[0] = Case(p[1], p[3], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
casecontent_statement : casecontent_condition COLON basic_statement
Below is the the instruction that describes the task: ### Input: casecontent_statement : casecontent_condition COLON basic_statement ### Response: def p_casecontent_statement(self, p): 'casecontent_statement : casecontent_condition COLON basic_statement' p[0] = Case(p[1], p[3], lineno=p.lineno(1)) ...
def write(self, output): """ Writes specified text to the underlying stream Parameters ---------- output bytes-like object Bytes to write """ self._stream.write(output) if self._auto_flush: self._stream.flush()
Writes specified text to the underlying stream Parameters ---------- output bytes-like object Bytes to write
Below is the the instruction that describes the task: ### Input: Writes specified text to the underlying stream Parameters ---------- output bytes-like object Bytes to write ### Response: def write(self, output): """ Writes specified text to the underlying strea...
def L(self,*args,**kwargs): """ NAME: L PURPOSE: calculate the angular momentum INPUT: (none) OUTPUT: angular momentum HISTORY: 2010-09-15 - Written - Bovy (NYU) """ #Make sure you are not using physic...
NAME: L PURPOSE: calculate the angular momentum INPUT: (none) OUTPUT: angular momentum HISTORY: 2010-09-15 - Written - Bovy (NYU)
Below is the the instruction that describes the task: ### Input: NAME: L PURPOSE: calculate the angular momentum INPUT: (none) OUTPUT: angular momentum HISTORY: 2010-09-15 - Written - Bovy (NYU) ### Response: def L(self,*args,**...
def metadata_add_description(self): """ Metadata: add description """ service_description = {} if (self.args.json): service_description = json.loads(self.args.json) if (self.args.url): if "url" in service_description: raise Exception("json service ...
Metadata: add description
Below is the the instruction that describes the task: ### Input: Metadata: add description ### Response: def metadata_add_description(self): """ Metadata: add description """ service_description = {} if (self.args.json): service_description = json.loads(self.args.json) i...
def FromReadings(cls, uuid, readings, root_key=AuthProvider.NoKey, signer=None, report_id=IOTileReading.InvalidReadingID, selector=0xFFFF, streamer=0, sent_timestamp=0): """Generate an instance of the report format from a list of readings and a uuid. The signed list report is creat...
Generate an instance of the report format from a list of readings and a uuid. The signed list report is created using the passed readings and signed using the specified method and AuthProvider. If no auth provider is specified, the report is signed using the default authorization chain. ...
Below is the the instruction that describes the task: ### Input: Generate an instance of the report format from a list of readings and a uuid. The signed list report is created using the passed readings and signed using the specified method and AuthProvider. If no auth provider is specified, the r...
def get_max_ptrm_check(ptrm_checks_included_temps, ptrm_checks_all_temps, ptrm_x, t_Arai, x_Arai): """ input: ptrm_checks_included_temps, ptrm_checks_all_temps, ptrm_x, t_Arai, x_Arai. sorts through included ptrm_checks and finds the largest ptrm check diff, the sum of the total diffs, and the perce...
input: ptrm_checks_included_temps, ptrm_checks_all_temps, ptrm_x, t_Arai, x_Arai. sorts through included ptrm_checks and finds the largest ptrm check diff, the sum of the total diffs, and the percentage of the largest check / original measurement at that temperature step output: max_diff, sum_diffs, che...
Below is the the instruction that describes the task: ### Input: input: ptrm_checks_included_temps, ptrm_checks_all_temps, ptrm_x, t_Arai, x_Arai. sorts through included ptrm_checks and finds the largest ptrm check diff, the sum of the total diffs, and the percentage of the largest check / original meas...
def cmRecall(cm, average=True): """ Calculates recall using :class:`~ignite.metrics.ConfusionMatrix` metric. Args: cm (ConfusionMatrix): instance of confusion matrix metric average (bool, optional): if True metric value is averaged over all classes Returns: MetricsLambda """ ...
Calculates recall using :class:`~ignite.metrics.ConfusionMatrix` metric. Args: cm (ConfusionMatrix): instance of confusion matrix metric average (bool, optional): if True metric value is averaged over all classes Returns: MetricsLambda
Below is the the instruction that describes the task: ### Input: Calculates recall using :class:`~ignite.metrics.ConfusionMatrix` metric. Args: cm (ConfusionMatrix): instance of confusion matrix metric average (bool, optional): if True metric value is averaged over all classes Returns: ...
def set_state(self, site, timestamp=None): """Write status dict to client status file. FIXME - should have some file lock to avoid race """ parser = ConfigParser() parser.read(self.status_file) status_section = 'incremental' if (not parser.has_section(status_sect...
Write status dict to client status file. FIXME - should have some file lock to avoid race
Below is the the instruction that describes the task: ### Input: Write status dict to client status file. FIXME - should have some file lock to avoid race ### Response: def set_state(self, site, timestamp=None): """Write status dict to client status file. FIXME - should have some file loc...
def get_blast(pdb_id, chain_id='A'): """ Return BLAST search results for a given PDB ID The key of the output dict())that outputs the full search results is 'BlastOutput_iterations' To get a list of just the results without the metadata of the search use: hits = full_results['BlastOutput_iterat...
Return BLAST search results for a given PDB ID The key of the output dict())that outputs the full search results is 'BlastOutput_iterations' To get a list of just the results without the metadata of the search use: hits = full_results['BlastOutput_iterations']['Iteration']['Iteration_hits']['Hit'] ...
Below is the the instruction that describes the task: ### Input: Return BLAST search results for a given PDB ID The key of the output dict())that outputs the full search results is 'BlastOutput_iterations' To get a list of just the results without the metadata of the search use: hits = full_results...
def check_include_exclude(attributes): """Check __include__ and __exclude__ attributes. :type attributes: dict """ include = attributes.get('__include__', tuple()) exclude = attributes.get('__exclude__', tuple()) if not isinstance(include, tuple): raise Type...
Check __include__ and __exclude__ attributes. :type attributes: dict
Below is the the instruction that describes the task: ### Input: Check __include__ and __exclude__ attributes. :type attributes: dict ### Response: def check_include_exclude(attributes): """Check __include__ and __exclude__ attributes. :type attributes: dict """ include = ...
def get_sampletype_info(self, obj): """Returns the info for a Sample Type """ info = self.get_base_info(obj) # Bika Setup folder bika_setup = api.get_bika_setup() # bika samplepoints bika_samplepoints = bika_setup.bika_samplepoints bika_samplepoints_uid ...
Returns the info for a Sample Type
Below is the the instruction that describes the task: ### Input: Returns the info for a Sample Type ### Response: def get_sampletype_info(self, obj): """Returns the info for a Sample Type """ info = self.get_base_info(obj) # Bika Setup folder bika_setup = api.get_bika_setup...
def templates(self): """Iterate over the defined Templates.""" template = lib.EnvGetNextDeftemplate(self._env, ffi.NULL) while template != ffi.NULL: yield Template(self._env, template) template = lib.EnvGetNextDeftemplate(self._env, template)
Iterate over the defined Templates.
Below is the the instruction that describes the task: ### Input: Iterate over the defined Templates. ### Response: def templates(self): """Iterate over the defined Templates.""" template = lib.EnvGetNextDeftemplate(self._env, ffi.NULL) while template != ffi.NULL: yield Template...
def validate_field_matches_type(field, value, field_type, select_items=None, _min=None, _max=None): """Validate a config field against a specific type.""" if (field_type == defs.TEXT_TYPE and not isinstance(value, six.string_types)) or \ (field_type == defs.STRING_TYPE and not isinstance(value, six.strin...
Validate a config field against a specific type.
Below is the the instruction that describes the task: ### Input: Validate a config field against a specific type. ### Response: def validate_field_matches_type(field, value, field_type, select_items=None, _min=None, _max=None): """Validate a config field against a specific type.""" if (field_type == defs.T...
def get(self, name: Text, final: C) -> C: """ Get the function to call which will run all middlewares. :param name: Name of the function to be called :param final: Function to call at the bottom of the stack (that's the one provided by the implementer). :re...
Get the function to call which will run all middlewares. :param name: Name of the function to be called :param final: Function to call at the bottom of the stack (that's the one provided by the implementer). :return:
Below is the the instruction that describes the task: ### Input: Get the function to call which will run all middlewares. :param name: Name of the function to be called :param final: Function to call at the bottom of the stack (that's the one provided by the implementer). ...
def clone(self): ''' Returns a shallow copy of the current instance, except that all variables are deep-cloned. ''' clone = copy(self) clone.variables = {k: v.clone() for (k, v) in self.variables.items()} return clone
Returns a shallow copy of the current instance, except that all variables are deep-cloned.
Below is the the instruction that describes the task: ### Input: Returns a shallow copy of the current instance, except that all variables are deep-cloned. ### Response: def clone(self): ''' Returns a shallow copy of the current instance, except that all variables are deep-cloned. '...
def _run_link(self, stream=sys.stdout, dry_run=False, stage_files=True, resubmit_failed=False): """Internal function that actually runs this link. This checks if input and output files are present. If input files are missing this will raise `OSError` if dry_run is False ...
Internal function that actually runs this link. This checks if input and output files are present. If input files are missing this will raise `OSError` if dry_run is False If all output files are present this will skip execution. Parameters ----------- stream : `file` ...
Below is the the instruction that describes the task: ### Input: Internal function that actually runs this link. This checks if input and output files are present. If input files are missing this will raise `OSError` if dry_run is False If all output files are present this will skip execut...
def dasopr(fname): """ Open a DAS file for reading. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dasopr_c.html :param fname: Name of a DAS file to be opened. :type fname: str :return: Handle assigned to the opened DAS file. :rtype: int """ fname = stypes.stringToCharP(fn...
Open a DAS file for reading. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dasopr_c.html :param fname: Name of a DAS file to be opened. :type fname: str :return: Handle assigned to the opened DAS file. :rtype: int
Below is the the instruction that describes the task: ### Input: Open a DAS file for reading. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dasopr_c.html :param fname: Name of a DAS file to be opened. :type fname: str :return: Handle assigned to the opened DAS file. :rtype: int ### R...
def enable_mfa_device(self, user_name, serial_number, authentication_code_1, authentication_code_2): """Enable MFA Device for user.""" user = self.get_user(user_name) if serial_number in user....
Enable MFA Device for user.
Below is the the instruction that describes the task: ### Input: Enable MFA Device for user. ### Response: def enable_mfa_device(self, user_name, serial_number, authentication_code_1, authentication_code_2): ...
def s3_download(url, dst): # type: (str, str) -> None """Download a file from S3. Args: url (str): the s3 url of the file. dst (str): the destination where the file will be saved. """ url = parse.urlparse(url) if url.scheme != 's3': raise ValueError("Expecting 's3' scheme,...
Download a file from S3. Args: url (str): the s3 url of the file. dst (str): the destination where the file will be saved.
Below is the the instruction that describes the task: ### Input: Download a file from S3. Args: url (str): the s3 url of the file. dst (str): the destination where the file will be saved. ### Response: def s3_download(url, dst): # type: (str, str) -> None """Download a file from S3. ...
def job_terminate(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /job-xxxx/terminate API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Applets-and-Entry-Points#API-method%3A-%2Fjob-xxxx%2Fterminate """ return DXHTTPRequest('/%s/terminate' ...
Invokes the /job-xxxx/terminate API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Applets-and-Entry-Points#API-method%3A-%2Fjob-xxxx%2Fterminate
Below is the the instruction that describes the task: ### Input: Invokes the /job-xxxx/terminate API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Applets-and-Entry-Points#API-method%3A-%2Fjob-xxxx%2Fterminate ### Response: def job_terminate(object_id, input_params={}, always_...
def __liftover_coordinates_genomic_deletions(self, intersecting_region): """ A 'private' helper member function to perform liftover in coordinate space when the length of the genomic match is smaller than the concensus match. We assume the genomic region contains deletions. In this case, we uniformly ...
A 'private' helper member function to perform liftover in coordinate space when the length of the genomic match is smaller than the concensus match. We assume the genomic region contains deletions. In this case, we uniformly distribute the deletions (gaps) through the genomic region. This is the trickie...
Below is the the instruction that describes the task: ### Input: A 'private' helper member function to perform liftover in coordinate space when the length of the genomic match is smaller than the concensus match. We assume the genomic region contains deletions. In this case, we uniformly distribute the...
def rawData(self, fileAdres=None): # skip skiprows skiprows = None skip_from = [b'Field', b'Moment'] with open(fileAdres, 'rb') as fr: #f = fr.read() for i, line in enumerate(fr, 1): # print(line.split()) if skip_from == line.split(...
#================================================= /datainterval_H/_M /slice the measured data into pieces /for every measured FORC #=================================================
Below is the the instruction that describes the task: ### Input: #================================================= /datainterval_H/_M /slice the measured data into pieces /for every measured FORC #================================================= ### Response: def rawData(self, fil...
def _get_all(self): """ Get all users from db and turn into list of dicts """ return [self._to_dict(row) for row in models.User.objects.all()]
Get all users from db and turn into list of dicts
Below is the the instruction that describes the task: ### Input: Get all users from db and turn into list of dicts ### Response: def _get_all(self): """ Get all users from db and turn into list of dicts """ return [self._to_dict(row) for row in models.User.objects.all()]
def _get_access_token(self): """ Get IAM access token using API key. """ err = 'Failed to contact IAM token service' try: resp = super(IAMSession, self).request( 'POST', self._token_url, auth=self._token_auth, ...
Get IAM access token using API key.
Below is the the instruction that describes the task: ### Input: Get IAM access token using API key. ### Response: def _get_access_token(self): """ Get IAM access token using API key. """ err = 'Failed to contact IAM token service' try: resp = super(IAMSession, s...
def handle(self, request: HttpRequest) -> HttpResponse: """ Prepares for the CallBackResolver and handles the response and exceptions :param request HttpRequest :rtype: HttpResponse """ self.__request_start = datetime.now() self.__request = request self.__...
Prepares for the CallBackResolver and handles the response and exceptions :param request HttpRequest :rtype: HttpResponse
Below is the the instruction that describes the task: ### Input: Prepares for the CallBackResolver and handles the response and exceptions :param request HttpRequest :rtype: HttpResponse ### Response: def handle(self, request: HttpRequest) -> HttpResponse: """ Prepares for the CallB...
def parse(filename, format=u"Jæren Sparebank", encoding="latin1"): """Parses bank CSV file and returns Transactions instance. Args: filename: Path to CSV file to read. format: CSV format; one of the entries in `elv.formats`. encoding: The CSV file encoding. Returns: A ``Tra...
Parses bank CSV file and returns Transactions instance. Args: filename: Path to CSV file to read. format: CSV format; one of the entries in `elv.formats`. encoding: The CSV file encoding. Returns: A ``Transactions`` object.
Below is the the instruction that describes the task: ### Input: Parses bank CSV file and returns Transactions instance. Args: filename: Path to CSV file to read. format: CSV format; one of the entries in `elv.formats`. encoding: The CSV file encoding. Returns: A ``Transact...
def _send_float(self,value): """ Return a float as a IEEE 754 format bytes object. """ # convert to float. this will throw a ValueError if the type is not # readily converted if type(value) != float: value = float(value) # Range check if val...
Return a float as a IEEE 754 format bytes object.
Below is the the instruction that describes the task: ### Input: Return a float as a IEEE 754 format bytes object. ### Response: def _send_float(self,value): """ Return a float as a IEEE 754 format bytes object. """ # convert to float. this will throw a ValueError if the type is no...
def _CreateLineStringForShape(self, parent, shape): """Create a KML LineString using coordinates from a shape. Args: parent: The parent ElementTree.Element instance. shape: The transitfeed.Shape instance. Returns: The LineString ElementTree.Element instance or None if coordinate_list is ...
Create a KML LineString using coordinates from a shape. Args: parent: The parent ElementTree.Element instance. shape: The transitfeed.Shape instance. Returns: The LineString ElementTree.Element instance or None if coordinate_list is empty.
Below is the the instruction that describes the task: ### Input: Create a KML LineString using coordinates from a shape. Args: parent: The parent ElementTree.Element instance. shape: The transitfeed.Shape instance. Returns: The LineString ElementTree.Element instance or None if coordinat...
def create(self, resource): """ Set all the labels for a resource. Args: resource: The object containing the resource URI and a list of labels Returns: dict: Resource Labels """ uri = self.URI + self.RESOURCES_PATH return self._client.cre...
Set all the labels for a resource. Args: resource: The object containing the resource URI and a list of labels Returns: dict: Resource Labels
Below is the the instruction that describes the task: ### Input: Set all the labels for a resource. Args: resource: The object containing the resource URI and a list of labels Returns: dict: Resource Labels ### Response: def create(self, resource): """ Set ...
def sanitize(self): ''' Check if the current settings conform to the LISP specifications and fix where possible. ''' # WARNING: http://tools.ietf.org/html/draft-ietf-lisp-ddt-00 # does not define this field so the description is taken from # http://tools.ietf.org/...
Check if the current settings conform to the LISP specifications and fix where possible.
Below is the the instruction that describes the task: ### Input: Check if the current settings conform to the LISP specifications and fix where possible. ### Response: def sanitize(self): ''' Check if the current settings conform to the LISP specifications and fix where possible. ...
def dcmanonym( dcmpth, displayonly=False, patient='anonymised', physician='anonymised', dob='19800101', verbose=True): ''' Anonymise DICOM file(s) Arguments: > dcmpth: it can be passed as a single DICOM file, or a folder containi...
Anonymise DICOM file(s) Arguments: > dcmpth: it can be passed as a single DICOM file, or a folder containing DICOM files, or a list of DICOM file paths. > patient: the name of the patient. > physician:the name of the referring physician. > dob: patient...
Below is the the instruction that describes the task: ### Input: Anonymise DICOM file(s) Arguments: > dcmpth: it can be passed as a single DICOM file, or a folder containing DICOM files, or a list of DICOM file paths. > patient: the name of the patient. > physi...
def distribute(n, iterable): """Distribute the items from *iterable* among *n* smaller iterables. >>> group_1, group_2 = distribute(2, [1, 2, 3, 4, 5, 6]) >>> list(group_1) [1, 3, 5] >>> list(group_2) [2, 4, 6] If the length of *iterable* is not evenly divisible by *n*,...
Distribute the items from *iterable* among *n* smaller iterables. >>> group_1, group_2 = distribute(2, [1, 2, 3, 4, 5, 6]) >>> list(group_1) [1, 3, 5] >>> list(group_2) [2, 4, 6] If the length of *iterable* is not evenly divisible by *n*, then the length of the returned...
Below is the the instruction that describes the task: ### Input: Distribute the items from *iterable* among *n* smaller iterables. >>> group_1, group_2 = distribute(2, [1, 2, 3, 4, 5, 6]) >>> list(group_1) [1, 3, 5] >>> list(group_2) [2, 4, 6] If the length of *iterable...
def resource_request_encode(self, request_id, uri_type, uri, transfer_type, storage): ''' The autopilot is requesting a resource (file, binary, other type of data) request_id : Request ID. This ID should be re-used when sending back URI con...
The autopilot is requesting a resource (file, binary, other type of data) request_id : Request ID. This ID should be re-used when sending back URI contents (uint8_t) uri_type : The type of requested URI. 0 = a file via URL. 1 = a UAVCAN bi...
Below is the the instruction that describes the task: ### Input: The autopilot is requesting a resource (file, binary, other type of data) request_id : Request ID. This ID should be re-used when sending back URI contents (uint8_t) uri_type ...
def enable_command(self, command: str) -> None: """ Enable a command by restoring its functions :param command: the command being enabled """ # If the commands is already enabled, then return if command not in self.disabled_commands: return help_func_...
Enable a command by restoring its functions :param command: the command being enabled
Below is the the instruction that describes the task: ### Input: Enable a command by restoring its functions :param command: the command being enabled ### Response: def enable_command(self, command: str) -> None: """ Enable a command by restoring its functions :param command: the co...