code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def generate_handler(): """Create the Blockade user and give them permissions.""" logger.debug("[#] Setting up user, group and permissions") client = boto3.client("iam", region_name=PRIMARY_REGION) # Create the user try: response = client.create_user( UserName=BLOCKADE_USER ...
Create the Blockade user and give them permissions.
Below is the the instruction that describes the task: ### Input: Create the Blockade user and give them permissions. ### Response: def generate_handler(): """Create the Blockade user and give them permissions.""" logger.debug("[#] Setting up user, group and permissions") client = boto3.client("iam", re...
def get_schema(self, db_name, table_name): """ Parameters: - db_name - table_name """ self.send_get_schema(db_name, table_name) return self.recv_get_schema()
Parameters: - db_name - table_name
Below is the the instruction that describes the task: ### Input: Parameters: - db_name - table_name ### Response: def get_schema(self, db_name, table_name): """ Parameters: - db_name - table_name """ self.send_get_schema(db_name, table_name) return self.recv_get_schema()
def get_composition_search_session(self): """Gets a composition search session. return: (osid.repository.CompositionSearchSession) - a ``CompositionSearchSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_composition_search(...
Gets a composition search session. return: (osid.repository.CompositionSearchSession) - a ``CompositionSearchSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_composition_search()`` is ``false`` *compliance:...
Below is the the instruction that describes the task: ### Input: Gets a composition search session. return: (osid.repository.CompositionSearchSession) - a ``CompositionSearchSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_com...
def Create(alias=None,location=None,session=None): """Claims a new network within a given account. https://www.ctl.io/api-docs/v2/#networks-claim-network Returns operation id and link to check status """ if not alias: alias = clc.v2.Account.GetAlias(session=session) if not location: location = clc.v2.A...
Claims a new network within a given account. https://www.ctl.io/api-docs/v2/#networks-claim-network Returns operation id and link to check status
Below is the the instruction that describes the task: ### Input: Claims a new network within a given account. https://www.ctl.io/api-docs/v2/#networks-claim-network Returns operation id and link to check status ### Response: def Create(alias=None,location=None,session=None): """Claims a new network within ...
def go_inactive(self, dt=datetime.utcnow().replace(tzinfo=pytz.UTC)): """Make the configuration object inactive. Keyword arguments: dt -- datetime of the moment when the configuration go inactive """ self.end = dt self.save()
Make the configuration object inactive. Keyword arguments: dt -- datetime of the moment when the configuration go inactive
Below is the the instruction that describes the task: ### Input: Make the configuration object inactive. Keyword arguments: dt -- datetime of the moment when the configuration go inactive ### Response: def go_inactive(self, dt=datetime.utcnow().replace(tzinfo=pytz.UTC)): """Make the configuration object i...
def _ParseValueData(self, parser_mediator, registry_key, registry_value): """Extracts event objects from a Explorer ProgramsCache value data. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinr...
Extracts event objects from a Explorer ProgramsCache value data. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key. registry_value (dfwinreg.WinRegis...
Below is the the instruction that describes the task: ### Input: Extracts event objects from a Explorer ProgramsCache value data. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegist...
def cachestr_repr(val): """ Representation of an object as a cache string. """ try: memview = memoryview(val) return memview.tobytes() except Exception: try: return to_json(val) except Exception: # SUPER HACK if repr(val.__class__) ...
Representation of an object as a cache string.
Below is the the instruction that describes the task: ### Input: Representation of an object as a cache string. ### Response: def cachestr_repr(val): """ Representation of an object as a cache string. """ try: memview = memoryview(val) return memview.tobytes() except Exception: ...
def init_user_ns(self): """Initialize all user-visible namespaces to their minimum defaults. Certain history lists are also initialized here, as they effectively act as user namespaces. Notes ----- All data structures here are only filled in, they are NOT reset by this ...
Initialize all user-visible namespaces to their minimum defaults. Certain history lists are also initialized here, as they effectively act as user namespaces. Notes ----- All data structures here are only filled in, they are NOT reset by this method. If they were not e...
Below is the the instruction that describes the task: ### Input: Initialize all user-visible namespaces to their minimum defaults. Certain history lists are also initialized here, as they effectively act as user namespaces. Notes ----- All data structures here are only fill...
def absent(name, service_name, auth=None, **kwargs): ''' Ensure an endpoint does not exists name Interface name url URL of the endpoint service_name Service name or ID region The region name to assign the endpoint ''' ret = {'name': name, 'c...
Ensure an endpoint does not exists name Interface name url URL of the endpoint service_name Service name or ID region The region name to assign the endpoint
Below is the the instruction that describes the task: ### Input: Ensure an endpoint does not exists name Interface name url URL of the endpoint service_name Service name or ID region The region name to assign the endpoint ### Response: def absent(name, service_na...
def mouseMoveEvent(self, event): """ Handle the mouse move event for a drag operation. """ #if event.buttons() & Qt.LeftButton and self._drag_origin is not None: #dist = (event.pos() - self._drag_origin).manhattanLength() #if dist >= QApplication.startDragDistance(): ...
Handle the mouse move event for a drag operation.
Below is the the instruction that describes the task: ### Input: Handle the mouse move event for a drag operation. ### Response: def mouseMoveEvent(self, event): """ Handle the mouse move event for a drag operation. """ #if event.buttons() & Qt.LeftButton and self._drag_origin is not None:...
def _get_components(self): """ Subclasses may override this method. """ return tuple([self._getitem__components(i) for i in range(self._len__components())])
Subclasses may override this method.
Below is the the instruction that describes the task: ### Input: Subclasses may override this method. ### Response: def _get_components(self): """ Subclasses may override this method. """ return tuple([self._getitem__components(i) for i in range(self._len__compo...
def lines_from_tree(tree, nodes_and_set:bool=False) -> iter: """Yield lines of bubble describing given BubbleTree""" NODE = 'NODE\t{}' INCL = 'IN\t{}\t{}' EDGE = 'EDGE\t{}\t{}\t1.0' SET = 'SET\t{}' if nodes_and_set: for node in tree.nodes(): yield NODE.format(node) ...
Yield lines of bubble describing given BubbleTree
Below is the the instruction that describes the task: ### Input: Yield lines of bubble describing given BubbleTree ### Response: def lines_from_tree(tree, nodes_and_set:bool=False) -> iter: """Yield lines of bubble describing given BubbleTree""" NODE = 'NODE\t{}' INCL = 'IN\t{}\t{}' EDGE = 'EDGE\t{...
def progress(iterator, enum=False, length=None): """ A helper utility to display a progress bar when iterating over a collection of a fixed length or a generator (with a declared length). If enum=True, then equivalent to enumerate with a progress bar. """ progress = ProgressBar() length...
A helper utility to display a progress bar when iterating over a collection of a fixed length or a generator (with a declared length). If enum=True, then equivalent to enumerate with a progress bar.
Below is the the instruction that describes the task: ### Input: A helper utility to display a progress bar when iterating over a collection of a fixed length or a generator (with a declared length). If enum=True, then equivalent to enumerate with a progress bar. ### Response: def progress(iterator, e...
def mysql_aes_decrypt(encrypted_val, key): """Mysql AES decrypt value with secret key. :param encrypted_val: Encrypted value. :param key: The AES key. :returns: The AES value decrypted. """ assert isinstance(encrypted_val, binary_type) \ or isinstance(encrypted_val, text_type) asser...
Mysql AES decrypt value with secret key. :param encrypted_val: Encrypted value. :param key: The AES key. :returns: The AES value decrypted.
Below is the the instruction that describes the task: ### Input: Mysql AES decrypt value with secret key. :param encrypted_val: Encrypted value. :param key: The AES key. :returns: The AES value decrypted. ### Response: def mysql_aes_decrypt(encrypted_val, key): """Mysql AES decrypt value with secr...
def create_widget(self): """ Create the toolkit widget for the proxy object. This method is called during the top-down pass, just before the 'init_widget()' method is called. This method should create the toolkit widget and assign it to the 'widget' attribute. """ self....
Create the toolkit widget for the proxy object. This method is called during the top-down pass, just before the 'init_widget()' method is called. This method should create the toolkit widget and assign it to the 'widget' attribute.
Below is the the instruction that describes the task: ### Input: Create the toolkit widget for the proxy object. This method is called during the top-down pass, just before the 'init_widget()' method is called. This method should create the toolkit widget and assign it to the 'widget' attri...
def get(self, query: Mapping[str, Any], context: PipelineContext = None) -> T: """Gets a query from the data source. 1) Extracts the query from the data source. 2) Inserts the result into any data sinks. 3) Transforms the result into the requested type if it wasn't already. 4) I...
Gets a query from the data source. 1) Extracts the query from the data source. 2) Inserts the result into any data sinks. 3) Transforms the result into the requested type if it wasn't already. 4) Inserts the transformed result into any data sinks. Args: query: The q...
Below is the the instruction that describes the task: ### Input: Gets a query from the data source. 1) Extracts the query from the data source. 2) Inserts the result into any data sinks. 3) Transforms the result into the requested type if it wasn't already. 4) Inserts the transforme...
def trips(self, val): """ Update ``self._trips_i`` if ``self.trips`` changes. """ self._trips = val if val is not None and not val.empty: self._trips_i = self._trips.set_index("trip_id") else: self._trips_i = None
Update ``self._trips_i`` if ``self.trips`` changes.
Below is the the instruction that describes the task: ### Input: Update ``self._trips_i`` if ``self.trips`` changes. ### Response: def trips(self, val): """ Update ``self._trips_i`` if ``self.trips`` changes. """ self._trips = val if val is not None and not val.empty: ...
def compute(self, activeColumns, basalInput, apicalInput=(), basalGrowthCandidates=None, apicalGrowthCandidates=None, learn=True): """ Perform one timestep. Use the basal and apical input to form a set of predictions, then a...
Perform one timestep. Use the basal and apical input to form a set of predictions, then activate the specified columns, then learn. @param activeColumns (numpy array) List of active columns @param basalInput (numpy array) List of active input bits for the basal dendrite segments @param apical...
Below is the the instruction that describes the task: ### Input: Perform one timestep. Use the basal and apical input to form a set of predictions, then activate the specified columns, then learn. @param activeColumns (numpy array) List of active columns @param basalInput (numpy array) List of...
def call(self, itemMethod): """ Invoke the given bound item method in the batch process. Return a Deferred which fires when the method has been invoked. """ item = itemMethod.im_self method = itemMethod.im_func.func_name return self.batchController.getProcess().a...
Invoke the given bound item method in the batch process. Return a Deferred which fires when the method has been invoked.
Below is the the instruction that describes the task: ### Input: Invoke the given bound item method in the batch process. Return a Deferred which fires when the method has been invoked. ### Response: def call(self, itemMethod): """ Invoke the given bound item method in the batch process. ...
def calc_A(Ys): '''Return the matrix A from a list of Y vectors.''' return sum(np.dot(np.reshape(Y, (3,1)), np.reshape(Y, (1, 3))) for Y in Ys)
Return the matrix A from a list of Y vectors.
Below is the the instruction that describes the task: ### Input: Return the matrix A from a list of Y vectors. ### Response: def calc_A(Ys): '''Return the matrix A from a list of Y vectors.''' return sum(np.dot(np.reshape(Y, (3,1)), np.reshape(Y, (1, 3))) for Y in Ys)
def create_contract(self, price=0, address=None, caller=None, balance=0, init=None, gas=None): """ Create a contract account. Sends a transaction to initialize the contract :param address: the address of the new account, if known. If omitted, a new address will be generated as closely to the Ye...
Create a contract account. Sends a transaction to initialize the contract :param address: the address of the new account, if known. If omitted, a new address will be generated as closely to the Yellow Paper as possible. :param balance: the initial balance of the account in Wei :param init: the ...
Below is the the instruction that describes the task: ### Input: Create a contract account. Sends a transaction to initialize the contract :param address: the address of the new account, if known. If omitted, a new address will be generated as closely to the Yellow Paper as possible. :param balance...
async def random_connection(self): """Connect to random agent from current :attr:`connections`. :returns: :class:`aiomas.Proxy` object for the connected agent. """ addr = choice(list(self._connections.keys())) return await self.env.connect(addr)
Connect to random agent from current :attr:`connections`. :returns: :class:`aiomas.Proxy` object for the connected agent.
Below is the the instruction that describes the task: ### Input: Connect to random agent from current :attr:`connections`. :returns: :class:`aiomas.Proxy` object for the connected agent. ### Response: async def random_connection(self): """Connect to random agent from current :attr:`connections`. ...
def gradient(self): """The gradient operator.""" # First we store the functional in a variable functional = self # The class corresponding to the gradient operator. class MyGradientOperator(odl.Operator): """Class implementing the gradient operator.""" ...
The gradient operator.
Below is the the instruction that describes the task: ### Input: The gradient operator. ### Response: def gradient(self): """The gradient operator.""" # First we store the functional in a variable functional = self # The class corresponding to the gradient operator. class ...
def SystemFee(self): """ Get the system fee. Returns: Fixed8: currently fixed to 0. """ tx_name = TransactionType.ToName(self.Type) return Fixed8.FromDecimal(settings.ALL_FEES.get(tx_name, 0))
Get the system fee. Returns: Fixed8: currently fixed to 0.
Below is the the instruction that describes the task: ### Input: Get the system fee. Returns: Fixed8: currently fixed to 0. ### Response: def SystemFee(self): """ Get the system fee. Returns: Fixed8: currently fixed to 0. """ tx_name = Trans...
def _analyze_pages_with_partial_read(self): """! @brief Estimate how many pages are the same by reading data. Pages are analyzed by reading the first 32 bytes and comparing with data to be programmed. """ # Quickly estimate how many pages are the same as current flash contents. ...
! @brief Estimate how many pages are the same by reading data. Pages are analyzed by reading the first 32 bytes and comparing with data to be programmed.
Below is the the instruction that describes the task: ### Input: ! @brief Estimate how many pages are the same by reading data. Pages are analyzed by reading the first 32 bytes and comparing with data to be programmed. ### Response: def _analyze_pages_with_partial_read(self): """! @brief E...
def align_options(options): """ Indents flags and aligns help texts. """ l = 0 for opt in options: if len(opt[0]) > l: l = len(opt[0]) s = [] for opt in options: s.append(' {0}{1} {2}'.format(opt[0], ' ' * (l - len(opt[0])), opt[1])) return '\n'.join(s)
Indents flags and aligns help texts.
Below is the the instruction that describes the task: ### Input: Indents flags and aligns help texts. ### Response: def align_options(options): """ Indents flags and aligns help texts. """ l = 0 for opt in options: if len(opt[0]) > l: l = len(opt[0]) s = [] for opt i...
def _refresh(self): """Background refreshing thread.""" while not self._stopevent.isSet(): line = self._serial.readline() #this is for python2/python3 compatibility. Is there a better way? try: line = line.encode().decode('utf-8') except A...
Background refreshing thread.
Below is the the instruction that describes the task: ### Input: Background refreshing thread. ### Response: def _refresh(self): """Background refreshing thread.""" while not self._stopevent.isSet(): line = self._serial.readline() #this is for python2/python3 compatibility....
def load_all_methods(self): r'''Method which picks out coefficients for the specified chemical from the various dictionaries and DataFrames storing it. All data is stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`, :obj:`all_methods` and obj:`all_methods_P` as a set of...
r'''Method which picks out coefficients for the specified chemical from the various dictionaries and DataFrames storing it. All data is stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`, :obj:`all_methods` and obj:`all_methods_P` as a set of methods for which the data ...
Below is the the instruction that describes the task: ### Input: r'''Method which picks out coefficients for the specified chemical from the various dictionaries and DataFrames storing it. All data is stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`, :obj:`all_methods` an...
def check_part(state, name, part_msg, missing_msg=None, expand_msg=None): """Return child state with name part as its ast tree""" if missing_msg is None: missing_msg = "Are you sure you defined the {{part}}? " if expand_msg is None: expand_msg = "Did you correctly specify the {{part}}? " ...
Return child state with name part as its ast tree
Below is the the instruction that describes the task: ### Input: Return child state with name part as its ast tree ### Response: def check_part(state, name, part_msg, missing_msg=None, expand_msg=None): """Return child state with name part as its ast tree""" if missing_msg is None: missing_msg = "...
def setup(app, version): """Called by Sphinx during phase 0 (initialization). :param sphinx.application.Sphinx app: Sphinx application object. :param str version: Version of sphinxcontrib-imgur. :returns: Extension metadata. :rtype: dict """ app.add_config_value('imgur_api_cache_ttl', 1728...
Called by Sphinx during phase 0 (initialization). :param sphinx.application.Sphinx app: Sphinx application object. :param str version: Version of sphinxcontrib-imgur. :returns: Extension metadata. :rtype: dict
Below is the the instruction that describes the task: ### Input: Called by Sphinx during phase 0 (initialization). :param sphinx.application.Sphinx app: Sphinx application object. :param str version: Version of sphinxcontrib-imgur. :returns: Extension metadata. :rtype: dict ### Response: def setu...
def forward_search_history(self, e): # (C-s) u'''Search forward starting at the current line and moving down through the the history as necessary. This is an incremental search.''' log("fwd_search_history") self._init_incremental_search(self._history.forward_search_history,...
u'''Search forward starting at the current line and moving down through the the history as necessary. This is an incremental search.
Below is the the instruction that describes the task: ### Input: u'''Search forward starting at the current line and moving down through the the history as necessary. This is an incremental search. ### Response: def forward_search_history(self, e): # (C-s) u'''Search forward starting at...
def predict_subsequences(self, sequence_dict, peptide_lengths=None): """Given a dictionary mapping unique keys to amino acid sequences, run MHC binding predictions on all candidate epitopes extracted from sequences and return a EpitopeCollection. Parameters ---------- fa...
Given a dictionary mapping unique keys to amino acid sequences, run MHC binding predictions on all candidate epitopes extracted from sequences and return a EpitopeCollection. Parameters ---------- fasta_dictionary : dict or string Mapping of protein identifiers to pr...
Below is the the instruction that describes the task: ### Input: Given a dictionary mapping unique keys to amino acid sequences, run MHC binding predictions on all candidate epitopes extracted from sequences and return a EpitopeCollection. Parameters ---------- fasta_diction...
def _ready_for_het_analysis(items): """Check if a sample has input information for heterogeneity analysis. We currently require a tumor/normal sample containing both CNV and variant calls. """ paired = vcfutils.get_paired_bams([dd.get_align_bam(d) for d in items], items) has_het = any(dd.get_hetcal...
Check if a sample has input information for heterogeneity analysis. We currently require a tumor/normal sample containing both CNV and variant calls.
Below is the the instruction that describes the task: ### Input: Check if a sample has input information for heterogeneity analysis. We currently require a tumor/normal sample containing both CNV and variant calls. ### Response: def _ready_for_het_analysis(items): """Check if a sample has input informatio...
def optimizeTransforms(element, options): """ Attempts to optimise transform specifications on the given node and its children. Returns the number of bytes saved after performing these reductions. """ num = 0 for transformAttr in ['transform', 'patternTransform', 'gradientTransform']: ...
Attempts to optimise transform specifications on the given node and its children. Returns the number of bytes saved after performing these reductions.
Below is the the instruction that describes the task: ### Input: Attempts to optimise transform specifications on the given node and its children. Returns the number of bytes saved after performing these reductions. ### Response: def optimizeTransforms(element, options): """ Attempts to optimise trans...
def Runtime_callFunctionOn(self, functionDeclaration, **kwargs): """ Function path: Runtime.callFunctionOn Domain: Runtime Method name: callFunctionOn Parameters: Required arguments: 'functionDeclaration' (type: string) -> Declaration of the function to call. Optional arguments: 'objec...
Function path: Runtime.callFunctionOn Domain: Runtime Method name: callFunctionOn Parameters: Required arguments: 'functionDeclaration' (type: string) -> Declaration of the function to call. Optional arguments: 'objectId' (type: RemoteObjectId) -> Identifier of the object to call function ...
Below is the the instruction that describes the task: ### Input: Function path: Runtime.callFunctionOn Domain: Runtime Method name: callFunctionOn Parameters: Required arguments: 'functionDeclaration' (type: string) -> Declaration of the function to call. Optional arguments: 'objectId'...
def sflow_profile_profile_sampling_rate(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") sflow_profile = ET.SubElement(config, "sflow-profile", xmlns="urn:brocade.com:mgmt:brocade-sflow") profile_name_key = ET.SubElement(sflow_profile, "profile-name") ...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def sflow_profile_profile_sampling_rate(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") sflow_profile = ET.SubElement(config, "sflow-profile", xmlns="urn:broc...
def treewalk(self, root, parsed, unparsed): """ Recursively walks the syntax tree at root and returns the items parsed, unparsed and possible suggestions """ suggestions = dict() if not unparsed: logger.debug("no tokens left unparsed. returning %s, %s", parsed, suggestions) ...
Recursively walks the syntax tree at root and returns the items parsed, unparsed and possible suggestions
Below is the the instruction that describes the task: ### Input: Recursively walks the syntax tree at root and returns the items parsed, unparsed and possible suggestions ### Response: def treewalk(self, root, parsed, unparsed): """ Recursively walks the syntax tree at root and returns the ...
def true_num_reactions(model, custom_spont_id=None): """Return the number of reactions associated with a gene. Args: model (Model): custom_spont_id (str): Optional custom spontaneous ID if it does not match the regular expression ``[Ss](_|)0001`` Returns: int: Number of reactions a...
Return the number of reactions associated with a gene. Args: model (Model): custom_spont_id (str): Optional custom spontaneous ID if it does not match the regular expression ``[Ss](_|)0001`` Returns: int: Number of reactions associated with a gene
Below is the the instruction that describes the task: ### Input: Return the number of reactions associated with a gene. Args: model (Model): custom_spont_id (str): Optional custom spontaneous ID if it does not match the regular expression ``[Ss](_|)0001`` Returns: int: Number of re...
def is_valid(self): '''checks if type is a valid type''' return (self.is_primitive and self.name) \ or (self.is_complex and self.name) \ or (self.is_list and self.nested) \ or (self.is_map and self.nested) \ or (self.is_model and self.nested)
checks if type is a valid type
Below is the the instruction that describes the task: ### Input: checks if type is a valid type ### Response: def is_valid(self): '''checks if type is a valid type''' return (self.is_primitive and self.name) \ or (self.is_complex and self.name) \ or (self.is_list and self.ne...
def _forward_outbound(self, channel): """ Forward outbound traffic (ssh -> websockets) """ try: while True: wait_read(channel.fileno()) data = channel.recv(1024) if not len(data): return self._websocket.send(...
Forward outbound traffic (ssh -> websockets)
Below is the the instruction that describes the task: ### Input: Forward outbound traffic (ssh -> websockets) ### Response: def _forward_outbound(self, channel): """ Forward outbound traffic (ssh -> websockets) """ try: while True: wait_read(channel.fileno()) ...
def endpoint_deactivate(endpoint_id): """ Executor for `globus endpoint deactivate` """ client = get_client() res = client.endpoint_deactivate(endpoint_id) formatted_print(res, text_format=FORMAT_TEXT_RAW, response_key="message")
Executor for `globus endpoint deactivate`
Below is the the instruction that describes the task: ### Input: Executor for `globus endpoint deactivate` ### Response: def endpoint_deactivate(endpoint_id): """ Executor for `globus endpoint deactivate` """ client = get_client() res = client.endpoint_deactivate(endpoint_id) formatted_prin...
def _set_radius_server(self, v, load=False): """ Setter method for radius_server, mapped from YANG variable /radius_server (container) If this variable is read-only (config: false) in the source YANG file, then _set_radius_server is considered as a private method. Backends looking to populate this v...
Setter method for radius_server, mapped from YANG variable /radius_server (container) If this variable is read-only (config: false) in the source YANG file, then _set_radius_server is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_radius_...
Below is the the instruction that describes the task: ### Input: Setter method for radius_server, mapped from YANG variable /radius_server (container) If this variable is read-only (config: false) in the source YANG file, then _set_radius_server is considered as a private method. Backends looking to pop...
def process_files(): """ Use Manager and Counter as context managers """ with enlighten.Manager() as manager: with manager.counter(total=SPLINES, desc='Reticulating:', unit='splines') as retic: for num in range(SPLINES): # pylint: disable=unused-variable time.sleep(...
Use Manager and Counter as context managers
Below is the the instruction that describes the task: ### Input: Use Manager and Counter as context managers ### Response: def process_files(): """ Use Manager and Counter as context managers """ with enlighten.Manager() as manager: with manager.counter(total=SPLINES, desc='Reticulating:',...
def writeline(self, line): """print a line of python, indenting it according to the current indent level. this also adjusts the indentation counter according to the content of the line. """ if not self.in_indent_lines: self._flush_adjusted_lines() ...
print a line of python, indenting it according to the current indent level. this also adjusts the indentation counter according to the content of the line.
Below is the the instruction that describes the task: ### Input: print a line of python, indenting it according to the current indent level. this also adjusts the indentation counter according to the content of the line. ### Response: def writeline(self, line): """print a line of p...
def make_transient(std, DMmax, Amin=6., Amax=20., rmax=20., rmin=0., DMmin=0.): """ Produce a mock transient pulse source for the purposes of characterizing the detection success of the current pipeline. Assumes - Code to inject the transients does so by inserting at an array index - Noise lev...
Produce a mock transient pulse source for the purposes of characterizing the detection success of the current pipeline. Assumes - Code to inject the transients does so by inserting at an array index - Noise level at the center of the data array is characteristic of the noise level throughout...
Below is the the instruction that describes the task: ### Input: Produce a mock transient pulse source for the purposes of characterizing the detection success of the current pipeline. Assumes - Code to inject the transients does so by inserting at an array index - Noise level at the center of...
def bisine_wahwah_wave(frequency): """Emit two sine waves with balance oscillating left and right.""" # # This is clearly intended to build on the bisine wave defined above, # so we can start by generating that. waves_a = bisine_wave(frequency) # # Then, by reversing axis 2, we swap the stereo channels. B...
Emit two sine waves with balance oscillating left and right.
Below is the the instruction that describes the task: ### Input: Emit two sine waves with balance oscillating left and right. ### Response: def bisine_wahwah_wave(frequency): """Emit two sine waves with balance oscillating left and right.""" # # This is clearly intended to build on the bisine wave defined ab...
def create_avg_rsp(rsp_fn, skydir, ltc, event_class, event_types, x, egy, cth_bins, npts=None): """Calculate the weighted response function. """ if npts is None: npts = int(np.ceil(np.max(cth_bins[1:] - cth_bins[:-1]) / 0.05)) wrsp = np.zeros((len(x), len(egy), len(cth_bins) ...
Calculate the weighted response function.
Below is the the instruction that describes the task: ### Input: Calculate the weighted response function. ### Response: def create_avg_rsp(rsp_fn, skydir, ltc, event_class, event_types, x, egy, cth_bins, npts=None): """Calculate the weighted response function. """ if npts is None: ...
def get_ajax_xeditable_choices(self, request, *args, **kwargs): """ AJAX GET handler for xeditable queries asking for field choice lists. """ field_name = request.GET.get(self.xeditable_fieldname_param) if not field_name: return HttpResponseBadRequest("Field name must be given") ...
AJAX GET handler for xeditable queries asking for field choice lists.
Below is the the instruction that describes the task: ### Input: AJAX GET handler for xeditable queries asking for field choice lists. ### Response: def get_ajax_xeditable_choices(self, request, *args, **kwargs): """ AJAX GET handler for xeditable queries asking for field choice lists. """ field_na...
def process_rr(data, record_type, record_keys, field, template): """ Meta method: Replace $field in template with the serialized $record_type records, using @record_key from each datum. """ if data is None: return template.replace(field, "") if type(record_keys) == list: pas...
Meta method: Replace $field in template with the serialized $record_type records, using @record_key from each datum.
Below is the the instruction that describes the task: ### Input: Meta method: Replace $field in template with the serialized $record_type records, using @record_key from each datum. ### Response: def process_rr(data, record_type, record_keys, field, template): """ Meta method: Replace $field in...
def get(query, *args, **kwargs): """Get action definitions to dump.""" run_sql = _get_run_sql() actions = [ dict(id=row[0], name=row[1], allowedkeywords=row[2], optional=row[3]) for action in query.split(',') for row in run_sql( 'select id,...
Get action definitions to dump.
Below is the the instruction that describes the task: ### Input: Get action definitions to dump. ### Response: def get(query, *args, **kwargs): """Get action definitions to dump.""" run_sql = _get_run_sql() actions = [ dict(id=row[0], name=row[1], allowedkeywords=row[...
def add_review(self, reviewer, product, review, date=None): """Add a new review from a given reviewer to a given product. Args: reviewer: an instance of Reviewer. product: an instance of Product. review: a float value. date: date the review issued. Retur...
Add a new review from a given reviewer to a given product. Args: reviewer: an instance of Reviewer. product: an instance of Product. review: a float value. date: date the review issued. Returns: the added new review object. Raises: T...
Below is the the instruction that describes the task: ### Input: Add a new review from a given reviewer to a given product. Args: reviewer: an instance of Reviewer. product: an instance of Product. review: a float value. date: date the review issued. Returns...
def salt_ssh(): ''' Execute the salt-ssh system ''' import salt.cli.ssh if '' in sys.path: sys.path.remove('') try: client = salt.cli.ssh.SaltSSH() _install_signal_handlers(client) client.run() except SaltClientError as err: trace = traceback.format_ex...
Execute the salt-ssh system
Below is the the instruction that describes the task: ### Input: Execute the salt-ssh system ### Response: def salt_ssh(): ''' Execute the salt-ssh system ''' import salt.cli.ssh if '' in sys.path: sys.path.remove('') try: client = salt.cli.ssh.SaltSSH() _install_sig...
def quick_response(self, status_code): """ Quickly construct response using a status code """ translator = Translator(environ=self.environ) if status_code == 404: self.status(404) self.message(translator.trans('http_messages.404')) elif status_code == 401: ...
Quickly construct response using a status code
Below is the the instruction that describes the task: ### Input: Quickly construct response using a status code ### Response: def quick_response(self, status_code): """ Quickly construct response using a status code """ translator = Translator(environ=self.environ) if status_code == 404:...
def get_current_user(self, objectmask=None): """Calls SoftLayer_Account::getCurrentUser""" if objectmask is None: objectmask = "mask[userStatus[name], parent[id, username]]" return self.account_service.getCurrentUser(mask=objectmask)
Calls SoftLayer_Account::getCurrentUser
Below is the the instruction that describes the task: ### Input: Calls SoftLayer_Account::getCurrentUser ### Response: def get_current_user(self, objectmask=None): """Calls SoftLayer_Account::getCurrentUser""" if objectmask is None: objectmask = "mask[userStatus[name], parent[id, usern...
def _get_key_redis_key(bank, key): ''' Return the Redis key given the bank name and the key name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}/{key}'.format( prefix=opts['key_prefix'], separator=opts['separator'], bank=bank, key=key )
Return the Redis key given the bank name and the key name.
Below is the the instruction that describes the task: ### Input: Return the Redis key given the bank name and the key name. ### Response: def _get_key_redis_key(bank, key): ''' Return the Redis key given the bank name and the key name. ''' opts = _get_redis_keys_opts() return '{prefix}{separato...
def upload(df, gfile="/New Spreadsheet", wks_name=None, col_names=True, row_names=True, clean=True, credentials=None, start_cell = 'A1', df_size = False, new_sheet_dimensions = (1000,100)): ''' Upload given Pandas DataFrame to Google Drive and returns gspread Worksheet object ...
Upload given Pandas DataFrame to Google Drive and returns gspread Worksheet object :param df: Pandas DataFrame :param gfile: path to Google Spreadsheet or gspread ID :param wks_name: worksheet name :param col_names: passing top row to column names for Pandas DataFrame :p...
Below is the the instruction that describes the task: ### Input: Upload given Pandas DataFrame to Google Drive and returns gspread Worksheet object :param df: Pandas DataFrame :param gfile: path to Google Spreadsheet or gspread ID :param wks_name: worksheet name :param col_n...
def is_leaf(obj): ''' the below is for nested-dict any type is not dict will be treated as a leaf empty dict will be treated as a leaf from edict.edict import * is_leaf(1) is_leaf({1:2}) is_leaf({}) ''' if(is_dict(obj)): length = obj.__len__() ...
the below is for nested-dict any type is not dict will be treated as a leaf empty dict will be treated as a leaf from edict.edict import * is_leaf(1) is_leaf({1:2}) is_leaf({})
Below is the the instruction that describes the task: ### Input: the below is for nested-dict any type is not dict will be treated as a leaf empty dict will be treated as a leaf from edict.edict import * is_leaf(1) is_leaf({1:2}) is_leaf({}) ### Response: def is_leaf...
def from_array(array): """ Deserialize a new EncryptedPassportElement from a given dictionary. :return: new EncryptedPassportElement instance. :rtype: EncryptedPassportElement """ if array is None or not array: return None # end if assert_type...
Deserialize a new EncryptedPassportElement from a given dictionary. :return: new EncryptedPassportElement instance. :rtype: EncryptedPassportElement
Below is the the instruction that describes the task: ### Input: Deserialize a new EncryptedPassportElement from a given dictionary. :return: new EncryptedPassportElement instance. :rtype: EncryptedPassportElement ### Response: def from_array(array): """ Deserialize a new Encrypted...
def http_error_307(self, url, fp, errcode, errmsg, headers, data=None): """Error 307 -- relocated, but turn POST into error.""" if data is None: return self.http_error_302(url, fp, errcode, errmsg, headers, data) else: return self.http_error_default(url, fp, errcode, errm...
Error 307 -- relocated, but turn POST into error.
Below is the the instruction that describes the task: ### Input: Error 307 -- relocated, but turn POST into error. ### Response: def http_error_307(self, url, fp, errcode, errmsg, headers, data=None): """Error 307 -- relocated, but turn POST into error.""" if data is None: return self.h...
def get_key_section_header(self, key, spaces): """Get the key of the header section :param key: the key name :param spaces: spaces to set at the beginning of the header """ header = super(NumpydocTools, self).get_key_section_header(key, spaces) header = spaces + header ...
Get the key of the header section :param key: the key name :param spaces: spaces to set at the beginning of the header
Below is the the instruction that describes the task: ### Input: Get the key of the header section :param key: the key name :param spaces: spaces to set at the beginning of the header ### Response: def get_key_section_header(self, key, spaces): """Get the key of the header section ...
def compare(cls, match, subject): """ Accepts two OrganizationName objects and returns an arbitrary, numerical score based upon how well the names match. """ if match.expand().lower() == subject.expand().lower(): return 4 elif match.kernel().lower() ==...
Accepts two OrganizationName objects and returns an arbitrary, numerical score based upon how well the names match.
Below is the the instruction that describes the task: ### Input: Accepts two OrganizationName objects and returns an arbitrary, numerical score based upon how well the names match. ### Response: def compare(cls, match, subject): """ Accepts two OrganizationName objects and returns a...
def get_field_min_max(self, name, **query_dict): """Returns the minimum and maximum values of the specified field. This requires two search calls to the service, each requesting a single value of a single field. @param name(string) Name of the field @param q(string) Query identi...
Returns the minimum and maximum values of the specified field. This requires two search calls to the service, each requesting a single value of a single field. @param name(string) Name of the field @param q(string) Query identifying range of records for min and max values @param...
Below is the the instruction that describes the task: ### Input: Returns the minimum and maximum values of the specified field. This requires two search calls to the service, each requesting a single value of a single field. @param name(string) Name of the field @param q(string) Que...
def transform_region(self, from_, to, transform_callback): """ Transform a part of the input string. :param from_: (int) start position. :param to: (int) end position. :param transform_callback: Callable which accepts a string and returns the transformed string. ...
Transform a part of the input string. :param from_: (int) start position. :param to: (int) end position. :param transform_callback: Callable which accepts a string and returns the transformed string.
Below is the the instruction that describes the task: ### Input: Transform a part of the input string. :param from_: (int) start position. :param to: (int) end position. :param transform_callback: Callable which accepts a string and returns the transformed string. ### Response: ...
def _check_status(self, ibsta): """Checks ibsta value.""" if ibsta & 0x4000: raise LinuxGpib.Timeout() elif ibsta & 0x8000: raise LinuxGpib.Error(self.error_status)
Checks ibsta value.
Below is the the instruction that describes the task: ### Input: Checks ibsta value. ### Response: def _check_status(self, ibsta): """Checks ibsta value.""" if ibsta & 0x4000: raise LinuxGpib.Timeout() elif ibsta & 0x8000: raise LinuxGpib.Error(self.error_status)
def dataframe(df, **kwargs): """Print table with data from the given pandas DataFrame Parameters ---------- df : DataFrame A pandas DataFrame with the table to print """ table(df.values, list(df.columns), **kwargs)
Print table with data from the given pandas DataFrame Parameters ---------- df : DataFrame A pandas DataFrame with the table to print
Below is the the instruction that describes the task: ### Input: Print table with data from the given pandas DataFrame Parameters ---------- df : DataFrame A pandas DataFrame with the table to print ### Response: def dataframe(df, **kwargs): """Print table with data from the given pandas D...
def set_options(self, options): """Sets the given options as instance attributes (only if they are known). :parameters: options : Dict All known instance attributes and more if the childclass has defined them before this call. :rtype: None ...
Sets the given options as instance attributes (only if they are known). :parameters: options : Dict All known instance attributes and more if the childclass has defined them before this call. :rtype: None
Below is the the instruction that describes the task: ### Input: Sets the given options as instance attributes (only if they are known). :parameters: options : Dict All known instance attributes and more if the childclass has defined them before this call...
def get_available_label_stores(self, usefield='tryall'): """ Get the label store values that may be used for writing this annotation. Available store values include: - the undefined values in the standard wfdb labels - the store values not used in the current a...
Get the label store values that may be used for writing this annotation. Available store values include: - the undefined values in the standard wfdb labels - the store values not used in the current annotation object. - the store values whose standard wfdb symbols/desc...
Below is the the instruction that describes the task: ### Input: Get the label store values that may be used for writing this annotation. Available store values include: - the undefined values in the standard wfdb labels - the store values not used in the current annotatio...
def get_local_time(index): """Localize datetime for better output in graphs :param pandas.DateTimeIndex index: pandas datetime index :return: aware time objet :rtype: datetime.time """ dt = index.to_pydatetime() dt = dt.replace(tzinfo=pytz.utc) return dt.astimezone(tzlocal()).time()
Localize datetime for better output in graphs :param pandas.DateTimeIndex index: pandas datetime index :return: aware time objet :rtype: datetime.time
Below is the the instruction that describes the task: ### Input: Localize datetime for better output in graphs :param pandas.DateTimeIndex index: pandas datetime index :return: aware time objet :rtype: datetime.time ### Response: def get_local_time(index): """Localize datetime for better output in...
def black(cls): "Make the text foreground color black." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.FOREGROUND_MASK #wAttributes |= win32.FOREGROUND_BLACK cls._set_text_attributes(wAttributes)
Make the text foreground color black.
Below is the the instruction that describes the task: ### Input: Make the text foreground color black. ### Response: def black(cls): "Make the text foreground color black." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.FOREGROUND_MASK #wAttributes |= win32.FOREGROU...
def modelsGetResultAndStatus(self, modelIDs): """ Get the results string and other status fields for a set of models. WARNING!!!: The order of the results are NOT necessarily in the same order as the order of the model IDs passed in!!! For each model, this returns a tuple containing: (modelID, re...
Get the results string and other status fields for a set of models. WARNING!!!: The order of the results are NOT necessarily in the same order as the order of the model IDs passed in!!! For each model, this returns a tuple containing: (modelID, results, status, updateCounter, numRecords, completionRe...
Below is the the instruction that describes the task: ### Input: Get the results string and other status fields for a set of models. WARNING!!!: The order of the results are NOT necessarily in the same order as the order of the model IDs passed in!!! For each model, this returns a tuple containing: ...
def duration(self): """Duration of this series in seconds :type: `~astropy.units.Quantity` scalar """ return units.Quantity(self.span[1] - self.span[0], self.xunit, dtype=float)
Duration of this series in seconds :type: `~astropy.units.Quantity` scalar
Below is the the instruction that describes the task: ### Input: Duration of this series in seconds :type: `~astropy.units.Quantity` scalar ### Response: def duration(self): """Duration of this series in seconds :type: `~astropy.units.Quantity` scalar """ return units.Quan...
def splitext_files_only(filepath): "Custom version of splitext that doesn't perform splitext on directories" return ( (filepath, '') if os.path.isdir(filepath) else os.path.splitext(filepath) )
Custom version of splitext that doesn't perform splitext on directories
Below is the the instruction that describes the task: ### Input: Custom version of splitext that doesn't perform splitext on directories ### Response: def splitext_files_only(filepath): "Custom version of splitext that doesn't perform splitext on directories" return ( (filepath, '') if os.path.isdir(filepat...
def read_bonedata(self, fid): """Read bone data from an acclaim skeleton file stream.""" bone_count = 0 lin = self.read_line(fid) while lin[0]!=':': parts = lin.split() if parts[0] == 'begin': bone_count += 1 self.vertices.append(v...
Read bone data from an acclaim skeleton file stream.
Below is the the instruction that describes the task: ### Input: Read bone data from an acclaim skeleton file stream. ### Response: def read_bonedata(self, fid): """Read bone data from an acclaim skeleton file stream.""" bone_count = 0 lin = self.read_line(fid) while lin[0]!=':': ...
def vol_per_rev_LS(id_number): """Look up the volume per revolution output by a Masterflex L/S pump through L/S tubing of the given ID number. :param id_number: Identification number of the L/S tubing. Valid numbers are 13-18, 24, 35, and 36. :type id_number: int :return: Volume per revolution out...
Look up the volume per revolution output by a Masterflex L/S pump through L/S tubing of the given ID number. :param id_number: Identification number of the L/S tubing. Valid numbers are 13-18, 24, 35, and 36. :type id_number: int :return: Volume per revolution output by a Masterflex L/S pump through t...
Below is the the instruction that describes the task: ### Input: Look up the volume per revolution output by a Masterflex L/S pump through L/S tubing of the given ID number. :param id_number: Identification number of the L/S tubing. Valid numbers are 13-18, 24, 35, and 36. :type id_number: int :re...
def route( self, uri, methods=frozenset({"GET"}), host=None, strict_slashes=None, stream=False, version=None, name=None, ): """Create a blueprint route from a decorated function. :param uri: endpoint at which the route will be accessib...
Create a blueprint route from a decorated function. :param uri: endpoint at which the route will be accessible. :param methods: list of acceptable HTTP methods. :param host: IP Address of FQDN for the sanic server to use. :param strict_slashes: Enforce the API urls are requested with a ...
Below is the the instruction that describes the task: ### Input: Create a blueprint route from a decorated function. :param uri: endpoint at which the route will be accessible. :param methods: list of acceptable HTTP methods. :param host: IP Address of FQDN for the sanic server to use. ...
def isIn(val, schema, name = None): # pylint: disable-msg=W0613 """ !~~isIn(data) """ if name is None: name = schema if not _lists.has_key(name): return False try: return val in _lists[name] except TypeError: return False
!~~isIn(data)
Below is the the instruction that describes the task: ### Input: !~~isIn(data) ### Response: def isIn(val, schema, name = None): # pylint: disable-msg=W0613 """ !~~isIn(data) """ if name is None: name = schema if not _lists.has_key(name): return False try: return v...
def assertStructIsInline(self, obj): """ Structs are always stored inline, so need to be created right where they are used. You'll get this error if you created it elsewhere. """ N.enforce_number(obj, N.UOffsetTFlags) if obj != self.Offset(): msg = ("...
Structs are always stored inline, so need to be created right where they are used. You'll get this error if you created it elsewhere.
Below is the the instruction that describes the task: ### Input: Structs are always stored inline, so need to be created right where they are used. You'll get this error if you created it elsewhere. ### Response: def assertStructIsInline(self, obj): """ Structs are always stored inl...
def fixed_point_quantized_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, w_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True, ...
Fixed-Point Quantized Convolution. Fixed-Point Quantized Convolution is the convolution function, except the definition of the inner product is modified. The input-output relation of this function is as follows: .. math:: y_{n, a, b} = \sum_{m} \sum_{i} \sum_{j} Q(w_{n, m, i, j}) x_{m, a + i,...
Below is the the instruction that describes the task: ### Input: Fixed-Point Quantized Convolution. Fixed-Point Quantized Convolution is the convolution function, except the definition of the inner product is modified. The input-output relation of this function is as follows: .. math:: y_...
def get_nts(self): """Read csv/tsv file and return specified data in a list of lists.""" data = [] nt_obj = None with open(self.fin) as fin_stream: for lnum, line in enumerate(fin_stream, 1): try: line = line.rstrip('\r\n') # chomp ...
Read csv/tsv file and return specified data in a list of lists.
Below is the the instruction that describes the task: ### Input: Read csv/tsv file and return specified data in a list of lists. ### Response: def get_nts(self): """Read csv/tsv file and return specified data in a list of lists.""" data = [] nt_obj = None with open(self.fin) as fin_...
def p_expression_binop(t): '''expression : expression PLUS expression | expression MINUS expression | expression TIMES expression | expression DIVIDE expression''' if t[2] == '+' : t[0] = t[1] + t[3] elif t[2] == '-': t[0] = t[1] - t[3] elif t[2] ==...
expression : expression PLUS expression | expression MINUS expression | expression TIMES expression | expression DIVIDE expression
Below is the the instruction that describes the task: ### Input: expression : expression PLUS expression | expression MINUS expression | expression TIMES expression | expression DIVIDE expression ### Response: def p_expression_binop(t): '''expression : expr...
async def create(self, query, *, dc=None): """Creates a new prepared query Parameters: Query (Object): Query definition dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. Returns: Object: New query ...
Creates a new prepared query Parameters: Query (Object): Query definition dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. Returns: Object: New query ID The create operation expects a body that d...
Below is the the instruction that describes the task: ### Input: Creates a new prepared query Parameters: Query (Object): Query definition dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. Returns: Obj...
def main(sample_id, assembly_file, coverage_file, coverage_bp_file, bam_file, opts, gsize): """Main executor of the process_assembly_mapping template. Parameters ---------- sample_id : str Sample Identification string. assembly_file : str Path to assembly file in Fasta form...
Main executor of the process_assembly_mapping template. Parameters ---------- sample_id : str Sample Identification string. assembly_file : str Path to assembly file in Fasta format. coverage_file : str Path to TSV file with coverage information for each contig. coverage...
Below is the the instruction that describes the task: ### Input: Main executor of the process_assembly_mapping template. Parameters ---------- sample_id : str Sample Identification string. assembly_file : str Path to assembly file in Fasta format. coverage_file : str Pat...
def valuecounter(table, *field, **kwargs): """ Find distinct values for the given field and count the number of occurrences. Returns a :class:`dict` mapping values to counts. E.g.:: >>> import petl as etl >>> table = [['foo', 'bar'], ... ['a', True], ... ['...
Find distinct values for the given field and count the number of occurrences. Returns a :class:`dict` mapping values to counts. E.g.:: >>> import petl as etl >>> table = [['foo', 'bar'], ... ['a', True], ... ['b'], ... ['b', True], ... ...
Below is the the instruction that describes the task: ### Input: Find distinct values for the given field and count the number of occurrences. Returns a :class:`dict` mapping values to counts. E.g.:: >>> import petl as etl >>> table = [['foo', 'bar'], ... ['a', True], ....
def write_wonambi(data, filename, subj_id='', dtype='float64'): """Write file in simple Wonambi format. Parameters ---------- data : instance of ChanTime data with only one trial filename : path to file file to export to (the extensions .won and .dat will be added) subj_id : str...
Write file in simple Wonambi format. Parameters ---------- data : instance of ChanTime data with only one trial filename : path to file file to export to (the extensions .won and .dat will be added) subj_id : str subject id dtype : str numpy dtype in which you wa...
Below is the the instruction that describes the task: ### Input: Write file in simple Wonambi format. Parameters ---------- data : instance of ChanTime data with only one trial filename : path to file file to export to (the extensions .won and .dat will be added) subj_id : str ...
def steps(current, target, max_steps): """ Steps between two values. :param current: Current value (0.0-1.0). :param target: Target value (0.0-1.0). :param max_steps: Maximum number of steps. """ if current < 0 or current > 1.0: raise ValueError("current value %s is out of bounds (0.0-1...
Steps between two values. :param current: Current value (0.0-1.0). :param target: Target value (0.0-1.0). :param max_steps: Maximum number of steps.
Below is the the instruction that describes the task: ### Input: Steps between two values. :param current: Current value (0.0-1.0). :param target: Target value (0.0-1.0). :param max_steps: Maximum number of steps. ### Response: def steps(current, target, max_steps): """ Steps between two values. ...
def _validate_compute_chunk_params( self, dates, symbols, initial_workspace): """ Verify that the values passed to compute_chunk are well-formed. """ root = self._root_mask_term clsname = type(self).__name__ # Writing this out explicitly so this errors in tes...
Verify that the values passed to compute_chunk are well-formed.
Below is the the instruction that describes the task: ### Input: Verify that the values passed to compute_chunk are well-formed. ### Response: def _validate_compute_chunk_params( self, dates, symbols, initial_workspace): """ Verify that the values passed to compute_chunk are well-formed...
def convert_conf_for_unreachable(params): """ The 'u' state for UNREACHABLE has been rewritten in 'x' in: * flap_detection_options * notification_options * snapshot_criteria So convert value from config file to keep compatibility with Nagios :param params: param...
The 'u' state for UNREACHABLE has been rewritten in 'x' in: * flap_detection_options * notification_options * snapshot_criteria So convert value from config file to keep compatibility with Nagios :param params: parameters of the host before put in properties :type param...
Below is the the instruction that describes the task: ### Input: The 'u' state for UNREACHABLE has been rewritten in 'x' in: * flap_detection_options * notification_options * snapshot_criteria So convert value from config file to keep compatibility with Nagios :param params...
def create_stoichiometric_matrix(model, array_type='dense', dtype=None): """Return a stoichiometric array representation of the given model. The the columns represent the reactions and rows represent metabolites. S[i,j] therefore contains the quantity of metabolite `i` produced (negative for consumed) ...
Return a stoichiometric array representation of the given model. The the columns represent the reactions and rows represent metabolites. S[i,j] therefore contains the quantity of metabolite `i` produced (negative for consumed) by reaction `j`. Parameters ---------- model : cobra.Model ...
Below is the the instruction that describes the task: ### Input: Return a stoichiometric array representation of the given model. The the columns represent the reactions and rows represent metabolites. S[i,j] therefore contains the quantity of metabolite `i` produced (negative for consumed) by reaction...
def grant_permission_to_users(self, permission, **kwargs): # noqa: E501 """Grants a specific user permission to multiple users # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True ...
Grants a specific user permission to multiple users # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.grant_permission_to_users(permission, async_req=True) >>> r...
Below is the the instruction that describes the task: ### Input: Grants a specific user permission to multiple users # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = ap...
def create_template(self, s, provider_name=None): """Creates a template from the given string based on the specified provider or the provider with highest precedence. Args: s: The string to convert to a template. provider_name: The name of the provider to use to create t...
Creates a template from the given string based on the specified provider or the provider with highest precedence. Args: s: The string to convert to a template. provider_name: The name of the provider to use to create the template.
Below is the the instruction that describes the task: ### Input: Creates a template from the given string based on the specified provider or the provider with highest precedence. Args: s: The string to convert to a template. provider_name: The name of the provider to use to ...
def _checkMode(self, ax_args): """Raise an exception if the mode in the attribute exchange arguments does not match what is expected for this class. @raises NotAXMessage: When there is no mode value in ax_args at all. @raises AXError: When mode does not match. """ mode ...
Raise an exception if the mode in the attribute exchange arguments does not match what is expected for this class. @raises NotAXMessage: When there is no mode value in ax_args at all. @raises AXError: When mode does not match.
Below is the the instruction that describes the task: ### Input: Raise an exception if the mode in the attribute exchange arguments does not match what is expected for this class. @raises NotAXMessage: When there is no mode value in ax_args at all. @raises AXError: When mode does not match...
def check(self, feature): """Check that fit can be called on reference data""" mapper = feature.as_dataframe_mapper() mapper.fit(self.X, y=self.y)
Check that fit can be called on reference data
Below is the the instruction that describes the task: ### Input: Check that fit can be called on reference data ### Response: def check(self, feature): """Check that fit can be called on reference data""" mapper = feature.as_dataframe_mapper() mapper.fit(self.X, y=self.y)
def get_circulations(elements: T) -> Iterable[T]: """Iterate over all possible circulations of an ordered collection (tuple or list). Example: >>> list(get_circulations([1, 2, 3])) [[1, 2, 3], [2, 3, 1], [3, 1, 2]] """ for i in range(len(elements)): yield elements[i:] + elements[:i]
Iterate over all possible circulations of an ordered collection (tuple or list). Example: >>> list(get_circulations([1, 2, 3])) [[1, 2, 3], [2, 3, 1], [3, 1, 2]]
Below is the the instruction that describes the task: ### Input: Iterate over all possible circulations of an ordered collection (tuple or list). Example: >>> list(get_circulations([1, 2, 3])) [[1, 2, 3], [2, 3, 1], [3, 1, 2]] ### Response: def get_circulations(elements: T) -> Iterable[T]: """Ite...
async def _pb_request(self, endpoint, request_pb, response_pb): """Send a Protocol Buffer formatted chat API request. Args: endpoint (str): The chat API endpoint to use. request_pb: The request body as a Protocol Buffer message. response_pb: The response body as a Pr...
Send a Protocol Buffer formatted chat API request. Args: endpoint (str): The chat API endpoint to use. request_pb: The request body as a Protocol Buffer message. response_pb: The response body as a Protocol Buffer message. Raises: NetworkError: If the re...
Below is the the instruction that describes the task: ### Input: Send a Protocol Buffer formatted chat API request. Args: endpoint (str): The chat API endpoint to use. request_pb: The request body as a Protocol Buffer message. response_pb: The response body as a Protocol...
def dynamic_content_item_show(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/dynamic_content#show-item" api_path = "/api/v2/dynamic_content/items/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/dynamic_content#show-item
Below is the the instruction that describes the task: ### Input: https://developer.zendesk.com/rest_api/docs/core/dynamic_content#show-item ### Response: def dynamic_content_item_show(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/dynamic_content#show-item" api_path = "/api/...
def update_module_types(): """ Download the repositories for all of the firmware_module_type records and update them using the `module.json` files from the repositories themselves. Currently only works for git repositories. """ local_url = config["local_server"]["url"] server = Server(local_...
Download the repositories for all of the firmware_module_type records and update them using the `module.json` files from the repositories themselves. Currently only works for git repositories.
Below is the the instruction that describes the task: ### Input: Download the repositories for all of the firmware_module_type records and update them using the `module.json` files from the repositories themselves. Currently only works for git repositories. ### Response: def update_module_types(): """ ...
def update_from_dict(self, d): """ Apply options from a serialized body to the current instance. Modifies the object in-place. Used mostly by ``from_dict``. """ d = d.copy() if 'query' in d: self.query._proxied = Q(d.pop('query')) if 'script' in d: ...
Apply options from a serialized body to the current instance. Modifies the object in-place. Used mostly by ``from_dict``.
Below is the the instruction that describes the task: ### Input: Apply options from a serialized body to the current instance. Modifies the object in-place. Used mostly by ``from_dict``. ### Response: def update_from_dict(self, d): """ Apply options from a serialized body to the current ins...
def insert(self, cache_key, paths, overwrite=False): """Cache the output of a build. By default, checks cache.has(key) first, only proceeding to create and insert an artifact if it is not already in the cache (though `overwrite` can be used to skip the check and unconditionally insert). :param Cac...
Cache the output of a build. By default, checks cache.has(key) first, only proceeding to create and insert an artifact if it is not already in the cache (though `overwrite` can be used to skip the check and unconditionally insert). :param CacheKey cache_key: A CacheKey object. :param list<str> pat...
Below is the the instruction that describes the task: ### Input: Cache the output of a build. By default, checks cache.has(key) first, only proceeding to create and insert an artifact if it is not already in the cache (though `overwrite` can be used to skip the check and unconditionally insert). :...
def resolve_url(self, resource_name): """Return a URL to a local copy of a resource, suitable for get_generator()""" if self.target_format == 'csv' and self.target_file != DEFAULT_METATAB_FILE: # For CSV packages, need to get the package and open it to get the resoruce URL, becuase ...
Return a URL to a local copy of a resource, suitable for get_generator()
Below is the the instruction that describes the task: ### Input: Return a URL to a local copy of a resource, suitable for get_generator() ### Response: def resolve_url(self, resource_name): """Return a URL to a local copy of a resource, suitable for get_generator()""" if self.target_format == 'csv...
def from_rfc3339(cls, stamp): """Parse RFC 3339-compliant timestamp, preserving nanoseconds. Args: stamp (str): RFC 3339 stamp, with up to nanosecond precision Returns: :class:`DatetimeWithNanoseconds`: an instance matching the timestamp string ...
Parse RFC 3339-compliant timestamp, preserving nanoseconds. Args: stamp (str): RFC 3339 stamp, with up to nanosecond precision Returns: :class:`DatetimeWithNanoseconds`: an instance matching the timestamp string Raises: ValueError: if `stamp...
Below is the the instruction that describes the task: ### Input: Parse RFC 3339-compliant timestamp, preserving nanoseconds. Args: stamp (str): RFC 3339 stamp, with up to nanosecond precision Returns: :class:`DatetimeWithNanoseconds`: an instance matching th...