<commit_before>var auth = require('./auth'),
    controllers = require('../controllers');

module.exports = function(app) {
    app.get('/', function(req, res) {
        res.render('index');
    });

    app.post('/login', auth.login);
    app.post('/logout', auth.logout);

    /* User-related routes START*/

    //Get all users
    app.get('/user', function(req, res) {
        res.render('index');
    });

    // Get user by ID
    app.get('/user/:id', function(req, res) {
        res.render('index');
    });

    // Register new user
    app.post('/user', controllers.usersController.registerUser);

    /*    User-related routes END   */
    /********************************/
    /* Category-related routes START*/

    // Get all categories
    app.get('/category', function(req, res) {
        res.render('index');
    });

    // Get category by ID
    app.get('/category/:id', function(req, res) {
        res.render('index');
    });

    // Create new Category
    app.post('/user', function(req, res) {
        res.render('index');
    });
    /* Category-related routes END*/
    /******************************/
    /* Offer-related routes Start*/

    // Get all Offers
    app.get('/offer', function(req, res) {
        res.render('index');
    });

    // Get Offer by ID
    app.get('/offer/:id', function(req, res) {
        res.render('index');
    });

    // Get all Offers by USER ID
    app.get('/offer/:userId', function(req, res) {
        res.render('index');
    });

    // Get all Offers by Category ID
    app.get('/offer/:categoryId', function(req, res) {
        res.render('index');
    });

    // Get latest Offers
    app.get('/offer/latest', function(req, res) {
        res.render('index');
    });

    // Get latest Offers by category
    app.get('/offer/latest/:categoryId', function(req, res) {
        res.render('index');
    });

    //Search Offers by title key word => TODO: receive an array of keywords
    app.get('/offer/:titleKeyWord', function(req, res) {
        res.render('index');
    });

    //Search Offers by description key word => TODO: receive an array of keywords
    app.get('/offer/latest/:descriptionKeyWord', function(req, res) {
        res.render('index');
    });

    // Create new Offer
    app.post('/offer', function(req, res) {
        res.render('index');
    });
    /* Offer-related routes END*/
    /******************************/
    /* Offer-related routes Start*/
};<commit_msg>added OfferController into the routes.js<commit_after>var auth = require('./auth'),
    controllers = require('../controllers');

module.exports = function(app) {
    app.get('/', function(req, res) {
        res.render('index');
    });

    app.post('/login', auth.login);
    app.post('/logout', auth.logout);

    /* User-related routes START*/

    //Get all users
    app.get('/user', function(req, res) {
        res.render('index');
    });

    // Get user by ID
    app.get('/user/:id', function(req, res) {
        res.render('index');
    });

    // Register new user
    app.post('/user', controllers.usersController.registerUser);

    /*    User-related routes END   */
    /********************************/
    /* Category-related routes START*/

    // Get all categories
    app.get('/category', function(req, res) {
        res.render('index');
    });

    // Get category by ID
    app.get('/category/:id', function(req, res) {
        res.render('index');
    });

    // Create new Category
    app.post('/user', function(req, res) {
        res.render('index');
    });
    /* Category-related routes END*/
    /******************************/
    /* Offer-related routes Start*/

    // Get all Offers
    app.get('/offer', function(req, res) {
        res.render('index');
    });

    // Get Offer by ID
    app.get('/offer/:id', controllers.offersController.getOfferById);

    // Get all Offers by USER ID
    app.get('/offer/:userId', function(req, res) {
        res.render('index');
    });

    // Get all Offers by Category ID
    app.get('/offer/:categoryId', function(req, res) {
        res.render('index');
    });

    // Get latest Offers
    app.get('/offer/latest', function(req, res) {
        res.render('index');
    });

    // Get latest Offers by category
    app.get('/offer/latest/:categoryId', function(req, res) {
        res.render('index');
    });

    //Search Offers by title key word => TODO: receive an array of keywords
    app.get('/offer/:titleKeyWord', function(req, res) {
        res.render('index');
    });

    //Search Offers by description key word => TODO: receive an array of keywords
    app.get('/offer/latest/:descriptionKeyWord', function(req, res) {
        res.render('index');
    });

    // Create new Offer
    app.post('/offer', controllers.offersController.createOffer);
    /* Offer-related routes END*/
    /******************************/
    /* Offer-related routes Start*/
};<|endoftext|>


<commit_before>// Copyright 2012 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// Flags: --allow-natives-syntax --smi-only-arrays --expose-gc
// Flags: --track-allocation-sites --noalways-opt

// Test element kind of objects.
// Since --smi-only-arrays affects builtins, its default setting at compile
// time sticks if built with snapshot.  If --smi-only-arrays is deactivated
// by default, only a no-snapshot build actually has smi-only arrays enabled
// in this test case.  Depending on whether smi-only arrays are actually
// enabled, this test takes the appropriate code path to check smi-only arrays.

// support_smi_only_arrays = %HasFastSmiElements(new Array(1,2,3,4,5,6,7,8));
support_smi_only_arrays = true;

if (support_smi_only_arrays) {
  print("Tests include smi-only arrays.");
} else {
  print("Tests do NOT include smi-only arrays.");
}

var elements_kind = {
  fast_smi_only            :  'fast smi only elements',
  fast                     :  'fast elements',
  fast_double              :  'fast double elements',
  dictionary               :  'dictionary elements',
  external_byte            :  'external byte elements',
  external_unsigned_byte   :  'external unsigned byte elements',
  external_short           :  'external short elements',
  external_unsigned_short  :  'external unsigned short elements',
  external_int             :  'external int elements',
  external_unsigned_int    :  'external unsigned int elements',
  external_float           :  'external float elements',
  external_double          :  'external double elements',
  external_pixel           :  'external pixel elements'
}

function getKind(obj) {
  if (%HasFastSmiElements(obj)) return elements_kind.fast_smi_only;
  if (%HasFastObjectElements(obj)) return elements_kind.fast;
  if (%HasFastDoubleElements(obj)) return elements_kind.fast_double;
  if (%HasDictionaryElements(obj)) return elements_kind.dictionary;
}

function isHoley(obj) {
  if (%HasFastHoleyElements(obj)) return true;
  return false;
}

function assertKind(expected, obj, name_opt) {
  if (!support_smi_only_arrays &&
      expected == elements_kind.fast_smi_only) {
    expected = elements_kind.fast;
  }
  assertEquals(expected, getKind(obj), name_opt);
}

function assertHoley(obj, name_opt) {
  assertEquals(true, isHoley(obj), name_opt);
}

function assertNotHoley(obj, name_opt) {
  assertEquals(false, isHoley(obj), name_opt);
}

if (support_smi_only_arrays) {
  obj = [];
  assertNotHoley(obj);
  assertKind(elements_kind.fast_smi_only, obj);

  obj = [1, 2, 3];
  assertNotHoley(obj);
  assertKind(elements_kind.fast_smi_only, obj);

  obj = new Array();
  assertNotHoley(obj);
  assertKind(elements_kind.fast_smi_only, obj);

  obj = new Array(0);
  assertNotHoley(obj);
  assertKind(elements_kind.fast_smi_only, obj);

  obj = new Array(2);
  assertHoley(obj);
  assertKind(elements_kind.fast_smi_only, obj);

  obj = new Array(1,2,3);
  assertNotHoley(obj);
  assertKind(elements_kind.fast_smi_only, obj);

  obj = new Array(1, "hi", 2, undefined);
  assertNotHoley(obj);
  assertKind(elements_kind.fast, obj);

  function fastliteralcase(literal, value) {
    literal[0] = value;
    return literal;
  }

  function get_standard_literal() {
    var literal = [1, 2, 3];
    return literal;
  }

  // Case: [1,2,3] as allocation site
  obj = fastliteralcase(get_standard_literal(), 1);
  assertKind(elements_kind.fast_smi_only, obj);
  obj = fastliteralcase(get_standard_literal(), 1.5);
  assertKind(elements_kind.fast_double, obj);
  obj = fastliteralcase(get_standard_literal(), 2);
  assertKind(elements_kind.fast_double, obj);

  // The test below is in a loop because arrays that live
  // at global scope without the chance of being recreated
  // don't have allocation site information attached.
  for (i = 0; i < 2; i++) {
    obj = fastliteralcase([5, 3, 2], 1.5);
    assertKind(elements_kind.fast_double, obj);
    obj = fastliteralcase([3, 6, 2], 1.5);
    assertKind(elements_kind.fast_double, obj);
    obj = fastliteralcase([2, 6, 3], 2);
    assertKind(elements_kind.fast_smi_only, obj);
  }

  // Verify that we will not pretransition the double->fast path.
  obj = fastliteralcase(get_standard_literal(), "elliot");
  assertKind(elements_kind.fast, obj);
  obj = fastliteralcase(get_standard_literal(), 3);
  assertKind(elements_kind.fast, obj);

  // Make sure this works in crankshafted code too.
  %OptimizeFunctionOnNextCall(get_standard_literal);
  get_standard_literal();
  obj = get_standard_literal();
  assertKind(elements_kind.fast, obj);

  function fastliteralcase_smifast(value) {
    var literal = [1, 2, 3, 4];
    literal[0] = value;
    return literal;
  }

  obj = fastliteralcase_smifast(1);
  assertKind(elements_kind.fast_smi_only, obj);
  obj = fastliteralcase_smifast("carter");
  assertKind(elements_kind.fast, obj);
  obj = fastliteralcase_smifast(2);
  assertKind(elements_kind.fast, obj);

  // Case: make sure transitions from packed to holey are tracked
  function fastliteralcase_smiholey(index, value) {
    var literal = [1, 2, 3, 4];
    literal[index] = value;
    return literal;
  }

  obj = fastliteralcase_smiholey(5, 1);
  assertKind(elements_kind.fast_smi_only, obj);
  assertHoley(obj);
  obj = fastliteralcase_smiholey(0, 1);
  assertKind(elements_kind.fast_smi_only, obj);
  assertHoley(obj);

  function newarraycase_smidouble(value) {
    var a = new Array();
    a[0] = value;
    return a;
  }

  // Case: new Array() as allocation site, smi->double
  obj = newarraycase_smidouble(1);
  assertKind(elements_kind.fast_smi_only, obj);
  obj = newarraycase_smidouble(1.5);
  assertKind(elements_kind.fast_double, obj);
  obj = newarraycase_smidouble(2);
  assertKind(elements_kind.fast_double, obj);

  function newarraycase_smiobj(value) {
    var a = new Array();
    a[0] = value;
    return a;
  }

  // Case: new Array() as allocation site, smi->fast
  obj = newarraycase_smiobj(1);
  assertKind(elements_kind.fast_smi_only, obj);
  obj = newarraycase_smiobj("gloria");
  assertKind(elements_kind.fast, obj);
  obj = newarraycase_smiobj(2);
  assertKind(elements_kind.fast, obj);

  function newarraycase_length_smidouble(value) {
    var a = new Array(3);
    a[0] = value;
    return a;
  }

  // Case: new Array(length) as allocation site
  obj = newarraycase_length_smidouble(1);
  assertKind(elements_kind.fast_smi_only, obj);
  obj = newarraycase_length_smidouble(1.5);
  assertKind(elements_kind.fast_double, obj);
  obj = newarraycase_length_smidouble(2);
  assertKind(elements_kind.fast_double, obj);

  // Try to continue the transition to fast object. This won't work for
  // constructed arrays because constructor dispatch is done on the
  // elements kind, and a DOUBLE array constructor won't create an allocation
  // memento.
  obj = newarraycase_length_smidouble("coates");
  assertKind(elements_kind.fast, obj);
  obj = newarraycase_length_smidouble(2);
  assertKind(elements_kind.fast_double, obj);

  function newarraycase_length_smiobj(value) {
    var a = new Array(3);
    a[0] = value;
    return a;
  }

  // Case: new Array(<length>) as allocation site, smi->fast
  obj = newarraycase_length_smiobj(1);
  assertKind(elements_kind.fast_smi_only, obj);
  obj = newarraycase_length_smiobj("gloria");
  assertKind(elements_kind.fast, obj);
  obj = newarraycase_length_smiobj(2);
  assertKind(elements_kind.fast, obj);

  function newarraycase_list_smidouble(value) {
    var a = new Array(1, 2, 3);
    a[0] = value;
    return a;
  }

  obj = newarraycase_list_smidouble(1);
  assertKind(elements_kind.fast_smi_only, obj);
  obj = newarraycase_list_smidouble(1.5);
  assertKind(elements_kind.fast_double, obj);
  obj = newarraycase_list_smidouble(2);
  assertKind(elements_kind.fast_double, obj);

  function newarraycase_list_smiobj(value) {
    var a = new Array(4, 5, 6);
    a[0] = value;
    return a;
  }

  obj = newarraycase_list_smiobj(1);
  assertKind(elements_kind.fast_smi_only, obj);
  obj = newarraycase_list_smiobj("coates");
  assertKind(elements_kind.fast, obj);
  obj = newarraycase_list_smiobj(2);
  assertKind(elements_kind.fast, obj);

  // Case: array constructor calls with out of date feedback.
  // The boilerplate should incorporate all feedback, but the input array
  // should be minimally transitioned based on immediate need.
  (function() {
    function foo(i) {
      // We have two cases, one for literals one for constructed arrays.
      var a = (i == 0)
        ? [1, 2, 3]
        : new Array(1, 2, 3);
      return a;
    }

    for (i = 0; i < 2; i++) {
      a = foo(i);
      b = foo(i);
      b[5] = 1;  // boilerplate goes holey
      assertHoley(foo(i));
      a[0] = 3.5;  // boilerplate goes holey double
      assertKind(elements_kind.fast_double, a);
      assertNotHoley(a);
      c = foo(i);
      assertKind(elements_kind.fast_double, c);
      assertHoley(c);
    }
  })();

  function newarraycase_onearg(len, value) {
    var a = new Array(len);
    a[0] = value;
    return a;
  }

  obj = newarraycase_onearg(5, 3.5);
  assertKind(elements_kind.fast_double, obj);
  obj = newarraycase_onearg(10, 5);
  assertKind(elements_kind.fast_double, obj);
  obj = newarraycase_onearg(0, 5);
  assertKind(elements_kind.fast_double, obj);
  // Now pass a length that forces the dictionary path.
  obj = newarraycase_onearg(100000, 5);
  assertKind(elements_kind.dictionary, obj);
  assertTrue(obj.length == 100000);

  // Verify that cross context calls work
  var realmA = Realm.current();
  var realmB = Realm.create();
  assertEquals(0, realmA);
  assertEquals(1, realmB);

  function instanceof_check(type) {
    assertTrue(new type() instanceof type);
    assertTrue(new type(5) instanceof type);
    assertTrue(new type(1,2,3) instanceof type);
  }

  function instanceof_check2(type) {
    assertTrue(new type() instanceof type);
    assertTrue(new type(5) instanceof type);
    assertTrue(new type(1,2,3) instanceof type);
  }

  var realmBArray = Realm.eval(realmB, "Array");
  instanceof_check(Array);
  instanceof_check(realmBArray);

  // instanceof_check2 is here because the call site goes through a state.
  // Since instanceof_check(Array) was first called with the current context
  // Array function, it went from (uninit->Array) then (Array->megamorphic).
  // We'll get a different state traversal if we start with realmBArray.
  // It'll go (uninit->realmBArray) then (realmBArray->megamorphic). Recognize
  // that state "Array" implies an AllocationSite is present, and code is
  // configured to use it.
  instanceof_check2(realmBArray);
  instanceof_check2(Array);

  %OptimizeFunctionOnNextCall(instanceof_check);

  // No de-opt will occur because HCallNewArray wasn't selected, on account of
  // the call site not being monomorphic to Array.
  instanceof_check(Array);
  assertOptimized(instanceof_check);
  instanceof_check(realmBArray);
  assertOptimized(instanceof_check);

  // Try to optimize again, but first clear all type feedback, and allow it
  // to be monomorphic on first call. Only after crankshafting do we introduce
  // realmBArray. This should deopt the method.
  %DeoptimizeFunction(instanceof_check);
  %ClearFunctionTypeFeedback(instanceof_check);
  instanceof_check(Array);
  instanceof_check(Array);
  %OptimizeFunctionOnNextCall(instanceof_check);
  instanceof_check(Array);
  assertOptimized(instanceof_check);

  instanceof_check(realmBArray);
  assertUnoptimized(instanceof_check);
}
<commit_msg>Allocation site tests aren't compatible with GcStress mode.<commit_after>// Copyright 2012 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// Flags: --allow-natives-syntax --smi-only-arrays --expose-gc
// Flags: --track-allocation-sites --noalways-opt

