<commit_before>import extend from '../utils/extend'
import { isSSR } from './platform'

let
  cookieSource,
  ssrRes

function encode (string) {
  return encodeURIComponent(string)
}

function decode (string) {
  return decodeURIComponent(string)
}

function stringifyCookieValue (value) {
  return encode(value === Object(value) ? JSON.stringify(value) : '' + value)
}

function read (string) {
  if (string === '') {
    return string
  }

  if (string.indexOf('"') === 0) {
    // This is a quoted cookie as according to RFC2068, unescape...
    string = string.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\')
  }

  // Replace server-side written pluses with spaces.
  // If we can't decode the cookie, ignore it, it's unusable.
  // If we can't parse the cookie, ignore it, it's unusable.
  string = decode(string.replace(/\+/g, ' '))

  try {
    string = JSON.parse(string)
  }
  catch (e) {}

  return string
}

function set (key, val, opts = {}) {
  let time = opts.expires

  if (typeof opts.expires === 'number') {
    time = new Date()
    time.setMilliseconds(time.getMilliseconds() + opts.expires * 864e+5)
  }

  const cookie = [
    encode(key), '=', stringifyCookieValue(val),
    time ? '; expires=' + time.toUTCString() : '', // use expires attribute, max-age is not supported by IE
    opts.path ? '; path=' + opts.path : '',
    opts.domain ? '; domain=' + opts.domain : '',
    opts.secure ? '; secure' : ''
  ].join('')

  if (isSSR) {
    ssrRes.setHeader('Set-Cookie', cookie)
  }
  else {
    document.cookie = cookie
  }
}

function get (key) {
  let
    result = key ? undefined : {},
    cookies = cookieSource.cookie ? cookieSource.cookie.split('; ') : [],
    i = 0,
    l = cookies.length,
    parts,
    name,
    cookie

  for (; i < l; i++) {
    parts = cookies[i].split('=')
    name = decode(parts.shift())
    cookie = parts.join('=')

    if (!key) {
      result[name] = cookie
    }
    else if (key === name) {
      result = read(cookie)
      break
    }
  }

  return result
}

function remove (key, options) {
  set(key, '', extend(true, {}, options, {
    expires: -1
  }))
}

function has (key) {
  return get(key) !== undefined
}

export default {
  get,
  set,
  has,
  remove,
  all: () => get(),

  __installed: false,
  install ({ $q, cfg }) {
    if (this.__installed) { return }
    this.__installed = true

    if (isSSR) {
      cookieSource = cfg.ssr.req.headers
      ssrRes = cfg.ssr.res
    }
    else {
      cookieSource = document
    }

    $q.cookies = this
  }
}
<commit_msg>feat: SSR - cookie plugin small enhancement<commit_after>import extend from '../utils/extend'
import { isSSR } from './platform'

let
  cookieSource,
  ssrRes

function encode (string) {
  return encodeURIComponent(string)
}

function decode (string) {
  return decodeURIComponent(string)
}

function stringifyCookieValue (value) {
  return encode(value === Object(value) ? JSON.stringify(value) : '' + value)
}

function read (string) {
  if (string === '') {
    return string
  }

  if (string.indexOf('"') === 0) {
    // This is a quoted cookie as according to RFC2068, unescape...
    string = string.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\')
  }

  // Replace server-side written pluses with spaces.
  // If we can't decode the cookie, ignore it, it's unusable.
  // If we can't parse the cookie, ignore it, it's unusable.
  string = decode(string.replace(/\+/g, ' '))

  try {
    string = JSON.parse(string)
  }
  catch (e) {}

  return string
}

function set (key, val, opts = {}) {
  let time = opts.expires

  if (typeof opts.expires === 'number') {
    time = new Date()
    time.setMilliseconds(time.getMilliseconds() + opts.expires * 864e+5)
  }

  const keyValue = `${encode(key)}=${stringifyCookieValue(val)}`

  const cookie = [
    keyValue,
    time ? '; expires=' + time.toUTCString() : '', // use expires attribute, max-age is not supported by IE
    opts.path ? '; path=' + opts.path : '',
    opts.domain ? '; domain=' + opts.domain : '',
    opts.secure ? '; secure' : ''
  ].join('')

  if (isSSR) {
    ssrRes.setHeader('Set-Cookie', cookie)

    // make temporary update so future get()
    // within same SSR timeframe would return the set value
    cookieSource.cookie = cookieSource.cookie
      ? `${keyValue}; ${cookieSource.cookie}`
      : cookie
  }
  else {
    document.cookie = cookie
  }
}

function get (key) {
  let
    result = key ? undefined : {},
    cookies = cookieSource.cookie ? cookieSource.cookie.split('; ') : [],
    i = 0,
    l = cookies.length,
    parts,
    name,
    cookie

  for (; i < l; i++) {
    parts = cookies[i].split('=')
    name = decode(parts.shift())
    cookie = parts.join('=')

    if (!key) {
      result[name] = cookie
    }
    else if (key === name) {
      result = read(cookie)
      break
    }
  }

  return result
}

function remove (key, options) {
  set(key, '', extend(true, {}, options, {
    expires: -1
  }))
}

function has (key) {
  return get(key) !== undefined
}

export default {
  get,
  set,
  has,
  remove,
  all: () => get(),

  __installed: false,
  install ({ $q, cfg }) {
    if (this.__installed) { return }
    this.__installed = true

    if (isSSR) {
      cookieSource = cfg.ssr.req.headers
      ssrRes = cfg.ssr.res
    }
    else {
      cookieSource = document
    }

    $q.cookies = this
  }
}
<|endoftext|>


<commit_before>import React, {Component, PropTypes} from 'react';
import {Radio} from 'semantic-ui-react';
import diff from 'virtual-dom/diff';
import {connectToStores} from 'fluxible-addons-react';

import DiffViewStore from '../../../stores/DiffViewStore';

import diff_fns from './diff_funcs';

const MESSAGES = {
    'Error_Version': 'Error message'
};

class DiffView extends Component {

    static defaultProps = {
        diffcontent: ' ',
        currContent: ' ',
        inverse: false,
    }

    state = {
        diffcontent: this.props.content,
        currContent: this.props.content,
        base: this.props.DiffViewStore.baseSlide,
        diff: this.props.DiffViewStore.diffSlide
    }

    componentDidMount = () => {
        this.diff();
    }

    toggleColor = () => {
        this.setState({
            inverse: !this.state.inverse
        });
    }

    diff = () => {

        /** FETCH 2 html strings to DIFF
        * baseSRC - current slide version
        * diffSRC - toDIFF slide verion
        */
        let baseSRC = this.state.base.content;
        let diffSRC = this.state.diff.content;

        const isUploaded = diffSRC.indexOf('pptx2html') !== -1;
        //PRE-PROCESS & CONVERT html into hyperscript
        diffSRC = diff_fns.preprocess(diffSRC, isUploaded);
        baseSRC = diff_fns.preprocess(baseSRC, isUploaded);

        //ADD ID as key per element
        const vTree = diff_fns.setKeys(diffSRC);
        const vTree2 = diff_fns.setKeys(baseSRC);

        if (!diff_fns.compareWrapperIds(diffSRC, baseSRC)) {
            this.setState({currContent: MESSAGES.Error_Version});
            return;
        }

        //DIFF 2 vTrees
        const diff_results = diff(vTree, vTree2);

        //REDUCE complex Object into flat Array
        const elements = Object.keys(diff_results).reduce((arr, key) => arr.concat(diff_results[key]), []);

        //LOG
        // console.group();
        // elements.map((e) => console.log('%c node:', 'color: red', e));
        // console.groupEnd();

        //CONSTRUCT Diff view Slide
        diffSRC = diff_fns.construct(elements, diffSRC, isUploaded, baseSRC);

        //UPDATE state
        this.setState({diffcontent: diffSRC});
        this.setState({currContent: baseSRC});
    }

    render() {
        const { inverse, diffcontent, currContent, isLoaded } = this.state;

        return (

Change color palette:
                    <Radio toggle onChange={this.toggleColor}/>

                      Latest revision
                      Diff view changes

                        <div className={`diff-view ${inverse ? 'inverse' : ''} `}>

        );
    }

}

DiffView = connectToStores(DiffView, [DiffViewStore], (context, props) => {
    return {DiffViewStore: context.getStore(DiffViewStore).getState()};
});

export default DiffView;
<commit_msg>add content loader<commit_after>import React, {Component, PropTypes} from 'react';
import {Radio} from 'semantic-ui-react';
import diff from 'virtual-dom/diff';
import {connectToStores} from 'fluxible-addons-react';

import DiffViewStore from '../../../stores/DiffViewStore';

import diff_fns from './diff_funcs';

const MESSAGES = {
    'Error_Version': 'Error message'
};

class DiffView extends Component {

    static defaultProps = {
        diffcontent: ' ',
        currContent: ' ',
        inverse: false,
        isLoaded: false
    }

    state = {
        diffcontent: this.props.content,
        currContent: this.props.content,
        base: this.props.DiffViewStore.baseSlide,
        diff: this.props.DiffViewStore.diffSlide
    }

    componentDidMount = () => {
        this.diff();
        this.setState({ isLoaded: true });
    }

    toggleColor = () => {
        this.setState({
            inverse: !this.state.inverse
        });
    }

    diff = () => {

        /** FETCH 2 html strings to DIFF
        * baseSRC - current slide version
        * diffSRC - toDIFF slide verion
        */
        let baseSRC = this.state.base.content;
        let diffSRC = this.state.diff.content;

        const isUploaded = diffSRC.indexOf('pptx2html') !== -1;
        //PRE-PROCESS & CONVERT html into hyperscript
        diffSRC = diff_fns.preprocess(diffSRC, isUploaded);
        baseSRC = diff_fns.preprocess(baseSRC, isUploaded);

        //ADD ID as key per element
        const vTree = diff_fns.setKeys(diffSRC);
        const vTree2 = diff_fns.setKeys(baseSRC);

        if (!diff_fns.compareWrapperIds(diffSRC, baseSRC)) {
            this.setState({currContent: MESSAGES.Error_Version});
            return;
        }

        //DIFF 2 vTrees
        const diff_results = diff(vTree, vTree2);

        //REDUCE complex Object into flat Array
        const elements = Object.keys(diff_results).reduce((arr, key) => arr.concat(diff_results[key]), []);

        //LOG
        // console.group();
        // elements.map((e) => console.log('%c node:', 'color: red', e));
        // console.groupEnd();

        //CONSTRUCT Diff view Slide
        diffSRC = diff_fns.construct(elements, diffSRC, isUploaded, baseSRC);

        //UPDATE state
        this.setState({diffcontent: diffSRC});
        this.setState({currContent: baseSRC});
    }

    render() {
        const { inverse, diffcontent, currContent, isLoaded } = this.state;

        if(!isLoaded) return (
Loading ...
);

        return (

Change color palette:
                    <Radio toggle onChange={this.toggleColor}/>

                      Latest revision
                      Diff view changes

                        <div className={`diff-view ${inverse ? 'inverse' : ''} `}>

        );
    }

}

DiffView = connectToStores(DiffView, [DiffViewStore], (context, props) => {
    return {DiffViewStore: context.getStore(DiffViewStore).getState()};
});

export default DiffView;
<|endoftext|>


<commit_before>'use strict';

const I = require("../lib/infestines")
const R = require("ramda")

const addU = (x, y) => x + y
const addC = I.curry(addU)

const d1 = {x:[1],z:{},y:{z:[1,2,{a:[3]}]}}
const d2 = {x:[1],z:{},y:{z:[1,2,{a:[3]}]}}

const ks = ["a", "b", "c"]
const vs = [1, 2, 3]

const vs1000 = Array(1000).fill(1)

const inc = x => x + 1
const inc2I = I.pipe(inc, inc)
const inc2R = R.pipe(inc, inc)

const bs = [
  'inc2I(1)',
  'inc2R(1)',

  'I.pipe(inc, inc)(1)',
  'R.pipe(inc, inc)(1)',

  'I.whereEqU(d1, d2)',
  'R.whereEq(d1, d2)',

  'I.mapPartialU(inc, vs)',
  'R.map(inc, vs)',

  'I.mapPartialU(inc, vs1000)',
  'R.map(inc, vs1000)',

  'I.zipObjPartialU(ks, vs)',
  'R.zipObj(ks, vs)',

  'I.keys(d1)',
  'R.keys(d1)',

  'I.values(d1)',
  'R.values(d1)',

  'addU(1, 2)',
  'addC(1, 2)',
  'R.add(1, 2)',

  'I.seq(0, inc)',
  'I.seq(0, inc, inc)',
  'I.seq(0, inc, inc, inc)',
  'I.seq(0, inc, inc, inc, inc)',

  'I.identicalU(null, null)',
  'R.identical(null, null)',

  'I.acyclicEqualsU(d1, d2)',
  'R.equals(d1, d2)',
]

