Example #1
1
    def remove(self, item):
        """
        Remove an element from an OrderedSet; it must be a member.

        If the element is not a member, raise a KeyError.
        """
        OrderedDict.__delitem__(self, item)
Example #2
1
    def __delete_main(self, keys):
        """ Delete items for indexing. """
        for k in keys:

            if k[-1] is "/":
                files_count -= 1
            kpart1, kpart2 = self.__get_dir_component(k)
            if kpart1 is not None:
                next_index = dict.__getitem__(self, kpart1)
                if next_index is None:
                    raise KeyError(k)
                next_index.__delitem__(kpart2)
            else:
                if k[-1] is "/":
                    temp_index = dict.__getitem__(new_index, file_key)
                    if type(temp_index) is Index:
                        files_count -= len(temp_index)
                OrderedDict.__delitem__(self, k)
                # self._list = None
                if self._list != None:
                    self._list.remove(k)
                self._full_key_list = None

            self._nfiles -= 1
        assert self._nfiles >= 0
Example #3
1
 def __delitem__(self, key):
     """
	>>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
	>>> del(T['B', 'A'])
	>>> T
	{('A', 'B'): 0.3, ('A', 'A'): 0.7}
	"""
     OrderedDict.__delitem__(self, key)
Example #4
1
    def discard(self, item):
        """
        Remove an element from an OrderedSet if it is a member.

        If the element is not a member, do nothing.
        """
        try:
            OrderedDict.__delitem__(self, item)
        except KeyError:
            pass
    def __delattr__(self, attribute):
        """
		This method deletes both key and sibling attribute.

		:param attribute.: Attribute. ( Object )
		"""

        if hasattr(self, "_OrderedDict__root") and hasattr(self, "_OrderedDict__map"):
            if self._OrderedDict__root:
                OrderedDict.__delitem__(self, attribute)
        OrderedDict.__delattr__(self, attribute)
    def __delitem__(self, key, *args, **kwargs):
        """
		This method deletes both key and sibling attribute.

		:param key.: Key. ( Object )
		:param \*args: Arguments. ( \* )
		:param \*\*kwargs: Key / Value pairs. ( Key / Value pairs )
		"""

        OrderedDict.__delitem__(self, key, *args, **kwargs)
        OrderedDict.__delattr__(self, key)
Example #7
1
class Metadata(MutableMapping):
    def __init__(self, seq=None):
        self.dct = OrderedDict(seq) if seq else OrderedDict()

    def __contains__(self, key):
        return self.dct.__contains__(key)

    def __getitem__(self, key):
        return self.dct.__getitem__(key)

    def __setitem__(self, key, value):
        self.dct.__setitem__(key, value)

    def __delitem__(self, key):
        return self.dct.__delitem__(key)

    def __iter__(self):
        return self.dct.__iter__()

    def __len__(self):
        return self.dct.__len__()

    def __repr__(self):
        return repr(self.dct)

    def __str__(self):
        return str(self.dct)
Example #8
1
class Buckets(object):
    """Proxy for OrderedDict"""

    def __init__(self, *args, **kwargs):
        self._od = OrderedDict(*args, **kwargs)

    def __getattr__(self, a):
        return getattr(self._od, a)

    def __setitem__(self, *args, **kwargs):
        return self._od.__setitem__(*args, **kwargs)

    def __getitem__(self, *args, **kwargs):
        return self._od.__getitem__(*args, **kwargs)

    def __delitem__(self, *args, **kwargs):
        return self._od.__delitem__(*args, **kwargs)

    def __eq__(self, other):
        if isinstance(other, Buckets):
            return self._od.__eq__(other._od)
        else:
            return self._od.__eq__(other)

    def copy(self, *args, **kwargs):
        new = Buckets()
        new._od = self._od.copy()
        return new
