text:
<?php

namespace dokuwiki\Remote;

use Doku_Renderer_xhtml;
use dokuwiki\ChangeLog\MediaChangeLog;
use dokuwiki\ChangeLog\PageChangeLog;
use dokuwiki\Extension\Event;

define('DOKU_API_VERSION', 10);

/**
 * Provides the core methods for the remote API.
 * The methods are ordered in 'wiki.<method>' and 'dokuwiki.<method>' namespaces
 */
class ApiCore
{
    /** @var int Increased whenever the API is changed */
    const API_VERSION = 10;

    /** @var Api */
    private $api;

    /**
     * @param Api $api
     */
    public function __construct(Api $api)
    {
        $this->api = $api;
    }

    /**
     * Returns details about the core methods
     *
     * @return array
     */
    public function __getRemoteInfo()
    {
        return array(
            'dokuwiki.getVersion' => array(
                'args' => array(),
                'return' => 'string',
                'doc' => 'Returns the running DokuWiki version.'
            ), 'dokuwiki.login' => array(
                'args' => array('string', 'string'),
                'return' => 'int',
                'doc' => 'Tries to login with the given credentials and sets auth cookies.',
                'public' => '1'
            ), 'dokuwiki.logoff' => array(
                'args' => array(),
                'return' => 'int',
                'doc' => 'Tries to logoff by expiring auth cookies and the associated PHP session.'
            ), 'dokuwiki.getPagelist' => array(
                'args' => array('string', 'array'),
                'return' => 'array',
                'doc' => 'List all pages within the given namespace.',
                'name' => 'readNamespace'
            ), 'dokuwiki.search' => array(
                'args' => array('string'),
                'return' => 'array',
                'doc' => 'Perform a fulltext search and return a list of matching pages'
            ), 'dokuwiki.getTime' => array(
                'args' => array(),
                'return' => 'int',
                'doc' => 'Returns the current time at the remote wiki server as Unix timestamp.',
            ), 'dokuwiki.setLocks' => array(
                'args' => array('array'),
                'return' => 'array',
                'doc' => 'Lock or unlock pages.'
            ), 'dokuwiki.getTitle' => array(
                'args' => array(),
                'return' => 'string',
                'doc' => 'Returns the wiki title.',
                'public' => '1'
            ), 'dokuwiki.appendPage' => array(
                'args' => array('string', 'string', 'array'),
                'return' => 'bool',
                'doc' => 'Append text to a wiki page.'
            ), 'dokuwiki.deleteUsers' => array(
                'args' => array('array'),
                'return' => 'bool',
                'doc' => 'Remove one or more users from the list of registered users.'
            ),  'wiki.getPage' => array(
                'args' => array('string'),
                'return' => 'string',
                'doc' => 'Get the raw Wiki text of page, latest version.',
                'name' => 'rawPage',
            ), 'wiki.getPageVersion' => array(
                'args' => array('string', 'int'),
                'name' => 'rawPage',
                'return' => 'string',
                'doc' => 'Return a raw wiki page'
            ), 'wiki.getPageHTML' => array(
                'args' => array('string'),
                'return' => 'string',
                'doc' => 'Return page in rendered HTML, latest version.',
                'name' => 'htmlPage'
            ), 'wiki.getPageHTMLVersion' => array(
                'args' => array('string', 'int'),
                'return' => 'string',
                'doc' => 'Return page in rendered HTML.',
                'name' => 'htmlPage'
            ), 'wiki.getAllPages' => array(
                'args' => array(),
                'return' => 'array',
                'doc' => 'Returns a list of all pages. The result is an array of utf8 pagenames.',
                'name' => 'listPages'
            ), 'wiki.getAttachments' => array(
                'args' => array('string', 'array'),
                'return' => 'array',
                'doc' => 'Returns a list of all media files.',
                'name' => 'listAttachments'
            ), 'wiki.getBackLinks' => array(
                'args' => array('string'),
                'return' => 'array',
                'doc' => 'Returns the pages that link to this page.',
                'name' => 'listBackLinks'
            ), 'wiki.getPageInfo' => array(
                'args' => array('string'),
                'return' => 'array',
                'doc' => 'Returns a struct with info about the page, latest version.',
                'name' => 'pageInfo'
            ), 'wiki.getPageInfoVersion' => array(
                'args' => array('string', 'int'),
                'return' => 'array',
                'doc' => 'Returns a struct with info about the page.',
                'name' => 'pageInfo'
            ), 'wiki.getPageVersions' => array(
                'args' => array('string', 'int'),
                'return' => 'array',
                'doc' => 'Returns the available revisions of the page.',
                'name' => 'pageVersions'
            ), 'wiki.putPage' => array(
                'args' => array('string', 'string', 'array'),
                'return' => 'bool',
                'doc' => 'Saves a wiki page.'
            ), 'wiki.listLinks' => array(
                'args' => array('string'),
                'return' => 'array',
                'doc' => 'Lists all links contained in a wiki page.'
            ), 'wiki.getRecentChanges' => array(
                'args' => array('int'),
                'return' => 'array',
                'Returns a struct about all recent changes since given timestamp.'
            ), 'wiki.getRecentMediaChanges' => array(
                'args' => array('int'),
                'return' => 'array',
                'Returns a struct about all recent media changes since given timestamp.'
            ), 'wiki.aclCheck' => array(
                'args' => array('string', 'string', 'array'),
                'return' => 'int',
                'doc' => 'Returns the permissions of a given wiki page. By default, for current user/groups'
            ), 'wiki.putAttachment' => array(
                'args' => array('string', 'file', 'array'),
                'return' => 'array',
                'doc' => 'Upload a file to the wiki.'
            ), 'wiki.deleteAttachment' => array(
                'args' => array('string'),
                'return' => 'int',
                'doc' => 'Delete a file from the wiki.'
            ), 'wiki.getAttachment' => array(
                'args' => array('string'),
                'doc' => 'Return a media file',
                'return' => 'file',
                'name' => 'getAttachment',
            ), 'wiki.getAttachmentInfo' => array(
                'args' => array('string'),
                'return' => 'array',
                'doc' => 'Returns a struct with info about the attachment.'
            ), 'dokuwiki.getXMLRPCAPIVersion' => array(
                'args' => array(),
                'name' => 'getAPIVersion',
                'return' => 'int',
                'doc' => 'Returns the XMLRPC API version.',
                'public' => '1',
            ), 'wiki.getRPCVersionSupported' => array(
                'args' => array(),
                'name' => 'wikiRpcVersion',
                'return' => 'int',
                'doc' => 'Returns 2 with the supported RPC API version.',
                'public' => '1'
            ),

        );
    }

    /**
     * @return string
     */
    public function getVersion()
    {
        return getVersion();
    }

    /**
     * @return int unix timestamp
     */
    public function getTime()
    {
        return time();
    }

    /**
     * Return a raw wiki page
     *
     * @param string $id wiki page id
     * @param int|string $rev revision timestamp of the page or empty string
     * @return string page text.
     * @throws AccessDeniedException if no permission for page
     */
    public function rawPage($id, $rev = '')
    {
        $id = $this->resolvePageId($id);
        if (auth_quickaclcheck($id) < AUTH_READ) {
            throw new AccessDeniedException('You are not allowed to read this file', 111);
        }
        $text = rawWiki($id, $rev);
        if (!$text) {
            return pageTemplate($id);
        } else {
            return $text;
        }
    }

    /**
     * Return a media file
     *
     * @author Gina Haeussge <osd@foosel.net>
     *
     * @param string $id file id
     * @return mixed media file
     * @throws AccessDeniedException no permission for media
     * @throws RemoteException not exist
     */
    public function getAttachment($id)
    {
        $id = cleanID($id);
        if (auth_quickaclcheck(getNS($id) . ':*') < AUTH_READ) {
            throw new AccessDeniedException('You are not allowed to read this file', 211);
        }

        $file = mediaFN($id);
        if (!@ file_exists($file)) {
            throw new RemoteException('The requested file does not exist', 221);
        }

        $data = io_readFile($file, false);
        return $this->api->toFile($data);
    }

    /**
     * Return info about a media file
     *
     * @author Gina Haeussge <osd@foosel.net>
     *
     * @param string $id page id
     * @return array
     */
    public function getAttachmentInfo($id)
    {
        $id = cleanID($id);
        $info = array(
            'lastModified' => $this->api->toDate(0),
            'size' => 0,
        );

        $file = mediaFN($id);
        if (auth_quickaclcheck(getNS($id) . ':*') >= AUTH_READ) {
            if (file_exists($file)) {
                $info['lastModified'] = $this->api->toDate(filemtime($file));
                $info['size'] = filesize($file);
            } else {
                //Is it deleted media with changelog?
                $medialog = new MediaChangeLog($id);
                $revisions = $medialog->getRevisions(0, 1);
                if (!empty($revisions)) {
                    $info['lastModified'] = $this->api->toDate($revisions[0]);
                }
            }
        }

        return $info;
    }

    /**
     * Return a wiki page rendered to html
     *
     * @param string $id page id
     * @param string|int $rev revision timestamp or empty string
     * @return null|string html
     * @throws AccessDeniedException no access to page
     */
    public function htmlPage($id, $rev = '')
    {
        $id = $this->resolvePageId($id);
        if (auth_quickaclcheck($id) < AUTH_READ) {
            throw new AccessDeniedException('You are not allowed to read this page', 111);
        }
        return p_wiki_xhtml($id, $rev, false);
    }

    /**
     * List all pages - we use the indexer list here
     *
     * @return array
     */
    public function listPages()
    {
        $list = array();
        $pages = idx_get_indexer()->getPages();
        $pages = array_filter(array_filter($pages, 'isVisiblePage'), 'page_exists');

        foreach (array_keys($pages) as $idx) {
            $perm = auth_quickaclcheck($pages[$idx]);
            if ($perm < AUTH_READ) {
                continue;
            }
            $page = array();
            $page['id'] = trim($pages[$idx]);
            $page['perms'] = $perm;
            $page['size'] = @filesize(wikiFN($pages[$idx]));
            $page['lastModified'] = $this->api->toDate(@filemtime(wikiFN($pages[$idx])));
            $list[] = $page;
        }

        return $list;
    }

    /**
     * List all pages in the given namespace (and below)
     *
     * @param string $ns
     * @param array $opts
     *    $opts['depth']   recursion level, 0 for all
     *    $opts['hash']    do md5 sum of content?
     * @return array
     */
    public function readNamespace($ns, $opts = array())
    {
        global $conf;

        if (!is_array($opts)) $opts = array();

        $ns = cleanID($ns);
        $dir = utf8_encodeFN(str_replace(':', '/', $ns));
        $data = array();
        $opts['skipacl'] = 0; // no ACL skipping for XMLRPC
        search($data, $conf['datadir'], 'search_allpages', $opts, $dir);
        return $data;
    }

