text:
"""
business-logic for libfs

The database contains 3 tables:
"views", "files" and "defaults".
"views" defines how the vitrual directory structure is created
"files" stores the actual information.

views has three columns:
view_name, directory_structure, filename_generator

- view_name is a string-identifier
- directory_structure is a csv-list in which order the metadata
are used to create the directory-structure.
- filename_generator is string, where %{key} is replaced by the corresponding
metadata, e.g. %{src_filename} just passes the original filename
whereas %{title} uses the title field.
"""

import errno
import logging
import os
import re

from importlib import import_module

from Libfs.misc import calltrace_logger, get_vpath_list
import json
import sys

LOGGER = logging.getLogger(__name__)

class BusinessLogic:
    """
    Accessing the actual DB for the library.
    """
    FILES_TABLE = "files"
    VTREE_TABLE = "trees"
    VIEWS_TABLE = "views"
    MAGIX_TABLE = "defaults"
    MAGIX_FIELD = "json"
    MAGIC_KEYS = ["valid_keys", "default_view"]
    DEFAULT_VIEW_NAME = "default"
    SRC_FILENAME_KEY = "src_filename"
    SRC_INODE_KEY = "src_inode"
    UNKNOWN = "Unknown"

    @calltrace_logger
    def __init__(self, db_connection, magix=None, current_view_name=None):
        """
        opens a sqlite file, does some checks,
        creates tables if required.
        """
        try:
            db_type, user, password, host, database = \
                re.match(r'(\S+)://(?:(.*?):(.*?))?(?:@(.*?)/)?(.*)', db_connection).groups()
        except AttributeError:
            # make sqlite3 with path the default
            if os.path.exists(db_connection) or os.path.isdir(os.path.dirname(db_connection)):
                db_type = "sqlite3"
                user = host = password = None
                database = db_connection
            else:
                sys.stderr.write("Cannot parse db-connection string.\n")
                sys.exit(1)

        try:
            db_module = import_module("Libfs.%s_be" % db_type)
            self.DB_BE = db_module.db_backend()
        except ImportError:
            sys.stderr.write("Sorry, database type %s not supported.\n" % db_type)
            sys.exit(2)

        # check if we can open the database at all.
        self.DB_BE.open(user, password, host, database)

        # check if the db contains all required tables
        if not self.check_db(): # do the table exist?
            do_setup_db = True
            # since we are creating the db, the default view must be DEFAULT_VIEW_NAME
            assert current_view_name in [self.DEFAULT_VIEW_NAME, None]
        else:
            do_setup_db = False

        if magix is None:
            self.magix = self.get_magix_from_db()
        else:
            self.magix = magix

        if current_view_name is None:
            self.current_view_name = self.DEFAULT_VIEW_NAME
            self.current_view = self.magix["default_view"]
        else:
            self.current_view_name = current_view_name
            self.current_view = self.get_view(self.current_view_name)

        self.setup_filename_parsing()

        if do_setup_db:
            self.setup_db()

        self.metadata_plugin = import_module("Libfs.plugins.%s" % (self.magix["plugin"]))

        self.ordered_files_keys = self.DB_BE.get_columns(self.FILES_TABLE)

        self.check_tables()
        LOGGER.debug("init: self.current_view = %s", self.current_view)

        self.max_dir_level = len(self.current_view["dirtree"])

        # in-memory cache for bookkeeping
        self.vdirs = []
        self.vtree = self.generate_vtree()
        # still in operations
        # pinode_fn2srcpath_map

    @calltrace_logger
    def lookup_dir(self, vpath):
        """
        return inode number of a vdir in the db
        """
        @calltrace_logger
        def do_lookup_dir(vtree, vpath_list, result):
            """
            recursive function to walk through the
            directory-levels i.e. db-keys
            """
            LOGGER.debug("do_lookup_dir: vtree=%s vpath_list=%s, result=%s",
                         vtree, vpath_list, result)
            if isinstance(vpath_list, str):
                LOGGER.debug("do_lookup_dir: encountered string.-> returning true")
                return result
            if len(vpath_list) == 0:
                LOGGER.debug("do_lookup_dir: vpath_list empty.")
                return True
            if vpath_list[0] in vtree.keys():
                return  do_lookup_dir(vtree[vpath_list[0]], vpath_list[1:], result)
            else:
                return False

        if do_lookup_dir(self.vtree, get_vpath_list(vpath), True):
            result = self.get_vdir_inode(vpath)
        else:
            result = False
        return result

    @calltrace_logger
    def seek_vtree(self, vpath="", vpath_list=None):
        """
        check, if a given vpath or vpath_list does actually exists.
        """
        def do_seek_vtree(vtree, vpath_list):
            """
            recursive fct to walk through the db by the current_view
            """
            if len(vpath_list) == 0:
                return vtree
            if vpath_list[0] in vtree.keys():
                return do_seek_vtree(vtree[vpath_list[0]], vpath_list[1:])
            else:
                sys.stderr.write("Internal Error: cannot find %s in vtree %s.\n" %
                                 (vpath_list, vtree))
                return False

        if vpath != "":
            vpath_list = get_vpath_list(vpath)
        if vpath_list is None:
            return self.vtree

        if len(vpath_list) > self.max_dir_level:
            raise RuntimeError("seek_vtree: len(vpath_list=%s) > self.max_dir_level=%s",
                               vpath_list, self.max_dir_level)
        result = do_seek_vtree(self.vtree, vpath_list)
        if not result:
            sys.stderr.write("Internal Error: cannot find %s or %s in vtree.\n" %
                             (vpath, vpath_list))
        return result

    @calltrace_logger
    def mkdir(self, vpath):
        """
        add dir to vtree. It stays only in memory and will only be commited to the
        db whenever a file is actually moved there.
        """
        vpath_list = get_vpath_list(vpath)
        dir_level = len(vpath_list) - 1
        LOGGER.debug("mkdir: vpath_list=%s, dir_level=%s", vpath, dir_level)
        # check validity of new metadata
        key = self.current_view["dirtree"][dir_level]
        value = vpath_list[-1]
        LOGGER.debug("checking key=\"%s\", value=\"%s\"", key, value)
        if not self.metadata_plugin.is_valid_metadata(key, value):
            return -errno.EINVAL
        # add this directory in the in-memory structures
        LOGGER.debug("vpath_list[:-1]=%s", vpath_list[:-1])
        LOGGER.debug("vtree=%s", self.vtree)
        this_vtree = self.seek_vtree(vpath_list=vpath_list[:-1])
        vnode = self.get_vdir_inode(vpath)
        this_vtree[vpath_list[-1]] = {}
        return vnode

    @calltrace_logger
    def rmdir(self, vpath):
        """
        remove a directory from the vpath.
        Throw an exception if dir is not empty
        """
        contents = self.get_contents_by_vpath(vpath)
        if len(contents) > 2:
            raise FUSEError(errno.ENOTEMPTY)
        return

    @calltrace_logger
    def get_vdir_inode(self, canon_path):
        """
        put vpath in a module-local cache
        """
        if not canon_path in self.vdirs:
            self.vdirs.append(canon_path)
        vnode = self.vdirs.index(canon_path) + 1
        return vnode

    @calltrace_logger
    def walk_vtree(self, node):
        """
        iterate tree in pre-order depth-first search order
        """
        yield node
        for child in node.children:
            for item in self.walk_vtree(child):
                yield item

    @calltrace_logger
    def get_magix_from_db(self):
        """
        read the magic constants from the db
        """
        res = self.DB_BE.execute_statment("select %s from %s" %
                                          (self.MAGIX_FIELD, self.MAGIX_TABLE))
        res = res[0][0]
        magix = json.loads(res)
        LOGGER.debug("magix=%s", magix)
        return magix

    @calltrace_logger
    def setup_db(self):
        """
        creates a new db.
        Creates tables "views" and "files"
        Sets defaults views.
        """

        self.DB_BE.execute_statment("create table %s ('%s' text)" %
                                    (self.MAGIX_TABLE, self.MAGIX_FIELD))
        self.DB_BE.execute_statment("insert into %s (%s) values('%s')" %
                                    (self.MAGIX_TABLE, self.MAGIX_FIELD, json.dumps(self.magix)))
        self.DB_BE.execute_statment("create table %s (name varchar unique, json text)" %
                                    (self.VIEWS_TABLE))
        self.DB_BE.execute_statment("insert into %s (name, json) values ('%s', '%s')" %
                                    (self.VIEWS_TABLE, self.DEFAULT_VIEW_NAME,
                                     json.dumps(self.current_view)))
        self.DB_BE.execute_statment("create table %s (%s varchar unique, %s integer unique, %s)" %
                                    (self.FILES_TABLE, self.SRC_FILENAME_KEY, self.SRC_INODE_KEY,
                                     ",".join(self.magix["valid_keys"])))
        self.DB_BE.commit()
        return

    @calltrace_logger
    def generate_vtree(self):
        """
        generate a dict representing the tree in the current view
        """
        def build_dict(vtree, tpl):
            """
            internal recursvie helper function
            """
            LOGGER.debug("build_vtree: %s %s", vtree, tpl)
            if len(tpl) == 0:
                return
            if not tpl[0] in vtree.keys():
                vtree[tpl[0]] = {}
            build_dict(vtree[tpl[0]], tpl[1:])
            return vtree

        self.vtree = {}
        res = self.DB_BE.execute_statment("SELECT DISTINCT %s from %s;" %
                                          (",".join(self.current_view["dirtree"]),
                                           self.FILES_TABLE))
        for tpl in res:
            self.vtree = build_dict(self.vtree, tpl)
        return

    @calltrace_logger
    def check_db(self):
        """
        checks tables for exinstance.
        """
        # get tables
        res = self.DB_BE.execute_statment("SELECT name FROM sqlite_master WHERE type='table';")
        tables = [tpl[0] for tpl in res]
        for _tab in [self.VIEWS_TABLE, self.FILES_TABLE]:
            if not _tab in tables:
                return False
        return True

    @calltrace_logger
    def check_tables(self):
        """
        check tables in database for validity.
        """
        # check FILES_TABLE for valid_keys
        for k in [self.SRC_FILENAME_KEY, self.SRC_INODE_KEY]:
            if not k in self.ordered_files_keys:
                sys.stderr.write("Internal Error: Mandatory key %s does not exist in db %s.\n" %
                                 (k, self.DB_BE))
                sys.stderr.write("Delete and recreate the library.\n")
                sys.exit(1)

        LOGGER.debug("self.ordered_keys=%s", self.ordered_files_keys)
        LOGGER.debug("self.magix[valid_keys]=%s", self.magix["valid_keys"])
        for k in self.ordered_files_keys:
            if k in [self.SRC_FILENAME_KEY, self.SRC_INODE_KEY]:
                continue
            if not k in self.magix["valid_keys"]:
                sys.stderr.write("Internal Error: Key %s is not valid.\n" % k)
                sys.stderr.write("Did you choose the right library-type ?\n")
                sys.stderr.write("Otherwise delete and recreate the library.\n")
                sys.exit(1)

        for k in self.magix["valid_keys"]:
            if not k in self.ordered_files_keys:
                sys.stderr.write("Internal Error: Valid key %s does not exist in db %s.\n" %
                                 (k, self.DB_BE))
                sys.stderr.write("Did you choose the right library-type ?\n")
                sys.stderr.write("Otherwise delete and recreate the library.\n")
                sys.exit(1)
        return

    @calltrace_logger
    def is_vdir(self, path):
        """
        return true if we have a virtual directory
        """
        # path must be canonicalized: start with a single /
        vpath_list = get_vpath_list(path)
        if len(vpath_list) > self.max_dir_level:
            return False
        LOGGER.debug("is_vdir: returning True")
        return True

    @calltrace_logger
    def get_key_of_vpath(self, vpath):
        """
        return the db field-name of this vpath
        """
        vpath_list = get_vpath_list(vpath)
        return self.current_view["dirtree"][len(vpath_list)]

    @calltrace_logger
    def add_entry(self, src_filename, metadata):
        """
        Adds a file-entry.
        """
        src_statinfo = os.stat(src_filename)
        metadata[self.SRC_FILENAME_KEY] = src_filename
        metadata[self.SRC_INODE_KEY] = src_statinfo.st_ino
        LOGGER.debug("metadata=%s", metadata)
        values = []
        for k in self.ordered_files_keys:
            try:
                values.append("%s" % metadata.get(k, self.UNKNOWN))
            except:
                sys.stderr.write("Ignoring Key %s, Values %s is not a string."\
                                 % (k, (metadata[k],)))
        # changing a list within a loop over itself,
        # huuu, but this should work
        for i, item  in enumerate(values):
            if len(item) == 0:
                values[i] = self.UNKNOWN
        values_param_str = ",".join(["?" for x in values])

        try:
            LOGGER.debug("ordered_files_keys = %s", self.ordered_files_keys)
            query_str = "INSERT INTO %s VALUES (%s)" % (self.FILES_TABLE, values_param_str)
            self.DB_BE.execute_statment(query_str, *values)
        except self.DB_BE.IntegrityError:
            update_str = ""
            for k in self.ordered_files_keys:
                update_str += "%s=?, " % (k)
            update_str = update_str[:-2]
            values.append(src_filename)
            query_str = "UPDATE %s SET %s WHERE src_filename=?" % (self.FILES_TABLE, update_str)
            self.DB_BE.execute_statment(query_str, *values)
        self.DB_BE.commit()
        # revert modifications to metadata
        metadata.pop(self.SRC_FILENAME_KEY)
        metadata.pop(self.SRC_INODE_KEY)
        return

    @calltrace_logger
    def remove_entry(self, src_filename):
        """
        removes a file-entry
        """
        self.DB_BE.execute_statment("DELETE from %s WHERE src_filename=?" %
                                    (self.FILES_TABLE), src_filename)
        self.DB_BE.commit()
        return

    @calltrace_logger
    def get_entry(self, src_filename):
        """
        returns the metadata to a src_filename
        """
        try:
            query_str = "SELECT %s FROM %s WHERE src_filename=?;" % \
               (",".join(["?" for x in self.ordered_files_keys]), self.FILES_TABLE)
            res = self.DB_BE.execute_statment(query_str, self.ordered_files_keys, src_filename)
            return res[0]
        except IndexError:
            return None

    @calltrace_logger
    def update_column(self, old_vpath_list, new_vpath_list):
        """
        when renaming a vdir, we have to update all concerned rows
        """
        assert len(old_vpath_list) == len(new_vpath_list)
        assert old_vpath_list != new_vpath_list
        where = ""
        update = ""
        for i, old_item in enumerate(old_vpath_list):
            new_item = new_vpath_list[i]
            LOGGER.debug("comparing old %s to new %s", old_item, new_item)
            where += "%s='%s' AND " % (self.current_view["dirtree"][i], old_item)
            if old_item != new_item:
                update += "%s='%s', " % (self.current_view["dirtree"][i], new_item)
        where = where[:-len("AND ")]
        update = update[:-len(", ")]
        self.DB_BE.execute_statment("UPDATE %s set %s WHERE %s" % (self.FILES_TABLE, update, where))
        self.DB_BE.commit()
        return

    @calltrace_logger
    def get_view(self, view_name):
        """
        returns the order in which virtual directories
        are created.
        """
        try:
            res = self.DB_BE.execute_statment("select name, json from %s WHERE name='%s';" %
                                              (self.VIEWS_TABLE, view_name))
            return json.loads(res[0])
        except IndexError:
            return None
        return

    @calltrace_logger
    def set_view(self, view_name, view):
        """
        sets directory creation order
        """
        # check if dirtree is valid
        for subdir in view["dirtree"]:
            if not subdir in self.magix["valid_keys"]:
                raise RuntimeError("set_view: Key %s is not valid." % subdir)
        self.DB_BE.execute_statment("insert into %s (name, json) values (%s, '%s')" %
                                    (self.VIEWS_TABLE, view_name, json.dumps(view)))
        self.DB_BE.commit()
        return

    @calltrace_logger
    def get_all_src_names(self):
        """
        return list of all src_names in db
        """
        res = self.DB_BE.execute_statment("SELECT %s FROM %s;" %
                                          (self.SRC_FILENAME_KEY, self.FILES_TABLE))
        return [tpl[0] for tpl in res]

    @calltrace_logger
    def get_srcfilename_by_srcinode(self, inode):
        """
        return src_filename
        """
        res = self.DB_BE.execute_statment("SELECT %s FROM %s WHERE %s=%s;" %
                                          (self.SRC_FILENAME_KEY, self.FILES_TABLE,
                                           self.SRC_INODE_KEY, inode))
        return res[0][0]

    @calltrace_logger
    def get_vpath_dict(self, vpath):
        """
        get a dict view_level = path
        """
        vpath_dict = {}
        vpath_list = get_vpath_list(vpath)
        for i, item in enumerate(vpath_list):
            vpath_dict[self.current_view["dirtree"][i]] = item
        LOGGER.debug("get_vpath_dict: %s -> %s", vpath, vpath_dict)
        return vpath_dict

    #
    # actually used for FUSE
    #

    def get_gen_filename(self, src_filename):
        """
        generate a virtual filename
        """
        gen_fn = self.current_view["fn_gen"]
        gen_fn = gen_fn.replace("%{src_filename}", os.path.basename(src_filename))
        query_str = "SELECT %s FROM %s WHERE src_filename=?;" % \
                    (",".join(self.magix["valid_keys"]), self.FILES_TABLE)
        res = self.DB_BE.execute_statment(query_str, src_filename)
        all_file_keys = res[0]
        LOGGER.debug("get_gen_filename src_filename:%s all_file_keys:%s",
                     src_filename, all_file_keys)
        for i, item in enumerate(self.magix["valid_keys"]):
            gen_fn = gen_fn.replace("%%{%s}" % (item), all_file_keys[i])
        return gen_fn

    def setup_filename_parsing(self):
        """
        compile the regular expression for the filename parsing
        """
        i = 0
        inside_key = False
        this_key = ""
        self.fn_gen_keys = []
        fn_generator = self.current_view["fn_gen"]
        reg_ex = ""
        # create a regex and key mapping
        while i < len(fn_generator):
            if inside_key:
                if fn_generator[i] == "}":
                    inside_key = False
                    self.fn_gen_keys.append(this_key)
                else:
                    this_key += fn_generator[i]
                i += 1
                continue

            if fn_generator[i] == "%":
                try:
                    if fn_generator[i+1] == "{":
                        inside_key = True
                        i += 2
                        this_key = ""
                        reg_ex += "(.*)"
                        continue
                except IndexError:
                    pass
            reg_ex += fn_generator[i]
            i += 1
        self.fn_regex = re.compile(reg_ex)
        return

    @calltrace_logger
    def get_metadata_from_gen_filename(self, gen_filename):
        """
        return a metadata-dict from a virtual filename
        """
        try:
            values = self.fn_regex.match(gen_filename).groups()
        except AttributeError:
            raise RuntimeError("get_metadata_from_gen_filename: "\
                               "Given filename does not match pattern %s" % self.fn_regex.pattern)

        if len(values) != len(self.fn_gen_keys):
            raise RuntimeError("get_metadata_from_gen_filename: "\
                       "Given filename match pattern %s, but gives incorrect number of items."\
                       "keys %s != values %s" % (self.fn_regex.pattern, self.fn_gen_keys, values))
        fn_metadata = {}
        for i, item in enumerate(self.fn_gen_keys):
            fn_metadata[item] = values[i]
        return fn_metadata

    @calltrace_logger
    def get_contents_by_vpath(self, vpath):
        """
        returns contents of virtual directory
        files are only returned and the very leaf of the current_view
        duplicate files have a (libfs:%d) counter appended on the spot.
        """
        LOGGER.debug("get_contents_by_vpath got vpath: %s", vpath)
        vpath_list = get_vpath_list(vpath)
        dir_level = len(vpath_list)
        LOGGER.debug("get_contents_by_vpath got tokens: %s", vpath_list)
        contents = []

        # add "." and ".." entries
        vnode = self.get_vdir_inode(vpath)
        contents.append((vnode, ".", None))
        if dir_level > 0:
            upper_vpath = "/".join(vpath_list[:-1])
            vnode = self.get_vdir_inode(upper_vpath)
            contents.append((vnode, "..", None))
        else:
            contents.append((-1, "..", "MOUNTPOINT_PARENT"))

        # we are at the end of the tree
        if dir_level == self.max_dir_level:
            where = ""
            for i, item in enumerate(vpath_list):
                where += "%s='%s' AND " % (self.current_view["dirtree"][i], item)
            where = where[:-len("AND ")]
            res = self.DB_BE.execute_statment("SELECT src_inode, src_filename FROM %s WHERE %s;" %
                                              (self.FILES_TABLE, where))
            file_name_occurrences = {}
            for src_inode, src_filename in res:
                file_vname = self.get_gen_filename(src_filename)
                if file_vname in file_name_occurrences:
                    file_name_occurrences[file_vname] += 1
                    file_vname = "%s (libfs:%d)" % (file_vname, file_name_occurrences[file_vname])
                else:
                    file_name_occurrences[file_vname] = 0
                contents.append((src_inode, file_vname, src_filename))
        else: # in vtree
            for val in self.seek_vtree(vpath_list=vpath_list):
                # path within a vdir must not be empty,
                # otherwise it is assinged to the dirvnode of the parent vdir
                assert len(val) > 0
                contents.append((self.get_vdir_inode(os.path.join(vpath, val)), val, None))

        LOGGER.debug("get_contents_by_vpath returning: %s", contents)
        # return vnode for contents
        return contents

    def get_inode_by_srcfilename(self, src_filename):
        """
        return the inode from a src_filename, callend by rename
        """
        res = self.DB_BE.execute_statment("SELECT src_inode FROM %s WHERE src_filename=?;" %
                                          (self.FILES_TABLE), src_filename)
        LOGGER.debug("result = %s", res)
        assert len(res) == 1
        return res[0][0]


