<commit_before>"use strict";

const Symbols = require("dc-constants").Symbols;

function PresetHelper($preset, $gameData, $choiceProvider) {
    let preset = $preset,
        gameData = $gameData,
        choiceProvider = $choiceProvider;
    $preset = $gameData = $choiceProvider;

    function apply() {
        adjustPlayers();
        return createStateFromPreset();
    }
    this.apply = apply;

    function createStateFromPreset() {
        return new preset.state.stateClass(...evaluateStateArgs());
    }

    function evaluateStateArgs() {
        let args = [ gameData, choiceProvider ];
        preset.state.args.forEach(function(arg) {
            switch(arg) {
                case Symbols.player1:
                    args.push(gameData.players[0]);
                    break;
                case Symbols.player2:
                    args.push(gameData.players[1]);
                    break;
                case Symbols.player3:
                    args.push(gameData.players[2]);
                    break;
                case Symbols.player4:
                    args.push(gameData.players[3]);
                    break;
                default:
                    args.push(arg);
                    break;
            }
        });

        return args;
    }

    function adjustPlayers() {
        for(let i = 0; i < gameData.players.length; ++i) {
            let playerPreset = preset.players[i];
            if(!playerPreset)
                break;

            let player = gameData.players[i];
            player.money = playerPreset.money;
            dealLoops(player, playerPreset, dealPresetCards);
        }

        for(let i = 0; i < gameData.players.length; ++i) {
            let playerPreset = preset.players[i];
            if(!playerPreset)
                break;

            dealLoops(gameData.players[i], playerPreset, dealRandomCards);
        }
    }

    function dealLoops(player, playerPreset, dealFunction) {
        playerPreset.dcCards.forEach(
            dealFunction.bind(null, player.gainDcCard, gameData.dcDeck)
        );

        playerPreset.cars.forEach(
            dealFunction.bind(null, player.gainCar, gameData.carDeck)
        );

        playerPreset.insurances.forEach(
            dealFunction.bind(null, player.gainInsurance, gameData.insuranceDeck)
        );
    }

    function dealPresetCards(gainCard, cards, cardPreset) {
        if(cardPreset !== Symbols.random)
            gainCard(cards.pickCard(cardPreset));
    }

    function dealRandomCards(gainCard, cards, cardPreset) {
        if(cardPreset === Symbols.random)
            gainCard(cards.pop());
    }
}

module.exports = function applyPreset(preset, gameData, choiceProvider) {
    return (new PresetHelper(preset, gameData, choiceProvider)).apply();
};<commit_msg>small fix<commit_after>"use strict";

const Symbols = require("dc-constants").Symbols;

function PresetHelper($preset, $gameData, $choiceProvider) {
    let preset = $preset,
        gameData = $gameData,
        choiceProvider = $choiceProvider;
    $preset = $gameData = $choiceProvider = null;

    function apply() {
        adjustPlayers();
        return createStateFromPreset();
    }
    this.apply = apply;

    function createStateFromPreset() {
        return new preset.state.stateClass(...evaluateStateArgs());
    }

    function evaluateStateArgs() {
        let args = [ gameData, choiceProvider ];
        preset.state.args.forEach(function(arg) {
            switch(arg) {
                case Symbols.player1:
                    args.push(gameData.players[0]);
                    break;
                case Symbols.player2:
                    args.push(gameData.players[1]);
                    break;
                case Symbols.player3:
                    args.push(gameData.players[2]);
                    break;
                case Symbols.player4:
                    args.push(gameData.players[3]);
                    break;
                default:
                    args.push(arg);
                    break;
            }
        });

        return args;
    }

    function adjustPlayers() {
        for(let i = 0; i < gameData.players.length; ++i) {
            let playerPreset = preset.players[i];
            if(!playerPreset)
                break;

            let player = gameData.players[i];
            player.money = playerPreset.money;
            dealLoops(player, playerPreset, dealPresetCards);
        }

        for(let i = 0; i < gameData.players.length; ++i) {
            let playerPreset = preset.players[i];
            if(!playerPreset)
                break;

            dealLoops(gameData.players[i], playerPreset, dealRandomCards);
        }
    }

    function dealLoops(player, playerPreset, dealFunction) {
        playerPreset.dcCards.forEach(
            dealFunction.bind(null, player.gainDcCard, gameData.dcDeck)
        );

        playerPreset.cars.forEach(
            dealFunction.bind(null, player.gainCar, gameData.carDeck)
        );

        playerPreset.insurances.forEach(
            dealFunction.bind(null, player.gainInsurance, gameData.insuranceDeck)
        );
    }

    function dealPresetCards(gainCard, cards, cardPreset) {
        if(cardPreset !== Symbols.random)
            gainCard(cards.pickCard(cardPreset));
    }

    function dealRandomCards(gainCard, cards, cardPreset) {
        if(cardPreset === Symbols.random)
            gainCard(cards.pop());
    }
}

module.exports = function applyPreset(preset, gameData, choiceProvider) {
    return (new PresetHelper(preset, gameData, choiceProvider)).apply();
};<|endoftext|>


<commit_before>import * as registerModule from './register.js';
import * as vuexInstance from '../vuexInstance.js';

global.module = { hot: jest.fn() };

const register = registerModule.default;
const importer = {
  getModules: jest.fn(),
};
const $api = {
  get: { bar: 'foo/bar' },
  act: { bar: 'foo/bar' },
  mutate: { bar: 'foo/bar' },
};
let module;
let self;

beforeEach(() => {
  vuexInstance.default.store = {};

  module = {
    $api,
    get: jest.fn(),
    act: jest.fn(),
    mutate: jest.fn(),
  };
  self = {
    $store: {
      registerModule: jest.fn(),
      unregisterModule: jest.fn(),
      _modules: {
        root: {
          _children: {
          },
        },
      },
    },
  };
  registerModule.setup(importer);

  importer.getModules.mockReturnValue({ 'foo-store': module });
});

describe('register => mixin', () => {
  it('exposes props', () => {
    const result = register('foo-store');
    expect(result.props).toEqual(['instance', 'preserve']);
  });

  describe('mixin.created', () => {
    it('adds registers module on $store', () => {
      const mixin = register('foo-store');
      mixin.created.call(self);
      expect(self.$store.registerModule).toBeCalled();
      mixin.destroyed.call(self);
    });

    it('adds $vuex+ propery', () => {
      const mixin = register.call(self, 'foo-store');
      mixin.created.call(self);
      expect(self['$vuex+']).toEqual({
        baseStoreName: 'foo',
        moduleName: 'foo',
        storeInstanceName: 'foo',
      });
      mixin.destroyed.call(self);
    });

    it('adds $vuex+ propery with camel cased instance', () => {
      importer.getModules.mockReturnValue({ 'foo-choo-store': module });
      self.instance = 'bar';
      const mixin = register.call(self, 'foo-choo-store');
      mixin.created.call(self);
      expect(self['$vuex+']).toEqual({
        baseStoreName: 'fooChoo',
        moduleName: 'fooChoo',
        storeInstanceName: 'fooChoo$bar',
      });
      mixin.destroyed.call(self);
    });
  });

  describe('mixin.destroyed', () => {
    it('removes stores without preseve=true', () => {
      const mixin = register.call(self, 'foo-store');
      mixin.created.call(self);
      mixin.destroyed.call(self);
      expect(self.$store.unregisterModule).toBeCalledWith('foo');
    });

    it('keeps stores with preseve=true', () => {
      self.preserve = true;
      const mixin = register.call(self, 'foo-store');
      mixin.created.call(self);
      mixin.destroyed.call(self);
      expect(self.$store.unregisterModule).not.toBeCalledWith('foo');
    });

    it('removes stores without preseve=true, when no instances left', () => {
      const mixin = register.call(self, 'foo-store');
      mixin.created.call(self);
      mixin.created.call(self);
      mixin.destroyed.call(self);
      expect(self.$store.unregisterModule).not.toBeCalledWith('foo');

      mixin.destroyed.call(self);
      expect(self.$store.unregisterModule).toBeCalledWith('foo');
    });
  });

  describe('HMR Handler', () => {
    it('Generates instanciator for new modules with wrapped method', () => {
      const instanceMethod = jest.fn();
      const hmrHandler = new registerModule.HmrHandler(instanceMethod);
      hmrHandler(42);
      expect(instanceMethod).toBeCalledWith(42);
    });
  });
});
<commit_msg>Fix failing tests<commit_after>import * as registerModule from './register.js';
import * as vuexInstance from '../vuexInstance.js';

global.module = { hot: jest.fn() };

const register = registerModule.default;
const importer = {
  getModules: jest.fn(),
};
const $api = {
  get: { bar: 'foo/bar' },
  act: { bar: 'foo/bar' },
  mutate: { bar: 'foo/bar' },
};
let module;
let self;

beforeEach(() => {
  vuexInstance.default.store = {};

  module = {
    $api,
    get: jest.fn(),
    act: jest.fn(),
    mutate: jest.fn(),
  };
  self = {
    $store: {
      registerModule: jest.fn(),
      unregisterModule: jest.fn(),
      _modules: {
        root: {
          _children: {
          },
        },
      },
    },
    $options: {
      propsData: {
      },
    },
  };
  registerModule.setup(importer);

  importer.getModules.mockReturnValue({ 'foo-store': module });
});