    /**
     * List all pages in the given namespace (and below)
     *
     * @param string $query
     * @return array
     */
    public function search($query)
    {
        $regex = array();
        $data = ft_pageSearch($query, $regex);
        $pages = array();

        // prepare additional data
        $idx = 0;
        foreach ($data as $id => $score) {
            $file = wikiFN($id);

            if ($idx < FT_SNIPPET_NUMBER) {
                $snippet = ft_snippet($id, $regex);
                $idx++;
            } else {
                $snippet = '';
            }

            $pages[] = array(
                'id' => $id,
                'score' => intval($score),
                'rev' => filemtime($file),
                'mtime' => filemtime($file),
                'size' => filesize($file),
                'snippet' => $snippet,
                'title' => useHeading('navigation') ? p_get_first_heading($id) : $id
            );
        }
        return $pages;
    }

    /**
     * Returns the wiki title.
     *
     * @return string
     */
    public function getTitle()
    {
        global $conf;
        return $conf['title'];
    }

    /**
     * List all media files.
     *
     * Available options are 'recursive' for also including the subnamespaces
     * in the listing, and 'pattern' for filtering the returned files against
     * a regular expression matching their name.
     *
     * @author Gina Haeussge <osd@foosel.net>
     *
     * @param string $ns
     * @param array $options
     *   $options['depth']     recursion level, 0 for all
     *   $options['showmsg']   shows message if invalid media id is used
     *   $options['pattern']   check given pattern
     *   $options['hash']      add hashes to result list
     * @return array
     * @throws AccessDeniedException no access to the media files
     */
    public function listAttachments($ns, $options = array())
    {
        global $conf;

        $ns = cleanID($ns);

        if (!is_array($options)) $options = array();
        $options['skipacl'] = 0; // no ACL skipping for XMLRPC

        if (auth_quickaclcheck($ns . ':*') >= AUTH_READ) {
            $dir = utf8_encodeFN(str_replace(':', '/', $ns));

            $data = array();
            search($data, $conf['mediadir'], 'search_media', $options, $dir);
            $len = count($data);
            if (!$len) return array();

            for ($i = 0; $i < $len; $i++) {
                unset($data[$i]['meta']);
                $data[$i]['perms'] = $data[$i]['perm'];
                unset($data[$i]['perm']);
                $data[$i]['lastModified'] = $this->api->toDate($data[$i]['mtime']);
            }
            return $data;
        } else {
            throw new AccessDeniedException('You are not allowed to list media files.', 215);
        }
    }

    /**
     * Return a list of backlinks
     *
     * @param string $id page id
     * @return array
     */
    public function listBackLinks($id)
    {
        return ft_backlinks($this->resolvePageId($id));
    }

    /**
     * Return some basic data about a page
     *
     * @param string $id page id
     * @param string|int $rev revision timestamp or empty string
     * @return array
     * @throws AccessDeniedException no access for page
     * @throws RemoteException page not exist
     */
    public function pageInfo($id, $rev = '')
    {
        $id = $this->resolvePageId($id);
        if (auth_quickaclcheck($id) < AUTH_READ) {
            throw new AccessDeniedException('You are not allowed to read this page', 111);
        }
        $file = wikiFN($id, $rev);
        $time = @filemtime($file);
        if (!$time) {
            throw new RemoteException('The requested page does not exist', 121);
        }

        // set revision to current version if empty, use revision otherwise
        // as the timestamps of old files are not necessarily correct
        if ($rev === '') {
            $rev = $time;
        }

        $pagelog = new PageChangeLog($id, 1024);
        $info = $pagelog->getRevisionInfo($rev);

        $data = array(
            'name' => $id,
            'lastModified' => $this->api->toDate($rev),
            'author' => is_array($info) ? (($info['user']) ? $info['user'] : $info['ip']) : null,
            'version' => $rev
        );

        return ($data);
    }

    /**
     * Save a wiki page
     *
     * @author Michael Klier <chi@chimeric.de>
     *
     * @param string $id page id
     * @param string $text wiki text
     * @param array $params parameters: summary, minor edit
     * @return bool
     * @throws AccessDeniedException no write access for page
     * @throws RemoteException no id, empty new page or locked
     */
    public function putPage($id, $text, $params = array())
    {
        global $TEXT;
        global $lang;

        $id = $this->resolvePageId($id);
        $TEXT = cleanText($text);
        $sum = $params['sum'];
        $minor = $params['minor'];

        if (empty($id)) {
            throw new RemoteException('Empty page ID', 131);
        }

        if (!page_exists($id) && trim($TEXT) == '') {
            throw new RemoteException('Refusing to write an empty new wiki page', 132);
        }

        if (auth_quickaclcheck($id) < AUTH_EDIT) {
            throw new AccessDeniedException('You are not allowed to edit this page', 112);
        }

        // Check, if page is locked
        if (checklock($id)) {
            throw new RemoteException('The page is currently locked', 133);
        }

        // SPAM check
        if (checkwordblock()) {
            throw new RemoteException('Positive wordblock check', 134);
        }

        // autoset summary on new pages
        if (!page_exists($id) && empty($sum)) {
            $sum = $lang['created'];
        }

        // autoset summary on deleted pages
        if (page_exists($id) && empty($TEXT) && empty($sum)) {
            $sum = $lang['deleted'];
        }

        lock($id);

        saveWikiText($id, $TEXT, $sum, $minor);

        unlock($id);

        // run the indexer if page wasn't indexed yet
        idx_addPage($id);

        return true;
    }

    /**
     * Appends text to a wiki page.
     *
     * @param string $id page id
     * @param string $text wiki text
     * @param array $params such as summary,minor
     * @return bool|string
     * @throws RemoteException
     */
    public function appendPage($id, $text, $params = array())
    {
        $currentpage = $this->rawPage($id);
        if (!is_string($currentpage)) {
            return $currentpage;
        }
        return $this->putPage($id, $currentpage . $text, $params);
    }

    /**
     * Remove one or more users from the list of registered users
     *
     * @param string[] $usernames List of usernames to remove
     *
     * @return bool
     *
     * @throws AccessDeniedException
     */
    public function deleteUsers($usernames)
    {
        if (!auth_isadmin()) {
            throw new AccessDeniedException('Only admins are allowed to delete users', 114);
        }
        /** @var \dokuwiki\Extension\AuthPlugin $auth */
        global $auth;
        return (bool)$auth->triggerUserMod('delete', array($usernames));
    }

    /**
     * Uploads a file to the wiki.
     *
     * Michael Klier <chi@chimeric.de>
     *
     * @param string $id page id
     * @param string $file
     * @param array $params such as overwrite
     * @return false|string
     * @throws RemoteException
     */
    public function putAttachment($id, $file, $params = array())
    {
        $id = cleanID($id);
        $auth = auth_quickaclcheck(getNS($id) . ':*');

        if (!isset($id)) {
            throw new RemoteException('Filename not given.', 231);
        }

        global $conf;

        $ftmp = $conf['tmpdir'] . '/' . md5($id . clientIP());

        // save temporary file
        @unlink($ftmp);
        io_saveFile($ftmp, $file);

        $res = media_save(array('name' => $ftmp), $id, $params['ow'], $auth, 'rename');
        if (is_array($res)) {
            throw new RemoteException($res[0], -$res[1]);
        } else {
            return $res;
        }
    }

    /**
     * Deletes a file from the wiki.
     *
     * @author Gina Haeussge <osd@foosel.net>
     *
     * @param string $id page id
     * @return int
     * @throws AccessDeniedException no permissions
     * @throws RemoteException file in use or not deleted
     */
    public function deleteAttachment($id)
    {
        $id = cleanID($id);
        $auth = auth_quickaclcheck(getNS($id) . ':*');
        $res = media_delete($id, $auth);
        if ($res & DOKU_MEDIA_DELETED) {
            return 0;
        } elseif ($res & DOKU_MEDIA_NOT_AUTH) {
            throw new AccessDeniedException('You don\'t have permissions to delete files.', 212);
        } elseif ($res & DOKU_MEDIA_INUSE) {
            throw new RemoteException('File is still referenced', 232);
        } else {
            throw new RemoteException('Could not delete file', 233);
        }
    }

    /**
     * Returns the permissions of a given wiki page for the current user or another user
     *
     * @param string $id page id
     * @param string|null $user username
     * @param array|null $groups array of groups
     * @return int permission level
     */
    public function aclCheck($id, $user = null, $groups = null)
    {
        /** @var \dokuwiki\Extension\AuthPlugin $auth */
        global $auth;

        $id = $this->resolvePageId($id);
        if ($user === null) {
            return auth_quickaclcheck($id);
        } else {
            if ($groups === null) {
                $userinfo = $auth->getUserData($user);
                if ($userinfo === false) {
                    $groups = array();
                } else {
                    $groups = $userinfo['grps'];
                }
            }
            return auth_aclcheck($id, $user, $groups);
        }
    }

    /**
     * Lists all links contained in a wiki page
     *
     * @author Michael Klier <chi@chimeric.de>
     *
     * @param string $id page id
     * @return array
     * @throws AccessDeniedException  no read access for page
     */
    public function listLinks($id)
    {
        $id = $this->resolvePageId($id);
        if (auth_quickaclcheck($id) < AUTH_READ) {
            throw new AccessDeniedException('You are not allowed to read this page', 111);
        }
        $links = array();

        // resolve page instructions
        $ins = p_cached_instructions(wikiFN($id));

        // instantiate new Renderer - needed for interwiki links
        $Renderer = new Doku_Renderer_xhtml();
        $Renderer->interwiki = getInterwiki();

        // parse parse instructions
        foreach ($ins as $in) {
            $link = array();
            switch ($in[0]) {
                case 'internallink':
                    $link['type'] = 'local';
                    $link['page'] = $in[1][0];
                    $link['href'] = wl($in[1][0]);
                    array_push($links, $link);
                    break;
                case 'externallink':
                    $link['type'] = 'extern';
                    $link['page'] = $in[1][0];
                    $link['href'] = $in[1][0];
                    array_push($links, $link);
                    break;
                case 'interwikilink':
                    $url = $Renderer->_resolveInterWiki($in[1][2], $in[1][3]);
                    $link['type'] = 'extern';
                    $link['page'] = $url;
                    $link['href'] = $url;
                    array_push($links, $link);
                    break;
            }
        }

        return ($links);
    }

