text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> For the given mold_id_path, look up the mold_id and translate <END_TASK> <USER_TASK:> Description: def lookup_path(self, mold_id_path, default=_marker): """ For the given mold_id_path, look up the mold_id and translate that path to its filesystem equivalent. """
fragments = mold_id_path.split('/') mold_id = '/'.join(fragments[:2]) try: subpath = [] for piece in fragments[2:]: if (sep in piece or (altsep and altsep in piece) or piece == pardir): raise KeyError elif piece and piece != '.': subpath.append(piece) path = self.mold_id_to_path(mold_id) except KeyError: if default is _marker: raise return default return join(path, *subpath)
<SYSTEM_TASK:> Lookup and verify path. <END_TASK> <USER_TASK:> Description: def verify_path(self, mold_id_path): """ Lookup and verify path. """
try: path = self.lookup_path(mold_id_path) if not exists(path): raise KeyError except KeyError: raise_os_error(ENOENT) return path
<SYSTEM_TASK:> Returns the skippers of configuration. <END_TASK> <USER_TASK:> Description: def _get_skippers(configure, file_name=None): """ Returns the skippers of configuration. :param configure: The configuration of HaTeMiLe. :type configure: hatemile.util.configure.Configure :param file_name: The file path of skippers configuration. :type file_name: str :return: The skippers of configuration. :rtype: list(dict(str, str)) """
skippers = [] if file_name is None: file_name = os.path.join(os.path.dirname(os.path.dirname( os.path.dirname(os.path.realpath(__file__)) )), 'skippers.xml') xmldoc = minidom.parse(file_name) skippers_xml = xmldoc.getElementsByTagName( 'skippers' )[0].getElementsByTagName('skipper') for skipper_xml in skippers_xml: skippers.append({ 'selector': skipper_xml.attributes['selector'].value, 'description': configure.get_parameter( skipper_xml.attributes['description'].value ), 'shortcut': skipper_xml.attributes['shortcut'].value }) return skippers
<SYSTEM_TASK:> Generate the list of skippers of page. <END_TASK> <USER_TASK:> Description: def _generate_list_skippers(self): """ Generate the list of skippers of page. :return: The list of skippers of page. :rtype: hatemile.util.html.htmldomelement.HTMLDOMElement """
container = self.parser.find( '#' + AccessibleNavigationImplementation.ID_CONTAINER_SKIPPERS ).first_result() html_list = None if container is None: local = self.parser.find('body').first_result() if local is not None: container = self.parser.create_element('div') container.set_attribute( 'id', AccessibleNavigationImplementation.ID_CONTAINER_SKIPPERS ) local.prepend_element(container) if container is not None: html_list = self.parser.find(container).find_children( 'ul' ).first_result() if html_list is None: html_list = self.parser.create_element('ul') container.append_element(html_list) self.list_skippers_added = True return html_list
<SYSTEM_TASK:> Generate the list of heading links of page. <END_TASK> <USER_TASK:> Description: def _generate_list_heading(self): """ Generate the list of heading links of page. """
local = self.parser.find('body').first_result() id_container_heading_before = ( AccessibleNavigationImplementation.ID_CONTAINER_HEADING_BEFORE ) id_container_heading_after = ( AccessibleNavigationImplementation.ID_CONTAINER_HEADING_AFTER ) if local is not None: container_before = self.parser.find( '#' + id_container_heading_before ).first_result() if (container_before is None) and (self.elements_heading_before): container_before = self.parser.create_element('div') container_before.set_attribute( 'id', id_container_heading_before ) text_container_before = self.parser.create_element('span') text_container_before.set_attribute( 'class', AccessibleNavigationImplementation.CLASS_TEXT_HEADING ) text_container_before.append_text(self.elements_heading_before) container_before.append_element(text_container_before) local.prepend_element(container_before) if container_before is not None: self.list_heading_before = self.parser.find( container_before ).find_children('ol').first_result() if self.list_heading_before is None: self.list_heading_before = self.parser.create_element('ol') container_before.append_element(self.list_heading_before) container_after = self.parser.find( '#' + id_container_heading_after ).first_result() if (container_after is None) and (self.elements_heading_after): container_after = self.parser.create_element('div') container_after.set_attribute('id', id_container_heading_after) text_container_after = self.parser.create_element('span') text_container_after.set_attribute( 'class', AccessibleNavigationImplementation.CLASS_TEXT_HEADING ) text_container_after.append_text(self.elements_heading_after) container_after.append_element(text_container_after) local.append_element(container_after) if container_after is not None: self.list_heading_after = self.parser.find( container_after ).find_children('ol').first_result() if self.list_heading_after is None: self.list_heading_after = self.parser.create_element('ol') container_after.append_element(self.list_heading_after) self.list_heading_added = True
<SYSTEM_TASK:> Check that the headings of page are sintatic correct. <END_TASK> <USER_TASK:> Description: def _is_valid_heading(self): """ Check that the headings of page are sintatic correct. :return: True if the headings of page are sintatic correct or False if not. :rtype: bool """
elements = self.parser.find('h1,h2,h3,h4,h5,h6').list_results() last_level = 0 count_main_heading = 0 self.validate_heading = True for element in elements: level = self._get_heading_level(element) if level == 1: if count_main_heading == 1: return False else: count_main_heading = 1 if (level - last_level) > 1: return False last_level = level return True
<SYSTEM_TASK:> Generate an anchor for the element. <END_TASK> <USER_TASK:> Description: def _generate_anchor_for(self, element, data_attribute, anchor_class): """ Generate an anchor for the element. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement :param data_attribute: The name of attribute that links the element with the anchor. :type data_attribute: str :param anchor_class: The HTML class of anchor. :type anchor_class: str :return: The anchor. :rtype: hatemile.util.html.htmldomelement.HTMLDOMElement """
self.id_generator.generate_id(element) if self.parser.find( '[' + data_attribute + '="' + element.get_attribute('id') + '"]' ).first_result() is None: if element.get_tag_name() == 'A': anchor = element else: anchor = self.parser.create_element('a') self.id_generator.generate_id(anchor) anchor.set_attribute('class', anchor_class) element.insert_before(anchor) if not anchor.has_attribute('name'): anchor.set_attribute('name', anchor.get_attribute('id')) anchor.set_attribute(data_attribute, element.get_attribute('id')) return anchor return None
<SYSTEM_TASK:> Replace the shortcut of elements, that has the shortcut passed. <END_TASK> <USER_TASK:> Description: def _free_shortcut(self, shortcut): """ Replace the shortcut of elements, that has the shortcut passed. :param shortcut: The shortcut. :type shortcut: str """
alpha_numbers = '1234567890abcdefghijklmnopqrstuvwxyz' elements = self.parser.find('[accesskey]').list_results() found = False for element in elements: shortcuts = element.get_attribute('accesskey').lower() if CommonFunctions.in_list(shortcuts, shortcut): for key in alpha_numbers: found = True for element_with_shortcuts in elements: shortcuts = element_with_shortcuts.get_attribute( 'accesskey' ).lower() if CommonFunctions.in_list(shortcuts, key): found = False break if found: element.set_attribute('accesskey', key) break if found: break
<SYSTEM_TASK:> When an item is deleted, first delete any Activity object that has been created <END_TASK> <USER_TASK:> Description: def remove_orphans(self, instance, **kwargs): """ When an item is deleted, first delete any Activity object that has been created on its behalf. """
from activity_monitor.models import Activity try: instance_content_type = ContentType.objects.get_for_model(instance) timeline_item = Activity.objects.get(content_type=instance_content_type, object_id=instance.pk) timeline_item.delete() except Activity.DoesNotExist: return
<SYSTEM_TASK:> Follow a particular model class, updating associated Activity objects automatically. <END_TASK> <USER_TASK:> Description: def follow_model(self, model): """ Follow a particular model class, updating associated Activity objects automatically. """
if model: self.models_by_name[model.__name__.lower()] = model signals.post_save.connect(create_or_update, sender=model) signals.post_delete.connect(self.remove_orphans, sender=model)
<SYSTEM_TASK:> Return a QuerySet of only items of a certain type. <END_TASK> <USER_TASK:> Description: def get_for_model(self, model): """ Return a QuerySet of only items of a certain type. """
return self.filter(content_type=ContentType.objects.get_for_model(model))
<SYSTEM_TASK:> Return the last time a given model's items were updated. Returns the <END_TASK> <USER_TASK:> Description: def get_last_update_of_model(self, model, **kwargs): """ Return the last time a given model's items were updated. Returns the epoch if the items were never updated. """
qs = self.get_for_model(model) if kwargs: qs = qs.filter(**kwargs) try: return qs.order_by('-timestamp')[0].timestamp except IndexError: return datetime.datetime.fromtimestamp(0)
<SYSTEM_TASK:> Applies the given Operation to each item in the stream. The Operation executes on the <END_TASK> <USER_TASK:> Description: def for_each(self, operation, limit=0, verbose=False): """ Applies the given Operation to each item in the stream. The Operation executes on the items in the stream in the order that they appear in the stream. If the limit is supplied, then processing of the stream will stop after that many items have been processed. """
if limit != 0: count = 0 while self.has_next(): operation.perform(self.next()) count += 1 if verbose: print count if count >= limit: break else: while self.has_next(): operation.perform(self.next())
<SYSTEM_TASK:> Returns true if the value case insentively matches agains the <END_TASK> <USER_TASK:> Description: def iregex(value, iregex): """Returns true if the value case insentively matches agains the regex. """
return re.match(iregex, value, flags=re.I)
<SYSTEM_TASK:> Get subdirectories without pycache <END_TASK> <USER_TASK:> Description: def get_subdirectories(directory): """ Get subdirectories without pycache """
return [name for name in os.listdir(directory) if name != '__pycache__' if os.path.isdir(os.path.join(directory, name))]
<SYSTEM_TASK:> Accurately get python executable <END_TASK> <USER_TASK:> Description: def get_python_path() -> str: """ Accurately get python executable """
python_bin = None if os.name == 'nt': python_root = os.path.abspath( os.path.join(os.__file__, os.pardir, os.pardir)) python_bin = os.path.join(python_root, 'python.exe') else: python_root = os.path.abspath( os.path.join(os.__file__, os.pardir, os.pardir, os.pardir)) python = os.__file__.rsplit('/')[-2] python_bin = os.path.join(python_root, 'bin', python) return python_bin
<SYSTEM_TASK:> Use field values from config.json and collect from request <END_TASK> <USER_TASK:> Description: def __collect_fields(self): """ Use field values from config.json and collect from request """
form = FormData() form.add_field(self.__username_field, required=True, error=self.__username_error) form.add_field(self.__password_field, required=True, error=self.__password_error) form.parse() self.username = form.values[self.__username_field] self.password = form.values[self.__password_field] return
<SYSTEM_TASK:> install board in boards.txt. <END_TASK> <USER_TASK:> Description: def install_board(board_id, board_options, hwpack='arduino', replace_existing=False): """install board in boards.txt. :param board_id: string identifier :param board_options: dict like :param replace_existing: bool :rtype: None """
doaction = 0 if board_id in boards(hwpack).keys(): log.debug('board already exists: %s', board_id) if replace_existing: log.debug('remove board: %s' , board_id) remove_board(board_id) doaction = 1 else: doaction = 1 if doaction: lines = bunch2properties(board_id, board_options) boards_txt().write_lines([''] + lines, append=1)
<SYSTEM_TASK:> Classmethod for convienence in returning both the sunrise and sunset <END_TASK> <USER_TASK:> Description: def cycles(cls, **kwargs): """ Classmethod for convienence in returning both the sunrise and sunset based on a location and date. Always calculates the sunrise and sunset on the given date, no matter the time passed into the function in the datetime object. Parameters: loc = Location4D (object) OR point = Shapely point (object) time = datetime in UTC (object) OR lat = latitude (float) lon = longitude (float) time = datetime in UTC (object) Returns: { 'sunrise': datetime in UTC, 'sunset': datetime in UTC } Sources: http://williams.best.vwh.net/sunrise_sunset_example.htm """
if "loc" not in kwargs: if "point" not in kwargs: if "lat" not in kwargs or "lon" not in kwargs: raise ValueError("You must supply some form of lat/lon coordinates") else: lat = kwargs.get("lat") lon = kwargs.get("lon") else: lat = kwargs.get("point").y lon = kwargs.get("point").x if "time" not in kwargs: raise ValueError("You must supply a datetime object") else: time = kwargs.get("time") else: lat = kwargs.get("loc").latitude lon = kwargs.get("loc").longitude time = kwargs.get("loc").time # Convert time to UTC. Save passed in timezone to return later. if time.tzinfo is None: time = time.replace(tzinfo=pytz.utc) original_zone = pytz.utc else: original_zone = time.tzinfo local_jd = time.timetuple().tm_yday utc_jd = time.astimezone(pytz.utc).timetuple().tm_yday # We ALWAYS want to return the sunrise/sunset for the day that was passed # in (with timezone accounted for), regardless of what the UTC day is. Modify # the UTC julian day here if need be. comp = cmp(utc_jd, local_jd) if comp == 1: utc_jd -= 1 elif comp == -1: utc_jd += 1 time = time.replace(hour=0, minute=0, second=0, microsecond=0) rising_h, rising_m = cls._calc(jd=utc_jd, lat=lat, lon=lon, stage=cls.RISING) setting_h, setting_m = cls._calc(jd=utc_jd, lat=lat, lon=lon, stage=cls.SETTING) # _calc returns UTC hours and minutes, so assume time is in UTC for a few lines... rising = time.replace(tzinfo=pytz.utc) + timedelta(hours=rising_h, minutes=rising_m) setting = time.replace(tzinfo=pytz.utc) + timedelta(hours=setting_h, minutes=setting_m) # LOOK: We may be adding 24 hours to the setting time. Why? if setting < rising: setting = setting + timedelta(hours=24) rising = rising.astimezone(original_zone) setting = setting.astimezone(original_zone) return { cls.RISING : rising, cls.SETTING : setting}
<SYSTEM_TASK:> The operation method of _speak_as method for spell-out. <END_TASK> <USER_TASK:> Description: def _operation_speak_as_spell_out(self, content, index, children): """ The operation method of _speak_as method for spell-out. :param content: The text content of element. :type content: str :param index: The index of pattern in text content of element. :type index: int :param children: The children of element. :type children: list(hatemile.util.html.htmldomelement.HTMLDOMElement) """
children.append(self._create_content_element( content[0:(index + 1)], 'spell-out' )) children.append(self._create_aural_content_element(' ', 'spell-out')) return children
<SYSTEM_TASK:> The operation method of _speak_as method for literal-punctuation. <END_TASK> <USER_TASK:> Description: def _operation_speak_as_literal_punctuation( self, content, index, children ): """ The operation method of _speak_as method for literal-punctuation. :param content: The text content of element. :type content: str :param index: The index of pattern in text content of element. :type index: int :param children: The children of element. :type children: list(hatemile.util.html.htmldomelement.HTMLDOMElement) """
data_property_value = 'literal-punctuation' if index != 0: children.append(self._create_content_element( content[0:index], data_property_value )) children.append(self._create_aural_content_element( ( ' ' + self._get_description_of_symbol(content[index:(index + 1)]) + ' ' ), data_property_value) ) children.append(self._create_visual_content_element( content[index:(index + 1)], data_property_value )) return children
<SYSTEM_TASK:> The operation method of _speak_as method for no-punctuation. <END_TASK> <USER_TASK:> Description: def _operation_speak_as_no_punctuation(self, content, index, children): """ The operation method of _speak_as method for no-punctuation. :param content: The text content of element. :type content: str :param index: The index of pattern in text content of element. :type index: int :param children: The children of element. :type children: list(hatemile.util.html.htmldomelement.HTMLDOMElement) """
if index != 0: children.append(self._create_content_element( content[0:index], 'no-punctuation' )) children.append(self._create_visual_content_element( content[index:(index + 1)], 'no-punctuation' )) return children
<SYSTEM_TASK:> The operation method of _speak_as method for digits. <END_TASK> <USER_TASK:> Description: def _operation_speak_as_digits(self, content, index, children): """ The operation method of _speak_as method for digits. :param content: The text content of element. :type content: str :param index: The index of pattern in text content of element. :type index: int :param children: The children of element. :type children: list(hatemile.util.html.htmldomelement.HTMLDOMElement) """
data_property_value = 'digits' if index != 0: children.append(self._create_content_element( content[0:index], data_property_value )) children.append(self._create_aural_content_element( ' ', data_property_value )) children.append(self._create_content_element( content[index:(index + 1)], data_property_value )) return children
<SYSTEM_TASK:> Load the symbols with configuration. <END_TASK> <USER_TASK:> Description: def _set_symbols(self, file_name, configure): """ Load the symbols with configuration. :param file_name: The file path of symbol configuration. :type file_name: str :param configure: The configuration of HaTeMiLe. :type configure: hatemile.util.configure.Configure """
self.symbols = [] if file_name is None: file_name = os.path.join(os.path.dirname(os.path.dirname( os.path.dirname(os.path.realpath(__file__)) )), 'symbols.xml') xmldoc = minidom.parse(file_name) symbols_xml = xmldoc.getElementsByTagName( 'symbols' )[0].getElementsByTagName('symbol') for symbol_xml in symbols_xml: self.symbols.append({ 'symbol': symbol_xml.attributes['symbol'].value, 'description': configure.get_parameter( symbol_xml.attributes['description'].value ) })
<SYSTEM_TASK:> Returns the symbol formated to be searched by regular expression. <END_TASK> <USER_TASK:> Description: def _get_formated_symbol(self, symbol): """ Returns the symbol formated to be searched by regular expression. :param symbol: The symbol. :type symbol: str :return: The symbol formated. :rtype: str """
# pylint: disable=no-self-use old_symbols = [ '\\', '.', '+', '*', '?', '^', '$', '[', ']', '{', '}', '(', ')', '|', '/', ',', '!', '=', ':', '-' ] replace_dict = { '\\': '\\\\', '.': r'\.', '+': r'\+', '*': r'\*', '?': r'\?', '^': r'\^', '$': r'\$', '[': r'\[', ']': r'\]', '{': r'\{', '}': r'\}', '(': r'\(', ')': r'\)', '|': r'\|', '/': r'\/', ',': r'\,', '!': r'\!', '=': r'\=', ':': r'\:', '-': r'\-' } for old in old_symbols: symbol = symbol.replace(old, replace_dict[old]) return symbol
<SYSTEM_TASK:> Returns the regular expression to search all symbols. <END_TASK> <USER_TASK:> Description: def _get_regular_expression_of_symbols(self): """ Returns the regular expression to search all symbols. :return: The regular expression to search all symbols. :rtype: str """
regular_expression = None for symbol in self.symbols: formated_symbol = self._get_formated_symbol(symbol['symbol']) if regular_expression is None: regular_expression = '(' + formated_symbol + ')' else: regular_expression = ( regular_expression + '|(' + formated_symbol + ')' ) return regular_expression
<SYSTEM_TASK:> Check that the children of element can be manipulated to apply the CSS <END_TASK> <USER_TASK:> Description: def _is_valid_inherit_element(self, element): """ Check that the children of element can be manipulated to apply the CSS properties. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement :return: True if the children of element can be manipulated to apply the CSS properties or False if the children of element cannot be manipulated to apply the CSS properties. :rtype: bool """
# pylint: disable=no-self-use tag_name = element.get_tag_name() return ( (tag_name in AccessibleCSSImplementation.VALID_INHERIT_TAGS) and (not element.has_attribute(CommonFunctions.DATA_IGNORE)) )
<SYSTEM_TASK:> Visit and execute a operation in element and descendants. <END_TASK> <USER_TASK:> Description: def _visit(self, element, operation): """ Visit and execute a operation in element and descendants. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement :param operation: The operation to be executed. :type operation: function """
if self._is_valid_inherit_element(element): if element.has_children_elements(): children = element.get_children_elements() for child in children: self._visit(child, operation) elif self._is_valid_element(element): operation(element)
<SYSTEM_TASK:> Create a element to show the content. <END_TASK> <USER_TASK:> Description: def _create_content_element(self, content, data_property_value): """ Create a element to show the content. :param content: The text content of element. :type content: str :param data_property_value: The value of custom attribute used to identify the fix. :type data_property_value: str :return: The element to show the content. :rtype: hatemile.util.html.htmldomelement.HTMLDOMElement """
content_element = self.html_parser.create_element('span') content_element.set_attribute( AccessibleCSSImplementation.DATA_ISOLATOR_ELEMENT, 'true' ) content_element.set_attribute( AccessibleCSSImplementation.DATA_SPEAK_AS, data_property_value ) content_element.append_text(content) return content_element
<SYSTEM_TASK:> Create a element to show the content, only to aural displays. <END_TASK> <USER_TASK:> Description: def _create_aural_content_element(self, content, data_property_value): """ Create a element to show the content, only to aural displays. :param content: The text content of element. :type content: str :param data_property_value: The value of custom attribute used to identify the fix. :type data_property_value: str :return: The element to show the content. :rtype: hatemile.util.html.htmldomelement.HTMLDOMElement """
content_element = self._create_content_element( content, data_property_value ) content_element.set_attribute('unselectable', 'on') content_element.set_attribute('class', 'screen-reader-only') return content_element
<SYSTEM_TASK:> Create a element to show the content, only to visual displays. <END_TASK> <USER_TASK:> Description: def _create_visual_content_element(self, content, data_property_value): """ Create a element to show the content, only to visual displays. :param content: The text content of element. :type content: str :param data_property_value: The value of custom attribute used to identify the fix. :type data_property_value: str :return: The element to show the content. :rtype: hatemile.util.html.htmldomelement.HTMLDOMElement """
content_element = self._create_content_element( content, data_property_value ) content_element.set_attribute('aria-hidden', 'true') content_element.set_attribute('role', 'presentation') return content_element
<SYSTEM_TASK:> Speak the content of element and descendants. <END_TASK> <USER_TASK:> Description: def _speak_normal_inherit(self, element): """ Speak the content of element and descendants. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement """
self._visit(element, self._speak_normal) element.normalize()
<SYSTEM_TASK:> No speak any content of element and descendants. <END_TASK> <USER_TASK:> Description: def _speak_none_inherit(self, element): """ No speak any content of element and descendants. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement """
self._isolate_text_node(element) self._visit(element, self._speak_none)
<SYSTEM_TASK:> Execute a operation by regular expression for element only. <END_TASK> <USER_TASK:> Description: def _speak_as( self, element, regular_expression, data_property_value, operation ): """ Execute a operation by regular expression for element only. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement :param regular_expression: The regular expression. :type regular_expression: str :param data_property_value: The value of custom attribute used to identify the fix. :type data_property_value: str :param operation: The operation to be executed. :type operation: function """
children = [] pattern = re.compile(regular_expression) content = element.get_text_content() while content: matches = pattern.search(content) if matches is not None: index = matches.start() children = operation(content, index, children) new_index = index + 1 content = content[new_index:] else: break if children: if content: children.append(self._create_content_element( content, data_property_value )) while element.has_children(): element.get_first_node_child().remove_node() for child in children: element.append_element(child)
<SYSTEM_TASK:> Revert changes of a speak_as method for element and descendants. <END_TASK> <USER_TASK:> Description: def _reverse_speak_as(self, element, data_property_value): """ Revert changes of a speak_as method for element and descendants. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement :param data_property_value: The value of custom attribute used to identify the fix. :type data_property_value: str """
data_property = ( '[' + AccessibleCSSImplementation.DATA_SPEAK_AS + '="' + data_property_value + '"]' ) auxiliar_elements = self.html_parser.find(element).find_descendants( data_property ).list_results() for auxiliar_element in auxiliar_elements: auxiliar_element.remove_node() content_elements = self.html_parser.find(element).find_descendants( data_property ).list_results() for content_element in content_elements: if ( (element.has_attribute( AccessibleCSSImplementation.DATA_ISOLATOR_ELEMENT )) and (element.has_attribute( AccessibleCSSImplementation.DATA_ISOLATOR_ELEMENT ) == 'true') ): self._replace_element_by_own_content(content_element) element.normalize()
<SYSTEM_TASK:> Use the default speak configuration of user agent for element and <END_TASK> <USER_TASK:> Description: def _speak_as_normal(self, element): """ Use the default speak configuration of user agent for element and descendants. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement """
self._reverse_speak_as(element, 'spell-out') self._reverse_speak_as(element, 'literal-punctuation') self._reverse_speak_as(element, 'no-punctuation') self._reverse_speak_as(element, 'digits')
<SYSTEM_TASK:> Speak one letter at a time for each word for elements and descendants. <END_TASK> <USER_TASK:> Description: def _speak_as_spell_out_inherit(self, element): """ Speak one letter at a time for each word for elements and descendants. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement """
self._reverse_speak_as(element, 'spell-out') self._isolate_text_node(element) self._visit(element, self._speak_as_spell_out)
<SYSTEM_TASK:> Speak the punctuation for elements and descendants. <END_TASK> <USER_TASK:> Description: def _speak_as_literal_punctuation_inherit(self, element): """ Speak the punctuation for elements and descendants. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement """
self._reverse_speak_as(element, 'literal-punctuation') self._reverse_speak_as(element, 'no-punctuation') self._isolate_text_node(element) self._visit(element, self._speak_as_literal_punctuation)
<SYSTEM_TASK:> Speak the digit at a time for each number for element and descendants. <END_TASK> <USER_TASK:> Description: def _speak_as_digits_inherit(self, element): """ Speak the digit at a time for each number for element and descendants. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement """
self._reverse_speak_as(element, 'digits') self._isolate_text_node(element) self._visit(element, self._speak_as_digits)
<SYSTEM_TASK:> The cells headers will be spoken for every data cell for element and <END_TASK> <USER_TASK:> Description: def _speak_header_always_inherit(self, element): """ The cells headers will be spoken for every data cell for element and descendants. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement """
self._speak_header_once_inherit(element) cell_elements = self.html_parser.find(element).find_descendants( 'td[headers],th[headers]' ).list_results() accessible_display = AccessibleDisplayImplementation( self.html_parser, self.configure ) for cell_element in cell_elements: accessible_display.display_cell_header(cell_element)
<SYSTEM_TASK:> The cells headers will be spoken one time for element and descendants. <END_TASK> <USER_TASK:> Description: def _speak_header_once_inherit(self, element): """ The cells headers will be spoken one time for element and descendants. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement """
header_elements = self.html_parser.find(element).find_descendants( '[' + AccessibleDisplayImplementation.DATA_ATTRIBUTE_HEADERS_OF + ']' ).list_results() for header_element in header_elements: header_element.remove_node()
<SYSTEM_TASK:> Provide the CSS features of speaking and speech properties in element. <END_TASK> <USER_TASK:> Description: def _provide_speak_properties_with_rule(self, element, rule): """ Provide the CSS features of speaking and speech properties in element. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement :param rule: The stylesheet rule. :type rule: hatemile.util.css.stylesheetrule.StyleSheetRule """
if rule.has_property('speak'): declarations = rule.get_declarations('speak') for declaration in declarations: property_value = declaration.get_value() if property_value == 'none': self._speak_none_inherit(element) elif property_value == 'normal': self._speak_normal_inherit(element) elif property_value == 'spell-out': self._speak_as_spell_out_inherit(element) if rule.has_property('speak-as'): declarations = rule.get_declarations('speak-as') for declaration in declarations: speak_as_values = declaration.get_values() self._speak_as_normal(element) for speak_as_value in speak_as_values: if speak_as_value == 'spell-out': self._speak_as_spell_out_inherit(element) elif speak_as_value == 'literal-punctuation': self._speak_as_literal_punctuation_inherit(element) elif speak_as_value == 'no-punctuation': self._speak_as_no_punctuation_inherit(element) elif speak_as_value == 'digits': self._speak_as_digits_inherit(element) if rule.has_property('speak-punctuation'): declarations = rule.get_declarations('speak-punctuation') for declaration in declarations: property_value = declaration.get_value() if property_value == 'code': self._speak_as_literal_punctuation_inherit(element) elif property_value == 'none': self._speak_as_no_punctuation_inherit(element) if rule.has_property('speak-numeral'): declarations = rule.get_declarations('speak-numeral') for declaration in declarations: property_value = declaration.get_value() if property_value == 'digits': self._speak_as_digits_inherit(element) elif property_value == 'continuous': self._speak_as_continuous_inherit(element) if rule.has_property('speak-header'): declarations = rule.get_declarations('speak-header') for declaration in declarations: property_value = declaration.get_value() if property_value == 'always': self._speak_header_always_inherit(element) elif property_value == 'once': self._speak_header_once_inherit(element)
<SYSTEM_TASK:> u"""return True when line is final <END_TASK> <USER_TASK:> Description: def _process_keyevent(self, keyinfo): u"""return True when line is final """
#Process exit keys. Only exit on empty line log(u"_process_keyevent <%s>"%keyinfo) def nop(e): pass if self.next_meta: self.next_meta = False keyinfo.meta = True keytuple = keyinfo.tuple() if self._insert_verbatim: self.insert_text(keyinfo) self._insert_verbatim = False self.argument = 0 return False if keytuple in self.exit_dispatch: pars = (self.l_buffer, lineobj.EndOfLine(self.l_buffer)) log(u"exit_dispatch:<%s, %s>"%pars) if lineobj.EndOfLine(self.l_buffer) == 0: raise EOFError if keyinfo.keyname or keyinfo.control or keyinfo.meta: default = nop else: default = self.self_insert dispatch_func = self.key_dispatch.get(keytuple, default) log(u"readline from keyboard:<%s,%s>"%(keytuple, dispatch_func)) r = None if dispatch_func: r = dispatch_func(keyinfo) self._keylog(dispatch_func, self.l_buffer) self.l_buffer.push_undo() self.previous_func = dispatch_func return r
<SYSTEM_TASK:> Parsing params, params is a dict <END_TASK> <USER_TASK:> Description: def parse_params(self, params): """ Parsing params, params is a dict and the dict value can be a string or an iterable, namely a list, we need to process those iterables """
for (key, value) in params.items(): if not isinstance(value, str): string_params = self.to_string(value) params[key] = string_params return params
<SYSTEM_TASK:> Picks up an object and transforms it <END_TASK> <USER_TASK:> Description: def to_string(self, obj): """ Picks up an object and transforms it into a string, by coercing each element in an iterable to a string and then joining them, or by trying to coerce the object directly """
try: converted = [str(element) for element in obj] string = ','.join(converted) except TypeError: # for now this is ok for booleans string = str(obj) return string
<SYSTEM_TASK:> Makes a get request by construction <END_TASK> <USER_TASK:> Description: def filter(self, endpoint, params): """ Makes a get request by construction the path from an endpoint and a dict with filter query params e.g. params = {'category__in': [1,2]} response = self.client.filter('/experiences/', params) """
params = self.parse_params(params) params = urlencode(params) path = '{0}?{1}'.format(endpoint, params) return self.get(path)
<SYSTEM_TASK:> Checks if the given attribute name is a entity attribute of the given <END_TASK> <USER_TASK:> Description: def is_domain_class_member_attribute(ent, attr_name): """ Checks if the given attribute name is a entity attribute of the given registered resource. """
attr = get_domain_class_attribute(ent, attr_name) return attr.kind == RESOURCE_ATTRIBUTE_KINDS.MEMBER
<SYSTEM_TASK:> Checks if the given attribute name is a aggregate attribute of the given <END_TASK> <USER_TASK:> Description: def is_domain_class_collection_attribute(ent, attr_name): """ Checks if the given attribute name is a aggregate attribute of the given registered resource. """
attr = get_domain_class_attribute(ent, attr_name) return attr.kind == RESOURCE_ATTRIBUTE_KINDS.COLLECTION
<SYSTEM_TASK:> Set user password with hash <END_TASK> <USER_TASK:> Description: def set_password(self, password): """ Set user password with hash """
self.password = Security.hash(password) self.save()
<SYSTEM_TASK:> Create a password reset request in the user_password_resets <END_TASK> <USER_TASK:> Description: def create_password_reset(cls, email, valid_for=3600) -> str: """ Create a password reset request in the user_password_resets database table. Hashed code gets stored in the database. Returns unhashed reset code """
user = cls.where_email(email) if user is None: return None PasswordResetModel.delete_where_user_id(user.id) token = JWT().create_token({ 'code': Security.random_string(5), # make unique 'user_id': user.id}, token_valid_for=valid_for) code = Security.generate_uuid(1) + "-" + Security.random_string(5) password_reset_model = PasswordResetModel() password_reset_model.token = token password_reset_model.code = code password_reset_model.user_id = user.id password_reset_model.save() return code
<SYSTEM_TASK:> Validates an unhashed code against a hashed code. <END_TASK> <USER_TASK:> Description: def validate_password_reset(cls, code, new_password): """ Validates an unhashed code against a hashed code. Once the code has been validated and confirmed new_password will replace the old users password """
password_reset_model = \ PasswordResetModel.where_code(code) if password_reset_model is None: return None jwt = JWT() if jwt.verify_token(password_reset_model.token): user = cls.where_id(jwt.data['data']['user_id']) if user is not None: user.set_password(new_password) PasswordResetModel.delete_where_user_id(user.id) return user password_reset_model.delete() # delete expired/invalid token return None
<SYSTEM_TASK:> View representation of the object <END_TASK> <USER_TASK:> Description: def response(self, callback=None): """ View representation of the object :param callback: Function to represent the error in view. Default : flask.jsonify :type callback: function :return: View """
if not callback: callback = type(self).AdvancedJsonify resp = { "status": "error", "message": self.message } if self.step: resp["step"] = self.step self.LOGGER.error(self.message, extra={"step": self.step, "context": self.context}) return callback(resp, status_code=self.code)
<SYSTEM_TASK:> Using the exclude lists, convert fields to a string. <END_TASK> <USER_TASK:> Description: def __json(self): """ Using the exclude lists, convert fields to a string. """
if self.exclude_list is None: self.exclude_list = [] fields = {} for key, item in vars(self).items(): if hasattr(self, '_sa_instance_state'): # load only deferred objects if len(orm.attributes.instance_state(self).unloaded) > 0: mapper = inspect(self) for column in mapper.attrs: column.key column.value if str(key).startswith('_') or key in self.exclude_list: continue fields[key] = item obj = Json.safe_object(fields) return str(obj)
<SYSTEM_TASK:> Manages the given entity under the given Unit Of Work. <END_TASK> <USER_TASK:> Description: def manage(cls, entity, unit_of_work): """ Manages the given entity under the given Unit Of Work. If `entity` is already managed by the given Unit Of Work, nothing is done. :raises ValueError: If the given entity is already under management by a different Unit Of Work. """
if hasattr(entity, '__everest__'): if not unit_of_work is entity.__everest__.unit_of_work: raise ValueError('Trying to register an entity that has been ' 'registered with another session!') else: entity.__everest__ = cls(entity, unit_of_work)
<SYSTEM_TASK:> Releases the given entity from management under the given Unit Of <END_TASK> <USER_TASK:> Description: def release(cls, entity, unit_of_work): """ Releases the given entity from management under the given Unit Of Work. :raises ValueError: If `entity` is not managed at all or is not managed by the given Unit Of Work. """
if not hasattr(entity, '__everest__'): raise ValueError('Trying to unregister an entity that has not ' 'been registered yet!') elif not unit_of_work is entity.__everest__.unit_of_work: raise ValueError('Trying to unregister an entity that has been ' 'registered with another session!') delattr(entity, '__everest__')
<SYSTEM_TASK:> Returns the state data for the given entity. <END_TASK> <USER_TASK:> Description: def get_state_data(cls, entity): """ Returns the state data for the given entity. This also works for unmanaged entities. """
attrs = get_domain_class_attribute_iterator(type(entity)) return dict([(attr, get_nested_attribute(entity, attr.entity_attr)) for attr in attrs if not attr.entity_attr is None])
<SYSTEM_TASK:> Sets the state data for the given entity to the given data. <END_TASK> <USER_TASK:> Description: def set_state_data(cls, entity, data): """ Sets the state data for the given entity to the given data. This also works for unmanaged entities. """
attr_names = get_domain_class_attribute_names(type(entity)) nested_items = [] for attr, new_attr_value in iteritems_(data): if not attr.entity_attr in attr_names: raise ValueError('Can not set attribute "%s" for entity ' '"%s".' % (attr.entity_attr, entity)) if '.' in attr.entity_attr: nested_items.append((attr, new_attr_value)) continue else: setattr(entity, attr.entity_attr, new_attr_value) for attr, new_attr_value in nested_items: try: set_nested_attribute(entity, attr.entity_attr, new_attr_value) except AttributeError as exc: if not new_attr_value is None: raise exc
<SYSTEM_TASK:> Transfers instance state data from the given source entity to the <END_TASK> <USER_TASK:> Description: def transfer_state_data(cls, source_entity, target_entity): """ Transfers instance state data from the given source entity to the given target entity. """
state_data = cls.get_state_data(source_entity) cls.set_state_data(target_entity, state_data)
<SYSTEM_TASK:> Sets the given state data on the given entity of the given class. <END_TASK> <USER_TASK:> Description: def __set_data(self, data): """ Sets the given state data on the given entity of the given class. :param data: State data to set. :type data: Dictionary mapping attributes to attribute values. :param entity: Entity to receive the state data. """
ent = self.__entity_ref() self.set_state_data(ent, data)
<SYSTEM_TASK:> Print the previous and current line with line numbers and <END_TASK> <USER_TASK:> Description: def pretty_print(self, carrot=True): """Print the previous and current line with line numbers and a carret under the current character position. Will also print a message if one is given to this exception. """
output = ['\n'] output.extend([line.pretty_print() for line in self.partpyobj.get_surrounding_lines(1, 0)]) if carrot: output.append('\n' + (' ' * (self.partpyobj.col + 5)) + '^' + '\n') if self.partpymsg: output.append(self.partpymsg) return ''.join(output)
<SYSTEM_TASK:> Given a string containing an nginx upstream section, return the pool name <END_TASK> <USER_TASK:> Description: def str_to_pool(upstream): """ Given a string containing an nginx upstream section, return the pool name and list of nodes. """
name = re.search('upstream +(.*?) +{', upstream).group(1) nodes = re.findall('server +(.*?);', upstream) return name, nodes
<SYSTEM_TASK:> Calculate the vertical swimming speed of this behavior. <END_TASK> <USER_TASK:> Description: def calculate_vss(self, method=None): """ Calculate the vertical swimming speed of this behavior. Takes into account the vertical swimming speed and the variance. Parameters: method: "gaussian" (default) or "random" "random" (vss - variance) < X < (vss + variance) """
if self.variance == float(0): return self.vss else: # Calculate gausian distribution and return if method == "gaussian" or method is None: return gauss(self.vss, self.variance) elif method == "random": return uniform(self.vss - self.variance, self.vss + self.variance) else: raise ValueError("Method of vss calculation not recognized, please use 'gaussian' or 'random'")
<SYSTEM_TASK:> Check the signal type of the experiment <END_TASK> <USER_TASK:> Description: def _check_experiment(self, name): """Check the signal type of the experiment Returns ------- True, if the signal type is supported, False otherwise Raises ------ Warning if the signal type is not supported """
with h5py.File(name=self.path, mode="r") as h5: sigpath = "/Experiments/{}/metadata/Signal".format(name) signal_type = h5[sigpath].attrs["signal_type"] if signal_type != "hologram": msg = "Signal type '{}' not supported: {}[{}]".format(signal_type, self.path, name) warnings.warn(msg, WrongSignalTypeWarnging) return signal_type == "hologram"
<SYSTEM_TASK:> Get all experiments from the hdf5 file <END_TASK> <USER_TASK:> Description: def _get_experiments(self): """Get all experiments from the hdf5 file"""
explist = [] with h5py.File(name=self.path, mode="r") as h5: if "Experiments" not in h5: msg = "Group 'Experiments' not found in {}.".format(self.path) raise HyperSpyNoDataFoundError(msg) for name in h5["Experiments"]: # check experiment if self._check_experiment(name): explist.append(name) explist.sort() if not explist: # if this error is raised, the signal_type is probably not # set to "hologram". msg = "No supported data found: {}".format(self.path) raise HyperSpyNoDataFoundError(msg) return explist
<SYSTEM_TASK:> Verify that `path` has the HyperSpy file format <END_TASK> <USER_TASK:> Description: def verify(path): """Verify that `path` has the HyperSpy file format"""
valid = False try: h5 = h5py.File(path, mode="r") except (OSError, IsADirectoryError): pass else: if ("file_format" in h5.attrs and h5.attrs["file_format"].lower() == "hyperspy" and "Experiments" in h5): valid = True return valid
<SYSTEM_TASK:> Removes the last traversal path node from this traversal path. <END_TASK> <USER_TASK:> Description: def pop(self): """ Removes the last traversal path node from this traversal path. """
node = self.nodes.pop() self.__keys.remove(node.key)
<SYSTEM_TASK:> Returns the proxy from the last node visited on the path, or `None`, <END_TASK> <USER_TASK:> Description: def parent(self): """ Returns the proxy from the last node visited on the path, or `None`, if no node has been visited yet. """
if len(self.nodes) > 0: parent = self.nodes[-1].proxy else: parent = None return parent
<SYSTEM_TASK:> Returns the relation operation from the last node visited on the <END_TASK> <USER_TASK:> Description: def relation_operation(self): """ Returns the relation operation from the last node visited on the path, or `None`, if no node has been visited yet. """
if len(self.nodes) > 0: rel_op = self.nodes[-1].relation_operation else: rel_op = None return rel_op
<SYSTEM_TASK:> u"""helper to ensure that text passed to WriteConsoleW is unicode <END_TASK> <USER_TASK:> Description: def ensure_unicode(text): u"""helper to ensure that text passed to WriteConsoleW is unicode"""
if isinstance(text, str): try: return text.decode(pyreadline_codepage, u"replace") except (LookupError, TypeError): return text.decode(u"ascii", u"replace") return text
<SYSTEM_TASK:> unwraps the callback and returns the raw content <END_TASK> <USER_TASK:> Description: def unwrap_raw(content): """ unwraps the callback and returns the raw content """
starting_symbol = get_start_symbol(content) ending_symbol = ']' if starting_symbol == '[' else '}' start = content.find(starting_symbol, 0) end = content.rfind(ending_symbol) return content[start:end+1]
<SYSTEM_TASK:> Combine word list into a bag-of-words. <END_TASK> <USER_TASK:> Description: def combine_word_list(word_list): """ Combine word list into a bag-of-words. Input: - word_list: This is a python list of strings. Output: - bag_of_words: This is the corresponding multi-set or bag-of-words, in the form of a python dictionary. """
bag_of_words = collections.defaultdict(int) for word in word_list: bag_of_words[word] += 1 return bag_of_words
<SYSTEM_TASK:> Reduces a number of keyword sets to a bag-of-words. <END_TASK> <USER_TASK:> Description: def reduce_list_of_bags_of_words(list_of_keyword_sets): """ Reduces a number of keyword sets to a bag-of-words. Input: - list_of_keyword_sets: This is a python list of sets of strings. Output: - bag_of_words: This is the corresponding multi-set or bag-of-words, in the form of a python dictionary. """
bag_of_words = dict() get_bag_of_words_keys = bag_of_words.keys for keyword_set in list_of_keyword_sets: for keyword in keyword_set: if keyword in get_bag_of_words_keys(): bag_of_words[keyword] += 1 else: bag_of_words[keyword] = 1 return bag_of_words
<SYSTEM_TASK:> Checks whether a target word is within editing distance of any one in a set of keywords. <END_TASK> <USER_TASK:> Description: def query_list_of_words(target_word, list_of_words, edit_distance=1): """ Checks whether a target word is within editing distance of any one in a set of keywords. Inputs: - target_word: A string containing the word we want to search in a list. - list_of_words: A python list of words. - edit_distance: For larger words, we also check for similar words based on edit_distance. Outputs: - new_list_of_words: This is the input list of words minus any found keywords. - found_list_of_words: This is the list of words that are within edit distance of the target word. """
# Initialize lists new_list_of_words = list() found_list_of_words = list() append_left_keyword = new_list_of_words.append append_found_keyword = found_list_of_words.append # Iterate over the list of words for word in list_of_words: if len(word) > 6: effective_edit_distance = edit_distance else: effective_edit_distance = 0 # No edit distance for small words. if abs(len(word)-len(target_word)) <= effective_edit_distance: if nltk.edit_distance(word, target_word) <= effective_edit_distance: append_found_keyword(word) else: append_left_keyword(word) else: append_left_keyword(word) return new_list_of_words, found_list_of_words
<SYSTEM_TASK:> Cache JSONAttributes data on instance and vice versa for convenience. <END_TASK> <USER_TASK:> Description: def fixup_instance(sender, **kwargs): """ Cache JSONAttributes data on instance and vice versa for convenience. """
instance = kwargs['instance'] for model_field in instance._meta.fields: if not isinstance(model_field, JSONAttributeField): continue if hasattr(instance, '_attr_field'): raise FieldError('multiple JSONAttributeField fields: ' 'only one is allowed per model!') field_name = model_field.name attrs = getattr(instance, field_name) # ensure JSONAttributeField's data is of JSONAttributes type if not isinstance(attrs, JSONAttributes): setattr(instance, field_name, JSONAttributes(attrs)) attrs = getattr(instance, field_name) # Cache model instance on JSONAttributes instance and vice-versa attrs._instance = instance attrs._get_from_instance = functools.partial( getattr, instance, field_name) instance._attr_field = attrs if not hasattr(instance, '_attr_field'): raise FieldError('missing JSONAttributeField field in ' 'fixup_instance decorator')
<SYSTEM_TASK:> Recursively find size of a tree. Slow. <END_TASK> <USER_TASK:> Description: def size(self): """ Recursively find size of a tree. Slow. """
if self is NULL: return 0 return 1 + self.left.size() + self.right.size()
<SYSTEM_TASK:> Find a value in a node, using a key function. The value is already a <END_TASK> <USER_TASK:> Description: def find_prekeyed(self, value, key): """ Find a value in a node, using a key function. The value is already a key. """
while self is not NULL: direction = cmp(value, key(self.value)) if direction < 0: self = self.left elif direction > 0: self = self.right elif direction == 0: return self.value
<SYSTEM_TASK:> Rotate the node to the left. <END_TASK> <USER_TASK:> Description: def rotate_left(self): """ Rotate the node to the left. """
right = self.right new = self._replace(right=self.right.left, red=True) top = right._replace(left=new, red=self.red) return top
<SYSTEM_TASK:> Flip colors of a node and its children. <END_TASK> <USER_TASK:> Description: def flip(self): """ Flip colors of a node and its children. """
left = self.left._replace(red=not self.left.red) right = self.right._replace(red=not self.right.red) top = self._replace(left=left, right=right, red=not self.red) return top
<SYSTEM_TASK:> Balance a node. <END_TASK> <USER_TASK:> Description: def balance(self): """ Balance a node. The balance is inductive and relies on all subtrees being balanced recursively or by construction. If the subtrees are not balanced, then this will not fix them. """
# Always lean left with red nodes. if self.right.red: self = self.rotate_left() # Never permit red nodes to have red children. Note that if the left-hand # node is NULL, it will short-circuit and fail this test, so we don't have # to worry about a dereference here. if self.left.red and self.left.left.red: self = self.rotate_right() # Finally, move red children on both sides up to the next level, reducing # the total redness. if self.left.red and self.right.red: self = self.flip() return self
<SYSTEM_TASK:> Insert a value into a tree rooted at the given node, and return <END_TASK> <USER_TASK:> Description: def insert(self, value, key): """ Insert a value into a tree rooted at the given node, and return whether this was an insertion or update. Balances the tree during insertion. An update is performed instead of an insertion if a value in the tree compares equal to the new value. """
# Base case: Insertion into the empty tree is just creating a new node # with no children. if self is NULL: return Node(value, NULL, NULL, True), True # Recursive case: Insertion into a non-empty tree is insertion into # whichever of the two sides is correctly compared. direction = cmp(key(value), key(self.value)) if direction < 0: left, insertion = self.left.insert(value, key) self = self._replace(left=left) elif direction > 0: right, insertion = self.right.insert(value, key) self = self._replace(right=right) elif direction == 0: # Exact hit on an existing node (this node, in fact). In this # case, perform an update. self = self._replace(value=value) insertion = False # And balance on the way back up. return self.balance(), insertion
<SYSTEM_TASK:> Shuffle red to the left of a tree. <END_TASK> <USER_TASK:> Description: def move_red_left(self): """ Shuffle red to the left of a tree. """
self = self.flip() if self.right is not NULL and self.right.left.red: self = self._replace(right=self.right.rotate_right()) self = self.rotate_left().flip() return self
<SYSTEM_TASK:> Shuffle red to the right of a tree. <END_TASK> <USER_TASK:> Description: def move_red_right(self): """ Shuffle red to the right of a tree. """
self = self.flip() if self.left is not NULL and self.left.left.red: self = self.rotate_right().flip() return self
<SYSTEM_TASK:> Delete the left-most value from a tree. <END_TASK> <USER_TASK:> Description: def delete_min(self): """ Delete the left-most value from a tree. """
# Base case: If there are no nodes lesser than this node, then this is the # node to delete. if self.left is NULL: return NULL, self.value # Acquire more reds if necessary to continue the traversal. The # double-deep check is fine because NULL is red. if not self.left.red and not self.left.left.red: self = self.move_red_left() # Recursive case: Delete the minimum node of all nodes lesser than this # node. left, value = self.left.delete_min() self = self._replace(left=left) return self.balance(), value
<SYSTEM_TASK:> Delete the right-most value from a tree. <END_TASK> <USER_TASK:> Description: def delete_max(self): """ Delete the right-most value from a tree. """
# Attempt to rotate left-leaning reds to the right. if self.left.red: self = self.rotate_right() # Base case: If there are no selfs greater than this self, then this is # the self to delete. if self.right is NULL: return NULL, self.value # Acquire more reds if necessary to continue the traversal. NULL is # red so this check doesn't need to check for NULL. if not self.right.red and not self.right.left.red: self = self.move_red_right() # Recursive case: Delete the maximum self of all selfs greater than this # self. right, value = self.right.delete_max() self = self._replace(right=right) return self.balance(), value
<SYSTEM_TASK:> Delete a value from a tree. <END_TASK> <USER_TASK:> Description: def delete(self, value, key): """ Delete a value from a tree. """
# Base case: The empty tree cannot possibly have the desired value. if self is NULL: raise KeyError(value) direction = cmp(key(value), key(self.value)) # Because we lean to the left, the left case stands alone. if direction < 0: if (not self.left.red and self.left is not NULL and not self.left.left.red): self = self.move_red_left() # Delete towards the left. left = self.left.delete(value, key) self = self._replace(left=left) else: # If we currently lean to the left, lean to the right for now. if self.left.red: self = self.rotate_right() # Best case: The node on our right (which we just rotated there) is a # red link and also we were just holding the node to delete. In that # case, we just rotated NULL into our current node, and the node to # the right is the lone matching node to delete. if direction == 0 and self.right is NULL: return NULL # No? Okay. Move more reds to the right so that we can continue to # traverse in that direction. At *this* spot, we do have to confirm # that node.right is not NULL... if (not self.right.red and self.right is not NULL and not self.right.left.red): self = self.move_red_right() if direction > 0: # Delete towards the right. right = self.right.delete(value, key) self = self._replace(right=right) else: # Annoying case: The current node was the node to delete all # along! Use a right-handed minimum deletion. First find the # replacement value to rebuild the current node with, then delete # the replacement value from the right-side tree. Finally, create # the new node with the old value replaced and the replaced value # deleted. rnode = self.right while rnode is not NULL: rnode = rnode.left right, replacement = self.right.delete_min() self = self._replace(value=replacement, right=right) return self.balance()
<SYSTEM_TASK:> Remove the maximum value and return it. <END_TASK> <USER_TASK:> Description: def pop_max(self): """ Remove the maximum value and return it. """
if self.root is NULL: raise KeyError("pop from an empty blackjack") self.root, value = self.root.delete_max() self._len -= 1 return value
<SYSTEM_TASK:> Remove the minimum value and return it. <END_TASK> <USER_TASK:> Description: def pop_min(self): """ Remove the minimum value and return it. """
if self.root is NULL: raise KeyError("pop from an empty blackjack") self.root, value = self.root.delete_min() self._len -= 1 return value
<SYSTEM_TASK:> Class decorator for inheriting docstrings. <END_TASK> <USER_TASK:> Description: def inherit_docstrings(cls): """Class decorator for inheriting docstrings. Automatically inherits base class doc-strings if not present in the derived class. """
@functools.wraps(cls) def _inherit_docstrings(cls): if not isinstance(cls, (type, colorise.compat.ClassType)): raise RuntimeError("Type is not a class") for name, value in colorise.compat.iteritems(vars(cls)): if isinstance(getattr(cls, name), types.MethodType): if not getattr(value, '__doc__', None): for base in cls.__bases__: basemethod = getattr(base, name, None) if basemethod and getattr(base, '__doc__', None): value.__doc__ = basemethod.__doc__ return cls return _inherit_docstrings(cls)
<SYSTEM_TASK:> Upload the build documentation site to LSST the Docs. <END_TASK> <USER_TASK:> Description: def upload(config): """Upload the build documentation site to LSST the Docs. Parameters ---------- config : `lander.config.Configuration` Site configuration, which includes upload information and credentials. """
token = get_keeper_token(config['keeper_url'], config['keeper_user'], config['keeper_password']) build_resource = register_build(config, token) ltdconveyor.upload_dir( build_resource['bucket_name'], build_resource['bucket_root_dir'], config['build_dir'], aws_access_key_id=config['aws_id'], aws_secret_access_key=config['aws_secret'], surrogate_key=build_resource['surrogate_key'], cache_control='max-age=31536000', surrogate_control=None, upload_dir_redirect_objects=True) confirm_build(config, token, build_resource)
<SYSTEM_TASK:> Get a temporary auth token from LTD Keeper. <END_TASK> <USER_TASK:> Description: def get_keeper_token(base_url, username, password): """Get a temporary auth token from LTD Keeper."""
token_endpoint = base_url + '/token' r = requests.get(token_endpoint, auth=(username, password)) if r.status_code != 200: raise RuntimeError('Could not authenticate to {0}: error {1:d}\n{2}'. format(base_url, r.status_code, r.json())) return r.json()['token']
<SYSTEM_TASK:> Return a unique identifier for the background data <END_TASK> <USER_TASK:> Description: def _compute_bgid(self, bg=None): """Return a unique identifier for the background data"""
if bg is None: bg = self._bgdata if isinstance(bg, qpimage.QPImage): # Single QPImage if "identifier" in bg: return bg["identifier"] else: data = [bg.amp, bg.pha] for key in sorted(list(bg.meta.keys())): val = bg.meta[key] data.append("{}={}".format(key, val)) return hash_obj(data) elif (isinstance(bg, list) and isinstance(bg[0], qpimage.QPImage)): # List of QPImage data = [] for bgii in bg: data.append(self._compute_bgid(bgii)) return hash_obj(data) elif (isinstance(bg, SeriesData) and (len(bg) == 1 or len(bg) == len(self))): # DataSet return bg.identifier else: raise ValueError("Unknown background data type: {}".format(bg))
<SYSTEM_TASK:> Return a unique identifier for the given data set <END_TASK> <USER_TASK:> Description: def identifier(self): """Return a unique identifier for the given data set"""
if self.background_identifier is None: idsum = self._identifier_data() else: idsum = hash_obj([self._identifier_data(), self.background_identifier]) return idsum
<SYSTEM_TASK:> Return time of data at index `idx` <END_TASK> <USER_TASK:> Description: def get_time(self, idx): """Return time of data at index `idx` Returns nan if the time is not defined"""
# raw data qpi = self.get_qpimage_raw(idx) if "time" in qpi.meta: thetime = qpi.meta["time"] else: thetime = np.nan return thetime
<SYSTEM_TASK:> Set background data <END_TASK> <USER_TASK:> Description: def set_bg(self, dataset): """Set background data Parameters ---------- dataset: `DataSet`, `qpimage.QPImage`, or int If the ``len(dataset)`` matches ``len(self)``, then background correction is performed element-wise. Otherwise, ``len(dataset)`` must be one and is used for all data of ``self``. See Also -------- get_qpimage: obtain the background corrected QPImage """
if isinstance(dataset, qpimage.QPImage): # Single QPImage self._bgdata = [dataset] elif (isinstance(dataset, list) and len(dataset) == len(self) and isinstance(dataset[0], qpimage.QPImage)): # List of QPImage self._bgdata = dataset elif (isinstance(dataset, SeriesData) and (len(dataset) == 1 or len(dataset) == len(self))): # DataSet self._bgdata = dataset else: raise ValueError("Bad length or type for bg: {}".format(dataset)) self.background_identifier = self._compute_bgid()
<SYSTEM_TASK:> Time of the data <END_TASK> <USER_TASK:> Description: def get_time(self, idx=0): """Time of the data Returns nan if the time is not defined """
thetime = super(SingleData, self).get_time(idx=0) return thetime
<SYSTEM_TASK:> Add a 'do' action to the steps. This is a function to execute <END_TASK> <USER_TASK:> Description: def do(self, fn, message=None, *args, **kwargs): """Add a 'do' action to the steps. This is a function to execute :param fn: A function :param message: Message indicating what this function does (used for debugging if assertions fail) """
self.items.put(ChainItem(fn, self.do, message, *args, **kwargs)) return self
<SYSTEM_TASK:> Add an 'assertion' action to the steps. This will evaluate the return value of the last 'do' step and <END_TASK> <USER_TASK:> Description: def expect(self, value, message='Failed: "{actual} {operator} {expected}" after step "{step}"', operator='=='): """Add an 'assertion' action to the steps. This will evaluate the return value of the last 'do' step and compare it to the value passed here using the specified operator. Checks that the first function will return 2 >>> AssertionChain().do(lambda: 1 + 1, 'add 1 + 1').expect(2) This will check that your function does not return None >>> AssertionChain().do(lambda: myfunction(), 'call my function').expect(None, operator='is not') :param value: The expected value :param message: The error message to raise if the assertion fails. You can access the variables: {actual} -- The actual value {expected} -- The expected value {step} -- The step just performed, which did not meet the expectation {operator} -- The operator used to make the comparison """
if operator not in self.valid_operators: raise ValueError('Illegal operator specified for ') self.items.put(ChainItem(value, self.expect, message, operator=operator)) return self
<SYSTEM_TASK:> Runs through all of the steps in the chain and runs each of them in sequence. <END_TASK> <USER_TASK:> Description: def perform(self): """Runs through all of the steps in the chain and runs each of them in sequence. :return: The value from the lat "do" step performed """
last_value = None last_step = None while self.items.qsize(): item = self.items.get() if item.flag == self.do: last_value = item.item(*item.args, **item.kwargs) last_step = item.message elif item.flag == self.expect: message = item.message local = {'value': last_value, 'expectation': item.item} expression = 'value {operator} expectation'.format(operator=item.operator) result = eval(expression, local) # Format the error message format_vars = { 'actual': last_value, 'expected': item.item, 'step': last_step, 'operator': item.operator } for var, val in format_vars.iteritems(): message = message.replace('{' + str(var) + '}', str(val)) assert result, message return last_value
<SYSTEM_TASK:> Return a list of all Volumes in this Storage Pool <END_TASK> <USER_TASK:> Description: def get_volumes(self): """ Return a list of all Volumes in this Storage Pool """
vols = [self.find_volume(name) for name in self.virsp.listVolumes()] return vols
<SYSTEM_TASK:> Returns the value of the specified attribute converted to a <END_TASK> <USER_TASK:> Description: def get_terminal_converted(self, attr): """ Returns the value of the specified attribute converted to a representation value. :param attr: Attribute to retrieve. :type attr: :class:`everest.representers.attributes.MappedAttribute` :returns: Representation string. """
value = self.data.get(attr.repr_name) return self.converter_registry.convert_to_representation( value, attr.value_type)