const s = new require("benchmark").Suite()
bs.forEach(b => s.add(b, eval("() => " + b)))
s.on('cycle', e => console.log(String(e.target))).run()
<commit_msg>Bench more<commit_after>'use strict';

const I = require("../lib/infestines")
const R = require("ramda")

const addU = (x, y) => x + y
const addC = I.curry(addU)

const d1 = {x:[1],z:{},y:{z:[1,2,{a:[3]}]}}
const d2 = {x:[1],z:{},y:{z:[1,2,{a:[3]}]}}

const ks = ["a", "b", "c"]
const vs = [1, 2, 3]

const vs1000 = Array(1000).fill(1)

const inc = x => x + 1
const inc2I = I.pipe(inc, inc)
const inc2R = R.pipe(inc, inc)

const bs = [
  'I.isArray(vs)',
  'I.isArray(d1)',
  'I.isArray(null)',

  'I.isObject(d1)',
  'I.isObject(vs)',
  'I.isObject(null)',

  'inc2I(1)',
  'inc2R(1)',

  'I.pipe(inc, inc)(1)',
  'R.pipe(inc, inc)(1)',

  'I.whereEqU(d1, d2)',
  'R.whereEq(d1, d2)',

  'I.mapPartialU(inc, vs)',
  'R.map(inc, vs)',

  'I.mapPartialU(inc, vs1000)',
  'R.map(inc, vs1000)',

  'I.zipObjPartialU(ks, vs)',
  'R.zipObj(ks, vs)',

  'I.keys(d1)',
  'R.keys(d1)',

  'I.values(d1)',
  'R.values(d1)',

  'addU(1, 2)',
  'addC(1, 2)',
  'R.add(1, 2)',

  'I.seq(0, inc)',
  'I.seq(0, inc, inc)',
  'I.seq(0, inc, inc, inc)',
  'I.seq(0, inc, inc, inc, inc)',

  'I.identicalU(null, null)',
  'R.identical(null, null)',

  'I.acyclicEqualsU(d1, d2)',
  'R.equals(d1, d2)',
]

const s = new require("benchmark").Suite()
bs.forEach(b => s.add(b, eval("() => " + b)))
s.on('cycle', e => console.log(String(e.target))).run()
<|endoftext|>