    /**
     * Returns a list of recent changes since give timestamp
     *
     * @author Michael Hamann <michael@content-space.de>
     * @author Michael Klier <chi@chimeric.de>
     *
     * @param int $timestamp unix timestamp
     * @return array
     * @throws RemoteException no valid timestamp
     */
    public function getRecentChanges($timestamp)
    {
        if (strlen($timestamp) != 10) {
            throw new RemoteException('The provided value is not a valid timestamp', 311);
        }

        $recents = getRecentsSince($timestamp);

        $changes = array();

        foreach ($recents as $recent) {
            $change = array();
            $change['name'] = $recent['id'];
            $change['lastModified'] = $this->api->toDate($recent['date']);
            $change['author'] = $recent['user'];
            $change['version'] = $recent['date'];
            $change['perms'] = $recent['perms'];
            $change['size'] = @filesize(wikiFN($recent['id']));
            array_push($changes, $change);
        }

        if (!empty($changes)) {
            return $changes;
        } else {
            // in case we still have nothing at this point
            throw new RemoteException('There are no changes in the specified timeframe', 321);
        }
    }

    /**
     * Returns a list of recent media changes since give timestamp
     *
     * @author Michael Hamann <michael@content-space.de>
     * @author Michael Klier <chi@chimeric.de>
     *
     * @param int $timestamp unix timestamp
     * @return array
     * @throws RemoteException no valid timestamp
     */
    public function getRecentMediaChanges($timestamp)
    {
        if (strlen($timestamp) != 10)
            throw new RemoteException('The provided value is not a valid timestamp', 311);

        $recents = getRecentsSince($timestamp, null, '', RECENTS_MEDIA_CHANGES);

        $changes = array();

        foreach ($recents as $recent) {
            $change = array();
            $change['name'] = $recent['id'];
            $change['lastModified'] = $this->api->toDate($recent['date']);
            $change['author'] = $recent['user'];
            $change['version'] = $recent['date'];
            $change['perms'] = $recent['perms'];
            $change['size'] = @filesize(mediaFN($recent['id']));
            array_push($changes, $change);
        }

        if (!empty($changes)) {
            return $changes;
        } else {
            // in case we still have nothing at this point
            throw new RemoteException('There are no changes in the specified timeframe', 321);
        }
    }

    /**
     * Returns a list of available revisions of a given wiki page
     * Number of returned pages is set by $conf['recent']
     * However not accessible pages are skipped, so less than $conf['recent'] could be returned
     *
     * @author Michael Klier <chi@chimeric.de>
     *
     * @param string $id page id
     * @param int $first skip the first n changelog lines
     *                      0 = from current(if exists)
     *                      1 = from 1st old rev
     *                      2 = from 2nd old rev, etc
     * @return array
     * @throws AccessDeniedException no read access for page
     * @throws RemoteException empty id
     */
    public function pageVersions($id, $first = 0)
    {
        $id = $this->resolvePageId($id);
        if (auth_quickaclcheck($id) < AUTH_READ) {
            throw new AccessDeniedException('You are not allowed to read this page', 111);
        }
        global $conf;

        $versions = array();

        if (empty($id)) {
            throw new RemoteException('Empty page ID', 131);
        }

        $first = (int) $first;
        $first_rev = $first - 1;
        $first_rev = $first_rev < 0 ? 0 : $first_rev;
        $pagelog = new PageChangeLog($id);
        $revisions = $pagelog->getRevisions($first_rev, $conf['recent']);

        if ($first == 0) {
            array_unshift($revisions, '');  // include current revision
            if (count($revisions) > $conf['recent']) {
                array_pop($revisions);          // remove extra log entry
            }
        }

        if (!empty($revisions)) {
            foreach ($revisions as $rev) {
                $file = wikiFN($id, $rev);
                $time = @filemtime($file);
                // we check if the page actually exists, if this is not the
                // case this can lead to less pages being returned than
                // specified via $conf['recent']
                if ($time) {
                    $pagelog->setChunkSize(1024);
                    $info = $pagelog->getRevisionInfo($rev ? $rev : $time);
                    if (!empty($info)) {
                        $data = array();
                        $data['user'] = $info['user'];
                        $data['ip'] = $info['ip'];
                        $data['type'] = $info['type'];
                        $data['sum'] = $info['sum'];
                        $data['modified'] = $this->api->toDate($info['date']);
                        $data['version'] = $info['date'];
                        array_push($versions, $data);
                    }
                }
            }
            return $versions;
        } else {
            return array();
        }
    }

    /**
     * The version of Wiki RPC API supported
     */
    public function wikiRpcVersion()
    {
        return 2;
    }

    /**
     * Locks or unlocks a given batch of pages
     *
     * Give an associative array with two keys: lock and unlock. Both should contain a
     * list of pages to lock or unlock
     *
     * Returns an associative array with the keys locked, lockfail, unlocked and
     * unlockfail, each containing lists of pages.
     *
     * @param array[] $set list pages with array('lock' => array, 'unlock' => array)
     * @return array
     */
    public function setLocks($set)
    {
        $locked = array();
        $lockfail = array();
        $unlocked = array();
        $unlockfail = array();

        foreach ((array) $set['lock'] as $id) {
            $id = $this->resolvePageId($id);
            if (auth_quickaclcheck($id) < AUTH_EDIT || checklock($id)) {
                $lockfail[] = $id;
            } else {
                lock($id);
                $locked[] = $id;
            }
        }

        foreach ((array) $set['unlock'] as $id) {
            $id = $this->resolvePageId($id);
            if (auth_quickaclcheck($id) < AUTH_EDIT || !unlock($id)) {
                $unlockfail[] = $id;
            } else {
                $unlocked[] = $id;
            }
        }

        return array(
            'locked' => $locked,
            'lockfail' => $lockfail,
            'unlocked' => $unlocked,
            'unlockfail' => $unlockfail,
        );
    }

    /**
     * Return API version
     *
     * @return int
     */
    public function getAPIVersion()
    {
        return self::API_VERSION;
    }

    /**
     * Login
     *
     * @param string $user
     * @param string $pass
     * @return int
     */
    public function login($user, $pass)
    {
        global $conf;
        /** @var \dokuwiki\Extension\AuthPlugin $auth */
        global $auth;

        if (!$conf['useacl']) return 0;
        if (!$auth) return 0;

        @session_start(); // reopen session for login
        $ok = null;
        if ($auth->canDo('external')) {
            $ok = $auth->trustExternal($user, $pass, false);
        }
        if ($ok === null){
            $evdata = array(
                'user' => $user,
                'password' => $pass,
                'sticky' => false,
                'silent' => true,
            );
            $ok = Event::createAndTrigger('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
        }
        session_write_close(); // we're done with the session

        return $ok;
    }

    /**
     * Log off
     *
     * @return int
     */
    public function logoff()
    {
        global $conf;
        global $auth;
        if (!$conf['useacl']) return 0;
        if (!$auth) return 0;

        auth_logoff();

        return 1;
    }

    /**
     * Resolve page id
     *
     * @param string $id page id
     * @return string
     */
    private function resolvePageId($id)
    {
        $id = cleanID($id);
        if (empty($id)) {
            global $conf;
            $id = cleanID($conf['start']);
        }
        return $id;
    }
}


text:
/*
* =============================================================================
*
*
*   FILENAME            : test_image_add.cpp
*
*   DESCRIPTION         : A test code for to understand the image data type
*
*   AUTHOR              : Mageswaran D
*
*
*   CHANGE HISTORY      :
*
*   DATE                : 22th April 2014
*
*   File Created.
*
* =============================================================================
*/

#include <cl_wrapper.hpp>
#include <cv_wrapper.h>

using namespace std;

int main()
{
    cout << "Image2d to Float Conversion" << endl;
    iv::CLSetup cl;
    iv::Program* prog;
    iv::KernelLauncher* kl;
    std::string file1 = "image2d_to_float.cl";
    std::vector<std::string> filesPath;
    filesPath.push_back(file1);

    cl.init();
    prog = cl.createProgram(filesPath);
    prog->buildProgram();
    kl = prog->createKernelLauncher("image2d_to_float");

    int width, height, step;
    uchar* pixelPointer;
    std::string image1Name = "shiva46x46.jpg";
    iv::CVSetup cv;
    cv.openImageBGRA(image1Name, width, height,
                     step, pixelPointer);
    cv.showImage();
    return 0;
}

redpajama_set_name: RedPajamaGithub


text:
A generator for [Yeoman](http://yeoman.io).

A Yeoman generator for Drupal

This generator will:

* Download Drupal
* Create the configuration file and grant permissions
* Create database
* Open install page

## Getting Started

To install generator-devpress from npm, run:

```
$ npm install -g generator-drupalbase
```

Finally, initiate the generator:

```
$ yo drupalbase
```
## License

[MIT License](http://en.wikipedia.org/wiki/MIT_License)

```
$ npm install -g yo
```


text:
@class NSString;

@interface BussinessExtendItem : MMObject
{
    NSString *nsIconUrl;
    NSString *nsName;
    NSString *nsJumpUrl;
}

@property(retain, nonatomic) NSString *nsJumpUrl; // @synthesize nsJumpUrl;
@property(retain, nonatomic) NSString *nsName; // @synthesize nsName;
@property(retain, nonatomic) NSString *nsIconUrl; // @synthesize nsIconUrl;
- (void).cxx_destruct;

@end


text:
        translate
        {{ App::getLocale() }}

        @foreach( [ 'en', 'it' ] as $lang )

                 $lang ] ) }}" onclick="event.preventDefault(); document.getElementById('lang-switch-{{ $lang }}').submit();">
                    {{ App::isLocale( $lang ) ? 'radio_button_checked' : 'radio_button_unchecked'  }}
                    {{ $lang }}

                <form id="lang-switch-{{ $lang }}" action="{{ url( '/lang', [ 'lang' => $lang ] ) }}" method="post" style="display: none;">
                    <input type="hidden" name="backuri" value="{{ Request::path() }}">
                    {{ csrf_field() }}
                </form>

        @endforeach


text:
package com.github.onsdigital.thetrain.response;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import spark.ResponseTransformer;

public class JsonTransformer implements ResponseTransformer {

    private static JsonTransformer INSTANCE = null;

    private Gson gson;

    private JsonTransformer() {
        GsonBuilder gsonBuilder = new GsonBuilder();

        if (true) {
            gsonBuilder.setPrettyPrinting();
        }

        this.gson = gsonBuilder.create();
    }

    @Override
    public String render(Object o) throws Exception {
        return gson.toJson(o);
    }

    public static JsonTransformer get() {
        if (INSTANCE == null) {
            synchronized (JsonTransformer.class) {
                if (INSTANCE == null) {
                    INSTANCE = new JsonTransformer();
                }
            }
        }
        return INSTANCE;
    }
}


text:
import {NgModule} from '@angular/core';

