code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _send_request(self): """Send a message containing the RPC method call """ msg = Message() msg.subject = "An RPC call!" msg.address = self._to msg.reply_to = self._reply_to msg.body = self._method msg.correlation_id = 5 # whatever... print("se...
Send a message containing the RPC method call
Below is the the instruction that describes the task: ### Input: Send a message containing the RPC method call ### Response: def _send_request(self): """Send a message containing the RPC method call """ msg = Message() msg.subject = "An RPC call!" msg.address = self._to ...
def dense_convolutional_network(units: tf.Tensor, n_hidden_list: List, filter_width=3, use_dilation=False, use_batch_norm=False, training_ph=None): """ Dens...
Densely connected convolutional layers. Based on the paper: [Gao 17] https://arxiv.org/abs/1608.06993 Args: units: a tensorflow tensor with dimensionality [None, n_tokens, n_features] n_hidden_list: list with number of hidden units at the ouput of each layer filter_w...
Below is the the instruction that describes the task: ### Input: Densely connected convolutional layers. Based on the paper: [Gao 17] https://arxiv.org/abs/1608.06993 Args: units: a tensorflow tensor with dimensionality [None, n_tokens, n_features] n_hidden_list: list with n...
def calc_std_mod_reduc(mod_reduc): """Calculate the standard deviation as a function of G/G_max. Equation 7.29 from Darendeli (2001). Parameters ---------- mod_reduc : array_like Modulus reduction values. Returns ------- std : :class:`numpy....
Calculate the standard deviation as a function of G/G_max. Equation 7.29 from Darendeli (2001). Parameters ---------- mod_reduc : array_like Modulus reduction values. Returns ------- std : :class:`numpy.ndarray` Standard deviation.
Below is the the instruction that describes the task: ### Input: Calculate the standard deviation as a function of G/G_max. Equation 7.29 from Darendeli (2001). Parameters ---------- mod_reduc : array_like Modulus reduction values. Returns ------- ...
def create(self, ignore=None): """Yield tuple with created index name and responses from a client.""" ignore = ignore or [] def _create(tree_or_filename, alias=None): """Create indices and aliases by walking DFS.""" # Iterate over aliases: for name, value in ...
Yield tuple with created index name and responses from a client.
Below is the the instruction that describes the task: ### Input: Yield tuple with created index name and responses from a client. ### Response: def create(self, ignore=None): """Yield tuple with created index name and responses from a client.""" ignore = ignore or [] def _create(tree_or_fi...
def _restore_clipboard_text(self, backup: str): """Restore the clipboard content.""" # Pasting takes some time, so wait a bit before restoring the content. Otherwise the restore is done before # the pasting happens, causing the backup to be pasted instead of the desired clipboard content. ...
Restore the clipboard content.
Below is the the instruction that describes the task: ### Input: Restore the clipboard content. ### Response: def _restore_clipboard_text(self, backup: str): """Restore the clipboard content.""" # Pasting takes some time, so wait a bit before restoring the content. Otherwise the restore is done bef...
def get_grade_entry_admin_session(self): """Gets the ``OsidSession`` associated with the grade entry administration service. return: (osid.grading.GradeEntryAdminSession) - a ``GradeEntryAdminSession`` raise: OperationFailed - unable to complete request raise: Unimplem...
Gets the ``OsidSession`` associated with the grade entry administration service. return: (osid.grading.GradeEntryAdminSession) - a ``GradeEntryAdminSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_grade_entry_admin()`` is ...
Below is the the instruction that describes the task: ### Input: Gets the ``OsidSession`` associated with the grade entry administration service. return: (osid.grading.GradeEntryAdminSession) - a ``GradeEntryAdminSession`` raise: OperationFailed - unable to complete request ...
def jdn_to_gdate(jdn): """ Convert from the Julian day to the Gregorian day. Algorithm from 'Julian and Gregorian Day Numbers' by Peter Meyer. Return: day, month, year """ # pylint: disable=invalid-name # The algorithm is a verbatim copy from Peter Meyer's article # No explanation in t...
Convert from the Julian day to the Gregorian day. Algorithm from 'Julian and Gregorian Day Numbers' by Peter Meyer. Return: day, month, year
Below is the the instruction that describes the task: ### Input: Convert from the Julian day to the Gregorian day. Algorithm from 'Julian and Gregorian Day Numbers' by Peter Meyer. Return: day, month, year ### Response: def jdn_to_gdate(jdn): """ Convert from the Julian day to the Gregorian day. ...
def merge(args): """ %prog merge protein-quartets registry LOST Merge protein quartets table with dna quartets registry. This is specific to the napus project. """ from jcvi.formats.base import DictFile p = OptionParser(merge.__doc__) opts, args = p.parse_args(args) if len(args) !...
%prog merge protein-quartets registry LOST Merge protein quartets table with dna quartets registry. This is specific to the napus project.
Below is the the instruction that describes the task: ### Input: %prog merge protein-quartets registry LOST Merge protein quartets table with dna quartets registry. This is specific to the napus project. ### Response: def merge(args): """ %prog merge protein-quartets registry LOST Merge prote...
def shell(self, term='xterm'): """ Start an interactive shell session This method invokes a shell on the remote SSH server and proxies traffic to/from both peers. You must connect to a SSH server using ssh_connect() prior to starting the session. """ channel = s...
Start an interactive shell session This method invokes a shell on the remote SSH server and proxies traffic to/from both peers. You must connect to a SSH server using ssh_connect() prior to starting the session.
Below is the the instruction that describes the task: ### Input: Start an interactive shell session This method invokes a shell on the remote SSH server and proxies traffic to/from both peers. You must connect to a SSH server using ssh_connect() prior to starting the session. ### R...
def lookup_controller(obj, remainder, request=None): ''' Traverses the requested url path and returns the appropriate controller object, including default routes. Handles common errors gracefully. ''' if request is None: warnings.warn( ( "The function signatu...
Traverses the requested url path and returns the appropriate controller object, including default routes. Handles common errors gracefully.
Below is the the instruction that describes the task: ### Input: Traverses the requested url path and returns the appropriate controller object, including default routes. Handles common errors gracefully. ### Response: def lookup_controller(obj, remainder, request=None): ''' Traverses the requeste...
def add_event(self, event): """ Add a new event and notify subscribers. event -- the event that occurred """ self.events.append(event) self.event_notify(event)
Add a new event and notify subscribers. event -- the event that occurred
Below is the the instruction that describes the task: ### Input: Add a new event and notify subscribers. event -- the event that occurred ### Response: def add_event(self, event): """ Add a new event and notify subscribers. event -- the event that occurred """ self...
def __xinclude_lxml(target, source, env): """ Resolving XIncludes, using the lxml module. """ from lxml import etree doc = etree.parse(str(source[0])) doc.xinclude() try: doc.write(str(target[0]), xml_declaration=True, encoding="UTF-8", pretty_print=True) ...
Resolving XIncludes, using the lxml module.
Below is the the instruction that describes the task: ### Input: Resolving XIncludes, using the lxml module. ### Response: def __xinclude_lxml(target, source, env): """ Resolving XIncludes, using the lxml module. """ from lxml import etree doc = etree.parse(str(source[0])) doc.xinclude...
def _get_adj_list_directional(self, umis, counts): ''' identify all umis within the hamming distance threshold and where the counts of the first umi is > (2 * second umi counts)-1''' adj_list = {umi: [] for umi in umis} if self.fuzzy_match: for umi1 in umis: ...
identify all umis within the hamming distance threshold and where the counts of the first umi is > (2 * second umi counts)-1
Below is the the instruction that describes the task: ### Input: identify all umis within the hamming distance threshold and where the counts of the first umi is > (2 * second umi counts)-1 ### Response: def _get_adj_list_directional(self, umis, counts): ''' identify all umis within the hamming dis...
def __generate_location(self): """ Reset the location of the cloud once it has left the viewable area of the screen. """ screen_width = world.get_backbuffer_size().X self.movement_speed = random.randrange(10, 25) # This line of code places the cloud to the right of the v...
Reset the location of the cloud once it has left the viewable area of the screen.
Below is the the instruction that describes the task: ### Input: Reset the location of the cloud once it has left the viewable area of the screen. ### Response: def __generate_location(self): """ Reset the location of the cloud once it has left the viewable area of the screen. """ s...
def write_rtt(jlink): """Writes kayboard input to JLink RTT buffer #0. This method is a loop that blocks waiting on stdin. When enter is pressed, LF and NUL bytes are added to the input and transmitted as a byte list. If the JLink is disconnected, it will exit gracefully. If any other exceptions ar...
Writes kayboard input to JLink RTT buffer #0. This method is a loop that blocks waiting on stdin. When enter is pressed, LF and NUL bytes are added to the input and transmitted as a byte list. If the JLink is disconnected, it will exit gracefully. If any other exceptions are raised, they will be caught...
Below is the the instruction that describes the task: ### Input: Writes kayboard input to JLink RTT buffer #0. This method is a loop that blocks waiting on stdin. When enter is pressed, LF and NUL bytes are added to the input and transmitted as a byte list. If the JLink is disconnected, it will exit gr...
def __is_valid_value_for_arg(self, arg, value, check_extension=True): """Check if value is allowed for arg Some commands only allow a limited set of values. The method always returns True for methods that do not provide such a set. :param arg: the argument's name :param...
Check if value is allowed for arg Some commands only allow a limited set of values. The method always returns True for methods that do not provide such a set. :param arg: the argument's name :param value: the value to check :param check_extension: check if value require...
Below is the the instruction that describes the task: ### Input: Check if value is allowed for arg Some commands only allow a limited set of values. The method always returns True for methods that do not provide such a set. :param arg: the argument's name :param value: the ...
def calc_point_distance_vary(self, chi_coords, point_fupper, mus): """ Calculate distance between point and the bank allowing the metric to vary based on varying upper frequency cutoff. Slower than calc_point_distance, but more reliable when upper frequency cutoff can change a lo...
Calculate distance between point and the bank allowing the metric to vary based on varying upper frequency cutoff. Slower than calc_point_distance, but more reliable when upper frequency cutoff can change a lot. Parameters ----------- chi_coords : numpy.array ...
Below is the the instruction that describes the task: ### Input: Calculate distance between point and the bank allowing the metric to vary based on varying upper frequency cutoff. Slower than calc_point_distance, but more reliable when upper frequency cutoff can change a lot. Parame...
def initializable(self): """True if the Slot is initializable.""" return bool(lib.EnvSlotInitableP(self._env, self._cls, self._name))
True if the Slot is initializable.
Below is the the instruction that describes the task: ### Input: True if the Slot is initializable. ### Response: def initializable(self): """True if the Slot is initializable.""" return bool(lib.EnvSlotInitableP(self._env, self._cls, self._name))
def transform_op(self, op, value): """For comparisons, if the value is None (null), the '=' operator must be replaced with ' is ' and the '!=' operator must be replaced with ' is not '. This function handles that conversion. It's up to the caller to call this function only on comparisons and not on assignme...
For comparisons, if the value is None (null), the '=' operator must be replaced with ' is ' and the '!=' operator must be replaced with ' is not '. This function handles that conversion. It's up to the caller to call this function only on comparisons and not on assignments.
Below is the the instruction that describes the task: ### Input: For comparisons, if the value is None (null), the '=' operator must be replaced with ' is ' and the '!=' operator must be replaced with ' is not '. This function handles that conversion. It's up to the caller to call this function only on comp...
def get_unset_cache(self): """return : returns a tuple (num_of_not_None_caches, [list of unset caches endpoint]) """ caches = [] if self._cached_api_global_response is None: caches.append('global') if self._cached_api_ticker_response is None: caches.append...
return : returns a tuple (num_of_not_None_caches, [list of unset caches endpoint])
Below is the the instruction that describes the task: ### Input: return : returns a tuple (num_of_not_None_caches, [list of unset caches endpoint]) ### Response: def get_unset_cache(self): """return : returns a tuple (num_of_not_None_caches, [list of unset caches endpoint]) """ caches = [] ...
def remove_out_of_image(self, fully=True, partly=False): """ Remove all polygons that are fully or partially outside of the image. Parameters ---------- fully : bool, optional Whether to remove polygons that are fully outside of the image. partly : bool, opt...
Remove all polygons that are fully or partially outside of the image. Parameters ---------- fully : bool, optional Whether to remove polygons that are fully outside of the image. partly : bool, optional Whether to remove polygons that are partially outside of th...
Below is the the instruction that describes the task: ### Input: Remove all polygons that are fully or partially outside of the image. Parameters ---------- fully : bool, optional Whether to remove polygons that are fully outside of the image. partly : bool, optional ...
def reduce(coro, iterable, initializer=None, limit=1, right=False, loop=None): """ Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value. Reduction will be executed sequentially without concurrency, so passed values...
Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value. Reduction will be executed sequentially without concurrency, so passed values would be in order. This function is the asynchronous coroutine equivalent to Python s...
Below is the the instruction that describes the task: ### Input: Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value. Reduction will be executed sequentially without concurrency, so passed values would be in order. ...
def add_cli_summarize(main: click.Group) -> click.Group: # noqa: D202 """Add a ``summarize`` command to main :mod:`click` function.""" @main.command() @click.pass_obj def summarize(manager: AbstractManager): """Summarize the contents of the database.""" if not manager.is_populated(): ...
Add a ``summarize`` command to main :mod:`click` function.
Below is the the instruction that describes the task: ### Input: Add a ``summarize`` command to main :mod:`click` function. ### Response: def add_cli_summarize(main: click.Group) -> click.Group: # noqa: D202 """Add a ``summarize`` command to main :mod:`click` function.""" @main.command() @click.pass_...
def get_elements(self, tag_name, attribute, with_namespace=True): """ Deprecated: use `get_all_attribute_value()` instead Return elements in xml files which match with the tag name and the specific attribute :param tag_name: a string which specify the tag name :param attribute: a...
Deprecated: use `get_all_attribute_value()` instead Return elements in xml files which match with the tag name and the specific attribute :param tag_name: a string which specify the tag name :param attribute: a string which specify the attribute
Below is the the instruction that describes the task: ### Input: Deprecated: use `get_all_attribute_value()` instead Return elements in xml files which match with the tag name and the specific attribute :param tag_name: a string which specify the tag name :param attribute: a string which spe...
def ModuleHelp(self, module): """Describe the key flags of a module. Args: module: A module object or a module name (a string). Returns: string describing the key flags of a module. """ helplist = [] self.__RenderOurModuleKeyFlags(module, helplist) return '\n'.join(helplist)
Describe the key flags of a module. Args: module: A module object or a module name (a string). Returns: string describing the key flags of a module.
Below is the the instruction that describes the task: ### Input: Describe the key flags of a module. Args: module: A module object or a module name (a string). Returns: string describing the key flags of a module. ### Response: def ModuleHelp(self, module): """Describe the key flags of a ...
def spin(compound, theta, around): """Rotate a compound in place around an arbitrary vector. Parameters ---------- compound : mb.Compound The compound being rotated. theta : float The angle by which to rotate the compound, in radians. around : np.ndarray, shape=(3,), dtype=float...
Rotate a compound in place around an arbitrary vector. Parameters ---------- compound : mb.Compound The compound being rotated. theta : float The angle by which to rotate the compound, in radians. around : np.ndarray, shape=(3,), dtype=float The axis about which to spin the ...
Below is the the instruction that describes the task: ### Input: Rotate a compound in place around an arbitrary vector. Parameters ---------- compound : mb.Compound The compound being rotated. theta : float The angle by which to rotate the compound, in radians. around : np.ndarr...
def format_metadata_to_key(key_metadata): """ <Purpose> Construct a key dictionary (e.g., securesystemslib.formats.RSAKEY_SCHEMA) according to the keytype of 'key_metadata'. The dict returned by this function has the exact format as the dict returned by one of the key generations functions, like ge...
<Purpose> Construct a key dictionary (e.g., securesystemslib.formats.RSAKEY_SCHEMA) according to the keytype of 'key_metadata'. The dict returned by this function has the exact format as the dict returned by one of the key generations functions, like generate_ed25519_key(). The dict returned has t...
Below is the the instruction that describes the task: ### Input: <Purpose> Construct a key dictionary (e.g., securesystemslib.formats.RSAKEY_SCHEMA) according to the keytype of 'key_metadata'. The dict returned by this function has the exact format as the dict returned by one of the key generations...
def _request(request, request_fallback=None): ''' Extract request fields wherever they may come from: GET, POST, forms, fallback ''' # Use lambdas to avoid evaluating bottle.request.* which may throw an Error all_dicts = [ lambda: request.json, lambda: request.forms, ...
Extract request fields wherever they may come from: GET, POST, forms, fallback
Below is the the instruction that describes the task: ### Input: Extract request fields wherever they may come from: GET, POST, forms, fallback ### Response: def _request(request, request_fallback=None): ''' Extract request fields wherever they may come from: GET, POST, forms, fallback ''' # Use la...
def resizeEvent(self, event): """Schedules an item layout if resize mode is \"adjust\". Somehow this is needed for correctly scaling down items. The reason this was reimplemented was the CommentDelegate. :param event: the resize event :type event: QtCore.QEvent :returns...
Schedules an item layout if resize mode is \"adjust\". Somehow this is needed for correctly scaling down items. The reason this was reimplemented was the CommentDelegate. :param event: the resize event :type event: QtCore.QEvent :returns: None :rtype: None :rais...
Below is the the instruction that describes the task: ### Input: Schedules an item layout if resize mode is \"adjust\". Somehow this is needed for correctly scaling down items. The reason this was reimplemented was the CommentDelegate. :param event: the resize event :type event: Qt...
def _getFromTime(self, atDate=None): """ Time that the event starts (in the local time zone). """ return getLocalTime(self.date_from, self.time_from, self.tz)
Time that the event starts (in the local time zone).
Below is the the instruction that describes the task: ### Input: Time that the event starts (in the local time zone). ### Response: def _getFromTime(self, atDate=None): """ Time that the event starts (in the local time zone). """ return getLocalTime(self.date_from, self.time_from, s...
def linkify_with_escalations(self, escalations): """ Link with escalations :param escalations: all escalations object :type escalations: alignak.objects.escalation.Escalations :return: None """ for i in self: if not hasattr(i, 'escalations'): ...
Link with escalations :param escalations: all escalations object :type escalations: alignak.objects.escalation.Escalations :return: None
Below is the the instruction that describes the task: ### Input: Link with escalations :param escalations: all escalations object :type escalations: alignak.objects.escalation.Escalations :return: None ### Response: def linkify_with_escalations(self, escalations): """ Link ...
def get_tagged_albums(self, tag, limit=None, cacheable=True): """Returns the albums tagged by a user.""" params = self._get_params() params["tag"] = tag params["taggingtype"] = "album" if limit: params["limit"] = limit doc = self._request(self.ws_prefix + ".g...
Returns the albums tagged by a user.
Below is the the instruction that describes the task: ### Input: Returns the albums tagged by a user. ### Response: def get_tagged_albums(self, tag, limit=None, cacheable=True): """Returns the albums tagged by a user.""" params = self._get_params() params["tag"] = tag params["taggi...
def _find_best_in_population(population, values): """Finds the population member with the lowest value.""" best_value = tf.math.reduce_min(input_tensor=values) best_index = tf.where(tf.math.equal(values, best_value))[0, 0] return ([population_part[best_index] for population_part in population], best_...
Finds the population member with the lowest value.
Below is the the instruction that describes the task: ### Input: Finds the population member with the lowest value. ### Response: def _find_best_in_population(population, values): """Finds the population member with the lowest value.""" best_value = tf.math.reduce_min(input_tensor=values) best_index = tf.whe...
def working_cycletime(start, end, workday_start=datetime.timedelta(hours=0), workday_end=datetime.timedelta(hours=24)): """ Get the working time between a beginning and an end point subtracting out non-office time """ def clamp(t, start, end): "Return 't' clamped to the range ['start', 'end']" ...
Get the working time between a beginning and an end point subtracting out non-office time
Below is the the instruction that describes the task: ### Input: Get the working time between a beginning and an end point subtracting out non-office time ### Response: def working_cycletime(start, end, workday_start=datetime.timedelta(hours=0), workday_end=datetime.timedelta(hours=24)): """ Get the workin...
def andrews_curves(frame, class_column, ax=None, samples=200, color=None, colormap=None, **kwds): """ Generate a matplotlib plot of Andrews curves, for visualising clusters of multivariate data. Andrews curves have the functional form: f(t) = x_1/sqrt(2) + x_2 sin(t) + x_3 cos(t...
Generate a matplotlib plot of Andrews curves, for visualising clusters of multivariate data. Andrews curves have the functional form: f(t) = x_1/sqrt(2) + x_2 sin(t) + x_3 cos(t) + x_4 sin(2t) + x_5 cos(2t) + ... Where x coefficients correspond to the values of each dimension and t is ...
Below is the the instruction that describes the task: ### Input: Generate a matplotlib plot of Andrews curves, for visualising clusters of multivariate data. Andrews curves have the functional form: f(t) = x_1/sqrt(2) + x_2 sin(t) + x_3 cos(t) + x_4 sin(2t) + x_5 cos(2t) + ... Where x ...
def check_psd(matrix, tolerance=1e-6): """ A square matrix is PSD if all eigenvalues of its Hermitian part are non- negative. The Hermitian part is given by (self + M*)/2, where M* is the complex conjugate transpose of M """ hermitian = (matrix + matrix.T.conjugate()) / 2 eigenvalues = np.linalg.ei...
A square matrix is PSD if all eigenvalues of its Hermitian part are non- negative. The Hermitian part is given by (self + M*)/2, where M* is the complex conjugate transpose of M
Below is the the instruction that describes the task: ### Input: A square matrix is PSD if all eigenvalues of its Hermitian part are non- negative. The Hermitian part is given by (self + M*)/2, where M* is the complex conjugate transpose of M ### Response: def check_psd(matrix, tolerance=1e-6): """ A s...
def summarize(self, text, topics=4, length=5, binary_matrix=True, topic_sigma_threshold=0.5): """ Implements the method of latent semantic analysis described by Steinberger and Jezek in the paper: J. Steinberger and K. Jezek (2004). Using latent semantic analysis in text summarization and summa...
Implements the method of latent semantic analysis described by Steinberger and Jezek in the paper: J. Steinberger and K. Jezek (2004). Using latent semantic analysis in text summarization and summary evaluation. Proc. ISIM ’04, pp. 93–100. :param text: a string of text to be summarized, path t...
Below is the the instruction that describes the task: ### Input: Implements the method of latent semantic analysis described by Steinberger and Jezek in the paper: J. Steinberger and K. Jezek (2004). Using latent semantic analysis in text summarization and summary evaluation. Proc. ISIM ’04, pp. 93...
def grab_bulbs(host, token=None): """Grab XML, then add all bulbs to a dict. Removes room functionality""" xml = grab_xml(host, token) bulbs = {} for room in xml: for device in room['device']: bulbs[int(device['did'])] = device return bulbs
Grab XML, then add all bulbs to a dict. Removes room functionality
Below is the the instruction that describes the task: ### Input: Grab XML, then add all bulbs to a dict. Removes room functionality ### Response: def grab_bulbs(host, token=None): """Grab XML, then add all bulbs to a dict. Removes room functionality""" xml = grab_xml(host, token) bulbs = {} for roo...
def main(args): """ %prog newicktree Plot Newick formatted tree. The gene structure can be plotted along if --gffdir is given. The gff file needs to be `genename.gff`. If --sizes is on, also show the number of amino acids. With --barcode a mapping file can be provided to convert seq names to ...
%prog newicktree Plot Newick formatted tree. The gene structure can be plotted along if --gffdir is given. The gff file needs to be `genename.gff`. If --sizes is on, also show the number of amino acids. With --barcode a mapping file can be provided to convert seq names to eg. species names, useful...
Below is the the instruction that describes the task: ### Input: %prog newicktree Plot Newick formatted tree. The gene structure can be plotted along if --gffdir is given. The gff file needs to be `genename.gff`. If --sizes is on, also show the number of amino acids. With --barcode a mapping file ...
def QA_indicator_BOLL(DataFrame, N=20, P=2): '布林线' C = DataFrame['close'] boll = MA(C, N) UB = boll + P * STD(C, N) LB = boll - P * STD(C, N) DICT = {'BOLL': boll, 'UB': UB, 'LB': LB} return pd.DataFrame(DICT)
布林线
Below is the the instruction that describes the task: ### Input: 布林线 ### Response: def QA_indicator_BOLL(DataFrame, N=20, P=2): '布林线' C = DataFrame['close'] boll = MA(C, N) UB = boll + P * STD(C, N) LB = boll - P * STD(C, N) DICT = {'BOLL': boll, 'UB': UB, 'LB': LB} return pd.DataFrame...
def get_git_repositories_activity_metrics(self, project, from_date, aggregation_type, skip, top): """GetGitRepositoriesActivityMetrics. [Preview API] Retrieves git activity metrics for repositories matching a specified criteria. :param str project: Project ID or project name :param datet...
GetGitRepositoriesActivityMetrics. [Preview API] Retrieves git activity metrics for repositories matching a specified criteria. :param str project: Project ID or project name :param datetime from_date: Date from which, the trends are to be fetched. :param str aggregation_type: Bucket siz...
Below is the the instruction that describes the task: ### Input: GetGitRepositoriesActivityMetrics. [Preview API] Retrieves git activity metrics for repositories matching a specified criteria. :param str project: Project ID or project name :param datetime from_date: Date from which, the tren...
def clone(self, *args, **overrides): """ Returns a clone of the object with matching parameter values containing the specified args and kwargs. """ link = overrides.pop('link', True) settings = dict(self.get_param_values(), **overrides) if 'id' not in settings: ...
Returns a clone of the object with matching parameter values containing the specified args and kwargs.
Below is the the instruction that describes the task: ### Input: Returns a clone of the object with matching parameter values containing the specified args and kwargs. ### Response: def clone(self, *args, **overrides): """ Returns a clone of the object with matching parameter values ...
def _get_popularity_baseline(self): """ Returns a new popularity model matching the data set this model was trained with. Can be used for comparison purposes. """ response = self.__proxy__.get_popularity_baseline() from .popularity_recommender import PopularityRecommen...
Returns a new popularity model matching the data set this model was trained with. Can be used for comparison purposes.
Below is the the instruction that describes the task: ### Input: Returns a new popularity model matching the data set this model was trained with. Can be used for comparison purposes. ### Response: def _get_popularity_baseline(self): """ Returns a new popularity model matching the data se...
def setCheckedItems(self, items): """ Returns the checked items for this combobox. :return items | [<str>, ..] """ if not self.isCheckable(): return model = self.model() for i in range(self.count()): item_text = self.i...
Returns the checked items for this combobox. :return items | [<str>, ..]
Below is the the instruction that describes the task: ### Input: Returns the checked items for this combobox. :return items | [<str>, ..] ### Response: def setCheckedItems(self, items): """ Returns the checked items for this combobox. :return items | [<str>...
def get_binary_dist(self, requirement): """ Get or create a cached binary distribution archive. :param requirement: A :class:`.Requirement` object. :returns: An iterable of tuples with two values each: A :class:`tarfile.TarInfo` object and a file-like object. ...
Get or create a cached binary distribution archive. :param requirement: A :class:`.Requirement` object. :returns: An iterable of tuples with two values each: A :class:`tarfile.TarInfo` object and a file-like object. Gets the cached binary distribution that was previously buil...
Below is the the instruction that describes the task: ### Input: Get or create a cached binary distribution archive. :param requirement: A :class:`.Requirement` object. :returns: An iterable of tuples with two values each: A :class:`tarfile.TarInfo` object and a file-like object. ...
def row_col_maker(app, fromdocname, all_needs, need_info, need_key, make_ref=False, ref_lookup=False, prefix=''): """ Creates and returns a column. :param app: current sphinx app :param fromdocname: current document :param all_needs: Dictionary of all need objects :param need_info: need_info ob...
Creates and returns a column. :param app: current sphinx app :param fromdocname: current document :param all_needs: Dictionary of all need objects :param need_info: need_info object, which stores all related need data :param need_key: The key to access the needed data from need_info :param make...
Below is the the instruction that describes the task: ### Input: Creates and returns a column. :param app: current sphinx app :param fromdocname: current document :param all_needs: Dictionary of all need objects :param need_info: need_info object, which stores all related need data :param need_...
def at_time(self, time, nearest_sample=False): """ Return the value at the specified gps time """ if nearest_sample: time += self.delta_t / 2.0 return self[int((time-self.start_time)*self.sample_rate)]
Return the value at the specified gps time
Below is the the instruction that describes the task: ### Input: Return the value at the specified gps time ### Response: def at_time(self, time, nearest_sample=False): """ Return the value at the specified gps time """ if nearest_sample: time += self.delta_t / 2.0 retur...
def route_request(self, request_json, metadata=None): ''' Route the request object to the right handler function ''' request = Request(request_json) request.metadata = metadata # add reprompt handler or some such for default? handler_fn = self._handlers[self._default] # Set defa...
Route the request object to the right handler function
Below is the the instruction that describes the task: ### Input: Route the request object to the right handler function ### Response: def route_request(self, request_json, metadata=None): ''' Route the request object to the right handler function ''' request = Request(request_json) request...
def find_commands(command_dir: str) -> List[str]: """ Get all command names in the a folder :return: List of commands names """ if not command_dir: return [] return [name for _, name, is_pkg in pkgutil.iter_modules([command_dir]) if not is_pkg and not name.startswith('_')]
Get all command names in the a folder :return: List of commands names
Below is the the instruction that describes the task: ### Input: Get all command names in the a folder :return: List of commands names ### Response: def find_commands(command_dir: str) -> List[str]: """ Get all command names in the a folder :return: List of commands names """ if not comma...
def loadbinary(fname): """ Load a numpy binary file or archive created by tabular.io.savebinary. Load a numpy binary file (``.npy``) or archive (``.npz``) created by :func:`tabular.io.savebinary`. The data and associated data type (e.g. `dtype`, including if given, column names) are load...
Load a numpy binary file or archive created by tabular.io.savebinary. Load a numpy binary file (``.npy``) or archive (``.npz``) created by :func:`tabular.io.savebinary`. The data and associated data type (e.g. `dtype`, including if given, column names) are loaded and reconstituted. If `fnam...
Below is the the instruction that describes the task: ### Input: Load a numpy binary file or archive created by tabular.io.savebinary. Load a numpy binary file (``.npy``) or archive (``.npz``) created by :func:`tabular.io.savebinary`. The data and associated data type (e.g. `dtype`, including if ...
def add_attribute_model(self, name, # type: str attr, # type: AttributeModel writeable_func=None, # type: Optional[Callable] ): # type: (...) -> AttributeModel """Register a pre-existing At...
Register a pre-existing AttributeModel to be added to the Block
Below is the the instruction that describes the task: ### Input: Register a pre-existing AttributeModel to be added to the Block ### Response: def add_attribute_model(self, name, # type: str attr, # type: AttributeModel writeable...
def queue_instances(instances): ''' Queue a set of instances to be provisioned later. Expects a list. Currently this only queries node data, and then places it in the cloud cache (if configured). If the salt-cloud-reactor is being used, these instances will be automatically provisioned using that. ...
Queue a set of instances to be provisioned later. Expects a list. Currently this only queries node data, and then places it in the cloud cache (if configured). If the salt-cloud-reactor is being used, these instances will be automatically provisioned using that. For more information about the salt-clo...
Below is the the instruction that describes the task: ### Input: Queue a set of instances to be provisioned later. Expects a list. Currently this only queries node data, and then places it in the cloud cache (if configured). If the salt-cloud-reactor is being used, these instances will be automatically...
def _load_entities(self): """ Must load all the entities it needs from cache, and return ``False`` if it could not find all of them. """ if not self._chat_peer: return True # Nothing to load (e.g. MessageDeleted) self._chat, self._input_chat = self._get_enti...
Must load all the entities it needs from cache, and return ``False`` if it could not find all of them.
Below is the the instruction that describes the task: ### Input: Must load all the entities it needs from cache, and return ``False`` if it could not find all of them. ### Response: def _load_entities(self): """ Must load all the entities it needs from cache, and return ``False`` if...
def print_stats(correctness, confidence, name): """ Prints out accuracy, coverage, etc. statistics :param correctness: ndarray One bool per example specifying whether it was correctly classified :param confidence: ndarray The probability associated with each prediction :param name: str The name of...
Prints out accuracy, coverage, etc. statistics :param correctness: ndarray One bool per example specifying whether it was correctly classified :param confidence: ndarray The probability associated with each prediction :param name: str The name of this type of data (e.g. "clean", "MaxConfidence")
Below is the the instruction that describes the task: ### Input: Prints out accuracy, coverage, etc. statistics :param correctness: ndarray One bool per example specifying whether it was correctly classified :param confidence: ndarray The probability associated with each prediction :param name: str ...
def origin_central_asia(origin): """\ Returns if the origin is located in Central Asia. Holds true for the following countries: * Afghanistan * Kazakhstan * Kyrgyzstan * Tajikistan * Turkmenistan * Uzbekistan `origin` The origin to check. """...
\ Returns if the origin is located in Central Asia. Holds true for the following countries: * Afghanistan * Kazakhstan * Kyrgyzstan * Tajikistan * Turkmenistan * Uzbekistan `origin` The origin to check.
Below is the the instruction that describes the task: ### Input: \ Returns if the origin is located in Central Asia. Holds true for the following countries: * Afghanistan * Kazakhstan * Kyrgyzstan * Tajikistan * Turkmenistan * Uzbekistan `origin` ...
def derivatives(self, x, y, Rs, theta_Rs, e1, e2, center_x=0, center_y=0): """ returns df/dx and df/dy of the function (integral of NFW) """ phi_G, q = param_util.ellipticity2phi_q(e1, e2) x_shift = x - center_x y_shift = y - center_y cos_phi = np.cos(phi_G) ...
returns df/dx and df/dy of the function (integral of NFW)
Below is the the instruction that describes the task: ### Input: returns df/dx and df/dy of the function (integral of NFW) ### Response: def derivatives(self, x, y, Rs, theta_Rs, e1, e2, center_x=0, center_y=0): """ returns df/dx and df/dy of the function (integral of NFW) """ phi_G...
def exception(self, timeout=None): """Return the exception raised by the call, if any. This blocks until the message has successfully been published, and returns the exception. If the call succeeded, return None. Args: timeout (Union[int, float]): The number of seconds befo...
Return the exception raised by the call, if any. This blocks until the message has successfully been published, and returns the exception. If the call succeeded, return None. Args: timeout (Union[int, float]): The number of seconds before this call times out and rai...
Below is the the instruction that describes the task: ### Input: Return the exception raised by the call, if any. This blocks until the message has successfully been published, and returns the exception. If the call succeeded, return None. Args: timeout (Union[int, float]): The...
def add_host(host): """ Put your host information in the prefix object. """ p = new_prefix() p.prefix = str(host['ipaddr']) p.type = "host" p.description = host['description'] p.node = host['fqdn'] p.avps = {} # Use remaining data from ipplan to populate comment field. if 'additiona...
Put your host information in the prefix object.
Below is the the instruction that describes the task: ### Input: Put your host information in the prefix object. ### Response: def add_host(host): """ Put your host information in the prefix object. """ p = new_prefix() p.prefix = str(host['ipaddr']) p.type = "host" p.description = host['descri...
def build_vocab(self, *args, **kwargs): """Construct the Vocab object for this field from one or more datasets. Arguments: Positional arguments: Dataset objects or other iterable data sources from which to construct the Vocab object that represents the set of...
Construct the Vocab object for this field from one or more datasets. Arguments: Positional arguments: Dataset objects or other iterable data sources from which to construct the Vocab object that represents the set of possible values for this field. If ...
Below is the the instruction that describes the task: ### Input: Construct the Vocab object for this field from one or more datasets. Arguments: Positional arguments: Dataset objects or other iterable data sources from which to construct the Vocab object that rep...
def update_asset_ddo(self, did, ddo): """ Update the ddo of a did already registered. :param did: Asset DID string :param ddo: DDO instance :return: API response (depends on implementation) """ response = self.requests_session.put(f'{self.url}/{did}', data=ddo.as...
Update the ddo of a did already registered. :param did: Asset DID string :param ddo: DDO instance :return: API response (depends on implementation)
Below is the the instruction that describes the task: ### Input: Update the ddo of a did already registered. :param did: Asset DID string :param ddo: DDO instance :return: API response (depends on implementation) ### Response: def update_asset_ddo(self, did, ddo): """ Updat...
def create_group(self, name): """Create a new group. Args: name (string): Name of the group to create. Raises: requests.HTTPError on failure. """ self.service.create_group( name, self.url_prefix, self.auth, self.session, self.sess...
Create a new group. Args: name (string): Name of the group to create. Raises: requests.HTTPError on failure.
Below is the the instruction that describes the task: ### Input: Create a new group. Args: name (string): Name of the group to create. Raises: requests.HTTPError on failure. ### Response: def create_group(self, name): """Create a new group. Args: ...
def handle_relative(self, event): """Relative mouse movement.""" delta_x, delta_y = self._get_relative(event) if delta_x: self.events.append( self.emulate_rel(0x00, delta_x, self.timeval)) if de...
Relative mouse movement.
Below is the the instruction that describes the task: ### Input: Relative mouse movement. ### Response: def handle_relative(self, event): """Relative mouse movement.""" delta_x, delta_y = self._get_relative(event) if delta_x: self.events.append( self.emulate_rel(...
def pretty_str(self, indent=0): """Return a human-readable string representation of this object. Kwargs: indent (int): The amount of spaces to use as indentation. """ spaces = ' ' * indent pretty = '{}namespace {}:\n'.format(spaces, self.name) pretty += '\n\n...
Return a human-readable string representation of this object. Kwargs: indent (int): The amount of spaces to use as indentation.
Below is the the instruction that describes the task: ### Input: Return a human-readable string representation of this object. Kwargs: indent (int): The amount of spaces to use as indentation. ### Response: def pretty_str(self, indent=0): """Return a human-readable string representatio...
def _parse_proc_pid_cgroup(content): """ Parse a /proc/*/cgroup file into tuples of (subsystem,cgroup). @param content: An iterable over the lines of the file. @return: a generator of tuples """ for ownCgroup in content: #each line is "id:subsystem,subsystem:path" ownCgroup = own...
Parse a /proc/*/cgroup file into tuples of (subsystem,cgroup). @param content: An iterable over the lines of the file. @return: a generator of tuples
Below is the the instruction that describes the task: ### Input: Parse a /proc/*/cgroup file into tuples of (subsystem,cgroup). @param content: An iterable over the lines of the file. @return: a generator of tuples ### Response: def _parse_proc_pid_cgroup(content): """ Parse a /proc/*/cgroup file i...
def find(file_node, dirs=ICON_DIRS, default_name=None, file_ext='.png'): """ Iterating all icon dirs, try to find a file called like the node's extension / mime subtype / mime type (in that order). For instance, for an MP3 file ("audio/mpeg"), this would look for: "mp3.png" / "au...
Iterating all icon dirs, try to find a file called like the node's extension / mime subtype / mime type (in that order). For instance, for an MP3 file ("audio/mpeg"), this would look for: "mp3.png" / "audio/mpeg.png" / "audio.png"
Below is the the instruction that describes the task: ### Input: Iterating all icon dirs, try to find a file called like the node's extension / mime subtype / mime type (in that order). For instance, for an MP3 file ("audio/mpeg"), this would look for: "mp3.png" / "audio/mpeg.png" / "audio.p...
def lookup_field_class(self, field, obj=None, default=None): """ Looks up any additional class we should include when rendering this field """ css = "" # is there a class specified for this field if field in self.field_config and 'class' in self.field_config[field]: ...
Looks up any additional class we should include when rendering this field
Below is the the instruction that describes the task: ### Input: Looks up any additional class we should include when rendering this field ### Response: def lookup_field_class(self, field, obj=None, default=None): """ Looks up any additional class we should include when rendering this field ...
def decode_timeseries_row(self, tsrow, tscols=None, convert_timestamp=False): """ Decodes a TsRow into a list :param tsrow: the protobuf TsRow to decode. :type tsrow: riak.pb.riak_ts_pb2.TsRow :param tscols: the protobuf TsColumn data to help decode...
Decodes a TsRow into a list :param tsrow: the protobuf TsRow to decode. :type tsrow: riak.pb.riak_ts_pb2.TsRow :param tscols: the protobuf TsColumn data to help decode. :type tscols: list :rtype list
Below is the the instruction that describes the task: ### Input: Decodes a TsRow into a list :param tsrow: the protobuf TsRow to decode. :type tsrow: riak.pb.riak_ts_pb2.TsRow :param tscols: the protobuf TsColumn data to help decode. :type tscols: list :rtype list ### Respon...
def _parse_total_magnetization(line, lines): """Parse the total magnetization, which is somewhat hidden""" toks = line.split() res = {"number of electrons": float(toks[3])} if len(toks) > 5: res["total magnetization"] = float(toks[5]) return res
Parse the total magnetization, which is somewhat hidden
Below is the the instruction that describes the task: ### Input: Parse the total magnetization, which is somewhat hidden ### Response: def _parse_total_magnetization(line, lines): """Parse the total magnetization, which is somewhat hidden""" toks = line.split() res = {"number of electrons": float(toks[...
def get_labels(self, depth=None): """ Returns a list with a copy of the labels in this cell. Parameters ---------- depth : integer or ``None`` If not ``None``, defines from how many reference levels to retrieve labels from. Returns ------...
Returns a list with a copy of the labels in this cell. Parameters ---------- depth : integer or ``None`` If not ``None``, defines from how many reference levels to retrieve labels from. Returns ------- out : list of ``Label`` List con...
Below is the the instruction that describes the task: ### Input: Returns a list with a copy of the labels in this cell. Parameters ---------- depth : integer or ``None`` If not ``None``, defines from how many reference levels to retrieve labels from. Returns...
def compare(array, other, op, ty_str): """ Performs passed-in comparison op between every element in the passed-in array and other, and returns an array of booleans. Args: array (WeldObject / Numpy.ndarray): Input array other (WeldObject / Numpy.ndarray): Second input array op (...
Performs passed-in comparison op between every element in the passed-in array and other, and returns an array of booleans. Args: array (WeldObject / Numpy.ndarray): Input array other (WeldObject / Numpy.ndarray): Second input array op (str): Op string used for element-wise comparison (=...
Below is the the instruction that describes the task: ### Input: Performs passed-in comparison op between every element in the passed-in array and other, and returns an array of booleans. Args: array (WeldObject / Numpy.ndarray): Input array other (WeldObject / Numpy.ndarray): Second input ...
def mean_length(infile, limit=None): '''Returns the mean length of the sequences in the input file. By default uses all sequences. To limit to the first N sequences, use limit=N''' total = 0 count = 0 seq_reader = sequences.file_reader(infile) for seq in seq_reader: total += len(seq) ...
Returns the mean length of the sequences in the input file. By default uses all sequences. To limit to the first N sequences, use limit=N
Below is the the instruction that describes the task: ### Input: Returns the mean length of the sequences in the input file. By default uses all sequences. To limit to the first N sequences, use limit=N ### Response: def mean_length(infile, limit=None): '''Returns the mean length of the sequences in the input ...
def get_file_extension(file_path): """ >>> get_file_extension("/a/b/c") '' >>> get_file_extension("/a/b.txt") 'txt' >>> get_file_extension("/a/b/c.tar.xz") 'xz' """ _ext = os.path.splitext(file_path)[-1] if _ext: return _ext[1:] if _ext.startswith('.') else _ext retu...
>>> get_file_extension("/a/b/c") '' >>> get_file_extension("/a/b.txt") 'txt' >>> get_file_extension("/a/b/c.tar.xz") 'xz'
Below is the the instruction that describes the task: ### Input: >>> get_file_extension("/a/b/c") '' >>> get_file_extension("/a/b.txt") 'txt' >>> get_file_extension("/a/b/c.tar.xz") 'xz' ### Response: def get_file_extension(file_path): """ >>> get_file_extension("/a/b/c") '' >>>...
def p_jsonpath_named_operator(self, p): "jsonpath : NAMED_OPERATOR" if p[1] == 'this': p[0] = This() elif p[1] == 'parent': p[0] = Parent() else: raise Exception('Unknown named operator `%s` at %s:%s' % (p[1], p.lineno(1), p.lexpos(1)))
jsonpath : NAMED_OPERATOR
Below is the the instruction that describes the task: ### Input: jsonpath : NAMED_OPERATOR ### Response: def p_jsonpath_named_operator(self, p): "jsonpath : NAMED_OPERATOR" if p[1] == 'this': p[0] = This() elif p[1] == 'parent': p[0] = Parent() else: ...
def sim(self, src, tar): """Return the prefix similarity of two strings. Prefix similarity is the ratio of the length of the shorter term that exactly matches the longer term to the length of the shorter term, beginning at the start of both terms. Parameters ---------- ...
Return the prefix similarity of two strings. Prefix similarity is the ratio of the length of the shorter term that exactly matches the longer term to the length of the shorter term, beginning at the start of both terms. Parameters ---------- src : str Source...
Below is the the instruction that describes the task: ### Input: Return the prefix similarity of two strings. Prefix similarity is the ratio of the length of the shorter term that exactly matches the longer term to the length of the shorter term, beginning at the start of both terms. ...
def delete_firewall_rule(self, server_uuid, firewall_rule_position): """ Delete a firewall rule based on a server uuid and rule position. """ url = '/server/{0}/firewall_rule/{1}'.format(server_uuid, firewall_rule_position) return self.request('DELETE', url)
Delete a firewall rule based on a server uuid and rule position.
Below is the the instruction that describes the task: ### Input: Delete a firewall rule based on a server uuid and rule position. ### Response: def delete_firewall_rule(self, server_uuid, firewall_rule_position): """ Delete a firewall rule based on a server uuid and rule position. """ ...
def executable_path(conn, executable): """ Remote validator that accepts a connection object to ensure that a certain executable is available returning its full path if so. Otherwise an exception with thorough details will be raised, informing the user that the executable was not found. """ ...
Remote validator that accepts a connection object to ensure that a certain executable is available returning its full path if so. Otherwise an exception with thorough details will be raised, informing the user that the executable was not found.
Below is the the instruction that describes the task: ### Input: Remote validator that accepts a connection object to ensure that a certain executable is available returning its full path if so. Otherwise an exception with thorough details will be raised, informing the user that the executable was not ...
def buffer_typechecks_and_display(self, call_id, payload): """Adds typecheck events to the buffer, and displays them right away. This is a workaround for this issue: https://github.com/ensime/ensime-server/issues/1616 """ self.buffer_typechecks(call_id, payload) self.edi...
Adds typecheck events to the buffer, and displays them right away. This is a workaround for this issue: https://github.com/ensime/ensime-server/issues/1616
Below is the the instruction that describes the task: ### Input: Adds typecheck events to the buffer, and displays them right away. This is a workaround for this issue: https://github.com/ensime/ensime-server/issues/1616 ### Response: def buffer_typechecks_and_display(self, call_id, payload): ...
def setCurrentAction(self, action): """ Sets the current action for this widget that highlights the size for this toolbar. :param action | <QAction> """ if action == self._currentAction: return self._currentAction = act...
Sets the current action for this widget that highlights the size for this toolbar. :param action | <QAction>
Below is the the instruction that describes the task: ### Input: Sets the current action for this widget that highlights the size for this toolbar. :param action | <QAction> ### Response: def setCurrentAction(self, action): """ Sets the current action for this wid...
def _get_all(self, *args, **kwargs): """If 'force' is in the headers, retrieve the list of keys from S3. Otherwise, use the list() function to retrieve the keys from MimicDB. """ headers = kwargs.get('headers', args[2] if len(args) > 2 else None) or dict() if 'force' in headers:...
If 'force' is in the headers, retrieve the list of keys from S3. Otherwise, use the list() function to retrieve the keys from MimicDB.
Below is the the instruction that describes the task: ### Input: If 'force' is in the headers, retrieve the list of keys from S3. Otherwise, use the list() function to retrieve the keys from MimicDB. ### Response: def _get_all(self, *args, **kwargs): """If 'force' is in the headers, retrieve the li...
def price_rounding(price, decimals=2): """Takes a decimal price and rounds to a number of decimal places""" try: exponent = D('.' + decimals * '0') except InvalidOperation: # Currencies with no decimal places, ex. JPY, HUF exponent = D() return price.quantize(exponent, rounding=R...
Takes a decimal price and rounds to a number of decimal places
Below is the the instruction that describes the task: ### Input: Takes a decimal price and rounds to a number of decimal places ### Response: def price_rounding(price, decimals=2): """Takes a decimal price and rounds to a number of decimal places""" try: exponent = D('.' + decimals * '0') excep...
def double_width(self, action): '''Enable/cancel doublewidth printing Args: action: Enable or disable doublewidth printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action. ''' if action == 'on': ...
Enable/cancel doublewidth printing Args: action: Enable or disable doublewidth printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action.
Below is the the instruction that describes the task: ### Input: Enable/cancel doublewidth printing Args: action: Enable or disable doublewidth printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action. ### Response: ...
def main(input_filename, songname, format, counter): """ Calculate the fingerprint hashses of the referenced audio file and save to disk as a pickle file """ # open the file & convert to wav song_data = AudioSegment.from_file(input_filename, format=format) song_data = song_data.set_channels...
Calculate the fingerprint hashses of the referenced audio file and save to disk as a pickle file
Below is the the instruction that describes the task: ### Input: Calculate the fingerprint hashses of the referenced audio file and save to disk as a pickle file ### Response: def main(input_filename, songname, format, counter): """ Calculate the fingerprint hashses of the referenced audio file and sav...
def control(self, on=[], off=[]): """ This method serves as the primary interaction point to the controls interface. - The 'on' and 'off' arguments can either be a list or a single string. This allows for both individual device control and batch controls. Note: ...
This method serves as the primary interaction point to the controls interface. - The 'on' and 'off' arguments can either be a list or a single string. This allows for both individual device control and batch controls. Note: Both the onlist and offlist are optional. ...
Below is the the instruction that describes the task: ### Input: This method serves as the primary interaction point to the controls interface. - The 'on' and 'off' arguments can either be a list or a single string. This allows for both individual device control and batch controls. ...
def build( src, requirements=None, local_package=None, config_file='config.yaml', profile_name=None, ): """Builds the file bundle. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_pa...
Builds the file bundle. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not availab...
Below is the the instruction that describes the task: ### Input: Builds the file bundle. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with sh...
def index(self, key): """ Return the index of the given item. :param key: :return: """ if isinstance(key, int): if 0 <= key < len(self.__keys): return key raise IndexError(key) elif isinstance(key, str): try: ...
Return the index of the given item. :param key: :return:
Below is the the instruction that describes the task: ### Input: Return the index of the given item. :param key: :return: ### Response: def index(self, key): """ Return the index of the given item. :param key: :return: """ if isinstance(key, int): ...
def receive(args, reactor=reactor, _debug_stash_wormhole=None): """I implement 'wormhole receive'. I return a Deferred that fires with None (for success), or signals one of the following errors: * WrongPasswordError: the two sides didn't use matching passwords * Timeout: something didn't happen fast eno...
I implement 'wormhole receive'. I return a Deferred that fires with None (for success), or signals one of the following errors: * WrongPasswordError: the two sides didn't use matching passwords * Timeout: something didn't happen fast enough for our tastes * TransferError: the sender rejected the transfe...
Below is the the instruction that describes the task: ### Input: I implement 'wormhole receive'. I return a Deferred that fires with None (for success), or signals one of the following errors: * WrongPasswordError: the two sides didn't use matching passwords * Timeout: something didn't happen fast enoug...
def _add_chrome_proxy_extension( chrome_options, proxy_string, proxy_user, proxy_pass): """ Implementation of https://stackoverflow.com/a/35293284 for https://stackoverflow.com/questions/12848327/ (Run Selenium on a proxy server that requires authentication.) """ if not "".join(sys.argv)...
Implementation of https://stackoverflow.com/a/35293284 for https://stackoverflow.com/questions/12848327/ (Run Selenium on a proxy server that requires authentication.)
Below is the the instruction that describes the task: ### Input: Implementation of https://stackoverflow.com/a/35293284 for https://stackoverflow.com/questions/12848327/ (Run Selenium on a proxy server that requires authentication.) ### Response: def _add_chrome_proxy_extension( chrome_opti...
async def monitor_status(self, alarm_status_callback=None, zone_changed_callback=None, output_changed_callback=None): """Start monitoring of the alarm status. Send command to satel integra to start sending updates. Read in a loop and cal...
Start monitoring of the alarm status. Send command to satel integra to start sending updates. Read in a loop and call respective callbacks when received messages.
Below is the the instruction that describes the task: ### Input: Start monitoring of the alarm status. Send command to satel integra to start sending updates. Read in a loop and call respective callbacks when received messages. ### Response: async def monitor_status(self, alarm_status_callback=Non...
def _set_avg_session_metrics(session_group): """Sets the metrics for the group to be the average of its sessions. The resulting session group metrics consist of the union of metrics across the group's sessions. The value of each session group metric is the average of that metric values across the sessions in t...
Sets the metrics for the group to be the average of its sessions. The resulting session group metrics consist of the union of metrics across the group's sessions. The value of each session group metric is the average of that metric values across the sessions in the group. The 'step' and 'wall_time_secs' fields...
Below is the the instruction that describes the task: ### Input: Sets the metrics for the group to be the average of its sessions. The resulting session group metrics consist of the union of metrics across the group's sessions. The value of each session group metric is the average of that metric values acros...
def homogenize(series_dict): """ Conform a set of SparseSeries (with NaN fill_value) to a common SparseIndex corresponding to the locations where they all have data Parameters ---------- series_dict : dict or DataFrame Notes ----- Using the dumbest algorithm I could think of. Shoul...
Conform a set of SparseSeries (with NaN fill_value) to a common SparseIndex corresponding to the locations where they all have data Parameters ---------- series_dict : dict or DataFrame Notes ----- Using the dumbest algorithm I could think of. Should put some more thought into this ...
Below is the the instruction that describes the task: ### Input: Conform a set of SparseSeries (with NaN fill_value) to a common SparseIndex corresponding to the locations where they all have data Parameters ---------- series_dict : dict or DataFrame Notes ----- Using the dumbest algor...
def _CalculateHashDataStream(self, file_entry, data_stream_name): """Calculates a message digest hash of the data of the file entry. Args: file_entry (dfvfs.FileEntry): file entry. data_stream_name (str): name of the data stream. Returns: bytes: digest hash or None. """ hash_cont...
Calculates a message digest hash of the data of the file entry. Args: file_entry (dfvfs.FileEntry): file entry. data_stream_name (str): name of the data stream. Returns: bytes: digest hash or None.
Below is the the instruction that describes the task: ### Input: Calculates a message digest hash of the data of the file entry. Args: file_entry (dfvfs.FileEntry): file entry. data_stream_name (str): name of the data stream. Returns: bytes: digest hash or None. ### Response: def _Calcu...
def Fritzsche(SG, Tavg, L=None, D=None, P1=None, P2=None, Q=None, Ts=288.7, Ps=101325., Zavg=1, E=1): r'''Calculation function for dealing with flow of a compressible gas in a pipeline with the Fritzsche formula. Can calculate any of the following, given all other inputs: * Flow rate ...
r'''Calculation function for dealing with flow of a compressible gas in a pipeline with the Fritzsche formula. Can calculate any of the following, given all other inputs: * Flow rate * Upstream pressure * Downstream pressure * Diameter of pipe * Length of pipe A variety of different co...
Below is the the instruction that describes the task: ### Input: r'''Calculation function for dealing with flow of a compressible gas in a pipeline with the Fritzsche formula. Can calculate any of the following, given all other inputs: * Flow rate * Upstream pressure * Downstream pressure *...
def has_more_pages(self): """ :return: ``True`` if there are more pages available on the server. """ # if has_next property exists, it represents whether more pages exist if self.has_next is not None: return self.has_next # otherwise, try to compute whether ...
:return: ``True`` if there are more pages available on the server.
Below is the the instruction that describes the task: ### Input: :return: ``True`` if there are more pages available on the server. ### Response: def has_more_pages(self): """ :return: ``True`` if there are more pages available on the server. """ # if has_next property exists, it r...
def remove_library_from_file_system(self, library_path, library_name): """Remove library from hard disk.""" library_file_system_path = self.get_os_path_to_library(library_path, library_name)[0] shutil.rmtree(library_file_system_path) self.refresh_libraries()
Remove library from hard disk.
Below is the the instruction that describes the task: ### Input: Remove library from hard disk. ### Response: def remove_library_from_file_system(self, library_path, library_name): """Remove library from hard disk.""" library_file_system_path = self.get_os_path_to_library(library_path, library_name...
def summary(self): """ A succinct summary of the Launcher configuration. Unlike the repr, a summary does not have to be complete but must supply key information relevant to the user. """ print("Type: %s" % self.__class__.__name__) print("Batch Name: %r" % self.ba...
A succinct summary of the Launcher configuration. Unlike the repr, a summary does not have to be complete but must supply key information relevant to the user.
Below is the the instruction that describes the task: ### Input: A succinct summary of the Launcher configuration. Unlike the repr, a summary does not have to be complete but must supply key information relevant to the user. ### Response: def summary(self): """ A succinct summary o...
def get_authzd_permissions(self, identifier, perm_domain): """ :type identifier: str :type domain: str :returns: a list of relevant json blobs, each a list of permission dicts """ related_perms = [] keys = ['*', perm_domain] def query_permissions(self)...
:type identifier: str :type domain: str :returns: a list of relevant json blobs, each a list of permission dicts
Below is the the instruction that describes the task: ### Input: :type identifier: str :type domain: str :returns: a list of relevant json blobs, each a list of permission dicts ### Response: def get_authzd_permissions(self, identifier, perm_domain): """ :type identifier: str ...
def future_import(feature, node): """ This seems to work """ root = find_root(node) if does_tree_import(u"__future__", feature, node): return # Look for a shebang or encoding line shebang_encoding_idx = None for idx, node in enumerate(root.children): # Is it a shebang ...
This seems to work
Below is the the instruction that describes the task: ### Input: This seems to work ### Response: def future_import(feature, node): """ This seems to work """ root = find_root(node) if does_tree_import(u"__future__", feature, node): return # Look for a shebang or encoding line ...
def explode(self, escalations): """Create instance of Escalation for each HostEscalation object :param escalations: list of escalation, used to add new ones :type escalations: alignak.objects.escalation.Escalations :return: None """ # Now we explode all escalations (host...
Create instance of Escalation for each HostEscalation object :param escalations: list of escalation, used to add new ones :type escalations: alignak.objects.escalation.Escalations :return: None
Below is the the instruction that describes the task: ### Input: Create instance of Escalation for each HostEscalation object :param escalations: list of escalation, used to add new ones :type escalations: alignak.objects.escalation.Escalations :return: None ### Response: def explode(self,...
def _init_idxs_strpat(self, usr_hdrs): """List of indexes whose values will be strings.""" strpat = self.strpat_hdrs.keys() self.idxs_strpat = [ Idx for Hdr, Idx in self.hdr2idx.items() if Hdr in usr_hdrs and Hdr in strpat]
List of indexes whose values will be strings.
Below is the the instruction that describes the task: ### Input: List of indexes whose values will be strings. ### Response: def _init_idxs_strpat(self, usr_hdrs): """List of indexes whose values will be strings.""" strpat = self.strpat_hdrs.keys() self.idxs_strpat = [ Idx for H...
def save(self, path=None, debug=False): """Save project to file. :param path: Path or file pointer. If you pass a file pointer, you're responsible for closing it. If path is not given, the :attr:`path` attribute is used, ...
Save project to file. :param path: Path or file pointer. If you pass a file pointer, you're responsible for closing it. If path is not given, the :attr:`path` attribute is used, usually the original path given to :attr:`load(...
Below is the the instruction that describes the task: ### Input: Save project to file. :param path: Path or file pointer. If you pass a file pointer, you're responsible for closing it. If path is not given, the :attr:`path` attribute is used,...