<commit_before>/*
 * Copyright © 2013 VillageReach.  All Rights Reserved.  This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
 *
 * If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

function SupplylineController($scope,$location,$dialog,messageService,ReportPrograms, SupplyingFacilities, SupervisoryNodes, Supplylines, Supplyline, SupplylineDelete) {

    //initialize
    $scope.supplylinesBackupMap = [];
    $scope.newSupplyline = {};
    $scope.supplylines = {};
    $scope.editSupplyline = {};
    $scope.creationError = '';

    if ($scope.$parent.newSupplylineMode || $scope.$parent.editSupplylineMode) {
        $scope.AddEditMode = true;
        $scope.title = ($scope.$parent.newSupplylineMode) ? $scope.title = 'Add Supply Line' : $scope.title = 'Edit Supply Line';

    } else {
        $scope.AddEditMode = false;
        $scope.title = 'Supply Lines';
    }

    // drop down lists
    ReportPrograms.get(function (data){
        $scope.programs = data.programs;
        //alert(JSON.stringify($scope.programs, null, 4));
    });

    SupplyingFacilities.get(function(data){
        $scope.facilities = data.facilities;
    });

    //$scope.facilities  ={};

    SupervisoryNodes.get(function(data){
        $scope.supervisoryNodes = data.supervisoryNodes;
    });

    // all supply lines
    Supplylines.get({}, function (data) {
        $scope.initialSupplylines = angular.copy(data.supplylines, $scope.initialSupplylines);
        $scope.supplylines = data.supplylines;
        //alert(JSON.stringify($scope.supplylines, null, 4));
        for(var supplylineIndex in data.supplylines){
            var supplyline = data.supplylines[supplylineIndex];
            $scope.supplylinesBackupMap[supplyline.id] =  $scope.getBackupSupplyline(supplyline);
        }

    }, function (data) {
        $location.path($scope.$parent.sourceUrl);
    });

//  given supply line
    $scope.getBackupSupplyline = function (supplyline) {
        return {
            programid: supplyline.programid,
            supplyingfacilityid: supplyline.supplyingfacilityid,
            supervisorynodeid: supplyline.supervisorynodeid,
            description: supplyline.description
        };
    };

    $scope.processSave = function (supplyline,form)
    {
      if ($scope.$parent.newSupplylineMode)
      {
         $scope.createSupplyline();
      } else {
          $scope.updateSupplyline(supplyline, form);
      }
    }

    //  switch to new mode
    $scope.startAddNewSupplyline = function() {
        $scope.setFlags('add','start');
        $scope.$parent.formActive = "supplyline-form-active";
    };

    // create supply line
    $scope.createSupplyline = function () {
        $scope.error = "";

        var form = document.getElementById('createSupplylineForm');

        if (form.$invalid) {
            $scope.showError = true;
            return;
        }
        $scope.showError = false;
        Supplylines.save({}, $scope.newSupplyline, function (data) {

            //alert(JSON.stringify(data.supplyline, null, 4));
            $scope.supplylines.unshift(data.supplyline);
            $scope.completeAddNewSupplyline(data.supplyline);
            $scope.message = data.success;
            setTimeout(function() {
                $scope.$apply(function() {
                    $scope.supplylineslist = data.supplyLineList;
                    $scope.message = "";
                });
            }, 4000);
            $scope.newSupplyline = {};
        }, function (data) {
            $scope.message = "";
            $scope.creationError = data.data.error;
        });
    };

   //  backup record
    $scope.completeAddNewSupplyline = function(supplyline) {
        $scope.supplylinesBackupMap[supplyline.id] = $scope.getBackupSupplyline(supplyline);
        $scope.showError = false;
        $scope.setFlags('add','end');
    };

// cancel record
    $scope.cancelAddNewSupplyline = function(supplyline) {
        $scope.showError = false;
        $scope.setFlags('cancel','cancel');
      };

//    //  scope is undefined,
    $scope.supplylineLoaded = function () {
        //alert(JSON.stringify($scope.supplylines, null, 4));
        return !($scope.supplylines == undefined || $scope.supplylines == null);
    };

    //
    $scope.startSupplylineEdit = function (supplylineUnderEdit) {
        $scope.supplylinesBackupMap[supplylineUnderEdit.id].editFormActive = "supplyline-form-active";
        Supplyline.get({id: supplylineUnderEdit.id}, function (data) {
        $scope.supplyline = data.supplyline;
            //alert(JSON.stringify($scope.supplyline, null, 4));
        }, {});
        $scope.setFlags('edit','start');
    };
    // update
    $scope.updateSupplyline = function (supplyline, form) {

       function updateUiData(sourceSupplyline) {

            var supplylinesLength = $scope.supplylines.length;

            for (var i = 0; i < supplylinesLength; i++) {
                if ($scope.supplylines[i].id == sourceSupplyline.id) {
                    $scope.supplylines[i].program = sourceSupplyline.program;
                    $scope.supplylines[i].supervisoryNode = sourceSupplyline.supervisoryNode;
                    $scope.supplylines[i].supplyingFacility = sourceSupplyline.supplyingFacility;
                    $scope.supplylines[i].description = sourceSupplyline.description;
                    $scope.supplylines[i].modifiedBy = sourceSupplyline.modifiedBy;
                    $scope.supplylines[i].modifiedDate = sourceSupplyline.modifiedDate;
                }
            }

        }
          $scope.error = "";
        if (form.$invalid) {
            $scope.showErrorForEdit = true;
            return;
        }

        $scope.supplylinesBackupMap[supplyline.id].error = '';
        $scope.showErrorForEdit = true;

        Supplyline.update({id:supplyline.id}, supplyline, function (data) {
            var returnedSupplyline = data.supplyline;
            $scope.supplylinesBackupMap[returnedSupplyline.id] = $scope.getBackupSupplyline(returnedSupplyline);
            updateUiData(data.supplylines);
            $scope.completeEditSupplyline(returnedSupplyline);
            $scope.message = data.success;
            setTimeout(function() {
                $scope.$apply(function() {
                    // refresh list
                    $scope.message = "";
                });
            }, 4000);
            $scope.error = "";
            $scope.newSupplyline = {};
            $scope.editSupplyline = {};
            $scope.AddEditMode = false;

            $scope.supplylinesBackupMap[returnedSupplyline.id].editFormActive = 'updated-item';
            $scope.supplylinesBackupMap[returnedSupplyline.id].edit = false;
        }, function (data) {
            $scope.message = "";
            $scope.startSupplylineEdit(supplyline);
            $scope.supplylinesBackupMap[supplyline.id].error = data.data.error;
        });
    };

    //  backup record
    $scope.completeEditSupplyline = function(supplyline) {
        $scope.supplylinesBackupMap[supplyline.id] = $scope.getBackupSupplyline(supplyline);

        var supplylinesLength = $scope.supplylines.length;

        for (var i = 0; i < supplylinesLength; i++) {
            if ($scope.supplylines[i].id == supplyline.id) {
                $scope.supplylines[i].program = supplyline.program;
                $scope.supplylines[i].supervisoryNode = supplyline.supervisoryNode;
                $scope.supplylines[i].supplyingFacility = supplyline.supplyingFacility;
                $scope.supplylines[i].description = supplyline.description;
                $scope.supplylines[i].modifiedBy = supplyline.modifiedBy;
                $scope.supplylines[i].modifiedDate = supplyline.modifiedDate;
            }
        }
        $scope.showError = false;
        $scope.setFlags('edit','end');
    };

    $scope.cancelSupplylineEdit = function (supplylineUnderEdit) {
        var backupSupplylineRow = $scope.supplylinesBackupMap[supplylineUnderEdit.id];
        supplylineUnderEdit.programid = backupSupplylineRow.programid;
        supplylineUnderEdit.supervisorynodeid = backupSupplylineRow.supervisorynodeid;
        supplylineUnderEdit.supplyingfacilityid = backupSupplylineRow.supplyingfacilityid;
        supplylineUnderEdit.description = backupSupplylineRow.description;
        $scope.supplylinesBackupMap[supplylineUnderEdit.id].error = '';
        $scope.supplylinesBackupMap[supplylineUnderEdit.id].editFormActive = '';
        $scope.setFlags('cancel','cancel');
    };

    $scope.showConfirmSupplylineDeleteWindow = function (supplylineUnderDelete) {
        var dialogOpts = {
            id: "deleteSupplylineDialog",
            header: messageService.get('Delete supplyline'),
            body: messageService.get('delete.facility.confirm', supplylineUnderDelete.description, supplylineUnderDelete.id)
        };
        $scope.supplylineUnderDelete = supplylineUnderDelete;
        OpenLmisDialog.newDialog(dialogOpts, $scope.deleteSupplylineCallBack, $dialog, messageService);
    };

    $scope.deleteSupplylineCallBack = function (result) {
        if (!result)
        {
            $scope.supplylinesBackupMap[$scope.supplylineUnderDelete.id].deleted = false;
            return;
        }

          SupplylineDelete.get({id : $scope.supplylineUnderDelete.id }, $scope.supplyline, function (data) {
          $scope.message = data.success;
          setTimeout(function() {
                $scope.$apply(function() {
                    $scope.supplylines = data.supplylines;
                    $scope.message = "";
                });
            }, 4000);
            $scope.error = "";
            $scope.newSupplyline = {};
            $scope.editSupplyline = {};
            $scope.setFlags('delete','delete');

         });

    };

 $scope.setFlags = function(mode, state)
 {

         $scope.$parent.editSupplylineMode = false;
         $scope.$parent.newSupplylineMode = false;
         $scope.AddEditMode = false;
         $scope.title = 'Supply Lines';

       if (mode == 'edit' && state == 'start') {
        $scope.$parent.editSupplylineMode = true;
        $scope.$parent.newSupplylineMode = false;
        $scope.AddEditMode = true;
        $scope.title = 'Edit Supply Line';
    }

     if (mode == 'edit' && state == 'end') {
         $scope.$parent.editSupplylineMode = false;
         $scope.$parent.newSupplylineMode = false;
         $scope.AddEditMode = false;
         $scope.title = 'Supply Lines';
     }

     if (mode == 'add' && state == 'start') {
         $scope.$parent.editSupplylineMode = false;
         $scope.$parent.newSupplylineMode = true;
         $scope.AddEditMode = true;
         $scope.title = 'Add Supply Line';
     }

     if (mode == 'add' && state == 'end') {
         $scope.$parent.editSupplylineMode = false;
         $scope.$parent.newSupplylineMode = false;
         $scope.AddEditMode = false;
         $scope.title = 'Supply Lines';
     }

 }

    //

};
<commit_msg>ELMIS-808 Fix the delete confirmation dialog box<commit_after>/*
 * Copyright © 2013 VillageReach.  All Rights Reserved.  This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
 *
 * If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

function SupplylineController($scope,$location,$dialog,messageService,ReportPrograms, SupplyingFacilities, SupervisoryNodes, Supplylines, Supplyline, SupplylineDelete) {

    //initialize
    $scope.supplylinesBackupMap = [];
    $scope.newSupplyline = {};
    $scope.supplylines = {};
    $scope.editSupplyline = {};
    $scope.creationError = '';

    if ($scope.$parent.newSupplylineMode || $scope.$parent.editSupplylineMode) {
        $scope.AddEditMode = true;
        $scope.title = ($scope.$parent.newSupplylineMode) ? $scope.title = 'Add Supply Line' : $scope.title = 'Edit Supply Line';

    } else {
        $scope.AddEditMode = false;
        $scope.title = 'Supply Lines';
    }

    // drop down lists
    ReportPrograms.get(function (data){
        $scope.programs = data.programs;
        //alert(JSON.stringify($scope.programs, null, 4));
    });

    SupplyingFacilities.get(function(data){
        $scope.facilities = data.facilities;
    });

    //$scope.facilities  ={};

    SupervisoryNodes.get(function(data){
        $scope.supervisoryNodes = data.supervisoryNodes;
    });

    // all supply lines
    Supplylines.get({}, function (data) {
        $scope.initialSupplylines = angular.copy(data.supplylines, $scope.initialSupplylines);
        $scope.supplylines = data.supplylines;
        //alert(JSON.stringify($scope.supplylines, null, 4));
        for(var supplylineIndex in data.supplylines){
            var supplyline = data.supplylines[supplylineIndex];
            $scope.supplylinesBackupMap[supplyline.id] =  $scope.getBackupSupplyline(supplyline);
        }

    }, function (data) {
        $location.path($scope.$parent.sourceUrl);
    });

//  given supply line
    $scope.getBackupSupplyline = function (supplyline) {
        return {
            programid: supplyline.programid,
            supplyingfacilityid: supplyline.supplyingfacilityid,
            supervisorynodeid: supplyline.supervisorynodeid,
            description: supplyline.description
        };
    };

    $scope.processSave = function (supplyline,form)
    {
      if ($scope.$parent.newSupplylineMode)
      {
         $scope.createSupplyline();
      } else {
          $scope.updateSupplyline(supplyline, form);
      }
    }

    //  switch to new mode
    $scope.startAddNewSupplyline = function() {
        $scope.setFlags('add','start');
        $scope.$parent.formActive = "supplyline-form-active";
    };

    // create supply line
    $scope.createSupplyline = function () {
        $scope.error = "";

        var form = document.getElementById('createSupplylineForm');

        if (form.$invalid) {
            $scope.showError = true;
            return;
        }
        $scope.showError = false;
        Supplylines.save({}, $scope.newSupplyline, function (data) {

            //alert(JSON.stringify(data.supplyline, null, 4));
            $scope.supplylines.unshift(data.supplyline);
            $scope.completeAddNewSupplyline(data.supplyline);
            $scope.message = data.success;
            setTimeout(function() {
                $scope.$apply(function() {
                    $scope.supplylineslist = data.supplyLineList;
                    $scope.message = "";
                });
            }, 4000);
            $scope.newSupplyline = {};
        }, function (data) {
            $scope.message = "";
            $scope.creationError = data.data.error;
        });
    };

   //  backup record
    $scope.completeAddNewSupplyline = function(supplyline) {
        $scope.supplylinesBackupMap[supplyline.id] = $scope.getBackupSupplyline(supplyline);
        $scope.showError = false;
        $scope.setFlags('add','end');
    };

// cancel record
    $scope.cancelAddNewSupplyline = function(supplyline) {
        $scope.showError = false;
        $scope.setFlags('cancel','cancel');
      };

//    //  scope is undefined,
    $scope.supplylineLoaded = function () {
        //alert(JSON.stringify($scope.supplylines, null, 4));
        return !($scope.supplylines == undefined || $scope.supplylines == null);
    };

    //
    $scope.startSupplylineEdit = function (supplylineUnderEdit) {
        $scope.supplylinesBackupMap[supplylineUnderEdit.id].editFormActive = "supplyline-form-active";
        Supplyline.get({id: supplylineUnderEdit.id}, function (data) {
        $scope.supplyline = data.supplyline;
            //alert(JSON.stringify($scope.supplyline, null, 4));
        }, {});
        $scope.setFlags('edit','start');
    };
    // update
    $scope.updateSupplyline = function (supplyline, form) {

       function updateUiData(sourceSupplyline) {

            var supplylinesLength = $scope.supplylines.length;

            for (var i = 0; i < supplylinesLength; i++) {
                if ($scope.supplylines[i].id == sourceSupplyline.id) {
                    $scope.supplylines[i].program = sourceSupplyline.program;
                    $scope.supplylines[i].supervisoryNode = sourceSupplyline.supervisoryNode;
                    $scope.supplylines[i].supplyingFacility = sourceSupplyline.supplyingFacility;
                    $scope.supplylines[i].description = sourceSupplyline.description;
                    $scope.supplylines[i].modifiedBy = sourceSupplyline.modifiedBy;
                    $scope.supplylines[i].modifiedDate = sourceSupplyline.modifiedDate;
                }
            }

        }
          $scope.error = "";
        if (form.$invalid) {
            $scope.showErrorForEdit = true;
            return;
        }

        $scope.supplylinesBackupMap[supplyline.id].error = '';
        $scope.showErrorForEdit = true;

        Supplyline.update({id:supplyline.id}, supplyline, function (data) {
            var returnedSupplyline = data.supplyline;
            $scope.supplylinesBackupMap[returnedSupplyline.id] = $scope.getBackupSupplyline(returnedSupplyline);
            updateUiData(data.supplylines);
            $scope.completeEditSupplyline(returnedSupplyline);
            $scope.message = data.success;
            setTimeout(function() {
                $scope.$apply(function() {
                    // refresh list
                    $scope.message = "";
                });
            }, 4000);
            $scope.error = "";
            $scope.newSupplyline = {};
            $scope.editSupplyline = {};
            $scope.AddEditMode = false;

            $scope.supplylinesBackupMap[returnedSupplyline.id].editFormActive = 'updated-item';
            $scope.supplylinesBackupMap[returnedSupplyline.id].edit = false;
        }, function (data) {
            $scope.message = "";
            $scope.startSupplylineEdit(supplyline);
            $scope.supplylinesBackupMap[supplyline.id].error = data.data.error;
        });
    };

    //  backup record
    $scope.completeEditSupplyline = function(supplyline) {
        $scope.supplylinesBackupMap[supplyline.id] = $scope.getBackupSupplyline(supplyline);

        var supplylinesLength = $scope.supplylines.length;

        for (var i = 0; i < supplylinesLength; i++) {
            if ($scope.supplylines[i].id == supplyline.id) {
                $scope.supplylines[i].program = supplyline.program;
                $scope.supplylines[i].supervisoryNode = supplyline.supervisoryNode;
                $scope.supplylines[i].supplyingFacility = supplyline.supplyingFacility;
                $scope.supplylines[i].description = supplyline.description;
                $scope.supplylines[i].modifiedBy = supplyline.modifiedBy;
                $scope.supplylines[i].modifiedDate = supplyline.modifiedDate;
            }
        }
        $scope.showError = false;
        $scope.setFlags('edit','end');
    };

    $scope.cancelSupplylineEdit = function (supplylineUnderEdit) {
        var backupSupplylineRow = $scope.supplylinesBackupMap[supplylineUnderEdit.id];
        supplylineUnderEdit.programid = backupSupplylineRow.programid;
        supplylineUnderEdit.supervisorynodeid = backupSupplylineRow.supervisorynodeid;
        supplylineUnderEdit.supplyingfacilityid = backupSupplylineRow.supplyingfacilityid;
        supplylineUnderEdit.description = backupSupplylineRow.description;
        $scope.supplylinesBackupMap[supplylineUnderEdit.id].error = '';
        $scope.supplylinesBackupMap[supplylineUnderEdit.id].editFormActive = '';
        $scope.setFlags('cancel','cancel');
    };

    $scope.showConfirmSupplylineDeleteWindow = function (supplylineUnderDelete) {
        var dialogOpts = {
            id: "deleteSupplylineDialog",
            header: "Delete supply line",
            body: "Please confirm that you want to delete the supply line with the ID: " + supplylineUnderDelete.id + " and Description: " + supplylineUnderDelete.description
        };
        $scope.supplylineUnderDelete = supplylineUnderDelete;
        OpenLmisDialog.newDialog(dialogOpts, $scope.deleteSupplylineCallBack, $dialog, messageService);
    };

    $scope.deleteSupplylineCallBack = function (result) {
        if (!result)
        {
            $scope.supplylinesBackupMap[$scope.supplylineUnderDelete.id].deleted = false;
            return;
        }

          SupplylineDelete.get({id : $scope.supplylineUnderDelete.id }, $scope.supplyline, function (data) {
          $scope.message = data.success;
          setTimeout(function() {
                $scope.$apply(function() {
                    $scope.supplylines = data.supplylines;
                    $scope.message = "";
                });
            }, 4000);
            $scope.error = "";
            $scope.newSupplyline = {};
            $scope.editSupplyline = {};
            $scope.setFlags('delete','delete');

         });

    };

 $scope.setFlags = function(mode, state)
 {

         $scope.$parent.editSupplylineMode = false;
         $scope.$parent.newSupplylineMode = false;
         $scope.AddEditMode = false;
         $scope.title = 'Supply Lines';

       if (mode == 'edit' && state == 'start') {
        $scope.$parent.editSupplylineMode = true;
        $scope.$parent.newSupplylineMode = false;
        $scope.AddEditMode = true;
        $scope.title = 'Edit Supply Line';
    }

     if (mode == 'edit' && state == 'end') {
         $scope.$parent.editSupplylineMode = false;
         $scope.$parent.newSupplylineMode = false;
         $scope.AddEditMode = false;
         $scope.title = 'Supply Lines';
     }

     if (mode == 'add' && state == 'start') {
         $scope.$parent.editSupplylineMode = false;
         $scope.$parent.newSupplylineMode = true;
         $scope.AddEditMode = true;
         $scope.title = 'Add Supply Line';
     }

     if (mode == 'add' && state == 'end') {
         $scope.$parent.editSupplylineMode = false;
         $scope.$parent.newSupplylineMode = false;
         $scope.AddEditMode = false;
         $scope.title = 'Supply Lines';
     }

 }

    //

};
<|endoftext|>


<commit_before>const FOLDER = '8haeeqygx59lzbsn';
const OCR_URL = `https://pdftotext.com`;
const RESTAURANT_CITY_LIFE = 'CITY_LIFE';
const RESTAURANT_ANTARES = 'ANTARES';

const requestPDF = require('request-promise-native').defaults({ json: true, baseUrl: OCR_URL });
const requestMessages = require('request-promise-native').defaults({ json: true });
const requestRestaurant = require('request').defaults({ encoding: null });
const fileType = require('file-type');
const puppeteer = require('puppeteer');

const now = new Date();
const DATE = `${('0'+now.getDate()).slice(-2)}_${(('0'+(now.getMonth()+1)).slice(-2))}_${now.getFullYear()}`;

const RESTAURANT_PARAMETERS = {
    [RESTAURANT_CITY_LIFE]: {
        url: 'http://www.cityliferistorante.it/upload/',
        name: 'City Life',
        logo: 'http://www.cityliferistorante.it/img/city_logo.png',
    },
    [RESTAURANT_ANTARES]: {
        url: 'https://antaresristorante.it/menu-del-giorno/',
        name: 'Antares',
        logo: 'https://bit.ly/37vEVoD',
    },
};

const getFile = url => new Promise((resolve, reject) => requestRestaurant(url, (err, res, data) => {
    if (err) {
        return reject(err);
    }
    const dataType = fileType(data);

    if (!dataType || dataType.ext !== 'pdf') {
        return reject(new Error('Not pdf'));
    }
    resolve(data);
}));

const getFilename = () => `menu_pranzo_${DATE}_16_00`;
const getRestaurantName = restaurant => RESTAURANT_PARAMETERS[restaurant]['name'];
const getRestaurantLogo = restaurant => RESTAURANT_PARAMETERS[restaurant]['logo'];
const getRestaurantUrl = restaurant => `${RESTAURANT_PARAMETERS[restaurant]['url']}`
const getRestaurantFileUrl = restaurant => `${getRestaurantUrl(restaurant)}${getFilename()}.pdf`;
const getShareUrl = url => url;

const sendHipchat = (restaurant, text, error = false) => {
    const { env: { HIPCHAT_URL } } = process;
    const PDF_URL = getRestaurantFileUrl(restaurant);
    const NAME = getRestaurantName(restaurant);
    const LOGO = getRestaurantLogo(restaurant);
    const SHARE_URL = getShareUrl(PDF_URL);
    const HUMAN_DATE = DATE.replace(/_/g, '/');

    return HIPCHAT_URL
        ? requestMessages.post(HIPCHAT_URL, {
            body: {
                color: error ? 'red' : 'green',
                message: `<a href=${SHARE_URL}><img src=${LOGO}><br><br>Menu ${NAME} del <b>${HUMAN_DATE}</b></a><br><br>${text.replace('\n', '<br>')}`,
                notify: true,
                message_format: 'html',
            }
        })
        : Promise.resolve();
};

const sendSlack = (restaurant, text, error = false) => {
    const { env: { SLACK_URL } } = process;
    const PDF_URL = getRestaurantFileUrl(restaurant);
    const NAME = getRestaurantName(restaurant);
    const LOGO = getRestaurantLogo(restaurant);
    const SHARE_URL = getShareUrl(PDF_URL);
    const HUMAN_DATE = DATE.replace(/_/g, '/');

    return SLACK_URL
        ? requestMessages.post(SLACK_URL, {
            body: {
                username: NAME,
                icon_url: LOGO,
                attachments: [
                    {
                        text,
                        fallback: `Menu del ${HUMAN_DATE}`,
                        title: `Menu del ${HUMAN_DATE}`,
                        title_link: SHARE_URL,
                        color: error ? 'danger' : 'good',
                        thumb_url: LOGO,
                        author_icon: LOGO,
                        author_name: NAME,
                    }
                ]
            }
        })
        : Promise.resolve();
};

const sendPushbullet = (restaurant, text, error = false) => {
    const { env: { PUSHBULLET_TOKEN } } = process;
    const PDF_URL = getRestaurantFileUrl(restaurant);
    const NAME = getRestaurantName(restaurant);
    const SHARE_URL = getShareUrl(PDF_URL);
    const HUMAN_DATE = DATE.replace(/_/g, '/');

    return PUSHBULLET_TOKEN
        ? requestMessages.post('https://api.pushbullet.com/v2/pushes', {
            body: {
                type: 'link',
                body: text,
                title: `Menu ${NAME} del ${HUMAN_DATE}`,
                url: SHARE_URL,
                channel_tag: 'antares'
            },
            headers: {
                'access-token': PUSHBULLET_TOKEN,
            }
        })
        : Promise.resolve();
};

const sendConsole = (restaurant, text, error = false) => {
    const { env: { CONSOLE_OUTPUT } } = process;

    if (CONSOLE_OUTPUT) {
        console[error ? 'error' : 'log'](getRestaurantName(restaurant), text)
    }
    return Promise.resolve();
}

const getMenuCityLife = () => {
    const restaurant = RESTAURANT_CITY_LIFE;
    const FILENAME = getFilename();
    const FILENAME_TXT = `${FILENAME}.txt`;
    const FILENAME_PDF = `${FILENAME}.pdf`;
    const PDF_URL = getRestaurantFileUrl(restaurant);
    const JOB_ID = Math.random().toString(16).substring(5);

    return getFile(PDF_URL)
        .then(file => requestPDF.post(`/upload/${FOLDER}`, {
            formData: {
                file: {
                    value: file,
                    options: {
                        filename: FILENAME_PDF,
                        contentType: 'application/pdf'
                    }
                },
                id: JOB_ID,
            }
        }))
        .then(data => requestPDF(`/convert/${FOLDER}/${JOB_ID}`, {
              qs: {
                  rnd: '0.16389987427930808'
              }
          })
        )
        .then(data => {
            if (data.status !== 'success') {
                throw new Error('Error during OCR start');
            }
            return new Promise(resolve => setTimeout(resolve, 2000));
        })
        .then(() => requestPDF(`/status/${FOLDER}/${JOB_ID}`))
        .then(data  => {
            if (data.status !== 'success') {
                throw new Error('Error during OCR status check');
            }
            return requestPDF(`/files/${FOLDER}/${JOB_ID}/${FILENAME_TXT}`)
        })
        .then(text => text
            .replace(/.*PASTA AL POMODORO\.?$/gsm, '')
            .split('\n')
            .filter(Boolean)
            .filter(row => row.match(/€ *[0-9]*[0-9],*\.*[0-9][0-9]/) === null)
            .filter(row => row.match(/PRIM.*/) === null)
            .filter(row => row.match(/SECOND.*/) === null)
            .filter(row => row.match(/PIATT.*/) === null)
            .filter(row => row.match(/BUON.*/) === null)
            .filter(row => row.match(/Buon.*/) === null)
            .filter(row => row.match(/UNICO.*/) === null)
            .filter(row => row.match(/BIS.*/) === null)
            .filter(row => row.match(/RISO.*INGLESE.*/) === null)
            .map(row => `${row[0]}${row.slice(1).toLowerCase()}`)
            .join('\n')
            .replace(/€.*/, '')
            .replace(/\.\n/g, '\n')
        )
        .then(text => Promise.all([
            sendHipchat(restaurant, text),
            sendSlack(restaurant, text),
            sendPushbullet(restaurant, text),
        ]))
        .catch(e => Promise.all([
            sendHipchat(restaurant, e.message, true),
            sendSlack(restaurant, e.message, true),
            sendPushbullet(restaurant, e.message, true),
            sendConsole(restaurant, e.message, true),
        ]));
};