import {AceEditorComponent}   from './ace-editor.component';

@NgModule({
    imports: [],
    exports: [AceEditorComponent],
    declarations: [AceEditorComponent],
    providers: [],
})
export class AceEditorModule {
}


text:
This is a vintage code, an old research about geometric functions to visualize more than 3 space dimensions.

Author: Gabriel Gonzalez
Developed in QBasic 1998-2001
gabriel at itgabs dot com

#How to run the .BAS?
These files were created using QBasic included in MS-DOS 6.x versions the last version released was inside MS-DOS 6.22

#How to install MS-DOS 6.22?
That will work on all newer Windows OS's (x86 and 64bit) such as Windows 7, 8 or Vista:
This package contains DOS 6.22 with pre-installed QBasic 1.1, QuickBasic 4.5,
QuickBasic Extended 7.1 and VisualBasic for DOS

Requirements (Freeware):

 1. Download and install VM Player http://www.vmware.com/go/downloadplayer/
 2. Download and unpack MS-DOS 6.22
Start VM Player and run MS-DOS 6.22; when asked whether it was copied or moved, select moved.

Now you'll have four options:

 1. Run QBasic 1.1 (Interpreter only):
 • Simply type in: "qbasic" (always without quotes) and hit [ENTER]

 2. Run QuickBasic 4.5 (Compiler):
 • type in: "cd qb45" - [ENTER]
 • type in: "qb" - [ENTER]

 3. Run Quickbasic Extended 7.1 PDS (Professional Development System) aka QBX:
 • type in: "cd qbx\bin" - [ENTER]
 • type in: "qbx" - [ENTER]

 4. Run Visual Basic for DOS:
 • type in: "cd vbdos" - [ENTER]
 • type in: "vbdos" - [ENTER]

Download MS-DOS 6.22 now by clicking the Download Button below!
http://www.qbasic.net/en/qbasic-downloads/DOS/DOS-622-vmware.htm#_msdos622

source: http://www.qbasic.net/en/qbasic-downloads/DOS/DOS-622-vmware.htm

#Create a Floppy disk inside the virtual machine

#Move or Load the files inside the floppy

#Open qbasic

Press ESC, Click in File, Open and A:/ select HIPERCUB.BAS and to run press F5 in the keyboard

#In the Black Screen press any of these keys

These set of keys change the position of the figure rotating the Hipercube over it center incrementing the angle in any set of 2 coordenates (X, Y) , (Y, Z) , (Z, X) , (Z, U) , (X, U) , (Y, U)

 q
 w
 a
 s
 z
 x
 e
 r
 d
 f
 c
 v

notice Z and U are angles perpendicular with the screen, so e and r move the hipercube but the shadow from 4D to 3D to the screen 2D is exactly the same.


text:
module.exports = options => function attachHALObj(halObj, container) {
  if (options.makeObjects) {
    // _links is an object
    var name = halObj.rel;
    delete halObj.rel;
    container[name] = halObj;
  } else {
    // _links is an array
    container.push(halObj);
  }
}


text:
class Pi < ActiveRecord::Base
  attr_accessible :address, :contact, :lat, :lng, :description, :name, :typePI

  validates_presence_of :name, :typePI, :lat, :lng
  validates_uniqueness_of :name, :scope => [:lat,:lng]
   # Type must be one of the default set
  validate :correct_type

  def as_json(options)
    {
        :name => name,
        :typePI => typePI,
        :lat => lat,
        :lng => lng,
        :address => address,
        :contact => contact,
        :description => description

    }
  end

  def correct_type
    unless ["Restaurant","Hotel","Bar","Transport","Parking","Conference","Historic Site"].include? self.typePI
      errors.add(:type, "incorrect type")
    end
  end

end


text:
<?php
namespace Notejam\NoteBundle\Tests\Controller;

use Liip\FunctionalTestBundle\Test\WebTestCase;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Notejam\UserBundle\Entity\User;
use Notejam\NoteBundle\Entity\Pad;

class PadControllerTest extends WebTestCase
{
    public function setUp()
    {
        $this->loadFixtures(array());
        // init kernel to init entity manager
        static::$kernel = static::createKernel(array('environment' => 'test'));
        static::$kernel->boot();
    }

    public function getEm() {
        $this->em = static::$kernel->getContainer()
            ->get('doctrine')
            ->getManager() ;
        return $this->em;
    }

    private function _createUser($email, $password) {
        $user = new User();

        $encoder = static::$kernel->getContainer()
            ->get('security.encoder_factory')
            ->getEncoder($user);

        $password = $encoder->encodePassword($password, $user->getSalt());
        $user->setEmail($email)
             ->setPassword($password);

        $this->getEm()->persist($user);
        $this->getEm()->flush();

        return $user;
    }

    private function _createPad($name, $user) {
        $pad = new Pad();
        $pad->setName($name);
        $pad->setUser($user);

        $this->getEm()->persist($pad);
        $this->getEm()->flush();

        return $pad;
    }

    private function _signIn($user)
    {
        $client = static::createClient();
        $session = $client->getContainer()->get('session');

        $firewall = 'main';
        $token = new UsernamePasswordToken(
            $user, $user->getPassword(), $firewall, array('ROLE_USER')
        );
        $session->set('_security_'.$firewall, serialize($token));
        $session->save();

        $cookie = new Cookie($session->getName(), $session->getId());
        $client->getCookieJar()->set($cookie);
        return $client;
    }

    public function testCreatePadSuccess()
    {
        $email = 'test@example.com';
        $password = '123123';
        $user = $this->_createUser($email, $password);

        $client = $this->_signIn($user);
        $client->followRedirects();
        $crawler = $client->request('GET', '/pads/create');
        $form = $crawler->filter('button')->form();
        $form['pad[name]'] = 'Pad';
        $crawler = $client->submit($form);
        $this->assertEquals(1, $crawler->filter('nav > ul > li')->count());
        $this->assertCount(
            1, $this->getEm()->getRepository('NotejamNoteBundle:Pad')->findAll()
        );
    }

    public function testCreatePadErrorRequiredFields()
    {
        $email = 'test@example.com';
        $password = '123123';
        $user = $this->_createUser($email, $password);

        $client = $this->_signIn($user);
        $crawler = $client->request('GET', '/pads/create');
        $form = $crawler->filter('button')->form();
        $crawler = $client->submit($form);
        $this->assertEquals(1, $crawler->filter('ul.errorlist > li')->count());
    }

    public function testEditPadSuccess()
    {
        $email = 'test@example.com';
        $password = '123123';
        $user = $this->_createUser($email, $password);
        $pad = $this->_createPad('initial pad', $user);

        $client = $this->_signIn($user);
        $crawler = $client->request('GET', "/pads/{$pad->getId()}/edit");
        $form = $crawler->filter('button')->form();
        $newName = 'new pad name';
        $form['pad[name]'] = $newName;
        $crawler = $client->submit($form);

        $updatedPad = $this->getEm()->getRepository(
            'NotejamNoteBundle:Pad'
        )->find(1);
        $this->assertEquals($newName, $updatedPad->getName());
    }

    public function testEditPadErrorRequiredFields()
    {
        $email = 'test@example.com';
        $password = '123123';
        $user = $this->_createUser($email, $password);
        $pad = $this->_createPad('initial pad', $user);

        $client = $this->_signIn($user);
        $crawler = $client->request('GET', "/pads/{$pad->getId()}/edit");
        $form = $crawler->filter('button')->form();
        $form['pad[name]'] = "";
        $crawler = $client->submit($form);
        $this->assertEquals(1, $crawler->filter('ul.errorlist > li')->count());
    }

    public function testDeletePadSuccess()
    {
        $email = 'test@example.com';
        $password = '123123';
        $user = $this->_createUser($email, $password);
        $pad = $this->_createPad('test pad', $user);

        $client = $this->_signIn($user);
        $crawler = $client->request('GET', "/pads/{$pad->getId()}/delete");
        $form = $crawler->filter('button')->form();
        $crawler = $client->submit($form);

        $this->assertCount(
            0, $this->getEm()->getRepository('NotejamNoteBundle:Pad')->findAll()
        );
    }

    public function testDeletePadErrorAnotherUser()
    {
        $email = 'test@example.com';
        $password = '123123';
        $user = $this->_createUser($email, $password);
        $pad = $this->_createPad('test pad', $user);

        $anotherUser = $this->_createUser('test2@example.com', $password);
        $client = $this->_signIn($anotherUser);
        $crawler = $client->request('GET', "/pads/{$pad->getId()}/delete");
        $this->assertTrue($client->getResponse()->isNotFound());
    }

    public function testViewPadNotesSuccess()
    {
        $email = 'test@example.com';
        $password = '123123';
        $user = $this->_createUser($email, $password);
        $pad = $this->_createPad('test pad', $user);

        $client = $this->_signIn($user);
        $client->followRedirects();
        $crawler = $client->request('GET', "/pads/{$pad->getId()}");
        $this->assertTrue($client->getResponse()->isSuccessful());
    }
}


text:
<?php echo $this->admin_panel->breadcrumb(array(
array( 'uri' => $CI->_get_uri('listing'), 'title' => humanize(get_class($CI)) ),
array( 'uri' => $CI->uri->uri_string, 'title' => 'Trash record'),
)) ?>

<fieldset>
    <legend><?php echo l('Confirmation') ?></legend>

        <?php if (count($ids) > 1): ?>
       <?php echo l('Are you sure want to trash %s records' , array(count($ids))) ?>?
        <?php else: ?>
       <?php echo l('Are you sure want to trash %s record' , array(count($id))) ?>?
        <?php endif ?>

</fieldset>

    <a href="<?php echo site_url($CI->_get_uri('trash').'/'.$id.'?confirmed=1') ?>" class="btn"><?php echo l('OK') ?>
    <a href="<?php echo site_url($CI->_get_uri('listing')) ?>" class="btn cancel"><?php echo l('Cancel') ?>


text:
package org.elasticsearch.search.aggregations.metrics;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.aggregations.bucket.global.Global;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.aggregations.metrics.min.Min;
import org.junit.Test;

import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.search.aggregations.AggregationBuilders.global;
import static org.elasticsearch.search.aggregations.AggregationBuilders.histogram;
import static org.elasticsearch.search.aggregations.AggregationBuilders.min;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;

/**
 *
 */
public class MinTests extends AbstractNumericTests {

