Ejemplo n.º 1
0
def patternProperties(validator, patternProperties, instance, schema):
    if not validator.is_type(instance, "object"):
        return

    for pattern, subschema in iteritems(patternProperties):
        for k, v in iteritems(instance):
            if re.search(pattern, k):
                for error in validator.descend(
                        v, subschema, path=k, schema_path=pattern
                ):
                    yield error
Ejemplo n.º 2
0
        def iter_errors(self, instance, _schema=None):
            if _schema is None:
                _schema = self.schema

            with self.resolver.in_scope(_schema.get("id", "")):
                ref = _schema.get("$ref")
                if ref is not None:
                    validators = [("$ref", ref)]
                else:
                    validators = iteritems(_schema)

                for k, v in validators:
                    validator = self.VALIDATORS.get(k)
                    if validator is None:
                        continue

                    errors = validator(self, v, instance, _schema) or ()
                    for error in errors:
                        # set details if not already set by the called fn
                        error._set(
                            validator=k,
                            validator_value=v,
                            instance=instance,
                            schema=_schema,
                        )
                        if k != "$ref":
                            error.schema_path.appendleft(k)
                        yield error
Ejemplo n.º 3
0
def list_threads():
    """List all available threads in most efficient way."""
    def order(item):
        """Order Threads by latest comment or start time."""
        thread = item[1]
        timestamp = thread['timestamp']
        return thread.get('last_comment', {}).get('timestamp') or timestamp

    # Read Threads from Links and Content databases
    with content.pipeline() as pipe:
        uids = []
        for thread_uid in links.lrange(build_key(THREADS_KEY), 0, -1):
            pipe.hgetall(build_key(THREAD_KEY, thread_uid))
            uids.append(thread_uid)
        threads = dict(zip(uids, pipe.execute()))

    # Make another multi request for threads' counters and last comments where
    # possible
    comments_request = OrderedDict()

    for thread_uid, thread in iteritems(threads):
        last_comment_uid = thread.get('last_comment_uid')
        if not last_comment_uid:
            continue
        comments_request[thread_uid] = thread['last_comment_uid']

    # We assume that last comment and comments counter available only for
    # threads with comments
    if comments_request:
        with links.pipeline() as pipe:
            for thread_uid in iterkeys(comments_request):
                pipe.get(build_key(THREAD_COUNTER_KEY, thread_uid))
            response = zip(iterkeys(comments_request), pipe.execute())

        for thread_uid, counter in response:
            threads[thread_uid]['comments_counter'] = counter

        with content.pipeline() as pipe:
            for thread_uid, comment_uid in iteritems(comments_request):
                key = build_key(COMMENT_KEY, thread_uid, comment_uid)
                pipe.hgetall(key)
            response = zip(iterkeys(comments_request), pipe.execute())

        for thread_uid, comment in response:
            threads[thread_uid]['last_comment'] = comment

    return OrderedDict(sorted(iteritems(threads), key=order, reverse=True))
Ejemplo n.º 4
0
    def total_errors(self):
        """
        The total number of errors in the entire tree, including children.

        """

        child_errors = sum(len(tree) for _, tree in iteritems(self._contents))
        return len(self.errors) + child_errors
Ejemplo n.º 5
0
 def update(self, other_dict):
     if not isinstance(other_dict, dict):
         raise TypeError('%r is not a dict.' % other_dict)
     now = datetime.datetime.now()
     tmp = {}
     for k, v in iteritems(other_dict):
         tmp[k] = [v, now]
     super(TimerDict, self).update(tmp)
Ejemplo n.º 6
0
def properties_draft4(validator, properties, instance, schema):
    if not validator.is_type(instance, "object"):
        return

    for property, subschema in iteritems(properties):
        if property in instance:
            for error in validator.descend(
                instance[property],
                subschema,
                path=property,
                schema_path=property,
            ):
                yield error
Ejemplo n.º 7
0
    def __init__(self, mapping=None, max_lifespan=3600*24*3):
        self.max_lifespan = 0
        self.set_lifespan(max_lifespan)

        now = datetime.datetime.now()
        tmp = {}
        if isinstance(mapping, dict):
            for k, v in iteritems(mapping):
                tmp[k] = [v, now]
            super(TimerDict, self).__init__(tmp)
        # todo: ...
        else:
            for k, v in mapping or ():
                tmp[k] = [v, now]
            super(TimerDict, self).__init__(tmp)
Ejemplo n.º 8
0
    def __init__(
        self, base_uri, referrer, store=(), cache_remote=True, handlers=(),
    ):
        self.base_uri = base_uri
        self.resolution_scope = base_uri
        # This attribute is not used, it is for backwards compatibility
        self.referrer = referrer
        self.cache_remote = cache_remote
        self.handlers = dict(handlers)

        self.store = _utils.URIDict(
            (id, validator.META_SCHEMA)
            for id, validator in iteritems(meta_schemas)
        )
        self.store.update(store)
        self.store[base_uri] = referrer