const getMenuAntares = () => {
    const restaurant = RESTAURANT_ANTARES;

    return puppeteer.launch({ args: ['--no-sandbox'] })
      .then(async browser => {
        const page = await browser.newPage();
        await page.goto(getRestaurantUrl(restaurant))
        const text = await page.evaluate(() => jQuery('[role=tabpanel].visibile > ul > li').map((idx, el) => el.innerText).get());
        return text.join('\n');
      })
      .then(text => Promise.all([
          sendHipchat(restaurant, text),
          sendSlack(restaurant, text),
          sendPushbullet(restaurant, text),
      ]))
      .catch(e => Promise.all([
          sendHipchat(restaurant, e.message, true),
          sendSlack(restaurant, e.message, true),
          sendPushbullet(restaurant, e.message, true),
          sendConsole(restaurant, e.message, true),
      ]));
}

module.exports = () => Promise.all([
          getMenuCityLife(),
          getMenuAntares()
        ]);
<commit_msg>Update antares selector<commit_after>const FOLDER = '8haeeqygx59lzbsn';
const OCR_URL = `https://pdftotext.com`;
const RESTAURANT_CITY_LIFE = 'CITY_LIFE';
const RESTAURANT_ANTARES = 'ANTARES';

const requestPDF = require('request-promise-native').defaults({ json: true, baseUrl: OCR_URL });
const requestMessages = require('request-promise-native').defaults({ json: true });
const requestRestaurant = require('request').defaults({ encoding: null });
const fileType = require('file-type');
const puppeteer = require('puppeteer');

const now = new Date();
const DATE = `${('0'+now.getDate()).slice(-2)}_${(('0'+(now.getMonth()+1)).slice(-2))}_${now.getFullYear()}`;

const RESTAURANT_PARAMETERS = {
    [RESTAURANT_CITY_LIFE]: {
        url: 'http://www.cityliferistorante.it/upload/',
        name: 'City Life',
        logo: 'http://www.cityliferistorante.it/img/city_logo.png',
    },
    [RESTAURANT_ANTARES]: {
        url: 'https://antaresristorante.it/menu-del-giorno/',
        name: 'Antares',
        logo: 'https://bit.ly/37vEVoD',
    },
};

const getFile = url => new Promise((resolve, reject) => requestRestaurant(url, (err, res, data) => {
    if (err) {
        return reject(err);
    }
    const dataType = fileType(data);

    if (!dataType || dataType.ext !== 'pdf') {
        return reject(new Error('Not pdf'));
    }
    resolve(data);
}));

const getFilename = () => `menu_pranzo_${DATE}_16_00`;
const getRestaurantName = restaurant => RESTAURANT_PARAMETERS[restaurant]['name'];
const getRestaurantLogo = restaurant => RESTAURANT_PARAMETERS[restaurant]['logo'];
const getRestaurantUrl = restaurant => `${RESTAURANT_PARAMETERS[restaurant]['url']}`
const getRestaurantFileUrl = restaurant => `${getRestaurantUrl(restaurant)}${getFilename()}.pdf`;
const getShareUrl = url => url;

const sendHipchat = (restaurant, text, error = false) => {
    const { env: { HIPCHAT_URL } } = process;
    const PDF_URL = getRestaurantFileUrl(restaurant);
    const NAME = getRestaurantName(restaurant);
    const LOGO = getRestaurantLogo(restaurant);
    const SHARE_URL = getShareUrl(PDF_URL);
    const HUMAN_DATE = DATE.replace(/_/g, '/');

    return HIPCHAT_URL
        ? requestMessages.post(HIPCHAT_URL, {
            body: {
                color: error ? 'red' : 'green',
                message: `<a href=${SHARE_URL}><img src=${LOGO}><br><br>Menu ${NAME} del <b>${HUMAN_DATE}</b></a><br><br>${text.replace('\n', '<br>')}`,
                notify: true,
                message_format: 'html',
            }
        })
        : Promise.resolve();
};

const sendSlack = (restaurant, text, error = false) => {
    const { env: { SLACK_URL } } = process;
    const PDF_URL = getRestaurantFileUrl(restaurant);
    const NAME = getRestaurantName(restaurant);
    const LOGO = getRestaurantLogo(restaurant);
    const SHARE_URL = getShareUrl(PDF_URL);
    const HUMAN_DATE = DATE.replace(/_/g, '/');

    return SLACK_URL
        ? requestMessages.post(SLACK_URL, {
            body: {
                username: NAME,
                icon_url: LOGO,
                attachments: [
                    {
                        text,
                        fallback: `Menu del ${HUMAN_DATE}`,
                        title: `Menu del ${HUMAN_DATE}`,
                        title_link: SHARE_URL,
                        color: error ? 'danger' : 'good',
                        thumb_url: LOGO,
                        author_icon: LOGO,
                        author_name: NAME,
                    }
                ]
            }
        })
        : Promise.resolve();
};

const sendPushbullet = (restaurant, text, error = false) => {
    const { env: { PUSHBULLET_TOKEN } } = process;
    const PDF_URL = getRestaurantFileUrl(restaurant);
    const NAME = getRestaurantName(restaurant);
    const SHARE_URL = getShareUrl(PDF_URL);
    const HUMAN_DATE = DATE.replace(/_/g, '/');

    return PUSHBULLET_TOKEN
        ? requestMessages.post('https://api.pushbullet.com/v2/pushes', {
            body: {
                type: 'link',
                body: text,
                title: `Menu ${NAME} del ${HUMAN_DATE}`,
                url: SHARE_URL,
                channel_tag: 'antares'
            },
            headers: {
                'access-token': PUSHBULLET_TOKEN,
            }
        })
        : Promise.resolve();
};

const sendConsole = (restaurant, text, error = false) => {
    const { env: { CONSOLE_OUTPUT } } = process;

    if (CONSOLE_OUTPUT) {
        console[error ? 'error' : 'log'](getRestaurantName(restaurant), text)
    }
    return Promise.resolve();
}

const getMenuCityLife = () => {
    const restaurant = RESTAURANT_CITY_LIFE;
    const FILENAME = getFilename();
    const FILENAME_TXT = `${FILENAME}.txt`;
    const FILENAME_PDF = `${FILENAME}.pdf`;
    const PDF_URL = getRestaurantFileUrl(restaurant);
    const JOB_ID = Math.random().toString(16).substring(5);

    return getFile(PDF_URL)
        .then(file => requestPDF.post(`/upload/${FOLDER}`, {
            formData: {
                file: {
                    value: file,
                    options: {
                        filename: FILENAME_PDF,
                        contentType: 'application/pdf'
                    }
                },
                id: JOB_ID,
            }
        }))
        .then(data => requestPDF(`/convert/${FOLDER}/${JOB_ID}`, {
              qs: {
                  rnd: '0.16389987427930808'
              }
          })
        )
        .then(data => {
            if (data.status !== 'success') {
                throw new Error('Error during OCR start');
            }
            return new Promise(resolve => setTimeout(resolve, 2000));
        })
        .then(() => requestPDF(`/status/${FOLDER}/${JOB_ID}`))
        .then(data  => {
            if (data.status !== 'success') {
                throw new Error('Error during OCR status check');
            }
            return requestPDF(`/files/${FOLDER}/${JOB_ID}/${FILENAME_TXT}`)
        })
        .then(text => text
            .replace(/.*PASTA AL POMODORO\.?$/gsm, '')
            .split('\n')
            .filter(Boolean)
            .filter(row => row.match(/€ *[0-9]*[0-9],*\.*[0-9][0-9]/) === null)
            .filter(row => row.match(/PRIM.*/) === null)
            .filter(row => row.match(/SECOND.*/) === null)
            .filter(row => row.match(/PIATT.*/) === null)
            .filter(row => row.match(/BUON.*/) === null)
            .filter(row => row.match(/Buon.*/) === null)
            .filter(row => row.match(/UNICO.*/) === null)
            .filter(row => row.match(/BIS.*/) === null)
            .filter(row => row.match(/RISO.*INGLESE.*/) === null)
            .map(row => `${row[0]}${row.slice(1).toLowerCase()}`)
            .join('\n')
            .replace(/€.*/, '')
            .replace(/\.\n/g, '\n')
        )
        .then(text => Promise.all([
            sendHipchat(restaurant, text),
            sendSlack(restaurant, text),
            sendPushbullet(restaurant, text),
        ]))
        .catch(e => Promise.all([
            sendHipchat(restaurant, e.message, true),
            sendSlack(restaurant, e.message, true),
            sendPushbullet(restaurant, e.message, true),
            sendConsole(restaurant, e.message, true),
        ]));
};