Example #9
1
class MetafeatureFunctions(object):
    def __init__(self):
        self.functions = OrderedDict()
        self.dependencies = OrderedDict()
        self.values = OrderedDict()

    def clear(self):
        self.values = OrderedDict()

    def __iter__(self):
        return self.functions.__iter__()

    def __getitem__(self, item):
        return self.functions.__getitem__(item)

    def __setitem__(self, key, value):
        return self.functions.__setitem__(key, value)

    def __delitem__(self, key):
        return self.functions.__delitem__(key)

    def __contains__(self, item):
        return self.functions.__contains__(item)

    def get_value(self, key):
        return self.values[key].value

    def set_value(self, key, item):
        self.values[key] = item

    def is_calculated(self, key):
        """Return if a helper function has already been executed.

        Necessary as get_value() can return None if the helper function hasn't
        been executed or if it returned None."""
        return key in self.values

    def get_dependency(self, name):
        """Return the dependency of metafeature "name".
        """
        return self.dependencies.get(name)

    def define(self, name, dependency=None):
        """Decorator for adding metafeature functions to a "dictionary" of
        metafeatures. This behaves like a function decorating a function,
        not a class decorating a function"""

        def wrapper(metafeature_class):
            instance = metafeature_class()
            self.__setitem__(name, instance)
            self.dependencies[name] = dependency
            return instance

        return wrapper
Example #10
1
class BaseCache(object):
    """
    BaseCache is a class that saves and operates on an OrderedDict. It has a
    certain capacity, stored in the attribute `maxsize`. Whether this
    capacity is reached, can be checked by using the boolean property
    `is_full`. To implement a custom cache, inherit from this class and
    override the methods ``__getitem__`` and ``__setitem__``.
    Call the method `sunpy.database.caching.BaseCache.callback` as soon
    as an item from the cache is removed.
    """

    def __init__(self, maxsize=float("inf")):
        self.maxsize = maxsize
        self._dict = OrderedDict()

    def get(self, key, default=None):  # pragma: no cover
        """Return the corresponding value to `key` if `key` is in the cache,
        `default` otherwise. This method has no side-effects, multiple calls
        with the same cache and the same passed key must always return the same
        value.

        """
        try:
            return self._dict[key]
        except KeyError:
            return default

    @abstractmethod
    def __getitem__(self, key):
        """abstract method: this method must be overwritten by inheriting
        subclasses. It defines what happens if an item from the cache is
        attempted to be accessed.

        """
        return  # pragma: no cover

    @abstractmethod
    def __setitem__(self, key, value):
        """abstract method: this method must be overwritten by inheriting
        subclasses. It defines what happens if a new value should be assigned
        to the given key. If the given key does already exist in the cache or
        not must be checked by the person who implements this method.
        """

    @abstractproperty
    def to_be_removed(self):
        """The item that will be removed on the next
        :meth:`sunpy.database.caching.BaseCache.remove` call.

        """

    @abstractmethod
    def remove(self):
        """Call this method to manually remove one item from the cache. Which
        item is removed, depends on the implementation of the cache. After the
        item has been removed, the callback method is called.

        """

    def callback(self, key, value):
        """This method should be called (by convention) if an item is removed
        from the cache because it is full. The passed key and value are the
        ones that are removed. By default this method does nothing, but it
        can be customized in a custom cache that inherits from this base class.

        """

    @property
    def is_full(self):
        """True if the number of items in the cache equals :attr:`maxsize`,
        False otherwise.

        """
        return len(self._dict) == self.maxsize

    def __delitem__(self, key):
        self._dict.__delitem__(key)

    def __contains__(self, key):
        return key in self._dict.keys()

    def __len__(self):
        return len(self._dict)

    def __iter__(self):
        for key in self._dict.__iter__():
            yield key

    def __reversed__(self):  # pragma: no cover
        for key in self._dict.__reversed__():
            yield key

    def clear(self):  # pragma: no cover
        return self._dict.clear()

    def keys(self):  # pragma: no cover
        return list(self._dict.keys())

    def values(self):  # pragma: no cover
        return list(self._dict.values())

    def items(self):  # pragma: no cover
        return list(self._dict.items())

    def iterkeys(self):  # pragma: no cover
        return iter(self._dict.keys())

    def itervalues(self):  # pragma: no cover
        for value in self._dict.values():
            yield value

    def iteritems(self):  # pragma: no cover
        for key, value in six.iteritems(self._dict):
            yield key, value

    def update(self, *args, **kwds):  # pragma: no cover
        self._dict.update(*args, **kwds)

    def pop(self, key, default=MutableMapping._MutableMapping__marker):  # pragma: no cover
        return self._dict.pop(key, default)

    def setdefault(self, key, default=None):  # pragma: no cover
        return self._dict.setdefault(key, default)

    def popitem(self, last=True):  # pragma: no cover
        return self._dict.popitem(last)

    def __reduce__(self):  # pragma: no cover
        return self._dict.__reduce__()

    def copy(self):  # pragma: no cover
        return self._dict.copy()

    def __eq__(self, other):  # pragma: no cover
        return self._dict.__eq__(other)

    def __ne__(self, other):  # pragma: no cover
        return self._dict.__ne__(other)

    def viewkeys(self):  # pragma: no cover
        return self._dict.keys()

    def viewvalues(self):  # pragma: no cover
        return self._dict.values()

    def viewitems(self):  # pragma: no cover
        return self._dict.items()

    @classmethod
    def fromkeys(cls, iterable, value=None):  # pragma: no cover
        return OrderedDict.fromkeys(iterable, value)

    def __repr__(self):  # pragma: no cover
        return "{0}({1!r})".format(self.__class__.__name__, dict(self._dict))