describe('register => mixin', () => {
  it('exposes props', () => {
    const result = register('foo-store');
    expect(result.props).toEqual(['instance', 'preserve']);
  });

  describe('mixin.created', () => {
    it('adds registers module on $store', () => {
      const mixin = register('foo-store');
      mixin.beforeCreate.call(self);
      expect(self.$store.registerModule).toBeCalled();
      mixin.destroyed.call(self);
    });

    it('adds $vuex+ propery', () => {
      const mixin = register.call(self, 'foo-store');
      mixin.beforeCreate.call(self);
      expect(self['$vuex+']).toEqual({
        baseStoreName: 'foo',
        moduleName: 'foo',
        storeInstanceName: 'foo',
      });
      mixin.destroyed.call(self);
    });

    it('adds $vuex+ propery with camel cased instance', () => {
      importer.getModules.mockReturnValue({ 'foo-choo-store': module });
      self.$options.propsData.instance = 'bar';
      const mixin = register.call(self, 'foo-choo-store');
      mixin.beforeCreate.call(self);
      expect(self['$vuex+']).toEqual({
        baseStoreName: 'fooChoo',
        moduleName: 'fooChoo',
        storeInstanceName: 'fooChoo$bar',
      });
      mixin.destroyed.call(self);
    });
  });

  describe('mixin.destroyed', () => {
    it('removes stores without preseve=true', () => {
      const mixin = register.call(self, 'foo-store');
      mixin.beforeCreate.call(self);
      mixin.destroyed.call(self);
      expect(self.$store.unregisterModule).toBeCalledWith('foo');
    });

    it('keeps stores with preseve=true', () => {
      self.preserve = true;
      const mixin = register.call(self, 'foo-store');
      mixin.beforeCreate.call(self);
      mixin.destroyed.call(self);
      expect(self.$store.unregisterModule).not.toBeCalledWith('foo');
    });

    it('removes stores without preseve=true, when no instances left', () => {
      const mixin = register.call(self, 'foo-store');
      mixin.beforeCreate.call(self);
      mixin.beforeCreate.call(self);
      mixin.destroyed.call(self);
      expect(self.$store.unregisterModule).not.toBeCalledWith('foo');

      mixin.destroyed.call(self);
      expect(self.$store.unregisterModule).toBeCalledWith('foo');
    });
  });

  describe('HMR Handler', () => {
    it('Generates instanciator for new modules with wrapped method', () => {
      const instanceMethod = jest.fn();
      const hmrHandler = new registerModule.HmrHandler(instanceMethod);
      hmrHandler(42);
      expect(instanceMethod).toBeCalledWith(42);
    });
  });
});
<|endoftext|>


