<commit_before>// ** I18N

// Calendar SK language
// Author: Peter Valach (pvalach@gmx.net)
// Encoding: utf-8
// Last update: 2003/10/29
// Distributed under the same terms as the calendar itself.

// full day names
Calendar._DN = new Array
("NedeÄľa",
 "Pondelok",
 "Utorok",
 "Streda",
 "Ĺ tvrtok",
 "Piatok",
 "Sobota",
 "NedeÄľa");

// short day names
Calendar._SDN = new Array
("Ned",
 "Pon",
 "Uto",
 "Str",
 "Ĺ tv",
 "Pia",
 "Sob",
 "Ned");

// full month names
Calendar._MN = new Array
("JanuĂˇr",
 "FebruĂˇr",
 "Marec",
 "AprĂl",
 "MĂˇj",
 "JĂşn",
 "JĂşl",
 "August",
 "September",
 "OktĂłber",
 "November",
 "December");

// short month names
Calendar._SMN = new Array
("Jan",
 "Feb",
 "Mar",
 "Apr",
 "MĂˇj",
 "JĂşn",
 "JĂşl",
 "Aug",
 "Sep",
 "Okt",
 "Nov",
 "Dec");

// First day of the week. "0" means display Sunday first, "1" means display
// Monday first, etc.
Calendar._FD = 1;

// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "O kalendĂˇri";

Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" +
"PoslednĂş verziu nĂˇjdete na: http://www.dynarch.com/projects/calendar/\n" +
"DistribuovanĂ© pod GNU LGPL.  ViÄŹ http://gnu.org/licenses/lgpl.html pre detaily." +
"\n\n" +
"VĂ˝ber dĂˇtumu:\n" +
"- PouĹľite tlaÄŤidlĂˇ \xab, \xbb pre vĂ˝ber roku\n" +
"- PouĹľite tlaÄŤidlĂˇ " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " pre vĂ˝ber mesiaca\n" +
"- Ak ktorĂ©koÄľvek z tĂ˝chto tlaÄŤidiel podrĹľĂte dlhĹˇie, zobrazĂ sa rĂ˝chly vĂ˝ber.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"VĂ˝ber ÄŤasu:\n" +
"- Kliknutie na niektorĂş poloĹľku ÄŤasu ju zvĂ˝Ĺˇi\n" +
"- Shift-klik ju znĂĹľi\n" +
"- Ak podrĹľĂte tlaÄŤĂtko stlaÄŤenĂ©, posĂşvanĂm menĂte hodnotu.";

Calendar._TT["PREV_YEAR"] = "PredoĹˇlĂ˝ rok (podrĹľte pre menu)";
Calendar._TT["PREV_MONTH"] = "PredoĹˇlĂ˝ mesiac (podrĹľte pre menu)";
Calendar._TT["GO_TODAY"] = "PrejsĹĄ na dneĹˇok";
Calendar._TT["NEXT_MONTH"] = "Nasl. mesiac (podrĹľte pre menu)";
Calendar._TT["NEXT_YEAR"] = "Nasl. rok (podrĹľte pre menu)";
Calendar._TT["SEL_DATE"] = "ZvoÄľte dĂˇtum";
Calendar._TT["DRAG_TO_MOVE"] = "PodrĹľanĂm tlaÄŤĂtka zmenĂte polohu";
Calendar._TT["PART_TODAY"] = " (dnes)";
Calendar._TT["MON_FIRST"] = "ZobraziĹĄ pondelok ako prvĂ˝";
Calendar._TT["SUN_FIRST"] = "ZobraziĹĄ nedeÄľu ako prvĂş";
Calendar._TT["CLOSE"] = "ZavrieĹĄ";
Calendar._TT["TODAY"] = "Dnes";
Calendar._TT["TIME_PART"] = "(Shift-)klik/ĹĄahanie zmenĂ hodnotu";

// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "$d. %m. %Y";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %e. %b";

Calendar._TT["WK"] = "tĂ˝Ĺľ";

// the following is to inform that "%s" is to be the first day of week
// %s will be replaced with the day name.
Calendar._TT["DAY_FIRST"] = "Display %s first";

// This may be locale-dependent.  It specifies the week-end days, as an array
// of comma-separated numbers.  The numbers are from 0 to 6: 0 means Sunday, 1
// means Monday, etc.
Calendar._TT["WEEKEND"] = "0,6";

Calendar._TT["TIME"] = "Time:";
<commit_msg>matej's patch<commit_after>// ** I18N

// Calendar SK language
// Author: Peter Valach (pvalach@gmx.net)
// Encoding: utf-8
// Last update: 2003/10/29
// Distributed under the same terms as the calendar itself.

// full day names
Calendar._DN = new Array
("Nedeľa",
 "Pondelok",
 "Utorok",
 "Streda",
 "Štvrtok",
 "Piatok",
 "Sobota",
 "Nedeľa");

// short day names
Calendar._SDN = new Array
("Ned",
 "Pon",
 "Uto",
 "Str",
 "Štv",
 "Pia",
 "Sob",
 "Ned");

// full month names
Calendar._MN = new Array
("Január",
 "Február",
 "Marec",
 "Apríl",
 "Máj",
 "Jún",
 "Júl",
 "August",
 "September",
 "Október",
 "November",
 "December");

// short month names
Calendar._SMN = new Array
("Jan",
 "Feb",
 "Mar",
 "Apr",
 "Máj",
 "Jún",
 "Júl",
 "Aug",
 "Sep",
 "Okt",
 "Nov",
 "Dec");

// First day of the week. "0" means display Sunday first, "1" means display
// Monday first, etc.
Calendar._FD = 1;

// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "O kalendári";

Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" +
"Poslednú verziu nájdete na: http://www.dynarch.com/projects/calendar/\n" +
"Distribuované pod GNU LGPL.  Viď http://gnu.org/licenses/lgpl.html pre detaily." +
"\n\n" +
"Výber dátumu:\n" +
"- Použite tlačidlá \xab, \xbb pre výber roku\n" +
"- Použite tlačidlá " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " pre výber mesiaca\n" +
"- Ak ktorékoľvek z týchto tlačidiel podržíte dlhšie, zobrazí sa rýchly výber.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Výber času:\n" +
"- Kliknutie na niektorú položku času ju zvýši\n" +
"- Shift-klik ju zníži\n" +
"- Ak podržíte tlačítko stlačené, posúvaním meníte hodnotu.";

Calendar._TT["PREV_YEAR"] = "Predošlý rok (podržte pre menu)";
Calendar._TT["PREV_MONTH"] = "Predošlý mesiac (podržte pre menu)";
Calendar._TT["GO_TODAY"] = "Prejsť na dnešok";
Calendar._TT["NEXT_MONTH"] = "Nasl. mesiac (podržte pre menu)";
Calendar._TT["NEXT_YEAR"] = "Nasl. rok (podržte pre menu)";
Calendar._TT["SEL_DATE"] = "Zvoľte dátum";
Calendar._TT["DRAG_TO_MOVE"] = "Podržaním tlačítka zmeníte polohu";
Calendar._TT["PART_TODAY"] = " (dnes)";
Calendar._TT["MON_FIRST"] = "Zobraziť pondelok ako prvý";
Calendar._TT["SUN_FIRST"] = "Zobraziť nedeľu ako prvú";
Calendar._TT["CLOSE"] = "Zavrieť";
Calendar._TT["TODAY"] = "Dnes";
Calendar._TT["TIME_PART"] = "(Shift-)klik/ťahanie zmení hodnotu";

// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "$d. %m. %Y";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %e. %b";

Calendar._TT["WK"] = "týž";

// the following is to inform that "%s" is to be the first day of week
// %s will be replaced with the day name.
Calendar._TT["DAY_FIRST"] = "Display %s first";

// This may be locale-dependent.  It specifies the week-end days, as an array
// of comma-separated numbers.  The numbers are from 0 to 6: 0 means Sunday, 1
// means Monday, etc.
Calendar._TT["WEEKEND"] = "0,6";

Calendar._TT["TIME"] = "Time:";

<|endoftext|>


<commit_before>var conf = require('../../conf');

/**
 * Check whether Transport Layer Security (TLS) is forced in the config. If
 * forceTLS option is set to true, redirect all unsecured HTTP traffic to HTTPS.
 **/
module.exports = function forceTLS(req, res, next) {
  if (conf.forceTLS && conf.securePort && !req.secure) {
    return res.redirect(['https://', req.get('Host'), req.url].join(''));
  }
  next();
}
<commit_msg>Add custom port to the redirect path<commit_after>var conf = require('../conf');

/**
 * Check whether Transport Layer Security (TLS) is forced in the config. If
 * forceTLS option is set to true, redirect all unsecured HTTP traffic to HTTPS.
 **/
module.exports = function forceTLS(req, res, next) {
  if (conf.forceTLS && conf.securePort && !req.secure) {
    var redirectPath = ['https://', req.hostname];

    if (conf.securePort != 443) {
      redirectPath.push(':');
      redirectPath.push(conf.securePort);
    }

    redirectPath.push(req.url);

    return res.redirect(301, redirectPath.join(''));
  }
  next();
}
<|endoftext|>


<commit_before>// Build a graph using an adjacency list.
// No vertex class
// Should have a storage property that holds vertex id along with all the edges.

// Methods:
// addVertex
// removeVertex
// addEdge
// removeEdge
// neighbors(vertex) -> return the array of neighbors for a vertex

class Vertex{
  constructor( val ){
    this.value = val;
    this.edges = {};
  }
}

class Graph{
  constructor(){
    this.vertices = {};
    this.totalVertices = 0;
    this.totalEdges = 0;
  }

  addVertex(val){
    if ( !this.vertices[val] ){
      this.vertices[val] = []; // storage
      this.totalVertices++;
    }
    else {
      return 'val exists';
    }
  }

  removeVertex(val){
    delete this.vertices[val];
    this.vertices--;
  }

  addEdge(valOne, valTwo){
    this.vertices[valOne].push(valTwo);
    this.vertices[valTwo].push(valOne);

    this.totalEdges++;
   }

}

<commit_msg>add remove edge method<commit_after>// Build a graph using an adjacency list.
// No vertex class
// Should have a storage property that holds vertex id along with all the edges.

// Methods:
// addVertex
// removeVertex
// addEdge
// removeEdge
// neighbors(vertex) -> return the array of neighbors for a vertex

class Vertex{
  constructor( val ){
    this.value = val;
    this.edges = {};
  }
}

class Graph{
  constructor(){
    this.vertices = {};
    this.totalVertices = 0;
    this.totalEdges = 0;
  }

  addVertex(val){
    if ( !this.vertices[val] ){
      this.vertices[val] = []; // storage
      this.totalVertices++;
    }
    else {
      return 'val exists';
    }
  }

  removeVertex(val){
    delete this.vertices[val];
    this.vertices--;
  }

  addEdge(valOne, valTwo){
    this.vertices[valOne].push(valTwo);
    this.vertices[valTwo].push(valOne);

    this.totalEdges++;
   }