const getMenuAntares = () => {
    const restaurant = RESTAURANT_ANTARES;

    return puppeteer.launch({ args: ['--no-sandbox'] })
      .then(async browser => {
        const page = await browser.newPage();
        await page.goto(getRestaurantUrl(restaurant))
        const text = await page.evaluate(() => jQuery('.elementor-image-box-content > ul > li').map((idx, el) => el.innerText).get());
        return text.join('\n');
      })
      .then(text => Promise.all([
          sendHipchat(restaurant, text),
          sendSlack(restaurant, text),
          sendPushbullet(restaurant, text),
      ]))
      .catch(e => Promise.all([
          sendHipchat(restaurant, e.message, true),
          sendSlack(restaurant, e.message, true),
          sendPushbullet(restaurant, e.message, true),
          sendConsole(restaurant, e.message, true),
      ]));
}

module.exports = () => Promise.all([
          getMenuCityLife(),
          getMenuAntares()
        ]);
<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
"use strict";

const util = require("util");
const compareLocations = require("./compareLocations");
const SortableSet = require("./util/SortableSet");
let debugId = 1000;

const sortById = (a, b) => {
	if(a.id < b.id) return -1;
	if(b.id < a.id) return 1;
	return 0;
};

const sortByIdentifier = (a, b) => {
	if(a.identifier() > b.identifier()) return 1;
	if(a.identifier() < b.identifier()) return -1;
	return 0;
};

class Chunk {

	constructor(name, module, loc) {
		this.id = null;
		this.ids = null;
		this.debugId = debugId++;
		this.name = name;
		this._modules = new SortableSet(undefined, sortByIdentifier);
		this.entrypoints = [];
		this._chunks = new Set();
		this.parents = [];
		this.blocks = [];
		this.origins = [];
		this.files = [];
		this.rendered = false;
		if(module) {
			this.origins.push({
				module,
				loc,
				name
			});
		}
	}

	get entry() {
		throw new Error("Chunk.entry was removed. Use hasRuntime()");
	}

	set entry(data) {
		throw new Error("Chunk.entry was removed. Use hasRuntime()");
	}

	get initial() {
		throw new Error("Chunk.initial was removed. Use isInitial()");
	}

	set initial(data) {
		throw new Error("Chunk.initial was removed. Use isInitial()");
	}

	hasRuntime() {
		if(this.entrypoints.length === 0) return false;
		return this.entrypoints[0].chunks[0] === this;
	}

	isInitial() {
		return this.entrypoints.length > 0;
	}

	hasEntryModule() {
		return !!this.entryModule;
	}

	addToCollection(collection, item) {
		if(item === this) {
			return false;
		}

		if(collection.indexOf(item) > -1) {
			return false;
		}

		collection.push(item);
		return true;
	}

	addChunk(chunk) {
		if(this._chunks.has(chunk)) {
			return false;
		}
		this._chunks.add(chunk);
		return true;
	}

	addParent(parentChunk) {
		return this.addToCollection(this.parents, parentChunk);
	}

	addModule(module) {
		if(!this._modules.has(module)) {
			this._modules.add(module);
			return true;
		}
		return false;
	}

	addBlock(block) {
		return this.addToCollection(this.blocks, block);
	}

	removeModule(module) {
		if(this._modules.delete(module)) {
			module.removeChunk(this);
			return true;
		}
		return false;
	}

	removeChunk(chunk) {
		if(!this._chunks.has(chunk)) {
			return false;
		}

		this._chunks.delete(chunk);
		chunk.removeParent(this);
		return true;
	}

	removeParent(chunk) {
		const idx = this.parents.indexOf(chunk);
		if(idx >= 0) {
			this.parents.splice(idx, 1);
			chunk.removeChunk(this);
			return true;
		}
		return false;
	}

	addOrigin(module, loc) {
		this.origins.push({
			module,
			loc,
			name: this.name
		});
	}

	setModules(modules) {
		this._modules = new SortableSet(modules, sortByIdentifier);
	}

	getNumberOfModules() {
		return this._modules.size;
	}

	get modulesIterable() {
		return this._modules;
	}

	forEachModule(fn) {
		this._modules.forEach(fn);
	}

	mapModules(fn) {
		return Array.from(this._modules, fn);
	}

	compareTo(otherChunk) {
		this._modules.sort();
		otherChunk._modules.sort();
		if(this._modules.size > otherChunk._modules.size) return -1;
		if(this._modules.size < otherChunk._modules.size) return 1;
		const a = this._modules[Symbol.iterator]();
		const b = otherChunk._modules[Symbol.iterator]();
		while(true) { // eslint-disable-line
			const aItem = a.next();
			const bItem = b.next();
			if(aItem.done) return 0;
			const aModuleIdentifier = aItem.value.identifier();
			const bModuleIdentifier = bItem.value.identifier();
			if(aModuleIdentifier > bModuleIdentifier) return -1;
			if(aModuleIdentifier < bModuleIdentifier) return 1;
		}
	}

	containsModule(module) {
		return this._modules.has(module);
	}

	getModules() {
		return Array.from(this._modules);
	}

	getModulesIdent() {
		this._modules.sort();
		let str = "";
		this._modules.forEach(m => {
			str += m.identifier() + "#";
		});
		return str;
	}

	remove(reason) {
		// cleanup modules
		// Array.from is used here to create a clone, because removeChunk modifies this._modules
		Array.from(this._modules).forEach(module => {
			module.removeChunk(this);
		});

		// cleanup parents
		this.parents.forEach(parentChunk => {
			// remove this chunk from its parents
			parentChunk._chunks.delete(this);

			// cleanup "sub chunks"
			this._chunks.forEach(chunk => {
				/**
				 * remove this chunk as "intermediary" and connect
				 * it "sub chunks" and parents directly
				 */
				// add parent to each "sub chunk"
				chunk.addParent(parentChunk);
				// add "sub chunk" to parent
				parentChunk.addChunk(chunk);
			});
		});

		/**
		 * we need to iterate again over the chunks
		 * to remove this from the chunks parents.
		 * This can not be done in the above loop
		 * as it is not garuanteed that `this.parents` contains anything.
		 */
		this._chunks.forEach(chunk => {
			// remove this as parent of every "sub chunk"
			const idx = chunk.parents.indexOf(this);
			if(idx >= 0) {
				chunk.parents.splice(idx, 1);
			}
		});

		// cleanup blocks
		this.blocks.forEach(block => {
			const idx = block.chunks.indexOf(this);
			if(idx >= 0) {
				block.chunks.splice(idx, 1);
				if(block.chunks.length === 0) {
					block.chunks = null;
					block.chunkReason = reason;
				}
			}
		});
	}

	moveModule(module, otherChunk) {
		module.removeChunk(this);
		module.addChunk(otherChunk);
		otherChunk.addModule(module);
		module.rewriteChunkInReasons(this, [otherChunk]);
	}

	replaceChunk(oldChunk, newChunk) {
		this._chunks.delete(oldChunk);
		if(this !== newChunk && newChunk.addParent(this)) {
			this.addChunk(newChunk);
		}
	}

	replaceParentChunk(oldParentChunk, newParentChunk) {
		const idx = this.parents.indexOf(oldParentChunk);
		if(idx >= 0) {
			this.parents.splice(idx, 1);
		}
		if(this !== newParentChunk && newParentChunk.addChunk(this)) {
			this.addParent(newParentChunk);
		}
	}

	integrate(otherChunk, reason) {
		if(!this.canBeIntegrated(otherChunk)) {
			return false;
		}

		// Array.from is used here to create a clone, because moveModule modifies otherChunk._modules
		const otherChunkModules = Array.from(otherChunk._modules);
		otherChunkModules.forEach(module => otherChunk.moveModule(module, this));
		otherChunk._modules.clear();

		otherChunk.parents.forEach(parentChunk => parentChunk.replaceChunk(otherChunk, this));
		otherChunk.parents.length = 0;

		otherChunk._chunks.forEach(chunk => chunk.replaceParentChunk(otherChunk, this));
		otherChunk._chunks.clear();

		otherChunk.blocks.forEach(b => {
			b.chunks = b.chunks ? b.chunks.map(c => {
				return c === otherChunk ? this : c;
			}) : [this];
			b.chunkReason = reason;
			this.addBlock(b);
		});
		otherChunk.blocks.length = 0;

		otherChunk.origins.forEach(origin => {
			this.origins.push(origin);
		});
		this.origins.forEach(origin => {
			if(!origin.reasons) {
				origin.reasons = [reason];
			} else if(origin.reasons[0] !== reason) {
				origin.reasons.unshift(reason);
			}
		});
		this._chunks.delete(otherChunk);
		this._chunks.delete(this);
		this.parents = this.parents.filter(parentChunk => {
			return parentChunk !== otherChunk && parentChunk !== this;
		});
		return true;
	}

	split(newChunk) {
		this.blocks.forEach(block => {
			newChunk.blocks.push(block);
			block.chunks.push(newChunk);
		});
		this._chunks.forEach(chunk => {
			newChunk.addChunk(chunk);
			chunk.parents.push(newChunk);
		});
		this.parents.forEach(parentChunk => {
			parentChunk.addChunk(newChunk);
			newChunk.parents.push(parentChunk);
		});
		this.entrypoints.forEach(entrypoint => {
			entrypoint.insertChunk(newChunk, this);
		});
	}

	isEmpty() {
		return this._modules.size === 0;
	}

	updateHash(hash) {
		hash.update(`${this.id} `);
		hash.update(this.ids ? this.ids.join(",") : "");
		hash.update(`${this.name || ""} `);
		this._modules.forEach(m => m.updateHash(hash));
	}

	canBeIntegrated(otherChunk) {
		if(otherChunk.isInitial()) {
			return false;
		}
		if(this.isInitial()) {
			if(otherChunk.parents.length !== 1 || otherChunk.parents[0] !== this) {
				return false;
			}
		}
		return true;
	}

	addMultiplierAndOverhead(size, options) {
		const overhead = typeof options.chunkOverhead === "number" ? options.chunkOverhead : 10000;
		const multiplicator = this.isInitial() ? (options.entryChunkMultiplicator || 10) : 1;

		return size * multiplicator + overhead;
	}

	modulesSize() {
		let count = 0;
		for(const module of this._modules) {
			count += module.size();
		}
		return count;
	}

	size(options) {
		return this.addMultiplierAndOverhead(this.modulesSize(), options);
	}

	integratedSize(otherChunk, options) {
		// Chunk if it's possible to integrate this chunk
		if(!this.canBeIntegrated(otherChunk)) {
			return false;
		}

		let integratedModulesSize = this.modulesSize();
		// only count modules that do not exist in this chunk!
		for(const otherModule of otherChunk._modules) {
			if(!this._modules.has(otherModule)) {
				integratedModulesSize += otherModule.size();
			}
		}

		return this.addMultiplierAndOverhead(integratedModulesSize, options);
	}

	getChunkMaps(includeEntries, realHash) {
		const chunksProcessed = [];
		const chunkHashMap = {};
		const chunkNameMap = {};
		(function addChunk(chunk) {
			if(chunksProcessed.indexOf(chunk) >= 0) return;
			chunksProcessed.push(chunk);
			if(!chunk.hasRuntime() || includeEntries) {
				chunkHashMap[chunk.id] = realHash ? chunk.hash : chunk.renderedHash;
				if(chunk.name)
					chunkNameMap[chunk.id] = chunk.name;
			}
			chunk._chunks.forEach(addChunk);
		}(this));
		return {
			hash: chunkHashMap,
			name: chunkNameMap
		};
	}