text:
WINRT_EXPORT namespace winrt {

namespace ABI::Windows::Foundation {

#ifndef WINRT_GENERIC_d6b166ec_099a_5ee2_ad2e_f4c88614aabb
#define WINRT_GENERIC_d6b166ec_099a_5ee2_ad2e_f4c88614aabb
template <> struct __declspec(uuid("d6b166ec-099a-5ee2-ad2e-f4c88614aabb")) __declspec(novtable) IAsyncOperation<Windows::Data::Pdf::PdfDocument> : impl_IAsyncOperation<Windows::Data::Pdf::PdfDocument> {};
#endif

#ifndef WINRT_GENERIC_8d4950b3_629d_5d7d_84cc_04c0dcf7942b
#define WINRT_GENERIC_8d4950b3_629d_5d7d_84cc_04c0dcf7942b
template <> struct __declspec(uuid("8d4950b3-629d-5d7d-84cc-04c0dcf7942b")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Data::Pdf::PdfDocument> : impl_AsyncOperationCompletedHandler<Windows::Data::Pdf::PdfDocument> {};
#endif

}

namespace Windows::Data::Pdf {

template <typename D>
struct WINRT_EBO impl_IPdfDocument
{
    Windows::Data::Pdf::PdfPage GetPage(uint32_t pageIndex) const;
    uint32_t PageCount() const;
    bool IsPasswordProtected() const;
};

template <typename D>
struct WINRT_EBO impl_IPdfDocumentStatics
{
    Windows::Foundation::IAsyncOperation<Windows::Data::Pdf::PdfDocument> LoadFromFileAsync(const Windows::Storage::IStorageFile & file) const;
    Windows::Foundation::IAsyncOperation<Windows::Data::Pdf::PdfDocument> LoadFromFileAsync(const Windows::Storage::IStorageFile & file, hstring_ref password) const;
    Windows::Foundation::IAsyncOperation<Windows::Data::Pdf::PdfDocument> LoadFromStreamAsync(const Windows::Storage::Streams::IRandomAccessStream & inputStream) const;
    Windows::Foundation::IAsyncOperation<Windows::Data::Pdf::PdfDocument> LoadFromStreamAsync(const Windows::Storage::Streams::IRandomAccessStream & inputStream, hstring_ref password) const;
};

template <typename D>
struct WINRT_EBO impl_IPdfPage
{
    Windows::Foundation::IAsyncAction RenderToStreamAsync(const Windows::Storage::Streams::IRandomAccessStream & outputStream) const;
    Windows::Foundation::IAsyncAction RenderToStreamAsync(const Windows::Storage::Streams::IRandomAccessStream & outputStream, const Windows::Data::Pdf::PdfPageRenderOptions & options) const;
    Windows::Foundation::IAsyncAction PreparePageAsync() const;
    uint32_t Index() const;
    Windows::Foundation::Size Size() const;
    Windows::Data::Pdf::PdfPageDimensions Dimensions() const;
    Windows::Data::Pdf::PdfPageRotation Rotation() const;
    float PreferredZoom() const;
};

template <typename D>
struct WINRT_EBO impl_IPdfPageDimensions
{
    Windows::Foundation::Rect MediaBox() const;
    Windows::Foundation::Rect CropBox() const;
    Windows::Foundation::Rect BleedBox() const;
    Windows::Foundation::Rect TrimBox() const;
    Windows::Foundation::Rect ArtBox() const;
};

template <typename D>
struct WINRT_EBO impl_IPdfPageRenderOptions
{
    Windows::Foundation::Rect SourceRect() const;
    void SourceRect(const Windows::Foundation::Rect & value) const;
    uint32_t DestinationWidth() const;
    void DestinationWidth(uint32_t value) const;
    uint32_t DestinationHeight() const;
    void DestinationHeight(uint32_t value) const;
    Windows::UI::Color BackgroundColor() const;
    void BackgroundColor(const Windows::UI::Color & value) const;
    bool IsIgnoringHighContrast() const;
    void IsIgnoringHighContrast(bool value) const;
    GUID BitmapEncoderId() const;
    void BitmapEncoderId(GUID value) const;
};

struct IPdfDocument :
    Windows::IInspectable,
    impl::consume<IPdfDocument>
{
    IPdfDocument(std::nullptr_t = nullptr) noexcept {}
    auto operator->() const noexcept { return ptr<IPdfDocument>(m_ptr); }
};

struct IPdfDocumentStatics :
    Windows::IInspectable,
    impl::consume<IPdfDocumentStatics>
{
    IPdfDocumentStatics(std::nullptr_t = nullptr) noexcept {}
    auto operator->() const noexcept { return ptr<IPdfDocumentStatics>(m_ptr); }
};

struct IPdfPage :
    Windows::IInspectable,
    impl::consume<IPdfPage>
{
    IPdfPage(std::nullptr_t = nullptr) noexcept {}
    auto operator->() const noexcept { return ptr<IPdfPage>(m_ptr); }
};

struct IPdfPageDimensions :
    Windows::IInspectable,
    impl::consume<IPdfPageDimensions>
{
    IPdfPageDimensions(std::nullptr_t = nullptr) noexcept {}
    auto operator->() const noexcept { return ptr<IPdfPageDimensions>(m_ptr); }
};

struct IPdfPageRenderOptions :
    Windows::IInspectable,
    impl::consume<IPdfPageRenderOptions>
{
    IPdfPageRenderOptions(std::nullptr_t = nullptr) noexcept {}
    auto operator->() const noexcept { return ptr<IPdfPageRenderOptions>(m_ptr); }
};

}

}

redpajama_set_name: RedPajamaGithub


text:
namespace navirice {

	class ServerSettings {
		public:
			size_t RGB = 0;
			size_t IR = 0;
			size_t Depth = 0;

			bool is_equal(ServerSettings other);
	};

	class ImageDistributionServer {
		private:
			// SERVER ATTRIB
			uint16_t port;
			int listener;
			struct sockaddr_in serv_addr;
			ServerSettings settings;

			// SERVER DATA
			std::mutex current_image_mutex;
			std::mutex settings_mutex;
			ProtoImageSet images;
			uint64_t image_count;

			// THREADS
			std::thread* scl;
			void server_connection_listener();

			// UTIL
			std::string get_prompt();
			void handle_request(int cli_sock, sockaddr_in cli_addr);
			void pipe_function(int cli_sock, sockaddr_in cli_addr, ServerSettings* instance_setting);
			void send_image(int cli_sock, sockaddr_in cli_addr);

		public:
			ImageDistributionServer(uint16_t port);
			~ImageDistributionServer();
			ServerSettings get_server_settings();
			void set_new_images(Image* new_color_image, Image* new_ir_image, Image* new_depth_image);
	};

}

#endif


text:
package com.nulabinc.backlog.r2b.redmine.service

import javax.inject.Inject

import com.nulabinc.backlog.migration.common.utils.Logging
import com.taskadapter.redmineapi.RedmineManager
import com.taskadapter.redmineapi.bean.IssueStatus

import scala.jdk.CollectionConverters._

/**
  * @author uchida
  */
class StatusServiceImpl @Inject() (redmine: RedmineManager)
    extends StatusService
    with Logging {

  override def allStatuses(): Seq[IssueStatus] = {
    try {
      redmine.getIssueManager.getStatuses.asScala.toSeq
    } catch {
      case e: Throwable =>
        logger.warn(e.getMessage, e)
        Seq.empty[IssueStatus]
    }
  }

}


text:
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * CampaignGroupPerformanceTarget.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
 */

package com.google.api.ads.adwords.axis.v201809.cm;

/**
 * Data representing a campaign group performance target. A campaign
 * group performance target is an
 *             entity that specifies a time range for a campaign group
 * and various metrics by which the
 *             performance of that campaign group can be measured for
 * the time period that the performance
 *             target is active.
 */
public class CampaignGroupPerformanceTarget  implements java.io.Serializable {
    /* Id of this campaign group performance target.
     *                 This field can
     * be selected using the value "Id".This
     * field can be filtered on.
     *                 This field is read
     * only and will be ignored when sent to the API for the following {@link
     * Operator}s: ADD.
     *                 This field is required
     * and should not be {@code null} when it is contained within {@link
     * Operator}s : REMOVE, SET. */
    private java.lang.Long id;

    /* Id of the campaign group that this performance target is for.
     * This field can be selected using
     * the value "CampaignGroupId".This
     * field can be filtered on.
     *                 This field is required
     * and should not be {@code null}. */
    private java.lang.Long campaignGroupId;

    /* The main configuration of the performance target.
     *                 This field is required
     * and should not be {@code null} when it is contained within {@link
     * Operator}s : ADD, SET. */
    private com.google.api.ads.adwords.axis.v201809.cm.PerformanceTarget performanceTarget;

    public CampaignGroupPerformanceTarget() {
    }

    public CampaignGroupPerformanceTarget(
           java.lang.Long id,
           java.lang.Long campaignGroupId,
           com.google.api.ads.adwords.axis.v201809.cm.PerformanceTarget performanceTarget) {
           this.id = id;
           this.campaignGroupId = campaignGroupId;
           this.performanceTarget = performanceTarget;
    }

    @Override
    public String toString() {
        return com.google.common.base.MoreObjects.toStringHelper(this.getClass())
            .omitNullValues()
            .add("campaignGroupId", getCampaignGroupId())
            .add("id", getId())
            .add("performanceTarget", getPerformanceTarget())
            .toString();
    }

    /**
     * Gets the id value for this CampaignGroupPerformanceTarget.
     *
     * @return id   * Id of this campaign group performance target.
     *                 This field can
     * be selected using the value "Id".This
     * field can be filtered on.
     *                 This field is read
     * only and will be ignored when sent to the API for the following {@link
     * Operator}s: ADD.
     *                 This field is required
     * and should not be {@code null} when it is contained within {@link
     * Operator}s : REMOVE, SET.
     */
    public java.lang.Long getId() {
        return id;
    }

    /**
     * Sets the id value for this CampaignGroupPerformanceTarget.
     *
     * @param id   * Id of this campaign group performance target.
     *                 This field can
     * be selected using the value "Id".This
     * field can be filtered on.
     *                 This field is read
     * only and will be ignored when sent to the API for the following {@link
     * Operator}s: ADD.
     *                 This field is required
     * and should not be {@code null} when it is contained within {@link
     * Operator}s : REMOVE, SET.
     */
    public void setId(java.lang.Long id) {
        this.id = id;
    }

    /**
     * Gets the campaignGroupId value for this CampaignGroupPerformanceTarget.
     *
     * @return campaignGroupId   * Id of the campaign group that this performance target is for.
     * This field can be selected using
     * the value "CampaignGroupId".This
     * field can be filtered on.
     *                 This field is required
     * and should not be {@code null}.
     */
    public java.lang.Long getCampaignGroupId() {
        return campaignGroupId;
    }

    /**
     * Sets the campaignGroupId value for this CampaignGroupPerformanceTarget.
     *
     * @param campaignGroupId   * Id of the campaign group that this performance target is for.
     * This field can be selected using
     * the value "CampaignGroupId".This
     * field can be filtered on.
     *                 This field is required
     * and should not be {@code null}.
     */
    public void setCampaignGroupId(java.lang.Long campaignGroupId) {
        this.campaignGroupId = campaignGroupId;
    }

    /**
     * Gets the performanceTarget value for this CampaignGroupPerformanceTarget.
     *
     * @return performanceTarget   * The main configuration of the performance target.
     *                 This field is required
     * and should not be {@code null} when it is contained within {@link
     * Operator}s : ADD, SET.
     */
    public com.google.api.ads.adwords.axis.v201809.cm.PerformanceTarget getPerformanceTarget() {
        return performanceTarget;
    }

    /**
     * Sets the performanceTarget value for this CampaignGroupPerformanceTarget.
     *
     * @param performanceTarget   * The main configuration of the performance target.
     *                 This field is required
     * and should not be {@code null} when it is contained within {@link
     * Operator}s : ADD, SET.
     */
    public void setPerformanceTarget(com.google.api.ads.adwords.axis.v201809.cm.PerformanceTarget performanceTarget) {
        this.performanceTarget = performanceTarget;
    }

    private java.lang.Object __equalsCalc = null;
    public synchronized boolean equals(java.lang.Object obj) {
        if (!(obj instanceof CampaignGroupPerformanceTarget)) return false;
        CampaignGroupPerformanceTarget other = (CampaignGroupPerformanceTarget) obj;
        if (obj == null) return false;
        if (this == obj) return true;
        if (__equalsCalc != null) {
            return (__equalsCalc == obj);
        }
        __equalsCalc = obj;
        boolean _equals;
        _equals = true &&
            ((this.id==null && other.getId()==null) ||
             (this.id!=null &&
              this.id.equals(other.getId()))) &&
            ((this.campaignGroupId==null && other.getCampaignGroupId()==null) ||
             (this.campaignGroupId!=null &&
              this.campaignGroupId.equals(other.getCampaignGroupId()))) &&
            ((this.performanceTarget==null && other.getPerformanceTarget()==null) ||
             (this.performanceTarget!=null &&
              this.performanceTarget.equals(other.getPerformanceTarget())));
        __equalsCalc = null;
        return _equals;
    }

    private boolean __hashCodeCalc = false;
    public synchronized int hashCode() {
        if (__hashCodeCalc) {
            return 0;
        }
        __hashCodeCalc = true;
        int _hashCode = 1;
        if (getId() != null) {
            _hashCode += getId().hashCode();
        }
        if (getCampaignGroupId() != null) {
            _hashCode += getCampaignGroupId().hashCode();
        }
        if (getPerformanceTarget() != null) {
            _hashCode += getPerformanceTarget().hashCode();
        }
        __hashCodeCalc = false;
        return _hashCode;
    }

    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(CampaignGroupPerformanceTarget.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "CampaignGroupPerformanceTarget"));
        org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("id");
        elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "id"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("campaignGroupId");
        elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "campaignGroupId"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("performanceTarget");
        elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "performanceTarget"));
        elemField.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "PerformanceTarget"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
    }

    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Custom Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanSerializer(
            _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Custom Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanDeserializer(
            _javaType, _xmlType, typeDesc);
    }

}