   removeEdge(valOne, valTwo){

    valOne.splice( valOne.indexOf(valTwo), 1 );
    valTwo.splice( valTwo.indexOf(valOne), 1 );

    this.totalEdges--;
  }

}

<|endoftext|>


<commit_before>// ---------------------------------------------------------------------------
// Usage: npm run transpile
// ---------------------------------------------------------------------------

"use strict";

const fs = require ('fs')
    , log = require ('ololog')
    , ansi = require ('ansicolor').nice
    , { unCamelCase, precisionConstants, safeString } = require ('ccxt/js/base/functions.js')
    , {
        createFolderRecursively,
        overwriteFile,
        replaceInFile,
    } = require ('ccxt/build/fs.js')
    , errors = require ('ccxt/js/base/errors.js')
    , Transpiler = require ('ccxt/build/transpile.js')
    , Exchange = require ('../js/base/Exchange.js')

// ============================================================================

class CCXTProTranspiler extends Transpiler {

    getBaseClass () {
        return new Exchange ()
    }

    getPHPPreamble () {
        return [
            "<?php",
            "namespace ccxtpro;",
            "include_once __DIR__ . '/../../vendor/autoload.php';",
            "// ----------------------------------------------------------------------------",
            "",
            "// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:",
            "// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code",
            "",
            "// -----------------------------------------------------------------------------",
            "",
        ].join ("\n")
    }

    createPythonClassDeclaration (className, baseClass) {
        const baseClasses = (baseClass.indexOf ('ccxt.') === 0) ?
            [ 'Exchange', baseClass ] :
            [ baseClass ]
        return 'class ' + className + '(' + baseClasses.join (', ') + '):'
    }

    createPythonClassImports (baseClass, async = false) {

        const baseClasses = {
            'Exchange': 'base.exchange',
        }

        async = (async ? '.async_support' : '')

        if (baseClass.indexOf ('ccxt.') === 0) {
            return [
                'from ccxtpro.base.exchange import Exchange',
                'import ccxt' + async + ' as ccxt'
            ]
        } else {
            return [
                'from ccxtpro.' + safeString (baseClasses, baseClass, baseClass) + ' import ' + baseClass
            ]
        }
        // return [
        //     (baseClass.indexOf ('ccxt.') === 0) ?
        //         ('import ccxt' + async + ' as ccxt') :
        //         ('from ccxtpro.' + safeString (baseClasses, baseClass, baseClass) + ' import ' + baseClass)
        // ]
    }

    createPythonClassHeader (ccxtImports, bodyAsString) {
        if (bodyAsString.indexOf ('ArrayCache') > -1) {
            ccxtImports.push ('from ccxtpro.base.cache import ArrayCache')
        }
        return [
            "# -*- coding: utf-8 -*-",
            "",
            "# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:",
            "# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code",
            "",
            // "from ccxtpro.base.exchange import Exchange",
            ... ccxtImports,
            // 'from ' + importFrom + ' import ' + baseClass,
            ... (bodyAsString.match (/basestring/) ? [
                "",
                "# -----------------------------------------------------------------------------",
                "",
                "try:",
                "    basestring  # Python 3",
                "except NameError:",
                "    basestring = str  # Python 2",
            ] : [])
        ]
    }

    createPHPClassDeclaration (className, baseClass) {
        let lines = [
            'class ' + className + ' extends ' + baseClass.replace ('ccxt.', '\\ccxt\\') + ' {',
        ]
        if (baseClass.indexOf ('ccxt.') === 0) {
            lines = lines.concat ([
                '',
                '    use ClientTrait;'
            ])
        }
        return lines.join ("\n")
    }

    createPHPClassHeader (className, baseClass, bodyAsString) {
        return [
            "<?php",
            "",
            "namespace ccxtpro;",
            "",
            "// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:",
            "// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code",
            "",
            "use Exception; // a common import",
        ]
    }

    // ------------------------------------------------------------------------

    transpileOrderBookTest () {
        const jsFile = './js/test/base/test.OrderBook.js'
        const pyFile = './python/test/test_order_book.py'
        const phpFile = './php/test/OrderBook.php'
        const pyImports = [
            '',
            'from ccxtpro.base.order_book import OrderBook, IndexedOrderBook, CountedOrderBook, IncrementalOrderBook, IncrementalIndexedOrderBook  # noqa: F402',
            '',
        ].join ('\n')
        this.transpileTest (jsFile, pyFile, phpFile, pyImports)
    }

    // ------------------------------------------------------------------------

    transpileCacheTest () {
        const jsFile = './js/test/base/test.Cache.js'
        const pyFile = './python/test/test_cache.py'
        const phpFile = './php/test/Cache.php'
        const pyImports = [
            '',
            'from ccxtpro.base.cache import ArrayCache  # noqa: F402',
            '',
        ].join ('\n')
        this.transpileTest (jsFile, pyFile, phpFile, pyImports)
    }

    // ------------------------------------------------------------------------

    transpileTest (jsFile, pyFile, phpFile, pyImports) {

        log.magenta ('Transpiling from', jsFile.yellow)

        let js = fs.readFileSync (jsFile).toString ()

        js = this.regexAll (js, [
            [ /\'use strict\';?\s+/g, '' ],
            [ /[^\n]+require[^\n]+\n/g, '' ],
            [ /function equals \([\S\s]+?return true\n}\n/g, '' ],
        ])

        const options = { js, removeEmptyLines: false }
        const transpiled = this.transpileJavaScriptToPythonAndPHP (options)
        const { python3Body, python2Body, phpBody } = transpiled
        const pythonHeader = [
            '',
            '',
            'def equals(a, b):',
            '    return a == b',
            '',
        ].join ('\n')

        const phpHeader = [
            '',
            'function equals($a, $b) {',
            '    return json_encode($a) === json_encode($b);',
            '}',
        ].join ('\n')

        const python = this.getPythonPreamble () + pyImports + pythonHeader + python2Body
        const php = this.getPHPPreamble () + phpHeader + phpBody

        log.magenta ('→', pyFile.yellow)
        log.magenta ('→', phpFile.yellow)

        overwriteFile (pyFile, python)
        overwriteFile (phpFile, php)
    }

    // ------------------------------------------------------------------------

    exportTypeScriptDeclarations (file, classes) {

        log.bright.cyan ('Exporting TypeScript declarations →', file.yellow)

        const regex = /\/[\n]{2}(?:    export class [^\s]+ extends [^\s]+ \{\}[\r]?[\n])+/
        const replacement = "/\n\n" + Object.keys (classes).map (className => {
            const baseClass = classes[className].replace (/ccxt\.[a-z]+/, 'Exchange')
            return '    export class ' + className + ' extends ' + baseClass + " {}"
        }).join ("\n") + "\n"

        replaceInFile (file, regex, replacement)
    }

    // ------------------------------------------------------------------------

    transpileEverything () {

        // default pattern is '.js'
        const [ /* node */, /* script */, pattern ] = process.argv
            // , python2Folder = './python/ccxtpro/', // CCXT Pro does not support Python 2
            , python3Folder = './python/ccxtpro/'
            , phpFolder     = './php/'
            , options = { /* python2Folder, */ python3Folder, phpFolder }

        // createFolderRecursively (python2Folder)
        createFolderRecursively (python3Folder)
        createFolderRecursively (phpFolder)

        this.transpileCacheTest ()
        this.transpileOrderBookTest ()
        const classes = this.transpileDerivedExchangeFiles ('./js/', options, pattern)

        if (classes === null) {
            log.bright.yellow ('0 files transpiled.')
            return;
        }

        // HINT: if we're going to support specific class definitions
        // this process won't work anymore as it will override the definitions
        this.exportTypeScriptDeclarations ('./ccxt.pro.d.ts', classes)

        // transpileErrorHierarchy ()

        // transpilePrecisionTests ()
        // transpileDateTimeTests ()
        // transpileCryptoTests ()

        log.bright.green ('Transpiled successfully.')
    }
}

// ============================================================================
// main entry point

if (require.main === module) {

    // if called directly like `node module`

    const transpiler = new CCXTProTranspiler ()
    transpiler.transpileEverything ()

} else {

    // do nothing if required as a module
}

// ============================================================================

module.exports = {}
<commit_msg>transpile.js minor edits / ArrayCache<commit_after>// ---------------------------------------------------------------------------
// Usage: npm run transpile
// ---------------------------------------------------------------------------

"use strict";

const fs = require ('fs')
    , log = require ('ololog')
    , ansi = require ('ansicolor').nice
    , { unCamelCase, precisionConstants, safeString } = require ('ccxt/js/base/functions.js')
    , {
        createFolderRecursively,
        overwriteFile,
        replaceInFile,
    } = require ('ccxt/build/fs.js')
    , errors = require ('ccxt/js/base/errors.js')
    , Transpiler = require ('ccxt/build/transpile.js')
    , Exchange = require ('../js/base/Exchange.js')

// ============================================================================

class CCXTProTranspiler extends Transpiler {

    getBaseClass () {
        return new Exchange ()
    }

    getPHPPreamble () {
        return [
            "<?php",
            "namespace ccxtpro;",
            "include_once __DIR__ . '/../../vendor/autoload.php';",
            "// ----------------------------------------------------------------------------",
            "",
            "// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:",
            "// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code",
            "",
            "// -----------------------------------------------------------------------------",
            "",
        ].join ("\n")
    }

    createPythonClassDeclaration (className, baseClass) {
        const baseClasses = (baseClass.indexOf ('ccxt.') === 0) ?
            [ 'Exchange', baseClass ] :
            [ baseClass ]
        return 'class ' + className + '(' + baseClasses.join (', ') + '):'
    }

    createPythonClassImports (baseClass, async = false) {

        const baseClasses = {
            'Exchange': 'base.exchange',
        }

        async = (async ? '.async_support' : '')

        if (baseClass.indexOf ('ccxt.') === 0) {
            return [
                'from ccxtpro.base.exchange import Exchange',
                'import ccxt' + async + ' as ccxt'
            ]
        } else {
            return [
                'from ccxtpro.' + safeString (baseClasses, baseClass, baseClass) + ' import ' + baseClass
            ]
        }
        // return [
        //     (baseClass.indexOf ('ccxt.') === 0) ?
        //         ('import ccxt' + async + ' as ccxt') :
        //         ('from ccxtpro.' + safeString (baseClasses, baseClass, baseClass) + ' import ' + baseClass)
        // ]
    }

    createPythonClassHeader (ccxtImports, bodyAsString) {
        let imports = ccxtImports
        if (bodyAsString.includes ('ArrayCache')) {
            imports = [
                ... ccxtImports,
                'from ccxtpro.base.cache import ArrayCache',
            ]
        }
        return [
            "# -*- coding: utf-8 -*-",
            "",
            "# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:",
            "# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code",
            "",
            // "from ccxtpro.base.exchange import Exchange",
            ... imports,
            // 'from ' + importFrom + ' import ' + baseClass,
            ... (bodyAsString.includes ('basestring') ? [
                "",
                "# -----------------------------------------------------------------------------",
                "",
                "try:",
                "    basestring  # Python 3",
                "except NameError:",
                "    basestring = str  # Python 2",
            ] : [])
        ]
    }

