<commit_before>///--------------------------------------------------------
///--------------------------------------------------------
/// ARRAY OF OBJECTS (Difficulty: 1/5)
///--------------------------------------------------------
///--------------------------------------------------------

/// Multi-part Problem

/// Tags: Higher-order functions, objects, arrays

var people = [
  {name: {first: "Alyssa", middle: "P.", last: "Hacker"}, gender:'female', age: 26},
  {name: {first: "Ben", last: "Bitdiddle"}, gender:'male', age: 34},
  {name: {first: "Eva", middle: "Lu", last: "Ator"}, gender:'female', age: 40},
  {name: {first: "Lem", middle: "E.", last: "Tweakit"}, gender:'male', age: 45},
  {name: {first: "Louis", last: "Reasoner"}, gender:'male', age: 21}
];

///--------------------------------------------------------
/// Return the average age of all of the people in the array people.
///--------------------------------------------------------

function averageAge(people) {
	/// YOUR CODE HERE
}

///--------------------------------------------------------
/// Return the sum of the age of all men in the array people.
///--------------------------------------------------------

function sumOfMen(people) {
	/// YOUR CODE HERE
}

///--------------------------------------------------------
/// Return an array with all people over 35.
///--------------------------------------------------------

function over35(people) {
	/// YOUR CODE HERE
}

///--------------------------------------------------------
/// Return an array with all people that have a last name
/// starting with a defined letter.
///--------------------------------------------------------

function lastName(people, letter) {
	/// YOUR CODE HERE
}

///--------------------------------------------------------
/// Return an array with all females that have a last name
/// longer than n letters
///--------------------------------------------------------

function femaleNameLength(people, n) {
	/// YOUR CODE HERE
}

///--------------------------------------------------------
/// Return an object with just the name age pairs of the
/// females under the age n.
///--------------------------------------------------------

function femaleUnder37(people, n) {
	/// YOUR CODE HERE
}

///--------------------------------------------------------
/// PRINT ODDS (Difficulty: 2/5)
///--------------------------------------------------------

/// Tags: Higher-order functions, objects

/// Write a function printOdds that takes an object and
/// returns an array with the odd values found in the
/// object.

// var x = {a: 6, b: 33, c: 12, d: 3};
// printOdds(x) => [33, 3]

function printOdds(x) {
/// YOUR CODE HERE
}

///--------------------------------------------------------
///--------------------------------------------------------
/// LARGEST BOX ART (Difficulty: 2/5)
///--------------------------------------------------------
///--------------------------------------------------------

/// Tags: Higher-order functions, objects, arrays

/// Return an array containing only the URL of the largest box art.

var boxarts = [
    { width: 200, height:200, url:"http://cdn-0.nflximg.com/images/2891/Fracture200.jpg" },
    { width: 150, height:200, url:"http://cdn-0.nflximg.com/images/2891/Fracture150.jpg" },
    { width: 300, height:200, url:"http://cdn-0.nflximg.com/images/2891/Fracture300.jpg" },
    { width: 425, height:150, url:"http://cdn-0.nflximg.com/images/2891/Fracture425.jpg" }
];

function largest(arr) {
/// YOUR CODE HERE
}

///--------------------------------------------------------
///--------------------------------------------------------
/// OBJECT SOME (Difficulty: 2/5)
///--------------------------------------------------------
///--------------------------------------------------------

/// Tags: Higher-order functions, objects

/// Write a function objectSome() that looks through an array of
/// objects (first argument collection) and returns an array of all objects
/// that have matching property and value pairs (second argument).
/// Each property and value pair of the source object has to be present in the
/// object from the collection if it is to be included in the returned array.
/// Try using filter

var obj1 = [
  { "a": 1, "b": 2 },
  { "a": 1 },
  { "a": 1, "b": 2, "c": 2 }
];

var obj2 = [
  { first: "Romeo", last: "Montague" },
  { first: "Mercutio", last: null },
  { first: "Tybalt", last: "Capulet" }
];

// objectSome(obj1, { "a": 1, "c": 2 });
// -> [{ "a": 1, "b": 2, "c": 2 }]

// objectSome(obj2, { last: "Capulet" });
// -> [{ first: "Tybalt", last: "Capulet" }]

function objectSome(collection, source) {
 /// YOUR CODE HERE
}

///--------------------------------------------------------
///--------------------------------------------------------
/// LARGEST NUMS (Difficulty: 2/5)
///--------------------------------------------------------
///--------------------------------------------------------

/// Tags: Higher-order functions, arrays

/// Return an array containing the largest number in each nested
/// array of numbers.  If array contains nothing, return null.
/// Use map and reduce to implement.

// largestNums([[4, 5, 1, 3, 10, 100], [13, 27, 18, 26], [32, 35, 37, 50, 39], [1000, 1001]]);
// => [ 100, 27, 50, 1001 ]

// largestNums([[], [2, 3, 1], [0]]);
// => [ null, 3, 0 ]

function largestNums(arr) {
/// YOUR CODE HERE
}

///--------------------------------------------------------
///--------------------------------------------------------
/// DESTROYER (Difficulty: 2/5)
///--------------------------------------------------------
///--------------------------------------------------------

/// Tags: Higher-order functions, arrays

/// Function destroyer will take an initial array
/// (the first argument in the destroyer function), followed by
/// one or more arguments.  It will remove all elements from the
/// initial array that are of the same value as these arguments.
/// Use filter or reduce

// destroyer([1, 2, 3, 1, 2, 3], 3, 2);
// => [1, 1]
// destroyer([5, 0, 5, 1, 2, 10, 6, 6, 3, 5], 5, 6, 10);
// => [ 0, 1, 2, 3 ]
// destroyer([1, 2, 3], 5, 6, 10);
// => [ 1, 2, 3 ]
// destroyer([1, 2, 3]);
// => [ 1, 2, 3 ]

function destroyer(arr) {
/// YOUR CODE HERE
}

///--------------------------------------------------------
///--------------------------------------------------------
/// EUCLIDEAN VALUE (Difficulty: 2/5)
///--------------------------------------------------------
///--------------------------------------------------------

/// Tags: Higher-order functions, callbacks, arrays

/// Write a function merge that takes two arrays of equal length and returns a single array that merges the values as a result of a callback.

function merge(arr1, arr2, callback) {
  /// YOUR CODE HERE
}

/// Write the callback function add
function add(a, b) {
  /// YOUR CODE HERE
}

/// x = merge([1, 5, 3, 12], [4, 7, 13, 3], add)
/// x === [5, 12, 16, 15]

/// Write a function using merge and reduce to find the euclidean distance between two points in a two-dimensional space.
/// Equation for calculating hypotenuse:  sqrt ( legLength1^2 + legLength2^2 )

function euclid(point1, point2) {
  /// YOUR CODE HERE
}

/// y = euclid([3, 5], [7, 2]);
/// y === 5

<commit_msg>Add expand<commit_after>///--------------------------------------------------------
///--------------------------------------------------------
/// ARRAY OF OBJECTS (Difficulty: 1/5)
///--------------------------------------------------------
///--------------------------------------------------------

/// Multi-part Problem

/// Tags: Higher-order functions, objects, arrays

var people = [
  {name: {first: "Alyssa", middle: "P.", last: "Hacker"}, gender:'female', age: 26},
  {name: {first: "Ben", last: "Bitdiddle"}, gender:'male', age: 34},
  {name: {first: "Eva", middle: "Lu", last: "Ator"}, gender:'female', age: 40},
  {name: {first: "Lem", middle: "E.", last: "Tweakit"}, gender:'male', age: 45},
  {name: {first: "Louis", last: "Reasoner"}, gender:'male', age: 21}
];

///--------------------------------------------------------
/// Return the average age of all of the people in the array people.
///--------------------------------------------------------

function averageAge(people) {
	/// YOUR CODE HERE
}

///--------------------------------------------------------
/// Return the sum of the age of all men in the array people.
///--------------------------------------------------------

function sumOfMen(people) {
	/// YOUR CODE HERE
}

///--------------------------------------------------------
/// Return an array with all people over 35.
///--------------------------------------------------------

function over35(people) {
	/// YOUR CODE HERE
}

///--------------------------------------------------------
/// Return an array with all people that have a last name
/// starting with a defined letter.
///--------------------------------------------------------

function lastName(people, letter) {
	/// YOUR CODE HERE
}

///--------------------------------------------------------
/// Return an array with all females that have a last name
/// longer than n letters
///--------------------------------------------------------

function femaleNameLength(people, n) {
	/// YOUR CODE HERE
}

///--------------------------------------------------------
/// Return an object with just the name age pairs of the
/// females under the age n.
///--------------------------------------------------------

function femaleUnder37(people, n) {
	/// YOUR CODE HERE
}

///--------------------------------------------------------
/// PRINT ODDS (Difficulty: 2/5)
///--------------------------------------------------------

/// Tags: Higher-order functions, objects

/// Write a function printOdds that takes an object and
/// returns an array with the odd values found in the
/// object.

// var x = {a: 6, b: 33, c: 12, d: 3};
// printOdds(x) => [33, 3]

function printOdds(x) {
/// TO DO: YOUR CODE HERE
}

///--------------------------------------------------------
///--------------------------------------------------------
/// LARGEST BOX ART (Difficulty: 2/5)
///--------------------------------------------------------
///--------------------------------------------------------

/// Tags: Higher-order functions, objects, arrays

/// Return an array containing only the URL of the largest box art.

var boxarts = [
    { width: 200, height:200, url:"http://cdn-0.nflximg.com/images/2891/Fracture200.jpg" },
    { width: 150, height:200, url:"http://cdn-0.nflximg.com/images/2891/Fracture150.jpg" },
    { width: 300, height:200, url:"http://cdn-0.nflximg.com/images/2891/Fracture300.jpg" },
    { width: 425, height:150, url:"http://cdn-0.nflximg.com/images/2891/Fracture425.jpg" }
];

function largest(arr) {
/// TO DO: YOUR CODE HERE
}

///--------------------------------------------------------
///--------------------------------------------------------
/// OBJECT SOME (Difficulty: 2/5)
///--------------------------------------------------------
///--------------------------------------------------------

/// Tags: Higher-order functions, objects

/// Write a function objectSome() that looks through an array of
/// objects (first argument collection) and returns an array of all objects
/// that have matching property and value pairs (second argument).
/// Each property and value pair of the source object has to be present in the
/// object from the collection if it is to be included in the returned array.
/// Try using filter

var obj1 = [
  { "a": 1, "b": 2 },
  { "a": 1 },
  { "a": 1, "b": 2, "c": 2 }
];

var obj2 = [
  { first: "Romeo", last: "Montague" },
  { first: "Mercutio", last: null },
  { first: "Tybalt", last: "Capulet" }
];

// objectSome(obj1, { "a": 1, "c": 2 });
// -> [{ "a": 1, "b": 2, "c": 2 }]

// objectSome(obj2, { last: "Capulet" });
// -> [{ first: "Tybalt", last: "Capulet" }]

function objectSome(collection, source) {
 /// TO DO: YOUR CODE HERE
}

///--------------------------------------------------------
///--------------------------------------------------------
/// LARGEST NUMS (Difficulty: 2/5)
///--------------------------------------------------------
///--------------------------------------------------------

/// Tags: Higher-order functions, arrays

/// Return an array containing the largest number in each nested
/// array of numbers.  If array contains nothing, return null.
/// Use map and reduce to implement.

