code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _get_label(self, axis): """Return plot label for column for the given axis.""" if axis == 'x': colname = self.x_col else: # y colname = self.y_col if colname == self._idxname: label = 'Index' else: col = self.tab[colname] ...
Return plot label for column for the given axis.
Below is the the instruction that describes the task: ### Input: Return plot label for column for the given axis. ### Response: def _get_label(self, axis): """Return plot label for column for the given axis.""" if axis == 'x': colname = self.x_col else: # y colname...
def pick_and_display_buffer(self, i): """ pick i-th buffer from list and display it :param i: int :return: None """ if len(self.buffers) == 1: # we don't need to display anything # listing is already displayed return else: ...
pick i-th buffer from list and display it :param i: int :return: None
Below is the the instruction that describes the task: ### Input: pick i-th buffer from list and display it :param i: int :return: None ### Response: def pick_and_display_buffer(self, i): """ pick i-th buffer from list and display it :param i: int :return: None ...
def varimp_plot(self, num_of_features=None, server=False): """ Plot the variable importance for a trained model. :param num_of_features: the number of features shown in the plot (default is 10 or all if less than 10). :param server: ? :returns: None. """ assert_...
Plot the variable importance for a trained model. :param num_of_features: the number of features shown in the plot (default is 10 or all if less than 10). :param server: ? :returns: None.
Below is the the instruction that describes the task: ### Input: Plot the variable importance for a trained model. :param num_of_features: the number of features shown in the plot (default is 10 or all if less than 10). :param server: ? :returns: None. ### Response: def varimp_plot(self, ...
def find_birthdays(request): """Return information on user birthdays.""" today = date.today() custom = False yr_inc = 0 if "birthday_month" in request.GET and "birthday_day" in request.GET: try: mon = int(request.GET["birthday_month"]) day = int(request.GET["birthday_...
Return information on user birthdays.
Below is the the instruction that describes the task: ### Input: Return information on user birthdays. ### Response: def find_birthdays(request): """Return information on user birthdays.""" today = date.today() custom = False yr_inc = 0 if "birthday_month" in request.GET and "birthday_day" in r...
def to_pinyin(s, delimiter=' ', all_readings=False, container='[]', accented=True): """Convert a string's Chinese characters to Pinyin readings. *s* is a string containing Chinese characters. *accented* is a boolean value indicating whether to return accented or numbered Pinyin readings. ...
Convert a string's Chinese characters to Pinyin readings. *s* is a string containing Chinese characters. *accented* is a boolean value indicating whether to return accented or numbered Pinyin readings. *delimiter* is the character used to indicate word boundaries in *s*. This is used to differenti...
Below is the the instruction that describes the task: ### Input: Convert a string's Chinese characters to Pinyin readings. *s* is a string containing Chinese characters. *accented* is a boolean value indicating whether to return accented or numbered Pinyin readings. *delimiter* is the character us...
def get_alert(self, id, **kwargs): # noqa: E501 """Get a specific alert # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert(id, async_req=True) ...
Get a specific alert # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert(id, async_req=True) >>> result = thread.get() :param async_req bool ...
Below is the the instruction that describes the task: ### Input: Get a specific alert # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert(id, async_req=True)...
def reinforce_grid(self): """ Performs grid reinforcement measures for all MV and LV grids Args: Returns: """ # TODO: Finish method and enable LV case for grid_district in self.mv_grid_districts(): # reinforce MV grid grid_district.mv_grid.rein...
Performs grid reinforcement measures for all MV and LV grids Args: Returns:
Below is the the instruction that describes the task: ### Input: Performs grid reinforcement measures for all MV and LV grids Args: Returns: ### Response: def reinforce_grid(self): """ Performs grid reinforcement measures for all MV and LV grids Args: Returns: """...
def run(self, params=None, return_columns=None, return_timestamps=None, initial_condition='original', reload=False): """ Simulate the model's behavior over time. Return a pandas dataframe with timestamps as rows, model elements as columns. Parameters ---------- ...
Simulate the model's behavior over time. Return a pandas dataframe with timestamps as rows, model elements as columns. Parameters ---------- params : dictionary Keys are strings of model component names. Values are numeric or pandas Series. Nu...
Below is the the instruction that describes the task: ### Input: Simulate the model's behavior over time. Return a pandas dataframe with timestamps as rows, model elements as columns. Parameters ---------- params : dictionary Keys are strings of model component n...
def fetch_followers(account_file, outfile, limit, do_loop): """ Fetch up to limit followers for each Twitter account in account_file. Write results to outfile file in format: screen_name user_id follower_id_1 follower_id_2 ...""" print('Fetching followers for accounts in %s' % account_file) niters ...
Fetch up to limit followers for each Twitter account in account_file. Write results to outfile file in format: screen_name user_id follower_id_1 follower_id_2 ...
Below is the the instruction that describes the task: ### Input: Fetch up to limit followers for each Twitter account in account_file. Write results to outfile file in format: screen_name user_id follower_id_1 follower_id_2 ... ### Response: def fetch_followers(account_file, outfile, limit, do_loop): ...
def flatten_args(shapes): r""" Decorator to flatten structured arguments to a function. Examples -------- >>> @flatten_args([(5,), ()]) ... def f(w, lambda_): ... return .5 * lambda_ * w.T.dot(w) >>> np.isclose(f(np.array([2., .5, .6, -.2, .9, .2])), .546) True >>> w = np.ar...
r""" Decorator to flatten structured arguments to a function. Examples -------- >>> @flatten_args([(5,), ()]) ... def f(w, lambda_): ... return .5 * lambda_ * w.T.dot(w) >>> np.isclose(f(np.array([2., .5, .6, -.2, .9, .2])), .546) True >>> w = np.array([2., .5, .6, -.2, .9]) ...
Below is the the instruction that describes the task: ### Input: r""" Decorator to flatten structured arguments to a function. Examples -------- >>> @flatten_args([(5,), ()]) ... def f(w, lambda_): ... return .5 * lambda_ * w.T.dot(w) >>> np.isclose(f(np.array([2., .5, .6, -.2, .9, ...
def events_for_unlock_lock( initiator_state: InitiatorTransferState, channel_state: NettingChannelState, secret: Secret, secrethash: SecretHash, pseudo_random_generator: random.Random, ) -> List[Event]: """ Unlocks the lock offchain, and emits the events for the successful pa...
Unlocks the lock offchain, and emits the events for the successful payment.
Below is the the instruction that describes the task: ### Input: Unlocks the lock offchain, and emits the events for the successful payment. ### Response: def events_for_unlock_lock( initiator_state: InitiatorTransferState, channel_state: NettingChannelState, secret: Secret, secreth...
def make_data(): """creates example data set""" I,d = multidict({1:80, 2:270, 3:250, 4:160, 5:180}) # demand J,M,f = multidict({1:[500,1000], 2:[500,1000], 3:[500,1000]}) # capacity, fixed costs c = {(1,1):4, (1,2):6, (1,3):9, # transportation costs (2,1):5, (2,2):4, (2,3):7, ...
creates example data set
Below is the the instruction that describes the task: ### Input: creates example data set ### Response: def make_data(): """creates example data set""" I,d = multidict({1:80, 2:270, 3:250, 4:160, 5:180}) # demand J,M,f = multidict({1:[500,1000], 2:[500,1000], 3:[500,1000]}) # capacity, fixed...
def is_in(self, *items): """Asserts that val is equal to one of the given items.""" if len(items) == 0: raise ValueError('one or more args must be given') else: for i in items: if self.val == i: return self self._err('Expected <...
Asserts that val is equal to one of the given items.
Below is the the instruction that describes the task: ### Input: Asserts that val is equal to one of the given items. ### Response: def is_in(self, *items): """Asserts that val is equal to one of the given items.""" if len(items) == 0: raise ValueError('one or more args must be given') ...
def en_last(self): """ Report the energies from the last SCF present in the output. Returns a |dict| providing the various energy values from the last SCF cycle performed in the output. Keys are those of :attr:`~opan.output.OrcaOutput.p_en`. Any energy value not relevant to the ...
Report the energies from the last SCF present in the output. Returns a |dict| providing the various energy values from the last SCF cycle performed in the output. Keys are those of :attr:`~opan.output.OrcaOutput.p_en`. Any energy value not relevant to the parsed output is assign...
Below is the the instruction that describes the task: ### Input: Report the energies from the last SCF present in the output. Returns a |dict| providing the various energy values from the last SCF cycle performed in the output. Keys are those of :attr:`~opan.output.OrcaOutput.p_en`. ...
def add_padding(self, name, left = 0, right = 0, top = 0, bottom = 0, value = 0, input_name = 'data', output_name = 'out', padding_type = 'constant'): """ Add a padding layer to the model. Kindly refer to NeuralNetwork.proto for details. Parameter...
Add a padding layer to the model. Kindly refer to NeuralNetwork.proto for details. Parameters ---------- name: str The name of this layer. left: int Number of elements to be padded on the left side of the input blob. right: int Number of eleme...
Below is the the instruction that describes the task: ### Input: Add a padding layer to the model. Kindly refer to NeuralNetwork.proto for details. Parameters ---------- name: str The name of this layer. left: int Number of elements to be padded on the left s...
def get_family_form(self, *args, **kwargs): """Pass through to provider FamilyAdminSession.get_family_form_for_update""" # Implemented from kitosid template for - # osid.resource.BinAdminSession.get_bin_form_for_update_template # This method might be a bit sketchy. Time will tell. ...
Pass through to provider FamilyAdminSession.get_family_form_for_update
Below is the the instruction that describes the task: ### Input: Pass through to provider FamilyAdminSession.get_family_form_for_update ### Response: def get_family_form(self, *args, **kwargs): """Pass through to provider FamilyAdminSession.get_family_form_for_update""" # Implemented from kitosid t...
def index(): """Show a list of available libraries, and resource files""" kwdb = current_app.kwdb libraries = get_collections(kwdb, libtype="library") resource_files = get_collections(kwdb, libtype="resource") return flask.render_template("libraryNames.html", data=...
Show a list of available libraries, and resource files
Below is the the instruction that describes the task: ### Input: Show a list of available libraries, and resource files ### Response: def index(): """Show a list of available libraries, and resource files""" kwdb = current_app.kwdb libraries = get_collections(kwdb, libtype="library") resource_file...
def _is_field_serializable(self, field_name): """Return True if the field can be serialized into a JSON doc.""" return ( self._meta.get_field(field_name).get_internal_type() in self.SIMPLE_UPDATE_FIELD_TYPES )
Return True if the field can be serialized into a JSON doc.
Below is the the instruction that describes the task: ### Input: Return True if the field can be serialized into a JSON doc. ### Response: def _is_field_serializable(self, field_name): """Return True if the field can be serialized into a JSON doc.""" return ( self._meta.get_field(field_...
def is_all_field_none(self): """ :rtype: bool """ if self._uuid is not None: return False if self._created is not None: return False if self._updated is not None: return False if self._merchant_reference is not None: ...
:rtype: bool
Below is the the instruction that describes the task: ### Input: :rtype: bool ### Response: def is_all_field_none(self): """ :rtype: bool """ if self._uuid is not None: return False if self._created is not None: return False if self._update...
def output(self, _filename): """ _filename is not used Args: _filename(string) """ txt = "" for contract in self.contracts: print('Contract {}'.format(contract.name)) for function in contract.functions: if f...
_filename is not used Args: _filename(string)
Below is the the instruction that describes the task: ### Input: _filename is not used Args: _filename(string) ### Response: def output(self, _filename): """ _filename is not used Args: _filename(string) """ txt = "" ...
def close_all(self): """ Closes all editors """ if self._try_close_dirty_tabs(): while self.count(): widget = self.widget(0) self.remove_tab(0) self.tab_closed.emit(widget) return True return False
Closes all editors
Below is the the instruction that describes the task: ### Input: Closes all editors ### Response: def close_all(self): """ Closes all editors """ if self._try_close_dirty_tabs(): while self.count(): widget = self.widget(0) self.remove_tab(...
def match(select, tag, namespaces=None, flags=0, **kwargs): """Match node.""" return compile(select, namespaces, flags, **kwargs).match(tag)
Match node.
Below is the the instruction that describes the task: ### Input: Match node. ### Response: def match(select, tag, namespaces=None, flags=0, **kwargs): """Match node.""" return compile(select, namespaces, flags, **kwargs).match(tag)
def do_cli(ctx, template, semantic_version): """Publish the application based on command line inputs.""" try: template_data = get_template_data(template) except ValueError as ex: click.secho("Publish Failed", fg='red') raise UserException(str(ex)) # Override SemanticVersion in t...
Publish the application based on command line inputs.
Below is the the instruction that describes the task: ### Input: Publish the application based on command line inputs. ### Response: def do_cli(ctx, template, semantic_version): """Publish the application based on command line inputs.""" try: template_data = get_template_data(template) except V...
def toggle_reciprocal(self): """Flip my ``reciprocal_portal`` boolean, and draw (or stop drawing) an extra arrow on the appropriate button to indicate the fact. """ self.screen.boardview.reciprocal_portal = not self.screen.boardview.reciprocal_portal if self.screen.board...
Flip my ``reciprocal_portal`` boolean, and draw (or stop drawing) an extra arrow on the appropriate button to indicate the fact.
Below is the the instruction that describes the task: ### Input: Flip my ``reciprocal_portal`` boolean, and draw (or stop drawing) an extra arrow on the appropriate button to indicate the fact. ### Response: def toggle_reciprocal(self): """Flip my ``reciprocal_portal`` boolean, and draw (or...
def compiler_info(compiler): """Determine the name + version of the compiler""" (out, err) = subprocess.Popen( ['/bin/sh', '-c', '{0} -v'.format(compiler)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE ).communicate('') gcc_clang = re.compile('(g...
Determine the name + version of the compiler
Below is the the instruction that describes the task: ### Input: Determine the name + version of the compiler ### Response: def compiler_info(compiler): """Determine the name + version of the compiler""" (out, err) = subprocess.Popen( ['/bin/sh', '-c', '{0} -v'.format(compiler)], stdin=subp...
def Uri(self): """ Constructs the connection URI from name, noSsl and port instance variables. """ return ("%s://%s%s" % (("https", "http")[self._noSsl == True], self._name, (":" + str(self._port), "")[ (((self._noSsl == False) and (self._port == 80)) or ((self._noSsl == True) and (self._port == 443)))]))
Constructs the connection URI from name, noSsl and port instance variables.
Below is the the instruction that describes the task: ### Input: Constructs the connection URI from name, noSsl and port instance variables. ### Response: def Uri(self): """ Constructs the connection URI from name, noSsl and port instance variables. """ return ("%s://%s%s" % (("https", "http")[self._noSsl == T...
def isNonPairTag(self, isnonpair=None): """ True if element is listed in nonpair tag table (``br`` for example) or if it ends with ``/>`` (``<hr />`` for example). You can also change state from pair to nonpair if you use this as setter. Args: isnonpair (boo...
True if element is listed in nonpair tag table (``br`` for example) or if it ends with ``/>`` (``<hr />`` for example). You can also change state from pair to nonpair if you use this as setter. Args: isnonpair (bool, default None): If set, internal nonpair state is ...
Below is the the instruction that describes the task: ### Input: True if element is listed in nonpair tag table (``br`` for example) or if it ends with ``/>`` (``<hr />`` for example). You can also change state from pair to nonpair if you use this as setter. Args: isnon...
def at_line(self, line: FileLine) -> Iterator[Statement]: """ Returns an iterator over all of the statements located at a given line. """ num = line.num for stmt in self.in_file(line.filename): if stmt.location.start.line == num: yield stmt
Returns an iterator over all of the statements located at a given line.
Below is the the instruction that describes the task: ### Input: Returns an iterator over all of the statements located at a given line. ### Response: def at_line(self, line: FileLine) -> Iterator[Statement]: """ Returns an iterator over all of the statements located at a given line. """ ...
def accumulate_from_superclasses(cls, propname): ''' Traverse the class hierarchy and accumulate the special sets of names ``MetaHasProps`` stores on classes: Args: name (str) : name of the special attribute to collect. Typically meaningful values are: ``__container_props__``, ...
Traverse the class hierarchy and accumulate the special sets of names ``MetaHasProps`` stores on classes: Args: name (str) : name of the special attribute to collect. Typically meaningful values are: ``__container_props__``, ``__properties__``, ``__properties_with_refs__``
Below is the the instruction that describes the task: ### Input: Traverse the class hierarchy and accumulate the special sets of names ``MetaHasProps`` stores on classes: Args: name (str) : name of the special attribute to collect. Typically meaningful values are: ``__container_props__...
def sort_flavor_list(request, flavors, with_menu_label=True): """Utility method to sort a list of flavors. By default, returns the available flavors, sorted by RAM usage (ascending). Override these behaviours with a ``CREATE_INSTANCE_FLAVOR_SORT`` dict in ``local_settings.py``. """ def get_key(...
Utility method to sort a list of flavors. By default, returns the available flavors, sorted by RAM usage (ascending). Override these behaviours with a ``CREATE_INSTANCE_FLAVOR_SORT`` dict in ``local_settings.py``.
Below is the the instruction that describes the task: ### Input: Utility method to sort a list of flavors. By default, returns the available flavors, sorted by RAM usage (ascending). Override these behaviours with a ``CREATE_INSTANCE_FLAVOR_SORT`` dict in ``local_settings.py``. ### Response: def sort_...
def recalculate(self): """ Recalcualtes the slider scene for this widget. """ # recalculate the scene geometry scene = self.scene() w = self.calculateSceneWidth() scene.setSceneRect(0, 0, w, self.height()) # recalculate the item layout ...
Recalcualtes the slider scene for this widget.
Below is the the instruction that describes the task: ### Input: Recalcualtes the slider scene for this widget. ### Response: def recalculate(self): """ Recalcualtes the slider scene for this widget. """ # recalculate the scene geometry scene = self.scene() w =...
def get_value(self): """ Evaluate self.expr to get the parameter's value """ if (self._value is None) and (self.expr is not None): self._value = self.expr.get_value() return self._value
Evaluate self.expr to get the parameter's value
Below is the the instruction that describes the task: ### Input: Evaluate self.expr to get the parameter's value ### Response: def get_value(self): """ Evaluate self.expr to get the parameter's value """ if (self._value is None) and (self.expr is not None): self._value =...
def update_book(self, book_form): """Updates an existing book. arg: book_form (osid.commenting.BookForm): the form containing the elements to be updated raise: IllegalState - ``book_form`` already used in an update transaction raise: InvalidArgument ...
Updates an existing book. arg: book_form (osid.commenting.BookForm): the form containing the elements to be updated raise: IllegalState - ``book_form`` already used in an update transaction raise: InvalidArgument - the form contains an invalid value ...
Below is the the instruction that describes the task: ### Input: Updates an existing book. arg: book_form (osid.commenting.BookForm): the form containing the elements to be updated raise: IllegalState - ``book_form`` already used in an update transaction ...
def csv(self, client_id): """Download the query results as csv.""" logging.info('Exporting CSV file [{}]'.format(client_id)) query = ( db.session.query(Query) .filter_by(client_id=client_id) .one() ) rejected_tables = security_manager.rejected...
Download the query results as csv.
Below is the the instruction that describes the task: ### Input: Download the query results as csv. ### Response: def csv(self, client_id): """Download the query results as csv.""" logging.info('Exporting CSV file [{}]'.format(client_id)) query = ( db.session.query(Query) ...
def execute_once(self): """One step of execution.""" symbol = self.tape.get(self.head, self.EMPTY_SYMBOL) index = self.alphabet.index(symbol) rule = self.states[self.state][index] if rule is None: raise RuntimeError('Unexpected symbol: ' + symbol) self.tape...
One step of execution.
Below is the the instruction that describes the task: ### Input: One step of execution. ### Response: def execute_once(self): """One step of execution.""" symbol = self.tape.get(self.head, self.EMPTY_SYMBOL) index = self.alphabet.index(symbol) rule = self.states[self.state][index] ...
def setProperty(self, full_path, protect, dummy = 7046): """Set property of a file. :param full_path: The full path to get the file or directory property. :param protect: 'Y' or 'N', 중요 표시 :return: ``True`` when success to set property or ``False`` """ data = {'orgresou...
Set property of a file. :param full_path: The full path to get the file or directory property. :param protect: 'Y' or 'N', 중요 표시 :return: ``True`` when success to set property or ``False``
Below is the the instruction that describes the task: ### Input: Set property of a file. :param full_path: The full path to get the file or directory property. :param protect: 'Y' or 'N', 중요 표시 :return: ``True`` when success to set property or ``False`` ### Response: def setProperty(self,...
def head(self, item): """Makes a HEAD request on a specific item.""" uri = "/%s/%s" % (self.uri_base, utils.get_id(item)) return self._head(uri)
Makes a HEAD request on a specific item.
Below is the the instruction that describes the task: ### Input: Makes a HEAD request on a specific item. ### Response: def head(self, item): """Makes a HEAD request on a specific item.""" uri = "/%s/%s" % (self.uri_base, utils.get_id(item)) return self._head(uri)
def utilisation(self): """Getter for various Utilisation variables""" if self._utilisation is None: api = "SYNO.Core.System.Utilization" url = "%s/entry.cgi?api=%s&version=1&method=get" % ( self.base_url, api) self._utilisation =...
Getter for various Utilisation variables
Below is the the instruction that describes the task: ### Input: Getter for various Utilisation variables ### Response: def utilisation(self): """Getter for various Utilisation variables""" if self._utilisation is None: api = "SYNO.Core.System.Utilization" url = "%s/entr...
def U(self): """ Returns a distributed matrix whose columns are the left singular vectors of the SingularValueDecomposition if computeU was set to be True. """ u = self.call("U") if u is not None: mat_name = u.getClass().getSimpleName() if mat_name...
Returns a distributed matrix whose columns are the left singular vectors of the SingularValueDecomposition if computeU was set to be True.
Below is the the instruction that describes the task: ### Input: Returns a distributed matrix whose columns are the left singular vectors of the SingularValueDecomposition if computeU was set to be True. ### Response: def U(self): """ Returns a distributed matrix whose columns are the left ...
def set_api_key(config, key): """Configure a new API key.""" if not key and "X-Api-Key" in config.api_key: del config.api_key["X-Api-Key"] else: config.api_key["X-Api-Key"] = key
Configure a new API key.
Below is the the instruction that describes the task: ### Input: Configure a new API key. ### Response: def set_api_key(config, key): """Configure a new API key.""" if not key and "X-Api-Key" in config.api_key: del config.api_key["X-Api-Key"] else: config.api_key["X-Api-Key"] = key
def _merge_single_runs(self, other_trajectory, used_runs): """ Updates the `run_information` of the current trajectory.""" count = len(self) # Variable to count the increasing new run indices and create # new run names run_indices = range(len(other_trajectory)) run_name_dict ...
Updates the `run_information` of the current trajectory.
Below is the the instruction that describes the task: ### Input: Updates the `run_information` of the current trajectory. ### Response: def _merge_single_runs(self, other_trajectory, used_runs): """ Updates the `run_information` of the current trajectory.""" count = len(self) # Variable to count ...
def analyze(self, chunkSize, *sinks): """ Figure out the best diffs to use to reach all our required volumes. """ measureSize = False if self.measureSize: for sink in sinks: if sink.isRemote: measureSize = True # Use destination (already ...
Figure out the best diffs to use to reach all our required volumes.
Below is the the instruction that describes the task: ### Input: Figure out the best diffs to use to reach all our required volumes. ### Response: def analyze(self, chunkSize, *sinks): """ Figure out the best diffs to use to reach all our required volumes. """ measureSize = False if self.m...
def importdb(indir): """Import a previously exported anchore DB""" ecode = 0 try: imgdir = os.path.join(indir, "images") feeddir = os.path.join(indir, "feeds") storedir = os.path.join(indir, "storedfiles") for d in [indir, imgdir, feeddir, storedir]: if not os.pa...
Import a previously exported anchore DB
Below is the the instruction that describes the task: ### Input: Import a previously exported anchore DB ### Response: def importdb(indir): """Import a previously exported anchore DB""" ecode = 0 try: imgdir = os.path.join(indir, "images") feeddir = os.path.join(indir, "feeds") ...
def consume_service(service_agreement_id, service_endpoint, account, files, destination_folder, index=None): """ Call the brizo endpoint to get access to the different files that form the asset. :param service_agreement_id: Service Agreement Id, str :param servic...
Call the brizo endpoint to get access to the different files that form the asset. :param service_agreement_id: Service Agreement Id, str :param service_endpoint: Url to consume, str :param account: Account instance of the consumer signing this agreement, hex-str :param files: List conta...
Below is the the instruction that describes the task: ### Input: Call the brizo endpoint to get access to the different files that form the asset. :param service_agreement_id: Service Agreement Id, str :param service_endpoint: Url to consume, str :param account: Account instance of the cons...
def preserve_shape(func): """Preserve shape of the image.""" @wraps(func) def wrapped_function(img, *args, **kwargs): shape = img.shape result = func(img, *args, **kwargs) result = result.reshape(shape) return result return wrapped_function
Preserve shape of the image.
Below is the the instruction that describes the task: ### Input: Preserve shape of the image. ### Response: def preserve_shape(func): """Preserve shape of the image.""" @wraps(func) def wrapped_function(img, *args, **kwargs): shape = img.shape result = func(img, *args, **kwargs) ...
def evaluate(self, agentml, user=None): """ Evaluate the conditional statement and return its contents if a successful evaluation takes place :param user: The active user object :type user: agentml.User or None :param agentml: The active AgentML instance :type ...
Evaluate the conditional statement and return its contents if a successful evaluation takes place :param user: The active user object :type user: agentml.User or None :param agentml: The active AgentML instance :type agentml: AgentML :return: Condition contents if the...
Below is the the instruction that describes the task: ### Input: Evaluate the conditional statement and return its contents if a successful evaluation takes place :param user: The active user object :type user: agentml.User or None :param agentml: The active AgentML instance ...
def add_flags(self, *flags): """Adds one or more flags to the query. For example: current-patch-set -> --current-patch-set """ if not isinstance(flags, (list, tuple)): flags = [str(flags)] self.extend(["--%s" % f for f in flags]) return self
Adds one or more flags to the query. For example: current-patch-set -> --current-patch-set
Below is the the instruction that describes the task: ### Input: Adds one or more flags to the query. For example: current-patch-set -> --current-patch-set ### Response: def add_flags(self, *flags): """Adds one or more flags to the query. For example: current-patch...
def visit_ListComp(self, node: ast.ListComp) -> None: """Represent the list comprehension by dumping its source code.""" if node in self._recomputed_values: value = self._recomputed_values[node] text = self._atok.get_text(node) self.reprs[text] = value self....
Represent the list comprehension by dumping its source code.
Below is the the instruction that describes the task: ### Input: Represent the list comprehension by dumping its source code. ### Response: def visit_ListComp(self, node: ast.ListComp) -> None: """Represent the list comprehension by dumping its source code.""" if node in self._recomputed_values: ...
def debug(self, request, message, extra_tags='', fail_silently=False): """Add a message with the ``DEBUG`` level.""" add(self.target_name, request, constants.DEBUG, message, extra_tags=extra_tags, fail_silently=fail_silently)
Add a message with the ``DEBUG`` level.
Below is the the instruction that describes the task: ### Input: Add a message with the ``DEBUG`` level. ### Response: def debug(self, request, message, extra_tags='', fail_silently=False): """Add a message with the ``DEBUG`` level.""" add(self.target_name, request, constants.DEBUG, message, extra_...
def add_size_info (self): """Set size of URL content (if any).. Should be overridden in subclasses.""" maxbytes = self.aggregate.config["maxfilesizedownload"] if self.size > maxbytes: self.add_warning( _("Content size %(size)s is larger than %(maxbytes)s.") % ...
Set size of URL content (if any).. Should be overridden in subclasses.
Below is the the instruction that describes the task: ### Input: Set size of URL content (if any).. Should be overridden in subclasses. ### Response: def add_size_info (self): """Set size of URL content (if any).. Should be overridden in subclasses.""" maxbytes = self.aggregate.conf...
def strings(self, minSize = 4, maxSize = 1024): """ Extract ASCII strings from the process memory. @type minSize: int @param minSize: (Optional) Minimum size of the strings to search for. @type maxSize: int @param maxSize: (Optional) Maximum size of the strings to sea...
Extract ASCII strings from the process memory. @type minSize: int @param minSize: (Optional) Minimum size of the strings to search for. @type maxSize: int @param maxSize: (Optional) Maximum size of the strings to search for. @rtype: iterator of tuple(int, int, str) ...
Below is the the instruction that describes the task: ### Input: Extract ASCII strings from the process memory. @type minSize: int @param minSize: (Optional) Minimum size of the strings to search for. @type maxSize: int @param maxSize: (Optional) Maximum size of the strings to se...
def compile_settings(model_path, file_path, ignore_errors=False): ''' a method to compile configuration values from different sources NOTE: method searches the environment variables, a local configuration path and the default values for a jsonmodel object for valid ...
a method to compile configuration values from different sources NOTE: method searches the environment variables, a local configuration path and the default values for a jsonmodel object for valid configuration values. if an environmental variable or key in...
Below is the the instruction that describes the task: ### Input: a method to compile configuration values from different sources NOTE: method searches the environment variables, a local configuration path and the default values for a jsonmodel object for valid configur...
def compact_references(basis_dict, ref_data): """ Creates a mapping of elements to reference keys A list is returned, with each element of the list being a dictionary with entries 'reference_info' containing data for (possibly) multiple references, and 'elements' which is a list of element Z number...
Creates a mapping of elements to reference keys A list is returned, with each element of the list being a dictionary with entries 'reference_info' containing data for (possibly) multiple references, and 'elements' which is a list of element Z numbers that those references apply to Parameters -...
Below is the the instruction that describes the task: ### Input: Creates a mapping of elements to reference keys A list is returned, with each element of the list being a dictionary with entries 'reference_info' containing data for (possibly) multiple references, and 'elements' which is a list of eleme...
def add_toolkit(topology, location): """Add an SPL toolkit to a topology. Args: topology(Topology): Topology to include toolkit in. location(str): Location of the toolkit directory. """ import streamsx.topology.topology assert isinstance(topology, streamsx.topology.topology.Topology...
Add an SPL toolkit to a topology. Args: topology(Topology): Topology to include toolkit in. location(str): Location of the toolkit directory.
Below is the the instruction that describes the task: ### Input: Add an SPL toolkit to a topology. Args: topology(Topology): Topology to include toolkit in. location(str): Location of the toolkit directory. ### Response: def add_toolkit(topology, location): """Add an SPL toolkit to a topol...
def remove_old(self, max_log_time): """Remove all logs which are older than the specified time.""" files = glob.glob('{}/queue-*'.format(self.log_dir)) files = list(map(lambda x: os.path.basename(x), files)) for log_file in files: # Get time stamp from filename n...
Remove all logs which are older than the specified time.
Below is the the instruction that describes the task: ### Input: Remove all logs which are older than the specified time. ### Response: def remove_old(self, max_log_time): """Remove all logs which are older than the specified time.""" files = glob.glob('{}/queue-*'.format(self.log_dir)) fil...
def render(self, form_id=None): ''' 动态输出html内容 ''' page_bar = self.page_bars.get(int(self.page / 10)) if page_bar is None: return '' _htmls = [] if form_id: _htmls.append(u'''<script> function goto_page(form_id,page){ ...
动态输出html内容
Below is the the instruction that describes the task: ### Input: 动态输出html内容 ### Response: def render(self, form_id=None): ''' 动态输出html内容 ''' page_bar = self.page_bars.get(int(self.page / 10)) if page_bar is None: return '' _htmls = [] if form_id:...
def shape_type(self): """ Unique integer identifying the type of this shape, like ``MSO_SHAPE_TYPE.TEXT_BOX``. """ if self.is_placeholder: return MSO_SHAPE_TYPE.PLACEHOLDER if self._sp.has_custom_geometry: return MSO_SHAPE_TYPE.FREEFORM if ...
Unique integer identifying the type of this shape, like ``MSO_SHAPE_TYPE.TEXT_BOX``.
Below is the the instruction that describes the task: ### Input: Unique integer identifying the type of this shape, like ``MSO_SHAPE_TYPE.TEXT_BOX``. ### Response: def shape_type(self): """ Unique integer identifying the type of this shape, like ``MSO_SHAPE_TYPE.TEXT_BOX``. ...
def add_flag(*args, **kwargs): """ define a single flag. add_flag(flagname, default_value, help='', **kwargs) add_flag([(flagname, default_value, help), ...]) or define flags without help message add_flag(flagname, default_value, help='', **kwargs) add_flag('gpu', 1, help='CUDA_VISIBLE_...
define a single flag. add_flag(flagname, default_value, help='', **kwargs) add_flag([(flagname, default_value, help), ...]) or define flags without help message add_flag(flagname, default_value, help='', **kwargs) add_flag('gpu', 1, help='CUDA_VISIBLE_DEVICES') :param args: :param kwarg...
Below is the the instruction that describes the task: ### Input: define a single flag. add_flag(flagname, default_value, help='', **kwargs) add_flag([(flagname, default_value, help), ...]) or define flags without help message add_flag(flagname, default_value, help='', **kwargs) add_flag('gp...
def relabel(self, label=None, group=None, depth=1): """Clone object and apply new group and/or label. Applies relabeling to child up to the supplied depth. Args: label (str, optional): New label to apply to returned object group (str, optional): New group to apply to re...
Clone object and apply new group and/or label. Applies relabeling to child up to the supplied depth. Args: label (str, optional): New label to apply to returned object group (str, optional): New group to apply to returned object depth (int, optional): Depth to which...
Below is the the instruction that describes the task: ### Input: Clone object and apply new group and/or label. Applies relabeling to child up to the supplied depth. Args: label (str, optional): New label to apply to returned object group (str, optional): New group to apply...
def getMaximinScores(profile): """ Returns a dictionary that associates integer representations of each candidate with their Copeland score. :ivar Profile profile: A Profile object that represents an election profile. """ # Currently, we expect the profile to contain complete ordering over can...
Returns a dictionary that associates integer representations of each candidate with their Copeland score. :ivar Profile profile: A Profile object that represents an election profile.
Below is the the instruction that describes the task: ### Input: Returns a dictionary that associates integer representations of each candidate with their Copeland score. :ivar Profile profile: A Profile object that represents an election profile. ### Response: def getMaximinScores(profile): """ R...
def login(self): """Login""" # perform the request data = {'apikey': self.apikey, 'username': self.username, 'password': self.password} r = self.session.post(self.base_url + '/login', json=data) r.raise_for_status() # set the Authorization header self.session.hea...
Login
Below is the the instruction that describes the task: ### Input: Login ### Response: def login(self): """Login""" # perform the request data = {'apikey': self.apikey, 'username': self.username, 'password': self.password} r = self.session.post(self.base_url + '/login', json=data) ...
def get_data(self, field, function=None, default=None): """ Get data from the striplog. """ f = function or utils.null data = [] for iv in self: d = iv.data.get(field) if d is None: if default is not None: d = de...
Get data from the striplog.
Below is the the instruction that describes the task: ### Input: Get data from the striplog. ### Response: def get_data(self, field, function=None, default=None): """ Get data from the striplog. """ f = function or utils.null data = [] for iv in self: d =...
def _populate(self): """ **Purpose**: Populate the ResourceManager class with the validated resource description """ if self._validated: self._prof.prof('populating rmgr', uid=self._uid) self._logger.debug('Populating resource manager ...
**Purpose**: Populate the ResourceManager class with the validated resource description
Below is the the instruction that describes the task: ### Input: **Purpose**: Populate the ResourceManager class with the validated resource description ### Response: def _populate(self): """ **Purpose**: Populate the ResourceManager class with the validated ...
def roc(self): """ROC plot """ return plot.roc(self.y_true, self.y_score, ax=_gen_ax())
ROC plot
Below is the the instruction that describes the task: ### Input: ROC plot ### Response: def roc(self): """ROC plot """ return plot.roc(self.y_true, self.y_score, ax=_gen_ax())
def add(self, value): """ Add a value to the buffer. """ ind = int(self._ind % self.shape) self._pos = self._ind % self.shape self._values[ind] = value if self._ind < self.shape: self._ind += 1 # fast fill else: self._ind += self._...
Add a value to the buffer.
Below is the the instruction that describes the task: ### Input: Add a value to the buffer. ### Response: def add(self, value): """ Add a value to the buffer. """ ind = int(self._ind % self.shape) self._pos = self._ind % self.shape self._values[ind] = value i...
def get_logs(self, container_id): """ Return the full stdout/stderr of a container""" stdout = self._docker.containers.get(container_id).logs(stdout=True, stderr=False).decode('utf8') stderr = self._docker.containers.get(container_id).logs(stdout=False, stderr=True).decode('utf8') return...
Return the full stdout/stderr of a container
Below is the the instruction that describes the task: ### Input: Return the full stdout/stderr of a container ### Response: def get_logs(self, container_id): """ Return the full stdout/stderr of a container""" stdout = self._docker.containers.get(container_id).logs(stdout=True, stderr=False).decode...
def browse(self): """ Save response in temporary file and open it in GUI browser. """ _, path = tempfile.mkstemp() self.save(path) webbrowser.open('file://' + path)
Save response in temporary file and open it in GUI browser.
Below is the the instruction that describes the task: ### Input: Save response in temporary file and open it in GUI browser. ### Response: def browse(self): """ Save response in temporary file and open it in GUI browser. """ _, path = tempfile.mkstemp() self.save(path) ...
def _remove_exploration(self): """ Called if trajectory is expanded, deletes all explored parameters from disk """ for param in self._explored_parameters.values(): if param._stored: try: self.f_delete_item(param) except Exception: ...
Called if trajectory is expanded, deletes all explored parameters from disk
Below is the the instruction that describes the task: ### Input: Called if trajectory is expanded, deletes all explored parameters from disk ### Response: def _remove_exploration(self): """ Called if trajectory is expanded, deletes all explored parameters from disk """ for param in self._explored_p...
def clip_datetime(dt, tz=DEFAULT_TZ, is_dst=None): """Limit a datetime to a valid range for datetime, datetime64, and Timestamp objects >>> from datetime import timedelta >>> clip_datetime(MAX_DATETIME + timedelta(100)) == pd.Timestamp(MAX_DATETIME, tz='utc') == MAX_TIMESTAMP True >>> MAX_TIMESTAMP ...
Limit a datetime to a valid range for datetime, datetime64, and Timestamp objects >>> from datetime import timedelta >>> clip_datetime(MAX_DATETIME + timedelta(100)) == pd.Timestamp(MAX_DATETIME, tz='utc') == MAX_TIMESTAMP True >>> MAX_TIMESTAMP Timestamp('2262-04-11 23:47:16.854775+0000', tz='UTC')
Below is the the instruction that describes the task: ### Input: Limit a datetime to a valid range for datetime, datetime64, and Timestamp objects >>> from datetime import timedelta >>> clip_datetime(MAX_DATETIME + timedelta(100)) == pd.Timestamp(MAX_DATETIME, tz='utc') == MAX_TIMESTAMP True >>> MAX...
def remove_prefix(self, prefix): """Removes prefix from this set. This is a no-op if the prefix doesn't exist in it. """ if prefix not in self.__prefix_map: return ni = self.__lookup_prefix(prefix) ni.prefixes.discard(prefix) del self.__prefix_map[pr...
Removes prefix from this set. This is a no-op if the prefix doesn't exist in it.
Below is the the instruction that describes the task: ### Input: Removes prefix from this set. This is a no-op if the prefix doesn't exist in it. ### Response: def remove_prefix(self, prefix): """Removes prefix from this set. This is a no-op if the prefix doesn't exist in it. """ ...
def cell_start(self, cell, cell_index=None, **kwargs): """ Set and save a cell's start state. Optionally called by engines during execution to initialize the metadata for a cell and save the notebook to the output path. """ if self.log_output: ceel_num = cell...
Set and save a cell's start state. Optionally called by engines during execution to initialize the metadata for a cell and save the notebook to the output path.
Below is the the instruction that describes the task: ### Input: Set and save a cell's start state. Optionally called by engines during execution to initialize the metadata for a cell and save the notebook to the output path. ### Response: def cell_start(self, cell, cell_index=None, **kwargs): ...
def _run_container(self, run_command_instance, callback): """ this is internal method """ tmpfile = os.path.join(get_backend_tmpdir(), random_tmp_filename()) # the cid file must not exist run_command_instance.options += ["--cidfile=%s" % tmpfile] logger.debug("podman command: %s"...
this is internal method
Below is the the instruction that describes the task: ### Input: this is internal method ### Response: def _run_container(self, run_command_instance, callback): """ this is internal method """ tmpfile = os.path.join(get_backend_tmpdir(), random_tmp_filename()) # the cid file must not exist ...
def _stopOnFailure(self, f): "utility method to stop the service when a failure occurs" if self.running: d = defer.maybeDeferred(self.stopService) d.addErrback(log.err, 'while stopping broken HgPoller service') return f
utility method to stop the service when a failure occurs
Below is the the instruction that describes the task: ### Input: utility method to stop the service when a failure occurs ### Response: def _stopOnFailure(self, f): "utility method to stop the service when a failure occurs" if self.running: d = defer.maybeDeferred(self.stopService) ...
def boolean(self, field, value=None, **validations): """*Asserts the field as JSON boolean.* The field consists of parts separated by spaces, the parts being object property names or array indices starting from 0, and the root being the instance created by the last request (see `Output`...
*Asserts the field as JSON boolean.* The field consists of parts separated by spaces, the parts being object property names or array indices starting from 0, and the root being the instance created by the last request (see `Output` for it). For asserting deeply nested properties or mul...
Below is the the instruction that describes the task: ### Input: *Asserts the field as JSON boolean.* The field consists of parts separated by spaces, the parts being object property names or array indices starting from 0, and the root being the instance created by the last request (see `Ou...
def get_package_metadata(self): """ Gets metatada relative to the country package the tax and benefit system is built from. :returns: Country package metadata :rtype: dict Example: >>> tax_benefit_system.get_package_metadata() >>> { ...
Gets metatada relative to the country package the tax and benefit system is built from. :returns: Country package metadata :rtype: dict Example: >>> tax_benefit_system.get_package_metadata() >>> { >>> 'location': '/path/to/dir/containing/pack...
Below is the the instruction that describes the task: ### Input: Gets metatada relative to the country package the tax and benefit system is built from. :returns: Country package metadata :rtype: dict Example: >>> tax_benefit_system.get_package_metadata() ...
def stop_server(self): """ Stop serving """ if self.api_server is not None: try: self.api_server.socket.shutdown(socket.SHUT_RDWR) except: log.warning("Failed to shut down API server socket") self.api_server.shutdown()
Stop serving
Below is the the instruction that describes the task: ### Input: Stop serving ### Response: def stop_server(self): """ Stop serving """ if self.api_server is not None: try: self.api_server.socket.shutdown(socket.SHUT_RDWR) except: ...
def ase(dbuser, dbpassword, args, gui): """Connection to atomic structures on the Catalysis-Hub server with ase db cli. Arguments to the the ase db cli client must be enclosed in one string. For example: <cathub ase 'formula=Ag6In6H -s energy -L 200'>. To see possible ase db arguments ru...
Connection to atomic structures on the Catalysis-Hub server with ase db cli. Arguments to the the ase db cli client must be enclosed in one string. For example: <cathub ase 'formula=Ag6In6H -s energy -L 200'>. To see possible ase db arguments run <ase db --help>
Below is the the instruction that describes the task: ### Input: Connection to atomic structures on the Catalysis-Hub server with ase db cli. Arguments to the the ase db cli client must be enclosed in one string. For example: <cathub ase 'formula=Ag6In6H -s energy -L 200'>. To see possib...
def post(self, path, data=None, **kwargs): """ HTTP post on the node """ if data: return (yield from self._compute.post("/projects/{}/{}/nodes/{}{}".format(self._project.id, self._node_type, self._id, path), data=data, **kwargs)) else: return (yield from s...
HTTP post on the node
Below is the the instruction that describes the task: ### Input: HTTP post on the node ### Response: def post(self, path, data=None, **kwargs): """ HTTP post on the node """ if data: return (yield from self._compute.post("/projects/{}/{}/nodes/{}{}".format(self._project....
def get_sid(principal): ''' Converts a username to a sid, or verifies a sid. Required for working with the DACL. Args: principal(str): The principal to lookup the sid. Can be a sid or a username. Returns: PySID Object: A sid Usage: .. code-block:: python ...
Converts a username to a sid, or verifies a sid. Required for working with the DACL. Args: principal(str): The principal to lookup the sid. Can be a sid or a username. Returns: PySID Object: A sid Usage: .. code-block:: python # Get a user's sid salt...
Below is the the instruction that describes the task: ### Input: Converts a username to a sid, or verifies a sid. Required for working with the DACL. Args: principal(str): The principal to lookup the sid. Can be a sid or a username. Returns: PySID Object: A sid Usage:...
def write_usnps(data, sidx, pnames): """ write the bisnp string """ ## grab bis data from tmparr tmparrs = os.path.join(data.dirs.outfiles, "tmp-{}.h5".format(data.name)) with h5py.File(tmparrs, 'r') as io5: bisarr = io5["bisarr"] ## trim to size b/c it was made longer than actual ...
write the bisnp string
Below is the the instruction that describes the task: ### Input: write the bisnp string ### Response: def write_usnps(data, sidx, pnames): """ write the bisnp string """ ## grab bis data from tmparr tmparrs = os.path.join(data.dirs.outfiles, "tmp-{}.h5".format(data.name)) with h5py.File(tmparrs, ...
def import_from_ding0(file, network): """ Import an eDisGo grid topology from `Ding0 data <https://github.com/openego/ding0>`_. This import method is specifically designed to load grid topology data in the format as `Ding0 <https://github.com/openego/ding0>`_ provides it via pickles. The i...
Import an eDisGo grid topology from `Ding0 data <https://github.com/openego/ding0>`_. This import method is specifically designed to load grid topology data in the format as `Ding0 <https://github.com/openego/ding0>`_ provides it via pickles. The import of the grid topology includes * the...
Below is the the instruction that describes the task: ### Input: Import an eDisGo grid topology from `Ding0 data <https://github.com/openego/ding0>`_. This import method is specifically designed to load grid topology data in the format as `Ding0 <https://github.com/openego/ding0>`_ provides it via ...
def plot_pnlratio(self): """ 画出pnl比率散点图 """ plt.scatter(x=self.pnl.sell_date.apply(str), y=self.pnl.pnl_ratio) plt.gcf().autofmt_xdate() return plt
画出pnl比率散点图
Below is the the instruction that describes the task: ### Input: 画出pnl比率散点图 ### Response: def plot_pnlratio(self): """ 画出pnl比率散点图 """ plt.scatter(x=self.pnl.sell_date.apply(str), y=self.pnl.pnl_ratio) plt.gcf().autofmt_xdate() return plt
def _do_login_locked(self): """Executes the login procedure (telnet) as well as setting up some connection defaults like turning off the prompt, etc.""" self._telnet = telnetlib.Telnet(self._host) self._telnet.read_until(LutronConnection.USER_PROMPT) self._telnet.write(self._user + b'\r\n') self...
Executes the login procedure (telnet) as well as setting up some connection defaults like turning off the prompt, etc.
Below is the the instruction that describes the task: ### Input: Executes the login procedure (telnet) as well as setting up some connection defaults like turning off the prompt, etc. ### Response: def _do_login_locked(self): """Executes the login procedure (telnet) as well as setting up some connectio...
def print_help(self, script_name: str): '''print a help message from the script''' textWidth = max(60, shutil.get_terminal_size((80, 20)).columns) if len(script_name) > 20: print(f'usage: sos run {script_name}') print( ' [workflow_name | -t ...
print a help message from the script
Below is the the instruction that describes the task: ### Input: print a help message from the script ### Response: def print_help(self, script_name: str): '''print a help message from the script''' textWidth = max(60, shutil.get_terminal_size((80, 20)).columns) if len(script_name) > 20: ...
def importConnFromExcel (fileName, sheetName): ''' Import connectivity rules from Excel sheet''' import openpyxl as xl # set columns colPreTags = 0 # 'A' colPostTags = 1 # 'B' colConnFunc = 2 # 'C' colSyn = 3 # 'D' colProb = 5 # 'F' colWeight = 6 # 'G' colAnnot = 8 # 'I' o...
Import connectivity rules from Excel sheet
Below is the the instruction that describes the task: ### Input: Import connectivity rules from Excel sheet ### Response: def importConnFromExcel (fileName, sheetName): ''' Import connectivity rules from Excel sheet''' import openpyxl as xl # set columns colPreTags = 0 # 'A' colPostTags = 1 # ...
def plot_incremental_transactions( model, transactions, datetime_col, customer_id_col, t, t_cal, datetime_format=None, freq="D", set_index_date=False, title="Tracking Daily Transactions", xlabel="day", ylabel="Transactions", ax=None, **kwargs ): """ Plot a...
Plot a figure of the predicted and actual cumulative transactions of users. Parameters ---------- model: lifetimes model A fitted lifetimes model transactions: pandas DataFrame DataFrame containing the transactions history of the customer_id datetime_col: str The column in t...
Below is the the instruction that describes the task: ### Input: Plot a figure of the predicted and actual cumulative transactions of users. Parameters ---------- model: lifetimes model A fitted lifetimes model transactions: pandas DataFrame DataFrame containing the transactions his...
def find_prepositions(chunked): """ The input is a list of [token, tag, chunk]-items. The output is a list of [token, tag, chunk, preposition]-items. PP-chunks followed by NP-chunks make up a PNP-chunk. """ # Tokens that are not part of a preposition just get the O-tag. for ch in chunked...
The input is a list of [token, tag, chunk]-items. The output is a list of [token, tag, chunk, preposition]-items. PP-chunks followed by NP-chunks make up a PNP-chunk.
Below is the the instruction that describes the task: ### Input: The input is a list of [token, tag, chunk]-items. The output is a list of [token, tag, chunk, preposition]-items. PP-chunks followed by NP-chunks make up a PNP-chunk. ### Response: def find_prepositions(chunked): """ The input is ...
def getSegmentOnCell(self, c, i, segIdx): """ Overrides :meth:`nupic.algorithms.backtracking_tm.BacktrackingTM.getSegmentOnCell`. """ segList = self.cells4.getNonEmptySegList(c,i) seg = self.cells4.getSegment(c, i, segList[segIdx]) numSyn = seg.size() assert numSyn != 0 # Accumulate seg...
Overrides :meth:`nupic.algorithms.backtracking_tm.BacktrackingTM.getSegmentOnCell`.
Below is the the instruction that describes the task: ### Input: Overrides :meth:`nupic.algorithms.backtracking_tm.BacktrackingTM.getSegmentOnCell`. ### Response: def getSegmentOnCell(self, c, i, segIdx): """ Overrides :meth:`nupic.algorithms.backtracking_tm.BacktrackingTM.getSegmentOnCell`. """ se...
def fetch_live(self, formatter=TableFormat): """ Fetch a live stream query. This is the equivalent of selecting the "Play" option for monitoring fields within the SMC UI. Data will be streamed back in real time. :param formatter: Formatter type for data representation. A...
Fetch a live stream query. This is the equivalent of selecting the "Play" option for monitoring fields within the SMC UI. Data will be streamed back in real time. :param formatter: Formatter type for data representation. Any type in :py:mod:`smc_monitoring.models.formatters`...
Below is the the instruction that describes the task: ### Input: Fetch a live stream query. This is the equivalent of selecting the "Play" option for monitoring fields within the SMC UI. Data will be streamed back in real time. :param formatter: Formatter type for data representatio...
def set_parameter_label(self, parameter, label): """ Sets the Label used in the User Interface for the given parameter. :type parameter: str or Parameter :type label: str """ labels = self.metadata\ .setdefault("AWS::CloudFormation::Interface", {})\ ...
Sets the Label used in the User Interface for the given parameter. :type parameter: str or Parameter :type label: str
Below is the the instruction that describes the task: ### Input: Sets the Label used in the User Interface for the given parameter. :type parameter: str or Parameter :type label: str ### Response: def set_parameter_label(self, parameter, label): """ Sets the Label used in the User I...
def set_brightness(host, did, value, token=None): """Set brightness of a bulb or fixture.""" urllib3.disable_warnings() if token: scheme = "https" if not token: scheme = "http" token = "1234567890" url = ( scheme + '://' + host + '/gwr/gop.php?cmd=DeviceSendComman...
Set brightness of a bulb or fixture.
Below is the the instruction that describes the task: ### Input: Set brightness of a bulb or fixture. ### Response: def set_brightness(host, did, value, token=None): """Set brightness of a bulb or fixture.""" urllib3.disable_warnings() if token: scheme = "https" if not token: scheme...
def matrix_iter_detail(matrix, version, scale=1, border=None): """\ Returns an iterator / generator over the provided matrix which includes the border and the scaling factor. This iterator / generator returns different values for dark / light modules and therefor the different parts (like the finde...
\ Returns an iterator / generator over the provided matrix which includes the border and the scaling factor. This iterator / generator returns different values for dark / light modules and therefor the different parts (like the finder patterns, alignment patterns etc.) are distinguishable. If this ...
Below is the the instruction that describes the task: ### Input: \ Returns an iterator / generator over the provided matrix which includes the border and the scaling factor. This iterator / generator returns different values for dark / light modules and therefor the different parts (like the finder...
def incr_obj(obj, **attrs): """Increments context variables """ for name, value in attrs.iteritems(): v = getattr(obj, name, None) if not hasattr(obj, name) or v is None: v = 0 setattr(obj, name, v + value)
Increments context variables
Below is the the instruction that describes the task: ### Input: Increments context variables ### Response: def incr_obj(obj, **attrs): """Increments context variables """ for name, value in attrs.iteritems(): v = getattr(obj, name, None) if not hasattr(obj, name) or v is None: ...
def generate_admin_metadata(name, creator_username=None): """Return admin metadata as a dictionary.""" if not dtoolcore.utils.name_is_valid(name): raise(DtoolCoreInvalidNameError()) if creator_username is None: creator_username = dtoolcore.utils.getuser() datetime_obj = datetime.datet...
Return admin metadata as a dictionary.
Below is the the instruction that describes the task: ### Input: Return admin metadata as a dictionary. ### Response: def generate_admin_metadata(name, creator_username=None): """Return admin metadata as a dictionary.""" if not dtoolcore.utils.name_is_valid(name): raise(DtoolCoreInvalidNameError()...
def get_setting(self, key, converter=None, choices=None): '''Returns the settings value for the provided key. If converter is str, unicode, bool or int the settings value will be returned converted to the provided type. If choices is an instance of list or tuple its item at position of t...
Returns the settings value for the provided key. If converter is str, unicode, bool or int the settings value will be returned converted to the provided type. If choices is an instance of list or tuple its item at position of the settings value be returned. .. note:: It is sugges...
Below is the the instruction that describes the task: ### Input: Returns the settings value for the provided key. If converter is str, unicode, bool or int the settings value will be returned converted to the provided type. If choices is an instance of list or tuple its item at position of t...
def bend(mapping, source, context=None): """ The main bending function. mapping: the map of benders source: a dict to be bent returns a new dict according to the provided map. """ context = {} if context is None else context transport = Transport(source, context) return _bend(mappi...
The main bending function. mapping: the map of benders source: a dict to be bent returns a new dict according to the provided map.
Below is the the instruction that describes the task: ### Input: The main bending function. mapping: the map of benders source: a dict to be bent returns a new dict according to the provided map. ### Response: def bend(mapping, source, context=None): """ The main bending function. mappin...
def keeprunning(wait_secs=0, exit_on_success=False, on_success=None, on_error=None, on_done=None): ''' Example 1: dosomething needs to run until completion condition without needing to have a loop in its code. Also, when error happens, we should NOT terminate execution >>> from deep...
Example 1: dosomething needs to run until completion condition without needing to have a loop in its code. Also, when error happens, we should NOT terminate execution >>> from deeputil import AttrDict >>> @keeprunning(wait_secs=1) ... def dosomething(state): ... state.i += 1 ... pri...
Below is the the instruction that describes the task: ### Input: Example 1: dosomething needs to run until completion condition without needing to have a loop in its code. Also, when error happens, we should NOT terminate execution >>> from deeputil import AttrDict >>> @keeprunning(wait_secs=1) ...
def get_page(session, url, json=False, post=False, data=None, headers=None, quiet=False, **kwargs): """ Download an HTML page using the requests session. @param session: Requests session. @type session: requests....
Download an HTML page using the requests session. @param session: Requests session. @type session: requests.Session @param url: URL pattern with optional keywords to format. @type url: str @param post: Flag that indicates whether POST request should be sent. @type post: bool @param data:...
Below is the the instruction that describes the task: ### Input: Download an HTML page using the requests session. @param session: Requests session. @type session: requests.Session @param url: URL pattern with optional keywords to format. @type url: str @param post: Flag that indicates whethe...
def get_db_prep_value(self, value, connection, prepared=False): """Prepare a value for DB interaction. Returns: - list(bytes) if not prepared - list(str) if prepared """ if prepared: return value if value is None: return [] value...
Prepare a value for DB interaction. Returns: - list(bytes) if not prepared - list(str) if prepared
Below is the the instruction that describes the task: ### Input: Prepare a value for DB interaction. Returns: - list(bytes) if not prepared - list(str) if prepared ### Response: def get_db_prep_value(self, value, connection, prepared=False): """Prepare a value for DB interaction. ...
def choose_labels(alternatives): """ Prompt the user select several labels from the provided alternatives. At least one label must be selected. :param list alternatives: Sequence of options that are available to select from :return: Several selected labels """ if not alternatives: ...
Prompt the user select several labels from the provided alternatives. At least one label must be selected. :param list alternatives: Sequence of options that are available to select from :return: Several selected labels
Below is the the instruction that describes the task: ### Input: Prompt the user select several labels from the provided alternatives. At least one label must be selected. :param list alternatives: Sequence of options that are available to select from :return: Several selected labels ### Response: de...