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'))
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]')
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
def __init__(self, cells, values): if len(cells) != len(values): raise ValueError("cells and values in a Range must have the same size") result = [] cleaned_cells = [] for index, cell in enumerate(cells): col = re.search(CELL_REF_RE, cell).group(1) row = re.search(CELL_REF_RE, cell).group(2) if '!' in cell: cleaned_cell = cell.split('!')[1] else: cleaned_cell = cell cleaned_cells.append(cleaned_cell) result.append(((row, col), values[index])) # cells ref need to be cleaned of sheet name => WARNING, sheet ref is lost !!! cells = cleaned_cells self.cells = cells # this is used to be able to reconstruct Ranges from results of Range operations self.length = len(cells) # get last cell last = cells[self.length - 1] first = cells[0] self.nb_cols = int(col2num(last[0])) - int(col2num(first[0])) + 1 self.nb_rows = int(last[1]) - int(first[1]) + 1 OrderedDict.__init__(self, result)
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)
def __init__(self, cells_tuple, values): cells, nr, nc = cells_tuple result = [] if len(cells) != len(values): raise ValueError("cells and values in a Range must have the same size") try: sheet = cells[0].split('!')[0] except: sheet = None for index, cell in enumerate(cells): found = re.search(CELL_REF_RE, cell) col = found.group(1) row = found.group(2) try: # Might not be needed result.append(((row, col), values[index])) except: result.append(((row, col), None)) self.cells = cells self.sheet = sheet self.length = len(cells) self.nb_cols = nc self.nb_rows = nr OrderedDict.__init__(self, result)
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 = {}
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()
def __init__(self, field=None, *args, **kw): self.field = field default = kw.pop('default', OrderedDict()) if not isinstance(default, OrderedDict): raise ValueError("An OrderedDictField's default must be an OrderedDict.") OrderedDict.__init__(self) Field.__init__(self, ftype=OrderedDict, default=default, *args, **kw)
def __init__(self, default_factory=None, *a, **kw): isnone = default_factory is None callable = isinstance(default_factory, Callable) if not isnone and not callable: raise TypeError("first argument must be callable") OrderedDict.__init__(self, *a, **kw) self.default_factory = default_factory
def __init__(self, xml): """Initialize APDetail. Args: :xml (str): XML string. Usage: :: >>> from airwaveapiclient import AirWaveAPIClient >>> from airwaveapiclient import APDetail >>> airwave = AirWaveAPIClient(username='******', >>> password='******', >>> url='https://192.168.1.1/') >>> airwave.login() >>> res = airwave.ap_detail(123) >>> airwave.logout() >>> obj = APDetail(res.text) >>> for radio in obj['radio']: ... for client in radio['client']: ... 'ID:%s, SIGNAL:%s, SNR:%s' % (client['@id'], ... client['signal'], ... client['snr']) 'ID:11000001, SIGNAL:-43, SNR:51' 'ID:11000002, SIGNAL:-50, SNR:44' 'ID:11000003, SIGNAL:-56, SNR:38' """ data = xmltodict.parse(xml) obj = data['amp:amp_ap_detail']['ap'] OrderedDict.__init__(self, obj)
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)
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
def __init__(self, *args, **kwargs): OrderedDict.__init__(self, *args, **kwargs) self.game_window = win_terface.WindowElement( 'MainWindow', 'Bejeweled 2 Deluxe 1.1', bringTop=True) self.window_left, self.window_top, _, _ = self.game_window.position self.read_field((X, Y) for Y in range(8) for X in range(8)) print(self)
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()
def __init__(self, maxsize): """ :param int maxsize: The maximum size of this cache. """ OrderedDict.__init__(self) self._maxsize = maxsize
def fromMapping(cls, mapping: dict): new = cls.__new__(cls) OrderedDict.__init__(new) for key in mapping: new[key] = mapping[key] return new
def __init__(self, name, aliases={}): HAResource.__init__(self, name) OrderedDict.__init__(self) self.type = "collection" self.lock = threading.Lock() self.aliases = aliases debug('debugCollection', self.name, "aliases:", self.aliases)
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)
def __init__(self, reader, nptypes, template): OrderedDict.__init__(self) if template is not None: for name in template: self[name] = template[name] return allptypes = numpy.arange(nptypes) for name in reader.schema.__blocks__: entry = getattr(reader.schema, name) if len(entry) == 1: entry = SchemaEntry(name=name, dtype=entry[0], ptypes=allptypes, conditions=()) elif len(entry) == 2: entry = SchemaEntry(name=name, dtype=entry[0], ptypes=entry[1], conditions=()) elif len(entry) == 3: entry = SchemaEntry(name=name, dtype=entry[0], ptypes=entry[1], conditions=entry[2]) else: raise SyntaxError('schema declaration is wrong') self[name] = entry
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()
def __init__(self, default_factory=None, *args, size=None, **kwargs): if default_factory is not None and not callable(default_factory): raise TypeError("default_factory must be callable") Labels.__init__(self, size) self._all = [] OrderedDict.__init__(self, *args, **kwargs) self._all = list(self.keys()) self.default_factory = default_factory
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)
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)
def __init__(self, items = [], size = None): if not isinstance(size, int): if isinstance(items, Cache): size = items.__size else: size = DEFAULT_CACHE_SIZE self.__size = size OrderedDict.__init__(self, items)
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,defaults={},strictsubstitute=False): """ `defaults` defines which fields to add when absent in a new item dictionary. If `strictsubstitute == True`, missing fields will cause error during substitution. """ OrderedDict.__init__(self) self.defaults = defaults self.strictsubstitute = strictsubstitute
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)
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()
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()
def __init__(self): OrderedDict.__init__(self) for line in self.DEFINITION.splitlines(): line = line.strip() if not line or line.startswith('#'): continue name, val = [x.strip() for x in line.partition('=')[0::2]] if val: val = eval( val, { 'zeroes': zeroes, 'NULL': NULL, 'DYN': None, 'nulls': nulls, 'short': short, 'random': random }) else: val = 0 if name in self: raise ValueError('Duplicate field in definition: %r' % name) self[name] = val
def __init__(self, *args, **kwargs): """ The initialization method """ OrderedDict.__init__(self, *args, **kwargs) if 'filename' in kwargs: self._set_filename(kwargs['filename']) else: log.error("filename not specified") # sys.exit() if os.path.isfile(self['location']): self.load(self['location']) # print ("ATTRIBUTE", attribute) for attribute in ['prefix']: if attribute in kwargs: self[attribute] = kwargs[attribute] else: self[attribute] = None self._update_meta()
def __init__(self, max_len, max_age_seconds, items=None, auto_refresh=False, auto_expired=False): # type: (Union[int, None], Union[float, None], Union[None,dict,OrderedDict,ExpiringDict]) -> None if not self.__is_instance_of_expiring_dict(items): self.__assertions(max_len, max_age_seconds) OrderedDict.__init__(self) self.max_len = max_len self.max_age = max_age_seconds self.lock = RLock() self.auto_refresh = auto_refresh if sys.version_info >= (3, 5): self._safe_keys = lambda: list(self.keys()) else: self._safe_keys = self.keys if items is not None: if self.__is_instance_of_expiring_dict(items): self.__copy_expiring_dict(max_len, max_age_seconds, items) elif self.__is_instance_of_dict(items): self.__copy_dict(items) elif self.__is_reduced_result(items): self.__copy_reduced_result(items) else: raise ValueError('can not unpack items') if auto_expired: self.thread = Thread(target=self._expiring_key, args=()) self.thread.setDaemon(True) self.thread.start()
def __init__(self, *args): # a list of the keys in this Index (including the dirs) self._list = [] # a list of all files in the tree (no dirs) # we lazy update this for performance reasons # We should think closely about this. If the keyspace is huge # pulling this into an array is more expensive than walking # the tree self._full_key_list = None # this should always be accurate self._nfiles = 0 self._path = "/" OrderedDict.__init__(self, *args) if not all(isinstance(k, str) for k in self): raise ValueError("All keys must be strings") self.refresh_full_key_list() self._nfiles = len(self._full_key_list) self._subset_cache = {}
def __init__(self): OrderedDict.__init__(self) self._config = None configpath = path.join(path.dirname(__file__), '../../../.config') configfile = path.join(configpath, 'config.json') # @var _configfile protected member variable to store configfile path self._configfile = configfile if path.exists(self._configfile): with open(configfile, 'rt') as f: try: self._config = load(f, object_hook=OrderedDict, encoding='utf8')["dfmetadata"] except IOError: raise IOError else: raise IOError self['type'] = None self['rowcount'] = None self['cols'] = None self['timeformat'] = None self['columns'] = list()
def __init__(self, krater_report_file): OrderedDict.__init__(self) #self = OrderedDict() with open(krater_report_file, "r") as in_fd: for line in in_fd: tmp = line.strip().split("\t") self[tmp[0]] = tmp[1] self["Number of distinct kmers"] = int(self["Number of distinct kmers"]) self["Number of distinct kmers with errors"] = int(self["Number of distinct kmers with errors"]) self["Fraction of distinct kmers with errors"] = float(self["Fraction of distinct kmers with errors"]) self["Total number of kmers"] = int(self["Total number of kmers"]) self["Total number of kmers with errors"] = int(self["Total number of kmers with errors"]) self["Fraction of kmers with errors"] = float(self["Fraction of kmers with errors"]) self["Width of first peak"] = int(self["Width of first peak"]) self["Mean kmer multiplicity in first peak"] = float(self["Mean kmer multiplicity in first peak"]) self["Kmer multiplicity at first maximum"] = float(self["Kmer multiplicity at first maximum"]) self["Standard deviation of kmer multiplicity in first peak"] = float(self["Standard deviation of kmer multiplicity in first peak"]) self["Variance coefficient of kmer multiplicity in first peak"] = float(self["Variance coefficient of kmer multiplicity in first peak"]) if "Estimated genome size, bp" in self: # for compatibility with older versions that don't count genome size self["Estimated genome size, bp"] = float(self["Estimated genome size, bp"]) if self["Estimated genome size, bp"] != 'NA' else None
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) with_spt = new_fs + '.spt' if isfile(with_spt): new_fs = with_spt child = NavItem(website, self, new_fs, slug) if child.title is None: continue self[child.slug] = child # Populate self as an OrderedDict self.title = context.get('nav_title')
def __init__(self, tracks=None, y_start=None, x_start=0, x_end=1, style=default_track_group_style, label=None, x_scale_factor=1, y_scale_factor=1, auto_scale=False, subplot_x_y_ratio=None, figure_x_y_ratio=None): if tracks: OrderedDict.__init__(self, tracks) else: OrderedDict.__init__(self) self.y_start = y_start self.y_end = None self.x_start = x_start self.x_end = x_end self.style = style self.label = label self.track_label_param_list = None self.x_scale_factor = x_scale_factor self.y_scale_factor = y_scale_factor # TODO: finish autoscale implementation self.auto_scale = auto_scale self.x_y_ratio = None self.subplot_x_y_ratio = subplot_x_y_ratio self.figure_x_y_ratio = figure_x_y_ratio
def __init__(self, coockiecutter_report_file, input_is_se=False): #self = OrderedDict() OrderedDict.__init__(self) self["left"] = OrderedDict() self["right"] = OrderedDict() self["se"] = OrderedDict() with open(coockiecutter_report_file, "r") as in_fd: tmp = "" for read_position in ("se", ) if input_is_se else ("left", "right"): while "ok" not in tmp: tmp = in_fd.readline() while "\t" in tmp: tmp = tmp.strip().split("\t") if "%" in tmp[1]: self[read_position][tmp[0]] = float(tmp[1].replace( "%", "")) else: self[read_position][tmp[0]] = int(tmp[1]) tmp = in_fd.readline() self.match_key = "match" if (("match" in self["left"]) or ("match" in self["se"])) else "adapter" self.retained_pairs_key = "ok" if input_is_se else "pe" if "pe" in self[ "left"] else "paired-end reads" pos = "se" if input_is_se else "left" self.input_pairs = self[pos]["ok"] + self[pos][self.match_key] + ( self[pos]["n"] if "n" in self[pos] else 0) self.retained_pairs = self[pos][self.retained_pairs_key] self.retained_pairs_fraction = float(self.retained_pairs) / float( self.input_pairs)
def __init__(self, *args, **kwds): if "max_cache_objects" in kwds: self.max_cache_objects = kwds["max_cache_objects"] self.size_limit = kwds.pop("size_limit", self.max_cache_objects) OrderedDict.__init__(self, *args, **kwds) self._check_size_limit()
def __init__(self, *args, max_length=1, **kwargs): assert isinstance(max_length, int) assert max_length >= 0 self.__max_length__ = max_length OrderedDict.__init__(self, *args, **kwargs)
def __init__(self, list_identifier=None, start_index=None): OrderedDict.__init__(self) self._list_identifier = list_identifier or "item" self._item_index = start_index or 0
def __init__(self, max_size): OrderedDict.__init__(self) assert max_size > 0 self.max_size = max_size
def __init__(self, name=None): OrderedDict.__init__(self) self[self.primary_key] = name
def __init__(self, *args, **kwds): self.size_limit = kwds.pop("size_limit", None) OrderedDict.__init__(self, *args, **kwds) self._check_size_limit()
def __init__(self, *args, **kwds): OrderedDict.__init__(self) self.update(*args, **kwds)
def __init__(self, language=None): OrderedDict.__init__(self) self.language = language
def __init__(self, default_factory, *args, **kwargs): OrderedDict.__init__(self, *args, **kwargs) self._default_factory = default_factory
def __init__(self, *args, **kwargs): self.max_cache_size = kwargs.pop("max_cache_size", 500) OrderedDict.__init__(self, *args, **kwargs)
def __init__(self, *args, **kwds): OrderedDict.__init__(self, *args, **kwds)
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 = six.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) elif isinstance(value, dict): if '__order__' in value: value = GroupableOrderedDict(value) v.append(value) 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
def __init__(self, *classes): self.classes = dict([(cls.__name__, cls) for cls in classes]) # {name: class, ...} OrderedDict.__init__(self)
def __init__(self, filename): OrderedDict.__init__(self) if filename[-4:] <> '.dat': raise Exception('wrong filename') self.filename = filename
def __init__(self, *args, **kwargs): self.limit = kwargs.pop("limit", None) OrderedDict.__init__(self, *args, **kwargs) self._remove_oldest()
def __init__(self, name="", **kwargs): self.name = name OrderedDict.__init__(self, kwargs)
def __init__(self, default_factory, *args, **kwargs): defaultdict.__init__(self, default_factory) OrderedDict.__init__(self, *args, **kwargs)
def __init__(self, default_factory=None, *a, **kw): if default_factory is not None and not callable(default_factory): raise TypeError('first argument must be callable') OrderedDict.__init__(self, *a, **kw) self.default_factory = default_factory
def __init__(self, statslist=None): OrderedDict.__init__(self) _statslist = statslist if not None else [] if statslist is not None: for stat in _statslist: self.add(stat)
def __init__(self, name, **values): OrderedDict.__init__(self) self.name = name self.update(values)
def __init__(self, *args, **kwds): self._lock = multiprocessing.Lock() self.maxlen = kwds.pop("maxlen", None) OrderedDict.__init__(self, *args, **kwds) self._checklen()