Ejemplo n.º 9
0
    def mySpawn(sh, escape, cmd, args, env):

        newargs = ' '.join(args[1:])
        cmdline = cmd + " " + newargs

        rv = 0
        env = {str(key): str(value) for key, value in iteritems(env)}
        if len(cmdline) > 32000 and cmd.endswith("ar"):
            cmdline = cmd + " " + args[1] + " " + args[2] + " "
            for i in range(3, len(args)):
                rv = mySubProcess(cmdline + args[i], env)
                if rv:
                    break
        else:
            rv = mySubProcess(cmdline, env)

        return rv
Ejemplo n.º 10
0
def main():
    """Wipe all data from Links and Content storages."""
    start_time = time.time()
    print('Start deleting available Threads')

    with app.app_context():
        # Storage requires app in global context
        import storage

        for thread_uid, thread in iteritems(storage.list_threads()):
            storage.delete_thread(thread_uid)
            print('    Thread deleted! UID #{0}, subject: {1}'.
                  format(thread_uid, thread['subject']))

        storage.links.delete(build_key(THREADS_KEY))

    print('All Threads deleted. Done in {0:.4f}s'.
          format(time.time() - start_time))
    return False
Ejemplo n.º 11
0
def dependencies(validator, dependencies, instance, schema):
    if not validator.is_type(instance, "object"):
        return

    for property, dependency in iteritems(dependencies):
        if property not in instance:
            continue

        if validator.is_type(dependency, "object"):
            for error in validator.descend(
                    instance, dependency, schema_path=property
            ):
                yield error
        else:
            dependencies = _utils.ensure_list(dependency)
            for dependency in dependencies:
                if dependency not in instance:
                    yield ValidationError(
                        "%r is a dependency of %r" % (dependency, property)
                    )
Ejemplo n.º 12
0
def properties_draft3(validator, properties, instance, schema):
    if not validator.is_type(instance, "object"):
        return

    for property, subschema in iteritems(properties):
        if property in instance:
            for error in validator.descend(
                instance[property],
                subschema,
                path=property,
                schema_path=property,
            ):
                yield error
        elif subschema.get("required", False):
            error = ValidationError("%r is a required property" % property)
            error._set(
                validator="required",
                validator_value=subschema["required"],
                instance=instance,
                schema=schema,
            )
            error.path.appendleft(property)
            error.schema_path.extend([property, "required"])
            yield error
Ejemplo n.º 13
0
                             5: "wlan_interface_state_associating",
                             6: "wlan_interface_state_discovering",
                             7: "wlan_interface_state_authenticating"}

# The DOT11_MAC_ADDRESS types are used to define an IEEE media access control
# (MAC) address.
DOT11_MAC_ADDRESS = c_ubyte * 6

# The DOT11_BSS_TYPE enumerated type defines a basic service set (BSS) network
# type.
DOT11_BSS_TYPE = c_uint
DOT11_BSS_TYPE_DICT_KV = {1: "dot11_BSS_type_infrastructure",
                          2: "dot11_BSS_type_independent",
                          3: "dot11_BSS_type_any"}
DOT11_BSS_TYPE_DICT_VK = { v: k for k, v in
        iteritems(DOT11_BSS_TYPE_DICT_KV) }

# The DOT11_PHY_TYPE enumeration defines an 802.11 PHY and media type.
DOT11_PHY_TYPE = c_uint
DOT11_PHY_TYPE_DICT = {0: "dot11_phy_type_unknown",
                       1: "dot11_phy_type_fhss",
                       2: "dot11_phy_type_dsss",
                       3: "dot11_phy_type_irbaseband",
                       4: "dot11_phy_type_ofdm",
                       5: "dot11_phy_type_hrdsss",
                       6: "dot11_phy_type_erp",
                       7: "dot11_phy_type_ht",
                       0x80000000: "dot11_phy_type_IHV_start",
                       0xffffffff: "dot11_phy_type_IHV_end"}