// largestNums([[4, 5, 1, 3, 10, 100], [13, 27, 18, 26], [32, 35, 37, 50, 39], [1000, 1001]]);
// => [ 100, 27, 50, 1001 ]

// largestNums([[], [2, 3, 1], [0]]);
// => [ null, 3, 0 ]

function largestNums(arr) {
/// TO DO: YOUR CODE HERE
}

///--------------------------------------------------------
///--------------------------------------------------------
/// DESTROYER (Difficulty: 2/5)
///--------------------------------------------------------
///--------------------------------------------------------

/// Tags: Higher-order functions, arrays

/// Function destroyer will take an initial array
/// (the first argument in the destroyer function), followed by
/// one or more arguments.  It will remove all elements from the
/// initial array that are of the same value as these arguments.
/// Use filter or reduce

// destroyer([1, 2, 3, 1, 2, 3], 3, 2);
// => [1, 1]
// destroyer([5, 0, 5, 1, 2, 10, 6, 6, 3, 5], 5, 6, 10);
// => [ 0, 1, 2, 3 ]
// destroyer([1, 2, 3], 5, 6, 10);
// => [ 1, 2, 3 ]
// destroyer([1, 2, 3]);
// => [ 1, 2, 3 ]

function destroyer(arr) {
/// YOUR CODE HERE
}

///--------------------------------------------------------
///--------------------------------------------------------
/// EUCLIDEAN VALUE (Difficulty: 3/5)
///--------------------------------------------------------
///--------------------------------------------------------

/// Tags: Higher-order functions, callbacks, arrays

/// Write a function merge that takes two arrays of equal length and returns a single array that merges the values as a result of a callback.

function merge(arr1, arr2, callback) {
  /// TO DO:YOUR CODE HERE
}

/// Write the callback function add
function add(a, b) {
  /// TO DO:YOUR CODE HERE
}

/// x = merge([1, 5, 3, 12], [4, 7, 13, 3], add)
/// x === [5, 12, 16, 15]

/// Write a function using merge and reduce to find the euclidean distance between two points in a two-dimensional space.
/// Equation for calculating hypotenuse:  sqrt ( legLength1^2 + legLength2^2 )

function euclid(point1, point2) {
  /// TO DO:YOUR CODE HERE
}

/// y = euclid([3, 5], [7, 2]);
/// y === 5

///--------------------------------------------------------
///--------------------------------------------------------
/// EXPAND (Difficulty: 3/5)
///--------------------------------------------------------
///--------------------------------------------------------

/// Tags: Higher-order functions, callbacks, arrays

/// Write a function expand that takes a function (callback) and value as parameters and returns an array containing the results of the callback. The callback function will always return a tuple OR null.  The first value in the tuple will be used as the value on the subsequent call, and the second value in the tuple will be added to the end of the array.  The function will continue running until the callback evaluates to null.

// let until20 = function(num) {
//   if (num > 20) {
//    return null;
//   } else {
//     return [num + 5, num]
//   }
// }
// expand(until20, 9);
// => [9, 14, 19]

function expand(callback, initVal) {
  /// TO DO: YOUR CODE HERE
}
<|endoftext|>


<commit_before>import { call, put, select } from 'redux-saga/effects'
import {
  loadAccountsSuccess,
  saveAccount,
  saveAccountSuccess,
  saveAccountFailure,
  removeAccount,
  removeAccountSuccess
} from '../actions/entities/accounts'
import { saveTransaction } from '../actions/entities/transactions'
import {
  loadAccountsSaga,
  saveAccountSaga,
  saveTransactionSaga,
  removeAccountSaga
} from './accounts'
import { getAccount } from '../selectors/entities/accounts'
import AccountsStorage from '../util/storage/accounts'

it('loads accounts', () => {
  const gen = loadAccountsSaga()

  expect(gen.next().value).toEqual(call(AccountsStorage.loadAll))
  const loaded = ['foo', 'bar']
  expect(gen.next(loaded).value).toEqual(put(loadAccountsSuccess(loaded)))
  expect(gen.next().done).toBeTruthy()
})

describe('save account', () => {
  const account = { id: 'A12345', name: 'foo' }
  const action = saveAccount(account)
  let gen
  beforeEach(() => (gen = saveAccountSaga(action)))

  it('puts success when no error', () => {
    expect(gen.next().value).toEqual(call(AccountsStorage.save, account))
    expect(gen.next().value).toEqual(put(saveAccountSuccess()))
    expect(gen.next().done).toBeTruthy()
  })

  it('puts failure when error', () => {
    expect(gen.next().value).toEqual(call(AccountsStorage.save, account))
    expect(gen.throw().value).toEqual(put(saveAccountFailure(account.id)))
  })
})

it('saves accounts affected in transaction', () => {
  const transaction = {
    id: 'T12345',
    accountId: 'A12345',
    linkedAccountId: 'A12346'
  }
  const accountA = { id: 'A12345', name: 'foo' }
  const accountB = { id: 'A12346', name: 'bar' }
  const action = saveTransaction(transaction)
  const gen = saveTransactionSaga(action)

  expect(gen.next().value).toEqual(call(getAccount, accountA.id))
  const selectorA = function() {}
  expect(gen.next(selectorA).value).toEqual(select(selectorA))
  expect(gen.next(accountA).value).toEqual(call(AccountsStorage.save, accountA))

  expect(gen.next().value).toEqual(call(getAccount, accountB.id))
  const selectorB = function() {}
  expect(gen.next(selectorB).value).toEqual(select(selectorB))
  expect(gen.next(accountB).value).toEqual(call(AccountsStorage.save, accountB))

  expect(gen.next().done).toBeTruthy()
})

it('removes account', () => {
  const action = removeAccount('A12345')
  const gen = removeAccountSaga(action)

  expect(gen.next().value).toEqual(call(AccountsStorage.remove, 'A12345'))
  expect(gen.next().value).toEqual(put(removeAccountSuccess()))
  expect(gen.next().done).toBeTruthy()
})
<commit_msg>Check if generator is finished<commit_after>import { call, put, select } from 'redux-saga/effects'
import {
  loadAccountsSuccess,
  saveAccount,
  saveAccountSuccess,
  saveAccountFailure,
  removeAccount,
  removeAccountSuccess
} from '../actions/entities/accounts'
import { saveTransaction } from '../actions/entities/transactions'
import {
  loadAccountsSaga,
  saveAccountSaga,
  saveTransactionSaga,
  removeAccountSaga
} from './accounts'
import { getAccount } from '../selectors/entities/accounts'
import AccountsStorage from '../util/storage/accounts'

it('loads accounts', () => {
  const gen = loadAccountsSaga()

  expect(gen.next().value).toEqual(call(AccountsStorage.loadAll))
  const loaded = ['foo', 'bar']
  expect(gen.next(loaded).value).toEqual(put(loadAccountsSuccess(loaded)))
  expect(gen.next().done).toBeTruthy()
})

describe('save account', () => {
  const account = { id: 'A12345', name: 'foo' }
  const action = saveAccount(account)
  let gen
  beforeEach(() => (gen = saveAccountSaga(action)))

  it('puts success when no error', () => {
    expect(gen.next().value).toEqual(call(AccountsStorage.save, account))
    expect(gen.next().value).toEqual(put(saveAccountSuccess()))
    expect(gen.next().done).toBeTruthy()
  })

  it('puts failure when error', () => {
    expect(gen.next().value).toEqual(call(AccountsStorage.save, account))
    expect(gen.throw().value).toEqual(put(saveAccountFailure(account.id)))
    expect(gen.next().done).toBeTruthy()
  })
})

it('saves accounts affected in transaction', () => {
  const transaction = {
    id: 'T12345',
    accountId: 'A12345',
    linkedAccountId: 'A12346'
  }
  const accountA = { id: 'A12345', name: 'foo' }
  const accountB = { id: 'A12346', name: 'bar' }
  const action = saveTransaction(transaction)
  const gen = saveTransactionSaga(action)

  expect(gen.next().value).toEqual(call(getAccount, accountA.id))
  const selectorA = function() {}
  expect(gen.next(selectorA).value).toEqual(select(selectorA))
  expect(gen.next(accountA).value).toEqual(call(AccountsStorage.save, accountA))

  expect(gen.next().value).toEqual(call(getAccount, accountB.id))
  const selectorB = function() {}
  expect(gen.next(selectorB).value).toEqual(select(selectorB))
  expect(gen.next(accountB).value).toEqual(call(AccountsStorage.save, accountB))

  expect(gen.next().done).toBeTruthy()
})

it('removes account', () => {
  const action = removeAccount('A12345')
  const gen = removeAccountSaga(action)

  expect(gen.next().value).toEqual(call(AccountsStorage.remove, 'A12345'))
  expect(gen.next().value).toEqual(put(removeAccountSuccess()))
  expect(gen.next().done).toBeTruthy()
})
<|endoftext|>


<commit_before>import unused from './es6-shims'; // eslint-disable-line
import Rx from 'rx';
import React from 'react';
import Fetchr from 'fetchr';
import debugFactory from 'debug';
import { Router } from 'react-router';
import { createLocation, createHistory } from 'history';
import { hydrate } from 'thundercats';
import { Render } from 'thundercats-react';

import { app$ } from '../common/app';

const debug = debugFactory('fcc:client');
const DOMContianer = document.getElementById('fcc');
const catState = window.__fcc__.data || {};
const services = new Fetchr({
  xhrPath: '/services'
});

Rx.config.longStackSupport = !!debug.enabled;
const history = createHistory();
const appLocation = createLocation(
  location.pathname + location.search
);
// returns an observable
app$({ history, location: appLocation })
  .flatMap(
    ({ AppCat }) => {
      // instantiate the cat with service
      const appCat = AppCat(null, services);
      // hydrate the stores
      return hydrate(appCat, catState)
        .map(() => appCat);
    },
    // not using nextLocation at the moment but will be used for
    // redirects in the future
    ({ nextLocation, props }, appCat) => ({ nextLocation, props, appCat })
  )
  .flatMap(({ props, appCat }) => {
    return Render(
      appCat,
      React.createElement(Router, props),
      DOMContianer
    );
  })
  .subscribe(
    () => {
      debug('react rendered');
    },
    err => {
      debug('an error has occured', err.stack);
    },
    () => {
      debug('react closed subscription');
    }
  );
<commit_msg>fix (hack) override history object with original<commit_after>import unused from './es6-shims'; // eslint-disable-line
import Rx from 'rx';
import React from 'react';
import Fetchr from 'fetchr';
import debugFactory from 'debug';
import { Router } from 'react-router';
import { createLocation, createHistory } from 'history';
import { hydrate } from 'thundercats';
import { Render } from 'thundercats-react';

import { app$ } from '../common/app';

const debug = debugFactory('fcc:client');
const DOMContianer = document.getElementById('fcc');
const catState = window.__fcc__.data || {};
const services = new Fetchr({
  xhrPath: '/services'
});

Rx.config.longStackSupport = !!debug.enabled;
const history = createHistory();
const appLocation = createLocation(
  location.pathname + location.search
);
// returns an observable
app$({ history, location: appLocation })
  .flatMap(
    ({ AppCat }) => {
      // instantiate the cat with service
      const appCat = AppCat(null, services);
      // hydrate the stores
      return hydrate(appCat, catState)
        .map(() => appCat);
    },
    // not using nextLocation at the moment but will be used for
    // redirects in the future
    ({ nextLocation, props }, appCat) => ({ nextLocation, props, appCat })
  )
  .flatMap(({ props, appCat }) => {
    props.history = history;
    return Render(
      appCat,
      React.createElement(Router, props),
      DOMContianer
    );
  })
  .subscribe(
    () => {
      debug('react rendered');
    },
    err => {
      debug('an error has occured', err.stack);
    },
    () => {
      debug('react closed subscription');
    }
  );