	sortItems() {
		this._modules.sortWith(sortById);
		this.origins.sort((a, b) => {
			const aIdent = a.module.identifier();
			const bIdent = b.module.identifier();
			if(aIdent < bIdent) return -1;
			if(aIdent > bIdent) return 1;
			return compareLocations(a.loc, b.loc);
		});
		this.origins.forEach(origin => {
			if(origin.reasons)
				origin.reasons.sort();
		});
		this.parents.sort(sortById);
		this._chunks = new Set(Array.from(this._chunks).sort(sortById));
	}

	toString() {
		return `Chunk[${Array.from(this._modules).join()}]`;
	}

	checkConstraints() {
		const chunk = this;
		chunk._chunks.forEach((child, idx) => {
			if(Array.from(chunk._chunks).indexOf(child) !== idx)
				throw new Error(`checkConstraints: duplicate child in chunk ${chunk.debugId} ${child.debugId}`);
			if(child.parents.indexOf(chunk) < 0)
				throw new Error(`checkConstraints: child missing parent ${chunk.debugId} -> ${child.debugId}`);
		});
		chunk.parents.forEach((parentChunk, idx) => {
			if(chunk.parents.indexOf(parentChunk) !== idx)
				throw new Error(`checkConstraints: duplicate parent in chunk ${chunk.debugId} ${parentChunk.debugId}`);
			if(parentChunk._chunks.indexOf(chunk) < 0)
				throw new Error(`checkConstraints: parent missing child ${parentChunk.debugId} <- ${chunk.debugId}`);
		});
	}
}

Object.defineProperty(Chunk.prototype, "modules", {
	configurable: false,
	get: util.deprecate(function() {
		return Array.from(this._modules);
	}, "Chunk.modules is deprecated. Use Chunk.getNumberOfModules/mapModules/forEachModule/containsModule instead."),
	set: util.deprecate(function(value) {
		this.setModules(value);
	}, "Chunk.modules is deprecated. Use Chunk.addModule/removeModule instead.")
});

module.exports = Chunk;
<commit_msg>deprecate chunk.chunks<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
"use strict";

const util = require("util");
const compareLocations = require("./compareLocations");
const SortableSet = require("./util/SortableSet");
let debugId = 1000;

const sortById = (a, b) => {
	if(a.id < b.id) return -1;
	if(b.id < a.id) return 1;
	return 0;
};

const sortByIdentifier = (a, b) => {
	if(a.identifier() > b.identifier()) return 1;
	if(a.identifier() < b.identifier()) return -1;
	return 0;
};

class Chunk {

	constructor(name, module, loc) {
		this.id = null;
		this.ids = null;
		this.debugId = debugId++;
		this.name = name;
		this._modules = new SortableSet(undefined, sortByIdentifier);
		this.entrypoints = [];
		this._chunks = new Set();
		this.parents = [];
		this.blocks = [];
		this.origins = [];
		this.files = [];
		this.rendered = false;
		if(module) {
			this.origins.push({
				module,
				loc,
				name
			});
		}
	}

	get entry() {
		throw new Error("Chunk.entry was removed. Use hasRuntime()");
	}

	set entry(data) {
		throw new Error("Chunk.entry was removed. Use hasRuntime()");
	}

	get initial() {
		throw new Error("Chunk.initial was removed. Use isInitial()");
	}

	set initial(data) {
		throw new Error("Chunk.initial was removed. Use isInitial()");
	}

	/**
	 * @return {Set} - a set containing the chunks
	 */
	getChunks() {
		return this._chunks;
	}

	hasRuntime() {
		if(this.entrypoints.length === 0) return false;
		return this.entrypoints[0].chunks[0] === this;
	}

	isInitial() {
		return this.entrypoints.length > 0;
	}

	hasEntryModule() {
		return !!this.entryModule;
	}

	addToCollection(collection, item) {
		if(item === this) {
			return false;
		}

		if(collection.indexOf(item) > -1) {
			return false;
		}

		collection.push(item);
		return true;
	}

	addChunk(chunk) {
		if(this._chunks.has(chunk)) {
			return false;
		}
		this._chunks.add(chunk);
		return true;
	}

	addParent(parentChunk) {
		return this.addToCollection(this.parents, parentChunk);
	}

	addModule(module) {
		if(!this._modules.has(module)) {
			this._modules.add(module);
			return true;
		}
		return false;
	}

	addBlock(block) {
		return this.addToCollection(this.blocks, block);
	}

	removeModule(module) {
		if(this._modules.delete(module)) {
			module.removeChunk(this);
			return true;
		}
		return false;
	}

	removeChunk(chunk) {
		if(!this._chunks.has(chunk)) {
			return false;
		}

		this._chunks.delete(chunk);
		chunk.removeParent(this);
		return true;
	}

	removeParent(chunk) {
		const idx = this.parents.indexOf(chunk);
		if(idx >= 0) {
			this.parents.splice(idx, 1);
			chunk.removeChunk(this);
			return true;
		}
		return false;
	}

	addOrigin(module, loc) {
		this.origins.push({
			module,
			loc,
			name: this.name
		});
	}

	setModules(modules) {
		this._modules = new SortableSet(modules, sortByIdentifier);
	}

	getNumberOfModules() {
		return this._modules.size;
	}

	get modulesIterable() {
		return this._modules;
	}

	forEachModule(fn) {
		this._modules.forEach(fn);
	}

	mapModules(fn) {
		return Array.from(this._modules, fn);
	}

	compareTo(otherChunk) {
		this._modules.sort();
		otherChunk._modules.sort();
		if(this._modules.size > otherChunk._modules.size) return -1;
		if(this._modules.size < otherChunk._modules.size) return 1;
		const a = this._modules[Symbol.iterator]();
		const b = otherChunk._modules[Symbol.iterator]();
		while(true) { // eslint-disable-line
			const aItem = a.next();
			const bItem = b.next();
			if(aItem.done) return 0;
			const aModuleIdentifier = aItem.value.identifier();
			const bModuleIdentifier = bItem.value.identifier();
			if(aModuleIdentifier > bModuleIdentifier) return -1;
			if(aModuleIdentifier < bModuleIdentifier) return 1;
		}
	}

	containsModule(module) {
		return this._modules.has(module);
	}

	getModules() {
		return Array.from(this._modules);
	}

	getModulesIdent() {
		this._modules.sort();
		let str = "";
		this._modules.forEach(m => {
			str += m.identifier() + "#";
		});
		return str;
	}

	remove(reason) {
		// cleanup modules
		// Array.from is used here to create a clone, because removeChunk modifies this._modules
		Array.from(this._modules).forEach(module => {
			module.removeChunk(this);
		});

		// cleanup parents
		this.parents.forEach(parentChunk => {
			// remove this chunk from its parents
			parentChunk._chunks.delete(this);

			// cleanup "sub chunks"
			this._chunks.forEach(chunk => {
				/**
				 * remove this chunk as "intermediary" and connect
				 * it "sub chunks" and parents directly
				 */
				// add parent to each "sub chunk"
				chunk.addParent(parentChunk);
				// add "sub chunk" to parent
				parentChunk.addChunk(chunk);
			});
		});

		/**
		 * we need to iterate again over the chunks
		 * to remove this from the chunks parents.
		 * This can not be done in the above loop
		 * as it is not garuanteed that `this.parents` contains anything.
		 */
		this._chunks.forEach(chunk => {
			// remove this as parent of every "sub chunk"
			const idx = chunk.parents.indexOf(this);
			if(idx >= 0) {
				chunk.parents.splice(idx, 1);
			}
		});

		// cleanup blocks
		this.blocks.forEach(block => {
			const idx = block.chunks.indexOf(this);
			if(idx >= 0) {
				block.chunks.splice(idx, 1);
				if(block.chunks.length === 0) {
					block.chunks = null;
					block.chunkReason = reason;
				}
			}
		});
	}

	moveModule(module, otherChunk) {
		module.removeChunk(this);
		module.addChunk(otherChunk);
		otherChunk.addModule(module);
		module.rewriteChunkInReasons(this, [otherChunk]);
	}

	replaceChunk(oldChunk, newChunk) {
		this._chunks.delete(oldChunk);
		if(this !== newChunk && newChunk.addParent(this)) {
			this.addChunk(newChunk);
		}
	}

	replaceParentChunk(oldParentChunk, newParentChunk) {
		const idx = this.parents.indexOf(oldParentChunk);
		if(idx >= 0) {
			this.parents.splice(idx, 1);
		}
		if(this !== newParentChunk && newParentChunk.addChunk(this)) {
			this.addParent(newParentChunk);
		}
	}

	integrate(otherChunk, reason) {
		if(!this.canBeIntegrated(otherChunk)) {
			return false;
		}

		// Array.from is used here to create a clone, because moveModule modifies otherChunk._modules
		const otherChunkModules = Array.from(otherChunk._modules);
		otherChunkModules.forEach(module => otherChunk.moveModule(module, this));
		otherChunk._modules.clear();

		otherChunk.parents.forEach(parentChunk => parentChunk.replaceChunk(otherChunk, this));
		otherChunk.parents.length = 0;

		otherChunk._chunks.forEach(chunk => chunk.replaceParentChunk(otherChunk, this));
		otherChunk._chunks.clear();

		otherChunk.blocks.forEach(b => {
			b.chunks = b.chunks ? b.chunks.map(c => {
				return c === otherChunk ? this : c;
			}) : [this];
			b.chunkReason = reason;
			this.addBlock(b);
		});
		otherChunk.blocks.length = 0;

		otherChunk.origins.forEach(origin => {
			this.origins.push(origin);
		});
		this.origins.forEach(origin => {
			if(!origin.reasons) {
				origin.reasons = [reason];
			} else if(origin.reasons[0] !== reason) {
				origin.reasons.unshift(reason);
			}
		});
		this._chunks.delete(otherChunk);
		this._chunks.delete(this);
		this.parents = this.parents.filter(parentChunk => {
			return parentChunk !== otherChunk && parentChunk !== this;
		});
		return true;
	}

	split(newChunk) {
		this.blocks.forEach(block => {
			newChunk.blocks.push(block);
			block.chunks.push(newChunk);
		});
		this._chunks.forEach(chunk => {
			newChunk.addChunk(chunk);
			chunk.parents.push(newChunk);
		});
		this.parents.forEach(parentChunk => {
			parentChunk.addChunk(newChunk);
			newChunk.parents.push(parentChunk);
		});
		this.entrypoints.forEach(entrypoint => {
			entrypoint.insertChunk(newChunk, this);
		});
	}

	isEmpty() {
		return this._modules.size === 0;
	}

	updateHash(hash) {
		hash.update(`${this.id} `);
		hash.update(this.ids ? this.ids.join(",") : "");
		hash.update(`${this.name || ""} `);
		this._modules.forEach(m => m.updateHash(hash));
	}

	canBeIntegrated(otherChunk) {
		if(otherChunk.isInitial()) {
			return false;
		}
		if(this.isInitial()) {
			if(otherChunk.parents.length !== 1 || otherChunk.parents[0] !== this) {
				return false;
			}
		}
		return true;
	}

	addMultiplierAndOverhead(size, options) {
		const overhead = typeof options.chunkOverhead === "number" ? options.chunkOverhead : 10000;
		const multiplicator = this.isInitial() ? (options.entryChunkMultiplicator || 10) : 1;

		return size * multiplicator + overhead;
	}

	modulesSize() {
		let count = 0;
		for(const module of this._modules) {
			count += module.size();
		}
		return count;
	}

	size(options) {
		return this.addMultiplierAndOverhead(this.modulesSize(), options);
	}

	integratedSize(otherChunk, options) {
		// Chunk if it's possible to integrate this chunk
		if(!this.canBeIntegrated(otherChunk)) {
			return false;
		}

		let integratedModulesSize = this.modulesSize();
		// only count modules that do not exist in this chunk!
		for(const otherModule of otherChunk._modules) {
			if(!this._modules.has(otherModule)) {
				integratedModulesSize += otherModule.size();
			}
		}

		return this.addMultiplierAndOverhead(integratedModulesSize, options);
	}

	getChunkMaps(includeEntries, realHash) {
		const chunksProcessed = [];
		const chunkHashMap = {};
		const chunkNameMap = {};
		(function addChunk(chunk) {
			if(chunksProcessed.indexOf(chunk) >= 0) return;
			chunksProcessed.push(chunk);
			if(!chunk.hasRuntime() || includeEntries) {
				chunkHashMap[chunk.id] = realHash ? chunk.hash : chunk.renderedHash;
				if(chunk.name)
					chunkNameMap[chunk.id] = chunk.name;
			}
			chunk._chunks.forEach(addChunk);
		}(this));
		return {
			hash: chunkHashMap,
			name: chunkNameMap
		};
	}