Example #11
1
class DotMap(MutableMapping, OrderedDict):
    def __init__(self, *args, **kwargs):
        self._map = OrderedDict()
        self._dynamic = True
        if kwargs:
            if "_dynamic" in kwargs:
                self._dynamic = kwargs["_dynamic"]
        if args:
            d = args[0]
            if isinstance(d, dict):
                for k, v in self.__call_items(d):
                    if type(v) is dict:
                        v = DotMap(v, _dynamic=self._dynamic)
                    if type(v) is list:
                        l = []
                        for i in v:
                            n = i
                            if type(i) is dict:
                                n = DotMap(i, _dynamic=self._dynamic)
                            l.append(n)
                        v = l
                    self._map[k] = v
        if kwargs:
            for k, v in self.__call_items(kwargs):
                if k is not "_dynamic":
                    self._map[k] = v

    def __call_items(self, obj):
        if hasattr(obj, "iteritems") and ismethod(getattr(obj, "iteritems")):
            return obj.iteritems()
        else:
            return obj.items()

    def items(self):
        return self.iteritems()

    def iteritems(self):
        return self.__call_items(self._map)

    def __iter__(self):
        return self._map.__iter__()

    def next(self):
        return self._map.next()

    def __setitem__(self, k, v):
        self._map[k] = v

    def __getitem__(self, k):
        if k not in self._map and self._dynamic and k != "_ipython_canary_method_should_not_exist_":
            # automatically extend to new DotMap
            self[k] = DotMap()
        return self._map[k]

    def __setattr__(self, k, v):
        if k in {"_map", "_dynamic", "_ipython_canary_method_should_not_exist_"}:
            super(DotMap, self).__setattr__(k, v)
        else:
            self[k] = v

    def __getattr__(self, k):
        if k == {"_map", "_dynamic", "_ipython_canary_method_should_not_exist_"}:
            super(DotMap, self).__getattr__(k)
        else:
            return self[k]

    def __delattr__(self, key):
        return self._map.__delitem__(key)

    def __contains__(self, k):
        return self._map.__contains__(k)

    def __str__(self):
        items = []
        for k, v in self.__call_items(self._map):
            # bizarre recursive assignment situation (why someone would do this is beyond me)
            if id(v) == id(self):
                items.append("{0}=DotMap(...)".format(k))
            else:
                items.append("{0}={1}".format(k, repr(v)))
        out = "DotMap({0})".format(", ".join(items))
        return out

    def __repr__(self):
        return str(self)

    def toDict(self):
        d = {}
        for k, v in self.items():
            if type(v) is DotMap:
                # bizarre recursive assignment support
                if id(v) == id(self):
                    v = d
                else:
                    v = v.toDict()
            elif type(v) is list:
                l = []
                for i in v:
                    n = i
                    if type(i) is DotMap:
                        n = i.toDict()
                    l.append(n)
                v = l
            d[k] = v
        return d

    def pprint(self):
        pprint(self.toDict())

    def empty(self):
        return not any(self)

        # proper dict subclassing

    def values(self):
        return self._map.values()

        # ipython support

    def __dir__(self):
        return self.keys()

    @classmethod
    def parseOther(self, other):
        if type(other) is DotMap:
            return other._map
        else:
            return other

    def __cmp__(self, other):
        other = DotMap.parseOther(other)
        return self._map.__cmp__(other)

    def __eq__(self, other):
        other = DotMap.parseOther(other)
        if not isinstance(other, dict):
            return False
        return self._map.__eq__(other)

    def __ge__(self, other):
        other = DotMap.parseOther(other)
        return self._map.__ge__(other)

    def __gt__(self, other):
        other = DotMap.parseOther(other)
        return self._map.__gt__(other)

    def __le__(self, other):
        other = DotMap.parseOther(other)
        return self._map.__le__(other)

    def __lt__(self, other):
        other = DotMap.parseOther(other)
        return self._map.__lt__(other)

    def __ne__(self, other):
        other = DotMap.parseOther(other)
        return self._map.__ne__(other)

    def __delitem__(self, key):
        return self._map.__delitem__(key)

    def __len__(self):
        return self._map.__len__()

    def clear(self):
        self._map.clear()

    def copy(self):
        return DotMap(self.toDict())

    def __copy__(self):
        return self.copy()

    def __deepcopy__(self, memo=None):
        return self.copy()

    def get(self, key, default=None):
        return self._map.get(key, default)

    def has_key(self, key):
        return key in self._map

    def iterkeys(self):
        return self._map.iterkeys()

    def itervalues(self):
        return self._map.itervalues()

    def keys(self):
        return self._map.keys()

    def pop(self, key, default=None):
        return self._map.pop(key, default)

    def popitem(self):
        return self._map.popitem()

    def setdefault(self, key, default=None):
        self._map.setdefault(key, default)

    def update(self, *args, **kwargs):
        if len(args) != 0:
            self._map.update(*args)
        self._map.update(kwargs)

    def viewitems(self):
        return self._map.viewitems()

    def viewkeys(self):
        return self._map.viewkeys()

    def viewvalues(self):
        return self._map.viewvalues()

    @classmethod
    def fromkeys(cls, seq, value=None):
        d = DotMap()
        d._map = OrderedDict.fromkeys(seq, value)
        return d

    def __getstate__(self):
        return self.__dict__

    def __setstate__(self, d):
        self.__dict__.update(d)