    createPHPClassDeclaration (className, baseClass) {
        let lines = [
            'class ' + className + ' extends ' + baseClass.replace ('ccxt.', '\\ccxt\\') + ' {',
        ]
        if (baseClass.indexOf ('ccxt.') === 0) {
            lines = lines.concat ([
                '',
                '    use ClientTrait;'
            ])
        }
        return lines.join ("\n")
    }

    createPHPClassHeader (className, baseClass, bodyAsString) {
        return [
            "<?php",
            "",
            "namespace ccxtpro;",
            "",
            "// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:",
            "// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code",
            "",
            "use Exception; // a common import",
        ]
    }

    // ------------------------------------------------------------------------

    transpileOrderBookTest () {
        const jsFile = './js/test/base/test.OrderBook.js'
        const pyFile = './python/test/test_order_book.py'
        const phpFile = './php/test/OrderBook.php'
        const pyImports = [
            '',
            'from ccxtpro.base.order_book import OrderBook, IndexedOrderBook, CountedOrderBook, IncrementalOrderBook, IncrementalIndexedOrderBook  # noqa: F402',
            '',
        ].join ('\n')
        this.transpileTest (jsFile, pyFile, phpFile, pyImports)
    }

    // ------------------------------------------------------------------------

    transpileCacheTest () {
        const jsFile = './js/test/base/test.Cache.js'
        const pyFile = './python/test/test_cache.py'
        const phpFile = './php/test/Cache.php'
        const pyImports = [
            '',
            'from ccxtpro.base.cache import ArrayCache  # noqa: F402',
            '',
        ].join ('\n')
        this.transpileTest (jsFile, pyFile, phpFile, pyImports)
    }

    // ------------------------------------------------------------------------

