text:
@class DVTNotificationToken, IDERunnable, IDESchemeBuildableReference, NSArray, NSDictionary, NSMutableArray, NSString;

@interface IDEProfileSchemeAction : IDESchemeAction <DVTXMLUnarchiving>
{
    IDERunnable *_runnable;
    NSMutableArray *_commandLineArgumentEntries;
    NSMutableArray *_environmentVariableEntries;
    id <IDEAnalysisToolService> _analysisToolService;
    BOOL _useCustomWorkingDirectory;
    NSString *_customWorkingDirectory;
    NSString *_resolvedCustomWorkingDirectory;
    BOOL _ignoresPersistentStateOnLaunch;
    BOOL _debugDocumentVersioning;
    BOOL _shouldUseLaunchSchemeArgsEnv;
    NSString *_buildConfiguration;
    NSString *_savedToolIdentifier;
    IDESchemeBuildableReference *_profileBuildableReferenceToUseForMacroExpansion;
    DVTNotificationToken *_buildablesToken;
    BOOL _askForAppToLaunch;
    Class _analysisToolServiceClass;
}

+ (id)keyPathsForValuesAffectingBuildableReferenceToUseForMacroExpansion;
+ (BOOL)automaticallyNotifiesObserversOfAnalysisToolService;
+ (id)keyPathsForValuesAffectingRunnable;
+ (id)keyPathsForValuesAffectingDoesNonActionWork;
+ (id)keyPathsForValuesAffectingSubtitle;
+ (void)initialize;
@property(retain) Class analysisToolServiceClass; // @synthesize analysisToolServiceClass=_analysisToolServiceClass;
@property BOOL askForAppToLaunch; // @synthesize askForAppToLaunch=_askForAppToLaunch;
@property BOOL useCustomWorkingDirectory; // @synthesize useCustomWorkingDirectory=_useCustomWorkingDirectory;
@property(nonatomic) BOOL shouldUseLaunchSchemeArgsEnv; // @synthesize shouldUseLaunchSchemeArgsEnv=_shouldUseLaunchSchemeArgsEnv;
@property(retain, nonatomic) NSString *savedToolIdentifier; // @synthesize savedToolIdentifier=_savedToolIdentifier;
@property BOOL ignoresPersistentStateOnLaunch; // @synthesize ignoresPersistentStateOnLaunch=_ignoresPersistentStateOnLaunch;
@property BOOL debugDocumentVersioning; // @synthesize debugDocumentVersioning=_debugDocumentVersioning;
@property(copy, nonatomic) NSString *customWorkingDirectory; // @synthesize customWorkingDirectory=_customWorkingDirectory;
@property(copy) NSString *buildConfiguration; // @synthesize buildConfiguration=_buildConfiguration;
- (void).cxx_destruct;
- (void)addMacroExpansion:(id)arg1 fromXMLUnarchiver:(id)arg2;
- (void)addEnvironmentVariables:(id)arg1 fromXMLUnarchiver:(id)arg2;
- (void)addCommandLineArguments:(id)arg1 fromXMLUnarchiver:(id)arg2;
- (void)addBuildableProductRunnable:(id)arg1 fromXMLUnarchiver:(id)arg2;
- (void)addPathRunnable:(id)arg1 fromXMLUnarchiver:(id)arg2;
- (void)dvt_encodeRelationshipsWithXMLArchiver:(id)arg1 version:(id)arg2;
- (void)setDebugDocumentVersioningFromUTF8String:(char *)arg1 fromXMLUnarchiver:(id)arg2;
- (void)setIgnoresPersistentStateOnLaunchFromUTF8String:(char *)arg1 fromXMLUnarchiver:(id)arg2;
- (void)setSavedToolIdentifierFromUTF8String:(char *)arg1 fromXMLUnarchiver:(id)arg2;
- (void)setShouldUseLaunchSchemeArgsEnvFromUTF8String:(char *)arg1 fromXMLUnarchiver:(id)arg2;
- (void)setUseCustomWorkingDirectoryFromUTF8String:(char *)arg1 fromXMLUnarchiver:(id)arg2;
- (void)setAskForAppToLaunchFromUTF8String:(char *)arg1 fromXMLUnarchiver:(id)arg2;
- (void)dvt_encodeAttributesWithXMLArchiver:(id)arg1 version:(id)arg2;
- (void)dvt_awakeFromXMLUnarchiver:(id)arg1;
- (id)_expandMacrosInString:(id)arg1;
- (void)setBuildableReferenceToUseForMacroExpansion:(id)arg1;
- (id)buildableReferenceToUseForMacroExpansion;
@property(readonly) NSString *resolvedCustomWorkingDirectory; // @synthesize resolvedCustomWorkingDirectory=_resolvedCustomWorkingDirectory;
@property(readonly) NSDictionary *environmentVariables;
@property(readonly) NSMutableArray *mutableEnvironmentVariableEntries; // @dynamic mutableEnvironmentVariableEntries;
@property(copy) NSArray *environmentVariableEntries; // @dynamic environmentVariableEntries;
- (id)commandLineArgumentsForDevice:(id)arg1;
@property(readonly) NSMutableArray *mutableCommandLineArgumentEntries; // @dynamic mutableCommandLineArgumentEntries;
@property(copy) NSArray *commandLineArgumentEntries; // @dynamic commandLineArgumentEntries;
- (id)_profileOperationWithExecutionEnvironment:(id)arg1 withBuildOperation:(id)arg2 buildParameters:(id)arg3 buildableProductDirectories:(id)arg4 testManager:(id)arg5 overridingTestingSpecifiers:(id)arg6 schemeActionRecord:(id)arg7 environmentVariables:(id)arg8 commandLineArguments:(id)arg9 outError:(id *)arg10 actionCallbackBlock:(CDUnknownBlockType)arg11;
- (id)_testRunnerForTestManager:(id)arg1 overridingTestingSpecifiers:(id)arg2;
- (id)profileOperationForExecutionEnvironment:(id)arg1 withBuildOperation:(id)arg2 buildParameters:(id)arg3 buildableProductDirectories:(id)arg4 schemeActionRecord:(id)arg5 outError:(id *)arg6 actionCallbackBlock:(CDUnknownBlockType)arg7;
- (id)profileOperationWithTestManager:(id)arg1 executionEnvironment:(id)arg2 withBuildOperation:(id)arg3 buildParameters:(id)arg4 buildableProductDirectories:(id)arg5 overridingTestingSpecifiers:(id)arg6 schemeActionRecord:(id)arg7 outError:(id *)arg8 actionCallbackBlock:(CDUnknownBlockType)arg9;
- (id)_filePathsForContainersAndExtensions;
- (void)setSelectedAnalysisToolIdentifier:(id)arg1 forPlatformIdentifier:(id)arg2;
@property(retain) IDERunnable *runnable; // @synthesize runnable=_runnable;
- (void)_updateProfileActionBuildableToUseForMacroExpansion;
- (void)setRunContext:(id)arg1;
- (BOOL)doesNonActionWork;
- (id)subtitle;
- (id)name;
- (void)primitiveInvalidate;
- (void)_commonInit;
- (id)initFromXMLUnarchiver:(id)arg1 archiveVersion:(float)arg2;
- (id)init;

// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;

@end


text:
import * as RDF from 'rdf-js';
import { GraphPointer } from 'clownface';

type Factory<OutQuad extends RDF.Quad = RDF.Quad,
    InQuad extends RDF.Quad = RDF.Quad,
    D extends RDF.DatasetCore<OutQuad, InQuad> = RDF.DatasetCore<OutQuad, InQuad>,
> = RDF.DataFactory<OutQuad, InQuad> & RDF.DatasetCoreFactory<OutQuad, InQuad, D>;

type BlankNodeOf<F extends Factory> = ReturnType<F['blankNode']>;
type NamedNodeOf<F extends Factory> = ReturnType<F['namedNode']>;
type LiteralOf<F extends Factory> = ReturnType<F['literal']>;
type DatasetOf<F extends Factory> = ReturnType<F['dataset']>;

declare namespace ValidationReport {
    interface Options<F extends Factory> {
        factory: F;
    }

    interface ValidationResult<F extends Factory = Factory> {
        term: BlankNodeOf<F> | NamedNodeOf<F>;
        dataset: DatasetOf<F>;
        cf: GraphPointer<BlankNodeOf<F> | NamedNodeOf<F>, DatasetOf<F>>;
        readonly message: Array<BlankNodeOf<F> | NamedNodeOf<F> | LiteralOf<F>>;
        readonly path: BlankNodeOf<F> | NamedNodeOf<F> | null;
        readonly focusNode: BlankNodeOf<F> | NamedNodeOf<F> | null;
        readonly severity: NamedNodeOf<F> | null;
        readonly sourceConstraintComponent: BlankNodeOf<F> | NamedNodeOf<F> | null;
        readonly sourceShape: BlankNodeOf<F> | NamedNodeOf<F> | null;
    }
}

declare class ValidationReport<F extends Factory = Factory> {
    constructor(resultQuads: RDF.Quad[], options: ValidationReport.Options<F>);
    term: BlankNodeOf<F> | NamedNodeOf<F>;
    dataset: DatasetOf<F>;
    conforms: boolean;
    results: Array<ValidationReport.ValidationResult<F>>;
}

export = ValidationReport;

redpajama_set_name: RedPajamaGithub


text:
#include <windows.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <io.h>

#define CMD_SIZE 500

/* This file creates the getbuildinfo.o object, by first
   invoking subwcrev.exe (if found), and then invoking cl.exe.
   As a side effect, it might generate PCBuild\getbuildinfo2.c
   also. If this isn't a subversion checkout, or subwcrev isn't
   found, it compiles ..\\Modules\\getbuildinfo.c instead.

   Currently, subwcrev.exe is found from the registry entries
   of TortoiseSVN.

   No attempt is made to place getbuildinfo.o into the proper
   binary directory. This isn't necessary, as this tool is
   invoked as a pre-link step for pythoncore, so that overwrites
   any previous getbuildinfo.o.

   However, if a second argument is provided, this will be used
   as a temporary directory where any getbuildinfo2.c and
   getbuildinfo.o files are put.  This is useful if multiple
   configurations are being built in parallel, to avoid them
   trampling each other's files.

*/