Example #12
1
class DotMap(OrderedDict):
    def __init__(self, *args, **kwargs):
        self._map = OrderedDict()
        if args:
            d = args[0]
            if type(d) is dict:
                for k, v in self.__call_items(d):
                    if type(v) is dict:
                        v = DotMap(v)
                    self._map[k] = v
        if kwargs:
            for k, v in self.__call_items(kwargs):
                self._map[k] = v

    def __call_items(self, obj):
        if hasattr(obj, "iteritems") and ismethod(getattr(obj, "iteritems")):
            return obj.iteritems()
        else:
            return obj.items()

    def items(self):
        return self.iteritems()

    def iteritems(self):
        return self.__call_items(self._map)

    def __iter__(self):
        return self._map.__iter__()

    def next(self):
        return self._map.next()

    def __setitem__(self, k, v):
        self._map[k] = v

    def __getitem__(self, k):
        if k not in self._map:
            # automatically extend to new DotMap
            self[k] = DotMap()
        return self._map[k]

    def __setattr__(self, k, v):
        if k == "_map":
            super(DotMap, self).__setattr__(k, v)
        else:
            self[k] = v

    def __getattr__(self, k):
        if k == "_map":
            super(DotMap, self).__getattr__(k)
        else:
            return self[k]

    def __delattr__(self, key):
        return self._map.__delitem__(key)

    def __contains__(self, k):
        return self._map.__contains__(k)

    def __str__(self):
        items = []
        for k, v in self.__call_items(self._map):
            items.append("{0}={1}".format(k, repr(v)))
        out = "DotMap({0})".format(", ".join(items))
        return out

    def __repr__(self):
        return str(self)

    def toDict(self):
        d = {}
        for k, v in self.items():
            if type(v) is DotMap:
                v = v.toDict()
            d[k] = v
        return d

    def pprint(self):
        pprint(self.toDict())

        # proper dict subclassing

    def values(self):
        return self._map.values()

    @classmethod
    def parseOther(self, other):
        if type(other) is DotMap:
            return other._map
        else:
            return other

    def __cmp__(self, other):
        other = DotMap.parseOther(other)
        return self._map.__cmp__(other)

    def __eq__(self, other):
        other = DotMap.parseOther(other)
        if not isinstance(other, dict):
            return False
        return self._map.__eq__(other)

    def __ge__(self, other):
        other = DotMap.parseOther(other)
        return self._map.__ge__(other)

    def __gt__(self, other):
        other = DotMap.parseOther(other)
        return self._map.__gt__(other)

    def __le__(self, other):
        other = DotMap.parseOther(other)
        return self._map.__le__(other)

    def __lt__(self, other):
        other = DotMap.parseOther(other)
        return self._map.__lt__(other)

    def __ne__(self, other):
        other = DotMap.parseOther(other)
        return self._map.__ne__(other)

    def __delitem__(self, key):
        return self._map.__delitem__(key)

    def __len__(self):
        return self._map.__len__()

    def clear(self):
        self._map.clear()

    def copy(self):
        return self

    def get(self, key, default=None):
        return self._map.get(key, default)

    def has_key(self, key):
        return key in self._map

    def iterkeys(self):
        return self._map.iterkeys()

    def itervalues(self):
        return self._map.itervalues()

    def keys(self):
        return self._map.keys()

    def pop(self, key, default=None):
        return self._map.pop(key, default)

    def popitem(self):
        return self._map.popitem()

    def setdefault(self, key, default=None):
        self._map.setdefault(key, default)

    def update(self, *args, **kwargs):
        if len(args) != 0:
            self._map.update(*args)
        self._map.update(kwargs)

    def viewitems(self):
        return self._map.viewitems()

    def viewkeys(self):
        return self._map.viewkeys()

    def viewvalues(self):
        return self._map.viewvalues()

    @classmethod
    def fromkeys(cls, seq, value=None):
        d = DotMap()
        d._map = OrderedDict.fromkeys(seq, value)
        return d
