code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def file_sizes(self): """Returns total filesize (in MB)""" size = sum(map(os.path.getsize, self.file_list)) return size / 1024 / 1024
Returns total filesize (in MB)
Below is the the instruction that describes the task: ### Input: Returns total filesize (in MB) ### Response: def file_sizes(self): """Returns total filesize (in MB)""" size = sum(map(os.path.getsize, self.file_list)) return size / 1024 / 1024
def _traverse(self, n=1): """Traverse state history. Used by `back` and `forward` methods. :param int n: Cursor increment. Positive values move forward in the browser history; negative values move backward. """ if not self.history: raise exceptions.RoboError('No...
Traverse state history. Used by `back` and `forward` methods. :param int n: Cursor increment. Positive values move forward in the browser history; negative values move backward.
Below is the the instruction that describes the task: ### Input: Traverse state history. Used by `back` and `forward` methods. :param int n: Cursor increment. Positive values move forward in the browser history; negative values move backward. ### Response: def _traverse(self, n=1): """...
def index_split(index, chunks): """Function to split pandas.Index and pandas.MultiIndex objects. Split :class:`pandas.Index` and :class:`pandas.MultiIndex` objects into chunks. This function is based on :func:`numpy.array_split`. Parameters ---------- index : pandas.Index, pandas.MultiIndex ...
Function to split pandas.Index and pandas.MultiIndex objects. Split :class:`pandas.Index` and :class:`pandas.MultiIndex` objects into chunks. This function is based on :func:`numpy.array_split`. Parameters ---------- index : pandas.Index, pandas.MultiIndex A pandas.Index or pandas.MultiInd...
Below is the the instruction that describes the task: ### Input: Function to split pandas.Index and pandas.MultiIndex objects. Split :class:`pandas.Index` and :class:`pandas.MultiIndex` objects into chunks. This function is based on :func:`numpy.array_split`. Parameters ---------- index : pand...
def upload(cls): """Uploads all the local views from :attr:`VIEW_PATHS` directory to CouchBase server This method **over-writes** all the server-side views with the same named ones coming from :attr:`VIEW_PATHS` folder. """ cls._check_folder() os.chdir(cls.VIEWS_...
Uploads all the local views from :attr:`VIEW_PATHS` directory to CouchBase server This method **over-writes** all the server-side views with the same named ones coming from :attr:`VIEW_PATHS` folder.
Below is the the instruction that describes the task: ### Input: Uploads all the local views from :attr:`VIEW_PATHS` directory to CouchBase server This method **over-writes** all the server-side views with the same named ones coming from :attr:`VIEW_PATHS` folder. ### Response: def upload(...
def remaining(self): """Determines how many bytes are remaining in the current context.""" if self.depth == 0: return _STREAM_REMAINING return self.limit - self.queue.position
Determines how many bytes are remaining in the current context.
Below is the the instruction that describes the task: ### Input: Determines how many bytes are remaining in the current context. ### Response: def remaining(self): """Determines how many bytes are remaining in the current context.""" if self.depth == 0: return _STREAM_REMAINING ...
def where(self, *args): ''' This method simulates a where condition. Use as follow: >>> yql.select('mytable').where(['name', '=', 'alain'], ['location', '!=', 'paris']) ''' if not self._table: raise errors.NoTableSelectedError('No Table Selected') clause = [] ...
This method simulates a where condition. Use as follow: >>> yql.select('mytable').where(['name', '=', 'alain'], ['location', '!=', 'paris'])
Below is the the instruction that describes the task: ### Input: This method simulates a where condition. Use as follow: >>> yql.select('mytable').where(['name', '=', 'alain'], ['location', '!=', 'paris']) ### Response: def where(self, *args): ''' This method simulates a where condition. Use as fol...
def sortby(listoflists,sortcols): """ Sorts a list of lists on the column(s) specified in the sequence sortcols. Usage: sortby(listoflists,sortcols) Returns: sorted list, unchanged column ordering """ newlist = abut(colex(listoflists,sortcols),listoflists) newlist.sort() try: numcols = len(so...
Sorts a list of lists on the column(s) specified in the sequence sortcols. Usage: sortby(listoflists,sortcols) Returns: sorted list, unchanged column ordering
Below is the the instruction that describes the task: ### Input: Sorts a list of lists on the column(s) specified in the sequence sortcols. Usage: sortby(listoflists,sortcols) Returns: sorted list, unchanged column ordering ### Response: def sortby(listoflists,sortcols): """ Sorts a list of lists on the col...
def load_pickle(file, encoding=None): """Load a pickle file. Args: file (str): Path to pickle file Returns: object: Loaded object from pickle file """ # TODO: test set encoding='latin1' for 2/3 incompatibility if encoding: with open(file, 'rb') as f: return...
Load a pickle file. Args: file (str): Path to pickle file Returns: object: Loaded object from pickle file
Below is the the instruction that describes the task: ### Input: Load a pickle file. Args: file (str): Path to pickle file Returns: object: Loaded object from pickle file ### Response: def load_pickle(file, encoding=None): """Load a pickle file. Args: file (str): Path to ...
def _block_from_ip_and_prefix(ip, prefix): """Create a tuple of (start, end) dotted-quad addresses from the given ip address and prefix length. :param ip: Ip address in block :type ip: long :param prefix: Prefix size for block :type prefix: int :returns: Tuple of block (start, end) """ ...
Create a tuple of (start, end) dotted-quad addresses from the given ip address and prefix length. :param ip: Ip address in block :type ip: long :param prefix: Prefix size for block :type prefix: int :returns: Tuple of block (start, end)
Below is the the instruction that describes the task: ### Input: Create a tuple of (start, end) dotted-quad addresses from the given ip address and prefix length. :param ip: Ip address in block :type ip: long :param prefix: Prefix size for block :type prefix: int :returns: Tuple of block (s...
def _show_organisation_logo(self): """Show the organisation logo in the dock if possible.""" dock_width = float(self.width()) # Don't let the image be more tha 100px height maximum_height = 100.0 # px pixmap = QPixmap(self.organisation_logo_path) if pixmap.height() < 1 o...
Show the organisation logo in the dock if possible.
Below is the the instruction that describes the task: ### Input: Show the organisation logo in the dock if possible. ### Response: def _show_organisation_logo(self): """Show the organisation logo in the dock if possible.""" dock_width = float(self.width()) # Don't let the image be more tha ...
def _get_odoo_version_info(addons_dir, odoo_version_override=None): """ Detect Odoo version from an addons directory """ odoo_version_info = None addons = os.listdir(addons_dir) for addon in addons: addon_dir = os.path.join(addons_dir, addon) if is_installable_addon(addon_dir): ...
Detect Odoo version from an addons directory
Below is the the instruction that describes the task: ### Input: Detect Odoo version from an addons directory ### Response: def _get_odoo_version_info(addons_dir, odoo_version_override=None): """ Detect Odoo version from an addons directory """ odoo_version_info = None addons = os.listdir(addons_dir) ...
def on_view_not_found( self, _, start_response: Callable[[str, List[Tuple[str, str]]], None], ) -> Iterable[bytes]: """ called when valid view is not found """ start_response( "405 Method Not Allowed", [('Content-type', 'text/plain')]) return ...
called when valid view is not found
Below is the the instruction that describes the task: ### Input: called when valid view is not found ### Response: def on_view_not_found( self, _, start_response: Callable[[str, List[Tuple[str, str]]], None], ) -> Iterable[bytes]: """ called when valid view is not found """ ...
def _ScanNode(self, scan_context, scan_node, auto_recurse=True): """Scans a node for supported formats. Args: scan_context (SourceScannerContext): source scanner context. scan_node (SourceScanNode): source scan node. auto_recurse (Optional[bool]): True if the scan should automatically ...
Scans a node for supported formats. Args: scan_context (SourceScannerContext): source scanner context. scan_node (SourceScanNode): source scan node. auto_recurse (Optional[bool]): True if the scan should automatically recurse as far as possible. Raises: BackEndError: if the s...
Below is the the instruction that describes the task: ### Input: Scans a node for supported formats. Args: scan_context (SourceScannerContext): source scanner context. scan_node (SourceScanNode): source scan node. auto_recurse (Optional[bool]): True if the scan should automatically ...
def get_all_fields(cls, class_obj=None, fields=None): """ TODO: This needs to be properly used """ def return_fields(obj): internal_fields = fields if internal_fields is None: internal_fields = {} for attribute in dir(obj): ...
TODO: This needs to be properly used
Below is the the instruction that describes the task: ### Input: TODO: This needs to be properly used ### Response: def get_all_fields(cls, class_obj=None, fields=None): """ TODO: This needs to be properly used """ def return_fields(obj): internal_fields = fields ...
def createPedChr23UsingPlink(options): """Run Plink to create a ped format. :param options: the options. :type options: argparse.Namespace Uses Plink to create a ``ped`` file of markers on the chromosome ``23``. It uses the ``recodeA`` options to use additive coding. It also subsets the data ...
Run Plink to create a ped format. :param options: the options. :type options: argparse.Namespace Uses Plink to create a ``ped`` file of markers on the chromosome ``23``. It uses the ``recodeA`` options to use additive coding. It also subsets the data to keep only samples with sex problems.
Below is the the instruction that describes the task: ### Input: Run Plink to create a ped format. :param options: the options. :type options: argparse.Namespace Uses Plink to create a ``ped`` file of markers on the chromosome ``23``. It uses the ``recodeA`` options to use additive coding. It als...
def after_app_request(self, f): """Like :meth:`Flask.after_request` but for a blueprint. Such a function is executed after each request, even if outside of the blueprint. """ self.record_once(lambda s: s.app.after_request_funcs .setdefault(None, []).append(f)) return...
Like :meth:`Flask.after_request` but for a blueprint. Such a function is executed after each request, even if outside of the blueprint.
Below is the the instruction that describes the task: ### Input: Like :meth:`Flask.after_request` but for a blueprint. Such a function is executed after each request, even if outside of the blueprint. ### Response: def after_app_request(self, f): """Like :meth:`Flask.after_request` but for a bluep...
def get_internal_call_graph(fpath, with_doctests=False): """ CommandLine: python -m utool.util_inspect get_internal_call_graph --show --modpath=~/code/ibeis/ibeis/init/main_helpers.py --show python -m utool.util_inspect get_internal_call_graph --show --modpath=~/code/dtool/dtool/depcache_table.p...
CommandLine: python -m utool.util_inspect get_internal_call_graph --show --modpath=~/code/ibeis/ibeis/init/main_helpers.py --show python -m utool.util_inspect get_internal_call_graph --show --modpath=~/code/dtool/dtool/depcache_table.py --show Example: >>> # DISABLE_DOCTEST >>> from...
Below is the the instruction that describes the task: ### Input: CommandLine: python -m utool.util_inspect get_internal_call_graph --show --modpath=~/code/ibeis/ibeis/init/main_helpers.py --show python -m utool.util_inspect get_internal_call_graph --show --modpath=~/code/dtool/dtool/depcache_table.p...
def child_count(self, only_direct=True): """Returns how many children this node has, either only the direct children of this node or inclusive of all children nodes of this node. """ if not only_direct: count = 0 for _node in self.dfs_iter(): count...
Returns how many children this node has, either only the direct children of this node or inclusive of all children nodes of this node.
Below is the the instruction that describes the task: ### Input: Returns how many children this node has, either only the direct children of this node or inclusive of all children nodes of this node. ### Response: def child_count(self, only_direct=True): """Returns how many children this node has, ...
def left_to_right(self): """This is for text that flows Left to Right""" self._entry_mode |= Command.MODE_INCREMENT self.command(self._entry_mode)
This is for text that flows Left to Right
Below is the the instruction that describes the task: ### Input: This is for text that flows Left to Right ### Response: def left_to_right(self): """This is for text that flows Left to Right""" self._entry_mode |= Command.MODE_INCREMENT self.command(self._entry_mode)
def parse_te(header): """Parse the "TE" header.""" pos = 0 names = [] while pos < len(header): name, pos = expect_re(re_token, header, pos) _, pos = accept_ws(header, pos) _, pos = accept_lit(';', header, pos) _, pos = accept_ws(header, pos) qvalue, pos = accept_r...
Parse the "TE" header.
Below is the the instruction that describes the task: ### Input: Parse the "TE" header. ### Response: def parse_te(header): """Parse the "TE" header.""" pos = 0 names = [] while pos < len(header): name, pos = expect_re(re_token, header, pos) _, pos = accept_ws(header, pos) _...
def get_cached_files(url, server_name="", document_root=None): """ Given a URL, return a list of paths of all cached variations of that file. Doesn't include the original file. """ import glob url_info = process_url(url, server_name, document_root, check_security=False) # get path to cache...
Given a URL, return a list of paths of all cached variations of that file. Doesn't include the original file.
Below is the the instruction that describes the task: ### Input: Given a URL, return a list of paths of all cached variations of that file. Doesn't include the original file. ### Response: def get_cached_files(url, server_name="", document_root=None): """ Given a URL, return a list of paths of all cac...
def mount(self, app, script_path): ''' Mount a Bottle application to a specific URL prefix ''' if not isinstance(app, Bottle): raise TypeError('Only Bottle instances are supported for now.') script_path = '/'.join(filter(None, script_path.split('/'))) path_depth = script_path...
Mount a Bottle application to a specific URL prefix
Below is the the instruction that describes the task: ### Input: Mount a Bottle application to a specific URL prefix ### Response: def mount(self, app, script_path): ''' Mount a Bottle application to a specific URL prefix ''' if not isinstance(app, Bottle): raise TypeError('Only Bottle ...
def RandomNormalInitializer(stddev=1e-2): """An initializer function for random normal coefficients.""" def init(shape, rng): return (stddev * backend.random.normal(rng, shape)).astype('float32') return init
An initializer function for random normal coefficients.
Below is the the instruction that describes the task: ### Input: An initializer function for random normal coefficients. ### Response: def RandomNormalInitializer(stddev=1e-2): """An initializer function for random normal coefficients.""" def init(shape, rng): return (stddev * backend.random.normal(rng, sh...
def _add_vdsm_forbidden_paths(self): """Add confidential sysprep vfds under /var/run/vdsm to forbidden paths """ for file_path in glob.glob("/var/run/vdsm/*"): if file_path.endswith(('.vfd', '/isoUploader', '/storage')): self.add_forbidden_path(file_path)
Add confidential sysprep vfds under /var/run/vdsm to forbidden paths
Below is the the instruction that describes the task: ### Input: Add confidential sysprep vfds under /var/run/vdsm to forbidden paths ### Response: def _add_vdsm_forbidden_paths(self): """Add confidential sysprep vfds under /var/run/vdsm to forbidden paths """ for file_path in gl...
def resolve_sid(f): """View handler decorator that adds SID resolve and PID validation. - For v1 calls, assume that ``did`` is a pid and raise NotFound exception if it's not valid. - For v2 calls, if DID is a valid PID, return it. If not, try to resolve it as a SID and, if successful, return th...
View handler decorator that adds SID resolve and PID validation. - For v1 calls, assume that ``did`` is a pid and raise NotFound exception if it's not valid. - For v2 calls, if DID is a valid PID, return it. If not, try to resolve it as a SID and, if successful, return the new PID. Else, raise NotF...
Below is the the instruction that describes the task: ### Input: View handler decorator that adds SID resolve and PID validation. - For v1 calls, assume that ``did`` is a pid and raise NotFound exception if it's not valid. - For v2 calls, if DID is a valid PID, return it. If not, try to resolve it as...
def parse_man_page(command, platform): """Parse the man page and return the parsed lines.""" page_path = find_page_location(command, platform) output_lines = parse_page(page_path) return output_lines
Parse the man page and return the parsed lines.
Below is the the instruction that describes the task: ### Input: Parse the man page and return the parsed lines. ### Response: def parse_man_page(command, platform): """Parse the man page and return the parsed lines.""" page_path = find_page_location(command, platform) output_lines = parse_page(page_pa...
def create_payload(self): """Wrap submitted data within an extra dict.""" payload = super(JobTemplate, self).create_payload() effective_user = payload.pop(u'effective_user', None) if effective_user: payload[u'ssh'] = {u'effective_user': effective_user} return {u'job...
Wrap submitted data within an extra dict.
Below is the the instruction that describes the task: ### Input: Wrap submitted data within an extra dict. ### Response: def create_payload(self): """Wrap submitted data within an extra dict.""" payload = super(JobTemplate, self).create_payload() effective_user = payload.pop(u'effective_us...
def catalog(self, table='', column=''): """Lookup the values available for querying.""" lookup_table = self.lookup_table if lookup_table is not None: if table: if column: column = column.upper() return lookup_table[table][column...
Lookup the values available for querying.
Below is the the instruction that describes the task: ### Input: Lookup the values available for querying. ### Response: def catalog(self, table='', column=''): """Lookup the values available for querying.""" lookup_table = self.lookup_table if lookup_table is not None: if table...
def getcpustat(self, process_name): """ get CPU stat for the give process name @param process_name: Process name, ex: firefox-bin. @type process_name: string @return: cpu stat list on success, else empty list If same process name, running multiple instance, ...
get CPU stat for the give process name @param process_name: Process name, ex: firefox-bin. @type process_name: string @return: cpu stat list on success, else empty list If same process name, running multiple instance, get the stat of all the process CPU usage ...
Below is the the instruction that describes the task: ### Input: get CPU stat for the give process name @param process_name: Process name, ex: firefox-bin. @type process_name: string @return: cpu stat list on success, else empty list If same process name, running multiple i...
def add_completions( replace_list: list, belstr: str, replace_span: Span, completion_text: str ) -> List[Mapping[str, Any]]: """Create completions to return given replacement list Args: replace_list: list of completion replacement values belstr: BEL String replace_span: start, stop ...
Create completions to return given replacement list Args: replace_list: list of completion replacement values belstr: BEL String replace_span: start, stop of belstr to replace completion_text: text to use for completion - used for creating highlight Returns: [{ ...
Below is the the instruction that describes the task: ### Input: Create completions to return given replacement list Args: replace_list: list of completion replacement values belstr: BEL String replace_span: start, stop of belstr to replace completion_text: text to use for compl...
def get_usernames_like(username,**kwargs): """ Return a list of usernames like the given string. """ checkname = "%%%s%%"%username rs = db.DBSession.query(User.username).filter(User.username.like(checkname)).all() return [r.username for r in rs]
Return a list of usernames like the given string.
Below is the the instruction that describes the task: ### Input: Return a list of usernames like the given string. ### Response: def get_usernames_like(username,**kwargs): """ Return a list of usernames like the given string. """ checkname = "%%%s%%"%username rs = db.DBSession.query(User.us...
def call_proxy(self, engine, payload, method, analyze_json_error_param, retry_request_substr_variants, stream=False): """ :param engine: Система :param payload: Данные для запроса :param method: string Может содержать native_call | tsv | json_newline :param ana...
:param engine: Система :param payload: Данные для запроса :param method: string Может содержать native_call | tsv | json_newline :param analyze_json_error_param: Нужно ли производить анализ параметра error в ответе прокси :param retry_request_substr_variants: Список подстрок, при наличии...
Below is the the instruction that describes the task: ### Input: :param engine: Система :param payload: Данные для запроса :param method: string Может содержать native_call | tsv | json_newline :param analyze_json_error_param: Нужно ли производить анализ параметра error в ответе прокси ...
def child(self, **kwargs): '''set childSelector.''' return AutomatorDeviceObject( self.device, self.selector.clone().child(**kwargs) )
set childSelector.
Below is the the instruction that describes the task: ### Input: set childSelector. ### Response: def child(self, **kwargs): '''set childSelector.''' return AutomatorDeviceObject( self.device, self.selector.clone().child(**kwargs) )
def cli(env, identifier, keys, permissions, hardware, virtual, logins, events): """User details.""" mgr = SoftLayer.UserManager(env.client) user_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'username') object_mask = "userStatus[name], parent[id, username], apiAuthenticationKeys[authenticationKe...
User details.
Below is the the instruction that describes the task: ### Input: User details. ### Response: def cli(env, identifier, keys, permissions, hardware, virtual, logins, events): """User details.""" mgr = SoftLayer.UserManager(env.client) user_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'username')...
def make_node(cls, operator, left, right, lineno, func=None, type_=None): """ Creates a binary node for a binary operation, e.g. A + 6 => '+' (A, 6) in prefix notation. Parameters: -operator: the binary operation token. e.g. 'PLUS' for A + 6 -le...
Creates a binary node for a binary operation, e.g. A + 6 => '+' (A, 6) in prefix notation. Parameters: -operator: the binary operation token. e.g. 'PLUS' for A + 6 -left: left operand -right: right operand -func: is a lambda function used when con...
Below is the the instruction that describes the task: ### Input: Creates a binary node for a binary operation, e.g. A + 6 => '+' (A, 6) in prefix notation. Parameters: -operator: the binary operation token. e.g. 'PLUS' for A + 6 -left: left operand -right...
def do_edit(self, line): """edit Edit the queue of write operations.""" self._split_args(line, 0, 0) self._command_processor.get_operation_queue().edit() self._print_info_if_verbose("The write operation queue was successfully edited")
edit Edit the queue of write operations.
Below is the the instruction that describes the task: ### Input: edit Edit the queue of write operations. ### Response: def do_edit(self, line): """edit Edit the queue of write operations.""" self._split_args(line, 0, 0) self._command_processor.get_operation_queue().edit() self._pri...
def get_field_by_name(self, name): ''' :param name: name of field to get :return: direct sub-field with the given name :raises: :class:`~kitty.core.KittyException` if no direct subfield with this name ''' if name in self._fields_dict: return self._fields_dict[...
:param name: name of field to get :return: direct sub-field with the given name :raises: :class:`~kitty.core.KittyException` if no direct subfield with this name
Below is the the instruction that describes the task: ### Input: :param name: name of field to get :return: direct sub-field with the given name :raises: :class:`~kitty.core.KittyException` if no direct subfield with this name ### Response: def get_field_by_name(self, name): ''' :pa...
def create_geometry(self, input_geometry, dip, upper_depth, lower_depth, mesh_spacing=1.0): ''' If geometry is defined as a numpy array then create instance of nhlib.geo.line.Line class, otherwise if already instance of class accept class :param input_geo...
If geometry is defined as a numpy array then create instance of nhlib.geo.line.Line class, otherwise if already instance of class accept class :param input_geometry: Trace (line) of the fault source as either i) instance of nhlib.geo.line.Line class ii) numpy...
Below is the the instruction that describes the task: ### Input: If geometry is defined as a numpy array then create instance of nhlib.geo.line.Line class, otherwise if already instance of class accept class :param input_geometry: Trace (line) of the fault source as either ...
def restore_population_parameters(self, global_default=True): """Setup UI for population parameter page from setting. :param global_default: If True, set to original default (from the value in definitions). :type global_default: bool """ if global_default: ...
Setup UI for population parameter page from setting. :param global_default: If True, set to original default (from the value in definitions). :type global_default: bool
Below is the the instruction that describes the task: ### Input: Setup UI for population parameter page from setting. :param global_default: If True, set to original default (from the value in definitions). :type global_default: bool ### Response: def restore_population_parameters(self...
def get_records_from_basket(self, bskid, group_basket=False, read_cache=True): """ Returns the records from the (public) basket with given bskid """ if bskid not in self.cached_baskets or not read_cache: if self.user: if group_b...
Returns the records from the (public) basket with given bskid
Below is the the instruction that describes the task: ### Input: Returns the records from the (public) basket with given bskid ### Response: def get_records_from_basket(self, bskid, group_basket=False, read_cache=True): """ Returns the records from the (public) baske...
def condor_submit(cmd): """ Submits cmd to HTCondor queue Parameters ---------- cmd: string Command to be submitted Returns ------- int returncode value from calling the submission command. """ is_running = subprocess.call('condor_status', shell=True) == 0 i...
Submits cmd to HTCondor queue Parameters ---------- cmd: string Command to be submitted Returns ------- int returncode value from calling the submission command.
Below is the the instruction that describes the task: ### Input: Submits cmd to HTCondor queue Parameters ---------- cmd: string Command to be submitted Returns ------- int returncode value from calling the submission command. ### Response: def condor_submit(cmd): """ ...
def create_rule(self, title, symbolizer=None, MinScaleDenominator=None, MaxScaleDenominator=None): """ Create a L{Rule} object on this style. A rule requires a title and symbolizer. If no symbolizer is specified, a PointSymbolizer will be assigned to the rule. @type title:...
Create a L{Rule} object on this style. A rule requires a title and symbolizer. If no symbolizer is specified, a PointSymbolizer will be assigned to the rule. @type title: string @param title: The name of the new L{Rule}. @type symbolizer: L{Symbolizer} I{class} ...
Below is the the instruction that describes the task: ### Input: Create a L{Rule} object on this style. A rule requires a title and symbolizer. If no symbolizer is specified, a PointSymbolizer will be assigned to the rule. @type title: string @param title: The name of the...
def send_build_data(build_dir, data, secret, response_url=None,clean_up=True): '''finish build sends the build and data (response) to a response url :param build_dir: the directory of the build :response_url: where to send the response. If None, won't send :param data: the data obje...
finish build sends the build and data (response) to a response url :param build_dir: the directory of the build :response_url: where to send the response. If None, won't send :param data: the data object to send as a post :param clean_up: If true (default) removes build directory
Below is the the instruction that describes the task: ### Input: finish build sends the build and data (response) to a response url :param build_dir: the directory of the build :response_url: where to send the response. If None, won't send :param data: the data object to send as a post :param clean_...
def create_package(self): """ Ensure that the package can be properly configured, and then create it. """ # Create the Lambda zip package (includes project and virtualenvironment) # Also define the path the handler file so it can be copied to the zip # root for ...
Ensure that the package can be properly configured, and then create it.
Below is the the instruction that describes the task: ### Input: Ensure that the package can be properly configured, and then create it. ### Response: def create_package(self): """ Ensure that the package can be properly configured, and then create it. """ # Create...
def unignore_reports(self): """Remove ignoring of future reports on this object. Undoes 'ignore_reports'. Future reports will now cause notifications and appear in the various moderation listings. """ url = self.reddit_session.config['unignore_reports'] data = {'id': se...
Remove ignoring of future reports on this object. Undoes 'ignore_reports'. Future reports will now cause notifications and appear in the various moderation listings.
Below is the the instruction that describes the task: ### Input: Remove ignoring of future reports on this object. Undoes 'ignore_reports'. Future reports will now cause notifications and appear in the various moderation listings. ### Response: def unignore_reports(self): """Remove ignorin...
def _take_batch(self, min_records): '''If we have enough data to build a batch, returns all the data in the buffer and then clears the buffer.''' if not self._buffer: return [] enough_messages = len(self._buffer) >= min_records enough_time = time.time() - self.time_...
If we have enough data to build a batch, returns all the data in the buffer and then clears the buffer.
Below is the the instruction that describes the task: ### Input: If we have enough data to build a batch, returns all the data in the buffer and then clears the buffer. ### Response: def _take_batch(self, min_records): '''If we have enough data to build a batch, returns all the data in the ...
def vcmp_host(opt_vcmp_host, opt_username, opt_password, opt_port): '''vcmp fixture''' m = ManagementRoot( opt_vcmp_host, opt_username, opt_password, port=opt_port) return m
vcmp fixture
Below is the the instruction that describes the task: ### Input: vcmp fixture ### Response: def vcmp_host(opt_vcmp_host, opt_username, opt_password, opt_port): '''vcmp fixture''' m = ManagementRoot( opt_vcmp_host, opt_username, opt_password, port=opt_port) return m
def stFeatureExtraction(signal, fs, win, step): """ This function implements the shor-term windowing process. For each short-term window a set of features is extracted. This results to a sequence of feature vectors, stored in a numpy matrix. ARGUMENTS signal: the input signal samples ...
This function implements the shor-term windowing process. For each short-term window a set of features is extracted. This results to a sequence of feature vectors, stored in a numpy matrix. ARGUMENTS signal: the input signal samples fs: the sampling freq (in Hz) win: ...
Below is the the instruction that describes the task: ### Input: This function implements the shor-term windowing process. For each short-term window a set of features is extracted. This results to a sequence of feature vectors, stored in a numpy matrix. ARGUMENTS signal: the input signal sam...
def _parse_date(self, raw_value): "Convert raw data to datetime.date" nday = bytes_to_bint(raw_value) + 678882 century = (4 * nday - 1) // 146097 nday = 4 * nday - 1 - 146097 * century day = nday // 4 nday = (4 * day + 3) // 1461 day = 4 * day + 3 - 1461 * nday ...
Convert raw data to datetime.date
Below is the the instruction that describes the task: ### Input: Convert raw data to datetime.date ### Response: def _parse_date(self, raw_value): "Convert raw data to datetime.date" nday = bytes_to_bint(raw_value) + 678882 century = (4 * nday - 1) // 146097 nday = 4 * nday - 1 - 14...
def get_role_by_account_sis_id(self, account_sis_id, role_id): """ Get information about a single role, for the passed account SIS ID. """ return self.get_role(self._sis_id(account_sis_id, sis_field="account"), role_id)
Get information about a single role, for the passed account SIS ID.
Below is the the instruction that describes the task: ### Input: Get information about a single role, for the passed account SIS ID. ### Response: def get_role_by_account_sis_id(self, account_sis_id, role_id): """ Get information about a single role, for the passed account SIS ID. """ ...
def _contains_egg_info( s, _egg_info_re=re.compile(r'([a-z0-9_.]+)-([a-z0-9_.!+-]+)', re.I)): """Determine whether the string looks like an egg_info. :param s: The string to parse. E.g. foo-2.1 """ return bool(_egg_info_re.search(s))
Determine whether the string looks like an egg_info. :param s: The string to parse. E.g. foo-2.1
Below is the the instruction that describes the task: ### Input: Determine whether the string looks like an egg_info. :param s: The string to parse. E.g. foo-2.1 ### Response: def _contains_egg_info( s, _egg_info_re=re.compile(r'([a-z0-9_.]+)-([a-z0-9_.!+-]+)', re.I)): """Determine whether the str...
def declarative(member_class=None, parameter='members', add_init_kwargs=True, sort_key=default_sort_key, is_member=None): """ Class decorator to enable classes to be defined in the style of django models. That is, @declarative classes will get an additional argument to constructor, containin...
Class decorator to enable classes to be defined in the style of django models. That is, @declarative classes will get an additional argument to constructor, containing an OrderedDict with all class members matching the specified type. :param class member_class: Class(es) to collect :par...
Below is the the instruction that describes the task: ### Input: Class decorator to enable classes to be defined in the style of django models. That is, @declarative classes will get an additional argument to constructor, containing an OrderedDict with all class members matching the specified type. ...
def _create_array(self, arr: np.ndarray) -> int: """Returns the handle of a RawArray created from the given numpy array. Args: arr: A numpy ndarray. Returns: The handle (int) of the array. Raises: ValueError: if arr is not a ndarray or of an unsupported d...
Returns the handle of a RawArray created from the given numpy array. Args: arr: A numpy ndarray. Returns: The handle (int) of the array. Raises: ValueError: if arr is not a ndarray or of an unsupported dtype. If the array is of an unsupported type, us...
Below is the the instruction that describes the task: ### Input: Returns the handle of a RawArray created from the given numpy array. Args: arr: A numpy ndarray. Returns: The handle (int) of the array. Raises: ValueError: if arr is not a ndarray or of an unsu...
def getcomments(self): """ Returns an array of comment dictionaries for this bug """ comment_list = self.bugzilla.get_comments([self.bug_id]) return comment_list['bugs'][str(self.bug_id)]['comments']
Returns an array of comment dictionaries for this bug
Below is the the instruction that describes the task: ### Input: Returns an array of comment dictionaries for this bug ### Response: def getcomments(self): """ Returns an array of comment dictionaries for this bug """ comment_list = self.bugzilla.get_comments([self.bug_id]) ...
def _add_sub_elements_from_dict(parent, sub_dict): """ Add SubElements to the parent element. :param parent: ElementTree.Element: The parent element for the newly created SubElement. :param sub_dict: dict: Used to create a new SubElement. See `dict_to_xml_schema` method docstring for more information. e.g.: {"e...
Add SubElements to the parent element. :param parent: ElementTree.Element: The parent element for the newly created SubElement. :param sub_dict: dict: Used to create a new SubElement. See `dict_to_xml_schema` method docstring for more information. e.g.: {"example": { "attrs": { "key1": "value1", ... ...
Below is the the instruction that describes the task: ### Input: Add SubElements to the parent element. :param parent: ElementTree.Element: The parent element for the newly created SubElement. :param sub_dict: dict: Used to create a new SubElement. See `dict_to_xml_schema` method docstring for more information....
def create_df_file_with_query(self, query, output): """ Dumps in df in chunks to avoid crashes. """ chunk_size = 100000 offset = 0 data = defaultdict(lambda : defaultdict(list)) with open(output, 'wb') as outfile: query = query.replace(';', '') qu...
Dumps in df in chunks to avoid crashes.
Below is the the instruction that describes the task: ### Input: Dumps in df in chunks to avoid crashes. ### Response: def create_df_file_with_query(self, query, output): """ Dumps in df in chunks to avoid crashes. """ chunk_size = 100000 offset = 0 data = defaultdict(lambda...
def decrypt(user=None, text=None, filename=None, output=None, use_passphrase=False, gnupghome=None, bare=False): ''' Decrypt a message or file user Which user's keychain to access, defaults to user Salt is running as. P...
Decrypt a message or file user Which user's keychain to access, defaults to user Salt is running as. Passing the user as ``salt`` will set the GnuPG home directory to the ``/etc/salt/gpgkeys``. text The encrypted text to decrypt. filename The encrypted filename to ...
Below is the the instruction that describes the task: ### Input: Decrypt a message or file user Which user's keychain to access, defaults to user Salt is running as. Passing the user as ``salt`` will set the GnuPG home directory to the ``/etc/salt/gpgkeys``. text The encryp...
def p_common_scalar_magic_dir(p): 'common_scalar : DIR' value = getattr(p.lexer, 'filename', None) if value is not None: value = os.path.dirname(value) p[0] = ast.MagicConstant(p[1].upper(), value, lineno=p.lineno(1))
common_scalar : DIR
Below is the the instruction that describes the task: ### Input: common_scalar : DIR ### Response: def p_common_scalar_magic_dir(p): 'common_scalar : DIR' value = getattr(p.lexer, 'filename', None) if value is not None: value = os.path.dirname(value) p[0] = ast.MagicConstant(p[1].upper(), v...
def _getCosimulation(self, func, **kwargs): ''' Returns a co-simulation instance of func. Uses the _simulator specified by self._simulator. Enables traces if self._trace is True func - MyHDL function to be simulated kwargs - dict of func interface assign...
Returns a co-simulation instance of func. Uses the _simulator specified by self._simulator. Enables traces if self._trace is True func - MyHDL function to be simulated kwargs - dict of func interface assignments: for signals and parameters
Below is the the instruction that describes the task: ### Input: Returns a co-simulation instance of func. Uses the _simulator specified by self._simulator. Enables traces if self._trace is True func - MyHDL function to be simulated kwargs - dict of func int...
def create(self, body=values.unset, media_url=values.unset): """ Create a new MessageInteractionInstance :param unicode body: Message body :param unicode media_url: Reserved :returns: Newly created MessageInteractionInstance :rtype: twilio.rest.proxy.v1.service.session....
Create a new MessageInteractionInstance :param unicode body: Message body :param unicode media_url: Reserved :returns: Newly created MessageInteractionInstance :rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionInstance
Below is the the instruction that describes the task: ### Input: Create a new MessageInteractionInstance :param unicode body: Message body :param unicode media_url: Reserved :returns: Newly created MessageInteractionInstance :rtype: twilio.rest.proxy.v1.service.session.participant....
def merge_pres_feats(pres, features): """ Helper function to merge pres and features to support legacy features argument """ sub = [] for psub, fsub in zip(pres, features): exp = [] for pexp, fexp in zip(psub, fsub): lst = [] for p, f in zip(pexp, fexp): ...
Helper function to merge pres and features to support legacy features argument
Below is the the instruction that describes the task: ### Input: Helper function to merge pres and features to support legacy features argument ### Response: def merge_pres_feats(pres, features): """ Helper function to merge pres and features to support legacy features argument """ sub = [] fo...
def reverse_reference(self): '''Changes the coordinates as if the reference sequence has been reverse complemented''' self.ref_start = self.ref_length - self.ref_start - 1 self.ref_end = self.ref_length - self.ref_end - 1
Changes the coordinates as if the reference sequence has been reverse complemented
Below is the the instruction that describes the task: ### Input: Changes the coordinates as if the reference sequence has been reverse complemented ### Response: def reverse_reference(self): '''Changes the coordinates as if the reference sequence has been reverse complemented''' self.ref_start = se...
def apdu_contents(self, use_dict=None, as_class=dict): """Return the contents of an object as a dict.""" if _debug: APCISequence._debug("apdu_contents use_dict=%r as_class=%r", use_dict, as_class) # make/extend the dictionary of content if use_dict is None: use_dict = as_cla...
Return the contents of an object as a dict.
Below is the the instruction that describes the task: ### Input: Return the contents of an object as a dict. ### Response: def apdu_contents(self, use_dict=None, as_class=dict): """Return the contents of an object as a dict.""" if _debug: APCISequence._debug("apdu_contents use_dict=%r as_class=%r",...
def pack(self): """ Pack message to binary stream. """ payload = io.BytesIO() # Advance num bytes equal to header size - the header is written later # after the payload of all segments and parts has been written: payload.seek(self.header_size, io.SEEK_CUR) # Write out pa...
Pack message to binary stream.
Below is the the instruction that describes the task: ### Input: Pack message to binary stream. ### Response: def pack(self): """ Pack message to binary stream. """ payload = io.BytesIO() # Advance num bytes equal to header size - the header is written later # after the payload of a...
def TDL(AN, BN): """ Helper function for MT2Plane. Adapted from MATLAB script `bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_ written by Andy Michael and Oliver Boyd. """ XN = AN[0] YN = AN[1] ZN = AN[2] XE = BN[0] YE = BN[1] ZE = BN[2] AAA...
Helper function for MT2Plane. Adapted from MATLAB script `bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_ written by Andy Michael and Oliver Boyd.
Below is the the instruction that describes the task: ### Input: Helper function for MT2Plane. Adapted from MATLAB script `bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_ written by Andy Michael and Oliver Boyd. ### Response: def TDL(AN, BN): """ Helper function for M...
def get_full_psd_matrix(self): """Function that returns the tf graph corresponding to the entire matrix M. Returns: matrix_h: unrolled version of tf matrix corresponding to H matrix_m: unrolled tf matrix corresponding to M """ if self.matrix_m is not None: return self.matrix_h, self.m...
Function that returns the tf graph corresponding to the entire matrix M. Returns: matrix_h: unrolled version of tf matrix corresponding to H matrix_m: unrolled tf matrix corresponding to M
Below is the the instruction that describes the task: ### Input: Function that returns the tf graph corresponding to the entire matrix M. Returns: matrix_h: unrolled version of tf matrix corresponding to H matrix_m: unrolled tf matrix corresponding to M ### Response: def get_full_psd_matrix(self):...
def receive(self): """ Read and return a message from the stream. If `None` is returned, then the socket is considered closed/errored. """ if self._closed: raise WebSocketError("Connection is already closed") try: return self.read_message() ...
Read and return a message from the stream. If `None` is returned, then the socket is considered closed/errored.
Below is the the instruction that describes the task: ### Input: Read and return a message from the stream. If `None` is returned, then the socket is considered closed/errored. ### Response: def receive(self): """ Read and return a message from the stream. If `None` is returned, then ...
def _build_ssh_client(self): """Prepare for Paramiko SSH connection.""" # Create instance of SSHClient object remote_conn_pre = paramiko.SSHClient() # Load host_keys for better SSH security if self.system_host_keys: remote_conn_pre.load_system_host_keys() if ...
Prepare for Paramiko SSH connection.
Below is the the instruction that describes the task: ### Input: Prepare for Paramiko SSH connection. ### Response: def _build_ssh_client(self): """Prepare for Paramiko SSH connection.""" # Create instance of SSHClient object remote_conn_pre = paramiko.SSHClient() # Load host_keys ...
async def digital_read(self, command): """ This method reads and returns the last reported value for a digital pin. Normally not used since digital pin updates will be provided automatically as they occur with the digital_message_reply being sent to the client after set_pin_mode is calle...
This method reads and returns the last reported value for a digital pin. Normally not used since digital pin updates will be provided automatically as they occur with the digital_message_reply being sent to the client after set_pin_mode is called.. (see enable_digital_reporting for message forma...
Below is the the instruction that describes the task: ### Input: This method reads and returns the last reported value for a digital pin. Normally not used since digital pin updates will be provided automatically as they occur with the digital_message_reply being sent to the client after set_pin_mod...
def dump_index(args, idx): """Create a metatab file for the index""" import csv import sys from metatab import MetatabDoc doc = MetatabDoc() pack_section = doc.new_section('Packages', ['Identifier', 'Name', 'Nvname', 'Version', 'Format']) r = doc['Root'] r.new_term('Root.Title', 'Pa...
Create a metatab file for the index
Below is the the instruction that describes the task: ### Input: Create a metatab file for the index ### Response: def dump_index(args, idx): """Create a metatab file for the index""" import csv import sys from metatab import MetatabDoc doc = MetatabDoc() pack_section = doc.new_section(...
def gen_tau(S, K, delta): """The Robust part of the RSD, we precompute an array for speed """ pivot = floor(K/S) return [S/K * 1/d for d in range(1, pivot)] \ + [S/K * log(S/delta)] \ + [0 for d in range(pivot, K)]
The Robust part of the RSD, we precompute an array for speed
Below is the the instruction that describes the task: ### Input: The Robust part of the RSD, we precompute an array for speed ### Response: def gen_tau(S, K, delta): """The Robust part of the RSD, we precompute an array for speed """ pivot = floor(K/S) return [S/K * 1/d for d in range(1, pi...
def remove(self, force=False): """ Remove this volume. Args: force (bool): Force removal of volumes that were already removed out of band by the volume driver plugin. Raises: :py:class:`docker.errors.APIError` If volume failed to r...
Remove this volume. Args: force (bool): Force removal of volumes that were already removed out of band by the volume driver plugin. Raises: :py:class:`docker.errors.APIError` If volume failed to remove.
Below is the the instruction that describes the task: ### Input: Remove this volume. Args: force (bool): Force removal of volumes that were already removed out of band by the volume driver plugin. Raises: :py:class:`docker.errors.APIError` If ...
def get_color_scheme(name): """Get syntax color scheme""" color_scheme = {} for key in sh.COLOR_SCHEME_KEYS: color_scheme[key] = CONF.get("appearance", "%s/%s" % (name, key)) return color_scheme
Get syntax color scheme
Below is the the instruction that describes the task: ### Input: Get syntax color scheme ### Response: def get_color_scheme(name): """Get syntax color scheme""" color_scheme = {} for key in sh.COLOR_SCHEME_KEYS: color_scheme[key] = CONF.get("appearance", "%s/%s" % (name, key)) return color_...
async def delete(self): """Delete this Bcache.""" await self._handler.delete( system_id=self.node.system_id, id=self.id)
Delete this Bcache.
Below is the the instruction that describes the task: ### Input: Delete this Bcache. ### Response: async def delete(self): """Delete this Bcache.""" await self._handler.delete( system_id=self.node.system_id, id=self.id)
def get_index_by_name(self, name): """Find the index number by block name""" for i in range(self.n_blocks): if self.get_block_name(i) == name: return i raise KeyError('Block name ({}) not found'.format(name))
Find the index number by block name
Below is the the instruction that describes the task: ### Input: Find the index number by block name ### Response: def get_index_by_name(self, name): """Find the index number by block name""" for i in range(self.n_blocks): if self.get_block_name(i) == name: return i ...
def get_adapter(self, url): """ Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter """ for (prefix, adapter) in self.adapters.items(): if url.lower().startswith(prefix.lower()): return adapter ...
Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter
Below is the the instruction that describes the task: ### Input: Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter ### Response: def get_adapter(self, url): """ Returns the appropriate connection adapter for the given URL. :rtype: ...
def has(self, character): ''' Get if character (or character code point) is contained by any range on this range group. :param character: character or unicode code point to look for :type character: str or int :returns: True if character is contained by any range, False ...
Get if character (or character code point) is contained by any range on this range group. :param character: character or unicode code point to look for :type character: str or int :returns: True if character is contained by any range, False otherwise :rtype: bool
Below is the the instruction that describes the task: ### Input: Get if character (or character code point) is contained by any range on this range group. :param character: character or unicode code point to look for :type character: str or int :returns: True if character is contain...
def request(self, method, url, **kwargs): """ Overrides ``requests.Session.request`` to renew the cookie and then retry the original request (if required). """ resp = super(CookieSession, self).request(method, url, **kwargs) if not self._auto_renew: return re...
Overrides ``requests.Session.request`` to renew the cookie and then retry the original request (if required).
Below is the the instruction that describes the task: ### Input: Overrides ``requests.Session.request`` to renew the cookie and then retry the original request (if required). ### Response: def request(self, method, url, **kwargs): """ Overrides ``requests.Session.request`` to renew the cook...
def add_hookspecs(self, module_or_class): """ add new hook specifications defined in the given module_or_class. Functions are recognized if they have been decorated accordingly. """ names = [] for name in dir(module_or_class): spec_opts = self.parse_hookspec_opts(module_or_cl...
add new hook specifications defined in the given module_or_class. Functions are recognized if they have been decorated accordingly.
Below is the the instruction that describes the task: ### Input: add new hook specifications defined in the given module_or_class. Functions are recognized if they have been decorated accordingly. ### Response: def add_hookspecs(self, module_or_class): """ add new hook specifications defined in the...
def _list_to_complex_array(complex_list): """Convert nested list of shape (..., 2) to complex numpy array with shape (...) Args: complex_list (list): List to convert. Returns: np.ndarray: Complex numpy aray Raises: QiskitError: If inner most array of input nested list is not o...
Convert nested list of shape (..., 2) to complex numpy array with shape (...) Args: complex_list (list): List to convert. Returns: np.ndarray: Complex numpy aray Raises: QiskitError: If inner most array of input nested list is not of length 2.
Below is the the instruction that describes the task: ### Input: Convert nested list of shape (..., 2) to complex numpy array with shape (...) Args: complex_list (list): List to convert. Returns: np.ndarray: Complex numpy aray Raises: QiskitError: If inner most array of input ...
def all_pods_are_ready(self, app_name): """ Check if all pods are ready for specific app :param app_name: str, name of the app :return: bool """ app_pod_exists = False for pod in self.list_pods(namespace=self.project): if app_name in pod.name and 'buil...
Check if all pods are ready for specific app :param app_name: str, name of the app :return: bool
Below is the the instruction that describes the task: ### Input: Check if all pods are ready for specific app :param app_name: str, name of the app :return: bool ### Response: def all_pods_are_ready(self, app_name): """ Check if all pods are ready for specific app :param app...
def force_extrapolation(self): """Force the underlying model to extrapolate. An example where this is useful: You create a source spectrum with non-default extrapolation behavior and you wish to force the underlying empirical model to extrapolate based on nearest point. .. note...
Force the underlying model to extrapolate. An example where this is useful: You create a source spectrum with non-default extrapolation behavior and you wish to force the underlying empirical model to extrapolate based on nearest point. .. note:: This is only applicable to...
Below is the the instruction that describes the task: ### Input: Force the underlying model to extrapolate. An example where this is useful: You create a source spectrum with non-default extrapolation behavior and you wish to force the underlying empirical model to extrapolate based on near...
def render(self, name, value, attrs=None): """ Render the ``icekit_events/recurrence_rule_widget/render.html`` template with the following context: rendered_widgets The rendered widgets. id The ``id`` attribute from the ``attrs`` keyword a...
Render the ``icekit_events/recurrence_rule_widget/render.html`` template with the following context: rendered_widgets The rendered widgets. id The ``id`` attribute from the ``attrs`` keyword argument. recurrence_rules A JSON ob...
Below is the the instruction that describes the task: ### Input: Render the ``icekit_events/recurrence_rule_widget/render.html`` template with the following context: rendered_widgets The rendered widgets. id The ``id`` attribute from the ``attrs`` key...
def get_all_language_codes(): """ Returns all language codes defined in settings.LANGUAGES and also the settings.MSGID_LANGUAGE if defined. >>> from django.conf import settings >>> settings.MSGID_LANGUAGE = 'en-us' >>> settings.LANGUAGES = (('en','English'),('de','German'),('nl-be','Belgium...
Returns all language codes defined in settings.LANGUAGES and also the settings.MSGID_LANGUAGE if defined. >>> from django.conf import settings >>> settings.MSGID_LANGUAGE = 'en-us' >>> settings.LANGUAGES = (('en','English'),('de','German'),('nl-be','Belgium dutch'),('fr-be','Belgium french'),) ...
Below is the the instruction that describes the task: ### Input: Returns all language codes defined in settings.LANGUAGES and also the settings.MSGID_LANGUAGE if defined. >>> from django.conf import settings >>> settings.MSGID_LANGUAGE = 'en-us' >>> settings.LANGUAGES = (('en','English'),('de',...
def tick(self): """Return the time cost string as expect.""" string = self.passed if self.rounding: string = round(string) if self.readable: string = self.readable(string) return string
Return the time cost string as expect.
Below is the the instruction that describes the task: ### Input: Return the time cost string as expect. ### Response: def tick(self): """Return the time cost string as expect.""" string = self.passed if self.rounding: string = round(string) if self.readable: ...
def output_extras(self, output_file): """ Returns dict mapping local path to remote name. """ output_directory = dirname(output_file) def local_path(name): return join(output_directory, self.path_helper.local_name(name)) files_directory = "%s_files%s" % (bas...
Returns dict mapping local path to remote name.
Below is the the instruction that describes the task: ### Input: Returns dict mapping local path to remote name. ### Response: def output_extras(self, output_file): """ Returns dict mapping local path to remote name. """ output_directory = dirname(output_file) def local_pat...
def usage(asked_for=0): '''Exit with a usage string, used for bad argument or with -h''' exit = fsq.const('FSQ_SUCCESS') if asked_for else\ fsq.const('FSQ_FAIL_PERM') f = sys.stdout if asked_for else sys.stderr shout('{0} [opts] src_queue trg_queue host item_id [item_id [...]]'.format( ...
Exit with a usage string, used for bad argument or with -h
Below is the the instruction that describes the task: ### Input: Exit with a usage string, used for bad argument or with -h ### Response: def usage(asked_for=0): '''Exit with a usage string, used for bad argument or with -h''' exit = fsq.const('FSQ_SUCCESS') if asked_for else\ fsq.const('F...
def get_all_parent_edges(self): """Return tuples for all parent GO IDs, containing current GO ID and parent GO ID.""" all_parent_edges = set() for parent in self.parents: all_parent_edges.add((self.item_id, parent.item_id)) all_parent_edges |= parent.get_all_parent_edges(...
Return tuples for all parent GO IDs, containing current GO ID and parent GO ID.
Below is the the instruction that describes the task: ### Input: Return tuples for all parent GO IDs, containing current GO ID and parent GO ID. ### Response: def get_all_parent_edges(self): """Return tuples for all parent GO IDs, containing current GO ID and parent GO ID.""" all_parent_edges = set...
def committer(cls, config_reader=None): """ :return: Actor instance corresponding to the configured committer. It behaves similar to the git implementation, such that the environment will override configuration values of config_reader. If no value is set at all, it will be ...
:return: Actor instance corresponding to the configured committer. It behaves similar to the git implementation, such that the environment will override configuration values of config_reader. If no value is set at all, it will be generated :param config_reader: ConfigReader t...
Below is the the instruction that describes the task: ### Input: :return: Actor instance corresponding to the configured committer. It behaves similar to the git implementation, such that the environment will override configuration values of config_reader. If no value is set at all, it will ...
def _check_release_cmp(name): ''' Helper function to compare release codename versions to the minion's current Salt version. If release codename isn't found, the function returns None. Otherwise, it returns the results of the version comparison as documented by the ``versions_cmp`` function in ...
Helper function to compare release codename versions to the minion's current Salt version. If release codename isn't found, the function returns None. Otherwise, it returns the results of the version comparison as documented by the ``versions_cmp`` function in ``salt.utils.versions.py``.
Below is the the instruction that describes the task: ### Input: Helper function to compare release codename versions to the minion's current Salt version. If release codename isn't found, the function returns None. Otherwise, it returns the results of the version comparison as documented by the ``...
def reset(self): ''' Reset the state of the container and its internal fields ''' super(TakeFrom, self).reset() self.random.seed(self.seed * self.max_elements + self.min_elements)
Reset the state of the container and its internal fields
Below is the the instruction that describes the task: ### Input: Reset the state of the container and its internal fields ### Response: def reset(self): ''' Reset the state of the container and its internal fields ''' super(TakeFrom, self).reset() self.random.seed(self.seed ...
def json_serializer(pid, data, *args): """Build a JSON Flask response using the given data. :param pid: The `invenio_pidstore.models.PersistentIdentifier` of the record. :param data: The record metadata. :returns: A Flask response with JSON data. :rtype: :py:class:`flask.Response`. """ ...
Build a JSON Flask response using the given data. :param pid: The `invenio_pidstore.models.PersistentIdentifier` of the record. :param data: The record metadata. :returns: A Flask response with JSON data. :rtype: :py:class:`flask.Response`.
Below is the the instruction that describes the task: ### Input: Build a JSON Flask response using the given data. :param pid: The `invenio_pidstore.models.PersistentIdentifier` of the record. :param data: The record metadata. :returns: A Flask response with JSON data. :rtype: :py:class:`fl...
def geturl(urllib2_resp): """ Use instead of urllib.addinfourl.geturl(), which appears to have some issues with dropping the double slash for certain schemes (e.g. file://). This implementation is probably over-eager, as it always restores '://' if it is missing, and it appears some url schemat...
Use instead of urllib.addinfourl.geturl(), which appears to have some issues with dropping the double slash for certain schemes (e.g. file://). This implementation is probably over-eager, as it always restores '://' if it is missing, and it appears some url schemata aren't always followed by '//' after...
Below is the the instruction that describes the task: ### Input: Use instead of urllib.addinfourl.geturl(), which appears to have some issues with dropping the double slash for certain schemes (e.g. file://). This implementation is probably over-eager, as it always restores '://' if it is missing, and ...
def get_log_rhos(target_action_log_probs, behaviour_action_log_probs): """With the selected log_probs for multi-discrete actions of behaviour and target policies we compute the log_rhos for calculating the vtrace.""" t = tf.stack(target_action_log_probs) b = tf.stack(behaviour_action_log_probs) log_...
With the selected log_probs for multi-discrete actions of behaviour and target policies we compute the log_rhos for calculating the vtrace.
Below is the the instruction that describes the task: ### Input: With the selected log_probs for multi-discrete actions of behaviour and target policies we compute the log_rhos for calculating the vtrace. ### Response: def get_log_rhos(target_action_log_probs, behaviour_action_log_probs): """With the selec...
def local_renderer(self): """ Retrieves the cached local renderer. """ if not self._local_renderer: r = self.create_local_renderer() self._local_renderer = r return self._local_renderer
Retrieves the cached local renderer.
Below is the the instruction that describes the task: ### Input: Retrieves the cached local renderer. ### Response: def local_renderer(self): """ Retrieves the cached local renderer. """ if not self._local_renderer: r = self.create_local_renderer() self._loca...
def sflow_profile_profile_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") sflow_profile = ET.SubElement(config, "sflow-profile", xmlns="urn:brocade.com:mgmt:brocade-sflow") profile_name = ET.SubElement(sflow_profile, "profile-name") profile_...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def sflow_profile_profile_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") sflow_profile = ET.SubElement(config, "sflow-profile", xmlns="urn:brocade.com:m...
def gene_filter(self, query, mongo_query): """ Adds gene-related filters to the query object Args: query(dict): a dictionary of query filters specified by the users mongo_query(dict): the query that is going to be submitted to the database Returns: mongo_que...
Adds gene-related filters to the query object Args: query(dict): a dictionary of query filters specified by the users mongo_query(dict): the query that is going to be submitted to the database Returns: mongo_query(dict): returned object contains gene and panel-relat...
Below is the the instruction that describes the task: ### Input: Adds gene-related filters to the query object Args: query(dict): a dictionary of query filters specified by the users mongo_query(dict): the query that is going to be submitted to the database Returns: ...
def describe(id_or_link, **kwargs): ''' :param id_or_link: String containing an object ID or dict containing a DXLink, or a list of object IDs or dicts containing a DXLink. Given an object ID, calls :meth:`~dxpy.bindings.DXDataObject.describe` on the object. Example:: d...
:param id_or_link: String containing an object ID or dict containing a DXLink, or a list of object IDs or dicts containing a DXLink. Given an object ID, calls :meth:`~dxpy.bindings.DXDataObject.describe` on the object. Example:: describe("file-1234") Given a list of object...
Below is the the instruction that describes the task: ### Input: :param id_or_link: String containing an object ID or dict containing a DXLink, or a list of object IDs or dicts containing a DXLink. Given an object ID, calls :meth:`~dxpy.bindings.DXDataObject.describe` on the object. ...
def create_column(self, name): """ calls: `POST https://developer.github.com/v3/projects/columns/#create-a-project-column>`_ :param name: string """ assert isinstance(name, (str, unicode)), name post_parameters = {"name": name} import_header = {"Accept": Consts.me...
calls: `POST https://developer.github.com/v3/projects/columns/#create-a-project-column>`_ :param name: string
Below is the the instruction that describes the task: ### Input: calls: `POST https://developer.github.com/v3/projects/columns/#create-a-project-column>`_ :param name: string ### Response: def create_column(self, name): """ calls: `POST https://developer.github.com/v3/projects/columns/#crea...
def stream_subsegments(self): """ Stream all closed subsegments to the daemon and remove reference to the parent segment. No-op for a not sampled segment. """ segment = self.current_segment() if self.streaming.is_eligible(segment): self.streaming.stre...
Stream all closed subsegments to the daemon and remove reference to the parent segment. No-op for a not sampled segment.
Below is the the instruction that describes the task: ### Input: Stream all closed subsegments to the daemon and remove reference to the parent segment. No-op for a not sampled segment. ### Response: def stream_subsegments(self): """ Stream all closed subsegments to the daemon ...