// Test element kind of objects.
// Since --smi-only-arrays affects builtins, its default setting at compile
// time sticks if built with snapshot.  If --smi-only-arrays is deactivated
// by default, only a no-snapshot build actually has smi-only arrays enabled
// in this test case.  Depending on whether smi-only arrays are actually
// enabled, this test takes the appropriate code path to check smi-only arrays.

// Reset the GC stress mode to be off. Needed because AllocationMementos only
// live for one gc, so a gc that happens in certain fragile areas of the test
// can break assumptions.
%SetFlags("--gc-interval=-1")

// support_smi_only_arrays = %HasFastSmiElements(new Array(1,2,3,4,5,6,7,8));
support_smi_only_arrays = true;

if (support_smi_only_arrays) {
  print("Tests include smi-only arrays.");
} else {
  print("Tests do NOT include smi-only arrays.");
}

var elements_kind = {
  fast_smi_only            :  'fast smi only elements',
  fast                     :  'fast elements',
  fast_double              :  'fast double elements',
  dictionary               :  'dictionary elements',
  external_byte            :  'external byte elements',
  external_unsigned_byte   :  'external unsigned byte elements',
  external_short           :  'external short elements',
  external_unsigned_short  :  'external unsigned short elements',
  external_int             :  'external int elements',
  external_unsigned_int    :  'external unsigned int elements',
  external_float           :  'external float elements',
  external_double          :  'external double elements',
  external_pixel           :  'external pixel elements'
}

function getKind(obj) {
  if (%HasFastSmiElements(obj)) return elements_kind.fast_smi_only;
  if (%HasFastObjectElements(obj)) return elements_kind.fast;
  if (%HasFastDoubleElements(obj)) return elements_kind.fast_double;
  if (%HasDictionaryElements(obj)) return elements_kind.dictionary;
}

function isHoley(obj) {
  if (%HasFastHoleyElements(obj)) return true;
  return false;
}

function assertKind(expected, obj, name_opt) {
  if (!support_smi_only_arrays &&
      expected == elements_kind.fast_smi_only) {
    expected = elements_kind.fast;
  }
  assertEquals(expected, getKind(obj), name_opt);
}

function assertHoley(obj, name_opt) {
  assertEquals(true, isHoley(obj), name_opt);
}

function assertNotHoley(obj, name_opt) {
  assertEquals(false, isHoley(obj), name_opt);
}