int make_buildinfo2(const char *tmppath)
{
    struct _stat st;
    HKEY hTortoise;
    char command[CMD_SIZE+1];
    DWORD type, size;
    if (_stat(".svn", &st) < 0)
        return 0;
    /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */
    if (_stat("no_subwcrev", &st) == 0)
        return 0;
    if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS &&
        RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS)
        /* Tortoise not installed */
        return 0;
    command[0] = '"';  /* quote the path to the executable */
    size = sizeof(command) - 1;
    if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS ||
        type != REG_SZ)
        /* Registry corrupted */
        return 0;
    strcat_s(command, CMD_SIZE, "bin\\subwcrev.exe");
    if (_stat(command+1, &st) < 0)
        /* subwcrev.exe not part of the release */
        return 0;
    strcat_s(command, CMD_SIZE, "\" .. ..\\Modules\\getbuildinfo.c \"");
    strcat_s(command, CMD_SIZE, tmppath); /* quoted tmppath */
    strcat_s(command, CMD_SIZE, "getbuildinfo2.c\"");
    puts(command); fflush(stdout);
    if (system(command) < 0)
        return 0;
    return 1;
}

const char DELIMS[] = { " \n" };

int get_mercurial_info(char * hgbranch, char * hgtag, char * hgrev, int size)
{
    int result = 0;
    char filename[CMD_SIZE];
    char cmdline[CMD_SIZE];

    strcpy_s(filename, CMD_SIZE, "tmpXXXXXX");
    if (_mktemp_s(filename, CMD_SIZE) == 0) {
        int rc;

        strcpy_s(cmdline, CMD_SIZE, "hg id -bit > ");
        strcat_s(cmdline, CMD_SIZE, filename);
        rc = system(cmdline);
        if (rc == 0) {
            FILE * fp;

            if (fopen_s(&fp, filename, "r") == 0) {
                char * cp = fgets(cmdline, CMD_SIZE, fp);

                if (cp) {
                    char * context = NULL;
                    char * tp = strtok_s(cp, DELIMS, &context);
                    if (tp) {
                        strcpy_s(hgrev, size, tp);
                        tp = strtok_s(NULL, DELIMS, &context);
                        if (tp) {
                            strcpy_s(hgbranch, size, tp);
                            tp = strtok_s(NULL, DELIMS, &context);
                            if (tp) {
                                strcpy_s(hgtag, size, tp);
                                result = 1;
                            }
                        }
                    }
                }
                fclose(fp);
            }
        }
        _unlink(filename);
    }
    return result;
}

int main(int argc, char*argv[])
{
    char command[CMD_SIZE] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL ";
    char tmppath[CMD_SIZE] = "";
    int do_unlink, result;
    char *tmpdir = NULL;
    if (argc <= 2 || argc > 3) {
        fprintf(stderr, "make_buildinfo $(ConfigurationName) [tmpdir]\n");
        return EXIT_FAILURE;
    }
    if (strcmp(argv[1], "Release") == 0) {
        strcat_s(command, CMD_SIZE, "-MD ");
    }
    else if (strcmp(argv[1], "Debug") == 0) {
        strcat_s(command, CMD_SIZE, "-D_DEBUG -MDd ");
    }
    else if (strcmp(argv[1], "ReleaseItanium") == 0) {
        strcat_s(command, CMD_SIZE, "-MD /USECL:MS_ITANIUM ");
    }
    else if (strcmp(argv[1], "ReleaseAMD64") == 0) {
        strcat_s(command, CMD_SIZE, "-MD ");
        strcat_s(command, CMD_SIZE, "-MD /USECL:MS_OPTERON ");
    }
    else {
        fprintf(stderr, "unsupported configuration %s\n", argv[1]);
        return EXIT_FAILURE;
    }
    if (argc > 2) {
        tmpdir = argv[2];
        strcat_s(tmppath, _countof(tmppath), tmpdir);
        /* Hack fix for bad command line:  If the command is issued like this:
         * $(SolutionDir)make_buildinfo.exe" Debug "$(IntDir)"
         * we will get a trailing quote because IntDir ends with a backslash that then
         * escapes the final ".  To simplify the life for developers, catch that problem
         * here by cutting it off.
         * The proper command line, btw is:
         * $(SolutionDir)make_buildinfo.exe" Debug "$(IntDir)\"
         * Hooray for command line parsing on windows.
         */
        if (strlen(tmppath) > 0 && tmppath[strlen(tmppath)-1] == '"')
            tmppath[strlen(tmppath)-1] = '\0';
        strcat_s(tmppath, _countof(tmppath), "\\");
    }

    if ((do_unlink = make_buildinfo2(tmppath))) {
        strcat_s(command, CMD_SIZE, "\"");
        strcat_s(command, CMD_SIZE, tmppath);
        strcat_s(command, CMD_SIZE, "getbuildinfo2.c\" -DSUBWCREV ");
    }
    else {
        char hgtag[CMD_SIZE];
        char hgbranch[CMD_SIZE];
        char hgrev[CMD_SIZE];

        if (get_mercurial_info(hgbranch, hgtag, hgrev, CMD_SIZE)) {
            strcat_s(command, CMD_SIZE, "-DHGBRANCH=\\\"");
            strcat_s(command, CMD_SIZE, hgbranch);
            strcat_s(command, CMD_SIZE, "\\\"");

            strcat_s(command, CMD_SIZE, " -DHGTAG=\\\"");
            strcat_s(command, CMD_SIZE, hgtag);
            strcat_s(command, CMD_SIZE, "\\\"");

            strcat_s(command, CMD_SIZE, " -DHGVERSION=\\\"");
            strcat_s(command, CMD_SIZE, hgrev);
            strcat_s(command, CMD_SIZE, "\\\" ");
        }
        strcat_s(command, CMD_SIZE, "..\\Modules\\getbuildinfo.c");
    }
    strcat_s(command, CMD_SIZE, " -Fo\"");
    strcat_s(command, CMD_SIZE, tmppath);
    strcat_s(command, CMD_SIZE, "getbuildinfo.o\" -I..\\Include -I..\\PC");
    puts(command); fflush(stdout);
    result = system(command);
    if (do_unlink) {
        command[0] = '\0';
        strcat_s(command, CMD_SIZE, "\"");
        strcat_s(command, CMD_SIZE, tmppath);
        strcat_s(command, CMD_SIZE, "getbuildinfo2.c\"");
        _unlink(command);
    }
    if (result < 0)
        return EXIT_FAILURE;
    return 0;
}


text:
from ._base import BaseHandler

from synapse.streams.config import PaginationConfig
from synapse.api.constants import Membership, EventTypes

from twisted.internet import defer

import collections
import logging

logger = logging.getLogger(__name__)

SyncConfig = collections.namedtuple("SyncConfig", [
    "user",
    "filter",
])

class TimelineBatch(collections.namedtuple("TimelineBatch", [
    "prev_batch",
    "events",
    "limited",
])):
    __slots__ = []

    def __nonzero__(self):
        """Make the result appear empty if there are no updates. This is used
        to tell if room needs to be part of the sync result.
        """
        return bool(self.events)

class JoinedSyncResult(collections.namedtuple("JoinedSyncResult", [
    "room_id",           # str
    "timeline",          # TimelineBatch
    "state",             # dict[(str, str), FrozenEvent]
    "ephemeral",
    "account_data",
])):
    __slots__ = []

    def __nonzero__(self):
        """Make the result appear empty if there are no updates. This is used
        to tell if room needs to be part of the sync result.
        """
        return bool(
            self.timeline
            or self.state
            or self.ephemeral
            or self.account_data
        )

class ArchivedSyncResult(collections.namedtuple("JoinedSyncResult", [
    "room_id",            # str
    "timeline",           # TimelineBatch
    "state",              # dict[(str, str), FrozenEvent]
    "account_data",
])):
    __slots__ = []

    def __nonzero__(self):
        """Make the result appear empty if there are no updates. This is used
        to tell if room needs to be part of the sync result.
        """
        return bool(
            self.timeline
            or self.state
            or self.account_data
        )

class InvitedSyncResult(collections.namedtuple("InvitedSyncResult", [
    "room_id",   # str
    "invite",    # FrozenEvent: the invite event
])):
    __slots__ = []

    def __nonzero__(self):
        """Invited rooms should always be reported to the client"""
        return True

class SyncResult(collections.namedtuple("SyncResult", [
    "next_batch",  # Token for the next sync
    "presence",  # List of presence events for the user.
    "joined",  # JoinedSyncResult for each joined room.
    "invited",  # InvitedSyncResult for each invited room.
    "archived",  # ArchivedSyncResult for each archived room.
])):
    __slots__ = []

    def __nonzero__(self):
        """Make the result appear empty if there are no updates. This is used
        to tell if the notifier needs to wait for more events when polling for
        events.
        """
        return bool(
            self.presence or self.joined or self.invited
        )