# The DOT11_AUTH_ALGORITHM enumerated type defines a wireless LAN
Ejemplo n.º 14
0
def make_license_header(target, source, env):
    src_copyright = source[0]
    src_license = source[1]
    dst = target[0]

    class LicenseReader:
        def __init__(self, license_file):
            self._license_file = license_file
            self.line_num = 0
            self.current = self.next_line()

        def next_line(self):
            line = self._license_file.readline()
            self.line_num += 1
            while line.startswith("#"):
                line = self._license_file.readline()
                self.line_num += 1
            self.current = line
            return line

        def next_tag(self):
            if not ':' in self.current:
                return ('', [])
            tag, line = self.current.split(":", 1)
            lines = [line.strip()]
            while self.next_line() and self.current.startswith(" "):
                lines.append(self.current.strip())
            return (tag, lines)

    from collections import OrderedDict
    projects = OrderedDict()
    license_list = []

    with open_utf8(src_copyright, "r") as copyright_file:
        reader = LicenseReader(copyright_file)
        part = {}
        while reader.current:
            tag, content = reader.next_tag()
            if tag in ("Files", "Copyright", "License"):
                part[tag] = content[:]
            elif tag == "Comment":
                # attach part to named project
                projects[content[0]] = projects.get(content[0], []) + [part]

            if not tag or not reader.current:
                # end of a paragraph start a new part
                if "License" in part and not "Files" in part:
                    # no Files tag in this one, so assume standalone license
                    license_list.append(part["License"])
                part = {}
                reader.next_line()

    data_list = []
    for project in itervalues(projects):
        for part in project:
            part["file_index"] = len(data_list)
            data_list += part["Files"]
            part["copyright_index"] = len(data_list)
            data_list += part["Copyright"]

    with open_utf8(dst, "w") as f:

        f.write("/* THIS FILE IS GENERATED DO NOT EDIT */\n")
        f.write("#ifndef _EDITOR_LICENSE_H\n")
        f.write("#define _EDITOR_LICENSE_H\n")
        f.write("const char *const GODOT_LICENSE_TEXT =")

        with open_utf8(src_license, "r") as license_file:
            for line in license_file:
                escaped_string = escape_string(line.strip())
                f.write("\n\t\t\"" + escaped_string + "\\n\"")
        f.write(";\n\n")

        f.write("struct ComponentCopyrightPart {\n"
                "\tconst char *license;\n"
                "\tconst char *const *files;\n"
                "\tconst char *const *copyright_statements;\n"
                "\tint file_count;\n"
                "\tint copyright_count;\n"
                "};\n\n")

        f.write("struct ComponentCopyright {\n"
                "\tconst char *name;\n"
                "\tconst ComponentCopyrightPart *parts;\n"
                "\tint part_count;\n"
                "};\n\n")

        f.write("const char *const COPYRIGHT_INFO_DATA[] = {\n")
        for line in data_list:
            f.write("\t\"" + escape_string(line) + "\",\n")
        f.write("};\n\n")

        f.write("const ComponentCopyrightPart COPYRIGHT_PROJECT_PARTS[] = {\n")
        part_index = 0
        part_indexes = {}
        for project_name, project in iteritems(projects):
            part_indexes[project_name] = part_index
            for part in project:
                f.write("\t{ \"" + escape_string(part["License"][0]) + "\", "
                        + "&COPYRIGHT_INFO_DATA[" + str(part["file_index"]) + "], "
                        + "&COPYRIGHT_INFO_DATA[" + str(part["copyright_index"]) + "], "
                        + str(len(part["Files"])) + ", "
                        + str(len(part["Copyright"])) + " },\n")
                part_index += 1
        f.write("};\n\n")

        f.write("const int COPYRIGHT_INFO_COUNT = " + str(len(projects)) + ";\n")

        f.write("const ComponentCopyright COPYRIGHT_INFO[] = {\n")
        for project_name, project in iteritems(projects):
            f.write("\t{ \"" + escape_string(project_name) + "\", "
                    + "&COPYRIGHT_PROJECT_PARTS[" + str(part_indexes[project_name]) + "], "
                    + str(len(project)) + " },\n")
        f.write("};\n\n")

        f.write("const int LICENSE_COUNT = " + str(len(license_list)) + ";\n")

        f.write("const char *const LICENSE_NAMES[] = {\n")
        for l in license_list:
            f.write("\t\"" + escape_string(l[0]) + "\",\n")
        f.write("};\n\n")

        f.write("const char *const LICENSE_BODIES[] = {\n\n")
        for l in license_list:
            for line in l[1:]:
                if line == ".":
                    f.write("\t\"\\n\"\n")
                else:
                    f.write("\t\"" + escape_string(line) + "\\n\"\n")
            f.write("\t\"\",\n\n")
        f.write("};\n\n")

        f.write("#endif\n")
Ejemplo n.º 15
0
 def _set(self, **kwargs):
     for k, v in iteritems(kwargs):
         if getattr(self, k) is _unset:
             setattr(self, k, v)
Ejemplo n.º 16
0
 def items(self, show_time=False):
     for k, v in iteritems(super(TimerDict, self)):
         if show_time:
             yield k, v
         else:
             yield k, v[0]