    @Test
    public void testEmptyAggregation() throws Exception {

        SearchResponse searchResponse = client().prepareSearch("empty_bucket_idx")
                .setQuery(matchAllQuery())
                .addAggregation(histogram("histo").field("value").interval(1l).minDocCount(0).subAggregation(min("min")))
                .execute().actionGet();

        assertThat(searchResponse.getHits().getTotalHits(), equalTo(2l));
        Histogram histo = searchResponse.getAggregations().get("histo");
        assertThat(histo, notNullValue());
        Histogram.Bucket bucket = histo.getBuckets().get(1);
        assertThat(bucket, notNullValue());

        Min min = bucket.getAggregations().get("min");
        assertThat(min, notNullValue());
        assertThat(min.getName(), equalTo("min"));
        assertThat(min.getValue(), equalTo(Double.POSITIVE_INFINITY));
    }

    @Test
    public void testUnmapped() throws Exception {
        SearchResponse searchResponse = client().prepareSearch("idx_unmapped")
                .setQuery(matchAllQuery())
                .addAggregation(min("min").field("value"))
                .execute().actionGet();

        assertThat(searchResponse.getHits().getTotalHits(), equalTo(0l));

        Min min = searchResponse.getAggregations().get("min");
        assertThat(min, notNullValue());
        assertThat(min.getName(), equalTo("min"));
        assertThat(min.getValue(), equalTo(Double.POSITIVE_INFINITY));
    }

    @Test
    public void testSingleValuedField() throws Exception {
        SearchResponse searchResponse = client().prepareSearch("idx")
                .setQuery(matchAllQuery())
                .addAggregation(min("min").field("value"))
                .execute().actionGet();

        assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));

        Min min = searchResponse.getAggregations().get("min");
        assertThat(min, notNullValue());
        assertThat(min.getName(), equalTo("min"));
        assertThat(min.getValue(), equalTo(1.0));
    }

    @Test
    public void testSingleValuedField_WithFormatter() throws Exception {
        SearchResponse searchResponse = client().prepareSearch("idx").setQuery(matchAllQuery())
                .addAggregation(min("min").format("0000.0").field("value")).execute().actionGet();

        assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));

        Min min = searchResponse.getAggregations().get("min");
        assertThat(min, notNullValue());
        assertThat(min.getName(), equalTo("min"));
        assertThat(min.getValue(), equalTo(1.0));
        assertThat(min.getValueAsString(), equalTo("0001.0"));
    }

    @Test
    public void testSingleValuedField_getProperty() throws Exception {

        SearchResponse searchResponse = client().prepareSearch("idx").setQuery(matchAllQuery())
                .addAggregation(global("global").subAggregation(min("min").field("value"))).execute().actionGet();

        assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));

        Global global = searchResponse.getAggregations().get("global");
        assertThat(global, notNullValue());
        assertThat(global.getName(), equalTo("global"));
        assertThat(global.getDocCount(), equalTo(10l));
        assertThat(global.getAggregations(), notNullValue());
        assertThat(global.getAggregations().asMap().size(), equalTo(1));

        Min min = global.getAggregations().get("min");
        assertThat(min, notNullValue());
        assertThat(min.getName(), equalTo("min"));
        double expectedMinValue = 1.0;
        assertThat(min.getValue(), equalTo(expectedMinValue));
        assertThat((Min) global.getProperty("min"), equalTo(min));
        assertThat((double) global.getProperty("min.value"), equalTo(expectedMinValue));
        assertThat((double) min.getProperty("value"), equalTo(expectedMinValue));
    }

    @Test
    public void testSingleValuedField_PartiallyUnmapped() throws Exception {
        SearchResponse searchResponse = client().prepareSearch("idx", "idx_unmapped")
                .setQuery(matchAllQuery())
                .addAggregation(min("min").field("value"))
                .execute().actionGet();

        assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));

        Min min = searchResponse.getAggregations().get("min");
        assertThat(min, notNullValue());
        assertThat(min.getName(), equalTo("min"));
        assertThat(min.getValue(), equalTo(1.0));
    }

    @Test
    public void testSingleValuedField_WithValueScript() throws Exception {
        SearchResponse searchResponse = client().prepareSearch("idx")
                .setQuery(matchAllQuery())
                .addAggregation(min("min").field("value").script("_value - 1"))
                .execute().actionGet();

        assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));

        Min min = searchResponse.getAggregations().get("min");
        assertThat(min, notNullValue());
        assertThat(min.getName(), equalTo("min"));
        assertThat(min.getValue(), equalTo(0.0));
    }

    @Test
    public void testSingleValuedField_WithValueScript_WithParams() throws Exception {
        SearchResponse searchResponse = client().prepareSearch("idx")
                .setQuery(matchAllQuery())
                .addAggregation(min("min").field("value").script("_value - dec").param("dec", 1))
                .execute().actionGet();

        assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));

        Min min = searchResponse.getAggregations().get("min");
        assertThat(min, notNullValue());
        assertThat(min.getName(), equalTo("min"));
        assertThat(min.getValue(), equalTo(0.0));
    }

    @Test
    public void testMultiValuedField() throws Exception {
        SearchResponse searchResponse = client().prepareSearch("idx")
                .setQuery(matchAllQuery())
                .addAggregation(min("min").field("values"))
                .execute().actionGet();

        assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));

        Min min = searchResponse.getAggregations().get("min");
        assertThat(min, notNullValue());
        assertThat(min.getName(), equalTo("min"));
        assertThat(min.getValue(), equalTo(2.0));
    }

    @Test
    public void testMultiValuedField_WithValueScript() throws Exception {
        SearchResponse searchResponse = client().prepareSearch("idx")
                .setQuery(matchAllQuery())
                .addAggregation(min("min").field("values").script("_value - 1"))
                .execute().actionGet();

        assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));

        Min min = searchResponse.getAggregations().get("min");
        assertThat(min, notNullValue());
        assertThat(min.getName(), equalTo("min"));
        assertThat(min.getValue(), equalTo(1.0));
    }

    @Test
    public void testMultiValuedField_WithValueScript_Reverse() throws Exception {
        // test what happens when values arrive in reverse order since the min aggregator is optimized to work on sorted values
        SearchResponse searchResponse = client().prepareSearch("idx")
                .setQuery(matchAllQuery())
                .addAggregation(min("min").field("values").script("_value * -1"))
                .execute().actionGet();

        assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));

        Min min = searchResponse.getAggregations().get("min");
        assertThat(min, notNullValue());
        assertThat(min.getName(), equalTo("min"));
        assertThat(min.getValue(), equalTo(-12d));
    }

    @Test
    public void testMultiValuedField_WithValueScript_WithParams() throws Exception {
        SearchResponse searchResponse = client().prepareSearch("idx")
                .setQuery(matchAllQuery())
                .addAggregation(min("min").field("values").script("_value - dec").param("dec", 1))
                .execute().actionGet();

        assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));

        Min min = searchResponse.getAggregations().get("min");
        assertThat(min, notNullValue());
        assertThat(min.getName(), equalTo("min"));
        assertThat(min.getValue(), equalTo(1.0));
    }

    @Test
    public void testScript_SingleValued() throws Exception {
        SearchResponse searchResponse = client().prepareSearch("idx")
                .setQuery(matchAllQuery())
                .addAggregation(min("min").script("doc['value'].value"))
                .execute().actionGet();

        assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));

        Min min = searchResponse.getAggregations().get("min");
        assertThat(min, notNullValue());
        assertThat(min.getName(), equalTo("min"));
        assertThat(min.getValue(), equalTo(1.0));
    }

    @Test
    public void testScript_SingleValued_WithParams() throws Exception {
        SearchResponse searchResponse = client().prepareSearch("idx")
                .setQuery(matchAllQuery())
                .addAggregation(min("min").script("doc['value'].value - dec").param("dec", 1))
                .execute().actionGet();

        assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));

        Min min = searchResponse.getAggregations().get("min");
        assertThat(min, notNullValue());
        assertThat(min.getName(), equalTo("min"));
        assertThat(min.getValue(), equalTo(0.0));
    }

    @Test
    public void testScript_ExplicitSingleValued_WithParams() throws Exception {
        SearchResponse searchResponse = client().prepareSearch("idx")
                .setQuery(matchAllQuery())
                .addAggregation(min("min").script("doc['value'].value - dec").param("dec", 1))
                .execute().actionGet();

        assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));

        Min min = searchResponse.getAggregations().get("min");
        assertThat(min, notNullValue());
        assertThat(min.getName(), equalTo("min"));
        assertThat(min.getValue(), equalTo(0.0));
    }

    @Test
    public void testScript_MultiValued() throws Exception {
        SearchResponse searchResponse = client().prepareSearch("idx")
                .setQuery(matchAllQuery())
                .addAggregation(min("min").script("doc['values'].values"))
                .execute().actionGet();

        assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));

        Min min = searchResponse.getAggregations().get("min");
        assertThat(min, notNullValue());
        assertThat(min.getName(), equalTo("min"));
        assertThat(min.getValue(), equalTo(2.0));
    }

    @Test
    public void testScript_ExplicitMultiValued() throws Exception {
        SearchResponse searchResponse = client().prepareSearch("idx")
                .setQuery(matchAllQuery())
                .addAggregation(min("min").script("doc['values'].values"))
                .execute().actionGet();

        assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));

        Min min = searchResponse.getAggregations().get("min");
        assertThat(min, notNullValue());
        assertThat(min.getName(), equalTo("min"));
        assertThat(min.getValue(), equalTo(2.0));
    }

    @Test
    public void testScript_MultiValued_WithParams() throws Exception {
        SearchResponse searchResponse = client().prepareSearch("idx")
                .setQuery(matchAllQuery())
                .addAggregation(min("min").script("List values = doc['values'].values; double[] res = new double[values.size()]; for (int i = 0; i < res.length; i++) { res[i] = values.get(i) - dec; }; return res;").param("dec", 1))
                .execute().actionGet();

        assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));

        Min min = searchResponse.getAggregations().get("min");
        assertThat(min, notNullValue());
        assertThat(min.getName(), equalTo("min"));
        assertThat(min.getValue(), equalTo(1.0));
    }

}


text:
package org.hildan.livedoc.core.readers.combined;

/**
 * Represent a type for which multiple instances can be merged into one.
 *
 * @param <T>
 *         the type of objects that can be merged
 */
public interface Mergeable<T> {

    /**
     * Merges this object with the given other object to return a new object. The given object's properties take
     * precedence over this object's properties.
     *
     * @param override
     *         the overriding other object
     * @param merger
     *         the {@link DocMerger} to use to delegate the merge of sub-elements
     *
     * @return a new object combining the properties of this object and the provided one
     */
    T merge(T override, DocMerger merger);
}


text:
layout: docs
title: Interactions
description: Utility classes that change how users interact with contents of a website.
group: utilities
toc: false
---

## Text selection

Change the way in which the content is selected when the user interacts with it.

{{< example >}}