text:
{{productDetails.name}}

                {{productDetails.main_image}}

{{productDetails.price}} {{currency}}

 {{productDetails.created_at |
                    date:"MM/dd/yyyy @ h:mma" }}

                <button type="button"
                        ng-click="addToCart()"
                        ng-disabled="isDisabled"
                        class="btn btn-success">Add to Cart
                </button>

Product categories:

                            {{ category.title }}


text:
package org.apache.flink.table.delegation;

import org.apache.flink.annotation.Internal;
import org.apache.flink.table.catalog.UnresolvedIdentifier;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.operations.QueryOperation;

import java.util.List;

/**
 * Provides methods for parsing SQL objects from a SQL string.
 */
@Internal
public interface Parser {

	/**
	 * Entry point for parsing SQL queries expressed as a String.
	 *
	 *
Note:If the created {@link Operation} is a {@link QueryOperation}
	 * it must be in a form that will be understood by the
	 * {@link Planner#translate(List)} method.
	 *
	 *
The produced Operation trees should already be validated.
	 *
	 * @param statement the SQL statement to evaluate
	 * @return parsed queries as trees of relational {@link Operation}s
	 * @throws org.apache.flink.table.api.SqlParserException when failed to parse the statement
	 */
	List<Operation> parse(String statement);

	/**
	 * Entry point for parsing SQL identifiers expressed as a String.
	 *
	 * @param identifier the SQL identifier to parse
	 * @return parsed identifier
	 * @throws org.apache.flink.table.api.SqlParserException when failed to parse the identifier
	 */
	UnresolvedIdentifier parseIdentifier(String identifier);
}


