code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _get_base_class_names(frame): """ Get baseclass names from the code object """ co, lasti = frame.f_code, frame.f_lasti code = co.co_code extends = [] for (op, oparg) in op_stream(code, lasti): if op in dis.hasconst: if type(co.co_consts[oparg]) == str: extend...
Get baseclass names from the code object
Below is the the instruction that describes the task: ### Input: Get baseclass names from the code object ### Response: def _get_base_class_names(frame): """ Get baseclass names from the code object """ co, lasti = frame.f_code, frame.f_lasti code = co.co_code extends = [] for (op, oparg) in o...
def get_capability_definitions(profile_manager): ''' Returns a list of all capability definitions. profile_manager Reference to the profile manager. ''' res_type = pbm.profile.ResourceType( resourceType=pbm.profile.ResourceTypeEnum.STORAGE) try: cap_categories = profile_...
Returns a list of all capability definitions. profile_manager Reference to the profile manager.
Below is the the instruction that describes the task: ### Input: Returns a list of all capability definitions. profile_manager Reference to the profile manager. ### Response: def get_capability_definitions(profile_manager): ''' Returns a list of all capability definitions. profile_manager...
def change_svc_event_handler(self, service, event_handler_command): """Modify service event handler Format of the line that triggers function call:: CHANGE_SVC_EVENT_HANDLER;<host_name>;<service_description>;<event_handler_command> :param service: service to modify event handler ...
Modify service event handler Format of the line that triggers function call:: CHANGE_SVC_EVENT_HANDLER;<host_name>;<service_description>;<event_handler_command> :param service: service to modify event handler :type service: alignak.objects.service.Service :param event_handler_c...
Below is the the instruction that describes the task: ### Input: Modify service event handler Format of the line that triggers function call:: CHANGE_SVC_EVENT_HANDLER;<host_name>;<service_description>;<event_handler_command> :param service: service to modify event handler :type se...
def from_metadata(metadata: Metadata) -> Any: """ Static factory method to create an equivalent instance of this type from the given `Metadata` instance. :param metadata: the `Metadata` instance to create an instance of this class from :return: the created instance of this class ...
Static factory method to create an equivalent instance of this type from the given `Metadata` instance. :param metadata: the `Metadata` instance to create an instance of this class from :return: the created instance of this class
Below is the the instruction that describes the task: ### Input: Static factory method to create an equivalent instance of this type from the given `Metadata` instance. :param metadata: the `Metadata` instance to create an instance of this class from :return: the created instance of this class ### R...
def manual_update_license(self, fd, filename='cdrouter.lic'): """Update the license on your CDRouter system manually by uploading a .lic license from the CDRouter Support Lounge. :param fd: File-like object to upload. :param filename: (optional) Filename to use for license as string. ...
Update the license on your CDRouter system manually by uploading a .lic license from the CDRouter Support Lounge. :param fd: File-like object to upload. :param filename: (optional) Filename to use for license as string. :return: :class:`system.Upgrade <system.Upgrade>` object :r...
Below is the the instruction that describes the task: ### Input: Update the license on your CDRouter system manually by uploading a .lic license from the CDRouter Support Lounge. :param fd: File-like object to upload. :param filename: (optional) Filename to use for license as string. ...
def get_port_name_from_id(node_id, port_id, nodes): """ Get the name of a port for a given node and port ID :param int node_id: node ID :param int port_id: port ID :param list nodes: list of nodes from :py:meth:`generate_nodes` :return: port name :rtype: str ...
Get the name of a port for a given node and port ID :param int node_id: node ID :param int port_id: port ID :param list nodes: list of nodes from :py:meth:`generate_nodes` :return: port name :rtype: str
Below is the the instruction that describes the task: ### Input: Get the name of a port for a given node and port ID :param int node_id: node ID :param int port_id: port ID :param list nodes: list of nodes from :py:meth:`generate_nodes` :return: port name :rtype: str ### Res...
def _step3(self, word): """step3() deals with -ic-, -full, -ness etc. similar strategy to step2.""" ch = word[-1] if ch == 'e': if word.endswith("icate"): return word[:-3] if self._m(word, len(word)-6) else word elif word.endswith("ative"): ...
step3() deals with -ic-, -full, -ness etc. similar strategy to step2.
Below is the the instruction that describes the task: ### Input: step3() deals with -ic-, -full, -ness etc. similar strategy to step2. ### Response: def _step3(self, word): """step3() deals with -ic-, -full, -ness etc. similar strategy to step2.""" ch = word[-1] if ch == 'e': ...
def _get_publish(self): """ Find this publish on remote """ publishes = self._get_publishes(self.client) for publish in publishes: if publish['Distribution'] == self.distribution and \ publish['Prefix'].replace("/", "_") == (self.prefix or '.') and...
Find this publish on remote
Below is the the instruction that describes the task: ### Input: Find this publish on remote ### Response: def _get_publish(self): """ Find this publish on remote """ publishes = self._get_publishes(self.client) for publish in publishes: if publish['Distribution'...
def cdx_clamp(cdx_iter, from_ts, to_ts): """ Clamp by start and end ts """ if from_ts and len(from_ts) < 14: from_ts = pad_timestamp(from_ts, PAD_14_DOWN) if to_ts and len(to_ts) < 14: to_ts = pad_timestamp(to_ts, PAD_14_UP) for cdx in cdx_iter: if from_ts and cdx[TIMES...
Clamp by start and end ts
Below is the the instruction that describes the task: ### Input: Clamp by start and end ts ### Response: def cdx_clamp(cdx_iter, from_ts, to_ts): """ Clamp by start and end ts """ if from_ts and len(from_ts) < 14: from_ts = pad_timestamp(from_ts, PAD_14_DOWN) if to_ts and len(to_ts) < ...
def full_data(self): """ Returns all the info available for the user in the following format: name [username] <id> (locale) bot_or_user If any data is not available, it is not added. """ data = [ self.full_name, self._username(), se...
Returns all the info available for the user in the following format: name [username] <id> (locale) bot_or_user If any data is not available, it is not added.
Below is the the instruction that describes the task: ### Input: Returns all the info available for the user in the following format: name [username] <id> (locale) bot_or_user If any data is not available, it is not added. ### Response: def full_data(self): """ Returns all the i...
def is_valid(arxiv_id): """ Check that a given arXiv ID is a valid one. :param arxiv_id: The arXiv ID to be checked. :returns: Boolean indicating whether the arXiv ID is valid or not. >>> is_valid('1506.06690') True >>> is_valid('1506.06690v1') True >>> is_valid('arXiv:1506.06690...
Check that a given arXiv ID is a valid one. :param arxiv_id: The arXiv ID to be checked. :returns: Boolean indicating whether the arXiv ID is valid or not. >>> is_valid('1506.06690') True >>> is_valid('1506.06690v1') True >>> is_valid('arXiv:1506.06690') True >>> is_valid('arXiv...
Below is the the instruction that describes the task: ### Input: Check that a given arXiv ID is a valid one. :param arxiv_id: The arXiv ID to be checked. :returns: Boolean indicating whether the arXiv ID is valid or not. >>> is_valid('1506.06690') True >>> is_valid('1506.06690v1') True ...
def run(self): """ Runs all tasks in this runner on the executor. Blocks until all tasks have been completed. :return: """ for task in self.get_next_tasks(None): self.executor.add_task(task, None) while not self.executor.is_done(): done_tas...
Runs all tasks in this runner on the executor. Blocks until all tasks have been completed. :return:
Below is the the instruction that describes the task: ### Input: Runs all tasks in this runner on the executor. Blocks until all tasks have been completed. :return: ### Response: def run(self): """ Runs all tasks in this runner on the executor. Blocks until all tasks have be...
def disable_FTDI_driver(): """Disable the FTDI drivers for the current platform. This is necessary because they will conflict with libftdi and accessing the FT232H. Note you can enable the FTDI drivers again by calling enable_FTDI_driver. """ logger.debug('Disabling FTDI driver.') if sys.platf...
Disable the FTDI drivers for the current platform. This is necessary because they will conflict with libftdi and accessing the FT232H. Note you can enable the FTDI drivers again by calling enable_FTDI_driver.
Below is the the instruction that describes the task: ### Input: Disable the FTDI drivers for the current platform. This is necessary because they will conflict with libftdi and accessing the FT232H. Note you can enable the FTDI drivers again by calling enable_FTDI_driver. ### Response: def disable_FTDI_...
def atlas_node_add_callback(atlas_state, callback_name, callback): """ Add a callback to the initialized atlas state """ if callback_name == 'store_zonefile': atlas_state['zonefile_crawler'].set_store_zonefile_callback(callback) else: raise ValueError("Unrecognized callback {}".form...
Add a callback to the initialized atlas state
Below is the the instruction that describes the task: ### Input: Add a callback to the initialized atlas state ### Response: def atlas_node_add_callback(atlas_state, callback_name, callback): """ Add a callback to the initialized atlas state """ if callback_name == 'store_zonefile': atlas_s...
def write_dot_file(G, filename): """ Writes the graph G in dot file format for graphviz visualization. Args: a Networkx graph A filename to name the dot files """ with io.open(filename, "w") as fh: fh.write("strict digraph DependencyDiagram {\n") edge_list = G.edges(...
Writes the graph G in dot file format for graphviz visualization. Args: a Networkx graph A filename to name the dot files
Below is the the instruction that describes the task: ### Input: Writes the graph G in dot file format for graphviz visualization. Args: a Networkx graph A filename to name the dot files ### Response: def write_dot_file(G, filename): """ Writes the graph G in dot file format for graphv...
def _namespace_filtered_iterator(graph, namespace): """Iterate over names in the given namespace.""" for it_namespace, name in _identifier_filtered_iterator(graph): if namespace == it_namespace: yield name
Iterate over names in the given namespace.
Below is the the instruction that describes the task: ### Input: Iterate over names in the given namespace. ### Response: def _namespace_filtered_iterator(graph, namespace): """Iterate over names in the given namespace.""" for it_namespace, name in _identifier_filtered_iterator(graph): if namespace...
def get_offers(self, pair="SWTH_NEO"): """ Function to fetch the open orders on the order book for the trade pair requested. Execution of this function is as follows:: get_offers(pair="SWTH_NEO") The expected return result for this function is as follows:: [{ ...
Function to fetch the open orders on the order book for the trade pair requested. Execution of this function is as follows:: get_offers(pair="SWTH_NEO") The expected return result for this function is as follows:: [{ 'id': '2716c0ca-59bb-4c86-8ee4-6b9528d0e5d2'...
Below is the the instruction that describes the task: ### Input: Function to fetch the open orders on the order book for the trade pair requested. Execution of this function is as follows:: get_offers(pair="SWTH_NEO") The expected return result for this function is as follows:: ...
def set_pixel(self, x, y, color): """ Color may be: value, tuple, list etc. If the image is set to contain more color-channels than len(color), the remaining channels will be filled automatically. Example (channels = 4, i.e. RGBA output): color = 17 -> color = [...
Color may be: value, tuple, list etc. If the image is set to contain more color-channels than len(color), the remaining channels will be filled automatically. Example (channels = 4, i.e. RGBA output): color = 17 -> color = [17,17,17,255] color = (17, 99) -> color = [17...
Below is the the instruction that describes the task: ### Input: Color may be: value, tuple, list etc. If the image is set to contain more color-channels than len(color), the remaining channels will be filled automatically. Example (channels = 4, i.e. RGBA output): color = 17...
def _on_library_path_changed(self, renderer, path, new_library_path): """Callback handling a change of a library path :param Gtk.CellRenderer renderer: Cell renderer showing the library path :param path: Path of library within the list store :param str new_library_path: New library path...
Callback handling a change of a library path :param Gtk.CellRenderer renderer: Cell renderer showing the library path :param path: Path of library within the list store :param str new_library_path: New library path
Below is the the instruction that describes the task: ### Input: Callback handling a change of a library path :param Gtk.CellRenderer renderer: Cell renderer showing the library path :param path: Path of library within the list store :param str new_library_path: New library path ### Respons...
def toTag(self, output): ''' This methods returns all data of this feed as feed xml tag :param output: XML Document to which the data should be added :type output: xml.dom.DOMImplementation.createDocument ''' feed = output.createElement('feed') feed.setAttribute('name', ...
This methods returns all data of this feed as feed xml tag :param output: XML Document to which the data should be added :type output: xml.dom.DOMImplementation.createDocument
Below is the the instruction that describes the task: ### Input: This methods returns all data of this feed as feed xml tag :param output: XML Document to which the data should be added :type output: xml.dom.DOMImplementation.createDocument ### Response: def toTag(self, output): ''' This m...
def delete_if_error(path): '''If any exception is raised inside the context, delete the file at the given path, and allow the exception to continue.''' try: yield except Exception: if os.path.exists(path): os.remove(path) raise
If any exception is raised inside the context, delete the file at the given path, and allow the exception to continue.
Below is the the instruction that describes the task: ### Input: If any exception is raised inside the context, delete the file at the given path, and allow the exception to continue. ### Response: def delete_if_error(path): '''If any exception is raised inside the context, delete the file at the given...
def _ConvertMethodType(self, methodType): """ Convert vmodl.reflect.DynamicTypeManager.MethodTypeInfo to pyVmomi method definition """ if methodType: name = methodType.name wsdlName = methodType.wsdlName version = methodType.version params = self._Filter...
Convert vmodl.reflect.DynamicTypeManager.MethodTypeInfo to pyVmomi method definition
Below is the the instruction that describes the task: ### Input: Convert vmodl.reflect.DynamicTypeManager.MethodTypeInfo to pyVmomi method definition ### Response: def _ConvertMethodType(self, methodType): """ Convert vmodl.reflect.DynamicTypeManager.MethodTypeInfo to pyVmomi method definit...
def _get_block_storage(kwargs): ''' Construct a block storage instance from passed arguments ''' if kwargs is None: kwargs = {} block_storage_name = kwargs.get('name', None) block_storage_size = kwargs.get('size', None) block_storage_description = kwargs.get('description', None) ...
Construct a block storage instance from passed arguments
Below is the the instruction that describes the task: ### Input: Construct a block storage instance from passed arguments ### Response: def _get_block_storage(kwargs): ''' Construct a block storage instance from passed arguments ''' if kwargs is None: kwargs = {} block_storage_name = k...
def encodeIntoArray(self, inpt, output): """ See the function description in base.py """ # Get the scaled value scaledVal = self._getScaledValue(inpt) if scaledVal is None: output[0:] = 0 else: self.encoder.encodeIntoArray(scaledVal, output) if self.verbosity >= 2: ...
See the function description in base.py
Below is the the instruction that describes the task: ### Input: See the function description in base.py ### Response: def encodeIntoArray(self, inpt, output): """ See the function description in base.py """ # Get the scaled value scaledVal = self._getScaledValue(inpt) if scaledVal is Non...
def setPadding(self, pad): """setPadding() -> bytes of length 1. Padding character.""" _baseDes.setPadding(self, pad) for key in (self.__key1, self.__key2, self.__key3): key.setPadding(pad)
setPadding() -> bytes of length 1. Padding character.
Below is the the instruction that describes the task: ### Input: setPadding() -> bytes of length 1. Padding character. ### Response: def setPadding(self, pad): """setPadding() -> bytes of length 1. Padding character.""" _baseDes.setPadding(self, pad) for key in (self.__key1, self.__key2, self.__key3): key...
def _readXputFile(self, file_cards, card_name, directory, session, spatial=False, spatialReferenceID=None, replaceParamFile=None, **kwargs): """ Read specific IO file for a GSSHA project to the database. """ # Automatically derive the spatial r...
Read specific IO file for a GSSHA project to the database.
Below is the the instruction that describes the task: ### Input: Read specific IO file for a GSSHA project to the database. ### Response: def _readXputFile(self, file_cards, card_name, directory, session, spatial=False, spatialReferenceID=None, replaceParamFile=None, **k...
def modify_instance_groups(self, instance_group_ids, new_sizes): """ Modify the number of nodes and configuration settings in an instance group. :type instance_group_ids: list(str) :param instance_group_ids: A list of the ID's of the instance groups to be modified ...
Modify the number of nodes and configuration settings in an instance group. :type instance_group_ids: list(str) :param instance_group_ids: A list of the ID's of the instance groups to be modified :type new_sizes: list(int) :param new_sizes: A list of the...
Below is the the instruction that describes the task: ### Input: Modify the number of nodes and configuration settings in an instance group. :type instance_group_ids: list(str) :param instance_group_ids: A list of the ID's of the instance groups to be modified ...
def internal_assert(condition, message=None, item=None, extra=None): """Raise InternalException if condition is False. If condition is a function, execute it on DEVELOP only.""" if DEVELOP and callable(condition): condition = condition() if not condition: if message is None: ...
Raise InternalException if condition is False. If condition is a function, execute it on DEVELOP only.
Below is the the instruction that describes the task: ### Input: Raise InternalException if condition is False. If condition is a function, execute it on DEVELOP only. ### Response: def internal_assert(condition, message=None, item=None, extra=None): """Raise InternalException if condition is False. If...
def create_or_update(self, resource_group, name, container_group): """ Create a new container group :param resource_group: the name of the resource group :type resource_group: str :param name: the name of the container group :type name: str :param container_group...
Create a new container group :param resource_group: the name of the resource group :type resource_group: str :param name: the name of the container group :type name: str :param container_group: the properties of the container group :type container_group: azure.mgmt.conta...
Below is the the instruction that describes the task: ### Input: Create a new container group :param resource_group: the name of the resource group :type resource_group: str :param name: the name of the container group :type name: str :param container_group: the properties o...
def pop(self): """Pop a request""" method_frame, header, body = self.server.basic_get(queue=self.key) if body: return self._decode_request(body)
Pop a request
Below is the the instruction that describes the task: ### Input: Pop a request ### Response: def pop(self): """Pop a request""" method_frame, header, body = self.server.basic_get(queue=self.key) if body: return self._decode_request(body)
def mxmtg(m1, m2, nrow1, nc1c2, nrow2): """ Multiply a matrix and the transpose of a matrix, both of arbitrary size. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mxmtg_c.html :param m1: Left-hand matrix to be multiplied. :type m1: NxM-Element Array of floats :param m2: Right-hand ma...
Multiply a matrix and the transpose of a matrix, both of arbitrary size. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mxmtg_c.html :param m1: Left-hand matrix to be multiplied. :type m1: NxM-Element Array of floats :param m2: Right-hand matrix whose transpose is to be multiplied :type m...
Below is the the instruction that describes the task: ### Input: Multiply a matrix and the transpose of a matrix, both of arbitrary size. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mxmtg_c.html :param m1: Left-hand matrix to be multiplied. :type m1: NxM-Element Array of floats :param ...
def post_build(self, pkt, pay): """ need to set the length of the whole PDU manually to avoid any bit fiddling use a dummy class to build the layer content also add padding if frame is < 64 bytes Note: padding only handles Ether/n*Dot1Q/EtherCat (no special mumbo ...
need to set the length of the whole PDU manually to avoid any bit fiddling use a dummy class to build the layer content also add padding if frame is < 64 bytes Note: padding only handles Ether/n*Dot1Q/EtherCat (no special mumbo jumbo) :param pkt: raw string containing th...
Below is the the instruction that describes the task: ### Input: need to set the length of the whole PDU manually to avoid any bit fiddling use a dummy class to build the layer content also add padding if frame is < 64 bytes Note: padding only handles Ether/n*Dot1Q/EtherCat (...
def checkMaxSessions(self, nMax=None): """ check whether max. number of saved sessions is reached if: remove the oldest session """ if nMax is None: nMax = self.opts['maxSessions'] l = self.stateNames() if len(l) > nMax: for f in l...
check whether max. number of saved sessions is reached if: remove the oldest session
Below is the the instruction that describes the task: ### Input: check whether max. number of saved sessions is reached if: remove the oldest session ### Response: def checkMaxSessions(self, nMax=None): """ check whether max. number of saved sessions is reached if: remove the ol...
def list(self, offset=0, limit=0, fields=None, sort=None, **kwargs): """Return filtered list of documents in a collection. For text-based search, we support searching on a name/string field by regex and text index. So strings passed in to a r=text search are used to filter collections b...
Return filtered list of documents in a collection. For text-based search, we support searching on a name/string field by regex and text index. So strings passed in to a r=text search are used to filter collections by text index and regex on a named field. :param offset: for pagination,...
Below is the the instruction that describes the task: ### Input: Return filtered list of documents in a collection. For text-based search, we support searching on a name/string field by regex and text index. So strings passed in to a r=text search are used to filter collections by text inde...
def _verifyReturnToArgs(query): """Verify that the arguments in the return_to URL are present in this response. """ message = Message.fromPostArgs(query) return_to = message.getArg(OPENID_NS, 'return_to') if return_to is None: raise ProtocolError('Response ha...
Verify that the arguments in the return_to URL are present in this response.
Below is the the instruction that describes the task: ### Input: Verify that the arguments in the return_to URL are present in this response. ### Response: def _verifyReturnToArgs(query): """Verify that the arguments in the return_to URL are present in this response. """ mes...
def GET_save_modifiedconditionitemvalues(self) -> None: """ToDo: extend functionality and add tests""" for item in state.conditionitems: state.modifiedconditionitemvalues[self._id][item.name] = \ list(item.device2target.values())[0].value
ToDo: extend functionality and add tests
Below is the the instruction that describes the task: ### Input: ToDo: extend functionality and add tests ### Response: def GET_save_modifiedconditionitemvalues(self) -> None: """ToDo: extend functionality and add tests""" for item in state.conditionitems: state.modifiedconditionitemval...
def base64url_to_long(data): """ Stricter then base64_to_long since it really checks that it's base64url encoded :param data: The base64 string :return: """ _data = as_bytes(data) _d = base64.urlsafe_b64decode(_data + b'==') # verify that it's base64url encoded and not just base64 ...
Stricter then base64_to_long since it really checks that it's base64url encoded :param data: The base64 string :return:
Below is the the instruction that describes the task: ### Input: Stricter then base64_to_long since it really checks that it's base64url encoded :param data: The base64 string :return: ### Response: def base64url_to_long(data): """ Stricter then base64_to_long since it really checks that it's ...
def normalize_sphere(alpha, delta): """Normalize angles of a point on a sphere. Parameters ---------- alpha: float The alpha (right ascension/longitude like) angle in degrees. delta: float The delta (declination/latitude like) angle in degrees. Returns ------- (alpha, d...
Normalize angles of a point on a sphere. Parameters ---------- alpha: float The alpha (right ascension/longitude like) angle in degrees. delta: float The delta (declination/latitude like) angle in degrees. Returns ------- (alpha, delta): (float, float) Normalized al...
Below is the the instruction that describes the task: ### Input: Normalize angles of a point on a sphere. Parameters ---------- alpha: float The alpha (right ascension/longitude like) angle in degrees. delta: float The delta (declination/latitude like) angle in degrees. Returns...
def fts_contrast2(self, fs, ft_name, inv): """Return `True` if there is a segment in `inv` that contrasts in feature `ft_name`. Args: fs (list): feature specifications used to filter `inv`. ft_name (str): name of the feature where contrast must be present. in...
Return `True` if there is a segment in `inv` that contrasts in feature `ft_name`. Args: fs (list): feature specifications used to filter `inv`. ft_name (str): name of the feature where contrast must be present. inv (list): collection of segments represented as Unicod...
Below is the the instruction that describes the task: ### Input: Return `True` if there is a segment in `inv` that contrasts in feature `ft_name`. Args: fs (list): feature specifications used to filter `inv`. ft_name (str): name of the feature where contrast must be present....
def needs_refresh(self): ''' This is called when the user is logged in, but they need to be reauthenticated because their session is stale. If you register a callback with `needs_refresh_handler`, then it will be called. Otherwise, it will take the following actions: ...
This is called when the user is logged in, but they need to be reauthenticated because their session is stale. If you register a callback with `needs_refresh_handler`, then it will be called. Otherwise, it will take the following actions: - Flash :attr:`LoginManager.needs_refresh_me...
Below is the the instruction that describes the task: ### Input: This is called when the user is logged in, but they need to be reauthenticated because their session is stale. If you register a callback with `needs_refresh_handler`, then it will be called. Otherwise, it will take the followi...
def generate_file_rst(fname, target_dir, src_dir, gallery_conf): """ Generate the rst file for a given example. Returns the amout of code (in characters) of the corresponding files. """ src_file = os.path.join(src_dir, fname) example_file = os.path.join(target_dir, fname) shutil.co...
Generate the rst file for a given example. Returns the amout of code (in characters) of the corresponding files.
Below is the the instruction that describes the task: ### Input: Generate the rst file for a given example. Returns the amout of code (in characters) of the corresponding files. ### Response: def generate_file_rst(fname, target_dir, src_dir, gallery_conf): """ Generate the rst file for a given...
def calcparams_cec(self, effective_irradiance, temp_cell, **kwargs): """ Use the :py:func:`calcparams_cec` function, the input parameters and ``self.module_parameters`` to calculate the module currents and resistances. Parameters ---------- effective_irradiance :...
Use the :py:func:`calcparams_cec` function, the input parameters and ``self.module_parameters`` to calculate the module currents and resistances. Parameters ---------- effective_irradiance : numeric The irradiance (W/m2) that is converted to photocurrent. te...
Below is the the instruction that describes the task: ### Input: Use the :py:func:`calcparams_cec` function, the input parameters and ``self.module_parameters`` to calculate the module currents and resistances. Parameters ---------- effective_irradiance : numeric ...
def clone(self, folder, git_repository): """Ensures theme destination folder and clone git specified repo in it. :param git_repository: git url of the theme folder :param folder: path of the git managed theme folder """ os.makedirs(folder) git.Git().clone(git_repository,...
Ensures theme destination folder and clone git specified repo in it. :param git_repository: git url of the theme folder :param folder: path of the git managed theme folder
Below is the the instruction that describes the task: ### Input: Ensures theme destination folder and clone git specified repo in it. :param git_repository: git url of the theme folder :param folder: path of the git managed theme folder ### Response: def clone(self, folder, git_repository): ...
def slice_list(in_list, lens): """Slice a list into several sub lists by a list of given length. Args: in_list (list): The list to be sliced. lens(int or list): The expected length of each out list. Returns: list: A list of sliced list. """ if not isinstance(lens, list): ...
Slice a list into several sub lists by a list of given length. Args: in_list (list): The list to be sliced. lens(int or list): The expected length of each out list. Returns: list: A list of sliced list.
Below is the the instruction that describes the task: ### Input: Slice a list into several sub lists by a list of given length. Args: in_list (list): The list to be sliced. lens(int or list): The expected length of each out list. Returns: list: A list of sliced list. ### Response: ...
def remove_compute(self, compute, **kwargs): """ Remove a 'compute' from the bundle :parameter str compute: name of the compute options :parameter **kwargs: any other tags to do the filter (except twig or context) :raise NotImplementedError: because it isn't ...
Remove a 'compute' from the bundle :parameter str compute: name of the compute options :parameter **kwargs: any other tags to do the filter (except twig or context) :raise NotImplementedError: because it isn't
Below is the the instruction that describes the task: ### Input: Remove a 'compute' from the bundle :parameter str compute: name of the compute options :parameter **kwargs: any other tags to do the filter (except twig or context) :raise NotImplementedError: because it isn't ### ...
def _filesec(self, files=None): """ Returns fileSec Element containing all files grouped by use. """ if files is None: files = self.all_files() filesec = etree.Element(utils.lxmlns("mets") + "fileSec") filegrps = {} for file_ in files: if ...
Returns fileSec Element containing all files grouped by use.
Below is the the instruction that describes the task: ### Input: Returns fileSec Element containing all files grouped by use. ### Response: def _filesec(self, files=None): """ Returns fileSec Element containing all files grouped by use. """ if files is None: files = self...
def subn_filter(s, find, replace, count=0): """A non-optimal implementation of a regex filter""" return re.gsub(find, replace, count, s)
A non-optimal implementation of a regex filter
Below is the the instruction that describes the task: ### Input: A non-optimal implementation of a regex filter ### Response: def subn_filter(s, find, replace, count=0): """A non-optimal implementation of a regex filter""" return re.gsub(find, replace, count, s)
def get_seebeck(self, output='eigs', doping_levels=True): """ Gives the seebeck coefficient (microV/K) in either a full 3x3 tensor form, as 3 eigenvalues, or as the average value (trace/3.0) If doping_levels=True, the results are given at different p and n doping ...
Gives the seebeck coefficient (microV/K) in either a full 3x3 tensor form, as 3 eigenvalues, or as the average value (trace/3.0) If doping_levels=True, the results are given at different p and n doping levels (given by self.doping), otherwise it is given as a series ...
Below is the the instruction that describes the task: ### Input: Gives the seebeck coefficient (microV/K) in either a full 3x3 tensor form, as 3 eigenvalues, or as the average value (trace/3.0) If doping_levels=True, the results are given at different p and n doping l...
def _slugify(text, delim=u'-'): """Generates an ASCII-only slug.""" result = [] for word in _punct_re.split(text.lower()): word = word.encode('utf-8') if word: result.append(word) slugified = delim.join([i.decode('utf-8') for i in result]) return re.sub('[^a-zA-Z0-9\\s\\-...
Generates an ASCII-only slug.
Below is the the instruction that describes the task: ### Input: Generates an ASCII-only slug. ### Response: def _slugify(text, delim=u'-'): """Generates an ASCII-only slug.""" result = [] for word in _punct_re.split(text.lower()): word = word.encode('utf-8') if word: result...
def int_gps_time_to_str(t): """Takes an integer GPS time, either given as int or lal.LIGOTimeGPS, and converts it to a string. If a LIGOTimeGPS with nonzero decimal part is given, raises a ValueError.""" if isinstance(t, int): return str(t) elif isinstance(t, float): # Wouldn't this...
Takes an integer GPS time, either given as int or lal.LIGOTimeGPS, and converts it to a string. If a LIGOTimeGPS with nonzero decimal part is given, raises a ValueError.
Below is the the instruction that describes the task: ### Input: Takes an integer GPS time, either given as int or lal.LIGOTimeGPS, and converts it to a string. If a LIGOTimeGPS with nonzero decimal part is given, raises a ValueError. ### Response: def int_gps_time_to_str(t): """Takes an integer GPS ti...
def instantiate_client(self, config): """ :param config: The config object. :type config: dict :return: The instantiated class. :rtype: :class:`revision.client.Client` """ modules = config.module.split('.') class_name = modules.pop() module_path = ...
:param config: The config object. :type config: dict :return: The instantiated class. :rtype: :class:`revision.client.Client`
Below is the the instruction that describes the task: ### Input: :param config: The config object. :type config: dict :return: The instantiated class. :rtype: :class:`revision.client.Client` ### Response: def instantiate_client(self, config): """ :param config: The config ob...
def _parse_input(incoming): """Performs the actual conversion of tags to ANSI escaped codes. Provides a version of the input without any colors for len() and other methods. Positional arguments: incoming -- the input unicode value. Returns: 2-item tuple. First item is the parsed output. Secon...
Performs the actual conversion of tags to ANSI escaped codes. Provides a version of the input without any colors for len() and other methods. Positional arguments: incoming -- the input unicode value. Returns: 2-item tuple. First item is the parsed output. Second item is a version of the input wi...
Below is the the instruction that describes the task: ### Input: Performs the actual conversion of tags to ANSI escaped codes. Provides a version of the input without any colors for len() and other methods. Positional arguments: incoming -- the input unicode value. Returns: 2-item tuple. Firs...
async def set_avatar(self, url: str): """ Set the avatar of the user. See also: `API reference`_ Args: url: The new avatar URL for the user. Must be a MXC URI. .. _API reference: https://matrix.org/docs/spec/client_server/r0.3.0.html#put-matrix-client-r0-profile-...
Set the avatar of the user. See also: `API reference`_ Args: url: The new avatar URL for the user. Must be a MXC URI. .. _API reference: https://matrix.org/docs/spec/client_server/r0.3.0.html#put-matrix-client-r0-profile-userid-avatar-url
Below is the the instruction that describes the task: ### Input: Set the avatar of the user. See also: `API reference`_ Args: url: The new avatar URL for the user. Must be a MXC URI. .. _API reference: https://matrix.org/docs/spec/client_server/r0.3.0.html#put-matrix-client-...
def get_rendered_fields(self, ctx=None): ''' :param ctx: rendering context in which the method was called :return: ordered list of the fields that will be rendered ''' if ctx is None: ctx = RenderContext() ctx.push(self) current = self._fields[self._fi...
:param ctx: rendering context in which the method was called :return: ordered list of the fields that will be rendered
Below is the the instruction that describes the task: ### Input: :param ctx: rendering context in which the method was called :return: ordered list of the fields that will be rendered ### Response: def get_rendered_fields(self, ctx=None): ''' :param ctx: rendering context in which the metho...
def get_dynamical_matrix_at_q(self, q): """Calculate dynamical matrix at a given q-point Parameters ---------- q: array_like A q-vector. shape=(3,), dtype='double' Returns ------- dynamical_matrix: ndarray Dynamical matrix. ...
Calculate dynamical matrix at a given q-point Parameters ---------- q: array_like A q-vector. shape=(3,), dtype='double' Returns ------- dynamical_matrix: ndarray Dynamical matrix. shape=(bands, bands), dtype='complex'
Below is the the instruction that describes the task: ### Input: Calculate dynamical matrix at a given q-point Parameters ---------- q: array_like A q-vector. shape=(3,), dtype='double' Returns ------- dynamical_matrix: ndarray Dy...
def _parse_date(date): """Parse from the user input `date`. e.g. current year 2016: input 6-26, 626, ... return 2016626 input 2016-6-26, 2016/6/26, ... retrun 2016626 This fn wouldn't check the date, it only gather the number as a string. """ result = ''.j...
Parse from the user input `date`. e.g. current year 2016: input 6-26, 626, ... return 2016626 input 2016-6-26, 2016/6/26, ... retrun 2016626 This fn wouldn't check the date, it only gather the number as a string.
Below is the the instruction that describes the task: ### Input: Parse from the user input `date`. e.g. current year 2016: input 6-26, 626, ... return 2016626 input 2016-6-26, 2016/6/26, ... retrun 2016626 This fn wouldn't check the date, it only gather the number as a string...
def get_secret(secret_name, default=None): """ Gets contents of secret file :param secret_name: The name of the secret present in BANANAS_SECRETS_DIR :param default: Default value to return if no secret was found :return: The secret or default if not found """ secrets_dir = get_secrets_dir(...
Gets contents of secret file :param secret_name: The name of the secret present in BANANAS_SECRETS_DIR :param default: Default value to return if no secret was found :return: The secret or default if not found
Below is the the instruction that describes the task: ### Input: Gets contents of secret file :param secret_name: The name of the secret present in BANANAS_SECRETS_DIR :param default: Default value to return if no secret was found :return: The secret or default if not found ### Response: def get_secre...
def terminate_all(self): """Terminate all worker processes.""" for worker in self._workers: worker.terminate() # for thread in self._threads: # try: # thread.terminate() # thread.wait() # except Exception: # pas...
Terminate all worker processes.
Below is the the instruction that describes the task: ### Input: Terminate all worker processes. ### Response: def terminate_all(self): """Terminate all worker processes.""" for worker in self._workers: worker.terminate() # for thread in self._threads: # try: ...
def plot_coordinates(network, pores=None, fig=None, **kwargs): r""" Produces a 3D plot showing specified pore coordinates as markers Parameters ---------- network : OpenPNM Network Object The network whose topological connections to plot pores : array_like (optional) The list o...
r""" Produces a 3D plot showing specified pore coordinates as markers Parameters ---------- network : OpenPNM Network Object The network whose topological connections to plot pores : array_like (optional) The list of pores to plot if only a sub-sample is desired. This is u...
Below is the the instruction that describes the task: ### Input: r""" Produces a 3D plot showing specified pore coordinates as markers Parameters ---------- network : OpenPNM Network Object The network whose topological connections to plot pores : array_like (optional) The list...
def corrections(self, word, prefix=1, distance=2): """Get corrections for word, if word is an invalid word. :prefix: is the number of characters the prefix of the word must have in common with the suggested corrections. :distance: is the character distance the corrections may have betw...
Get corrections for word, if word is an invalid word. :prefix: is the number of characters the prefix of the word must have in common with the suggested corrections. :distance: is the character distance the corrections may have between the input word. This limits the number of availabl...
Below is the the instruction that describes the task: ### Input: Get corrections for word, if word is an invalid word. :prefix: is the number of characters the prefix of the word must have in common with the suggested corrections. :distance: is the character distance the corrections may ha...
def mgd(self, mgdid=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): """Method to query :class:`.models.MGD` objects in database :param mgdid: Mouse genome informatics database ID(s) :type mgdid: str or tuple(str) or None :param hgnc_symbol: HGNC symbol(s) ...
Method to query :class:`.models.MGD` objects in database :param mgdid: Mouse genome informatics database ID(s) :type mgdid: str or tuple(str) or None :param hgnc_symbol: HGNC symbol(s) :type hgnc_symbol: str or tuple(str) or None :param hgnc_identifier: identifiers(s) in :clas...
Below is the the instruction that describes the task: ### Input: Method to query :class:`.models.MGD` objects in database :param mgdid: Mouse genome informatics database ID(s) :type mgdid: str or tuple(str) or None :param hgnc_symbol: HGNC symbol(s) :type hgnc_symbol: str or tuple(...
def GetPatternAs(self, patternId: int, riid): """ Call IUIAutomationElement::GetCurrentPatternAs. Get a new pattern by pattern id if it supports the pattern, todo. patternId: int, a value in class `PatternId`. riid: GUID. Refer https://docs.microsoft.com/en-us/windows/des...
Call IUIAutomationElement::GetCurrentPatternAs. Get a new pattern by pattern id if it supports the pattern, todo. patternId: int, a value in class `PatternId`. riid: GUID. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationele...
Below is the the instruction that describes the task: ### Input: Call IUIAutomationElement::GetCurrentPatternAs. Get a new pattern by pattern id if it supports the pattern, todo. patternId: int, a value in class `PatternId`. riid: GUID. Refer https://docs.microsoft.com/en-us/windows/...
def pmap(f, iterable, n=None, dummy=False, p=None): """ parallel map of a function to an iterable if each item in iterable is itself an iterable, then automatically call f(*item) instead of f(item) Arguments: f: function iterable: any iterable where each item is sent to f n: numbe...
parallel map of a function to an iterable if each item in iterable is itself an iterable, then automatically call f(*item) instead of f(item) Arguments: f: function iterable: any iterable where each item is sent to f n: number of cpus (default is number on machine) dummy: use dummy ...
Below is the the instruction that describes the task: ### Input: parallel map of a function to an iterable if each item in iterable is itself an iterable, then automatically call f(*item) instead of f(item) Arguments: f: function iterable: any iterable where each item is sent to f n: ...
def write_graph(self, filename): """ Write raw graph data which can be post-processed using graphviz. """ f = open(filename, 'w') f.write(self._get_graphviz_data()) f.close()
Write raw graph data which can be post-processed using graphviz.
Below is the the instruction that describes the task: ### Input: Write raw graph data which can be post-processed using graphviz. ### Response: def write_graph(self, filename): """ Write raw graph data which can be post-processed using graphviz. """ f = open(filename, 'w') f...
def call_service(self, service_id, action): """Call a Vera service. This will call the Vera api to change device state. """ result = self.vera_request(id='action', serviceId=service_id, action=action) logger.debug("call_service: " ...
Call a Vera service. This will call the Vera api to change device state.
Below is the the instruction that describes the task: ### Input: Call a Vera service. This will call the Vera api to change device state. ### Response: def call_service(self, service_id, action): """Call a Vera service. This will call the Vera api to change device state. """ ...
def textContent(self, text: str) -> None: # type: ignore """Set text content to inner node.""" if self._inner_element: self._inner_element.textContent = text else: # Need a trick to call property of super-class super().textContent = text
Set text content to inner node.
Below is the the instruction that describes the task: ### Input: Set text content to inner node. ### Response: def textContent(self, text: str) -> None: # type: ignore """Set text content to inner node.""" if self._inner_element: self._inner_element.textContent = text else: ...
def get_cache_key(page, language): """ Create the cache key for the current page and language """ from cms.cache import _get_cache_key try: site_id = page.node.site_id except AttributeError: # CMS_3_4 site_id = page.site_id return _get_cache_key('page_meta', page, language, ...
Create the cache key for the current page and language
Below is the the instruction that describes the task: ### Input: Create the cache key for the current page and language ### Response: def get_cache_key(page, language): """ Create the cache key for the current page and language """ from cms.cache import _get_cache_key try: site_id = pag...
def geno(self, y, from_bounds=None, copy_if_changed=True, copy_always=False, repair=None, archive=None): """maps the phenotypic input argument into the genotypic space, that is, computes essentially the inverse of ``pheno``. By default a copy is made only to prevent to...
maps the phenotypic input argument into the genotypic space, that is, computes essentially the inverse of ``pheno``. By default a copy is made only to prevent to modify ``y``. The inverse of the user-defined transformation (if any) is only needed if external solutions are injected, it ...
Below is the the instruction that describes the task: ### Input: maps the phenotypic input argument into the genotypic space, that is, computes essentially the inverse of ``pheno``. By default a copy is made only to prevent to modify ``y``. The inverse of the user-defined transformation (i...
def kernelparams(): ''' Return the kernel boot parameters ''' if salt.utils.platform.is_windows(): # TODO: add grains using `bcdedit /enum {current}` return {} else: try: with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr: cmdline = fhr.read(...
Return the kernel boot parameters
Below is the the instruction that describes the task: ### Input: Return the kernel boot parameters ### Response: def kernelparams(): ''' Return the kernel boot parameters ''' if salt.utils.platform.is_windows(): # TODO: add grains using `bcdedit /enum {current}` return {} else: ...
def setup_menu(self): """Setup context menu""" self.copy_action = create_action(self, _('Copy'), shortcut=keybinding('Copy'), icon=ima.icon('editcopy'), triggered=self.copy, ...
Setup context menu
Below is the the instruction that describes the task: ### Input: Setup context menu ### Response: def setup_menu(self): """Setup context menu""" self.copy_action = create_action(self, _('Copy'), shortcut=keybinding('Copy'), ...
def get_video_transcript_url(video_id, language_code): """ Returns course video transcript url or None if no transcript Arguments: video_id: it can be an edx_video_id or an external_id extracted from external sources in a video component. language_code: language code of a video transcript ...
Returns course video transcript url or None if no transcript Arguments: video_id: it can be an edx_video_id or an external_id extracted from external sources in a video component. language_code: language code of a video transcript
Below is the the instruction that describes the task: ### Input: Returns course video transcript url or None if no transcript Arguments: video_id: it can be an edx_video_id or an external_id extracted from external sources in a video component. language_code: language code of a video transcript...
def _find(self, url): """Return properties document for path.""" # Query the permanent view to find a url vr = self.db.view("properties/by_url", key=url, include_docs=True) _logger.debug("find(%r) returned %s" % (url, len(vr))) assert len(vr) <= 1, "Found multiple matches for %r"...
Return properties document for path.
Below is the the instruction that describes the task: ### Input: Return properties document for path. ### Response: def _find(self, url): """Return properties document for path.""" # Query the permanent view to find a url vr = self.db.view("properties/by_url", key=url, include_docs=True) ...
def init(access_token, environment='production', scrub_fields=None, url_fields=None, **kw): """ Saves configuration variables in this module's SETTINGS. access_token: project access token. Get this from the Rollbar UI: - click "Settings" in the top nav - click "Projects"...
Saves configuration variables in this module's SETTINGS. access_token: project access token. Get this from the Rollbar UI: - click "Settings" in the top nav - click "Projects" in the left nav - copy-paste the appropriate token. environment: environment name...
Below is the the instruction that describes the task: ### Input: Saves configuration variables in this module's SETTINGS. access_token: project access token. Get this from the Rollbar UI: - click "Settings" in the top nav - click "Projects" in the left nav ...
def set_wd_mult(self, args_wd_mult): """Sets an individual weight decay multiplier for each parameter. By default, if `param_idx2name` was provided in the constructor, the weight decay multipler is set as 0 for all parameters whose name don't end with ``_weight`` or ``_gamma``. ...
Sets an individual weight decay multiplier for each parameter. By default, if `param_idx2name` was provided in the constructor, the weight decay multipler is set as 0 for all parameters whose name don't end with ``_weight`` or ``_gamma``. .. note:: The default weight decay mult...
Below is the the instruction that describes the task: ### Input: Sets an individual weight decay multiplier for each parameter. By default, if `param_idx2name` was provided in the constructor, the weight decay multipler is set as 0 for all parameters whose name don't end with ``_weight`` or...
def _init_metadata(self): """stub""" super(CalculationInteractionQuestionFormRecord, self)._init_metadata() QuestionTextFormRecord._init_metadata(self) QuestionFilesFormRecord._init_metadata(self) self._variables_metadata = { 'element_id': Id(self.my_osid_object_form....
stub
Below is the the instruction that describes the task: ### Input: stub ### Response: def _init_metadata(self): """stub""" super(CalculationInteractionQuestionFormRecord, self)._init_metadata() QuestionTextFormRecord._init_metadata(self) QuestionFilesFormRecord._init_metadata(self) ...
def list_lbaas_loadbalancers(self, retrieve_all=True, **_params): """Fetches a list of all lbaas_loadbalancers for a project.""" return self.list('loadbalancers', self.lbaas_loadbalancers_path, retrieve_all, **_params)
Fetches a list of all lbaas_loadbalancers for a project.
Below is the the instruction that describes the task: ### Input: Fetches a list of all lbaas_loadbalancers for a project. ### Response: def list_lbaas_loadbalancers(self, retrieve_all=True, **_params): """Fetches a list of all lbaas_loadbalancers for a project.""" return self.list('loadbalancers', ...
def addonModules(cls, recurse=True): """ Returns all the modules that this addon class uses to load plugins from. :param recurse | <bool> :return [<str> || <module>, ..] """ prop = '_{0}__addon_modules'.format(cls.__name__) out =...
Returns all the modules that this addon class uses to load plugins from. :param recurse | <bool> :return [<str> || <module>, ..]
Below is the the instruction that describes the task: ### Input: Returns all the modules that this addon class uses to load plugins from. :param recurse | <bool> :return [<str> || <module>, ..] ### Response: def addonModules(cls, recurse=True): """ ...
def annual_heating_design_day_996(self): """A design day object representing the annual 99.6% heating design day.""" self._load_header_check() if bool(self._heating_dict) is True: avg_press = self.atmospheric_station_pressure.average avg_press = None if avg_press == 99999...
A design day object representing the annual 99.6% heating design day.
Below is the the instruction that describes the task: ### Input: A design day object representing the annual 99.6% heating design day. ### Response: def annual_heating_design_day_996(self): """A design day object representing the annual 99.6% heating design day.""" self._load_header_check() ...
def include_sqlalchemy_models(nc, Base): """Include all SQLAlchemy models in the script context. :param nc: notebook_context dictionary :param Base: SQLAlchemy model Base class from where the all models inherit. """ from sqlalchemy.ext.declarative.clsregistry import _ModuleMarker # Include al...
Include all SQLAlchemy models in the script context. :param nc: notebook_context dictionary :param Base: SQLAlchemy model Base class from where the all models inherit.
Below is the the instruction that describes the task: ### Input: Include all SQLAlchemy models in the script context. :param nc: notebook_context dictionary :param Base: SQLAlchemy model Base class from where the all models inherit. ### Response: def include_sqlalchemy_models(nc, Base): """Include all...
def apply_transformation(self, structure, return_ranked_list=False): """ Apply the transformation. Args: structure: input structure return_ranked_list (bool): Whether or not multiple structures are returned. If return_ranked_list is a number, that number ...
Apply the transformation. Args: structure: input structure return_ranked_list (bool): Whether or not multiple structures are returned. If return_ranked_list is a number, that number of structures is returned. Returns: Depending on ret...
Below is the the instruction that describes the task: ### Input: Apply the transformation. Args: structure: input structure return_ranked_list (bool): Whether or not multiple structures are returned. If return_ranked_list is a number, that number of s...
def get_config_input_source_config_source_running_running(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_config = ET.Element("get_config") config = get_config input = ET.SubElement(get_config, "input") source = ET.SubElement(input, "...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def get_config_input_source_config_source_running_running(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_config = ET.Element("get_config") config...
def _checksum(self): """Performs the checksum for the current TLE.""" for line in [self._line1, self._line2]: check = 0 for char in line[:-1]: if char.isdigit(): check += int(char) if char == "-": check += 1 ...
Performs the checksum for the current TLE.
Below is the the instruction that describes the task: ### Input: Performs the checksum for the current TLE. ### Response: def _checksum(self): """Performs the checksum for the current TLE.""" for line in [self._line1, self._line2]: check = 0 for char in line[:-1]: ...
def publish(cls, message, client_filter=None): """Publish messages to subscribers. Args: message: The message to publish. client_filter: A filter function to call passing in each client. Only clients for whom the function returns True will have the message ...
Publish messages to subscribers. Args: message: The message to publish. client_filter: A filter function to call passing in each client. Only clients for whom the function returns True will have the message sent to them.
Below is the the instruction that describes the task: ### Input: Publish messages to subscribers. Args: message: The message to publish. client_filter: A filter function to call passing in each client. Only clients for whom the function returns True will have the ...
def make_stream( name, # type: Text bin_file, # type: RawIOBase mode="r", # type: Text buffering=-1, # type: int encoding=None, # type: Optional[Text] errors=None, # type: Optional[Text] newline="", # type: Optional[Text] line_buffering=False, # type: bool **kwargs # type: A...
Take a Python 2.x binary file and return an IO Stream.
Below is the the instruction that describes the task: ### Input: Take a Python 2.x binary file and return an IO Stream. ### Response: def make_stream( name, # type: Text bin_file, # type: RawIOBase mode="r", # type: Text buffering=-1, # type: int encoding=None, # type: Optional[Text] e...
def update_reminder_item(self, reminder_item_id, reminder_item_dict): """ Updates a reminder item :param reminder_item_id: the reminder item id :param reminder_item_dict: dict :return: dict """ return self._create_put_request( resource=REMINDER_ITEMS,...
Updates a reminder item :param reminder_item_id: the reminder item id :param reminder_item_dict: dict :return: dict
Below is the the instruction that describes the task: ### Input: Updates a reminder item :param reminder_item_id: the reminder item id :param reminder_item_dict: dict :return: dict ### Response: def update_reminder_item(self, reminder_item_id, reminder_item_dict): """ Updat...
def create_flavor(self, nova, name, ram, vcpus, disk, flavorid="auto", ephemeral=0, swap=0, rxtx_factor=1.0, is_public=True): """Create the specified flavor.""" try: nova.flavors.find(name=name) except (exceptions.NotFound, exceptions.NoUniqueMatch): ...
Create the specified flavor.
Below is the the instruction that describes the task: ### Input: Create the specified flavor. ### Response: def create_flavor(self, nova, name, ram, vcpus, disk, flavorid="auto", ephemeral=0, swap=0, rxtx_factor=1.0, is_public=True): """Create the specified flavor.""" try: ...
def list_bundled_profiles(): """list profiles that are bundled with IPython.""" path = os.path.join(get_ipython_package_dir(), u'config', u'profile') files = os.listdir(path) profiles = [] for profile in files: full_path = os.path.join(path, profile) if os.path.isdir(full_path) and p...
list profiles that are bundled with IPython.
Below is the the instruction that describes the task: ### Input: list profiles that are bundled with IPython. ### Response: def list_bundled_profiles(): """list profiles that are bundled with IPython.""" path = os.path.join(get_ipython_package_dir(), u'config', u'profile') files = os.listdir(path) ...
def get_normed_points(point_array, norm): # good to go """ input: point_array, norm output: normed array """ norm = float(norm) #floated_array = [] #for p in point_array: # need to make sure each point is a float #floated_array.append(float(p)) points = old_div(numpy.array(point_...
input: point_array, norm output: normed array
Below is the the instruction that describes the task: ### Input: input: point_array, norm output: normed array ### Response: def get_normed_points(point_array, norm): # good to go """ input: point_array, norm output: normed array """ norm = float(norm) #floated_array = [] #for p in ...
def get_single_color_func(color): """Create a color function which returns a single hue and saturation with. different values (HSV). Accepted values are color strings as usable by PIL/Pillow. >>> color_func1 = get_single_color_func('deepskyblue') >>> color_func2 = get_single_color_func('#00b4d2') ...
Create a color function which returns a single hue and saturation with. different values (HSV). Accepted values are color strings as usable by PIL/Pillow. >>> color_func1 = get_single_color_func('deepskyblue') >>> color_func2 = get_single_color_func('#00b4d2')
Below is the the instruction that describes the task: ### Input: Create a color function which returns a single hue and saturation with. different values (HSV). Accepted values are color strings as usable by PIL/Pillow. >>> color_func1 = get_single_color_func('deepskyblue') >>> color_func2 = get_si...
def plot_graph(G, bbox=None, fig_height=6, fig_width=None, margin=0.02, axis_off=True, equal_aspect=False, bgcolor='w', show=True, save=False, close=True, file_format='png', filename='temp', dpi=300, annotate=False, node_color='#66ccff', node_size=15, node_alp...
Plot a networkx spatial graph. Parameters ---------- G : networkx multidigraph bbox : tuple bounding box as north,south,east,west - if None will calculate from spatial extents of data. if passing a bbox, you probably also want to pass margin=0 to constrain it. fig_height : i...
Below is the the instruction that describes the task: ### Input: Plot a networkx spatial graph. Parameters ---------- G : networkx multidigraph bbox : tuple bounding box as north,south,east,west - if None will calculate from spatial extents of data. if passing a bbox, you probably a...
def participating_ec_states(self): '''The state of each execution context this component is participating in. ''' with self._mutex: if not self._participating_ec_states: if self.participating_ecs: states = [] for ec in ...
The state of each execution context this component is participating in.
Below is the the instruction that describes the task: ### Input: The state of each execution context this component is participating in. ### Response: def participating_ec_states(self): '''The state of each execution context this component is participating in. ''' with self...
def delete(self, ids): """ Method to delete vrf's by their id's :param ids: Identifiers of vrf's :return: None """ url = build_uri_with_ids('api/v3/vrf/%s/', ids) return super(ApiVrf, self).delete(url)
Method to delete vrf's by their id's :param ids: Identifiers of vrf's :return: None
Below is the the instruction that describes the task: ### Input: Method to delete vrf's by their id's :param ids: Identifiers of vrf's :return: None ### Response: def delete(self, ids): """ Method to delete vrf's by their id's :param ids: Identifiers of vrf's :retu...
def add_ssh_key(self, name, ssh_pub_key): """ This method allows you to add a new public SSH key to your account. Required parameters name: String, the name you want to give this SSH key. ssh_pub_key: String, the actual public SSH key. ...
This method allows you to add a new public SSH key to your account. Required parameters name: String, the name you want to give this SSH key. ssh_pub_key: String, the actual public SSH key.
Below is the the instruction that describes the task: ### Input: This method allows you to add a new public SSH key to your account. Required parameters name: String, the name you want to give this SSH key. ssh_pub_key: String, the actual public SSH...
def _extract_error(self, resp): """ Extract the actual error message from a solr response. """ reason = resp.headers.get('reason', None) full_response = None if reason is None: try: # if response is in json format reason = resp...
Extract the actual error message from a solr response.
Below is the the instruction that describes the task: ### Input: Extract the actual error message from a solr response. ### Response: def _extract_error(self, resp): """ Extract the actual error message from a solr response. """ reason = resp.headers.get('reason', None) full...
def __CombineGlobalParams(self, global_params, default_params): """Combine the given params with the defaults.""" util.Typecheck(global_params, (type(None), self.__client.params_type)) result = self.__client.params_type() global_params = global_params or self.__client.params_type() ...
Combine the given params with the defaults.
Below is the the instruction that describes the task: ### Input: Combine the given params with the defaults. ### Response: def __CombineGlobalParams(self, global_params, default_params): """Combine the given params with the defaults.""" util.Typecheck(global_params, (type(None), self.__client.param...
def narrow(self): """Decrease the interval size.""" t, h = self.time, self.half_duration h /= self.scaling_coeff_x self.set_interval((t - h, t + h))
Decrease the interval size.
Below is the the instruction that describes the task: ### Input: Decrease the interval size. ### Response: def narrow(self): """Decrease the interval size.""" t, h = self.time, self.half_duration h /= self.scaling_coeff_x self.set_interval((t - h, t + h))
def get_instance(self, payload): """ Build an instance of MessageInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.message.MessageInstance :rtype: twilio.rest.api.v2010.account.message.MessageInstance """ return ...
Build an instance of MessageInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.message.MessageInstance :rtype: twilio.rest.api.v2010.account.message.MessageInstance
Below is the the instruction that describes the task: ### Input: Build an instance of MessageInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.message.MessageInstance :rtype: twilio.rest.api.v2010.account.message.MessageInstance ### Respons...
def read_chip_sn(self): '''Reading Chip S/N Note ---- Bits [MSB-LSB] | [15] | [14-6] | [5-0] Content | reserved | wafer number | chip number ''' commands = [] commands.extend(self.register.get_commands("ConfMode")) self.register_utils.send_commands(com...
Reading Chip S/N Note ---- Bits [MSB-LSB] | [15] | [14-6] | [5-0] Content | reserved | wafer number | chip number
Below is the the instruction that describes the task: ### Input: Reading Chip S/N Note ---- Bits [MSB-LSB] | [15] | [14-6] | [5-0] Content | reserved | wafer number | chip number ### Response: def read_chip_sn(self): '''Reading Chip S/N Note ---- Bit...
def classifier(self): """ Returns classifier from classifier.pkl """ clf = pickle.load(open(os.path.join(self.repopath, 'classifier.pkl'))) return clf
Returns classifier from classifier.pkl
Below is the the instruction that describes the task: ### Input: Returns classifier from classifier.pkl ### Response: def classifier(self): """ Returns classifier from classifier.pkl """ clf = pickle.load(open(os.path.join(self.repopath, 'classifier.pkl'))) return clf
def listen_loop(self): """Starts the listen loop and executes the receieve_datagram method whenever a packet is receieved. Args: None Returns: None """ while self.listening: try: data, address = self.sock.recvfrom(self.b...
Starts the listen loop and executes the receieve_datagram method whenever a packet is receieved. Args: None Returns: None
Below is the the instruction that describes the task: ### Input: Starts the listen loop and executes the receieve_datagram method whenever a packet is receieved. Args: None Returns: None ### Response: def listen_loop(self): """Starts the listen loop and execute...