	sortItems() {
		this._modules.sortWith(sortById);
		this.origins.sort((a, b) => {
			const aIdent = a.module.identifier();
			const bIdent = b.module.identifier();
			if(aIdent < bIdent) return -1;
			if(aIdent > bIdent) return 1;
			return compareLocations(a.loc, b.loc);
		});
		this.origins.forEach(origin => {
			if(origin.reasons)
				origin.reasons.sort();
		});
		this.parents.sort(sortById);
		this._chunks = new Set(Array.from(this._chunks).sort(sortById));
	}

	toString() {
		return `Chunk[${Array.from(this._modules).join()}]`;
	}

	checkConstraints() {
		const chunk = this;
		chunk._chunks.forEach((child, idx) => {
			if(Array.from(chunk._chunks).indexOf(child) !== idx)
				throw new Error(`checkConstraints: duplicate child in chunk ${chunk.debugId} ${child.debugId}`);
			if(child.parents.indexOf(chunk) < 0)
				throw new Error(`checkConstraints: child missing parent ${chunk.debugId} -> ${child.debugId}`);
		});
		chunk.parents.forEach((parentChunk, idx) => {
			if(chunk.parents.indexOf(parentChunk) !== idx)
				throw new Error(`checkConstraints: duplicate parent in chunk ${chunk.debugId} ${parentChunk.debugId}`);
			if(parentChunk._chunks.indexOf(chunk) < 0)
				throw new Error(`checkConstraints: parent missing child ${parentChunk.debugId} <- ${chunk.debugId}`);
		});
	}
}

Object.defineProperty(Chunk.prototype, "modules", {
	configurable: false,
	get: util.deprecate(function() {
		return Array.from(this._modules);
	}, "Chunk.modules is deprecated. Use Chunk.getNumberOfModules/mapModules/forEachModule/containsModule instead."),
	set: util.deprecate(function(value) {
		this.setModules(value);
	}, "Chunk.modules is deprecated. Use Chunk.addModule/removeModule instead.")
});

Object.defineProperty(Chunk.prototype, "chunks", {
	configurable: false,
	get: util.deprecate(function() {
		return Array.from(this._chunks);
	}, "Chunk.chunks: Use Chunk.getChunks() instead"),
	set() {
		throw new Error("Readonly. Use Chunk.addChunk/removeChunk/getChunks to access/modify chunks.");
	}
});

module.exports = Chunk;
<|endoftext|>


<commit_before>(function() {
  var mongrel2 = require('m2njs');

  /*
    This should match the equivalent in your mongrel2
    configuration file.
    nodejshandler.conf is an example mongrel2 configuration file.
  */
  var config = {
    recv_spec: 'tcp://127.0.0.1:9996',
    send_spec: 'tcp://127.0.0.1:9997',
    identity: '81b7114c-534c-4107-9f17-b317cfd59f62'
  }

  mongrel2.connect(config.recv_spec, config.send_spec, config.identity, function(msg, reply) {
    /*
      In this example, I an additional header to send back.
    */
    var headers = msg.headers;
    headers.responder = 'Hello, world from Node.JS handler!';
    reply(200, headers, JSON.stringify(msg));
  });

}).call(this);<commit_msg>Fixed typo<commit_after>(function() {
  var mongrel2 = require('m2njs');

  /*
    This should match the equivalent in your mongrel2
    configuration file.
    nodejshandler.conf is an example mongrel2 configuration file.
  */
  var config = {
    recv_spec: 'tcp://127.0.0.1:9996',
    send_spec: 'tcp://127.0.0.1:9997',
    identity: '81b7114c-534c-4107-9f17-b317cfd59f62'
  }

  mongrel2.connect(config.recv_spec, config.send_spec, config.identity, function(msg, reply) {
    /*
      In this example, I add an additional header to send back.
    */
    var headers = msg.headers;
    headers.responder = 'Hello, world from Node.JS handler!';
    reply(200, headers, JSON.stringify(msg));
  });

}).call(this);
<|endoftext|>


<commit_before>const Discord = require('discord.js');
exports.run = (client, message, args) => {
  const modlog = client.channels.find('name', 'pie-log');
  const anno2 = client.channels.find('name', 'reports');
  const mainuser = message.guild.member(message.author);
const say = args.slice(1).join(' ');
  const guildmember = message.content.split(" ").join(" ").slice(8) && args.slice(2)
if (say.length < 1) return message.reply('Please specify on the reason for reporting.').catch(console.error);
message.delete()

client.channels.get(anno2.id).send({embed: {
  color: 0xffff00,
  title: `Report filed`,
  description: ``,
  fields: [{
    name: "ROBLOX Username:",
    value: `${guildmember}`
  },{
  name: "Report reason:",
  value: `${say}`
  }]
    }
    })

mainuser.sendMessage({embed: {
  color: 0xff0000,
  title: "Report Filed",
  description: (`\n**You have filed a report**\n`),
fields: [{
name: "You filed a report against this ROBLOX player:",
value: `${guildmember}`
},{
name: "Reason:",
value: `${say}`
},{
name: "If you believe that this was an error, please contact a high rank immediately, false report may get you warned!",
value: "Otherwise, your report will be dealt with. You may also head over to the mainframe to file one: https://www.roblox.com/games/1191242893/Mainframe"
}]
    }})
  };
exports.conf = {
enabled: true,
guildOnly: false,
aliases: [],
permLevel: 0
};

exports.help = {
name: 'report',
description: 'Files a report to the high ranks.',
usage: 'report (ROBLOX USERNAME) message'
};
<commit_msg>Update report.js<commit_after>const Discord = require('discord.js');
exports.run = (client, message) => {
  const modlog = client.channels.find('name', 'pie-log');
  const anno2 = client.channels.find('name', 'reports');
  const mainuser = message.guild.member(message.author);
const say = args.slice(8).join(' ');
if (say.length < 1) return message.reply('Please specify on the reason for reporting.').catch(console.error);
message.delete()

client.channels.get(anno2.id).send({embed: {
  color: 0xffff00,
  title: `Report filed`,
  description: ``,
  fields: [{
    name: "Reporter:",
    value: `${message.author}`
  },{
  name: "Report reason:",
  value: `${say}`
  }]
    }
    })

mainuser.sendMessage({embed: {
  color: 0xff0000,
  title: "Report Filed",
  description: (`\n**You have filed a report**\n`),
fields: [{
name: "Your discord tag:",
value: `${message.author}`
},{
name: "Reason:",
value: `${say}`
},{
name: "If you believe that this was an error, please contact a high rank immediately, false report may get you warned!",
value: "Otherwise, your report will be dealt with. You may also head over to the mainframe to file one: https://www.roblox.com/games/1191242893/Mainframe"
}]
    }})
  };
exports.conf = {
enabled: true,
guildOnly: false,
aliases: [],
permLevel: 0
};

exports.help = {
name: 'report',
description: 'Files a report to the high ranks.',
usage: 'report message'
};
<|endoftext|>


<commit_before>// This test shows: ReactElement vs ReactComponent vs ReactClass vs React.Component
// For more information see: https://github.com/DJCordhose/react-component-test/blob/master/README.md

import jsdom from 'mocha-jsdom';
import ReactTestUtils from 'react-addons-test-utils';

import unexpected from 'unexpected';

const expect = unexpected.clone();

import React from 'react';
import ReactDOM from 'react-dom';

class MyClassComponentIntrospection extends React.Component {

	constructor(props) {
		super(props);
		MyClassComponentIntrospection.constructorCalled = true;
	}

	render() {
		MyClassComponentIntrospection.renderCalled = true;
		return
hello
;
	}
}
MyClassComponentIntrospection.constructorCalled = false;
MyClassComponentIntrospection.renderCalled = false;

class MyClassComponent extends React.Component {
	render() {
		return
hello
;
	}
}

function MyFunctionalComponent() {
	return
hello
;
}

const MyES5Component = React.createClass({
	render() {
		return
Hello ES5
;
	}
});

describe('React', () => {

	jsdom();

	describe('component', () => {

		beforeEach(() => {

			MyClassComponentIntrospection.constructorCalled = false;
			MyClassComponentIntrospection.renderCalled = false;
		});

		it('does not call the constructor on createElement', () => {

			React.createElement(MyClassComponentIntrospection);

			expect(MyClassComponentIntrospection.constructorCalled, 'to be false');
			expect(MyClassComponentIntrospection.renderCalled, 'to be false');
		});

		it('calls the constructor after render', () => {

			const container = document.createElement('div');
			const element = React.createElement(MyClassComponentIntrospection);

			ReactDOM.render(element, container);

			expect(MyClassComponentIntrospection.constructorCalled, 'to be true');
			expect(MyClassComponentIntrospection.renderCalled, 'to be true');
		});

	});

	describe('render', () => {
		let component;

		describe('for an ES6 component', () => {

			beforeEach(() => {

				const container = document.createElement('div');
				component = ReactDOM.render(<MyClassComponent />, container);
			});

			it('returns an instance of React.Component', () => {
				// console.log(component.__proto__.__proto__);

				expect(component instanceof React.Component, 'to be true');
				// expect(component.__proto__ === MyClassComponent.prototype, 'to be true');
				// expect(component.__proto__.__proto__ === React.Component.prototype, 'to be true');
				// console.log(component);

			});

			it('returns an instance of MyClassComponent', () => {

				expect(component instanceof MyClassComponent, 'to be true');
			});

			it('does not return the component itself', () => {
				expect(component, 'not to be', MyClassComponent);
			});
		});

		describe('for an ES5 component', () => {

			beforeEach(() => {

				const container = document.createElement('div');
				component = ReactDOM.render(<MyES5Component />, container);
			});

			it('does not return an instance of React.Component', () => {
				expect(component instanceof React.Component, 'to be false');
			});

			it('protoype shares methods with React.Component', () => {
				// but rahter something really weird:
				expect(React.Component.prototype, 'not to be', component.__proto__.__proto__);
				expect(React.Component.prototype.setState, 'to be', component.__proto__.__proto__.setState);
				expect(React.Component.prototype.forceUpdate, 'to be', component.__proto__.__proto__.forceUpdate);
				// console.log(React.Component);
			});

			it('returns an instance of MyClassComponent', () => {

				expect(component instanceof MyES5Component, 'to be true');
			});

			it('does not return the component itself', () => {
				expect(component, 'not to be', MyES5Component);
			});

		});

		describe('for a functional component', () => {

			beforeEach(() => {
				const container = document.createElement('div');
				component = ReactDOM.render(<MyFunctionalComponent />, container);
			});

			it('returns null', () => {
				expect(component, 'to be null');
			});
		});

	});

	describe('createElement', () => {

		let element;

		describe('for an ES6 component', () => {

			beforeEach(() => {
				element = <MyClassComponent />;
			});

			it('is an object', () => {
				expect(element, 'to be an object');
			});

			it('has props', () => {
				expect(element.props, 'to be an object');
			});

			it('has a type of the MyClassComponent function', () => {
				expect(element.type, 'to be', MyClassComponent);
			});
		});

		describe('for an ES5 component', () => {

			beforeEach(() => {
				element = <MyES5Component />;
			});

			it('is an object', () => {
				expect(element, 'to be an object');
			});

			it('has props', () => {
				expect(element.props, 'to be an object');
			});

			it('has a type of the MyES5Component function', () => {
				expect(element.type, 'to be', MyES5Component);
			});
		});
		describe('for an functional component', () => {

			beforeEach(() => {
				element = <MyFunctionalComponent />;
			});

			it('is an object', () => {
				expect(element, 'to be an object');
			});

			it('has props', () => {
				expect(element.props, 'to be an object');
			});

			it('has a type of the MyFunctionalComponent function', () => {
				expect(element.type, 'to be', MyFunctionalComponent);
			});
		});
	});

	describe('Shallow Renderer', () => {
		let element;

		describe('for an ES6 component', () => {

			beforeEach(() => {
				const renderer = ReactTestUtils.createRenderer();
				renderer.render(<MyClassComponent />);
				element = renderer.getRenderOutput();
			});

			it('returns an object', () => {

				expect(element, 'to be an object');
			});

			it('returns a $$typeof symbol', () => {
				expect(typeof element.$$typeof, 'to be', 'symbol');
			});
			it('returns a symbol react.element', () => {
				const symbol = Symbol.for('react.element');
				expect(element.$$typeof, 'to be', symbol);
			});

			it('returns the same object as createElement(div)', () => {
				expect(element, 'to equal', React.createElement('div', {}, 'hello'));
			});
		});
	});
});
<commit_msg>Added prototype tests back for class component<commit_after>// This test shows: ReactElement vs ReactComponent vs ReactClass vs React.Component
// For more information see: https://github.com/DJCordhose/react-component-test/blob/master/README.md

import jsdom from 'mocha-jsdom';
import ReactTestUtils from 'react-addons-test-utils';

import unexpected from 'unexpected';

const expect = unexpected.clone();