text:
#ifndef FEColorMatrix_h
#define FEColorMatrix_h

#include "platform/graphics/filters/FilterEffect.h"
#include "wtf/Vector.h"

namespace blink {

enum ColorMatrixType {
    FECOLORMATRIX_TYPE_UNKNOWN          = 0,
    FECOLORMATRIX_TYPE_MATRIX           = 1,
    FECOLORMATRIX_TYPE_SATURATE         = 2,
    FECOLORMATRIX_TYPE_HUEROTATE        = 3,
    FECOLORMATRIX_TYPE_LUMINANCETOALPHA = 4
};

class PLATFORM_EXPORT FEColorMatrix : public FilterEffect {
public:
    static PassRefPtrWillBeRawPtr<FEColorMatrix> create(Filter*, ColorMatrixType, const Vector<float>&);

    ColorMatrixType type() const;
    bool setType(ColorMatrixType);

    const Vector<float>& values() const;
    bool setValues(const Vector<float>&);

    TextStream& externalRepresentation(TextStream&, int indention) const override;

    static inline void calculateSaturateComponents(float* components, float value);
    static inline void calculateHueRotateComponents(float* components, float value);

private:
    FEColorMatrix(Filter*, ColorMatrixType, const Vector<float>&);

    PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override;

    bool affectsTransparentPixels() override;