if (support_smi_only_arrays) {
  obj = [];
  assertNotHoley(obj);
  assertKind(elements_kind.fast_smi_only, obj);

  obj = [1, 2, 3];
  assertNotHoley(obj);
  assertKind(elements_kind.fast_smi_only, obj);

  obj = new Array();
  assertNotHoley(obj);
  assertKind(elements_kind.fast_smi_only, obj);

  obj = new Array(0);
  assertNotHoley(obj);
  assertKind(elements_kind.fast_smi_only, obj);

  obj = new Array(2);
  assertHoley(obj);
  assertKind(elements_kind.fast_smi_only, obj);

  obj = new Array(1,2,3);
  assertNotHoley(obj);
  assertKind(elements_kind.fast_smi_only, obj);

  obj = new Array(1, "hi", 2, undefined);
  assertNotHoley(obj);
  assertKind(elements_kind.fast, obj);

  function fastliteralcase(literal, value) {
    literal[0] = value;
    return literal;
  }

  function get_standard_literal() {
    var literal = [1, 2, 3];
    return literal;
  }

  // Case: [1,2,3] as allocation site
  obj = fastliteralcase(get_standard_literal(), 1);
  assertKind(elements_kind.fast_smi_only, obj);
  obj = fastliteralcase(get_standard_literal(), 1.5);
  assertKind(elements_kind.fast_double, obj);
  obj = fastliteralcase(get_standard_literal(), 2);
  assertKind(elements_kind.fast_double, obj);

  // The test below is in a loop because arrays that live
  // at global scope without the chance of being recreated
  // don't have allocation site information attached.
  for (i = 0; i < 2; i++) {
    obj = fastliteralcase([5, 3, 2], 1.5);
    assertKind(elements_kind.fast_double, obj);
    obj = fastliteralcase([3, 6, 2], 1.5);
    assertKind(elements_kind.fast_double, obj);
    obj = fastliteralcase([2, 6, 3], 2);
    assertKind(elements_kind.fast_smi_only, obj);
  }

  // Verify that we will not pretransition the double->fast path.
  obj = fastliteralcase(get_standard_literal(), "elliot");
  assertKind(elements_kind.fast, obj);
  obj = fastliteralcase(get_standard_literal(), 3);
  assertKind(elements_kind.fast, obj);

  // Make sure this works in crankshafted code too.
  %OptimizeFunctionOnNextCall(get_standard_literal);
  get_standard_literal();
  obj = get_standard_literal();
  assertKind(elements_kind.fast, obj);

  function fastliteralcase_smifast(value) {
    var literal = [1, 2, 3, 4];
    literal[0] = value;
    return literal;
  }

  obj = fastliteralcase_smifast(1);
  assertKind(elements_kind.fast_smi_only, obj);
  obj = fastliteralcase_smifast("carter");
  assertKind(elements_kind.fast, obj);
  obj = fastliteralcase_smifast(2);
  assertKind(elements_kind.fast, obj);

  // Case: make sure transitions from packed to holey are tracked
  function fastliteralcase_smiholey(index, value) {
    var literal = [1, 2, 3, 4];
    literal[index] = value;
    return literal;
  }

  obj = fastliteralcase_smiholey(5, 1);
  assertKind(elements_kind.fast_smi_only, obj);
  assertHoley(obj);
  obj = fastliteralcase_smiholey(0, 1);
  assertKind(elements_kind.fast_smi_only, obj);
  assertHoley(obj);

  function newarraycase_smidouble(value) {
    var a = new Array();
    a[0] = value;
    return a;
  }

  // Case: new Array() as allocation site, smi->double
  obj = newarraycase_smidouble(1);
  assertKind(elements_kind.fast_smi_only, obj);
  obj = newarraycase_smidouble(1.5);
  assertKind(elements_kind.fast_double, obj);
  obj = newarraycase_smidouble(2);
  assertKind(elements_kind.fast_double, obj);

  function newarraycase_smiobj(value) {
    var a = new Array();
    a[0] = value;
    return a;
  }

  // Case: new Array() as allocation site, smi->fast
  obj = newarraycase_smiobj(1);
  assertKind(elements_kind.fast_smi_only, obj);
  obj = newarraycase_smiobj("gloria");
  assertKind(elements_kind.fast, obj);
  obj = newarraycase_smiobj(2);
  assertKind(elements_kind.fast, obj);

  function newarraycase_length_smidouble(value) {
    var a = new Array(3);
    a[0] = value;
    return a;
  }

  // Case: new Array(length) as allocation site
  obj = newarraycase_length_smidouble(1);
  assertKind(elements_kind.fast_smi_only, obj);
  obj = newarraycase_length_smidouble(1.5);
  assertKind(elements_kind.fast_double, obj);
  obj = newarraycase_length_smidouble(2);
  assertKind(elements_kind.fast_double, obj);

  // Try to continue the transition to fast object. This won't work for
  // constructed arrays because constructor dispatch is done on the
  // elements kind, and a DOUBLE array constructor won't create an allocation
  // memento.
  obj = newarraycase_length_smidouble("coates");
  assertKind(elements_kind.fast, obj);
  obj = newarraycase_length_smidouble(2);
  assertKind(elements_kind.fast_double, obj);

  function newarraycase_length_smiobj(value) {
    var a = new Array(3);
    a[0] = value;
    return a;
  }

  // Case: new Array(<length>) as allocation site, smi->fast
  obj = newarraycase_length_smiobj(1);
  assertKind(elements_kind.fast_smi_only, obj);
  obj = newarraycase_length_smiobj("gloria");
  assertKind(elements_kind.fast, obj);
  obj = newarraycase_length_smiobj(2);
  assertKind(elements_kind.fast, obj);

  function newarraycase_list_smidouble(value) {
    var a = new Array(1, 2, 3);
    a[0] = value;
    return a;
  }

  obj = newarraycase_list_smidouble(1);
  assertKind(elements_kind.fast_smi_only, obj);
  obj = newarraycase_list_smidouble(1.5);
  assertKind(elements_kind.fast_double, obj);
  obj = newarraycase_list_smidouble(2);
  assertKind(elements_kind.fast_double, obj);

  function newarraycase_list_smiobj(value) {
    var a = new Array(4, 5, 6);
    a[0] = value;
    return a;
  }

  obj = newarraycase_list_smiobj(1);
  assertKind(elements_kind.fast_smi_only, obj);
  obj = newarraycase_list_smiobj("coates");
  assertKind(elements_kind.fast, obj);
  obj = newarraycase_list_smiobj(2);
  assertKind(elements_kind.fast, obj);

  // Case: array constructor calls with out of date feedback.
  // The boilerplate should incorporate all feedback, but the input array
  // should be minimally transitioned based on immediate need.
  (function() {
    function foo(i) {
      // We have two cases, one for literals one for constructed arrays.
      var a = (i == 0)
        ? [1, 2, 3]
        : new Array(1, 2, 3);
      return a;
    }

    for (i = 0; i < 2; i++) {
      a = foo(i);
      b = foo(i);
      b[5] = 1;  // boilerplate goes holey
      assertHoley(foo(i));
      a[0] = 3.5;  // boilerplate goes holey double
      assertKind(elements_kind.fast_double, a);
      assertNotHoley(a);
      c = foo(i);
      assertKind(elements_kind.fast_double, c);
      assertHoley(c);
    }
  })();

  function newarraycase_onearg(len, value) {
    var a = new Array(len);
    a[0] = value;
    return a;
  }

  obj = newarraycase_onearg(5, 3.5);
  assertKind(elements_kind.fast_double, obj);
  obj = newarraycase_onearg(10, 5);
  assertKind(elements_kind.fast_double, obj);
  obj = newarraycase_onearg(0, 5);
  assertKind(elements_kind.fast_double, obj);
  // Now pass a length that forces the dictionary path.
  obj = newarraycase_onearg(100000, 5);
  assertKind(elements_kind.dictionary, obj);
  assertTrue(obj.length == 100000);

  // Verify that cross context calls work
  var realmA = Realm.current();
  var realmB = Realm.create();
  assertEquals(0, realmA);
  assertEquals(1, realmB);

  function instanceof_check(type) {
    assertTrue(new type() instanceof type);
    assertTrue(new type(5) instanceof type);
    assertTrue(new type(1,2,3) instanceof type);
  }

  function instanceof_check2(type) {
    assertTrue(new type() instanceof type);
    assertTrue(new type(5) instanceof type);
    assertTrue(new type(1,2,3) instanceof type);
  }

  var realmBArray = Realm.eval(realmB, "Array");
  instanceof_check(Array);
  instanceof_check(realmBArray);

  // instanceof_check2 is here because the call site goes through a state.
  // Since instanceof_check(Array) was first called with the current context
  // Array function, it went from (uninit->Array) then (Array->megamorphic).
  // We'll get a different state traversal if we start with realmBArray.
  // It'll go (uninit->realmBArray) then (realmBArray->megamorphic). Recognize
  // that state "Array" implies an AllocationSite is present, and code is
  // configured to use it.
  instanceof_check2(realmBArray);
  instanceof_check2(Array);

  %OptimizeFunctionOnNextCall(instanceof_check);

  // No de-opt will occur because HCallNewArray wasn't selected, on account of
  // the call site not being monomorphic to Array.
  instanceof_check(Array);
  assertOptimized(instanceof_check);
  instanceof_check(realmBArray);
  assertOptimized(instanceof_check);

  // Try to optimize again, but first clear all type feedback, and allow it
  // to be monomorphic on first call. Only after crankshafting do we introduce
  // realmBArray. This should deopt the method.
  %DeoptimizeFunction(instanceof_check);
  %ClearFunctionTypeFeedback(instanceof_check);
  instanceof_check(Array);
  instanceof_check(Array);
  %OptimizeFunctionOnNextCall(instanceof_check);
  instanceof_check(Array);
  assertOptimized(instanceof_check);

  instanceof_check(realmBArray);
  assertUnoptimized(instanceof_check);
}
<|endoftext|>


<commit_before>var async = require('async');
var util = require('util');

module.exports = function(app, passport, auth, config, acl, public_api) {

    var vendors = require('../app/controllers/vendors');

    /**
     * Middleware authentication using vergin-acl
     * -------------------------
     *
     * Function accepts action and resource params. Uses req.user.role to perform a check
     * assigns quest role if no other roles exist
     *
     * @see config/acl_roles.js for roles
     *
     * @note vergin-acl doesn't support middleware out of the box, so we wrap its check in our own middleware
     *
     * @todo move to middleware... !
     *
     */

    function isUserAllowed(action, resource) {
        return function(req, res, next) {

            // add quest role for non-logged in users.
            if (!req.user || !req.user.role) {
                req.user = {
                    role: 'guest'
                };
            }

            console.info(util.format('Can user role %s %s %s?', req.user.role, action, resource));

            // perform acl query on resource + action
            // responds with 401 and message if user doesn't have permissions
            acl.query(req.user.role, resource, action, function(err, allowed) {
                if (err) throw (err);
                if (allowed) {
                    next();
                } else {
                    return res.failure(util.format('You are not authorized to %s %s', action, resource), 401);
                }
            });
        };
    }

    /**
     * USERS / AUTH routes
     * -------------------------
     */
    var users = require('../app/controllers/users');
    app.post('/api/v1/auth/login', function(req, res, next) {
        // here we fun a function which calls another function... this gives us access to req, res, and next
        // however there must be a cleaner way to do this
        // @todo refactor
        users.signin(req, res, next, passport);
    });
    app.get('/api/v1/auth/logout', users.signout);
    app.post('/api/v1/auth/logout', users.signout); // makes testing easier with postman

    /**
     * USERS / GENERAL routes
     * -------------------------
     */
    //var users = require('../app/controllers/users');
    app.get('/api/v1/users', isUserAllowed('list', 'users'), users.all);
    app.post('/api/v1/users', isUserAllowed('create', 'users'), users.create);
    // @todo check for vendor, is this their approved sales rep?
    app.get('/api/v1/users/:userId', isUserAllowed('view', 'users'), users.show);

    // sales rep and vendor = edit their own info
    app.put('/api/v1/users/:userId', isUserAllowed('update', 'users'), users.update);
    app.del('/api/v1/users/:userId', isUserAllowed('delete', 'users'), users.destroy);

    // update user role
    app.put('/api/v1/users/:userId/role', isUserAllowed('updateRole', 'users'), users.updateRole);

    // update user password
    app.put('/api/v1/users/:userId/password', isUserAllowed('updatePassword', 'users'), users.updatePassword);
    app.put('/api/v1/users/:userId/reset_password', users.resetPassword);

    // get users vendors
    app.get('/api/v1/users/:userId/vendors', isUserAllowed('list', 'vendors'), vendors.listForUser);
    app.get('/api/v1/users/:userId/non_vendors', isUserAllowed('list', 'vendors'), vendors.listNotForUser);

    app.param('userId', users.user);

    /**
     * QUOTES routes
     * -------------------------
     */
    var quotes = require('../app/controllers/quotes');

    app.get('/api/v1/quotes', isUserAllowed('list', 'quotes'), quotes.all);
    app.post('/api/v1/quotes', isUserAllowed('create', 'quotes'), function(req, res, next) {

        console.info('INTERNAL QUOTE API accessed....');
        next();

    }, vendors.findByBodyOrParams, quotes.validateQuoteRequest, quotes.createOrUpdate);
    app.get('/api/v1/quotes/:quoteId', isUserAllowed('view', 'quotes'), quotes.show);
    app.put('/api/v1/quotes/:quoteId', isUserAllowed('update', 'quotes'), vendors.findByBodyOrParams, quotes.validateQuoteRequest, quotes.createOrUpdate);
    app.del('/api/v1/quotes/:quoteId', isUserAllowed('delete', 'quotes'), quotes.destroy);

    app.post('/public_api/v1/quotes', function(req, res, next) {

        console.info('PUBLIC QUOTE API accessed');
        next();

    }, public_api.validateApiKey, public_api.throttle, quotes.validateQuoteRequest, quotes.createOrUpdate);

    var webshot = require('../app/controllers/webshot')(app, config);

    // @todo Adjust function when we send webshot to pdf
    // @see https://www.pivotaltracker.com/story/show/57533434
    // @note we should prob be using something like uploadfs to allow our app to send to amazon...
    // currently we are only storing files locally.
    app.get('/api/v1/quotes/:id/download', webshot.getWebshotFromUrl);

    app.param('quoteId', quotes.quote);

    /**
     * APPLICATIONS routes
     * -------------------------
     */
    var applications = require('../app/controllers/applications');
    //app.get('/applications', user.is('admin'), user.is('salesRep'), user.is('vendor'), applications.all);

    app.get('/api/v1/applications', isUserAllowed('list', 'applications'), applications.all);
    app.post('/api/v1/applications/find', applications.find);
    app.post('/api/v1/applications', isUserAllowed('create', 'applications'), applications.create);
    app.get('/api/v1/applications/:applicationId', isUserAllowed('view', 'applications'), applications.show);
    app.put('/api/v1/applications/:applicationId', isUserAllowed('update', 'applications'), applications.update);
    app.del('/api/v1/applications/:applicationId', isUserAllowed('delete', 'applications'), applications.destroy);

    app.param('applicationId', applications.application);

    /**
     * VENDORS routes
     * -------------------------
     *
     */

    //app.get('/vendors', user.is('admin'), vendors.all);
    // show all vendors, or just users vendors based on role
    app.get('/api/v1/vendors', isUserAllowed('list', 'vendors'), vendors.all);
    app.post('/api/v1/vendors', isUserAllowed('create', 'vendors'), vendors.create);

    app.get('/api/v1/vendors/tags/:tagType', vendors.getDistinctTags);

    // @todo this technically works for now, but needs to be locked down with different show functions per role
    app.get('/api/v1/vendors/:vendorId', isUserAllowed('view', 'vendors'), vendors.show);
    app.put('/api/v1/vendors/:vendorId', isUserAllowed('update', 'vendors'), vendors.update);
    app.del('/api/v1/vendors/:vendorId', isUserAllowed('delete', 'vendors'), vendors.destroy);

    // get programs for a vendor
    // @todo replace when we get a proper children setup

    app.get('/api/v1/vendors/:vendorId/salesRep', isUserAllowed('view', 'users'), vendors.getSalesRep);
    app.get('/api/v1/vendors/:vendorId/programs', vendors.getCurrentVendorPrograms);
    app.get('/api/v1/vendors/:vendorId/available_programs', isUserAllowed('updatePrograms', 'vendors'), vendors.getAvailableVendorPrograms);

    app.param('vendorId', vendors.vendor);

    /**
     * PROGRAMS routes
     * -------------------------
     *
     * Current Rules
     * - Logged in = view all programs, view single program
     * - Admin = CRUD programs
     *
     * @todo vendors should only be able to view their programs
     *
     */
    var programs = require('../app/controllers/programs');
    app.get('/api/v1/programs', isUserAllowed('list', 'programs'), programs.all);
    app.post('/api/v1/programs', isUserAllowed('create', 'programs'), programs.create);
    app.get('/api/v1/programs/:programId', isUserAllowed('view', 'programs'), programs.show);
    app.put('/api/v1/programs/:programId', isUserAllowed('update', 'programs'), programs.update);
    app.del('/api/v1/programs/:programId', isUserAllowed('delete', 'programs'), programs.destroy);

    app.param('programId', programs.program);

};
<commit_msg>Add route for vendor find.<commit_after>var async = require('async');
var util = require('util');