<commit_before>define(function (require, exports, module) {
    "use strict";

    // Declare variables
    var CodeMirror          = brackets.getModule("thirdparty/CodeMirror/lib/codemirror"),
        LanguageManager     = brackets.getModule("language/LanguageManager");

    // codemirror-nsis (https://github.com/idleberg/codemirror-nsis)
    CodeMirror.defineSimpleMode("nsis",{
      start:[
        // Numbers
        {regex: /(?:[+-]?)(?:0x[\d,a-f]+)|(?:0o[0-7]+)|(?:0b[0,1]+)|(?:\d+.?\d*)/, token: "number"},

        // Strings
        { regex: /"(?:[^\\"]|\\.)*"?/, token: "string" },
        { regex: /'(?:[^\\']|\\.)*'?/, token: "string" },
        { regex: /`(?:[^\\`]|\\.)*`?/, token: "string" },

        // Compile Time Commands
        {regex: /^\s*(?:\!(include|addincludedir|addplugindir|appendfile|cd|delfile|echo|error|execute|packhdr|pragma|finalize|getdllversion|gettlbversion|system|tempfile|warning|verbose|define|undef|insertmacro|macro|macroend|makensis|searchparse|searchreplace))\b/, token: "keyword"},

        // Conditional Compilation
        {regex: /^\s*(?:\!(if(?:n?def)?|ifmacron?def|macro))\b/, token: "keyword", indent: true},
        {regex: /^\s*(?:\!(else|endif|macroend))\b/, token: "keyword", dedent: true},

        // Runtime Commands
        {regex: /^\s*(?:Abort|AddBrandingImage|AddSize|AllowRootDirInstall|AllowSkipFiles|AutoCloseWindow|BGFont|BGGradient|BrandingText|BringToFront|Call|CallInstDLL|Caption|ChangeUI|CheckBitmap|ClearErrors|CompletedText|ComponentText|CopyFiles|CRCCheck|CreateDirectory|CreateFont|CreateShortCut|Delete|DeleteINISec|DeleteINIStr|DeleteRegKey|DeleteRegValue|DetailPrint|DetailsButtonText|DirText|DirVar|DirVerify|EnableWindow|EnumRegKey|EnumRegValue|Exch|Exec|ExecShell|ExecShellWait|ExecWait|ExpandEnvStrings|File|FileBufSize|FileClose|FileErrorText|FileOpen|FileRead|FileReadByte|FileReadUTF16LE|FileReadWord|FileWriteUTF16LE|FileSeek|FileWrite|FileWriteByte|FileWriteWord|FindClose|FindFirst|FindNext|FindWindow|FlushINI|GetCurInstType|GetCurrentAddress|GetDlgItem|GetDLLVersion|GetDLLVersionLocal|GetErrorLevel|GetFileTime|GetFileTimeLocal|GetFullPathName|GetFunctionAddress|GetInstDirError|GetLabelAddress|GetTempFileName|Goto|HideWindow|Icon|IfAbort|IfErrors|IfFileExists|IfRebootFlag|IfSilent|InitPluginsDir|InstallButtonText|InstallColors|InstallDir|InstallDirRegKey|InstProgressFlags|InstType|InstTypeGetText|InstTypeSetText|Int64Cmp|Int64CmpU|Int64Fmt|IntCmp|IntCmpU|IntFmt|IntOp|IntPtrCmp|IntPtrCmpU|IntPtrOp|IsWindow|LangString|LicenseBkColor|LicenseData|LicenseForceSelection|LicenseLangString|LicenseText|LoadAndSetImage|LoadLanguageFile|LockWindow|LogSet|LogText|ManifestDPIAware|ManifestLongPathAware|ManifestMaxVersionTested|ManifestSupportedOS|MessageBox|MiscButtonText|Name|Nop|OutFile|Page|PageCallbacks|PEAddResource|PEDllCharacteristics|PEAddResource|PESubsysVer|Pop|Push|Quit|ReadEnvStr|ReadINIStr|ReadRegDWORD|ReadRegStr|Reboot|RegDLL|Rename|RequestExecutionLevel|ReserveFile|Return|RMDir|SearchPath|SectionGetFlags|SectionGetInstTypes|SectionGetSize|SectionGetText|SectionIn|SectionSetFlags|SectionSetInstTypes|SectionSetSize|SectionSetText|SendMessage|SetAutoClose|SetBrandingImage|SetCompress|SetCompressor|SetCompressorDictSize|SetCtlColors|SetCurInstType|SetDatablockOptimize|SetDateSave|SetDetailsPrint|SetDetailsView|SetErrorLevel|SetErrors|SetFileAttributes|SetFont|SetOutPath|SetOverwrite|SetRebootFlag|SetRegView|SetShellVarContext|SetSilent|ShowInstDetails|ShowUninstDetails|ShowWindow|SilentInstall|SilentUnInstall|Sleep|SpaceTexts|StrCmp|StrCmpS|StrCpy|StrLen|SubCaption|Unicode|UninstallButtonText|UninstallCaption|UninstallIcon|UninstallSubCaption|UninstallText|UninstPage|UnRegDLL|Var|VIAddVersionKey|VIFileVersion|VIProductVersion|WindowIcon|WriteINIStr|WriteRegBin|WriteRegDWORD|WriteRegExpandStr|WriteRegMultiStr|WriteRegNone|WriteRegStr|WriteUninstaller|XPStyle)\b/, token: "keyword"},
        {regex: /^\s*(?:Function|PageEx|Section(?:Group)?)\b/, token: "keyword", indent: true},
        {regex: /^\s*(?:(Function|PageEx|Section(?:Group)?)End)\b/, token: "keyword", dedent: true},

        // Command Options
        {regex: /\b(?:ARCHIVE|FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_NORMAL|FILE_ATTRIBUTE_OFFLINE|FILE_ATTRIBUTE_READONLY|FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_TEMPORARY|HIDDEN|HKCC|HKCR(32|64)?|HKCU(32|64)?|HKDD|HKEY_CLASSES_ROOT|HKEY_CURRENT_CONFIG|HKEY_CURRENT_USER|HKEY_DYN_DATA|HKEY_LOCAL_MACHINE|HKEY_PERFORMANCE_DATA|HKEY_USERS|HKLM(32|64)?|HKPD|HKU|IDABORT|IDCANCEL|IDD_DIR|IDD_INST|IDD_INSTFILES|IDD_LICENSE|IDD_SELCOM|IDD_UNINST|IDD_VERIFY|IDIGNORE|IDNO|IDOK|IDRETRY|IDYES|MB_ABORTRETRYIGNORE|MB_DEFBUTTON1|MB_DEFBUTTON2|MB_DEFBUTTON3|MB_DEFBUTTON4|MB_ICONEXCLAMATION|MB_ICONINFORMATION|MB_ICONQUESTION|MB_ICONSTOP|MB_OK|MB_OKCANCEL|MB_RETRYCANCEL|MB_RIGHT|MB_RTLREADING|MB_SETFOREGROUND|MB_TOPMOST|MB_USERICON|MB_YESNO|MB_YESNOCANCEL|NORMAL|OFFLINE|READONLY|SHCTX|SHELL_CONTEXT|SW_HIDE|SW_SHOWDEFAULT|SW_SHOWMAXIMIZED|SW_SHOWMINIMIZED|SW_SHOWNORMAL|SYSTEM|TEMPORARY)\b/, token: "atom"},
        {regex: /\b(?:admin|all|auto|both|bottom|bzip2|components|current|custom|directory|force|hide|highest|ifdiff|ifnewer|instfiles|lastused|leave|left|license|listonly|lzma|nevershow|none|normal|notset|right|show|silent|silentlog|textonly|top|try|un\.components|un\.custom|un\.directory|un\.instfiles|un\.license|uninstConfirm|user|Win10|Win7|Win8|WinVista|zlib)\b/, token: "builtin"},

        // LogicLib.nsh
        {regex: /\$\{(?:And(?:If(?:Not)?|Unless)|Break|Case(?:Else)?|Continue|Default|Do(?:Until|While)?|Else(?:If(?:Not)?|Unless)?|End(?:If|Select|Switch)|Exit(?:Do|For|While)|For(?:Each)?|If(?:Cmd|Not(?:Then)?|Then)?|Loop(?:Until|While)?|Or(?:If(?:Not)?|Unless)|Select|Switch|Unless|While)\}/, token: "variable-2", indent: true},

        // FileFunc.nsh
        {regex: /\$\{(?:BannerTrimPath|DirState|DriveSpace|Get(BaseName|Drives|ExeName|ExePath|FileAttributes|FileExt|FileName|FileVersion|Options|OptionsS|Parameters|Parent|Root|Size|Time)|Locate|RefreshShellIcons)\}/, token: "variable-2", dedent: true},

        // Memento.nsh
        {regex: /\$\{(?:Memento(?:Section(?:Done|End|Restore|Save)?|UnselectedSection))\}/, token: "variable-2", dedent: true},

        // TextFunc.nsh
        {regex: /\$\{(?:Config(?:Read|ReadS|Write|WriteS)|File(?:Join|ReadFromEnd|Recode)|Line(?:Find|Read|Sum)|Text(?:Compare|CompareS)|TrimNewLines)\}/, token: "variable-2", dedent: true},

        // WinVer.nsh
        {regex: /\$\{(?:(?:At(?:Least|Most)|Is)(?:ServicePack|Win(?:7|8|10|95|98|200(?:0|3|8(?:R2)?)|ME|NT4|Vista|XP))|Is(?:NT|Server))\}/, token: "variable", dedent: true},

        // WordFunc.nsh
        {regex: /\$\{(?:StrFilterS?|Version(?:Compare|Convert)|Word(?:AddS?|Find(?:(?:2|3)X)?S?|InsertS?|ReplaceS?))\}/, token: "variable-2", dedent: true},

        // x64.nsh
        {regex: /\$\{(?:RunningX64)\}/, token: "variable", dedent: true},
        {regex: /\$\{(?:Disable|Enable)X64FSRedirection\}/, token: "variable-2", dedent: true},

        // Line Comment
        {regex: /(#|;).*/, token: "comment"},

        // Block Comment
        {regex: /\/\*/, token: "comment", next: "comment"},

        // Operator
        {regex: /[-+\/*=<>!]+/, token: "operator"},

        // Variable
        {regex: /\$\w+/, token: "variable"},

        // Constant
        {regex: /\${[\w\.:-]+}/, token: "variable-2"},

        // Language String
        {regex: /\$\([\w\.:-]+\)/, token: "variable-3"}
      ],
      comment: [
        {regex: /.*?\*\//, token: "comment", next: "start"},
        {regex: /.*/, token: "comment"}
      ],
      meta: {
        electricInput: /^\s*((Function|PageEx|Section|Section(Group)?)End|(\!(endif|macroend))|\$\{(End(If|Unless|While)|Loop(Until)|Next)\})$/,
        blockCommentStart: "/*",
        blockCommentEnd: "*/",
        lineComment: ["#", ";"]
      }
    });

    CodeMirror.defineMIME("text/x-nsis", "nsis");

    // Define language
    LanguageManager.defineLanguage("nsis", {
        name: "NSIS",
        mode: "nsis",
        fileExtensions: ["nsh", "nsi"]
    });
});
<commit_msg>add NSIS 3.05 commands<commit_after>define(function (require, exports, module) {
    "use strict";

    // Declare variables
    var CodeMirror          = brackets.getModule("thirdparty/CodeMirror/lib/codemirror"),
        LanguageManager     = brackets.getModule("language/LanguageManager");

    // codemirror-nsis (https://github.com/idleberg/codemirror-nsis)
    CodeMirror.defineSimpleMode("nsis",{
      start:[
        // Numbers
        {regex: /(?:[+-]?)(?:0x[\d,a-f]+)|(?:0o[0-7]+)|(?:0b[0,1]+)|(?:\d+.?\d*)/, token: "number"},

        // Strings
        { regex: /"(?:[^\\"]|\\.)*"?/, token: "string" },
        { regex: /'(?:[^\\']|\\.)*'?/, token: "string" },
        { regex: /`(?:[^\\`]|\\.)*`?/, token: "string" },

        // Compile Time Commands
        {regex: /^\s*(?:\!(include|addincludedir|addplugindir|appendfile|cd|delfile|echo|error|execute|packhdr|pragma|finalize|getdllversion|gettlbversion|system|tempfile|warning|verbose|define|undef|insertmacro|macro|macroend|makensis|searchparse|searchreplace))\b/, token: "keyword"},

        // Conditional Compilation
        {regex: /^\s*(?:\!(if(?:n?def)?|ifmacron?def|macro))\b/, token: "keyword", indent: true},
        {regex: /^\s*(?:\!(else|endif|macroend))\b/, token: "keyword", dedent: true},

        // Runtime Commands
        {regex: /^\s*(?:Abort|AddBrandingImage|AddSize|AllowRootDirInstall|AllowSkipFiles|AutoCloseWindow|BGFont|BGGradient|BrandingText|BringToFront|Call|CallInstDLL|Caption|ChangeUI|CheckBitmap|ClearErrors|CompletedText|ComponentText|CopyFiles|CRCCheck|CreateDirectory|CreateFont|CreateShortCut|Delete|DeleteINISec|DeleteINIStr|DeleteRegKey|DeleteRegValue|DetailPrint|DetailsButtonText|DirText|DirVar|DirVerify|EnableWindow|EnumRegKey|EnumRegValue|Exch|Exec|ExecShell|ExecShellWait|ExecWait|ExpandEnvStrings|File|FileBufSize|FileClose|FileErrorText|FileOpen|FileRead|FileReadByte|FileReadUTF16LE|FileReadWord|FileWriteUTF16LE|FileSeek|FileWrite|FileWriteByte|FileWriteWord|FindClose|FindFirst|FindNext|FindWindow|FlushINI|GetCurInstType|GetCurrentAddress|GetDlgItem|GetDLLVersion|GetDLLVersionLocal|GetErrorLevel|GetFileTime|GetFileTimeLocal|GetFullPathName|GetFunctionAddress|GetInstDirError|GetLabelAddress|GetTempFileName|Goto|HideWindow|Icon|IfAbort|IfErrors|IfFileExists|IfRebootFlag|IfSilent|InitPluginsDir|InstallButtonText|InstallColors|InstallDir|InstallDirRegKey|InstProgressFlags|InstType|InstTypeGetText|InstTypeSetText|Int64Cmp|Int64CmpU|Int64Fmt|IntCmp|IntCmpU|IntFmt|IntOp|IntPtrCmp|IntPtrCmpU|IntPtrOp|IsWindow|LangString|LicenseBkColor|LicenseData|LicenseForceSelection|LicenseLangString|LicenseText|LoadAndSetImage|LoadLanguageFile|LockWindow|LogSet|LogText|ManifestDPIAware|ManifestLongPathAware|ManifestMaxVersionTested|ManifestSupportedOS|MessageBox|MiscButtonText|Name|Nop|OutFile|Page|PageCallbacks|PEAddResource|PEDllCharacteristics|PERemoveResource|PESubsysVer|Pop|Push|Quit|ReadEnvStr|ReadINIStr|ReadRegDWORD|ReadRegStr|Reboot|RegDLL|Rename|RequestExecutionLevel|ReserveFile|Return|RMDir|SearchPath|SectionGetFlags|SectionGetInstTypes|SectionGetSize|SectionGetText|SectionIn|SectionSetFlags|SectionSetInstTypes|SectionSetSize|SectionSetText|SendMessage|SetAutoClose|SetBrandingImage|SetCompress|SetCompressor|SetCompressorDictSize|SetCtlColors|SetCurInstType|SetDatablockOptimize|SetDateSave|SetDetailsPrint|SetDetailsView|SetErrorLevel|SetErrors|SetFileAttributes|SetFont|SetOutPath|SetOverwrite|SetRebootFlag|SetRegView|SetShellVarContext|SetSilent|ShowInstDetails|ShowUninstDetails|ShowWindow|SilentInstall|SilentUnInstall|Sleep|SpaceTexts|StrCmp|StrCmpS|StrCpy|StrLen|SubCaption|Unicode|UninstallButtonText|UninstallCaption|UninstallIcon|UninstallSubCaption|UninstallText|UninstPage|UnRegDLL|Var|VIAddVersionKey|VIFileVersion|VIProductVersion|WindowIcon|WriteINIStr|WriteRegBin|WriteRegDWORD|WriteRegExpandStr|WriteRegMultiStr|WriteRegNone|WriteRegStr|WriteUninstaller|XPStyle)\b/, token: "keyword"},
        {regex: /^\s*(?:Function|PageEx|Section(?:Group)?)\b/, token: "keyword", indent: true},
        {regex: /^\s*(?:(Function|PageEx|Section(?:Group)?)End)\b/, token: "keyword", dedent: true},

        // Command Options
        {regex: /\b(?:ARCHIVE|FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_NORMAL|FILE_ATTRIBUTE_OFFLINE|FILE_ATTRIBUTE_READONLY|FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_TEMPORARY|HIDDEN|HKCC|HKCR(32|64)?|HKCU(32|64)?|HKDD|HKEY_CLASSES_ROOT|HKEY_CURRENT_CONFIG|HKEY_CURRENT_USER|HKEY_DYN_DATA|HKEY_LOCAL_MACHINE|HKEY_PERFORMANCE_DATA|HKEY_USERS|HKLM(32|64)?|HKPD|HKU|IDABORT|IDCANCEL|IDD_DIR|IDD_INST|IDD_INSTFILES|IDD_LICENSE|IDD_SELCOM|IDD_UNINST|IDD_VERIFY|IDIGNORE|IDNO|IDOK|IDRETRY|IDYES|MB_ABORTRETRYIGNORE|MB_DEFBUTTON1|MB_DEFBUTTON2|MB_DEFBUTTON3|MB_DEFBUTTON4|MB_ICONEXCLAMATION|MB_ICONINFORMATION|MB_ICONQUESTION|MB_ICONSTOP|MB_OK|MB_OKCANCEL|MB_RETRYCANCEL|MB_RIGHT|MB_RTLREADING|MB_SETFOREGROUND|MB_TOPMOST|MB_USERICON|MB_YESNO|MB_YESNOCANCEL|NORMAL|OFFLINE|READONLY|SHCTX|SHELL_CONTEXT|SW_HIDE|SW_SHOWDEFAULT|SW_SHOWMAXIMIZED|SW_SHOWMINIMIZED|SW_SHOWNORMAL|SYSTEM|TEMPORARY)\b/, token: "atom"},
        {regex: /\b(?:admin|all|auto|both|bottom|bzip2|components|current|custom|directory|force|hide|highest|ifdiff|ifnewer|instfiles|lastused|leave|left|license|listonly|lzma|nevershow|none|normal|notset|right|show|silent|silentlog|textonly|top|try|un\.components|un\.custom|un\.directory|un\.instfiles|un\.license|uninstConfirm|user|Win10|Win7|Win8|WinVista|zlib)\b/, token: "builtin"},

        // LogicLib.nsh
        {regex: /\$\{(?:And(?:If(?:Not)?|Unless)|Break|Case(?:Else)?|Continue|Default|Do(?:Until|While)?|Else(?:If(?:Not)?|Unless)?|End(?:If|Select|Switch)|Exit(?:Do|For|While)|For(?:Each)?|If(?:Cmd|Not(?:Then)?|Then)?|Loop(?:Until|While)?|Or(?:If(?:Not)?|Unless)|Select|Switch|Unless|While)\}/, token: "variable-2", indent: true},

        // FileFunc.nsh
        {regex: /\$\{(?:BannerTrimPath|DirState|DriveSpace|Get(BaseName|Drives|ExeName|ExePath|FileAttributes|FileExt|FileName|FileVersion|Options|OptionsS|Parameters|Parent|Root|Size|Time)|Locate|RefreshShellIcons)\}/, token: "variable-2", dedent: true},

        // Memento.nsh
        {regex: /\$\{(?:Memento(?:Section(?:Done|End|Restore|Save)?|UnselectedSection))\}/, token: "variable-2", dedent: true},

        // TextFunc.nsh
        {regex: /\$\{(?:Config(?:Read|ReadS|Write|WriteS)|File(?:Join|ReadFromEnd|Recode)|Line(?:Find|Read|Sum)|Text(?:Compare|CompareS)|TrimNewLines)\}/, token: "variable-2", dedent: true},

        // WinVer.nsh
        {regex: /\$\{(?:(?:At(?:Least|Most)|Is)(?:ServicePack|Win(?:7|8|10|95|98|200(?:0|3|8(?:R2)?)|ME|NT4|Vista|XP))|Is(?:NT|Server))\}/, token: "variable", dedent: true},

        // WordFunc.nsh
        {regex: /\$\{(?:StrFilterS?|Version(?:Compare|Convert)|Word(?:AddS?|Find(?:(?:2|3)X)?S?|InsertS?|ReplaceS?))\}/, token: "variable-2", dedent: true},

        // x64.nsh
        {regex: /\$\{(?:RunningX64)\}/, token: "variable", dedent: true},
        {regex: /\$\{(?:Disable|Enable)X64FSRedirection\}/, token: "variable-2", dedent: true},

        // Line Comment
        {regex: /(#|;).*/, token: "comment"},

        // Block Comment
        {regex: /\/\*/, token: "comment", next: "comment"},

        // Operator
        {regex: /[-+\/*=<>!]+/, token: "operator"},

        // Variable
        {regex: /\$\w+/, token: "variable"},

        // Constant
        {regex: /\${[\w\.:-]+}/, token: "variable-2"},

        // Language String
        {regex: /\$\([\w\.:-]+\)/, token: "variable-3"}
      ],
      comment: [
        {regex: /.*?\*\//, token: "comment", next: "start"},
        {regex: /.*/, token: "comment"}
      ],
      meta: {
        electricInput: /^\s*((Function|PageEx|Section|Section(Group)?)End|(\!(endif|macroend))|\$\{(End(If|Unless|While)|Loop(Until)|Next)\})$/,
        blockCommentStart: "/*",
        blockCommentEnd: "*/",
        lineComment: ["#", ";"]
      }
    });

    CodeMirror.defineMIME("text/x-nsis", "nsis");

    // Define language
    LanguageManager.defineLanguage("nsis", {
        name: "NSIS",
        mode: "nsis",
        fileExtensions: ["nsh", "nsi"]
    });
});
<|endoftext|>


<commit_before>'use strict';

var strips = require('./strips');

var currentImage; // image element, hidden
var currentPolys; // specifically these are cut-strip polygons in pixel coords relative to currentImage

function loadImageFromFile(file, cb) {
  // Prevent any non-image file type from being read.
  if (!file.type.match(/image.*/)) {
    console.log('The dropped file is not an image: ', file.type);
    return;
  }

  var reader = new FileReader();
  reader.onload = function(e) {
    var image = new Image();
    image.onload = function() {
      cb(image);
    };
    image.src = e.target.result;
  };
  reader.readAsDataURL(file);
}

function renderPolys(canvas, polys) {
  var ctx = canvas.getContext('2d');

  ctx.fillStyle = 'black';
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  ctx.fillStyle = 'white';
  for (var i = 0; i < polys.length; i++) {
    var poly = polys[i];
    ctx.beginPath();
    for (var j = 0; j < poly.length; j++) {
      var p = poly[j];
      ctx.lineTo(p.x, p.y);
    }
    ctx.closePath();
    ctx.fill();
  }
}

function polysToSVG(image, polys, forPreview) {
  var framePadFrac = 0.05;
  var imageMaxDim = Math.max(image.width, image.height);
  var framePadPx = framePadFrac*imageMaxDim;
  var withFrameWidthPx = image.width + 2*framePadPx;
  var withFrameHeightPx = image.height + 2*framePadPx;

  // We give an extra mm of safe area padding beyond what Ponoko says, so we do 6mm instead of 5mm
  // These safeXXX vars are in mm units
  var safeAreaWidth = 788;
  var safeAreaHeight = 382;
  var safeOffset = 6;

  var polyScale = Math.min(safeAreaWidth/withFrameWidthPx, safeAreaHeight/withFrameHeightPx);
  var polyOffset = {
    x: safeOffset + framePadPx*polyScale,
    y: safeOffset + framePadPx*polyScale,
  };

  var totalWidth = polyScale*withFrameWidthPx + 2*safeOffset;
  var totalHeight = polyScale*withFrameHeightPx + 2*safeOffset;
  var svgWidth = totalWidth + 'mm';
  var svgHeight = totalHeight + 'mm';
  var viewBox = '0 0 ' + totalWidth + ' ' + totalHeight;

  var frameCutX = safeOffset;
  var frameCutY = safeOffset;
  var frameCutWidth = polyScale*withFrameWidthPx;
  var frameCutHeight = polyScale*withFrameHeightPx;

  var polyCutStyle;
  var frameCutStyle;
  if (forPreview) {
    // For web preview
    polyCutStyle = 'stroke="none" fill="white"';
    frameCutStyle = 'stroke="none" fill="black"';
  } else {
    // For real laser cutting
    var laserCutColor = 'rgb(0,0,255)';
    var laserCutStrokeWidth = '0.01';
    polyCutStyle = 'fill="none" stroke="' + laserCutColor + '" stroke-width="' + laserCutStrokeWidth + '"';
    frameCutStyle = polyCutStyle;
  }

  var polysPathData = '';
  for (var i = 0; i < currentPolys.length; i++) {
    var poly = currentPolys[i];

    for (var j = 0; j < poly.length; j++) {
      var p = poly[j];
      var tp = {
        x: p.x*polyScale + polyOffset.x,
        y: p.y*polyScale + polyOffset.y,
      };

      if (j === 0) {
        polysPathData += 'M'; // moveto absolute
      } else {
        polysPathData += 'L'; // lineto absolute
      }
      polysPathData += tp.x.toFixed(4) + ',' + tp.y.toFixed(4);
    }
    polysPathData += 'z'; // closepath
  }

  var exportText = '';
  exportText += '<?xml version="1.0" encoding="utf-8"?>\n<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n';
  exportText += '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="' + svgWidth + '" height="' + svgHeight + '" viewBox="' + viewBox + '">\n';
  var polyCutText = '  <path ' + polyCutStyle + ' d="' + polysPathData + '"/>\n';
  var frameCutText = '  <rect ' + frameCutStyle + ' x="' + frameCutX + '" y="' + frameCutX + '" width="' + frameCutWidth + '" height="' + frameCutHeight + '"/>\n';
  if (forPreview) {
    exportText += frameCutText;
    exportText += polyCutText;
  } else {
    exportText += polyCutText;
    exportText += frameCutText;
  }
  exportText += '</svg>';

  return exportText;
}

function setCurrentImage(image) {
    currentImage = image;

    console.log('Loaded image ' + image.width + 'x' + image.height);

    var canvas = document.createElement('canvas');
    canvas.width = image.width;
    canvas.height = image.height;

    var mainElem = document.getElementById('main');
    mainElem.insertBefore(canvas, mainElem.firstChild);

    var ctx = canvas.getContext('2d');
    ctx.drawImage(image, 0, 0, image.width, image.height);
    var imageData = ctx.getImageData(0, 0, image.width, image.height);
    console.log('Extracted ' + imageData.data.length + ' bytes of image data');

    console.log('Sampling ...');
    var testStrips = new strips.SimpleVerticalStrips(image.width, image.height, 118, 200);
    currentPolys = testStrips.sampleToPolys(imageData, 1);
    console.log('Finished sampling');
    renderPolys(canvas, currentPolys);
}

document.addEventListener('DOMContentLoaded', function() {
  var dropTarget = document;
  dropTarget.addEventListener('dragover', function(e){ e.preventDefault(); }, true);
  dropTarget.addEventListener('drop', function(e) {
    e.preventDefault();
    loadImageFromFile(e.dataTransfer.files[0], function(image) {
      setCurrentImage(image);
    });
  }, true);

  document.getElementById('preview-link').addEventListener('click', function(e) {
    if (!currentPolys) {
      return;
    }

    var svgData = polysToSVG(currentImage, currentPolys, true);

    this.href = 'data:image/svg+xml,' + encodeURIComponent(svgData);
  }, false);

  document.getElementById('download-link').addEventListener('click', function(e) {
    if (!currentPolys) {
      return;
    }

    var svgData = polysToSVG(currentImage, currentPolys, false);

    this.href = 'data:image/svg+xml,' + encodeURIComponent(svgData);
  }, false);
});
<commit_msg>Simulate beam width in preview SVG<commit_after>'use strict';

var strips = require('./strips');

var currentImage; // image element, hidden
var currentPolys; // specifically these are cut-strip polygons in pixel coords relative to currentImage

function loadImageFromFile(file, cb) {
  // Prevent any non-image file type from being read.
  if (!file.type.match(/image.*/)) {
    console.log('The dropped file is not an image: ', file.type);
    return;
  }

  var reader = new FileReader();
  reader.onload = function(e) {
    var image = new Image();
    image.onload = function() {
      cb(image);
    };
    image.src = e.target.result;
  };
  reader.readAsDataURL(file);
}

function renderPolys(canvas, polys) {
  var ctx = canvas.getContext('2d');

  ctx.fillStyle = 'black';
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  ctx.fillStyle = 'white';
  for (var i = 0; i < polys.length; i++) {
    var poly = polys[i];
    ctx.beginPath();
    for (var j = 0; j < poly.length; j++) {
      var p = poly[j];
      ctx.lineTo(p.x, p.y);
    }
    ctx.closePath();
    ctx.fill();
  }
}

function polysToSVG(image, polys, forPreview) {
  var framePadFrac = 0.05;
  var imageMaxDim = Math.max(image.width, image.height);
  var framePadPx = framePadFrac*imageMaxDim;
  var withFrameWidthPx = image.width + 2*framePadPx;
  var withFrameHeightPx = image.height + 2*framePadPx;

  // We give an extra mm of safe area padding beyond what Ponoko says, so we do 6mm instead of 5mm
  // These safeXXX vars are in mm units
  var safeAreaWidth = 788;
  var safeAreaHeight = 382;
  var safeOffset = 6;
  var beamWidth = 0.3; // Ponoko says 0.1-0.2mm on either side, so take average

  var polyScale = Math.min(safeAreaWidth/withFrameWidthPx, safeAreaHeight/withFrameHeightPx);
  var polyOffset = {
    x: safeOffset + framePadPx*polyScale,
    y: safeOffset + framePadPx*polyScale,
  };

  var totalWidth = polyScale*withFrameWidthPx + 2*safeOffset;
  var totalHeight = polyScale*withFrameHeightPx + 2*safeOffset;
  var svgWidth = totalWidth + 'mm';
  var svgHeight = totalHeight + 'mm';
  var viewBox = '0 0 ' + totalWidth + ' ' + totalHeight;

  var frameCutX = safeOffset;
  var frameCutY = safeOffset;
  var frameCutWidth = polyScale*withFrameWidthPx;
  var frameCutHeight = polyScale*withFrameHeightPx;

  var polyCutStyle;
  var frameCutStyle;
  if (forPreview) {
    // For web preview
    polyCutStyle = 'stroke="white" stroke-width="' + beamWidth + '" fill="white"'; // simulate slight enlargement due to beam width
    frameCutStyle = 'stroke="none" fill="black"';
  } else {
    // For real laser cutting
    var laserCutColor = 'rgb(0,0,255)';
    var laserCutStrokeWidth = '0.01';
    polyCutStyle = 'fill="none" stroke="' + laserCutColor + '" stroke-width="' + laserCutStrokeWidth + '"';
    frameCutStyle = polyCutStyle;
  }

  var polysPathData = '';
  for (var i = 0; i < currentPolys.length; i++) {
    var poly = currentPolys[i];

    for (var j = 0; j < poly.length; j++) {
      var p = poly[j];
      var tp = {
        x: p.x*polyScale + polyOffset.x,
        y: p.y*polyScale + polyOffset.y,
      };

      if (j === 0) {
        polysPathData += 'M'; // moveto absolute
      } else {
        polysPathData += 'L'; // lineto absolute
      }
      polysPathData += tp.x.toFixed(4) + ',' + tp.y.toFixed(4);
    }
    polysPathData += 'z'; // closepath
  }

  var exportText = '';
  exportText += '<?xml version="1.0" encoding="utf-8"?>\n<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n';
  exportText += '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="' + svgWidth + '" height="' + svgHeight + '" viewBox="' + viewBox + '">\n';
  var polyCutText = '  <path ' + polyCutStyle + ' d="' + polysPathData + '"/>\n';
  var frameCutText = '  <rect ' + frameCutStyle + ' x="' + frameCutX + '" y="' + frameCutX + '" width="' + frameCutWidth + '" height="' + frameCutHeight + '"/>\n';
  if (forPreview) {
    exportText += frameCutText;
    exportText += polyCutText;
  } else {
    exportText += polyCutText;
    exportText += frameCutText;
  }
  exportText += '</svg>';

  return exportText;
}

function setCurrentImage(image) {
    currentImage = image;

    console.log('Loaded image ' + image.width + 'x' + image.height);

    var canvas = document.createElement('canvas');
    canvas.width = image.width;
    canvas.height = image.height;

    var mainElem = document.getElementById('main');
    mainElem.insertBefore(canvas, mainElem.firstChild);

    var ctx = canvas.getContext('2d');
    ctx.drawImage(image, 0, 0, image.width, image.height);
    var imageData = ctx.getImageData(0, 0, image.width, image.height);
    console.log('Extracted ' + imageData.data.length + ' bytes of image data');

    console.log('Sampling ...');
    var testStrips = new strips.SimpleVerticalStrips(image.width, image.height, 118, 200);
    currentPolys = testStrips.sampleToPolys(imageData, 1);
    console.log('Finished sampling');
    renderPolys(canvas, currentPolys);
}

document.addEventListener('DOMContentLoaded', function() {
  var dropTarget = document;
  dropTarget.addEventListener('dragover', function(e){ e.preventDefault(); }, true);
  dropTarget.addEventListener('drop', function(e) {
    e.preventDefault();
    loadImageFromFile(e.dataTransfer.files[0], function(image) {
      setCurrentImage(image);
    });
  }, true);

  document.getElementById('preview-link').addEventListener('click', function(e) {
    if (!currentPolys) {
      return;
    }

    var svgData = polysToSVG(currentImage, currentPolys, true);

    this.href = 'data:image/svg+xml,' + encodeURIComponent(svgData);
  }, false);

  document.getElementById('download-link').addEventListener('click', function(e) {
    if (!currentPolys) {
      return;
    }

    var svgData = polysToSVG(currentImage, currentPolys, false);

    this.href = 'data:image/svg+xml,' + encodeURIComponent(svgData);
  }, false);
});
<|endoftext|>


<commit_before>var decks = ['meetup'];
var cards = [];
var queue = [];
var s;
var visible;

var said = [];
var skip = [];
var forget = [];

function escape_(s) {
    if (typeof s === 'string') {
        return s.replace(/&/g, '&')
                .replace(/>/g, '>')
                .replace(/</g, '<')
                .replace(/'/g, ''')
                .replace(/"/g, '"');
    } else {
        return s;
    }
}

function newCard(card) {
    return '
' + escape_(card.body) +
           '' + escape_(card.details) + '
';
}

function deck(items) {
    // Append this deck's cards to the global `cards` array.
    cards = cards.concat(items);

    // Append this deck's cards to the global `queue` array.
    queue = queue.concat(items);
}

function draw() {
    // TODO: If no more cards left, say that!
    visible = queue.shift();

    if (!visible) {
        $('main div').html("
You're on your own!
");
        $('main menu').hide();
        return;
    }

    var rememberedSaid = JSON.parse(localStorage.said || '[]');
    var rememberedForget = JSON.parse(localStorage.forget || '[]');
    if (rememberedSaid.indexOf(visible.id) > -1 ||
        rememberedForget.indexOf(visible.id) > -1) {
        // Draw another if we've already "said it" or "forget it."
        return draw();
    }

    if (visible) {
        $('main div').html(newCard(visible));
    }
}

for (var i = 0; i < decks.length; i++) {
    s = document.createElement('script');
    s.src = 'decks/' + decks[i] + '.js';
    if (i == 0) {
        s.onload = draw;
    }
    document.body.appendChild(s);
}

function saidIt() {
    said.push(visible);

    // Remember in localStorage.
    var remembered = JSON.parse(localStorage.said || '[]');
    remembered.push(visible.id);
    localStorage.said = JSON.stringify(remembered);

    draw();
}

function forgetIt() {
    forget.push(visible);

    // Remember in localStorage.
    var remembered = JSON.parse(localStorage.forget || '[]');
    remembered.push(visible.id);
    localStorage.forget = JSON.stringify(remembered);

    draw();
}

function skipIt() {
    skip.push(visible);

    // Push onto the end of the queue.
    queue.push(visible);
    draw();
}

function resetAll() {
    localStorage.clear();
    location.reload();
}

$(document.body).on('click', 'button', function() {
    switch ($(this).attr('class')) {
        case 'said-it':
            console.log('said', visible.id);
            saidIt(visible);
            break;
        case 'forget-it':
            console.log('forget', visible.id);
            forgetIt(visible);
            break;
        case 'skip-it':
            console.log('skip', visible.id);
            skipIt(visible);
            break;
        case 'view-all':
            console.log('view-all');
            break;
        case 'reset-all':
            console.log('reset-all');
            resetAll();
            break;
    }
    $('.show').removeClass('show');
}).on('click', 'h1', function() {
    location.reload();
});
<commit_msg>remove old comment<commit_after>var decks = ['meetup'];
var cards = [];
var queue = [];
var s;
var visible;

var said = [];
var skip = [];
var forget = [];

function escape_(s) {
    if (typeof s === 'string') {
        return s.replace(/&/g, '&')
                .replace(/>/g, '>')
                .replace(/</g, '<')
                .replace(/'/g, ''')
                .replace(/"/g, '"');
    } else {
        return s;
    }
}

function newCard(card) {
    return '
' + escape_(card.body) +
           '' + escape_(card.details) + '
';
}

function deck(items) {
    // Append this deck's cards to the global `cards` array.
    cards = cards.concat(items);

    // Append this deck's cards to the global `queue` array.
    queue = queue.concat(items);
}

function draw() {
    visible = queue.shift();

    if (!visible) {
        $('main div').html("
You're on your own!
");
        $('main menu').hide();
        return;
    }

    var rememberedSaid = JSON.parse(localStorage.said || '[]');
    var rememberedForget = JSON.parse(localStorage.forget || '[]');
    if (rememberedSaid.indexOf(visible.id) > -1 ||
        rememberedForget.indexOf(visible.id) > -1) {
        // Draw another if we've already "said it" or "forget it."
        return draw();
    }

    if (visible) {
        $('main div').html(newCard(visible));
    }
}

for (var i = 0; i < decks.length; i++) {
    s = document.createElement('script');
    s.src = 'decks/' + decks[i] + '.js';
    if (i == 0) {
        s.onload = draw;
    }
    document.body.appendChild(s);
}

function saidIt() {
    said.push(visible);

    // Remember in localStorage.
    var remembered = JSON.parse(localStorage.said || '[]');
    remembered.push(visible.id);
    localStorage.said = JSON.stringify(remembered);

    draw();
}

function forgetIt() {
    forget.push(visible);

    // Remember in localStorage.
    var remembered = JSON.parse(localStorage.forget || '[]');
    remembered.push(visible.id);
    localStorage.forget = JSON.stringify(remembered);

    draw();
}

function skipIt() {
    skip.push(visible);

    // Push onto the end of the queue.
    queue.push(visible);
    draw();
}

function resetAll() {
    localStorage.clear();
    location.reload();
}

$(document.body).on('click', 'button', function() {
    switch ($(this).attr('class')) {
        case 'said-it':
            console.log('said', visible.id);
            saidIt(visible);
            break;
        case 'forget-it':
            console.log('forget', visible.id);
            forgetIt(visible);
            break;
        case 'skip-it':
            console.log('skip', visible.id);
            skipIt(visible);
            break;
        case 'view-all':
            console.log('view-all');
            break;
        case 'reset-all':
            console.log('reset-all');
            resetAll();
            break;
    }
    $('.show').removeClass('show');
}).on('click', 'h1', function() {
    location.reload();
});
<|endoftext|>


<commit_before>// structure of rule
// {
//     template: 'templateName'
//     words: 'key words option1/option2/option3 option* option_'
//     args: []
//     ack: true/false (If acknowledge must be written into .text back
//     _break: true  // if break processing rules if match
//
//

/* jshint -W097 */// jshint strict:false
/*jslint node: true */
'use strict';

var utils           = require(__dirname + '/lib/utils'); // Get common adapter utils
//noinspection JSUnresolvedFunction
var adapter         = utils.adapter('text2command');
var model           = require(__dirname + '/admin/langModel');
var devicesControl  = require(__dirname + '/lib/devicesControl');
var simpleControl   = require(__dirname + '/lib/simpleControl');
var simpleAnswers   = require(__dirname + '/lib/simpleAnswers');

var rules;
var commandsCallbacks;
var systemConfig    = {};
var enums           = {};
var processTimeout  = null;
var processQueue    = [];

adapter.on('stateChange', function (id, state) {
    //noinspection JSUnresolvedVariable
    if (state && !state.ack && state.val) {
        if (id === adapter.namespace + '.text') {
            //noinspection JSUnresolvedVariable
            processText(state.val.toString(), sayIt);
        }
    } else
    //noinspection JSUnresolvedVariable
    if (state && id === adapter.config.processorId && state.ack) {
        // answer received
        if (processTimeout) {
            clearTimeout(processTimeout);
            processTimeout = null;
            var task = processQueue.shift();
            //noinspection JSUnresolvedVariable
            if (state.val) {
                if (task.callback) {
                    //noinspection JSUnresolvedVariable
                    task.callback((task.withLanguage ? task.language + ';' : '') + state.val);
                }
            } else {
                //noinspection JSUnresolvedVariable
                processText((task.withLanguage ? task.language + ';' : '') + task.command, task.callback, null, null, true);
            }
            setTimeout(useExternalProcessor, 0);
        }
    }
});

adapter.on('objectChange', function (id/*, obj*/) {
    if (id.substring(0, 5) === 'enum.') {
        // read all enums
        //noinspection JSUnresolvedFunction
        adapter.getEnums('', function (err, list) {
            enums = list;
            devicesControl.init(enums);
        });
    }
});

adapter.on('ready', function () {
    main();
    //noinspection JSUnresolvedFunction
    adapter.subscribeStates(adapter.namespace + '.text');
});

// New message arrived. obj is array with current messages
adapter.on('message', function (obj) {
    if (obj) {
        //noinspection JSUnresolvedVariable
        switch (obj.command) {
            case 'send':
                if (obj.message) {
                    //noinspection JSUnresolvedVariable
                    processText(typeof obj.message === 'object' ? obj.message.text : obj.message, function (res) {
                        var responseObj = JSON.parse(JSON.stringify(obj.message));
                        if (typeof responseObj !== 'object') responseObj = {text: responseObj};
                        responseObj.response = res;

                        if (obj.callback) {
                            //noinspection JSUnresolvedFunction, JSUnresolvedVariable
                            adapter.sendTo(obj.from, obj.command, responseObj, obj.callback);
                        }
                    }, JSON.parse(JSON.stringify(obj.message)), obj.from);
                }
                break;

            default:
                //noinspection JSUnresolvedVariable
                adapter.log.warn('Unknown command: ' + obj.command);
                break;
        }
    }

    return true;
});

function sayIt(text) {
    //noinspection JSUnresolvedFunction
    adapter.setState('response', text || '', function (err) {
        if (err) adapter.log.error(err);
    });

    //noinspection JSUnresolvedVariable
    if (!text || !adapter.config.sayitInstance) return;

    //noinspection JSUnresolvedVariable,JSUnresolvedFunction
    adapter.setForeignState(adapter.config.sayitInstance, text, function (err) {
        if (err) adapter.log.error(err);
    });
}

function useExternalProcessor() {
    if (!processTimeout && processQueue.length) {
        var task = processQueue[0];

        // send task to external processor
        //noinspection JSUnresolvedVariable,JSUnresolvedFunction
        adapter.setForeignState(adapter.config.processorId, JSON.stringify(task));

        // wait x seconds for answer
        //noinspection JSUnresolvedVariable
        processTimeout = setTimeout(function () {
            processTimeout = null;

            // no answer in given period
            var _task = processQueue.shift();

            // process with rules
            //noinspection JSUnresolvedVariable
            processText((_task.withLanguage ? _task.language + ';' : '') + _task.command, _task.callback, null, null, true);

            // process next
            useExternalProcessor();
        }, adapter.config.processorTimeout || 1000);
    }
}

function processText(cmd, cb, messageObj, from, afterProcessor) {
    adapter.log.info('processText: "' + cmd + '"');
    if (cmd === null || cmd === undefined) {
        adapter.log.error('processText: invalid command!');
        //noinspection JSUnresolvedFunction
        simpleAnswers.sayError(systemConfig.language, 'processText: invalid command!', null, null, function (result) {
            cb(result ? ((withLang ? lang + ';' : '') + result) : '');
        });
        return;
    }
    cmd = cmd.toString();
    var originalCmd = cmd;

    var withLang = false;
    var ix       = cmd.indexOf(';');
    var lang;

    cmd = cmd.toLowerCase();

    // extract language
    if (ix !== -1) {
        withLang    = true;
        lang        = cmd.substring(0, ix);
        cmd         = cmd.substring(ix + 1);
        originalCmd = originalCmd.substring(ix + 1);
    }
    lang = lang || adapter.config.language || systemConfig.language || 'en';

    // if desired processing by javascript
    //noinspection JSUnresolvedVariable
    if (!afterProcessor && adapter.config.processorId) {
        var task = messageObj || {};

        task.language =       lang;
        task.command =        originalCmd;
        task.withLanguage =   withLang;
        task.from =           from;
        task.callback =       cb;

        if (processQueue.length < 100) {
            processQueue.push(task);
            useExternalProcessor();
            return;
        } else {
            adapter.log.error('External process queue is full. Try to use rules.');
        }
    } else if (afterProcessor) {
        //noinspection JSUnresolvedVariable
        adapter.log.warn('Timeout for external processor: ' + adapter.config.processorId);
    }

    //noinspection JSUnresolvedFunction
    var matchedRules = model.findMatched(cmd, rules);

    var result = '';
    var count = matchedRules.length;
    for (var m = 0; m < matchedRules.length; m++) {

        //noinspection JSUnresolvedVariable
        if (model.commands[rules[matchedRules[m]].template] && model.commands[rules[matchedRules[m]].template].extractText) {
            //noinspection JSUnresolvedFunction,JSUnresolvedVariable
            cmd = simpleControl.extractText(cmd, originalCmd, rules[matchedRules[m]].words);
        }

        //noinspection JSUnresolvedVariable
        if (commandsCallbacks[rules[matchedRules[m]].template]) {
            //noinspection JSUnresolvedVariable
            commandsCallbacks[rules[matchedRules[m]].template](lang, cmd, rules[matchedRules[m]].args, rules[matchedRules[m]].ack, function (response) {
                adapter.log.info('Response: ' + response);

                // somehow combine answers
                if (response) {
                    //noinspection JSReferencingMutableVariableFromClosure
                    result += (result ? ', ' : '') + response;
                }

                if (!--count) {
                    if (cb) {
                        //noinspection JSReferencingMutableVariableFromClosure
                        cb(result ? ((withLang ? lang + ';' : '') + result) : '');
                    }
                    cb = null;
                }
            });
        }
        else {
            count--;
            if (rules[matchedRules[m]].ack) {
                //noinspection JSUnresolvedFunction
                result += (result ? ', ' : '') + simpleAnswers.getRandomPhrase(rules[matchedRules[m]].ack);
            }
        }
    }

    if (!matchedRules.length) {
        //noinspection JSUnresolvedFunction
        simpleAnswers.sayIDontUnderstand(lang, cmd, null, null, function (result) {
            if (cb) cb(result ? ((withLang ? lang + ';' : '') + result) : '');
            cb = null;
        });
    } else if (!count) {
        if (cb) cb(result ? ((withLang ? lang + ';' : '') + result) : '');
        cb = null;
    }
}

function main() {
    rules = adapter.config.rules || {};
    //noinspection JSUnresolvedVariable
    commandsCallbacks = {
        whatTimeIsIt:       simpleControl.sayTime,
        whatIsYourName:     simpleControl.sayName,
        outsideTemperature: simpleControl.sayTemperature,
        insideTemperature:  simpleControl.sayTemperature,
        functionOnOff:      devicesControl.controlByFunction,
        blindsUpDown:       devicesControl.controlBlinds,
        userDeviceControl:  simpleControl.userDeviceControl,
        sendText:           simpleControl.sendText,
/*        openLock:           openLock,*/
        userQuery:          simpleControl.userQuery
    };

    //noinspection JSUnresolvedFunction
    adapter.subscribeForeignObjects('enum.*');
    //noinspection JSUnresolvedVariable
    if (adapter.config.processorId) {
        //noinspection JSUnresolvedFunction,JSUnresolvedVariable
        adapter.subscribeForeignStates(adapter.config.processorId);
    }

    // read system configuration
    //noinspection JSUnresolvedFunction
    adapter.getForeignObject('system.config', function (err, obj) {
        //noinspection JSUnresolvedVariable
        systemConfig = (obj ? obj.common : {}) || {};
        simpleControl.init(systemConfig, adapter);
    });

    // read all enums
    //noinspection JSUnresolvedFunction
    adapter.getEnums('', function (err, list) {
        enums = list;
        devicesControl.init(enums, adapter);
    });
}

<commit_msg>fix util.js usage and use utils.Adapter<commit_after>// structure of rule
// {
//     template: 'templateName'
//     words: 'key words option1/option2/option3 option* option_'
//     args: []
//     ack: true/false (If acknowledge must be written into .text back
//     _break: true  // if break processing rules if match
//
//

/* jshint -W097 */// jshint strict:false
/*jslint node: true */
'use strict';

var utils           = require(__dirname + '/lib/utils'); // Get common adapter utils
//noinspection JSUnresolvedFunction
var adapter         = utils.Adapter('text2command');
var model           = require(__dirname + '/admin/langModel');
var devicesControl  = require(__dirname + '/lib/devicesControl');
var simpleControl   = require(__dirname + '/lib/simpleControl');
var simpleAnswers   = require(__dirname + '/lib/simpleAnswers');

var rules;
var commandsCallbacks;
var systemConfig    = {};
var enums           = {};
var processTimeout  = null;
var processQueue    = [];

adapter.on('stateChange', function (id, state) {
    //noinspection JSUnresolvedVariable
    if (state && !state.ack && state.val) {
        if (id === adapter.namespace + '.text') {
            //noinspection JSUnresolvedVariable
            processText(state.val.toString(), sayIt);
        }
    } else
    //noinspection JSUnresolvedVariable
    if (state && id === adapter.config.processorId && state.ack) {
        // answer received
        if (processTimeout) {
            clearTimeout(processTimeout);
            processTimeout = null;
            var task = processQueue.shift();
            //noinspection JSUnresolvedVariable
            if (state.val) {
                if (task.callback) {
                    //noinspection JSUnresolvedVariable
                    task.callback((task.withLanguage ? task.language + ';' : '') + state.val);
                }
            } else {
                //noinspection JSUnresolvedVariable
                processText((task.withLanguage ? task.language + ';' : '') + task.command, task.callback, null, null, true);
            }
            setTimeout(useExternalProcessor, 0);
        }
    }
});

adapter.on('objectChange', function (id/*, obj*/) {
    if (id.substring(0, 5) === 'enum.') {
        // read all enums
        //noinspection JSUnresolvedFunction
        adapter.getEnums('', function (err, list) {
            enums = list;
            devicesControl.init(enums);
        });
    }
});

adapter.on('ready', function () {
    main();
    //noinspection JSUnresolvedFunction
    adapter.subscribeStates(adapter.namespace + '.text');
});

// New message arrived. obj is array with current messages
adapter.on('message', function (obj) {
    if (obj) {
        //noinspection JSUnresolvedVariable
        switch (obj.command) {
            case 'send':
                if (obj.message) {
                    //noinspection JSUnresolvedVariable
                    processText(typeof obj.message === 'object' ? obj.message.text : obj.message, function (res) {
                        var responseObj = JSON.parse(JSON.stringify(obj.message));
                        if (typeof responseObj !== 'object') responseObj = {text: responseObj};
                        responseObj.response = res;

                        if (obj.callback) {
                            //noinspection JSUnresolvedFunction, JSUnresolvedVariable
                            adapter.sendTo(obj.from, obj.command, responseObj, obj.callback);
                        }
                    }, JSON.parse(JSON.stringify(obj.message)), obj.from);
                }
                break;

            default:
                //noinspection JSUnresolvedVariable
                adapter.log.warn('Unknown command: ' + obj.command);
                break;
        }
    }

    return true;
});

function sayIt(text) {
    //noinspection JSUnresolvedFunction
    adapter.setState('response', text || '', function (err) {
        if (err) adapter.log.error(err);
    });

    //noinspection JSUnresolvedVariable
    if (!text || !adapter.config.sayitInstance) return;

    //noinspection JSUnresolvedVariable,JSUnresolvedFunction
    adapter.setForeignState(adapter.config.sayitInstance, text, function (err) {
        if (err) adapter.log.error(err);
    });
}

function useExternalProcessor() {
    if (!processTimeout && processQueue.length) {
        var task = processQueue[0];

        // send task to external processor
        //noinspection JSUnresolvedVariable,JSUnresolvedFunction
        adapter.setForeignState(adapter.config.processorId, JSON.stringify(task));

        // wait x seconds for answer
        //noinspection JSUnresolvedVariable
        processTimeout = setTimeout(function () {
            processTimeout = null;

            // no answer in given period
            var _task = processQueue.shift();

            // process with rules
            //noinspection JSUnresolvedVariable
            processText((_task.withLanguage ? _task.language + ';' : '') + _task.command, _task.callback, null, null, true);

            // process next
            useExternalProcessor();
        }, adapter.config.processorTimeout || 1000);
    }
}

function processText(cmd, cb, messageObj, from, afterProcessor) {
    adapter.log.info('processText: "' + cmd + '"');
    if (cmd === null || cmd === undefined) {
        adapter.log.error('processText: invalid command!');
        //noinspection JSUnresolvedFunction
        simpleAnswers.sayError(systemConfig.language, 'processText: invalid command!', null, null, function (result) {
            cb(result ? ((withLang ? lang + ';' : '') + result) : '');
        });
        return;
    }
    cmd = cmd.toString();
    var originalCmd = cmd;

    var withLang = false;
    var ix       = cmd.indexOf(';');
    var lang;

    cmd = cmd.toLowerCase();

    // extract language
    if (ix !== -1) {
        withLang    = true;
        lang        = cmd.substring(0, ix);
        cmd         = cmd.substring(ix + 1);
        originalCmd = originalCmd.substring(ix + 1);
    }
    lang = lang || adapter.config.language || systemConfig.language || 'en';

    // if desired processing by javascript
    //noinspection JSUnresolvedVariable
    if (!afterProcessor && adapter.config.processorId) {
        var task = messageObj || {};

        task.language =       lang;
        task.command =        originalCmd;
        task.withLanguage =   withLang;
        task.from =           from;
        task.callback =       cb;

        if (processQueue.length < 100) {
            processQueue.push(task);
            useExternalProcessor();
            return;
        } else {
            adapter.log.error('External process queue is full. Try to use rules.');
        }
    } else if (afterProcessor) {
        //noinspection JSUnresolvedVariable
        adapter.log.warn('Timeout for external processor: ' + adapter.config.processorId);
    }

    //noinspection JSUnresolvedFunction
    var matchedRules = model.findMatched(cmd, rules);

    var result = '';
    var count = matchedRules.length;
    for (var m = 0; m < matchedRules.length; m++) {

        //noinspection JSUnresolvedVariable
        if (model.commands[rules[matchedRules[m]].template] && model.commands[rules[matchedRules[m]].template].extractText) {
            //noinspection JSUnresolvedFunction,JSUnresolvedVariable
            cmd = simpleControl.extractText(cmd, originalCmd, rules[matchedRules[m]].words);
        }

        //noinspection JSUnresolvedVariable
        if (commandsCallbacks[rules[matchedRules[m]].template]) {
            //noinspection JSUnresolvedVariable
            commandsCallbacks[rules[matchedRules[m]].template](lang, cmd, rules[matchedRules[m]].args, rules[matchedRules[m]].ack, function (response) {
                adapter.log.info('Response: ' + response);

                // somehow combine answers
                if (response) {
                    //noinspection JSReferencingMutableVariableFromClosure
                    result += (result ? ', ' : '') + response;
                }

                if (!--count) {
                    if (cb) {
                        //noinspection JSReferencingMutableVariableFromClosure
                        cb(result ? ((withLang ? lang + ';' : '') + result) : '');
                    }
                    cb = null;
                }
            });
        }
        else {
            count--;
            if (rules[matchedRules[m]].ack) {
                //noinspection JSUnresolvedFunction
                result += (result ? ', ' : '') + simpleAnswers.getRandomPhrase(rules[matchedRules[m]].ack);
            }
        }
    }

    if (!matchedRules.length) {
        //noinspection JSUnresolvedFunction
        simpleAnswers.sayIDontUnderstand(lang, cmd, null, null, function (result) {
            if (cb) cb(result ? ((withLang ? lang + ';' : '') + result) : '');
            cb = null;
        });
    } else if (!count) {
        if (cb) cb(result ? ((withLang ? lang + ';' : '') + result) : '');
        cb = null;
    }
}

function main() {
    rules = adapter.config.rules || {};
    //noinspection JSUnresolvedVariable
    commandsCallbacks = {
        whatTimeIsIt:       simpleControl.sayTime,
        whatIsYourName:     simpleControl.sayName,
        outsideTemperature: simpleControl.sayTemperature,
        insideTemperature:  simpleControl.sayTemperature,
        functionOnOff:      devicesControl.controlByFunction,
        blindsUpDown:       devicesControl.controlBlinds,
        userDeviceControl:  simpleControl.userDeviceControl,
        sendText:           simpleControl.sendText,
/*        openLock:           openLock,*/
        userQuery:          simpleControl.userQuery
    };

    //noinspection JSUnresolvedFunction
    adapter.subscribeForeignObjects('enum.*');
    //noinspection JSUnresolvedVariable
    if (adapter.config.processorId) {
        //noinspection JSUnresolvedFunction,JSUnresolvedVariable
        adapter.subscribeForeignStates(adapter.config.processorId);
    }

    // read system configuration
    //noinspection JSUnresolvedFunction
    adapter.getForeignObject('system.config', function (err, obj) {
        //noinspection JSUnresolvedVariable
        systemConfig = (obj ? obj.common : {}) || {};
        simpleControl.init(systemConfig, adapter);
    });

    // read all enums
    //noinspection JSUnresolvedFunction
    adapter.getEnums('', function (err, list) {
        enums = list;
        devicesControl.init(enums, adapter);
    });
}

<|endoftext|>


<commit_before>// http://jsfiddle.net/mekwall/up4nu/ modified to keep track of two sets fo nav items
// Cache selectors

var lastId
    , lastId2
    , primaryItems = document.querySelectorAll( '.sugar-nav-item' )
    , secondaryItems = document.querySelectorAll( '.sugar-nav-subitem' )
    ;

function getHrefValues( obj ) {

    var hrefArray = [];

    for ( var i = 0; i < obj.length; i++ ) {

        var href = obj[ i ].getAttribute( 'href' );

        hrefArray[ i ] = document.querySelectorAll( href )[ 0 ];
    }

    return hrefArray;
}

var primaryScrollItems = getHrefValues( primaryItems );
var secondaryScrollItems = getHrefValues( secondaryItems );

// var lastId, lastId2, topMenu = $('#sugar-nav'),
//     // All list items
//     menuItems = topMenu.find('a'),
//     primaryItems = topMenu.find('.sugar-nav-item'),
//     secondaryItems = topMenu.find('.sugar-nav-subitem'),
//     // Anchors corresponding to menu items
//     scrollPrimaryItems = primaryItems.map(function() {
//         var item = $($(this).attr('href'));
//         if (item.length) {
//             return item;
//         }
//     }),
//     scrollSecondaryItems = secondaryItems.map(function() {
//         var item = $($(this).attr('href'));
//         if (item.length) {
//             return item;
//         }
//     });
//
// // Bind click handler to menu items
// // so we can get a fancy scroll animation
// menuItems.click(function(e) {
//     var href = $(this).attr('href'),
//         offsetTop = href === '#' ? 0 : $(href).offset().top + 1;
//
//     $('html, body').stop().animate({
//         scrollTop: offsetTop
//     }, 300);
//     e.preventDefault();
// });

window.addEventListener( 'scroll', function( e ) {

    var currentPrimary = 0
        , currentSecondary = 0
        ;

    for ( var j = 0; j < primaryScrollItems.length; j++ ) {

        var primaryOffset = primaryScrollItems[ j ].getBoundingClientRect().top - 5;

        if ( primaryOffset < 0 ) {

            currentPrimary = j;

        }
        else {
            break;
        }
    }
    for ( var k = 0; k < secondaryScrollItems.length; k++ ) {

        var secondaryOffset = secondaryScrollItems[ k ].getBoundingClientRect().top - 5;

        if ( secondaryOffset < 0 ) {

            currentSecondary = k;
        }
        else {
            break;
        }
    }

    if ( lastId !== currentPrimary ) {

        if ( primaryItems[ lastId ]) {

            primaryItems[ lastId ].classList.remove( 'active' );
        }
        primaryItems[ currentPrimary ].classList.add( 'active' );

        lastId = currentPrimary;
    }
    if ( lastId2 !== currentSecondary ) {

        if ( secondaryItems[ lastId2 ]) {

            secondaryItems[ lastId2 ].classList.remove( 'active' );
        }
        secondaryItems[ currentSecondary ].classList.add( 'active' );

        lastId2 = currentSecondary;
    }
});<commit_msg>remove smooth scroll jump function<commit_after>// http://jsfiddle.net/mekwall/up4nu/ modified to keep track of two sets fo nav items
// Cache selectors

var lastId
    , lastId2
    , primaryItems = document.querySelectorAll( '.sugar-nav-item' )
    , secondaryItems = document.querySelectorAll( '.sugar-nav-subitem' )
    ;

function getHrefValues( obj ) {

    var hrefArray = [];

    for ( var i = 0; i < obj.length; i++ ) {

        var href = obj[ i ].getAttribute( 'href' );

        hrefArray[ i ] = document.querySelectorAll( href )[ 0 ];
    }

    return hrefArray;
}

var primaryScrollItems = getHrefValues( primaryItems );
var secondaryScrollItems = getHrefValues( secondaryItems );

window.addEventListener( 'scroll', function( e ) {

    var currentPrimary = 0
        , currentSecondary = 0
        ;

    for ( var j = 0; j < primaryScrollItems.length; j++ ) {

        var primaryOffset = primaryScrollItems[ j ].getBoundingClientRect().top - 5;

        if ( primaryOffset < 0 ) {

            currentPrimary = j;

        }
        else {
            break;
        }
    }
    for ( var k = 0; k < secondaryScrollItems.length; k++ ) {

        var secondaryOffset = secondaryScrollItems[ k ].getBoundingClientRect().top - 5;

        if ( secondaryOffset < 0 ) {

            currentSecondary = k;
        }
        else {
            break;
        }
    }

    if ( lastId !== currentPrimary ) {

        if ( primaryItems[ lastId ]) {

            primaryItems[ lastId ].classList.remove( 'active' );
        }
        primaryItems[ currentPrimary ].classList.add( 'active' );

        lastId = currentPrimary;
    }
    if ( lastId2 !== currentSecondary ) {

        if ( secondaryItems[ lastId2 ]) {

            secondaryItems[ lastId2 ].classList.remove( 'active' );
        }
        secondaryItems[ currentSecondary ].classList.add( 'active' );

        lastId2 = currentSecondary;
    }
});<|endoftext|>