Example #13
0
def OPTIMO(wlf, n):
    pages = []
    # Read pages from file.
    f = open(wlf)
    pages = f.read().splitlines()
    f.close()
    cache_list = OrderedDict()
    page_fault = 0
    count = 0
    # Insertion of pages to memory and calculation of page faults.
    for page in pages:
        tam_cache = len(cache_list)
        lista = []
        count += 1
        if not cache_list.__contains__(page):
            if tam_cache < n:
                cache_list[page] = ""
                page_fault += 1
            else:
                lista = [pages[x] for x in range(count + 1, len(pages))]
                list_inters = set(lista).intersection(cache_list)
                if len(list_inters) == len(cache_list):
                    cache_list.popitem()
                    cache_list[page] = ""
                    page_fault += 1
                else:
                    lista_comp = set(list_inters).symmetric_difference(cache_list)
                    elem = lista_comp.pop()
                    cache_list.__delitem__(elem)
                    cache_list[page] = ""
                    page_fault += 1
    return page_fault
    print "Resultados: "
    print "Miss rate: ", "              " + str(round((float(page_fault * 100) / (3721736)), 3)) + "%"
    print "Miss rate (warm cache): ", " " + str(round((float(page_fault * 100) / (3721736 - n)), 3)) + "%"
    with open("log.csv", "a") as output:
        output.write("OPTIMO," + str(page_fault) + "," + str(n) + "\n")
    output.close()
