Example #1
1
    def fromMapping(cls, mapping: dict):
        new = cls.__new__(cls)
        OrderedDict.__init__(new)
        for key in mapping:
            new[key] = mapping[key]

        return new
Example #2
1
 def __init__(self, *args, **kwds):
     self.size_limit = kwds.pop("size_limit", 300000)
     self.size_grace = kwds.pop("size_grace", 100000)
     self.overflow_callback = kwds.pop("overflow_callback", None)
     self.overflow = False
     OrderedDict.__init__(self, *args, **kwds)
     self._check_size_limit()
Example #3
1
    def __init__(self, cdxline=""):
        OrderedDict.__init__(self)

        cdxline = cdxline.rstrip()

        # Allows for filling the fields later or in a custom way
        if not cdxline:
            self.cdxline = cdxline
            return

        fields = cdxline.split(" ")

        cdxformat = None
        for i in self.CDX_FORMATS:
            if len(i) == len(fields):
                cdxformat = i

        if not cdxformat:
            msg = "unknown {0}-field cdx format".format(len(fields))
            raise CDXException(msg)

        for header, field in itertools.izip(cdxformat, fields):
            self[header] = field

        self.cdxline = cdxline
Example #4
1
	def __init__(self, form):
		if not etree.iselement(form):
			raise TypeError, "Form() requires a <form> element, not type '%s'" % type(form).__name__
		if form.tag != 'form':
			raise ValueError, "Form() requires a <form> element, not <%s>" % form.tag
		OrderedDict.__init__(self)
		self.action = form.get('action')
		self.method = form.get('method', 'get').lower()
		self.enctype = form.get('enctype', MIME_URLFORM)
		self.charset = [val.strip().lower() for val in form.get('accept-charset', '').split(',') if val]
		self.accept = [val.strip().lower() for val in form.get('accept', '').split(',') if val]
#		self._items = OrderedDict()
		labels = dict((elem.get('for'), gettext(elem)) for elem in form.iterfind('.//label[@for]'))
		for elem in form.iterfind('.//*[@name]'):
			name = elem.get('name')
			type = elem.get('type', 'text').lower() if elem.tag == 'input' else elem.tag
			if type in ('text', 'password', 'hidden'):
				self[name] = Form.Item(type, elem.get('value', ''))
			elif type == 'textarea':
				self[name] = Form.Item(type, gettext(elem))
			elif type in ('radio', 'checkbox'):
				value = elem.get('value', 'on')
				label = labels.get(elem.get('id')) or gettext(elem) or elem.tail or value
				item = self.setdefault(name, Form.OptItem(type))
				item.addopt(value, label, hasflag(elem, 'checked'))
			elif type == 'submit':
				value = elem.get('value', 'Submit Query')
				item = self.setdefault(name, Form.OptItem(type))
				item.addopt(value, value)
			elif type == 'select':
				item = self[name] = Form.OptItem(type, hasflag(elem, 'multiple'))
				for opt in elem.iterfind('.//option'):
					text = gettext(opt)
					item.addopt(opt.get('value', text), text, hasflag(opt, 'selected'))
Example #5
1
 def __init__(self, *args, **kwds):
     # Note:  "*args, **kwds" are needed to support re-creating the instance
     # after pickling, via OrderedDict's pickling interface.
     OrderedDict.__init__(self, *args, **kwds)
     # These dicts map from 't' and 'b' attributes to trigger numbers.
     self.t_attrs = {}
     self.b_attrs = {}
Example #6
1
 def __init__(self, indirect=False, **items):
     Container.__init__(self, indirect)
     OrderedDict.__init__(self, **items)
     if self.__class__.type:
         self["Type"] = Name(self.__class__.type)
     if self.__class__.subtype:
         self["Subtype"] = Name(self.__class__.subtype)
Example #7
1
    def __new__(cls, *args):
        """Create a new immutable GroupableOrderedDict."""
        new = OrderedDict.__new__(cls)
        OrderedDict.__init__(new)

        if len(args) > 1:
            raise TypeError("expected at most 1 arguments, got {}".format(len(args)))

        ordering = []
        values = args[0]

        if values:
            if isinstance(values, GroupableOrderedDict):
                values = values.iteritems(with_order=False, repeated=True)
            elif isinstance(values, dict):
                if "__order__" in values:
                    order = values.pop("__order__")

                    tmp = []
                    c = Counter()
                    for key in order:
                        v = values[key]
                        if not isinstance(v, (tuple, list)):
                            if c[key] == 0:
                                tmp.append((key, v))
                            else:
                                raise Exception(
                                    "Order and values don't match" "on key {0} at position {1}".format(key, c[key])
                                )
                        else:
                            tmp.append((key, v[c[key]]))
                        c[key] += 1
                    values = tmp
                else:
                    values = iteritems(values)

            for key, value in values:
                if key not in new:
                    OrderedDict.__setitem__(new, key, [])
                v = []
                if isinstance(value, (tuple, list)):
                    for item in value:
                        v.append(item)
                        ordering.append(key)
                else:
                    v.append(value)
                    ordering.append(key)

                OrderedDict.__getitem__(new, key).extend(v)

        # Immutable...
        for key, value in dict.items(new):
            OrderedDict.__setitem__(new, key, tuple(value))

        OrderedDict.__setitem__(new, "__order__", tuple(ordering))
        return new