<|endoftext|>


<commit_before>var constants = require('./constants');
var baseConfig = require('./webpack.config');

module.exports = Object.assign(baseConfig, {
    output: {
        library: 'flight-with-child-components',
        filename: 'flight-with-child-components.js',
        libraryTarget: 'umd',
        path: constants.BUILD_DIRECTORY
    }
});
<commit_msg>feat: rename global to withChildComponents<commit_after>var constants = require('./constants');
var baseConfig = require('./webpack.config');

module.exports = Object.assign(baseConfig, {
    output: {
        library: 'withChildComponents',
        filename: 'flight-with-child-components.js',
        libraryTarget: 'umd',
        path: constants.BUILD_DIRECTORY
    }
});
<|endoftext|>


<commit_before>/* global AutoForm, _, Template */

AutoForm.addInputType("noUiSlider", {
  template: "afNoUiSlider",
  valueOut: function(){
    var slider = this.find('.nouislider');
    var isDecimal = this.closest(".at-nouislider").data("decimal");

    if( this.attr("data-type") === "Object" ){
      var parser = (isDecimal)? parseFloat : parseInt;
      var first = parser.call(null, slider.val()[0]);
      var second = parser.call(null, slider.val()[1]);
      var value = {
        lower: first > second ? second : first,
        upper: first > second ? first : second
      };
      return value;
    }else{
      return slider.val();
    }
  }
});

Template.afNoUiSlider.helpers({
  atts: function () {
    var data = Template.currentData(); // get data reactively
    var atts = data.atts;
    atts["data-type"] = data.schemaType.name;
    if( atts["class"] ){
      atts["class"] += " at-nouislider";
    }else{
      atts["class"] = "at-nouislider";
    }

    atts.doLabels = ( atts.labelLeft || atts.labelRight );

    atts["data-decimal"] = data.decimal;

    return _.omit(atts, 'noUiSliderOptions', 'noUiSlider_pipsOptions');
  }
});

var calculateOptions = function(data){
  var schemaMinMax = _.pick(data, 'max', 'min');
  var autoformOptions = _.pick(data.atts || {}, 'max', 'min', 'step', 'start', 'range');
  var noUiSliderOptions = (data.atts || {}).noUiSliderOptions;

  var options = _.extend({}, schemaMinMax, autoformOptions, noUiSliderOptions);

  // Adjust data initialization based on schema type
  if( options.start === undefined ){
    if( data.schemaType.name === "Object" ){
      if( data.value && data.value.lower ){
        options.start = [
          data.value.lower,
          data.value.upper
        ];
      }else{
        options.start = [
          typeof data.min === "number" ? data.min : 0,
          typeof data.max === "number" ? data.max : 100
        ];
      }
      options.connect = true;
    }else{
      options.start = data.value || 0;
    }
  } else {
    options.start = JSON.parse(options.start);
  }

  if( options.range === undefined ){
    options.range = {
      min: typeof options.min === "number" ? options.min : 0,
      max: typeof options.max === "number" ? options.max : 100
    };
  } else {
    options.range = JSON.parse(options.range);
  }
  delete options.min;
  delete options.max;

  // default step to 1 if not otherwise defined
  if( options.step === undefined ){
    options.step = 1;
  }

  return options;
};

Template.afNoUiSlider.rendered = function () {
  var template = this;
  var $s = template.$('.nouislider');

  var setup = function(c){
    var data = Template.currentData(); // get data reactively
    var options = calculateOptions( data );
    $s.noUiSlider(options, true);

    if (c.firstRun) {
      $s.on('slide', function(){
        // This is a trick to fool some logic in AutoForm that makes
        // sure values have actually changed on whichever element
        // emits a change event. Eventually AutoForm will give
        // input types the control of indicating exactly when
        // their value changes rather than relying on the change event
        $s.parent()[0].value = JSON.stringify($s.val());
        $s.parent().change();
        $s.data('changed','true');
      });
    }

    if( data.atts.noUiSlider_pipsOptions ){
      $s.noUiSlider_pips(
        data.atts.noUiSlider_pipsOptions
      );
    }
  };

  template.autorun( setup );
};
<commit_msg>Removed the JSON.parse that would overwrite configured options for range and start properties.<commit_after>/* global AutoForm, _, Template */

AutoForm.addInputType("noUiSlider", {
  template: "afNoUiSlider",
  valueOut: function(){
    var slider = this.find('.nouislider');
    var isDecimal = this.closest(".at-nouislider").data("decimal");

    if( this.attr("data-type") === "Object" ){
      var parser = (isDecimal)? parseFloat : parseInt;
      var first = parser.call(null, slider.val()[0]);
      var second = parser.call(null, slider.val()[1]);
      var value = {
        lower: first > second ? second : first,
        upper: first > second ? first : second
      };
      return value;
    }else{
      return slider.val();
    }
  }
});

Template.afNoUiSlider.helpers({
  atts: function () {
    var data = Template.currentData(); // get data reactively
    var atts = data.atts;
    atts["data-type"] = data.schemaType.name;
    if( atts["class"] ){
      atts["class"] += " at-nouislider";
    }else{
      atts["class"] = "at-nouislider";
    }

    atts.doLabels = ( atts.labelLeft || atts.labelRight );

    atts["data-decimal"] = data.decimal;

    return _.omit(atts, 'noUiSliderOptions', 'noUiSlider_pipsOptions');
  }
});

var calculateOptions = function(data){
  var schemaMinMax = _.pick(data, 'max', 'min');
  var autoformOptions = _.pick(data.atts || {}, 'max', 'min', 'step', 'start', 'range');
  var noUiSliderOptions = (data.atts || {}).noUiSliderOptions;

  var options = _.extend({}, schemaMinMax, autoformOptions, noUiSliderOptions);

  // Adjust data initialization based on schema type
  if( options.start === undefined ){
    if( data.schemaType.name === "Object" ){
      if( data.value && data.value.lower ){
        options.start = [
          data.value.lower,
          data.value.upper
        ];
      }else{
        options.start = [
          typeof data.min === "number" ? data.min : 0,
          typeof data.max === "number" ? data.max : 100
        ];
      }
      options.connect = true;
    }else{
      options.start = data.value || 0;
    }
  }

  if( options.range === undefined ){
    options.range = {
      min: typeof options.min === "number" ? options.min : 0,
      max: typeof options.max === "number" ? options.max : 100
    };
  }

  delete options.min;
  delete options.max;

  // default step to 1 if not otherwise defined
  if( options.step === undefined ){
    options.step = 1;
  }

  return options;
};

Template.afNoUiSlider.rendered = function () {
  var template = this;
  var $s = template.$('.nouislider');

  var setup = function(c){
    var data = Template.currentData(); // get data reactively
    var options = calculateOptions( data );
    $s.noUiSlider(options, true);

    if (c.firstRun) {
      $s.on('slide', function(){
        // This is a trick to fool some logic in AutoForm that makes
        // sure values have actually changed on whichever element
        // emits a change event. Eventually AutoForm will give
        // input types the control of indicating exactly when
        // their value changes rather than relying on the change event
        $s.parent()[0].value = JSON.stringify($s.val());
        $s.parent().change();
        $s.data('changed','true');
      });
    }

    if( data.atts.noUiSlider_pipsOptions ){
      $s.noUiSlider_pips(
        data.atts.noUiSlider_pipsOptions
      );
    }
  };

  template.autorun( setup );
};
<|endoftext|>


<commit_before>var dragDrop = require('drag-drop/buffer');
var id3v2 = require('id3v2-parser');
var BufferList = require('bl');

var parser = new id3v2();

dragDrop('body', function(files) {
  var bl = new BufferList();
  bl.append(files[0])
  bl.pipe(parser);
});

parser.on('data', function(tag) {
  console.log(tag);
});<commit_msg>Create a new parser for each file<commit_after>var dragDrop = require('drag-drop/buffer');
var id3v2 = require('id3v2-parser');
var BufferList = require('bl');

dragDrop('body', function(files) {
  var parser = new id3v2();

  parser.on('data', function(tag) {
    console.log(tag);
  });

  var bl = new BufferList();

  bl.append(files[0])
  bl.pipe(parser);
});<|endoftext|>


<commit_before>/*
 *  GameoverScene.js
 *  2014/06/23
 *  @auther minimo
 *  This Program is MIT license.
 *
 */

