code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def trigger(self, identifier, force=True): """Trigger an upgrade task.""" self.debug(identifier) url = "{base}/{identifier}".format( base=self.local_base_url, identifier=identifier ) param = {} if force: param['force'] = force e...
Trigger an upgrade task.
Below is the the instruction that describes the task: ### Input: Trigger an upgrade task. ### Response: def trigger(self, identifier, force=True): """Trigger an upgrade task.""" self.debug(identifier) url = "{base}/{identifier}".format( base=self.local_base_url, iden...
def series_index(self, series): """ Return the integer index of *series* in this sequence. """ for idx, s in enumerate(self): if series is s: return idx raise ValueError('series not in chart data object')
Return the integer index of *series* in this sequence.
Below is the the instruction that describes the task: ### Input: Return the integer index of *series* in this sequence. ### Response: def series_index(self, series): """ Return the integer index of *series* in this sequence. """ for idx, s in enumerate(self): if series i...
def standardize(self, axis=1): """ Divide by standard deviation either within or across records. Parameters ---------- axis : int, optional, default = 0 Which axis to standardize along, within (1) or across (0) records """ if axis == 1: re...
Divide by standard deviation either within or across records. Parameters ---------- axis : int, optional, default = 0 Which axis to standardize along, within (1) or across (0) records
Below is the the instruction that describes the task: ### Input: Divide by standard deviation either within or across records. Parameters ---------- axis : int, optional, default = 0 Which axis to standardize along, within (1) or across (0) records ### Response: def standardize...
def edit( request, slug, rev_id=None, template_name='wakawaka/edit.html', extra_context=None, wiki_page_form=WikiPageForm, wiki_delete_form=DeleteWikiPageForm, ): """ Displays the form for editing and deleting a page. """ # Get the page for slug and get a specific revision, i...
Displays the form for editing and deleting a page.
Below is the the instruction that describes the task: ### Input: Displays the form for editing and deleting a page. ### Response: def edit( request, slug, rev_id=None, template_name='wakawaka/edit.html', extra_context=None, wiki_page_form=WikiPageForm, wiki_delete_form=DeleteWikiPageFor...
def filter(objects, Type=None, min=-1, max=-1): #PYCHOK muppy filter """Filter objects. The filter can be by type, minimum size, and/or maximum size. Keyword arguments: Type -- object type to filter by min -- minimum object size max -- maximum object size """ res = [] if min > max...
Filter objects. The filter can be by type, minimum size, and/or maximum size. Keyword arguments: Type -- object type to filter by min -- minimum object size max -- maximum object size
Below is the the instruction that describes the task: ### Input: Filter objects. The filter can be by type, minimum size, and/or maximum size. Keyword arguments: Type -- object type to filter by min -- minimum object size max -- maximum object size ### Response: def filter(objects, Type=None,...
def unit_action(self, cmd, pos, shift): """Return a `sc_pb.Action` filled with the cmd and appropriate target.""" action = sc_pb.Action() if pos: action_spatial = pos.action_spatial(action) unit_command = action_spatial.unit_command unit_command.ability_id = cmd.ability_id unit_comma...
Return a `sc_pb.Action` filled with the cmd and appropriate target.
Below is the the instruction that describes the task: ### Input: Return a `sc_pb.Action` filled with the cmd and appropriate target. ### Response: def unit_action(self, cmd, pos, shift): """Return a `sc_pb.Action` filled with the cmd and appropriate target.""" action = sc_pb.Action() if pos: acti...
def print_coordinates(atoms, V, title=""): """ Print coordinates V with corresponding atoms to stdout in XYZ format. Parameters ---------- atoms : list List of element types V : array (N,3) matrix of atomic coordinates title : string (optional) Title of molecule ...
Print coordinates V with corresponding atoms to stdout in XYZ format. Parameters ---------- atoms : list List of element types V : array (N,3) matrix of atomic coordinates title : string (optional) Title of molecule
Below is the the instruction that describes the task: ### Input: Print coordinates V with corresponding atoms to stdout in XYZ format. Parameters ---------- atoms : list List of element types V : array (N,3) matrix of atomic coordinates title : string (optional) Title of...
def port_profile_restrict_flooding_container_restrict_flooding(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") port_profile = ET.SubElement(config, "port-profile", xmlns="urn:brocade.com:mgmt:brocade-port-profile") name_key = ET.SubElement(port_profile, ...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def port_profile_restrict_flooding_container_restrict_flooding(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") port_profile = ET.SubElement(config, "port-prof...
def add_worksheet_indexes(portal): """Add indexes for better worksheet handling """ logger.info("Adding worksheet indexes") add_index(portal, catalog_id="bika_analysis_catalog", index_name="getCategoryTitle", index_attribute="getCategoryTitle", index_metatype="...
Add indexes for better worksheet handling
Below is the the instruction that describes the task: ### Input: Add indexes for better worksheet handling ### Response: def add_worksheet_indexes(portal): """Add indexes for better worksheet handling """ logger.info("Adding worksheet indexes") add_index(portal, catalog_id="bika_analysis_catalog",...
def get_default_config(self): """ Return the default config for the handler """ config = super(HostedGraphiteHandler, self).get_default_config() config.update({ 'apikey': '', 'host': 'carbon.hostedgraphite.com', 'port': 2003, 'prot...
Return the default config for the handler
Below is the the instruction that describes the task: ### Input: Return the default config for the handler ### Response: def get_default_config(self): """ Return the default config for the handler """ config = super(HostedGraphiteHandler, self).get_default_config() config.u...
def create_sequence_sites(chain, seq_site_length): """Create sequence sites using sequence ids. :param dict chain: Chain object that contains chemical shift values and assignment information. :param int seq_site_length: Length of a single sequence site. :return: List of sequence sites. ...
Create sequence sites using sequence ids. :param dict chain: Chain object that contains chemical shift values and assignment information. :param int seq_site_length: Length of a single sequence site. :return: List of sequence sites. :rtype: :py:class:`list`
Below is the the instruction that describes the task: ### Input: Create sequence sites using sequence ids. :param dict chain: Chain object that contains chemical shift values and assignment information. :param int seq_site_length: Length of a single sequence site. :return: List of sequence ...
def wrapModel(self, model): """ Converts application-provided model objects to L{IResource} providers. """ res = IResource(model, None) if res is None: frag = INavigableFragment(model) fragmentName = getattr(frag, 'fragmentName', None) if fragm...
Converts application-provided model objects to L{IResource} providers.
Below is the the instruction that describes the task: ### Input: Converts application-provided model objects to L{IResource} providers. ### Response: def wrapModel(self, model): """ Converts application-provided model objects to L{IResource} providers. """ res = IResource(model, Non...
def _return(self, load): ''' Handle the return data sent from the minions ''' # Generate EndTime endtime = salt.utils.jid.jid_to_time(salt.utils.jid.gen_jid(self.opts)) # If the return data is invalid, just ignore it if any(key not in load for key in ('return', 'j...
Handle the return data sent from the minions
Below is the the instruction that describes the task: ### Input: Handle the return data sent from the minions ### Response: def _return(self, load): ''' Handle the return data sent from the minions ''' # Generate EndTime endtime = salt.utils.jid.jid_to_time(salt.utils.jid.ge...
def viterbi_segment(text, P): """Find the best segmentation of the string of characters, given the UnigramTextModel P.""" # best[i] = best probability for text[0:i] # words[i] = best word ending at position i n = len(text) words = [''] + list(text) best = [1.0] + [0.0] * n ## Fill in the...
Find the best segmentation of the string of characters, given the UnigramTextModel P.
Below is the the instruction that describes the task: ### Input: Find the best segmentation of the string of characters, given the UnigramTextModel P. ### Response: def viterbi_segment(text, P): """Find the best segmentation of the string of characters, given the UnigramTextModel P.""" # best[i] = ...
def relative_private_config_file(self): """ Returns the private-config file relative to the project directory. :returns: path to private-config file. None if the file doesn't exist """ path = os.path.join(self.working_dir, 'private-config.cfg') if os.path.exists(path): ...
Returns the private-config file relative to the project directory. :returns: path to private-config file. None if the file doesn't exist
Below is the the instruction that describes the task: ### Input: Returns the private-config file relative to the project directory. :returns: path to private-config file. None if the file doesn't exist ### Response: def relative_private_config_file(self): """ Returns the private-config fil...
def max_spline_jumps(self, convert_to_muC_per_cm2=True, all_in_polar=True): """ Get maximum difference between spline and same branch polarization data. """ tot = self.get_same_branch_polarization_data( convert_to_muC_per_cm2=convert_to_muC_per_cm2, all_in_polar=all_in_polar)...
Get maximum difference between spline and same branch polarization data.
Below is the the instruction that describes the task: ### Input: Get maximum difference between spline and same branch polarization data. ### Response: def max_spline_jumps(self, convert_to_muC_per_cm2=True, all_in_polar=True): """ Get maximum difference between spline and same branch polarization ...
def _clean_index(self): "Clean index values after loading." for idx_name, idx_def in self.index_defs.items(): if idx_def['type'] == 'lazy': self.build_index(idx_name) for index_name, values in self.indexes.items(): for value in values: if n...
Clean index values after loading.
Below is the the instruction that describes the task: ### Input: Clean index values after loading. ### Response: def _clean_index(self): "Clean index values after loading." for idx_name, idx_def in self.index_defs.items(): if idx_def['type'] == 'lazy': self.build_index(i...
def result(self, result): """Sets the result of this ResponseStatus. :param result: The result of this ResponseStatus. # noqa: E501 :type: str """ if result is None: raise ValueError("Invalid value for `result`, must not be `None`") # noqa: E501 allowed_va...
Sets the result of this ResponseStatus. :param result: The result of this ResponseStatus. # noqa: E501 :type: str
Below is the the instruction that describes the task: ### Input: Sets the result of this ResponseStatus. :param result: The result of this ResponseStatus. # noqa: E501 :type: str ### Response: def result(self, result): """Sets the result of this ResponseStatus. :param result: T...
def get_proxies(self, url): """ Get the proxies that are applicable to a given URL, according to the PAC file. :param str url: The URL for which to find appropriate proxies. :return: All the proxies that apply to the given URL. Can be empty, which means to abort the request....
Get the proxies that are applicable to a given URL, according to the PAC file. :param str url: The URL for which to find appropriate proxies. :return: All the proxies that apply to the given URL. Can be empty, which means to abort the request. :rtype: list[str]
Below is the the instruction that describes the task: ### Input: Get the proxies that are applicable to a given URL, according to the PAC file. :param str url: The URL for which to find appropriate proxies. :return: All the proxies that apply to the given URL. Can be empty, which means ...
def execute(self): """ Execute the query with optional timeout. The response to the execute query is the raw payload received from the websocket and will contain multiple dict keys and values. It is more common to call query.fetch_XXX which will filter the return result based on ...
Execute the query with optional timeout. The response to the execute query is the raw payload received from the websocket and will contain multiple dict keys and values. It is more common to call query.fetch_XXX which will filter the return result based on the method. Each result set wil...
Below is the the instruction that describes the task: ### Input: Execute the query with optional timeout. The response to the execute query is the raw payload received from the websocket and will contain multiple dict keys and values. It is more common to call query.fetch_XXX which will filt...
def GlobReportMatch(self, stat_response): """Called when we've found a matching a StatEntry.""" # By default write the stat_response to the AFF4 VFS. with data_store.DB.GetMutationPool() as pool: WriteStatEntries([stat_response], client_id=self.client_id, ...
Called when we've found a matching a StatEntry.
Below is the the instruction that describes the task: ### Input: Called when we've found a matching a StatEntry. ### Response: def GlobReportMatch(self, stat_response): """Called when we've found a matching a StatEntry.""" # By default write the stat_response to the AFF4 VFS. with data_store.DB.GetMuta...
def toggle_laser(self, state): """Toggle the power state of the laser. :param state: Boolean state of the laser :type state: boolean :rtype: boolean :Example: >>> alpha.toggle_laser(True) True """ # Send the command byte and wait 10 ms ...
Toggle the power state of the laser. :param state: Boolean state of the laser :type state: boolean :rtype: boolean :Example: >>> alpha.toggle_laser(True) True
Below is the the instruction that describes the task: ### Input: Toggle the power state of the laser. :param state: Boolean state of the laser :type state: boolean :rtype: boolean :Example: >>> alpha.toggle_laser(True) True ### Response: def toggle_laser(self, s...
def get_docs(self, vocab): """Recover Doc objects from the annotations, using the given vocab.""" for string in self.strings: vocab[string] orth_col = self.attrs.index(ORTH) for tokens, spaces in zip(self.tokens, self.spaces): words = [vocab.strings[orth] for orth...
Recover Doc objects from the annotations, using the given vocab.
Below is the the instruction that describes the task: ### Input: Recover Doc objects from the annotations, using the given vocab. ### Response: def get_docs(self, vocab): """Recover Doc objects from the annotations, using the given vocab.""" for string in self.strings: vocab[string] ...
def _is_file(fs, path): """ Check that the given path is a file. Note that unlike `os.path.isfile`, we *do* propagate file system errors other than a non-existent path or non-existent directory component. E.g., should EPERM or ELOOP be raised, an exception will bubble up. """ try: ...
Check that the given path is a file. Note that unlike `os.path.isfile`, we *do* propagate file system errors other than a non-existent path or non-existent directory component. E.g., should EPERM or ELOOP be raised, an exception will bubble up.
Below is the the instruction that describes the task: ### Input: Check that the given path is a file. Note that unlike `os.path.isfile`, we *do* propagate file system errors other than a non-existent path or non-existent directory component. E.g., should EPERM or ELOOP be raised, an exception will bub...
def _draw_rect(self, rect, painter): """ Draw the background rectangle using the current style primitive color. :param rect: The fold zone rect to draw :param painter: The widget's painter. """ c = self.editor.sideareas_color grad = QLinearGradient(rect.topLeft(...
Draw the background rectangle using the current style primitive color. :param rect: The fold zone rect to draw :param painter: The widget's painter.
Below is the the instruction that describes the task: ### Input: Draw the background rectangle using the current style primitive color. :param rect: The fold zone rect to draw :param painter: The widget's painter. ### Response: def _draw_rect(self, rect, painter): """ Draw the bac...
def transform(self, column): """Applies an exponential to values to turn them positive numbers. Args: column (pandas.DataFrame): Data to transform. Returns: pd.DataFrame """ self.check_data_type() return pd.DataFrame({self.col_name: np.exp(colum...
Applies an exponential to values to turn them positive numbers. Args: column (pandas.DataFrame): Data to transform. Returns: pd.DataFrame
Below is the the instruction that describes the task: ### Input: Applies an exponential to values to turn them positive numbers. Args: column (pandas.DataFrame): Data to transform. Returns: pd.DataFrame ### Response: def transform(self, column): """Applies an expon...
def pageviews(params): """takes a couple (optional) query parameters and queries influxdb and sends a modified response """ # set up default values default_from, default_to, yesterday, _ = make_default_times() # get params try: series = params.get("site", [DEFAULT_SERIES])[0] fr...
takes a couple (optional) query parameters and queries influxdb and sends a modified response
Below is the the instruction that describes the task: ### Input: takes a couple (optional) query parameters and queries influxdb and sends a modified response ### Response: def pageviews(params): """takes a couple (optional) query parameters and queries influxdb and sends a modified response """ # set ...
def get(self, key, default=None): """ Retrieve an item from the cache by key. :param key: The cache key :type key: str :param default: The default value to return :type default: mixed :rtype: mixed """ val = self._store.get(key) if val ...
Retrieve an item from the cache by key. :param key: The cache key :type key: str :param default: The default value to return :type default: mixed :rtype: mixed
Below is the the instruction that describes the task: ### Input: Retrieve an item from the cache by key. :param key: The cache key :type key: str :param default: The default value to return :type default: mixed :rtype: mixed ### Response: def get(self, key, default=None):...
def find_near_matches_generic_ngrams(subsequence, sequence, search_params): """search for near-matches of subsequence in sequence This searches for near-matches, where the nearly-matching parts of the sequence must meet the following limitations (relative to the subsequence): * the maximum allowed num...
search for near-matches of subsequence in sequence This searches for near-matches, where the nearly-matching parts of the sequence must meet the following limitations (relative to the subsequence): * the maximum allowed number of character substitutions * the maximum allowed number of new characters i...
Below is the the instruction that describes the task: ### Input: search for near-matches of subsequence in sequence This searches for near-matches, where the nearly-matching parts of the sequence must meet the following limitations (relative to the subsequence): * the maximum allowed number of charact...
def gaussian_convolve (maj1, min1, pa1, maj2, min2, pa2): """Convolve two Gaussians analytically. Given the shapes of two 2-dimensional Gaussians, this function returns the shape of their convolution. Arguments: maj1 Major axis of input Gaussian 1. min1 Minor axis of input Gaussia...
Convolve two Gaussians analytically. Given the shapes of two 2-dimensional Gaussians, this function returns the shape of their convolution. Arguments: maj1 Major axis of input Gaussian 1. min1 Minor axis of input Gaussian 1. pa1 Orientation angle of input Gaussian 1, in radi...
Below is the the instruction that describes the task: ### Input: Convolve two Gaussians analytically. Given the shapes of two 2-dimensional Gaussians, this function returns the shape of their convolution. Arguments: maj1 Major axis of input Gaussian 1. min1 Minor axis of input Gau...
def onTWriteCallback__init(self, sim): """ Process for injecting of this callback loop into simulator """ yield from self.onTWriteCallback(sim) self.intf.t._sigInside.registerWriteCallback( self.onTWriteCallback, self.getEnable) self.intf.o._sigIns...
Process for injecting of this callback loop into simulator
Below is the the instruction that describes the task: ### Input: Process for injecting of this callback loop into simulator ### Response: def onTWriteCallback__init(self, sim): """ Process for injecting of this callback loop into simulator """ yield from self.onTWriteCallback(sim) ...
def cleanup(): """ Remove all cache directories :return: """ script_dir = os.path.dirname(__file__) if not os.path.islink(__file__) else os.path.dirname(os.readlink(__file__)) script_dir = os.path.realpath(os.path.join(script_dir, "..")) shutil.rmtree(os.path.join(script_dir, "dist"), ignore...
Remove all cache directories :return:
Below is the the instruction that describes the task: ### Input: Remove all cache directories :return: ### Response: def cleanup(): """ Remove all cache directories :return: """ script_dir = os.path.dirname(__file__) if not os.path.islink(__file__) else os.path.dirname(os.readlink(__file__)...
def get_payload(self, *args, **kwargs): """Receive all passed in args, kwargs, and combine them together with any required params""" if not kwargs: kwargs = self.default_params else: kwargs.update(self.default_params) for item in args: if isinstance(it...
Receive all passed in args, kwargs, and combine them together with any required params
Below is the the instruction that describes the task: ### Input: Receive all passed in args, kwargs, and combine them together with any required params ### Response: def get_payload(self, *args, **kwargs): """Receive all passed in args, kwargs, and combine them together with any required params""" ...
def trail_space(self, filters=lambda p: p.ext == ".py"): # pragma: no cover """ Trail white space at end of each line for every ``.py`` file. **中文文档** 将目录下的所有被选择的文件中行末的空格删除。 """ self.assert_is_dir_and_exists() for p in self.select_file(filters): tr...
Trail white space at end of each line for every ``.py`` file. **中文文档** 将目录下的所有被选择的文件中行末的空格删除。
Below is the the instruction that describes the task: ### Input: Trail white space at end of each line for every ``.py`` file. **中文文档** 将目录下的所有被选择的文件中行末的空格删除。 ### Response: def trail_space(self, filters=lambda p: p.ext == ".py"): # pragma: no cover """ Trail white space at end of...
def __format_path(self, path): """ Format path to its internal (stored in watch manager) representation. """ # Unicode strings are converted back to strings, because it seems # that inotify_add_watch from ctypes does not work well when # it receives an ctypes.create_unico...
Format path to its internal (stored in watch manager) representation.
Below is the the instruction that describes the task: ### Input: Format path to its internal (stored in watch manager) representation. ### Response: def __format_path(self, path): """ Format path to its internal (stored in watch manager) representation. """ # Unicode strings are con...
def check_field_cohesion(self, present_label_fields): """ Check that the content and structure of different fields are consistent with one another. """ # Ensure all written annotation fields have the same length nannots = len(self.sample) for field in ['sample', ...
Check that the content and structure of different fields are consistent with one another.
Below is the the instruction that describes the task: ### Input: Check that the content and structure of different fields are consistent with one another. ### Response: def check_field_cohesion(self, present_label_fields): """ Check that the content and structure of different fields are con...
def decimal_day_to_day_hour_min_sec( self, daysFloat): """*Convert a day from decimal format to hours mins and sec* Precision should be respected. **Key Arguments:** - ``daysFloat`` -- the day as a decimal. **Return:** - ``daysInt`` -- ...
*Convert a day from decimal format to hours mins and sec* Precision should be respected. **Key Arguments:** - ``daysFloat`` -- the day as a decimal. **Return:** - ``daysInt`` -- day as an integer - ``hoursInt`` -- hour as an integer (None if input precsion...
Below is the the instruction that describes the task: ### Input: *Convert a day from decimal format to hours mins and sec* Precision should be respected. **Key Arguments:** - ``daysFloat`` -- the day as a decimal. **Return:** - ``daysInt`` -- day as an integer ...
def align_with(self, other): """ Align the dataframe's index with another. """ return self.__class__(self.data.reindex_like(other), **self._kwargs)
Align the dataframe's index with another.
Below is the the instruction that describes the task: ### Input: Align the dataframe's index with another. ### Response: def align_with(self, other): """ Align the dataframe's index with another. """ return self.__class__(self.data.reindex_like(other), **self._kwargs)
def latch_file_info(self, args): """Extract the file paths from a set of arguments """ self.file_dict.clear() for key, val in self.file_args.items(): try: file_path = args[key] if file_path is None: continue ...
Extract the file paths from a set of arguments
Below is the the instruction that describes the task: ### Input: Extract the file paths from a set of arguments ### Response: def latch_file_info(self, args): """Extract the file paths from a set of arguments """ self.file_dict.clear() for key, val in self.file_args.items(): ...
def getImgIds(self, imgIds=[], catIds=[]): ''' Get img ids that satisfy given filter conditions. :param imgIds (int array) : get imgs for given ids :param catIds (int array) : get imgs with all given cats :return: ids (int array) : integer array of img ids ''' im...
Get img ids that satisfy given filter conditions. :param imgIds (int array) : get imgs for given ids :param catIds (int array) : get imgs with all given cats :return: ids (int array) : integer array of img ids
Below is the the instruction that describes the task: ### Input: Get img ids that satisfy given filter conditions. :param imgIds (int array) : get imgs for given ids :param catIds (int array) : get imgs with all given cats :return: ids (int array) : integer array of img ids ### Response: d...
def add_user(self, team, params={}, **options): """The user making this call must be a member of the team in order to add others. The user to add must exist in the same organization as the team in order to be added. The user to add can be referenced by their globally unique user ID or their ema...
The user making this call must be a member of the team in order to add others. The user to add must exist in the same organization as the team in order to be added. The user to add can be referenced by their globally unique user ID or their email address. Returns the full user record for the add...
Below is the the instruction that describes the task: ### Input: The user making this call must be a member of the team in order to add others. The user to add must exist in the same organization as the team in order to be added. The user to add can be referenced by their globally unique user ID or ...
def dpotrs(A, B, lower=1): """ Wrapper for lapack dpotrs function :param A: Matrix A :param B: Matrix B :param lower: is matrix lower (true) or upper (false) :returns: """ A = force_F_ordered(A) return lapack.dpotrs(A, B, lower=lower)
Wrapper for lapack dpotrs function :param A: Matrix A :param B: Matrix B :param lower: is matrix lower (true) or upper (false) :returns:
Below is the the instruction that describes the task: ### Input: Wrapper for lapack dpotrs function :param A: Matrix A :param B: Matrix B :param lower: is matrix lower (true) or upper (false) :returns: ### Response: def dpotrs(A, B, lower=1): """ Wrapper for lapack dpotrs function :para...
def get_disabled(): ''' Return the disabled services CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() for name in _iter_service_names(): if _service_is_upstart(name): if _upstart_is_disabled(name): ret.add(name) ...
Return the disabled services CLI Example: .. code-block:: bash salt '*' service.get_disabled
Below is the the instruction that describes the task: ### Input: Return the disabled services CLI Example: .. code-block:: bash salt '*' service.get_disabled ### Response: def get_disabled(): ''' Return the disabled services CLI Example: .. code-block:: bash salt '*' s...
def get_params(self): """ Get an odict of the parameter names and values """ return odict([(key,param.value) for key,param in self.params.items()])
Get an odict of the parameter names and values
Below is the the instruction that describes the task: ### Input: Get an odict of the parameter names and values ### Response: def get_params(self): """ Get an odict of the parameter names and values """ return odict([(key,param.value) for key,param in self.params.items()])
def Extract_Checkpoints(self): ''' Extract the checkpoints and store in self.tracking_data ''' # Make sure page is available if self.page is None: raise Exception("The HTML data was not fetched due to some reasons") soup = BeautifulSoup(self.page,'html.parser') # Check for invalid tracking number b...
Extract the checkpoints and store in self.tracking_data
Below is the the instruction that describes the task: ### Input: Extract the checkpoints and store in self.tracking_data ### Response: def Extract_Checkpoints(self): ''' Extract the checkpoints and store in self.tracking_data ''' # Make sure page is available if self.page is None: raise Exception("T...
def bind(self, data_shapes, label_shapes=None, for_training=True, inputs_need_grad=False, force_rebind=False, shared_module=None, grad_req='write'): """Binds the symbols to construct executors. This is necessary before one can perform computation with the module. Param...
Binds the symbols to construct executors. This is necessary before one can perform computation with the module. Parameters ---------- data_shapes : list of (str, tuple) Typically is ``data_iter.provide_data``. label_shapes : list of (str, tuple) Typically...
Below is the the instruction that describes the task: ### Input: Binds the symbols to construct executors. This is necessary before one can perform computation with the module. Parameters ---------- data_shapes : list of (str, tuple) Typically is ``data_iter.provide_data...
def format_field_by_match(self, value, match): """Formats a field by a Regex match of the format spec pattern.""" groups = match.groups() fill, align, sign, sharp, zero, width, comma, prec, type_ = groups if not comma and not prec and type_ not in list('fF%'): return None ...
Formats a field by a Regex match of the format spec pattern.
Below is the the instruction that describes the task: ### Input: Formats a field by a Regex match of the format spec pattern. ### Response: def format_field_by_match(self, value, match): """Formats a field by a Regex match of the format spec pattern.""" groups = match.groups() fill, align, ...
def set_volume(self, volume): """Set volume.""" for data in self._group.get('clients'): client = self._server.client(data.get('id')) yield from client.set_volume(volume, update_group=False) client.update_volume({ 'volume': { 'percen...
Set volume.
Below is the the instruction that describes the task: ### Input: Set volume. ### Response: def set_volume(self, volume): """Set volume.""" for data in self._group.get('clients'): client = self._server.client(data.get('id')) yield from client.set_volume(volume, update_group=F...
def _argcheck(*args, **kwargs): """ Check that arguments are consistent with spark array construction. Conditions are: (1) a positional argument is a SparkContext (2) keyword arg 'context' is a SparkContext (3) an argument is a BoltArraySpark, or (4) an argument ...
Check that arguments are consistent with spark array construction. Conditions are: (1) a positional argument is a SparkContext (2) keyword arg 'context' is a SparkContext (3) an argument is a BoltArraySpark, or (4) an argument is a nested list containing a BoltArraySpark
Below is the the instruction that describes the task: ### Input: Check that arguments are consistent with spark array construction. Conditions are: (1) a positional argument is a SparkContext (2) keyword arg 'context' is a SparkContext (3) an argument is a BoltArraySpark, or ...
def pdf(self): r""" Generate the vector of probabilities for the Beta-binomial (n, a, b) distribution. The Beta-binomial distribution takes the form .. math:: p(k \,|\, n, a, b) = {n \choose k} \frac{B(k + a, n - k + b)}{B(a, b)}, \qquad k = ...
r""" Generate the vector of probabilities for the Beta-binomial (n, a, b) distribution. The Beta-binomial distribution takes the form .. math:: p(k \,|\, n, a, b) = {n \choose k} \frac{B(k + a, n - k + b)}{B(a, b)}, \qquad k = 0, \ldots, n, ...
Below is the the instruction that describes the task: ### Input: r""" Generate the vector of probabilities for the Beta-binomial (n, a, b) distribution. The Beta-binomial distribution takes the form .. math:: p(k \,|\, n, a, b) = {n \choose k} \frac{B(k + a,...
def parse_rdf_payload(self, data, headers): ''' small function to parse RDF payloads from various repository endpoints Args: data (response.data): data from requests response headers (response.headers): headers from requests response Returns: (rdflib.Graph): parsed graph ''' # handle edge case ...
small function to parse RDF payloads from various repository endpoints Args: data (response.data): data from requests response headers (response.headers): headers from requests response Returns: (rdflib.Graph): parsed graph
Below is the the instruction that describes the task: ### Input: small function to parse RDF payloads from various repository endpoints Args: data (response.data): data from requests response headers (response.headers): headers from requests response Returns: (rdflib.Graph): parsed graph ### Response...
def initial_closure(self): """Computes the initial closure using the START_foo production.""" first_rule = DottedRule(self.start, 0, END_OF_INPUT) return self.closure([first_rule])
Computes the initial closure using the START_foo production.
Below is the the instruction that describes the task: ### Input: Computes the initial closure using the START_foo production. ### Response: def initial_closure(self): """Computes the initial closure using the START_foo production.""" first_rule = DottedRule(self.start, 0, END_OF_INPUT) retu...
def revoke_permission(user, permission_name): """ Revoke a specified permission from a user. Permissions are only revoked if they are in the scope any of the user's roles. If the permission is out of scope, a RolePermissionScopeException is raised. """ roles = get_user_roles(user) for ...
Revoke a specified permission from a user. Permissions are only revoked if they are in the scope any of the user's roles. If the permission is out of scope, a RolePermissionScopeException is raised.
Below is the the instruction that describes the task: ### Input: Revoke a specified permission from a user. Permissions are only revoked if they are in the scope any of the user's roles. If the permission is out of scope, a RolePermissionScopeException is raised. ### Response: def revoke_permission(us...
def get_value(self, item, default=None): """Get the value of a child""" try: return self[item].value except (AttributeError, KeyError) as e: return default
Get the value of a child
Below is the the instruction that describes the task: ### Input: Get the value of a child ### Response: def get_value(self, item, default=None): """Get the value of a child""" try: return self[item].value except (AttributeError, KeyError) as e: return default
def get_load(jid): ''' Return the load data that marks a specified jid ''' serv = _get_serv(ret=None) sql = "select load from jids where jid = '{0}'".format(jid) log.debug(">> Now in get_load %s", jid) data = serv.query(sql) log.debug(">> Now Data: %s", data) if data: return...
Return the load data that marks a specified jid
Below is the the instruction that describes the task: ### Input: Return the load data that marks a specified jid ### Response: def get_load(jid): ''' Return the load data that marks a specified jid ''' serv = _get_serv(ret=None) sql = "select load from jids where jid = '{0}'".format(jid) l...
def inline_transform(filename, key): """Encrypt file inline. Encrypts a given file with the given key, and replaces it directly without any extra space requirement. :param filename: The name of the file to encrypt. :type filename: str :param key: The key used to encrypt the file. :type...
Encrypt file inline. Encrypts a given file with the given key, and replaces it directly without any extra space requirement. :param filename: The name of the file to encrypt. :type filename: str :param key: The key used to encrypt the file. :type key: str
Below is the the instruction that describes the task: ### Input: Encrypt file inline. Encrypts a given file with the given key, and replaces it directly without any extra space requirement. :param filename: The name of the file to encrypt. :type filename: str :param key: The key used to en...
def most_frequent_terms(self, count=0): """ Returns ``count`` of terms sorted by their frequency in descending order. :parameter int count: Max. number of returned terms. Value 0 means no limit (default). """ # sort terms by number of occurrences in descendin...
Returns ``count`` of terms sorted by their frequency in descending order. :parameter int count: Max. number of returned terms. Value 0 means no limit (default).
Below is the the instruction that describes the task: ### Input: Returns ``count`` of terms sorted by their frequency in descending order. :parameter int count: Max. number of returned terms. Value 0 means no limit (default). ### Response: def most_frequent_terms(self, count=0): ...
def form_group_wrapped(f): """ Wrap a field within a bootstrap form-group. Additionally sets has-error This decorator sets has-error if the field has any errors. """ @wraps(f) def wrapped(self, field, *args, **kwargs): classes = ['form-group'] if field.errors: classe...
Wrap a field within a bootstrap form-group. Additionally sets has-error This decorator sets has-error if the field has any errors.
Below is the the instruction that describes the task: ### Input: Wrap a field within a bootstrap form-group. Additionally sets has-error This decorator sets has-error if the field has any errors. ### Response: def form_group_wrapped(f): """ Wrap a field within a bootstrap form-group. Additionally sets...
def fetch_response(self, req_payload, **kwargs): """payload has been sent, do anything else you need to do (eg, wait for response?) :param req_payload: Payload, the payload sent to the server :returns: Payload, the response payload """ if req_payload.uuid: uuids = se...
payload has been sent, do anything else you need to do (eg, wait for response?) :param req_payload: Payload, the payload sent to the server :returns: Payload, the response payload
Below is the the instruction that describes the task: ### Input: payload has been sent, do anything else you need to do (eg, wait for response?) :param req_payload: Payload, the payload sent to the server :returns: Payload, the response payload ### Response: def fetch_response(self, req_payload, *...
def _add_subject_node(self, node, subj_str): """Add a node containing a subject string.""" child = node.add_child(name=subj_str) child.add_feature(SUBJECT_NODE_TAG, True) return child
Add a node containing a subject string.
Below is the the instruction that describes the task: ### Input: Add a node containing a subject string. ### Response: def _add_subject_node(self, node, subj_str): """Add a node containing a subject string.""" child = node.add_child(name=subj_str) child.add_feature(SUBJECT_NODE_TAG, True) ...
def simple_paginate(self, per_page=15, current_page=None, columns=None): """ Paginate the given query. :param per_page: The number of records per page :type per_page: int :param current_page: The current page of results :type current_page: int :param columns: T...
Paginate the given query. :param per_page: The number of records per page :type per_page: int :param current_page: The current page of results :type current_page: int :param columns: The columns to return :type columns: list :return: The paginator :rty...
Below is the the instruction that describes the task: ### Input: Paginate the given query. :param per_page: The number of records per page :type per_page: int :param current_page: The current page of results :type current_page: int :param columns: The columns to return ...
def bottomup(cls): """Get all bottomup `Relationship` instances. Example: >>> from pronto import Relationship >>> for r in Relationship.bottomup(): ... print(r) Relationship('is_a') Relationship('part_of') Relationship('develop...
Get all bottomup `Relationship` instances. Example: >>> from pronto import Relationship >>> for r in Relationship.bottomup(): ... print(r) Relationship('is_a') Relationship('part_of') Relationship('develops_from')
Below is the the instruction that describes the task: ### Input: Get all bottomup `Relationship` instances. Example: >>> from pronto import Relationship >>> for r in Relationship.bottomup(): ... print(r) Relationship('is_a') Relationship('part...
def github_tags_newer(github_repo, versions_file, update_majors): """ Get new tags from a github repository. Cannot use github API because it doesn't support chronological ordering of tags. @param github_repo: the github repository, e.g. 'drupal/drupal/'. @param versions_file: the file path where th...
Get new tags from a github repository. Cannot use github API because it doesn't support chronological ordering of tags. @param github_repo: the github repository, e.g. 'drupal/drupal/'. @param versions_file: the file path where the versions database can be found. @param update_majors: major versions to ...
Below is the the instruction that describes the task: ### Input: Get new tags from a github repository. Cannot use github API because it doesn't support chronological ordering of tags. @param github_repo: the github repository, e.g. 'drupal/drupal/'. @param versions_file: the file path where the version...
def peers(self): "list of the (host, port) pairs of all connected peer Hubs" return [addr for (addr, peer) in self._dispatcher.peers.items() if peer.up]
list of the (host, port) pairs of all connected peer Hubs
Below is the the instruction that describes the task: ### Input: list of the (host, port) pairs of all connected peer Hubs ### Response: def peers(self): "list of the (host, port) pairs of all connected peer Hubs" return [addr for (addr, peer) in self._dispatcher.peers.items() if pe...
def get_items_by_ids(self, item_ids): """Gets an ``ItemList`` corresponding to the given ``IdList``. In plenary mode, the returned list contains all of the items specified in the ``Id`` list, in the order of the list, including duplicates, or an error results if an ``Id`` in the ...
Gets an ``ItemList`` corresponding to the given ``IdList``. In plenary mode, the returned list contains all of the items specified in the ``Id`` list, in the order of the list, including duplicates, or an error results if an ``Id`` in the supplied list is not found or inaccessible. Othe...
Below is the the instruction that describes the task: ### Input: Gets an ``ItemList`` corresponding to the given ``IdList``. In plenary mode, the returned list contains all of the items specified in the ``Id`` list, in the order of the list, including duplicates, or an error results if an `...
def wns_send_message( uri, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs ): """ Sends a notification request to WNS. There are four notification types that WNS can send: toast, tile, badge and raw. Toast, tile, and badge can all be customized to use different templates/icons/sounds/lau...
Sends a notification request to WNS. There are four notification types that WNS can send: toast, tile, badge and raw. Toast, tile, and badge can all be customized to use different templates/icons/sounds/launch params/etc. See docs for more information: https://msdn.microsoft.com/en-us/library/windows/apps/br212853...
Below is the the instruction that describes the task: ### Input: Sends a notification request to WNS. There are four notification types that WNS can send: toast, tile, badge and raw. Toast, tile, and badge can all be customized to use different templates/icons/sounds/launch params/etc. See docs for more informa...
def run(self, *args, **kwargs): """Entry point for the scheduler Args: *args: Optional arguments **kwargs: Optional keyword arguments Returns: None """ accounts = list(AWSAccount.get_all(include_disabled=False).values()) # S3 Bucket ...
Entry point for the scheduler Args: *args: Optional arguments **kwargs: Optional keyword arguments Returns: None
Below is the the instruction that describes the task: ### Input: Entry point for the scheduler Args: *args: Optional arguments **kwargs: Optional keyword arguments Returns: None ### Response: def run(self, *args, **kwargs): """Entry point for the schedu...
def sample_path(self, seed): """ Return the model name and a list of branch ids. :param seed: the seed used for the sampling """ branchset = self.root_branchset branch_ids = [] while branchset is not None: [branch] = sample(branchset.branches, 1, seed...
Return the model name and a list of branch ids. :param seed: the seed used for the sampling
Below is the the instruction that describes the task: ### Input: Return the model name and a list of branch ids. :param seed: the seed used for the sampling ### Response: def sample_path(self, seed): """ Return the model name and a list of branch ids. :param seed: the seed used fo...
def send_password_reset_link(self, username): """Sends the user a password reset link (by email) Args: username: The account username. Returns: True: Succeeded False: If unsuccessful """ response = self._post(self.rest_url + "/user/mail/pass...
Sends the user a password reset link (by email) Args: username: The account username. Returns: True: Succeeded False: If unsuccessful
Below is the the instruction that describes the task: ### Input: Sends the user a password reset link (by email) Args: username: The account username. Returns: True: Succeeded False: If unsuccessful ### Response: def send_password_reset_link(self, username): ...
def var_set(self, session, **kwargs): """ Sets the given variables or prints the current ones. "set answer=42" """ if not kwargs: session.write_line( self._utils.make_table( ("Name", "Value"), session.variables.items() ) ...
Sets the given variables or prints the current ones. "set answer=42"
Below is the the instruction that describes the task: ### Input: Sets the given variables or prints the current ones. "set answer=42" ### Response: def var_set(self, session, **kwargs): """ Sets the given variables or prints the current ones. "set answer=42" """ if not kwargs: ...
def run(self): """Start listening to the server""" logger.info(u'Started listening') while not self._stop: xml = self._readxml() # Exit on invalid XML if xml is None: break # Raw xml only if not self.modelize: ...
Start listening to the server
Below is the the instruction that describes the task: ### Input: Start listening to the server ### Response: def run(self): """Start listening to the server""" logger.info(u'Started listening') while not self._stop: xml = self._readxml() # Exit on invalid XML ...
def add_route(self, target_id, stream): """ Arrange for messages whose `dst_id` is `target_id` to be forwarded on the directly connected stream for `via_id`. This method is called automatically in response to :data:`mitogen.core.ADD_ROUTE` messages, but remains public while the d...
Arrange for messages whose `dst_id` is `target_id` to be forwarded on the directly connected stream for `via_id`. This method is called automatically in response to :data:`mitogen.core.ADD_ROUTE` messages, but remains public while the design has not yet settled, and situations may arise ...
Below is the the instruction that describes the task: ### Input: Arrange for messages whose `dst_id` is `target_id` to be forwarded on the directly connected stream for `via_id`. This method is called automatically in response to :data:`mitogen.core.ADD_ROUTE` messages, but remains public wh...
def sixteen2eight(I: np.ndarray, Clim: tuple) -> np.ndarray: """ scipy.misc.bytescale had bugs inputs: ------ I: 2-D Numpy array of grayscale image data Clim: length 2 of tuple or numpy 1-D array specifying lowest and highest expected values in grayscale image Michael Hirsch, Ph.D. """ ...
scipy.misc.bytescale had bugs inputs: ------ I: 2-D Numpy array of grayscale image data Clim: length 2 of tuple or numpy 1-D array specifying lowest and highest expected values in grayscale image Michael Hirsch, Ph.D.
Below is the the instruction that describes the task: ### Input: scipy.misc.bytescale had bugs inputs: ------ I: 2-D Numpy array of grayscale image data Clim: length 2 of tuple or numpy 1-D array specifying lowest and highest expected values in grayscale image Michael Hirsch, Ph.D. ### Response...
def _save_results(self): """Save results dictionary to json file.""" with open(self.results_file, 'w') as results_file: json.dump(self.results, results_file)
Save results dictionary to json file.
Below is the the instruction that describes the task: ### Input: Save results dictionary to json file. ### Response: def _save_results(self): """Save results dictionary to json file.""" with open(self.results_file, 'w') as results_file: json.dump(self.results, results_file)
def get_assessment_parts_by_bank(self, bank_id): """Gets the list of assessment parts associated with an ``Bank``. arg: bank_id (osid.id.Id): ``Id`` of the ``Bank`` return: (osid.assessment.authoring.AssessmentPartList) - list of related assessment parts raise: NotFo...
Gets the list of assessment parts associated with an ``Bank``. arg: bank_id (osid.id.Id): ``Id`` of the ``Bank`` return: (osid.assessment.authoring.AssessmentPartList) - list of related assessment parts raise: NotFound - ``bank_id`` is not found raise: NullArgument ...
Below is the the instruction that describes the task: ### Input: Gets the list of assessment parts associated with an ``Bank``. arg: bank_id (osid.id.Id): ``Id`` of the ``Bank`` return: (osid.assessment.authoring.AssessmentPartList) - list of related assessment parts rais...
def query(self, *args, **kwargs): """ Reimplemented from base class. This method does not add additional functionality of the base class' :meth:`~couchbase.bucket.Bucket.query` method (all the functionality is encapsulated in the view class anyway). However it does requi...
Reimplemented from base class. This method does not add additional functionality of the base class' :meth:`~couchbase.bucket.Bucket.query` method (all the functionality is encapsulated in the view class anyway). However it does require one additional keyword argument :param cla...
Below is the the instruction that describes the task: ### Input: Reimplemented from base class. This method does not add additional functionality of the base class' :meth:`~couchbase.bucket.Bucket.query` method (all the functionality is encapsulated in the view class anyway). However it ...
def get_possible_builds(self, purpose=PURPOSE_RUN): """ Returns a list of possible status ids that are valid entry points into this ISCM. For each status, there is a list of phases that need to be executed, i.e.: [ { status_id: "ykyk...", run_phases: [ ] }, { s...
Returns a list of possible status ids that are valid entry points into this ISCM. For each status, there is a list of phases that need to be executed, i.e.: [ { status_id: "ykyk...", run_phases: [ ] }, { status_id: "znzn...", run_phases: [ <phase3> ] }, { status_id: "...
Below is the the instruction that describes the task: ### Input: Returns a list of possible status ids that are valid entry points into this ISCM. For each status, there is a list of phases that need to be executed, i.e.: [ { status_id: "ykyk...", run_phases: [ ] }, { stat...
def build(sub_parser, cmds): """todo: Docstring for build :param sub_parser: arg description :type sub_parser: type description :return: :rtype: """ res = {} for cmd in cmds: res[cmd.name] = cmd(sub_parser) # end for cmd in cmds return res
todo: Docstring for build :param sub_parser: arg description :type sub_parser: type description :return: :rtype:
Below is the the instruction that describes the task: ### Input: todo: Docstring for build :param sub_parser: arg description :type sub_parser: type description :return: :rtype: ### Response: def build(sub_parser, cmds): """todo: Docstring for build :param sub_parser: arg description ...
def setrange(self, name, offset, value): """ Overwrite bytes in the value of ``name`` starting at ``offset`` with ``value``. If ``offset`` plus the length of ``value`` exceeds the length of the original value, the new value will be larger than before. If ``offset`` exceeds the le...
Overwrite bytes in the value of ``name`` starting at ``offset`` with ``value``. If ``offset`` plus the length of ``value`` exceeds the length of the original value, the new value will be larger than before. If ``offset`` exceeds the length of the original value, null bytes will be used t...
Below is the the instruction that describes the task: ### Input: Overwrite bytes in the value of ``name`` starting at ``offset`` with ``value``. If ``offset`` plus the length of ``value`` exceeds the length of the original value, the new value will be larger than before. If ``offset`` exceed...
def process(self): """ Apply basic cleaning functions to the Path object, in- place. """ log.debug('Processing drawing') with self._cache: for func in self._process_functions(): func() return self
Apply basic cleaning functions to the Path object, in- place.
Below is the the instruction that describes the task: ### Input: Apply basic cleaning functions to the Path object, in- place. ### Response: def process(self): """ Apply basic cleaning functions to the Path object, in- place. """ log.debug('Processing drawing') with self._ca...
def get_all_SpCells(self): """ For each postsynaptic cell existing on this RANK, load or compute the presynaptic cell index for each synaptic connection This function takes no kwargs. Parameters ---------- None Returns ------- SpCells ...
For each postsynaptic cell existing on this RANK, load or compute the presynaptic cell index for each synaptic connection This function takes no kwargs. Parameters ---------- None Returns ------- SpCells : dict `output[cellindex][populatio...
Below is the the instruction that describes the task: ### Input: For each postsynaptic cell existing on this RANK, load or compute the presynaptic cell index for each synaptic connection This function takes no kwargs. Parameters ---------- None Returns --...
def getResultsRangeDict(self): """Return a dictionary with the specification fields for each service. The keys of the dictionary are the keywords of each analysis service. Each service contains a dictionary in which each key is the name of the spec field: specs['keywo...
Return a dictionary with the specification fields for each service. The keys of the dictionary are the keywords of each analysis service. Each service contains a dictionary in which each key is the name of the spec field: specs['keyword'] = {'min': value, ...
Below is the the instruction that describes the task: ### Input: Return a dictionary with the specification fields for each service. The keys of the dictionary are the keywords of each analysis service. Each service contains a dictionary in which each key is the name of the spec fie...
def _read_stc(stc_file): """Read Segment Table of Contents file. Returns ------- hdr : dict - next_segment : Sample frequency in Hertz - final : Number of channels stored - padding : Padding stamps : ndarray of dtype - segment_name : Name of ERD / ETC file segment ...
Read Segment Table of Contents file. Returns ------- hdr : dict - next_segment : Sample frequency in Hertz - final : Number of channels stored - padding : Padding stamps : ndarray of dtype - segment_name : Name of ERD / ETC file segment - start_stamp : First samp...
Below is the the instruction that describes the task: ### Input: Read Segment Table of Contents file. Returns ------- hdr : dict - next_segment : Sample frequency in Hertz - final : Number of channels stored - padding : Padding stamps : ndarray of dtype - segment_nam...
def _create_get_processed_line_func(self, cli, document): """ Create a function that takes a line number of the current document and returns a _ProcessedLine(processed_tokens, source_to_display, display_to_source) tuple. """ def transform(lineno, tokens): " Tr...
Create a function that takes a line number of the current document and returns a _ProcessedLine(processed_tokens, source_to_display, display_to_source) tuple.
Below is the the instruction that describes the task: ### Input: Create a function that takes a line number of the current document and returns a _ProcessedLine(processed_tokens, source_to_display, display_to_source) tuple. ### Response: def _create_get_processed_line_func(self, cli, document): ...
def get_attr(self, key, name, default=None): """ :param key: dataset path :param name: name of the attribute :param default: value to return if the attribute is missing """ try: obj = h5py.File.__getitem__(self.hdf5, key) except KeyError: i...
:param key: dataset path :param name: name of the attribute :param default: value to return if the attribute is missing
Below is the the instruction that describes the task: ### Input: :param key: dataset path :param name: name of the attribute :param default: value to return if the attribute is missing ### Response: def get_attr(self, key, name, default=None): """ :param key: dataset path :p...
def monkeypatch_os_fork_functions(): """ Replace os.fork* with wrappers that use ForkSafeLock to acquire all locks before forking and release them afterwards. """ builtin_function = type(''.join) if hasattr(os, 'fork') and isinstance(os.fork, builtin_function): global _orig_os_fork ...
Replace os.fork* with wrappers that use ForkSafeLock to acquire all locks before forking and release them afterwards.
Below is the the instruction that describes the task: ### Input: Replace os.fork* with wrappers that use ForkSafeLock to acquire all locks before forking and release them afterwards. ### Response: def monkeypatch_os_fork_functions(): """ Replace os.fork* with wrappers that use ForkSafeLock to acquire ...
def _pop(line, key, use_rest): ''' Helper for the line parser. If key is a prefix of line, will remove ir from the line and will extract the value (space separation), and the rest of the line. If use_rest is True, the value will be the rest of the line. Return a tuple with the value and the r...
Helper for the line parser. If key is a prefix of line, will remove ir from the line and will extract the value (space separation), and the rest of the line. If use_rest is True, the value will be the rest of the line. Return a tuple with the value and the rest of the line.
Below is the the instruction that describes the task: ### Input: Helper for the line parser. If key is a prefix of line, will remove ir from the line and will extract the value (space separation), and the rest of the line. If use_rest is True, the value will be the rest of the line. Return a tupl...
def _extract_obo_relation(cls, rawterm): """Extract the relationships defined in the rawterm. """ relations = {} if 'subClassOf' in rawterm: relations[Relationship('is_a')] = l = [] l.extend(map(cls._get_id_from_url, rawterm.pop('subClassOf'))) return rela...
Extract the relationships defined in the rawterm.
Below is the the instruction that describes the task: ### Input: Extract the relationships defined in the rawterm. ### Response: def _extract_obo_relation(cls, rawterm): """Extract the relationships defined in the rawterm. """ relations = {} if 'subClassOf' in rawterm: r...
def are_items_shuffled(self): """Tests if the items or parts appear in a random order. return: (boolean) - ``true`` if the items appear in a random order, ``false`` otherwise *compliance: mandatory -- This method must be implemented.* """ if self._my_map['itemsS...
Tests if the items or parts appear in a random order. return: (boolean) - ``true`` if the items appear in a random order, ``false`` otherwise *compliance: mandatory -- This method must be implemented.*
Below is the the instruction that describes the task: ### Input: Tests if the items or parts appear in a random order. return: (boolean) - ``true`` if the items appear in a random order, ``false`` otherwise *compliance: mandatory -- This method must be implemented.* ### Response: d...
def parse_function_params(params): """ parse function params to args and kwargs. Args: params (str): function param in string Returns: dict: function meta dict { "args": [], "kwargs": {} } Examples: >>> parse_function_pa...
parse function params to args and kwargs. Args: params (str): function param in string Returns: dict: function meta dict { "args": [], "kwargs": {} } Examples: >>> parse_function_params("") {'args': [], 'kwargs': {}}...
Below is the the instruction that describes the task: ### Input: parse function params to args and kwargs. Args: params (str): function param in string Returns: dict: function meta dict { "args": [], "kwargs": {} } Examples: ...
def chunks(data, chunk_size): """ Yield chunk_size chunks from data.""" for i in xrange(0, len(data), chunk_size): yield data[i:i+chunk_size]
Yield chunk_size chunks from data.
Below is the the instruction that describes the task: ### Input: Yield chunk_size chunks from data. ### Response: def chunks(data, chunk_size): """ Yield chunk_size chunks from data.""" for i in xrange(0, len(data), chunk_size): yield data[i:i+chunk_size]
def write(self, message): """Writes the given message up the wire. Does not expect a response back for the message. :param message: Message to write. """ message.id = message.id or self.writer.next_message_id() if message.message_type in self.CALL_REQ_TYPES...
Writes the given message up the wire. Does not expect a response back for the message. :param message: Message to write.
Below is the the instruction that describes the task: ### Input: Writes the given message up the wire. Does not expect a response back for the message. :param message: Message to write. ### Response: def write(self, message): """Writes the given message up the wire. D...
def send_frame(self, cmd, headers=None, body=''): """ Encode and send a stomp frame through the underlying transport. :param str cmd: the protocol command :param dict headers: a map of headers to include in the frame :param body: the content of the message """ ...
Encode and send a stomp frame through the underlying transport. :param str cmd: the protocol command :param dict headers: a map of headers to include in the frame :param body: the content of the message
Below is the the instruction that describes the task: ### Input: Encode and send a stomp frame through the underlying transport. :param str cmd: the protocol command :param dict headers: a map of headers to include in the frame :param body: the content of the message ### Response: ...
def _send_command_raw(self, command, opt=''): """ Description: The TV doesn't handle long running connections very well, so we open a new connection every time. There might be a better way to do this, but it's pretty quick and resilient. Returns:...
Description: The TV doesn't handle long running connections very well, so we open a new connection every time. There might be a better way to do this, but it's pretty quick and resilient. Returns: If a value is being requested ( opt2 is "?" ), ...
Below is the the instruction that describes the task: ### Input: Description: The TV doesn't handle long running connections very well, so we open a new connection every time. There might be a better way to do this, but it's pretty quick and resilient. Retur...
def _execCmd(self, cmd, args): """Execute command and return result body as list of lines. @param cmd: Command string. @param args: Comand arguments string. @return: Result dictionary. """ output = self._eslconn.api(cmd, args) ...
Execute command and return result body as list of lines. @param cmd: Command string. @param args: Comand arguments string. @return: Result dictionary.
Below is the the instruction that describes the task: ### Input: Execute command and return result body as list of lines. @param cmd: Command string. @param args: Comand arguments string. @return: Result dictionary. ### Response: def _execCmd(self, cmd, args): ...
def raw_section_content_identifier(self, value): """ Setter for **self. __raw_section_content_identifier** attribute. :param value: Attribute value. :type value: unicode """ if value is not None: assert type(value) is unicode, "'{0}' attribute: '{1}' type is...
Setter for **self. __raw_section_content_identifier** attribute. :param value: Attribute value. :type value: unicode
Below is the the instruction that describes the task: ### Input: Setter for **self. __raw_section_content_identifier** attribute. :param value: Attribute value. :type value: unicode ### Response: def raw_section_content_identifier(self, value): """ Setter for **self. __raw_section_...
def create_layer(self, lipid_indices=None, flip_orientation=False): """Create a monolayer of lipids. Parameters ---------- lipid_indices : list, optional, default=None A list of indices associated with each lipid in the layer. flip_orientation : bool, optional, defau...
Create a monolayer of lipids. Parameters ---------- lipid_indices : list, optional, default=None A list of indices associated with each lipid in the layer. flip_orientation : bool, optional, default=False Flip the orientation of the layer with respect to the z-di...
Below is the the instruction that describes the task: ### Input: Create a monolayer of lipids. Parameters ---------- lipid_indices : list, optional, default=None A list of indices associated with each lipid in the layer. flip_orientation : bool, optional, default=False ...
def GetDisabledOutputClasses(cls): """Retrieves the disabled output classes and its associated name. Yields: tuple[str, type]: output module name and class. """ for _, output_class in iter(cls._disabled_output_classes.items()): yield output_class.NAME, output_class
Retrieves the disabled output classes and its associated name. Yields: tuple[str, type]: output module name and class.
Below is the the instruction that describes the task: ### Input: Retrieves the disabled output classes and its associated name. Yields: tuple[str, type]: output module name and class. ### Response: def GetDisabledOutputClasses(cls): """Retrieves the disabled output classes and its associated name. ...
def health_check(self): """Gets a single item to determine if Dynamo is functioning.""" logger.debug('Health Check on Table: {namespace}'.format( namespace=self.namespace )) try: self.get_all() return True except ClientError as e: ...
Gets a single item to determine if Dynamo is functioning.
Below is the the instruction that describes the task: ### Input: Gets a single item to determine if Dynamo is functioning. ### Response: def health_check(self): """Gets a single item to determine if Dynamo is functioning.""" logger.debug('Health Check on Table: {namespace}'.format( name...
def command_schema(self, name=None): ''' Prints current database schema (according sqlalchemy database model):: ./manage.py sqla:schema [name] ''' meta_name = table_name = None if name: if isinstance(self.metadata, MetaData): table_name = ...
Prints current database schema (according sqlalchemy database model):: ./manage.py sqla:schema [name]
Below is the the instruction that describes the task: ### Input: Prints current database schema (according sqlalchemy database model):: ./manage.py sqla:schema [name] ### Response: def command_schema(self, name=None): ''' Prints current database schema (according sqlalchemy database mo...