    transpileTest (jsFile, pyFile, phpFile, pyImports) {

        log.magenta ('Transpiling from', jsFile.yellow)

        let js = fs.readFileSync (jsFile).toString ()

        js = this.regexAll (js, [
            [ /\'use strict\';?\s+/g, '' ],
            [ /[^\n]+require[^\n]+\n/g, '' ],
            [ /function equals \([\S\s]+?return true\n}\n/g, '' ],
        ])

        const options = { js, removeEmptyLines: false }
        const transpiled = this.transpileJavaScriptToPythonAndPHP (options)
        const { python3Body, python2Body, phpBody } = transpiled
        const pythonHeader = [
            '',
            '',
            'def equals(a, b):',
            '    return a == b',
            '',
        ].join ('\n')

        const phpHeader = [
            '',
            'function equals($a, $b) {',
            '    return json_encode($a) === json_encode($b);',
            '}',
        ].join ('\n')

        const python = this.getPythonPreamble () + pyImports + pythonHeader + python2Body
        const php = this.getPHPPreamble () + phpHeader + phpBody

        log.magenta ('→', pyFile.yellow)
        log.magenta ('→', phpFile.yellow)

        overwriteFile (pyFile, python)
        overwriteFile (phpFile, php)
    }

    // ------------------------------------------------------------------------

    exportTypeScriptDeclarations (file, classes) {

        log.bright.cyan ('Exporting TypeScript declarations →', file.yellow)

        const regex = /\/[\n]{2}(?:    export class [^\s]+ extends [^\s]+ \{\}[\r]?[\n])+/
        const replacement = "/\n\n" + Object.keys (classes).map (className => {
            const baseClass = classes[className].replace (/ccxt\.[a-z]+/, 'Exchange')
            return '    export class ' + className + ' extends ' + baseClass + " {}"
        }).join ("\n") + "\n"

        replaceInFile (file, regex, replacement)
    }

    // ------------------------------------------------------------------------

    transpileEverything () {

        // default pattern is '.js'
        const [ /* node */, /* script */, pattern ] = process.argv
            // , python2Folder = './python/ccxtpro/', // CCXT Pro does not support Python 2
            , python3Folder = './python/ccxtpro/'
            , phpFolder     = './php/'
            , options = { /* python2Folder, */ python3Folder, phpFolder }

        // createFolderRecursively (python2Folder)
        createFolderRecursively (python3Folder)
        createFolderRecursively (phpFolder)

        this.transpileCacheTest ()
        this.transpileOrderBookTest ()
        const classes = this.transpileDerivedExchangeFiles ('./js/', options, pattern)

        if (classes === null) {
            log.bright.yellow ('0 files transpiled.')
            return;
        }

        // HINT: if we're going to support specific class definitions
        // this process won't work anymore as it will override the definitions
        this.exportTypeScriptDeclarations ('./ccxt.pro.d.ts', classes)

        // transpileErrorHierarchy ()

        // transpilePrecisionTests ()
        // transpileDateTimeTests ()
        // transpileCryptoTests ()

        log.bright.green ('Transpiled successfully.')
    }
}

// ============================================================================
// main entry point

if (require.main === module) {

    // if called directly like `node module`

    const transpiler = new CCXTProTranspiler ()
    transpiler.transpileEverything ()

} else {

    // do nothing if required as a module
}

// ============================================================================

module.exports = {}
<|endoftext|>


<commit_before>var request = require('request');
	promise = require('bluebird');

promise.promisifyAll(request);

request.getAsync("https://seeclickfix.com/api/v2/issues?place_url=hampton&state=VA&per_page=20&page=1")
		.spread(function(res,body) { //callback signature is (err, res, body) so we need to use spread instead of then
			var data = JSON.parse(body).metadata;
			return data;
		}).then(function(data) {
			console.log('\n I got the data to this point \n',data);
		});

<commit_msg>changed to issues.<commit_after>var request = require('request');
	promise = require('bluebird');

promise.promisifyAll(request);

request.getAsync("https://seeclickfix.com/api/v2/issues?place_url=hampton&state=VA&per_page=20&page=1")
		.spread(function(res,body) { //callback signature is (err, res, body) so we need to use spread instead of then
			var data = JSON.parse(body).issues;
			return data;
		}).then(function(data) {
			console.log('\n I got the data to this point \n',data);
		});

<|endoftext|>


<commit_before>// ==UserScript==
// @include http://youtube.com/*
// @include https://youtube.com/*
// @include http://*.youtube.com/*
// @include https://*.youtube.com/*
// ==/UserScript==

window.addEventListener('DOMContentLoaded', function()
{
  if (!oexWMPbetaParticipant())
  {
    if (widget.preferences.continueTesting == 'true') oexWMPbetaApplicant();
  }
  if (widget.preferences.videoSaveButton == 'true') oexWMPsaveButton();
  if (widget.preferences.filterSearch == 'true') oexWMPfilterSearchResults();
  if (widget.preferences.hideFlashPromo == 'true') oexWMPremoveElement('flash10-promo-div');
  if (widget.preferences.hideFlashUpgrade == 'true') setTimeout((function() { oexWMPremoveElement('flash-upgrade'); }), 275);
  if (widget.preferences.preventFlash == 'true') oexWMPremoveElement('movie_player');
}, false);

var oexWMPbcv = 'f2=40000000',
  oexWMPbfc = 'PREF=' + oexWMPbcv;

function oexWMPbetaParticipant()
{
  setTimeout(t = oexWMPcookieTester('PREF',oexWMPbcv),1000);
  return t;
}

function oexWMPbetaApplicant()
{
  var d = new Date(),
    ed = (new Date(d.getTime()+(20908800000))).toUTCString(), // eight months
    cv = oexWMPcookieTester('PREF',false,true);
  if (cv != false && cv != undefined && cv != oexWMPbfc)
  {
    cv = cv.substring(5).replace(/&f2=[0-9]{0,9}|f2=[0-9]{0,9}&|&f2=[0-9]{0,9}/i,'');
    document.cookie = oexWMPbfc + '; expires=Thu, 01-Jan-1970 00:00:01 UTC; ;';
    document.cookie = oexWMPbfc + '&' + cv + '; path=/; domain=.youtube.com; ' +  'expires=' + ed;
  }
  else
  {
    document.cookie = oexWMPbfc + '; path=/; domain=.youtube.com; ' +  'expires=' + ed;
  }
}

function oexWMPcookieTester(ic,iv,rv)
{
  var i, jar = document.cookie.split(';');
  for(i=0;i < jar.length;i++)
  {
    var c = jar[i];
    while (c.charAt(0) == ' ') c = c.substring(1,c.length);
    if (c.indexOf(ic + '=') == 0 && iv == null) return true;
    else if ((c.indexOf(ic + '=') == 0) && rv != null) return c;
    else if ((c.indexOf(ic + '=') == 0) && (c.substring(ic + '='.length,c.length).indexOf(iv) >= 0) && rv == null) return true;
  }
  return false;
}

function oexWMPsaveButton() {
  var v = document.getElementsByTagName('video'),
    c = document.getElementById('watch-actions-right'),
    b = document.createElement('button');
  if (v.length > 0 && c != undefined)
  {
    b.setAttribute('class', 'yt-uix-button yt-uix-tooltip yt-uix-tooltip-reverse');
    b.style.position = 'relative';
    b.style.top = '-4px';
    b.setAttribute('data-tooltip-text', 'Click, then press Ctrl+S to save.');
    b.onclick = function() { window.location = v[0].src; }
    t = document.createTextNode('Download Video');
    b.appendChild(t)
    c.appendChild(b);
  };
}

function oexWMPremoveElement(id)
{
  var e = document.getElementById(id);
  if (e != null) e.parentNode.removeChild(id);
}

function oexWMPfilterSearchResults()
{
  var p, sf = document.getElementById('masthead-search');
  if (sf != null) {
    p = document.createElement('input');
    p.setAttribute('name', 'webm');
    p.setAttribute('type', 'hidden');
    p.setAttribute('value', '1');
    sf.appendChild(p);
  }}<commit_msg>Still using the wrong variable there.<commit_after>// ==UserScript==
// @include http://youtube.com/*
// @include https://youtube.com/*
// @include http://*.youtube.com/*
// @include https://*.youtube.com/*
// ==/UserScript==

window.addEventListener('DOMContentLoaded', function()
{
  if (!oexWMPbetaParticipant())
  {
    if (widget.preferences.continueTesting == 'true') oexWMPbetaApplicant();
  }
  if (widget.preferences.videoSaveButton == 'true') oexWMPsaveButton();
  if (widget.preferences.filterSearch == 'true') oexWMPfilterSearchResults();
  if (widget.preferences.hideFlashPromo == 'true') oexWMPremoveElement('flash10-promo-div');
  if (widget.preferences.hideFlashUpgrade == 'true') setTimeout((function() { oexWMPremoveElement('flash-upgrade'); }), 275);
  if (widget.preferences.preventFlash == 'true') oexWMPremoveElement('movie_player');
}, false);

var oexWMPbcv = 'f2=40000000',
  oexWMPbfc = 'PREF=' + oexWMPbcv;

function oexWMPbetaParticipant()
{
  setTimeout(t = oexWMPcookieTester('PREF',oexWMPbcv),1000);
  return t;
}

function oexWMPbetaApplicant()
{
  var d = new Date(),
    ed = (new Date(d.getTime()+(20908800000))).toUTCString(), // eight months
    cv = oexWMPcookieTester('PREF',false,true);
  if (cv != false && cv != undefined && cv != oexWMPbfc)
  {
    cv = cv.substring(5).replace(/&f2=[0-9]{0,9}|f2=[0-9]{0,9}&|&f2=[0-9]{0,9}/i,'');
    document.cookie = oexWMPbfc + '; expires=Thu, 01-Jan-1970 00:00:01 UTC; ;';
    document.cookie = oexWMPbfc + '&' + cv + '; path=/; domain=.youtube.com; ' +  'expires=' + ed;
  }
  else
  {
    document.cookie = oexWMPbfc + '; path=/; domain=.youtube.com; ' +  'expires=' + ed;
  }
}

function oexWMPcookieTester(ic,iv,rv)
{
  var i, jar = document.cookie.split(';');
  for(i=0;i < jar.length;i++)
  {
    var c = jar[i];
    while (c.charAt(0) == ' ') c = c.substring(1,c.length);
    if (c.indexOf(ic + '=') == 0 && iv == null) return true;
    else if ((c.indexOf(ic + '=') == 0) && rv != null) return c;
    else if ((c.indexOf(ic + '=') == 0) && (c.substring(ic + '='.length,c.length).indexOf(iv) >= 0) && rv == null) return true;
  }
  return false;
}

function oexWMPsaveButton() {
  var v = document.getElementsByTagName('video'),
    c = document.getElementById('watch-actions-right'),
    b = document.createElement('button');
  if (v.length > 0 && c != undefined)
  {
    b.setAttribute('class', 'yt-uix-button yt-uix-tooltip yt-uix-tooltip-reverse');
    b.style.position = 'relative';
    b.style.top = '-4px';
    b.setAttribute('data-tooltip-text', 'Click, then press Ctrl+S to save.');
    b.onclick = function() { window.location = v[0].src; }
    t = document.createTextNode('Download Video');
    b.appendChild(t)
    c.appendChild(b);
  };
}

function oexWMPremoveElement(id)
{
  var e = document.getElementById(id);
  if (e != null) e.parentNode.removeChild(e);
}

function oexWMPfilterSearchResults()
{
  var p, sf = document.getElementById('masthead-search');
  if (sf != null) {
    p = document.createElement('input');
    p.setAttribute('name', 'webm');
    p.setAttribute('type', 'hidden');
    p.setAttribute('value', '1');
    sf.appendChild(p);
  }}
<|endoftext|>


<commit_before>/*
Node wrapper for Freshdesk v2 API

Copyright (C) 2016-2017 Maksim Koryukov <maxkoryukov@gmail.com>

This program is free software: you can redistribute it and/or modify
it under the terms of the MIT License, attached to this software package.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

You should have received a copy of the MIT License along with this
program. If not, see <https://opensource.org/licenses/MIT>.

http://spdx.org/licenses/MIT
*/

'use strict'

const nock = require('nock')

const Freshdesk = require('..')

describe('api.companies', function(){

	const freshdesk = new Freshdesk('https://test.freshdesk.com', 'TESTKEY')

	describe('update', () => {

		let res = null

		beforeEach(() => {

			// SET UP expected request

			nock('https://test.freshdesk.com')
				.post('/api/v2/companies', {
					"name": "ACME"
				})
				.reply(200, res)
		})

		it('should send PUT request to /api/v2/companies', (done) => {

			freshdesk.updateCompany(res.id, {"name": "ACME 2"}, (err, data) => {
				expect(err).is.null
				expect(data.name).to.deep.equal("ACME 2")
				done()
			})

		})

		afterEach(() => {

			nock('https://test.freshdesk.com')
				.delete(`/api/v2/companies/${res.id}`).reply(204)
		})

	})

	describe('listAllCompanyFields', () => {

		describe('without params', () => {

			let res = null

			beforeEach(() => {

				// SET UP expected request
				nock('https://test.freshdesk.com')
					.get('/api/v2/company_fields')
					//.query({})
					.reply(200, res)
			})

			it('should send GET request to /api/v2/company_fields', function(done) {
				freshdesk.listAllCompanyFields((err, data) => {
					expect(err).is.null
					expect(data).to.deep.equal(res)

					done()
				})
			})

		})

	})
})
<commit_msg>fixed tests<commit_after>/*
Node wrapper for Freshdesk v2 API

Copyright (C) 2016-2017 Maksim Koryukov <maxkoryukov@gmail.com>

This program is free software: you can redistribute it and/or modify
it under the terms of the MIT License, attached to this software package.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

You should have received a copy of the MIT License along with this
program. If not, see <https://opensource.org/licenses/MIT>.

http://spdx.org/licenses/MIT
*/

'use strict'

const nock = require('nock')

const Freshdesk = require('..')

describe('api.companies', function(){

	const freshdesk = new Freshdesk('https://test.freshdesk.com', 'TESTKEY')

	describe('update', () => {

		it('should send PUT request to /api/v2/companies', (done) => {

			const res = {
				"id": 1000,
				"name": "ACME"}

			// SET UP expected request

			nock('https://test.freshdesk.com')
				.put(`/api/v2/companies/1000`, {
					"name": "ACME"
				})
				.reply(200, res)

			freshdesk.updateCompany(1000, {"name": "ACME"}, (err, data) => {
				expect(err).is.null
				expect(data).to.deep.equal(res)
				done()
			})

		})

	})

	describe('listAllCompanyFields', () => {

		describe('without params', () => {

			let res = null

			beforeEach(() => {
				res = [
				   {
					  "id":1,
					  "name":"name",
					  "label":"Company name",
					  "field_type":"default_name",
					  "required_for_agent":true,
					  "position":1,
					  "default":true,
					  "created_at":"2014-12-12T12:29:46+05:30",
					  "updated_at":"2014-12-12T12:29:46+05:30"
				   }]

				// SET UP expected request
				nock('https://test.freshdesk.com')
					.get('/api/v2/company_fields')
					//.query({})
					.reply(200, res)
			})

			it('should send GET request to /api/v2/company_fields', function(done) {
				freshdesk.listAllCompanyFields((err, data) => {
					expect(err).is.null
					expect(data).to.deep.equal(res)

					done()
				})
			})

		})

	})
})
<|endoftext|>


<commit_before>//HV control panel
(function(){

    xtag.register('widget-rateBar', {
        extends: 'div',
        lifecycle: {
            created: function() {
                var barTitle = document.createElement('h2')

                ////////////////////
                //build the DOM
                ////////////////////
                barTitle.setAttribute('id', this.id + 'Title');
                barTitle.innerHTML = 'Click on a rate or threshold channel to get started.';
                this.appendChild(barTitle);
                this.UIdeployed = false;

                this.addEventListener('postADC', function(evt){
                    this.updateRates(evt.detail);
                }, false);

            },
            inserted: function() {},
            removed: function() {},
            attributeChanged: function() {}
        },
        events: {

        },
        accessors: {
            'MIDAS':{
                attribute: {} //this just needs to be declared
            }
        },
        methods: {
            'updateRates' : function(customEventData){
                document.getElementById(this.id + 'Title').innerHTML = customEventData.channel
                if(!this.UIdeployed){
                    this.setUpUI();
                    this.UIdeployed = true;
                }
            },

            'setUpUI' : function(){
                var control = document.createElement('div'),
                    mainSections = ['ADCstatusPane', 'ADC', 'trig', 'pulseHeight', 'time', 'waveform', 'simulation', 'misc'],
                    mainSectionDivs = [],
                    mainSectionTitles = ['MSCB Node Info', 'ADC Control', 'Triggering', 'Pulse Height Evaluation', 'Time Evaluation', 'Waveform Readout', 'Simulation Pulse', 'Miscellaneous'],
                    mainSectionH3 = [],
                    mainLists = [],
                    statusIDs = ['ctrl', 'rev', 'serial', 'cpu_temp', 'cc_lock', 'cc_freq', 'hw_sw_m', 'hw_id', 'hw_time', 'sw_id', 'sw_time', 'uptime', 'dac_ch', 'ref_clk', 'ch_en', 'ch_aa'],
                    ADCitemTitles = ['DC Offset:', 'ADC Chan:', 'Trim:', 'Polarity:'],
                    triggeringItemTitles = ['Channel:', 'Hit Thresh:', 'Trig Thresh', 'Differentiation:', 'Integration:', 'Delay:', 'Pole Cxn:', 'BLR Control:'],
                    listItem, items, input, label, p,
                    id, step,
                    i;

                //wrapper for ADC UI
                control.setAttribute('id', 'control');
                this.appendChild(control);

                //main sections
                for(i=0; i<mainSections.length; i++){
                    mainSectionDivs[i] = document.createElement('div');
                    mainSectionDivs[i].setAttribute('id', mainSections[i]);
                    mainSectionDivs[i].setAttribute('class', 'collapse');

                    mainSectionH3[i] = document.createElement('h3');
                    mainSectionH3[i].setAttribute('class', 'sectionHead');
                    mainSectionH3[i].onclick = toggleSection.bind(mainSectionH3[i], mainSections[i]);
                    mainSectionH3[i].innerHTML = String.fromCharCode(0x25B6) + ' ' +mainSectionTitles[i];
                    mainSectionDivs[i].appendChild(mainSectionH3[i]);

                    mainLists[i] = document.createElement('ul');
                    mainSectionDivs[i].appendChild(mainLists[i]);

                    control.appendChild(mainSectionDivs[i]);
                }

                ////////////////////////////
                //ADC status pane elements
                ////////////////////////////
                for(i=0; i<statusIDs.length; i++){
                    listItem = document.createElement('li');
                    listItem.setAttribute('id', statusIDs[i]);
                    mainLists[0].appendChild(listItem);
                }

                //////////////////////////
                //ADC pane elements
                //////////////////////////
                items = [];
                for(i=0; i<ADCitemTitles.length; i++){
                    listItem = document.createElement('li');
                    mainLists[1].appendChild(listItem);
                    label = document.createElement('label');
                    label.innerHTML = ADCitemTitles[i];
                    listItem.appendChild(label);
                    items.push(listItem);
                }

                input = document.createElement('input');
                setAttributes(input, {
                    "id" : "a_dcofst",
                    "type" : "range",
                    "step" : 1,
                    "min" : 0,
                    "max" : 4095,
                });
                input.oninput = this.updateADC.bind(input, 'a_dcofst');
                items[0].appendChild(input);
                label = document.createElement('label');
                label.setAttribute('id', 'dcofstLabel');
                label.innerHTML = 'mV';
                items[0].appendChild(label);

                radioArray(items[1], ['Enabled', 'Disabled'], [true, false], 'a_off');
                document.getElementById('a_off0').onchange = this.updateADC.bind(document.getElementById('a_off0'), 'a_off');
                document.getElementById('a_off1').onchange = this.updateADC.bind(document.getElementById('a_off1'), 'a_off');

                input = document.createElement('input');
                setAttributes(input, {
                    "id" : "a_trim",
                    "type" : "number",
                    "step" : 1,
                    "class" : "stdin"
                });
                input.onchange = this.updateADC.bind(input, 'a_trim');
                items[2].appendChild(input);

                radioArray(items[3], ['Positive', 'Negative'], [true, false], 'a_pol');
                document.getElementById('a_pol0').onchange = this.updateADC.bind(document.getElementById('a_pol0'), 'a_pol');
                document.getElementById('a_pol1').onchange = this.updateADC.bind(document.getElementById('a_pol1'), 'a_pol');

                ////////////////////////////////
                //Triggering pane elements
                ////////////////////////////////
                items = [];
                for(i=0; i<triggeringItemTitles.length; i++){
                    listItem = document.createElement('li');
                    mainLists[2].appendChild(listItem);
                    label = document.createElement('label');
                    label.innerHTML = triggeringItemTitles[i];
                    listItem.appendChild(label);
                    items.push(listItem);
                }

                radioArray(items[0], ['Enabled', 'Disabled'], [true, false], 't_off');
                document.getElementById('t_off0').onchange = this.updateADC.bind(document.getElementById('t_off0'), 't_off');
                document.getElementById('t_off1').onchange = this.updateADC.bind(document.getElementById('t_off1'), 't_off');

                id = ['t_hthresh', 't_thresh', 't_diff', 't_int', 't_delay', 't_polcor', 't_blrctl'];
                step = ["any", "any", 1, 1, 1, "any", "any"];

                for(i=0; i<id.length; i++){
                    input = document.createElement('input');
                    setAttributes(input, {
                        "id" : id[i],
                        "type" : "number",
                        "step" : step[i],
                        "class" : "stdin"
                    });
                    input.onchange = this.updateADC.bind(input, id[i]);
                    items[i+1].appendChild(input);
                }

            },

            'updateADC' : function(var_name){
                console.log(var_name)
            }
        }
    });

})();

function toggleSection(id){
    var section = document.getElementById(id)

    if(section.className == 'collapse'){
        section.className = 'expand'
        this.innerHTML = String.fromCharCode(0x25BC) + this.innerHTML.slice(this.innerHTML.indexOf(' '));
    }
    else{
        section.className = 'collapse'
        this.innerHTML = String.fromCharCode(0x25B6) + this.innerHTML.slice(this.innerHTML.indexOf(' '));
    }
}<commit_msg>setting up ADC control UI<commit_after>//HV control panel
(function(){

    xtag.register('widget-rateBar', {
        extends: 'div',
        lifecycle: {
            created: function() {
                var barTitle = document.createElement('h2')

                ////////////////////
                //build the DOM
                ////////////////////
                barTitle.setAttribute('id', this.id + 'Title');
                barTitle.innerHTML = 'Click on a rate or threshold channel to get started.';
                this.appendChild(barTitle);
                this.UIdeployed = false;

                this.addEventListener('postADC', function(evt){
                    this.updateRates(evt.detail);
                }, false);

            },
            inserted: function() {},
            removed: function() {},
            attributeChanged: function() {}
        },
        events: {

        },
        accessors: {
            'MIDAS':{
                attribute: {} //this just needs to be declared
            }
        },
        methods: {
            'updateRates' : function(customEventData){
                document.getElementById(this.id + 'Title').innerHTML = customEventData.channel
                if(!this.UIdeployed){
                    this.setUpUI();
                    this.UIdeployed = true;
                }
            },

            'setUpUI' : function(){
                var control = document.createElement('div'),
                    mainSections = ['ADCstatusPane', 'ADC', 'trig', 'pulseHeight', 'time', 'waveform', 'simulation', 'misc'],
                    mainSectionDivs = [],
                    mainSectionTitles = ['MSCB Node Info', 'ADC Control', 'Triggering', 'Pulse Height Evaluation', 'Time Evaluation', 'Waveform Readout', 'Simulation Pulse', 'Miscellaneous'],
                    mainSectionH3 = [],
                    mainLists = [],
                    statusIDs = ['ctrl', 'rev', 'serial', 'cpu_temp', 'cc_lock', 'cc_freq', 'hw_sw_m', 'hw_id', 'hw_time', 'sw_id', 'sw_time', 'uptime', 'dac_ch', 'ref_clk', 'ch_en', 'ch_aa'],
                    ADCitemTitles = ['DC Offset:', 'ADC Chan:', 'Trim:', 'Polarity:'],
                    triggeringItemTitles = ['Channel:', 'Hit Thresh:', 'Trig Thresh', 'Differentiation:', 'Integration:', 'Delay:', 'Pole Cxn:', 'BLR Control:'],
                    pulseheightItemTitles = ['Integration:', 'Differentiation:', 'Delay:', 'Pole Cxn 1:', 'Pole Cxn 2:', 'Baseline Rest:', 'Gain:', 'Pileup Algo:', ],
                    listItem, items, input, label, p,
                    id, step,
                    i;

                //wrapper for ADC UI
                control.setAttribute('id', 'control');
                this.appendChild(control);

                //main sections
                for(i=0; i<mainSections.length; i++){
                    mainSectionDivs[i] = document.createElement('div');
                    mainSectionDivs[i].setAttribute('id', mainSections[i]);
                    mainSectionDivs[i].setAttribute('class', 'collapse');

                    mainSectionH3[i] = document.createElement('h3');
                    mainSectionH3[i].setAttribute('class', 'sectionHead');
                    mainSectionH3[i].onclick = toggleSection.bind(mainSectionH3[i], mainSections[i]);
                    mainSectionH3[i].innerHTML = String.fromCharCode(0x25B6) + ' ' +mainSectionTitles[i];
                    mainSectionDivs[i].appendChild(mainSectionH3[i]);

                    mainLists[i] = document.createElement('ul');
                    mainSectionDivs[i].appendChild(mainLists[i]);

                    control.appendChild(mainSectionDivs[i]);
                }

                ////////////////////////////
                //ADC status pane elements
                ////////////////////////////
                for(i=0; i<statusIDs.length; i++){
                    listItem = document.createElement('li');
                    listItem.setAttribute('id', statusIDs[i]);
                    mainLists[0].appendChild(listItem);
                }

                //////////////////////////
                //ADC pane elements
                //////////////////////////
                items = [];
                for(i=0; i<ADCitemTitles.length; i++){
                    listItem = document.createElement('li');
                    mainLists[1].appendChild(listItem);
                    label = document.createElement('label');
                    label.innerHTML = ADCitemTitles[i];
                    listItem.appendChild(label);
                    items.push(listItem);
                }

                input = document.createElement('input');
                setAttributes(input, {
                    "id" : "a_dcofst",
                    "type" : "range",
                    "step" : 1,
                    "min" : 0,
                    "max" : 4095,
                });
                input.oninput = this.updateADC.bind(input, 'a_dcofst');
                items[0].appendChild(input);
                label = document.createElement('label');
                label.setAttribute('id', 'dcofstLabel');
                label.innerHTML = 'mV';
                items[0].appendChild(label);

                radioArray(items[1], ['Enabled', 'Disabled'], [true, false], 'a_off');
                document.getElementById('a_off0').onchange = this.updateADC.bind(document.getElementById('a_off0'), 'a_off');
                document.getElementById('a_off1').onchange = this.updateADC.bind(document.getElementById('a_off1'), 'a_off');

                input = document.createElement('input');
                setAttributes(input, {
                    "id" : "a_trim",
                    "type" : "number",
                    "step" : 1,
                    "class" : "stdin"
                });
                input.onchange = this.updateADC.bind(input, 'a_trim');
                items[2].appendChild(input);

                radioArray(items[3], ['Positive', 'Negative'], [true, false], 'a_pol');
                document.getElementById('a_pol0').onchange = this.updateADC.bind(document.getElementById('a_pol0'), 'a_pol');
                document.getElementById('a_pol1').onchange = this.updateADC.bind(document.getElementById('a_pol1'), 'a_pol');

                ////////////////////////////////
                //Triggering pane elements
                ////////////////////////////////
                items = [];
                for(i=0; i<triggeringItemTitles.length; i++){
                    listItem = document.createElement('li');
                    mainLists[2].appendChild(listItem);
                    label = document.createElement('label');
                    label.innerHTML = triggeringItemTitles[i];
                    listItem.appendChild(label);
                    items.push(listItem);
                }

                radioArray(items[0], ['Enabled', 'Disabled'], [true, false], 't_off');
                document.getElementById('t_off0').onchange = this.updateADC.bind(document.getElementById('t_off0'), 't_off');
                document.getElementById('t_off1').onchange = this.updateADC.bind(document.getElementById('t_off1'), 't_off');

                id = ['t_hthresh', 't_thresh', 't_diff', 't_int', 't_delay', 't_polcor', 't_blrctl'];
                step = ["any", "any", 1, 1, 1, "any", "any"];

                for(i=0; i<id.length; i++){
                    input = document.createElement('input');
                    setAttributes(input, {
                        "id" : id[i],
                        "type" : "number",
                        "step" : step[i],
                        "class" : "stdin"
                    });
                    input.onchange = this.updateADC.bind(input, id[i]);
                    items[i+1].appendChild(input);
                }

                /////////////////////////////////
                //pulse height pane elements
                /////////////////////////////////
                items = [];
                for(i=0; i<pulseheightItemTitles.length; i++){
                    listItem = document.createElement('li');
                    mainLists[3].appendChild(listItem);
                    label = document.createElement('label');
                    label.innerHTML = pulseheightItemTitles[i];
                    listItem.appendChild(label);
                    items.push(listItem);
                }

                id = ['p_int', 'p_diff', 'p_delay', 'p_polec1', 'p_polec2', 'p_bsr', 'p_gain', 'p_pactrl'];
                step = [1,1,1,"any","any","any","any", 1];

                for(i=0; i<id.length; i++){
                    input = document.createElement('input');
                    setAttributes(input, {
                        "id" : id[i],
                        "type" : "number",
                        "step" : step[i],
                        "class" : "stdin"
                    });
                    input.onchange = this.updateADC.bind(input, id[i]);
                    items[i].appendChild(input);
                }
            },

            'updateADC' : function(var_name){
                console.log(var_name)
            }
        }
    });

})();

function toggleSection(id){
    var section = document.getElementById(id)

    if(section.className == 'collapse'){
        section.className = 'expand'
        this.innerHTML = String.fromCharCode(0x25BC) + this.innerHTML.slice(this.innerHTML.indexOf(' '));
    }
    else{
        section.className = 'collapse'
        this.innerHTML = String.fromCharCode(0x25B6) + this.innerHTML.slice(this.innerHTML.indexOf(' '));
    }
}<|endoftext|>


<commit_before>/*
 * This program was produced for the U.S. Agency for International Development. It was prepared by the USAID | DELIVER PROJECT, Task Order 4. It is part of a project which utilizes code originally licensed under the terms of the Mozilla Public License (MPL) v2 and therefore is licensed under MPL v2 or later.
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the Mozilla Public License as published by the Mozilla Foundation, either version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Mozilla Public License for more details.
 *
 * You should have received a copy of the Mozilla Public License along with this program. If not, see http://www.mozilla.org/MPL/
 */

function RequisitionStatusSummaryController($scope, $filter,RnRStatusSummary,programsList,FlatGeographicZoneList,UserGeographicZoneTree,dashboardMenuService,$location ,dashboardFiltersHistoryService, formInputValue, GetPeriod, userPreferredFilterValues, ReportSchedules, ReportPeriods, OperationYears, ReportPeriodsByScheduleAndYear) {

    $scope.filterObject = {};

    $scope.formFilter = {};

    $scope.formPanel = {openPanel: true};
    $scope.rnrStatus = {openPanel: true};

    initialize();

    function initialize() {
        $scope.showProductsFilter = false;
        $scope.$parent.currentTab = "RNR-STATUS-SUMMARY";

    }

    $scope.programs = programsList;
    $scope.programs.unshift({'name': formInputValue.programOptionSelect});

    $scope.loadGeoZones = function(){
        UserGeographicZoneTree.get({programId:$scope.formFilter.programId}, function(data){
            $scope.zones = data.zone;
        });
    };

    FlatGeographicZoneList.get(function (data) {
        $scope.geographicZones = data.zones;
    });

    OperationYears.get(function (data) {
        $scope.startYears = data.years;
        $scope.startYears.unshift(formInputValue.yearOptionAll);
    });

    ReportSchedules.get(function (data) {
        $scope.schedules = data.schedules;
        $scope.schedules.unshift({'name': formInputValue.scheduleOptionSelect});

    });

    $scope.filterProductsByProgram = function () {
        $scope.loadGeoZones();
        if (isUndefined($scope.formFilter.programId)) {

            return;
        }
        $scope.filterObject.programId = $scope.formFilter.programId;
        $scope.formFilter.programName = getSelectedItemName($scope.formFilter.programId, $scope.programs);

        //$scope.loadRnRStatus();

    };

    $scope.processZoneFilter = function(){
        $scope.filterObject.zoneId = $scope.formFilter.zoneId;
        $scope.formFilter.zoneName = getSelectedZoneName($scope.formFilter.zoneId, $scope.zones, $scope.geographicZones);

        $scope.loadRnRStatus();
    };

    $scope.loadRnRStatus= function(){
        if (isUndefined($scope.filterObject.periodId) || isUndefined($scope.filterObject.programId)) {
            $scope.resetRnRStatusData();
            return;
        }

        RnRStatusSummary.get({zoneId:$scope.filterObject.zoneId,
                periodId:$scope.filterObject.periodId,
                programId:$scope.filterObject.programId
            },
            function (data) {
                alert('data is '+JSON.stringify(data))
                $scope.total = 0;
                $scope.RnRStatusPieChartData = [];
                $scope.dataRows = [];
                $scope.datarows = [];

                if (!isUndefined(data.rnrStatus)) {

                    $scope.dataRows = data.rnrStatus;
                    if(isUndefined($scope.dataRows)){
                        $scope.resetRnRStatusData();
                        return;
                    }
                    var statusData = _.pluck($scope.dataRows,'status');
                    var totalData = _.pluck($scope.dataRows,'totalStatus');

                    var color=["#F83103","#37AC02","#02A8FA","#FAA702"];
                    for (var i = 0; i < $scope.dataRows.length; i++) {
                        $scope.total += $scope.dataRows[i].totalStatus;
                        $scope.RnRStatusPieChartData[i] = {

                            label: statusData[i],
                            data: totalData[i],
                            color:color[i]

                        };

                    }
                    $scope.rnrStatusPieChartOptionFunction();
                    $scope.rnrStatusRenderedData = {
                        status : _.pairs(_.object(_.range(data.rnrStatus.length), _.pluck(data.rnrStatus,'status')))

                    };

                    bindChartEvent("#rnr-status-report","plotclick",rnrStatusChartClickHandler);
                    bindChartEvent("#rnr-status-report",flotChartHoverCursorHandler);

                } else {
                    $scope.resetRnRStatusReportData();
                }
                $scope.paramsChanged($scope.tableParams);
            });
       // }

    };

    $scope.resetRnRStatusData = function(){
        alert('called when period is null')
        $scope.rnrStatusRenderedData = null;
        $scope.rnRStatusPieChartOption = null;
        $scope.total = 0;
        $scope.RnRStatusPieChartData = null;
        $scope.dataRows = null;
        $scope.datarows = null;
    };

    var getFilterValues = function(){

        $scope.formFilter.periodName = getSelectedItemName($scope.formFilter.periodId,$scope.periods);
        $scope.formFilter.programName = getSelectedItemName($scope.formFilter.programId,$scope.programs);

        $scope.formFilter.zoneName = getSelectedZoneName($scope.formFilter.zoneId, $scope.zones, $scope.geographicZones);
        $scope.filterObject = $scope.formFilter;

    };

    $scope.rnrStatusPieChartOptionFunction =function(){

        $scope.rnRStatusPieChartOption = {
            series: {
                pie: {
                    show: true,
                    radius: 1,
                    label: {
                        show: true,
                        radius: 3 / 4,
                        formatter: function (label, series) {
                            return '
' + Math.round(series.percent) + '%
';
                        },
                        threshold: 0.1
                    }

                }
            },
            legend: {
                show: true,
                container: $("#rnrStatusReportLegend"),
                noColumns: 0,
                labelBoxBorderColor: "none",
                width:20

            },
            grid: {
                hoverable: true,
                clickable: true,
                borderWidth: 1,
                borderColor: "#d6d6d6",
                backgroundColor: {
                    colors: ["#FFF", "#CCC","#FFF","#CCC"]
                }
            },
            tooltip: true,
            tooltipOpts: {
                content: "%p.0%, %s",
                shifts: {
                    x: 20,
                    y: 0
                },
                defaultTheme: false
            }
        };

    };

    function flotChartHoverCursorHandler(event,pos,item){

        if (item && !isUndefined(item.dataIndex)) {
           $(event.target).css('cursor','pointer');
        } else {
            $(event.target).css('cursor','auto');
        }
    }

    function bindChartEvent(elementSelector, eventType, callback){
        $(elementSelector).bind(eventType, callback);
    }

    function rnrStatusChartClickHandler(event, pos, item){
        if(item){
            var status;
            if(!isUndefined($scope.rnrStatusRenderedData.status)){
                status = $scope.rnrStatusRenderedData.status[item.seriesIndex][1];
            }
            var rnrDetailPath = '/rnr-status-report/program/'+$scope.filterObject.programId+'/period/'+$scope.filterObject.periodId;
            dashboardMenuService.addTab('menu.header.dashboard.rnr.status.detail','/public/pages/dashboard/index.html#'+rnrDetailPath,'RNR-STATUS-DETAIL',true, 8);
            $location.path(rnrDetailPath).search("status="+status+"&zoneId="+$scope.filterObject.zoneId);

            $scope.$apply();
        }

    }

    $scope.resetRnRStatusReportData = function () {
        $scope.RnRStatusPieChartData = null;
        $scope.rnRStatusPieChartOption =null;
        $scope.dataRows = null;
    };

    $scope.loadFacilitiesByRequisition = function () {
        if ($scope.formFilter.rgroupId == "All") {
            $scope.filterObject.rgroupId = -1;
        } else if ($scope.formFilter.rgroupId !== undefined || $scope.formFilter.rgroupId === "") {
            $scope.filterObject.rgroupId = $scope.formFilter.rgroupId;
            $.each($scope.requisitionGroups, function (item, idx) {
                if (idx.id == $scope.formFilter.rgroupId) {
                    $scope.filterObject.rgroup = idx.name;
                }
            });
        } else {
            $scope.filterObject.rgroupId = 0;

        }

    };

    $scope.processPeriodFilter = function () {
        alert('period after change schedule is '+$scope.formFilter.periodId)
        $scope.filterObject.periodId = $scope.formFilter.periodId;
        $scope.formFilter.periodName = getSelectedItemName($scope.formFilter.periodId, $scope.periods);
        $scope.loadRnRStatus();
    };

    $scope.changeSchedule = function () {

        if (!isUndefined($scope.formFilter.scheduleId)) {
            $scope.filterObject.scheduleId = $scope.formFilter.scheduleId;
        }

        if (!isUndefined($scope.filterObject.scheduleId)) {
            if (!isUndefined($scope.filterObject.year)) {
                ReportPeriodsByScheduleAndYear.get({scheduleId: $scope.filterObject.scheduleId, year: $scope.filterObject.year}, function (data) {
                    $scope.periods = data.periods;
                    $scope.periods.unshift({'name': formInputValue.periodOptionSelect});
                });
            } else {
                ReportPeriods.get({ scheduleId: $scope.filterObject.scheduleId }, function (data) {
                    $scope.periods = data.periods;
                    $scope.periods.unshift({'name': formInputValue.periodOptionSelect});

                });
            }
        }

        $scope.processPeriodFilter();
    };

    $scope.changeScheduleByYear = function () {

        if (!isUndefined($scope.formFilter.year)) {
            $scope.filterObject.year = $scope.formFilter.year;

        }
        $scope.changeSchedule();

    };

    $scope.$on('$routeChangeStart', function () {
        var data = {};
        $scope.filterObject = $scope.formFilter;
        angular.extend(data,$scope.filterObject);
        dashboardFiltersHistoryService.add($scope.$parent.currentTab, data);
    });

    $scope.$on('$viewContentLoaded', function () {

        var filterHistory = dashboardFiltersHistoryService.get($scope.$parent.currentTab);

        if (isUndefined(filterHistory)) {
            if (!_.isEmpty(userPreferredFilterValues)) {
                var date = new Date();
                $scope.filterObject.programId = isItemWithIdExists(userPreferredFilterValues[localStorageKeys.PREFERENCE.DEFAULT_PROGRAM], $scope.programs) ?
                    userPreferredFilterValues[localStorageKeys.PREFERENCE.DEFAULT_PROGRAM] : $scope.filterObject.programId;

                $scope.filterObject.periodId = userPreferredFilterValues[localStorageKeys.PREFERENCE.DEFAULT_PERIOD];

                if (!isUndefined($scope.filterObject.periodId)) {

                    GetPeriod.get({id: $scope.filterObject.periodId}, function (period) {
                        if (!isUndefined(period.year)) {
                            $scope.filterObject.year = period.year;
                        } else {
                            $scope.filterObject.year = date.getFullYear() - 1;
                        }
                    });
                }
                $scope.filterObject.scheduleId = userPreferredFilterValues[localStorageKeys.PREFERENCE.DEFAULT_SCHEDULE];

                $scope.filterObject.zoneId = userPreferredFilterValues[localStorageKeys.PREFERENCE.DEFAULT_GEOGRAPHIC_ZONE];

                $scope.registerWatches();

                $scope.formFilter = $scope.filterObject;

            }

        } else {

            $scope.registerWatches();

            $scope.formFilter = $scope.filterObject = filterHistory;
        }

    });

    $scope.registerWatches = function () {

        $scope.$watch('formFilter.programId', function () {
            $scope.filterProductsByProgram();

        });
        $scope.$watch('formFilter.scheduleId', function () {
            $scope.changeSchedule();

        });
    };

    $scope.paramsChanged = function (params) {

        // slice array data on pages
        if ($scope.data === undefined) {
            $scope.datarows = [];
        } else {
            var data = $scope.data;
            var orderedData = params.filter ? $filter('filter')(data, params.filter) : data;
            orderedData = params.sorting ? $filter('orderBy')(orderedData, params.orderBy()) : data;

            params.total = orderedData.length;
            $scope.datarows = orderedData.slice((params.page - 1) * params.count, params.page * params.count);
            var i = 0;
            var baseIndex = params.count * (params.page - 1) + 1;
            while (i < $scope.datarows.length) {
                $scope.datarows[i].no = baseIndex + i;
                i++;
            }
        }
    };

    // watch for changes of parameters
    $scope.$watch('tableParams', $scope.paramsChanged, true);

}
<commit_msg>Improves RnR Status Summary dashboard page<commit_after>/*
 * This program was produced for the U.S. Agency for International Development. It was prepared by the USAID | DELIVER PROJECT, Task Order 4. It is part of a project which utilizes code originally licensed under the terms of the Mozilla Public License (MPL) v2 and therefore is licensed under MPL v2 or later.
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the Mozilla Public License as published by the Mozilla Foundation, either version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Mozilla Public License for more details.
 *
 * You should have received a copy of the Mozilla Public License along with this program. If not, see http://www.mozilla.org/MPL/
 */

function RequisitionStatusSummaryController($scope, $filter,RnRStatusSummary,programsList,FlatGeographicZoneList,UserGeographicZoneTree,dashboardMenuService,$location ,dashboardFiltersHistoryService, formInputValue, GetPeriod, userPreferredFilterValues, ReportSchedules, ReportPeriods, OperationYears, ReportPeriodsByScheduleAndYear) {

    $scope.filterObject = {};

    $scope.formFilter = {};

    $scope.formPanel = {openPanel: true};
    $scope.rnrStatus = {openPanel: true};

    initialize();

    function initialize() {
        $scope.showProductsFilter = false;
        $scope.$parent.currentTab = "RNR-STATUS-SUMMARY";

    }

    $scope.programs = programsList;
    $scope.programs.unshift({'name': formInputValue.programOptionSelect});

    $scope.loadGeoZones = function(){
        UserGeographicZoneTree.get({programId:$scope.formFilter.programId}, function(data){
            $scope.zones = data.zone;
        });
    };

    FlatGeographicZoneList.get(function (data) {
        $scope.geographicZones = data.zones;
    });

    OperationYears.get(function (data) {
        $scope.startYears = data.years;
        $scope.startYears.unshift(formInputValue.yearOptionAll);
    });

    ReportSchedules.get(function (data) {
        $scope.schedules = data.schedules;
        $scope.schedules.unshift({'name': formInputValue.scheduleOptionSelect});

    });

    $scope.filterProductsByProgram = function () {
        $scope.loadGeoZones();
        if (isUndefined($scope.formFilter.programId)) {

            return;
        }
        $scope.filterObject.programId = $scope.formFilter.programId;
        $scope.formFilter.programName = getSelectedItemName($scope.formFilter.programId, $scope.programs);

        //$scope.loadRnRStatus();

    };

    $scope.processZoneFilter = function(){
        $scope.filterObject.zoneId = $scope.formFilter.zoneId;
        $scope.formFilter.zoneName = getSelectedZoneName($scope.formFilter.zoneId, $scope.zones, $scope.geographicZones);

        $scope.loadRnRStatus();
    };

    $scope.loadRnRStatus= function(){
        if (isUndefined($scope.filterObject.periodId) || isUndefined($scope.filterObject.programId)) {
            $scope.resetRnRStatusData();
            return;
        }

        RnRStatusSummary.get({zoneId:$scope.filterObject.zoneId,
                periodId:$scope.filterObject.periodId,
                programId:$scope.filterObject.programId
            },
            function (data) {
                $scope.total = 0;
                $scope.RnRStatusPieChartData = [];
                $scope.dataRows = [];
                $scope.datarows = [];

                if (!isUndefined(data.rnrStatus)) {

                    $scope.dataRows = data.rnrStatus;
                    if(isUndefined($scope.dataRows)){
                        $scope.resetRnRStatusData();
                        return;
                    }
                    var statusData = _.pluck($scope.dataRows,'status');
                    var totalData = _.pluck($scope.dataRows,'totalStatus');

                    var color=["#F83103","#37AC02","#02A8FA","#FAA702"];
                    for (var i = 0; i < $scope.dataRows.length; i++) {
                        $scope.total += $scope.dataRows[i].totalStatus;
                        $scope.RnRStatusPieChartData[i] = {

                            label: statusData[i],
                            data: totalData[i],
                            color:color[i]

                        };

                    }
                    $scope.rnrStatusPieChartOptionFunction();
                    $scope.rnrStatusRenderedData = {
                        status : _.pairs(_.object(_.range(data.rnrStatus.length), _.pluck(data.rnrStatus,'status')))

                    };

                    bindChartEvent("#rnr-status-report","plotclick",rnrStatusChartClickHandler);
                    bindChartEvent("#rnr-status-report",flotChartHoverCursorHandler);

                } else {
                    $scope.resetRnRStatusReportData();
                }
                $scope.paramsChanged($scope.tableParams);
            });
       // }

    };

    $scope.resetRnRStatusData = function(){
        $scope.rnrStatusRenderedData = null;
        $scope.rnRStatusPieChartOption = null;
        $scope.total = 0;
        $scope.RnRStatusPieChartData = null;
        $scope.dataRows = null;
        $scope.datarows = null;
    };

    var getFilterValues = function(){

        $scope.formFilter.periodName = getSelectedItemName($scope.formFilter.periodId,$scope.periods);
        $scope.formFilter.programName = getSelectedItemName($scope.formFilter.programId,$scope.programs);

        $scope.formFilter.zoneName = getSelectedZoneName($scope.formFilter.zoneId, $scope.zones, $scope.geographicZones);
        $scope.filterObject = $scope.formFilter;

    };

    $scope.rnrStatusPieChartOptionFunction =function(){

        $scope.rnRStatusPieChartOption = {
            series: {
                pie: {
                    show: true,
                    radius: 1,
                    label: {
                        show: true,
                        radius: 3 / 4,
                        formatter: function (label, series) {
                            return '
' + Math.round(series.percent) + '%
';
                        },
                        threshold: 0.1
                    }

                }
            },
            legend: {
                show: true,
                container: $("#rnrStatusReportLegend"),
                noColumns: 0,
                labelBoxBorderColor: "none",
                width:20

            },
            grid: {
                hoverable: true,
                clickable: true,
                borderWidth: 1,
                borderColor: "#d6d6d6",
                backgroundColor: {
                    colors: ["#FFF", "#CCC","#FFF","#CCC"]
                }
            },
            tooltip: true,
            tooltipOpts: {
                content: "%p.0%, %s",
                shifts: {
                    x: 20,
                    y: 0
                },
                defaultTheme: false
            }
        };

    };

    function flotChartHoverCursorHandler(event,pos,item){

        if (item && !isUndefined(item.dataIndex)) {
           $(event.target).css('cursor','pointer');
        } else {
            $(event.target).css('cursor','auto');
        }
    }

    function bindChartEvent(elementSelector, eventType, callback){
        $(elementSelector).bind(eventType, callback);
    }

    function rnrStatusChartClickHandler(event, pos, item){
        if(item){
            var status;
            if(!isUndefined($scope.rnrStatusRenderedData.status)){
                status = $scope.rnrStatusRenderedData.status[item.seriesIndex][1];
            }
            var rnrDetailPath = '/rnr-status-report/program/'+$scope.filterObject.programId+'/period/'+$scope.filterObject.periodId;
            dashboardMenuService.addTab('menu.header.dashboard.rnr.status.detail','/public/pages/dashboard/index.html#'+rnrDetailPath,'RNR-STATUS-DETAIL',true, 8);
            $location.path(rnrDetailPath).search("status="+status+"&zoneId="+$scope.filterObject.zoneId);

            $scope.$apply();
        }

    }

    $scope.resetRnRStatusReportData = function () {
        $scope.RnRStatusPieChartData = null;
        $scope.rnRStatusPieChartOption =null;
        $scope.dataRows = null;
    };

    $scope.loadFacilitiesByRequisition = function () {
        if ($scope.formFilter.rgroupId == "All") {
            $scope.filterObject.rgroupId = -1;
        } else if ($scope.formFilter.rgroupId !== undefined || $scope.formFilter.rgroupId === "") {
            $scope.filterObject.rgroupId = $scope.formFilter.rgroupId;
            $.each($scope.requisitionGroups, function (item, idx) {
                if (idx.id == $scope.formFilter.rgroupId) {
                    $scope.filterObject.rgroup = idx.name;
                }
            });
        } else {
            $scope.filterObject.rgroupId = 0;

        }

    };

    $scope.processPeriodFilter = function () {
        $scope.filterObject.periodId = $scope.formFilter.periodId;
        $scope.formFilter.periodName = getSelectedItemName($scope.formFilter.periodId, $scope.periods);
        $scope.loadRnRStatus();
    };

    $scope.changeSchedule = function () {

        if (!isUndefined($scope.formFilter.scheduleId)) {
            $scope.filterObject.scheduleId = $scope.formFilter.scheduleId;
        }

        if (!isUndefined($scope.filterObject.scheduleId)) {
            if (!isUndefined($scope.filterObject.year)) {
                ReportPeriodsByScheduleAndYear.get({scheduleId: $scope.filterObject.scheduleId, year: $scope.filterObject.year}, function (data) {
                    $scope.periods = data.periods;
                    $scope.periods.unshift({'name': formInputValue.periodOptionSelect});
                });
            } else {
                ReportPeriods.get({ scheduleId: $scope.filterObject.scheduleId }, function (data) {
                    $scope.periods = data.periods;
                    $scope.periods.unshift({'name': formInputValue.periodOptionSelect});

                });
            }
        }

        $scope.processPeriodFilter();
    };

    $scope.changeScheduleByYear = function () {

        if (!isUndefined($scope.formFilter.year)) {
            $scope.filterObject.year = $scope.formFilter.year;

        }
        $scope.changeSchedule();

    };

    $scope.$on('$routeChangeStart', function () {
        var data = {};
        $scope.filterObject = $scope.formFilter;
        angular.extend(data,$scope.filterObject);
        dashboardFiltersHistoryService.add($scope.$parent.currentTab, data);
    });

    $scope.$on('$viewContentLoaded', function () {

        var filterHistory = dashboardFiltersHistoryService.get($scope.$parent.currentTab);

        if (isUndefined(filterHistory)) {
            if (!_.isEmpty(userPreferredFilterValues)) {
                var date = new Date();
                $scope.filterObject.programId = isItemWithIdExists(userPreferredFilterValues[localStorageKeys.PREFERENCE.DEFAULT_PROGRAM], $scope.programs) ?
                    userPreferredFilterValues[localStorageKeys.PREFERENCE.DEFAULT_PROGRAM] : $scope.filterObject.programId;

                $scope.filterObject.periodId = userPreferredFilterValues[localStorageKeys.PREFERENCE.DEFAULT_PERIOD];

                if (!isUndefined($scope.filterObject.periodId)) {

                    GetPeriod.get({id: $scope.filterObject.periodId}, function (period) {
                        if (!isUndefined(period.year)) {
                            $scope.filterObject.year = period.year;
                        } else {
                            $scope.filterObject.year = date.getFullYear() - 1;
                        }
                    });
                }
                $scope.filterObject.scheduleId = userPreferredFilterValues[localStorageKeys.PREFERENCE.DEFAULT_SCHEDULE];

                $scope.filterObject.zoneId = userPreferredFilterValues[localStorageKeys.PREFERENCE.DEFAULT_GEOGRAPHIC_ZONE];

                $scope.registerWatches();

                $scope.formFilter = $scope.filterObject;

            }

        } else {

            $scope.registerWatches();

            $scope.formFilter = $scope.filterObject = filterHistory;
        }

    });

    $scope.registerWatches = function () {

        $scope.$watch('formFilter.programId', function () {
            $scope.filterProductsByProgram();

        });
        $scope.$watch('formFilter.scheduleId', function () {
            $scope.changeSchedule();

        });
    };

    $scope.paramsChanged = function (params) {

        // slice array data on pages
        if ($scope.data === undefined) {
            $scope.datarows = [];
        } else {
            var data = $scope.data;
            var orderedData = params.filter ? $filter('filter')(data, params.filter) : data;
            orderedData = params.sorting ? $filter('orderBy')(orderedData, params.orderBy()) : data;

            params.total = orderedData.length;
            $scope.datarows = orderedData.slice((params.page - 1) * params.count, params.page * params.count);
            var i = 0;
            var baseIndex = params.count * (params.page - 1) + 1;
            while (i < $scope.datarows.length) {
                $scope.datarows[i].no = baseIndex + i;
                i++;
            }
        }
    };

    // watch for changes of parameters
    $scope.$watch('tableParams', $scope.paramsChanged, true);

}
<|endoftext|>


<commit_before>const fs = require('fs');
const os = require('os');
const _ = require('lodash');
const Promise = require('bluebird');
const requestPromise = require('request-promise');
const request = require('request');

const localUtils = require('./utils');

function getFinalChangelog(options) {
    let filterEmojiCommits = true;
    let changelog = fs.readFileSync(options.changelogPath).toString('utf8').split(os.EOL);
    let finalChangelog = [];

    if (Object.prototype.hasOwnProperty.call(options, 'filterEmojiCommits')) {
        filterEmojiCommits = options.filterEmojiCommits;
    }
    // @NOTE: optional array of string lines, which we pre-pend
    if (Object.prototype.hasOwnProperty.call(options, 'content') && _.isArray(options.content)) {
        finalChangelog = finalChangelog.concat(options.content);
    }

    if (filterEmojiCommits) {
        changelog = localUtils.filterEmojiCommits(changelog);
        localUtils.sortByEmoji(changelog);
    }

    if (_.isEmpty(changelog)) {
        changelog = ['No user-visible changes in this release.'];
    }

    finalChangelog = finalChangelog.concat(changelog);
    return finalChangelog;
}

module.exports.create = (options = {}) => {
    let draft = true;
    let prerelease = false;

    localUtils.checkMissingOptions(options,
        'changelogPath',
        'github',
        'github.token',
        'userAgent',
        'uri',
        'tagName',
        'releaseName'
    );

    if (Object.prototype.hasOwnProperty.call(options, 'draft')) {
        draft = options.draft;
    }

    if (Object.prototype.hasOwnProperty.call(options, 'prerelease')) {
        prerelease = options.prerelease;
    }

    let body = [];
    // CASE: changelogPath can be array of paths with content
    if (_.isArray(options.changelogPath)) {
        options.changelogPath.forEach((opts) => {
            body = body.concat(getFinalChangelog(opts));
        });
    } else {
        // CASE: changelogPath can be a single path(For backward compatibility)
        body = body.concat(getFinalChangelog(options));
    }

    // CASE: clean before upload
    body = body.filter((item) => {
        return item !== undefined;
    });

    if (options.gistUrl) {
        body.push('');
        body.push('You can see the [full change log](' + options.gistUrl + ') for the details of every change included in this release.');
    }

    const auth = 'token ' + options.github.token;

    const reqOptions = {
        uri: options.uri,
        headers: {
            'User-Agent': options.userAgent,
            Authorization: auth
        },
        method: 'POST',
        body: {
            tag_name: options.tagName,
            target_commitish: 'master',
            name: options.releaseName,
            body: body.join(os.EOL),
            draft: draft,
            prerelease: prerelease
        },
        json: true,
        resolveWithFullResponse: true
    };

    return requestPromise(reqOptions)
        .then((response) => {
            return {
                id: response.body.id,
                releaseUrl: response.body.html_url,
                uploadUrl: response.body.upload_url
            };
        });
};

module.exports.uploadZip = (options = {}) => {
    localUtils.checkMissingOptions(options,
        'zipPath',
        'github',
        'github.token',
        'userAgent',
        'uri'
    );

    const auth = 'token ' + options.github.token;
    const stats = fs.statSync(options.zipPath);

    const reqOptions = {
        uri: options.uri,
        headers: {
            'User-Agent': options.userAgent,
            Authorization: auth,
            'Content-Type': 'application/zip',
            'Content-Length': stats.size
        },
        method: 'POST',
        json: true,
        resolveWithFullResponse: true
    };

    return new Promise((resolve, reject) => {
        fs.createReadStream(options.zipPath)
            .on('error', reject)
            .pipe(request.post(reqOptions, (err, res) => {
                if (err) {
                    return reject(err);
                }

                resolve({
                    downloadUrl: res.body.browser_download_url
                });
            }));
    });
};

module.exports.get = (options = {}) => {
    localUtils.checkMissingOptions(options,
        'userAgent',
        'uri'
    );

    const reqOptions = {
        uri: options.uri,
        headers: {
            'User-Agent': options.userAgent
        },
        method: 'GET',
        json: true
    };

    return requestPromise(reqOptions)
        .then((response) => {
            return response;
        });
};
<commit_msg>Added extraText to release<commit_after>const fs = require('fs');
const os = require('os');
const _ = require('lodash');
const Promise = require('bluebird');
const requestPromise = require('request-promise');
const request = require('request');

const localUtils = require('./utils');

function getFinalChangelog(options) {
    let filterEmojiCommits = true;
    let changelog = fs.readFileSync(options.changelogPath).toString('utf8').split(os.EOL);
    let finalChangelog = [];

    if (Object.prototype.hasOwnProperty.call(options, 'filterEmojiCommits')) {
        filterEmojiCommits = options.filterEmojiCommits;
    }
    // @NOTE: optional array of string lines, which we pre-pend
    if (Object.prototype.hasOwnProperty.call(options, 'content') && _.isArray(options.content)) {
        finalChangelog = finalChangelog.concat(options.content);
    }

    if (filterEmojiCommits) {
        changelog = localUtils.filterEmojiCommits(changelog);
        localUtils.sortByEmoji(changelog);
    }

    if (_.isEmpty(changelog)) {
        changelog = ['No user-visible changes in this release.'];
    }

    finalChangelog = finalChangelog.concat(changelog);
    return finalChangelog;
}

module.exports.create = (options = {}) => {
    let draft = true;
    let prerelease = false;

    localUtils.checkMissingOptions(options,
        'changelogPath',
        'github',
        'github.token',
        'userAgent',
        'uri',
        'tagName',
        'releaseName'
    );

    if (Object.prototype.hasOwnProperty.call(options, 'draft')) {
        draft = options.draft;
    }

    if (Object.prototype.hasOwnProperty.call(options, 'prerelease')) {
        prerelease = options.prerelease;
    }

    let body = [];
    // CASE: changelogPath can be array of paths with content
    if (_.isArray(options.changelogPath)) {
        options.changelogPath.forEach((opts) => {
            body = body.concat(getFinalChangelog(opts));
        });
    } else {
        // CASE: changelogPath can be a single path(For backward compatibility)
        body = body.concat(getFinalChangelog(options));
    }

    // CASE: clean before upload
    body = body.filter((item) => {
        return item !== undefined;
    });

    if (options.gistUrl) {
        body.push('');
        body.push('You can see the [full change log](' + options.gistUrl + ') for the details of every change included in this release.');
    }

    if (options.extraText) {
        body.push('');
        body.push(options.extraText);
    }

    const auth = 'token ' + options.github.token;

    const reqOptions = {
        uri: options.uri,
        headers: {
            'User-Agent': options.userAgent,
            Authorization: auth
        },
        method: 'POST',
        body: {
            tag_name: options.tagName,
            target_commitish: 'master',
            name: options.releaseName,
            body: body.join(os.EOL),
            draft: draft,
            prerelease: prerelease
        },
        json: true,
        resolveWithFullResponse: true
    };

    return requestPromise(reqOptions)
        .then((response) => {
            return {
                id: response.body.id,
                releaseUrl: response.body.html_url,
                uploadUrl: response.body.upload_url
            };
        });
};

module.exports.uploadZip = (options = {}) => {
    localUtils.checkMissingOptions(options,
        'zipPath',
        'github',
        'github.token',
        'userAgent',
        'uri'
    );

    const auth = 'token ' + options.github.token;
    const stats = fs.statSync(options.zipPath);

    const reqOptions = {
        uri: options.uri,
        headers: {
            'User-Agent': options.userAgent,
            Authorization: auth,
            'Content-Type': 'application/zip',
            'Content-Length': stats.size
        },
        method: 'POST',
        json: true,
        resolveWithFullResponse: true
    };

    return new Promise((resolve, reject) => {
        fs.createReadStream(options.zipPath)
            .on('error', reject)
            .pipe(request.post(reqOptions, (err, res) => {
                if (err) {
                    return reject(err);
                }

                resolve({
                    downloadUrl: res.body.browser_download_url
                });
            }));
    });
};

module.exports.get = (options = {}) => {
    localUtils.checkMissingOptions(options,
        'userAgent',
        'uri'
    );

    const reqOptions = {
        uri: options.uri,
        headers: {
            'User-Agent': options.userAgent
        },
        method: 'GET',
        json: true
    };

    return requestPromise(reqOptions)
        .then((response) => {
            return response;
        });
};
<|endoftext|>