import React from 'react';
import ReactDOM from 'react-dom';

class MyClassComponentIntrospection extends React.Component {

	constructor(props) {
		super(props);
		MyClassComponentIntrospection.constructorCalled = true;
	}

	render() {
		MyClassComponentIntrospection.renderCalled = true;
		return
hello
;
	}
}
MyClassComponentIntrospection.constructorCalled = false;
MyClassComponentIntrospection.renderCalled = false;

class MyClassComponent extends React.Component {
	render() {
		return
hello
;
	}
}

function MyFunctionalComponent() {
	return
hello
;
}

const MyES5Component = React.createClass({
	render() {
		return
Hello ES5
;
	}
});

describe('React', () => {

	jsdom();

	describe('component', () => {

		beforeEach(() => {

			MyClassComponentIntrospection.constructorCalled = false;
			MyClassComponentIntrospection.renderCalled = false;
		});

		it('does not call the constructor on createElement', () => {

			React.createElement(MyClassComponentIntrospection);

			expect(MyClassComponentIntrospection.constructorCalled, 'to be false');
			expect(MyClassComponentIntrospection.renderCalled, 'to be false');
		});

		it('calls the constructor after render', () => {

			const container = document.createElement('div');
			const element = React.createElement(MyClassComponentIntrospection);

			ReactDOM.render(element, container);

			expect(MyClassComponentIntrospection.constructorCalled, 'to be true');
			expect(MyClassComponentIntrospection.renderCalled, 'to be true');
		});

	});

	describe('render', () => {
		let component;

		describe('for an ES6 component', () => {

			beforeEach(() => {

				const container = document.createElement('div');
				component = ReactDOM.render(<MyClassComponent />, container);
			});

			it('returns an instance of React.Component', () => {

				expect(component instanceof React.Component, 'to be true');
			});

			it('has a prototype of the original component prototype', () => {

				expect(component.__proto__, 'to be', MyClassComponent.prototype);
			});

			it('has a grand-parent prototype of the React.Component prototype', () => {

				expect(component.__proto__.__proto__, 'to be', React.Component.prototype);
			});

			it('returns an instance of MyClassComponent', () => {

				expect(component instanceof MyClassComponent, 'to be true');
			});

			it('does not return the component itself', () => {
				expect(component, 'not to be', MyClassComponent);
			});
		});

		describe('for an ES5 component', () => {

			beforeEach(() => {

				const container = document.createElement('div');
				component = ReactDOM.render(<MyES5Component />, container);
			});

			it('does not return an instance of React.Component', () => {
				expect(component instanceof React.Component, 'to be false');
			});

			it('protoype shares methods with React.Component', () => {
				// but rather something really weird:
				expect(React.Component.prototype, 'not to be', component.__proto__.__proto__);
				expect(React.Component.prototype.setState, 'to be', component.__proto__.__proto__.setState);
				expect(React.Component.prototype.forceUpdate, 'to be', component.__proto__.__proto__.forceUpdate);
				// console.log(React.Component);
			});

			it('returns an instance of MyClassComponent', () => {

				expect(component instanceof MyES5Component, 'to be true');
			});

			it('does not return the component itself', () => {
				expect(component, 'not to be', MyES5Component);
			});

		});

		describe('for a functional component', () => {

			beforeEach(() => {
				const container = document.createElement('div');
				component = ReactDOM.render(<MyFunctionalComponent />, container);
			});

			it('returns null', () => {
				expect(component, 'to be null');
			});
		});

	});

	describe('createElement', () => {

		let element;

		describe('for an ES6 component', () => {

			beforeEach(() => {
				element = <MyClassComponent />;
			});

			it('is an object', () => {
				expect(element, 'to be an object');
			});

			it('has props', () => {
				expect(element.props, 'to be an object');
			});

			it('has a type of the MyClassComponent function', () => {
				expect(element.type, 'to be', MyClassComponent);
			});
		});

		describe('for an ES5 component', () => {

			beforeEach(() => {
				element = <MyES5Component />;
			});

			it('is an object', () => {
				expect(element, 'to be an object');
			});

			it('has props', () => {
				expect(element.props, 'to be an object');
			});

			it('has a type of the MyES5Component function', () => {
				expect(element.type, 'to be', MyES5Component);
			});
		});
		describe('for an functional component', () => {

			beforeEach(() => {
				element = <MyFunctionalComponent />;
			});

			it('is an object', () => {
				expect(element, 'to be an object');
			});

			it('has props', () => {
				expect(element.props, 'to be an object');
			});

			it('has a type of the MyFunctionalComponent function', () => {
				expect(element.type, 'to be', MyFunctionalComponent);
			});
		});
	});

	describe('Shallow Renderer', () => {
		let element;

		describe('for an ES6 component', () => {

			beforeEach(() => {
				const renderer = ReactTestUtils.createRenderer();
				renderer.render(<MyClassComponent />);
				element = renderer.getRenderOutput();
			});

			it('returns an object', () => {

				expect(element, 'to be an object');
			});

			it('returns a $$typeof symbol', () => {
				expect(typeof element.$$typeof, 'to be', 'symbol');
			});
			it('returns a symbol react.element', () => {
				const symbol = Symbol.for('react.element');
				expect(element.$$typeof, 'to be', symbol);
			});

			it('returns the same object as createElement(div)', () => {
				expect(element, 'to equal', React.createElement('div', {}, 'hello'));
			});
		});
	});
});
<|endoftext|>


<commit_before>
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

import Kibo from 'base/kibo'

var BOLD = 'font-weight: bold; font-size: 13px;'
var INFO = 'color: #006600;' + BOLD
var DEBUG = 'color: #0000ff;' + BOLD
var WARN = 'color: #ff8000;' + BOLD
var ERROR = 'color: #ff0000;' + BOLD

var LEVEL_DEBUG = 0
var LEVEL_INFO = 1
var LEVEL_WARN = 2
var LEVEL_ERROR = 3
var LEVEL_DISABLED = 4

var COLORS = [DEBUG, INFO, WARN, ERROR, ERROR]
var DESCRIPTIONS = ['debug', 'info', 'warn', 'error', 'disabled']

export default class Log {
  constructor(level = LEVEL_INFO, offLevel = LEVEL_DISABLED) {
    this.kibo = new Kibo()
    this.kibo.down(['ctrl shift d'], () => this.onOff())
    this.BLACKLIST = ['timeupdate', 'playback:timeupdate', 'playback:progress', 'container:hover', 'container:timeupdate', 'container:progress']
    this.level = level
    this.offLevel = offLevel
  }

  debug(klass) {this.log(klass, LEVEL_DEBUG, Array.prototype.slice.call(arguments, 1))}
  info(klass) {this.log(klass, LEVEL_INFO, Array.prototype.slice.call(arguments, 1))}
  warn(klass) {this.log(klass, LEVEL_WARN, Array.prototype.slice.call(arguments, 1))}
  error(klass) {this.log(klass, LEVEL_ERROR, Array.prototype.slice.call(arguments, 1))}

  onOff() {
    if (this.level === this.offLevel) {
      this.level = this.previousLevel
    } else {
      this.previousLevel = this.level
      this.level = this.offLevel
    }
    // handle instances where console.log is unavailable
    if (window.console && window.console.log) {
      console.log("%c[Clappr.Log] set log level to " + DESCRIPTIONS[this.level], WARN)
    }
  }

  level(newLevel) {
    this.level = newLevel
  }

  log(klass, level, message) {
    if (this.BLACKLIST.indexOf(message[0]) >= 0) return
    if (level < this.level) return

    if (!message) {
      message = klass
      klass = null
    }
    var klassDescription = ""
    var color = COLORS[level]
    if (klass) {
      klassDescription = "[" + klass + "]"
    }
    if (window.console && window.console.log) {
      console.log.apply(console, ["%c[" + DESCRIPTIONS[level] + "]" + klassDescription, color].concat(message))
    }
  }
}

Log.LEVEL_DEBUG = LEVEL_DEBUG
Log.LEVEL_INFO = LEVEL_INFO
Log.LEVEL_WARN = LEVEL_WARN
Log.LEVEL_ERROR = LEVEL_ERROR

Log.getInstance = function() {
  if (this._instance === undefined) {
    this._instance = new this()
    this._instance.previousLevel = this._instance.level
    this._instance.level = this._instance.offLevel
  }
  return this._instance
}

Log.setLevel = function(level) { this.getInstance().level = level }

Log.debug = function(klass) { this.getInstance().debug.apply(this.getInstance(), arguments) }
Log.info = function(klass) { this.getInstance().info.apply(this.getInstance(), arguments) }
Log.warn = function(klass) { this.getInstance().warn.apply(this.getInstance(), arguments) }
Log.error = function(klass) { this.getInstance().error.apply(this.getInstance(), arguments) }
<commit_msg>Log: always shows error messages<commit_after>
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

import Kibo from 'base/kibo'

var BOLD = 'font-weight: bold; font-size: 13px;'
var INFO = 'color: #006600;' + BOLD
var DEBUG = 'color: #0000ff;' + BOLD
var WARN = 'color: #ff8000;' + BOLD
var ERROR = 'color: #ff0000;' + BOLD

var LEVEL_DEBUG = 0
var LEVEL_INFO = 1
var LEVEL_WARN = 2
var LEVEL_ERROR = 3
var LEVEL_DISABLED = LEVEL_ERROR

var COLORS = [DEBUG, INFO, WARN, ERROR, ERROR]
var DESCRIPTIONS = ['debug', 'info', 'warn', 'error', 'disabled']

export default class Log {
  constructor(level = LEVEL_INFO, offLevel = LEVEL_DISABLED) {
    this.kibo = new Kibo()
    this.kibo.down(['ctrl shift d'], () => this.onOff())
    this.BLACKLIST = ['timeupdate', 'playback:timeupdate', 'playback:progress', 'container:hover', 'container:timeupdate', 'container:progress']
    this.level = level
    this.offLevel = offLevel
  }

  debug(klass) {this.log(klass, LEVEL_DEBUG, Array.prototype.slice.call(arguments, 1))}
  info(klass) {this.log(klass, LEVEL_INFO, Array.prototype.slice.call(arguments, 1))}
  warn(klass) {this.log(klass, LEVEL_WARN, Array.prototype.slice.call(arguments, 1))}
  error(klass) {this.log(klass, LEVEL_ERROR, Array.prototype.slice.call(arguments, 1))}

  onOff() {
    if (this.level === this.offLevel) {
      this.level = this.previousLevel
    } else {
      this.previousLevel = this.level
      this.level = this.offLevel
    }
    // handle instances where console.log is unavailable
    if (window.console && window.console.log) {
      console.log("%c[Clappr.Log] set log level to " + DESCRIPTIONS[this.level], WARN)
    }
  }

  level(newLevel) {
    this.level = newLevel
  }

  log(klass, level, message) {
    if (this.BLACKLIST.indexOf(message[0]) >= 0) return
    if (level < this.level) return

    if (!message) {
      message = klass
      klass = null
    }
    var klassDescription = ""
    var color = COLORS[level]
    if (klass) {
      klassDescription = "[" + klass + "]"
    }
    if (window.console && window.console.log) {
      console.log.apply(console, ["%c[" + DESCRIPTIONS[level] + "]" + klassDescription, color].concat(message))
    }
  }
}

Log.LEVEL_DEBUG = LEVEL_DEBUG
Log.LEVEL_INFO = LEVEL_INFO
Log.LEVEL_WARN = LEVEL_WARN
Log.LEVEL_ERROR = LEVEL_ERROR

Log.getInstance = function() {
  if (this._instance === undefined) {
    this._instance = new this()
    this._instance.previousLevel = this._instance.level
    this._instance.level = this._instance.offLevel
  }
  return this._instance
}

Log.setLevel = function(level) { this.getInstance().level = level }

Log.debug = function(klass) { this.getInstance().debug.apply(this.getInstance(), arguments) }
Log.info = function(klass) { this.getInstance().info.apply(this.getInstance(), arguments) }
Log.warn = function(klass) { this.getInstance().warn.apply(this.getInstance(), arguments) }
Log.error = function(klass) { this.getInstance().error.apply(this.getInstance(), arguments) }
<|endoftext|>


<commit_before>import uuid from '../util/uuid';
/**
 * To ensure no conflicts with other potential Inferno instances on the page
 */
const nodeID = '_InfernoNodeID' + uuid;

const ID_PROP = '__Inferno__id__';
let counter = 1;

export default function InfernoNodeID(node, get) {
    return node[nodeID] || (nodeID ? null : node[nodeID] = counter++);
}<commit_msg>fixed broken events<commit_after>const ID_PROP = '__Inferno__id__';
let counter = 1;

export default function InfernoNodeID(node, onlyGet) {
    return node[ID_PROP] || (onlyGet? null : node[ID_PROP] = counter++);
}<|endoftext|>