code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def create_key(key_name, save_path, region=None, key=None, keyid=None, profile=None): ''' Creates a key and saves it to a given path. Returns the private key. CLI Example: .. code-block:: bash salt myminion boto_ec2.create_key mykey /root/ ''' conn = _get_conn(regio...
Creates a key and saves it to a given path. Returns the private key. CLI Example: .. code-block:: bash salt myminion boto_ec2.create_key mykey /root/
Below is the the instruction that describes the task: ### Input: Creates a key and saves it to a given path. Returns the private key. CLI Example: .. code-block:: bash salt myminion boto_ec2.create_key mykey /root/ ### Response: def create_key(key_name, save_path, region=None, key=None, keyi...
def save(self, designName=""): # type: (ASaveDesign) -> None """Save the current design to file""" self.try_stateful_function( ss.SAVING, ss.READY, self.do_save, designName)
Save the current design to file
Below is the the instruction that describes the task: ### Input: Save the current design to file ### Response: def save(self, designName=""): # type: (ASaveDesign) -> None """Save the current design to file""" self.try_stateful_function( ss.SAVING, ss.READY, self.do_save, design...
def registerInternalRouters(app): """ These are the endpoints which are used to display measurements in the flask-profiler dashboard. Note: these should be defined after wrapping user defined endpoints via wrapAppEndpoints() :param app: Flask application instance :return: """ urlPat...
These are the endpoints which are used to display measurements in the flask-profiler dashboard. Note: these should be defined after wrapping user defined endpoints via wrapAppEndpoints() :param app: Flask application instance :return:
Below is the the instruction that describes the task: ### Input: These are the endpoints which are used to display measurements in the flask-profiler dashboard. Note: these should be defined after wrapping user defined endpoints via wrapAppEndpoints() :param app: Flask application instance :ret...
def _parse_pool_transaction_file( ledger, nodeReg, cliNodeReg, nodeKeys, activeValidators, ledger_size=None): """ helper function for parseLedgerForHaAndKeys """ for _, txn in ledger.getAllTxn(to=ledger_size): if get_type(txn) == NODE: ...
helper function for parseLedgerForHaAndKeys
Below is the the instruction that describes the task: ### Input: helper function for parseLedgerForHaAndKeys ### Response: def _parse_pool_transaction_file( ledger, nodeReg, cliNodeReg, nodeKeys, activeValidators, ledger_size=None): """ helper function for parseLedgerForHaAn...
def RunValidationFromOptions(feed, options): """Validate feed, run in profiler if in options, and return an exit code.""" if options.performance: return ProfileRunValidationOutputFromOptions(feed, options) else: return RunValidationOutputFromOptions(feed, options)
Validate feed, run in profiler if in options, and return an exit code.
Below is the the instruction that describes the task: ### Input: Validate feed, run in profiler if in options, and return an exit code. ### Response: def RunValidationFromOptions(feed, options): """Validate feed, run in profiler if in options, and return an exit code.""" if options.performance: return Prof...
def discard(self, changeset_id: uuid.UUID) -> None: """ Throws away all journaled data starting at the given changeset """ self._validate_changeset(changeset_id) self.journal.pop_changeset(changeset_id)
Throws away all journaled data starting at the given changeset
Below is the the instruction that describes the task: ### Input: Throws away all journaled data starting at the given changeset ### Response: def discard(self, changeset_id: uuid.UUID) -> None: """ Throws away all journaled data starting at the given changeset """ self._validate_cha...
def textalign(text, maxlength, align='left'): """ Align Text When Given Full Length """ if align == 'left': return text elif align == 'centre' or align == 'center': spaces = ' ' * (int((maxlength - len(text)) / 2)) elif align == 'right': spaces = (maxlength - len(text)) ...
Align Text When Given Full Length
Below is the the instruction that describes the task: ### Input: Align Text When Given Full Length ### Response: def textalign(text, maxlength, align='left'): """ Align Text When Given Full Length """ if align == 'left': return text elif align == 'centre' or align == 'center': s...
def integrate(self,t,pot,method='symplec4_c',dt=None): """ NAME: integrate PURPOSE: integrate the orbit INPUT: t - list of times at which to output (0 has to be in this!) pot - potential instance or list of instances method= 'odeint'...
NAME: integrate PURPOSE: integrate the orbit INPUT: t - list of times at which to output (0 has to be in this!) pot - potential instance or list of instances method= 'odeint' for scipy's odeint 'leapfrog' for a simple leapfrog imp...
Below is the the instruction that describes the task: ### Input: NAME: integrate PURPOSE: integrate the orbit INPUT: t - list of times at which to output (0 has to be in this!) pot - potential instance or list of instances method= 'odeint' for s...
def INDEX_OF_CP(string_expression, substring_expression, start=None, end=None): """ Searches a string for an occurence of a substring and returns the UTF-8 code point index (zero-based) of the first occurence. If the substring is not found, returns -1. https://docs.mongodb.com/manual/reference/operator/...
Searches a string for an occurence of a substring and returns the UTF-8 code point index (zero-based) of the first occurence. If the substring is not found, returns -1. https://docs.mongodb.com/manual/reference/operator/aggregation/indexOfCP/ for more details :param string_expression: The string or expr...
Below is the the instruction that describes the task: ### Input: Searches a string for an occurence of a substring and returns the UTF-8 code point index (zero-based) of the first occurence. If the substring is not found, returns -1. https://docs.mongodb.com/manual/reference/operator/aggregation/indexOfCP/ ...
def getFieldsForActiveJobsOfType(self, jobType, fields=[]): """ Helper function for querying the models table including relevant job info where the job type matches the specified jobType. Only records for which there is a matching jobId in both tables is returned, and only the requested fields are retu...
Helper function for querying the models table including relevant job info where the job type matches the specified jobType. Only records for which there is a matching jobId in both tables is returned, and only the requested fields are returned in each result, assuming that there is not a conflict. Thi...
Below is the the instruction that describes the task: ### Input: Helper function for querying the models table including relevant job info where the job type matches the specified jobType. Only records for which there is a matching jobId in both tables is returned, and only the requested fields are ret...
def _is_updated(old_conf, new_conf): ''' Compare the API results to the current statefile data ''' changed = {} # Dirty json hacking to get parameters in the same format new_conf = _json_to_unicode(salt.utils.json.loads( salt.utils.json.dumps(new_conf, ensure_ascii=False))) old_conf...
Compare the API results to the current statefile data
Below is the the instruction that describes the task: ### Input: Compare the API results to the current statefile data ### Response: def _is_updated(old_conf, new_conf): ''' Compare the API results to the current statefile data ''' changed = {} # Dirty json hacking to get parameters in the sam...
def field_value(self, value): """Validate against NodeType. """ if not self.is_array: return self.field_type(value) if isinstance(value, (list, tuple, set)): return [self.field_type(item) for item in value] return self.field_type(value)
Validate against NodeType.
Below is the the instruction that describes the task: ### Input: Validate against NodeType. ### Response: def field_value(self, value): """Validate against NodeType. """ if not self.is_array: return self.field_type(value) if isinstance(value, (list, tuple, set)): ...
def get_monitor_value(self): "Pick the monitored value." if self.monitor=='trn_loss' and len(self.learn.recorder.losses) == 0: return None elif len(self.learn.recorder.val_losses) == 0: return None values = {'train_loss':self.learn.recorder.losses[-1].cpu().numpy(), 'va...
Pick the monitored value.
Below is the the instruction that describes the task: ### Input: Pick the monitored value. ### Response: def get_monitor_value(self): "Pick the monitored value." if self.monitor=='trn_loss' and len(self.learn.recorder.losses) == 0: return None elif len(self.learn.recorder.val_losses) == 0: ...
def ndcg(truth, recommend, k=None): """Normalized Discounted Cumulative Grain (NDCG). Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. k (int): Top-k items in `recommend` will be recommended. Returns: float:...
Normalized Discounted Cumulative Grain (NDCG). Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. k (int): Top-k items in `recommend` will be recommended. Returns: float: NDCG.
Below is the the instruction that describes the task: ### Input: Normalized Discounted Cumulative Grain (NDCG). Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. k (int): Top-k items in `recommend` will be recommended. ...
def bind(self, source, dest, destmeth): """Guild compatible version of :py:meth:`connect`. This allows Pyctools compound components to be used in `Guild <https://github.com/sparkslabs/guild>`_ pipelines. """ self.connect(source, getattr(dest, destmeth))
Guild compatible version of :py:meth:`connect`. This allows Pyctools compound components to be used in `Guild <https://github.com/sparkslabs/guild>`_ pipelines.
Below is the the instruction that describes the task: ### Input: Guild compatible version of :py:meth:`connect`. This allows Pyctools compound components to be used in `Guild <https://github.com/sparkslabs/guild>`_ pipelines. ### Response: def bind(self, source, dest, destmeth): """Guild c...
def will_set(self, topic, payload=None, qos=0, retain=False): """Set a Will to be sent by the broker in case the client disconnects unexpectedly. This must be called before connect() to have any effect. topic: The topic that the will message should be published on. payload: The message...
Set a Will to be sent by the broker in case the client disconnects unexpectedly. This must be called before connect() to have any effect. topic: The topic that the will message should be published on. payload: The message to send as a will. If not given, or set to None a zero length me...
Below is the the instruction that describes the task: ### Input: Set a Will to be sent by the broker in case the client disconnects unexpectedly. This must be called before connect() to have any effect. topic: The topic that the will message should be published on. payload: The message to ...
def Close(self): """Close and destroy the object. This is similar to Flush, but does not maintain object validity. Hence the object should not be interacted with after Close(). Raises: LockError: The lease for this object has expired. """ if self.locked and self.CheckLease() == 0: ...
Close and destroy the object. This is similar to Flush, but does not maintain object validity. Hence the object should not be interacted with after Close(). Raises: LockError: The lease for this object has expired.
Below is the the instruction that describes the task: ### Input: Close and destroy the object. This is similar to Flush, but does not maintain object validity. Hence the object should not be interacted with after Close(). Raises: LockError: The lease for this object has expired. ### Response: ...
def rle_decode(mask_rle:str, shape:Tuple[int,int])->NPArrayMask: "Return an image array from run-length encoded string `mask_rle` with `shape`." s = mask_rle.split() starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])] starts -= 1 ends = starts + lengths img = np.zeros(...
Return an image array from run-length encoded string `mask_rle` with `shape`.
Below is the the instruction that describes the task: ### Input: Return an image array from run-length encoded string `mask_rle` with `shape`. ### Response: def rle_decode(mask_rle:str, shape:Tuple[int,int])->NPArrayMask: "Return an image array from run-length encoded string `mask_rle` with `shape`." s = m...
def retired(self): """ Function for generating retired languages. Returns a dict('code', (datetime, [language, ...], 'description')). """ def gen(): import csv import re from datetime import datetime from pkg_resources import resource_file...
Function for generating retired languages. Returns a dict('code', (datetime, [language, ...], 'description')).
Below is the the instruction that describes the task: ### Input: Function for generating retired languages. Returns a dict('code', (datetime, [language, ...], 'description')). ### Response: def retired(self): """ Function for generating retired languages. Returns a dict('code', (datetime, [language...
def add_mvn(self, name, input_name, output_name, across_channels = True, normalize_variance = True, epsilon = 1e-5): """ Add an MVN (mean variance normalization) layer. Computes mean, variance and normalizes the input. Parameters ---------- name: str The name of this...
Add an MVN (mean variance normalization) layer. Computes mean, variance and normalizes the input. Parameters ---------- name: str The name of this layer. input_name: str The input blob name of this layer. output_name: str The output blob name...
Below is the the instruction that describes the task: ### Input: Add an MVN (mean variance normalization) layer. Computes mean, variance and normalizes the input. Parameters ---------- name: str The name of this layer. input_name: str The input blob name of ...
def enter(self, delay, priority, action, argument=(), kwargs=_sentinel): """A variant that specifies the time as a relative time. This is actually the more commonly used interface. """ time = self.timefunc() + delay return self.enterabs(time, priority, action, argument, kwargs)
A variant that specifies the time as a relative time. This is actually the more commonly used interface.
Below is the the instruction that describes the task: ### Input: A variant that specifies the time as a relative time. This is actually the more commonly used interface. ### Response: def enter(self, delay, priority, action, argument=(), kwargs=_sentinel): """A variant that specifies the time as a...
def _alignment(elist, flist, e2f, f2e): ''' elist, flist wordlist for each language e2f translatoin alignment from e to f alignment is [(e, f)] f2e translatoin alignment from f to e alignment is [(e, f)] return alignment: {...
elist, flist wordlist for each language e2f translatoin alignment from e to f alignment is [(e, f)] f2e translatoin alignment from f to e alignment is [(e, f)] return alignment: {(f, e)} flist ---------------...
Below is the the instruction that describes the task: ### Input: elist, flist wordlist for each language e2f translatoin alignment from e to f alignment is [(e, f)] f2e translatoin alignment from f to e alignment is [(e, f)] return ...
def fix_header(pofile): """ Replace default headers with edX headers """ # By default, django-admin.py makemessages creates this header: # # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE...
Replace default headers with edX headers
Below is the the instruction that describes the task: ### Input: Replace default headers with edX headers ### Response: def fix_header(pofile): """ Replace default headers with edX headers """ # By default, django-admin.py makemessages creates this header: # # SOME DESCRIPTIVE TITLE. ...
def isclose(a, b, rel_tol=1e-10, abs_tol=0.0): """ Compares two parameter values. :param a: First parameter :param b: Second parameter :param rel_tol: Relative tolerance :param abs_tol: Absolute tolerance :return: Boolean telling whether or not the parameters are close enough to be the same ...
Compares two parameter values. :param a: First parameter :param b: Second parameter :param rel_tol: Relative tolerance :param abs_tol: Absolute tolerance :return: Boolean telling whether or not the parameters are close enough to be the same
Below is the the instruction that describes the task: ### Input: Compares two parameter values. :param a: First parameter :param b: Second parameter :param rel_tol: Relative tolerance :param abs_tol: Absolute tolerance :return: Boolean telling whether or not the parameters are close enough to be...
def create_widget(self): """ Create the underlying widget. A dialog is not a subclass of view, hence we don't set name as widget or children will try to use it as their parent. """ d = self.declaration style = d.style or '@style/Widget.DeviceDefault.PopupMenu' s...
Create the underlying widget. A dialog is not a subclass of view, hence we don't set name as widget or children will try to use it as their parent.
Below is the the instruction that describes the task: ### Input: Create the underlying widget. A dialog is not a subclass of view, hence we don't set name as widget or children will try to use it as their parent. ### Response: def create_widget(self): """ Create the underlying widget. ...
def revoke_role(self, role_name, principal_name, principal_type): """ Parameters: - role_name - principal_name - principal_type """ self.send_revoke_role(role_name, principal_name, principal_type) return self.recv_revoke_role()
Parameters: - role_name - principal_name - principal_type
Below is the the instruction that describes the task: ### Input: Parameters: - role_name - principal_name - principal_type ### Response: def revoke_role(self, role_name, principal_name, principal_type): """ Parameters: - role_name - principal_name - principal_type """ ...
def get_default_config(self): """ Returns the default collector settings """ config = super(EndecaDgraphCollector, self).get_default_config() config.update({ 'path': 'endeca.dgraph', 'host': 'localhost', 'port': 8080, 'timeout': 1, ...
Returns the default collector settings
Below is the the instruction that describes the task: ### Input: Returns the default collector settings ### Response: def get_default_config(self): """ Returns the default collector settings """ config = super(EndecaDgraphCollector, self).get_default_config() config.update({...
def get_registry_value(key, default=None): """ Gets the utility for IRegistry and returns the value for the key passed in. If there is no value for the key passed in, returns default value :param key: the key in the registry to look for :param default: default value if the key is not registered ...
Gets the utility for IRegistry and returns the value for the key passed in. If there is no value for the key passed in, returns default value :param key: the key in the registry to look for :param default: default value if the key is not registered :return: value in the registry for the key passed in
Below is the the instruction that describes the task: ### Input: Gets the utility for IRegistry and returns the value for the key passed in. If there is no value for the key passed in, returns default value :param key: the key in the registry to look for :param default: default value if the key is not r...
def parse_size_name(type_name): """Calculate size and encoding from a type name. This method takes a C-style type string like uint8_t[10] and returns - the total size in bytes - the unit size of each member (if it's an array) - the scruct.{pack,unpack} format code for decoding the base type - w...
Calculate size and encoding from a type name. This method takes a C-style type string like uint8_t[10] and returns - the total size in bytes - the unit size of each member (if it's an array) - the scruct.{pack,unpack} format code for decoding the base type - whether it is an array.
Below is the the instruction that describes the task: ### Input: Calculate size and encoding from a type name. This method takes a C-style type string like uint8_t[10] and returns - the total size in bytes - the unit size of each member (if it's an array) - the scruct.{pack,unpack} format code for ...
def encrypt_to_file(contents, filename): """ Encrypts ``contents`` and writes it to ``filename``. ``contents`` should be a bytes string. ``filename`` should end with ``.enc``. Returns the secret key used for the encryption. Decrypt the file with :func:`doctr.travis.decrypt_file`. """ ...
Encrypts ``contents`` and writes it to ``filename``. ``contents`` should be a bytes string. ``filename`` should end with ``.enc``. Returns the secret key used for the encryption. Decrypt the file with :func:`doctr.travis.decrypt_file`.
Below is the the instruction that describes the task: ### Input: Encrypts ``contents`` and writes it to ``filename``. ``contents`` should be a bytes string. ``filename`` should end with ``.enc``. Returns the secret key used for the encryption. Decrypt the file with :func:`doctr.travis.decrypt_fil...
def _call_yum(args, **kwargs): ''' Call yum/dnf. ''' params = {'output_loglevel': 'trace', 'python_shell': False, 'env': salt.utils.environment.get_module_environment(globals())} params.update(kwargs) cmd = [] if salt.utils.systemd.has_scope(__context__) and __sal...
Call yum/dnf.
Below is the the instruction that describes the task: ### Input: Call yum/dnf. ### Response: def _call_yum(args, **kwargs): ''' Call yum/dnf. ''' params = {'output_loglevel': 'trace', 'python_shell': False, 'env': salt.utils.environment.get_module_environment(globals())}...
def filter_data(self, min_len, max_len): """ Preserves only samples which satisfy the following inequality: min_len <= sample sequence length <= max_len :param min_len: minimum sequence length :param max_len: maximum sequence length """ logging.info(f'Filteri...
Preserves only samples which satisfy the following inequality: min_len <= sample sequence length <= max_len :param min_len: minimum sequence length :param max_len: maximum sequence length
Below is the the instruction that describes the task: ### Input: Preserves only samples which satisfy the following inequality: min_len <= sample sequence length <= max_len :param min_len: minimum sequence length :param max_len: maximum sequence length ### Response: def filter_data(sel...
def clone(id, path): """ - Download all files in a dataset or from a Job output Eg: alice/projects/mnist/1/files, alice/projects/mnist/1/output or alice/dataset/mnist-data/1/ Using /output will download the files that are saved at the end of the job. Note: This will download the files that are sa...
- Download all files in a dataset or from a Job output Eg: alice/projects/mnist/1/files, alice/projects/mnist/1/output or alice/dataset/mnist-data/1/ Using /output will download the files that are saved at the end of the job. Note: This will download the files that are saved at the end of the job. ...
Below is the the instruction that describes the task: ### Input: - Download all files in a dataset or from a Job output Eg: alice/projects/mnist/1/files, alice/projects/mnist/1/output or alice/dataset/mnist-data/1/ Using /output will download the files that are saved at the end of the job. Note: This...
def remove_useless(self): """Returns a new grammar containing just useful rules.""" if not self.is_contextfree(): raise ValueError("grammar must be context-free") by_lhs = collections.defaultdict(list) by_rhs = collections.defaultdict(list) for [lhs], rhs in self.rule...
Returns a new grammar containing just useful rules.
Below is the the instruction that describes the task: ### Input: Returns a new grammar containing just useful rules. ### Response: def remove_useless(self): """Returns a new grammar containing just useful rules.""" if not self.is_contextfree(): raise ValueError("grammar must be context-...
def load_project(cls, fname, auto_update=None, make_plot=True, draw=False, alternative_axes=None, main=False, encoding=None, enable_post=False, new_fig=True, clear=None, **kwargs): """ Load a project from a file or dict This classme...
Load a project from a file or dict This classmethod allows to load a project that has been stored using the :meth:`save_project` method and reads all the data and creates the figures. Since the data is stored in external files when saving a project, make sure that the data is a...
Below is the the instruction that describes the task: ### Input: Load a project from a file or dict This classmethod allows to load a project that has been stored using the :meth:`save_project` method and reads all the data and creates the figures. Since the data is stored in exter...
def turnstile_command(conf_file, command, arguments=[], channel=None, debug=False): """ Issue a command to all running control daemons. :param conf_file: Name of the configuration file. :param command: The command to execute. Note that 'ping' is handled specia...
Issue a command to all running control daemons. :param conf_file: Name of the configuration file. :param command: The command to execute. Note that 'ping' is handled specially; in particular, the "channel" parameter is implied. (A random value will be ...
Below is the the instruction that describes the task: ### Input: Issue a command to all running control daemons. :param conf_file: Name of the configuration file. :param command: The command to execute. Note that 'ping' is handled specially; in particular, the "channel" ...
def create_email(self, name, subject, html, text=''): """ [DECPRECATED] API call to create an email """ return self.create_template(name, subject, html, text)
[DECPRECATED] API call to create an email
Below is the the instruction that describes the task: ### Input: [DECPRECATED] API call to create an email ### Response: def create_email(self, name, subject, html, text=''): """ [DECPRECATED] API call to create an email """ return self.create_template(name, subject, html, text)
def _raw_pack(key_handle, flags, data): """ Common code for packing payload to YHSM_HMAC_SHA1_GENERATE command. """ # #define YHSM_HMAC_RESET 0x01 // Flag to indicate reset at first packet # #define YHSM_HMAC_FINAL 0x02 // Flag to indicate that the hash shall be calculated ...
Common code for packing payload to YHSM_HMAC_SHA1_GENERATE command.
Below is the the instruction that describes the task: ### Input: Common code for packing payload to YHSM_HMAC_SHA1_GENERATE command. ### Response: def _raw_pack(key_handle, flags, data): """ Common code for packing payload to YHSM_HMAC_SHA1_GENERATE command. """ # #define YHSM_HMAC_RESET 0...
def _stop_ubridge_capture(self, adapter_number): """ Stop a packet capture in uBridge. :param adapter_number: adapter number """ vnet = "ethernet{}.vnet".format(adapter_number) if vnet not in self._vmx_pairs: raise VMwareError("vnet {} not in VMX file".forma...
Stop a packet capture in uBridge. :param adapter_number: adapter number
Below is the the instruction that describes the task: ### Input: Stop a packet capture in uBridge. :param adapter_number: adapter number ### Response: def _stop_ubridge_capture(self, adapter_number): """ Stop a packet capture in uBridge. :param adapter_number: adapter number ...
def revnet_cifar_base(): """Tiny hparams suitable for CIFAR/etc.""" hparams = revnet_base() hparams.num_channels_init_block = 32 hparams.first_batch_norm = [False, True, True] hparams.init_stride = 1 hparams.init_kernel_size = 3 hparams.init_maxpool = False hparams.strides = [1, 2, 2] hparams.batch_si...
Tiny hparams suitable for CIFAR/etc.
Below is the the instruction that describes the task: ### Input: Tiny hparams suitable for CIFAR/etc. ### Response: def revnet_cifar_base(): """Tiny hparams suitable for CIFAR/etc.""" hparams = revnet_base() hparams.num_channels_init_block = 32 hparams.first_batch_norm = [False, True, True] hparams.init_...
def normalize_path(path, base_path=u'/', is_dir=None): u""" Normalize a path to use it with a gitmatch pattern. This ensures that the separators are forward slashes. If a path is rooted (starts with a slash), it has to be a subdirectory of `base_path`. The path root is then changed to be based of `b...
u""" Normalize a path to use it with a gitmatch pattern. This ensures that the separators are forward slashes. If a path is rooted (starts with a slash), it has to be a subdirectory of `base_path`. The path root is then changed to be based of `base_path`. :type path: text_type :param path: A PO...
Below is the the instruction that describes the task: ### Input: u""" Normalize a path to use it with a gitmatch pattern. This ensures that the separators are forward slashes. If a path is rooted (starts with a slash), it has to be a subdirectory of `base_path`. The path root is then changed to be b...
def getSingleVisualProperty(self, visualProperty, verbose=None): """ Return the Visual Property specified by the `visualProperty` parameter. Additional details on common Visual Properties can be found in the [Basic Visual Lexicon JavaDoc API](http://chianti.ucsd.edu/cytoscape-3.6.1/API/...
Return the Visual Property specified by the `visualProperty` parameter. Additional details on common Visual Properties can be found in the [Basic Visual Lexicon JavaDoc API](http://chianti.ucsd.edu/cytoscape-3.6.1/API/org/cytoscape/view/presentation/property/BasicVisualLexicon.html) :param vis...
Below is the the instruction that describes the task: ### Input: Return the Visual Property specified by the `visualProperty` parameter. Additional details on common Visual Properties can be found in the [Basic Visual Lexicon JavaDoc API](http://chianti.ucsd.edu/cytoscape-3.6.1/API/org/cytoscape/vi...
def find_match_command(self, rule): """Return a matching (possibly munged) command, if found in rule.""" command_string = rule['command'] command_list = command_string.split() self.logdebug('comparing "%s" to "%s"\n' % (command_list, self.original_command_list)) ...
Return a matching (possibly munged) command, if found in rule.
Below is the the instruction that describes the task: ### Input: Return a matching (possibly munged) command, if found in rule. ### Response: def find_match_command(self, rule): """Return a matching (possibly munged) command, if found in rule.""" command_string = rule['command'] command_li...
def nac_v(msg): """Calculate NACv, Navigation Accuracy Category - Velocity Args: msg (string): 28 bytes hexadecimal message string, TC = 19 Returns: int or string: 95% horizontal accuracy bounds for velocity, Horizontal Figure of Merit int or string: 95% vertical accuracy bounds fo...
Calculate NACv, Navigation Accuracy Category - Velocity Args: msg (string): 28 bytes hexadecimal message string, TC = 19 Returns: int or string: 95% horizontal accuracy bounds for velocity, Horizontal Figure of Merit int or string: 95% vertical accuracy bounds for velocity, Vertical Fi...
Below is the the instruction that describes the task: ### Input: Calculate NACv, Navigation Accuracy Category - Velocity Args: msg (string): 28 bytes hexadecimal message string, TC = 19 Returns: int or string: 95% horizontal accuracy bounds for velocity, Horizontal Figure of Merit ...
def create_server(cloud, **kwargs): """ Create a new instance """ if cloud == 'ec2': _create_server_ec2(**kwargs) elif cloud == 'rackspace': _create_server_rackspace(**kwargs) elif cloud == 'gce': _create_server_gce(**kwargs) else: raise ValueError("Unknow...
Create a new instance
Below is the the instruction that describes the task: ### Input: Create a new instance ### Response: def create_server(cloud, **kwargs): """ Create a new instance """ if cloud == 'ec2': _create_server_ec2(**kwargs) elif cloud == 'rackspace': _create_server_rackspace(**kwargs...
def permission_required_with_ajax(perm, login_url=None): """ Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary, but returns a special response for ajax requests. See :meth:`eulcore.django.auth.decorators.user_passes_test_...
Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary, but returns a special response for ajax requests. See :meth:`eulcore.django.auth.decorators.user_passes_test_with_ajax`. Usage is the same as :meth:`django.contrib.auth....
Below is the the instruction that describes the task: ### Input: Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary, but returns a special response for ajax requests. See :meth:`eulcore.django.auth.decorators.user_passes_test_...
def get_website_endpoint(self): """ Returns the fully qualified hostname to use is you want to access this bucket as a website. This doesn't validate whether the bucket has been correctly configured as a website or not. """ l = [self.name] l.append(S3WebsiteEndpo...
Returns the fully qualified hostname to use is you want to access this bucket as a website. This doesn't validate whether the bucket has been correctly configured as a website or not.
Below is the the instruction that describes the task: ### Input: Returns the fully qualified hostname to use is you want to access this bucket as a website. This doesn't validate whether the bucket has been correctly configured as a website or not. ### Response: def get_website_endpoint(self): ...
def batch_predict(training_dir, prediction_input_file, output_dir, mode, batch_size=16, shard_files=True, output_format='csv', cloud=False): """Blocking versoin of batch_predict. See documentation of batch_prediction_async. """ job = batch_predict_async( training_dir=t...
Blocking versoin of batch_predict. See documentation of batch_prediction_async.
Below is the the instruction that describes the task: ### Input: Blocking versoin of batch_predict. See documentation of batch_prediction_async. ### Response: def batch_predict(training_dir, prediction_input_file, output_dir, mode, batch_size=16, shard_files=True, output_format='csv', ...
def create_snapshot(self, volume, name=None, description=None, force=False): """ Creates a snapshot of the volume, with an optional name and description. Normally snapshots will not happen if the volume is attached. To override this default behavior, pass force=True. """ ...
Creates a snapshot of the volume, with an optional name and description. Normally snapshots will not happen if the volume is attached. To override this default behavior, pass force=True.
Below is the the instruction that describes the task: ### Input: Creates a snapshot of the volume, with an optional name and description. Normally snapshots will not happen if the volume is attached. To override this default behavior, pass force=True. ### Response: def create_snapshot(self, volume...
def clear_selection(self): """Clears text cursor selection.""" text_cursor = self._editor.textCursor() text_cursor.clearSelection() self._editor.setTextCursor(text_cursor)
Clears text cursor selection.
Below is the the instruction that describes the task: ### Input: Clears text cursor selection. ### Response: def clear_selection(self): """Clears text cursor selection.""" text_cursor = self._editor.textCursor() text_cursor.clearSelection() self._editor.setTextCursor(text_cursor)
def import_authors(self, tree): """ Retrieve all the authors used in posts and convert it to new or existing author and return the conversion. """ self.write_out(self.style.STEP('- Importing authors\n')) post_authors = set() for item in tree.findall('chan...
Retrieve all the authors used in posts and convert it to new or existing author and return the conversion.
Below is the the instruction that describes the task: ### Input: Retrieve all the authors used in posts and convert it to new or existing author and return the conversion. ### Response: def import_authors(self, tree): """ Retrieve all the authors used in posts and convert it...
def set(self, name, value): """ Stores the given variable/value in the object for later retrieval. :type name: string :param name: The name of the variable. :type value: object :param value: The value of the variable. """ if self.vars is None: ...
Stores the given variable/value in the object for later retrieval. :type name: string :param name: The name of the variable. :type value: object :param value: The value of the variable.
Below is the the instruction that describes the task: ### Input: Stores the given variable/value in the object for later retrieval. :type name: string :param name: The name of the variable. :type value: object :param value: The value of the variable. ### Response: def set(self, n...
def arc(self, radius, initial_angle, final_angle, number_of_points=0.01, max_points=199, final_width=None, final_distance=None, layer=0, datatype=0): """ Add a curved section to the path. ...
Add a curved section to the path. Parameters ---------- radius : number Central radius of the section. initial_angle : number Initial angle of the curve (in *radians*). final_angle : number Final angle of the curve (in *radians*). numb...
Below is the the instruction that describes the task: ### Input: Add a curved section to the path. Parameters ---------- radius : number Central radius of the section. initial_angle : number Initial angle of the curve (in *radians*). final_angle : num...
def remove_external_data_field(tensor, field_key): # type: (TensorProto, Text) -> None """ Remove a field from a Tensor's external_data key-value store. Modifies tensor object in place. @params tensor: Tensor object from which value will be removed field_key: The key of the field to be remove...
Remove a field from a Tensor's external_data key-value store. Modifies tensor object in place. @params tensor: Tensor object from which value will be removed field_key: The key of the field to be removed
Below is the the instruction that describes the task: ### Input: Remove a field from a Tensor's external_data key-value store. Modifies tensor object in place. @params tensor: Tensor object from which value will be removed field_key: The key of the field to be removed ### Response: def remove_ext...
def err(self, output, newline=True): """Outputs an error string to the console (stderr).""" click.echo(output, nl=newline, err=True)
Outputs an error string to the console (stderr).
Below is the the instruction that describes the task: ### Input: Outputs an error string to the console (stderr). ### Response: def err(self, output, newline=True): """Outputs an error string to the console (stderr).""" click.echo(output, nl=newline, err=True)
def delete_collection_cluster_role_binding(self, **kwargs): """ delete collection of ClusterRoleBinding This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_cluster_role_bindin...
delete collection of ClusterRoleBinding This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_cluster_role_binding(async_req=True) >>> result = thread.get() :param async_req bo...
Below is the the instruction that describes the task: ### Input: delete collection of ClusterRoleBinding This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_cluster_role_binding(async_req...
def ToStream(value): """ Serialize the given `value` to a an array of bytes. Args: value (neo.IO.Mixins.SerializableMixin): object extending SerializableMixin. Returns: bytes: not hexlified """ ms = StreamManager.GetStream() writer = Bina...
Serialize the given `value` to a an array of bytes. Args: value (neo.IO.Mixins.SerializableMixin): object extending SerializableMixin. Returns: bytes: not hexlified
Below is the the instruction that describes the task: ### Input: Serialize the given `value` to a an array of bytes. Args: value (neo.IO.Mixins.SerializableMixin): object extending SerializableMixin. Returns: bytes: not hexlified ### Response: def ToStream(value): ...
def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering c...
Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC ...
Below is the the instruction that describes the task: ### Input: Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. ver...
def echo(msg, *args, **kwargs): '''Wraps click.echo, handles formatting and check encoding''' file = kwargs.pop('file', None) nl = kwargs.pop('nl', True) err = kwargs.pop('err', False) color = kwargs.pop('color', None) msg = safe_unicode(msg).format(*args, **kwargs) click.echo(msg, file=file...
Wraps click.echo, handles formatting and check encoding
Below is the the instruction that describes the task: ### Input: Wraps click.echo, handles formatting and check encoding ### Response: def echo(msg, *args, **kwargs): '''Wraps click.echo, handles formatting and check encoding''' file = kwargs.pop('file', None) nl = kwargs.pop('nl', True) err = kwar...
def send(self, messages): """Send a SMS message, or an array of SMS messages""" tmpSms = SMS(to='', message='') if str(type(messages)) == str(type(tmpSms)): messages = [messages] xml_root = self.__init_xml('Message') wrapper_id = 0 for m in messages: ...
Send a SMS message, or an array of SMS messages
Below is the the instruction that describes the task: ### Input: Send a SMS message, or an array of SMS messages ### Response: def send(self, messages): """Send a SMS message, or an array of SMS messages""" tmpSms = SMS(to='', message='') if str(type(messages)) == str(type(tmpSms)): ...
def itin(self): """Generate a random United States Individual Taxpayer Identification Number (ITIN). An United States Individual Taxpayer Identification Number (ITIN) is a tax processing number issued by the Internal Revenue Service. It is a nine-digit number that always begins ...
Generate a random United States Individual Taxpayer Identification Number (ITIN). An United States Individual Taxpayer Identification Number (ITIN) is a tax processing number issued by the Internal Revenue Service. It is a nine-digit number that always begins with the number 9 and has a...
Below is the the instruction that describes the task: ### Input: Generate a random United States Individual Taxpayer Identification Number (ITIN). An United States Individual Taxpayer Identification Number (ITIN) is a tax processing number issued by the Internal Revenue Service. It is a nin...
def ingest(topic, text, **kwargs): """ Ingest the given text for the topic """ if not text: raise ValueError('No text given to ingest for topic: ' + topic) data = {'topic': topic, 'text': text.strip()} data.update(kwargs) db.markovify.insert(data)
Ingest the given text for the topic
Below is the the instruction that describes the task: ### Input: Ingest the given text for the topic ### Response: def ingest(topic, text, **kwargs): """ Ingest the given text for the topic """ if not text: raise ValueError('No text given to ingest for topic: ' + topic) data = {'topic': topic, ...
def start(self, callback, rate=SENSOR_DELAY_NORMAL): """ Start listening to sensor events. Sensor event data depends on the type of sensor that was given to Parameters ---------- callback: Callable A callback that takes one argument that will be pass...
Start listening to sensor events. Sensor event data depends on the type of sensor that was given to Parameters ---------- callback: Callable A callback that takes one argument that will be passed the sensor data. Sensor data is a dict with da...
Below is the the instruction that describes the task: ### Input: Start listening to sensor events. Sensor event data depends on the type of sensor that was given to Parameters ---------- callback: Callable A callback that takes one argument that will be ...
def _debug_log(self, msg): """Debug log messages if debug=True""" if not self.debug: return sys.stderr.write('{}\n'.format(msg))
Debug log messages if debug=True
Below is the the instruction that describes the task: ### Input: Debug log messages if debug=True ### Response: def _debug_log(self, msg): """Debug log messages if debug=True""" if not self.debug: return sys.stderr.write('{}\n'.format(msg))
def getLaneChangeState(self, vehID, direction): """getLaneChangeState(string, int) -> (int, int) Return the lane change state for the vehicle """ self._connection._beginMessage( tc.CMD_GET_VEHICLE_VARIABLE, tc.CMD_CHANGELANE, vehID, 1 + 4) self._connection._string += ...
getLaneChangeState(string, int) -> (int, int) Return the lane change state for the vehicle
Below is the the instruction that describes the task: ### Input: getLaneChangeState(string, int) -> (int, int) Return the lane change state for the vehicle ### Response: def getLaneChangeState(self, vehID, direction): """getLaneChangeState(string, int) -> (int, int) Return the lane change s...
def start(self, phase, stage, **kwargs): """Start a new routine, stage or phase""" return ProgressSection(self, self._session, phase, stage, self._logger, **kwargs)
Start a new routine, stage or phase
Below is the the instruction that describes the task: ### Input: Start a new routine, stage or phase ### Response: def start(self, phase, stage, **kwargs): """Start a new routine, stage or phase""" return ProgressSection(self, self._session, phase, stage, self._logger, **kwargs)
def calloc(self, sim_nmemb, sim_size): """ A somewhat faithful implementation of libc `calloc`. :param sim_nmemb: the number of elements to allocated :param sim_size: the size of each element (in bytes) :returns: the address of the allocation, or a NULL pointer if the a...
A somewhat faithful implementation of libc `calloc`. :param sim_nmemb: the number of elements to allocated :param sim_size: the size of each element (in bytes) :returns: the address of the allocation, or a NULL pointer if the allocation failed
Below is the the instruction that describes the task: ### Input: A somewhat faithful implementation of libc `calloc`. :param sim_nmemb: the number of elements to allocated :param sim_size: the size of each element (in bytes) :returns: the address of the allocation, or a NULL pointe...
def handle_one_request(self): """Handle a single HTTP request. You normally don't need to override this method; see the class __doc__ string for information on how to handle specific HTTP commands such as GET and POST. """ try: self.raw_requestline = self.rf...
Handle a single HTTP request. You normally don't need to override this method; see the class __doc__ string for information on how to handle specific HTTP commands such as GET and POST.
Below is the the instruction that describes the task: ### Input: Handle a single HTTP request. You normally don't need to override this method; see the class __doc__ string for information on how to handle specific HTTP commands such as GET and POST. ### Response: def handle_one_request(se...
def reverse(self, *args, **kwargs): """Look up a path by name and fill in the provided parameters. Example: >>> handler = lambda: None # just a bogus handler >>> router = PathRouter(('post', '/posts/{slug}', handler)) >>> router.reverse('post', slug='my-post') ...
Look up a path by name and fill in the provided parameters. Example: >>> handler = lambda: None # just a bogus handler >>> router = PathRouter(('post', '/posts/{slug}', handler)) >>> router.reverse('post', slug='my-post') '/posts/my-post'
Below is the the instruction that describes the task: ### Input: Look up a path by name and fill in the provided parameters. Example: >>> handler = lambda: None # just a bogus handler >>> router = PathRouter(('post', '/posts/{slug}', handler)) >>> router.reverse('post'...
def main(): """ Input asteroid family, filter type, and image type to query SSOIS """ parser = argparse.ArgumentParser(description='Run SSOIS and return the available images in a particular filter.') parser.add_argument("--filter", action="store", de...
Input asteroid family, filter type, and image type to query SSOIS
Below is the the instruction that describes the task: ### Input: Input asteroid family, filter type, and image type to query SSOIS ### Response: def main(): """ Input asteroid family, filter type, and image type to query SSOIS """ parser = argparse.ArgumentParser(description='Run SSOIS and return ...
def to_csc(self): """Convert Dataset to scipy's Compressed Sparse Column matrix.""" self._X_train = csc_matrix(self._X_train) self._X_test = csc_matrix(self._X_test)
Convert Dataset to scipy's Compressed Sparse Column matrix.
Below is the the instruction that describes the task: ### Input: Convert Dataset to scipy's Compressed Sparse Column matrix. ### Response: def to_csc(self): """Convert Dataset to scipy's Compressed Sparse Column matrix.""" self._X_train = csc_matrix(self._X_train) self._X_test = csc_matrix(...
def unlink(self): """unlinks the shared memory""" if os.name == "posix": self.__linux_unlink__() elif os.name == "nt": self.__windows_unlink__() else: raise HolodeckException("Currently unsupported os: " + os.name)
unlinks the shared memory
Below is the the instruction that describes the task: ### Input: unlinks the shared memory ### Response: def unlink(self): """unlinks the shared memory""" if os.name == "posix": self.__linux_unlink__() elif os.name == "nt": self.__windows_unlink__() else: ...
def _schedule_snapshot_retrieve(dataset, prefix, snapshots): ''' Update snapshots dict with current snapshots dataset: string name of filesystem or volume prefix : string prefix for the snapshots e.g. 'test' will result in snapshots being named 'test-yyyymmdd_hhmm' snapshots...
Update snapshots dict with current snapshots dataset: string name of filesystem or volume prefix : string prefix for the snapshots e.g. 'test' will result in snapshots being named 'test-yyyymmdd_hhmm' snapshots : OrderedDict preseeded OrderedDict with configuration
Below is the the instruction that describes the task: ### Input: Update snapshots dict with current snapshots dataset: string name of filesystem or volume prefix : string prefix for the snapshots e.g. 'test' will result in snapshots being named 'test-yyyymmdd_hhmm' snapshots : O...
def queue_actions(self, source, actions, event_args=None): """ Queue a list of \a actions for processing from \a source. Triggers an aura refresh afterwards. """ source.event_args = event_args ret = self.trigger_actions(source, actions) source.event_args = None return ret
Queue a list of \a actions for processing from \a source. Triggers an aura refresh afterwards.
Below is the the instruction that describes the task: ### Input: Queue a list of \a actions for processing from \a source. Triggers an aura refresh afterwards. ### Response: def queue_actions(self, source, actions, event_args=None): """ Queue a list of \a actions for processing from \a source. Triggers an ...
def execute(self, correlation_id, args): """ Executes the command given specific arguments as an input. Args: correlation_id: a unique correlation/transaction id args: command arguments Returns: an execution result. Rai...
Executes the command given specific arguments as an input. Args: correlation_id: a unique correlation/transaction id args: command arguments Returns: an execution result. Raises: MicroserviceError: when execution fails for w...
Below is the the instruction that describes the task: ### Input: Executes the command given specific arguments as an input. Args: correlation_id: a unique correlation/transaction id args: command arguments Returns: an execution result. ...
def to_joint_gaussian(self): """ The linear Gaussian Bayesian Networks are an alternative representation for the class of multivariate Gaussian distributions. This method returns an equivalent joint Gaussian distribution. Returns ------- GaussianDistribution: An ...
The linear Gaussian Bayesian Networks are an alternative representation for the class of multivariate Gaussian distributions. This method returns an equivalent joint Gaussian distribution. Returns ------- GaussianDistribution: An equivalent joint Gaussian ...
Below is the the instruction that describes the task: ### Input: The linear Gaussian Bayesian Networks are an alternative representation for the class of multivariate Gaussian distributions. This method returns an equivalent joint Gaussian distribution. Returns ------- Gauss...
def put(self, message, indent=0): ''' Print message with an indent. :param message: :param indent: :return: ''' color = self._colors_conf.get(indent + indent % 2, self._colors_conf.get(0, self._default_color)) for chunk in [' ' * indent, self._colors[col...
Print message with an indent. :param message: :param indent: :return:
Below is the the instruction that describes the task: ### Input: Print message with an indent. :param message: :param indent: :return: ### Response: def put(self, message, indent=0): ''' Print message with an indent. :param message: :param indent: :...
def mapreads(data, sample, nthreads, force): """ Attempt to map reads to reference sequence. This reads in the fasta files (samples.files.edits), and maps each read to the reference. Unmapped reads are dropped right back in the de novo pipeline. Reads that map successfully are processed and pushed...
Attempt to map reads to reference sequence. This reads in the fasta files (samples.files.edits), and maps each read to the reference. Unmapped reads are dropped right back in the de novo pipeline. Reads that map successfully are processed and pushed downstream and joined with the rest of the data post...
Below is the the instruction that describes the task: ### Input: Attempt to map reads to reference sequence. This reads in the fasta files (samples.files.edits), and maps each read to the reference. Unmapped reads are dropped right back in the de novo pipeline. Reads that map successfully are processed...
def symbolic(self, A): """ Return the symbolic factorization of sparse matrix ``A`` Parameters ---------- sparselib Library name in ``umfpack`` and ``klu`` A Sparse matrix Returns symbolic factorization ------- ""...
Return the symbolic factorization of sparse matrix ``A`` Parameters ---------- sparselib Library name in ``umfpack`` and ``klu`` A Sparse matrix Returns symbolic factorization -------
Below is the the instruction that describes the task: ### Input: Return the symbolic factorization of sparse matrix ``A`` Parameters ---------- sparselib Library name in ``umfpack`` and ``klu`` A Sparse matrix Returns symbolic factorization ...
def find_rings(self, including=None): """ Find ring structures in the MoleculeGraph. :param including: list of site indices. If including is not None, then find_rings will only return those rings including the specified sites. By default, this parameter is None, and ...
Find ring structures in the MoleculeGraph. :param including: list of site indices. If including is not None, then find_rings will only return those rings including the specified sites. By default, this parameter is None, and all rings will be returned. :return: dict {ind...
Below is the the instruction that describes the task: ### Input: Find ring structures in the MoleculeGraph. :param including: list of site indices. If including is not None, then find_rings will only return those rings including the specified sites. By default, this parameter is Non...
def empirical(X): """Compute empirical covariance as baseline estimator. """ print("Empirical") cov = np.dot(X.T, X) / n_samples return cov, np.linalg.inv(cov)
Compute empirical covariance as baseline estimator.
Below is the the instruction that describes the task: ### Input: Compute empirical covariance as baseline estimator. ### Response: def empirical(X): """Compute empirical covariance as baseline estimator. """ print("Empirical") cov = np.dot(X.T, X) / n_samples return cov, np.linalg.inv(cov)
def _generate(self): """ Generates set of consecutive patterns. """ n = self._n w = self._w assert type(w) is int, "List for w not supported" for i in xrange(n / w): pattern = set(xrange(i * w, (i+1) * w)) self._patterns[i] = pattern
Generates set of consecutive patterns.
Below is the the instruction that describes the task: ### Input: Generates set of consecutive patterns. ### Response: def _generate(self): """ Generates set of consecutive patterns. """ n = self._n w = self._w assert type(w) is int, "List for w not supported" for i in xrange(n / w): ...
def help(project, task, step, variables): """Run a help step.""" task_name = step.args or variables['task'] try: task = project.find_task(task_name) except NoSuchTaskError as e: yield events.task_not_found(task_name, e.similarities) raise StopTask text = f'# {task.name}\n'...
Run a help step.
Below is the the instruction that describes the task: ### Input: Run a help step. ### Response: def help(project, task, step, variables): """Run a help step.""" task_name = step.args or variables['task'] try: task = project.find_task(task_name) except NoSuchTaskError as e: yield e...
def _lookup_proxmox_task(upid): ''' Retrieve the (latest) logs and retrieve the status for a UPID. This can be used to verify whether a task has completed. ''' log.debug('Getting creation status for upid: %s', upid) tasks = query('get', 'cluster/tasks') if tasks: for task in tasks: ...
Retrieve the (latest) logs and retrieve the status for a UPID. This can be used to verify whether a task has completed.
Below is the the instruction that describes the task: ### Input: Retrieve the (latest) logs and retrieve the status for a UPID. This can be used to verify whether a task has completed. ### Response: def _lookup_proxmox_task(upid): ''' Retrieve the (latest) logs and retrieve the status for a UPID. T...
def set_default_headers(self, *args, **kwargs): """Set the default headers for all requests.""" self.set_header('Access-Control-Allow-Origin', '*') self.set_header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept') self.set_header('A...
Set the default headers for all requests.
Below is the the instruction that describes the task: ### Input: Set the default headers for all requests. ### Response: def set_default_headers(self, *args, **kwargs): """Set the default headers for all requests.""" self.set_header('Access-Control-Allow-Origin', '*') self.set_header('Acces...
def get_subordinate_clauses(tiger_docgraph): """ given a document graph of a TIGER syntax tree, return all node IDs of nodes representing subordinate clause constituents. Parameters ---------- tiger_docgraph : DiscourseDocumentGraph or TigerDocumentGraph document graph from which subord...
given a document graph of a TIGER syntax tree, return all node IDs of nodes representing subordinate clause constituents. Parameters ---------- tiger_docgraph : DiscourseDocumentGraph or TigerDocumentGraph document graph from which subordinate clauses will be extracted Returns ------- ...
Below is the the instruction that describes the task: ### Input: given a document graph of a TIGER syntax tree, return all node IDs of nodes representing subordinate clause constituents. Parameters ---------- tiger_docgraph : DiscourseDocumentGraph or TigerDocumentGraph document graph from ...
def extractfile(self, member): ''' Extract a member from the archive as a file object. `member' may be a filename or an RPMInfo object. The file-like object is read-only and provides the following methods: read(), readline(), readlines(), seek() and tell() ''' if ...
Extract a member from the archive as a file object. `member' may be a filename or an RPMInfo object. The file-like object is read-only and provides the following methods: read(), readline(), readlines(), seek() and tell()
Below is the the instruction that describes the task: ### Input: Extract a member from the archive as a file object. `member' may be a filename or an RPMInfo object. The file-like object is read-only and provides the following methods: read(), readline(), readlines(), seek() and tell() ### R...
def with_updated_configuration(self, options=None, attribute_options=None): """ Returns a context in which this representer is updated with the given options and attribute options. """ return self._mapping.with_updated_configuration(options=opti...
Returns a context in which this representer is updated with the given options and attribute options.
Below is the the instruction that describes the task: ### Input: Returns a context in which this representer is updated with the given options and attribute options. ### Response: def with_updated_configuration(self, options=None, attribute_options=None): """ ...
def copy(self, deep=True, data=None): """Returns a copy of this object. `deep` is ignored since data is stored in the form of pandas.Index, which is already immutable. Dimensions, attributes and encodings are always copied. Use `data` to create a new object with the same struct...
Returns a copy of this object. `deep` is ignored since data is stored in the form of pandas.Index, which is already immutable. Dimensions, attributes and encodings are always copied. Use `data` to create a new object with the same structure as original but entirely new data. ...
Below is the the instruction that describes the task: ### Input: Returns a copy of this object. `deep` is ignored since data is stored in the form of pandas.Index, which is already immutable. Dimensions, attributes and encodings are always copied. Use `data` to create a new object ...
def show_page(self, course): """ Prepares and shows the course page """ username = self.user_manager.session_username() if not self.user_manager.course_is_open_to_user(course, lti=False): return self.template_helper.get_renderer().course_unavailable() else: tasks ...
Prepares and shows the course page
Below is the the instruction that describes the task: ### Input: Prepares and shows the course page ### Response: def show_page(self, course): """ Prepares and shows the course page """ username = self.user_manager.session_username() if not self.user_manager.course_is_open_to_user(course, l...
def fit(self, X, y=None, **kwargs): """ Parameters ---------- X : ndarray or DataFrame of shape n x m A matrix of n instances with m features y : ndarray or Series of length n An array or series of target or class values kwargs: keyword argument...
Parameters ---------- X : ndarray or DataFrame of shape n x m A matrix of n instances with m features y : ndarray or Series of length n An array or series of target or class values kwargs: keyword arguments passed to Scikit-Learn API. Returns -...
Below is the the instruction that describes the task: ### Input: Parameters ---------- X : ndarray or DataFrame of shape n x m A matrix of n instances with m features y : ndarray or Series of length n An array or series of target or class values kwargs: key...
def _DrawHours(self): """Generates svg to show a vertical hour and sub-hour grid Returns: # A string containing a polyline tag for each grid line " <polyline class="FullHour" points="20,0 ..." """ tmpstrs = [] for i in range(0, self._gwidth, self._min_grid): if i % self._hour_grid...
Generates svg to show a vertical hour and sub-hour grid Returns: # A string containing a polyline tag for each grid line " <polyline class="FullHour" points="20,0 ..."
Below is the the instruction that describes the task: ### Input: Generates svg to show a vertical hour and sub-hour grid Returns: # A string containing a polyline tag for each grid line " <polyline class="FullHour" points="20,0 ..." ### Response: def _DrawHours(self): """Generates svg to show ...
def merge_dicts(dict1, dict2, append_lists=False): """ Merge the second dict into the first Not intended to merge list of dicts. :param append_lists: If true, instead of clobbering a list with the new value, append all of the new values onto the original list. """ for key in dict2: ...
Merge the second dict into the first Not intended to merge list of dicts. :param append_lists: If true, instead of clobbering a list with the new value, append all of the new values onto the original list.
Below is the the instruction that describes the task: ### Input: Merge the second dict into the first Not intended to merge list of dicts. :param append_lists: If true, instead of clobbering a list with the new value, append all of the new values onto the original list. ### Response: def merge_dic...
def dispatch_request(self): """Does the request dispatching. Matches the URL and returns the return value of the view or error handler. This does not have to be a response object. In order to convert the return value to a proper response object, call :func:`make_response`. .....
Does the request dispatching. Matches the URL and returns the return value of the view or error handler. This does not have to be a response object. In order to convert the return value to a proper response object, call :func:`make_response`. .. versionchanged:: 0.7 This n...
Below is the the instruction that describes the task: ### Input: Does the request dispatching. Matches the URL and returns the return value of the view or error handler. This does not have to be a response object. In order to convert the return value to a proper response object, call :fun...
def parametrize(params): """Return list of params as params. >>> parametrize(['a']) 'a' >>> parametrize(['a', 'b']) 'a[b]' >>> parametrize(['a', 'b', 'c']) 'a[b][c]' """ returned = str(params[0]) returned += "".join("[" + str(p) + "]" for p in params[1:]) return returned
Return list of params as params. >>> parametrize(['a']) 'a' >>> parametrize(['a', 'b']) 'a[b]' >>> parametrize(['a', 'b', 'c']) 'a[b][c]'
Below is the the instruction that describes the task: ### Input: Return list of params as params. >>> parametrize(['a']) 'a' >>> parametrize(['a', 'b']) 'a[b]' >>> parametrize(['a', 'b', 'c']) 'a[b][c]' ### Response: def parametrize(params): """Return list of params as params. >>>...
def _resolve_deps(self, formula_def): ''' Return a list of packages which need to be installed, to resolve all dependencies ''' pkg_info = self.pkgdb['{0}.info'.format(self.db_prov)](formula_def['name']) if not isinstance(pkg_info, dict): pkg_info = {} ...
Return a list of packages which need to be installed, to resolve all dependencies
Below is the the instruction that describes the task: ### Input: Return a list of packages which need to be installed, to resolve all dependencies ### Response: def _resolve_deps(self, formula_def): ''' Return a list of packages which need to be installed, to resolve all dependencie...
def _write(self, dap_index, transfer_count, transfer_request, transfer_data): """ Write one or more commands """ assert dap_index == 0 # dap index currently unsupported assert isinstance(transfer_count, six.integer_types) assert isinstance(transfer_request...
Write one or more commands
Below is the the instruction that describes the task: ### Input: Write one or more commands ### Response: def _write(self, dap_index, transfer_count, transfer_request, transfer_data): """ Write one or more commands """ assert dap_index == 0 # dap index currently unsu...
def Split(cls, extended_path_mask): ''' Splits the given path into their components: recursive, dirname, in_filters and out_filters :param str: extended_path_mask: The "extended path mask" to split :rtype: tuple(bool,bool,str,list(str),list(str)) :returns: ...
Splits the given path into their components: recursive, dirname, in_filters and out_filters :param str: extended_path_mask: The "extended path mask" to split :rtype: tuple(bool,bool,str,list(str),list(str)) :returns: Returns the extended path 5 components: -...
Below is the the instruction that describes the task: ### Input: Splits the given path into their components: recursive, dirname, in_filters and out_filters :param str: extended_path_mask: The "extended path mask" to split :rtype: tuple(bool,bool,str,list(str),list(str)) :retur...
def quaternion(self): """:obj:`numpy.ndarray` of float: A quaternion vector in wxyz layout. """ q_xyzw = transformations.quaternion_from_matrix(self.matrix) q_wxyz = np.roll(q_xyzw, 1) return q_wxyz
:obj:`numpy.ndarray` of float: A quaternion vector in wxyz layout.
Below is the the instruction that describes the task: ### Input: :obj:`numpy.ndarray` of float: A quaternion vector in wxyz layout. ### Response: def quaternion(self): """:obj:`numpy.ndarray` of float: A quaternion vector in wxyz layout. """ q_xyzw = transformations.quaternion_from_matrix(s...
def get_sub_node(self, node): """Extract node from document if desired.""" subnode = node.find('office:document') if subnode: mimetype = subnode.attrs['office:mimetype'] self.type = MIMEMAP[mimetype] node = node.find('office:body') return node
Extract node from document if desired.
Below is the the instruction that describes the task: ### Input: Extract node from document if desired. ### Response: def get_sub_node(self, node): """Extract node from document if desired.""" subnode = node.find('office:document') if subnode: mimetype = subnode.attrs['office:m...