code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def has_property(elem_to_parse, xpath): """ Parse xpath for any attribute reference "path/@attr" and check for root and presence of attribute. :return: True if xpath is present in the element along with any attribute referenced, otherwise False """ xroot, attr = get_xpath_tuple(xpath) if not x...
Parse xpath for any attribute reference "path/@attr" and check for root and presence of attribute. :return: True if xpath is present in the element along with any attribute referenced, otherwise False
Below is the the instruction that describes the task: ### Input: Parse xpath for any attribute reference "path/@attr" and check for root and presence of attribute. :return: True if xpath is present in the element along with any attribute referenced, otherwise False ### Response: def has_property(elem_to_parse,...
def sci(x, digs): """Format x as [-]d.dddE[+-]ddd with 'digs' digits after the point and exactly one digit before. If digs is <= 0, one digit is kept and the point is suppressed.""" if type(x) != type(''): x = repr(x) sign, intpart, fraction, expo = extract(x) if not intpart: while fract...
Format x as [-]d.dddE[+-]ddd with 'digs' digits after the point and exactly one digit before. If digs is <= 0, one digit is kept and the point is suppressed.
Below is the the instruction that describes the task: ### Input: Format x as [-]d.dddE[+-]ddd with 'digs' digits after the point and exactly one digit before. If digs is <= 0, one digit is kept and the point is suppressed. ### Response: def sci(x, digs): """Format x as [-]d.dddE[+-]ddd with 'digs' digi...
def set_iter_mesh(self, mesh, shift=None, is_time_reversal=True, is_mesh_symmetry=True, is_eigenvectors=False, is_gamma_center=False): """Create an IterMesh instancer Attr...
Create an IterMesh instancer Attributes ---------- See set_mesh method.
Below is the the instruction that describes the task: ### Input: Create an IterMesh instancer Attributes ---------- See set_mesh method. ### Response: def set_iter_mesh(self, mesh, shift=None, is_time_reversal=True, ...
def find_rt_jar(javahome=None): """Find the path to the Java standard library jar. The jar is expected to exist at the path 'jre/lib/rt.jar' inside a standard Java installation directory. The directory is found using the following procedure: 1. If the javehome argument is provided, use the value a...
Find the path to the Java standard library jar. The jar is expected to exist at the path 'jre/lib/rt.jar' inside a standard Java installation directory. The directory is found using the following procedure: 1. If the javehome argument is provided, use the value as the directory. 2. If the J...
Below is the the instruction that describes the task: ### Input: Find the path to the Java standard library jar. The jar is expected to exist at the path 'jre/lib/rt.jar' inside a standard Java installation directory. The directory is found using the following procedure: 1. If the javehome argumen...
def show_raslog_output_show_all_raslog_raslog_entries_log_type(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_raslog = ET.Element("show_raslog") config = show_raslog output = ET.SubElement(show_raslog, "output") show_all_raslog = ET...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def show_raslog_output_show_all_raslog_raslog_entries_log_type(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_raslog = ET.Element("show_raslog") ...
def deep_align(objects, join='inner', copy=True, indexes=None, exclude=frozenset(), raise_on_invalid=True): """Align objects for merging, recursing into dictionary values. This function is not public API. """ from .dataarray import DataArray from .dataset import Dataset if index...
Align objects for merging, recursing into dictionary values. This function is not public API.
Below is the the instruction that describes the task: ### Input: Align objects for merging, recursing into dictionary values. This function is not public API. ### Response: def deep_align(objects, join='inner', copy=True, indexes=None, exclude=frozenset(), raise_on_invalid=True): """Align o...
def _apply_user_port_channel_config(self, nexus_host, vpc_nbr): """Adds STP and no lacp suspend config to port channel. """ cli_cmds = self._get_user_port_channel_config(nexus_host, vpc_nbr) if cli_cmds: self._send_cli_conf_string(nexus_host, cli_cmds) else: vpc_...
Adds STP and no lacp suspend config to port channel.
Below is the the instruction that describes the task: ### Input: Adds STP and no lacp suspend config to port channel. ### Response: def _apply_user_port_channel_config(self, nexus_host, vpc_nbr): """Adds STP and no lacp suspend config to port channel. """ cli_cmds = self._get_user_port_channel_con...
def ajModeles(self): """ Lecture des modèles, et enregistrement de leurs désinences """ sl = [] lines = [line for line in lignesFichier(self.path("modeles.la"))] max = len(lines) - 1 for i, l in enumerate(lines): if l.startswith('$'): varname, ...
Lecture des modèles, et enregistrement de leurs désinences
Below is the the instruction that describes the task: ### Input: Lecture des modèles, et enregistrement de leurs désinences ### Response: def ajModeles(self): """ Lecture des modèles, et enregistrement de leurs désinences """ sl = [] lines = [line for line in lignesFichier(self.path...
def from_header(self, binary): """Generate a SpanContext object using the trace context header. The value of enabled parsed from header is int. Need to convert to bool. :type binary: bytes :param binary: Trace context header which was extracted from the re...
Generate a SpanContext object using the trace context header. The value of enabled parsed from header is int. Need to convert to bool. :type binary: bytes :param binary: Trace context header which was extracted from the request headers. :rtype: :class:`~o...
Below is the the instruction that describes the task: ### Input: Generate a SpanContext object using the trace context header. The value of enabled parsed from header is int. Need to convert to bool. :type binary: bytes :param binary: Trace context header which was extracted from th...
def mk_class_name(*parts): """Create a valid class name from a list of strings.""" cap = lambda s: s and (s[0].capitalize() + s[1:]) return "".join(["".join([cap(i) for i in re.split("[\ \-\_\.]", str(p))]) for p in parts])
Create a valid class name from a list of strings.
Below is the the instruction that describes the task: ### Input: Create a valid class name from a list of strings. ### Response: def mk_class_name(*parts): """Create a valid class name from a list of strings.""" cap = lambda s: s and (s[0].capitalize() + s[1:]) return "".join(["".join([cap(i) ...
def send_command_return(self, obj, command, *arguments): """ Send command with single line output. :param obj: requested object. :param command: command to send. :param arguments: list of command arguments. :return: command output. """ return self._perform_comman...
Send command with single line output. :param obj: requested object. :param command: command to send. :param arguments: list of command arguments. :return: command output.
Below is the the instruction that describes the task: ### Input: Send command with single line output. :param obj: requested object. :param command: command to send. :param arguments: list of command arguments. :return: command output. ### Response: def send_command_return(self, ob...
def _get_clumpp_table(self, kpop, max_var_multiple, quiet): """ private function to clumpp results""" ## concat results for k=x reps, excluded = _concat_reps(self, kpop, max_var_multiple, quiet) if reps: ninds = reps[0].inds nreps = len(reps) else: ninds = nreps = 0 if n...
private function to clumpp results
Below is the the instruction that describes the task: ### Input: private function to clumpp results ### Response: def _get_clumpp_table(self, kpop, max_var_multiple, quiet): """ private function to clumpp results""" ## concat results for k=x reps, excluded = _concat_reps(self, kpop, max_var_multiple, ...
def to_element(self, include_namespaces=False): """Return an ElementTree Element representing this instance. Args: include_namespaces (bool, optional): If True, include xml namespace attributes on the root element Return: ~xml.etree.ElementTree.Element: ...
Return an ElementTree Element representing this instance. Args: include_namespaces (bool, optional): If True, include xml namespace attributes on the root element Return: ~xml.etree.ElementTree.Element: an Element.
Below is the the instruction that describes the task: ### Input: Return an ElementTree Element representing this instance. Args: include_namespaces (bool, optional): If True, include xml namespace attributes on the root element Return: ~xml.etree.ElementTree...
def log_variable_sizes(var_list=None, tag=None, verbose=False): """Log the sizes and shapes of variables, and the total size. Args: var_list: a list of variables; defaults to trainable_variables tag: a string; defaults to "Trainable Variables" verbose: bool, if True, log every weight; otherwise, log to...
Log the sizes and shapes of variables, and the total size. Args: var_list: a list of variables; defaults to trainable_variables tag: a string; defaults to "Trainable Variables" verbose: bool, if True, log every weight; otherwise, log total size only.
Below is the the instruction that describes the task: ### Input: Log the sizes and shapes of variables, and the total size. Args: var_list: a list of variables; defaults to trainable_variables tag: a string; defaults to "Trainable Variables" verbose: bool, if True, log every weight; otherwise, log to...
def logpdf_link(self, inv_link_f, y, Y_metadata=None): """ Log Likelihood Function given link(f) .. math:: \\ln p(y_{i}|\lambda(f_{i})) = \\ln \\Gamma\\left(\\frac{v+1}{2}\\right) - \\ln \\Gamma\\left(\\frac{v}{2}\\right) - \\ln \\sqrt{v \\pi\\sigma^{2}} - \\frac{v+1}{2}\\ln \\left(...
Log Likelihood Function given link(f) .. math:: \\ln p(y_{i}|\lambda(f_{i})) = \\ln \\Gamma\\left(\\frac{v+1}{2}\\right) - \\ln \\Gamma\\left(\\frac{v}{2}\\right) - \\ln \\sqrt{v \\pi\\sigma^{2}} - \\frac{v+1}{2}\\ln \\left(1 + \\frac{1}{v}\\left(\\frac{(y_{i} - \lambda(f_{i}))^{2}}{\\sigma^{2}}\\r...
Below is the the instruction that describes the task: ### Input: Log Likelihood Function given link(f) .. math:: \\ln p(y_{i}|\lambda(f_{i})) = \\ln \\Gamma\\left(\\frac{v+1}{2}\\right) - \\ln \\Gamma\\left(\\frac{v}{2}\\right) - \\ln \\sqrt{v \\pi\\sigma^{2}} - \\frac{v+1}{2}\\ln \\left(1 + \\...
def template_delete(call=None, kwargs=None): ''' Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the t...
Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The ID of the template to delete. Can be used instead of ``name``. ...
Below is the the instruction that describes the task: ### Input: Deletes the given template from OpenNebula. Either a name or a template_id must be supplied. .. versionadded:: 2016.3.0 name The name of the template to delete. Can be used instead of ``template_id``. template_id The...
def instance_attr_ancestors(self, name, context=None): """Iterate over the parents that define the given name as an attribute. :param name: The name to find definitions for. :type name: str :returns: The parents that define the given name as an instance attribute. :...
Iterate over the parents that define the given name as an attribute. :param name: The name to find definitions for. :type name: str :returns: The parents that define the given name as an instance attribute. :rtype: iterable(NodeNG)
Below is the the instruction that describes the task: ### Input: Iterate over the parents that define the given name as an attribute. :param name: The name to find definitions for. :type name: str :returns: The parents that define the given name as an instance attribute. ...
def OnUpdate(self, event): """Updates the toolbar states""" # Gray out undo and redo id not available undo_toolid = self.label2id["Undo"] redo_toolid = self.label2id["Redo"] self.EnableTool(undo_toolid, undo.stack().canundo()) self.EnableTool(redo_toolid, undo.stack()....
Updates the toolbar states
Below is the the instruction that describes the task: ### Input: Updates the toolbar states ### Response: def OnUpdate(self, event): """Updates the toolbar states""" # Gray out undo and redo id not available undo_toolid = self.label2id["Undo"] redo_toolid = self.label2id["Redo"] ...
def _item_to_document_ref(iterator, item): """Convert Document resource to document ref. Args: iterator (google.api_core.page_iterator.GRPCIterator): iterator response item (dict): document resource """ document_id = item.name.split(_helpers.DOCUMENT_PATH_DELIMITER)[-1] ...
Convert Document resource to document ref. Args: iterator (google.api_core.page_iterator.GRPCIterator): iterator response item (dict): document resource
Below is the the instruction that describes the task: ### Input: Convert Document resource to document ref. Args: iterator (google.api_core.page_iterator.GRPCIterator): iterator response item (dict): document resource ### Response: def _item_to_document_ref(iterator, item): """...
def deserialize_duration(attr): """Deserialize ISO-8601 formatted string into TimeDelta object. :param str attr: response string to be deserialized. :rtype: TimeDelta :raises: DeserializationError if string format invalid. """ if isinstance(attr, ET.Element): ...
Deserialize ISO-8601 formatted string into TimeDelta object. :param str attr: response string to be deserialized. :rtype: TimeDelta :raises: DeserializationError if string format invalid.
Below is the the instruction that describes the task: ### Input: Deserialize ISO-8601 formatted string into TimeDelta object. :param str attr: response string to be deserialized. :rtype: TimeDelta :raises: DeserializationError if string format invalid. ### Response: def deserialize_duratio...
def create_model_schema(target_model): """ This function creates a graphql schema that provides a single model """ from nautilus.database import db # create the schema instance schema = graphene.Schema(auto_camelcase=False) # grab the primary key from the model primary_key = target_model.prim...
This function creates a graphql schema that provides a single model
Below is the the instruction that describes the task: ### Input: This function creates a graphql schema that provides a single model ### Response: def create_model_schema(target_model): """ This function creates a graphql schema that provides a single model """ from nautilus.database import db # crea...
def is_valid_cidr(string_network): """ Very simple check of the cidr format in no_proxy variable. :rtype: bool """ if string_network.count('/') == 1: try: mask = int(string_network.split('/')[1]) except ValueError: return False if mask < 1 or mask > ...
Very simple check of the cidr format in no_proxy variable. :rtype: bool
Below is the the instruction that describes the task: ### Input: Very simple check of the cidr format in no_proxy variable. :rtype: bool ### Response: def is_valid_cidr(string_network): """ Very simple check of the cidr format in no_proxy variable. :rtype: bool """ if string_network.count...
def vlan_dot1q_tag_native(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") vlan = ET.SubElement(config, "vlan", xmlns="urn:brocade.com:mgmt:brocade-vlan") dot1q = ET.SubElement(vlan, "dot1q") tag = ET.SubElement(dot1q, "tag") native = ET.S...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def vlan_dot1q_tag_native(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") vlan = ET.SubElement(config, "vlan", xmlns="urn:brocade.com:mgmt:brocade-vlan") ...
def append(self, data_frame): """ Append another DataFrame to this DataFrame. If the new data_frame has columns that are not in the current DataFrame then new columns will be created. All of the indexes in the data_frame must be different from the current indexes or will raise an error. ...
Append another DataFrame to this DataFrame. If the new data_frame has columns that are not in the current DataFrame then new columns will be created. All of the indexes in the data_frame must be different from the current indexes or will raise an error. :param data_frame: DataFrame to append ...
Below is the the instruction that describes the task: ### Input: Append another DataFrame to this DataFrame. If the new data_frame has columns that are not in the current DataFrame then new columns will be created. All of the indexes in the data_frame must be different from the current indexes or wi...
def geoms(self, scale=None, bounds=None, as_element=True): """ Returns the geometries held by the Feature. Parameters ---------- scale: str Scale of the geometry to return expressed as string. Available scales depends on the Feature type. NaturalEa...
Returns the geometries held by the Feature. Parameters ---------- scale: str Scale of the geometry to return expressed as string. Available scales depends on the Feature type. NaturalEarthFeature: '10m', '50m', '110m' GSHHSFeature: ...
Below is the the instruction that describes the task: ### Input: Returns the geometries held by the Feature. Parameters ---------- scale: str Scale of the geometry to return expressed as string. Available scales depends on the Feature type. NaturalEarthFeature...
def setter(self, func): """Register a set function for the DynamicProperty This function must take two arguments, self and the new value. Input value to the function is validated with prop validation prior to execution. """ if not callable(func): raise TypeEr...
Register a set function for the DynamicProperty This function must take two arguments, self and the new value. Input value to the function is validated with prop validation prior to execution.
Below is the the instruction that describes the task: ### Input: Register a set function for the DynamicProperty This function must take two arguments, self and the new value. Input value to the function is validated with prop validation prior to execution. ### Response: def setter(self, f...
def send_cmd(cmd, args, ret): """Collect and send analytics for CLI command. Args: args (list): parsed args for the CLI command. ret (int): return value of the CLI command. """ from dvc.daemon import daemon if not Analytics._is_enabled(cmd): ...
Collect and send analytics for CLI command. Args: args (list): parsed args for the CLI command. ret (int): return value of the CLI command.
Below is the the instruction that describes the task: ### Input: Collect and send analytics for CLI command. Args: args (list): parsed args for the CLI command. ret (int): return value of the CLI command. ### Response: def send_cmd(cmd, args, ret): """Collect and send analy...
async def stop(self): """ Stops playback from lavalink. .. important:: This method will clear the queue. """ await self.node.stop(self.channel.guild.id) self.queue = [] self.current = None self.position = 0 self._paused = False
Stops playback from lavalink. .. important:: This method will clear the queue.
Below is the the instruction that describes the task: ### Input: Stops playback from lavalink. .. important:: This method will clear the queue. ### Response: async def stop(self): """ Stops playback from lavalink. .. important:: This method will clear the...
def zipWithUniqueId(self): """ Zips this RDD with generated unique Long ids. Items in the kth partition will get ids k, n+k, 2*n+k, ..., where n is the number of partitions. So there may exist gaps, but this method won't trigger a spark job, which is different from L{zip...
Zips this RDD with generated unique Long ids. Items in the kth partition will get ids k, n+k, 2*n+k, ..., where n is the number of partitions. So there may exist gaps, but this method won't trigger a spark job, which is different from L{zipWithIndex} >>> sc.parallelize(["a", "b...
Below is the the instruction that describes the task: ### Input: Zips this RDD with generated unique Long ids. Items in the kth partition will get ids k, n+k, 2*n+k, ..., where n is the number of partitions. So there may exist gaps, but this method won't trigger a spark job, which is differ...
def name_targets(func): """ Wrap a function such that returning ``'a', 'b', 'c', [1, 2, 3]`` transforms the value into ``dict(a=1, b=2, c=3)``. This is useful in the case where the last parameter is an SCons command. """ def wrap(*a, **kw): ret = func(*a, **kw) return dict(zip(r...
Wrap a function such that returning ``'a', 'b', 'c', [1, 2, 3]`` transforms the value into ``dict(a=1, b=2, c=3)``. This is useful in the case where the last parameter is an SCons command.
Below is the the instruction that describes the task: ### Input: Wrap a function such that returning ``'a', 'b', 'c', [1, 2, 3]`` transforms the value into ``dict(a=1, b=2, c=3)``. This is useful in the case where the last parameter is an SCons command. ### Response: def name_targets(func): """ Wr...
def bind(self, ticket, device_id, user_id): """ 绑定设备 详情请参考 https://iot.weixin.qq.com/wiki/new/index.html?page=3-4-7 :param ticket: 绑定操作合法性的凭证(由微信后台生成,第三方H5通过客户端jsapi获得) :param device_id: 设备id :param user_id: 用户对应的openid :return: 返回的 JSON 数据包 """ ...
绑定设备 详情请参考 https://iot.weixin.qq.com/wiki/new/index.html?page=3-4-7 :param ticket: 绑定操作合法性的凭证(由微信后台生成,第三方H5通过客户端jsapi获得) :param device_id: 设备id :param user_id: 用户对应的openid :return: 返回的 JSON 数据包
Below is the the instruction that describes the task: ### Input: 绑定设备 详情请参考 https://iot.weixin.qq.com/wiki/new/index.html?page=3-4-7 :param ticket: 绑定操作合法性的凭证(由微信后台生成,第三方H5通过客户端jsapi获得) :param device_id: 设备id :param user_id: 用户对应的openid :return: 返回的 JSON 数据包 ### Resp...
def _serialize_parameters(parameters): """Serialize some parameters to match python native types with formats specified in google api docs like: * True/False -> "true"/"false", * {"a": 1, "b":2} -> "a:1|b:2" :type parameters: dict oif query parameters """ for ke...
Serialize some parameters to match python native types with formats specified in google api docs like: * True/False -> "true"/"false", * {"a": 1, "b":2} -> "a:1|b:2" :type parameters: dict oif query parameters
Below is the the instruction that describes the task: ### Input: Serialize some parameters to match python native types with formats specified in google api docs like: * True/False -> "true"/"false", * {"a": 1, "b":2} -> "a:1|b:2" :type parameters: dict oif query parameters ### Resp...
def parse_play(boxscore_id, details, is_hm): """Parse play details from a play-by-play string describing a play. Assuming valid input, this function returns structured data in a dictionary describing the play. If the play detail string was invalid, this function returns None. :param boxscore_id: t...
Parse play details from a play-by-play string describing a play. Assuming valid input, this function returns structured data in a dictionary describing the play. If the play detail string was invalid, this function returns None. :param boxscore_id: the boxscore ID of the play :param details: detai...
Below is the the instruction that describes the task: ### Input: Parse play details from a play-by-play string describing a play. Assuming valid input, this function returns structured data in a dictionary describing the play. If the play detail string was invalid, this function returns None. :par...
def hiddenColumns( self ): """ Returns a list of the hidden columns for this tree. :return [<str>, ..] """ output = [] columns = self.columns() for c, column in enumerate(columns): if ( not self.isColumnHidden(c) ): ...
Returns a list of the hidden columns for this tree. :return [<str>, ..]
Below is the the instruction that describes the task: ### Input: Returns a list of the hidden columns for this tree. :return [<str>, ..] ### Response: def hiddenColumns( self ): """ Returns a list of the hidden columns for this tree. :return [<str>, ....
def hashed(field_name, percent, fields=None, count=0): """Provides a sampling strategy based on hashing and selecting a percentage of data. Args: field_name: the name of the field to hash. percent: the percentage of the resulting hashes to select. fields: an optional list of field names to re...
Provides a sampling strategy based on hashing and selecting a percentage of data. Args: field_name: the name of the field to hash. percent: the percentage of the resulting hashes to select. fields: an optional list of field names to retrieve. count: optional maximum count of rows to pick. ...
Below is the the instruction that describes the task: ### Input: Provides a sampling strategy based on hashing and selecting a percentage of data. Args: field_name: the name of the field to hash. percent: the percentage of the resulting hashes to select. fields: an optional list of field name...
def is_fw_complete(self): """This API returns the completion status of FW. This returns True if a FW is created with a active policy that has more than one rule associated with it and if a driver init is done successfully. """ LOG.info("In fw_complete needed %(fw_created...
This API returns the completion status of FW. This returns True if a FW is created with a active policy that has more than one rule associated with it and if a driver init is done successfully.
Below is the the instruction that describes the task: ### Input: This API returns the completion status of FW. This returns True if a FW is created with a active policy that has more than one rule associated with it and if a driver init is done successfully. ### Response: def is_fw_complet...
def fetchmany(self, size=None): """Fetch the next set of rows of a query result, returning a sequence of sequences (e.g. a list of tuples). An empty sequence is returned when no more rows are available. The number of rows to fetch per call is specified by the parameter. If it is not given, the ...
Fetch the next set of rows of a query result, returning a sequence of sequences (e.g. a list of tuples). An empty sequence is returned when no more rows are available. The number of rows to fetch per call is specified by the parameter. If it is not given, the cursor's arraysize determines the n...
Below is the the instruction that describes the task: ### Input: Fetch the next set of rows of a query result, returning a sequence of sequences (e.g. a list of tuples). An empty sequence is returned when no more rows are available. The number of rows to fetch per call is specified by the parameter...
def get_pixel_distance(self, x1, y1, x2, y2): """Calculate distance between the given pixel positions. Parameters ---------- x1, y1, x2, y2 : number Pixel coordinates. Returns ------- dist : float Rounded distance. """ dx...
Calculate distance between the given pixel positions. Parameters ---------- x1, y1, x2, y2 : number Pixel coordinates. Returns ------- dist : float Rounded distance.
Below is the the instruction that describes the task: ### Input: Calculate distance between the given pixel positions. Parameters ---------- x1, y1, x2, y2 : number Pixel coordinates. Returns ------- dist : float Rounded distance. ### Respons...
def to_task(self): """Return a task object representing this async job.""" from google.appengine.api.taskqueue import Task from google.appengine.api.taskqueue import TaskRetryOptions self._increment_recursion_level() self.check_recursion_depth() url = "%s/%s" % (ASYNC_E...
Return a task object representing this async job.
Below is the the instruction that describes the task: ### Input: Return a task object representing this async job. ### Response: def to_task(self): """Return a task object representing this async job.""" from google.appengine.api.taskqueue import Task from google.appengine.api.taskqueue imp...
def inflate_plugins(self, plugins_definition, inflate_method): """ Inflate multiple plugins based on a list/dict definition. Args: plugins_definition (list/dict): the plugins definitions. inflate_method (method): the method to indlate each plugin. Returns: ...
Inflate multiple plugins based on a list/dict definition. Args: plugins_definition (list/dict): the plugins definitions. inflate_method (method): the method to indlate each plugin. Returns: list: a list of plugin instances. Raises: ValueError: w...
Below is the the instruction that describes the task: ### Input: Inflate multiple plugins based on a list/dict definition. Args: plugins_definition (list/dict): the plugins definitions. inflate_method (method): the method to indlate each plugin. Returns: list: a...
def mmi_ramp_roman(raster_layer): """Generate an mmi ramp using range of 1-10 on roman. A standarised range is used so that two shakemaps of different intensities can be properly compared visually with colours stretched accross the same range. The colours used are the 'standard' colours commonly s...
Generate an mmi ramp using range of 1-10 on roman. A standarised range is used so that two shakemaps of different intensities can be properly compared visually with colours stretched accross the same range. The colours used are the 'standard' colours commonly shown for the mercalli scale e.g. on w...
Below is the the instruction that describes the task: ### Input: Generate an mmi ramp using range of 1-10 on roman. A standarised range is used so that two shakemaps of different intensities can be properly compared visually with colours stretched accross the same range. The colours used are the '...
def chown(self, tarinfo, targetpath): """Set owner of targetpath according to tarinfo. """ if pwd and hasattr(os, "geteuid") and os.geteuid() == 0: # We have to be root to do so. try: g = grp.getgrnam(tarinfo.gname)[2] except KeyError: ...
Set owner of targetpath according to tarinfo.
Below is the the instruction that describes the task: ### Input: Set owner of targetpath according to tarinfo. ### Response: def chown(self, tarinfo, targetpath): """Set owner of targetpath according to tarinfo. """ if pwd and hasattr(os, "geteuid") and os.geteuid() == 0: # We h...
def run_gradle(path=kernel_path, cmd='build', skip_tests=False): """Return a Command for running gradle scripts. Parameters ---------- path: str, optional The base path of the node package. Defaults to the repo root. cmd: str, optional The command to run with gradlew. """ ...
Return a Command for running gradle scripts. Parameters ---------- path: str, optional The base path of the node package. Defaults to the repo root. cmd: str, optional The command to run with gradlew.
Below is the the instruction that describes the task: ### Input: Return a Command for running gradle scripts. Parameters ---------- path: str, optional The base path of the node package. Defaults to the repo root. cmd: str, optional The command to run with gradlew. ### Response: d...
def email_url_config(cls, url, backend=None): """Parses an email URL.""" config = {} url = urlparse(url) if not isinstance(url, cls.URL_CLASS) else url # Remove query strings path = url.path[1:] path = unquote_plus(path.split('?', 2)[0]) # Update with environm...
Parses an email URL.
Below is the the instruction that describes the task: ### Input: Parses an email URL. ### Response: def email_url_config(cls, url, backend=None): """Parses an email URL.""" config = {} url = urlparse(url) if not isinstance(url, cls.URL_CLASS) else url # Remove query strings ...
def get_for_nearest_ancestor(self, cls, attribute_name): """ Find a prior with the attribute analysis_path from the config for this class or one of its ancestors Parameters ---------- cls: class The class of interest attribute_name: String The ana...
Find a prior with the attribute analysis_path from the config for this class or one of its ancestors Parameters ---------- cls: class The class of interest attribute_name: String The analysis_path of the attribute Returns ------- prior_arr...
Below is the the instruction that describes the task: ### Input: Find a prior with the attribute analysis_path from the config for this class or one of its ancestors Parameters ---------- cls: class The class of interest attribute_name: String The analysis_pa...
def __regkey_value(self, path, name='', start_key=None): r'''Return the data of value mecabrc at MeCab HKEY node. On Windows, the path to the mecabrc as set in the Windows Registry is used to deduce the path to libmecab.dll. Returns: The full path to the mecabrc on W...
r'''Return the data of value mecabrc at MeCab HKEY node. On Windows, the path to the mecabrc as set in the Windows Registry is used to deduce the path to libmecab.dll. Returns: The full path to the mecabrc on Windows. Raises: WindowsError: A problem wa...
Below is the the instruction that describes the task: ### Input: r'''Return the data of value mecabrc at MeCab HKEY node. On Windows, the path to the mecabrc as set in the Windows Registry is used to deduce the path to libmecab.dll. Returns: The full path to the mecabrc o...
def get_questions(self, answered=None, honor_sequential=True, update=True): """gets all available questions for this section if answered == False: only return next unanswered question if answered == True: only return next answered question if answered in None: return next question wheth...
gets all available questions for this section if answered == False: only return next unanswered question if answered == True: only return next answered question if answered in None: return next question whether answered or not if honor_sequential == True: only return questions if sectio...
Below is the the instruction that describes the task: ### Input: gets all available questions for this section if answered == False: only return next unanswered question if answered == True: only return next answered question if answered in None: return next question whether answered or not...
def add_local(self, field_name, field): """Add a local variable in the current scope :field_name: The field's name :field: The field :returns: None """ self._dlog("adding local '{}'".format(field_name)) field._pfp__name = field_name # TODO do we allow cl...
Add a local variable in the current scope :field_name: The field's name :field: The field :returns: None
Below is the the instruction that describes the task: ### Input: Add a local variable in the current scope :field_name: The field's name :field: The field :returns: None ### Response: def add_local(self, field_name, field): """Add a local variable in the current scope :fie...
def apply(self, df): """Takes a pd.DataFrame and returns the newly defined column, i.e. a pd.Series that has the same index as `df`. """ if hasattr(self.definition, '__call__'): r = self.definition(df) elif self.definition in df.columns: r = df[self.defini...
Takes a pd.DataFrame and returns the newly defined column, i.e. a pd.Series that has the same index as `df`.
Below is the the instruction that describes the task: ### Input: Takes a pd.DataFrame and returns the newly defined column, i.e. a pd.Series that has the same index as `df`. ### Response: def apply(self, df): """Takes a pd.DataFrame and returns the newly defined column, i.e. a pd.Series tha...
def check_config_xml(self, contents): """ Check whether the given XML config file contents is well-formed and it has all the required parameters. :param string contents: the XML config file contents or XML config string :param bool is_config_string: if ``True``, contents is a co...
Check whether the given XML config file contents is well-formed and it has all the required parameters. :param string contents: the XML config file contents or XML config string :param bool is_config_string: if ``True``, contents is a config string :rtype: :class:`~aeneas.validator.Vali...
Below is the the instruction that describes the task: ### Input: Check whether the given XML config file contents is well-formed and it has all the required parameters. :param string contents: the XML config file contents or XML config string :param bool is_config_string: if ``True``, conte...
def create_project(self, key, name=None, assignee=None, type="Software", template_name=None): """Create a project with the specified parameters. :param key: Mandatory. Must match JIRA project key requirements, usually only 2-10 uppercase characters. :type: str :param name: If not specif...
Create a project with the specified parameters. :param key: Mandatory. Must match JIRA project key requirements, usually only 2-10 uppercase characters. :type: str :param name: If not specified it will use the key value. :type name: Optional[str] :param assignee: If not specifie...
Below is the the instruction that describes the task: ### Input: Create a project with the specified parameters. :param key: Mandatory. Must match JIRA project key requirements, usually only 2-10 uppercase characters. :type: str :param name: If not specified it will use the key value. ...
def get_default_config(self): """ Returns the default collector settings """ config = super(OneWireCollector, self).get_default_config() config.update({ 'path': 'owfs', 'owfs': '/mnt/1wire', # 'scan': {'temperature': 't'}, # 'id:24....
Returns the default collector settings
Below is the the instruction that describes the task: ### Input: Returns the default collector settings ### Response: def get_default_config(self): """ Returns the default collector settings """ config = super(OneWireCollector, self).get_default_config() config.update({ ...
def fantope(x, rho, dim, tol=1e-4): """ Projection onto the fantope [1]_ .. [1] Vu, Vincent Q., et al. "Fantope projection and selection: A near-optimal convex relaxation of sparse PCA." Advances in neural information processing systems. 2013. """ U, V = np.linalg.eigh(x) ...
Projection onto the fantope [1]_ .. [1] Vu, Vincent Q., et al. "Fantope projection and selection: A near-optimal convex relaxation of sparse PCA." Advances in neural information processing systems. 2013.
Below is the the instruction that describes the task: ### Input: Projection onto the fantope [1]_ .. [1] Vu, Vincent Q., et al. "Fantope projection and selection: A near-optimal convex relaxation of sparse PCA." Advances in neural information processing systems. 2013. ### Response: def f...
def convertDirMP3ToWav(dirName, Fs, nC, useMp3TagsAsName = False): ''' This function converts the MP3 files stored in a folder to WAV. If required, the output names of the WAV files are based on MP3 tags, otherwise the same names are used. ARGUMENTS: - dirName: the path of the folder where the MP3s...
This function converts the MP3 files stored in a folder to WAV. If required, the output names of the WAV files are based on MP3 tags, otherwise the same names are used. ARGUMENTS: - dirName: the path of the folder where the MP3s are stored - Fs: the sampling rate of the generated WAV files ...
Below is the the instruction that describes the task: ### Input: This function converts the MP3 files stored in a folder to WAV. If required, the output names of the WAV files are based on MP3 tags, otherwise the same names are used. ARGUMENTS: - dirName: the path of the folder where the MP3s are store...
def DeleteGroup(r, group, dry_run=False): """ Deletes a node group. @type group: str @param group: the node group to delete @type dry_run: bool @param dry_run: whether to peform a dry run @rtype: int @return: job id """ query = { "dry-run": dry_run, } return r...
Deletes a node group. @type group: str @param group: the node group to delete @type dry_run: bool @param dry_run: whether to peform a dry run @rtype: int @return: job id
Below is the the instruction that describes the task: ### Input: Deletes a node group. @type group: str @param group: the node group to delete @type dry_run: bool @param dry_run: whether to peform a dry run @rtype: int @return: job id ### Response: def DeleteGroup(r, group, dry_run=False)...
def prepare_renderable(request, test_case_result, is_admin): """Return a completed Renderable.""" test_case = test_case_result.test_case file_directory = request.registry.settings['file_directory'] sha1 = test_case_result.diff.sha1 if test_case_result.diff else None kwargs = {'number': test_case.id,...
Return a completed Renderable.
Below is the the instruction that describes the task: ### Input: Return a completed Renderable. ### Response: def prepare_renderable(request, test_case_result, is_admin): """Return a completed Renderable.""" test_case = test_case_result.test_case file_directory = request.registry.settings['file_directo...
def git_url_ssh_to_https(url): """Convert a git url url will look like https://github.com/ARMmbed/mbed-cloud-sdk-python.git or git@github.com:ARMmbed/mbed-cloud-sdk-python.git we want: https://${GITHUB_TOKEN}@github.com/ARMmbed/mbed-cloud-sdk-python-private.git """ path = url.split(...
Convert a git url url will look like https://github.com/ARMmbed/mbed-cloud-sdk-python.git or git@github.com:ARMmbed/mbed-cloud-sdk-python.git we want: https://${GITHUB_TOKEN}@github.com/ARMmbed/mbed-cloud-sdk-python-private.git
Below is the the instruction that describes the task: ### Input: Convert a git url url will look like https://github.com/ARMmbed/mbed-cloud-sdk-python.git or git@github.com:ARMmbed/mbed-cloud-sdk-python.git we want: https://${GITHUB_TOKEN}@github.com/ARMmbed/mbed-cloud-sdk-python-private.gi...
def get_composite_reflectivity(self, tower_id, background='#000000', include_legend=True, include_counties=True, include_warnings=True, include_highways=True, include_cities=True, include_rivers=True, include_topography=True): """ Get...
Get the composite reflectivity for a noaa radar site. :param tower_id: The noaa tower id. Ex Huntsville, Al -> 'HTX'. :type tower_id: str :param background: The hex background color. :type background: str :param include_legend: True - include legend. :type include_legend...
Below is the the instruction that describes the task: ### Input: Get the composite reflectivity for a noaa radar site. :param tower_id: The noaa tower id. Ex Huntsville, Al -> 'HTX'. :type tower_id: str :param background: The hex background color. :type background: str :para...
def get_key_from_envs(envs, key): """Return the value of a key from the given dict respecting namespaces. Data can also be a list of data dicts. """ # if it barks like a dict, make it a list have to use `get` since dicts and # lists both have __getitem__ if hasattr(envs, 'get'): envs =...
Return the value of a key from the given dict respecting namespaces. Data can also be a list of data dicts.
Below is the the instruction that describes the task: ### Input: Return the value of a key from the given dict respecting namespaces. Data can also be a list of data dicts. ### Response: def get_key_from_envs(envs, key): """Return the value of a key from the given dict respecting namespaces. Data can...
def any2utf8(text, errors='strict', encoding='utf8'): """Convert a string (unicode or bytestring in `encoding`), to bytestring in utf8.""" if isinstance(text, unicode): return text.encode('utf8') # do bytestring -> unicode -> utf8 full circle, to ensure valid utf8 return unicode(text, encoding, ...
Convert a string (unicode or bytestring in `encoding`), to bytestring in utf8.
Below is the the instruction that describes the task: ### Input: Convert a string (unicode or bytestring in `encoding`), to bytestring in utf8. ### Response: def any2utf8(text, errors='strict', encoding='utf8'): """Convert a string (unicode or bytestring in `encoding`), to bytestring in utf8.""" if isinsta...
def list_stateful_set_for_all_namespaces(self, **kwargs): """ list or watch objects of kind StatefulSet This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_stateful_set_for_all_namespaces(...
list or watch objects of kind StatefulSet This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_stateful_set_for_all_namespaces(async_req=True) >>> result = thread.get() :param async_req bo...
Below is the the instruction that describes the task: ### Input: list or watch objects of kind StatefulSet This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_stateful_set_for_all_namespaces(async_req...
async def evaluate_trained_model(state): """Evaluate the most recently trained model against the current best model. Args: state: the RL loop State instance. """ return await evaluate_model( state.train_model_path, state.best_model_path, os.path.join(fsdb.eval_dir(), state.train_model_name), s...
Evaluate the most recently trained model against the current best model. Args: state: the RL loop State instance.
Below is the the instruction that describes the task: ### Input: Evaluate the most recently trained model against the current best model. Args: state: the RL loop State instance. ### Response: async def evaluate_trained_model(state): """Evaluate the most recently trained model against the current best mod...
def excerpts(n_samples, n_excerpts=None, excerpt_size=None): """Yield (start, end) where start is included and end is excluded.""" assert n_excerpts >= 2 step = _excerpt_step(n_samples, n_excerpts=n_excerpts, excerpt_size=excerpt_size) for i in range(n_e...
Yield (start, end) where start is included and end is excluded.
Below is the the instruction that describes the task: ### Input: Yield (start, end) where start is included and end is excluded. ### Response: def excerpts(n_samples, n_excerpts=None, excerpt_size=None): """Yield (start, end) where start is included and end is excluded.""" assert n_excerpts >= 2 step =...
def get_fields(model_class): """ Pass in a mongo model class and extract all the attributes which are mongoengine fields Returns: list of strings of field attributes """ return [ attr for attr, value in model_class.__dict__.items() if issubclass(type(value), (mongo.base....
Pass in a mongo model class and extract all the attributes which are mongoengine fields Returns: list of strings of field attributes
Below is the the instruction that describes the task: ### Input: Pass in a mongo model class and extract all the attributes which are mongoengine fields Returns: list of strings of field attributes ### Response: def get_fields(model_class): """ Pass in a mongo model class and extract all t...
def serve(request, path, document_root=None, show_indexes=False, default=''): """ Serve static files below a given point in the directory structure. To use, put a URL pattern such as:: (r'^(?P<path>.*)$', 'django.views.static.serve', {'document_root' : '/path/to/my/files/'}) in yo...
Serve static files below a given point in the directory structure. To use, put a URL pattern such as:: (r'^(?P<path>.*)$', 'django.views.static.serve', {'document_root' : '/path/to/my/files/'}) in your URLconf. You must provide the ``document_root`` param. You may also set ``show_inde...
Below is the the instruction that describes the task: ### Input: Serve static files below a given point in the directory structure. To use, put a URL pattern such as:: (r'^(?P<path>.*)$', 'django.views.static.serve', {'document_root' : '/path/to/my/files/'}) in your URLconf. You must ...
def isValidFeatureWriter(klass): """Return True if 'klass' is a valid feature writer class. A valid feature writer class is a class (of type 'type'), that has two required attributes: 1) 'tableTag' (str), which can be "GSUB", "GPOS", or other similar tags. 2) 'write' (bound method), with the signatu...
Return True if 'klass' is a valid feature writer class. A valid feature writer class is a class (of type 'type'), that has two required attributes: 1) 'tableTag' (str), which can be "GSUB", "GPOS", or other similar tags. 2) 'write' (bound method), with the signature matching the same method from ...
Below is the the instruction that describes the task: ### Input: Return True if 'klass' is a valid feature writer class. A valid feature writer class is a class (of type 'type'), that has two required attributes: 1) 'tableTag' (str), which can be "GSUB", "GPOS", or other similar tags. 2) 'write' (bo...
def disp(self, idx=100): # r_[0:5,1e2:1e9:1e2,-10:0]): """displays selected data from (files written by) the class `CMADataLogger`. Arguments --------- `idx` indices corresponding to rows in the data file; if idx is a scalar (int), the first two, then e...
displays selected data from (files written by) the class `CMADataLogger`. Arguments --------- `idx` indices corresponding to rows in the data file; if idx is a scalar (int), the first two, then every idx-th, and the last three rows are displayed. ...
Below is the the instruction that describes the task: ### Input: displays selected data from (files written by) the class `CMADataLogger`. Arguments --------- `idx` indices corresponding to rows in the data file; if idx is a scalar (int), the first two, then...
def get_dates_range(self, scale='auto', start=None, end=None, date_max='2010-01-01'): ''' Returns a list of dates sampled according to the specified parameters. :param scale: {'auto', 'maximum', 'daily', 'weekly', 'monthly', 'quarterly', 'yearly'} ...
Returns a list of dates sampled according to the specified parameters. :param scale: {'auto', 'maximum', 'daily', 'weekly', 'monthly', 'quarterly', 'yearly'} Scale specifies the sampling intervals. 'auto' will heuristically choose a scale for quick processing :param ...
Below is the the instruction that describes the task: ### Input: Returns a list of dates sampled according to the specified parameters. :param scale: {'auto', 'maximum', 'daily', 'weekly', 'monthly', 'quarterly', 'yearly'} Scale specifies the sampling intervals. 'auto' w...
def acts_as_state_machine(cls): """ a decorator which sets two properties on a class: * the 'current_state' property: a read-only property, returning the state machine's current state, as 'State' object * the 'states' property: a tuple of all valid state machine states, as 'State' objects cl...
a decorator which sets two properties on a class: * the 'current_state' property: a read-only property, returning the state machine's current state, as 'State' object * the 'states' property: a tuple of all valid state machine states, as 'State' objects class objects may use current_state and states...
Below is the the instruction that describes the task: ### Input: a decorator which sets two properties on a class: * the 'current_state' property: a read-only property, returning the state machine's current state, as 'State' object * the 'states' property: a tuple of all valid state machine states, ...
def power_cycle_vm(virtual_machine, action='on'): ''' Powers on/off a virtual machine specified by it's name. virtual_machine vim.VirtualMachine object to power on/off virtual machine action Operation option to power on/off the machine ''' if action == 'on': try: ...
Powers on/off a virtual machine specified by it's name. virtual_machine vim.VirtualMachine object to power on/off virtual machine action Operation option to power on/off the machine
Below is the the instruction that describes the task: ### Input: Powers on/off a virtual machine specified by it's name. virtual_machine vim.VirtualMachine object to power on/off virtual machine action Operation option to power on/off the machine ### Response: def power_cycle_vm(virtual_m...
def __fix_field_date(self, item, attribute): """Fix possible errors in the field date""" field_date = str_to_datetime(item[attribute]) try: _ = int(field_date.strftime("%z")[0:3]) except ValueError: logger.warning("%s in commit %s has a wrong format", attribute,...
Fix possible errors in the field date
Below is the the instruction that describes the task: ### Input: Fix possible errors in the field date ### Response: def __fix_field_date(self, item, attribute): """Fix possible errors in the field date""" field_date = str_to_datetime(item[attribute]) try: _ = int(field_date.s...
def date_from_number(self, value): """ Converts a float value to corresponding datetime instance. """ if not isinstance(value, numbers.Real): return None delta = datetime.timedelta(days=value) return self._null_date + delta
Converts a float value to corresponding datetime instance.
Below is the the instruction that describes the task: ### Input: Converts a float value to corresponding datetime instance. ### Response: def date_from_number(self, value): """ Converts a float value to corresponding datetime instance. """ if not isinstance(value, numbers.Real): ...
def computePhase2(self, doLearn=False): """ This is the phase 2 of learning, inference and multistep prediction. During this phase, all the cell with lateral support have their predictedState turned on and the firing segments are queued up for updates. Parameters: ------------------------------...
This is the phase 2 of learning, inference and multistep prediction. During this phase, all the cell with lateral support have their predictedState turned on and the firing segments are queued up for updates. Parameters: -------------------------------------------- doLearn: Boolean flag to que...
Below is the the instruction that describes the task: ### Input: This is the phase 2 of learning, inference and multistep prediction. During this phase, all the cell with lateral support have their predictedState turned on and the firing segments are queued up for updates. Parameters: -------------...
def row_factory(cursor, row): """Returns a sqlite row factory that returns a dictionary""" d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d
Returns a sqlite row factory that returns a dictionary
Below is the the instruction that describes the task: ### Input: Returns a sqlite row factory that returns a dictionary ### Response: def row_factory(cursor, row): """Returns a sqlite row factory that returns a dictionary""" d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[...
def _interpolate_missing_data(data, mask, method='cubic'): """ Interpolate missing data as identified by the ``mask`` keyword. Parameters ---------- data : 2D `~numpy.ndarray` An array containing the 2D image. mask : 2D bool `~numpy.ndarray` A 2D booleen mask array with the sam...
Interpolate missing data as identified by the ``mask`` keyword. Parameters ---------- data : 2D `~numpy.ndarray` An array containing the 2D image. mask : 2D bool `~numpy.ndarray` A 2D booleen mask array with the same shape as the input ``data``, where a `True` value indicates t...
Below is the the instruction that describes the task: ### Input: Interpolate missing data as identified by the ``mask`` keyword. Parameters ---------- data : 2D `~numpy.ndarray` An array containing the 2D image. mask : 2D bool `~numpy.ndarray` A 2D booleen mask array with the same ...
def copy_framebuffer(self, dst, src) -> None: ''' Copy framebuffer content. Use this method to: - blit framebuffers. - copy framebuffer content into a texture. - downsample framebuffers. (it will allow to read the framebuffer's content) ...
Copy framebuffer content. Use this method to: - blit framebuffers. - copy framebuffer content into a texture. - downsample framebuffers. (it will allow to read the framebuffer's content) - downsample a framebuffer directly to a texture. ...
Below is the the instruction that describes the task: ### Input: Copy framebuffer content. Use this method to: - blit framebuffers. - copy framebuffer content into a texture. - downsample framebuffers. (it will allow to read the framebuffer's content) ...
def swipe_bottom(self, steps=10, *args, **selectors): """ Swipe the UI object with *selectors* from center to bottom See `Swipe Left` for more details. """ self.device(**selectors).swipe.down(steps=steps)
Swipe the UI object with *selectors* from center to bottom See `Swipe Left` for more details.
Below is the the instruction that describes the task: ### Input: Swipe the UI object with *selectors* from center to bottom See `Swipe Left` for more details. ### Response: def swipe_bottom(self, steps=10, *args, **selectors): """ Swipe the UI object with *selectors* from center to bottom ...
def normalize(arg=None): """Normalizes an argument for signing purpose. This is used for normalizing the arguments of RPC method calls. :param arg: The argument to normalize :return: A string representating the normalized argument. .. doctest:: >>> from cloud.rpc import normalize >>> ...
Normalizes an argument for signing purpose. This is used for normalizing the arguments of RPC method calls. :param arg: The argument to normalize :return: A string representating the normalized argument. .. doctest:: >>> from cloud.rpc import normalize >>> normalize(['foo', 42, 'bar']) ...
Below is the the instruction that describes the task: ### Input: Normalizes an argument for signing purpose. This is used for normalizing the arguments of RPC method calls. :param arg: The argument to normalize :return: A string representating the normalized argument. .. doctest:: >>> from...
def set_mtime(self, name, mtime, size): """Set modification time on file.""" self.check_write(name) os.utime(os.path.join(self.cur_dir, name), (-1, mtime))
Set modification time on file.
Below is the the instruction that describes the task: ### Input: Set modification time on file. ### Response: def set_mtime(self, name, mtime, size): """Set modification time on file.""" self.check_write(name) os.utime(os.path.join(self.cur_dir, name), (-1, mtime))
def to_json(self): """ :return: str """ json_dict = self.to_json_basic() json_dict['closed_channels'] = self.closed json_dict['opened_channels'] = self.opened json_dict['closed_long_channels'] = self.closed_long return json.dumps(json_dict)
:return: str
Below is the the instruction that describes the task: ### Input: :return: str ### Response: def to_json(self): """ :return: str """ json_dict = self.to_json_basic() json_dict['closed_channels'] = self.closed json_dict['opened_channels'] = self.opened json_dic...
def _reload(self, module=None): """Reload the source function from the source module. **Internal use only** Update the source function of the formula. This method is used to updated the underlying formula when the source code of the module in which the source function is...
Reload the source function from the source module. **Internal use only** Update the source function of the formula. This method is used to updated the underlying formula when the source code of the module in which the source function is read from is modified. If the for...
Below is the the instruction that describes the task: ### Input: Reload the source function from the source module. **Internal use only** Update the source function of the formula. This method is used to updated the underlying formula when the source code of the module in which the ...
def lastOfferedMonth(self): ''' Sometimes a Series is associated with a month other than the one in which the first class begins, so this returns a (year,month) tuple that can be used in admin instead. ''' lastOfferedSeries = self.event_set.order_by('-startTime').first() ...
Sometimes a Series is associated with a month other than the one in which the first class begins, so this returns a (year,month) tuple that can be used in admin instead.
Below is the the instruction that describes the task: ### Input: Sometimes a Series is associated with a month other than the one in which the first class begins, so this returns a (year,month) tuple that can be used in admin instead. ### Response: def lastOfferedMonth(self): ''' So...
def clean_username(self, username): """ Performs any cleaning on the "username" prior to using it to get or create the user object. Returns the cleaned username. By default, changes the username case according to `settings.CAS_FORCE_CHANGE_USERNAME_CASE`. """ us...
Performs any cleaning on the "username" prior to using it to get or create the user object. Returns the cleaned username. By default, changes the username case according to `settings.CAS_FORCE_CHANGE_USERNAME_CASE`.
Below is the the instruction that describes the task: ### Input: Performs any cleaning on the "username" prior to using it to get or create the user object. Returns the cleaned username. By default, changes the username case according to `settings.CAS_FORCE_CHANGE_USERNAME_CASE`. ### Respo...
def _retrieve(self, namespace, stream, start_id, end_time, order, limit, configuration): """ Retrieve events for `stream` between `start_id` and `end_time`. `stream` : The stream to return events for. `start_id` : Return events with id > `start_id`. `end_time` : Return events ending ...
Retrieve events for `stream` between `start_id` and `end_time`. `stream` : The stream to return events for. `start_id` : Return events with id > `start_id`. `end_time` : Return events ending <= `end_time`. `order` : Whether to return the results in ResultOrder.ASCENDING or ResultOrder.DESC...
Below is the the instruction that describes the task: ### Input: Retrieve events for `stream` between `start_id` and `end_time`. `stream` : The stream to return events for. `start_id` : Return events with id > `start_id`. `end_time` : Return events ending <= `end_time`. `order` : Whether to return t...
def build_struct_type(s_sdt): ''' Build an xsd complexType out of a S_SDT. ''' s_dt = nav_one(s_sdt).S_DT[17]() struct = ET.Element('xs:complexType', name=s_dt.name) first_filter = lambda selected: not nav_one(selected).S_MBR[46, 'succeeds']() s_mbr = nav_any(s_sdt).S_MBR[44](first...
Build an xsd complexType out of a S_SDT.
Below is the the instruction that describes the task: ### Input: Build an xsd complexType out of a S_SDT. ### Response: def build_struct_type(s_sdt): ''' Build an xsd complexType out of a S_SDT. ''' s_dt = nav_one(s_sdt).S_DT[17]() struct = ET.Element('xs:complexType', name=s_dt.name) ...
def add_node(self, kind, image_id, image_user, flavor, security_group, image_userdata='', name=None, **extra): """ Adds a new node to the cluster. This factory method provides an easy way to add a new node to the cluster by specifying all relevant parameters. The node do...
Adds a new node to the cluster. This factory method provides an easy way to add a new node to the cluster by specifying all relevant parameters. The node does not get started nor setup automatically, this has to be done manually afterwards. :param str kind: kind of node to start. this r...
Below is the the instruction that describes the task: ### Input: Adds a new node to the cluster. This factory method provides an easy way to add a new node to the cluster by specifying all relevant parameters. The node does not get started nor setup automatically, this has to be done manuall...
def refresh(self, accept=MEDIA_TYPE_TAXII_V20): """Update the API Root's information and list of Collections""" self.refresh_information(accept) self.refresh_collections(accept)
Update the API Root's information and list of Collections
Below is the the instruction that describes the task: ### Input: Update the API Root's information and list of Collections ### Response: def refresh(self, accept=MEDIA_TYPE_TAXII_V20): """Update the API Root's information and list of Collections""" self.refresh_information(accept) self.refr...
def _summarize_in_roi(self, label_mask, num_clusters_per_roi=1, metric='minkowski'): """returns a single row summarizing (typically via mean) all rows in an ROI.""" this_label = self.carpet[label_mask.flatten(), :] if num_clusters_per_roi == 1: out_matrix = self._summary_func(this_l...
returns a single row summarizing (typically via mean) all rows in an ROI.
Below is the the instruction that describes the task: ### Input: returns a single row summarizing (typically via mean) all rows in an ROI. ### Response: def _summarize_in_roi(self, label_mask, num_clusters_per_roi=1, metric='minkowski'): """returns a single row summarizing (typically via mean) all rows in ...
def _mem(self): """Record Memory usage.""" value = int(psutil.virtual_memory().percent) set_metric("memory", value, category=self.category) gauge("memory", value)
Record Memory usage.
Below is the the instruction that describes the task: ### Input: Record Memory usage. ### Response: def _mem(self): """Record Memory usage.""" value = int(psutil.virtual_memory().percent) set_metric("memory", value, category=self.category) gauge("memory", value)
def _parse_processor_embedded_health(self, data): """Parse the get_host_health_data() for essential properties :param data: the output returned by get_host_health_data() :returns: processor details like cpu arch and number of cpus. """ processor = self.get_value_as_list((data['...
Parse the get_host_health_data() for essential properties :param data: the output returned by get_host_health_data() :returns: processor details like cpu arch and number of cpus.
Below is the the instruction that describes the task: ### Input: Parse the get_host_health_data() for essential properties :param data: the output returned by get_host_health_data() :returns: processor details like cpu arch and number of cpus. ### Response: def _parse_processor_embedded_health(sel...
def noise_set_type(n: tcod.noise.Noise, typ: int) -> None: """Set a Noise objects default noise algorithm. Args: typ (int): Any NOISE_* constant. """ n.algorithm = typ
Set a Noise objects default noise algorithm. Args: typ (int): Any NOISE_* constant.
Below is the the instruction that describes the task: ### Input: Set a Noise objects default noise algorithm. Args: typ (int): Any NOISE_* constant. ### Response: def noise_set_type(n: tcod.noise.Noise, typ: int) -> None: """Set a Noise objects default noise algorithm. Args: typ (int)...
def update_project(config, task_presenter, results, long_description, tutorial, watch): # pragma: no cover """Update project templates and information.""" if watch: res = _update_project_watch(config, task_presenter, results, long_description, tutor...
Update project templates and information.
Below is the the instruction that describes the task: ### Input: Update project templates and information. ### Response: def update_project(config, task_presenter, results, long_description, tutorial, watch): # pragma: no cover """Update project templates and information.""" if watch: ...
def send_alert_to_configured_integration(integration_alert): """Send IntegrationAlert to configured integration.""" try: alert = integration_alert.alert configured_integration = integration_alert.configured_integration integration = configured_integration.integration integration_...
Send IntegrationAlert to configured integration.
Below is the the instruction that describes the task: ### Input: Send IntegrationAlert to configured integration. ### Response: def send_alert_to_configured_integration(integration_alert): """Send IntegrationAlert to configured integration.""" try: alert = integration_alert.alert configured...
def _fix_key(key): '''Normalize keys to Unicode strings.''' if isinstance(key, unicode): return key if isinstance(key, str): # On my system, the default encoding is `ascii`, so let's # explicitly say UTF-8? return unicode(key, 'utf-8') rais...
Normalize keys to Unicode strings.
Below is the the instruction that describes the task: ### Input: Normalize keys to Unicode strings. ### Response: def _fix_key(key): '''Normalize keys to Unicode strings.''' if isinstance(key, unicode): return key if isinstance(key, str): # On my system, the default ...
def select_with_correspondence( self, selector, result_selector=KeyedElement): '''Apply a callable to each element in an input sequence, generating a new sequence of 2-tuples where the first element is the input value and the second is the transformed input va...
Apply a callable to each element in an input sequence, generating a new sequence of 2-tuples where the first element is the input value and the second is the transformed input value. The generated sequence is lazily evaluated. Note: This method uses deferred execution. Args: ...
Below is the the instruction that describes the task: ### Input: Apply a callable to each element in an input sequence, generating a new sequence of 2-tuples where the first element is the input value and the second is the transformed input value. The generated sequence is lazily evaluated....
def delete(self, run_id): """ Delete all metrics belonging to the given run. :param run_id: ID of the Run that the metric belongs to. """ self.generic_dao.delete_record( self.metrics_collection_name, {"run_id": self._parse_run_id(run_id)})
Delete all metrics belonging to the given run. :param run_id: ID of the Run that the metric belongs to.
Below is the the instruction that describes the task: ### Input: Delete all metrics belonging to the given run. :param run_id: ID of the Run that the metric belongs to. ### Response: def delete(self, run_id): """ Delete all metrics belonging to the given run. :param run_id: ID of the...
def acquire(self, signal=True): """ Locks the account. Method has no effect if the constructor argument `needs_lock` wsa set to False. :type signal: bool :param signal: Whether to emit the acquired_event signal. """ if not self.needs_lock: ret...
Locks the account. Method has no effect if the constructor argument `needs_lock` wsa set to False. :type signal: bool :param signal: Whether to emit the acquired_event signal.
Below is the the instruction that describes the task: ### Input: Locks the account. Method has no effect if the constructor argument `needs_lock` wsa set to False. :type signal: bool :param signal: Whether to emit the acquired_event signal. ### Response: def acquire(self, signal=Tr...
def _combine_indexers(old_key, shape, new_key): """ Combine two indexers. Parameters ---------- old_key: ExplicitIndexer The first indexer for the original array shape: tuple of ints Shape of the original array to be indexed by old_key new_key: The second indexer for ind...
Combine two indexers. Parameters ---------- old_key: ExplicitIndexer The first indexer for the original array shape: tuple of ints Shape of the original array to be indexed by old_key new_key: The second indexer for indexing original[old_key]
Below is the the instruction that describes the task: ### Input: Combine two indexers. Parameters ---------- old_key: ExplicitIndexer The first indexer for the original array shape: tuple of ints Shape of the original array to be indexed by old_key new_key: The second in...
def stop(self, timeout=5): """ Stop the container. The container must have been created. :param timeout: Timeout in seconds to wait for the container to stop before sending a ``SIGKILL``. Default: 5 (half the Docker default) """ self.inner().stop(timeout=...
Stop the container. The container must have been created. :param timeout: Timeout in seconds to wait for the container to stop before sending a ``SIGKILL``. Default: 5 (half the Docker default)
Below is the the instruction that describes the task: ### Input: Stop the container. The container must have been created. :param timeout: Timeout in seconds to wait for the container to stop before sending a ``SIGKILL``. Default: 5 (half the Docker default) ### Response: def stop(...
def doigrf(lon, lat, alt, date, **kwargs): """ Calculates the interpolated (<2015) or extrapolated (>2015) main field and secular variation coefficients and passes them to the Malin and Barraclough routine (function pmag.magsyn) to calculate the field from the coefficients. Parameters: --------...
Calculates the interpolated (<2015) or extrapolated (>2015) main field and secular variation coefficients and passes them to the Malin and Barraclough routine (function pmag.magsyn) to calculate the field from the coefficients. Parameters: ----------- lon : east longitude in degrees (0 to 360 or -...
Below is the the instruction that describes the task: ### Input: Calculates the interpolated (<2015) or extrapolated (>2015) main field and secular variation coefficients and passes them to the Malin and Barraclough routine (function pmag.magsyn) to calculate the field from the coefficients. Parameters...