Example #8
0
 def __init__(self, entrytype, citekey, fields, src):
     OrderedDict.__init__(self)
     self.bibsrc = src
     for key, val in fields.items():
         self[key] = val
     self.citekey = citekey
     self.entrytype = entrytype
Example #9
0
    def __init__(self, *args, **kwargs):
        """
        Initilizes a DataModelDict. Can be initilized like an OrderedDict, or by supplying a json/xml string or file-like object.
        
        Additional Keyword Arguments when initilizing with json/xml info:
        parse_float -- data type to use for floating point values parsed from the json/xml info
        parse_int -- data type to use for integer values parsed from the json/xml info
        """

        OrderedDict.__init__(self)

        # If string or file-like object, call load
        if len(args) == 1 and (isinstance(args[0], (str, unicode)) or hasattr(args[0], "read")):
            format = kwargs.get("format", None)
            parse_float = kwargs.get("parse_float", float)
            parse_int = kwargs.get("parse_int", int)
            convert_NaN = kwargs.get("convert_NaN", True)
            encoding = kwargs.get("encoding", "utf-8")
            self.load(
                args[0],
                format=format,
                parse_int=parse_int,
                parse_float=parse_float,
                convert_NaN=convert_NaN,
                encoding=encoding,
            )

        # Otherwise, call update (from OrderedDict)
        else:
            self.update(*args, **kwargs)
Example #10
0
    def __init__(self, max_len=0):
        assert max_len >= 1

        OrderedDict.__init__(self)
        self.max_len = max_len
        self.key_time_map = {}
        self.lock = RLock()
Example #11
0
File: yuri.py Project: jparise/yuri
    def __init__(self, query=None):
        """Initialize a QueryDict.

        If a query string is provided, it will be parsed and used as the basis
        for the QueryDict's fields.

        Name-value pairs can be separated by either ampersands or semicolons:
        >>> QueryDict('a=1&b=2;c=3')
        {'a': '1', 'b': '2', 'c': '3'}

        Multiple values can be associated with a single name:
        >>> QueryDict('name=value1&name=value2')
        {'name': ['value1', 'value2']}

        Fields without values are supported:
        >>> QueryDict('lonely')
        {'lonely': ''}

        Names and values are percent-encoded as necessary:
        >>> QueryDict('name=two words')
        {'name': 'two words'}
        """
        OrderedDict.__init__(self)
        if query is not None:
            self.parse(query)
Example #12
0
    def __init__(self, website, parent, fs, slug):
        OrderedDict.__init__(self)
        self.parent = parent
        self.fs = fs
        self.filename = basename(fs)
        self.url = "/" if parent is None else "/".join([parent.url if parent.url != "/" else "", slug])

        self.by_fs[fs] = self
        self.by_url[self.url] = self

        self.slug = slug
        self.isdir = isdir(fs)

        if self.isdir:
            simplate = self.find_index(website.indices, fs)
        elif fs.endswith(".spt"):
            simplate = fs
        else:
            simplate = None

        context = {}
        if simplate is not None:
            context = get_simplate_context(website, simplate)
            slugs = context.get("nav_children", [])
            for slug in slugs:
                new_fs = join(fs, slug)
                if not isdir(new_fs):
                    new_fs += ".spt"
                child = NavItem(website, self, new_fs, slug)
                self[child.slug] = child  # Populate self as an OrderedDict

        self.title = context.get("nav_title", "[Untitled]")
Example #13
0
 def __init__(self, name):
     self.name = name
     self.category = -1
     self.extension = False
     self.deplevel = 0
     self.ideps = OrderedDict()
     self.MAP[name] = self
     OrderedDict.__init__(self)
Example #14
0
 def __init__(self, items=None):
     if items:
         items = dict(items)
         sorted_keys = sorted_classes(items.keys(), reverse=True)
         items = [(key, items[key]) for key in sorted_keys]
     else:
         items = {}
     OrderedDict.__init__(self, items)
Example #15
0
    def __init__(self, max_len, max_age_seconds):
        assert max_age_seconds >= 0
        assert max_len >= 1

        OrderedDict.__init__(self)
        self.max_len = max_len
        self.max_age = max_age_seconds
        self.lock = RLock()