This paragraph will be entirely selected when clicked by the user.

This paragraph has default select behavior.

This paragraph will not be selectable when clicked by the user.

{{< /example >}}

## Pointer events

Bootstrap provides `pe-none` and `pe-auto` classes to prevent or add element interactions.

{{< example >}}

This link can not be clicked.

This link can be clicked (this is default behaviour).

This link can not be clicked because the pointer-events property is inherited from its parent. However, this link has a pe-auto class and can be clicked.

{{< /example >}}


text:
// (C) Copyright 2015 Martin Dougiamas
//
// 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.

import { Injectable, Injector } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { AddonWorkshopAssessmentStrategyHandler } from '../../../providers/assessment-strategy-delegate';
import { AddonModWorkshopAssessmentStrategyCommentsComponent } from '../component/comments';

/**
 * Handler for comments assessment strategy plugin.
 */
@Injectable()
export class AddonModWorkshopAssessmentStrategyCommentsHandler implements AddonWorkshopAssessmentStrategyHandler {
    name = 'AddonModWorkshopAssessmentStrategyComments';
    strategyName = 'comments';

    constructor(private translate: TranslateService) {}

    /**
     * Whether or not the handler is enabled on a site level.
     * @return {boolean|Promise<boolean>} Whether or not the handler is enabled on a site level.
     */
    isEnabled(): boolean | Promise<boolean> {
        return true;
    }

    /**
     * Return the Component to render the plugin.
     * It's recommended to return the class of the component, but you can also return an instance of the component.
     *
     * @param {Injector} injector Injector.
     * @return {any|Promise<any>} The component (or promise resolved with component) to use, undefined if not found.
     */
    getComponent(injector: Injector): any | Promise<any> {
        return AddonModWorkshopAssessmentStrategyCommentsComponent;
    }

    /**
     * Prepare original values to be shown and compared.
     *
     * @param  {any}    form       Original data of the form.
     * @param  {number} workshopId Workshop Id
     * @return {Promise<any[]>}    Promise resolved with original values sorted.
     */
     getOriginalValues(form: any, workshopId: number): Promise<any[]> {
        const originalValues = [];

        form.fields.forEach((field, n) => {
            field.dimtitle = this.translate.instant('addon.mod_workshop_assessment_comments.dimensionnumber', {$a: field.number});

            if (!form.current[n]) {
                form.current[n] = {};
            }

            originalValues[n] = {
                peercomment: form.current[n].peercomment || '',
                number: field.number
            };
        });

        return Promise.resolve(originalValues);
    }

    /**
     * Check if the assessment data has changed for a certain submission and workshop for a this strategy plugin.
     *
     * @param  {any[]} originalValues Original values of the form.
     * @param  {any[]} currentValues  Current values of the form.
     * @return {boolean}              True if data has changed, false otherwise.
     */
    hasDataChanged(originalValues: any[], currentValues: any[]): boolean {
        for (const x in originalValues) {
            if (originalValues[x].peercomment != currentValues[x].peercomment) {
                return true;
            }
        }

        return false;
    }

    /**
     * Prepare assessment data to be sent to the server depending on the strategy selected.
     *
     * @param  {any{}} currentValues Current values of the form.
     * @param  {any}   form          Assessment form data.
     * @return {Promise<any>}        Promise resolved with the data to be sent. Or rejected with the input errors object.
     */
    prepareAssessmentData(currentValues: any[], form: any): Promise<any> {
        const data = {};
        const errors = {};
        let hasErrors = false;

        form.fields.forEach((field, idx) => {
            if (currentValues[idx].peercomment) {
                data['peercomment__idx_' + idx] = currentValues[idx].peercomment;
            } else {
                errors['peercomment_' + idx] = this.translate.instant('core.err_required');
                hasErrors = true;
            }

            data['gradeid__idx_' + idx] = parseInt(form.current[idx].gradeid, 10) || 0;
            data['dimensionid__idx_' + idx] = parseInt(field.dimensionid, 10);
        });

        if (hasErrors) {
            return Promise.reject(errors);
        }

        return Promise.resolve(data);
    }
}


text:
@interface PodsDummy_Pods_SSMVVM : NSObject
@end
@implementation PodsDummy_Pods_SSMVVM
@end


text:
class User < ApplicationRecord
  has_many :goals, dependent: :destroy
  has_many :missions, dependent: :destroy
  belongs_to :level, optional: true
  attr_accessor :remember_token

  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  has_secure_password

  validates :name, presence: true, length: {maximum: 64}
  validates :balance, numericality: { greater_than_or_equal_to: 0 }
  validates :email, presence: true, length: {maximum: 255},
            format: {with: VALID_EMAIL_REGEX},
            uniqueness: {case_sensitive: false}
  # allow_nil because has_secure_password will catch it beforehand anyways
  validates :password, presence: true, length: {minimum: 6}, allow_nil: true

  def User.digest(string)
    cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST
                                                : BCrypt::Engine.cost
    BCrypt::Password.create(string, cost: cost)
  end

  # returns: random token
  def User.new_token
    SecureRandom.urlsafe_base64
  end

  def remember
    self.remember_token = User.new_token
    update_attribute(:remember_digest, User.digest(self.remember_token))
  end

  def authenticated?(remember_token)
    return false if remember_digest.nil?
    BCrypt::Password.new(remember_digest).is_password?(remember_token)
  end

  def forget
    update_attribute(:remember_digest, nil)
  end

  def get_coins amount
    self.balance += amount
    self.coins_earned += amount
    @completed_levels = []
    while !self.level.nil? && self.balance >= self.level.cum_value
      @completed_levels.append self.level
      self.level = Level.find_by_id(self.level.id + 1)
    end
    logger.error "@completed_levels = #{@completed_levels}"
  end

  def level_progress
    level_start = level.cum_value - level.value
    ratio = (self.balance - level_start).to_f / level.value
    ratio = 1.0 if ratio > 1.0
    (100 * ratio).to_i
  end

  def check_missions
    @completed_missions = {}
    self.missions.each do |mission|
      if mission.complete?(self)
        self.get_coins mission.value
        logger.error "Unable to delete mission #{mission.id}" unless mission.destroy
        self.missions_completed += 1
        replacement = Mission.generate_mission_for(self, mission.position)
        logger.error "Unable to save mission #{mission.id}" unless replacement.save
        @completed_missions[mission.position] = mission
      end
    end
  end

  def remove_stale_missions(task_id)
    @stale_missions = {}
    self.missions.each do |mission|
      if mission.task_dependency == task_id
        @stale_missions[mission.position] = mission
        logger.error "Unable to delete mission #{mission.id}" unless mission.destroy
        replacement = Mission.generate_mission_for(self, mission.position)
        logger.error "Unable to save mission #{mission.id}" unless replacement.save
      end
    end
  end

  def completed_levels
    @completed_levels = [] if @completed_levels.nil?
    @completed_levels
  end

  def completed_missions
    @completed_missions = {} if @completed_missions.nil?
    @completed_missions
  end

  def stale_missions
    @stale_missions = {} if @stale_missions.nil?
    @stale_missions
  end

  def tasks
    self.goals.map { |goal| goal.tasks }.flatten
  end
end


text:
'use strict';

/**
 * The elastic pool edition capability.
 *
 */
class ElasticPoolEditionCapability {
  /**
   * Create a ElasticPoolEditionCapability.
   * @property {string} [name] The elastic pool edition name.
   * @property {array} [supportedElasticPoolPerformanceLevels] The list of
   * supported elastic pool DTU levels for the edition.
   * @property {boolean} [zoneRedundant] Whether or not zone redundancy is
   * supported for the edition.
   * @property {string} [status] The status of the capability. Possible values
   * include: 'Visible', 'Available', 'Default', 'Disabled'
   * @property {string} [reason] The reason for the capability not being
   * available.
   */
  constructor() {
  }