module.exports = function(app, passport, auth, config, acl, public_api) {

    var vendors = require('../app/controllers/vendors');

    /**
     * Middleware authentication using vergin-acl
     * -------------------------
     *
     * Function accepts action and resource params. Uses req.user.role to perform a check
     * assigns quest role if no other roles exist
     *
     * @see config/acl_roles.js for roles
     *
     * @note vergin-acl doesn't support middleware out of the box, so we wrap its check in our own middleware
     *
     * @todo move to middleware... !
     *
     */

    function isUserAllowed(action, resource) {
        return function(req, res, next) {

            // add quest role for non-logged in users.
            if (!req.user || !req.user.role) {
                req.user = {
                    role: 'guest'
                };
            }

            console.info(util.format('Can user role %s %s %s?', req.user.role, action, resource));

            // perform acl query on resource + action
            // responds with 401 and message if user doesn't have permissions
            acl.query(req.user.role, resource, action, function(err, allowed) {
                if (err) throw (err);
                if (allowed) {
                    next();
                } else {
                    return res.failure(util.format('You are not authorized to %s %s', action, resource), 401);
                }
            });
        };
    }

    /**
     * USERS / AUTH routes
     * -------------------------
     */
    var users = require('../app/controllers/users');
    app.post('/api/v1/auth/login', function(req, res, next) {
        // here we fun a function which calls another function... this gives us access to req, res, and next
        // however there must be a cleaner way to do this
        // @todo refactor
        users.signin(req, res, next, passport);
    });
    app.get('/api/v1/auth/logout', users.signout);
    app.post('/api/v1/auth/logout', users.signout); // makes testing easier with postman

    /**
     * USERS / GENERAL routes
     * -------------------------
     */
    //var users = require('../app/controllers/users');
    app.get('/api/v1/users', isUserAllowed('list', 'users'), users.all);
    app.post('/api/v1/users', isUserAllowed('create', 'users'), users.create);
    // @todo check for vendor, is this their approved sales rep?
    app.get('/api/v1/users/:userId', isUserAllowed('view', 'users'), users.show);

    // sales rep and vendor = edit their own info
    app.put('/api/v1/users/:userId', isUserAllowed('update', 'users'), users.update);
    app.del('/api/v1/users/:userId', isUserAllowed('delete', 'users'), users.destroy);

    // update user role
    app.put('/api/v1/users/:userId/role', isUserAllowed('updateRole', 'users'), users.updateRole);

    // update user password
    app.put('/api/v1/users/:userId/password', isUserAllowed('updatePassword', 'users'), users.updatePassword);
    app.put('/api/v1/users/:userId/reset_password', users.resetPassword);

    // get users vendors
    app.get('/api/v1/users/:userId/vendors', isUserAllowed('list', 'vendors'), vendors.listForUser);
    app.get('/api/v1/users/:userId/non_vendors', isUserAllowed('list', 'vendors'), vendors.listNotForUser);

    app.param('userId', users.user);

    /**
     * QUOTES routes
     * -------------------------
     */
    var quotes = require('../app/controllers/quotes');

    app.get('/api/v1/quotes', isUserAllowed('list', 'quotes'), quotes.all);
    app.post('/api/v1/quotes', isUserAllowed('create', 'quotes'), function(req, res, next) {

        console.info('INTERNAL QUOTE API accessed....');
        next();

    }, vendors.findByBodyOrParams, quotes.validateQuoteRequest, quotes.createOrUpdate);
    app.get('/api/v1/quotes/:quoteId', isUserAllowed('view', 'quotes'), quotes.show);
    app.put('/api/v1/quotes/:quoteId', isUserAllowed('update', 'quotes'), vendors.findByBodyOrParams, quotes.validateQuoteRequest, quotes.createOrUpdate);
    app.del('/api/v1/quotes/:quoteId', isUserAllowed('delete', 'quotes'), quotes.destroy);

    app.post('/public_api/v1/quotes', function(req, res, next) {

        console.info('PUBLIC QUOTE API accessed');
        next();

    }, public_api.validateApiKey, public_api.throttle, quotes.validateQuoteRequest, quotes.createOrUpdate);

    var webshot = require('../app/controllers/webshot')(app, config);

    // @todo Adjust function when we send webshot to pdf
    // @see https://www.pivotaltracker.com/story/show/57533434
    // @note we should prob be using something like uploadfs to allow our app to send to amazon...
    // currently we are only storing files locally.
    app.get('/api/v1/quotes/:id/download', webshot.getWebshotFromUrl);

    app.param('quoteId', quotes.quote);

    /**
     * APPLICATIONS routes
     * -------------------------
     */
    var applications = require('../app/controllers/applications');
    //app.get('/applications', user.is('admin'), user.is('salesRep'), user.is('vendor'), applications.all);

    app.get('/api/v1/applications', isUserAllowed('list', 'applications'), applications.all);
    app.post('/api/v1/applications/find', applications.find);
    app.post('/api/v1/applications', isUserAllowed('create', 'applications'), applications.create);
    app.get('/api/v1/applications/:applicationId', isUserAllowed('view', 'applications'), applications.show);
    app.put('/api/v1/applications/:applicationId', isUserAllowed('update', 'applications'), applications.update);
    app.del('/api/v1/applications/:applicationId', isUserAllowed('delete', 'applications'), applications.destroy);

    app.param('applicationId', applications.application);

    /**
     * VENDORS routes
     * -------------------------
     *
     */

    //app.get('/vendors', user.is('admin'), vendors.all);
    // show all vendors, or just users vendors based on role
    app.get('/api/v1/vendors', isUserAllowed('list', 'vendors'), vendors.all);
    app.post('/api/v1/vendors', isUserAllowed('create', 'vendors'), vendors.create);
    app.post('/api/v1/vendors/find', vendors.find);

    app.get('/api/v1/vendors/tags/:tagType', vendors.getDistinctTags);

    // @todo this technically works for now, but needs to be locked down with different show functions per role
    app.get('/api/v1/vendors/:vendorId', isUserAllowed('view', 'vendors'), vendors.show);
    app.put('/api/v1/vendors/:vendorId', isUserAllowed('update', 'vendors'), vendors.update);
    app.del('/api/v1/vendors/:vendorId', isUserAllowed('delete', 'vendors'), vendors.destroy);

    // get programs for a vendor
    // @todo replace when we get a proper children setup

    app.get('/api/v1/vendors/:vendorId/salesRep', isUserAllowed('view', 'users'), vendors.getSalesRep);
    app.get('/api/v1/vendors/:vendorId/programs', vendors.getCurrentVendorPrograms);
    app.get('/api/v1/vendors/:vendorId/available_programs', isUserAllowed('updatePrograms', 'vendors'), vendors.getAvailableVendorPrograms);

    app.param('vendorId', vendors.vendor);

    /**
     * PROGRAMS routes
     * -------------------------
     *
     * Current Rules
     * - Logged in = view all programs, view single program
     * - Admin = CRUD programs
     *
     * @todo vendors should only be able to view their programs
     *
     */
    var programs = require('../app/controllers/programs');
    app.get('/api/v1/programs', isUserAllowed('list', 'programs'), programs.all);
    app.post('/api/v1/programs', isUserAllowed('create', 'programs'), programs.create);
    app.get('/api/v1/programs/:programId', isUserAllowed('view', 'programs'), programs.show);
    app.put('/api/v1/programs/:programId', isUserAllowed('update', 'programs'), programs.update);
    app.del('/api/v1/programs/:programId', isUserAllowed('delete', 'programs'), programs.destroy);

    app.param('programId', programs.program);

};
<|endoftext|>


<commit_before>import { routerRedux } from 'dva/router';
import pathToRegexp from 'path-to-regexp';

import { fetchLogin } from '../services/local.service';
import { write, read, remove } from '../utils/localstorge';
import { takeLatest } from '../utils/sageHelper';

export default {
    namespace: 'login',
    state: {
        email: '',
        rememberMe: false
    },
    reducers: {
        triggerCheckBox(state, action) {
            return {
                ...state,
                ...action.payload
            };
        },
        saveEmail(state, action) {
            return {
                ...state,
                ...action.payload
            };
        }
    },
    effects: {
        login: takeLatest(function* login({ payload }, { call, put, select }) {
            const { email, password, onSuccess, onError } = payload;
            const rememberMe = yield select(state => state.login.rememberMe);
            const attemptedUrl = yield select(state => state.app.attemptedUrl);
            try {
                // 调用登录服务
                const response = yield call(fetchLogin, email, password);
                if (response) {
                    // 调用登录成功回调
                    yield onSuccess('Login success : )');
                    if (rememberMe) {
                        yield write('email', email);
                    } else {
                        yield remove('email');
                    }
                    // 路由切换到之前尝试访问的url
                    yield put(routerRedux.push({ pathname: attemptedUrl }));
                } else {
                    // 调用登录失败回调
                    yield onError(response.message);
                }
            } catch (error) {
                yield onError(error.code, error.message);
            }
        })
    },
    subscriptions: {
        saveEmail({ dispatch, history }) {
            return history.listen(({ pathname }) => {
                const match = pathToRegexp('/login').exec(pathname);
                if (match) {
                    const email = read('email');
                    dispatch({ type: 'saveEmail', payload: { email } });
                }
            });
        }
    }
};
<commit_msg>chore: 修改文件名<commit_after>import { routerRedux } from 'dva/router';
import pathToRegexp from 'path-to-regexp';

import { fetchLogin } from '../services/login.service.';
import { write, read, remove } from '../utils/localstorge';
import { takeLatest } from '../utils/sageHelper';

export default {
    namespace: 'login',
    state: {
        email: '',
        rememberMe: false
    },
    reducers: {
        triggerCheckBox(state, action) {
            return {
                ...state,
                ...action.payload
            };
        },
        saveEmail(state, action) {
            return {
                ...state,
                ...action.payload
            };
        }
    },
    effects: {
        login: takeLatest(function* login({ payload }, { call, put, select }) {
            const { email, password, onSuccess, onError } = payload;
            const rememberMe = yield select(state => state.login.rememberMe);
            const attemptedUrl = yield select(state => state.app.attemptedUrl);
            try {
                // 调用登录服务
                const response = yield call(fetchLogin, email, password);
                if (response) {
                    // 调用登录成功回调
                    yield onSuccess('Login success : )');
                    if (rememberMe) {
                        yield write('email', email);
                    } else {
                        yield remove('email');
                    }
                    // 路由切换到之前尝试访问的url
                    yield put(routerRedux.push({ pathname: attemptedUrl }));
                } else {
                    // 调用登录失败回调
                    yield onError(response.message);
                }
            } catch (error) {
                yield onError(error.code, error.message);
            }
        })
    },
    subscriptions: {
        saveEmail({ dispatch, history }) {
            return history.listen(({ pathname }) => {
                const match = pathToRegexp('/login').exec(pathname);
                if (match) {
                    const email = read('email');
                    dispatch({ type: 'saveEmail', payload: { email } });
                }
            });
        }
    }
};
<|endoftext|>


