code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def sort_by(items, attr): """ General sort filter - sorts by either attribute or key. """ def key_func(item): try: return getattr(item, attr) except AttributeError: try: return item[attr] except TypeError: getattr(item, ...
General sort filter - sorts by either attribute or key.
Below is the the instruction that describes the task: ### Input: General sort filter - sorts by either attribute or key. ### Response: def sort_by(items, attr): """ General sort filter - sorts by either attribute or key. """ def key_func(item): try: return getattr(item, attr) ...
def _make_temp_filename(prefix): ''' Generate a temporary file that would not live beyond the lifetime of unity_server. Caller is expected to clean up the temp file as soon as the file is no longer needed. But temp files created using this method will be cleaned up when unity_server restarts ...
Generate a temporary file that would not live beyond the lifetime of unity_server. Caller is expected to clean up the temp file as soon as the file is no longer needed. But temp files created using this method will be cleaned up when unity_server restarts
Below is the the instruction that describes the task: ### Input: Generate a temporary file that would not live beyond the lifetime of unity_server. Caller is expected to clean up the temp file as soon as the file is no longer needed. But temp files created using this method will be cleaned up when ...
def get_language_tabs(self): """ Determine the language tabs to show. """ current_language = self.get_current_language() if self.object: available_languages = list(self.object.get_available_languages()) else: available_languages = [] retur...
Determine the language tabs to show.
Below is the the instruction that describes the task: ### Input: Determine the language tabs to show. ### Response: def get_language_tabs(self): """ Determine the language tabs to show. """ current_language = self.get_current_language() if self.object: available_...
def create(self, properties): """ Create a new (user-defined) User Role in this HMC. Authorization requirements: * Task permission to the "Manage User Roles" task. Parameters: properties (dict): Initial property values. Allowable properties are defined i...
Create a new (user-defined) User Role in this HMC. Authorization requirements: * Task permission to the "Manage User Roles" task. Parameters: properties (dict): Initial property values. Allowable properties are defined in section 'Request body contents' in s...
Below is the the instruction that describes the task: ### Input: Create a new (user-defined) User Role in this HMC. Authorization requirements: * Task permission to the "Manage User Roles" task. Parameters: properties (dict): Initial property values. Allowable prope...
def _maybe_download_corpus(tmp_dir, vocab_type): """Download and unpack the corpus. Args: tmp_dir: directory containing dataset. vocab_type: which vocabulary are we using. Returns: The list of names of files. """ if vocab_type == text_problems.VocabType.CHARACTER: dataset_url = ("https://s3...
Download and unpack the corpus. Args: tmp_dir: directory containing dataset. vocab_type: which vocabulary are we using. Returns: The list of names of files.
Below is the the instruction that describes the task: ### Input: Download and unpack the corpus. Args: tmp_dir: directory containing dataset. vocab_type: which vocabulary are we using. Returns: The list of names of files. ### Response: def _maybe_download_corpus(tmp_dir, vocab_type): """Downloa...
def create(self, name): """Create user with provided name and return his id.""" with contextlib.closing(self.database.cursor()) as cursor: cursor.execute('INSERT INTO users(name) VALUES (?)', (name,)) return cursor.lastrowid
Create user with provided name and return his id.
Below is the the instruction that describes the task: ### Input: Create user with provided name and return his id. ### Response: def create(self, name): """Create user with provided name and return his id.""" with contextlib.closing(self.database.cursor()) as cursor: cursor.execute('INS...
def get_id_count(search_term): """Get the number of citations in Pubmed for a search query. Parameters ---------- search_term : str A term for which the PubMed search should be performed. Returns ------- int or None The number of citations for the query, or None if the quer...
Get the number of citations in Pubmed for a search query. Parameters ---------- search_term : str A term for which the PubMed search should be performed. Returns ------- int or None The number of citations for the query, or None if the query fails.
Below is the the instruction that describes the task: ### Input: Get the number of citations in Pubmed for a search query. Parameters ---------- search_term : str A term for which the PubMed search should be performed. Returns ------- int or None The number of citations for...
def put_manifest(self, manifest): """Store the manifest.""" logger.debug("Putting manifest") text = json.dumps(manifest, indent=2, sort_keys=True) key = self.get_manifest_key() self.put_text(key, text)
Store the manifest.
Below is the the instruction that describes the task: ### Input: Store the manifest. ### Response: def put_manifest(self, manifest): """Store the manifest.""" logger.debug("Putting manifest") text = json.dumps(manifest, indent=2, sort_keys=True) key = self.get_manifest_key() ...
def color(self): """ Whether or not color should be output """ return self.tty_stream if self.options.color is None \ else self.options.color
Whether or not color should be output
Below is the the instruction that describes the task: ### Input: Whether or not color should be output ### Response: def color(self): """ Whether or not color should be output """ return self.tty_stream if self.options.color is None \ else self.options.color
def get_filled_structure(self, subgroup=None): ''' method in charged of filling an structure containing the object fields values taking into account the 'group' attribute from the corresponding form object, which is necesary to fill the details form as it is configured in the 'gr...
method in charged of filling an structure containing the object fields values taking into account the 'group' attribute from the corresponding form object, which is necesary to fill the details form as it is configured in the 'group' attribute
Below is the the instruction that describes the task: ### Input: method in charged of filling an structure containing the object fields values taking into account the 'group' attribute from the corresponding form object, which is necesary to fill the details form as it is configured in the '...
def wait(self): """Waits for all submitted jobs to complete.""" logging.info("waiting for {} jobs to complete".format(len(self.submissions))) while not self.shutdown: time.sleep(1)
Waits for all submitted jobs to complete.
Below is the the instruction that describes the task: ### Input: Waits for all submitted jobs to complete. ### Response: def wait(self): """Waits for all submitted jobs to complete.""" logging.info("waiting for {} jobs to complete".format(len(self.submissions))) while not self.shutdown: ...
def register_views(app_name, view_filename, urlpatterns=None): """ app_name APP名 view_filename views 所在的文件 urlpatterns url中已经存在的urlpatterns return urlpatterns 只导入View结尾的,是类的视图 """ app_module = __import__(app_name) view_module = getattr(app_module, view_filename) v...
app_name APP名 view_filename views 所在的文件 urlpatterns url中已经存在的urlpatterns return urlpatterns 只导入View结尾的,是类的视图
Below is the the instruction that describes the task: ### Input: app_name APP名 view_filename views 所在的文件 urlpatterns url中已经存在的urlpatterns return urlpatterns 只导入View结尾的,是类的视图 ### Response: def register_views(app_name, view_filename, urlpatterns=None): """ app_name APP名 ...
def name(self) -> str: """Return template's name (includes whitespace).""" h = self._atomic_partition(self._first_arg_sep)[0] if len(h) == len(self.string): return h[2:-2] return h[2:]
Return template's name (includes whitespace).
Below is the the instruction that describes the task: ### Input: Return template's name (includes whitespace). ### Response: def name(self) -> str: """Return template's name (includes whitespace).""" h = self._atomic_partition(self._first_arg_sep)[0] if len(h) == len(self.string): ...
def x_upper_limit(self, limit=None): """Returns or sets (if a value is provided) the value at which the x-axis should end. By default this is the highest x value in the associated series. :param limit: If given, the chart's x_upper_limit will be set to this. :raises ValueError: ...
Returns or sets (if a value is provided) the value at which the x-axis should end. By default this is the highest x value in the associated series. :param limit: If given, the chart's x_upper_limit will be set to this. :raises ValueError: if you try to make the upper limit smaller than ...
Below is the the instruction that describes the task: ### Input: Returns or sets (if a value is provided) the value at which the x-axis should end. By default this is the highest x value in the associated series. :param limit: If given, the chart's x_upper_limit will be set to this. ...
def beep(self, duration, frequency): """Generates a beep. :param duration: The duration in seconds, in the range 0.1 to 5. :param frequency: The frequency in Hz, in the range 500 to 5000. """ cmd = 'BEEP', [Float(min=0.1, max=5.0), Integer(min=500, max=5000)] self._writ...
Generates a beep. :param duration: The duration in seconds, in the range 0.1 to 5. :param frequency: The frequency in Hz, in the range 500 to 5000.
Below is the the instruction that describes the task: ### Input: Generates a beep. :param duration: The duration in seconds, in the range 0.1 to 5. :param frequency: The frequency in Hz, in the range 500 to 5000. ### Response: def beep(self, duration, frequency): """Generates a beep. ...
def power_on_vm(name, datacenter=None, service_instance=None): ''' Powers on a virtual machine specified by it's name. name Name of the virtual machine datacenter Datacenter of the virtual machine service_instance Service instance (vim.ServiceInstance) of the vCenter. ...
Powers on a virtual machine specified by it's name. name Name of the virtual machine datacenter Datacenter of the virtual machine service_instance Service instance (vim.ServiceInstance) of the vCenter. Default is None. .. code-block:: bash salt '*' vsphere.po...
Below is the the instruction that describes the task: ### Input: Powers on a virtual machine specified by it's name. name Name of the virtual machine datacenter Datacenter of the virtual machine service_instance Service instance (vim.ServiceInstance) of the vCenter. De...
def _grabContentFromUrl(self, url): """ Function that abstracts capturing a URL. This method rewrites the one from Wrapper. :param url: The URL to be processed. :return: The response in a Json format. """ # Defining an empty object for the res...
Function that abstracts capturing a URL. This method rewrites the one from Wrapper. :param url: The URL to be processed. :return: The response in a Json format.
Below is the the instruction that describes the task: ### Input: Function that abstracts capturing a URL. This method rewrites the one from Wrapper. :param url: The URL to be processed. :return: The response in a Json format. ### Response: def _grabContentFromUrl(self, url):...
def returnSupportedOptions(self, options): """This method takes a requested options list from a client, and returns the ones that are supported.""" # We support the options blksize and tsize right now. # FIXME - put this somewhere else? accepted_options = {} for option in...
This method takes a requested options list from a client, and returns the ones that are supported.
Below is the the instruction that describes the task: ### Input: This method takes a requested options list from a client, and returns the ones that are supported. ### Response: def returnSupportedOptions(self, options): """This method takes a requested options list from a client, and retur...
def geoocoords_to_tile_coords(cls, lon, lat, zoom): """ Calculates the tile numbers corresponding to the specified geocoordinates at the specified zoom level Coordinates shall be provided in degrees and using the Mercator Projection (http://en.wikipedia.org/wiki/Mercator_projection) :pa...
Calculates the tile numbers corresponding to the specified geocoordinates at the specified zoom level Coordinates shall be provided in degrees and using the Mercator Projection (http://en.wikipedia.org/wiki/Mercator_projection) :param lon: longitude :type lon: int or float :param lat: l...
Below is the the instruction that describes the task: ### Input: Calculates the tile numbers corresponding to the specified geocoordinates at the specified zoom level Coordinates shall be provided in degrees and using the Mercator Projection (http://en.wikipedia.org/wiki/Mercator_projection) :param...
def _parse_oracle(lines): """ Performs the actual file parsing, returning a dict of the config values in a given Oracle DB config file. Despite their differences, the two filetypes are similar enough to allow idential parsing. """ config = {} for line in get_active_lines(lines): ...
Performs the actual file parsing, returning a dict of the config values in a given Oracle DB config file. Despite their differences, the two filetypes are similar enough to allow idential parsing.
Below is the the instruction that describes the task: ### Input: Performs the actual file parsing, returning a dict of the config values in a given Oracle DB config file. Despite their differences, the two filetypes are similar enough to allow idential parsing. ### Response: def _parse_oracle(lines): ...
def _flow_check_handler_internal(self): """Periodic handler to check if installed flows are present. This handler runs periodically to check if installed flows are present. This function cannot detect and delete the stale flows, if present. It requires more complexity to delete stale fl...
Periodic handler to check if installed flows are present. This handler runs periodically to check if installed flows are present. This function cannot detect and delete the stale flows, if present. It requires more complexity to delete stale flows. Generally, stale flows are not present...
Below is the the instruction that describes the task: ### Input: Periodic handler to check if installed flows are present. This handler runs periodically to check if installed flows are present. This function cannot detect and delete the stale flows, if present. It requires more complexity ...
def com_google_fonts_check_metadata_italic_style(ttFont, font_metadata): """METADATA.pb font.style "italic" matches font internals?""" from fontbakery.utils import get_name_entry_strings from fontbakery.constants import MacStyle if font_metadata.style != "italic": yield SKIP, "This check only applies to it...
METADATA.pb font.style "italic" matches font internals?
Below is the the instruction that describes the task: ### Input: METADATA.pb font.style "italic" matches font internals? ### Response: def com_google_fonts_check_metadata_italic_style(ttFont, font_metadata): """METADATA.pb font.style "italic" matches font internals?""" from fontbakery.utils import get_name_ent...
def cli(obj): """Display alerts like unix "top" command.""" client = obj['client'] timezone = obj['timezone'] screen = Screen(client, timezone) screen.run()
Display alerts like unix "top" command.
Below is the the instruction that describes the task: ### Input: Display alerts like unix "top" command. ### Response: def cli(obj): """Display alerts like unix "top" command.""" client = obj['client'] timezone = obj['timezone'] screen = Screen(client, timezone) screen.run()
def gateway(self): """Return the detail of the gateway.""" url = 'https://tccna.honeywell.com/WebAPI/emea/api/v1/gateway' response = requests.get(url, headers=self._headers()) response.raise_for_status() return response.json()
Return the detail of the gateway.
Below is the the instruction that describes the task: ### Input: Return the detail of the gateway. ### Response: def gateway(self): """Return the detail of the gateway.""" url = 'https://tccna.honeywell.com/WebAPI/emea/api/v1/gateway' response = requests.get(url, headers=self._headers()) ...
def em_schedule(**kwargs): """Run multiple energy minimizations one after each other. :Keywords: *integrators* list of integrators (from 'l-bfgs', 'cg', 'steep') [['bfgs', 'steep']] *nsteps* list of maximum number of steps; one for each integrator in in t...
Run multiple energy minimizations one after each other. :Keywords: *integrators* list of integrators (from 'l-bfgs', 'cg', 'steep') [['bfgs', 'steep']] *nsteps* list of maximum number of steps; one for each integrator in in the *integrators* list [[100,1000]]...
Below is the the instruction that describes the task: ### Input: Run multiple energy minimizations one after each other. :Keywords: *integrators* list of integrators (from 'l-bfgs', 'cg', 'steep') [['bfgs', 'steep']] *nsteps* list of maximum number of steps; one for...
def toupper(self): """ Translate characters from lower to upper case for a particular column. :returns: new H2OFrame with all strings in the current frame converted to the uppercase. """ return H2OFrame._expr(expr=ExprNode("toupper", self), cache=self._ex._cache)
Translate characters from lower to upper case for a particular column. :returns: new H2OFrame with all strings in the current frame converted to the uppercase.
Below is the the instruction that describes the task: ### Input: Translate characters from lower to upper case for a particular column. :returns: new H2OFrame with all strings in the current frame converted to the uppercase. ### Response: def toupper(self): """ Translate characters from lo...
def cache_data(self, request, data, key='params'): """ Cache data in the session store. :param request: :attr:`django.http.HttpRequest` :param data: Arbitrary data to store. :param key: `str` The key under which to store the data. """ request.session['%s:%s' % (c...
Cache data in the session store. :param request: :attr:`django.http.HttpRequest` :param data: Arbitrary data to store. :param key: `str` The key under which to store the data.
Below is the the instruction that describes the task: ### Input: Cache data in the session store. :param request: :attr:`django.http.HttpRequest` :param data: Arbitrary data to store. :param key: `str` The key under which to store the data. ### Response: def cache_data(self, request, data,...
def mark_offer_as_lose(self, offer_id): """ Mark offer as lose :param offer_id: the offer id :return Response """ return self._create_put_request( resource=OFFERS, billomat_id=offer_id, command=LOSE, )
Mark offer as lose :param offer_id: the offer id :return Response
Below is the the instruction that describes the task: ### Input: Mark offer as lose :param offer_id: the offer id :return Response ### Response: def mark_offer_as_lose(self, offer_id): """ Mark offer as lose :param offer_id: the offer id :return Response ""...
def _reshape_by_device_single(x, num_devices): """Reshape x into a shape [num_devices, ...].""" x_shape = list(x.shape) batch_size = x_shape[0] batch_size_per_device = batch_size // num_devices # We require that num_devices divides batch_size evenly. if batch_size_per_device * num_devices != batch_size: ...
Reshape x into a shape [num_devices, ...].
Below is the the instruction that describes the task: ### Input: Reshape x into a shape [num_devices, ...]. ### Response: def _reshape_by_device_single(x, num_devices): """Reshape x into a shape [num_devices, ...].""" x_shape = list(x.shape) batch_size = x_shape[0] batch_size_per_device = batch_size // num...
def E(poly, dist=None, **kws): """ Expected value operator. 1st order statistics of a probability distribution or polynomial on a given probability space. Args: poly (Poly, Dist): Input to take expected value on. dist (Dist): Defines the space the expected v...
Expected value operator. 1st order statistics of a probability distribution or polynomial on a given probability space. Args: poly (Poly, Dist): Input to take expected value on. dist (Dist): Defines the space the expected value is taken on. It is ignored if ...
Below is the the instruction that describes the task: ### Input: Expected value operator. 1st order statistics of a probability distribution or polynomial on a given probability space. Args: poly (Poly, Dist): Input to take expected value on. dist (Dist): Define...
def ask_pascal_16(self, next_rva_ptr): """The next RVA is taken to be the one immediately following this one. Such RVA could indicate the natural end of the string and will be checked with the possible length contained in the first word. """ length = self.__get_...
The next RVA is taken to be the one immediately following this one. Such RVA could indicate the natural end of the string and will be checked with the possible length contained in the first word.
Below is the the instruction that describes the task: ### Input: The next RVA is taken to be the one immediately following this one. Such RVA could indicate the natural end of the string and will be checked with the possible length contained in the first word. ### Response: def ask_pascal_...
def _handle_result_line(self, sline): """ Parses the data line and adds to the dictionary. :param sline: a split data line to parse :returns: the number of rows to jump and parse the next data line or return the code error -1 """ as_kw = sline[3] a_result ...
Parses the data line and adds to the dictionary. :param sline: a split data line to parse :returns: the number of rows to jump and parse the next data line or return the code error -1
Below is the the instruction that describes the task: ### Input: Parses the data line and adds to the dictionary. :param sline: a split data line to parse :returns: the number of rows to jump and parse the next data line or return the code error -1 ### Response: def _handle_result_line(self...
async def freedomscores(self, root): """Nation's `Freedoms`: three basic indicators of the nation's Civil Rights, Economy, and Political Freedom, as percentages. Returns ------- an :class:`ApiQuery` of :class:`collections.OrderedDict` with \ keys of str and values of int...
Nation's `Freedoms`: three basic indicators of the nation's Civil Rights, Economy, and Political Freedom, as percentages. Returns ------- an :class:`ApiQuery` of :class:`collections.OrderedDict` with \ keys of str and values of int Keys being, in order: ``Civil Right...
Below is the the instruction that describes the task: ### Input: Nation's `Freedoms`: three basic indicators of the nation's Civil Rights, Economy, and Political Freedom, as percentages. Returns ------- an :class:`ApiQuery` of :class:`collections.OrderedDict` with \ keys of ...
def get_events(self, service_location_id, appliance_id, start, end, max_number=None): """ Request events for a given appliance Parameters ---------- service_location_id : int appliance_id : int start : int | dt.datetime | pd.Timestamp e...
Request events for a given appliance Parameters ---------- service_location_id : int appliance_id : int start : int | dt.datetime | pd.Timestamp end : int | dt.datetime | pd.Timestamp start and end support epoch (in milliseconds), datetime and Pan...
Below is the the instruction that describes the task: ### Input: Request events for a given appliance Parameters ---------- service_location_id : int appliance_id : int start : int | dt.datetime | pd.Timestamp end : int | dt.datetime | pd.Timestamp start ...
def scaffold(args): """ %prog scaffold ctgfasta reads1.fasta mapping1.bed reads2.fasta mapping2.bed ... Run BAMBUS on set of contigs, reads and read mappings. """ from jcvi.formats.base import FileMerger from jcvi.formats.bed import mates from jcvi.formats.conti...
%prog scaffold ctgfasta reads1.fasta mapping1.bed reads2.fasta mapping2.bed ... Run BAMBUS on set of contigs, reads and read mappings.
Below is the the instruction that describes the task: ### Input: %prog scaffold ctgfasta reads1.fasta mapping1.bed reads2.fasta mapping2.bed ... Run BAMBUS on set of contigs, reads and read mappings. ### Response: def scaffold(args): """ %prog scaffold ctgfasta reads1.fasta...
def gen_xml_doc(self): """ Generate the text tags that should be inserted in the content.xml of a full model """ res = self.make_doc() var_tag = """ <text:user-field-decl office:value-type="string" office:string-value="%s" text:name="py3o.%s"/>""" ...
Generate the text tags that should be inserted in the content.xml of a full model
Below is the the instruction that describes the task: ### Input: Generate the text tags that should be inserted in the content.xml of a full model ### Response: def gen_xml_doc(self): """ Generate the text tags that should be inserted in the content.xml of a full model """ ...
def find_ss_regions(dssp_residues, loop_assignments=(' ', 'B', 'S', 'T')): """Separates parsed DSSP data into groups of secondary structure. Notes ----- Example: all residues in a single helix/loop/strand will be gathered into a list, then the next secondary structure element will be gathered i...
Separates parsed DSSP data into groups of secondary structure. Notes ----- Example: all residues in a single helix/loop/strand will be gathered into a list, then the next secondary structure element will be gathered into a separate list, and so on. Parameters ---------- dssp_residues :...
Below is the the instruction that describes the task: ### Input: Separates parsed DSSP data into groups of secondary structure. Notes ----- Example: all residues in a single helix/loop/strand will be gathered into a list, then the next secondary structure element will be gathered into a separat...
def expand_path_cfg(path_cfg, alias_dict={ }, overriding_kargs={ }): """expand a path config Args: path_cfg (str, tuple, dict): a config for path alias_dict (dict): a dict for aliases overriding_kargs (dict): to be used for recursive call """ if isinstance(path_cfg, str): ...
expand a path config Args: path_cfg (str, tuple, dict): a config for path alias_dict (dict): a dict for aliases overriding_kargs (dict): to be used for recursive call
Below is the the instruction that describes the task: ### Input: expand a path config Args: path_cfg (str, tuple, dict): a config for path alias_dict (dict): a dict for aliases overriding_kargs (dict): to be used for recursive call ### Response: def expand_path_cfg(path_cfg, alias_dict...
def upload_headimg(self, account, media_file): """ 上传客服账号头像 详情请参考 http://mp.weixin.qq.com/wiki/1/70a29afed17f56d537c833f89be979c9.html :param account: 完整客服账号 :param media_file: 要上传的头像文件,一个 File-Object :return: 返回的 JSON 数据包 """ return self._post( ...
上传客服账号头像 详情请参考 http://mp.weixin.qq.com/wiki/1/70a29afed17f56d537c833f89be979c9.html :param account: 完整客服账号 :param media_file: 要上传的头像文件,一个 File-Object :return: 返回的 JSON 数据包
Below is the the instruction that describes the task: ### Input: 上传客服账号头像 详情请参考 http://mp.weixin.qq.com/wiki/1/70a29afed17f56d537c833f89be979c9.html :param account: 完整客服账号 :param media_file: 要上传的头像文件,一个 File-Object :return: 返回的 JSON 数据包 ### Response: def upload_headimg(self...
def transferCoincidences(network, fromElementName, toElementName): """ Gets the coincidence matrix from one element and sets it on another element (using locked handles, a la nupic.bindings.research.lockHandle). TODO: Generalize to more node types, parameter name pairs, etc. Does not work across processes...
Gets the coincidence matrix from one element and sets it on another element (using locked handles, a la nupic.bindings.research.lockHandle). TODO: Generalize to more node types, parameter name pairs, etc. Does not work across processes.
Below is the the instruction that describes the task: ### Input: Gets the coincidence matrix from one element and sets it on another element (using locked handles, a la nupic.bindings.research.lockHandle). TODO: Generalize to more node types, parameter name pairs, etc. Does not work across processes. ### ...
def add_component(self, entity, component): """Add component to entity. Long-hand for :func:`essence.Entity.add`. :param entity: entity to associate :type entity: :class:`essence.Entity` :param component: component to add to the entity :type component: :class:`essence.C...
Add component to entity. Long-hand for :func:`essence.Entity.add`. :param entity: entity to associate :type entity: :class:`essence.Entity` :param component: component to add to the entity :type component: :class:`essence.Component`
Below is the the instruction that describes the task: ### Input: Add component to entity. Long-hand for :func:`essence.Entity.add`. :param entity: entity to associate :type entity: :class:`essence.Entity` :param component: component to add to the entity :type component: :cl...
def calculate_size(name, include_value, local_only): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += BOOLEAN_SIZE_IN_BYTES data_size += BOOLEAN_SIZE_IN_BYTES return data_size
Calculates the request payload size
Below is the the instruction that describes the task: ### Input: Calculates the request payload size ### Response: def calculate_size(name, include_value, local_only): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += BOOLEAN_SIZE_IN_BYTES ...
def _get_plot_data(self): """Extract only good data point for plotting.""" _marker_type = self.settings.get('markerstyle', 'o') if self.x_col == self._idxname: x_data = self._idx else: x_data = self.tab[self.x_col].data if self.y_col == self._idxname: ...
Extract only good data point for plotting.
Below is the the instruction that describes the task: ### Input: Extract only good data point for plotting. ### Response: def _get_plot_data(self): """Extract only good data point for plotting.""" _marker_type = self.settings.get('markerstyle', 'o') if self.x_col == self._idxname: ...
def file_saved_in_other_editorstack(self, original_filename, filename): """ File was just saved in another editorstack, let's synchronize! This avoids file being automatically reloaded. The original filename is passed instead of an index in case the tabs on the editor stac...
File was just saved in another editorstack, let's synchronize! This avoids file being automatically reloaded. The original filename is passed instead of an index in case the tabs on the editor stacks were moved and are now in a different order - see issue 5703. Filename is...
Below is the the instruction that describes the task: ### Input: File was just saved in another editorstack, let's synchronize! This avoids file being automatically reloaded. The original filename is passed instead of an index in case the tabs on the editor stacks were moved and are now...
def parse_pv(header): """ Parses the PV array from an astropy FITS header. Args: header: astropy.io.fits.header.Header The header containing the PV values. Returns: cd: 2d array (list(list(float)) [[PV1_0, PV1_1, ... PV1_N], [PV2_0, PV2_1, ... PV2_N]] Note that N de...
Parses the PV array from an astropy FITS header. Args: header: astropy.io.fits.header.Header The header containing the PV values. Returns: cd: 2d array (list(list(float)) [[PV1_0, PV1_1, ... PV1_N], [PV2_0, PV2_1, ... PV2_N]] Note that N depends on the order of the fit. Fo...
Below is the the instruction that describes the task: ### Input: Parses the PV array from an astropy FITS header. Args: header: astropy.io.fits.header.Header The header containing the PV values. Returns: cd: 2d array (list(list(float)) [[PV1_0, PV1_1, ... PV1_N], [PV2_0, PV2_1,...
def handle_url(url, session, res): """Parse one search result page.""" print("Parsing", url, file=sys.stderr) try: data = getPageContent(url, session) except IOError as msg: print("ERROR:", msg, file=sys.stderr) return for match in url_matcher.finditer(data): url = ma...
Parse one search result page.
Below is the the instruction that describes the task: ### Input: Parse one search result page. ### Response: def handle_url(url, session, res): """Parse one search result page.""" print("Parsing", url, file=sys.stderr) try: data = getPageContent(url, session) except IOError as msg: ...
def dumps(self, fd, **kwargs): """ Returns the concrete content for a file descriptor. BACKWARD COMPATIBILITY: if you ask for file descriptors 0 1 or 2, it will return the data from stdin, stdout, or stderr as a flat string. :param fd: A file descriptor. :return: Th...
Returns the concrete content for a file descriptor. BACKWARD COMPATIBILITY: if you ask for file descriptors 0 1 or 2, it will return the data from stdin, stdout, or stderr as a flat string. :param fd: A file descriptor. :return: The concrete content. :rtype: str
Below is the the instruction that describes the task: ### Input: Returns the concrete content for a file descriptor. BACKWARD COMPATIBILITY: if you ask for file descriptors 0 1 or 2, it will return the data from stdin, stdout, or stderr as a flat string. :param fd: A file descriptor. ...
def calc_qt_v1(self): """Calculate the total discharge after possible abstractions. Required control parameter: |Abstr| Required flux sequence: |OutUH| Calculated flux sequence: |QT| Basic equation: :math:`QT = max(OutUH - Abstr, 0)` Examples: Trying to ab...
Calculate the total discharge after possible abstractions. Required control parameter: |Abstr| Required flux sequence: |OutUH| Calculated flux sequence: |QT| Basic equation: :math:`QT = max(OutUH - Abstr, 0)` Examples: Trying to abstract less then available, a...
Below is the the instruction that describes the task: ### Input: Calculate the total discharge after possible abstractions. Required control parameter: |Abstr| Required flux sequence: |OutUH| Calculated flux sequence: |QT| Basic equation: :math:`QT = max(OutUH - Abstr, ...
def _make_index(self): """ Perform the index computation. It groups layers by type into a dictionary, to allow quick access. """ out = {} for layer in self._layers: cls = layer.__class__ out[cls] = out.get(cls, []) + [layer] return out
Perform the index computation. It groups layers by type into a dictionary, to allow quick access.
Below is the the instruction that describes the task: ### Input: Perform the index computation. It groups layers by type into a dictionary, to allow quick access. ### Response: def _make_index(self): """ Perform the index computation. It groups layers by type into a dictionary, to a...
def collect_basic_info(): """ collect basic info about the system, os, python version... """ s = sys.version_info _collect(json.dumps({'sys.version_info':tuple(s)})) _collect(sys.version) return sys.version
collect basic info about the system, os, python version...
Below is the the instruction that describes the task: ### Input: collect basic info about the system, os, python version... ### Response: def collect_basic_info(): """ collect basic info about the system, os, python version... """ s = sys.version_info _collect(json.dumps({'sys.version_info':tu...
def abort(self, exception=exc.ConnectError): """ Aborts a connection and puts all pending futures into an error state. If ``sys.exc_info()`` is set (i.e. this is being called in an exception handler) then pending futures will have that exc info set. Otherwise the given ``except...
Aborts a connection and puts all pending futures into an error state. If ``sys.exc_info()`` is set (i.e. this is being called in an exception handler) then pending futures will have that exc info set. Otherwise the given ``exception`` parameter is used (defaults to ``ConnectError``).
Below is the the instruction that describes the task: ### Input: Aborts a connection and puts all pending futures into an error state. If ``sys.exc_info()`` is set (i.e. this is being called in an exception handler) then pending futures will have that exc info set. Otherwise the given ``ex...
def _hash_filter_fn(self, filter_fn, **kwargs): """ Construct string representing state of filter_fn Used to cache filtered variants or effects uniquely depending on filter fn values """ filter_fn_name = self._get_function_name(filter_fn, default="filter-none") logger.debug("...
Construct string representing state of filter_fn Used to cache filtered variants or effects uniquely depending on filter fn values
Below is the the instruction that describes the task: ### Input: Construct string representing state of filter_fn Used to cache filtered variants or effects uniquely depending on filter fn values ### Response: def _hash_filter_fn(self, filter_fn, **kwargs): """ Construct string representing sta...
def _format_message(value, line_length, indent="", first_indent=None): ''' Return a string with newlines so that the given string fits into this line length. At the start of the line the indent is added. This can be used for commenting the message out within a file or to indent your text. ...
Return a string with newlines so that the given string fits into this line length. At the start of the line the indent is added. This can be used for commenting the message out within a file or to indent your text. All \\t will be replaced with 4 spaces. @param value: The strin...
Below is the the instruction that describes the task: ### Input: Return a string with newlines so that the given string fits into this line length. At the start of the line the indent is added. This can be used for commenting the message out within a file or to indent your text. All...
def get(self, path, default=_NoDefault, as_type=None, resolve_references=True): """ Gets a value for the specified path. :param path: the configuration key to fetch a value for, steps separated by the separator supplied to the constructor (default ``.``) :param d...
Gets a value for the specified path. :param path: the configuration key to fetch a value for, steps separated by the separator supplied to the constructor (default ``.``) :param default: a value to return if no value is found for the supplied path (``None`` is allowe...
Below is the the instruction that describes the task: ### Input: Gets a value for the specified path. :param path: the configuration key to fetch a value for, steps separated by the separator supplied to the constructor (default ``.``) :param default: a value to return if no...
def _from_binary_ace_header(cls, binary_stream): """See base class.""" ''' ACE Type - 1 ACE Control flags - 1 Size - 2 (includes header size) ''' type, control_flags, size = cls._REPR.unpack(binary_stream) nw_obj = cls((ACEType(type), ACEControlFlags(control_flags), size)) _MOD_...
See base class.
Below is the the instruction that describes the task: ### Input: See base class. ### Response: def _from_binary_ace_header(cls, binary_stream): """See base class.""" ''' ACE Type - 1 ACE Control flags - 1 Size - 2 (includes header size) ''' type, control_flags, size = cls._REPR.unpa...
def phrase_pinyin(phrase, style, heteronym, errors='default', strict=True): """词语拼音转换. :param phrase: 词语 :param errors: 指定如何处理没有拼音的字符 :param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母 :return: 拼音列表 :rtype: list """ py = [] if phrase in PHRASES_DICT: py = deepcopy(PHRASES_DICT[phrase]) ...
词语拼音转换. :param phrase: 词语 :param errors: 指定如何处理没有拼音的字符 :param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母 :return: 拼音列表 :rtype: list
Below is the the instruction that describes the task: ### Input: 词语拼音转换. :param phrase: 词语 :param errors: 指定如何处理没有拼音的字符 :param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母 :return: 拼音列表 :rtype: list ### Response: def phrase_pinyin(phrase, style, heteronym, errors='default', strict=True): """词语拼音转换. ...
def maybe_infer_dtype_type(element): """Try to infer an object's dtype, for use in arithmetic ops Uses `element.dtype` if that's available. Objects implementing the iterator protocol are cast to a NumPy array, and from there the array's type is used. Parameters ---------- element : object ...
Try to infer an object's dtype, for use in arithmetic ops Uses `element.dtype` if that's available. Objects implementing the iterator protocol are cast to a NumPy array, and from there the array's type is used. Parameters ---------- element : object Possibly has a `.dtype` attribute, a...
Below is the the instruction that describes the task: ### Input: Try to infer an object's dtype, for use in arithmetic ops Uses `element.dtype` if that's available. Objects implementing the iterator protocol are cast to a NumPy array, and from there the array's type is used. Parameters -------...
def add_ylabel(self, text=None): """ Add a label to the y-axis. """ y = self.fit.meta['dependent'] if not text: text = '$' + y['tex_symbol'] + r'$ $(\si{' + y['siunitx'] + r'})$' self.plt.set_ylabel(text)
Add a label to the y-axis.
Below is the the instruction that describes the task: ### Input: Add a label to the y-axis. ### Response: def add_ylabel(self, text=None): """ Add a label to the y-axis. """ y = self.fit.meta['dependent'] if not text: text = '$' + y['tex_symbol'] + r'$ $(\si{' + ...
def publish_tcp(self, topic, data, **kwargs): """Use :meth:`NsqdTCPClient.publish` instead. .. deprecated:: 1.0.0 """ return self.__tcp_client.publish(topic, data, **kwargs)
Use :meth:`NsqdTCPClient.publish` instead. .. deprecated:: 1.0.0
Below is the the instruction that describes the task: ### Input: Use :meth:`NsqdTCPClient.publish` instead. .. deprecated:: 1.0.0 ### Response: def publish_tcp(self, topic, data, **kwargs): """Use :meth:`NsqdTCPClient.publish` instead. .. deprecated:: 1.0.0 """ return self...
def connect(self, host=None, port=None, connect=False, **kwargs): """ Explicitly creates the MongoClient; this method must be used in order to specify a non-default host or port to the MongoClient. Takes arguments identical to MongoClient.__init__""" try: self.__conne...
Explicitly creates the MongoClient; this method must be used in order to specify a non-default host or port to the MongoClient. Takes arguments identical to MongoClient.__init__
Below is the the instruction that describes the task: ### Input: Explicitly creates the MongoClient; this method must be used in order to specify a non-default host or port to the MongoClient. Takes arguments identical to MongoClient.__init__ ### Response: def connect(self, host=None, port=...
def get_types_by_attr(resource, template_id=None): """ Using the attributes of the resource, get all the types that this resource matches. @returns a dictionary, keyed on the template name, with the value being the list of type names which match the resources attributes. ...
Using the attributes of the resource, get all the types that this resource matches. @returns a dictionary, keyed on the template name, with the value being the list of type names which match the resources attributes.
Below is the the instruction that describes the task: ### Input: Using the attributes of the resource, get all the types that this resource matches. @returns a dictionary, keyed on the template name, with the value being the list of type names which match the resources attributes. ##...
def street_name(self): """ :example 'Crist Parks' """ pattern = self.random_element(self.street_name_formats) return self.generator.parse(pattern)
:example 'Crist Parks'
Below is the the instruction that describes the task: ### Input: :example 'Crist Parks' ### Response: def street_name(self): """ :example 'Crist Parks' """ pattern = self.random_element(self.street_name_formats) return self.generator.parse(pattern)
def isValid(cntxt: Context, m: FixedShapeMap) -> Tuple[bool, List[str]]: """`5.2 Validation Definition <http://shex.io/shex-semantics/#validation>`_ The expression isValid(G, m) indicates that for every nodeSelector/shapeLabel pair (n, s) in m, s has a corresponding shape expression se and satisfies(n,...
`5.2 Validation Definition <http://shex.io/shex-semantics/#validation>`_ The expression isValid(G, m) indicates that for every nodeSelector/shapeLabel pair (n, s) in m, s has a corresponding shape expression se and satisfies(n, se, G, m). satisfies is defined below for each form of shape expression...
Below is the the instruction that describes the task: ### Input: `5.2 Validation Definition <http://shex.io/shex-semantics/#validation>`_ The expression isValid(G, m) indicates that for every nodeSelector/shapeLabel pair (n, s) in m, s has a corresponding shape expression se and satisfies(n, se, G, m)....
def _read_oem(string): """ Args: string (str): String containing the OEM Return: Ephem: """ ephems = [] required = ('REF_FRAME', 'CENTER_NAME', 'TIME_SYSTEM', 'OBJECT_ID', 'OBJECT_NAME') mode = None for line in string.splitlines(): if not line or line.startswit...
Args: string (str): String containing the OEM Return: Ephem:
Below is the the instruction that describes the task: ### Input: Args: string (str): String containing the OEM Return: Ephem: ### Response: def _read_oem(string): """ Args: string (str): String containing the OEM Return: Ephem: """ ephems = [] required =...
def socket_monitor_loop(self): ''' Monitor the socket and log captured data. ''' try: while True: gevent.socket.wait_read(self.socket.fileno()) self._handle_log_rotations() self.capture_packet() finally: self.clean_up()
Monitor the socket and log captured data.
Below is the the instruction that describes the task: ### Input: Monitor the socket and log captured data. ### Response: def socket_monitor_loop(self): ''' Monitor the socket and log captured data. ''' try: while True: gevent.socket.wait_read(self.socket.fileno()) ...
def setValidityErrorHandler(self, err_func, warn_func, arg=None): """ Register error and warning handlers for RelaxNG validation. These will be called back as f(msg,arg) """ libxml2mod.xmlRelaxNGSetValidErrors(self._o, err_func, warn_func, arg)
Register error and warning handlers for RelaxNG validation. These will be called back as f(msg,arg)
Below is the the instruction that describes the task: ### Input: Register error and warning handlers for RelaxNG validation. These will be called back as f(msg,arg) ### Response: def setValidityErrorHandler(self, err_func, warn_func, arg=None): """ Register error and warning handlers for Re...
def on_response(self, msg): """ setup response if correlation id is the good one """ LOGGER.debug("natsd.Requester.on_response: " + str(sys.getsizeof(msg)) + " bytes received") working_response = json.loads(msg.data.decode()) working_properties = DriverTools.json2properti...
setup response if correlation id is the good one
Below is the the instruction that describes the task: ### Input: setup response if correlation id is the good one ### Response: def on_response(self, msg): """ setup response if correlation id is the good one """ LOGGER.debug("natsd.Requester.on_response: " + str(sys.getsizeof(msg))...
def _format_dates(self, start, end): """Format start and end dates.""" start = self._split_date(start) end = self._split_date(end) return start, end
Format start and end dates.
Below is the the instruction that describes the task: ### Input: Format start and end dates. ### Response: def _format_dates(self, start, end): """Format start and end dates.""" start = self._split_date(start) end = self._split_date(end) return start, end
def sphericalAngSep(ra0, dec0, ra1, dec1, radians=False): """ Compute the spherical angular separation between two points on the sky. //Taken from http://www.movable-type.co.uk/scripts/gis-faq-5.1.html NB: For small distances you can probably use sqrt( dDec**2 + cos^2(dec)*...
Compute the spherical angular separation between two points on the sky. //Taken from http://www.movable-type.co.uk/scripts/gis-faq-5.1.html NB: For small distances you can probably use sqrt( dDec**2 + cos^2(dec)*dRa) where dDec = dec1 - dec0 and dRa = ra1 - ra0 ...
Below is the the instruction that describes the task: ### Input: Compute the spherical angular separation between two points on the sky. //Taken from http://www.movable-type.co.uk/scripts/gis-faq-5.1.html NB: For small distances you can probably use sqrt( dDec**2 + cos^2(dec)*dRa) ...
def delete_assessment_part(self, assessment_part_id): """Removes an asessment part and all mapped items. arg: assessment_part_id (osid.id.Id): the ``Id`` of the ``AssessmentPart`` raise: NotFound - ``assessment_part_id`` not found raise: NullArgument - ``assessment_...
Removes an asessment part and all mapped items. arg: assessment_part_id (osid.id.Id): the ``Id`` of the ``AssessmentPart`` raise: NotFound - ``assessment_part_id`` not found raise: NullArgument - ``assessment_part_id`` is ``null`` raise: OperationFailed - unable to...
Below is the the instruction that describes the task: ### Input: Removes an asessment part and all mapped items. arg: assessment_part_id (osid.id.Id): the ``Id`` of the ``AssessmentPart`` raise: NotFound - ``assessment_part_id`` not found raise: NullArgument - ``assessm...
def set_value(self, value, status=Sensor.NOMINAL, timestamp=None): """Set sensor value with optinal specification of status and timestamp""" if timestamp is None: timestamp = self._manager.time() self.set(timestamp, status, value)
Set sensor value with optinal specification of status and timestamp
Below is the the instruction that describes the task: ### Input: Set sensor value with optinal specification of status and timestamp ### Response: def set_value(self, value, status=Sensor.NOMINAL, timestamp=None): """Set sensor value with optinal specification of status and timestamp""" if timestam...
def build(self, shutit): """Initializes target ready for build and updating package management if in container. """ if shutit.build['delivery'] in ('docker','dockerfile'): if shutit.get_current_shutit_pexpect_session_environment().install_type == 'apt': shutit.add_to_bashrc('export DEBIAN_FRONTEND=noninter...
Initializes target ready for build and updating package management if in container.
Below is the the instruction that describes the task: ### Input: Initializes target ready for build and updating package management if in container. ### Response: def build(self, shutit): """Initializes target ready for build and updating package management if in container. """ if shutit.build['delivery'] in...
def remove_core_element(self, model): """Remove respective core element of handed outcome model :param OutcomeModel model: Outcome model which core element should be removed :return: """ assert model.outcome.parent is self.model.state gui_helper_state_machine.delete_core...
Remove respective core element of handed outcome model :param OutcomeModel model: Outcome model which core element should be removed :return:
Below is the the instruction that describes the task: ### Input: Remove respective core element of handed outcome model :param OutcomeModel model: Outcome model which core element should be removed :return: ### Response: def remove_core_element(self, model): """Remove respective core eleme...
def register_widget(self, widget_cls, **widget_kwargs): """ Registers the given widget. Widgets must inherit ``DashboardWidgetBase`` and you cannot register the same widget twice. :widget_cls: A class that inherits ``DashboardWidgetBase``. """ if not issubclass...
Registers the given widget. Widgets must inherit ``DashboardWidgetBase`` and you cannot register the same widget twice. :widget_cls: A class that inherits ``DashboardWidgetBase``.
Below is the the instruction that describes the task: ### Input: Registers the given widget. Widgets must inherit ``DashboardWidgetBase`` and you cannot register the same widget twice. :widget_cls: A class that inherits ``DashboardWidgetBase``. ### Response: def register_widget(self, widg...
def dedupe_cols(frame): """ Need to dedupe columns that have the same name. """ cols = list(frame.columns) for i, item in enumerate(frame.columns): if item in frame.columns[:i]: cols[i] = "toDROP" frame.columns = cols return frame.drop("toDROP", 1, errors='ignore')
Need to dedupe columns that have the same name.
Below is the the instruction that describes the task: ### Input: Need to dedupe columns that have the same name. ### Response: def dedupe_cols(frame): """ Need to dedupe columns that have the same name. """ cols = list(frame.columns) for i, item in enumerate(frame.columns): if item in ...
def delete(self, symbol, chunk_range=None, audit=None): """ Delete all chunks for a symbol, or optionally, chunks within a range Parameters ---------- symbol : str symbol name for the item chunk_range: range object a date range to delete a...
Delete all chunks for a symbol, or optionally, chunks within a range Parameters ---------- symbol : str symbol name for the item chunk_range: range object a date range to delete audit: dict dict to store in the audit log
Below is the the instruction that describes the task: ### Input: Delete all chunks for a symbol, or optionally, chunks within a range Parameters ---------- symbol : str symbol name for the item chunk_range: range object a date range to delete audit: d...
def _temporal_distance_pdf(self): """ Temporal distance probability density function. Returns ------- non_delta_peak_split_points: numpy.array non_delta_peak_densities: numpy.array len(density) == len(temporal_distance_split_points_ordered) -1 delta_p...
Temporal distance probability density function. Returns ------- non_delta_peak_split_points: numpy.array non_delta_peak_densities: numpy.array len(density) == len(temporal_distance_split_points_ordered) -1 delta_peak_loc_to_probability_mass : dict
Below is the the instruction that describes the task: ### Input: Temporal distance probability density function. Returns ------- non_delta_peak_split_points: numpy.array non_delta_peak_densities: numpy.array len(density) == len(temporal_distance_split_points_ordered) -1 ...
def _request(self, method, resource_uri, **kwargs): """Perform a method on a resource. Args: method: requests.`method` resource_uri: resource endpoint Raises: HTTPError Returns: JSON Response """ data = kwargs.get('data') ...
Perform a method on a resource. Args: method: requests.`method` resource_uri: resource endpoint Raises: HTTPError Returns: JSON Response
Below is the the instruction that describes the task: ### Input: Perform a method on a resource. Args: method: requests.`method` resource_uri: resource endpoint Raises: HTTPError Returns: JSON Response ### Response: def _request(self, method,...
def generate_report( book_url, fund_ids: StringOption( section="Funds", sort_tag="c", documentation_string="Comma-separated list of fund ids.", default_value="8123,8146,8148,8147") ): """Generates the report output""" return render_report(book_...
Generates the report output
Below is the the instruction that describes the task: ### Input: Generates the report output ### Response: def generate_report( book_url, fund_ids: StringOption( section="Funds", sort_tag="c", documentation_string="Comma-separated list of fund ids.", ...
def MediaBoxSize(self): """Retrieve width, height of /MediaBox.""" CheckParent(self) val = _fitz.Page_MediaBoxSize(self) val = Point(val) if not bool(val): r = self.rect val = Point(r.width, r.height) return val
Retrieve width, height of /MediaBox.
Below is the the instruction that describes the task: ### Input: Retrieve width, height of /MediaBox. ### Response: def MediaBoxSize(self): """Retrieve width, height of /MediaBox.""" CheckParent(self) val = _fitz.Page_MediaBoxSize(self) val = Point(val) if not bool(val): ...
def close(self): """Send CLOSE command to device.""" close_command = StandardSend(self._address, COMMAND_LIGHT_OFF_0X13_0X00) self._send_method(close_command, self._close_message_received)
Send CLOSE command to device.
Below is the the instruction that describes the task: ### Input: Send CLOSE command to device. ### Response: def close(self): """Send CLOSE command to device.""" close_command = StandardSend(self._address, COMMAND_LIGHT_OFF_0X13_0X00) self._send_method(c...
def out_filename(template, n_val, mode): """Determine the output filename""" return '{0}_{1}_{2}.cpp'.format(template.name, n_val, mode.identifier)
Determine the output filename
Below is the the instruction that describes the task: ### Input: Determine the output filename ### Response: def out_filename(template, n_val, mode): """Determine the output filename""" return '{0}_{1}_{2}.cpp'.format(template.name, n_val, mode.identifier)
def update(self, fields=None, async_=None, jira=None, notify=True, **kwargs): """Update this resource on the server. Keyword arguments are marshalled into a dict before being sent. If this resource doesn't support ``PUT``, a :py:exc:`.JIRAError` will be raised; subclasses that specialize this m...
Update this resource on the server. Keyword arguments are marshalled into a dict before being sent. If this resource doesn't support ``PUT``, a :py:exc:`.JIRAError` will be raised; subclasses that specialize this method will only raise errors in case of user error. :param fields: Field...
Below is the the instruction that describes the task: ### Input: Update this resource on the server. Keyword arguments are marshalled into a dict before being sent. If this resource doesn't support ``PUT``, a :py:exc:`.JIRAError` will be raised; subclasses that specialize this method will o...
def sync(self, old_token=None): """Get the current sync token and changed items for synchronization. ``old_token`` an old sync token which is used as the base of the delta update. If sync token is missing, all items are returned. ValueError is raised for invalid or old tokens. "...
Get the current sync token and changed items for synchronization. ``old_token`` an old sync token which is used as the base of the delta update. If sync token is missing, all items are returned. ValueError is raised for invalid or old tokens.
Below is the the instruction that describes the task: ### Input: Get the current sync token and changed items for synchronization. ``old_token`` an old sync token which is used as the base of the delta update. If sync token is missing, all items are returned. ValueError is raised for invali...
def process_callback(self, block=True): """Dispatch a single callback in the current thread. :param boolean block: If True, blocks waiting for a callback to come. :return: True if a callback was processed; otherwise False. """ try: (callback, args) = self._queue.get(...
Dispatch a single callback in the current thread. :param boolean block: If True, blocks waiting for a callback to come. :return: True if a callback was processed; otherwise False.
Below is the the instruction that describes the task: ### Input: Dispatch a single callback in the current thread. :param boolean block: If True, blocks waiting for a callback to come. :return: True if a callback was processed; otherwise False. ### Response: def process_callback(self, block=True):...
def stream_file(self, path, fast_lane=True): """ Create a temp file, stream it to the server if online and append its content using the write() method. This makes sure that we have all newest data of this file on the server directly. At the end of the job, the content the serve...
Create a temp file, stream it to the server if online and append its content using the write() method. This makes sure that we have all newest data of this file on the server directly. At the end of the job, the content the server received is stored as git blob on the server. It is then commit...
Below is the the instruction that describes the task: ### Input: Create a temp file, stream it to the server if online and append its content using the write() method. This makes sure that we have all newest data of this file on the server directly. At the end of the job, the content the s...
def add_model(self, model): """ Add a `RegressionModel` instance. Parameters ---------- model : `RegressionModel` Should have a ``.name`` attribute matching one of the groupby segments. """ logger.debug( 'adding model {} to gr...
Add a `RegressionModel` instance. Parameters ---------- model : `RegressionModel` Should have a ``.name`` attribute matching one of the groupby segments.
Below is the the instruction that describes the task: ### Input: Add a `RegressionModel` instance. Parameters ---------- model : `RegressionModel` Should have a ``.name`` attribute matching one of the groupby segments. ### Response: def add_model(self, model): ...
def update(self, portfolio, date, perfs=None): ''' Actualizes the portfolio universe with the alog state ''' # Make the manager aware of current simulation self.portfolio = portfolio self.perfs = perfs self.date = date
Actualizes the portfolio universe with the alog state
Below is the the instruction that describes the task: ### Input: Actualizes the portfolio universe with the alog state ### Response: def update(self, portfolio, date, perfs=None): ''' Actualizes the portfolio universe with the alog state ''' # Make the manager aware of current simul...
def drawPoints(self, pointPen, filterRedundantPoints=False): """draw self using pointPen""" if filterRedundantPoints: pointPen = FilterRedundantPointPen(pointPen) for contour in self.contours: pointPen.beginPath(identifier=contour["identifier"]) for segmentTyp...
draw self using pointPen
Below is the the instruction that describes the task: ### Input: draw self using pointPen ### Response: def drawPoints(self, pointPen, filterRedundantPoints=False): """draw self using pointPen""" if filterRedundantPoints: pointPen = FilterRedundantPointPen(pointPen) for contour ...
def get_block_by_hash(self, block_hash: Hash32) -> BaseBlock: """ Returns the requested block as specified by block hash. """ validate_word(block_hash, title="Block Hash") block_header = self.get_block_header_by_hash(block_hash) return self.get_block_by_header(block_heade...
Returns the requested block as specified by block hash.
Below is the the instruction that describes the task: ### Input: Returns the requested block as specified by block hash. ### Response: def get_block_by_hash(self, block_hash: Hash32) -> BaseBlock: """ Returns the requested block as specified by block hash. """ validate_word(block_ha...
def __update_window(self, width, height, message_no, page_no): """ Update the window with the menu and the new text """ file_exists_label = '-F-ILE' if not os.path.exists(self.__create_file_name(message_no)): file_exists_label = '(f)ile' # Clear the screen if PLATFOR...
Update the window with the menu and the new text
Below is the the instruction that describes the task: ### Input: Update the window with the menu and the new text ### Response: def __update_window(self, width, height, message_no, page_no): """ Update the window with the menu and the new text """ file_exists_label = '-F-ILE' if not os.path...
def _parse_tmx(path): """Generates examples from TMX file.""" def _get_tuv_lang(tuv): for k, v in tuv.items(): if k.endswith("}lang"): return v raise AssertionError("Language not found in `tuv` attributes.") def _get_tuv_seg(tuv): segs = tuv.findall("seg") assert len(segs) == 1, "In...
Generates examples from TMX file.
Below is the the instruction that describes the task: ### Input: Generates examples from TMX file. ### Response: def _parse_tmx(path): """Generates examples from TMX file.""" def _get_tuv_lang(tuv): for k, v in tuv.items(): if k.endswith("}lang"): return v raise AssertionError("Language n...
def query(self, coords, mode='random_sample'): """ Returns A0 at the given coordinates. There are several different query modes, which handle the probabilistic nature of the map differently. Args: coords (:obj:`astropy.coordinates.SkyCoord`): The coordinates to query. ...
Returns A0 at the given coordinates. There are several different query modes, which handle the probabilistic nature of the map differently. Args: coords (:obj:`astropy.coordinates.SkyCoord`): The coordinates to query. mode (Optional[:obj:`str`]): Five different query modes are a...
Below is the the instruction that describes the task: ### Input: Returns A0 at the given coordinates. There are several different query modes, which handle the probabilistic nature of the map differently. Args: coords (:obj:`astropy.coordinates.SkyCoord`): The coordinates to query. ...
def running_objects(self): """Return the objects associated with this workflow.""" return [obj for obj in self.database_objects if obj.status in [obj.known_statuses.RUNNING]]
Return the objects associated with this workflow.
Below is the the instruction that describes the task: ### Input: Return the objects associated with this workflow. ### Response: def running_objects(self): """Return the objects associated with this workflow.""" return [obj for obj in self.database_objects if obj.status in [obj.know...
def report(self, name, ok, msg=None, deltat=20): '''report a sensor error''' r = self.reports[name] if time.time() < r.last_report + deltat: r.ok = ok return r.last_report = time.time() if ok and not r.ok: self.say("%s OK" % name) r.ok ...
report a sensor error
Below is the the instruction that describes the task: ### Input: report a sensor error ### Response: def report(self, name, ok, msg=None, deltat=20): '''report a sensor error''' r = self.reports[name] if time.time() < r.last_report + deltat: r.ok = ok return ...
def config(scope=None): """ Get the juju charm configuration (scope==None) or individual key, (scope=str). The returned value is a Python data structure loaded as JSON from the Juju config command. :param scope: If set, return the value for the specified key. :type scope: Optional[str] :re...
Get the juju charm configuration (scope==None) or individual key, (scope=str). The returned value is a Python data structure loaded as JSON from the Juju config command. :param scope: If set, return the value for the specified key. :type scope: Optional[str] :returns: Either the whole config as a ...
Below is the the instruction that describes the task: ### Input: Get the juju charm configuration (scope==None) or individual key, (scope=str). The returned value is a Python data structure loaded as JSON from the Juju config command. :param scope: If set, return the value for the specified key. :...
def remove(self, auto_confirm=False, verbose=False): """Remove paths in ``self.paths`` with confirmation (unless ``auto_confirm`` is True).""" if not self.paths: logger.info( "Can't uninstall '%s'. No files were found to uninstall.", self.dist.project...
Remove paths in ``self.paths`` with confirmation (unless ``auto_confirm`` is True).
Below is the the instruction that describes the task: ### Input: Remove paths in ``self.paths`` with confirmation (unless ``auto_confirm`` is True). ### Response: def remove(self, auto_confirm=False, verbose=False): """Remove paths in ``self.paths`` with confirmation (unless ``auto_confirm`...
def preprocess(self, nb_man, resources, km=None): """ Wraps the parent class process call slightly """ with self.setup_preprocessor(nb_man.nb, resources, km=km): if self.log_output: self.log.info("Executing notebook with kernel: {}".format(self.kernel_name)) ...
Wraps the parent class process call slightly
Below is the the instruction that describes the task: ### Input: Wraps the parent class process call slightly ### Response: def preprocess(self, nb_man, resources, km=None): """ Wraps the parent class process call slightly """ with self.setup_preprocessor(nb_man.nb, resources, km=km...
def match_all(d_SMEFT, parameters=None): """Match the SMEFT Warsaw basis onto the WET JMS basis.""" p = default_parameters.copy() if parameters is not None: # if parameters are passed in, overwrite the default values p.update(parameters) C = wilson.util.smeftutil.wcxf2arrays_symmetrized(...
Match the SMEFT Warsaw basis onto the WET JMS basis.
Below is the the instruction that describes the task: ### Input: Match the SMEFT Warsaw basis onto the WET JMS basis. ### Response: def match_all(d_SMEFT, parameters=None): """Match the SMEFT Warsaw basis onto the WET JMS basis.""" p = default_parameters.copy() if parameters is not None: # if p...
def print_tensor(td_tensor, indent="| ", max_depth=-1, depth=0): """ print_tensor(td_tensor, indent=" ", max_depth=-1) Prints the dependency graph of a :py:class:`Tensor` *td_tensor*, where each new level is indented by *indent*. When *max_depth* is positive, the graph is truncated at that depth, where...
print_tensor(td_tensor, indent=" ", max_depth=-1) Prints the dependency graph of a :py:class:`Tensor` *td_tensor*, where each new level is indented by *indent*. When *max_depth* is positive, the graph is truncated at that depth, where each tensor and each op count as a level.
Below is the the instruction that describes the task: ### Input: print_tensor(td_tensor, indent=" ", max_depth=-1) Prints the dependency graph of a :py:class:`Tensor` *td_tensor*, where each new level is indented by *indent*. When *max_depth* is positive, the graph is truncated at that depth, where e...