Example #14
0
File: yuri.py Project: jparise/yuri
 def __delitem__(self, name):
     """Delete a field and all of its values."""
     name = name.lower()
     OrderedDict.__delitem__(self, name)
Example #15
0
 def __delitem__(self, name):
     self._delitem(name)
     OrderedDict.__delitem__(self, name)
Example #16
0
class Headers:
    """Utility for managing HTTP headers for both clients and servers.

    It has a dictionary like interface with few extra functions to facilitate
    the insertion of multiple header values. Header fields are
    **case insensitive**, therefore doing::

        >>> h = Headers()
        >>> h['Content-Length'] = '1050'

    is equivalent to

        >>> h['content-length'] = '1050'

    :param headers: optional iterable over header field/value pairs.
    :param kind: optional headers type, one of ``server``, ``client`` or
        ``both``.
    :param strict: if ``True`` only valid headers field will be included.

    This :class:`Headers` container maintains an ordering as suggested by
    http://www.w3.org/Protocols/rfc2616/rfc2616.html:

    .. epigraph::

        The order in which header fields with differing field names are
        received is not significant. However, it is "good practice" to send
        general-header fields first, followed by request-header or
        response-header fields, and ending with the entity-header fields.

        -- rfc2616 section 4.2

    The strict parameter is rarely used and it forces the omission on
    non-standard header fields.
    """

    @classmethod
    def make(cls, headers):
        if not isinstance(headers, cls):
            headers = cls(headers)
        return headers

    def __init__(self, *args, **kwargs):
        self._headers = OrderedDict()
        if args or kwargs:
            self.update(*args, **kwargs)

    def __repr__(self):
        return self._headers.__repr__()

    def __str__(self):
        return "\r\n".join(self._ordered())

    def __bytes__(self):
        return str(self).encode(DEFAULT_CHARSET)

    def __len__(self):
        return len(self._headers)

    def update(self, *args, **kwargs):
        """Extend the headers with an ``iterable``.

        :param iterable: a dictionary or an iterable over keys, values tuples.
        """
        if len(args) == 1:
            for key, value in mapping_iterator(args[0]):
                self.add_header(key, value)
        elif args:
            raise TypeError("update expected at most 1 arguments, got %d" % len(args))
        for key, value in kwargs.items():
            self.add_header(key, value)

    def override(self, iterable):
        """Extend headers by overriding fields form iterable.

        :param iterable: a dictionary or an iterable over keys, values tuples.
        """
        seen = set()
        for key, value in mapping_iterator(iterable):
            key = key.lower()
            if key in seen:
                self.add_header(key, value)
            else:
                seen.add(key)
                self[key] = value

    def copy(self):
        return self.__class__(self)

    def __contains__(self, key):
        return header_field(key) in self._headers

    def __getitem__(self, key):
        key = header_field(key)
        values = self._headers[key]
        joiner = HEADER_FIELDS_JOINER.get(key, ", ")
        if joiner is None:
            joiner = "; "
        return joiner.join(values)

    def __delitem__(self, key):
        self._headers.__delitem__(header_field(key))

    def __setitem__(self, key, value):
        key = header_field(key)
        if key and value:
            if not isinstance(value, list):
                value = header_values(key, value)
            self._headers[key] = value

    def get(self, key, default=None):
        """Get the field value at ``key`` as comma separated values.

        For example::

            >>> from pulsar.utils.httpurl import Headers
            >>> h = Headers(kind='client')
            >>> h.add_header('accept-encoding', 'gzip')
            >>> h.add_header('accept-encoding', 'deflate')
            >>> h.get('accept-encoding')

        results in::

            'gzip, deflate'
        """
        if key in self:
            return self.__getitem__(key)
        else:
            return default

    def get_all(self, key, default=None):
        """Get the values at header ``key`` as a list rather than a
        string separated by comma (which is returned by the
        :meth:`get` method).

        For example::

            >>> from pulsar.utils.httpurl import Headers
            >>> h = Headers(kind='client')
            >>> h.add_header('accept-encoding', 'gzip')
            >>> h.add_header('accept-encoding', 'deflate')
            >>> h.get_all('accept-encoding')

        results in::

            ['gzip', 'deflate']
        """
        return self._headers.get(header_field(key), default)

    def has(self, field, value):
        """Check if ``value`` is available in header ``field``."""
        value = value.lower()
        for c in self.get_all(field, ()):
            if c.lower() == value:
                return True
        return False

    def pop(self, key, *args):
        return self._headers.pop(header_field(key), *args)

    def clear(self):
        """Same as :meth:`dict.clear`, it removes all headers.
        """
        self._headers.clear()

    def getheaders(self, key):  # pragma    nocover
        """Required by cookielib in python 2.

        If the key is not available, it returns an empty list.
        """
        return self._headers.get(header_field(key), [])

    def add_header(self, key, values):
        """Add ``values`` to ``key`` header.

        If the header is already available, append the value to the list.

        :param key: header name
        :param values: a string value or a list/tuple of strings values
            for header ``key``
        """
        key = header_field(key)
        if key and values:
            if not isinstance(values, (tuple, list)):
                values = header_values(key, values)
            current = self._headers.get(key, [])
            for value in values:
                if value and value not in current:
                    current.append(value)
            self._headers[key] = current

    def remove_header(self, key, value=None):
        """Remove the header at ``key``.

        If ``value`` is provided, it removes only that value if found.
        """
        key = header_field(key)
        if key:
            if value:
                value = value.lower()
                values = self._headers.get(key, [])
                removed = None
                for v in values:
                    if v.lower() == value:
                        removed = v
                        values.remove(v)
                self._headers[key] = values
                return removed
            else:
                return self._headers.pop(key, None)

    def flat(self, version, status):
        """Full headers bytes representation"""
        vs = version + (status, self)
        return ("HTTP/%s.%s %s\r\n%s" % vs).encode(DEFAULT_CHARSET)

    def __iter__(self):
        dj = ", "
        for k, values in self._headers.items():
            joiner = HEADER_FIELDS_JOINER.get(k, dj)
            if joiner:
                yield k, joiner.join(values)
            else:
                for value in values:
                    yield k, value

    def _ordered(self):
        for key, header in self:
            yield "%s: %s" % (key, header)
        yield ""
        yield ""