<commit_before>"use strict";

/*global nodeca, _*/

var NLib = require('nlib');
var Async = NLib.Vendor.Async;

var Section = nodeca.models.forum.Section;
var Thread = nodeca.models.forum.Thread;

var forum_breadcrumbs = require('../../lib/forum_breadcrumbs.js');
var to_tree = require('../../lib/to_tree.js');

var threads_in_fields = {
  '_id': 1,
  'id': 1,
  'title': 1,
  'prefix': 1,
  'forum_id': 1,
  'cache': 1
};

var subforums_in_fields = {
  '_id' : 1,
  'id' : 1,
  'title' : 1,
  'description' : 1,
  'parent' : 1,
  'parent_list' : 1,
  'moderator_list' : 1,
  'display_order' : 1,
  'cache' : 1
};

var forum_info_out_fields = [
  'id',
  'title',
  'description',
  'is_category'
];

// Prefetch forum to simplify permisson check.
// Check that forum exists.
//
nodeca.filters.before('@', function (params, next) {
  var env = this;

  env.extras.puncher.start('Forum info prefetch');

  Section.findOne({id: params.id}).setOptions({ lean: true })
      .exec(function(err, forum) {

    if (err) {
      next(err);
      return;
    }

    // No forum -> "Not Found" status
    if (!forum) {
      next({ statusCode: 404 });
      return;
    }

    env.data.section = forum;

    env.extras.puncher.stop();

    next(err);
  });
});

//
// fetch and prepare threads and sub-forums
// ToDo pagination
//
// ##### params
//
// - `id`   forum id
//
module.exports = function (params, next) {
  var env = this;
  var paginate_by;
  var sort = {};
  var ts_from = null;
  var ts_to = null;

  // fetch and prepare threads
  env.extras.puncher.start('Get threads');

  var max_threads = nodeca.settings.global.get('max_threads_per_page');

  var start = (params.page - 1) * max_threads;
  var end   = params.page * max_threads;

  if (env.session.hb) {
    paginate_by = 'cache.hb.last_ts';
  }
  else {
    paginate_by = 'cache.real.last_ts';
  }
  sort[paginate_by] = -1;

  // FIXME add state condition only visible thread
  var query = { forum_id: params.id };

  Async.series([
    // get start bourder
    function(callback){
      Thread.find(query).select('cache').sort(sort).skip(start)
          .limit(1).setOptions({ lean: true }).exec(function(err, docs) {

        // No page -> "Not Found" status
        if (!docs.length) {
          next({ statusCode: 404 });
          return;
        }

        if (env.session.hb) {
          ts_from = docs[0].cache.hb.last_ts;
        }
        else {
          ts_from = docs[0].cache.real.last_ts;
        }
        callback();
      });
    },
    // get end bourder
    function(callback){
      Thread.find(query).select('cache').sort(sort).skip(end)
          .limit(1).setOptions({ lean: true }).exec(function(err, docs) {
        if (docs.length) {
          if (env.session.hb) {
            ts_to = docs[0].cache.hb.last_ts;
          }
          else {
            ts_to = docs[0].cache.real.last_ts;
          }
        }
        callback();
      });
    },
    // fetch threads
    function(callback) {
      // FIXME modify state condition (deleted and etc) if user has permission
      if (!!ts_to) {
        query[paginate_by] = { $lt: ts_from, $gte: ts_to };
      }
      else {
        query[paginate_by] = { $lt: ts_from };
      }

      Thread.find(query).select(threads_in_fields).sort(sort)
          .setOptions({ lean: true }).exec(function(err, threads){
        if (err) {
          callback(err);
          return;
        }

        env.data.threads = threads;

        env.extras.puncher.stop(_.isArray(threads) ? { count: threads.length } : null);

        callback();
      });
    },
    // fetch sub-forums
    function(callback){
      env.extras.puncher.start('Get subforums');

      var max_level = env.data.section.level + 2; // need two next levels
      var query = {
        level: { $lte: max_level },
        parent_list: env.data.section._id
      };

      // FIXME add permissions check
      Section.find(query).select(subforums_in_fields).sort('display_order')
          .setOptions({ lean: true }).exec(function(err, sections){
        if (err) {
          callback(err);
          return;
        }
        env.data.sections = sections;

        env.extras.puncher.stop({ count: sections.length });

        callback();
      });
    },
  ], next);

};

// Build response:
//  - forums list -> filtered tree
//  - collect users ids (last posters / moderators / threads authors + last)
//  - threads
//
nodeca.filters.after('@', function (params, next) {
  var env = this;

  env.extras.puncher.start('Post-process forums/threads/users');

  //
  // Process sections
  //

  if (env.session.hb) {
    this.data.sections = this.data.sections.map(function(doc) {
      doc.cache.real = doc.cache.hb;
      return doc;
    });
  }

  var root = this.data.section._id;
  this.response.data.sections = to_tree(this.data.sections, root);

  env.data.users = env.data.users || [];

  // collect users from subforums
  this.data.sections.forEach(function(doc){
    if (!!doc.moderator_list) {
      doc.moderator_list.forEach(function(user) {
        env.data.users.push(user);
      });
    }
    if (doc.cache.real.last_user) {
      env.data.users.push(doc.cache.real.last_user);
    }
  });

  //
  // Process threads
  //

  if (env.session.hb) {
    this.data.threads = this.data.threads.map(function(doc) {
      doc.cache.real = doc.cache.hb;
      return doc;
    });
  }

  this.response.data.threads = this.data.threads;

  // collect users from threads
  this.data.threads.forEach(function(doc) {
    if (doc.cache.real.first_user) {
      env.data.users.push(doc.cache.real.first_user);
    }
    if (doc.cache.real.last_user) {
      env.data.users.push(doc.cache.real.last_user);
    }
  });

  env.extras.puncher.stop();

  next();
});

// Fill head meta & fetch/fill breadcrumbs
//
nodeca.filters.after('@', function (params, next) {
  var env = this;
  var data = this.response.data;
  var forum = this.data.section;

  if (this.session.hb) {
    forum.cache.real = forum.cache.hb;
  }
  // prepare page title
  data.head.title = forum.title;

  // prepare forum info
  data.forum = _.pick(forum, forum_info_out_fields);

  // prepare pagination data
  var max_threads = nodeca.settings.global.get('max_threads_per_page');
  data.max_page = Math.ceil(forum.cache.real.thread_count / max_threads);

  // fetch breadcrumbs data
  var query = { _id: { $in: forum.parent_list } };
  var fields = { '_id': 1, 'id': 1, 'title': 1 };

  env.extras.puncher.start('Build breadcrumbs');

  Section.find(query).select(fields).sort({ 'level': 1 })
      .setOptions({lean:true}).exec(function(err, parents){
    if (err) {
      next(err);
      return;
    }

    parents.push(forum);
    data.widgets.breadcrumbs = forum_breadcrumbs(env, parents);

    env.extras.puncher.stop();

    next();
  });
});
<commit_msg>Now sub-forums fetching only on first section page<commit_after>"use strict";

/*global nodeca, _*/

var NLib = require('nlib');
var Async = NLib.Vendor.Async;

var Section = nodeca.models.forum.Section;
var Thread = nodeca.models.forum.Thread;

var forum_breadcrumbs = require('../../lib/forum_breadcrumbs.js');
var to_tree = require('../../lib/to_tree.js');

var threads_in_fields = {
  '_id': 1,
  'id': 1,
  'title': 1,
  'prefix': 1,
  'forum_id': 1,
  'cache': 1
};

var subforums_in_fields = {
  '_id' : 1,
  'id' : 1,
  'title' : 1,
  'description' : 1,
  'parent' : 1,
  'parent_list' : 1,
  'moderator_list' : 1,
  'display_order' : 1,
  'cache' : 1
};

var forum_info_out_fields = [
  'id',
  'title',
  'description',
  'is_category'
];

// Prefetch forum to simplify permisson check.
// Check that forum exists.
//
nodeca.filters.before('@', function (params, next) {
  var env = this;

  env.extras.puncher.start('Forum info prefetch');

  Section.findOne({id: params.id}).setOptions({ lean: true })
      .exec(function(err, forum) {

    if (err) {
      next(err);
      return;
    }

    // No forum -> "Not Found" status
    if (!forum) {
      next({ statusCode: 404 });
      return;
    }

    env.data.section = forum;

    env.extras.puncher.stop();

    next(err);
  });
});

//
// fetch and prepare threads and sub-forums(only on first page)
// ToDo pagination
//
// ##### params
//
// - `id`   forum id
//
module.exports = function (params, next) {
  var env = this;
  var paginate_by;
  var sort = {};
  var ts_from = null;
  var ts_to = null;

  // fetch and prepare threads
  env.extras.puncher.start('Get threads');

  var max_threads = nodeca.settings.global.get('max_threads_per_page');

  var start = (params.page - 1) * max_threads;
  var end   = params.page * max_threads;

  if (env.session.hb) {
    paginate_by = 'cache.hb.last_ts';
  }
  else {
    paginate_by = 'cache.real.last_ts';
  }
  sort[paginate_by] = -1;

  // FIXME add state condition only visible thread
  var query = { forum_id: params.id };

  Async.series([
    // get start bourder
    function(callback){
      Thread.find(query).select('cache').sort(sort).skip(start)
          .limit(1).setOptions({ lean: true }).exec(function(err, docs) {

        // No page -> "Not Found" status
        if (!docs.length) {
          next({ statusCode: 404 });
          return;
        }

        if (env.session.hb) {
          ts_from = docs[0].cache.hb.last_ts;
        }
        else {
          ts_from = docs[0].cache.real.last_ts;
        }
        callback();
      });
    },
    // get end bourder
    function(callback){
      Thread.find(query).select('cache').sort(sort).skip(end)
          .limit(1).setOptions({ lean: true }).exec(function(err, docs) {
        if (docs.length) {
          if (env.session.hb) {
            ts_to = docs[0].cache.hb.last_ts;
          }
          else {
            ts_to = docs[0].cache.real.last_ts;
          }
        }
        callback();
      });
    },
    // fetch threads
    function(callback) {
      // FIXME modify state condition (deleted and etc) if user has permission
      if (!!ts_to) {
        query[paginate_by] = { $lt: ts_from, $gte: ts_to };
      }
      else {
        query[paginate_by] = { $lt: ts_from };
      }

      Thread.find(query).select(threads_in_fields).sort(sort)
          .setOptions({ lean: true }).exec(function(err, threads){
        if (err) {
          callback(err);
          return;
        }

        env.data.threads = threads;

        env.extras.puncher.stop(_.isArray(threads) ? { count: threads.length } : null);

        callback();
      });
    },
    // fetch sub-forums
    function(callback){
      env.data.sections = [];
      // subforums fetched only on first page
      if (params.page > 1) {
        callback();
        return;
      }
      env.extras.puncher.start('Get subforums');

      var max_level = env.data.section.level + 2; // need two next levels
      var query = {
        level: { $lte: max_level },
        parent_list: env.data.section._id
      };

      // FIXME add permissions check
      Section.find(query).select(subforums_in_fields).sort('display_order')
          .setOptions({ lean: true }).exec(function(err, sections){
        if (err) {
          callback(err);
          return;
        }
        env.data.sections = sections;

        env.extras.puncher.stop({ count: sections.length });

        callback();
      });
    },
  ], next);

};