Example #16
0
    def __init__(self, name, namespace_hint=None):
        OrderedDict.__init__(self)

        self.name = name
        if namespace_hint:
            self.namespace_hint = namespace_hint
        else:
            self.namespace_hint = self.name.upper()
Example #17
0
    def __init__(self, timeout=None, size_limit=None):
        self.timeout = timeout
        self.size_limit = size_limit
        OrderedDict.__init__(self)

        self.reactor = reactor if test_reactor is None else test_reactor

        self._check_size_limit()
Example #18
0
 def __init__(self, fname, statdt, writestep=20):
     OrderedDict.__init__(self)
     self.fname = fname
     self.writen = 0
     self.writestep = writestep
     self.print_on_write = False
     self.statdt = statdt
     self.writes = 0
Example #19
0
 def __init__(self, *args, **kwds):
     """
     :param kwds:
         * size_limit: The maximum number of entries. If this is exceeded, the elements inserted first will be popped until the limit is reached.
     """
     self.size_limit = kwds.pop("size_limit", None)
     OrderedDict.__init__(self, *args, **kwds)
     self._check_size_limit()
Example #20
0
    def __init__(self, keys, table_row, filename=None):
        """Construct the outline."""

        # Extract values
        OrderedDict.__init__(self, zip(keys, cell_values(table_row)))

        # Store the file and line information
        Node.__init__(self, table_row, filename=filename)
Example #21
0
    def __init__(self, data=None):
        """
				>>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
				"""
        OrderedDict.__init__(self)

        if data:
            self.update([item for item in six.iteritems(data) if abs(item[1]) > numpy.finfo(numpy.float).eps])
    def __init__(self, *args, **kwargs):
        """
		This method initializes the class.

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

        OrderedDict.__init__(self, *args, **kwargs)
Example #23
0
    def __init__(self, defaultdict=None, initdict=None, filelist=None):
        self.default = defaultdict if defaultdict is not None else OrderedDict()
        OrderedDict.__init__(self, self.default)
        self.filelist = []

        if initdict is not None:
            self.update(initdict)
        if filelist is not None:
            self.read(filelist)
Example #24
0
 def __init__(self, init_val=(), strict=True):
     OrderedDict.__init__(self, init_val, strict=strict)
     self._keys = self.keys
     self._values = self.values
     self._items = self.items
     self.keys = Keys(self)
     self.values = Values(self)
     self.items = Items(self)
     self._att_dict = {"keys": self.setkeys, "items": self.setitems, "values": self.setvalues}
Example #25
0
 def __init__(self, filename):
     """Initialize config object"""
     assert filename is not None
     OrderedDict.__init__(self)
     path = save_config_path(XDG_DIRECTORY)
     self.path = join(path, filename)
     if not isinstance(self.path, str) or not exists(self.path):
         raise MissingConfigFile(self.path)
     self.load()
Example #26
0
    def __init__(self, errors):
        """
                BodyData.__init__

                errors                  : Errors object
        """
        OrderedDict.__init__(self)

        self.errors = errors
Example #27
0
 def __init__(self, *args, **kwds):
     """
 Initialize an ordered dictionary with mapped keys.  The signature is the same as
 regular dictionaries, but keyword arguments are not recommended because
 their insertion order is arbitrary.
     """
     OrderedDict.__init__(self, *args, **kwds)
     self.setattrOnly(Adict.OID_STRING, Adict.nextOid)
     self.setPid(Adict.nextOid)
     Adict.nextOid += 1
Example #28
0
 def __init__(self, factory, formatter=None, default=None, separator='='):
     Storage.__init__(self, factory)
     OrderedDict.__init__(self)
     self._re_split = re.compile("^([a-zA-Z]+\w*){separator}(.*)".format(separator=re.escape(separator)))
     self._default = default
     if formatter is None:
         formatter = self.__formatter__
     self._formatter = formatter
     self._automatic_labels = {}
     self._ordinals = {}
 def __init__(self, *args):
     OrderedDict.__init__(self, {})  ## requirement for the empty {} here seems to be a python bug?
     self.keyMap = OrderedDict([(k.lower(), k) for k in OrderedDict.keys(self)])
     if len(args) == 0:
         return
     elif len(args) == 1 and isinstance(args[0], dict):
         for k in args[0]:
             self[k] = args[0][k]
     else:
         raise Exception("CaselessDict may only be instantiated with a single dict.")
Example #30
0
    def __init__(self, method, *args, **kwds):
        """
    constructor

    @type method: str
    @param method: http method
    """
        self.__disabled = False
        self.__method = method.upper()
        OrderedDict.__init__(self, *args, **kwds)