Example #17
0
 def __delitem__(self, name):
     norm_name = HTTPHeaders._normalize_name(name)
     OrderedDict.__delitem__(self, norm_name)
     del self._as_list[norm_name]
Example #18
0
 def __delitem__(self, key):
     """Remove items without raising exceptions."""
     if key in self:
         OrderedDict.__delitem__(self, key)
         if self.token:
             self.token.reserialize()
 def __delitem__(self, key):
     kl = key.lower()
     if kl not in self.keyMap:
         raise KeyError(key)
     OrderedDict.__delitem__(self, self.keyMap[kl])
     del self.keyMap[kl]
Example #20
0
 def __delitem__(self, key, **kwargs):
     OrderedDict.__delitem__(self, self.id(key))
     OrderedDict.__delitem__(self, self.rev_id(key))
Example #21
0
        # If we reached the end of the length of the arguments, return i.
        if i == len_of_remaining_page:
            return i


#
#  Authored by Juan Mite
#  LRU algorithm
#
if policy.upper() == "LRU":
    print "Evaluando una caché LRU con " + str(cache_tam) + " entradas, tiempo estimado 25 segundos..."
    with open(workload_file) as f:
        for line in f:
            if cache.__contains__(line):
                # HIT
                cache.__delitem__(line)
                cache[line] = ""
                hites = hites + 1
            else:
                # MISS
                misses = misses + 1
                cache[line] = ""
                if len(cache) > cache_tam:
                    cache.popitem(last=False)
    references = hites + misses
    print "Resultados: "
    print "Miss rate: ", "              " + str(round((float(misses) / (references)), 3)) + "% (" + str(
        misses
    ) + " misses out of " + str(references) + " references)"
    print "Miss rate (warm cache): ", " " + str(round((float(misses) / (references - cache_tam)), 3)) + "% (" + str(
        hites
Example #22
0
 def __delitem__(self, key, *args, **kwds):
     l = _lower(key)
     OrderedDict.__delitem__(self, l, *args, **kwds)
     del self.__map[l]
class BestPracticeWarning(collections.MutableMapping, base.ValidationError):
    """Represents a best practice warning. These are built within best
    practice rule checking methods and attached to
    :class:`BestPracticeWarningCollection` instances.

    Note:
        This class acts like a dictionary and contains the following keys
        at a minimum:

        * ``'id'``: The id of a node associated with the warning.
        * ``'idref'``: The idref of a node associated with the warning.
        * ``'line'``: The line number of the offending node.
        * ``'message'``: A message associated with the warning.
        * ``'tag'``: The lxml tag for the offending node.

        These keys can be retrieved via the :attr:`core_keys` property.

        Instances of this class may attach additional keys. These `other keys`
        can be obtained via the :attr:`other_keys` property.

    Args:
        node: The ``lxml._Element`` node associated with this warning.
        message: A message for this warning.

    """

    def __init__(self, node, message=None):
        base.ValidationError.__init__(self)

        self._inner = OrderedDict()
        self._node = node

        self["line"] = node.sourceline
        self["message"] = message
        self["id"] = node.attrib.get("id")
        self["idref"] = node.attrib.get("idref")
        self["tag"] = node.tag

    def __unicode__(self):
        return unicode(self.message)

    def __str__(self):
        return unicode(self).encode("utf-8")

    def __getitem__(self, key):
        return self._inner.__getitem__(key)

    def __delitem__(self, key):
        self._inner.__delitem__(key)

    def __setitem__(self, key, value):
        self._inner.__setitem__(key, value)

    def __len__(self):
        return self._inner.__len__()

    def __iter__(self):
        return self._inner.__iter__()

    @property
    def line(self):
        """Returns the line number of the warning node in the input document.

        """
        return self["line"]

    @property
    def message(self):
        """Returns a message associated with the warning. This may return
        ``None`` if there is no warning message.

        """
        return self["message"]

    @property
    def core_keys(self):
        """Returns a ``tuple`` of  the keys that can always be found on
        instance of this class.

        Returns:
            A tuple including the following keys.

            * ``'id'``: The id of the warning node. The associated value
              may be ``None``.
            * ``'idref'``: The idref of the warning node. The associated value
              may be ``None``.
            * ``'line'``: The line number of the warning node in the input
              document. The associated value may be ``None``.
            * ``'tag'``: The ``{namespace}localname`` value of the warning
              node.
            * ``'message'``: An optional message that can be attached to the
              warning. The associated value may be ``None``.
        """
        return ("id", "idref", "line", "tag", "message")

    @property
    def other_keys(self):
        """Returns a ``tuple`` of keys attached to instances of this class that
        are not found in the :attr:`core_keys`.

        """
        return tuple(x for x in self.iterkeys() if x not in self.core_keys)

    def as_dict(self):
        """Returns a dictionary representation of this class instance. This
        is implemented for consistency across other validation error types.

        The :class:`.BestPracticeWarning` class extends
        :class:`collections.MutableMapping`, so this method isn't really
        necessary.

        """
        return dict(self.iteritems())