// Build response:
//  - forums list -> filtered tree
//  - collect users ids (last posters / moderators / threads authors + last)
//  - threads
//
nodeca.filters.after('@', function (params, next) {
  var env = this;

  env.extras.puncher.start('Post-process forums/threads/users');

  //
  // Process sections
  //

  if (env.session.hb) {
    this.data.sections = this.data.sections.map(function(doc) {
      doc.cache.real = doc.cache.hb;
      return doc;
    });
  }

  var root = this.data.section._id;
  this.response.data.sections = to_tree(this.data.sections, root);

  env.data.users = env.data.users || [];

  // collect users from subforums
  this.data.sections.forEach(function(doc){
    if (!!doc.moderator_list) {
      doc.moderator_list.forEach(function(user) {
        env.data.users.push(user);
      });
    }
    if (doc.cache.real.last_user) {
      env.data.users.push(doc.cache.real.last_user);
    }
  });

  //
  // Process threads
  //

  if (env.session.hb) {
    this.data.threads = this.data.threads.map(function(doc) {
      doc.cache.real = doc.cache.hb;
      return doc;
    });
  }

  this.response.data.threads = this.data.threads;

  // collect users from threads
  this.data.threads.forEach(function(doc) {
    if (doc.cache.real.first_user) {
      env.data.users.push(doc.cache.real.first_user);
    }
    if (doc.cache.real.last_user) {
      env.data.users.push(doc.cache.real.last_user);
    }
  });

  env.extras.puncher.stop();

  next();
});

// Fill head meta & fetch/fill breadcrumbs
//
nodeca.filters.after('@', function (params, next) {
  var env = this;
  var data = this.response.data;
  var forum = this.data.section;

  if (this.session.hb) {
    forum.cache.real = forum.cache.hb;
  }
  // prepare page title
  data.head.title = forum.title;

  // prepare forum info
  data.forum = _.pick(forum, forum_info_out_fields);

  // prepare pagination data
  var max_threads = nodeca.settings.global.get('max_threads_per_page');
  data.max_page = Math.ceil(forum.cache.real.thread_count / max_threads);

  // fetch breadcrumbs data
  var query = { _id: { $in: forum.parent_list } };
  var fields = { '_id': 1, 'id': 1, 'title': 1 };

  env.extras.puncher.start('Build breadcrumbs');

  Section.find(query).select(fields).sort({ 'level': 1 })
      .setOptions({lean:true}).exec(function(err, parents){
    if (err) {
      next(err);
      return;
    }

    parents.push(forum);
    data.widgets.breadcrumbs = forum_breadcrumbs(env, parents);

    env.extras.puncher.stop();

    next();
  });
});
<|endoftext|>


<commit_before>/* KAAE Watch Scheduler */

import _ from 'lodash';
import later from 'later';
import doActions from './actions';

var Schedule = [];

function getCount(client) {
  return client.count({
    index:'watcher',
    type:"watch"
  });
}

function getWatcher(count,client) {
  return client.search({
    index:'watcher',
    type:"watch",
    size:count
  });
}

function doalert(server,client) {
  server.log(['status', 'debug', 'KaaE'], 'Reloading Watchers...');
  getCount(client).then(function(resp){
    getWatcher(resp.count,client).then(function(resp){
      /* Orphanizer */
        var orphans = _.difference(_.each(Object.keys( Schedule )), _.map(resp.hits.hits, '_id')  );
        _.each(orphans, function(orphan){
                server.log(['status', 'info', 'KaaE'],'Deleting orphan watcher: '+orphan);
                Schedule[orphan].later.clear();
                delete Schedule[orphan];
        });

      /* Scheduler */
      _.each(resp.hits.hits, function(hit){

        if (Schedule[hit._id]) {
          if (_.isEqual(Schedule[hit._id].hit, hit)) { return; }
          else { server.log(['status', 'info', 'KaaE'],'Clearing watcher: '+hit._id); Schedule[hit._id].later.clear(); }
        }

          Schedule[hit._id] = {};
          Schedule[hit._id].hit = hit;

          if(hit._source.trigger.schedule.later){
            // https://bunkat.github.io/later/parsers.html#text
            var interval = later.parse.text(hit._source.trigger.schedule.later);
            Schedule[hit._id].interval = hit._source.trigger.schedule.later;
          }
          else if(hit._source.trigger.schedule.interval % 1 === 0){
            // max 60 seconds!
            var interval = later.parse.recur().every(hit._source.trigger.schedule.interval).second();
            Schedule[hit._id].interval = hit._source.trigger.schedule.interval;
          }

          if (hit._source.report) {
            /* Report */
            Schedule[hit._id].later = later.setInterval(function(){ reporting(hit,interval) }, interval);
            server.log(['status', 'info', 'KaaE'], 'Scheduled Report: '+hit._id+' every '+Schedule[hit._id].interval );
          } else {
            /* Watcher */
            Schedule[hit._id].later = later.setInterval(function(){ watching(hit,interval) }, interval);
            server.log(['status', 'info', 'KaaE'], 'Scheduled Watch: '+hit._id+' every '+Schedule[hit._id].interval );
          }

          function watching(task,interval) {
            server.log(['status', 'info', 'KaaE'], 'Executing watch: '+task._id+' Next Round of '+task._id+' at '+later.schedule(interval).next(1) );

	    server.log(['status', 'debug', 'KaaE', 'WATCHER DEBUG'], task);

            var watch = task._source;
            var request = watch.input.search.request;
            var condition = watch.condition.script.script;
            var transform = watch.transform ? watch.transform : {};
            var actions = watch.actions;

            client.search(request).then(function(payload){
              if (!payload || !condition || !actions) {
		    server.log(['status', 'debug', 'KaaE', 'WATCHER TASK'], 'Watcher Malformed or Missing Key Parameters!');
		    return;
	      }

	      server.log(['status', 'debug', 'KaaE', 'PAYLOAD DEBUG'], payload);

              /* Validate Condition */
              try { var ret = eval(condition); } catch (err) {
                          server.log(['status', 'info', 'KaaE'], 'Condition Error for '+task._id+': '+err);
              }
              if (ret) {
                  if (transform.script) {
                      try { eval(transform.script.script); } catch (err) {
                          server.log(['status', 'info', 'KaaE'], 'Transform Script Error for '+task._id+': '+err);
                      }
                      doActions(server,actions,payload);
                  } else if (transform.search) {
                      client.search(transform.search.request).then(function(payload) {
                          if (!payload) return;
                          doActions(server,actions,payload);
                      });
                  } else {
                      doActions(server,actions,payload);
                  }
              }
            });
        }
        function reporting(task,interval) {
          server.log(['status', 'info', 'KaaE'], 'Executing report: '+task._id+' Next round at '+later.schedule(interval).next(1) );
          var actions = task._source.actions;
          var payload = { "_id": task._id };
          if (!actions) { server.log(['status', 'info', 'KaaE'], 'Condition Error for '+task._id); return; }
          doActions(server,actions,payload);
        }
      });
    });
  });
}

module.exports = {
  doalert: doalert,
  getCount: getCount,
  getWatcher: getWatcher
};
<commit_msg>Implement condition for coordinate_search in Kibi<commit_after>/* KAAE Watch Scheduler */

import _ from 'lodash';
import later from 'later';
import doActions from './actions';

var Schedule = [];

function getCount(client) {
  return client.count({
    index:'watcher',
    type:"watch"
  });
}

function getWatcher(count,client) {
  return client.search({
    index:'watcher',
    type:"watch",
    size:count
  });
}

function doalert(server,client) {
  server.log(['status', 'debug', 'KaaE'], 'Reloading Watchers...');
  getCount(client).then(function(resp){
    getWatcher(resp.count,client).then(function(resp){
      /* Orphanizer */
        var orphans = _.difference(_.each(Object.keys( Schedule )), _.map(resp.hits.hits, '_id')  );
        _.each(orphans, function(orphan){
                server.log(['status', 'info', 'KaaE'],'Deleting orphan watcher: '+orphan);
                Schedule[orphan].later.clear();
                delete Schedule[orphan];
        });

      /* Scheduler */
      _.each(resp.hits.hits, function(hit){

        if (Schedule[hit._id]) {
          if (_.isEqual(Schedule[hit._id].hit, hit)) { return; }
          else { server.log(['status', 'info', 'KaaE'],'Clearing watcher: '+hit._id); Schedule[hit._id].later.clear(); }
        }

          Schedule[hit._id] = {};
          Schedule[hit._id].hit = hit;

          if(hit._source.trigger.schedule.later){
            // https://bunkat.github.io/later/parsers.html#text
            var interval = later.parse.text(hit._source.trigger.schedule.later);
            Schedule[hit._id].interval = hit._source.trigger.schedule.later;
          }
          else if(hit._source.trigger.schedule.interval % 1 === 0){
            // max 60 seconds!
            var interval = later.parse.recur().every(hit._source.trigger.schedule.interval).second();
            Schedule[hit._id].interval = hit._source.trigger.schedule.interval;
          }

          if (hit._source.report) {
            /* Report */
            Schedule[hit._id].later = later.setInterval(function(){ reporting(hit,interval) }, interval);
            server.log(['status', 'info', 'KaaE'], 'Scheduled Report: '+hit._id+' every '+Schedule[hit._id].interval );
          } else {
            /* Watcher */
            Schedule[hit._id].later = later.setInterval(function(){ watching(hit,interval) }, interval);
            server.log(['status', 'info', 'KaaE'], 'Scheduled Watch: '+hit._id+' every '+Schedule[hit._id].interval );
          }

          function watching(task,interval) {
            server.log(['status', 'info', 'KaaE'], 'Executing watch: '+task._id+' Next Round of '+task._id+' at '+later.schedule(interval).next(1) );

	    server.log(['status', 'debug', 'KaaE', 'WATCHER DEBUG'], task);

            var watch = task._source;
            var request = watch.input.search.request;
            var condition = watch.condition.script.script;
            var transform = watch.transform ? watch.transform : {};
            var actions = watch.actions;

	    if (JSON.stringify(request).indexOf('filterjoin') !== -1) {
		/* Kibi Join Query */
		client.coordinate_search(request).then(function(payload){
		      if (!payload || !condition || !actions) {
			    server.log(['status', 'debug', 'KaaE', 'WATCHER TASK'], 'Watcher Malformed or Missing Key Parameters!');
			    return;
		      }

		      server.log(['status', 'debug', 'KaaE', 'PAYLOAD DEBUG'], payload);

		      /* Validate Condition */
		      try { var ret = eval(condition); } catch (err) {
				  server.log(['status', 'info', 'KaaE'], 'Condition Error for '+task._id+': '+err);
		      }
		      if (ret) {
			  if (transform.script) {
			      try { eval(transform.script.script); } catch (err) {
				  server.log(['status', 'info', 'KaaE'], 'Transform Script Error for '+task._id+': '+err);
			      }
			      doActions(server,actions,payload);
			  } else if (transform.search) {
			      client.search(transform.search.request).then(function(payload) {
				  if (!payload) return;
				  doActions(server,actions,payload);
			      });
			  } else {
			      doActions(server,actions,payload);
			  }
		      }
		    });
	    } else {
		/* Normal ES Query */
		client.search(request).then(function(payload){
		      if (!payload || !condition || !actions) {
			    server.log(['status', 'debug', 'KaaE', 'WATCHER TASK'], 'Watcher Malformed or Missing Key Parameters!');
			    return;
		      }

		      server.log(['status', 'debug', 'KaaE', 'PAYLOAD DEBUG'], payload);

		      /* Validate Condition */
		      try { var ret = eval(condition); } catch (err) {
				  server.log(['status', 'info', 'KaaE'], 'Condition Error for '+task._id+': '+err);
		      }
		      if (ret) {
			  if (transform.script) {
			      try { eval(transform.script.script); } catch (err) {
				  server.log(['status', 'info', 'KaaE'], 'Transform Script Error for '+task._id+': '+err);
			      }
			      doActions(server,actions,payload);
			  } else if (transform.search) {
			      client.search(transform.search.request).then(function(payload) {
				  if (!payload) return;
				  doActions(server,actions,payload);
			      });
			  } else {
			      doActions(server,actions,payload);
			  }
		      }
		    });
	    }
        }
        function reporting(task,interval) {
          server.log(['status', 'info', 'KaaE'], 'Executing report: '+task._id+' Next round at '+later.schedule(interval).next(1) );
          var actions = task._source.actions;
          var payload = { "_id": task._id };
          if (!actions) { server.log(['status', 'info', 'KaaE'], 'Condition Error for '+task._id); return; }
          doActions(server,actions,payload);
        }
      });
    });
  });
}

