code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def kwarg_decorator(func): """ Turns a function that accepts a single arg and some kwargs in to a decorator that can optionally be called with kwargs: .. code-block:: python @kwarg_decorator def my_decorator(func, bar=True, baz=None): ... @my_decorator def ...
Turns a function that accepts a single arg and some kwargs in to a decorator that can optionally be called with kwargs: .. code-block:: python @kwarg_decorator def my_decorator(func, bar=True, baz=None): ... @my_decorator def my_func(): pass @m...
Below is the the instruction that describes the task: ### Input: Turns a function that accepts a single arg and some kwargs in to a decorator that can optionally be called with kwargs: .. code-block:: python @kwarg_decorator def my_decorator(func, bar=True, baz=None): ... ...
def write_reference(self, ref_index): """ Writes a reference :param ref_index: Local index (0-based) to the reference """ self._writeStruct( ">BL", 1, (self.TC_REFERENCE, ref_index + self.BASE_REFERENCE_IDX) )
Writes a reference :param ref_index: Local index (0-based) to the reference
Below is the the instruction that describes the task: ### Input: Writes a reference :param ref_index: Local index (0-based) to the reference ### Response: def write_reference(self, ref_index): """ Writes a reference :param ref_index: Local index (0-based) to the reference ""...
def get_dataset(lcc_server, dataset_id, strformat=False, page=1): '''This downloads a JSON form of a dataset from the specified lcc_server. If the dataset contains more than 1000 rows, it will be paginated, so you must use the `page` kwarg to get the page you...
This downloads a JSON form of a dataset from the specified lcc_server. If the dataset contains more than 1000 rows, it will be paginated, so you must use the `page` kwarg to get the page you want. The dataset JSON will contain the keys 'npages', 'currpage', and 'rows_per_page' to help with this. The 'r...
Below is the the instruction that describes the task: ### Input: This downloads a JSON form of a dataset from the specified lcc_server. If the dataset contains more than 1000 rows, it will be paginated, so you must use the `page` kwarg to get the page you want. The dataset JSON will contain the keys 'n...
def availableRoles(self): ''' Returns the set of roles for this event. Since roles are not always custom specified for event, this looks for the set of available roles in multiple places. If no roles are found, then the method returns an empty list, in which case it can be assumed that...
Returns the set of roles for this event. Since roles are not always custom specified for event, this looks for the set of available roles in multiple places. If no roles are found, then the method returns an empty list, in which case it can be assumed that the event's registration is not role-...
Below is the the instruction that describes the task: ### Input: Returns the set of roles for this event. Since roles are not always custom specified for event, this looks for the set of available roles in multiple places. If no roles are found, then the method returns an empty list, in which case...
def get_matching_blocks(self): """Return list of triples describing matching subsequences. Each triple is of the form (i, j, n), and means that a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in i and in j. New in Python 2.5, it's also guaranteed that if (i, j, ...
Return list of triples describing matching subsequences. Each triple is of the form (i, j, n), and means that a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in i and in j. New in Python 2.5, it's also guaranteed that if (i, j, n) and (i', j', n') are adjacent triples i...
Below is the the instruction that describes the task: ### Input: Return list of triples describing matching subsequences. Each triple is of the form (i, j, n), and means that a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in i and in j. New in Python 2.5, it's also guarant...
def sql_program_name_func(command): """ Extract program name from `command`. >>> sql_program_name_func('ls') 'ls' >>> sql_program_name_func('git status') 'git' >>> sql_program_name_func('EMACS=emacs make') 'make' :type command: str """ args = command.split(' ') for pro...
Extract program name from `command`. >>> sql_program_name_func('ls') 'ls' >>> sql_program_name_func('git status') 'git' >>> sql_program_name_func('EMACS=emacs make') 'make' :type command: str
Below is the the instruction that describes the task: ### Input: Extract program name from `command`. >>> sql_program_name_func('ls') 'ls' >>> sql_program_name_func('git status') 'git' >>> sql_program_name_func('EMACS=emacs make') 'make' :type command: str ### Response: def sql_progra...
def send_sms(request, to_number, body, callback_urlname="sms_status_callback"): """ Create :class:`OutgoingSMS` object and send SMS using Twilio. """ client = TwilioRestClient(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN) from_number = settings.TWILIO_PHONE_NUMBER message = OutgoingS...
Create :class:`OutgoingSMS` object and send SMS using Twilio.
Below is the the instruction that describes the task: ### Input: Create :class:`OutgoingSMS` object and send SMS using Twilio. ### Response: def send_sms(request, to_number, body, callback_urlname="sms_status_callback"): """ Create :class:`OutgoingSMS` object and send SMS using Twilio. """ client =...
def create_snapshot(kwargs=None, call=None): ''' Create a new disk snapshot. Must specify `name` and `disk_name`. CLI Example: .. code-block:: bash salt-cloud -f create_snapshot gce name=snap1 disk_name=pd ''' if call != 'function': raise SaltCloudSystemExit( 'The...
Create a new disk snapshot. Must specify `name` and `disk_name`. CLI Example: .. code-block:: bash salt-cloud -f create_snapshot gce name=snap1 disk_name=pd
Below is the the instruction that describes the task: ### Input: Create a new disk snapshot. Must specify `name` and `disk_name`. CLI Example: .. code-block:: bash salt-cloud -f create_snapshot gce name=snap1 disk_name=pd ### Response: def create_snapshot(kwargs=None, call=None): ''' Cr...
def PrepareMergeTaskStorage(self, task): """Prepares a task storage for merging. Moves the task storage file from the processed directory to the merge directory. Args: task (Task): task. Raises: IOError: if the storage type is not supported or if the storage file cannot be r...
Prepares a task storage for merging. Moves the task storage file from the processed directory to the merge directory. Args: task (Task): task. Raises: IOError: if the storage type is not supported or if the storage file cannot be renamed. OSError: if the storage type is no...
Below is the the instruction that describes the task: ### Input: Prepares a task storage for merging. Moves the task storage file from the processed directory to the merge directory. Args: task (Task): task. Raises: IOError: if the storage type is not supported or if the sto...
def check_is_uuid(self, uuid_str: str): """Check if it's an Isogeo UUID handling specific form. :param str uuid_str: UUID string to check """ # check uuid type if not isinstance(uuid_str, str): raise TypeError("'uuid_str' expected a str value.") else: ...
Check if it's an Isogeo UUID handling specific form. :param str uuid_str: UUID string to check
Below is the the instruction that describes the task: ### Input: Check if it's an Isogeo UUID handling specific form. :param str uuid_str: UUID string to check ### Response: def check_is_uuid(self, uuid_str: str): """Check if it's an Isogeo UUID handling specific form. :param str uuid_str...
def start_reporter(redis_address, stdout_file=None, stderr_file=None, redis_password=None): """Start a reporter process. Args: redis_address (str): The address of the Redis instance. stdout_file: A file handle opened for writing to redire...
Start a reporter process. Args: redis_address (str): The address of the Redis instance. stdout_file: A file handle opened for writing to redirect stdout to. If no redirection should happen, then this should be None. stderr_file: A file handle opened for writing to redirect stder...
Below is the the instruction that describes the task: ### Input: Start a reporter process. Args: redis_address (str): The address of the Redis instance. stdout_file: A file handle opened for writing to redirect stdout to. If no redirection should happen, then this should be None. ...
def register(self, service, name=''): """ Exposes a given service to this API. """ try: is_model = issubclass(service, orb.Model) except StandardError: is_model = False # expose an ORB table dynamically as a service if is_model: ...
Exposes a given service to this API.
Below is the the instruction that describes the task: ### Input: Exposes a given service to this API. ### Response: def register(self, service, name=''): """ Exposes a given service to this API. """ try: is_model = issubclass(service, orb.Model) except StandardEr...
def _is_same_type_as_root(self, obj): """ Testing if we try to collect an object of the same type as root. This is not really a good sign, because it means that we are going to collect a whole new tree, that will maybe collect a new tree, that will... """ if not self.ALLO...
Testing if we try to collect an object of the same type as root. This is not really a good sign, because it means that we are going to collect a whole new tree, that will maybe collect a new tree, that will...
Below is the the instruction that describes the task: ### Input: Testing if we try to collect an object of the same type as root. This is not really a good sign, because it means that we are going to collect a whole new tree, that will maybe collect a new tree, that will... ### Response: def _is_sa...
def transform(self, Y): """Transform input data `Y` to reduced data space defined by `self.data` Takes data in the same ambient space as `self.data` and transforms it to be in the same reduced space as `self.data_nu`. Parameters ---------- Y : array-like, shape=[n_sampl...
Transform input data `Y` to reduced data space defined by `self.data` Takes data in the same ambient space as `self.data` and transforms it to be in the same reduced space as `self.data_nu`. Parameters ---------- Y : array-like, shape=[n_samples_y, n_features] n_fea...
Below is the the instruction that describes the task: ### Input: Transform input data `Y` to reduced data space defined by `self.data` Takes data in the same ambient space as `self.data` and transforms it to be in the same reduced space as `self.data_nu`. Parameters ---------- ...
def login_oauth2_user(valid, oauth): """Log in a user after having been verified.""" if valid: oauth.user.login_via_oauth2 = True _request_ctx_stack.top.user = oauth.user identity_changed.send(current_app._get_current_object(), identity=Identity(oauth.user.i...
Log in a user after having been verified.
Below is the the instruction that describes the task: ### Input: Log in a user after having been verified. ### Response: def login_oauth2_user(valid, oauth): """Log in a user after having been verified.""" if valid: oauth.user.login_via_oauth2 = True _request_ctx_stack.top.user = oauth.user...
def write_library_constants(): """Write libtcod constants into the tcod.constants module.""" from tcod._libtcod import lib, ffi import tcod.color with open("tcod/constants.py", "w") as f: all_names = [] f.write(CONSTANT_MODULE_HEADER) for name in dir(lib): value = ge...
Write libtcod constants into the tcod.constants module.
Below is the the instruction that describes the task: ### Input: Write libtcod constants into the tcod.constants module. ### Response: def write_library_constants(): """Write libtcod constants into the tcod.constants module.""" from tcod._libtcod import lib, ffi import tcod.color with open("tcod/c...
def send_message(self, subject=None, text=None, markdown=None, message_dict=None): """ Helper function to send a message to a group """ message = FiestaMessage(self.api, self, subject, text, markdown, message_dict) return message.send()
Helper function to send a message to a group
Below is the the instruction that describes the task: ### Input: Helper function to send a message to a group ### Response: def send_message(self, subject=None, text=None, markdown=None, message_dict=None): """ Helper function to send a message to a group """ message = FiestaMessage...
def get_external_paths(self): """Returns a list of the external paths listed in the combobox.""" return [to_text_string(self.itemText(i)) for i in range(EXTERNAL_PATHS, self.count())]
Returns a list of the external paths listed in the combobox.
Below is the the instruction that describes the task: ### Input: Returns a list of the external paths listed in the combobox. ### Response: def get_external_paths(self): """Returns a list of the external paths listed in the combobox.""" return [to_text_string(self.itemText(i)) fo...
def main(): """ Usage: pre-sugartex [OPTIONS] Reads from stdin and writes to stdout. When no options: only replace U+02CE Modifier Letter Low Grave Accent (that looks like low '`') with $ Options: --all Full SugarTeX replace with regexp, --kiwi Same as above but wi...
Usage: pre-sugartex [OPTIONS] Reads from stdin and writes to stdout. When no options: only replace U+02CE Modifier Letter Low Grave Accent (that looks like low '`') with $ Options: --all Full SugarTeX replace with regexp, --kiwi Same as above but with kiwi flavor, --...
Below is the the instruction that describes the task: ### Input: Usage: pre-sugartex [OPTIONS] Reads from stdin and writes to stdout. When no options: only replace U+02CE Modifier Letter Low Grave Accent (that looks like low '`') with $ Options: --all Full SugarTeX replace wit...
def clean_conf_folder(self, locale): """Remove the configuration directory for `locale`""" dirname = self.configuration.get_messages_dir(locale) dirname.removedirs_p()
Remove the configuration directory for `locale`
Below is the the instruction that describes the task: ### Input: Remove the configuration directory for `locale` ### Response: def clean_conf_folder(self, locale): """Remove the configuration directory for `locale`""" dirname = self.configuration.get_messages_dir(locale) dirname.removedirs_...
async def stop(self, _signal): """ Finish all running tasks, cancel remaining tasks, then stop loop. :param _signal: :return: """ self.logger.info(f'Stopping spider: {self.name}') await self._cancel_tasks() self.loop.stop()
Finish all running tasks, cancel remaining tasks, then stop loop. :param _signal: :return:
Below is the the instruction that describes the task: ### Input: Finish all running tasks, cancel remaining tasks, then stop loop. :param _signal: :return: ### Response: async def stop(self, _signal): """ Finish all running tasks, cancel remaining tasks, then stop loop. :par...
def _get_object_from_python_path(python_path): """Method that will fetch a Marshmallow schema from a path to it. Args: python_path (str): The string path to the Marshmallow schema. Returns: marshmallow.Schema: The schema matching the provided path. Raises: ...
Method that will fetch a Marshmallow schema from a path to it. Args: python_path (str): The string path to the Marshmallow schema. Returns: marshmallow.Schema: The schema matching the provided path. Raises: TypeError: This is raised if the specified object ...
Below is the the instruction that describes the task: ### Input: Method that will fetch a Marshmallow schema from a path to it. Args: python_path (str): The string path to the Marshmallow schema. Returns: marshmallow.Schema: The schema matching the provided path. R...
def get_hosts(self, pattern="all"): """ find all host names matching a pattern string, taking into account any inventory restrictions or applied subsets. """ # process patterns if isinstance(pattern, list): pattern = ';'.join(pattern) patterns = patt...
find all host names matching a pattern string, taking into account any inventory restrictions or applied subsets.
Below is the the instruction that describes the task: ### Input: find all host names matching a pattern string, taking into account any inventory restrictions or applied subsets. ### Response: def get_hosts(self, pattern="all"): """ find all host names matching a pattern string, taking int...
def jenkins_request_with_headers(jenkins_server, req): """ We need to get the headers in addition to the body answer to get the location from them This function uses jenkins_request method from python-jenkins library with just the return call changed :param jenkins_server: The server to query ...
We need to get the headers in addition to the body answer to get the location from them This function uses jenkins_request method from python-jenkins library with just the return call changed :param jenkins_server: The server to query :param req: The request to execute :return: Dict containing ...
Below is the the instruction that describes the task: ### Input: We need to get the headers in addition to the body answer to get the location from them This function uses jenkins_request method from python-jenkins library with just the return call changed :param jenkins_server: The server to query...
def _resources(self, custom_indicators=False): """Initialize the resource module. This method will make a request to the ThreatConnect API to dynamically build classes to support custom Indicators. All other resources are available via this class. .. Note:: Resource Classes ca...
Initialize the resource module. This method will make a request to the ThreatConnect API to dynamically build classes to support custom Indicators. All other resources are available via this class. .. Note:: Resource Classes can be accessed using ``tcex.resources.<Class>`` or using ...
Below is the the instruction that describes the task: ### Input: Initialize the resource module. This method will make a request to the ThreatConnect API to dynamically build classes to support custom Indicators. All other resources are available via this class. .. Note:: Resource...
def handle_request(self, connection, msg): """Dispatch a request message to the appropriate method. Parameters ---------- connection : ClientConnection object The client connection the message was from. msg : Message object The request message to process....
Dispatch a request message to the appropriate method. Parameters ---------- connection : ClientConnection object The client connection the message was from. msg : Message object The request message to process. Returns ------- done_future ...
Below is the the instruction that describes the task: ### Input: Dispatch a request message to the appropriate method. Parameters ---------- connection : ClientConnection object The client connection the message was from. msg : Message object The request mess...
def sort_cards(cards, ranks=None): """ Sorts a given list of cards, either by poker ranks, or big two ranks. :arg cards: The cards to sort. :arg dict ranks: The rank dict to reference for sorting. If ``None``, it will default to ``DEFAULT_RANKS``. :returns: The sort...
Sorts a given list of cards, either by poker ranks, or big two ranks. :arg cards: The cards to sort. :arg dict ranks: The rank dict to reference for sorting. If ``None``, it will default to ``DEFAULT_RANKS``. :returns: The sorted cards.
Below is the the instruction that describes the task: ### Input: Sorts a given list of cards, either by poker ranks, or big two ranks. :arg cards: The cards to sort. :arg dict ranks: The rank dict to reference for sorting. If ``None``, it will default to ``DEFAULT_RANKS``. :ret...
def add_finder_patterns(matrix, is_micro): """\ Adds the finder pattern(s) to the matrix. QR Codes get three finder patterns, Micro QR Codes have just one finder pattern. ISO/IEC 18004:2015(E) -- 6.3.3 Finder pattern (page 16) ISO/IEC 18004:2015(E) -- 6.3.4 Separator (page 17) :param matr...
\ Adds the finder pattern(s) to the matrix. QR Codes get three finder patterns, Micro QR Codes have just one finder pattern. ISO/IEC 18004:2015(E) -- 6.3.3 Finder pattern (page 16) ISO/IEC 18004:2015(E) -- 6.3.4 Separator (page 17) :param matrix: The matrix. :param bool is_micro: Indicate...
Below is the the instruction that describes the task: ### Input: \ Adds the finder pattern(s) to the matrix. QR Codes get three finder patterns, Micro QR Codes have just one finder pattern. ISO/IEC 18004:2015(E) -- 6.3.3 Finder pattern (page 16) ISO/IEC 18004:2015(E) -- 6.3.4 Separator (page 1...
def get_gradebook_columns_by_genus_type(self, gradebook_column_genus_type): """Gets a ``GradebookColumnList`` corresponding to the given gradebook column genus ``Type`` which does not include gradebook columns of genus types derived from the specified ``Type``. In plenary mode, the returned list contai...
Gets a ``GradebookColumnList`` corresponding to the given gradebook column genus ``Type`` which does not include gradebook columns of genus types derived from the specified ``Type``. In plenary mode, the returned list contains all known gradebook columns or an error results. Otherwise, the returned lis...
Below is the the instruction that describes the task: ### Input: Gets a ``GradebookColumnList`` corresponding to the given gradebook column genus ``Type`` which does not include gradebook columns of genus types derived from the specified ``Type``. In plenary mode, the returned list contains all known grade...
def Initialize(self): """Open the delegate object.""" if "r" in self.mode: delegate = self.Get(self.Schema.DELEGATE) if delegate: self.delegate = aff4.FACTORY.Open( delegate, mode=self.mode, token=self.token, age=self.age_policy)
Open the delegate object.
Below is the the instruction that describes the task: ### Input: Open the delegate object. ### Response: def Initialize(self): """Open the delegate object.""" if "r" in self.mode: delegate = self.Get(self.Schema.DELEGATE) if delegate: self.delegate = aff4.FACTORY.Open( deleg...
def make_input(self, seq_idx: int, word_vec_prev: mx.sym.Symbol, decoder_state: mx.sym.Symbol) -> AttentionInput: """ Returns AttentionInput to be fed into the attend callable returned by the on() method. :param seq_idx: Decoder time step...
Returns AttentionInput to be fed into the attend callable returned by the on() method. :param seq_idx: Decoder time step. :param word_vec_prev: Embedding of previously predicted ord :param decoder_state: Current decoder state :return: Attention input.
Below is the the instruction that describes the task: ### Input: Returns AttentionInput to be fed into the attend callable returned by the on() method. :param seq_idx: Decoder time step. :param word_vec_prev: Embedding of previously predicted ord :param decoder_state: Current decoder state ...
def create(cls, name, protocol_number, protocol_agent=None, comment=None): """ Create the IP Service :param str name: name of ip-service :param int protocol_number: ip proto number for this service :param str,ProtocolAgent protocol_agent: optional protocol agent for ...
Create the IP Service :param str name: name of ip-service :param int protocol_number: ip proto number for this service :param str,ProtocolAgent protocol_agent: optional protocol agent for this service :param str comment: optional comment :raises CreateElementFailed: ...
Below is the the instruction that describes the task: ### Input: Create the IP Service :param str name: name of ip-service :param int protocol_number: ip proto number for this service :param str,ProtocolAgent protocol_agent: optional protocol agent for this service :para...
def names(self): """ Returns a list of queues available, ``None`` if no such queues found. Remember this will only shows queues with at least one item enqueued. """ data = None if not self.connected: raise ConnectionError('Queue is not connected') ...
Returns a list of queues available, ``None`` if no such queues found. Remember this will only shows queues with at least one item enqueued.
Below is the the instruction that describes the task: ### Input: Returns a list of queues available, ``None`` if no such queues found. Remember this will only shows queues with at least one item enqueued. ### Response: def names(self): """ Returns a list of queues available, ``None`...
def i18n(ctx, update=False): '''Extract translatable strings''' header('Extract translatable strings') info('Extract Python strings') lrun('python setup.py extract_messages') # Fix crowdin requiring Language with `2-digit` iso code in potfile # to produce 2-digit iso code pofile # Opening ...
Extract translatable strings
Below is the the instruction that describes the task: ### Input: Extract translatable strings ### Response: def i18n(ctx, update=False): '''Extract translatable strings''' header('Extract translatable strings') info('Extract Python strings') lrun('python setup.py extract_messages') # Fix crow...
def set_thresh(thresh,p=False,hostname=None): '''Sets the level of the threshold slider. If ``p==True`` will be interpreted as a _p_-value''' driver_send("SET_THRESHNEW %s *%s" % (str(thresh),"p" if p else ""),hostname=hostname)
Sets the level of the threshold slider. If ``p==True`` will be interpreted as a _p_-value
Below is the the instruction that describes the task: ### Input: Sets the level of the threshold slider. If ``p==True`` will be interpreted as a _p_-value ### Response: def set_thresh(thresh,p=False,hostname=None): '''Sets the level of the threshold slider. If ``p==True`` will be interpreted as a _p_-v...
def add_instruction(self, reil_instruction): """Add an instruction for analysis. """ for expr in self._translator.translate(reil_instruction): self._solver.add(expr)
Add an instruction for analysis.
Below is the the instruction that describes the task: ### Input: Add an instruction for analysis. ### Response: def add_instruction(self, reil_instruction): """Add an instruction for analysis. """ for expr in self._translator.translate(reil_instruction): self._solver.add(expr)
def add_to_rc(self, content): """ add content to the rc script. """ if not self.rewrite_config: raise DirectoryException("Error! Directory was not intialized w/ rewrite_config.") if not self.rc_file: self.rc_path, self.rc_file = self.__get_rc_handle(self.r...
add content to the rc script.
Below is the the instruction that describes the task: ### Input: add content to the rc script. ### Response: def add_to_rc(self, content): """ add content to the rc script. """ if not self.rewrite_config: raise DirectoryException("Error! Directory was not intialized w/ r...
def _marginal_hidden_probs(self): """Compute marginal pdf for each individual observable.""" initial_log_probs = tf.broadcast_to(self._log_init, tf.concat([self.batch_shape_tensor(), [self._num_states]], ...
Compute marginal pdf for each individual observable.
Below is the the instruction that describes the task: ### Input: Compute marginal pdf for each individual observable. ### Response: def _marginal_hidden_probs(self): """Compute marginal pdf for each individual observable.""" initial_log_probs = tf.broadcast_to(self._log_init, ...
def windowed_run_count(da, window, dim='time'): """Return the number of consecutive true values in array for runs at least as long as given duration. Parameters ---------- da: N-dimensional Xarray data array (boolean) Input data array window : int Minimum run le...
Return the number of consecutive true values in array for runs at least as long as given duration. Parameters ---------- da: N-dimensional Xarray data array (boolean) Input data array window : int Minimum run length. dim : Xarray dimension (default = 'time')...
Below is the the instruction that describes the task: ### Input: Return the number of consecutive true values in array for runs at least as long as given duration. Parameters ---------- da: N-dimensional Xarray data array (boolean) Input data array window : int ...
def open_dut(self, port=None): """ Open connection to dut. :param port: com port to use. :return: """ if port is not None: self.comport = port try: self.open_connection() except (DutConnectionError, ValueError) as err: ...
Open connection to dut. :param port: com port to use. :return:
Below is the the instruction that describes the task: ### Input: Open connection to dut. :param port: com port to use. :return: ### Response: def open_dut(self, port=None): """ Open connection to dut. :param port: com port to use. :return: """ if po...
def block_layer(inputs, filters, block_fn, blocks, strides, is_training, name, data_format="channels_first", use_td=False, targeting_rate=None, keep_prob=None):...
Creates one layer of blocks for the ResNet model. Args: inputs: `Tensor` of size `[batch, channels, height, width]`. filters: `int` number of filters for the first convolution of the layer. block_fn: `function` for the block to use within the model blocks: `int` number of blocks contained in the laye...
Below is the the instruction that describes the task: ### Input: Creates one layer of blocks for the ResNet model. Args: inputs: `Tensor` of size `[batch, channels, height, width]`. filters: `int` number of filters for the first convolution of the layer. block_fn: `function` for the block to use with...
def _system_handler(self, data, ts): """Distributes system messages to the appropriate handler. System messages include everything that arrives as a dict, or a list containing a heartbeat. :param data: :param ts: :return: """ self.log.debug("_system_hand...
Distributes system messages to the appropriate handler. System messages include everything that arrives as a dict, or a list containing a heartbeat. :param data: :param ts: :return:
Below is the the instruction that describes the task: ### Input: Distributes system messages to the appropriate handler. System messages include everything that arrives as a dict, or a list containing a heartbeat. :param data: :param ts: :return: ### Response: def _system_...
def cache_s3(self, url, named): # pragma: no cover """Basically this is not to deploy automatically this is to be run once all is properly defined to catch the xsd in your own S3 instance and avoid third party (like government servers) failure, trying to manage the cache transparently t...
Basically this is not to deploy automatically this is to be run once all is properly defined to catch the xsd in your own S3 instance and avoid third party (like government servers) failure, trying to manage the cache transparently to the user. This method was created due to SAT is too ...
Below is the the instruction that describes the task: ### Input: Basically this is not to deploy automatically this is to be run once all is properly defined to catch the xsd in your own S3 instance and avoid third party (like government servers) failure, trying to manage the cache transpare...
def of_pyobj(self, pyobj): """Use default hash method to return hash value of a piece of Python picklable object. """ m = self.hash_algo() m.update(pickle.dumps(pyobj, protocol=self.pk_protocol)) if self.return_int: return int(m.hexdigest(), 16) else: ...
Use default hash method to return hash value of a piece of Python picklable object.
Below is the the instruction that describes the task: ### Input: Use default hash method to return hash value of a piece of Python picklable object. ### Response: def of_pyobj(self, pyobj): """Use default hash method to return hash value of a piece of Python picklable object. """ ...
async def _send_text(self, request: Request, stack: Stack): """ Send text layers to the user. Each layer will go in its own bubble. Also, Facebook limits messages to 320 chars, so if any message is longer than that it will be split into as many messages as needed to be accepted ...
Send text layers to the user. Each layer will go in its own bubble. Also, Facebook limits messages to 320 chars, so if any message is longer than that it will be split into as many messages as needed to be accepted by Facebook.
Below is the the instruction that describes the task: ### Input: Send text layers to the user. Each layer will go in its own bubble. Also, Facebook limits messages to 320 chars, so if any message is longer than that it will be split into as many messages as needed to be accepted by Facebook...
def level(self): """ Returns the the user's profile level, note that this runs a separate request because the profile level data isn't in the standard player summary output even though it should be. Which is also why it's not implemented as a separate class. You won't need this o...
Returns the the user's profile level, note that this runs a separate request because the profile level data isn't in the standard player summary output even though it should be. Which is also why it's not implemented as a separate class. You won't need this output and not the profile output
Below is the the instruction that describes the task: ### Input: Returns the the user's profile level, note that this runs a separate request because the profile level data isn't in the standard player summary output even though it should be. Which is also why it's not implemented as a separ...
def get_date(context, value): """Tries to return a DateTime.DateTime object """ if not value: return None if isinstance(value, DateTime): return value if isinstance(value, datetime): return dt2DT(value) if not isinstance(value, basestring): return None def tr...
Tries to return a DateTime.DateTime object
Below is the the instruction that describes the task: ### Input: Tries to return a DateTime.DateTime object ### Response: def get_date(context, value): """Tries to return a DateTime.DateTime object """ if not value: return None if isinstance(value, DateTime): return value if isi...
def _handle_autoreload(self,cfg_file,*args,**options): """Command 'supervisor autoreload' watches for code changes. This command provides a simulation of the Django dev server's auto-reloading mechanism that will restart all supervised processes. It's not quite as accurate as Django's ...
Command 'supervisor autoreload' watches for code changes. This command provides a simulation of the Django dev server's auto-reloading mechanism that will restart all supervised processes. It's not quite as accurate as Django's autoreloader because it runs in a separate process, so it ...
Below is the the instruction that describes the task: ### Input: Command 'supervisor autoreload' watches for code changes. This command provides a simulation of the Django dev server's auto-reloading mechanism that will restart all supervised processes. It's not quite as accurate as Django...
def buffer(self, buf): """ Returns a textual description of the contents of the argument passed as a buffer or None if an error occurred and the MAGIC_ERROR flag is set. A call to errno() will return the numeric error code. """ try: # attempt python3 approach first ...
Returns a textual description of the contents of the argument passed as a buffer or None if an error occurred and the MAGIC_ERROR flag is set. A call to errno() will return the numeric error code.
Below is the the instruction that describes the task: ### Input: Returns a textual description of the contents of the argument passed as a buffer or None if an error occurred and the MAGIC_ERROR flag is set. A call to errno() will return the numeric error code. ### Response: def buffer(self, buf): ...
def getEstimatedNodeCounts(self, queuedJobShapes, currentNodeCounts): """ Given the resource requirements of queued jobs and the current size of the cluster, returns a dict mapping from nodeShape to the number of nodes we want in the cluster right now. """ nodesToRunQueuedJobs = ...
Given the resource requirements of queued jobs and the current size of the cluster, returns a dict mapping from nodeShape to the number of nodes we want in the cluster right now.
Below is the the instruction that describes the task: ### Input: Given the resource requirements of queued jobs and the current size of the cluster, returns a dict mapping from nodeShape to the number of nodes we want in the cluster right now. ### Response: def getEstimatedNodeCounts(self, queuedJobShapes,...
def get_select_title_url(self, attach=None): """ 获取商户专属开票链接 商户调用接口,获取链接。用户扫码,可以选择抬头发给商户。可以将链接转成二维码,立在收银台。 详情请参考 https://mp.weixin.qq.com/wiki?id=mp1496554912_vfWU0 :param attach: 附加字段,用户提交发票时会发送给商户 :return: 商户专属开票链接 """ return self._post( ...
获取商户专属开票链接 商户调用接口,获取链接。用户扫码,可以选择抬头发给商户。可以将链接转成二维码,立在收银台。 详情请参考 https://mp.weixin.qq.com/wiki?id=mp1496554912_vfWU0 :param attach: 附加字段,用户提交发票时会发送给商户 :return: 商户专属开票链接
Below is the the instruction that describes the task: ### Input: 获取商户专属开票链接 商户调用接口,获取链接。用户扫码,可以选择抬头发给商户。可以将链接转成二维码,立在收银台。 详情请参考 https://mp.weixin.qq.com/wiki?id=mp1496554912_vfWU0 :param attach: 附加字段,用户提交发票时会发送给商户 :return: 商户专属开票链接 ### Response: def get_select_title_url(sel...
def envGet(self, name, default=None, conv=None): """Return value for environment variable or None. @param name: Name of environment variable. @param default: Default value if variable is undefined. @param conv: Function for converting value to desired type. @retu...
Return value for environment variable or None. @param name: Name of environment variable. @param default: Default value if variable is undefined. @param conv: Function for converting value to desired type. @return: Value of environment variable.
Below is the the instruction that describes the task: ### Input: Return value for environment variable or None. @param name: Name of environment variable. @param default: Default value if variable is undefined. @param conv: Function for converting value to desired type. ...
def format_duration(secs): """ Format a duration in seconds as minutes and seconds. """ secs = int(secs) if abs(secs) > 60: mins = abs(secs) / 60 secs = abs(secs) - (mins * 60) return '%s%im %02is' % ('-' if secs < 0 else '', mins, secs) return '%is' % secs
Format a duration in seconds as minutes and seconds.
Below is the the instruction that describes the task: ### Input: Format a duration in seconds as minutes and seconds. ### Response: def format_duration(secs): """ Format a duration in seconds as minutes and seconds. """ secs = int(secs) if abs(secs) > 60: mins = abs(secs) / 60 ...
def set_master(self, url): """Set the master url that this object works with.""" m = urlparse(url) self.master_scheme = m.scheme self.master_netloc = m.netloc self.master_path = os.path.dirname(m.path)
Set the master url that this object works with.
Below is the the instruction that describes the task: ### Input: Set the master url that this object works with. ### Response: def set_master(self, url): """Set the master url that this object works with.""" m = urlparse(url) self.master_scheme = m.scheme self.master_netloc = m.netl...
def http_basic(r, username, password): """Attaches HTTP Basic Authentication to the given Request object. Arguments should be considered non-positional. """ username = str(username) password = str(password) auth_s = b64encode('%s:%s' % (username, password)) r.headers['Authorization'] = ('B...
Attaches HTTP Basic Authentication to the given Request object. Arguments should be considered non-positional.
Below is the the instruction that describes the task: ### Input: Attaches HTTP Basic Authentication to the given Request object. Arguments should be considered non-positional. ### Response: def http_basic(r, username, password): """Attaches HTTP Basic Authentication to the given Request object. Argumen...
def get_ipaths(self): """ Returns generator of paths from nodes marked as added, changed or removed. """ for node in itertools.chain(self.added, self.changed, self.removed): yield node.path
Returns generator of paths from nodes marked as added, changed or removed.
Below is the the instruction that describes the task: ### Input: Returns generator of paths from nodes marked as added, changed or removed. ### Response: def get_ipaths(self): """ Returns generator of paths from nodes marked as added, changed or removed. """ for node...
def request_writes(self, offset, data): """Request any available writes given new incoming data. You call this method by providing new data along with the offset associated with the data. If that new data unlocks any contiguous writes that can now be submitted, this method will...
Request any available writes given new incoming data. You call this method by providing new data along with the offset associated with the data. If that new data unlocks any contiguous writes that can now be submitted, this method will return all applicable writes. This is don...
Below is the the instruction that describes the task: ### Input: Request any available writes given new incoming data. You call this method by providing new data along with the offset associated with the data. If that new data unlocks any contiguous writes that can now be submitted, this ...
def next_stop(self): """Return the next stop for this bus.""" p = self.api.predictions(vid=self.vid)['prd'] pobj = Prediction.fromapi(self.api, p[0]) pobj._busobj = self return pobj
Return the next stop for this bus.
Below is the the instruction that describes the task: ### Input: Return the next stop for this bus. ### Response: def next_stop(self): """Return the next stop for this bus.""" p = self.api.predictions(vid=self.vid)['prd'] pobj = Prediction.fromapi(self.api, p[0]) pobj._busobj = self...
def strtime(at=None, fmt=PERFECT_TIME_FORMAT): """Returns formatted utcnow.""" if not at: at = utcnow() return at.strftime(fmt)
Returns formatted utcnow.
Below is the the instruction that describes the task: ### Input: Returns formatted utcnow. ### Response: def strtime(at=None, fmt=PERFECT_TIME_FORMAT): """Returns formatted utcnow.""" if not at: at = utcnow() return at.strftime(fmt)
def readpipe(self, chunk=None): """ Return iterator that iterates over STDIN line by line If ``chunk`` is set to a positive non-zero integer value, then the reads are performed in chunks of that many lines, and returned as a list. Otherwise the lines are returned one by one. """...
Return iterator that iterates over STDIN line by line If ``chunk`` is set to a positive non-zero integer value, then the reads are performed in chunks of that many lines, and returned as a list. Otherwise the lines are returned one by one.
Below is the the instruction that describes the task: ### Input: Return iterator that iterates over STDIN line by line If ``chunk`` is set to a positive non-zero integer value, then the reads are performed in chunks of that many lines, and returned as a list. Otherwise the lines are returne...
def plot_job_history(jobs, interval='year'): """Plots the job history of the user from the given list of jobs. Args: jobs (list): A list of jobs with type IBMQjob. interval (str): Interval over which to examine. Returns: fig: A Matplotlib figure instance. """ def get_date(j...
Plots the job history of the user from the given list of jobs. Args: jobs (list): A list of jobs with type IBMQjob. interval (str): Interval over which to examine. Returns: fig: A Matplotlib figure instance.
Below is the the instruction that describes the task: ### Input: Plots the job history of the user from the given list of jobs. Args: jobs (list): A list of jobs with type IBMQjob. interval (str): Interval over which to examine. Returns: fig: A Matplotlib figure instance. ### Respo...
def read(self, address, size): """Read arbitrary size content from memory. """ value = 0x0 for i in range(0, size): value |= self._read_byte(address + i) << (i * 8) return value
Read arbitrary size content from memory.
Below is the the instruction that describes the task: ### Input: Read arbitrary size content from memory. ### Response: def read(self, address, size): """Read arbitrary size content from memory. """ value = 0x0 for i in range(0, size): value |= self._read_byte(address +...
def play(self): """Starts an animation playing.""" if self.state == PygAnimation.PLAYING: pass # nothing to do elif self.state == PygAnimation.STOPPED: # restart from beginning of animation self.index = 0 # first image in list self.elapsed = 0 ...
Starts an animation playing.
Below is the the instruction that describes the task: ### Input: Starts an animation playing. ### Response: def play(self): """Starts an animation playing.""" if self.state == PygAnimation.PLAYING: pass # nothing to do elif self.state == PygAnimation.STOPPED: # restart f...
def update_batch(self, **kwargs): """ Simplistic batch update operation implemented in terms of `replace()`. Assumes that: - Request and response schemas contains lists of items. - Request items define a primary key identifier - The entire batch succeeds or fails tog...
Simplistic batch update operation implemented in terms of `replace()`. Assumes that: - Request and response schemas contains lists of items. - Request items define a primary key identifier - The entire batch succeeds or fails together.
Below is the the instruction that describes the task: ### Input: Simplistic batch update operation implemented in terms of `replace()`. Assumes that: - Request and response schemas contains lists of items. - Request items define a primary key identifier - The entire batch succee...
def Cpg(self): r'''Gas-phase heat capacity of the chemical at its current temperature, in units of [J/kg/K]. For calculation of this property at other temperatures, or specifying manually the method used to calculate it, and more - see the object oriented interface :obj:`thermo.h...
r'''Gas-phase heat capacity of the chemical at its current temperature, in units of [J/kg/K]. For calculation of this property at other temperatures, or specifying manually the method used to calculate it, and more - see the object oriented interface :obj:`thermo.heat_capacity.HeatCapaci...
Below is the the instruction that describes the task: ### Input: r'''Gas-phase heat capacity of the chemical at its current temperature, in units of [J/kg/K]. For calculation of this property at other temperatures, or specifying manually the method used to calculate it, and more - see the ob...
def _dictToAlignments(self, diamondDict, read): """ Take a dict (made by DiamondTabularFormatReader.records) and convert it to a list of alignments. @param diamondDict: A C{dict}, from records(). @param read: A C{Read} instance, containing the read that DIAMOND used ...
Take a dict (made by DiamondTabularFormatReader.records) and convert it to a list of alignments. @param diamondDict: A C{dict}, from records(). @param read: A C{Read} instance, containing the read that DIAMOND used to create this record. @return: A C{list} of L{dark.alignmen...
Below is the the instruction that describes the task: ### Input: Take a dict (made by DiamondTabularFormatReader.records) and convert it to a list of alignments. @param diamondDict: A C{dict}, from records(). @param read: A C{Read} instance, containing the read that DIAMOND used ...
def get_account_info(self): """ Gets account info. @return: AccountInfo """ attrs = {sconstant.A_BY: sconstant.V_NAME} account = SOAPpy.Types.stringType(data=self.auth_token.account_name, attrs=attrs) params = {sconstant....
Gets account info. @return: AccountInfo
Below is the the instruction that describes the task: ### Input: Gets account info. @return: AccountInfo ### Response: def get_account_info(self): """ Gets account info. @return: AccountInfo """ attrs = {sconstant.A_BY: sconstant.V_NAME} account = SOAPpy.Type...
def get_create_base_agent(self, agent): """Return BaseAgent from an Agent, creating it if needed. Parameters ---------- agent : indra.statements.Agent Returns ------- base_agent : indra.mechlinker.BaseAgent """ try: base_agent = self....
Return BaseAgent from an Agent, creating it if needed. Parameters ---------- agent : indra.statements.Agent Returns ------- base_agent : indra.mechlinker.BaseAgent
Below is the the instruction that describes the task: ### Input: Return BaseAgent from an Agent, creating it if needed. Parameters ---------- agent : indra.statements.Agent Returns ------- base_agent : indra.mechlinker.BaseAgent ### Response: def get_create_base_ag...
def imrphenomc_tmplt(**kwds): """ Return an IMRPhenomC waveform using CUDA to generate the phase and amplitude Main Paper: arXiv:1005.3306 """ # Pull out the input arguments f_min = float128(kwds['f_lower']) f_max = float128(kwds['f_final']) delta_f = float128(kwds['delta_f']) distance...
Return an IMRPhenomC waveform using CUDA to generate the phase and amplitude Main Paper: arXiv:1005.3306
Below is the the instruction that describes the task: ### Input: Return an IMRPhenomC waveform using CUDA to generate the phase and amplitude Main Paper: arXiv:1005.3306 ### Response: def imrphenomc_tmplt(**kwds): """ Return an IMRPhenomC waveform using CUDA to generate the phase and amplitude Main...
def deleteGenome(species, name) : """Removes a genome from the database""" printf('deleting genome (%s, %s)...' % (species, name)) conf.db.beginTransaction() objs = [] allGood = True try : genome = Genome_Raba(name = name, species = species.lower()) objs.append(genome) ...
Removes a genome from the database
Below is the the instruction that describes the task: ### Input: Removes a genome from the database ### Response: def deleteGenome(species, name) : """Removes a genome from the database""" printf('deleting genome (%s, %s)...' % (species, name)) conf.db.beginTransaction() objs = [] allGood = T...
def start_agent(agent, recp, desc, allocation_id=None, *args, **kwargs): ''' Tells remote host agent to start agent identified by desc. The result value of the fiber is IRecipient. ''' f = fiber.Fiber() f.add_callback(agent.initiate_protocol, IRecipient(recp), desc, allocation...
Tells remote host agent to start agent identified by desc. The result value of the fiber is IRecipient.
Below is the the instruction that describes the task: ### Input: Tells remote host agent to start agent identified by desc. The result value of the fiber is IRecipient. ### Response: def start_agent(agent, recp, desc, allocation_id=None, *args, **kwargs): ''' Tells remote host agent to start agent iden...
def _write_str(self, data): """ Converts the given data then writes it :param data: Data to be written :return: The result of ``self.output.write()`` """ with self.__lock: self.output.write( to_str(data, self.encoding) .encode(...
Converts the given data then writes it :param data: Data to be written :return: The result of ``self.output.write()``
Below is the the instruction that describes the task: ### Input: Converts the given data then writes it :param data: Data to be written :return: The result of ``self.output.write()`` ### Response: def _write_str(self, data): """ Converts the given data then writes it :para...
def build_info(name, path=None, module=None): """Return the build info tuple.""" verlist = get_version_list(path, module) verlist[0] = name return tuple(verlist)
Return the build info tuple.
Below is the the instruction that describes the task: ### Input: Return the build info tuple. ### Response: def build_info(name, path=None, module=None): """Return the build info tuple.""" verlist = get_version_list(path, module) verlist[0] = name return tuple(verlist)
def clean_response_type(self): """ :rfc:`3.1.1` Lists of values are space delimited. """ response_type = self.cleaned_data.get('response_type') if not response_type: raise OAuthValidationError({'error': 'invalid_request', 'error_description': "No 'res...
:rfc:`3.1.1` Lists of values are space delimited.
Below is the the instruction that describes the task: ### Input: :rfc:`3.1.1` Lists of values are space delimited. ### Response: def clean_response_type(self): """ :rfc:`3.1.1` Lists of values are space delimited. """ response_type = self.cleaned_data.get('response_type') i...
def get_vc_dir_from_vs_dir(self): """ Get Visual C++ directory from Visual Studio directory. """ vc_dir = os.path.join(self.vs_dir, 'vc') if os.path.isdir(vc_dir): logging.info(_('using vc: %s'), vc_dir) return vc_dir logging.debug(_('vc not found:...
Get Visual C++ directory from Visual Studio directory.
Below is the the instruction that describes the task: ### Input: Get Visual C++ directory from Visual Studio directory. ### Response: def get_vc_dir_from_vs_dir(self): """ Get Visual C++ directory from Visual Studio directory. """ vc_dir = os.path.join(self.vs_dir, 'vc') if ...
def reset_hba(self): """Remove all records from pg_hba.conf.""" status = self.get_status() if status == 'not-initialized': raise ClusterError( 'cannot modify HBA records: cluster is not initialized') pg_hba = os.path.join(self._data_dir, 'pg_hba.conf') ...
Remove all records from pg_hba.conf.
Below is the the instruction that describes the task: ### Input: Remove all records from pg_hba.conf. ### Response: def reset_hba(self): """Remove all records from pg_hba.conf.""" status = self.get_status() if status == 'not-initialized': raise ClusterError( 'can...
def unique_iter(seq): """ See http://www.peterbe.com/plog/uniqifiers-benchmark Originally f8 written by Dave Kirby """ seen = set() return [x for x in seq if x not in seen and not seen.add(x)]
See http://www.peterbe.com/plog/uniqifiers-benchmark Originally f8 written by Dave Kirby
Below is the the instruction that describes the task: ### Input: See http://www.peterbe.com/plog/uniqifiers-benchmark Originally f8 written by Dave Kirby ### Response: def unique_iter(seq): """ See http://www.peterbe.com/plog/uniqifiers-benchmark Originally f8 written by Dave Kirby """ seen...
def _update_camera(self, camera_center): """Update the camera transform based on the new camera center.""" self._world_tl_to_world_camera_rel.offset = ( -self._world_to_world_tl.fwd_pt(camera_center) * self._world_tl_to_world_camera_rel.scale)
Update the camera transform based on the new camera center.
Below is the the instruction that describes the task: ### Input: Update the camera transform based on the new camera center. ### Response: def _update_camera(self, camera_center): """Update the camera transform based on the new camera center.""" self._world_tl_to_world_camera_rel.offset = ( -self._...
def update(self, identity_id, service, total_allowance=None, analyze_queries=None): """ Update the limit :param identity_id: The ID of the identity to retrieve :param service: The service that the token is linked to :param total_allowance: The total allowance for this token'...
Update the limit :param identity_id: The ID of the identity to retrieve :param service: The service that the token is linked to :param total_allowance: The total allowance for this token's limit :param analyze_queries: The number of analyze calls :return: dic...
Below is the the instruction that describes the task: ### Input: Update the limit :param identity_id: The ID of the identity to retrieve :param service: The service that the token is linked to :param total_allowance: The total allowance for this token's limit :param ...
def GetHostMemSwappedMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemSwappedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Undocumented.
Below is the the instruction that describes the task: ### Input: Undocumented. ### Response: def GetHostMemSwappedMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemSwappedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: r...
def Private(input_dim, num_outputs, kernel, output, kappa=None,name='X'): """ Builds a kernel for an Intrinsic Coregionalization Model :input_dim: Input dimensionality :num_outputs: Number of outputs :param kernel: kernel that will be multiplied by the coregionalize kernel (matrix B). :type ker...
Builds a kernel for an Intrinsic Coregionalization Model :input_dim: Input dimensionality :num_outputs: Number of outputs :param kernel: kernel that will be multiplied by the coregionalize kernel (matrix B). :type kernel: a GPy kernel :param W_rank: number tuples of the corregionalization parameter...
Below is the the instruction that describes the task: ### Input: Builds a kernel for an Intrinsic Coregionalization Model :input_dim: Input dimensionality :num_outputs: Number of outputs :param kernel: kernel that will be multiplied by the coregionalize kernel (matrix B). :type kernel: a GPy kernel...
def primary_container_name(names, default=None, strip_trailing_slash=True): """ From the list of names, finds the primary name of the container. Returns the defined default value (e.g. the container id or ``None``) in case it cannot find any. :param names: List with name and aliases of the container. ...
From the list of names, finds the primary name of the container. Returns the defined default value (e.g. the container id or ``None``) in case it cannot find any. :param names: List with name and aliases of the container. :type names: list[unicode | str] :param default: Default value. :param strip_...
Below is the the instruction that describes the task: ### Input: From the list of names, finds the primary name of the container. Returns the defined default value (e.g. the container id or ``None``) in case it cannot find any. :param names: List with name and aliases of the container. :type names: lis...
def getShocks(self): ''' Gets permanent and transitory income shocks for this period as well as preference shocks. Parameters ---------- None Returns ------- None ''' IndShockConsumerType.getShocks(self) # Get permanent and transitory inc...
Gets permanent and transitory income shocks for this period as well as preference shocks. Parameters ---------- None Returns ------- None
Below is the the instruction that describes the task: ### Input: Gets permanent and transitory income shocks for this period as well as preference shocks. Parameters ---------- None Returns ------- None ### Response: def getShocks(self): ''' Gets pe...
def parse_rest_response(self, records, rowcount, row_type=list): """Parse the REST API response to DB API cursor flat response""" if self.is_plain_count: # result of "SELECT COUNT() FROM ... WHERE ..." assert list(records) == [] yield rowcount # originally [resp.json...
Parse the REST API response to DB API cursor flat response
Below is the the instruction that describes the task: ### Input: Parse the REST API response to DB API cursor flat response ### Response: def parse_rest_response(self, records, rowcount, row_type=list): """Parse the REST API response to DB API cursor flat response""" if self.is_plain_count: ...
def RenderWidget(self): """Returns a QWidget subclass instance. Exact class depends on self.type""" t = self.type if t == int: ret = QSpinBox() ret.setMaximum(999999999) ret.setValue(self.value) elif t == float: ret = QLineEdit() ...
Returns a QWidget subclass instance. Exact class depends on self.type
Below is the the instruction that describes the task: ### Input: Returns a QWidget subclass instance. Exact class depends on self.type ### Response: def RenderWidget(self): """Returns a QWidget subclass instance. Exact class depends on self.type""" t = self.type if t == int: ...
def serializable_value(self, obj): ''' Produce the value as it should be serialized. Sometimes it is desirable for the serialized value to differ from the ``__get__`` in order for the ``__get__`` value to appear simpler for user or developer convenience. Args: obj (...
Produce the value as it should be serialized. Sometimes it is desirable for the serialized value to differ from the ``__get__`` in order for the ``__get__`` value to appear simpler for user or developer convenience. Args: obj (HasProps) : the object to get the serialized at...
Below is the the instruction that describes the task: ### Input: Produce the value as it should be serialized. Sometimes it is desirable for the serialized value to differ from the ``__get__`` in order for the ``__get__`` value to appear simpler for user or developer convenience. A...
def edge_coord_in_direction(tile_id, direction): """ Returns the edge coordinate in the given direction at the given tile identifier. :param tile_id: tile identifier, int :param direction: direction, str :return: edge coord, int """ tile_coord = tile_id_to_coord(tile_id) for edge_coord ...
Returns the edge coordinate in the given direction at the given tile identifier. :param tile_id: tile identifier, int :param direction: direction, str :return: edge coord, int
Below is the the instruction that describes the task: ### Input: Returns the edge coordinate in the given direction at the given tile identifier. :param tile_id: tile identifier, int :param direction: direction, str :return: edge coord, int ### Response: def edge_coord_in_direction(tile_id, direction)...
def list_fpgas(self): """Return a list with all the supported FPGAs""" # Print table click.echo('\nSupported FPGAs:\n') FPGALIST_TPL = ('{fpga:30} {type:<5} {size:<5} {pack:<10}') terminal_width, _ = click.get_terminal_size() click.echo('-' * terminal_width) cl...
Return a list with all the supported FPGAs
Below is the the instruction that describes the task: ### Input: Return a list with all the supported FPGAs ### Response: def list_fpgas(self): """Return a list with all the supported FPGAs""" # Print table click.echo('\nSupported FPGAs:\n') FPGALIST_TPL = ('{fpga:30} {type:<5} {s...
def default_security_rules_list(security_group, resource_group, **kwargs): ''' .. versionadded:: 2019.2.0 List default security rules within a security group. :param security_group: The network security group to query. :param resource_group: The resource group name assigned to the network...
.. versionadded:: 2019.2.0 List default security rules within a security group. :param security_group: The network security group to query. :param resource_group: The resource group name assigned to the network security group. CLI Example: .. code-block:: bash salt-call azurear...
Below is the the instruction that describes the task: ### Input: .. versionadded:: 2019.2.0 List default security rules within a security group. :param security_group: The network security group to query. :param resource_group: The resource group name assigned to the network security group. ...
def validated_formatter(self, url_format): """validate visualization url format""" # We try to create a string by substituting all known # parameters. If an unknown parameter is present, an error # will be thrown valid_parameters = { "${CLUSTER}": "cluster", "${ENVIRON}": "environ", ...
validate visualization url format
Below is the the instruction that describes the task: ### Input: validate visualization url format ### Response: def validated_formatter(self, url_format): """validate visualization url format""" # We try to create a string by substituting all known # parameters. If an unknown parameter is present, an ...
def dRV(self, dt, band='g'): """Returns dRV of star A, if A is brighter than B+C, or of star B if B+C is brighter """ return (self.orbpop.dRV_1(dt)*self.A_brighter(band) + self.orbpop.dRV_2(dt)*self.BC_brighter(band))
Returns dRV of star A, if A is brighter than B+C, or of star B if B+C is brighter
Below is the the instruction that describes the task: ### Input: Returns dRV of star A, if A is brighter than B+C, or of star B if B+C is brighter ### Response: def dRV(self, dt, band='g'): """Returns dRV of star A, if A is brighter than B+C, or of star B if B+C is brighter """ return (self...
def mask(self, table): """ Use the current Query object to count the number of entries in `table` that satisfy `queries`. Parameters ---------- table : NumPy structured array, astropy Table, etc. Returns ------- mask : numpy bool array ""...
Use the current Query object to count the number of entries in `table` that satisfy `queries`. Parameters ---------- table : NumPy structured array, astropy Table, etc. Returns ------- mask : numpy bool array
Below is the the instruction that describes the task: ### Input: Use the current Query object to count the number of entries in `table` that satisfy `queries`. Parameters ---------- table : NumPy structured array, astropy Table, etc. Returns ------- mask : n...
def open(self, mode='a', **kwargs): """ Open the file in the specified mode Parameters ---------- mode : {'a', 'w', 'r', 'r+'}, default 'a' See HDFStore docstring or tables.open_file for info about modes """ tables = _tables() if self._mode !...
Open the file in the specified mode Parameters ---------- mode : {'a', 'w', 'r', 'r+'}, default 'a' See HDFStore docstring or tables.open_file for info about modes
Below is the the instruction that describes the task: ### Input: Open the file in the specified mode Parameters ---------- mode : {'a', 'w', 'r', 'r+'}, default 'a' See HDFStore docstring or tables.open_file for info about modes ### Response: def open(self, mode='a', **kwargs):...
def roll_up_down_capture(returns, factor_returns, window=10, **kwargs): """ Computes the up/down capture measure over a rolling window. see documentation for :func:`~empyrical.stats.up_down_capture`. (pass all args, kwargs required) Parameters ---------- returns : pd.Series or np.ndarray ...
Computes the up/down capture measure over a rolling window. see documentation for :func:`~empyrical.stats.up_down_capture`. (pass all args, kwargs required) Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation i...
Below is the the instruction that describes the task: ### Input: Computes the up/down capture measure over a rolling window. see documentation for :func:`~empyrical.stats.up_down_capture`. (pass all args, kwargs required) Parameters ---------- returns : pd.Series or np.ndarray Daily ret...
def read_PIA0_B_control(self, cpu_cycles, op_address, address): """ read from 0xff03 -> PIA 0 B side Control reg. """ value = self.pia_0_B_control.value log.error( "%04x| read $%04x (PIA 0 B side Control reg.) send $%02x (%s) back.\t|%s", op_address, addre...
read from 0xff03 -> PIA 0 B side Control reg.
Below is the the instruction that describes the task: ### Input: read from 0xff03 -> PIA 0 B side Control reg. ### Response: def read_PIA0_B_control(self, cpu_cycles, op_address, address): """ read from 0xff03 -> PIA 0 B side Control reg. """ value = self.pia_0_B_control.value ...
def train_hmm(self,observation_list, iterations, quantities): """ Runs the Baum Welch Algorithm and finds the new model parameters **Arguments**: :param observation_list: A nested list, or a list of lists :type observation_list: Contains a list multiple observation sequences. ...
Runs the Baum Welch Algorithm and finds the new model parameters **Arguments**: :param observation_list: A nested list, or a list of lists :type observation_list: Contains a list multiple observation sequences. :param iterations: Maximum number of iterations for the algorithm ...
Below is the the instruction that describes the task: ### Input: Runs the Baum Welch Algorithm and finds the new model parameters **Arguments**: :param observation_list: A nested list, or a list of lists :type observation_list: Contains a list multiple observation sequences. :p...
def delete(self): ''' Deletes this model from the database, calling delete in each field to properly delete special cases ''' redis = type(self).get_redis() for fieldname, field in self.proxy: field.delete(redis) redis.delete(self.key()) redis.srem(type(self...
Deletes this model from the database, calling delete in each field to properly delete special cases
Below is the the instruction that describes the task: ### Input: Deletes this model from the database, calling delete in each field to properly delete special cases ### Response: def delete(self): ''' Deletes this model from the database, calling delete in each field to properly delete spec...
def XCHG(cpu, dest, src): """ Exchanges register/memory with register. Exchanges the contents of the destination (first) and source (second) operands. The operands can be two general-purpose registers or a register and a memory location. If a memory operand is referenced, the pr...
Exchanges register/memory with register. Exchanges the contents of the destination (first) and source (second) operands. The operands can be two general-purpose registers or a register and a memory location. If a memory operand is referenced, the processor's locking protocol is automati...
Below is the the instruction that describes the task: ### Input: Exchanges register/memory with register. Exchanges the contents of the destination (first) and source (second) operands. The operands can be two general-purpose registers or a register and a memory location. If a memory operan...
def _get_distance_scaling_term(self, C, mag, rrup): """ Returns the magnitude dependent distance scaling term """ if mag < 6.75: mag_factor = -(C["b1_lo"] + C["b2_lo"] * mag) else: mag_factor = -(C["b1_hi"] + C["b2_hi"] * mag) return mag_factor * n...
Returns the magnitude dependent distance scaling term
Below is the the instruction that describes the task: ### Input: Returns the magnitude dependent distance scaling term ### Response: def _get_distance_scaling_term(self, C, mag, rrup): """ Returns the magnitude dependent distance scaling term """ if mag < 6.75: mag_facto...
def search_show_top_unite(self, category, genre=None, area=None, year=None, orderby=None, headnum=1, tailnum=1, onesiteflag=None, page=1, count=20): """doc: http://open.youku.com/docs/doc?id=86 """ url = 'h...
doc: http://open.youku.com/docs/doc?id=86
Below is the the instruction that describes the task: ### Input: doc: http://open.youku.com/docs/doc?id=86 ### Response: def search_show_top_unite(self, category, genre=None, area=None, year=None, orderby=None, headnum=1, tailnum=1, onesiteflag=None, ...