tm.define("shotgun.GameoverScene", {
    superClass: tm.app.Scene,

    parentScene: null,
    mode: 0,
    bonus: false,
    dispExtend: false,

    //ラベル用フォントパラメータ
    headerParam: {fontFamily:"CasinoRegular", align: "center", baseline:"middle", outlineWidth:2 },
    labelParam: {fontFamily:"Yasashisa", align: "center", baseline:"middle", outlineWidth:2 },
    scoreParam: {fontFamily:"Yasashisa", align: "left", baseline:"middle", outlineWidth:2 },
    extendParam: {fontFamily:"Yasashisa", align: "center", baseline:"middle", outlineWidth:2, fillStyle: "red" },

    init: function(parentScene) {
        this.superInit();
        this.background = "rgba(0, 0, 0, 0.0)";

        this.parentScene = parentScene;
        this.mode = parentScene.mode;
        this.bonus = parentScene.bonus;

        //スコア情報取得
        var m = appMain.returnJoker? this.mode+10: this.mode;
        var lastScore = appMain.lastScore[m];
        var highScore = appMain.highScore[m];
        var newRecord = parentScene.newRecord;

        //バックグラウンド
        this.bg = tm.display.RectangleShape({width: SC_W, height: SC_H, fillStyle: appMain.bgColor, strokeStyle: appMain.bgColor})
            .addChildTo(this)
            .setPosition(SC_W*0.5, SC_H*0.5);

        var that = this;
        var width = SC_W, height = 90;

        //メインとリザルトを分けてレイヤーを作成
        this.mainLayer = tm.app.Object2D().addChildTo(this);
        this.resultLayer = tm.app.Object2D().addChildTo(this);

        this.top = tm.display.OutlineLabel("RESULT", 60)
            .addChildTo(this)
            .setParam(this.headerParam)
            .setPosition(SC_W*0.5, SC_H*0.05);

        //スコア表示
        this.score = tm.display.OutlineLabel("SCORE "+lastScore, 50)
            .addChildTo(this)
            .setParam(this.labelParam)
            .setPosition(SC_W*0.5, SC_H*0.12);

        this.score = tm.display.OutlineLabel("YOUR BEST SCORE IS "+highScore, 35)
            .addChildTo(this)
            .setParam(this.labelParam)
            .setPosition(SC_W*0.5, SC_H*0.17);
        if (newRecord) {
            var nr = tm.display.OutlineLabel("NewRecord!!", 20)
                .addChildTo(this)
                .setParam(this.labelParam)
                .setFillStyle("Red")
                .setFillStyleOutline("rgb(255,200,200)")
                .setPosition(SC_W*0.82, SC_H*0.20);
        }

        //GameCenterへスコア登録
        submitScore(this.mode, appMain.returnJoker, lastScore);

        //役一覧
        for (var i = 0; i < 12; i++) {
            var handName = $trans(appMain.handList[i].name);
            tm.display.OutlineLabel(handName+":"+this.parentScene.handCount[appMain.handList[i].point], 35)
                .addChildTo(this.resultLayer)
                .setParam(this.scoreParam)
                .setPosition(SC_W*0.2, SC_H*0.22+(i*42));
        }

        //ボタン用パラメータ
        var param = {flat: appMain.buttonFlat, fontSize:50};

        //全画面広告ボタン
/*
        this.Ad = shotgun.Button(width*0.3, height, "Ad", param)
            .addChildTo(this)
            .setPosition(SC_W*0.15, SC_H*0.7)
            .addEventListener("pushed", function() {
                if(ENABLE_PHONEGAP && AdMob) {
                    AdMob.prepareInterstitial({
                        adId:admobid.interstitial,
                        autoShow:true
                    });
                }
                if (that.mode != GAMEMODE_HARD) appMain.bonusLife = 1;
            });
*/
        //GAMECENTER
        shotgun.Button(width*0.4, height, "RANKING", param)
            .addChildTo(this)
            .setPosition(SC_W*0.5, SC_H*0.70)
            .addEventListener("pushed", function() {
                var mode = that.parentScene.mode;
                var lb = "Normal_";
                if (mode == GAMEMODE_HARD) lb = "Hard_";
                if (appMain.returnJoker) lb += "RJ";
                showLeadersBoard(lb);
            });

        //SNS
        shotgun.Button(width*0.3, height, "SNS", param)
            .addChildTo(this)
            .setPosition(SC_W*0.85, SC_H*0.70)
            .addEventListener("pushed", function() {
                sendSocialMessage(that.mode, appMain.returnJoker, lastScore);
            });

        //リトライボタン
        this.retry = shotgun.Button(width, height, "TRY AGAIN", param)
            .addChildTo(this)
            .setPosition(SC_W*0.5, SC_H*0.78)
            .addEventListener("pushed", function() {
                var mode = that.parentScene.mode;
                that.parentScene = null;
                that.mask.tweener.clear().fadeIn(300).call(function(){appMain.replaceScene(shotgun.MainScene(mode, true));});
            });

        //戻るボタン
        this.back = shotgun.Button(width, height, "RETURN TO TITLE", param)
            .addChildTo(this)
            .setPosition(SC_W*0.5, SC_H*0.86)
            .addEventListener("pushed", function() {
                that.parentScene = null;
                that.mask.tweener.clear().fadeIn(300).call(function(){appMain.replaceScene(shotgun.TitleScene());});
            });

        //ライフサービステロップ
/*
        if (this.mode == GAMEMODE_NORMAL && !this.bonus) {
            if (appMain.telopCount < 0 || appMain.firstNormalGameOver) {
                this.telop = shotgun.Telop()
                    .addChildTo(this)
                    .setPosition(SC_W*0.5, SC_H*0.5)
                    .add({text:$trans("Adボタンで広告を見るとライフ１個ボーナス！"), size:28, dispWait:5000, silent:true});
                appMain.telopCount = 4;
            }
            appMain.telopCount--;
            appMain.firstNormalGameOver = false;
            appMain.saveConfig();
        }
*/
        //目隠し
        this.mask = tm.display.RectangleShape({width: SC_W, height: SC_H, fillStyle: "rgba(0, 0, 0, 1.0)", strokeStyle: "rgba(0, 0, 0, 1.0)"})
            .addChildTo(this)
            .setPosition(SC_W*0.5, SC_H*0.5);
        this.mask.tweener.clear().fadeOut(200);

        //全画面広告
        var dice = rand(0, 10);
        if (dice < 3) {
            if(ENABLE_PHONEGAP && AdMob) {
                function(){
                    AdMob.prepareInterstitial({
                        adId:admobid.interstitial,
                        autoShow:true
                    });
                }();
            }
        }
    },

    update: function() {
        if (!this.dispExtend && appMain.bonusLife != 0) {
            var that = this;
            var c = tm.display.Sprite("card", CARD_W, CARD_H)
                .addChildTo(this.retry)
                .setPosition(190, 0)
                .setFrameIndex(13*3)
                .tweener.clear()
                .fadeOut(1)
                .wait(1000)
                .call(function(){
                    that.Ad.remove();
                })
                .wait(1000)
                .fadeIn(1)
                .scale(0.4, 1000, "easeOutBounce")
                .call(function(){
                    tm.display.OutlineLabel("+", 70)
                        .addChildTo(that.retry)
                        .setParam(that.extendParam)
                        .setPosition(150, 0);
                });
            this.dispExtend = true;
        }
    },

    //タッチorクリック開始処理
    ontouchstart: function(e) {
    },

    //タッチorクリック移動処理
    ontouchmove: function(e) {
    },

    //タッチorクリック終了処理
    ontouchend: function(e) {
    },

});
<commit_msg>広告関連再修正<commit_after>/*
 *  GameoverScene.js
 *  2014/06/23
 *  @auther minimo
 *  This Program is MIT license.
 *
 */

tm.define("shotgun.GameoverScene", {
    superClass: tm.app.Scene,

    parentScene: null,
    mode: 0,
    bonus: false,
    dispExtend: false,

    //ラベル用フォントパラメータ
    headerParam: {fontFamily:"CasinoRegular", align: "center", baseline:"middle", outlineWidth:2 },
    labelParam: {fontFamily:"Yasashisa", align: "center", baseline:"middle", outlineWidth:2 },
    scoreParam: {fontFamily:"Yasashisa", align: "left", baseline:"middle", outlineWidth:2 },
    extendParam: {fontFamily:"Yasashisa", align: "center", baseline:"middle", outlineWidth:2, fillStyle: "red" },

    init: function(parentScene) {
        this.superInit();
        this.background = "rgba(0, 0, 0, 0.0)";

        this.parentScene = parentScene;
        this.mode = parentScene.mode;
        this.bonus = parentScene.bonus;

        //スコア情報取得
        var m = appMain.returnJoker? this.mode+10: this.mode;
        var lastScore = appMain.lastScore[m];
        var highScore = appMain.highScore[m];
        var newRecord = parentScene.newRecord;

        //バックグラウンド
        this.bg = tm.display.RectangleShape({width: SC_W, height: SC_H, fillStyle: appMain.bgColor, strokeStyle: appMain.bgColor})
            .addChildTo(this)
            .setPosition(SC_W*0.5, SC_H*0.5);

        var that = this;
        var width = SC_W, height = 90;

        //メインとリザルトを分けてレイヤーを作成
        this.mainLayer = tm.app.Object2D().addChildTo(this);
        this.resultLayer = tm.app.Object2D().addChildTo(this);

        this.top = tm.display.OutlineLabel("RESULT", 60)
            .addChildTo(this)
            .setParam(this.headerParam)
            .setPosition(SC_W*0.5, SC_H*0.05);

        //スコア表示
        this.score = tm.display.OutlineLabel("SCORE "+lastScore, 50)
            .addChildTo(this)
            .setParam(this.labelParam)
            .setPosition(SC_W*0.5, SC_H*0.12);

        this.score = tm.display.OutlineLabel("YOUR BEST SCORE IS "+highScore, 35)
            .addChildTo(this)
            .setParam(this.labelParam)
            .setPosition(SC_W*0.5, SC_H*0.17);
        if (newRecord) {
            var nr = tm.display.OutlineLabel("NewRecord!!", 20)
                .addChildTo(this)
                .setParam(this.labelParam)
                .setFillStyle("Red")
                .setFillStyleOutline("rgb(255,200,200)")
                .setPosition(SC_W*0.82, SC_H*0.20);
        }

        //GameCenterへスコア登録
        submitScore(this.mode, appMain.returnJoker, lastScore);

        //役一覧
        for (var i = 0; i < 12; i++) {
            var handName = $trans(appMain.handList[i].name);
            tm.display.OutlineLabel(handName+":"+this.parentScene.handCount[appMain.handList[i].point], 35)
                .addChildTo(this.resultLayer)
                .setParam(this.scoreParam)
                .setPosition(SC_W*0.2, SC_H*0.22+(i*42));
        }

        //ボタン用パラメータ
        var param = {flat: appMain.buttonFlat, fontSize:50};

        //全画面広告ボタン
/*
        this.Ad = shotgun.Button(width*0.3, height, "Ad", param)
            .addChildTo(this)
            .setPosition(SC_W*0.15, SC_H*0.7)
            .addEventListener("pushed", function() {
                if(ENABLE_PHONEGAP && AdMob) {
                    AdMob.prepareInterstitial({
                        adId:admobid.interstitial,
                        autoShow:true
                    });
                }
                if (that.mode != GAMEMODE_HARD) appMain.bonusLife = 1;
            });
*/
        //GAMECENTER
        shotgun.Button(width*0.4, height, "RANKING", param)
            .addChildTo(this)
            .setPosition(SC_W*0.5, SC_H*0.70)
            .addEventListener("pushed", function() {
                var mode = that.parentScene.mode;
                var lb = "Normal_";
                if (mode == GAMEMODE_HARD) lb = "Hard_";
                if (appMain.returnJoker) lb += "RJ";
                showLeadersBoard(lb);
            });

        //SNS
        shotgun.Button(width*0.3, height, "SNS", param)
            .addChildTo(this)
            .setPosition(SC_W*0.85, SC_H*0.70)
            .addEventListener("pushed", function() {
                sendSocialMessage(that.mode, appMain.returnJoker, lastScore);
            });

        //リトライボタン
        this.retry = shotgun.Button(width, height, "TRY AGAIN", param)
            .addChildTo(this)
            .setPosition(SC_W*0.5, SC_H*0.78)
            .addEventListener("pushed", function() {
                var mode = that.parentScene.mode;
                that.parentScene = null;
                that.mask.tweener.clear().fadeIn(300).call(function(){appMain.replaceScene(shotgun.MainScene(mode, true));});
            });

        //戻るボタン
        this.back = shotgun.Button(width, height, "RETURN TO TITLE", param)
            .addChildTo(this)
            .setPosition(SC_W*0.5, SC_H*0.86)
            .addEventListener("pushed", function() {
                that.parentScene = null;
                that.mask.tweener.clear().fadeIn(300).call(function(){appMain.replaceScene(shotgun.TitleScene());});
            });

        //ライフサービステロップ
/*
        if (this.mode == GAMEMODE_NORMAL && !this.bonus) {
            if (appMain.telopCount < 0 || appMain.firstNormalGameOver) {
                this.telop = shotgun.Telop()
                    .addChildTo(this)
                    .setPosition(SC_W*0.5, SC_H*0.5)
                    .add({text:$trans("Adボタンで広告を見るとライフ１個ボーナス！"), size:28, dispWait:5000, silent:true});
                appMain.telopCount = 4;
            }
            appMain.telopCount--;
            appMain.firstNormalGameOver = false;
            appMain.saveConfig();
        }
*/
        //目隠し
        this.mask = tm.display.RectangleShape({width: SC_W, height: SC_H, fillStyle: "rgba(0, 0, 0, 1.0)", strokeStyle: "rgba(0, 0, 0, 1.0)"})
            .addChildTo(this)
            .setPosition(SC_W*0.5, SC_H*0.5);
        this.mask.tweener.clear().fadeOut(200);

        //全画面広告
        if(ENABLE_PHONEGAP && AdMob) {
            var dice = rand(0, 10);
            if (dice < 3) {
                AdMob.prepareInterstitial({
                    adId:admobid.interstitial,
                    autoShow:true
                });
            }
        }
    },

    update: function() {
        if (!this.dispExtend && appMain.bonusLife != 0) {
            var that = this;
            var c = tm.display.Sprite("card", CARD_W, CARD_H)
                .addChildTo(this.retry)
                .setPosition(190, 0)
                .setFrameIndex(13*3)
                .tweener.clear()
                .fadeOut(1)
                .wait(1000)
                .call(function(){
                    that.Ad.remove();
                })
                .wait(1000)
                .fadeIn(1)
                .scale(0.4, 1000, "easeOutBounce")
                .call(function(){
                    tm.display.OutlineLabel("+", 70)
                        .addChildTo(that.retry)
                        .setParam(that.extendParam)
                        .setPosition(150, 0);
                });
            this.dispExtend = true;
        }
    },

    //タッチorクリック開始処理
    ontouchstart: function(e) {
    },

    //タッチorクリック移動処理
    ontouchmove: function(e) {
    },

    //タッチorクリック終了処理
    ontouchend: function(e) {
    },

});
<|endoftext|>


