code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _list_of_dictionaries_to_csv( self, csvType="human"): """Convert a python list of dictionaries to pretty csv output **Key Arguments:** - ``csvType`` -- human, machine or reST **Return:** - ``output`` -- the contents of a CSV file """ ...
Convert a python list of dictionaries to pretty csv output **Key Arguments:** - ``csvType`` -- human, machine or reST **Return:** - ``output`` -- the contents of a CSV file
Below is the the instruction that describes the task: ### Input: Convert a python list of dictionaries to pretty csv output **Key Arguments:** - ``csvType`` -- human, machine or reST **Return:** - ``output`` -- the contents of a CSV file ### Response: def _list_of_dictiona...
def topic_update(channel, topic_channel): """ Creates an embed UI for the topic update Args: channel (discord.Channel): The Discord channel to bind the embed to topic_channel: The new topic channel Returns: embed: The created embed """ if topic_channel is not None: ...
Creates an embed UI for the topic update Args: channel (discord.Channel): The Discord channel to bind the embed to topic_channel: The new topic channel Returns: embed: The created embed
Below is the the instruction that describes the task: ### Input: Creates an embed UI for the topic update Args: channel (discord.Channel): The Discord channel to bind the embed to topic_channel: The new topic channel Returns: embed: The created embed ### Response: def topic_update...
def dropcols(df, start=None, end=None): """Drop columns that contain NaN within [start, end] inclusive. A wrapper around DataFrame.dropna() that builds an easier *subset* syntax for tseries-indexed DataFrames. Parameters ---------- df : DataFrame start : str or datetime, default N...
Drop columns that contain NaN within [start, end] inclusive. A wrapper around DataFrame.dropna() that builds an easier *subset* syntax for tseries-indexed DataFrames. Parameters ---------- df : DataFrame start : str or datetime, default None start cutoff date, inclusive e...
Below is the the instruction that describes the task: ### Input: Drop columns that contain NaN within [start, end] inclusive. A wrapper around DataFrame.dropna() that builds an easier *subset* syntax for tseries-indexed DataFrames. Parameters ---------- df : DataFrame start : str o...
def show_stack(self, message_regex="^.*$", min_level=logging.DEBUG, limit=4096, once=True): """ Enable showing the origin of log messages by dumping a stack trace into the ``stack`` logger at the :const:``logging.INFO`` severity. :param message_regex: is a full-line regex which ...
Enable showing the origin of log messages by dumping a stack trace into the ``stack`` logger at the :const:``logging.INFO`` severity. :param message_regex: is a full-line regex which the message must satisfy in order to trigger stack dump :param min_level: the minimum severity the m...
Below is the the instruction that describes the task: ### Input: Enable showing the origin of log messages by dumping a stack trace into the ``stack`` logger at the :const:``logging.INFO`` severity. :param message_regex: is a full-line regex which the message must satisfy in order to tr...
def save(self, force_insert=False, force_update=False, commit=True): """ Se sobreescribe el método save para crear o modificar al User en caso que el parámetro commit sea True. """ usuario = super().save(commit=False) if commit: user = None if self.instance.pk is not None: user...
Se sobreescribe el método save para crear o modificar al User en caso que el parámetro commit sea True.
Below is the the instruction that describes the task: ### Input: Se sobreescribe el método save para crear o modificar al User en caso que el parámetro commit sea True. ### Response: def save(self, force_insert=False, force_update=False, commit=True): """ Se sobreescribe el método save para crear o modifi...
def _get_interface_name_from_hosting_port(self, port): """ Extract the underlying subinterface name for a port e.g. Port-channel10.200 or GigabitEthernet0/0/0.500 """ try: vlan = port['hosting_info']['segmentation_id'] int_prefix = port['hosting_info']['ph...
Extract the underlying subinterface name for a port e.g. Port-channel10.200 or GigabitEthernet0/0/0.500
Below is the the instruction that describes the task: ### Input: Extract the underlying subinterface name for a port e.g. Port-channel10.200 or GigabitEthernet0/0/0.500 ### Response: def _get_interface_name_from_hosting_port(self, port): """ Extract the underlying subinterface name for a po...
def from_signed_raw(cls: Type[MembershipType], signed_raw: str) -> MembershipType: """ Return Membership instance from signed raw format :param signed_raw: Signed raw format string :return: """ lines = signed_raw.splitlines(True) n = 0 version = int(Memb...
Return Membership instance from signed raw format :param signed_raw: Signed raw format string :return:
Below is the the instruction that describes the task: ### Input: Return Membership instance from signed raw format :param signed_raw: Signed raw format string :return: ### Response: def from_signed_raw(cls: Type[MembershipType], signed_raw: str) -> MembershipType: """ Return Member...
def _quantize_wp(wp, nbits, qm, axis=0, **kwargs): """ Quantize the weight blob :param wp: numpy.array Weight parameters :param nbits: int Number of bits :param qm: Quantization mode :param lut_function: (``callable function``) Python callable representing a look...
Quantize the weight blob :param wp: numpy.array Weight parameters :param nbits: int Number of bits :param qm: Quantization mode :param lut_function: (``callable function``) Python callable representing a look-up table Returns ------- scale: numpy.array ...
Below is the the instruction that describes the task: ### Input: Quantize the weight blob :param wp: numpy.array Weight parameters :param nbits: int Number of bits :param qm: Quantization mode :param lut_function: (``callable function``) Python callable representing ...
def command(self, cmd, expected_retcode=0): # pylint: disable=invalid-name # expected_retcode kwd argument is used in many test cases, we cannot rename it. """ Shortcut for sending a command to this node specifically. :param cmd: Command to send :param expected_retcode: Expected...
Shortcut for sending a command to this node specifically. :param cmd: Command to send :param expected_retcode: Expected return code as int, default is 0 :return: CliResponse
Below is the the instruction that describes the task: ### Input: Shortcut for sending a command to this node specifically. :param cmd: Command to send :param expected_retcode: Expected return code as int, default is 0 :return: CliResponse ### Response: def command(self, cmd, expected_retcod...
def get_args(args, kwargs, arg_names): '''Get arguments as a dict. ''' n_args = len(arg_names) if len(args) + len(kwargs) > n_args: raise MoultScannerError('Too many arguments supplied. Expected: {}'.format(n_args)) out_args = {} for i, a in enumerate(args): out_args[arg_names[i...
Get arguments as a dict.
Below is the the instruction that describes the task: ### Input: Get arguments as a dict. ### Response: def get_args(args, kwargs, arg_names): '''Get arguments as a dict. ''' n_args = len(arg_names) if len(args) + len(kwargs) > n_args: raise MoultScannerError('Too many arguments supplied. E...
def dens_floc_init(ConcAluminum, ConcClay, coag, material): """Return the density of the initial floc. Initial floc is made primarily of the primary colloid and nanoglobs. """ return (conc_floc(ConcAluminum, ConcClay, coag).magnitude / frac_vol_floc_initial(ConcAluminum, ConcClay, coag, mat...
Return the density of the initial floc. Initial floc is made primarily of the primary colloid and nanoglobs.
Below is the the instruction that describes the task: ### Input: Return the density of the initial floc. Initial floc is made primarily of the primary colloid and nanoglobs. ### Response: def dens_floc_init(ConcAluminum, ConcClay, coag, material): """Return the density of the initial floc. Initial fl...
def addCallSetFromName(self, sampleName): """ Adds a CallSet for the specified sample name. """ callSet = CallSet(self, sampleName) self.addCallSet(callSet)
Adds a CallSet for the specified sample name.
Below is the the instruction that describes the task: ### Input: Adds a CallSet for the specified sample name. ### Response: def addCallSetFromName(self, sampleName): """ Adds a CallSet for the specified sample name. """ callSet = CallSet(self, sampleName) self.addCallSet(ca...
def repositories(doc): """View for getting repositories""" for repository_id, repo in doc.get('repositories', {}).items(): repo['id'] = repository_id repo['organisation_id'] = doc['_id'] yield repository_id, repo
View for getting repositories
Below is the the instruction that describes the task: ### Input: View for getting repositories ### Response: def repositories(doc): """View for getting repositories""" for repository_id, repo in doc.get('repositories', {}).items(): repo['id'] = repository_id repo['organisation_id'] = doc['_...
def from_series(series): """ Deseralize a PercentRankTransform the given pandas.Series, as returned by `to_series()`. Parameters ---------- series : pandas.Series Returns ------- PercentRankTransform """ result = PercentRankTrans...
Deseralize a PercentRankTransform the given pandas.Series, as returned by `to_series()`. Parameters ---------- series : pandas.Series Returns ------- PercentRankTransform
Below is the the instruction that describes the task: ### Input: Deseralize a PercentRankTransform the given pandas.Series, as returned by `to_series()`. Parameters ---------- series : pandas.Series Returns ------- PercentRankTransform ### Response: def fro...
def update_metadata(self, href=None, metadata=None, version=None): """Update the metadata in a bundle. 'href' the relative href to the metadata. May not be None. 'metadata' may be None, or an object that can be converted to a JSON string. See API documentation for restrictions. The ...
Update the metadata in a bundle. 'href' the relative href to the metadata. May not be None. 'metadata' may be None, or an object that can be converted to a JSON string. See API documentation for restrictions. The conversion will take place before the API call. 'version' the ob...
Below is the the instruction that describes the task: ### Input: Update the metadata in a bundle. 'href' the relative href to the metadata. May not be None. 'metadata' may be None, or an object that can be converted to a JSON string. See API documentation for restrictions. The con...
def thread_details(io_handler, thread_id, max_depth=0): """ Prints details about the thread with the given ID (not its name) """ # Normalize maximum depth try: max_depth = int(max_depth) if max_depth < 1: max_depth = None except (Va...
Prints details about the thread with the given ID (not its name)
Below is the the instruction that describes the task: ### Input: Prints details about the thread with the given ID (not its name) ### Response: def thread_details(io_handler, thread_id, max_depth=0): """ Prints details about the thread with the given ID (not its name) """ # Normaliz...
def advance_dialog(self, *args): """Try to display the next dialog described in my ``todo``.""" self.clear_widgets() try: self._update_dialog(self.todo[self.idx]) except IndexError: pass
Try to display the next dialog described in my ``todo``.
Below is the the instruction that describes the task: ### Input: Try to display the next dialog described in my ``todo``. ### Response: def advance_dialog(self, *args): """Try to display the next dialog described in my ``todo``.""" self.clear_widgets() try: self._update_dialog(s...
def _indent(code, by=1): """Indents every nonempty line of the given code.""" return "".join( (" " * by if line else "") + line for line in code.splitlines(True) )
Indents every nonempty line of the given code.
Below is the the instruction that describes the task: ### Input: Indents every nonempty line of the given code. ### Response: def _indent(code, by=1): """Indents every nonempty line of the given code.""" return "".join( (" " * by if line else "") + line for line in code.splitlines(True) )
def create_global_step(session: tf.Session) -> tf.Variable: """ Creates the Tensorflow 'global_step' variable (see `MonitorContext.global_step_tensor`). :param session: Tensorflow session the optimiser is running in :return: The variable tensor. """ global_step_tensor = tf.Variable(0, trainable=...
Creates the Tensorflow 'global_step' variable (see `MonitorContext.global_step_tensor`). :param session: Tensorflow session the optimiser is running in :return: The variable tensor.
Below is the the instruction that describes the task: ### Input: Creates the Tensorflow 'global_step' variable (see `MonitorContext.global_step_tensor`). :param session: Tensorflow session the optimiser is running in :return: The variable tensor. ### Response: def create_global_step(session: tf.Session) ->...
def contains_extra(marker): """Check whehter a marker contains an "extra == ..." operand. """ if not marker: return False marker = Marker(str(marker)) return _markers_contains_extra(marker._markers)
Check whehter a marker contains an "extra == ..." operand.
Below is the the instruction that describes the task: ### Input: Check whehter a marker contains an "extra == ..." operand. ### Response: def contains_extra(marker): """Check whehter a marker contains an "extra == ..." operand. """ if not marker: return False marker = Marker(str(marker)) ...
def restore_scrollbar_positions(self): """Restore scrollbar positions once tree is loaded""" hor, ver = self._scrollbar_positions self.horizontalScrollBar().setValue(hor) self.verticalScrollBar().setValue(ver)
Restore scrollbar positions once tree is loaded
Below is the the instruction that describes the task: ### Input: Restore scrollbar positions once tree is loaded ### Response: def restore_scrollbar_positions(self): """Restore scrollbar positions once tree is loaded""" hor, ver = self._scrollbar_positions self.horizontalScrollBar().setV...
def append(self, value): """Append an element to the fact.""" if self.asserted: raise RuntimeError("Fact already asserted") self._multifield.append(value)
Append an element to the fact.
Below is the the instruction that describes the task: ### Input: Append an element to the fact. ### Response: def append(self, value): """Append an element to the fact.""" if self.asserted: raise RuntimeError("Fact already asserted") self._multifield.append(value)
def get_session_key(self, username, password_hash): """ Retrieve a session key with a username and a md5 hash of the user's password. """ params = {"username": username, "authToken": md5(username + password_hash)} request = _Request(self.network, "auth.getMobileSession",...
Retrieve a session key with a username and a md5 hash of the user's password.
Below is the the instruction that describes the task: ### Input: Retrieve a session key with a username and a md5 hash of the user's password. ### Response: def get_session_key(self, username, password_hash): """ Retrieve a session key with a username and a md5 hash of the user's pa...
def get_data_excel_xml(file_name, file_contents=None, on_demand=False): ''' Loads xml excel format files. Args: file_name: The name of the local file, or the holder for the extension type when the file_contents are supplied. file_contents: The file-like object holding contents o...
Loads xml excel format files. Args: file_name: The name of the local file, or the holder for the extension type when the file_contents are supplied. file_contents: The file-like object holding contents of file_name. If left as None, then file_name is directly loaded. ...
Below is the the instruction that describes the task: ### Input: Loads xml excel format files. Args: file_name: The name of the local file, or the holder for the extension type when the file_contents are supplied. file_contents: The file-like object holding contents of file_name. ...
def exists(self, filetype, remote=None, **kwargs): '''Checks if the given type of file exists locally Parameters ---------- filetype : str File type parameter. remote : bool If True, checks for remote existence of the file Returns ------...
Checks if the given type of file exists locally Parameters ---------- filetype : str File type parameter. remote : bool If True, checks for remote existence of the file Returns ------- exists : bool Boolean indicating if the ...
Below is the the instruction that describes the task: ### Input: Checks if the given type of file exists locally Parameters ---------- filetype : str File type parameter. remote : bool If True, checks for remote existence of the file Returns ...
def load(ctx, input, output): """Read clusters from file and save to model file.""" log.debug('chemdataextractor.cluster.load') import pickle click.echo('Reading %s' % input.name) clusters = {} for line in input.readlines(): cluster, word, freq = line.split() clusters[word] = clu...
Read clusters from file and save to model file.
Below is the the instruction that describes the task: ### Input: Read clusters from file and save to model file. ### Response: def load(ctx, input, output): """Read clusters from file and save to model file.""" log.debug('chemdataextractor.cluster.load') import pickle click.echo('Reading %s' % inpu...
def to_pb(self): """Converts the union into a single GC rule as a protobuf. :rtype: :class:`.table_v2_pb2.GcRule` :returns: The converted current object. """ union = table_v2_pb2.GcRule.Union(rules=[rule.to_pb() for rule in self.rules]) return table_v2_pb2.GcRule(union=u...
Converts the union into a single GC rule as a protobuf. :rtype: :class:`.table_v2_pb2.GcRule` :returns: The converted current object.
Below is the the instruction that describes the task: ### Input: Converts the union into a single GC rule as a protobuf. :rtype: :class:`.table_v2_pb2.GcRule` :returns: The converted current object. ### Response: def to_pb(self): """Converts the union into a single GC rule as a protobuf. ...
def name(self): """Dict with locale codes as keys and localized name as value""" # pylint:disable=E1101 return next((self.names.get(x) for x in self._locales if x in self.names), None)
Dict with locale codes as keys and localized name as value
Below is the the instruction that describes the task: ### Input: Dict with locale codes as keys and localized name as value ### Response: def name(self): """Dict with locale codes as keys and localized name as value""" # pylint:disable=E1101 return next((self.names.get(x) for x in self._loc...
def retrieve_tx(self, txid): """Returns rawtx for <txid>.""" txid = deserialize.txid(txid) tx = self.service.get_tx(txid) return serialize.tx(tx)
Returns rawtx for <txid>.
Below is the the instruction that describes the task: ### Input: Returns rawtx for <txid>. ### Response: def retrieve_tx(self, txid): """Returns rawtx for <txid>.""" txid = deserialize.txid(txid) tx = self.service.get_tx(txid) return serialize.tx(tx)
def colRowIsOnFgsPixel(self, col, row, padding=-50): """Is col row on a science pixel? #See Kepler Flight Segment User's Manual (SP0039-702) \S 5.4 (p88) Inputs: col, row (floats or ints) padding If padding <0, pixel must be on silicon and this many pixels...
Is col row on a science pixel? #See Kepler Flight Segment User's Manual (SP0039-702) \S 5.4 (p88) Inputs: col, row (floats or ints) padding If padding <0, pixel must be on silicon and this many pixels away from the edge of the CCD to return True Returns: ...
Below is the the instruction that describes the task: ### Input: Is col row on a science pixel? #See Kepler Flight Segment User's Manual (SP0039-702) \S 5.4 (p88) Inputs: col, row (floats or ints) padding If padding <0, pixel must be on silicon and this many p...
def user_choice(prompt, choices=("yes", "no"), default=None): """ Prompts the user for confirmation. The default value, if any, is capitalized. :param prompt: Information to display to the user. :param choices: an iterable of possible choices. :param default: default choice :return: the user's...
Prompts the user for confirmation. The default value, if any, is capitalized. :param prompt: Information to display to the user. :param choices: an iterable of possible choices. :param default: default choice :return: the user's choice
Below is the the instruction that describes the task: ### Input: Prompts the user for confirmation. The default value, if any, is capitalized. :param prompt: Information to display to the user. :param choices: an iterable of possible choices. :param default: default choice :return: the user's choi...
def diagnostics(self): """Dictionary access to all diagnostic variables :type: dict """ diag_dict = {} for key in self._diag_vars: try: #diag_dict[key] = getattr(self,key) # using self.__dict__ doesn't count diagnostics defined ...
Dictionary access to all diagnostic variables :type: dict
Below is the the instruction that describes the task: ### Input: Dictionary access to all diagnostic variables :type: dict ### Response: def diagnostics(self): """Dictionary access to all diagnostic variables :type: dict """ diag_dict = {} for key in sel...
def _send_command_to_servers(self, head, body): """Sends a command to all server nodes. Sending command to a server node will cause that server node to invoke ``KVStoreServer.controller`` to execute the command. This function returns after the command has been executed on all server ...
Sends a command to all server nodes. Sending command to a server node will cause that server node to invoke ``KVStoreServer.controller`` to execute the command. This function returns after the command has been executed on all server nodes. Parameters ---------- ...
Below is the the instruction that describes the task: ### Input: Sends a command to all server nodes. Sending command to a server node will cause that server node to invoke ``KVStoreServer.controller`` to execute the command. This function returns after the command has been executed on all...
def reset(self): """Reset all fields, almost like creating a new object. Note: Forgets changes you have made not saved to database! (Remember: Others might reference the object already, expecting something else!) Override this method if you add properties not defined in _sqlFiel...
Reset all fields, almost like creating a new object. Note: Forgets changes you have made not saved to database! (Remember: Others might reference the object already, expecting something else!) Override this method if you add properties not defined in _sqlFields.
Below is the the instruction that describes the task: ### Input: Reset all fields, almost like creating a new object. Note: Forgets changes you have made not saved to database! (Remember: Others might reference the object already, expecting something else!) Override this method if you add p...
def _get_synset_offsets(synset_idxes): """Returs pointer offset in the WordNet file for every synset index. Notes ----- Internal function. Do not call directly. Preserves order -- for [x,y,z] returns [offset(x),offset(y),offset(z)]. Parameters ---------- synset_idxes : list of ints ...
Returs pointer offset in the WordNet file for every synset index. Notes ----- Internal function. Do not call directly. Preserves order -- for [x,y,z] returns [offset(x),offset(y),offset(z)]. Parameters ---------- synset_idxes : list of ints Lists synset IDs, which need offset. ...
Below is the the instruction that describes the task: ### Input: Returs pointer offset in the WordNet file for every synset index. Notes ----- Internal function. Do not call directly. Preserves order -- for [x,y,z] returns [offset(x),offset(y),offset(z)]. Parameters ---------- synset_i...
def p_expr_lbound(p): """ bexpr : LBOUND LP ARRAY_ID RP | UBOUND LP ARRAY_ID RP """ entry = SYMBOL_TABLE.access_array(p[3], p.lineno(3)) if entry is None: p[0] = None return entry.accessed = True if p[1] == 'LBOUND': p[0] = make_number(entry.bounds[OPTIONS....
bexpr : LBOUND LP ARRAY_ID RP | UBOUND LP ARRAY_ID RP
Below is the the instruction that describes the task: ### Input: bexpr : LBOUND LP ARRAY_ID RP | UBOUND LP ARRAY_ID RP ### Response: def p_expr_lbound(p): """ bexpr : LBOUND LP ARRAY_ID RP | UBOUND LP ARRAY_ID RP """ entry = SYMBOL_TABLE.access_array(p[3], p.lineno(3)) if ...
def undecorate(func): """Returns the decorator and the undecorated function of given object.""" orig_call_wrapper = lambda x: x for call_wrapper, unwrap in SUPPORTED_DECORATOR.items(): if isinstance(func, call_wrapper): func = unwrap(func) orig_call_wrapper = call_wrapper ...
Returns the decorator and the undecorated function of given object.
Below is the the instruction that describes the task: ### Input: Returns the decorator and the undecorated function of given object. ### Response: def undecorate(func): """Returns the decorator and the undecorated function of given object.""" orig_call_wrapper = lambda x: x for call_wrapper, unwrap in ...
def Verify(self): """ Verify block using the verification script. Returns: bool: True if valid. False otherwise. """ if not self.Hash.ToBytes() == GetGenesis().Hash.ToBytes(): return False bc = GetBlockchain() if not bc.ContainsBlock(sel...
Verify block using the verification script. Returns: bool: True if valid. False otherwise.
Below is the the instruction that describes the task: ### Input: Verify block using the verification script. Returns: bool: True if valid. False otherwise. ### Response: def Verify(self): """ Verify block using the verification script. Returns: bool: True i...
def how_vulnerable( chain, blackbox_mapping, sanitiser_nodes, potential_sanitiser, blackbox_assignments, interactive, vuln_deets ): """Iterates through the chain of nodes and checks the blackbox nodes against the blackbox mapping and sanitiser dictionary. Note: potential_sanitiser i...
Iterates through the chain of nodes and checks the blackbox nodes against the blackbox mapping and sanitiser dictionary. Note: potential_sanitiser is the only hack here, it is because we do not take p-use's into account yet. e.g. we can only say potentially instead of definitely sanitised in the path_traversal...
Below is the the instruction that describes the task: ### Input: Iterates through the chain of nodes and checks the blackbox nodes against the blackbox mapping and sanitiser dictionary. Note: potential_sanitiser is the only hack here, it is because we do not take p-use's into account yet. e.g. we can only ...
def to_dict(self): """ Return a dict representation of an osmnet osmnet_config instance. """ return {'logs_folder': self.logs_folder, 'log_file': self.log_file, 'log_console': self.log_console, 'log_name': self.log_name, 'lo...
Return a dict representation of an osmnet osmnet_config instance.
Below is the the instruction that describes the task: ### Input: Return a dict representation of an osmnet osmnet_config instance. ### Response: def to_dict(self): """ Return a dict representation of an osmnet osmnet_config instance. """ return {'logs_folder': self.logs_folder, ...
def get_task_scfcycles(self, nids=None, wslice=None, task_class=None, exclude_ok_tasks=False): """ Return list of (taks, scfcycle) tuples for all the tasks in the flow with a SCF algorithm e.g. electronic GS-SCF iteration, DFPT-SCF iterations etc. Args: nids: List of node id...
Return list of (taks, scfcycle) tuples for all the tasks in the flow with a SCF algorithm e.g. electronic GS-SCF iteration, DFPT-SCF iterations etc. Args: nids: List of node identifiers. wslice: Slice object used to select works. task_class: String or class used to s...
Below is the the instruction that describes the task: ### Input: Return list of (taks, scfcycle) tuples for all the tasks in the flow with a SCF algorithm e.g. electronic GS-SCF iteration, DFPT-SCF iterations etc. Args: nids: List of node identifiers. wslice: Slice object us...
def write(filename, mesh, file_format=None, **kwargs): """Writes mesh together with data to a file. :params filename: File to write to. :type filename: str :params point_data: Named additional point data to write to the file. :type point_data: dict """ if not file_format: # deduce ...
Writes mesh together with data to a file. :params filename: File to write to. :type filename: str :params point_data: Named additional point data to write to the file. :type point_data: dict
Below is the the instruction that describes the task: ### Input: Writes mesh together with data to a file. :params filename: File to write to. :type filename: str :params point_data: Named additional point data to write to the file. :type point_data: dict ### Response: def write(filename, mesh, f...
def create_style_from_font(font): """ Convert from font string/tyuple into a Qt style sheet string :param font: "Arial 10 Bold" or ('Arial', 10, 'Bold) :return: style string that can be combined with other style strings """ if font is None: return '' if type(font) is str: _...
Convert from font string/tyuple into a Qt style sheet string :param font: "Arial 10 Bold" or ('Arial', 10, 'Bold) :return: style string that can be combined with other style strings
Below is the the instruction that describes the task: ### Input: Convert from font string/tyuple into a Qt style sheet string :param font: "Arial 10 Bold" or ('Arial', 10, 'Bold) :return: style string that can be combined with other style strings ### Response: def create_style_from_font(font): """ ...
def update_instance_sensors(self, opt=None): """ Method runs through all sensor modules and updates to the latest sensor values. After running through each sensor module, The sensor head (the I2C multiplexer), is disabled in order to avoid address conflicts. ...
Method runs through all sensor modules and updates to the latest sensor values. After running through each sensor module, The sensor head (the I2C multiplexer), is disabled in order to avoid address conflicts. Usage: plant_sensor_object.updateAllSensors(bus...
Below is the the instruction that describes the task: ### Input: Method runs through all sensor modules and updates to the latest sensor values. After running through each sensor module, The sensor head (the I2C multiplexer), is disabled in order to avoid address conflicts. ...
def get_cache_time( self, path: str, modified: Optional[datetime.datetime], mime_type: str ) -> int: """Override to customize cache control behavior. Return a positive number of seconds to make the result cacheable for that amount of time or 0 to mark resource as cacheable f...
Override to customize cache control behavior. Return a positive number of seconds to make the result cacheable for that amount of time or 0 to mark resource as cacheable for an unspecified amount of time (subject to browser heuristics). By default returns cache expiry of 10 yea...
Below is the the instruction that describes the task: ### Input: Override to customize cache control behavior. Return a positive number of seconds to make the result cacheable for that amount of time or 0 to mark resource as cacheable for an unspecified amount of time (subject to br...
def _compute_mean(self, C, g, mag, hypo_depth, dists, imt): """ Compute mean according to equation on Table 2, page 2275. """ delta = 0.00750 * 10 ** (0.507 * mag) # computing R for different values of mag if mag < 6.5: R = np.sqrt(dists.rhypo ** 2 + delta *...
Compute mean according to equation on Table 2, page 2275.
Below is the the instruction that describes the task: ### Input: Compute mean according to equation on Table 2, page 2275. ### Response: def _compute_mean(self, C, g, mag, hypo_depth, dists, imt): """ Compute mean according to equation on Table 2, page 2275. """ delta = 0.00750 * 1...
def view_hmap(token, dstore): """ Display the highest 20 points of the mean hazard map. Called as $ oq show hmap:0.1 # 10% PoE """ try: poe = valid.probability(token.split(':')[1]) except IndexError: poe = 0.1 mean = dict(extract(dstore, 'hcurves?kind=mean'))['mean'] oq ...
Display the highest 20 points of the mean hazard map. Called as $ oq show hmap:0.1 # 10% PoE
Below is the the instruction that describes the task: ### Input: Display the highest 20 points of the mean hazard map. Called as $ oq show hmap:0.1 # 10% PoE ### Response: def view_hmap(token, dstore): """ Display the highest 20 points of the mean hazard map. Called as $ oq show hmap:0.1 # 10% Po...
def _addDPFiles(self, *files): """callback to add DPs corresponding to files.""" # quiet flag is always true self.new_entry_dialog.addDataProducts(self.purrer.makeDataProducts( [(file, True) for file in files], unbanish=True, unignore=True))
callback to add DPs corresponding to files.
Below is the the instruction that describes the task: ### Input: callback to add DPs corresponding to files. ### Response: def _addDPFiles(self, *files): """callback to add DPs corresponding to files.""" # quiet flag is always true self.new_entry_dialog.addDataProducts(self.purrer.makeDataP...
def whois_domains_history(self, domains): """Calls WHOIS domain history end point Args: domains: An enumerable of domains Returns: A dict of {domain: domain_history_result} """ api_name = 'opendns-whois-domain-history' fmt_url_path = u'whois/{0}/h...
Calls WHOIS domain history end point Args: domains: An enumerable of domains Returns: A dict of {domain: domain_history_result}
Below is the the instruction that describes the task: ### Input: Calls WHOIS domain history end point Args: domains: An enumerable of domains Returns: A dict of {domain: domain_history_result} ### Response: def whois_domains_history(self, domains): """Calls WHOIS do...
def get_summary(summary_file): """Parses a FastQC summary report file and returns it as a dictionary. This function parses a typical FastQC summary report file, retrieving only the information on the first two columns. For instance, a line could be:: 'PASS Basic Statistics SH10762A_1.fastq.gz'...
Parses a FastQC summary report file and returns it as a dictionary. This function parses a typical FastQC summary report file, retrieving only the information on the first two columns. For instance, a line could be:: 'PASS Basic Statistics SH10762A_1.fastq.gz' This parser will build a diction...
Below is the the instruction that describes the task: ### Input: Parses a FastQC summary report file and returns it as a dictionary. This function parses a typical FastQC summary report file, retrieving only the information on the first two columns. For instance, a line could be:: 'PASS Basic ...
def _remove_nonascii(self, df): """Make copy and remove non-ascii characters from it.""" df_copy = df.copy(deep=True) for col in df_copy.columns: if (df_copy[col].dtype == np.dtype('O')): df_copy[col] = df[col].apply( lambda x: re.sub(r'[^\x00-\x7f]', r'', x) if isinstance(x, six.st...
Make copy and remove non-ascii characters from it.
Below is the the instruction that describes the task: ### Input: Make copy and remove non-ascii characters from it. ### Response: def _remove_nonascii(self, df): """Make copy and remove non-ascii characters from it.""" df_copy = df.copy(deep=True) for col in df_copy.columns: if (df_copy[col].dty...
def render(self, context): self.prepare(context) " Cached wrapper around self._render(). " if getattr(settings, 'DOUBLE_RENDER', False) and self.can_double_render: if 'SECOND_RENDER' not in context: return self.double_render() key = self.get_cache_key() ...
Cached wrapper around self._render().
Below is the the instruction that describes the task: ### Input: Cached wrapper around self._render(). ### Response: def render(self, context): self.prepare(context) " Cached wrapper around self._render(). " if getattr(settings, 'DOUBLE_RENDER', False) and self.can_double_render: ...
def begin_script(self): """Indicate we are going to start loading a script.""" if self.remote_bridge.status in (BRIDGE_STATUS.RECEIVED, BRIDGE_STATUS.VALIDATED, BRIDGE_STATUS.EXECUTING): return [1] #FIXME: Return correct error here self.remote_bridge.status = BRIDGE_STATUS.WAITING...
Indicate we are going to start loading a script.
Below is the the instruction that describes the task: ### Input: Indicate we are going to start loading a script. ### Response: def begin_script(self): """Indicate we are going to start loading a script.""" if self.remote_bridge.status in (BRIDGE_STATUS.RECEIVED, BRIDGE_STATUS.VALIDATED, BRIDGE_ST...
def dpub(self, topic, delay_ms, msg, callback=None): """ publish multiple messages in one command (efficiently) :param topic: nsq topic :param delay_ms: tell nsqd to delay delivery for this long (integer milliseconds) :param msg: message body (bytes) :param callback: fun...
publish multiple messages in one command (efficiently) :param topic: nsq topic :param delay_ms: tell nsqd to delay delivery for this long (integer milliseconds) :param msg: message body (bytes) :param callback: function which takes (conn, data) (data may be nsq.Error)
Below is the the instruction that describes the task: ### Input: publish multiple messages in one command (efficiently) :param topic: nsq topic :param delay_ms: tell nsqd to delay delivery for this long (integer milliseconds) :param msg: message body (bytes) :param callback: functio...
def to_map_with_default(value, default_value): """ Converts JSON string into map object or returns default value when conversion is not possible. :param value: the JSON string to convert. :param default_value: the default value. :return: Map object value or default when conver...
Converts JSON string into map object or returns default value when conversion is not possible. :param value: the JSON string to convert. :param default_value: the default value. :return: Map object value or default when conversion is not supported.
Below is the the instruction that describes the task: ### Input: Converts JSON string into map object or returns default value when conversion is not possible. :param value: the JSON string to convert. :param default_value: the default value. :return: Map object value or default when conv...
def iter_files(root, exts=None, recursive=False): """ Iterate over file paths within root filtered by specified extensions. :param compat.string_types root: Root folder to start collecting files :param iterable exts: Restrict results to given file extensions :param bool recursive: Wether to walk the...
Iterate over file paths within root filtered by specified extensions. :param compat.string_types root: Root folder to start collecting files :param iterable exts: Restrict results to given file extensions :param bool recursive: Wether to walk the complete directory tree :rtype collections.Iterable[str]:...
Below is the the instruction that describes the task: ### Input: Iterate over file paths within root filtered by specified extensions. :param compat.string_types root: Root folder to start collecting files :param iterable exts: Restrict results to given file extensions :param bool recursive: Wether to w...
def search_keyword_top(self, category=None, count=20, period='today'): """doc: http://open.youku.com/docs/doc?id=84 """ url = 'https://openapi.youku.com/v2/searches/keyword/top.json' params = { 'client_id': self.client_id, 'count': count, 'period': per...
doc: http://open.youku.com/docs/doc?id=84
Below is the the instruction that describes the task: ### Input: doc: http://open.youku.com/docs/doc?id=84 ### Response: def search_keyword_top(self, category=None, count=20, period='today'): """doc: http://open.youku.com/docs/doc?id=84 """ url = 'https://openapi.youku.com/v2/searches/keywo...
def resume(self, container_id=None, sudo=None): ''' resume a stopped OciImage container, if it exists Equivalent command line example: singularity oci resume <container_ID> Parameters ========== container_id: the id to stop. sudo: Add sudo to the...
resume a stopped OciImage container, if it exists Equivalent command line example: singularity oci resume <container_ID> Parameters ========== container_id: the id to stop. sudo: Add sudo to the command. If the container was created by root, ...
Below is the the instruction that describes the task: ### Input: resume a stopped OciImage container, if it exists Equivalent command line example: singularity oci resume <container_ID> Parameters ========== container_id: the id to stop. sudo: Ad...
def tick(self): """Clock tick called every self.inter """ if self.events: if self.queueDepth and (len(self.events) > self.queueDepth): # Remove maximum of self.queueDepth items from queue events = self.events[:self.queueDepth] self.even...
Clock tick called every self.inter
Below is the the instruction that describes the task: ### Input: Clock tick called every self.inter ### Response: def tick(self): """Clock tick called every self.inter """ if self.events: if self.queueDepth and (len(self.events) > self.queueDepth): # Remove maxim...
def calculateImpliedVolatility( self, contract: Contract, optionPrice: float, underPrice: float, implVolOptions: List[TagValue] = None) -> OptionComputation: """ Calculate the volatility given the option price. This method is blocking. https://intera...
Calculate the volatility given the option price. This method is blocking. https://interactivebrokers.github.io/tws-api/option_computations.html Args: contract: Option contract. optionPrice: Option price to use in calculation. underPrice: Price of the underl...
Below is the the instruction that describes the task: ### Input: Calculate the volatility given the option price. This method is blocking. https://interactivebrokers.github.io/tws-api/option_computations.html Args: contract: Option contract. optionPrice: Option pri...
def xyz2stereonet(x, y, z): """ Converts x, y, z in _world_ cartesian coordinates into lower-hemisphere stereonet coordinates. Parameters ---------- x, y, z : array-likes Sequences of world coordinates Returns ------- lon, lat : arrays Sequences of longitudes and la...
Converts x, y, z in _world_ cartesian coordinates into lower-hemisphere stereonet coordinates. Parameters ---------- x, y, z : array-likes Sequences of world coordinates Returns ------- lon, lat : arrays Sequences of longitudes and latitudes (in radians)
Below is the the instruction that describes the task: ### Input: Converts x, y, z in _world_ cartesian coordinates into lower-hemisphere stereonet coordinates. Parameters ---------- x, y, z : array-likes Sequences of world coordinates Returns ------- lon, lat : arrays S...
def name(self): """ Returns the type name of the `Stream` field (read-only).""" size = len(self) if size > 0: return self.item_type.name.capitalize() + str(size) else: return self.item_type.name.capitalize()
Returns the type name of the `Stream` field (read-only).
Below is the the instruction that describes the task: ### Input: Returns the type name of the `Stream` field (read-only). ### Response: def name(self): """ Returns the type name of the `Stream` field (read-only).""" size = len(self) if size > 0: return self.item_type.name.capita...
def reroot(self, rppr=None, pretend=False): """Reroot the phylogenetic tree. This operation calls ``rppr reroot`` to generate the rerooted tree, so you must have ``pplacer`` and its auxiliary tools ``rppr`` and ``guppy`` installed for it to work. You can specify the path to ``r...
Reroot the phylogenetic tree. This operation calls ``rppr reroot`` to generate the rerooted tree, so you must have ``pplacer`` and its auxiliary tools ``rppr`` and ``guppy`` installed for it to work. You can specify the path to ``rppr`` by giving it as the *rppr* argument. ...
Below is the the instruction that describes the task: ### Input: Reroot the phylogenetic tree. This operation calls ``rppr reroot`` to generate the rerooted tree, so you must have ``pplacer`` and its auxiliary tools ``rppr`` and ``guppy`` installed for it to work. You can specify t...
def newFromBehavior(name, id=None): """ Given a name, return a behaviored ContentLine or Component. """ name = name.upper() behavior = getBehavior(name, id) if behavior is None: raise VObjectError("No behavior found named %s" % name) if behavior.isComponent: obj = Component(n...
Given a name, return a behaviored ContentLine or Component.
Below is the the instruction that describes the task: ### Input: Given a name, return a behaviored ContentLine or Component. ### Response: def newFromBehavior(name, id=None): """ Given a name, return a behaviored ContentLine or Component. """ name = name.upper() behavior = getBehavior(name, id)...
def _GetTempOutputFileHandles(self, value_type): """Returns the tracker for a given value type.""" try: return self.temp_output_trackers[value_type], False except KeyError: return self._CreateOutputFileHandles(value_type), True
Returns the tracker for a given value type.
Below is the the instruction that describes the task: ### Input: Returns the tracker for a given value type. ### Response: def _GetTempOutputFileHandles(self, value_type): """Returns the tracker for a given value type.""" try: return self.temp_output_trackers[value_type], False except KeyError: ...
def serve_forever(args=None): """ Creates the server and serves forever :param args: Optional args if you decided to use your own argument parser. Default is None to let the JsonServer setup its own parser and parse command line arguments. """ class Unbuffered(object): def _...
Creates the server and serves forever :param args: Optional args if you decided to use your own argument parser. Default is None to let the JsonServer setup its own parser and parse command line arguments.
Below is the the instruction that describes the task: ### Input: Creates the server and serves forever :param args: Optional args if you decided to use your own argument parser. Default is None to let the JsonServer setup its own parser and parse command line arguments. ### Response: def serve...
def weekday_series(self, start, end, weekday, return_date=False): """Generate a datetime series with same weekday number. ISO weekday number: Mon to Sun = 1 to 7 Usage:: >>> start, end = "2014-01-01 06:30:25", "2014-02-01 06:30:25" >>> rolex.weekday_series(start, end, ...
Generate a datetime series with same weekday number. ISO weekday number: Mon to Sun = 1 to 7 Usage:: >>> start, end = "2014-01-01 06:30:25", "2014-02-01 06:30:25" >>> rolex.weekday_series(start, end, weekday=2) # All Tuesday [ datetime(2014, 1, 7, 6...
Below is the the instruction that describes the task: ### Input: Generate a datetime series with same weekday number. ISO weekday number: Mon to Sun = 1 to 7 Usage:: >>> start, end = "2014-01-01 06:30:25", "2014-02-01 06:30:25" >>> rolex.weekday_series(start, end, weekday=...
def set(self, key: Any, value: Any) -> None: """ Sets the value of a key to a supplied value """ if key is not None: self[key] = value
Sets the value of a key to a supplied value
Below is the the instruction that describes the task: ### Input: Sets the value of a key to a supplied value ### Response: def set(self, key: Any, value: Any) -> None: """ Sets the value of a key to a supplied value """ if key is not None: self[key] = value
def config(): ''' Display fault manager configuration CLI Example: .. code-block:: bash salt '*' fmadm.config ''' ret = {} fmadm = _check_fmadm() cmd = '{cmd} config'.format( cmd=fmadm ) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] result...
Display fault manager configuration CLI Example: .. code-block:: bash salt '*' fmadm.config
Below is the the instruction that describes the task: ### Input: Display fault manager configuration CLI Example: .. code-block:: bash salt '*' fmadm.config ### Response: def config(): ''' Display fault manager configuration CLI Example: .. code-block:: bash salt '*' f...
def list_models(self, **kwargs): """ List models. Lists Watson Knowledge Studio [custom models](https://cloud.ibm.com/docs/services/natural-language-understanding/customizing.html) that are deployed to your Natural Language Understanding service. :param dict headers: A ...
List models. Lists Watson Knowledge Studio [custom models](https://cloud.ibm.com/docs/services/natural-language-understanding/customizing.html) that are deployed to your Natural Language Understanding service. :param dict headers: A `dict` containing the request headers :return...
Below is the the instruction that describes the task: ### Input: List models. Lists Watson Knowledge Studio [custom models](https://cloud.ibm.com/docs/services/natural-language-understanding/customizing.html) that are deployed to your Natural Language Understanding service. :param ...
def metadata(self, map_id, secure=False): """Returns TileJSON metadata for a tileset. Parameters ---------- map_id : str The map's unique identifier in the format username.id. secure : bool, optional The representation of the requested resources, ...
Returns TileJSON metadata for a tileset. Parameters ---------- map_id : str The map's unique identifier in the format username.id. secure : bool, optional The representation of the requested resources, where True indicates representation as HTTPS en...
Below is the the instruction that describes the task: ### Input: Returns TileJSON metadata for a tileset. Parameters ---------- map_id : str The map's unique identifier in the format username.id. secure : bool, optional The representation of the requested re...
def get_send_result(self): """Method to get the progress of work notice sending.""" send_result = self.json_response.get("send_result", None) self.logger.info("%s\t%s" % (self.request_method, self.request_url)) return send_result
Method to get the progress of work notice sending.
Below is the the instruction that describes the task: ### Input: Method to get the progress of work notice sending. ### Response: def get_send_result(self): """Method to get the progress of work notice sending.""" send_result = self.json_response.get("send_result", None) self.logger.info...
def create(cls, name, dead_interval=40, hello_interval=10, hello_interval_type='normal', dead_multiplier=1, mtu_mismatch_detection=True, retransmit_interval=5, router_priority=1, transmit_delay=1, authentication_type=None, password=None, key_cha...
Create custom OSPF interface settings profile :param str name: name of interface settings :param int dead_interval: in seconds :param str hello_interval: in seconds :param str hello_interval_type: \|normal\|fast_hello :param int dead_multipler: fast hello packet multipler ...
Below is the the instruction that describes the task: ### Input: Create custom OSPF interface settings profile :param str name: name of interface settings :param int dead_interval: in seconds :param str hello_interval: in seconds :param str hello_interval_type: \|normal\|fast_hello ...
def getPopUpURL(self, CorpNum, NTSConfirmNum, UserID=None): """ 홈택스 전자세금계산서 보기 팝업 URL args CorpNum : 팝빌회원 사업자번호 NTSConfirmNum : 국세청 승인 번호 UserID : 팝빌회원 아이디 return 전자세금계산서 보기 팝업 URL 반환 raise Popbil...
홈택스 전자세금계산서 보기 팝업 URL args CorpNum : 팝빌회원 사업자번호 NTSConfirmNum : 국세청 승인 번호 UserID : 팝빌회원 아이디 return 전자세금계산서 보기 팝업 URL 반환 raise PopbillException
Below is the the instruction that describes the task: ### Input: 홈택스 전자세금계산서 보기 팝업 URL args CorpNum : 팝빌회원 사업자번호 NTSConfirmNum : 국세청 승인 번호 UserID : 팝빌회원 아이디 return 전자세금계산서 보기 팝업 URL 반환 raise PopbillEx...
async def get_access_token(self, oauth_verifier, request_token=None, loop=None, **params): """Get access_token from OAuth1 provider. :returns: (access_token, access_token_secret, provider_data) """ # Possibility to provide REQUEST DATA to the method if not isinstance(oauth_verif...
Get access_token from OAuth1 provider. :returns: (access_token, access_token_secret, provider_data)
Below is the the instruction that describes the task: ### Input: Get access_token from OAuth1 provider. :returns: (access_token, access_token_secret, provider_data) ### Response: async def get_access_token(self, oauth_verifier, request_token=None, loop=None, **params): """Get access_token from OAu...
def get_harddisk_sleep(): ''' Display the amount of idle time until the hard disk sleeps. :return: A string representing the sleep settings for the hard disk :rtype: str CLI Example: ..code-block:: bash salt '*' power.get_harddisk_sleep ''' ret = salt.utils.mac_utils.execute_...
Display the amount of idle time until the hard disk sleeps. :return: A string representing the sleep settings for the hard disk :rtype: str CLI Example: ..code-block:: bash salt '*' power.get_harddisk_sleep
Below is the the instruction that describes the task: ### Input: Display the amount of idle time until the hard disk sleeps. :return: A string representing the sleep settings for the hard disk :rtype: str CLI Example: ..code-block:: bash salt '*' power.get_harddisk_sleep ### Response: d...
def _get_head_types(pat): """ Accepts a pytree Pattern Node and returns a set of the pattern types which will match first. """ if isinstance(pat, (pytree.NodePattern, pytree.LeafPattern)): # NodePatters must either have no type and no content # or a type and content -- so they don't g...
Accepts a pytree Pattern Node and returns a set of the pattern types which will match first.
Below is the the instruction that describes the task: ### Input: Accepts a pytree Pattern Node and returns a set of the pattern types which will match first. ### Response: def _get_head_types(pat): """ Accepts a pytree Pattern Node and returns a set of the pattern types which will match first. ...
def fcontext_delete_policy(name, filetype=None, sel_type=None, sel_user=None, sel_level=None): ''' .. versionadded:: 2019.2.0 Deletes the SELinux policy for a given filespec and other optional parameters. Returns the result of the call to semanage. Note that you don't have to remove an entry befo...
.. versionadded:: 2019.2.0 Deletes the SELinux policy for a given filespec and other optional parameters. Returns the result of the call to semanage. Note that you don't have to remove an entry before setting a new one for a given filespec and filetype, as adding one with semanage automatically o...
Below is the the instruction that describes the task: ### Input: .. versionadded:: 2019.2.0 Deletes the SELinux policy for a given filespec and other optional parameters. Returns the result of the call to semanage. Note that you don't have to remove an entry before setting a new one for a given f...
def map_(input_layer, fn): """Maps the given function across this sequence. To map an entire template across the sequence, use the `as_fn` method on the template. Args: input_layer: The input tensor. fn: A function of 1 argument that is applied to each item in the sequence. Returns: A new sequen...
Maps the given function across this sequence. To map an entire template across the sequence, use the `as_fn` method on the template. Args: input_layer: The input tensor. fn: A function of 1 argument that is applied to each item in the sequence. Returns: A new sequence Pretty Tensor. Raises: ...
Below is the the instruction that describes the task: ### Input: Maps the given function across this sequence. To map an entire template across the sequence, use the `as_fn` method on the template. Args: input_layer: The input tensor. fn: A function of 1 argument that is applied to each item in the ...
def dropna_columns(data: pd.DataFrame, max_na_values: int=0.15): """ Remove columns with more NA values than threshold level :param data: :param max_na_values: proportion threshold of max na values :return: """ size = data.shape[0] df_na = (data.isnull().sum()/size) >= max_na_values ...
Remove columns with more NA values than threshold level :param data: :param max_na_values: proportion threshold of max na values :return:
Below is the the instruction that describes the task: ### Input: Remove columns with more NA values than threshold level :param data: :param max_na_values: proportion threshold of max na values :return: ### Response: def dropna_columns(data: pd.DataFrame, max_na_values: int=0.15): """ Remove c...
def arg(*args, **kwargs): """ Dcorates a function or a class method to add to the argument parser """ def decorate(func): """ Decorate """ # we'll set the command name with the passed cmd_name argument, if # exist, else the command name will be the function name ...
Dcorates a function or a class method to add to the argument parser
Below is the the instruction that describes the task: ### Input: Dcorates a function or a class method to add to the argument parser ### Response: def arg(*args, **kwargs): """ Dcorates a function or a class method to add to the argument parser """ def decorate(func): """ Decorate ...
def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*'...
Process part
Below is the the instruction that describes the task: ### Input: Process part ### Response: def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False ...
def shall_skip(app, module, private): """Check if we want to skip this module. :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param module: the module name :type module: :class:`str` :param private: True, if privates are allowed :type private: :class:`bool` ""...
Check if we want to skip this module. :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param module: the module name :type module: :class:`str` :param private: True, if privates are allowed :type private: :class:`bool`
Below is the the instruction that describes the task: ### Input: Check if we want to skip this module. :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param module: the module name :type module: :class:`str` :param private: True, if privates are allowed :type priva...
def get_response(self, **kwargs): """ Returns a Response object containing this object's status code and a JSON object containing the key "error" with the value of this object's error message in the body. Keyword args are passed through to the Response. """ return...
Returns a Response object containing this object's status code and a JSON object containing the key "error" with the value of this object's error message in the body. Keyword args are passed through to the Response.
Below is the the instruction that describes the task: ### Input: Returns a Response object containing this object's status code and a JSON object containing the key "error" with the value of this object's error message in the body. Keyword args are passed through to the Response. ### Respons...
def v_reference_choice(ctx, stmt): """Make sure that the default case exists""" d = stmt.search_one('default') if d is not None: m = stmt.search_one('mandatory') if m is not None and m.arg == 'true': err_add(ctx.errors, stmt.pos, 'DEFAULT_AND_MANDATORY', ()) ptr = attrsea...
Make sure that the default case exists
Below is the the instruction that describes the task: ### Input: Make sure that the default case exists ### Response: def v_reference_choice(ctx, stmt): """Make sure that the default case exists""" d = stmt.search_one('default') if d is not None: m = stmt.search_one('mandatory') if m is...
def _approxaAInv(self,Or,Op,Oz,ar,ap,az,interp=True): """ NAME: _approxaAInv PURPOSE: return R,vR,... coordinates for a point based on the linear approximation around the stream track INPUT: Or,Op,Oz,ar,ap,az - phase space coordinates in frequ...
NAME: _approxaAInv PURPOSE: return R,vR,... coordinates for a point based on the linear approximation around the stream track INPUT: Or,Op,Oz,ar,ap,az - phase space coordinates in frequency-angle space interp= (True)...
Below is the the instruction that describes the task: ### Input: NAME: _approxaAInv PURPOSE: return R,vR,... coordinates for a point based on the linear approximation around the stream track INPUT: Or,Op,Oz,ar,ap,az - phase space coordinates in frequency-...
def shell(): version_too_old = False if sys.version_info[0] == 2: if sys.version_info < (2, 7): version_too_old = True elif sys.version_info.major == 3 and sys.version_info < (3, 5): version_too_old = True if version_too_old: print('Pyradio requires python 2.7...
Setting ESCAPE key delay to 25ms Refer to: https://stackoverflow.com/questions/27372068/why-does-the-escape-key-have-a-delay-in-python-curses
Below is the the instruction that describes the task: ### Input: Setting ESCAPE key delay to 25ms Refer to: https://stackoverflow.com/questions/27372068/why-does-the-escape-key-have-a-delay-in-python-curses ### Response: def shell(): version_too_old = False if sys.version_info[0] == 2: if sys.v...
def get_health_monitor(self, loadbalancer): """ Returns a dict representing the health monitor for the load balancer. If no monitor has been configured, returns an empty dict. """ uri = "/loadbalancers/%s/healthmonitor" % utils.get_id(loadbalancer) resp, body = se...
Returns a dict representing the health monitor for the load balancer. If no monitor has been configured, returns an empty dict.
Below is the the instruction that describes the task: ### Input: Returns a dict representing the health monitor for the load balancer. If no monitor has been configured, returns an empty dict. ### Response: def get_health_monitor(self, loadbalancer): """ Returns a dict representing ...
def cleanup_codra_edus(self): """Remove leading/trailing '_!' from CODRA EDUs and unescape its double quotes.""" for leafpos in self.tree.treepositions('leaves'): edu_str = self.tree[leafpos] edu_str = EDU_START_RE.sub("", edu_str) edu_str = TRIPLE_ESCAPE_RE.sub('"',...
Remove leading/trailing '_!' from CODRA EDUs and unescape its double quotes.
Below is the the instruction that describes the task: ### Input: Remove leading/trailing '_!' from CODRA EDUs and unescape its double quotes. ### Response: def cleanup_codra_edus(self): """Remove leading/trailing '_!' from CODRA EDUs and unescape its double quotes.""" for leafpos in self.tree.treep...
def _get_rules_from_aws(self): """ Load the EC2 security rules off AWS into a list of dict. Returns: list """ list_of_rules = list() if self.profile: boto3.setup_default_session(profile_name=self.profile) if self.region: ec2 ...
Load the EC2 security rules off AWS into a list of dict. Returns: list
Below is the the instruction that describes the task: ### Input: Load the EC2 security rules off AWS into a list of dict. Returns: list ### Response: def _get_rules_from_aws(self): """ Load the EC2 security rules off AWS into a list of dict. Returns: list ...
def library_supports_api(library_version, api_version, different_major_breaks_support=True): """ Returns whether api_version is supported by given library version. E. g. library_version (1,3,21) returns True for api_version (1,3,21), (1,3,19), (1,3,'x'), (1,2,'x'), (1, 'x') False for (1,3,24), (...
Returns whether api_version is supported by given library version. E. g. library_version (1,3,21) returns True for api_version (1,3,21), (1,3,19), (1,3,'x'), (1,2,'x'), (1, 'x') False for (1,3,24), (1,4,'x'), (2,'x') different_major_breaks_support - if enabled and library and api major versions are...
Below is the the instruction that describes the task: ### Input: Returns whether api_version is supported by given library version. E. g. library_version (1,3,21) returns True for api_version (1,3,21), (1,3,19), (1,3,'x'), (1,2,'x'), (1, 'x') False for (1,3,24), (1,4,'x'), (2,'x') different_maj...
def _set_alarm_sample(self, v, load=False): """ Setter method for alarm_sample, mapped from YANG variable /rmon/alarm_entry/alarm_sample (alarm-sample-type) If this variable is read-only (config: false) in the source YANG file, then _set_alarm_sample is considered as a private method. Backends looki...
Setter method for alarm_sample, mapped from YANG variable /rmon/alarm_entry/alarm_sample (alarm-sample-type) If this variable is read-only (config: false) in the source YANG file, then _set_alarm_sample is considered as a private method. Backends looking to populate this variable should do so via callin...
Below is the the instruction that describes the task: ### Input: Setter method for alarm_sample, mapped from YANG variable /rmon/alarm_entry/alarm_sample (alarm-sample-type) If this variable is read-only (config: false) in the source YANG file, then _set_alarm_sample is considered as a private method. B...
def GetPixelColorsOfRects(self, rects: list) -> list: """ rects: a list of rects, such as [(0,0,10,10), (10,10,20,20),(x,y,width,height)]. Return list, a list whose elements are ctypes.Array which is an iterable array of int values in argb. """ rects2 = [(x, y, x + width, y + hei...
rects: a list of rects, such as [(0,0,10,10), (10,10,20,20),(x,y,width,height)]. Return list, a list whose elements are ctypes.Array which is an iterable array of int values in argb.
Below is the the instruction that describes the task: ### Input: rects: a list of rects, such as [(0,0,10,10), (10,10,20,20),(x,y,width,height)]. Return list, a list whose elements are ctypes.Array which is an iterable array of int values in argb. ### Response: def GetPixelColorsOfRects(self, rects: list) ...
def create_instances(configuration): """Create necessary class instances from a configuration with no argument to the constructor :param dict configuration: configuration dict like in :attr:`~pyextdirect.configuration.Base.configuration` :return: a class-instance mapping :rtype: dict """ insta...
Create necessary class instances from a configuration with no argument to the constructor :param dict configuration: configuration dict like in :attr:`~pyextdirect.configuration.Base.configuration` :return: a class-instance mapping :rtype: dict
Below is the the instruction that describes the task: ### Input: Create necessary class instances from a configuration with no argument to the constructor :param dict configuration: configuration dict like in :attr:`~pyextdirect.configuration.Base.configuration` :return: a class-instance mapping :rtype...
def get_containers_by_name(self, name): """ get all task which relative with task name :param name: :class:`str`, task name :return: :class:`list`, container list """ code, containers = self.get_containers() if code != httplib.OK: return [] ...
get all task which relative with task name :param name: :class:`str`, task name :return: :class:`list`, container list
Below is the the instruction that describes the task: ### Input: get all task which relative with task name :param name: :class:`str`, task name :return: :class:`list`, container list ### Response: def get_containers_by_name(self, name): """ get all task which relative with task...
def pverb(self, *args, **kwargs): """ Console verbose message to STDOUT """ if not self.verbose: return self.pstd(*args, **kwargs)
Console verbose message to STDOUT
Below is the the instruction that describes the task: ### Input: Console verbose message to STDOUT ### Response: def pverb(self, *args, **kwargs): """ Console verbose message to STDOUT """ if not self.verbose: return self.pstd(*args, **kwargs)
def retry_failure_fab_dev_create(self, tenant_id, fw_data, fw_dict): """This module calls routine in fabric to retry the failure cases. If device is not successfully cfg/uncfg, it calls the device manager routine to cfg/uncfg the device. """ result = fw_data.get('result').split(...
This module calls routine in fabric to retry the failure cases. If device is not successfully cfg/uncfg, it calls the device manager routine to cfg/uncfg the device.
Below is the the instruction that describes the task: ### Input: This module calls routine in fabric to retry the failure cases. If device is not successfully cfg/uncfg, it calls the device manager routine to cfg/uncfg the device. ### Response: def retry_failure_fab_dev_create(self, tenant_id, fw_...
def change_format(self): """ Ask user for display format for floats and use it. This function also checks whether the format is valid and emits `sig_option_changed`. """ format, valid = QInputDialog.getText(self, _('Format'), ...
Ask user for display format for floats and use it. This function also checks whether the format is valid and emits `sig_option_changed`.
Below is the the instruction that describes the task: ### Input: Ask user for display format for floats and use it. This function also checks whether the format is valid and emits `sig_option_changed`. ### Response: def change_format(self): """ Ask user for display format for ...
def istr_type(istr): """ Given an "ion" specification, determine its "type", e.g. 1D, Events, etc. """ data = set(i.rstrip('0123456789') for i in tokens(istr)) has_events = not data.isdisjoint(istr_type_evts) has_2d = not data.isdisjoint(istr_type_2d) has_1d = data.difference(istr_type_evts)...
Given an "ion" specification, determine its "type", e.g. 1D, Events, etc.
Below is the the instruction that describes the task: ### Input: Given an "ion" specification, determine its "type", e.g. 1D, Events, etc. ### Response: def istr_type(istr): """ Given an "ion" specification, determine its "type", e.g. 1D, Events, etc. """ data = set(i.rstrip('0123456789') for i in ...
def start(self, daemon = False): """Start the threads.""" self.daemon = daemon self.io_threads = [] self.event_thread = EventDispatcherThread(self.event_dispatcher, daemon = daemon, exc_queue = self.exc_queue) self.event_thread.start() ...
Start the threads.
Below is the the instruction that describes the task: ### Input: Start the threads. ### Response: def start(self, daemon = False): """Start the threads.""" self.daemon = daemon self.io_threads = [] self.event_thread = EventDispatcherThread(self.event_dispatcher, ...