class SyncHandler(BaseHandler):

    def __init__(self, hs):
        super(SyncHandler, self).__init__(hs)
        self.event_sources = hs.get_event_sources()
        self.clock = hs.get_clock()

    @defer.inlineCallbacks
    def wait_for_sync_for_user(self, sync_config, since_token=None, timeout=0,
                               full_state=False):
        """Get the sync for a client if we have new data for it now. Otherwise
        wait for new data to arrive on the server. If the timeout expires, then
        return an empty sync result.
        Returns:
            A Deferred SyncResult.
        """

        if timeout == 0 or since_token is None or full_state:
            # we are going to return immediately, so don't bother calling
            # notifier.wait_for_events.
            result = yield self.current_sync_for_user(sync_config, since_token,
                                                      full_state=full_state)
            defer.returnValue(result)
        else:
            def current_sync_callback(before_token, after_token):
                return self.current_sync_for_user(sync_config, since_token)

            result = yield self.notifier.wait_for_events(
                sync_config.user, timeout, current_sync_callback,
                from_token=since_token
            )
            defer.returnValue(result)

    def current_sync_for_user(self, sync_config, since_token=None,
                              full_state=False):
        """Get the sync for client needed to match what the server has now.
        Returns:
            A Deferred SyncResult.
        """
        if since_token is None or full_state:
            return self.full_state_sync(sync_config, since_token)
        else:
            return self.incremental_sync_with_gap(sync_config, since_token)

    @defer.inlineCallbacks
    def full_state_sync(self, sync_config, timeline_since_token):
        """Get a sync for a client which is starting without any state.

        If a 'message_since_token' is given, only timeline events which have
        happened since that token will be returned.

        Returns:
            A Deferred SyncResult.
        """
        now_token = yield self.event_sources.get_current_token()

        now_token, ephemeral_by_room = yield self.ephemeral_by_room(
            sync_config, now_token
        )

        presence_stream = self.event_sources.sources["presence"]
        # TODO (mjark): This looks wrong, shouldn't we be getting the presence
        # UP to the present rather than after the present?
        pagination_config = PaginationConfig(from_token=now_token)
        presence, _ = yield presence_stream.get_pagination_rows(
            user=sync_config.user,
            pagination_config=pagination_config.get_source_config("presence"),
            key=None
        )
        room_list = yield self.store.get_rooms_for_user_where_membership_is(
            user_id=sync_config.user.to_string(),
            membership_list=(
                Membership.INVITE,
                Membership.JOIN,
                Membership.LEAVE,
                Membership.BAN
            )
        )

        tags_by_room = yield self.store.get_tags_for_user(
            sync_config.user.to_string()
        )

        joined = []
        invited = []
        archived = []
        for event in room_list:
            if event.membership == Membership.JOIN:
                room_sync = yield self.full_state_sync_for_joined_room(
                    room_id=event.room_id,
                    sync_config=sync_config,
                    now_token=now_token,
                    timeline_since_token=timeline_since_token,
                    ephemeral_by_room=ephemeral_by_room,
                    tags_by_room=tags_by_room,
                )
                joined.append(room_sync)
            elif event.membership == Membership.INVITE:
                invite = yield self.store.get_event(event.event_id)
                invited.append(InvitedSyncResult(
                    room_id=event.room_id,
                    invite=invite,
                ))
            elif event.membership in (Membership.LEAVE, Membership.BAN):
                leave_token = now_token.copy_and_replace(
                    "room_key", "s%d" % (event.stream_ordering,)
                )
                room_sync = yield self.full_state_sync_for_archived_room(
                    sync_config=sync_config,
                    room_id=event.room_id,
                    leave_event_id=event.event_id,
                    leave_token=leave_token,
                    timeline_since_token=timeline_since_token,
                    tags_by_room=tags_by_room,
                )
                archived.append(room_sync)

        defer.returnValue(SyncResult(
            presence=presence,
            joined=joined,
            invited=invited,
            archived=archived,
            next_batch=now_token,
        ))

    @defer.inlineCallbacks
    def full_state_sync_for_joined_room(self, room_id, sync_config,
                                        now_token, timeline_since_token,
                                        ephemeral_by_room, tags_by_room):
        """Sync a room for a client which is starting without any state
        Returns:
            A Deferred JoinedSyncResult.
        """

        batch = yield self.load_filtered_recents(
            room_id, sync_config, now_token, since_token=timeline_since_token
        )

        current_state = yield self.get_state_at(room_id, now_token)

        defer.returnValue(JoinedSyncResult(
            room_id=room_id,
            timeline=batch,
            state=current_state,
            ephemeral=ephemeral_by_room.get(room_id, []),
            account_data=self.account_data_for_room(
                room_id, tags_by_room
            ),
        ))

    def account_data_for_room(self, room_id, tags_by_room):
        account_data = []
        tags = tags_by_room.get(room_id)
        if tags is not None:
            account_data.append({
                "type": "m.tag",
                "content": {"tags": tags},
            })
        return account_data

    @defer.inlineCallbacks
    def ephemeral_by_room(self, sync_config, now_token, since_token=None):
        """Get the ephemeral events for each room the user is in
        Args:
            sync_config (SyncConfig): The flags, filters and user for the sync.
            now_token (StreamToken): Where the server is currently up to.
            since_token (StreamToken): Where the server was when the client
                last synced.
        Returns:
            A tuple of the now StreamToken, updated to reflect the which typing
            events are included, and a dict mapping from room_id to a list of
            typing events for that room.
        """

        typing_key = since_token.typing_key if since_token else "0"

        rooms = yield self.store.get_rooms_for_user(sync_config.user.to_string())
        room_ids = [room.room_id for room in rooms]

        typing_source = self.event_sources.sources["typing"]
        typing, typing_key = yield typing_source.get_new_events(
            user=sync_config.user,
            from_key=typing_key,
            limit=sync_config.filter.ephemeral_limit(),
            room_ids=room_ids,
            is_guest=False,
        )
        now_token = now_token.copy_and_replace("typing_key", typing_key)

        ephemeral_by_room = {}

        for event in typing:
            # we want to exclude the room_id from the event, but modifying the
            # result returned by the event source is poor form (it might cache
            # the object)
            room_id = event["room_id"]
            event_copy = {k: v for (k, v) in event.iteritems()
                          if k != "room_id"}
            ephemeral_by_room.setdefault(room_id, []).append(event_copy)

        receipt_key = since_token.receipt_key if since_token else "0"

        receipt_source = self.event_sources.sources["receipt"]
        receipts, receipt_key = yield receipt_source.get_new_events(
            user=sync_config.user,
            from_key=receipt_key,
            limit=sync_config.filter.ephemeral_limit(),
            room_ids=room_ids,
            # /sync doesn't support guest access, they can't get to this point in code
            is_guest=False,
        )
        now_token = now_token.copy_and_replace("receipt_key", receipt_key)

        for event in receipts:
            room_id = event["room_id"]
            # exclude room id, as above
            event_copy = {k: v for (k, v) in event.iteritems()
                          if k != "room_id"}
            ephemeral_by_room.setdefault(room_id, []).append(event_copy)

        defer.returnValue((now_token, ephemeral_by_room))

    @defer.inlineCallbacks
    def full_state_sync_for_archived_room(self, room_id, sync_config,
                                          leave_event_id, leave_token,
                                          timeline_since_token, tags_by_room):
        """Sync a room for a client which is starting without any state
        Returns:
            A Deferred JoinedSyncResult.
        """

        batch = yield self.load_filtered_recents(
            room_id, sync_config, leave_token, since_token=timeline_since_token
        )

        leave_state = yield self.store.get_state_for_event(leave_event_id)

        defer.returnValue(ArchivedSyncResult(
            room_id=room_id,
            timeline=batch,
            state=leave_state,
            account_data=self.account_data_for_room(
                room_id, tags_by_room
            ),
        ))

    @defer.inlineCallbacks
    def incremental_sync_with_gap(self, sync_config, since_token):
        """ Get the incremental delta needed to bring the client up to
        date with the server.
        Returns:
            A Deferred SyncResult.
        """
        now_token = yield self.event_sources.get_current_token()

        rooms = yield self.store.get_rooms_for_user(sync_config.user.to_string())
        room_ids = [room.room_id for room in rooms]

        presence_source = self.event_sources.sources["presence"]
        presence, presence_key = yield presence_source.get_new_events(
            user=sync_config.user,
            from_key=since_token.presence_key,
            limit=sync_config.filter.presence_limit(),
            room_ids=room_ids,
            # /sync doesn't support guest access, they can't get to this point in code
            is_guest=False,
        )
        now_token = now_token.copy_and_replace("presence_key", presence_key)

        now_token, ephemeral_by_room = yield self.ephemeral_by_room(
            sync_config, now_token, since_token
        )

        rm_handler = self.hs.get_handlers().room_member_handler
        app_service = yield self.store.get_app_service_by_user_id(
            sync_config.user.to_string()
        )
        if app_service:
            rooms = yield self.store.get_app_service_rooms(app_service)
            joined_room_ids = set(r.room_id for r in rooms)
        else:
            joined_room_ids = yield rm_handler.get_joined_rooms_for_user(
                sync_config.user
            )

        timeline_limit = sync_config.filter.timeline_limit()

        room_events, _ = yield self.store.get_room_events_stream(
            sync_config.user.to_string(),
            from_key=since_token.room_key,
            to_key=now_token.room_key,
            limit=timeline_limit + 1,
        )

        tags_by_room = yield self.store.get_updated_tags(
            sync_config.user.to_string(),
            since_token.account_data_key,
        )

        joined = []
        archived = []
        if len(room_events) <= timeline_limit:
            # There is no gap in any of the rooms. Therefore we can just
            # partition the new events by room and return them.
            logger.debug("Got %i events for incremental sync - not limited",
                         len(room_events))

            invite_events = []
            leave_events = []
            events_by_room_id = {}
            for event in room_events:
                events_by_room_id.setdefault(event.room_id, []).append(event)
                if event.room_id not in joined_room_ids:
                    if (event.type == EventTypes.Member
                            and event.state_key == sync_config.user.to_string()):
                        if event.membership == Membership.INVITE:
                            invite_events.append(event)
                        elif event.membership in (Membership.LEAVE, Membership.BAN):
                            leave_events.append(event)

            for room_id in joined_room_ids:
                recents = events_by_room_id.get(room_id, [])
                logger.debug("Events for room %s: %r", room_id, recents)
                state = {
                    (event.type, event.state_key): event
                    for event in recents if event.is_state()}
                limited = False

                if recents:
                    prev_batch = now_token.copy_and_replace(
                        "room_key", recents[0].internal_metadata.before
                    )
                else:
                    prev_batch = now_token

                just_joined = yield self.check_joined_room(sync_config, state)
                if just_joined:
                    logger.debug("User has just joined %s: needs full state",
                                 room_id)
                    state = yield self.get_state_at(room_id, now_token)
                    # the timeline is inherently limited if we've just joined
                    limited = True

                room_sync = JoinedSyncResult(
                    room_id=room_id,
                    timeline=TimelineBatch(
                        events=recents,
                        prev_batch=prev_batch,
                        limited=limited,
                    ),
                    state=state,
                    ephemeral=ephemeral_by_room.get(room_id, []),
                    account_data=self.account_data_for_room(
                        room_id, tags_by_room
                    ),
                )
                logger.debug("Result for room %s: %r", room_id, room_sync)

                if room_sync:
                    joined.append(room_sync)

        else:
            logger.debug("Got %i events for incremental sync - hit limit",
                         len(room_events))

            invite_events = yield self.store.get_invites_for_user(
                sync_config.user.to_string()
            )

            leave_events = yield self.store.get_leave_and_ban_events_for_user(
                sync_config.user.to_string()
            )

            for room_id in joined_room_ids:
                room_sync = yield self.incremental_sync_with_gap_for_room(
                    room_id, sync_config, since_token, now_token,
                    ephemeral_by_room, tags_by_room
                )
                if room_sync:
                    joined.append(room_sync)

        for leave_event in leave_events:
            room_sync = yield self.incremental_sync_for_archived_room(
                sync_config, leave_event, since_token, tags_by_room
            )
            archived.append(room_sync)

        invited = [
            InvitedSyncResult(room_id=event.room_id, invite=event)
            for event in invite_events
        ]

        defer.returnValue(SyncResult(
            presence=presence,
            joined=joined,
            invited=invited,
            archived=archived,
            next_batch=now_token,
        ))

    @defer.inlineCallbacks
    def load_filtered_recents(self, room_id, sync_config, now_token,
                              since_token=None):
        """
        :returns a Deferred TimelineBatch
        """
        limited = True
        recents = []
        filtering_factor = 2
        timeline_limit = sync_config.filter.timeline_limit()
        load_limit = max(timeline_limit * filtering_factor, 100)
        max_repeat = 3  # Only try a few times per room, otherwise
        room_key = now_token.room_key
        end_key = room_key

        while limited and len(recents) < timeline_limit and max_repeat:
            events, keys = yield self.store.get_recent_events_for_room(
                room_id,
                limit=load_limit + 1,
                from_token=since_token.room_key if since_token else None,
                end_token=end_key,
            )
            (room_key, _) = keys
            end_key = "s" + room_key.split('-')[-1]
            loaded_recents = sync_config.filter.filter_room_timeline(events)
            loaded_recents = yield self._filter_events_for_client(
                sync_config.user.to_string(), loaded_recents,
            )
            loaded_recents.extend(recents)
            recents = loaded_recents
            if len(events) <= load_limit:
                limited = False
            max_repeat -= 1

        if len(recents) > timeline_limit:
            limited = True
            recents = recents[-timeline_limit:]
            room_key = recents[0].internal_metadata.before

        prev_batch_token = now_token.copy_and_replace(
            "room_key", room_key
        )

        defer.returnValue(TimelineBatch(
            events=recents, prev_batch=prev_batch_token, limited=limited
        ))

    @defer.inlineCallbacks
    def incremental_sync_with_gap_for_room(self, room_id, sync_config,
                                           since_token, now_token,
                                           ephemeral_by_room, tags_by_room):
        """ Get the incremental delta needed to bring the client up to date for
        the room. Gives the client the most recent events and the changes to
        state.
        Returns:
            A Deferred JoinedSyncResult
        """
        logger.debug("Doing incremental sync for room %s between %s and %s",
                     room_id, since_token, now_token)

        # TODO(mjark): Check for redactions we might have missed.

        batch = yield self.load_filtered_recents(
            room_id, sync_config, now_token, since_token,
        )

        logging.debug("Recents %r", batch)

        current_state = yield self.get_state_at(room_id, now_token)

        state_at_previous_sync = yield self.get_state_at(
            room_id, stream_position=since_token
        )

        state = yield self.compute_state_delta(
            since_token=since_token,
            previous_state=state_at_previous_sync,
            current_state=current_state,
        )

        just_joined = yield self.check_joined_room(sync_config, state)
        if just_joined:
            state = yield self.get_state_at(room_id, now_token)

        room_sync = JoinedSyncResult(
            room_id=room_id,
            timeline=batch,
            state=state,
            ephemeral=ephemeral_by_room.get(room_id, []),
            account_data=self.account_data_for_room(
                room_id, tags_by_room
            ),
        )

        logging.debug("Room sync: %r", room_sync)

        defer.returnValue(room_sync)

    @defer.inlineCallbacks
    def incremental_sync_for_archived_room(self, sync_config, leave_event,
                                           since_token, tags_by_room):
        """ Get the incremental delta needed to bring the client up to date for
        the archived room.
        Returns:
            A Deferred ArchivedSyncResult
        """

        stream_token = yield self.store.get_stream_token_for_event(
            leave_event.event_id
        )

        leave_token = since_token.copy_and_replace("room_key", stream_token)

        batch = yield self.load_filtered_recents(
            leave_event.room_id, sync_config, leave_token, since_token,
        )

        logging.debug("Recents %r", batch)

        state_events_at_leave = yield self.store.get_state_for_event(
            leave_event.event_id
        )

        state_at_previous_sync = yield self.get_state_at(
            leave_event.room_id, stream_position=since_token
        )

        state_events_delta = yield self.compute_state_delta(
            since_token=since_token,
            previous_state=state_at_previous_sync,
            current_state=state_events_at_leave,
        )

        room_sync = ArchivedSyncResult(
            room_id=leave_event.room_id,
            timeline=batch,
            state=state_events_delta,
            account_data=self.account_data_for_room(
                leave_event.room_id, tags_by_room
            ),
        )

        logging.debug("Room sync: %r", room_sync)

        defer.returnValue(room_sync)

    @defer.inlineCallbacks
    def get_state_after_event(self, event):
        """
        Get the room state after the given event

        :param synapse.events.EventBase event: event of interest
        :return: A Deferred map from ((type, state_key)->Event)
        """
        state = yield self.store.get_state_for_event(event.event_id)
        if event.is_state():
            state = state.copy()
            state[(event.type, event.state_key)] = event
        defer.returnValue(state)

    @defer.inlineCallbacks
    def get_state_at(self, room_id, stream_position):
        """ Get the room state at a particular stream position
        :param str room_id: room for which to get state
        :param StreamToken stream_position: point at which to get state
        :returns: A Deferred map from ((type, state_key)->Event)
        """
        last_events, token = yield self.store.get_recent_events_for_room(
            room_id, end_token=stream_position.room_key, limit=1,
        )

        if last_events:
            last_event = last_events[-1]
            state = yield self.get_state_after_event(last_event)

        else:
            # no events in this room - so presumably no state
            state = {}
        defer.returnValue(state)

    def compute_state_delta(self, since_token, previous_state, current_state):
        """ Works out the differnce in state between the current state and the
        state the client got when it last performed a sync.

        :param str since_token: the point we are comparing against
        :param dict[(str,str), synapse.events.FrozenEvent] previous_state: the
            state to compare to
        :param dict[(str,str), synapse.events.FrozenEvent] current_state: the
            new state

        :returns A new event dictionary
        """
        # TODO(mjark) Check if the state events were received by the server
        # after the previous sync, since we need to include those state
        # updates even if they occured logically before the previous event.
        # TODO(mjark) Check for new redactions in the state events.

        state_delta = {}
        for key, event in current_state.iteritems():
            if (key not in previous_state or
                    previous_state[key].event_id != event.event_id):
                state_delta[key] = event
        return state_delta

    def check_joined_room(self, sync_config, state_delta):
        """
        Check if the user has just joined the given room (so should
        be given the full state)

        :param sync_config:
        :param dict[(str,str), synapse.events.FrozenEvent] state_delta: the
           difference in state since the last sync

        :returns A deferred Tuple (state_delta, limited)
        """
        join_event = state_delta.get((
            EventTypes.Member, sync_config.user.to_string()), None)
        if join_event is not None:
            if join_event.content["membership"] == Membership.JOIN:
                return True
        return False