  /**
   * Defines the metadata of ElasticPoolEditionCapability
   *
   * @returns {object} metadata of ElasticPoolEditionCapability
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'ElasticPoolEditionCapability',
      type: {
        name: 'Composite',
        className: 'ElasticPoolEditionCapability',
        modelProperties: {
          name: {
            required: false,
            readOnly: true,
            serializedName: 'name',
            type: {
              name: 'String'
            }
          },
          supportedElasticPoolPerformanceLevels: {
            required: false,
            readOnly: true,
            serializedName: 'supportedElasticPoolPerformanceLevels',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'ElasticPoolPerformanceLevelCapabilityElementType',
                  type: {
                    name: 'Composite',
                    className: 'ElasticPoolPerformanceLevelCapability'
                  }
              }
            }
          },
          zoneRedundant: {
            required: false,
            readOnly: true,
            serializedName: 'zoneRedundant',
            type: {
              name: 'Boolean'
            }
          },
          status: {
            required: false,
            readOnly: true,
            serializedName: 'status',
            type: {
              name: 'Enum',
              allowedValues: [ 'Visible', 'Available', 'Default', 'Disabled' ]
            }
          },
          reason: {
            required: false,
            serializedName: 'reason',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = ElasticPoolEditionCapability;


text:
namespace core {

template <class...>
struct arg_wrapper;

template <class T, class TName, class TIsRoot, template <class...> class TList, class... TCtor, class TDependency, class TDeps>
struct arg_wrapper<T, TName, TIsRoot, TList<TCtor...>, TDependency, TDeps> {
  using type __BOOST_DI_UNUSED = T;
  using expected __BOOST_DI_UNUSED = typename TDependency::expected;
  using given __BOOST_DI_UNUSED = typename TDependency::given;
  using name __BOOST_DI_UNUSED = TName;
  using arity __BOOST_DI_UNUSED = aux::integral_constant<int, sizeof...(TCtor)>;
  using scope __BOOST_DI_UNUSED = typename TDependency::scope;
  using is_root __BOOST_DI_UNUSED = TIsRoot;

  template <class T_, class TName_, class TDefault_>
  using resolve = decltype(core::binder::resolve<T_, TName_, TDefault_>((TDeps*)0));
};

template <class T>
struct allow_void : T {};

template <>
struct allow_void<void> : aux::true_type {};

class policy {
  template <class TArg, class TPolicy, class TPolicies>
  static void call_impl(const TPolicies& policies) noexcept {
    static_cast<const TPolicy&>(policies)(TArg{});
  }

  template <class TArg, class TPolicy>
  struct try_call_impl : allow_void<decltype((aux::declval<TPolicy>())(aux::declval<TArg>()))> {};

 public:
  template <class, class>
  struct try_call;

  template <class TArg, class... TPolicies>
  struct try_call<TArg, pool_t<TPolicies...>> : aux::is_same<aux::bool_list<aux::always<TPolicies>::value...>,
                                                             aux::bool_list<try_call_impl<TArg, TPolicies>::value...>> {};

  template <class TArg, class... TPolicies>
  static void call(__BOOST_DI_UNUSED const pool_t<TPolicies...>& policies) noexcept {
    (void)aux::swallow{0, (call_impl<TArg, TPolicies>(policies), 0)...};
  }
};

}  // core

#endif


text:
function f = sqrt(f)
%SQRT   Square root.
%
% SQRT(F) returns the square root chebfun2 of a positive chebfun2 F.

% Copyright 2013 by The University of Oxford and The Chebfun Developers.
% See http://www.maths.ox.ac.uk/chebfun/ for Chebfun information.

if ( isempty(f.fun2) ) % check for empty chebfun2.
    return;
end

% positive/negative test.
[bol wzero] = singlesigntest(f);

if bol == 0 || wzero == 1
   error('CHEBFUN2:SQRT','A change of sign/zero has been detected, unable to represent the result.');
end

% Still call the constructor in case we missed a change of sign.

op = @(x,y) sqrt(f.feval(x,y)); % resample.
rect = f.corners;               % Domain.
f = chebfun2(op,rect);          % Call constructor.

end


text:
package liquibase.sqlgenerator.core;

import liquibase.changelog.ChangeSet;
import liquibase.sdk.database.MockDatabase;
import liquibase.sql.Sql;
import liquibase.sqlgenerator.AbstractSqlGeneratorTest;
import liquibase.sqlgenerator.MockSqlGeneratorChain;
import liquibase.statement.core.MarkChangeSetRanStatement;
import org.junit.Test;

import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;

public class MarkChangeSetRanGeneratorTest extends AbstractSqlGeneratorTest<MarkChangeSetRanStatement> {
    public MarkChangeSetRanGeneratorTest() throws Exception {
        super(new MarkChangeSetRanGenerator());
    }

    @Override
    protected MarkChangeSetRanStatement createSampleSqlStatement() {
        return new MarkChangeSetRanStatement(new ChangeSet("1", "a", false, false, "c", null, null, null), ChangeSet.ExecType.EXECUTED);
    }

    @Test
    public void generateSql_markRan() {
        Sql[] sqls = new MarkChangeSetRanGenerator().generateSql(new MarkChangeSetRanStatement(new ChangeSet("1", "a", false, false, "c", null, null, null), ChangeSet.ExecType.MARK_RAN), new MockDatabase(), new MockSqlGeneratorChain());
        assertEquals(1, sqls.length);
        assertTrue(sqls[0].toSql(), sqls[0].toSql().contains("MARK_RAN"));
    }
}


text:
<?php

/**
 * NOTE: When loading ExternalAccounts for use in an authentication context
 * (that is, you're going to act as the account or link identities or anything
 * like that) you should require CAN_EDIT capability even if you aren't actually
 * editing the ExternalAccount.
 *
 * ExternalAccounts have a permissive CAN_VIEW policy (like users) because they
 * interact directly with objects and can leave comments, sign documents, etc.
 * However, CAN_EDIT is restricted to users who own the accounts.
 */
final class PhabricatorExternalAccountQuery
  extends PhabricatorCursorPagedPolicyAwareQuery {

  private $ids;
  private $phids;
  private $accountTypes;
  private $accountDomains;
  private $accountIDs;
  private $userPHIDs;
  private $needImages;
  private $accountSecrets;

  public function withUserPHIDs(array $user_phids) {
    $this->userPHIDs = $user_phids;
    return $this;
  }

  public function withAccountIDs(array $account_ids) {
    $this->accountIDs = $account_ids;
    return $this;
  }

  public function withAccountDomains(array $account_domains) {
    $this->accountDomains = $account_domains;
    return $this;
  }

  public function withAccountTypes(array $account_types) {
    $this->accountTypes = $account_types;
    return $this;
  }

  public function withPHIDs(array $phids) {
    $this->phids = $phids;
    return $this;
  }

  public function withIDs($ids) {
    $this->ids = $ids;
    return $this;
  }

  public function withAccountSecrets(array $secrets) {
    $this->accountSecrets = $secrets;
    return $this;
  }

  public function needImages($need) {
    $this->needImages = $need;
    return $this;
  }

  public function loadPage() {
    $table = new PhabricatorExternalAccount();
    $conn_r = $table->establishConnection('r');

    $data = queryfx_all(
      $conn_r,
      'SELECT * FROM %T %Q %Q %Q',
      $table->getTableName(),
      $this->buildWhereClause($conn_r),
      $this->buildOrderClause($conn_r),
      $this->buildLimitClause($conn_r));

    return $table->loadAllFromArray($data);
  }

  public function willFilterPage(array $accounts) {
    if ($this->needImages) {
      $file_phids = mpull($accounts, 'getProfileImagePHID');
      $file_phids = array_filter($file_phids);

      if ($file_phids) {
        // NOTE: We use the omnipotent viewer here because these files are
        // usually created during registration and can't be associated with
        // the correct policies, since the relevant user account does not exist
        // yet. In effect, if you can see an ExternalAccount, you can see its
        // profile image.
        $files = id(new PhabricatorFileQuery())
          ->setViewer(PhabricatorUser::getOmnipotentUser())
          ->withPHIDs($file_phids)
          ->execute();
        $files = mpull($files, null, 'getPHID');
      } else {
        $files = array();
      }

      $default_file = null;
      foreach ($accounts as $account) {
        $image_phid = $account->getProfileImagePHID();
        if ($image_phid && isset($files[$image_phid])) {
          $account->attachProfileImageFile($files[$image_phid]);
        } else {
          if ($default_file === null) {
            $default_file = PhabricatorFile::loadBuiltin(
              $this->getViewer(),
              'profile.png');
          }
          $account->attachProfileImageFile($default_file);
        }
      }
    }

    return $accounts;
  }

  protected function buildWhereClause(AphrontDatabaseConnection $conn_r) {
    $where = array();

    $where[] = $this->buildPagingClause($conn_r);

    if ($this->ids) {
      $where[] = qsprintf(
        $conn_r,
        'id IN (%Ld)',
        $this->ids);
    }

    if ($this->phids) {
      $where[] = qsprintf(
        $conn_r,
        'phid IN (%Ls)',
        $this->phids);
    }

    if ($this->accountTypes) {
      $where[] = qsprintf(
        $conn_r,
        'accountType IN (%Ls)',
        $this->accountTypes);
    }

    if ($this->accountDomains) {
      $where[] = qsprintf(
        $conn_r,
        'accountDomain IN (%Ls)',
        $this->accountDomains);
    }

    if ($this->accountIDs) {
      $where[] = qsprintf(
        $conn_r,
        'accountID IN (%Ls)',
        $this->accountIDs);
    }

    if ($this->userPHIDs) {
      $where[] = qsprintf(
        $conn_r,
        'userPHID IN (%Ls)',
        $this->userPHIDs);
    }

    if ($this->accountSecrets) {
      $where[] = qsprintf(
        $conn_r,
        'accountSecret IN (%Ls)',
        $this->accountSecrets);
    }

    return $this->formatWhereClause($where);
  }

  public function getQueryApplicationClass() {
    return 'PhabricatorPeopleApplication';
  }

  /**
   * Attempts to find an external account and if none exists creates a new
   * external account with a shiny new ID and PHID.
   *
   * NOTE: This function assumes the first item in various query parameters is
   * the correct value to use in creating a new external account.
   */
  public function loadOneOrCreate() {
    $account = $this->executeOne();
    if (!$account) {
      $account = new PhabricatorExternalAccount();
      if ($this->accountIDs) {
        $account->setAccountID(reset($this->accountIDs));
      }
      if ($this->accountTypes) {
        $account->setAccountType(reset($this->accountTypes));
      }
      if ($this->accountDomains) {
        $account->setAccountDomain(reset($this->accountDomains));
      }
      if ($this->accountSecrets) {
        $account->setAccountSecret(reset($this->accountSecrets));
      }
      if ($this->userPHIDs) {
        $account->setUserPHID(reset($this->userPHIDs));
      }
      $account->save();
    }
    return $account;
  }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- The original name of the app is Memento Calendar. In Greek though the name is Εορτολόγιο Memento (Nameday Almanac Memento)
as the name makes more sense. If there is a local specific name, make sure to write it here. If not, leave it as is-->
    <string name="localised_app_name">Memento Calendar</string>
    <string name="today">Oggi</string>
    <string name="tomorrow">Domani</string>
    <string name="birthday">Compleanno</string>
    <string name="birthdays">Compleanni</string>
    <string name="namedays">Onomastici</string>
    <string name="nameday">Onomastico</string>
    <string name="contacts_birthday">"E' il compleanno di %s!"</string>
    <string name="contacts_nameday">"E' l'onomastico di %s!"</string>
    <string name="namedays_no_names">Nessun onomastico in questo giorno</string>
    <string name="birthday_no_birthday">Nessun compleanno in questo giorno</string>
    <string name="action_settings">Impostazioni</string>
    <string name="disable">Disattiva</string>
    <string name="enable">Attiva</string>
    <string name="today_celebrates_one">%1$s</string>
    <string name="today_celebrates_two">%1$s e %2$s</string>
    <string name="today_celebrates_many">%1$s e altri %2$d</string>
    <string name="about">Informazioni</string>
    <string name="service_dailyreminder">Servizio di notifica giornaliera</string>
    <string name="display_namedays">Visualizza onomastici</string>
    <string name="display_namedays_on">Verranno visualizzati gli onomastici per tutti i tuoi contatti</string>
    <string name="display_namedays_off">Gli onomastici non verranno visualizzati</string>
    <string name="contact_dev">Contatta lo sviluppatore</string>
    <string name="contact_dev_summary">Hai trovato un bug? Hai un suggerimento? Fammelo sapere!</string>
    <string name="choose">Scegli</string>
    <string name="number">numero</string>
    <string name="Call">Chiama</string>
    <string name="action_text">Invia SMS</string>
    <string name="action_send_mail">Invia e-mail</string>
    <string name="no_app_found">Nessuna applicazione trovata per questa azione</string>
    <string name="send_mail_via">Invia e-mail con</string>
    <string name="daily_reminder">Notifica giornaliera</string>
    <string name="daily_reminder_summary">"Notificami per ogni evento del giorno"</string>
    <string name="Sound">Suoneria</string>
    <string name="vibrate">Vibrazione</string>
    <string name="daily_reminder_time_summary">Ogni giorno alle %s</string>
    <string name="set_time">Imposta ora</string>
    <string name="set">Imposta</string>
    <string name="Discard">Ignora</string>
    <string name="contact_added">Contatto aggiunto</string>
    <string name="failed_to_add_contact">Il contatto non può essere aggiunto</string>
    <string name="contact_updated">Contatto aggiornato</string>
    <string name="failed_to_update_contact">Il contatto non può essere aggiornato</string>
    <string name="ringtone_silent">Silenzioso</string>
    <string name="contacts_today">Contatti che celebrano oggi</string>
    <string name="no_contacts_to_wish">Nessun contatto celebra oggi</string>
    <string name="upcoming">Prossimamente</string>
    <string name="turns_age">Compie %1$d anni</string>
    <string name="display_namedays_names">Onomastici di oggi</string>
    <string name="share_text">Prova %1$s - una bella app di promemoria per compleanni e onomastici per Android! Installala da %2$s</string>
    <string name="share_via">Condividi con</string>
    <string name="licences">Licenze</string>
    <string name="about_dev">Sviluppato e progettato da Alex Styl</string>
    <string name="about_special_thanks">"Ringraziamenti speciali a

Andreas Sfakianakis per il suo lavoro alla libreria di translitterazione dal Greco ("Greeklish")
Kosta Stoupas per la traduzione in Tedesco
Aggela Stylianidou per la traduzione in Francese
Gian Maria Calzolari per la traduzione in Italiano
Andrejs Kotovs per la traduzione in Lituano"</string>
    <string name="about_thanks_special_someone">e *%s* perché usi e supporti l\'app! :)</string>
    <string name="about_contact">C\'è qualche cosa di errato nella app? Hai un suggerimento? Invia una e-mail a %s</string>
    <string name="you">Tu</string>
    <string name="switch_on">Attivo</string>
    <string name="switch_off">Spento</string>
    <string name="thanks_for_support">Grazie per supportare l\'app</string>
    <string name="donate">Dona</string>
    <string name="loading">Sto caricando...</string>
    <string name="action_search">Cerca</string>
    <string name="contacts">Contatti</string>
    <string name="search_namedays_on">Onomastico il</string>
    <string name="show_more">Mostra altri</string>
    <string name="create">Crea</string>
    <!-- The name for contacts with empty Display name-->
    <string name="no_name">(Nessun nome)</string>
    <string name="include_year">Includi l\'anno?</string>
    <string name="Save">Salva</string>
    <string name="add">Aggiungi</string>
    <string name="contact_no_birthday">Compleanno non impostato</string>
    <string name="contact_no_nameday">Nessun onomastico per il nome %s</string>
    <string name="edit">Modifica</string>
    <string name="Add_birthday">Aggiungi compleanno</string>
    <string name="search">Cerca</string>
    <string name="and">e</string>
    <string name="Greek">Greco</string>
    <string name="Italian">Italiano</string>
    <string name="Czech">Ceco</string>
    <string name="Slovak">Slovacco</string>
    <string name="Russian">Russo</string>
    <string name="Latvian_Traditional">Lituano</string>
    <string name="Hungarian">Ungherese</string>
    <string name="nameday_language_title">Calendario onomastico</string>
    <string name="no_sound">Silenzioso</string>
    <string name="label_widget_namedays">"Memento - Onomastici"</string>
    <string name="share">Condividi</string>
    <string name="support_app">Supporta l\'app</string>
    <string name="fb_go_to_fanpage">Vai alla pagina Facebook</string>
    <string name="rate_rate_ask">Quanto valuteresti l\'app?</string>
    <string name="rate_1_stars">"Pessima"</string>
    <string name="rate_2_stars">"Non mi piace"</string>
    <string name="rate_3_stars">"Va bene"</string>
    <string name="rate_4_stars">"Mi è piaciuta"</string>
    <string name="rate_5_stars">"L'adoro!"</string>
    <string name="rate">Valutazione</string>
    <string name="message">Messaggio</string>
    <string name="contact_turns_age">%1$s compie %2$d anni</string>
    <string name="no_results_found">Nessun risultato trovato</string>
    <string name="contact_celebration_count">%d contatti celebrano oggi</string>
    <string name="todays_namedays">Onomastici di oggi</string>
    <string name="celebrates_one_namedays">"Onomastico di oggi"</string>
    <string name="celebrates_many_namedays">"Onomastici di oggi"</string>
    <string name="action_via">%s con…</string>
    <string name="go_to_fb_short">Mi piace</string>
    <string name="rate_app">Valuta l\'app</string>
    <string name="like_page">Mi piace su Facebook</string>
    <string name="days_namedays">Onomastici del %1$s</string>
    <string name="get_days">Installa %1$s da %2$s</string>
    <string name="hide_names_hints">Puoi nascondere I nomi che non vuoi visualizzare nella app premendoli a lungo.</string>
    <string name="got_it">OK, ho capito</string>
    <string name="namedays_contacts_only_on">Verranno visualizzati gli onomastici solo per i contatti memorizzati</string>
    <string name="namedays_contacts_only_off">Verranno visualizzati tutti gli onomastici dell\'anno</string>
    <string name="namedays_contacts_only">Onomastici solo per i contatti</string>
    <string name="support_message">Mi auguro che tu sia soddisfatto della app e che ti sia utile. Ecco alcuni modi per supportarmi:</string>
    <string name="translate">Tradurre l\'applicazione</string>
    <string name="translate_the_app_title">Per tradurre l\'applicazione</string>
    <string name="translate_the_app_message">Visita l\'url seguente dal browser del tuo computer</string>
    <!-- Neutral button on a dialog, saying that pressing the button will copy to clipboard the url to translate the app -->
    <string name="copy_link">Copia il link</string>
    <string name="copied_to_clipboard">Link copiato negli appunti</string>
    <string name="select_donation_amount">Scegli l\'importo che vuoi donare</string>
    <string name="View_contact">Visualizza il contatto</string>
    <string name="no_birthday_set">Compleanno non impostato</string>
    <string name="No_contacts_with_events_found_Tap_the_plus_to_add_some">"Non ho trovato contatti con eventi speciali.\nTocca il '+' per aggiungerne"</string>
    <string name="No_contacts_with_events_found">"Non ho trovato contatti con eventi speciali"</string>
    <string name="add_birthday">Aggiungi compleanno</string>
    <string name="Birthday_date">Compleanno</string>
    <string name="Contact_name">Nome contatto</string>
    <string name="Themes">Temi</string>
    <string name="Romanian">Romeno</string>
    <string name="Configure_widget">Configura il widget</string>
    <string name="Done">Fatto</string>
    <string name="Transparency">Trasparenza</string>
    <string name="Use_dark_theme">Tema scuro?</string>
    <string name="Contact_names">Nomi dei contatti</string>
    <string name="Bank_holiday">Festività</string>
    <string name="Bank_holidays">Festività</string>
    <string name="GoogleP_community">Comunità Google+</string>
    <string name="Display_Bankholidays">Visualizza Festività</string>
    <string name="Bankholidays_Country">Nazione</string>
    <string name="Bankholidays_are_currently_supported_only_for_Greek">Al momento sono supportate solo le Festività greche</string>
    <string name="Clear">Pulisci</string>
    <string name="Search_for_contacts">Ricerca dei contatti</string>
    <string name="Search_for_contacts_or_namedays">Ricerca dei contatti o onomastici</string>
    <string name="Memento_requires_your_permission_to_read_your_contacts_in_order_to_display_when_they_celebrate">L\'app necessita il tuo permesso di leggere i contatti per poter visualizzare le date.</string>
    <string name="Fact_Some_people_give_free_cake_to_those_who_wish_them_Happy_Birthday._Use_Memento_to_keep_track_of_potential_cake_givers">Alcune persone offrono una torta a chi gli augura Buon Compleanno. Usa questa app per tenere traccia dei potenziali donatori di torta.</string>
    <string name="Grant_permission">Concedi il permesso</string>
    <string name="Use_all_parts_of_names">Usa sia il nome che il cognome</string>
    <string name="The_app_will_lookup_namedays_for_all_names_in_a_contact_including_surname">"L'app cercherà gli onomastici per il nome completo dei contatti (cognome incluso)"</string>
    <string name="The_app_will_lookup_namedays_only_in_contacts_given_names_excluding_surname">"L\'app cercherà gli onomastici per il solo nome dei contatti (cognome escluso)"</string>
    <string name="eventlabel_on_dateLabel">%1$s il %2$s</string>
    <string name="Anniversary">Anniversario</string>
    <string name="Other">Altro</string>
    <string name="Custom">Personalizzato</string>
    <string name="Add_event">Aggiungi evento</string>
    <string name="Change_photo">Cambia la foto</string>
    <string name="Remove_photo">Rimuovi la foto</string>
    <string name="Take_new_photo">Scatta una nuova foto</string>
    <string name="Pick_existing_photo">Scegli una foto esistente</string>
    <string name="Discard_changes">Annulli le modifiche?</string>
    <string name="No_events_on_this_date">Nessun evento in questa data</string>
    <string name="Invite_friend">Invita un amico</string>
    <string name="Facebook_Log_In">Accedi a Facebook</string>
    <string name="Your_Friends_will_be_here_shortly_smiley">I tuoi Amici saranno qui a breve :)</string>
    <string name="An_error_came_up">Si è verificato un errore</string>
    <string name="Try_again_in_a_bit">Riprova tra poco</string>
    <string name="Hi_X">Ciao, %s!</string>
    <string name="Import_from_Facebook">Importa da Facebook</string>
    <string name="Friends_update_daily">Aggiornamento Amici giornalmente</string>
    <string name="Memento_on_Facebook">Memento su Facebook</string>
    <string name="log_out">Esci</string>
    <string name="Facebook_profile">Profilo Facebook</string>
    <string name="has_nameday_on">Onomastico il %s</string>
    <string name="has_birthday_on">Compleanno il %s</string>
    <string name="has_birthday_on_age">Compie %1$d anni il %2$s</string>
    <string name="title_add_birthday">Aggiungi compleanno</string>
    <string name="Post_on_Facebook">Apri il diario</string>
    <string name="romanian">Rumeno</string>
</resources>


text:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Leviathan.Testing.TestParsedObject>
	<AField1>1</AField1>
	<AField2>Test1</AField2>
	<AProperty1>2</AProperty1>
	<AProperty2>Test2</AProperty2>
</Leviathan.Testing.TestParsedObject>


text:
import * as React from 'react';

declare namespace F7FabButtons {
  interface Props {
    slot? : string
    id? : string | number
    className? : string
    style? : React.CSSProperties
    position? : string
    color? : string
    colorTheme? : string
    textColor? : string
    bgColor? : string
    borderColor? : string
    rippleColor? : string
    themeDark? : boolean

  }
}
declare class F7FabButtons extends React.Component<F7FabButtons.Props, {}> {

}
export default F7FabButtons;