module.exports = {
  doalert: doalert,
  getCount: getCount,
  getWatcher: getWatcher
};
<|endoftext|>


<commit_before>
var _ = require('highland');

var EventEmitter = require('events').EventEmitter;

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

var notify = require('./notification');

var emitter = new EventEmitter();

exports.dataStream = _('data', emitter);

// exports.statusStream = _('status', emitter);

var ls = require('lightstreamer-client');

var dd = require('./data_dictionary');

var SCHEMA = ['TimeStamp', 'Value', 'Status.Class', 'CalibratedData'];

// the data stream
var lsClient = new ls.LightstreamerClient('http://push.lightstreamer.com', 'ISSLIVE');

lsClient.connectionOptions.setSlowingEnabled(false);

// MERGE indicates that we only want to receive data when the value(s) have changed
var telemetrySub = new ls.Subscription('MERGE', dd.list, SCHEMA);
var timeSub = new ls.Subscription('MERGE', 'TIME_000001', ['Status.Class']);

var statusIdx = dd.hash.STATUS;
var telemetrySessionId;

// interpret status based on our connection health with lightstreamer
function statusUpdate() {

  var cs = lsClient.getStatus(),

  resolvedStatus = 0,

  isSubscribed = telemetrySub.isSubscribed(),

  now = Date.now() / 1000 | 0,

  data;

  if (cs.indexOf('CONNECTED') > -1 && isSubscribed) {

    resolvedStatus = 1;

  } else {

    resolvedStatus = 0;
  }

  data = {
    k: statusIdx,
    v: resolvedStatus,
    t: now,
    s: resolvedStatus === 1 ? 24 : 2,  // 24 and 2 are values from telemetry
    sid: now
  };

  // console.log(data);

  emitter.emit('data', data);
}

lsClient.addListener({

  onStatusChange: function (status) {

    statusUpdate();
  }
});

lsClient.subscribe(timeSub);
lsClient.connect();

var unsubTimeout = null;

timeSub.addListener({

  onUnsubscription: function () {

    lsClient.unsubscribe(telemetrySub);
  },

  onItemUpdate: function (update) {

    var status = update.getValue('Status.Class'),
    subscribed = telemetrySub.isSubscribed();

    if (status === '24' && unsubTimeout) {

      clearTimeout(unsubTimeout);
      unsubTimeout = null;
    }

    if (status === '24' && !subscribed) {

      lsClient.subscribe(telemetrySub);

    } else if (status !== '24' && subscribed) {

      // give 20 seconds to collect any outstanding data from lightstreamer
      unsubTimeout = setTimeout(function () {

        lsClient.unsubscribe(telemetrySub);

      }, 20000);
    }
  }
});

telemetrySub.addListener({

  onSubscription: function () {

    telemetrySessionId = utils.getTimeBasedId();
    statusUpdate();
  },

  onUnsubscription: function () {

    statusUpdate();
  },

  onItemUpdate: function (update) {

    var fValue = 0,

    fTimeStamp = 0,

    iStatus = 0,

    idx = dd.hash[update.getItemName()];

    try {

      fValue = parseFloat(update.getValue('Value'));
      fTimeStamp = parseFloat(update.getValue('TimeStamp'));
      iStatus = parseInt(update.getValue('Status.Class'), 10);

    } catch (ex) {

      console.error(ex);
    }

    if (fTimeStamp) {
      var now = new Date();
      var year = new Date(Date.UTC(now.getUTCFullYear(), 0)); // This year, jan 1, 00:00:00, utc
      // THE TELEMETRY TIME SEEMS TO ADD 24 HOURS TO NUMBER
      // OF HOURS IN THE YEAR SO FAR.  STRANGE.  TODO
      // so we subtract 24 from fTimeStamp, convert to seconds
      // add to number of seconds as of THIS_YEAR-01-01T00:00:00 UTC
      // truncate the decimal places for a result in seconds, aka unixtime
      fTimeStamp = (((fTimeStamp - 24) * 3600) + (year.getTime() / 1000)) | 0;
    }

    // handle TIME_000001
    if (idx === 296) {
      // in this case utilize the timestamp for the value
      fValue = fTimeStamp;
    }

    var data = {
      k: idx,
      v: fValue,
      cv: update.getValue('CalibratedData'),
      t: fTimeStamp,
      s: iStatus,
      sid: telemetrySessionId
    };

    emitter.emit('data', data);

    // if(update.getItemName() === 'USLAB000024') {
    //   console.log(update.getItemName());
    //   SCHEMA.forEach(function(key) { console.log(key + ': ' + update.getValue(key)); });
    // }
  }
});
<commit_msg>update how to detect streaming connection to telemetry<commit_after>
var _ = require('highland');

var EventEmitter = require('events').EventEmitter;

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

var emitter = new EventEmitter();

exports.dataStream = _('data', emitter);

// exports.statusStream = _('status', emitter);

var ls = require('lightstreamer-client');

var dd = require('./data_dictionary');

var SCHEMA = ['TimeStamp', 'Value', 'Status.Class', 'CalibratedData'];

// the data stream
var lsClient = new ls.LightstreamerClient('http://push.lightstreamer.com', 'ISSLIVE');

lsClient.connectionOptions.setSlowingEnabled(false);

// MERGE indicates that we only want to receive data when the value(s) have changed
var telemetrySub = new ls.Subscription('MERGE', dd.list, SCHEMA);
var timeSub = new ls.Subscription('MERGE', 'TIME_000001', ['Status.Class']);

var statusIdx = dd.hash.STATUS;

var telemetrySessionId;

var lastStatus;

var time00001Timeout;

function statusUpdate(connected) {

  var now = Date.now() / 1000 | 0, data;

  data = {
    k: statusIdx.toString(),
    v: connected ? 1 : 0,
    t: now,
    s: connected ? 24 : 2,  // 24 and 2 are values from telemetry
    sid: now
  };

  if (!lastStatus) {

    console.log(data);

    emitter.emit('data', data);

  } else if (lastStatus && lastStatus.s !== data.s) {

    console.log(data);

    emitter.emit('data', data);
  }

  lastStatus = data;
}

lsClient.subscribe(timeSub);
lsClient.connect();

var unsubTimeout = null;

timeSub.addListener({

  onUnsubscription: function () {

    lsClient.unsubscribe(telemetrySub);
  },

  onItemUpdate: function (update) {

    var status = update.getValue('Status.Class'),
    subscribed = telemetrySub.isSubscribed();

    if (status === '24' && unsubTimeout) {

      clearTimeout(unsubTimeout);
      unsubTimeout = null;
    }

    if (status === '24' && !subscribed) {

      lsClient.subscribe(telemetrySub);

    } else if (status !== '24' && subscribed) {

      // give 20 seconds to collect any outstanding data from lightstreamer
      unsubTimeout = setTimeout(function () {

        lsClient.unsubscribe(telemetrySub);

      }, 10000);
    }
  }
});

telemetrySub.addListener({

  onSubscription: function () {

    telemetrySessionId = utils.getTimeBasedId();

    // setup a timeout to notify clients if data is not streaming
    clearTimeout(time00001Timeout);
    time00001Timeout = setTimeout(function () { statusUpdate(false); }, 10000);
  },

  onItemUpdate: function (update) {

    var fValue = 0,

    fTimeStamp = 0,

    iStatus = 0,

    idx = dd.hash[update.getItemName()];

    try {

      fValue = parseFloat(update.getValue('Value'));
      fTimeStamp = parseFloat(update.getValue('TimeStamp'));
      iStatus = parseInt(update.getValue('Status.Class'), 10);

    } catch (ex) {

      console.error(ex);
    }

    if (fTimeStamp) {
      var now = new Date();
      var year = new Date(Date.UTC(now.getUTCFullYear(), 0)); // This year, jan 1, 00:00:00, utc
      // THE TELEMETRY TIME SEEMS TO ADD 24 HOURS TO NUMBER
      // OF HOURS IN THE YEAR SO FAR.  STRANGE.  TODO
      // so we subtract 24 from fTimeStamp, convert to seconds
      // add to number of seconds as of THIS_YEAR-01-01T00:00:00 UTC
      // truncate the decimal places for a result in seconds, aka unixtime
      fTimeStamp = (((fTimeStamp - 24) * 3600) + (year.getTime() / 1000)) | 0;
    }

    // handle TIME_000001
    if (idx === 296) {
      // in this case utilize the timestamp for the value
      fValue = fTimeStamp;

      // data is streaming, notify clients
      statusUpdate(true);
      // setup a timeout to notify clients if stops streaming
      clearTimeout(time00001Timeout);
      time00001Timeout = setTimeout(function () { statusUpdate(false); }, 10000);
    }

    var data = {
      k: idx,
      v: fValue,
      cv: update.getValue('CalibratedData'),
      t: fTimeStamp,
      s: iStatus,
      sid: telemetrySessionId
    };

    emitter.emit('data', data);

    // if(update.getItemName() === 'USLAB000024') {
    //   console.log(update.getItemName());
    //   SCHEMA.forEach(function(key) { console.log(key + ': ' + update.getValue(key)); });
    // }
  }
});
<|endoftext|>