text:
rstudio CHANGELOG
=================

0.1.0
-----
- Initial release of rstudio

0.2.0
-----
- Added [Shiny Server](http://www.rstudio.com/shiny/server/) support
- Added tentative support for Debian (Joe Stump)
- Updated the APT installation to use the official APT repositories for Ubuntu and Debian
- Updated the Nginx configuration to support serving both RStudio and Shiny from the same server
- Now depends on the [r](https://github.com/stevendanna/cookbook-r/) cookbook.
- Fixed support for `node['rstudio']['cran']['packages']` using `r_package` LWRP from the `r` cookbook.

0.3.1
-----
- Test fixes and updated dependency versions

0.4.0
-----
- Shiny recipe fix via PR #10


text:
namespace DeJong.Networking.Core
{
    using System;

#if !DEBUG
    [System.Diagnostics.DebuggerStepThrough]
#endif
    internal sealed class PacketReceiveEventArgs : EventArgs
    {
        public readonly int PacketSize;

        public PacketReceiveEventArgs(int size)
        {
            PacketSize = size;
        }
    }
}


text:
<?php
namespace Projek\Slim\Database;

use Projek\Slim\Container;
use Slim\PDO\Database;
use Slim\PDO\Statement\StatementContainer;

abstract class Models implements \Countable
{
    const UPDATED = 'updated_at';
    const CREATED = 'created_at';
    const DELETED = 'deleted_at';

    /**
     * @var Database
     */
    protected $db;

    /**
     * @var string
     */
    protected $table = '';

    /**
     * @var string
     */
    protected $primary = 'id';

    /**
     * @var bool
     */
    protected $timestamps = true;

    /**
     * @var array
     */
    protected $attributes = [];

    /**
     * @var bool
     */
    protected $softDeletes = false;

    /**
     * @var static
     */
    private static $instance;

    /**
     * @param Database|array|null $attributes
     */
    public function __construct($attributes = null)
    {
        if (is_array($attributes)) {
            $this->attributes = $attributes;
        }

        self::$instance = $this;
    }

    /**
     * Show specific or all data
     *
     * @param  mixed $terms
     * @param  array $columns
     *
     * @return Results|false
     */
    public static function show($terms = null, array $columns = [])
    {
        $self = self::newSelf();

        if (!$self->table()) {
            return false;
        }

        $query = $self->select($columns);

        $self->normalizeTerms($query, $terms);

        $model = $self->attributes? static::class : $self;

        return new Results($query, $model);
    }

    /**
     * Create new data
     *
     * @param  array $pairs
     *
     * @return int|false
     */
    public static function create(array $pairs = null)
    {
        $self = self::newSelf($pairs);

        if (!empty($self->attributes) && null === $pairs) {
            $pairs = $self->attributes;
        }

        if (!$self->table()) {
            return false;
        }

        if (empty($pairs)) {
            throw new \LogicException('Could not create empty data');
        }

        if ($self->timestamps) {
            $pairs[self::CREATED] = $pairs[self::UPDATED] = $self->freshDate();
        }

        $query = $self->insert(array_keys($pairs))->values(array_values($pairs));

        if ($result = $query->execute()) {
            $self->attributes[$self->primary()] = $result;

            return $result;
        }

        return false;
    }

    /**
     * Update spesific data
     *
     * @param  array $pairs
     * @param  mixed $terms
     *
     * @return int|false
     */
    public static function patch($pairs = null, $terms = null)
    {
        $self = self::newSelf();

        if (!$self->table()) {
            return false;
        }

        if (!empty($self->attributes) && null === $terms) {
            $terms = $self->attributes;
        }

        if (empty($pairs)) {
            throw new \LogicException('Could not update empty data');
        }

        if ($self->timestamps) {
            $pairs[self::UPDATED] = $self->freshDate();
        }

        $query = $self->update($pairs);

        $self->normalizeTerms($query, $terms);

        if ($result = $query->execute()) {
            $self->attributes = array_merge($self->attributes, $pairs);

            return $result;
        }

        return 0;
    }

    /**
     * Delete specific data
     *
     * @param  mixed $terms
     *
     * @return int|false
     */
    public static function delete($terms = null)
    {
        $self = static::newSelf($terms);

        if (!empty($self->attributes) && null === $terms) {
            $terms = $self->attributes[$self->primary()];
        }

        if (empty($terms)) {
            throw new \LogicException('Could not delete empty data');
        }

        if ($self->softDeletes) {
            return $self->patch([self::DELETED => $self->freshDate()], $terms);
        }

        if (!$self->table()) {
            return false;
        }

        $query = $self->remove();

        $self->normalizeTerms($query, $terms);

        return $query->execute();
    }

    /**
     * Restore soft-deleted data
     *
     * @param  mixed $terms
     *
     * @return int|false
     */
    public static function restore($terms = null)
    {
        $self = self::newSelf();

        if ($self->softDeletes) {
            return $self->patch([self::DELETED => '0000-00-00 00:00:00'], $terms);
        }

        return false;
    }

    /**
     * Count all data
     *
     * @param  callable|array|int  $terms
     *
     * @return int
     */
    public function count($terms = null)
    {
        if (!$this->table()) {
            return 0;
        }

        $query = $this->select(['count(*) count']);

        $this->normalizeTerms($query, $terms);

        return (int) $query->execute()->fetch()['count'];
    }

    /**
     * Get table name
     *
     * @return string
     */
    public function table()
    {
        return $this->table;
    }

    /**
     * Get primary key name
     *
     * @return int
     */
    public function primary()
    {
        return $this->primary;
    }

    /**
     * Get primary key value
     *
     * @return int|null
     */
    public function key()
    {
        return !empty($this->attributes) ? $this->attributes[$this->primary()] : null;
    }

    /**
     * Get qualified primary key name
     *
     * @return string
     */
    public function qualifiedPrimary()
    {
        return $this->table().'.'.$this->primary();
    }

    /**
     * Select data from table
     *
     * @param  array $columns
     *
     * @return \Slim\PDO\Statement\SelectStatement
     */
    protected function select(array $columns = [])
    {
        $columns = !is_array($columns) ? func_get_args() : $columns;

        if (empty($columns)) {
            $columns = ['*'];
        }

        return static::db()->select($columns)->from($this->table());
    }

    /**
     * Select data from table
     *
     * @param  array $pairs
     *
     * @return \Slim\PDO\Statement\InsertStatement
     */
    protected function insert($pairs)
    {
        return static::db()->insert($pairs)->into($this->table());
    }

    /**
     * Select data from table
     *
     * @param  array $pairs
     *
     * @return \Slim\PDO\Statement\UpdateStatement
     */
    protected function update($pairs)
    {
        return static::db()->update(array_filter($pairs))->table($this->table());
    }

    /**
     * Select data from table
     *
     * @return \Slim\PDO\Statement\DeleteStatement
     */
    protected function remove()
    {
        return static::db()->delete($this->table);
    }

    /**
     * @param  string|static $model
     * @param  string|null $first
     * @param  string $operator
     * @param  string|null $second
     * @param  string $joinType
     *
     * @return \Slim\PDO\Statement\SelectStatement
     */
    protected function join($model, $first = null, $operator = '=', $second = null, $joinType = 'INNER')
    {
        list($model, $first, $second) = $this->normalizeJoins($model, $first, $second);

        return $this->select()->join($model->table(), $first, $operator, $second, $joinType);
    }

    /**
     * @param  Models|string $model
     * @param  string $first
     * @param  string $second
     *
     * @return array
     */
    protected function normalizeJoins($model, $first = null, $second = null)
    {
        if (is_string($model)) {
            /** @var  Models $model */
            $model = new $model;
        }

        if (!$model instanceof Models) {
            throw new \InvalidArgumentException(sprintf(
                'Expected 1 parameter of %s to be string or %s instance, %s given.',
                __FUNCTION__,
                static::class,
                gettype($model)
            ));
        }

        if (null === $first) {
            $first = $this->primary();
        }

        if (null === $second) {
            $second = $this->table().'_'.$model->primary();
        }

        return [$model, $this->table().'.'.$first, $model->table().'.'.$second];
    }

    /**
     * Normalize query terms
     *
     * @param  \Slim\PDO\Statement\StatementContainer $stmt
     * @param  Models|array|int|callable $terms
     *
     * @return void
     */
    protected function normalizeTerms(StatementContainer $stmt, $terms)
    {
        if ($terms instanceof Models) {
            $terms = $terms->key();
        }

        if (is_callable($terms)) {
            $terms($stmt);
        } elseif (is_numeric($terms) && !is_float($terms)) {
            $stmt->where($this->primary, '=', (int) $terms);
        } elseif (is_array($terms)) {
            foreach ($terms as $key => $value) {
                $sign = '=';
                if (strpos($key, ' ') !== false) {
                    list($key, $sign) = explode(' ', $key);
                }

                if (is_array($value)) {
                    $stmt->whereIn($key, $value);
                } elseif (null === $value) {
                    $stmt->whereNull($key);
                } else {
                    $stmt->where($key, $sign, $value);
                }
            }
        }
    }

    /**
     * Generate new data
     *
     * @return  string
     */
    protected function freshDate()
    {
        return date('Y-m-d H:i:s');
    }

    /**
     * @return Database
     */
    final protected static function db()
    {
        return Container::instance()->get('db');
    }

    /**
     * @param  null|array $attributes
     *
     * @return static
     */
    final protected static function newSelf($attributes = null)
    {
        return self::$instance ?: new static($attributes);
    }

    public function __get($field)
    {
        return isset($this->attributes[$field]) ? $this->attributes[$field] : null;
    }

    public function __set($field, $value)
    {
        $this->attributes[$field] = $value;
    }

    public static function __callStatic($method, $params)
    {
        $model = new static();
        $protected = ['freshDate'];

        if (!in_array($method, $protected) && method_exists($model, $method)) {
            return call_user_func_array([$model, $method], $params);
        }

        throw new \BadMethodCallException(
            sprintf('Undefined method %s in %s.', $method, static::class)
        );
    }
}


text:
gsettings set org.gnome.desktop.wm.preferences          mouse-button-modifier               "'<Alt>'"
gsettings set org.gnome.desktop.wm.preferences          resize-with-right-button            "true"

gsettings set org.gnome.desktop.background              show-desktop-icons                  "false"

gsettings set org.gnome.desktop.calendar                show-weekdate                       "true"

gsettings set org.gnome.desktop.input-sources           xkb-options                         "['compose:caps']"

gsettings set org.gnome.desktop.wm.keybindings          switch-to-workspace-1               "[]"
gsettings set org.gnome.desktop.wm.keybindings          switch-to-workspace-2               "[]"
gsettings set org.gnome.desktop.wm.keybindings          switch-to-workspace-3               "[]"
gsettings set org.gnome.desktop.wm.keybindings          switch-to-workspace-4               "[]"
gsettings set org.gnome.desktop.wm.keybindings          switch-to-workspace-5               "[]"
gsettings set org.gnome.desktop.wm.keybindings          switch-to-workspace-6               "[]"
gsettings set org.gnome.desktop.wm.keybindings          switch-to-workspace-7               "[]"
gsettings set org.gnome.desktop.wm.keybindings          switch-to-workspace-8               "[]"
gsettings set org.gnome.desktop.wm.keybindings          switch-to-workspace-9               "[]"
gsettings set org.gnome.desktop.wm.keybindings          switch-to-workspace-10              "[]"
gsettings set org.gnome.desktop.wm.keybindings          switch-to-workspace-11              "[]"
gsettings set org.gnome.desktop.wm.keybindings          switch-to-workspace-12              "[]"
gsettings set org.gnome.desktop.wm.keybindings          move-to-workspace-1                 "[]"
gsettings set org.gnome.desktop.wm.keybindings          move-to-workspace-2                 "[]"
gsettings set org.gnome.desktop.wm.keybindings          move-to-workspace-3                 "[]"
gsettings set org.gnome.desktop.wm.keybindings          move-to-workspace-4                 "[]"
gsettings set org.gnome.desktop.wm.keybindings          move-to-workspace-5                 "[]"
gsettings set org.gnome.desktop.wm.keybindings          move-to-workspace-6                 "[]"
gsettings set org.gnome.desktop.wm.keybindings          move-to-workspace-7                 "[]"
gsettings set org.gnome.desktop.wm.keybindings          move-to-workspace-8                 "[]"
gsettings set org.gnome.desktop.wm.keybindings          move-to-workspace-9                 "[]"
gsettings set org.gnome.desktop.wm.keybindings          move-to-workspace-10                "[]"
gsettings set org.gnome.desktop.wm.keybindings          move-to-workspace-11                "[]"
gsettings set org.gnome.desktop.wm.keybindings          move-to-workspace-12                "[]"
gsettings set org.gnome.desktop.wm.keybindings          switch-to-workspace-down            "[]"
gsettings set org.gnome.desktop.wm.keybindings          switch-to-workspace-last            "[]"
gsettings set org.gnome.desktop.wm.keybindings          switch-to-workspace-left            "['<Super>Page_Up']"
gsettings set org.gnome.desktop.wm.keybindings          switch-to-workspace-right           "['<Super>Page_Down']"
gsettings set org.gnome.desktop.wm.keybindings          switch-to-workspace-up              "[]"
gsettings set org.gnome.desktop.wm.keybindings          switch-windows                      "['<Alt>Tab']"
gsettings set org.gnome.desktop.wm.keybindings          switch-windows-backward             "['<Shift><Alt>Tab']"
gsettings set org.gnome.desktop.wm.keybindings          toggle-above                        "[]"
gsettings set org.gnome.desktop.wm.keybindings          toggle-fullscreen                   "['<Alt>F11']"
gsettings set org.gnome.desktop.wm.keybindings          toggle-maximized                    "['<Alt>F10', '<Primary><Super>Up']"
gsettings set org.gnome.desktop.wm.keybindings          toggle-on-all-workspaces            "[]"
gsettings set org.gnome.desktop.wm.keybindings          toggle-shaded                       "[]"
gsettings set org.gnome.desktop.wm.keybindings          unmaximize                          "[]"
gsettings set org.gnome.desktop.wm.keybindings          begin-move                          "['<Alt>F7']"
gsettings set org.gnome.desktop.wm.keybindings          begin-resize                        "['<Alt>F8']"
gsettings set org.gnome.desktop.wm.keybindings          close                               "['<Primary>q']"

gsettings set org.gnome.mutter                          dynamic-workspaces                  "false"
gsettings set org.gnome.mutter.keybindings              toggle-tiled-left                   "['<Control><Super>Left']"
gsettings set org.gnome.mutter.keybindings              toggle-tiled-right                  "['<Control><Super>Right']"

gsettings set org.gnome.shell.keybindings               focus-active-notification           "[]"
gsettings set org.gnome.shell.keybindings               open-application-menu               "[]"
gsettings set org.gnome.shell.keybindings               screenshot                          "['<Shift>Print']"
gsettings set org.gnome.shell.keybindings               screenshot-window                   "['<Alt>Print']"
gsettings set org.gnome.shell.keybindings               shift-overview-down                 "['<Super><Alt>Down']"
gsettings set org.gnome.shell.keybindings               shift-overview-up                   "['<Super><Alt>Up']"
gsettings set org.gnome.shell.keybindings               show-screen-recording-ui            "['<Ctrl><Shift><Alt>R']"
gsettings set org.gnome.shell.keybindings               show-screenshot-ui                  "['Print']"
gsettings set org.gnome.shell.keybindings               switch-to-application-1             "['<Super>1']"
gsettings set org.gnome.shell.keybindings               switch-to-application-2             "['<Super>2']"
gsettings set org.gnome.shell.keybindings               switch-to-application-3             "['<Super>3']"
gsettings set org.gnome.shell.keybindings               switch-to-application-4             "['<Super>4']"
gsettings set org.gnome.shell.keybindings               switch-to-application-5             "['<Super>5']"
gsettings set org.gnome.shell.keybindings               switch-to-application-6             "['<Super>6']"
gsettings set org.gnome.shell.keybindings               switch-to-application-7             "['<Super>7']"
gsettings set org.gnome.shell.keybindings               switch-to-application-8             "['<Super>8']"
gsettings set org.gnome.shell.keybindings               switch-to-application-9             "['<Super>9']"
gsettings set org.gnome.shell.keybindings               toggle-application-view             "['<Super>a']"
gsettings set org.gnome.shell.keybindings               toggle-message-tray                 "['<Super>v','<Super>m']"
gsettings set org.gnome.shell.keybindings               toggle-overview                     "['<Super>s']"

gsettings set org.gnome.shell.app-switcher              current-workspace-only              "false"

gsettings set org.gnome.settings-daemon.plugins.power   sleep-inactive-ac-timeout           "3600"
gsettings set org.gnome.settings-daemon.plugins.power   sleep-inactive-ac-type              "'nothing'"

gsettings set org.gnome.settings-daemon.plugins.media-keys    screensaver                   "['<Super>l']"
gsettings set org.gnome.settings-daemon.plugins.media-keys    home                          "['<Ctrl><Alt>h']"
gsettings set org.gnome.settings-daemon.plugins.media-keys    calculator                    "['<Ctrl><Alt>c']"

gsettings set org.gnome.desktop.interface                clock-show-seconds                 "true"
gsettings set org.gnome.desktop.interface                clock-show-weekday                 "true"
gsettings set org.gnome.desktop.interface                clock-show-date                    "true"

gsettings set org.gnome.desktop.screensaver              lock-delay                         "uint32 3600"

gsettings set org.gnome.desktop.search-providers         disable-external                   "true"

gsettings set org.gnome.desktop.privacy                  remove-old-temp-files              "true"
gsettings set org.gnome.desktop.privacy                  old-files-age                      "uint32 14"
gsettings set org.gnome.desktop.privacy                  remove-old-trash-files             "true"

gsettings set org.gnome.shell.extensions.dash-to-dock    animate-show-apps                  "false"
gsettings set org.gnome.shell.extensions.dash-to-dock    app-hotkey-1                       "['<Super>1']"
gsettings set org.gnome.shell.extensions.dash-to-dock    app-hotkey-2                       "['<Super>2']"
gsettings set org.gnome.shell.extensions.dash-to-dock    app-hotkey-3                       "['<Super>3']"
gsettings set org.gnome.shell.extensions.dash-to-dock    app-hotkey-4                       "['<Super>4']"
gsettings set org.gnome.shell.extensions.dash-to-dock    app-hotkey-5                       "['<Super>5']"
gsettings set org.gnome.shell.extensions.dash-to-dock    app-hotkey-6                       "['<Super>6']"
gsettings set org.gnome.shell.extensions.dash-to-dock    app-hotkey-7                       "['<Super>7']"
gsettings set org.gnome.shell.extensions.dash-to-dock    app-hotkey-8                       "['<Super>8']"
gsettings set org.gnome.shell.extensions.dash-to-dock    app-hotkey-9                       "['<Super>9']"
gsettings set org.gnome.shell.extensions.dash-to-dock    app-hotkey-10                      "['<Super>0']"
gsettings set org.gnome.shell.extensions.dash-to-dock    icon-size-fixed                    "true"
gsettings set org.gnome.shell.extensions.dash-to-dock    dash-max-icon-size                 "64"
gsettings set org.gnome.shell.extensions.dash-to-dock    default-windows-preview-to-open    "false"
gsettings set org.gnome.shell.extensions.dash-to-dock    disable-overview-on-startup        "true"
gsettings set org.gnome.shell.extensions.dash-to-dock    dock-fixed                         "false"
gsettings set org.gnome.shell.extensions.dash-to-dock    dock-position                      "'LEFT'"
gsettings set org.gnome.shell.extensions.dash-to-dock    apply-custom-theme                 "true"
gsettings set org.gnome.shell.extensions.dash-to-dock    autohide                           "true"
gsettings set org.gnome.shell.extensions.dash-to-dock    autohide-in-fullscreen             "true"
gsettings set org.gnome.shell.extensions.dash-to-dock    click-action                       "'cycle-windows'"
gsettings set org.gnome.shell.extensions.dash-to-dock    extend-height                      "false"
gsettings set org.gnome.shell.extensions.dash-to-dock    hot-keys                           "true"
gsettings set org.gnome.shell.extensions.dash-to-dock    hotkeys-overlay                    "true"
gsettings set org.gnome.shell.extensions.dash-to-dock    hotkeys-show-dock                  "true"
gsettings set org.gnome.shell.extensions.dash-to-dock    intellihide                        "true"
gsettings set org.gnome.shell.extensions.dash-to-dock    intellihide-mode                   "'ALL_WINDOWS'"
gsettings set org.gnome.shell.extensions.dash-to-dock    isolate-locations                  "false"
gsettings set org.gnome.shell.extensions.dash-to-dock    isolate-monitors                   "false"
gsettings set org.gnome.shell.extensions.dash-to-dock    isolate-workspaces                 "false"
gsettings set org.gnome.shell.extensions.dash-to-dock    manualhide                         "false"
gsettings set org.gnome.shell.extensions.dash-to-dock    middle-click-action                "'launch'"
gsettings set org.gnome.shell.extensions.dash-to-dock    multi-monitor                      "false"
gsettings set org.gnome.shell.extensions.dash-to-dock    require-pressure-to-show           "false"
gsettings set org.gnome.shell.extensions.dash-to-dock    scroll-action                      "'do-nothing'"
gsettings set org.gnome.shell.extensions.dash-to-dock    scroll-switch-workspace            "true"
gsettings set org.gnome.shell.extensions.dash-to-dock    scroll-to-focused-application      "true"
gsettings set org.gnome.shell.extensions.dash-to-dock    shift-click-action                 "'minimize'"
gsettings set org.gnome.shell.extensions.dash-to-dock    shortcut                           "['<Super>q']"
gsettings set org.gnome.shell.extensions.dash-to-dock    shortcut-text                      "'<Super>q'"
gsettings set org.gnome.shell.extensions.dash-to-dock    show-apps-at-top                   "false"
gsettings set org.gnome.shell.extensions.dash-to-dock    show-dock-urgent-notify            "true"
gsettings set org.gnome.shell.extensions.dash-to-dock    show-favorites                     "true"
gsettings set org.gnome.shell.extensions.dash-to-dock    show-mounts                        "true"
gsettings set org.gnome.shell.extensions.dash-to-dock    show-mounts-network                "false"
gsettings set org.gnome.shell.extensions.dash-to-dock    show-mounts-only-mounted           "true"
gsettings set org.gnome.shell.extensions.dash-to-dock    show-running                       "true"
gsettings set org.gnome.shell.extensions.dash-to-dock    show-show-apps-button              "true"
gsettings set org.gnome.shell.extensions.dash-to-dock    show-trash                         "true"
gsettings set org.gnome.shell.extensions.dash-to-dock    show-windows-preview               "false"
gsettings set org.gnome.shell.extensions.dash-to-dock    activate-single-window             "true"

gsettings set org.gnome.shell.extensions.gtile           insets-primary-left                "0"
gsettings set org.gnome.shell.extensions.gtile           show-toggle-tiling                 "['<Super>t']"
gsettings set org.gnome.shell.extensions.gtile           window-margin                      "0"

gsettings set org.gnome.gthumb.browser                   scroll-action                      "'zoom'"


text:
#pragma once
#include <aws/chime/Chime_EXPORTS.h>
#include <aws/chime/ChimeRequest.h>

namespace Aws
{
namespace Chime
{
namespace Model
{

  /**
   */
  class AWS_CHIME_API GetMessagingSessionEndpointRequest : public ChimeRequest
  {
  public:
    GetMessagingSessionEndpointRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "GetMessagingSessionEndpoint"; }

    Aws::String SerializePayload() const override;

  };

} // namespace Model
} // namespace Chime
} // namespace Aws


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="256dp"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:fitsSystemWindows="true">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginStart="48dp"
            app:expandedTitleMarginEnd="64dp">

            <com.ljd.news.presentation.view.component.AutoLoadImageView
                android:id="@+id/zhi_hu_story_image"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="centerCrop"
                android:fitsSystemWindows="true"
                app:layout_collapseMode="parallax" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                app:layout_collapseMode="pin" />

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">
        <FrameLayout
            android:id="@+id/web_view_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        </FrameLayout>
    </android.support.v4.widget.NestedScrollView>

    <android.support.design.widget.FloatingActionButton
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        app:layout_anchor="@id/appbar"
        app:layout_anchorGravity="bottom|right|end"
        android:layout_margin="@dimen/fab_margin"
        android:clickable="true"/>
    <include layout="@layout/view_progress"/>

</android.support.design.widget.CoordinatorLayout>


text:
/* */
function split(value, separator, includeSeparator, openLevel, closeLevel) {
  var withRegex = typeof separator != 'string';
  var hasSeparator = withRegex ?
    separator.test(value) :
    value.indexOf(separator);

  if (!hasSeparator)
    return [value];

  openLevel = openLevel || '(';
  closeLevel = closeLevel || ')';

  if (value.indexOf(openLevel) == -1 && !includeSeparator)
    return value.split(separator);

  var level = 0;
  var cursor = 0;
  var lastStart = 0;
  var len = value.length;
  var tokens = [];

  while (cursor < len) {
    if (value[cursor] == openLevel) {
      level++;
    } else if (value[cursor] == closeLevel) {
      level--;
    }

    if (level === 0 && cursor > 0 && cursor + 1 < len && (withRegex ? separator.test(value[cursor]) : value[cursor] == separator)) {
      tokens.push(value.substring(lastStart, cursor + (includeSeparator ? 1 : 0)));
      lastStart = cursor + 1;
    }

    cursor++;
  }

  if (lastStart < cursor + 1) {
    var lastValue = value.substring(lastStart);
    var lastCharacter = lastValue[lastValue.length - 1];
    if (!includeSeparator && (withRegex ? separator.test(lastCharacter) : lastCharacter == separator))
      lastValue = lastValue.substring(0, lastValue.length - 1);

    tokens.push(lastValue);
  }

  return tokens;
}

module.exports = split;


text:
<!DOCTYPE html >

          <meta http-equiv="X-UA-Compatible" content="IE=edge" />
          <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
          <title>SANSA-Stack 0.8.0 ScalaDoc  - net.sansa_stack.inference.spark.forwardchaining.triples.ForwardRuleReasonerNaive</title>
          <meta name="description" content="SANSA - Stack 0.8.0 ScalaDoc - net.sansa stack.inference.spark.forwardchaining.triples.ForwardRuleReasonerNaive" />
          <meta name="keywords" content="SANSA Stack 0.8.0 ScalaDoc net.sansa stack.inference.spark.forwardchaining.triples.ForwardRuleReasonerNaive" />
          <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

      <link href="../../../../../../lib/index.css" media="screen" type="text/css" rel="stylesheet" />
      <link href="../../../../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
      <link href="../../../../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />

        SANSA-Stack 0.8.0 ScalaDoc
        < Back

            <input autocapitalize="none" placeholder="Search" id="index-input" type="text" accesskey="/" />
            
            

Packages

        

        package

        root

Definition Classes

root

        

        package

        net

Definition Classes

root

        

        package

        sansa_stack

Definition Classes

net

        

        package

        inference

Definition Classes

sansa_stack

        

        package

        spark

Definition Classes

inference

        

        package

        forwardchaining

Definition Classes

spark

        

        package

        triples

Definition Classes

forwardchaining

                        AbstractForwardRuleReasoner

                        AbstractForwardRuleReasonerRDFS

                        FixpointIteration

                        ForwardRuleReasoner

                        ForwardRuleReasonerEL

                        ForwardRuleReasonerNaive

                        ForwardRuleReasonerOWLHorst

                        ForwardRuleReasonerOptimized

                        ForwardRuleReasonerOptimizedNative

                        ForwardRuleReasonerRDFS

                        ForwardRuleReasonerRDFSDataframe

                        TransitiveReasoner

c

net.sansa_stack.inference.spark.forwardchaining.triples

ForwardRuleReasonerNaive

        

        class

        ForwardRuleReasonerNaive extends AbstractForwardRuleReasoner[Jena, RDD[Triple], RDFGraphNative]

A naive implementation of the forward chaining based reasoner that does fix-point iteration, i.e. it applies
all rules in each iteration until no new data has been generated.
.

Source

ForwardRuleReasonerNaive.scala

            Linear Supertypes

AbstractForwardRuleReasoner[Jena, RDD[Triple], RDFGraphNative], Logging, AnyRef, Any

          

            <input id="mbrsel-input" placeholder="Filter all members" type="text" accesskey="/" />

          

            Ordering

Alphabetic

By Inheritance

                  Inherited

ForwardRuleReasonerNaive

AbstractForwardRuleReasoner

Logging

AnyRef

Any

Hide All

Show All

              Visibility

Public

All

Instance Constructors

        

        new

        ForwardRuleReasonerNaive(sc: SparkContext, rules: Set[Rule])

Value Members

        

        final
        def

        !=(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        

        final
        def

        ##(): Int

Definition Classes

AnyRef → Any

        

        final
        def

        ==(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        

        def

        apply(graph: RDFGraphNative): RDFGraphNative

Applies forward chaining to the given RDF graph and returns a new RDF graph that contains all additional
triples based on the underlying set of rules.

Applies forward chaining to the given RDF graph and returns a new RDF graph that contains all additional
triples based on the underlying set of rules.

graph

the RDF graph

returns

the materialized RDF graph

Definition Classes

ForwardRuleReasonerNaive → AbstractForwardRuleReasoner

        

        def

        applyRule(rule: Rule, graph: RDFGraphNative): RDFGraphNative

Apply a single rule on the given graph.

Apply a single rule on the given graph.

rule

the rule

graph

the graph

        

        def

        applyRules(graph: RDFGraphNative): RDFGraphNative

Apply a set of rules on the given graph.

Apply a set of rules on the given graph.

graph

the graph

        

        final
        def

        asInstanceOf[T0]: T0

Definition Classes

Any

        

        def

        clone(): AnyRef

Attributes

protected[lang]

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

                @native()

        

        def

        debug(msg: ⇒ String, o: Any, os: Any*): Unit

Definition Classes

Logging

        

        def

        debug(msg: ⇒ String, e: Throwable): Unit

Definition Classes

Logging

        

        def

        debug(msg: ⇒ String): Unit

Definition Classes

Logging

        

        final
        def

        eq(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        

        def

        equals(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        

        def

        error(msg: ⇒ String, o: Any, os: Any*): Unit

Definition Classes

Logging

        

        def

        error(msg: ⇒ String, e: Throwable): Unit

Definition Classes

Logging

        

        def

        error(msg: ⇒ String): Unit

Definition Classes

Logging

        

        def

        finalize(): Unit

Attributes

protected[lang]

Definition Classes

AnyRef

Annotations

                @throws(

      classOf[java.lang.Throwable]
    )

        

        final
        def

        getClass(): Class[_]

Definition Classes

AnyRef → Any

Annotations

                @native()

        

        def

        hashCode(): Int

Definition Classes

AnyRef → Any

Annotations

                @native()

        

        def

        info(msg: ⇒ String, o: Any, os: Any*): Unit

Definition Classes

Logging

        

        def

        info(msg: ⇒ String, e: Throwable): Unit

Definition Classes

Logging

        

        def

        info(msg: ⇒ String): Unit

Definition Classes

Logging

        

        final
        def

        isInstanceOf[T0]: Boolean

Definition Classes

Any

        

        def

        log: Logger

Attributes

protected

Definition Classes

Logging

        

        def

        logName: String

Attributes

protected

Definition Classes

Logging

        

        final
        def

        ne(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        

        final
        def

        notify(): Unit

Definition Classes

AnyRef

Annotations

                @native()

        

        final
        def

        notifyAll(): Unit

Definition Classes

AnyRef

Annotations

                @native()

        

        val

        ruleExecutor: RuleExecutorNative

        

        final
        def

        synchronized[T0](arg0: ⇒ T0): T0

Definition Classes

AnyRef

        

        def

        toString(): String

Definition Classes

AnyRef → Any

        

        def

        trace(msg: ⇒ String, o: Any, os: Any*): Unit

Definition Classes

Logging

        

        def

        trace(msg: ⇒ String, e: Throwable): Unit

Definition Classes

Logging

        

        def

        trace(msg: ⇒ String): Unit

Definition Classes

Logging

        

        final
        def

        wait(): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        

        final
        def

        wait(arg0: Long, arg1: Int): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        

        final
        def

        wait(arg0: Long): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

                @native()

        

        def

        warn(msg: ⇒ String, o: Any, os: Any*): Unit

Definition Classes

Logging

        

        def

        warn(msg: ⇒ String, e: Throwable): Unit

Definition Classes

Logging

        

        def

        warn(msg: ⇒ String): Unit

Definition Classes

Logging

Inherited from AbstractForwardRuleReasoner[Jena, RDD[Triple], RDFGraphNative]

Inherited from Logging

Inherited from AnyRef

Inherited from Any

Ungrouped


text:
/**
 * @param {Array} data
 * @return {Object}
 */
function createDiffData(data) {
    return { length:data.length, data:data, modified:[] };
}

/**
 * Finds the Shortest Middle Snake (SMS).
 * @param {Object} dataA
 * @param {Number} lowerA
 * @param {Number} upperA
 * @param {Object} dataB
 * @param {Number} lowerB
 * @param {Number} upperB
 * @param {Function} equals
 * @return {Object}
 */
function sms(dataA, lowerA, upperA, dataB, lowerB, upperB, equals) {
    var ret = {}, MAX = dataA.length + dataB.length + 1,
        downK = lowerA - lowerB, // the k-line to start the forward search
        upK = upperA - upperB, // the k-line to start the reverse search
        delta = (upperA - lowerA) - (upperB - lowerB),
        oddDelta = (delta & 1) !== 0,
        downDelta = new Array(2 * MAX + 2), // vector for the (0,0) to (x,y) search
        upVector = new Array(2 * MAX + 2), // vector for the (u,v) to (N,M) search
        downOffset = MAX - downK,
        upOffset = MAX - upK,
        maxD = ((upperA - lowerA + upperB - lowerB) / 2) + 1;

    // init vectors
    downDelta[downOffset + downK + 1] = lowerA;
    upVector[upOffset + upK - 1] = upperA;
    var x, y;
    for (var D = 0; D <= maxD; D++) {
        // Extend the forward path.
        for (var k = downK - D; k <= downK + D; k += 2) {
            // find the only or better starting point
            if (k === downK - D) {
                x = downDelta[downOffset + k + 1]; // down
            } else {
                x = downDelta[downOffset + k - 1] + 1; // a step to the right
                if ((k < downK + D) && (downDelta[downOffset + k + 1] >= x)) {
                    x = downDelta[downOffset + k + 1]; // down
                }
            }
            y = x - k;

            // find the end of the furthest reaching forward D-path in diagonal k.
            while (x < upperA && y < upperB && equals(dataA.data[x], dataB.data[y])) {
                x++;
                y++;
            }
            downDelta[downOffset + k] = x;

            // overlap ?
            if (oddDelta && (upK - D < k) && (k < upK + D)) {
                if (upVector[upOffset + k] <= downDelta[downOffset + k]) {
                    ret.x = downDelta[downOffset + k];
                    ret.y = downDelta[downOffset + k] - k;
                    return (ret);
                }
            }
        }

        // Extend the reverse path.
        for (k = upK - D; k <= upK + D; k += 2) {
            if (k === upK + D) {
                x = upVector[upOffset + k - 1]; // up
            } else {
                x = upVector[upOffset + k + 1] - 1; // left
                if (k > upK - D && upVector[upOffset + k - 1] < x) {
                    x = upVector[upOffset + k - 1]; // up
                }
            }
            y = x - k;

            while (x > lowerA && y > lowerB && equals(dataA.data[x - 1], dataB.data[y - 1])) {
                x--;
                y--; // diagonal
            }
            upVector[upOffset + k] = x;

            // overlap ?
            if (!oddDelta && downK - D <= k && k <= downK + D) {
                if (upVector[upOffset + k] <= downDelta[downOffset + k]) {
                    ret.x = downDelta[downOffset + k];
                    ret.y = downDelta[downOffset + k] - k;
                    return (ret);
                }
            }
        }
    }
    assert(false);
}

/**
 * This is the divide-and-conquer implementation of the longest common-sub-sequence (LCS)
 * algorithm.
 *
 * @param {Array} dataA
 * @param {Number} lowerA
 * @param {Number} upperA
 * @param {Array} dataB
 * @param {Number} lowerB
 * @param {Number} upperB
 * @param {Function} equals
 */
function lcs(dataA, lowerA, upperA, dataB, lowerB, upperB, equals) {
    // Fast walk through equal items at the start
    while (lowerA < upperA && lowerB < upperB && equals(dataA.data[lowerA], dataB.data[lowerB])) {
        lowerA++;
        lowerB++;
    }

    // Fast walk through equal lines at the end
    while (lowerA < upperA && lowerB < upperB && equals(dataA.data[upperA - 1], dataB.data[upperB - 1])) {
        --upperA;
        --upperB;
    }

    if (lowerA === upperA) {
        // mark as inserted lines.
        while (lowerB < upperB) {
            dataB.modified[lowerB++] = true;
        }

    } else if (lowerB === upperB) {
        // mark as deleted lines.
        while (lowerA < upperA) {
            dataA.modified[lowerA++] = true;
        }

    } else {
        // Find the middle snake and length of an optimal path for A and B
        var smsResult = sms(dataA, lowerA, upperA, dataB, lowerB, upperB, equals);

        // The path is from LowerX to (x,y) and (x,y) to UpperX
        lcs(dataA, lowerA, smsResult.x, dataB, lowerB, smsResult.y, equals);
        lcs(dataA, smsResult.x, upperA, dataB, smsResult.y, upperB, equals);
    }
}

/**
 * @param {object} dataA
 * @param {object} dataB
 * @returns {Array}
 */
function createDiffs(dataA, dataB) {
    var result = [],
        startA, startB,
        lineA = 0, lineB = 0,
        lengthA = dataA.length,
        lengthB = dataB.length;

    while (lineA < lengthA || lineB < lengthB) {
        if ((lineA < lengthA) && (!dataA.modified[lineA]) && (lineB < lengthB) && (!dataB.modified[lineB])) {
            // equal lines
            lineA++;
            lineB++;

        } else {
            // maybe deleted and/or inserted lines
            startA = lineA;
            startB = lineB;
            while (lineA < lengthA && (lineB >= lengthB || dataA.modified[lineA])) {
                lineA++;
            }

            while (lineB < lengthB && (lineA >= lengthA || dataB.modified[lineB])) {
                lineB++;
            }

            if (startA < lineA || startB < lineB) {
                result.push({
                    startA:startA,
                    startB:startB,
                    deletedA:lineA - startA,
                    insertedB:lineB - startB
                });
            }
        }
    }
    return result;
}

/** @namespace photon.array */
provide("photon.array",
    /**
     * @lends photon.array
     */
    {
        find:function (array, fromIndex, fn, obj) {
            var i = photon.array.findIndex(array, fromIndex, fn, obj);
            return i !== -1 ? array[i] : null;
        },
        findIndex:function (array, fromIndex, fn, obj) {
            if (photon.isFunction(fromIndex)) {
                obj = fn; fn = fromIndex; fromIndex = 0;
            }
            for (var i = fromIndex, n = array.length; i < n; i++) {
                var item = array[i];
                if (fn.call(obj, item, i, array)) {
                    return i;
                }
            }
            return -1;
        },
        map:arrayNativePrototype &&
            arrayNativePrototype.map ?
            function (array, mapper, obj) {
                return arrayNativePrototype.map.call(array, mapper, obj);
            } :
            function (array, mapper, obj) {
                var length = array.length, result = new Array(length),
                    actualArray = photon.isString(array) ? array.split('') : array;
                for (var i = 0; i < length; i++) {
                    if (i in actualArray) {
                        result[i] = mapper.call(obj, actualArray[i], i, array);
                    }
                }
                return result;
            },
        filter:arrayNativePrototype &&
            arrayNativePrototype.filter ?
            function (array, filter, obj) {
                return arrayNativePrototype.filter.call(array, filter, obj);
            } :
            function (array, filter, obj) {
                var arrayLength = array.length;
                var result = [];
                var resultIndex = 0;
                var arrayToFilter = photon.isString(array) ? array.split('') : array;
                for (var index = 0; index < arrayLength; index++) {
                    if (index in arrayToFilter) {
                        var value = arrayToFilter[index];  // in case array is mutated by filter
                        if (filter.call(obj, value, index, array)) {
                            result[resultIndex++] = value;
                        }
                    }
                }
                return result;
            },
        forEach:arrayNativePrototype && arrayNativePrototype.forEach ?
            function (array, fn, obj) {
                arrayNativePrototype.forEach.call(array, fn, obj);
            } :
            function (array, fn, obj) {
                array = photon.isString(array) ? array.split('') : array;
                for (var i = 0, n = array.length; i < n; i++) {
                    if (i in array) {
                        fn.call(obj, array[i], i, array);
                    }
                }
            },
        indexOf:arrayNativePrototype && arrayNativePrototype.indexOf ?
            function (array, item, fromIndex) {
                return arrayNativePrototype.indexOf.call(array, item, fromIndex);
            } :
            function (array, item, fromIndex) {
                fromIndex = photon.isNullOrUndefined(fromIndex) ? 0
                    : (fromIndex < 0 ? Math.max(0, array.length + fromIndex) : fromIndex);

                if (photon.isString(array)) {
                    // Array.prototype.indexOf uses === so only strings should be found.
                    if (!photon.isString(item) || item.length !== 1) {
                        return -1;
                    }
                    return array.indexOf(item, fromIndex);
                }

                for (var i = fromIndex, n = array.length; i < n; i++) {
                    if (i in array && array[i] === item) {
                        return i;
                    }
                }
                return -1;
            },
        removeDuplicates:function (array, returnArray, selector, thisObj) {
            if (photon.isFunction(returnArray)) {
                thisObj = selector;
                selector = returnArray;
                returnArray = null;
            }

            returnArray = returnArray || array;

            var map = {}, insertIndex = 0, readIndex = 0;
            while (readIndex < array.length) {
                var current = array[readIndex++];

                // use selector if supplied
                if (selector) {
                    current = selector.call(thisObj, current);
                }

                // map to key
                var currentType = typeof current;
                var key = currentType === 'object' && current !== null ?
                    'o' + photon.getUID(current) :
                    currentType.charAt(0) + current;

                // lookup and add if not there
                if (!map.hasOwnProperty(key)) {
                    map[key] = true;
                    returnArray[insertIndex++] = current;
                }
            }
            returnArray.length = insertIndex;
        },
        /**
         * Returns the differences between two arrays
         * @param {Array} a
         * @param {Array} b
         * @returns {Array}
         */
        diff:function (a, b, equals) {
            var dataA = createDiffData(a),
                dataB = createDiffData(b);

            lcs(dataA, 0, dataA.length, dataB, 0, dataB.length, equals || function (a, b) {
                return a === b;
            });
            return createDiffs(dataA, dataB);
        },
        toArray:function (arrayLike,fromIndex, length) {
            if (photon.isArray(arrayLike)) {
                return arrayLike;
            }
            var result = [];
            fromIndex = fromIndex || 0;
            if (photon.isUndefined(length)) {
                length = arrayLike.length - fromIndex;
            }
            for (var i = fromIndex; i < length; i++) {
                result[i] = arrayLike[i];
            }
            return result;
        },
        remove:function (array, item) {
            var index = photon.array.indexOf(array, item);
            if (index !== -1) {
                array.splice(index, 1);
                return true;
            }
            return false;
        }
    });