code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def get_class(context, field, obj=None): """ Looks up the class for this field """ view = context['view'] return view.lookup_field_class(field, obj, "field_" + field)
Looks up the class for this field
Below is the the instruction that describes the task: ### Input: Looks up the class for this field ### Response: def get_class(context, field, obj=None): """ Looks up the class for this field """ view = context['view'] return view.lookup_field_class(field, obj, "field_" + field)
def convert(self, obj): """Takes a dict corresponding to the honeybadgerfish JSON blob of the 1.0.* type and converts it to BY_ID_HONEY_BADGERFISH version. The object is modified in place and returned. """ if self.pristine_if_invalid: raise NotImplementedError('pristi...
Takes a dict corresponding to the honeybadgerfish JSON blob of the 1.0.* type and converts it to BY_ID_HONEY_BADGERFISH version. The object is modified in place and returned.
Below is the the instruction that describes the task: ### Input: Takes a dict corresponding to the honeybadgerfish JSON blob of the 1.0.* type and converts it to BY_ID_HONEY_BADGERFISH version. The object is modified in place and returned. ### Response: def convert(self, obj): """Takes a di...
def gini(self): """ geo.gini() Return computed Gini coefficient. """ if self.count()>1: xsort = sorted(self.raster.data[self.raster.mask == False].flatten()) # increasing order y = np.cumsum(xsort) B = sum(y) / (y[-1] * len(xsort)) ...
geo.gini() Return computed Gini coefficient.
Below is the the instruction that describes the task: ### Input: geo.gini() Return computed Gini coefficient. ### Response: def gini(self): """ geo.gini() Return computed Gini coefficient. """ if self.count()>1: xsort = sorted(self.raster.data[self.rast...
def axis_to_data(ax, width): """For a width in axis coordinates, return the corresponding in data coordinates. Parameters ---------- ax : matplotlib.axis Axis object from matplotlib. width : float Width in xaxis coordinates. """ xlim = ax.get_xlim() widthx = width*(x...
For a width in axis coordinates, return the corresponding in data coordinates. Parameters ---------- ax : matplotlib.axis Axis object from matplotlib. width : float Width in xaxis coordinates.
Below is the the instruction that describes the task: ### Input: For a width in axis coordinates, return the corresponding in data coordinates. Parameters ---------- ax : matplotlib.axis Axis object from matplotlib. width : float Width in xaxis coordinates. ### Response: def ax...
def is_cross_origin(request): """Compare headers HOST and ORIGIN. Remove protocol prefix from ORIGIN, then compare. Return true if they are not equal example HTTP_HOST: '127.0.0.1:5000' example HTTP_ORIGIN: 'http://127.0.0.1:5000' """ origin = request.environ.get("HTTP_ORIGIN") host = reques...
Compare headers HOST and ORIGIN. Remove protocol prefix from ORIGIN, then compare. Return true if they are not equal example HTTP_HOST: '127.0.0.1:5000' example HTTP_ORIGIN: 'http://127.0.0.1:5000'
Below is the the instruction that describes the task: ### Input: Compare headers HOST and ORIGIN. Remove protocol prefix from ORIGIN, then compare. Return true if they are not equal example HTTP_HOST: '127.0.0.1:5000' example HTTP_ORIGIN: 'http://127.0.0.1:5000' ### Response: def is_cross_origin(reques...
def align(self, scale, center, angle, height, width): """ Create a thumbnail from the original image that is scaled by the given factor, centered on the center pixel, oriented along the grasp angle, and cropped to the desired height and width. Parameters ---------- scale : float...
Create a thumbnail from the original image that is scaled by the given factor, centered on the center pixel, oriented along the grasp angle, and cropped to the desired height and width. Parameters ---------- scale : float scale factor to apply center : 2D array ...
Below is the the instruction that describes the task: ### Input: Create a thumbnail from the original image that is scaled by the given factor, centered on the center pixel, oriented along the grasp angle, and cropped to the desired height and width. Parameters ---------- scale : fl...
def cal_gpa(grades): """ 根据成绩数组计算课程平均绩点和 gpa, 算法不一定与学校一致, 结果仅供参考 :param grades: :meth:`models.StudentSession.get_my_achievements` 返回的成绩数组 :return: 包含了课程平均绩点和 gpa 的元组 """ # 课程总数 courses_sum = len(grades) # 课程绩点和 points_sum = 0 # 学分和 credit_sum = 0 # 课程学分 x 课程绩点之和 gpa_...
根据成绩数组计算课程平均绩点和 gpa, 算法不一定与学校一致, 结果仅供参考 :param grades: :meth:`models.StudentSession.get_my_achievements` 返回的成绩数组 :return: 包含了课程平均绩点和 gpa 的元组
Below is the the instruction that describes the task: ### Input: 根据成绩数组计算课程平均绩点和 gpa, 算法不一定与学校一致, 结果仅供参考 :param grades: :meth:`models.StudentSession.get_my_achievements` 返回的成绩数组 :return: 包含了课程平均绩点和 gpa 的元组 ### Response: def cal_gpa(grades): """ 根据成绩数组计算课程平均绩点和 gpa, 算法不一定与学校一致, 结果仅供参考 :param g...
def get_statepostal(self, obj): """State postal abbreviation if county or state else ``None``.""" if obj.division.level.name == DivisionLevel.STATE: return us.states.lookup(obj.division.code).abbr elif obj.division.level.name == DivisionLevel.COUNTY: return us.states.look...
State postal abbreviation if county or state else ``None``.
Below is the the instruction that describes the task: ### Input: State postal abbreviation if county or state else ``None``. ### Response: def get_statepostal(self, obj): """State postal abbreviation if county or state else ``None``.""" if obj.division.level.name == DivisionLevel.STATE: ...
def no_duplicates(function, *args, **kwargs): """ Makes sure that no duplicated tasks are enqueued. """ @wraps(function) def wrapper(self, *args, **kwargs): key = generate_key(function, *args, **kwargs) try: function(self, *args, **kwargs) finally: log...
Makes sure that no duplicated tasks are enqueued.
Below is the the instruction that describes the task: ### Input: Makes sure that no duplicated tasks are enqueued. ### Response: def no_duplicates(function, *args, **kwargs): """ Makes sure that no duplicated tasks are enqueued. """ @wraps(function) def wrapper(self, *args, **kwargs): k...
def __get_language_match(self, languageCode, languageIds): """Compares ``languageCode`` to the provided ``languageIds`` to find the closest match and returns it, if a match is not found returns ``None``. e.g. if ``languageCode`` is ``en_CA`` and ``languageIds`` contains ``...
Compares ``languageCode`` to the provided ``languageIds`` to find the closest match and returns it, if a match is not found returns ``None``. e.g. if ``languageCode`` is ``en_CA`` and ``languageIds`` contains ``en``, the return value will be ``en``
Below is the the instruction that describes the task: ### Input: Compares ``languageCode`` to the provided ``languageIds`` to find the closest match and returns it, if a match is not found returns ``None``. e.g. if ``languageCode`` is ``en_CA`` and ``languageIds`` contains ``en...
def qseries(fseries, Q, f0, return_complex=False): """Calculate the energy 'TimeSeries' for the given fseries Parameters ---------- fseries: 'pycbc FrequencySeries' frequency-series data set Q: q value f0: central frequency return_complex: {False, bool} Retur...
Calculate the energy 'TimeSeries' for the given fseries Parameters ---------- fseries: 'pycbc FrequencySeries' frequency-series data set Q: q value f0: central frequency return_complex: {False, bool} Return the raw complex series instead of the normalized power. ...
Below is the the instruction that describes the task: ### Input: Calculate the energy 'TimeSeries' for the given fseries Parameters ---------- fseries: 'pycbc FrequencySeries' frequency-series data set Q: q value f0: central frequency return_complex: {False, bool} ...
def p_variable_declaration_list_noin(self, p): """ variable_declaration_list_noin \ : variable_declaration_noin | variable_declaration_list_noin COMMA variable_declaration_noin """ if len(p) == 2: p[0] = [p[1]] else: p[1].append(p[3...
variable_declaration_list_noin \ : variable_declaration_noin | variable_declaration_list_noin COMMA variable_declaration_noin
Below is the the instruction that describes the task: ### Input: variable_declaration_list_noin \ : variable_declaration_noin | variable_declaration_list_noin COMMA variable_declaration_noin ### Response: def p_variable_declaration_list_noin(self, p): """ variable_declaratio...
def make_imagehdu(data, wcs=None): """ Create a FITS `~astropy.io.fits.ImageHDU` containing the input 2D image. Parameters ---------- data : 2D array-like The input 2D data. wcs : `~astropy.wcs.WCS`, optional The world coordinate system (WCS) transformation to include in ...
Create a FITS `~astropy.io.fits.ImageHDU` containing the input 2D image. Parameters ---------- data : 2D array-like The input 2D data. wcs : `~astropy.wcs.WCS`, optional The world coordinate system (WCS) transformation to include in the output FITS header. Returns ...
Below is the the instruction that describes the task: ### Input: Create a FITS `~astropy.io.fits.ImageHDU` containing the input 2D image. Parameters ---------- data : 2D array-like The input 2D data. wcs : `~astropy.wcs.WCS`, optional The world coordinate system (WCS) transform...
def obs(self): """ return the number of observations for your SASdata object """ code = "proc sql;select count(*) format best32. into :lastobs from " + self.libref + '.' + self.table + self._dsopts() + ";%put lastobs=&lastobs tom;quit;" if self.sas.nosub: print(code)...
return the number of observations for your SASdata object
Below is the the instruction that describes the task: ### Input: return the number of observations for your SASdata object ### Response: def obs(self): """ return the number of observations for your SASdata object """ code = "proc sql;select count(*) format best32. into :lastobs fro...
def which(name): """ Returns the full path to executable in path matching provided name. `name` String value. Returns string or ``None``. """ # we were given a filename, return it if it's executable if os.path.dirname(name) != '': if not os.path.isdir(name) and...
Returns the full path to executable in path matching provided name. `name` String value. Returns string or ``None``.
Below is the the instruction that describes the task: ### Input: Returns the full path to executable in path matching provided name. `name` String value. Returns string or ``None``. ### Response: def which(name): """ Returns the full path to executable in path matching provided na...
def start(self, blocking=False): """ Start the interface :param blocking: Should the call block until stop() is called (default: False) :type blocking: bool :rtype: None """ self.debug("()") # Init GPIO # Enable warnings GPIO.s...
Start the interface :param blocking: Should the call block until stop() is called (default: False) :type blocking: bool :rtype: None
Below is the the instruction that describes the task: ### Input: Start the interface :param blocking: Should the call block until stop() is called (default: False) :type blocking: bool :rtype: None ### Response: def start(self, blocking=False): """ Start the int...
def correlation_matvec(P, obs1, obs2=None, times=[1]): r"""Time-correlation for equilibrium experiment - via matrix vector products. Parameters ---------- P : (M, M) ndarray Transition matrix obs1 : (M,) ndarray Observable, represented as vector on state space obs2 : (M,) ndarra...
r"""Time-correlation for equilibrium experiment - via matrix vector products. Parameters ---------- P : (M, M) ndarray Transition matrix obs1 : (M,) ndarray Observable, represented as vector on state space obs2 : (M,) ndarray (optional) Second observable, for cross-correlati...
Below is the the instruction that describes the task: ### Input: r"""Time-correlation for equilibrium experiment - via matrix vector products. Parameters ---------- P : (M, M) ndarray Transition matrix obs1 : (M,) ndarray Observable, represented as vector on state space obs2 : (...
def delete_component(self, instance_name): '''Delete a component. Deletes the component specified by @ref instance_name from the manager. This will invalidate any objects that are children of this node. @param instance_name The instance name of the component to delete. @raises ...
Delete a component. Deletes the component specified by @ref instance_name from the manager. This will invalidate any objects that are children of this node. @param instance_name The instance name of the component to delete. @raises FailedToDeleteComponentError
Below is the the instruction that describes the task: ### Input: Delete a component. Deletes the component specified by @ref instance_name from the manager. This will invalidate any objects that are children of this node. @param instance_name The instance name of the component to delete. ...
def SXTB(self, params): """ STXB Ra, Rb Sign extend the byte in Rb and store the result in Ra """ Ra, Rb = self.get_two_parameters(r'\s*([^\s,]*),\s*([^\s,]*)(,\s*[^\s,]*)*\s*', params) self.check_arguments(low_registers=(Ra, Rb)) def SXTB_func(): i...
STXB Ra, Rb Sign extend the byte in Rb and store the result in Ra
Below is the the instruction that describes the task: ### Input: STXB Ra, Rb Sign extend the byte in Rb and store the result in Ra ### Response: def SXTB(self, params): """ STXB Ra, Rb Sign extend the byte in Rb and store the result in Ra """ Ra, Rb = self.get_two_...
def _download_audio_files(self, records, target_path): """ Download all audio files based on the given records. """ for record in records: audio_folder = os.path.join(target_path, 'audio', record[2]) audio_file = os.path.join(audio_folder, '{}.mp3'.format(record[...
Download all audio files based on the given records.
Below is the the instruction that describes the task: ### Input: Download all audio files based on the given records. ### Response: def _download_audio_files(self, records, target_path): """ Download all audio files based on the given records. """ for record in records: ...
def formfield(self, **kwargs): """Get the form for field.""" defaults = { 'form_class': RichTextFormField, 'config': self.config, } defaults.update(kwargs) return super(RichTextField, self).formfield(**defaults)
Get the form for field.
Below is the the instruction that describes the task: ### Input: Get the form for field. ### Response: def formfield(self, **kwargs): """Get the form for field.""" defaults = { 'form_class': RichTextFormField, 'config': self.config, } defaults.update(kwargs) ...
def pipe_reverse(context=None, _INPUT=None, conf=None, **kwargs): """An operator that reverses the order of source items. Not loopable. Not lazy. Parameters ---------- context : pipe2py.Context object _INPUT : pipe2py.modules pipe like object (iterable of items) conf : unused Yields ...
An operator that reverses the order of source items. Not loopable. Not lazy. Parameters ---------- context : pipe2py.Context object _INPUT : pipe2py.modules pipe like object (iterable of items) conf : unused Yields ------ _OUTPUT : items
Below is the the instruction that describes the task: ### Input: An operator that reverses the order of source items. Not loopable. Not lazy. Parameters ---------- context : pipe2py.Context object _INPUT : pipe2py.modules pipe like object (iterable of items) conf : unused Yields --...
def get_project_info(configs, heartbeat, data): """Find the current project and branch. First looks for a .wakatime-project file. Second, uses the --project arg. Third, uses the folder name from a revision control repository. Last, uses the --alternate-project arg. Returns a project, branch tuple....
Find the current project and branch. First looks for a .wakatime-project file. Second, uses the --project arg. Third, uses the folder name from a revision control repository. Last, uses the --alternate-project arg. Returns a project, branch tuple.
Below is the the instruction that describes the task: ### Input: Find the current project and branch. First looks for a .wakatime-project file. Second, uses the --project arg. Third, uses the folder name from a revision control repository. Last, uses the --alternate-project arg. Returns a project,...
def parallel_epd_lclist(lclist, externalparams, timecols=None, magcols=None, errcols=None, lcformat='hat-sql', lcformatdir=None, epdsmooth_sigclip=3.0, ...
This applies EPD in parallel to all LCs in the input list. Parameters ---------- lclist : list of str This is the list of light curve files to run EPD on. externalparams : dict or None This is a dict that indicates which keys in the lcdict obtained from the lcfile correspond t...
Below is the the instruction that describes the task: ### Input: This applies EPD in parallel to all LCs in the input list. Parameters ---------- lclist : list of str This is the list of light curve files to run EPD on. externalparams : dict or None This is a dict that indicates w...
async def variant(self, elem=None, elem_type=None, params=None): """ Loads/dumps variant type :param elem: :param elem_type: :param params: :return: """ elem_type = elem_type if elem_type else elem.__class__ version = await self.version(elem_type, ...
Loads/dumps variant type :param elem: :param elem_type: :param params: :return:
Below is the the instruction that describes the task: ### Input: Loads/dumps variant type :param elem: :param elem_type: :param params: :return: ### Response: async def variant(self, elem=None, elem_type=None, params=None): """ Loads/dumps variant type :param...
def all(self, instance): """Get all ACLs associated with the instance specified by name. :param str instance: The name of the instance from which to fetch ACLs. :returns: A list of :py:class:`Acl` objects associated with the specified instance. :rtype: list """ url = sel...
Get all ACLs associated with the instance specified by name. :param str instance: The name of the instance from which to fetch ACLs. :returns: A list of :py:class:`Acl` objects associated with the specified instance. :rtype: list
Below is the the instruction that describes the task: ### Input: Get all ACLs associated with the instance specified by name. :param str instance: The name of the instance from which to fetch ACLs. :returns: A list of :py:class:`Acl` objects associated with the specified instance. :rtype: l...
def show_rsa(minion_id, dns_name): ''' Show a private RSA key CLI Example: .. code-block:: bash salt-run digicert.show_rsa myminion domain.example.com ''' cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR) bank = 'digicert/domains' data = cache.fetch( bank, dns_nam...
Show a private RSA key CLI Example: .. code-block:: bash salt-run digicert.show_rsa myminion domain.example.com
Below is the the instruction that describes the task: ### Input: Show a private RSA key CLI Example: .. code-block:: bash salt-run digicert.show_rsa myminion domain.example.com ### Response: def show_rsa(minion_id, dns_name): ''' Show a private RSA key CLI Example: .. code-bloc...
def get_all_users(**kwargs): """ Get the username & ID of all users. Use the the filter if it has been provided The filter has to be a list of values """ users_qry = db.DBSession.query(User) filter_type = kwargs.get('filter_type') filter_value = kwargs.get('filter_value') ...
Get the username & ID of all users. Use the the filter if it has been provided The filter has to be a list of values
Below is the the instruction that describes the task: ### Input: Get the username & ID of all users. Use the the filter if it has been provided The filter has to be a list of values ### Response: def get_all_users(**kwargs): """ Get the username & ID of all users. Use the the fi...
def add_resource(self, ref, **properties): """Add one or more resources entities, from a url and property values, possibly adding multiple entries for an excel spreadsheet or ZIP file""" raise NotImplementedError("Still uses decompose_url") du = Bunch(decompose_url(ref)) added...
Add one or more resources entities, from a url and property values, possibly adding multiple entries for an excel spreadsheet or ZIP file
Below is the the instruction that describes the task: ### Input: Add one or more resources entities, from a url and property values, possibly adding multiple entries for an excel spreadsheet or ZIP file ### Response: def add_resource(self, ref, **properties): """Add one or more resources entities, ...
def workflow_states_column(self, obj): """ Return text description of workflow states assigned to object """ workflow_states = models.WorkflowState.objects.filter( content_type=self._get_obj_ct(obj), object_id=obj.pk, ) return ', '.join([unicode(wfs) for wfs in wo...
Return text description of workflow states assigned to object
Below is the the instruction that describes the task: ### Input: Return text description of workflow states assigned to object ### Response: def workflow_states_column(self, obj): """ Return text description of workflow states assigned to object """ workflow_states = models.WorkflowState.objects.fi...
def _append_comment(ret, comment): ''' append ``comment`` to ``ret['comment']`` ''' if ret['comment']: ret['comment'] = ret['comment'].rstrip() + '\n' + comment else: ret['comment'] = comment return ret
append ``comment`` to ``ret['comment']``
Below is the the instruction that describes the task: ### Input: append ``comment`` to ``ret['comment']`` ### Response: def _append_comment(ret, comment): ''' append ``comment`` to ``ret['comment']`` ''' if ret['comment']: ret['comment'] = ret['comment'].rstrip() + '\n' + comment else: ...
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'results') and self.results is not None: _dict['results'] = [x._to_dict() for x in self.results] if hasattr(self, 'result_index') and self.result_index is not None: ...
Return a json dictionary representing this model.
Below is the the instruction that describes the task: ### Input: Return a json dictionary representing this model. ### Response: def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'results') and self.results is not None: _dict...
def _cast_to_type(self, value): """ Convert the value to an int and raise error on failures""" try: return int(value) except (ValueError, TypeError): self.fail('invalid', value=value)
Convert the value to an int and raise error on failures
Below is the the instruction that describes the task: ### Input: Convert the value to an int and raise error on failures ### Response: def _cast_to_type(self, value): """ Convert the value to an int and raise error on failures""" try: return int(value) except (ValueError, TypeEr...
def _clean(self, value): """Perform a standardized pipline of operations across an iterable.""" value = (str(v) for v in value) if self.strip: value = (v.strip() for v in value) if not self.empty: value = (v for v in value if v) return value
Perform a standardized pipline of operations across an iterable.
Below is the the instruction that describes the task: ### Input: Perform a standardized pipline of operations across an iterable. ### Response: def _clean(self, value): """Perform a standardized pipline of operations across an iterable.""" value = (str(v) for v in value) if self.strip: value = (v.st...
def get_for_control_var_and_eval_expr(comm_type, kwargs): """Returns tuple that consists of control variable name and iterable that is result of evaluated expression of given for loop. For example: - given 'for $i in $(echo "foo bar")' it returns (['i'], ['foo', 'bar']) - given 'for $i, $j in $foo'...
Returns tuple that consists of control variable name and iterable that is result of evaluated expression of given for loop. For example: - given 'for $i in $(echo "foo bar")' it returns (['i'], ['foo', 'bar']) - given 'for $i, $j in $foo' it returns (['i', 'j'], [('foo', 'bar')])
Below is the the instruction that describes the task: ### Input: Returns tuple that consists of control variable name and iterable that is result of evaluated expression of given for loop. For example: - given 'for $i in $(echo "foo bar")' it returns (['i'], ['foo', 'bar']) - given 'for $i, $j in $...
def build_sourcemap(sources): """ Similar to build_headermap(), but builds a dictionary of includes from the "source" files (i.e. ".c/.cc" files). """ sourcemap = {} for sfile in sources: inc = find_includes(sfile) sourcemap[sfile] = set(inc) return sourcemap
Similar to build_headermap(), but builds a dictionary of includes from the "source" files (i.e. ".c/.cc" files).
Below is the the instruction that describes the task: ### Input: Similar to build_headermap(), but builds a dictionary of includes from the "source" files (i.e. ".c/.cc" files). ### Response: def build_sourcemap(sources): """ Similar to build_headermap(), but builds a dictionary of includes from th...
def makeEndOfPrdvPfuncCond(self): ''' Construct the end-of-period marginal value function conditional on next period's state. Parameters ---------- None Returns ------- EndofPrdvPfunc_cond : MargValueFunc The end-of-period marginal va...
Construct the end-of-period marginal value function conditional on next period's state. Parameters ---------- None Returns ------- EndofPrdvPfunc_cond : MargValueFunc The end-of-period marginal value function conditional on a particular s...
Below is the the instruction that describes the task: ### Input: Construct the end-of-period marginal value function conditional on next period's state. Parameters ---------- None Returns ------- EndofPrdvPfunc_cond : MargValueFunc The end-of-per...
def set_disk_timeout(timeout, power='ac', scheme=None): ''' Set the disk timeout in minutes for the given power scheme Args: timeout (int): The amount of time in minutes before the disk will timeout power (str): Set the value for AC or DC power. Default is ``ac``. V...
Set the disk timeout in minutes for the given power scheme Args: timeout (int): The amount of time in minutes before the disk will timeout power (str): Set the value for AC or DC power. Default is ``ac``. Valid options are: - ``ac`` (AC Power) ...
Below is the the instruction that describes the task: ### Input: Set the disk timeout in minutes for the given power scheme Args: timeout (int): The amount of time in minutes before the disk will timeout power (str): Set the value for AC or DC power. Default is ``ac``. ...
def _paload8(ins): ''' Loads an 8 bit value from a memory address If 2nd arg. start with '*', it is always treated as an indirect value. ''' output = _paddr(ins.quad[2]) output.append('ld a, (hl)') output.append('push af') return output
Loads an 8 bit value from a memory address If 2nd arg. start with '*', it is always treated as an indirect value.
Below is the the instruction that describes the task: ### Input: Loads an 8 bit value from a memory address If 2nd arg. start with '*', it is always treated as an indirect value. ### Response: def _paload8(ins): ''' Loads an 8 bit value from a memory address If 2nd arg. start with '*', it is always...
def _check_action(action): """check for invalid actions""" if isinstance(action, types.StringTypes): action = action.lower() if action not in ['learn', 'forget', 'report', 'revoke']: raise SpamCError('The action option is invalid') return action
check for invalid actions
Below is the the instruction that describes the task: ### Input: check for invalid actions ### Response: def _check_action(action): """check for invalid actions""" if isinstance(action, types.StringTypes): action = action.lower() if action not in ['learn', 'forget', 'report', 'revoke']: ...
def tweets_default(*args): """ Tweets for the default settings. """ query_type = settings.TWITTER_DEFAULT_QUERY_TYPE args = (settings.TWITTER_DEFAULT_QUERY, settings.TWITTER_DEFAULT_NUM_TWEETS) per_user = None if query_type == QUERY_TYPE_LIST: per_user = 1 return twee...
Tweets for the default settings.
Below is the the instruction that describes the task: ### Input: Tweets for the default settings. ### Response: def tweets_default(*args): """ Tweets for the default settings. """ query_type = settings.TWITTER_DEFAULT_QUERY_TYPE args = (settings.TWITTER_DEFAULT_QUERY, settings.TWITT...
def write_def_finish(self, node, buffered, filtered, cached, callstack=True): """write the end section of a rendering function, either outermost or inline. this takes into account if the rendering function was filtered, buffered, etc. and closes the corresponding try: block...
write the end section of a rendering function, either outermost or inline. this takes into account if the rendering function was filtered, buffered, etc. and closes the corresponding try: block if any, and writes code to retrieve captured content, apply filters, send proper ret...
Below is the the instruction that describes the task: ### Input: write the end section of a rendering function, either outermost or inline. this takes into account if the rendering function was filtered, buffered, etc. and closes the corresponding try: block if any, and writes code...
def setCovariance(self,cov): """ set hyperparameters from given covariance """ chol = LA.cholesky(cov,lower=True) params = chol[sp.tril_indices(self.dim)] self.setParams(params)
set hyperparameters from given covariance
Below is the the instruction that describes the task: ### Input: set hyperparameters from given covariance ### Response: def setCovariance(self,cov): """ set hyperparameters from given covariance """ chol = LA.cholesky(cov,lower=True) params = chol[sp.tril_indices(self.dim)] self.se...
def execute(self): """Run selected module generator.""" if self._cli_arguments['cfn']: generate_sample_cfn_module(self.env_root) elif self._cli_arguments['sls']: generate_sample_sls_module(self.env_root) elif self._cli_arguments['sls-tsc']: generate_sa...
Run selected module generator.
Below is the the instruction that describes the task: ### Input: Run selected module generator. ### Response: def execute(self): """Run selected module generator.""" if self._cli_arguments['cfn']: generate_sample_cfn_module(self.env_root) elif self._cli_arguments['sls']: ...
def source_range_slices(start, end, nr_var_dict): """ Given a range of source numbers, as well as a dictionary containing the numbers of each source, returns a dictionary containing slices for each source variable type. """ return OrderedDict((k, slice(s,e,1)) for k, (s, e) in s...
Given a range of source numbers, as well as a dictionary containing the numbers of each source, returns a dictionary containing slices for each source variable type.
Below is the the instruction that describes the task: ### Input: Given a range of source numbers, as well as a dictionary containing the numbers of each source, returns a dictionary containing slices for each source variable type. ### Response: def source_range_slices(start, end, nr_var_dict): """ ...
def _parse_expr(text, ldelim="(", rdelim=")"): """Parse mathematical expression using PyParsing.""" var = pyparsing.Word(pyparsing.alphas + "_", pyparsing.alphanums + "_") point = pyparsing.Literal(".") exp = pyparsing.CaselessLiteral("E") number = pyparsing.Combine( pyparsing.Word("+-" + py...
Parse mathematical expression using PyParsing.
Below is the the instruction that describes the task: ### Input: Parse mathematical expression using PyParsing. ### Response: def _parse_expr(text, ldelim="(", rdelim=")"): """Parse mathematical expression using PyParsing.""" var = pyparsing.Word(pyparsing.alphas + "_", pyparsing.alphanums + "_") point...
def apply_units_to_cache(self, data): """ Apply units to :class:`ParameterizedXLS` data reader. """ # parameter parameter_name = self.parameters['parameter']['name'] parameter_units = str(self.parameters['parameter']['units']) data[parameter_name] *= UREG(paramete...
Apply units to :class:`ParameterizedXLS` data reader.
Below is the the instruction that describes the task: ### Input: Apply units to :class:`ParameterizedXLS` data reader. ### Response: def apply_units_to_cache(self, data): """ Apply units to :class:`ParameterizedXLS` data reader. """ # parameter parameter_name = self.paramete...
def job_from_resource(self, resource): """Detect correct job type from resource and instantiate. :type resource: dict :param resource: one job resource from API response :rtype: One of: :class:`google.cloud.bigquery.job.LoadJob`, :class:`google.cloud.big...
Detect correct job type from resource and instantiate. :type resource: dict :param resource: one job resource from API response :rtype: One of: :class:`google.cloud.bigquery.job.LoadJob`, :class:`google.cloud.bigquery.job.CopyJob`, :class:`google...
Below is the the instruction that describes the task: ### Input: Detect correct job type from resource and instantiate. :type resource: dict :param resource: one job resource from API response :rtype: One of: :class:`google.cloud.bigquery.job.LoadJob`, :clas...
def upsert(cls, name, **fields): """Insert or update an instance""" instance = cls.get(name) if instance: instance._set_fields(fields) else: instance = cls(name=name, **fields) instance = failsafe_add(cls.query.session, instance, name=name) ret...
Insert or update an instance
Below is the the instruction that describes the task: ### Input: Insert or update an instance ### Response: def upsert(cls, name, **fields): """Insert or update an instance""" instance = cls.get(name) if instance: instance._set_fields(fields) else: instance =...
def initialize(self, request): """Store the data we'll need to make the postback from the request object.""" if request.method == 'GET': # PDT only - this data is currently unused self.query = request.META.get('QUERY_STRING', '') elif request.method == 'POST': ...
Store the data we'll need to make the postback from the request object.
Below is the the instruction that describes the task: ### Input: Store the data we'll need to make the postback from the request object. ### Response: def initialize(self, request): """Store the data we'll need to make the postback from the request object.""" if request.method == 'GET': ...
def calculate_checksum_on_bytes( b, algorithm=d1_common.const.DEFAULT_CHECKSUM_ALGORITHM ): """Calculate the checksum of ``bytes``. Warning: This method requires the entire object to be buffered in (virtual) memory, which should normally be avoided in production code. Args: b: bytes ...
Calculate the checksum of ``bytes``. Warning: This method requires the entire object to be buffered in (virtual) memory, which should normally be avoided in production code. Args: b: bytes Raw bytes algorithm: str Checksum algorithm, ``MD5`` or ``SHA1`` / ``SHA-1``. Retur...
Below is the the instruction that describes the task: ### Input: Calculate the checksum of ``bytes``. Warning: This method requires the entire object to be buffered in (virtual) memory, which should normally be avoided in production code. Args: b: bytes Raw bytes algorithm: str ...
def stash(self, path): """Stashes the directory or file and returns its new location. """ if os.path.isdir(path): new_path = self._get_directory_stash(path) else: new_path = self._get_file_stash(path) self._moves.append((path, new_path)) if os.pat...
Stashes the directory or file and returns its new location.
Below is the the instruction that describes the task: ### Input: Stashes the directory or file and returns its new location. ### Response: def stash(self, path): """Stashes the directory or file and returns its new location. """ if os.path.isdir(path): new_path = self._get_direc...
def getOperationNameForId(i: int): """ Convert an operation id into the corresponding string """ assert isinstance(i, (int)), "This method expects an integer argument" for key in operations: if int(operations[key]) is int(i): return key raise ValueError("Unknown Operation ID %d" ...
Convert an operation id into the corresponding string
Below is the the instruction that describes the task: ### Input: Convert an operation id into the corresponding string ### Response: def getOperationNameForId(i: int): """ Convert an operation id into the corresponding string """ assert isinstance(i, (int)), "This method expects an integer argument" ...
def unpack_to_nibbles(bindata): """unpack packed binary data to nibbles :param bindata: binary packed from nibbles :return: nibbles sequence, may have a terminator """ o = bin_to_nibbles(bindata) flags = o[0] if flags & 2: o.append(NIBBLE_TERMINATOR) if flags & 1 == 1: o...
unpack packed binary data to nibbles :param bindata: binary packed from nibbles :return: nibbles sequence, may have a terminator
Below is the the instruction that describes the task: ### Input: unpack packed binary data to nibbles :param bindata: binary packed from nibbles :return: nibbles sequence, may have a terminator ### Response: def unpack_to_nibbles(bindata): """unpack packed binary data to nibbles :param bindata: b...
def _copy(self): """Creates a deep copy of this request.""" copied_uri = Uri(self.uri.scheme, self.uri.host, self.uri.port, self.uri.path, self.uri.query.copy()) new_request = HttpRequest(uri=copied_uri, method=self.method, headers=self.headers.copy()) ...
Creates a deep copy of this request.
Below is the the instruction that describes the task: ### Input: Creates a deep copy of this request. ### Response: def _copy(self): """Creates a deep copy of this request.""" copied_uri = Uri(self.uri.scheme, self.uri.host, self.uri.port, self.uri.path, self.uri.query.copy()) new_...
def Draw(self, *args, **kwargs): """ Parameters ---------- args : positional arguments Positional arguments are passed directly to ROOT's Draw kwargs : keyword arguments If keyword arguments are present, then a clone is drawn instead with DrawC...
Parameters ---------- args : positional arguments Positional arguments are passed directly to ROOT's Draw kwargs : keyword arguments If keyword arguments are present, then a clone is drawn instead with DrawCopy, where the name, title, and style attributes are ...
Below is the the instruction that describes the task: ### Input: Parameters ---------- args : positional arguments Positional arguments are passed directly to ROOT's Draw kwargs : keyword arguments If keyword arguments are present, then a clone is drawn instead ...
def load_characters(self): """Fetches the MAL media characters page and sets the current media's character attributes. :rtype: :class:`.Media` :return: current media object. """ characters_page = self.session.session.get(u'http://myanimelist.net/' + self.__class__.__name__.lower() + u'/' + str(sel...
Fetches the MAL media characters page and sets the current media's character attributes. :rtype: :class:`.Media` :return: current media object.
Below is the the instruction that describes the task: ### Input: Fetches the MAL media characters page and sets the current media's character attributes. :rtype: :class:`.Media` :return: current media object. ### Response: def load_characters(self): """Fetches the MAL media characters page and sets th...
def write(self, text, flush=False, error=False, prompt=False): """Simulate stdout and stderr""" if prompt: self.flush() if not is_string(text): # This test is useful to discriminate QStrings from decoded str text = to_text_string(text) self.__bu...
Simulate stdout and stderr
Below is the the instruction that describes the task: ### Input: Simulate stdout and stderr ### Response: def write(self, text, flush=False, error=False, prompt=False): """Simulate stdout and stderr""" if prompt: self.flush() if not is_string(text): # This test ...
def up(tgt='*', tgt_type='glob', timeout=None, gather_job_timeout=None): # pylint: disable=C0103 ''' .. versionchanged:: 2017.7.0 The ``expr_form`` argument has been renamed to ``tgt_type``, earlier releases must use ``expr_form``. Print a list of all of the minions that are up CLI Ex...
.. versionchanged:: 2017.7.0 The ``expr_form`` argument has been renamed to ``tgt_type``, earlier releases must use ``expr_form``. Print a list of all of the minions that are up CLI Example: .. code-block:: bash salt-run manage.up salt-run manage.up tgt="webservers" tgt_t...
Below is the the instruction that describes the task: ### Input: .. versionchanged:: 2017.7.0 The ``expr_form`` argument has been renamed to ``tgt_type``, earlier releases must use ``expr_form``. Print a list of all of the minions that are up CLI Example: .. code-block:: bash ...
def download_icon_font(icon_font, directory): """Download given (implemented) icon font into passed directory""" try: downloader = AVAILABLE_ICON_FONTS[icon_font]['downloader'](directory) downloader.download_files() return downloader except KeyError: # pragma: no cover raise...
Download given (implemented) icon font into passed directory
Below is the the instruction that describes the task: ### Input: Download given (implemented) icon font into passed directory ### Response: def download_icon_font(icon_font, directory): """Download given (implemented) icon font into passed directory""" try: downloader = AVAILABLE_ICON_FONTS[icon_fo...
def current_kv_names(self): """Return set of string names of current available Splunk KV collections""" return current_kv_names(self.sci, self.username, self.appname, request=self._request)
Return set of string names of current available Splunk KV collections
Below is the the instruction that describes the task: ### Input: Return set of string names of current available Splunk KV collections ### Response: def current_kv_names(self): """Return set of string names of current available Splunk KV collections""" return current_kv_names(self.sci, self.usernam...
def personal_unlockAccount(self, address, passphrase=None, duration=None): """https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_unlockaccount :param address: Account address :type address: str :param passphrase: Passphrase of account (optional) :type passphr...
https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_unlockaccount :param address: Account address :type address: str :param passphrase: Passphrase of account (optional) :type passphrase: str :param duration: Duration to be unlocked (optional) :type du...
Below is the the instruction that describes the task: ### Input: https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_unlockaccount :param address: Account address :type address: str :param passphrase: Passphrase of account (optional) :type passphrase: str ...
def sort_by_name(names): """Sort by last name, uniquely.""" def last_name_key(full_name): parts = full_name.split(' ') if len(parts) == 1: return full_name.upper() last_first = parts[-1] + ' ' + ' '.join(parts[:-1]) return last_first.upper() return sorted(set(na...
Sort by last name, uniquely.
Below is the the instruction that describes the task: ### Input: Sort by last name, uniquely. ### Response: def sort_by_name(names): """Sort by last name, uniquely.""" def last_name_key(full_name): parts = full_name.split(' ') if len(parts) == 1: return full_name.upper() ...
def viewport(self) -> Tuple[int, int, int, int]: ''' tuple: The viewport of the framebuffer. ''' return self.mglo.viewport
tuple: The viewport of the framebuffer.
Below is the the instruction that describes the task: ### Input: tuple: The viewport of the framebuffer. ### Response: def viewport(self) -> Tuple[int, int, int, int]: ''' tuple: The viewport of the framebuffer. ''' return self.mglo.viewport
def map(self, callable): """ Apply 'callable' function over all values. """ for k,v in self.iteritems(): self[k] = callable(v)
Apply 'callable' function over all values.
Below is the the instruction that describes the task: ### Input: Apply 'callable' function over all values. ### Response: def map(self, callable): """ Apply 'callable' function over all values. """ for k,v in self.iteritems(): self[k] = callable(v)
def get_correctness(self, question_id): """get measure of correctness for the question""" response = self.get_response(question_id) if response.is_answered(): item = self._get_item(response.get_item_id()) return item.get_correctness_for_response(response) raise er...
get measure of correctness for the question
Below is the the instruction that describes the task: ### Input: get measure of correctness for the question ### Response: def get_correctness(self, question_id): """get measure of correctness for the question""" response = self.get_response(question_id) if response.is_answered(): ...
def _exists(self, path): """S3 directory is not S3Ojbect. """ if path.endswith('/'): return True return self.storage.exists(path)
S3 directory is not S3Ojbect.
Below is the the instruction that describes the task: ### Input: S3 directory is not S3Ojbect. ### Response: def _exists(self, path): """S3 directory is not S3Ojbect. """ if path.endswith('/'): return True return self.storage.exists(path)
def repositories(self): """Get dependencies by repositories """ if self.repo == "sbo": self.sbo_case_insensitive() self.find_pkg = sbo_search_pkg(self.name) if self.find_pkg: self.dependencies_list = Requires(self.flag).sbo(self.name) e...
Get dependencies by repositories
Below is the the instruction that describes the task: ### Input: Get dependencies by repositories ### Response: def repositories(self): """Get dependencies by repositories """ if self.repo == "sbo": self.sbo_case_insensitive() self.find_pkg = sbo_search_pkg(self.name...
def close(self): """ Stop the server. """ logger.info("Stop server") self.stopped.set() for event in self.to_be_stopped: event.set() self._socket.close()
Stop the server.
Below is the the instruction that describes the task: ### Input: Stop the server. ### Response: def close(self): """ Stop the server. """ logger.info("Stop server") self.stopped.set() for event in self.to_be_stopped: event.set() self._socket.clos...
def prefilter_lines(self, lines, continue_prompt=False): """Prefilter multiple input lines of text. This is the main entry point for prefiltering multiple lines of input. This simply calls :meth:`prefilter_line` for each line of input. This covers cases where there are multipl...
Prefilter multiple input lines of text. This is the main entry point for prefiltering multiple lines of input. This simply calls :meth:`prefilter_line` for each line of input. This covers cases where there are multiple lines in the user entry, which is the case when the user g...
Below is the the instruction that describes the task: ### Input: Prefilter multiple input lines of text. This is the main entry point for prefiltering multiple lines of input. This simply calls :meth:`prefilter_line` for each line of input. This covers cases where there are multip...
def order_modified_volume(self, volume_id, new_size=None, new_iops=None, new_tier_level=None): """Places an order for modifying an existing block volume. :param volume_id: The ID of the volume to be modified :param new_size: The new size/capacity for the volume :param new_iops: The new ...
Places an order for modifying an existing block volume. :param volume_id: The ID of the volume to be modified :param new_size: The new size/capacity for the volume :param new_iops: The new IOPS for the volume :param new_tier_level: The new tier level for the volume :return: Retu...
Below is the the instruction that describes the task: ### Input: Places an order for modifying an existing block volume. :param volume_id: The ID of the volume to be modified :param new_size: The new size/capacity for the volume :param new_iops: The new IOPS for the volume :param ne...
def export_throw_event_info(node_params, output_element): """ Adds EndEvent or IntermediateThrowingEvent attributes to exported XML element :param node_params: dictionary with given intermediate throw event parameters, :param output_element: object representing BPMN XML 'intermediateThr...
Adds EndEvent or IntermediateThrowingEvent attributes to exported XML element :param node_params: dictionary with given intermediate throw event parameters, :param output_element: object representing BPMN XML 'intermediateThrowEvent' element.
Below is the the instruction that describes the task: ### Input: Adds EndEvent or IntermediateThrowingEvent attributes to exported XML element :param node_params: dictionary with given intermediate throw event parameters, :param output_element: object representing BPMN XML 'intermediateThrowEvent' ...
def estimate_shift(x, y, smoother=None, w=None, index_and_value=False, ignore_edge=1/3., method='valid'): """Estimate the time shift between two signals based on their cross correlation Arguements: smoother: Smoothing function applied to correlation values before finding peak w:...
Estimate the time shift between two signals based on their cross correlation Arguements: smoother: Smoothing function applied to correlation values before finding peak w: Window. Sequence of values between 0 and 1 for wind centered on 0-shift to weight correlation by before fi...
Below is the the instruction that describes the task: ### Input: Estimate the time shift between two signals based on their cross correlation Arguements: smoother: Smoothing function applied to correlation values before finding peak w: Window. Sequence of values between 0 and 1 for wind ce...
def sample(self, n_samples): """Generate specified `n_samples` of new data from model. `v~U[0,1],v~C^-1(u|v)` Args: n_samples: `int`, amount of samples to create. Returns: np.ndarray: Array of length `n_samples` with generated data from the model. """ if...
Generate specified `n_samples` of new data from model. `v~U[0,1],v~C^-1(u|v)` Args: n_samples: `int`, amount of samples to create. Returns: np.ndarray: Array of length `n_samples` with generated data from the model.
Below is the the instruction that describes the task: ### Input: Generate specified `n_samples` of new data from model. `v~U[0,1],v~C^-1(u|v)` Args: n_samples: `int`, amount of samples to create. Returns: np.ndarray: Array of length `n_samples` with generated data from the ...
def createStatus(self, project_id, branch, sha, state, target_url=None, description=None, context=None): """ :param project_id: Project ID from GitLab :param branch: Branch name to create the status for. :param sha: Full sha to create the status ...
:param project_id: Project ID from GitLab :param branch: Branch name to create the status for. :param sha: Full sha to create the status for. :param state: one of the following 'pending', 'success', 'failed' or 'cancelled'. :param target_url: Target url to associate...
Below is the the instruction that describes the task: ### Input: :param project_id: Project ID from GitLab :param branch: Branch name to create the status for. :param sha: Full sha to create the status for. :param state: one of the following 'pending', 'success', 'failed' ...
def nonlocal_packages_path(self): """Returns package search paths with local path removed.""" paths = self.packages_path[:] if self.local_packages_path in paths: paths.remove(self.local_packages_path) return paths
Returns package search paths with local path removed.
Below is the the instruction that describes the task: ### Input: Returns package search paths with local path removed. ### Response: def nonlocal_packages_path(self): """Returns package search paths with local path removed.""" paths = self.packages_path[:] if self.local_packages_path in pat...
def to_currency(self, val, currency='EUR', cents=True, separator=',', adjective=False): """ Args: val: Numeric value currency (str): Currency code cents (bool): Verbose cents separator (str): Cent separator adjective (bool):...
Args: val: Numeric value currency (str): Currency code cents (bool): Verbose cents separator (str): Cent separator adjective (bool): Prefix currency name with adjective Returns: str: Formatted string
Below is the the instruction that describes the task: ### Input: Args: val: Numeric value currency (str): Currency code cents (bool): Verbose cents separator (str): Cent separator adjective (bool): Prefix currency name with adjective Returns: ...
def decode_body(body, content_type): """Decode event body""" if isinstance(body, dict): return body else: try: decoded_body = base64.b64decode(body) except: return body if content_type == 'application/json': ...
Decode event body
Below is the the instruction that describes the task: ### Input: Decode event body ### Response: def decode_body(body, content_type): """Decode event body""" if isinstance(body, dict): return body else: try: decoded_body = base64.b64decode(body) ...
def named(self, name): '''Returns .get_by('name', name)''' name = self.serialize(name) return self.get_by('name', name)
Returns .get_by('name', name)
Below is the the instruction that describes the task: ### Input: Returns .get_by('name', name) ### Response: def named(self, name): '''Returns .get_by('name', name)''' name = self.serialize(name) return self.get_by('name', name)
def cache_py2_modules(): """ Currently this function is unneeded, as we are not attempting to provide import hooks for modules with ambiguous names: email, urllib, pickle. """ if len(sys.py2_modules) != 0: return assert not detect_hooks() import urllib sys.py2_modules['urllib'] =...
Currently this function is unneeded, as we are not attempting to provide import hooks for modules with ambiguous names: email, urllib, pickle.
Below is the the instruction that describes the task: ### Input: Currently this function is unneeded, as we are not attempting to provide import hooks for modules with ambiguous names: email, urllib, pickle. ### Response: def cache_py2_modules(): """ Currently this function is unneeded, as we are not a...
def delete_plate(self, plate_id, delete_meta_data=False): """ Delete a plate from the database :param plate_id: The plate id :param delete_meta_data: Optionally delete all meta data associated with this plate as well :return: None """ if plate_id not in ...
Delete a plate from the database :param plate_id: The plate id :param delete_meta_data: Optionally delete all meta data associated with this plate as well :return: None
Below is the the instruction that describes the task: ### Input: Delete a plate from the database :param plate_id: The plate id :param delete_meta_data: Optionally delete all meta data associated with this plate as well :return: None ### Response: def delete_plate(self, plate_id, d...
def list_math_addition(a, b): """! @brief Addition of two lists. @details Each element from list 'a' is added to element from list 'b' accordingly. @param[in] a (list): List of elements that supports mathematic addition.. @param[in] b (list): List of elements that supports mathematic addi...
! @brief Addition of two lists. @details Each element from list 'a' is added to element from list 'b' accordingly. @param[in] a (list): List of elements that supports mathematic addition.. @param[in] b (list): List of elements that supports mathematic addition.. @return (list) Resul...
Below is the the instruction that describes the task: ### Input: ! @brief Addition of two lists. @details Each element from list 'a' is added to element from list 'b' accordingly. @param[in] a (list): List of elements that supports mathematic addition.. @param[in] b (list): List of element...
def detect_file_triggers(trigger_patterns): """The existence of files matching configured globs will trigger a version bump""" triggers = set() for trigger, pattern in trigger_patterns.items(): matches = glob.glob(pattern) if matches: _LOG.debug("trigger: %s bump from %r\n\t%s", ...
The existence of files matching configured globs will trigger a version bump
Below is the the instruction that describes the task: ### Input: The existence of files matching configured globs will trigger a version bump ### Response: def detect_file_triggers(trigger_patterns): """The existence of files matching configured globs will trigger a version bump""" triggers = set() for...
def security_group_get(auth=None, **kwargs): ''' Get a single security group. This will create a default security group if one does not exist yet for a particular project id. filters A Python dictionary of filter conditions to push down CLI Example: .. code-block:: bash salt ...
Get a single security group. This will create a default security group if one does not exist yet for a particular project id. filters A Python dictionary of filter conditions to push down CLI Example: .. code-block:: bash salt '*' neutronng.security_group_get \ name=1dcac31...
Below is the the instruction that describes the task: ### Input: Get a single security group. This will create a default security group if one does not exist yet for a particular project id. filters A Python dictionary of filter conditions to push down CLI Example: .. code-block:: bash ...
def remove_uuid_id_like_indexes(app_name, database=None): """ Remove all of varchar_pattern_ops indexes that django created for uuid columns. A search is never done with a filter of the style (uuid__like='1ae3c%'), so all such indexes can be removed from Versionable models. This will only try to...
Remove all of varchar_pattern_ops indexes that django created for uuid columns. A search is never done with a filter of the style (uuid__like='1ae3c%'), so all such indexes can be removed from Versionable models. This will only try to remove indexes if they exist in the database, so it should be saf...
Below is the the instruction that describes the task: ### Input: Remove all of varchar_pattern_ops indexes that django created for uuid columns. A search is never done with a filter of the style (uuid__like='1ae3c%'), so all such indexes can be removed from Versionable models. This will only try to ...
def _startProgramsNode(self, name, attrs): """Process the start of a node under xtvd/programs""" if name == 'program': self._programId = attrs.get('id') self._series = None self._title = None self._subtitle = None self._description = None ...
Process the start of a node under xtvd/programs
Below is the the instruction that describes the task: ### Input: Process the start of a node under xtvd/programs ### Response: def _startProgramsNode(self, name, attrs): """Process the start of a node under xtvd/programs""" if name == 'program': self._programId = attrs.get('id') ...
def _create_child(self, tag): """Create a new child element with the given tag.""" return etree.SubElement(self._root, self._get_namespace_tag(tag))
Create a new child element with the given tag.
Below is the the instruction that describes the task: ### Input: Create a new child element with the given tag. ### Response: def _create_child(self, tag): """Create a new child element with the given tag.""" return etree.SubElement(self._root, self._get_namespace_tag(tag))
def to_dict(self): """ Get a dictionary of the attributes of this Language object, which can be useful for constructing a similar object. """ if self._dict is not None: return self._dict result = {} for key in self.ATTRIBUTES: value = geta...
Get a dictionary of the attributes of this Language object, which can be useful for constructing a similar object.
Below is the the instruction that describes the task: ### Input: Get a dictionary of the attributes of this Language object, which can be useful for constructing a similar object. ### Response: def to_dict(self): """ Get a dictionary of the attributes of this Language object, which ...
def colorstart(fgcolor, bgcolor, weight): ''' Begin a text style. ''' if weight: weight = bold else: weight = norm if bgcolor: out('\x1b[%s;%s;%sm' % (weight, fgcolor, bgcolor)) else: out('\x1b[%s;%sm' % (weight, fgcolor))
Begin a text style.
Below is the the instruction that describes the task: ### Input: Begin a text style. ### Response: def colorstart(fgcolor, bgcolor, weight): ''' Begin a text style. ''' if weight: weight = bold else: weight = norm if bgcolor: out('\x1b[%s;%s;%sm' % (weight, fgcolor, bgcolor)...
def get_identifier(self): """Validate and returns disqus_identifier option value. :returns: disqus_identifier config value. :rtype: str """ if 'disqus_identifier' in self.options: return self.options['disqus_identifier'] title_nodes = self.state.document.tra...
Validate and returns disqus_identifier option value. :returns: disqus_identifier config value. :rtype: str
Below is the the instruction that describes the task: ### Input: Validate and returns disqus_identifier option value. :returns: disqus_identifier config value. :rtype: str ### Response: def get_identifier(self): """Validate and returns disqus_identifier option value. :returns: dis...
def get_value(self, label, takeable=False): """ Retrieve single value at passed index label .. deprecated:: 0.21.0 Please use .at[] or .iat[] accessors. Parameters ---------- index : label takeable : interpret the index as indexers, default False ...
Retrieve single value at passed index label .. deprecated:: 0.21.0 Please use .at[] or .iat[] accessors. Parameters ---------- index : label takeable : interpret the index as indexers, default False Returns ------- value : scalar value
Below is the the instruction that describes the task: ### Input: Retrieve single value at passed index label .. deprecated:: 0.21.0 Please use .at[] or .iat[] accessors. Parameters ---------- index : label takeable : interpret the index as indexers, default False ...
def k_depth(d, depth, _counter=1): """Iterate keys on specific depth. depth has to be greater equal than 0. Usage reference see :meth:`DictTree.kv_depth()<DictTree.kv_depth>` """ if depth == 0: yield d[_meta]["_rootname"] else: if _counter == dept...
Iterate keys on specific depth. depth has to be greater equal than 0. Usage reference see :meth:`DictTree.kv_depth()<DictTree.kv_depth>`
Below is the the instruction that describes the task: ### Input: Iterate keys on specific depth. depth has to be greater equal than 0. Usage reference see :meth:`DictTree.kv_depth()<DictTree.kv_depth>` ### Response: def k_depth(d, depth, _counter=1): """Iterate keys on specific depth. ...
def _compute_asset_lifetimes(self, country_codes): """ Compute and cache a recarray of asset lifetimes. """ equities_cols = self.equities.c if country_codes: buf = np.array( tuple( sa.select(( equities_cols.s...
Compute and cache a recarray of asset lifetimes.
Below is the the instruction that describes the task: ### Input: Compute and cache a recarray of asset lifetimes. ### Response: def _compute_asset_lifetimes(self, country_codes): """ Compute and cache a recarray of asset lifetimes. """ equities_cols = self.equities.c if coun...
def get_file_descriptor(self): """Return the file descriptor for the given websocket""" try: return uwsgi.connection_fd() except IOError as e: self.close() raise WebSocketError(e)
Return the file descriptor for the given websocket
Below is the the instruction that describes the task: ### Input: Return the file descriptor for the given websocket ### Response: def get_file_descriptor(self): """Return the file descriptor for the given websocket""" try: return uwsgi.connection_fd() except IOError as e: ...
def setup_versioned_routes(routes, version=None): """Set up routes with a version prefix.""" prefix = '/' + version if version else "" for r in routes: path, method = r route(prefix + path, method, routes[r])
Set up routes with a version prefix.
Below is the the instruction that describes the task: ### Input: Set up routes with a version prefix. ### Response: def setup_versioned_routes(routes, version=None): """Set up routes with a version prefix.""" prefix = '/' + version if version else "" for r in routes: path, method = r ro...
def install_requirements(self, requires): """ Install the listed requirements """ # Temporarily install dependencies required by setup.py before trying to import them. sys.path[0:0] = ['setup-requires'] pkg_resources.working_set.add_entry('setup-requires') to_install = l...
Install the listed requirements
Below is the the instruction that describes the task: ### Input: Install the listed requirements ### Response: def install_requirements(self, requires): """ Install the listed requirements """ # Temporarily install dependencies required by setup.py before trying to import them. sys....
def enable_logging( level='WARNING' ): """Enable sending logs to stderr. Useful for shell sessions. level Logging threshold, as defined in the logging module of the Python standard library. Defaults to 'WARNING'. """ log = logging.getLogger( 'mrcrowbar' ) log.setLevel( level ) o...
Enable sending logs to stderr. Useful for shell sessions. level Logging threshold, as defined in the logging module of the Python standard library. Defaults to 'WARNING'.
Below is the the instruction that describes the task: ### Input: Enable sending logs to stderr. Useful for shell sessions. level Logging threshold, as defined in the logging module of the Python standard library. Defaults to 'WARNING'. ### Response: def enable_logging( level='WARNING' ): "...
def MT2Axes(mt): """ Calculates the principal axes of a given moment tensor. :param mt: :class:`~MomentTensor` :return: tuple of :class:`~PrincipalAxis` T, N and P Adapted from ps_tensor / utilmeca.c / `Generic Mapping Tools (GMT) <http://gmt.soest.hawaii.edu>`_. """ (D, V) = np.linalg...
Calculates the principal axes of a given moment tensor. :param mt: :class:`~MomentTensor` :return: tuple of :class:`~PrincipalAxis` T, N and P Adapted from ps_tensor / utilmeca.c / `Generic Mapping Tools (GMT) <http://gmt.soest.hawaii.edu>`_.
Below is the the instruction that describes the task: ### Input: Calculates the principal axes of a given moment tensor. :param mt: :class:`~MomentTensor` :return: tuple of :class:`~PrincipalAxis` T, N and P Adapted from ps_tensor / utilmeca.c / `Generic Mapping Tools (GMT) <http://gmt.soest.hawai...
def _build_full_list(self): """Build a full list of pages. Examples: >>> _SlicedPaginator(1, 7, 5)._build_full_list() [1, 2, 3, 4, 5] >>> _SlicedPaginator(6, 7, 5)._build_full_list() [3, 4, 5, 6, 7] >>> _SlicedPaginator(6, 7, 5)._build_full_list() ...
Build a full list of pages. Examples: >>> _SlicedPaginator(1, 7, 5)._build_full_list() [1, 2, 3, 4, 5] >>> _SlicedPaginator(6, 7, 5)._build_full_list() [3, 4, 5, 6, 7] >>> _SlicedPaginator(6, 7, 5)._build_full_list() [3, 4, 5, 6, 7] >>> import ite...
Below is the the instruction that describes the task: ### Input: Build a full list of pages. Examples: >>> _SlicedPaginator(1, 7, 5)._build_full_list() [1, 2, 3, 4, 5] >>> _SlicedPaginator(6, 7, 5)._build_full_list() [3, 4, 5, 6, 7] >>> _SlicedPaginator(6, 7,...
def get_doc(func): """Extract and dedent the __doc__ of a function. Unlike `textwrap.dedent()` it also works when the first line is not indented. """ doc = func.__doc__ if not doc: return "" # doc has only one line if "\n" not in doc: return doc # Only Python core ...
Extract and dedent the __doc__ of a function. Unlike `textwrap.dedent()` it also works when the first line is not indented.
Below is the the instruction that describes the task: ### Input: Extract and dedent the __doc__ of a function. Unlike `textwrap.dedent()` it also works when the first line is not indented. ### Response: def get_doc(func): """Extract and dedent the __doc__ of a function. Unlike `textwrap.dedent()`...