    ColorMatrixType m_type;

    // The m_values vector may not contain the right number of values. Always check
    // before accessing contents.
    Vector<float> m_values;
};

} // namespace blink

#endif // FEColorMatrix_h


text:
package com.alibaba.rocketmq.client.hook;

import java.util.List;

import com.alibaba.rocketmq.common.message.MessageExt;
import com.alibaba.rocketmq.common.message.MessageQueue;

public class ConsumeMessageContext {
    private String consumerGroup;
    private List<MessageExt> msgList;
    private MessageQueue mq;
    private boolean success;
    private Object arg;

    public String getConsumerGroup() {
        return consumerGroup;
    }

    public void setConsumerGroup(String consumerGroup) {
        this.consumerGroup = consumerGroup;
    }

    public List<MessageExt> getMsgList() {
        return msgList;
    }

    public void setMsgList(List<MessageExt> msgList) {
        this.msgList = msgList;
    }

    public MessageQueue getMq() {
        return mq;
    }

    public void setMq(MessageQueue mq) {
        this.mq = mq;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public Object getArg() {
        return arg;
    }

    public void setArg(Object arg) {
        this.arg = arg;
    }

    @Override
    public String toString() {
        return "ConsumeMessageContext [consumerGroup=" + consumerGroup + ", msgList=" + msgList + ", mq="
                + mq + ", success=" + success + ", arg=" + arg + "]";
    }
}


text:
$(document).ready(function () {
    $(function() {
    highlight_errors_validate();
    // Setup form validation on the element
    $("#resetpassword_form").validate({
        // Specify the validation rules
        rules: {
            password: {
                required: true,
                minlength: 6
            },
            confirm_password: {
                required: true,
                equalTo: '#password'
            }
        },

        // Specify the validation error messages
        messages: {
            password: {
                required: '

Please enter a Password
',
                minlength: '

The password should be of 6 characters in length
'
            },
            confirm_password: {
                required: '

Confirm password is required
',
                equalTo: '

The confirm password should match password.
'
            }
        },

        submitHandler: function(form) {
            $.ajax
            ({
                type: 'POST',
                url: $(form).attr('action'),
                data: $(form).serialize(),
                dataType : 'json',
                success: function(data) {
                    $('#form_error').html('');
                    $('#confirm_password_error').html('');
                    $('#password_error').html('');
                    if (data.success){
                        // when password reset success
                        $('#form_error').html('

'+ data.message +'
');
                        // reset is successful -> redirect to home after 3 secs.
                        setTimeout(function(){
                                $('#form_error').empty();
                                window.location.href = "home";
                            }, 3000);
                    }
                    else
                    {
                        if(data.message != null)
                        {
                            $('#form_error').html('

'+ data.message +'
');
                        }
                        else
                        {
                            if(typeof(data.confirm_password) != "undefined" && data.confirm_password != "" )
                                $('#confirm_password_error').html('

' + data.confirm_password + '
');
                            if(typeof(data.password) != "undefined" && data.password != "" )
                                $('#password_error').html('

' + data.password + '
');
                        }
                    }
            },
            error: function(data) {
                console.log(data);
            }
        });
            return false;
        },
    });
});

});


text:
FactoryGirl.define do
  # Project without repository
  #
  # Project does not have bare repository.
  # Use this factory if you dont need repository in tests
  factory :empty_project, class: 'Project' do
    sequence(:name) { |n| "project#{n}" }
    path { name.downcase.gsub(/\s/, '_') }
    namespace
    creator
    snippets_enabled true

    trait :public do
      visibility_level Gitlab::VisibilityLevel::PUBLIC
    end

    trait :internal do
      visibility_level Gitlab::VisibilityLevel::INTERNAL
    end

    trait :private do
      visibility_level Gitlab::VisibilityLevel::PRIVATE
    end
  end

  # Project with empty repository
  #
  # This is a case when you just created a project
  # but not pushed any code there yet
  factory :project_empty_repo, parent: :empty_project do
    after :create do |project|
      project.create_repository
    end
  end

  # Project with test repository
  #
  # Test repository source can be found at
  # https://gitlab.com/gitlab-org/gitlab-test
  factory :project, parent: :empty_project do
    path { 'gitlabhq' }

    after :create do |project|
      TestEnv.copy_repo(project)
    end
  end

  factory :redmine_project, parent: :project do
    issues_tracker { "redmine" }
    issues_tracker_id { "project_name_in_redmine" }
  end
end


text:
import datetime as dt
import typing as t

import peewee as pw
from marshmallow import Schema, fields

class Timestamp(fields.Field):

    default_error_messages = {"invalid": "Not a valid timestamp."}

    def _serialize(
        self, value: dt.datetime, attr: t.Optional[str], obj: pw.Model, **kwargs
    ) -> t.Optional[int]:
        """Serialize given datetime to timestamp."""
        if value is None:
            return None

        if value.tzinfo is None:
            value = value.replace(tzinfo=dt.timezone.utc)

        return int(value.timestamp())

    def _deserialize(
        self,
        value: t.Union[str, int, float],
        attr: t.Optional[str],
        data: t.Optional[t.Mapping[str, t.Any]],
        **kwargs,
    ) -> dt.datetime:
        if not value:  # Falsy values, e.g. '', None, [] are not valid
            raise self.make_error("invalid")

        try:
            return dt.datetime.utcfromtimestamp(float(value))
        except ValueError:
            raise self.make_error("invalid")

class MSTimestamp(Timestamp):
    def _serialize(
        self, value: dt.datetime, attr: t.Optional[str], obj: pw.Model, *_, **__
    ) -> t.Optional[int]:
        """Serialize given datetime to timestamp."""
        val = super(MSTimestamp, self)._serialize(value, attr, obj)
        if val is None:
            return None

        return val * 1000

    def _deserialize(
        self,
        value: t.Union[str, int, float],
        attr: t.Optional[str],
        data: t.Optional[t.Mapping[str, t.Any]],
        **_,
    ) -> dt.datetime:
        if value:
            value = int(value) / 1e3

        return super(MSTimestamp, self)._deserialize(value, attr, data)

class Related(fields.Nested):
    def __init__(self, nested: Schema = None, meta: t.Dict = None, **kwargs):  # type: ignore
        self.field = None
        self.meta = meta or {}
        super(Related, self).__init__(nested, **kwargs)  # type: ignore

    def init_model(self, model: pw.Model, name: str):
        from .schema import ModelSchema

        field = model._meta.fields.get(name)  # type: ignore
        if not field:
            field = getattr(model, name).field
            self.many = True
            rel_model = field.model
        else:
            rel_model = field.rel_model

        self.field = field
        self.attribute = self.attribute or name
        self.meta["model"] = rel_model
        meta = type("Meta", (), self.meta)
        self.nested = type("Schema", (ModelSchema,), {"Meta": meta})

    def _deserialize(self, value, attr, data, **_):
        if self.field is None:
            raise RuntimeError("Init model first.")

        if not isinstance(value, dict):
            return self.field.rel_field.python_value(value)

        return super(Related, self)._deserialize(value, attr, data)

class ForeignKey(fields.Raw):
    string_keys = False

    def _bind_to_schema(self, field_name, schema):
        self.string_keys = schema.opts.string_keys
        super()._bind_to_schema(field_name, schema)

    def get_value(self, obj: pw.Model, attr: str, **_) -> t.Any:  # type: ignore
        """Return the value for a given key from an object."""
        value = obj.__data__.get(self.attribute)
        if value is not None and self.string_keys:
            value = str(value)
        return value


text:
export ARCHS= armv7 arm64
export TARGET=iphone:latest:4.3
SDKVERSION = 7.0

include theos/makefiles/common.mk

TWEAK_NAME = InboxCount
InboxCount_FILES = Tweak.xm

include $(THEOS_MAKE_PATH)/tweak.mk

after-install::
	install.exec "killall -9 MobileMail"


text:
<!doctype html>
<html class="no-js" <?php language_attributes(); ?>>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="alternate" type="application/rss+xml" title="<?= get_bloginfo('name'); ?> Feed" href="<?= esc_url(get_feed_link()); ?>">

    <link rel="icon" href="<?php bloginfo('template_directory'); ?>/dist/images/favicon.png" />
    <link rel="shortcut icon" href="<?php bloginfo('template_directory'); ?>/dist/images/favicon.png" />

    <?php wp_head(); ?>
  </head>


text:
package adapterManager

import (
	"istio.io/mixer/pkg/adapter"
	"istio.io/mixer/pkg/pool"
)

type env struct {
	logger adapter.Logger
	gp     *pool.GoroutinePool
}

func newEnv(aspect string, gp *pool.GoroutinePool) adapter.Env {
	return env{
		logger: newLogger(aspect),
		gp:     gp,
	}
}

func (e env) Logger() adapter.Logger {
	return e.logger
}

func (e env) ScheduleWork(fn adapter.WorkFunc) {
	e.gp.ScheduleWork(func() {
		defer func() {
			if r := recover(); r != nil {
				_ = e.Logger().Errorf("Adapter worker failed: %v", r) // nolint: gas

				// TODO: Beyond logging, we want to do something proactive here.
				//       For example, we want to probably terminate the originating
				//       adapter and record the failure so we can count how often
				//       it happens, etc.
			}
		}()

		fn()
	})
}

func (e env) ScheduleDaemon(fn adapter.DaemonFunc) {
	go func() {
		defer func() {
			if r := recover(); r != nil {
				_ = e.Logger().Errorf("Adapter daemon failed: %v", r) // nolint: gas

				// TODO: Beyond logging, we want to do something proactive here.
				//       For example, we want to probably terminate the originating
				//       adapter and record the failure so we can count how often
				//       it happens, etc.
			}
		}()

		fn()
	}()
}


text:
package org.deeplearning4j.nn.conf;

import org.deeplearning4j.nn.conf.serde.format.DataFormatDeserializer;
import org.deeplearning4j.nn.conf.serde.format.DataFormatSerializer;
import org.nd4j.shade.jackson.databind.annotation.JsonDeserialize;
import org.nd4j.shade.jackson.databind.annotation.JsonSerialize;

@JsonSerialize(using = DataFormatSerializer.class)
@JsonDeserialize(using = DataFormatDeserializer.class)
public interface DataFormat {
}


text:
require 'twilio-ruby'

response = Twilio::TwiML::VoiceResponse.new
response.redirect('http://www.foo.com/nextInstructions')

puts response


text:
@implementation MIHMessageDigest5

- (NSData *)hashValueOfData:(NSData *)data
{
    MD5_CTX md5Ctx;
    unsigned char hashValue[MD5_DIGEST_LENGTH];
    if(!MD5_Init(&md5Ctx)) {
        @throw [NSException openSSLException];
    }
    if (!MD5_Update(&md5Ctx, data.bytes, data.length)) {
        @throw [NSException openSSLException];
    }
    if (!MD5_Final(hashValue, &md5Ctx)) {
        @throw [NSException openSSLException];
    }
    return [NSData dataWithBytes:hashValue length:MD5_DIGEST_LENGTH];
}

@end


text:
using Signum.Entities.Workflow;
using Signum.Engine.Workflow;
using Signum.Engine;
using Signum.Engine.Operations;
using Signum.Entities;
using Signum.React.Facades;
using System;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using Signum.Entities.Basics;
using Signum.Engine.DynamicQuery;
using Signum.Engine.Basics;
using Signum.Engine.Authorization;
using Newtonsoft.Json;
using Signum.Utilities;
using Signum.React.ApiControllers;
using Microsoft.AspNetCore.Mvc;
using Signum.React.Filters;
using static Signum.React.ApiControllers.OperationController;
using Signum.Entities.Reflection;
using System.ComponentModel.DataAnnotations;
using Signum.Entities.Isolation;
using Signum.Engine.Isolation;
using Signum.Entities.Authorization;

namespace Signum.React.Workflow
{
    [ValidateModelFilter]
    public class IsolationController : Controller
    {
        [HttpGet("api/isolations")]
        public List<Lite<IsolationEntity>> Isolations()
        {
            var current = UserEntity.Current.TryMixin<IsolationMixin>()?.Isolation;

            if (current != null)
                throw new UnauthorizedAccessException("User is only allowed to see isolation:" + current);

            return IsolationLogic.Isolations.Value;
        }
    }
}


text:
package com.vladmihalcea.book.hpjp.spring.transaction.transfer.domain;

import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.persistence.Version;

/**
 * @author Vlad Mihalcea
 */
@Entity(name = "Account")
@Table(name = "account")
public class Account {

    @Id
    private String iban;

    private String owner;

    private long balance;

    @Version
    private short version;

    public String getIban() {
        return iban;
    }

    public Account setIban(String iban) {
        this.iban = iban;
        return this;
    }

    public String getOwner() {
        return owner;
    }

    public Account setOwner(String owner) {
        this.owner = owner;
        return this;
    }

    public long getBalance() {
        return balance;
    }

    public Account setBalance(long balance) {
        this.balance = balance;
        return this;
    }
}


text:
package flags

import (
	"flag"
	"os"
	"testing"
)

func TestSetFlagsFromEnv(t *testing.T) {
	fs := flag.NewFlagSet("testing", flag.ExitOnError)
	fs.String("a", "", "")
	fs.String("b", "", "")
	fs.String("c", "", "")
	fs.Parse([]string{})

	os.Clearenv()
	// flags should be settable using env vars
	os.Setenv("ETCD_A", "foo")
	// and command-line flags
	if err := fs.Set("b", "bar"); err != nil {
		t.Fatal(err)
	}

	// first verify that flags are as expected before reading the env
	for f, want := range map[string]string{
		"a": "",
		"b": "bar",
	} {
		if got := fs.Lookup(f).Value.String(); got != want {
			t.Fatalf("flag %q=%q, want %q", f, got, want)
		}
	}

	// now read the env and verify flags were updated as expected
	err := SetFlagsFromEnv("ETCD", fs)
	if err != nil {
		t.Errorf("err=%v, want nil", err)
	}
	for f, want := range map[string]string{
		"a": "foo",
		"b": "bar",
	} {
		if got := fs.Lookup(f).Value.String(); got != want {
			t.Errorf("flag %q=%q, want %q", f, got, want)
		}
	}
}

func TestSetFlagsFromEnvBad(t *testing.T) {
	// now verify that an error is propagated
	fs := flag.NewFlagSet("testing", flag.ExitOnError)
	fs.Int("x", 0, "")
	os.Setenv("ETCD_X", "not_a_number")
	if err := SetFlagsFromEnv("ETCD", fs); err == nil {
		t.Errorf("err=nil, want != nil")
	}
}

func TestSetFlagsFromEnvParsingError(t *testing.T) {
	fs := flag.NewFlagSet("etcd", flag.ContinueOnError)
	var tickMs uint
	fs.UintVar(&tickMs, "heartbeat-interval", 0, "Time (in milliseconds) of a heartbeat interval.")

	if oerr := os.Setenv("ETCD_HEARTBEAT_INTERVAL", "100 # ms"); oerr != nil {
		t.Fatal(oerr)
	}
	defer os.Unsetenv("ETCD_HEARTBEAT_INTERVAL")

	if serr := SetFlagsFromEnv("ETCD", fs); serr.Error() != `invalid value "100 # ms" for ETCD_HEARTBEAT_INTERVAL: strconv.ParseUint: parsing "100 # ms": invalid syntax` {
		t.Fatalf("expected parsing error, got %v", serr)
	}
}


text:
<?php

abstract class Dlayer_Form_Tool_Form extends Dlayer_Form
{
    protected $tool = array();
    protected $sub_tool_model = null;
    protected $field_type;
    protected $data = array();
    protected $element_data = array();

    protected $preset = null;

    /**
     * Set the properties for the form
     *
     * @param array $tool Tool and environment data array
     * @param array $data Current data for content item
     * @param array $element_data Data array containing data for elements (Select menu etc.)
     * @param array|NULL $options Zend form options
     */
    public function __construct(array $tool, array $data, array $element_data, $options = null)
    {
        $this->tool = $tool;
        $this->data = $data;
        $this->element_data = $element_data;

        parent::__construct($options);
    }

    /**
     * Set up the tool elements, these are the elements that are part of every tool and set the environment
     * properties and tool options
     *
     * @return void The elements are written to the $this->elements private property
     */
    protected function generateToolElements()
    {
        $tool = new Zend_Form_Element_Hidden('tool');
        $tool->setValue($this->tool['name']);

        $this->elements['tool'] = $tool;

        if ($this->sub_tool_model !== null) {
            $sub_tool_model = new Zend_Form_Element_Hidden('sub_tool_model');
            $sub_tool_model->setValue($this->sub_tool_model);

            $this->elements['sub_tool_model'] = $sub_tool_model;
        }

        if (isset($this->field_type) && $this->field_type !== null) {
            $field_type = new Zend_Form_Element_Hidden('field_type');
            $field_type->setValue($this->field_type);

            $this->elements['field_type'] = $field_type;
        }

        if (isset($this->preset) && $this->preset === 1) {
            $preset = new Zend_Form_Element_Hidden('preset');
            $preset->setValue($this->preset);

            $this->elements['preset'] = $preset;
        }

        $multi_use = new Zend_Form_Element_Hidden('multi_use');
        $multi_use->setValue($this->tool['multi_use']);

        $this->elements['multi_use'] = $multi_use;

        $form_id = new Zend_Form_Element_Hidden('form_id');
        $form_id->setValue($this->tool['form_id']);

        $this->elements['form_id'] = $form_id;

        $field_id = new Zend_Form_Element_Hidden('field_id');
        $field_id->setValue($this->tool['field_id']);

        $this->elements['field_id'] = $field_id;
    }

    protected function generateSubmitElement()
    {
        $submit = new Zend_Form_Element_Submit('submit');
        $submit->setAttribs(array('class' => 'btn btn-sm btn-success'));
        $submit->setLabel('Save');

        $this->elements['submit'] = $submit;
    }

    abstract protected function generateUserElements();

    /**
     * Create the form elements and assign them to $this->elements, array will be passed to
     * Dlayer_Form::addElementsToForm()
     *
     * @return void
     */
    protected function generateFormElements()
    {
        $this->generateToolElements();

        $this->generateUserElements();

        $this->generateSubmitElement();
    }

    /**
     * Add validation rules
     *
     * @return void
     */
    protected function validationRules()
    {
        // TODO: Implement validationRules() method.
    }

    /**
     * Add the default element decorators
     *
     * @return void
     */
    protected function addDefaultElementDecorators()
    {
        $this->setDecorators(array(
            'FormElements',
            array('Form', array('class' => 'form'))
        ));

        $this->setElementDecorators(array(
            array('ViewHelper'),
            array('Description', array('tag' => 'p', 'class' => 'help-block')),
            array('Errors', array('class' => 'alert alert-danger')),
            array('Label'),
            array(
                'HtmlTag',
                array(
                    'tag' => 'div',
                    'class' => array(
                        'callback' => function ($decorator) {
                            if ($decorator->getElement()->hasErrors()) {
                                return 'form-group has-error';
                            } else {
                                return 'form-group';
                            }
                        }
                    )
                )
            )
        ));

        $this->setDisplayGroupDecorators(array(
            'FormElements',
            'Fieldset',
        ));
    }

    protected function addCustomElementDecorators()
    {
        $this->elements['submit']->setDecorators(array(
            array('ViewHelper'),
            array(
                'HtmlTag',
                array(
                    'tag' => 'div',
                    'class' => 'form-group form-group-submit'
                )
            )
        ));
    }
}


text:
import React from 'react';
import About from './About';
import Banner from './Banner';
import { connect } from 'react-redux';

const mapStateToProps = state => ({
  appName: state.common.appName
});

const mapDispatchToProps = dispatch => ({
  onLoad: payload => dispatch({ type: 'HOME_PAGE_LOADED', payload })
});

class Home extends React.Component {
  render() {
    return (
      <div className="container-fluid" id="main-container">
        <Banner />
        <About />
      </div>
    );
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Home);


text:
(function () {
    var JavaWrapper = require(EclairJS_Globals.NAMESPACE + '/JavaWrapper');
    var Logger = require(EclairJS_Globals.NAMESPACE + '/Logger');
    var Utils = require(EclairJS_Globals.NAMESPACE + '/Utils');

    /**
     * A class that implements
     * [[http://en.wikipedia.org/wiki/Gradient_boosting  Stochastic Gradient Boosting]]
     * for regression and binary classification.
     *
     * The implementation is based upon:
     *   J.H. Friedman.  "Stochastic Gradient Boosting."  1999.
     *
     * Notes on Gradient Boosting vs. TreeBoost:
     *  - This implementation is for Stochastic Gradient Boosting, not for TreeBoost.
     *  - Both algorithms learn tree ensembles by minimizing loss functions.
     *  - TreeBoost (Friedman, 1999) additionally modifies the outputs at tree leaf nodes
     *    based on the loss function, whereas the original gradient boosting method does not.
     *     - When the loss is SquaredError, these methods give the same result, but they could differ
     *       for other loss functions.
     *
     * @param boostingStrategy Parameters for the gradient boosting algorithm.
     * @classdesc
     */

    /**
     * @param {module:eclairjs/mllib/tree/configuration.BoostingStrategy} boostingStrategy
     *  @class
     *  @memberof module:eclairjs/mllib/tree
     */
    var GradientBoostedTrees = function (boostingStrategy) {
        this.logger = Logger.getLogger("GradientBoostedTrees_js");
        var jvmObject;
        var obj = Utils.unwrapObject(boostingStrategy);
        if (obj instanceof org.apache.spark.mllib.tree.configuration.BoostingStrategy) {
            jvmObject = new org.apache.spark.mllib.tree.GradientBoostedTrees(obj);
        } else if (boostingStrategy instanceof org.apache.spark.mllib.tree.GradientBoostedTrees) {
            jvmObject = obj;
        } else {
            throw "GradientBoostedTrees constructor accepts only a BoostingStrategy";
        }
        JavaWrapper.call(this, jvmObject);

    };

    GradientBoostedTrees.prototype = Object.create(JavaWrapper.prototype);

    GradientBoostedTrees.prototype.constructor = GradientBoostedTrees;

    /**
     * Method to train a gradient boosting model
     * @param {module:eclairjs.RDD} input  Training dataset: RDD of {@link LabeledPoint}.
     * @returns {module:eclairjs/mllib/tree/model.GradientBoostedTreesModel}  a gradient boosted trees model that can be used for prediction
     */
    GradientBoostedTrees.prototype.run = function (input) {
        var input_uw = Utils.unwrapObject(input);
        var javaObject = this.getJavaObject().run(input_uw);
        return Utils.javaToJs(javaObject);
    };

    /**
     * Method to validate a gradient boosting model
     * @param {module:eclairjs.RDD} input  Training dataset: RDD of {@link LabeledPoint}.
     * @param {module:eclairjs.RDD} validationInput  Validation dataset.
     *                        This dataset should be different from the training dataset,
     *                        but it should follow the same distribution.
     *                        E.g., these two datasets could be created from an original dataset
     *                        by using [[org.apache.spark.rdd.RDD.randomSplit()]]
     * @returns {module:eclairjs/mllib/tree/model.GradientBoostedTreesModel}  a gradient boosted trees model that can be used for prediction
     */
    GradientBoostedTrees.prototype.runWithValidation = function (input, validationInput) {
        var input_uw = Utils.unwrapObject(input);
        var validationInput_uw = Utils.unwrapObject(validationInput);
        var javaObject = this.getJavaObject().runWithValidation(input_uw, validationInput_uw);
        return Utils.javaToJs(javaObject);
    };

//
// static methods
//

    /**
     * Method to train a gradient boosting model.
     *
     * @param {module:eclairjs.RDD} input  Training dataset: RDD of {@link LabeledPoint}.
     *              For classification, labels should take values {0, 1, ..., numClasses-1}.
     *              For regression, labels are real numbers.
     * @param {module:eclairjs/mllib/tree/configuration.BoostingStrategy} boostingStrategy  Configuration options for the boosting algorithm.
     * @returns {module:eclairjs/mllib/tree/model.GradientBoostedTreesModel}  a gradient boosted trees model that can be used for prediction
     */
    GradientBoostedTrees.train = function (input, boostingStrategy) {
        var input_uw = Utils.unwrapObject(input);
        var boostingStrategy_uw = Utils.unwrapObject(boostingStrategy);
        var javaObject = org.apache.spark.mllib.tree.GradientBoostedTrees.train(input_uw, boostingStrategy_uw);
        return Utils.javaToJs(javaObject);
    };

    module.exports = GradientBoostedTrees;

})();


text:
package com.gemstone.gemfire.internal.process;

import org.apache.logging.log4j.Logger;

import com.gemstone.gemfire.internal.logging.LogService;
import com.gemstone.org.jgroups.util.StringId;

/**
 * Extracted from LogWriterImpl and changed to static.
 *
 * @author Kirk Lund
 */
public class StartupStatus {
  private static final Logger logger = LogService.getLogger();

  /** protected by static synchronized */
  private static StartupStatusListener listener;

  /**
   * Writes both a message and exception to this writer.
   * If a startup listener is registered,
   * the message will be written to the listener as well
   * to be reported to a user.
   * @since 7.0
   */
  public static synchronized void startup(StringId msgID, Object[] params) {
    String message = msgID.toLocalizedString(params);

    if (listener != null) {
      listener.setStatus(message);
    }

    logger.info(message);
  }

  public static synchronized void setListener(StartupStatusListener listener) {
    StartupStatus.listener = listener;
  }

  public static synchronized StartupStatusListener getStartupListener() {
    return StartupStatus.listener;
  }

  public static synchronized void clearListener() {
    StartupStatus.listener = null;
  }
}


text:
//==============================================================================

//==============================================================================

//------------------------------------------------------------------------------
#ifndef CTextureVideoH
#define CTextureVideoH
//------------------------------------------------------------------------------
#include "materials/CTexture2d.h"
#include "graphics/CVideo.h"
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
namespace chai3d {
//------------------------------------------------------------------------------

//==============================================================================
/*!
    \file   CTextureVideo.h

    \brief
    Implements video textures.
*/
//==============================================================================

//------------------------------------------------------------------------------
class cTextureVideo;
typedef std::shared_ptr<cTextureVideo> cTextureVideoPtr;
//------------------------------------------------------------------------------

//==============================================================================
/*!
    \class      cTextureVideo
    \ingroup    materials

    \brief
    This class implements a video texture map

    \details
    This class implements a video bitmap texture used for OpenGL texture-mapping
    of a \ref cVideo object.
*/
//==============================================================================
class cTextureVideo : public cTexture2d
{
    //--------------------------------------------------------------------------
    // CONSTRUCTOR & DESTRUCTOR:
    //--------------------------------------------------------------------------

public:

    //! Constructor of cTextureVideo.
    cTextureVideo();

    //! Destructor of cTextureVideo.
    virtual ~cTextureVideo();

    //! Shared cTextureVideo allocator.
    static cTextureVideoPtr create() { return (std::make_shared<cTextureVideo>()); }

    //--------------------------------------------------------------------------
    // PUBLIC METHODS:
    //--------------------------------------------------------------------------

public:

    //! This method loads a texture video file.
    virtual bool loadFromFile(const std::string& a_fileName);

    //! This method enables texturing and set this texture as the current texture.
    virtual void renderInitialize(cRenderOptions& a_options);

    //--------------------------------------------------------------------------
    // PUBLIC MEMBERS:
    //--------------------------------------------------------------------------

public:

    //! Video object (Use this to get data about the texture itself).
    cVideoPtr m_video;
};

//------------------------------------------------------------------------------
} // namespace chai3d
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
#endif
//------------------------------------------------------------------------------


text:
  #ifndef WILDCARD
    #define WILDCARD '*'
  #endif
#endif
#ifndef EMPTY
#define EMPTY '_'
#endif

using std::string;
using std::deque;

namespace TM
{
  //----------------------------------------------------------------------------
  // class representing the tape of the turing machine
  //
  class Tape
  {
    public:
      //------------------------------------------------------------------------
      // Standard Constructor
      //
      Tape();
      //------------------------------------------------------------------------
      // Standard Destructor
      //
      virtual ~Tape();
      //------------------------------------------------------------------------
      // Standard Copy Constructor
      //
      Tape(const Tape& another);
      //------------------------------------------------------------------------
      // operator =
      //
      Tape& operator=(const Tape& another);
      //------------------------------------------------------------------------
      // move Read/Write Head by move
      //
      void moveHead(const int& move);
      //------------------------------------------------------------------------
      // write the character on the tape (always)
      //
      void forceWrite(const char& toWrite);
      //------------------------------------------------------------------------
      // write the character on the tape (except for wildcards)
      //
      void write(const char& toWrite);
      //------------------------------------------------------------------------
      // read the character of the tape
      //
      const char read();
      //------------------------------------------------------------------------
      // preset the number of characters to be outputted
      // when displaying the tape
      //
      void setPrintTapeFieldCount(const int& count);
      //------------------------------------------------------------------------
      // load the tape from the given file
      //
      void loadInput(const string& input);
      //------------------------------------------------------------------------
      // load the tape from the given file (in hexnotation)
      //
      void loadHexInput(const string& path);
#ifndef DISABLE_TOY
      //------------------------------------------------------------------------
      // load the tape from the given file (toy code)
      //
      void loadToyInput(const string& path);
#endif
      //------------------------------------------------------------------------
      // clear the tape
      //
      void clear();
      //------------------------------------------------------------------------
      // save the tape and the given input to the file
      //
      void saveTape(const string &path, const string &input) const;
      //------------------------------------------------------------------------
      // reset the head position to 0 (tape start)
      //
      void resetHead();
      //------------------------------------------------------------------------
      // set the head to the tape end
      //
      void setHeadAtEnd();
      //------------------------------------------------------------------------
      // return the tape content (preset size)
      //
      const string printTape();
      //------------------------------------------------------------------------
      // return the tape content (given size)
      //
      const string printTape(const int& sizeOfFields);
      //------------------------------------------------------------------------
      // read the file (file path is on tape)
      //
      void readFile();
      //------------------------------------------------------------------------
      // write tape content into the file (file path is on tape)
      //
      void writeFile();

    private:
      //------------------------------------------------------------------------
      // position of read/write head
      //
      int mHeadPos;
      //------------------------------------------------------------------------
      // number of characters to be printed
      //
      int mFieldCount;
      //------------------------------------------------------------------------
      // tape content
      //
      deque<char> mTape;

      //------------------------------------------------------------------------
      // extend the tape to the left
      //
      void extendTapeLeft();
      //------------------------------------------------------------------------
      // extend the tape to the right
      //
      void extendTapeRight();

      //------------------------------------------------------------------------
      // read the filename of the tape
      //
      const string readFileNameFromTape();

  };

}

#endif


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Labyrinthula roscoffensis Chadef.

### Remarks
null


text:
(function() {

  $('#step3Form').on('submit', function(e) {
    var jsonResult = '{ "applyTo": [';
    var hasChecked = false;

    $('.sectionTabs:checked').each(function(e)
    {
      if (hasChecked)
        jsonResult += ', ';
      jsonResult += '"' + $(this).val() + '"';
      hasChecked = true;
    });

    if (!hasChecked)
    {
      e.preventDefault();
      alert('Please select at least one entry type');
    }

    jsonResult += ']}'

    alert(jsonResult);
    $('#applyTo').val(jsonResult);
  });

  $('#export').on('submit', function(e) {
    e.preventDefault();

    $('#exportResultContainer').removeClass('hidden');
    $('#exportResult').text('');

    var action = $(this).find("[name='action']").val();

    Craft.postActionRequest(action, $(this).serialize(), function(response) {
      var json = JSON.stringify(response, undefined, 2);
      $('#exportResult').text(json);
    });
  });

})();


text:
package com.manolovn.cssdroid.parser.domain;

import java.util.LinkedHashSet;
import java.util.Set;

/**
 * Stylesheet main context
 */
public class StyleSheet {

    private Set<Node> rules;
    private Set<VariableNode> variables;

    public StyleSheet() {
        rules = new LinkedHashSet<>();
        variables = new LinkedHashSet<>();
    }

    public Set<VariableNode> getVariables() {
        return variables;
    }

    public void addVariable(VariableNode node) {
        if (node == null) {
            return;
        }
        variables.add(node);
    }

    public void addRule(Node rule) {
        if (rule == null) {
            return;
        }
        rules.add(rule);
    }

    public Set<Node> getRules() {
        return rules;
    }
}


text:
/*
 * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
 * Use is subject to license terms.
 *
 * Copyright (c) 2011, 2015, Intel Corporation.
 */
/*
 * This file is part of Lustre, http://www.lustre.org/
 * Lustre is a trademark of Sun Microsystems, Inc.
 */

#ifndef __LINUX_FLD_H
#define __LINUX_FLD_H

/** \defgroup fld fld
 *
 * @{
 */

#include "lustre/lustre_idl.h"
#include "../../include/linux/libcfs/libcfs.h"

struct lu_client_fld;
struct lu_server_fld;
struct lu_fld_hash;
struct fld_cache;

extern const struct dt_index_features fld_index_features;
extern const char fld_index_name[];

/*
 * FLD (Fid Location Database) interface.
 */
enum {
	LUSTRE_CLI_FLD_HASH_DHT = 0,
	LUSTRE_CLI_FLD_HASH_RRB
};

struct lu_fld_target {
	struct list_head	       ft_chain;
	struct obd_export       *ft_exp;
	struct lu_server_fld    *ft_srv;
	__u64		    ft_idx;
};

struct lu_server_fld {
	/**
	 * super sequence controller export, needed to forward fld
	 * lookup  request.
	 */
	struct obd_export       *lsf_control_exp;

	/** Client FLD cache. */
	struct fld_cache	*lsf_cache;

	/** Protect index modifications */
	struct mutex		lsf_lock;

	/** Fld service name in form "fld-srv-lustre-MDTXXX" */
	char		     lsf_name[LUSTRE_MDT_MAXNAMELEN];

};

struct lu_client_fld {
	/** Client side debugfs entry. */
	struct dentry		*lcf_debugfs_entry;

	/** List of exports client FLD knows about. */
	struct list_head	       lcf_targets;

	/** Current hash to be used to chose an export. */
	struct lu_fld_hash      *lcf_hash;

	/** Exports count. */
	int		      lcf_count;

	/** Lock protecting exports list and fld_hash. */
	spinlock_t		 lcf_lock;

	/** Client FLD cache. */
	struct fld_cache	*lcf_cache;

	/** Client fld debugfs entry name. */
	char			 lcf_name[LUSTRE_MDT_MAXNAMELEN];

	int			 lcf_flags;
};

/* Client methods */
int fld_client_init(struct lu_client_fld *fld,
		    const char *prefix, int hash);

void fld_client_fini(struct lu_client_fld *fld);

void fld_client_flush(struct lu_client_fld *fld);

int fld_client_lookup(struct lu_client_fld *fld, u64 seq, u32 *mds,
		      __u32 flags, const struct lu_env *env);

int fld_client_create(struct lu_client_fld *fld,
		      struct lu_seq_range *range,
		      const struct lu_env *env);

int fld_client_delete(struct lu_client_fld *fld, u64 seq,
		      const struct lu_env *env);

int fld_client_add_target(struct lu_client_fld *fld,
			  struct lu_fld_target *tar);

int fld_client_del_target(struct lu_client_fld *fld,
			  __u64 idx);

void fld_client_debugfs_fini(struct lu_client_fld *fld);

/** @} fld */

#endif


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace x.UnitTest.Models
{
    public class Fruit
    {
        public String Variety { get; set; }

        public float Weight { get; set; }
    }
}