<commit_before>import {startApp} from 'superdesk-core/scripts/index';
import annotationsLibraryExtension from 'superdesk-core/scripts/extensions/annotationsLibrary/dist/src/extension';
import markForUserExtension from 'superdesk-core/scripts/extensions/markForUser/dist/src/extension';
import datetimeFieldExtension from 'superdesk-core/scripts/extensions/datetimeField/dist/src/extension';
import planningExtension from 'superdesk-planning/client/planning-extension/dist/extension';

setTimeout(() => {
    startApp(
        [
            annotationsLibraryExtension,
            markForUserExtension,
            datetimeFieldExtension,
            planningExtension,
        ],
        {},
    );
});

export default angular.module('main.superdesk', []);
<commit_msg>redo extension loading (#3234)<commit_after>import {startApp} from 'superdesk-core/scripts/index';

setTimeout(() => {
    startApp(
        [
            {
                id: 'annotationsLibrary',
                load: () => import('superdesk-core/scripts/extensions/annotationsLibrary'),
            },
            {
                id: 'markForUserExtension',
                load: () => import('superdesk-core/scripts/extensions/markForUser'),
            },
            {
                id: 'datetimeFieldExtension',
                load: () => import('superdesk-core/scripts/extensions/datetimeField'),
            },
            {
                id: 'planningExtension',
                load: () => import('superdesk-planning/client/planning-extension'),
            },
        ],
        {},
    );
});

export default angular.module('main.superdesk', []);
<|endoftext|>


<commit_before>var stringify = require('../common/stringify')
var constant = require('./constants')
var util = require('../common/util')

var Karma = function (socket, iframe, opener, navigator, location) {
  var startEmitted = false
  var reloadingContext = false
  var self = this
  var queryParams = util.parseQueryParams(location.search)
  var browserId = queryParams.id || util.generateId('manual-')
  var displayName = queryParams.displayName
  var returnUrl = queryParams['return_url' + ''] || null

  var resultsBufferLimit = 50
  var resultsBuffer = []

  this.VERSION = constant.VERSION
  this.config = {}

  // Expose for testing purposes as there is no global socket.io
  // registry anymore.
  this.socket = socket

  // Set up postMessage bindings for current window
  // DEV: These are to allow windows in separate processes execute local tasks
  //   Electron is one of these environments
  if (window.addEventListener) {
    window.addEventListener('message', function handleMessage (evt) {
      // Resolve the origin of our message
      var origin = evt.origin || evt.originalEvent.origin

      // If the message isn't from our host, then reject it
      if (origin !== window.location.origin) {
        return
      }

      // Take action based on the message type
      var method = evt.data.__karmaMethod
      if (method) {
        if (!self[method]) {
          self.error('Received `postMessage` for "' + method + '" but the method doesn\'t exist')
          return
        }
        self[method].apply(self, evt.data.__karmaArguments)
      }
    }, false)
  }

  var childWindow = null
  var navigateContextTo = function (url) {
    if (self.config.useIframe === false) {
      // run in new window
      if (self.config.runInParent === false) {
        // If there is a window already open, then close it
        // DEV: In some environments (e.g. Electron), we don't have setter access for location
        if (childWindow !== null && childWindow.closed !== true) {
          childWindow.close()
        }
        childWindow = opener(url)
      // run context on parent element and dynamically loading scripts
      } else if (url !== 'about:blank') {
        var loadScript = function (idx) {
          if (idx < window.__karma__.scriptUrls.length) {
            var ele = document.createElement('script')
            ele.src = window.__karma__.scriptUrls[idx]
            ele.onload = function () {
              loadScript(idx + 1)
            }
            document.body.appendChild(ele)
          } else {
            window.__karma__.loaded()
          }
        }
        loadScript(0)
      }
    // run in iframe
    } else {
      iframe.src = url
    }
  }

  this.onbeforeunload = function () {
    if (!reloadingContext) {
      // TODO(vojta): show what test (with explanation about jasmine.UPDATE_INTERVAL)
      self.error('Some of your tests did a full page reload!')
    }
  }

  this.log = function (type, args) {
    var values = []

    for (var i = 0; i < args.length; i++) {
      values.push(this.stringify(args[i], 3))
    }

    this.info({log: values.join(', '), type: type})
  }

  this.stringify = stringify

  var clearContext = function () {
    reloadingContext = true

    navigateContextTo('about:blank')
  }

  // error during js file loading (most likely syntax error)
  // we are not going to execute at all
  this.error = function (msg, url, line) {
    var message = msg

    if (url) {
      message = msg + '\nat ' + url + (line ? ':' + line : '')
    }

    socket.emit('karma_error', message)
    this.complete()
    return false
  }

  this.result = function (result) {
    if (!startEmitted) {
      socket.emit('start', {total: null})
      startEmitted = true
    }

    if (resultsBufferLimit === 1) {
      return socket.emit('result', result)
    }

    resultsBuffer.push(result)

    if (resultsBuffer.length === resultsBufferLimit) {
      socket.emit('result', resultsBuffer)
      resultsBuffer = []
    }
  }

  this.complete = function (result) {
    if (resultsBuffer.length) {
      socket.emit('result', resultsBuffer)
      resultsBuffer = []
    }

    if (self.config.clearContext) {
      // give the browser some time to breath, there could be a page reload, but because a bunch of
      // tests could run in the same event loop, we wouldn't notice.
      setTimeout(function () {
        clearContext()
      }, 0)
    }

    socket.emit('complete', result || {}, function () {
      if (returnUrl) {
        location.href = returnUrl
      }
    })
  }

  this.info = function (info) {
    // TODO(vojta): introduce special API for this
    if (!startEmitted && util.isDefined(info.total)) {
      socket.emit('start', info)
      startEmitted = true
    } else {
      socket.emit('info', info)
    }
  }

  socket.on('execute', function (cfg) {
    // reset startEmitted and reload the iframe
    startEmitted = false
    self.config = cfg
    // if not clearing context, reloadingContext always true to prevent beforeUnload error
    reloadingContext = !self.config.clearContext
    navigateContextTo(constant.CONTEXT_URL)

    // clear the console before run
    // works only on FF (Safari, Chrome do not allow to clear console from js source)
    if (window.console && window.console.clear) {
      window.console.clear()
    }
  })
  socket.on('stop', function () {
    this.complete()
  }.bind(this))

  // report browser name, id
  socket.on('connect', function () {
    socket.io.engine.on('upgrade', function () {
      resultsBufferLimit = 1
    })
    var info = {
      name: navigator.userAgent,
      id: browserId
    }
    if (displayName) {
      info.displayName = displayName
    }
    socket.emit('register', info)
  })
}

module.exports = Karma
<commit_msg>fix(client): don't crash if receive array-like results<commit_after>var stringify = require('../common/stringify')
var constant = require('./constants')
var util = require('../common/util')

var Karma = function (socket, iframe, opener, navigator, location) {
  var startEmitted = false
  var reloadingContext = false
  var self = this
  var queryParams = util.parseQueryParams(location.search)
  var browserId = queryParams.id || util.generateId('manual-')
  var displayName = queryParams.displayName
  var returnUrl = queryParams['return_url' + ''] || null

  var resultsBufferLimit = 50
  var resultsBuffer = []

  this.VERSION = constant.VERSION
  this.config = {}

  // Expose for testing purposes as there is no global socket.io
  // registry anymore.
  this.socket = socket

  // Set up postMessage bindings for current window
  // DEV: These are to allow windows in separate processes execute local tasks
  //   Electron is one of these environments
  if (window.addEventListener) {
    window.addEventListener('message', function handleMessage (evt) {
      // Resolve the origin of our message
      var origin = evt.origin || evt.originalEvent.origin

      // If the message isn't from our host, then reject it
      if (origin !== window.location.origin) {
        return
      }

      // Take action based on the message type
      var method = evt.data.__karmaMethod
      if (method) {
        if (!self[method]) {
          self.error('Received `postMessage` for "' + method + '" but the method doesn\'t exist')
          return
        }
        self[method].apply(self, evt.data.__karmaArguments)
      }
    }, false)
  }

  var childWindow = null
  var navigateContextTo = function (url) {
    if (self.config.useIframe === false) {
      // run in new window
      if (self.config.runInParent === false) {
        // If there is a window already open, then close it
        // DEV: In some environments (e.g. Electron), we don't have setter access for location
        if (childWindow !== null && childWindow.closed !== true) {
          childWindow.close()
        }
        childWindow = opener(url)
      // run context on parent element and dynamically loading scripts
      } else if (url !== 'about:blank') {
        var loadScript = function (idx) {
          if (idx < window.__karma__.scriptUrls.length) {
            var ele = document.createElement('script')
            ele.src = window.__karma__.scriptUrls[idx]
            ele.onload = function () {
              loadScript(idx + 1)
            }
            document.body.appendChild(ele)
          } else {
            window.__karma__.loaded()
          }
        }
        loadScript(0)
      }
    // run in iframe
    } else {
      iframe.src = url
    }
  }

  this.onbeforeunload = function () {
    if (!reloadingContext) {
      // TODO(vojta): show what test (with explanation about jasmine.UPDATE_INTERVAL)
      self.error('Some of your tests did a full page reload!')
    }
  }

  this.log = function (type, args) {
    var values = []

    for (var i = 0; i < args.length; i++) {
      values.push(this.stringify(args[i], 3))
    }

    this.info({log: values.join(', '), type: type})
  }

  this.stringify = stringify

  var clearContext = function () {
    reloadingContext = true

    navigateContextTo('about:blank')
  }

  // error during js file loading (most likely syntax error)
  // we are not going to execute at all
  this.error = function (msg, url, line) {
    var message = msg

    if (url) {
      message = msg + '\nat ' + url + (line ? ':' + line : '')
    }

    socket.emit('karma_error', message)
    this.complete()
    return false
  }

  this.result = function (originalResult) {
    var convertedResult = {}

    // Convert all array-like objects to real arrays.
    for (var propertyName in originalResult) {
      if (originalResult.hasOwnProperty(propertyName)) {
        var propertyValue = originalResult[propertyName]

        if (Object.prototype.toString.call(propertyValue) === '[object Array]') {
          convertedResult[propertyName] = Array.prototype.slice.call(propertyValue)
        } else {
          convertedResult[propertyName] = propertyValue
        }
      }
    }

    if (!startEmitted) {
      socket.emit('start', {total: null})
      startEmitted = true
    }

    if (resultsBufferLimit === 1) {
      return socket.emit('result', convertedResult)
    }

    resultsBuffer.push(convertedResult)

    if (resultsBuffer.length === resultsBufferLimit) {
      socket.emit('result', resultsBuffer)
      resultsBuffer = []
    }
  }

  this.complete = function (result) {
    if (resultsBuffer.length) {
      socket.emit('result', resultsBuffer)
      resultsBuffer = []
    }

    if (self.config.clearContext) {
      // give the browser some time to breath, there could be a page reload, but because a bunch of
      // tests could run in the same event loop, we wouldn't notice.
      setTimeout(function () {
        clearContext()
      }, 0)
    }

    socket.emit('complete', result || {}, function () {
      if (returnUrl) {
        location.href = returnUrl
      }
    })
  }

  this.info = function (info) {
    // TODO(vojta): introduce special API for this
    if (!startEmitted && util.isDefined(info.total)) {
      socket.emit('start', info)
      startEmitted = true
    } else {
      socket.emit('info', info)
    }
  }

  socket.on('execute', function (cfg) {
    // reset startEmitted and reload the iframe
    startEmitted = false
    self.config = cfg
    // if not clearing context, reloadingContext always true to prevent beforeUnload error
    reloadingContext = !self.config.clearContext
    navigateContextTo(constant.CONTEXT_URL)

    // clear the console before run
    // works only on FF (Safari, Chrome do not allow to clear console from js source)
    if (window.console && window.console.clear) {
      window.console.clear()
    }
  })
  socket.on('stop', function () {
    this.complete()
  }.bind(this))

  // report browser name, id
  socket.on('connect', function () {
    socket.io.engine.on('upgrade', function () {
      resultsBufferLimit = 1
    })
    var info = {
      name: navigator.userAgent,
      id: browserId
    }
    if (displayName) {
      info.displayName = displayName
    }
    socket.emit('register', info)
  })
}

module.exports = Karma
<|endoftext|>


<commit_before>window.light = {};

light.init = function(){

	//switch off when quality is medium
	if(DDD.quality){
		DDD.lightPulses = false;
	}

	//add main light
 	light.intensity = DDD.lightPulses ? 0.7 : 1;
 	light.hemisphere = new THREE.HemisphereLight(0xffffff, 0x999999, light.intensity);
 	DDD.scene.add(light.hemisphere);

 	light.fadeIn();

 	//create message lights - windows sucks
 	light.nr = DDD.directX ? 75 : 100;
 	light.base = new THREE.PointLight( 0xffffff, 0, 700 );
 	DDD.scene.add(light.base);

	if(DDD.lightPulses)	light.create();
};

light.fadeIn = function(){

	$({foo:0}).animate({foo:100}, {
		duration: 5000,
	    step: function(val) {

	    	//fade hemispere
	        light.hemisphere.intensity = (val/100)*light.intensity;

	        //fade lines
	        $.each(graph.force.links(), function(key, link){
		        DDD.lines[key].material.opacity = (val/100)*0.2;
		    });
	    }
	})

};

light.create = function(){
	light.l = [];
	for (var i = 0 ; i < light.nr ; i ++){
		light.l[i] = light.base.clone();
		DDD.scene.add(light.l[i]);
	}

	light.i = 0;
}

light.get = function(){
	var l = light.l[light.i];
	light.i++;
	if(light.i >= light.nr) light.i = 0;
	return l;
}<commit_msg>bug fix<commit_after>window.light = {};

light.init = function(){

	//switch off when quality is medium
	if(DDD.quality < 2){
		DDD.lightPulses = false;
	}

	//add main light
 	light.intensity = DDD.lightPulses ? 0.7 : 1;
 	light.hemisphere = new THREE.HemisphereLight(0xffffff, 0x999999, light.intensity);
 	DDD.scene.add(light.hemisphere);

 	light.fadeIn();

 	//create message lights - windows sucks
 	light.nr = DDD.directX ? 75 : 100;
 	light.base = new THREE.PointLight( 0xffffff, 0, 700 );
 	DDD.scene.add(light.base);

	if(DDD.lightPulses)	light.create();
};

light.fadeIn = function(){

	$({foo:0}).animate({foo:100}, {
		duration: 5000,
	    step: function(val) {

	    	//fade hemispere
	        light.hemisphere.intensity = (val/100)*light.intensity;

	        //fade lines
	        $.each(graph.force.links(), function(key, link){
		        DDD.lines[key].material.opacity = (val/100)*0.2;
		    });
	    }
	})

};

light.create = function(){
	light.l = [];
	for (var i = 0 ; i < light.nr ; i ++){
		light.l[i] = light.base.clone();
		DDD.scene.add(light.l[i]);
	}

	light.i = 0;
}

light.get = function(){
	var l = light.l[light.i];
	light.i++;
	if(light.i >= light.nr) light.i = 0;
	return l;
}<|endoftext|>


<commit_before>'use strict'

import React, {
  Component,
  DatePickerAndroid,
  Image,
  StyleSheet,
  Switch,
  Text,
  TextInput,
  TouchableWithoutFeedback,
  View
} from 'react-native';

import Button from '../components/button';
import Header from '../components/header';

import ButtonStyles from '../styles/button-styles';

class CreateEvent extends Component {

  constructor(props) {
    super(props);
    this.state = {
      loaded: true,

      title: '',
      publicEvent: true,
      dateStart: 'pick a start date',
      dateEnd: 'pick an end date',
      description: ''
    }
  }

  async showDatePicker(stateKey, options, start) {
    try {
      var newState = {};
      var tempDate = new Date();
      var tempDateStr = tempDate.toLocaleDateString();
      const {action, year, month, day} = await DatePickerAndroid.open(options);

      if (action === DatePickerAndroid.dismissedAction) {
        if(start) {
          tempDateStr = this.state.dateStart;
        } else {
          tempDateStr = this.state.dateEnd;
        }
      } else {
        tempDate = new Date(year, month, day);
        tempDateStr = tempDate.toLocaleDateString();
      }
      if(start) {
        this.setState({dateStart: tempDateStr});
      } else {
        this.setState({dateEnd: tempDateStr});
      }
    } catch ({code, message}) {
      console.warn(`Error in example '${stateKey}': `, message);
    }
  }

  render(){
    return(
      <View style = {{backgroundColor: 'orange', flex: 1}}>
        {this.renderPageTitle()}
        {this.renderToggle()}
        {this.renderTitleInput()}
        {this.renderDateTimeInput()}
        {this.renderDescriptionInput()}
        {this.renderButtons()}
      </View>
    );
  }

  renderPageTitle(){
    return(
      <Header
        text = "Create a New Event"
        loaded = {this.state.loaded}
      />
    );
  }

  renderToggle(){
    return(
      <View style = {{flexDirection:'row'}}>
        <Switch
          onTintColor = "#0000ff"
          onValueChange = {(value) => this.setState({publicEvent: value})}
          style = {{marginBottom: 10}}
          value = {this.state.publicEvent}
        />
        <Text>
          {this.state.publicEvent ? ' Public Event' : 'Private Event'}
        </Text>
      </View>
    );
  }

  renderTitleInput(){
    return(
      <TextInput
        blurOnSubmit = {true}
        onChangeText = {(text) => this.setState({title: text})}
        value = {this.state.title}
        placeholder = {"Give Your Event a Title."}
        placeholderTextColor = 'black'
        underlineColorAndroid = 'black'
      />
    );
  }

  renderDateTimeInput(){
    return (
      <View>
        <Text style = {{color:'white'}}>
          Start:
        </Text>
        <View style = {{ flexDirection:'row'}}>
          <TouchableWithoutFeedback onPress = {
            this.showDatePicker.bind(this, 'min', {
              date: this.state.minDate,
              minDate: new Date(),
            }, true)
          }>
            <Text style = {{color:'black'}}>
              {this.state.dateStart}
            </Text>
          </TouchableWithoutFeedback>
        </View>
        <Text style = {{color:'white'}}>
          End:
        </Text>
        <View style = {{ flexDirection:'row'}}>
          <View style = {{ flexDirection:'row'}}>
            <TouchableWithoutFeedback onPress = {
              this.showDatePicker.bind(this, 'min', {
                date: this.state.minDate,
                minDate: new Date(this.state.dateStart),
              }, false )
            }>
              <Text style = {{color:'black'}}>
                {this.state.dateEnd}
              </Text>
            </TouchableWithoutFeedback>
          </View>
        </View>
      </View>
    );
  }

  renderDescriptionInput(){
    var limit = 100;
    var remainder = limit - this.state.description.length;
    var remainderColor = remainder > 5 ? 'blue' : 'red';

    return (
      <View>
        <TextInput
          maxLength = {limit}
          multiline = {true}
          style = {Header.body, {color:'black'}}
          onChangeText = {(text) => this.setState({description: text})}
          value = {this.state.description}
          placeholder = {"Leave a short description of your event for your guests:"}
          placeholderTextColor = 'black'
          underlineColorAndroid = 'black'
        />
        <Text style = {{color: remainderColor}}>
          {remainder}
        </Text>
      </View>
    );
  }

  renderButtons(){
    return (
      <View style = {{alignItems: 'center'}}>
        <Button
          text = "Invite Friends!"
          onPress = {this.createGuestList.bind(this)}
          button_styles = {ButtonStyles.primary_button}
          button_text_styles = {ButtonStyles.primary_button_text}
        />

        <Button
          text = "Create Event!"
          onPress = {this.createEvent.bind(this)}
          button_styles = {ButtonStyles.primary_button}
          button_text_styles = {ButtonStyles.primary_button_text}
        />

      <Button
        text = "Clear"
        onPress = {this.clearEvent.bind(this)}
        button_styles = {ButtonStyles.primary_button}
        button_text_styles = {ButtonStyles.primary_button_text}
      />

    </View>
    );
  }

  createGuestList(){
    alert('friends list unimplemented')
  }

  createEvent(){

    alert(this.state.title)
    alert('this event is a public event: ' + this.state.publicEvent);
    alert('start: ' + this.state.dateStart + ' end: ' + this.state.dateEnd);
    alert(this.state.description);
  }

  clearEvent(){
    alert('Cleared :(');
    this.setState({
      title: '',
      publicEvent: true,
      dateStart: 'pick a start date',
      dateEnd: 'pick an end date',
      description: ''
    })

  }
}

module.exports = CreateEvent;
<commit_msg>setting event time; note: it's not working<commit_after>'use strict'

import React, {
  Component,
  DatePickerAndroid,
  Image,
  StyleSheet,
  Switch,
  Text,
  TextInput,
  TouchableWithoutFeedback,
  TimePickerAndroid,
  View
} from 'react-native';

import Button from '../components/button';
import Header from '../components/header';

import ButtonStyles from '../styles/button-styles';

class CreateEvent extends Component {

  constructor(props) {
    super(props);
    this.state = {
      loaded: true,

      title: '',
      publicEvent: true,
      dateStart: 'pick a start date',
      dateEnd: 'pick an end date',
      timeStart: 'pick a start time',
      timeEnd: 'pick an end time',
      description: ''
    }
  }

  async showDatePicker(stateKey, options, start) {
    try {
      var newState = {};
      var tempDate = new Date();
      var tempDateStr = tempDate.toLocaleDateString();
      const {action, year, month, day} = await DatePickerAndroid.open(options);

      if (action === DatePickerAndroid.dismissedAction) {
        if(start) {
          tempDateStr = this.state.dateStart;
        } else {
          tempDateStr = this.state.dateEnd;
        }
      } else {
        tempDate = new Date(year, month, day);
        tempDateStr = tempDate.toLocaleDateString();
      }
      if(start) {
        this.setState({dateStart: tempDateStr});
      } else {
        this.setState({dateEnd: tempDateStr});
      }
    } catch ({code, message}) {
      console.warn(`Error in example '${stateKey}': `, message);
    }
  }

  async showTimePicker(stateKey, start) {
    try {
      const {action, m, h} = await TimePickerAndroid.open();
      tempMin = m;
      tempHour = h;
      var tempTimeStr = '';

      if (action === TimePickerAndroid.dismissedAction) {
        if(start) {
          tempTimeStr = this.state.timeStart;
        } else {
          tempTimeStr = this.state.timeEnd;
        }
      } else if(action === TimePickerAndroid.timeSetAction){
        alert('poo');
        tempTimeStr = this.formatTime(h, m);

      }
      if(start) {
        this.setState({timeStart: tempTimeStr});
      } else {
        this.setState({timeEnd: tempTimeStr});
      }
    } catch ({code, message}) {
      console.warn(`Error in example '${stateKey}': `, message);
    }
  }

  formatTime(hour, minute) {
    return hour + ':' + (minute < 10 ? '0' + minute : minute);
  }

  render(){
    return(
      <View style = {{backgroundColor: 'orange', flex: 1}}>
        {this.renderPageTitle()}
        {this.renderToggle()}
        {this.renderTitleInput()}
        {this.renderDateTimeInput()}
        {this.renderDescriptionInput()}
        {this.renderButtons()}
      </View>
    );
  }

  renderPageTitle(){
    return(
      <Header
        text = "Create a New Event"
        loaded = {this.state.loaded}
      />
    );
  }

  renderToggle(){
    return(
      <View style = {{flexDirection:'row'}}>
        <Switch
          onTintColor = "#0000ff"
          onValueChange = {(value) => this.setState({publicEvent: value})}
          style = {{marginBottom: 10}}
          value = {this.state.publicEvent}
        />
        <Text>
          {this.state.publicEvent ? ' Public Event' : 'Private Event'}
        </Text>
      </View>
    );
  }

  renderTitleInput(){
    return(
      <TextInput
        blurOnSubmit = {true}
        onChangeText = {(text) => this.setState({title: text})}
        value = {this.state.title}
        placeholder = {"Give Your Event a Title."}
        placeholderTextColor = 'black'
        underlineColorAndroid = 'black'
      />
    );
  }

  renderDateTimeInput(){
    return (
      <View>

        <Text style = {{color:'white'}}>
          Start:
        </Text>

        <View style = {{ flexDirection:'row'}}>
          <TouchableWithoutFeedback onPress = {
            this.showDatePicker.bind(this, 'min', {
              date: this.state.minDate,
              minDate: new Date(),
            }, true)
          }>
            <Text style = {{color:'black'}}>
              {this.state.dateStart}
            </Text>
          </TouchableWithoutFeedback>

          <TouchableWithoutFeedback
            onPress={this.showTimePicker.bind(this, true)}>
            <Text style={{color:'black'}}>{this.state.timeStart}</Text>
          </TouchableWithoutFeedback>

        </View>

        <Text style = {{color:'white'}}>
          End:
        </Text>
        <View style = {{ flexDirection:'row'}}>
          <View style = {{ flexDirection:'row'}}>
            <TouchableWithoutFeedback onPress = {
              this.showDatePicker.bind(this, 'min', {
                date: this.state.minDate,
                minDate: new Date(this.state.dateStart),
              }, false )
            }>
              <Text style = {{color:'black'}}>
                {this.state.dateEnd}
              </Text>
            </TouchableWithoutFeedback>
          </View>
        </View>
      </View>
    );
  }

  renderDescriptionInput(){
    var limit = 100;
    var remainder = limit - this.state.description.length;
    var remainderColor = remainder > 5 ? 'blue' : 'red';

    return (
      <View>
        <TextInput
          maxLength = {limit}
          multiline = {true}
          style = {Header.body, {color:'black'}}
          onChangeText = {(text) => this.setState({description: text})}
          value = {this.state.description}
          placeholder = {"Leave a short description of your event for your guests:"}
          placeholderTextColor = 'black'
          underlineColorAndroid = 'black'
        />
        <Text style = {{color: remainderColor}}>
          {remainder}
        </Text>
      </View>
    );
  }

  renderButtons(){
    return (
      <View style = {{alignItems: 'center'}}>
        <Button
          text = "Invite Friends!"
          onPress = {this.createGuestList.bind(this)}
          button_styles = {ButtonStyles.primary_button}
          button_text_styles = {ButtonStyles.primary_button_text}
        />

        <Button
          text = "Create Event!"
          onPress = {this.createEvent.bind(this)}
          button_styles = {ButtonStyles.primary_button}
          button_text_styles = {ButtonStyles.primary_button_text}
        />

      <Button
        text = "Clear"
        onPress = {this.clearEvent.bind(this)}
        button_styles = {ButtonStyles.primary_button}
        button_text_styles = {ButtonStyles.primary_button_text}
      />

    </View>
    );
  }

  createGuestList(){
    alert('friends list unimplemented')
  }

  createEvent(){

    alert(this.state.title)
    alert('this event is a public event: ' + this.state.publicEvent);
    alert('start: ' + this.state.dateStart + ' end: ' + this.state.dateEnd);
    alert(this.state.description);
  }

  clearEvent(){
    alert('Cleared :(');
    this.setState({
      title: '',
      publicEvent: true,
      dateStart: 'pick a start date',
      dateEnd: 'pick an end date',
      timeStart: 'pick a start time',
      timeEnd: 'pick an end time',
      description: ''
    })

  }
}

module.exports = CreateEvent;
<|endoftext|>


<commit_before>import EventEmitter from 'events'

class FeedcastApi extends EventEmitter {
  constructor(){
    super();
    this.apiUrl = 'https://www.feedcast.com.br/api'
  }

  getChannels({page = 1, per_page = 24}){
    return new Promise((complete, reject) => {
      const req = new XMLHttpRequest();

      req.open('GET', `${this.apiUrl}/channels?page=${page}&per_page=${per_page}`, true);

      req.onload = () => {
        let result = JSON.parse(req.response)
        //TODO: get total from responseHeaders
        // when it is allowed by server
        result.total = 178
        complete(result);
      };

      req.onerror = () => {
        reject(req.statusText);
      };

      req.send();
    })
  }

  getChannelInfo({uuid = null}){
    return new Promise((complete, reject) => {
      const req = new XMLHttpRequest();

      req.open('GET', `${this.apiUrl}/channels/${uuid}`, true);

      req.onload = () => {
        let result = JSON.parse(req.response)
        complete(result);
      };

      req.onerror = () => {
        reject(req.statusText);
      };

      req.send();
    })
  }

  getChannelEpisodes({ uuid = null, page = 1, per_page = 10}){
    return new Promise((complete, reject) => {
      const req = new XMLHttpRequest();

      const url = `${this.apiUrl}/channels/${uuid}/episodes`;

      req.open('GET',`${url}?page=${page}&per_page=${per_page}`, true);

      req.onload = () => {
        let result = JSON.parse(req.response);
        //TODO: get total from responseHeaders
        // when it is allowed by server
        result.total = 500
        complete(result);
      };

      req.onerror = () => {
        reject(req.statusText);
      };

      req.send();
    })
  }

}

const feedcastApi = new FeedcastApi();

export default feedcastApi;
<commit_msg>feature: Get total results from api response header<commit_after>import EventEmitter from 'events'

class FeedcastApi extends EventEmitter {
  constructor(){
    super();
    this.apiUrl = 'https://www.feedcast.com.br/api'
  }

  getChannels({page = 1, per_page = 24}){
    return new Promise((complete, reject) => {
      const req = new XMLHttpRequest();

      req.open('GET', `${this.apiUrl}/channels?page=${page}&per_page=${per_page}`, true);

      req.onload = () => {
        let result = JSON.parse(req.response)
        result.total = req.getResponseHeader('total')
        complete(result);
      };

      req.onerror = () => {
        reject(req.statusText);
      };

      req.send();
    })
  }

  getChannelInfo({uuid = null}){
    return new Promise((complete, reject) => {
      const req = new XMLHttpRequest();

      req.open('GET', `${this.apiUrl}/channels/${uuid}`, true);

      req.onload = () => {
        let result = JSON.parse(req.response)
        complete(result);
      };

      req.onerror = () => {
        reject(req.statusText);
      };

      req.send();
    })
  }

  getChannelEpisodes({ uuid = null, page = 1, per_page = 10}){
    return new Promise((complete, reject) => {
      const req = new XMLHttpRequest();

      const url = `${this.apiUrl}/channels/${uuid}/episodes`;

      req.open('GET',`${url}?page=${page}&per_page=${per_page}`, true);

      req.onload = () => {
        let result = JSON.parse(req.response);
        result.total = req.getResponseHeader('total')
        complete(result);
      };

      req.onerror = () => {
        reject(req.statusText);
      };

      req.send();
    })
  }

}

const feedcastApi = new FeedcastApi();

export default feedcastApi;
<|endoftext|>


<commit_before>// Backbone.Repository
// -------------------
// v0.1.0
//
// Copyright (c)2013-2014 John Nickell
// Distributed under MIT license
(function (root, factory) {

    if (typeof define == 'function' && define.amd) {
        // AMD
        define(['backbone', 'jquery', 'underscore'], factory);
    } else if (typeof exports == 'object') {
        // Node
        module.exports = factory(require('backbone'), require('jquery'), require('underscore'));
    } else {
        // Browser globals
        factory(root.Backbone, root.jQuery, root._);
    }

})(this, function (Backbone, $, _) {

    "use strict";

    // Backbone.Repository constructor
    var Repository = Backbone.Repository = function (options) {
        options || (options = {});
        // Allows setting modelType at runtime
        if (options.modelType) {
            this.modelType = options.modelType;
        }
        // Allows setting collectionType at runtime
        if (options.collectionType) {
            this.collectionType = options.collectionType;
        }
    };

    // Add Repository methods
    _.extend(Repository.prototype, {

        // Default model type
        modelType: Backbone.Model,

        // Default collection type
        collectionType: Backbone.Collection,

        // Backbone.Repository.findAll
        // ---------------------------
        // Fetches the collection
        //
        // param object parameters Additional data to send
        //
        // returns jQuery.Promise
        findAll: function (parameters) {
            var collection = new this.collectionType();

            return this._fetch(collection, parameters);
        },

        // Backbone.Repository.find
        // ------------------------
        // Fetches a single model by ID
        //
        // param integer id         The model id
        // param object  parameters Additional data to send
        //
        // returns jQuery.Promise
        find: function (id, parameters) {
            var model = new this.modelType({id: id});

            return this._fetch(model, parameters);
        },

        // Backbone.Repository.findBy
        // --------------------------
        // Fetches a set of models by search criteria
        //
        // param object  criteria   Attribute hash to match
        // param object  parameters Additional data to send
        // param boolean first      True to return the first match only
        //
        // returns jQuery.Promise
        findBy: function (criteria, parameters, first) {
            var collection = new this.collectionType();

            return this._fetchWhere(collection, criteria, parameters, first);
        },

        // Backbone.Repository.findOneBy
        // -----------------------------
        // Fetches a single model by search criteria
        //
        // param object criteria   Attribute hash to match
        // param object parameters Additional data to send
        //
        // returns jQuery.Promise
        findOneBy: function (criteria, parameters) {
            return this.findBy(criteria, parameters, true);
        },

        // Backbone.Repository.insert
        // --------------------------
        // Persists a new model to a collection
        //
        // param Backbone.Collection collection The collection instance
        // param object              data       The model attributes
        //
        // returns jQuery.Promise
        insert: function (collection, data) {
            var defer = $.Deferred();
            var promise = defer.promise();
            var model = collection.create(data, {
                wait: true,
                success: _.bind(this._deferSuccess, defer),
                error: _.bind(this._deferError, defer)
            });

            return promise;
        },

        // Backbone.Repository.save
        // ------------------------
        // Alias for Backbone.Repository.update
        //
        // param Backbone.Model model The model instance
        // param object         data  The model attributes
        //
        // returns jQuery.Promise
        save: function (model, data) {
            return this.update(model, data);
        },

        // Backbone.Repository.update
        // --------------------------
        // Saves a model apart from a collection
        //
        // param Backbone.Model model The model instance
        // param object         data  The model attributes
        //
        // returns jQuery.Promise
        update: function (model, data) {
            var defer = $.Deferred();
            var promise = defer.promise();
            model.save(data, {
                wait: true,
                success: _.bind(this._deferSuccess, defer),
                error: _.bind(this._deferError, defer)
            });

            return promise;
        },

        // Backbone.Repository.remove
        // --------------------------
        // Removes a model from persistance
        //
        // param Backbone.Model model The model instance
        //
        // returns jQuery.Promise
        remove: function (model) {
            var defer = $.Deferred();
            var promise = defer.promise();
            model.destroy({
                wait: true,
                success: _.bind(this._deferSuccess, defer),
                error: _.bind(this._deferError, defer)
            });

            return promise;
        },

        // Handles server read operation
        // internal
        // returns jQuery.Promise
        _fetch: function (object, parameters) {
            var defer = $.Deferred();
            var promise = defer.promise();
            object.fetch({
                success: _.bind(this._deferSuccess, defer),
                error: _.bind(this._deferError, defer),
                data: parameters
            });

            return promise;
        },

        // Handles criteria read operation
        // internal
        // returns jQuery.Promise
        _fetchWhere: function (collection, criteria, parameters, first) {
            var defer = $.Deferred();
            var promise = defer.promise();
            collection.fetch({
                success: function (data, response, options) {
                    defer.resolve(first ? data.findWhere(criteria) : data.where(criteria));
                },
                error: function (data, response, options) {
                    defer.reject(response.responseJSON ? response.responseJSON : response);
                },
                data: parameters
            });

            return promise;
        },

        // Resolves a deferred response after a success
        // internal
        // returns void
        _deferSuccess: function (data, response, options) {
            this.resolve(data);
        },

        // Resolves a deferred response after an error
        // internal
        // returns void
        _deferError: function (data, response, options) {
            this.reject(response.responseJSON ? response.responseJSON : response);
        }

    });

    // Add Backbone extend method
    Repository.extend = Backbone.Model.extend;

    // Return Repository constructor
    return Repository;

});
<commit_msg>responseText appears to be more reliable<commit_after>// Backbone.Repository
// -------------------
// v0.1.0
//
// Copyright (c)2013-2014 John Nickell
// Distributed under MIT license
(function (root, factory) {

    if (typeof define == 'function' && define.amd) {
        // AMD
        define(['backbone', 'jquery', 'underscore'], factory);
    } else if (typeof exports == 'object') {
        // Node
        module.exports = factory(require('backbone'), require('jquery'), require('underscore'));
    } else {
        // Browser globals
        factory(root.Backbone, root.jQuery, root._);
    }

})(this, function (Backbone, $, _) {

    "use strict";

    // Backbone.Repository constructor
    var Repository = Backbone.Repository = function (options) {
        options || (options = {});
        // Allows setting modelType at runtime
        if (options.modelType) {
            this.modelType = options.modelType;
        }
        // Allows setting collectionType at runtime
        if (options.collectionType) {
            this.collectionType = options.collectionType;
        }
    };

    // Add Repository methods
    _.extend(Repository.prototype, {

        // Default model type
        modelType: Backbone.Model,

        // Default collection type
        collectionType: Backbone.Collection,

        // Backbone.Repository.findAll
        // ---------------------------
        // Fetches the collection
        //
        // param object parameters Additional data to send
        //
        // returns jQuery.Promise
        findAll: function (parameters) {
            var collection = new this.collectionType();

            return this._fetch(collection, parameters);
        },

        // Backbone.Repository.find
        // ------------------------
        // Fetches a single model by ID
        //
        // param integer id         The model id
        // param object  parameters Additional data to send
        //
        // returns jQuery.Promise
        find: function (id, parameters) {
            var model = new this.modelType({id: id});

            return this._fetch(model, parameters);
        },

        // Backbone.Repository.findBy
        // --------------------------
        // Fetches a set of models by search criteria
        //
        // param object  criteria   Attribute hash to match
        // param object  parameters Additional data to send
        // param boolean first      True to return the first match only
        //
        // returns jQuery.Promise
        findBy: function (criteria, parameters, first) {
            var collection = new this.collectionType();

            return this._fetchWhere(collection, criteria, parameters, first);
        },

        // Backbone.Repository.findOneBy
        // -----------------------------
        // Fetches a single model by search criteria
        //
        // param object criteria   Attribute hash to match
        // param object parameters Additional data to send
        //
        // returns jQuery.Promise
        findOneBy: function (criteria, parameters) {
            return this.findBy(criteria, parameters, true);
        },

        // Backbone.Repository.insert
        // --------------------------
        // Persists a new model to a collection
        //
        // param Backbone.Collection collection The collection instance
        // param object              data       The model attributes
        //
        // returns jQuery.Promise
        insert: function (collection, data) {
            var defer = $.Deferred();
            var promise = defer.promise();
            var model = collection.create(data, {
                wait: true,
                success: _.bind(this._deferSuccess, defer),
                error: _.bind(this._deferError, defer)
            });

            return promise;
        },

        // Backbone.Repository.save
        // ------------------------
        // Alias for Backbone.Repository.update
        //
        // param Backbone.Model model The model instance
        // param object         data  The model attributes
        //
        // returns jQuery.Promise
        save: function (model, data) {
            return this.update(model, data);
        },

        // Backbone.Repository.update
        // --------------------------
        // Saves a model apart from a collection
        //
        // param Backbone.Model model The model instance
        // param object         data  The model attributes
        //
        // returns jQuery.Promise
        update: function (model, data) {
            var defer = $.Deferred();
            var promise = defer.promise();
            model.save(data, {
                wait: true,
                success: _.bind(this._deferSuccess, defer),
                error: _.bind(this._deferError, defer)
            });

            return promise;
        },

        // Backbone.Repository.remove
        // --------------------------
        // Removes a model from persistance
        //
        // param Backbone.Model model The model instance
        //
        // returns jQuery.Promise
        remove: function (model) {
            var defer = $.Deferred();
            var promise = defer.promise();
            model.destroy({
                wait: true,
                success: _.bind(this._deferSuccess, defer),
                error: _.bind(this._deferError, defer)
            });

            return promise;
        },

        // Handles server read operation
        // internal
        // returns jQuery.Promise
        _fetch: function (object, parameters) {
            var defer = $.Deferred();
            var promise = defer.promise();
            object.fetch({
                success: _.bind(this._deferSuccess, defer),
                error: _.bind(this._deferError, defer),
                data: parameters
            });

            return promise;
        },

        // Handles criteria read operation
        // internal
        // returns jQuery.Promise
        _fetchWhere: function (collection, criteria, parameters, first) {
            var defer = $.Deferred();
            var promise = defer.promise();
            collection.fetch({
                success: function (data, response, options) {
                    defer.resolve(first ? data.findWhere(criteria) : data.where(criteria));
                },
                error: function (data, response, options) {
                    defer.reject(response.responseJSON ? response.responseJSON : response);
                },
                data: parameters
            });

            return promise;
        },

        // Resolves a deferred response after a success
        // internal
        // returns void
        _deferSuccess: function (data, response, options) {
            this.resolve(data);
        },

        // Resolves a deferred response after an error
        // internal
        // returns void
        _deferError: function (data, response, options) {
            this.reject(response.responseText ? response.responseText : response);
        }

    });

    // Add Backbone extend method
    Repository.extend = Backbone.Model.extend;

    // Return Repository constructor
    return Repository;

});
<|endoftext|>


<commit_before>for (var i = 0; i < 6; i++) {
  var row = document.querySelector("table").insertRow(-1);
  for (var j = 0; j < 6; j++) {
    var letter = String.fromCharCode("A".charCodeAt(0) + j - 1);
    row.insertCell(-1).innerHTML = i && j ? "<input id='" + letter + i + "'/>" :
      i || letter;
  }
}

var DATA = {};
var INPUTS = [].slice.call(document.querySelectorAll("input"));

INPUTS.forEach(function (element) {

  element.onfocus = function (event) {
    event.target.value = localStorage[event.target.id] || "";
  };

  element.onblur = function (event) {
    localStorage[event.target.id] = event.target.value;
    window.computeAll();
  };

  function getter() {
    var value = localStorage[element.id] || "";
    if (value.charAt(0) === "=") {
      console.log('DATA:', DATA, value.substring(1));
      //DATA
      return DATA.eval(value.substring(1));
    } else {
      return isNaN(parseFloat(value)) ? value : parseFloat(value);
    }
  }

  Object.defineProperty(DATA, element.id, {
    get: getter
  });

  Object.defineProperty(DATA, element.id.toLowerCase(), {
    get: getter
  });

});

window.computeAll = (function () {
  return function () {
    INPUTS.forEach(function (element) {
      try {
        element.value = DATA[element.id];
      } catch (exception) {
        //console.warn('Exception:', exception);
      }
    });
  };
})();
<commit_msg>Added a tokenizer function that is used to split entries.<commit_after>for (var i = 0; i < 6; i++) {
  var row = document.querySelector("table").insertRow(-1);
  for (var j = 0; j < 6; j++) {
    var letter = String.fromCharCode("A".charCodeAt(0) + j - 1);
    row.insertCell(-1).innerHTML = i && j ? "<input id='" + letter + i + "'/>" :
      i || letter;
  }
}

function tokenize(value) {
  var results = [];
  var tokenRegEx =
    /\s*([A-Z]|\d+|\d+|[+\-\/\*]|sum\(\s*[a-z]\d+\s*:\s*[a-z]\d+\s*\))/g;

  var m;
  while ((m = tokenRegEx.exec(value)) !== null) {
    results.push(m[0]);
  }
  return result;
}

var DATA = {};
var INPUTS = [].slice.call(document.querySelectorAll("input"));

INPUTS.forEach(function (element) {

  element.onfocus = function (event) {
    event.target.value = localStorage[event.target.id] || "";
  };

  element.onblur = function (event) {
    localStorage[event.target.id] = event.target.value;
    window.computeAll();
  };

  function getter() {
    var value = localStorage[element.id] || "";
    if (value.charAt(0) === "=") {
      console.log('DATA:', DATA, value.substring(1));
      //DATA
      return DATA.eval(value.substring(1));
    } else {
      return isNaN(parseFloat(value)) ? value : parseFloat(value);
    }
  }

  Object.defineProperty(DATA, element.id, {
    get: getter
  });

  Object.defineProperty(DATA, element.id.toLowerCase(), {
    get: getter
  });

});

window.computeAll = (function () {
  return function () {
    INPUTS.forEach(function (element) {
      try {
        element.value = DATA[element.id];
      } catch (exception) {
        //console.warn('Exception:', exception);
      }
    });
  };
})();
<|endoftext|>