<commit_before>Meteor.methods({
  addUser (user) {
    // Add new user
    var userId = Accounts.createUser(user);

    return userId;
  },
  addUsersAndSendEnrollmentEmails (enrollmentDocument) {
    // original example: https://stackoverflow.com/a/16098693/1191545

    // Get emails from enrollment document
    const emailAddresses = enrollmentDocument.emailAddresses;

    // Create user and send enrollment email for each email address
    emailAddresses.forEach((emailAddress) => {
      // Create a user with current email address
      const userId = Accounts.createUser({
        email: emailAddress,
        enrollmentPending: true
      });

      // Send enrollment email to newly created user
      Accounts.sendEnrollmentEmail(userId);
    });
  },
  addUserToAdminRole (userId) {
    // Add user to admin role
    Roles.addUsersToRoles(userId, "admin");
  },
  deleteUser (user) {
    console.log(user);
    // Make sure user object provided with '_id' property
    check(user, Object);
    check(user._id, String);

    // Get current user id, for security check
    const currentUserId = this.userId;

    // Make sure current user has 'admin' role
    if (Roles.userIsInRole(currentUserId, 'admin')) {
      // Make sure user can't delete own Account
      if (currentUserId !== user._id) {
        // If safe, delete provided user Object
        Meteor.users.remove(user);
      }
    }
  },
  editUserFormSubmit (user) {
    // Get user email
    var userEmail = user.email;

    var userId = user._id;

    // Edit user, setting first email
    Meteor.users.update(userId, {$set: {"emails.0.address": userEmail}});

    return userId;
  },
  removeUserFromAdminRole (userId) {
    // Add user to admin role
    Roles.removeUsersFromRoles(userId, "admin");
  }
});
<commit_msg>Simplify<commit_after>Meteor.methods({
  addUser (user) {
    // Add new user
    var userId = Accounts.createUser(user);

    return userId;
  },
  addUsersAndSendEnrollmentEmails (enrollmentDocument) {
    // original example: https://stackoverflow.com/a/16098693/1191545

    // Get emails from enrollment document
    const emailAddresses = enrollmentDocument.emailAddresses;

    // Create user and send enrollment email for each email address
    emailAddresses.forEach((emailAddress) => {
      // Create a user with current email address
      const userId = Accounts.createUser({
        email: emailAddress
      });

      // Send enrollment email to newly created user
      Accounts.sendEnrollmentEmail(userId);
    });
  },
  addUserToAdminRole (userId) {
    // Add user to admin role
    Roles.addUsersToRoles(userId, "admin");
  },
  deleteUser (user) {
    console.log(user);
    // Make sure user object provided with '_id' property
    check(user, Object);
    check(user._id, String);

    // Get current user id, for security check
    const currentUserId = this.userId;

    // Make sure current user has 'admin' role
    if (Roles.userIsInRole(currentUserId, 'admin')) {
      // Make sure user can't delete own Account
      if (currentUserId !== user._id) {
        // If safe, delete provided user Object
        Meteor.users.remove(user);
      }
    }
  },
  editUserFormSubmit (user) {
    // Get user email
    var userEmail = user.email;

    var userId = user._id;

    // Edit user, setting first email
    Meteor.users.update(userId, {$set: {"emails.0.address": userEmail}});

    return userId;
  },
  removeUserFromAdminRole (userId) {
    // Add user to admin role
    Roles.removeUsersFromRoles(userId, "admin");
  }
});
<|endoftext|>


<commit_before>const Rexec = require('child_process').exec;
const fs = require('fs');
const tools = require('../toolbox');

exports.name = 'DADA2';
exports.category = 'Clustering';
exports.multicore = false;

exports.run = function(os,config,callback){
  let token = os.token;
  let directory = '/app/data/' + token + '/';
  let tags = directory + config.params.inputs.tags;
  //let fwd = config.params.inputs.fwd;
  //let rev = config.params.inputs.rev;
  let by_lib = config.params.params.by_lib;
  let asvs_seq = config.params.outputs.asvs_seq;
  let asvs_table = config.params.outputs.asvs_tab;
  let proc = os.cores;

  let fwd = Object.values(config.params.inputs.fwd);
  let rev = Object.values(config.params.inputs.rev);

	fwd = fwd.map((fastq) => {return directory + fastq + ";"})
  rev = rev.map((fastq) => {return directory + fastq + ";"})

  console.log('value of by_lib: ' + by_lib)

  var command = ['/app/lib/R_scripts/dada2.R',by_lib,tags,asvs_seq,asvs_table,token,proc,fwd,rev];
  console.log('R command line:' + command);

  var child = Rexec('Rscript '+command.join(' '));

  child.stdout.on('data', function(data) {
		console.log('STDOUT:' + data);
		fs.appendFileSync(directory + config.log, data);
	});
	child.stderr.on('data', function(data) {
		console.log('STDERR:' + data);
		fs.appendFileSync(directory + config.log, data);
	});

  child.on('close', (code) => {
		if (code != 0) {
			console.log("Error code " + code + " during DADA2");
			callback(os, code);
		} else {
			callback(os, null);
		}
	});

}
<commit_msg>concat<commit_after>const Rexec = require('child_process').exec;
const fs = require('fs');
const tools = require('../toolbox');

exports.name = 'DADA2';
exports.category = 'Clustering';
exports.multicore = false;

exports.run = function(os,config,callback){
  let token = os.token;
  let directory = '/app/data/' + token + '/';
  let tags = directory + config.params.inputs.tags;
  //let fwd = config.params.inputs.fwd;
  //let rev = config.params.inputs.rev;
  let by_lib = config.params.params.by_lib;
  let asvs_seq = config.params.outputs.asvs_seq;
  let asvs_table = config.params.outputs.asvs_tab;
  let proc = os.cores;

  let fwd = Object.values(config.params.inputs.fwd);
  let rev = Object.values(config.params.inputs.rev);

	fwd = fwd.map((fastq) => {return directory + fastq})
  rev = rev.map((fastq) => {return directory + fastq})

  console.log('value of by_lib: ' + by_lib)

  var command = ['/app/lib/R_scripts/dada2.R',by_lib,tags,asvs_seq,asvs_table,token,proc,fwd,rev];
  console.log('R command line:' + command);

  var child = Rexec('Rscript '+command.join(' '));

  child.stdout.on('data', function(data) {
		console.log('STDOUT:' + data);
		fs.appendFileSync(directory + config.log, data);
	});
	child.stderr.on('data', function(data) {
		console.log('STDERR:' + data);
		fs.appendFileSync(directory + config.log, data);
	});

  child.on('close', (code) => {
		if (code != 0) {
			console.log("Error code " + code + " during DADA2");
			callback(os, code);
		} else {
			callback(os, null);
		}
	});

}
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import defaultPropTypes from './defaultPropTypes';

class Notification extends Component {
  constructor(props) {
    super(props);

    this.getBarStyle = this.getBarStyle.bind(this);
    this.getActionStyle = this.getActionStyle.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.onDismiss && nextProps.isActive && !this.props.isActive) {
      this.dismissTimeout = setTimeout(nextProps.onDismiss, nextProps.dismissAfter);
    }
  }

  componentWillUnmount() {
    clearTimeout(this.dismissTimeout);
  }

  /*
   * @description Dynamically get the styles for the bar.
   * @returns {object} result The style.
   */
  getBarStyle() {
    if (this.props.style === false) return {};

    const { isActive, barStyle, activeBarStyle } = this.props;

    const baseStyle = {
      position: 'fixed',
      bottom: '2rem',
      left: '-100%',
      width: 'auto',
      padding: '1rem',
      margin: 0,
      color: '#fafafa',
      font: '1rem normal Roboto, sans-serif',
      borderRadius: '5px',
      background: '#212121',
      borderSizing: 'border-box',
      boxShadow: '0 0 1px 1px rgba(10, 10, 11, .125)',
      cursor: 'default',
      WebKittransition: '.5s cubic-bezier(0.89, 0.01, 0.5, 1.1)',
      MozTransition: '.5s cubic-bezier(0.89, 0.01, 0.5, 1.1)',
      msTransition: '.5s cubic-bezier(0.89, 0.01, 0.5, 1.1)',
      OTransition: '.5s cubic-bezier(0.89, 0.01, 0.5, 1.1)',
      transition: '.5s cubic-bezier(0.89, 0.01, 0.5, 1.1)',
      WebkitTransform: 'translatez(0)',
      MozTransform: 'translatez(0)',
      msTransform: 'translatez(0)',
      OTransform: 'translatez(0)',
      transform: 'translatez(0)'
    };

    return isActive ? Object.assign({}, baseStyle, {
      left: '1rem'
    }, barStyle, activeBarStyle) : Object.assign({}, baseStyle, barStyle);
  }

  /*
   * @function getActionStyle
   * @description Dynamically get the styles for the action text.
   * @returns {object} result The style.
   */
  getActionStyle() {
    return this.props.style !== false ? Object.assign({}, {
      padding: '0.125rem',
      marginLeft: '1rem',
      color: '#f44336',
      font: '.75rem normal Roboto, sans-serif',
      lineHeight: '1rem',
      letterSpacing: '.125ex',
      textTransform: 'uppercase',
      borderRadius: '5px',
      cursor: 'pointer'
    }, this.props.actionStyle) : {};
  }

  /*
   * @function handleClick
   * @description Handle click events on the action button.
   */
  handleClick = event => {
    event.preventDefault();

    if (this.props.onClick && typeof this.props.onClick === 'function') {
      return this.props.onClick(event);
    }

    return event;
  }

  render() {
    let className = 'notification-bar';

    if (this.props.isActive) className += ' ' + this.props.activeClassName;
    if (this.props.className) className += ' ' + this.props.className;

    return (

            {this.props.message}

          {this.props.action ? (

              {this.props.action}

          ) : null}

    );
  }
}

Notification.propTypes = defaultPropTypes;

Notification.defaultProps = {
  isActive: false,
  dismissAfter: 2000,
  activeClassName: 'notification-bar-active'
}

export default Notification;
<commit_msg>Remove event parameter from handleClick<commit_after>import React, { Component, PropTypes } from 'react';
import defaultPropTypes from './defaultPropTypes';

class Notification extends Component {
  constructor(props) {
    super(props);

    this.getBarStyle = this.getBarStyle.bind(this);
    this.getActionStyle = this.getActionStyle.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.onDismiss && nextProps.isActive && !this.props.isActive) {
      this.dismissTimeout = setTimeout(nextProps.onDismiss, nextProps.dismissAfter);
    }
  }

  componentWillUnmount() {
    clearTimeout(this.dismissTimeout);
  }

  /*
   * @description Dynamically get the styles for the bar.
   * @returns {object} result The style.
   */
  getBarStyle() {
    if (this.props.style === false) return {};

    const { isActive, barStyle, activeBarStyle } = this.props;

    const baseStyle = {
      position: 'fixed',
      bottom: '2rem',
      left: '-100%',
      width: 'auto',
      padding: '1rem',
      margin: 0,
      color: '#fafafa',
      font: '1rem normal Roboto, sans-serif',
      borderRadius: '5px',
      background: '#212121',
      borderSizing: 'border-box',
      boxShadow: '0 0 1px 1px rgba(10, 10, 11, .125)',
      cursor: 'default',
      WebKittransition: '.5s cubic-bezier(0.89, 0.01, 0.5, 1.1)',
      MozTransition: '.5s cubic-bezier(0.89, 0.01, 0.5, 1.1)',
      msTransition: '.5s cubic-bezier(0.89, 0.01, 0.5, 1.1)',
      OTransition: '.5s cubic-bezier(0.89, 0.01, 0.5, 1.1)',
      transition: '.5s cubic-bezier(0.89, 0.01, 0.5, 1.1)',
      WebkitTransform: 'translatez(0)',
      MozTransform: 'translatez(0)',
      msTransform: 'translatez(0)',
      OTransform: 'translatez(0)',
      transform: 'translatez(0)'
    };

    return isActive ? Object.assign({}, baseStyle, {
      left: '1rem'
    }, barStyle, activeBarStyle) : Object.assign({}, baseStyle, barStyle);
  }

  /*
   * @function getActionStyle
   * @description Dynamically get the styles for the action text.
   * @returns {object} result The style.
   */
  getActionStyle() {
    return this.props.style !== false ? Object.assign({}, {
      padding: '0.125rem',
      marginLeft: '1rem',
      color: '#f44336',
      font: '.75rem normal Roboto, sans-serif',
      lineHeight: '1rem',
      letterSpacing: '.125ex',
      textTransform: 'uppercase',
      borderRadius: '5px',
      cursor: 'pointer'
    }, this.props.actionStyle) : {};
  }

  /*
   * @function handleClick
   * @description Handle click events on the action button.
   */
  handleClick = () => {
    if (this.props.onClick && typeof this.props.onClick === 'function') {
      return this.props.onClick();
    }
  }

  render() {
    let className = 'notification-bar';

    if (this.props.isActive) className += ' ' + this.props.activeClassName;
    if (this.props.className) className += ' ' + this.props.className;

    return (

            {this.props.message}

          {this.props.action ? (

              {this.props.action}

          ) : null}

    );
  }
}

Notification.propTypes = defaultPropTypes;

Notification.defaultProps = {
  isActive: false,
  dismissAfter: 2000,
  activeClassName: 'notification-bar-active'
}

export default Notification;
<|endoftext|>