<commit_before>/*

sample.js - a few sample parsers

The MIT License (MIT)

Copyright (c) 2015 Dale Schumacher

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

*/
"use strict";

var tart = require('tart-tracing');
var tracing = tart.tracing();
var sponsor = tracing.sponsor;

var ok = sponsor(function(m) {
    console.log('ok:', m);
});
var fail = sponsor(function(m) {
    console.log('FAIL!', m);
});

var PEG = require('../index.js');

var grammar = {};
var nameRule = function nameRule(name, pattern) {
    var rule = sponsor(function ruleBeh(m) {
        console.log('rule:', name, m);
        pattern({
            in: m.in,
            ok: this.sponsor(function okBeh(r) {
                m.ok({
                    in: r.in,
                    value: [name, r.value]
                });
            }),
            fail: m.fail
        });
    });
    grammar[name] = sponsor(
        PEG.packratPtrn(rule, name)
    );
};
var callRule = function callRule(name) {
    // delay name lookup until rule is invoked
    return function callBeh(m) {
        var rule = grammar[name];
        if (typeof rule !== 'function') {
            throw Error('Unknown grammar rule: ' + name);
        }
        rule(m);
    };
};

nameRule('Grammar',
    sponsor(PEG.sequencePtrn([
        callRule('_'),
        sponsor(PEG.oneOrMorePtrn(
            callRule('Rule')
        )),
        callRule('EOF')
    ]))
);
nameRule('Rule',
    sponsor(PEG.sequencePtrn([
        callRule('Name'),
        callRule('LEFTARROW'),
        callRule('Expression')
    ]))
);
nameRule('Expression',
    sponsor(PEG.sequencePtrn([
        callRule('Sequence'),
        sponsor(PEG.zeroOrMorePtrn(
            sponsor(PEG.sequencePtrn([
                callRule('SLASH'),
                callRule('Sequence')
            ]))
        ))
    ]))
);
nameRule('Sequence',
    sponsor(PEG.zeroOrMorePtrn(
        callRule('Prefix')
    ))
);
nameRule('Prefix',
    sponsor(PEG.sequencePtrn([
        sponsor(PEG.zeroOrOnePtrn(
            sponsor(PEG.choicePtrn([
                callRule('AND'),
                callRule('NOT')
            ]))
        )),
        callRule('Suffix')
    ]))
);
nameRule('Suffix',
    sponsor(PEG.sequencePtrn([
        callRule('Primary'),
        sponsor(PEG.zeroOrOnePtrn(
            sponsor(PEG.choicePtrn([
                callRule('QUESTION'),
                callRule('STAR'),
                callRule('PLUS')
            ]))
        ))
    ]))
);
nameRule('Primary',
    sponsor(PEG.choicePtrn([
        sponsor(PEG.sequencePtrn([
            callRule('Name'),
            sponsor(PEG.notPtrn(
                callRule('LEFTARROW')
            ))
        ])),
        callRule('Literal'),
        callRule('DOT')
    ]))
);
nameRule('Literal',
    sponsor(PEG.sequencePtrn([
        sponsor(PEG.terminalPtrn('"')),
        sponsor(PEG.oneOrMorePtrn(
            sponsor(PEG.sequencePtrn([
                sponsor(PEG.notPtrn(
                    sponsor(PEG.terminalPtrn('"'))
                )),
                callRule('Character')
            ]))
        )),
        sponsor(PEG.terminalPtrn('"')),
        callRule('_')
    ]))
);

nameRule('Name',
    sponsor(PEG.sequencePtrn([
        sponsor(PEG.predicatePtrn(function(token) {
            return /[a-zA-Z_]/.test(token);
        })),
        sponsor(PEG.zeroOrMorePtrn(
            sponsor(PEG.predicatePtrn(function(token) {
                return /[a-zA-Z_0-9]/.test(token);
            }))
        )),
        callRule('_')
    ]))
);
nameRule('Character',
    sponsor(PEG.sequencePtrn([
/*
        sponsor(PEG.notPtrn(
            sponsor(PEG.terminalPtrn('\\'))
        )),
*/
        sponsor(PEG.anythingBeh)
    ]))
);

nameRule('LEFTARROW',
    sponsor(PEG.sequencePtrn([
        sponsor(PEG.terminalPtrn('<')),
        sponsor(PEG.terminalPtrn('-')),
        callRule('_')
    ]))
);
nameRule('SLASH',
    sponsor(PEG.sequencePtrn([
        sponsor(PEG.terminalPtrn('/')),
        callRule('_')
    ]))
);
nameRule('AND',
    sponsor(PEG.sequencePtrn([
        sponsor(PEG.terminalPtrn('&')),
        callRule('_')
    ]))
);
nameRule('NOT',
    sponsor(PEG.sequencePtrn([
        sponsor(PEG.terminalPtrn('!')),
        callRule('_')
    ]))
);
nameRule('QUESTION',
    sponsor(PEG.sequencePtrn([
        sponsor(PEG.terminalPtrn('?')),
        callRule('_')
    ]))
);
nameRule('STAR',
    sponsor(PEG.sequencePtrn([
        sponsor(PEG.terminalPtrn('*')),
        callRule('_')
    ]))
);
nameRule('PLUS',
    sponsor(PEG.sequencePtrn([
        sponsor(PEG.terminalPtrn('+')),
        callRule('_')
    ]))
);
nameRule('OPEN',
    sponsor(PEG.sequencePtrn([
        sponsor(PEG.terminalPtrn('(')),
        callRule('_')
    ]))
);
nameRule('CLOSE',
    sponsor(PEG.sequencePtrn([
        sponsor(PEG.terminalPtrn(')')),
        callRule('_')
    ]))
);
nameRule('DOT',
    sponsor(PEG.sequencePtrn([
        sponsor(PEG.terminalPtrn('.')),
        callRule('_')
    ]))
);

nameRule('_',  // optional whitespace
    sponsor(PEG.zeroOrMorePtrn(
        sponsor(PEG.choicePtrn([
            callRule('Space'),
            callRule('Comment')
        ]))
    ))
);
nameRule('Comment',
    sponsor(PEG.sequencePtrn([
        sponsor(PEG.terminalPtrn('#')),
        sponsor(PEG.zeroOrMorePtrn(
            sponsor(PEG.sequencePtrn([
                sponsor(PEG.notPtrn(
                    callRule('EOL')
                )),
                sponsor(PEG.anythingBeh)
            ]))
        ))
    ]))
);
nameRule('Space',
    sponsor(PEG.predicatePtrn(function(token) {
        return /\s/.test(token);
    }))
);
nameRule('EOL',
    sponsor(PEG.choicePtrn([
        sponsor(PEG.terminalPtrn('\n')),
        sponsor(PEG.sequencePtrn([
            sponsor(PEG.terminalPtrn('\r')),
            sponsor(PEG.zeroOrOnePtrn(
                sponsor(PEG.terminalPtrn('\n'))
            ))
        ]))
    ]))
);
nameRule('EOF',
    sponsor(PEG.notPtrn(
        sponsor(PEG.anythingBeh)
    ))
);

var input = {
//    source: '\r\n# comment\n',
    source: 'EOL <- "\n" / "\r" "\n"?\r\n',
    offset: 0
};

//(callRule('_'))({
(callRule('Grammar'))({
    in: input,
    ok: ok,
    fail: fail
});

tracing.eventLoop({
/*
    log: function (effect) {
        console.log('DEBUG', effect);
    },
*/
    fail: function (exception) {
        console.log('FAIL!', exception);
    }
});
<commit_msg>Complete PEG grammar and more logging<commit_after>/*

sample.js - a few sample parsers

The MIT License (MIT)

Copyright (c) 2015 Dale Schumacher

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

*/
"use strict";

var tart = require('tart-tracing');
var tracing = tart.tracing();
var sponsor = tracing.sponsor;

var ok = sponsor(function(m) {
    console.log('ok:', JSON.stringify(m, null, '  '));
});
var fail = sponsor(function(m) {
    console.log('FAIL!', JSON.stringify(m, null, '  '));
});

var PEG = require('../index.js');

var grammar = {};
var nameRule = function nameRule(name, pattern) {
    var rule = sponsor(function ruleBeh(m) {
        console.log('rule:', name, m);
        pattern({
            in: m.in,
            ok: this.sponsor(function okBeh(r) {
                var match = {
                    in: r.in,
                    value: [name, r.value]
                };
                console.log('match:', match);
                m.ok(match);
            }),
            fail: m.fail
        });
    });
    grammar[name] = rule;
/*
    grammar[name] = sponsor(
        PEG.packratPtrn(rule, name)
    );
*/
};
var callRule = function callRule(name) {
    // delay name lookup until rule is invoked
    return function callBeh(m) {
        var rule = grammar[name];
        if (typeof rule !== 'function') {
            throw Error('Unknown grammar rule: ' + name);
        }
        rule(m);
    };
};

nameRule('Grammar',
    sponsor(PEG.sequencePtrn([
        callRule('_'),
        sponsor(PEG.oneOrMorePtrn(
            callRule('Rule')
        )),
        callRule('EOF')
    ]))
);
nameRule('Rule',
    sponsor(PEG.sequencePtrn([
        callRule('Name'),
        callRule('LEFTARROW'),
        callRule('Expression')
    ]))
);
nameRule('Expression',
    sponsor(PEG.sequencePtrn([
        callRule('Sequence'),
        sponsor(PEG.zeroOrMorePtrn(
            sponsor(PEG.sequencePtrn([
                callRule('SLASH'),
                callRule('Sequence')
            ]))
        ))
    ]))
);
nameRule('Sequence',
    sponsor(PEG.zeroOrMorePtrn(
        callRule('Prefix')
    ))
);
nameRule('Prefix',
    sponsor(PEG.sequencePtrn([
        sponsor(PEG.zeroOrOnePtrn(
            sponsor(PEG.choicePtrn([
                callRule('AND'),
                callRule('NOT')
            ]))
        )),
        callRule('Suffix')
    ]))
);
nameRule('Suffix',
    sponsor(PEG.sequencePtrn([
        callRule('Primary'),
        sponsor(PEG.zeroOrOnePtrn(
            sponsor(PEG.choicePtrn([
                callRule('QUESTION'),
                callRule('STAR'),
                callRule('PLUS')
            ]))
        ))
    ]))
);
nameRule('Primary',
    sponsor(PEG.choicePtrn([
        sponsor(PEG.sequencePtrn([
            callRule('Name'),
            sponsor(PEG.notPtrn(
                callRule('LEFTARROW')
            ))
        ])),
        sponsor(PEG.sequencePtrn([
            callRule('OPEN'),
            callRule('Expression'),
            callRule('CLOSE')
        ])),
        callRule('Literal'),
        callRule('Class'),
        callRule('DOT')
    ]))
);

nameRule('Name',
    sponsor(PEG.sequencePtrn([
        sponsor(PEG.predicatePtrn(function(token) {
            return /[a-zA-Z_]/.test(token);
        })),
        sponsor(PEG.zeroOrMorePtrn(
            sponsor(PEG.predicatePtrn(function(token) {
                return /[a-zA-Z_0-9]/.test(token);
            }))
        )),
        callRule('_')
    ]))
);
nameRule('Literal',
    sponsor(PEG.choicePtrn([
        sponsor(PEG.sequencePtrn([
            sponsor(PEG.terminalPtrn('"')),
            sponsor(PEG.oneOrMorePtrn(
                sponsor(PEG.sequencePtrn([
                    sponsor(PEG.notPtrn(
                        sponsor(PEG.terminalPtrn('"'))
                    )),
                    callRule('Character')
                ]))
            )),
            sponsor(PEG.terminalPtrn('"')),
            callRule('_')
        ])),
        sponsor(PEG.sequencePtrn([
            sponsor(PEG.terminalPtrn("'")),
            sponsor(PEG.oneOrMorePtrn(
                sponsor(PEG.sequencePtrn([
                    sponsor(PEG.notPtrn(
                        sponsor(PEG.terminalPtrn("'"))
                    )),
                    callRule('Character')
                ]))
            )),
            sponsor(PEG.terminalPtrn("'")),
            callRule('_')
        ]))
    ]))
);
nameRule('Class',
    sponsor(PEG.sequencePtrn([
        sponsor(PEG.terminalPtrn('[')),
        sponsor(PEG.oneOrMorePtrn(
            sponsor(PEG.sequencePtrn([
                sponsor(PEG.notPtrn(
                    sponsor(PEG.terminalPtrn(']'))
                )),
                callRule('Range')
            ]))
        )),
        sponsor(PEG.terminalPtrn(']')),
        callRule('_')
    ]))
);
nameRule('Range',
    sponsor(PEG.choicePtrn([
        sponsor(PEG.sequencePtrn([
            callRule('Character'),
            sponsor(PEG.terminalPtrn('-')),
            callRule('Character')
        ])),
        callRule('Character')
    ]))
);
nameRule('Character',
    sponsor(PEG.choicePtrn([
        sponsor(PEG.sequencePtrn([
            sponsor(PEG.terminalPtrn('\\')),
            sponsor(PEG.predicatePtrn(function(token) {
                return /[nrt'"[\]\\]/.test(token);
            }))
        ])),
        sponsor(PEG.sequencePtrn([
            sponsor(PEG.terminalPtrn('\\')),
            sponsor(PEG.terminalPtrn('u')),
            sponsor(PEG.predicatePtrn(function(token) {
                return /[0-9a-fA-F]/.test(token);
            })),
            sponsor(PEG.predicatePtrn(function(token) {
                return /[0-9a-fA-F]/.test(token);
            })),
            sponsor(PEG.predicatePtrn(function(token) {
                return /[0-9a-fA-F]/.test(token);
            })),
            sponsor(PEG.predicatePtrn(function(token) {
                return /[0-9a-fA-F]/.test(token);
            }))
        ])),
        sponsor(PEG.sequencePtrn([
            sponsor(PEG.notPtrn(
                sponsor(PEG.terminalPtrn('\\'))
            )),
            sponsor(PEG.anythingBeh)
        ]))
    ]))
);

nameRule('LEFTARROW',
    sponsor(PEG.sequencePtrn([
        sponsor(PEG.terminalPtrn('<')),
        sponsor(PEG.terminalPtrn('-')),
        callRule('_')
    ]))
);
nameRule('SLASH',
    sponsor(PEG.sequencePtrn([
        sponsor(PEG.terminalPtrn('/')),
        callRule('_')
    ]))
);
nameRule('AND',
    sponsor(PEG.sequencePtrn([
        sponsor(PEG.terminalPtrn('&')),
        callRule('_')
    ]))
);
nameRule('NOT',
    sponsor(PEG.sequencePtrn([
        sponsor(PEG.terminalPtrn('!')),
        callRule('_')
    ]))
);
nameRule('QUESTION',
    sponsor(PEG.sequencePtrn([
        sponsor(PEG.terminalPtrn('?')),
        callRule('_')
    ]))
);
nameRule('STAR',
    sponsor(PEG.sequencePtrn([
        sponsor(PEG.terminalPtrn('*')),
        callRule('_')
    ]))
);
nameRule('PLUS',
    sponsor(PEG.sequencePtrn([
        sponsor(PEG.terminalPtrn('+')),
        callRule('_')
    ]))
);
nameRule('OPEN',
    sponsor(PEG.sequencePtrn([
        sponsor(PEG.terminalPtrn('(')),
        callRule('_')
    ]))
);
nameRule('CLOSE',
    sponsor(PEG.sequencePtrn([
        sponsor(PEG.terminalPtrn(')')),
        callRule('_')
    ]))
);
nameRule('DOT',
    sponsor(PEG.sequencePtrn([
        sponsor(PEG.terminalPtrn('.')),
        callRule('_')
    ]))
);

nameRule('_',  // optional whitespace
    sponsor(PEG.zeroOrMorePtrn(
        sponsor(PEG.choicePtrn([
            callRule('Space'),
            callRule('Comment')
        ]))
    ))
);
nameRule('Comment',
    sponsor(PEG.sequencePtrn([
        sponsor(PEG.terminalPtrn('#')),
        sponsor(PEG.zeroOrMorePtrn(
            sponsor(PEG.sequencePtrn([
                sponsor(PEG.notPtrn(
                    callRule('EOL')
                )),
                sponsor(PEG.anythingBeh)
            ]))
        ))
    ]))
);
nameRule('Space',
    sponsor(PEG.predicatePtrn(function(token) {
        return /\s/.test(token);
    }))
);
nameRule('EOL',
    sponsor(PEG.choicePtrn([
        sponsor(PEG.terminalPtrn('\n')),
        sponsor(PEG.sequencePtrn([
            sponsor(PEG.terminalPtrn('\r')),
            sponsor(PEG.zeroOrOnePtrn(
                sponsor(PEG.terminalPtrn('\n'))
            ))
        ]))
    ]))
);
nameRule('EOF',
    sponsor(PEG.notPtrn(
        sponsor(PEG.anythingBeh)
    ))
);

var input = {
//    source: '\r\n# comment\n',
    source: 'Comment <- [#] (!EOL .)* EOL\r'
          + "EOL <- '\n'\n"
          + '     / "\r" "\n"?\r\n',
    offset: 0
};

//(callRule('_'))({
(callRule('Grammar'))({
    in: input,
    ok: ok,
    fail: fail
});

tracing.eventLoop({
/*
    log: function (effect) {
        console.log('DEBUG', effect);
    },
*/
    fail: function (exception) {
        console.log('FAIL!', exception);
    }
});
<|endoftext|>


<commit_before>var res = [8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1, 0.5],
	start = new L.LatLng(57.704503026010514, 11.965263344824994),
	crs = L.CRS.proj4js('EPSG:2400'
						,'+lon_0=15.808277777799999 +lat_0=0.0 +k=1.0 '
						+ '+x_0=1500000.0 +y_0=0.0 +proj=tmerc +ellps=bessel '
						+ '+units=m '
						+ '+towgs84=414.1,41.3,603.1,-0.855,2.141,-7.023,0 +no_defs',
						new L.Transformation(1, 0, -1, 0));

crs.scale = function(zoom) {
    return 1 / res[zoom];
};

var	map = new L.Map('map', {
	crs: crs,
	continuousWorld: true,
	worldCopyJump: false
});
var mapUrl = 'http://api.geosition.com/tile/lmv/{z}/{x}/{y}.png',
	attrib = 'Map data © 2011 Lantmäteriet, Imagery © 2011 Kartena',
	tilelayer = new L.TileLayer(mapUrl, {
		tms: false,   // this is the default (xyz scheme). Change to true if using TMS scheme.
		,maxZoom: 14
		,minZoom: 0
		,continuousWorld: true
		,attribution: attrib
	});
var b = new Billing.Leaflet(map,
							"github-demo",
							"lmv",
							parseInt(Math.random() * 10000000),
							window.location.hostname,
							window.location.href);
map.addLayer(tilelayer);
map.setView(start, 13);
<commit_msg>Fixed extra comma in layer settings.<commit_after>var res = [8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1, 0.5],
	start = new L.LatLng(57.704503026010514, 11.965263344824994),
	crs = L.CRS.proj4js('EPSG:2400'
						,'+lon_0=15.808277777799999 +lat_0=0.0 +k=1.0 '
						+ '+x_0=1500000.0 +y_0=0.0 +proj=tmerc +ellps=bessel '
						+ '+units=m '
						+ '+towgs84=414.1,41.3,603.1,-0.855,2.141,-7.023,0 +no_defs',
						new L.Transformation(1, 0, -1, 0));

crs.scale = function(zoom) {
    return 1 / res[zoom];
};

var	map = new L.Map('map', {
	crs: crs,
	continuousWorld: true,
	worldCopyJump: false
});
var mapUrl = 'http://api.geosition.com/tile/lmv/{z}/{x}/{y}.png',
	attrib = 'Map data © 2011 Lantmäteriet, Imagery © 2011 Kartena',
	tilelayer = new L.TileLayer(mapUrl, {
		tms: false   // this is the default (xyz scheme). Change to true if using TMS scheme.
		,maxZoom: 14
		,minZoom: 0
		,continuousWorld: true
		,attribution: attrib
	});
var b = new Billing.Leaflet(map,
							"github-demo",
							"lmv",
							parseInt(Math.random() * 10000000),
							window.location.hostname,
							window.location.href);
map.addLayer(tilelayer);
map.setView(start, 13);
<|endoftext|>


<commit_before>import React from 'react'
import Modal from 'app/components/modal'

const Add = React.createClass({
  handleAdd(){
    const title=this.refs.title.value
    const description=this.refs.description.value
    this.props.onAdd(title, description)
  },
  render(){
    const props = this.props

    return (
      <Modal>

{i18n("Add Issue")}

              {i18n("Title")}
              <input type="text" ref="title" placeholder={i18n("Short issue description")}/>

              {i18n("Description")}
              <textarea ref="description" placeholder={i18n("Short issue description")}></textarea>

            <button className="ui button yellow" onClick={this.handleAdd}>
            {i18n("Add Issue")}
            </button>

      </Modal>
    )
  }
})

export default Add
<commit_msg>Added missing i18n dependency at issues add<commit_after>import React from 'react'
import Modal from 'app/components/modal'
import i18n from 'app/utils/i18n'

const Add = React.createClass({
  handleAdd(){
    const title=this.refs.title.value
    const description=this.refs.description.value
    this.props.onAdd(title, description)
  },
  render(){
    const props = this.props

    return (
      <Modal>

{i18n("Add Issue")}

              {i18n("Title")}
              <input type="text" ref="title" placeholder={i18n("Short issue description")}/>

              {i18n("Description")}
              <textarea ref="description" placeholder={i18n("Short issue description")}></textarea>

            <button className="ui button yellow" onClick={this.handleAdd}>
            {i18n("Add Issue")}
            </button>

      </Modal>
    )
  }
})

export default Add
<|endoftext|>


<commit_before>#!/usr/bin/env node

// Asserts that log replay will skip over the positions array.

require('./proof')(1, function (step, tmp, Strata, deepEqual, say, gather) {
    var fs = require('fs'), strata
    step(function () {
        strata = new Strata({ directory: tmp, leafSize: 3, branchSize: 3 })
        strata.create(step())
    }, function () {
        strata.mutator('a', step())
    }, function (cursor) {
        step(function () {
            cursor.insert('a', 'a', ~ cursor.index, step())
        }, function () {
            cursor.unlock()
        })
    }, function () {
        gather(step, strata)
    }, function (records) {
        deepEqual(records, [ 'a' ], 'written')
        strata.close(step())
    }, function () {
        strata = new Strata({ directory: tmp, leafSize: 3, branchSize: 3, replay: true })
        strata.open(step())
    }, function () {
        strata.iterator('a', step())
    }, function (cursor) {
        cursor.unlock()
    })
})
<commit_msg>Tidy `t/coverage/replay.t.js`.<commit_after>#!/usr/bin/env node

// Asserts that log replay will skip over the positions array.

require('./proof')(1, function (step, Strata, tmp, gather, deepEqual, say) {
    var strata
    step(function () {
        strata = new Strata({ directory: tmp, leafSize: 3, branchSize: 3 })
        strata.create(step())
    }, function () {
        strata.mutator('a', step())
    }, function (cursor) {
        step(function () {
            cursor.insert('a', 'a', ~ cursor.index, step())
        }, function () {
            cursor.unlock()
        })
    }, function () {
        gather(step, strata)
    }, function (records) {
        deepEqual(records, [ 'a' ], 'written')
        strata.close(step())
    }, function () {
        strata = new Strata({ directory: tmp, leafSize: 3, branchSize: 3, replay: true })
        strata.open(step())
    }, function () {
        strata.iterator('a', step())
    }, function (cursor) {
        cursor.unlock()
    })
})
<|endoftext|>


<commit_before>/*---------------------------------------------------------
 * OpenERP gantt_improvement
 *---------------------------------------------------------*/
openerp.gantt_improvement = function (instance) {
    var _t = instance.web._t,
        _lt = instance.web._lt,
        QWeb = instance.web.qweb,
        date_begin = null,
        date_end = null,
        day_today = 0,
        day_end = 0,
        day_offset = null,
        gantt_tasks = null,
        last_move_task = null,
        gantt_loaded = false,
        put_project_links = true,
        put_contraint_links = true;

    instance.web.views.add('gantt', 'instance.gantt_improvement.GanttView');
    instance.gantt_improvement.GanttView = instance.web_gantt.GanttView.extend({
        events: {
            'click .oe_gantt_buttons_days .previous_week': 'previous_week',
            'click .oe_gantt_buttons_days .previous_day': 'previous_day',
            'click .oe_gantt_buttons_days .today': 'today',
            'click .oe_gantt_buttons_days .next_day': 'next_day',
            'click .oe_gantt_buttons_days .next_week': 'next_week',
            'click .oe_gantt_buttons_days .go_date': 'go_date',
            'click .oe_gantt_buttons_days .gantt_improvement_input_date': 'go_date',
            'click .oe_gantt_button_create' : 'on_task_create',
        },

        init: function (parent) {

            var self = this;
            new instance.web.Model("res.users").query(["gantt_improvement_day_offset", "gantt_improvement_links_contraint", "gantt_improvement_links_projects"]).first().then(function (result) {
                day_offset = result.gantt_improvement_day_offset;
                put_contraint_links = result.gantt_improvement_links_contraint;
                put_project_links = result.gantt_improvement_links_projects;
            });

            this._super.apply(this, arguments);
            this.has_been_loaded = $.Deferred();
            this.chart_id = _.uniqueId();
            this.today();
        },
        load_gantt: function (fields_view_get, fields_get) {
            var self = this;
            this.fields_view = fields_view_get;
            this.$el.addClass(this.fields_view.arch.attrs['class']);

            return self.alive(new instance.web.Model(this.dataset.model)
            .call('fields_get')).then(function (fields) {
                self.fields = fields;
                self.has_been_loaded.resolve();
            });

        },
        on_data_loaded_2: function (tasks, group_bys) {
            var self = this;
            var model = new instance.web.Model(this.dataset.model).query().all().then(function (result) {
                self.on_data_loaded_3(result, group_bys);
            });
        },
        on_data_loaded_3: function (tasks, group_bys) {
            $(".oe_gantt").html("");
            var self = this;
            var projects = [];
            gantt_tasks = [];
            date_begin = null;
            date_end = null;
            day_today = 0;
            day_end = 0;

            for (var i in tasks) {
                if (tasks[i].date_end !== false && tasks[i].date_end !== undefined && tasks[i].date_start !== false && tasks[i].date_start !== undefined) {
                    gantt_tasks[tasks[i].id] = tasks[i];
                    var tasks_parent_id = i;
                    var tasks_parent_name = 'task'+i;

                    if (tasks[i][group_bys] !== undefined) {
                        tasks_parent_id = tasks[i][group_bys][0];
                        tasks_parent_name = tasks[i][group_bys][1];
                    }

                    if (projects[tasks_parent_id] === undefined) {
                        projects[tasks_parent_id] = [];
                        projects[tasks_parent_id].id = tasks_parent_id;
                        projects[tasks_parent_id].name = tasks_parent_name;
                        projects[tasks_parent_id].tasks = [];
                        projects[tasks_parent_id].date_start = tasks[i].date_start;
                        projects[tasks_parent_id].date_end = tasks[i].date_end;
                    }

                    projects[tasks_parent_id].tasks.push(tasks[i]);
                    if (projects[tasks_parent_id].date_start < tasks[i].date_start)
                        projects[tasks_parent_id].date_start = tasks[i].date_start;
                    if (projects[tasks_parent_id].date_end > tasks[i].date_end)
                        projects[tasks_parent_id].date_end = tasks[i].date_end;
                    if (date_end === null || date_end < tasks[i].date_end)
                         date_end = tasks[i].date_end;
                    if (date_begin === null || date_begin > tasks[i].date_start)
                        date_begin = tasks[i].date_start;
                }
            }
            date_begin = instance.web.auto_str_to_date(date_begin);
            date_end = instance.web.auto_str_to_date(date_end);
            day_end = Math.round((date_end - date_begin)/(1000*60*60*24));
            day_today = Math.round((new Date() - date_begin)/(1000*60*60*24));

            var data = [];
            var links = [];
            for (var y in projects) {
                var currentProjectTask = {};
                currentProjectTask.id = "proj"+projects[y].id;
                currentProjectTask.text = (projects[y].name);
                currentProjectTask.open = true;
                data.push(currentProjectTask);

                for (var x in projects[y].tasks) {
                    if (put_project_links === true) {
                        links.push({
                            'id': projects[y].tasks[x].id,
                            'source': ("proj"+projects[y].id),
                            'target': projects[y].tasks[x].id,
                            'type': 1,
                        });
                    }
                    if (put_contraint_links === true) {
                        if (projects[y].tasks[x].next_phase_ids !== undefined) {
                            if (projects[y].tasks[x].next_phase_ids[0] !== undefined) {
                                links.push({
                                    'id': projects[y].tasks[x].id+"next",
                                    'source': projects[y].tasks[x].id,
                                    'target': projects[y].tasks[x].next_phase_ids[0],
                                    'type': 0,
                                });
                            }
                        }
                    }

                    var currentTask = {};
                    currentTask.id = projects[y].tasks[x].id;
                    currentTask.text = (projects[y].tasks[x].name);
                    var d1 = instance.web.auto_str_to_date(projects[y].tasks[x].date_start);
                    var d2 = instance.web.auto_str_to_date(projects[y].tasks[x].date_end);
                    var utc1 = Date.UTC(d1.getFullYear(), d1.getMonth(), d1.getDate());
                    var utc2 = Date.UTC(d2.getFullYear(), d2.getMonth(), d2.getDate());
                    var duration = Math.floor((utc2 - utc1) / (1000 * 60 * 60 * 24));
                        duration += 1;
                    var start = d1.getDate()+'-'+(d1.getMonth() + 1)+"-"+d1.getFullYear();
                    currentTask.start_date = start;
                    currentTask.duration = duration;
                    currentTask.order = projects[y].tasks[x].sequence;
                    currentTask.parent = "proj"+projects[y].id;
                    if (projects[y].tasks[x].progress !== undefined)
                        currentTask.progress = projects[y].tasks[x].progress;
                    data.push(currentTask);
                }
            }
            var datas_tasks = {'data' : data, 'links' : links};

            if (gantt_loaded)
                gantt.clearAll();

            gantt.config.columns=[
                {name:"text", label:"Task name", tree:true, },
            ];
            gantt.config.details_on_dblclick = false;
            gantt.config.min_column_width = 28;
            gantt.config.grid_width = 200;
            gantt.config.row_height = 20;
            gantt.config.date_scale = "%d";
            gantt.config.scale_height = 20*3;
            gantt.config.drag_links = false;
            gantt.config.drag_progress = false;

            var weekScaleTemplate = function (date){
                var dateToStr = gantt.date.date_to_str("%d %M");
                var weekNum = gantt.date.date_to_str("(week %W)");
                var endDate = gantt.date.add(gantt.date.add(date, 1, "week"), -1, "day");
                return dateToStr(date) + " - " + dateToStr(endDate) + " " + weekNum(date);
            };
            gantt.config.subscales = [
                {unit:"month", step:1, date:"%F, %Y"},
                {unit:"week", step:1, template:weekScaleTemplate}
            ];
            if (gantt_loaded === false) {
                gantt.templates.scale_cell_class = function (date){
                    if(date.getDay() === 0||date.getDay() === 6){
                        return "weekend";
                    }
                };
                gantt.templates.task_cell_class = function (item,date){
                    if(date.getDay()===0||date.getDay()===6){
                        return "weekend";
                    }
                };
                gantt.templates.link_class = function (link){
                    switch (link.type){
                        case 0:
                            return "constraint";
                    }
                };
                gantt.attachEvent("onTaskClick", function (id, e) {
                    if (gantt_tasks[id] !== undefined)
                        self.on_task_display(gantt_tasks[id]);
                });
                gantt.attachEvent("onTaskDrag", function (id, mode, task, original){
                    last_move_task = task;
                });
                gantt.attachEvent("onAfterTaskDrag", function (id, mode, e){
                    self.on_task_changed();
                });
            }
            gantt_loaded = true;
            gantt.init(this.chart_id);
            gantt.parse(datas_tasks);
        },
        previous_week: function () {
            this.scroll_for(-7);
        },
        previous_day: function () {
            this.scroll_for(-1);
        },
        today: function () {
            if ($('.gantt_container').length !== 0 && day_offset !== null) {
                this.go_to_date(new Date());
            } else {
                var self = this;
                setTimeout(function (){self.today();}, 300);
            }

        },
        scroll_for: function (nb_day) {
            gantt.scrollTo(gantt.getScrollState().x + (nb_day * gantt.config.min_column_width));
        },
        go_to_date: function (date) {
            var date_offset = new Date();
            date_offset.setTime(date.getTime() - ((day_offset - 3) * 24 * 3600 * 1000));
            gantt.showDate(date_offset);
        },
        go_date: function () {
            var date_input = $("#gantt_improvement_input_date").val();
            if (date_input !== '') {
                var date = instance.web.auto_str_to_date(date_input);
                this.go_to_date(new Date(date));
            }
        },
        next_day: function () {
            this.scroll_for(1);
        },
        next_week: function () {
            this.scroll_for(7);
        },
        on_task_changed: function () {
            var self = this;
            var itask = gantt_tasks[last_move_task.id];
            var start = last_move_task.start_date;
            var duration = last_move_task.duration * 24;
            var end = start.clone().addMilliseconds(duration * 60 * 60 * 1000);
            var data = {};
            data[self.fields_view.arch.attrs.date_start] =
                instance.web.auto_date_to_str(start, self.fields[self.fields_view.arch.attrs.date_start].type);
            if (self.fields_view.arch.attrs.date_stop) {
                data[self.fields_view.arch.attrs.date_stop] =
                    instance.web.auto_date_to_str(end, self.fields[self.fields_view.arch.attrs.date_stop].type);
            } else { // we assume date_duration is defined
                data[self.fields_view.arch.attrs.date_delay] = duration;
            }
            this.dataset.write(itask.id, data);
        },
    });
};<commit_msg>FIX tasks with zero duration<commit_after>/*---------------------------------------------------------
 * OpenERP gantt_improvement
 *---------------------------------------------------------*/
openerp.gantt_improvement = function (instance) {
    var _t = instance.web._t,
        _lt = instance.web._lt,
        QWeb = instance.web.qweb,
        date_begin = null,
        date_end = null,
        day_today = 0,
        day_end = 0,
        day_offset = null,
        gantt_tasks = null,
        last_move_task = null,
        gantt_loaded = false,
        put_project_links = true,
        put_contraint_links = true;

    instance.web.views.add('gantt', 'instance.gantt_improvement.GanttView');
    instance.gantt_improvement.GanttView = instance.web_gantt.GanttView.extend({
        events: {
            'click .oe_gantt_buttons_days .previous_week': 'previous_week',
            'click .oe_gantt_buttons_days .previous_day': 'previous_day',
            'click .oe_gantt_buttons_days .today': 'today',
            'click .oe_gantt_buttons_days .next_day': 'next_day',
            'click .oe_gantt_buttons_days .next_week': 'next_week',
            'click .oe_gantt_buttons_days .go_date': 'go_date',
            'click .oe_gantt_buttons_days .gantt_improvement_input_date': 'go_date',
            'click .oe_gantt_button_create' : 'on_task_create',
        },

        init: function (parent) {

            var self = this;
            new instance.web.Model("res.users").query(["gantt_improvement_day_offset", "gantt_improvement_links_contraint", "gantt_improvement_links_projects"]).first().then(function (result) {
                day_offset = result.gantt_improvement_day_offset;
                put_contraint_links = result.gantt_improvement_links_contraint;
                put_project_links = result.gantt_improvement_links_projects;
            });

            this._super.apply(this, arguments);
            this.has_been_loaded = $.Deferred();
            this.chart_id = _.uniqueId();
            this.today();
        },
        load_gantt: function (fields_view_get, fields_get) {
            var self = this;
            this.fields_view = fields_view_get;
            this.$el.addClass(this.fields_view.arch.attrs['class']);

            return self.alive(new instance.web.Model(this.dataset.model)
            .call('fields_get')).then(function (fields) {
                self.fields = fields;
                self.has_been_loaded.resolve();
            });

        },
        on_data_loaded_2: function (tasks, group_bys) {
            var self = this;

            var model = new instance.web.Model(this.dataset.model).query().all().then(function (result) {
                self.on_data_loaded_3(result, group_bys);
            });
        },
        on_data_loaded_3: function (tasks, group_bys) {
            $(".oe_gantt").html("");
            var self = this;
            var projects = [];
            gantt_tasks = [];
            date_begin = null;
            date_end = null;
            day_today = 0;
            day_end = 0;

            for (var i in tasks) {
                if (tasks[i].date_start !== false && tasks[i].date_start !== undefined) {
                    if (tasks[i].date_end === false || tasks[i].date_end === undefined)
                        tasks[i].date_end = tasks[i].date_start;
                    gantt_tasks[tasks[i].id] = tasks[i];
                    var tasks_parent_id = i;
                    var tasks_parent_name = 'task'+i;

                    if (group_bys[0] === '' || group_bys[0] === undefined) {
                        tasks_parent_id = 0;
                        tasks_parent_name = 'Gantt View';
                    }
                    else if (tasks[i][group_bys[0]] !== undefined) {
                        tasks_parent_id = tasks[i][group_bys][0];
                        tasks_parent_name = tasks[i][group_bys][1];
                    }

                    if (projects[tasks_parent_id] === undefined) {
                        projects[tasks_parent_id] = [];
                        projects[tasks_parent_id].id = tasks_parent_id;
                        projects[tasks_parent_id].name = tasks_parent_name;
                        projects[tasks_parent_id].tasks = [];
                        projects[tasks_parent_id].date_start = tasks[i].date_start;
                        projects[tasks_parent_id].date_end = tasks[i].date_end;
                    }

                    projects[tasks_parent_id].tasks.push(tasks[i]);
                    if (projects[tasks_parent_id].date_start < tasks[i].date_start)
                        projects[tasks_parent_id].date_start = tasks[i].date_start;
                    if (projects[tasks_parent_id].date_end > tasks[i].date_end)
                        projects[tasks_parent_id].date_end = tasks[i].date_end;
                    if (date_end === null || date_end < tasks[i].date_end)
                         date_end = tasks[i].date_end;
                    if (date_begin === null || date_begin > tasks[i].date_start)
                        date_begin = tasks[i].date_start;
                }
            }
            date_begin = instance.web.auto_str_to_date(date_begin);
            date_end = instance.web.auto_str_to_date(date_end);
            day_end = Math.round((date_end - date_begin)/(1000*60*60*24));
            day_today = Math.round((new Date() - date_begin)/(1000*60*60*24));

            var data = [];
            var links = [];
            for (var y in projects) {
                var currentProjectTask = {};
                currentProjectTask.id = "proj"+projects[y].id;
                currentProjectTask.text = (projects[y].name);
                currentProjectTask.open = true;
                data.push(currentProjectTask);

                for (var x in projects[y].tasks) {
                    if (put_project_links === true) {
                        links.push({
                            'id': projects[y].tasks[x].id,
                            'source': ("proj"+projects[y].id),
                            'target': projects[y].tasks[x].id,
                            'type': 1,
                        });
                    }
                    if (put_contraint_links === true) {
                        if (projects[y].tasks[x].next_phase_ids !== undefined) {
                            if (projects[y].tasks[x].next_phase_ids[0] !== undefined) {
                                links.push({
                                    'id': projects[y].tasks[x].id+"next",
                                    'source': projects[y].tasks[x].id,
                                    'target': projects[y].tasks[x].next_phase_ids[0],
                                    'type': 0,
                                });
                            }
                        }
                    }

                    var currentTask = {};
                    currentTask.id = projects[y].tasks[x].id;
                    currentTask.text = (projects[y].tasks[x].name);
                    var d1 = instance.web.auto_str_to_date(projects[y].tasks[x].date_start);
                    var d2 = instance.web.auto_str_to_date(projects[y].tasks[x].date_end);
                    var utc1 = Date.UTC(d1.getFullYear(), d1.getMonth(), d1.getDate());
                    var utc2 = Date.UTC(d2.getFullYear(), d2.getMonth(), d2.getDate());
                    var duration = Math.floor((utc2 - utc1) / (1000 * 60 * 60 * 24));
                        duration += 1;
                    var start = d1.getDate()+'-'+(d1.getMonth() + 1)+"-"+d1.getFullYear();
                    currentTask.start_date = start;
                    currentTask.duration = duration;
                    currentTask.order = projects[y].tasks[x].sequence;
                    currentTask.parent = "proj"+projects[y].id;
                    if (projects[y].tasks[x].progress !== undefined)
                        currentTask.progress = projects[y].tasks[x].progress;
                    data.push(currentTask);
                }
            }
            var datas_tasks = {'data' : data, 'links' : links};

            if (gantt_loaded)
                gantt.clearAll();

            gantt.config.columns=[
                {name:"text", label:"Task name", tree:true, },
            ];
            gantt.config.details_on_dblclick = false;
            gantt.config.min_column_width = 28;
            gantt.config.grid_width = 200;
            gantt.config.row_height = 20;
            gantt.config.date_scale = "%d";
            gantt.config.scale_height = 20*3;
            gantt.config.drag_links = false;
            gantt.config.drag_progress = false;

            var weekScaleTemplate = function (date){
                var dateToStr = gantt.date.date_to_str("%d %M");
                var weekNum = gantt.date.date_to_str("(week %W)");
                var endDate = gantt.date.add(gantt.date.add(date, 1, "week"), -1, "day");
                return dateToStr(date) + " - " + dateToStr(endDate) + " " + weekNum(date);
            };
            gantt.config.subscales = [
                {unit:"month", step:1, date:"%F, %Y"},
                {unit:"week", step:1, template:weekScaleTemplate}
            ];
            if (gantt_loaded === false) {
                gantt.templates.scale_cell_class = function (date){
                    if(date.getDay() === 0||date.getDay() === 6){
                        return "weekend";
                    }
                };
                gantt.templates.task_cell_class = function (item,date){
                    if(date.getDay()===0||date.getDay()===6){
                        return "weekend";
                    }
                };
                gantt.templates.link_class = function (link){
                    switch (link.type){
                        case 0:
                            return "constraint";
                    }
                };
                gantt.attachEvent("onTaskClick", function (id, e) {
                    if (gantt_tasks[id] !== undefined)
                        self.on_task_display(gantt_tasks[id]);
                });
                gantt.attachEvent("onTaskDrag", function (id, mode, task, original){
                    last_move_task = task;
                });
                gantt.attachEvent("onAfterTaskDrag", function (id, mode, e){
                    self.on_task_changed();
                });
            }
            gantt_loaded = true;
            gantt.init(this.chart_id);
            gantt.parse(datas_tasks);
        },
        previous_week: function () {
            this.scroll_for(-7);
        },
        previous_day: function () {
            this.scroll_for(-1);
        },
        today: function () {
            if ($('.gantt_container').length !== 0 && day_offset !== null) {
                this.go_to_date(new Date());
            } else {
                var self = this;
                setTimeout(function (){self.today();}, 300);
            }

        },
        scroll_for: function (nb_day) {
            gantt.scrollTo(gantt.getScrollState().x + (nb_day * gantt.config.min_column_width));
        },
        go_to_date: function (date) {
            var date_offset = new Date();
            date_offset.setTime(date.getTime() - ((day_offset - 3) * 24 * 3600 * 1000));
            gantt.showDate(date_offset);
        },
        go_date: function () {
            var date_input = $("#gantt_improvement_input_date").val();
            if (date_input !== '') {
                var date = instance.web.auto_str_to_date(date_input);
                this.go_to_date(new Date(date));
            }
        },
        next_day: function () {
            this.scroll_for(1);
        },
        next_week: function () {
            this.scroll_for(7);
        },
        on_task_changed: function () {
            var self = this;
            var itask = gantt_tasks[last_move_task.id];
            var start = last_move_task.start_date;
            var duration = last_move_task.duration * 24;
            var end = start.clone().addMilliseconds(duration * 60 * 60 * 1000);
            var data = {};
            data[self.fields_view.arch.attrs.date_start] =
                instance.web.auto_date_to_str(start, self.fields[self.fields_view.arch.attrs.date_start].type);
            if (self.fields_view.arch.attrs.date_stop) {
                data[self.fields_view.arch.attrs.date_stop] =
                    instance.web.auto_date_to_str(end, self.fields[self.fields_view.arch.attrs.date_stop].type);
            } else { // we assume date_duration is defined
                data[self.fields_view.arch.attrs.date_delay] = duration;
            }
            this.dataset.write(itask.id, data);
        },
    });
};<|endoftext|>


<commit_before>require('budo')('src/index.js', {
    browserify: {
        debug: true,
    },

    dir: ['src/static', 'dist'],
    host: '0.0.0.0',
    live: true,
    open: true,
    portfind: true,
    pushstate: true,
    serve: 'assets/bundle.js',
    stream: process.stdout,

    watchGlob: [
        'src/**/*.{html,css,json}'
    ]
});
<commit_msg>Also watch dist/ for CSS changes<commit_after>require('budo')('src/index.js', {
    browserify: {
        debug: true,
    },

    dir: ['src/static', 'dist'],
    host: '0.0.0.0',
    live: true,
    open: true,
    portfind: true,
    pushstate: true,
    serve: 'assets/bundle.js',
    stream: process.stdout,

    watchGlob: [
        '{dist,src}/**/*.{html,css,json}'
    ]
});
<|endoftext|>


<commit_before>const loadGrunt = require('load-grunt-config');

module.exports = function loadGruntConfig(grunt) {
  loadGrunt(grunt);
};
<commit_msg>Delete the Gruntfile.js file from the generators/linter/templates/ folder<commit_after><|endoftext|>


<commit_before>import Controller from '@ember/controller';
import {getSymbol} from 'ghost-admin/utils/currency';
import {inject as service} from '@ember/service';
import {tracked} from '@glimmer/tracking';

export default class DashboardController extends Controller {
    @service feature;
    @service session;
    @service membersStats;
    @service store;

    @tracked
    events = {
        data: null,
        error: null,
        loading: false
    };
    @tracked
    mrrStats = {
        data: null,
        error: null,
        loading: false
    };
    @tracked
    memberCountStats = {
        data: null,
        error: null,
        loading: false
    };

    @tracked
    topMembers = {
        data: null,
        error: null,
        loading: false
    };

    get showTopMembers() {
        return this.feature.get('emailAnalytics') && this.settings.get('emailTrackOpens');
    }

    constructor(...args) {
        super(...args);
        this.loadEvents();
        this.loadTopMembers();
        this.loadCharts();
    }

    loadMRRStats() {
        this.membersStats.fetchMRR().then((stats) => {
            this.events.loading = false;

            let currencyStats = stats[0] || {
                data: [],
                currency: 'usd'
            };
            if (currencyStats) {
                currencyStats.data = this.membersStats.fillDates(currencyStats.data) || {};
                const dateValues = Object.values(currencyStats.data).map(val => val / 100);
                const currentMRR = dateValues.length ? dateValues[dateValues.length - 1] : 0;
                const rangeStartMRR = dateValues.length ? dateValues[0] : 0;
                const percentChange = rangeStartMRR !== 0 ? ((currentMRR - rangeStartMRR) / rangeStartMRR) * 100 : 0.0;
                this.mrrStats.data = {
                    current: `${getSymbol(currencyStats.currency)}${currentMRR}`,
                    percentChange,
                    options: {
                        rangeInDays: 30
                    },
                    data: {
                        label: 'MRR',
                        dateLabels: Object.keys(currencyStats.data),
                        dateValues
                    },
                    title: 'MRR',
                    stats: currencyStats
                };
            }
        }, (error) => {
            this.mrrStats.error = error;
            this.events.loading = false;
        });
    }

    loadMemberCountStats() {
        this.membersStats.fetchCounts().then((stats) => {
            this.events.loading = false;

            if (stats) {
                stats.data = this.membersStats.fillCountDates(stats.data) || {};
                const dateValues = Object.values(stats.data);

                this.memberCountStats.data = {
                    all: {
                        total: dateValues.length ? dateValues[dateValues.length - 1].total : 0,
                        options: {
                            rangeInDays: 30
                        },
                        data: {
                            label: 'Members',
                            dateLabels: Object.keys(stats.data),
                            dateValues: dateValues.map(d => d.total)
                        },
                        title: 'Total Members',
                        stats: stats
                    },
                    paid: {
                        total: dateValues.length ? dateValues[dateValues.length - 1].paid : 0,
                        options: {
                            rangeInDays: 30
                        },
                        data: {
                            label: 'Members',
                            dateLabels: Object.keys(stats.data),
                            dateValues: dateValues.map(d => d.paid)
                        },
                        title: 'Paid Members',
                        stats: stats
                    }
                };
            }
        }, (error) => {
            this.mrrStats.error = error;
            this.events.loading = false;
        });
    }

    loadCharts() {
        this.loadMRRStats();
        this.loadMemberCountStats();
    }

    loadEvents() {
        this.events.loading = true;
        this.membersStats.fetchTimeline().then(({events}) => {
            this.events.data = events;
            this.events.loading = false;
        }, (error) => {
            this.events.error = error;
            this.events.loading = false;
        });
    }

    loadTopMembers() {
        this.topMembers.loading = true;
        let query = {
            filter: 'email_open_rate:-null',
            order: 'email_open_rate desc',
            limit: 10
        };
        this.store.query('member', query).then((result) => {
            this.topMembers.data = result;
            this.topMembers.loading = false;
        }, (error) => {
            this.topMembers.error = error;
            this.topMembers.loading = false;
        });
    }
}
<commit_msg>Added missing setting service<commit_after>import Controller from '@ember/controller';
import {getSymbol} from 'ghost-admin/utils/currency';
import {inject as service} from '@ember/service';
import {tracked} from '@glimmer/tracking';

export default class DashboardController extends Controller {
    @service feature;
    @service session;
    @service membersStats;
    @service store;
    @service settings;

    @tracked
    events = {
        data: null,
        error: null,
        loading: false
    };
    @tracked
    mrrStats = {
        data: null,
        error: null,
        loading: false
    };
    @tracked
    memberCountStats = {
        data: null,
        error: null,
        loading: false
    };

    @tracked
    topMembers = {
        data: null,
        error: null,
        loading: false
    };

    get showTopMembers() {
        return this.feature.get('emailAnalytics') && this.settings.get('emailTrackOpens');
    }

    constructor(...args) {
        super(...args);
        this.loadEvents();
        this.loadTopMembers();
        this.loadCharts();
    }

    loadMRRStats() {
        this.membersStats.fetchMRR().then((stats) => {
            this.events.loading = false;

            let currencyStats = stats[0] || {
                data: [],
                currency: 'usd'
            };
            if (currencyStats) {
                currencyStats.data = this.membersStats.fillDates(currencyStats.data) || {};
                const dateValues = Object.values(currencyStats.data).map(val => val / 100);
                const currentMRR = dateValues.length ? dateValues[dateValues.length - 1] : 0;
                const rangeStartMRR = dateValues.length ? dateValues[0] : 0;
                const percentChange = rangeStartMRR !== 0 ? ((currentMRR - rangeStartMRR) / rangeStartMRR) * 100 : 0.0;
                this.mrrStats.data = {
                    current: `${getSymbol(currencyStats.currency)}${currentMRR}`,
                    percentChange,
                    options: {
                        rangeInDays: 30
                    },
                    data: {
                        label: 'MRR',
                        dateLabels: Object.keys(currencyStats.data),
                        dateValues
                    },
                    title: 'MRR',
                    stats: currencyStats
                };
            }
        }, (error) => {
            this.mrrStats.error = error;
            this.events.loading = false;
        });
    }

    loadMemberCountStats() {
        this.membersStats.fetchCounts().then((stats) => {
            this.events.loading = false;

            if (stats) {
                stats.data = this.membersStats.fillCountDates(stats.data) || {};
                const dateValues = Object.values(stats.data);

                this.memberCountStats.data = {
                    all: {
                        total: dateValues.length ? dateValues[dateValues.length - 1].total : 0,
                        options: {
                            rangeInDays: 30
                        },
                        data: {
                            label: 'Members',
                            dateLabels: Object.keys(stats.data),
                            dateValues: dateValues.map(d => d.total)
                        },
                        title: 'Total Members',
                        stats: stats
                    },
                    paid: {
                        total: dateValues.length ? dateValues[dateValues.length - 1].paid : 0,
                        options: {
                            rangeInDays: 30
                        },
                        data: {
                            label: 'Members',
                            dateLabels: Object.keys(stats.data),
                            dateValues: dateValues.map(d => d.paid)
                        },
                        title: 'Paid Members',
                        stats: stats
                    }
                };
            }
        }, (error) => {
            this.mrrStats.error = error;
            this.events.loading = false;
        });
    }

    loadCharts() {
        this.loadMRRStats();
        this.loadMemberCountStats();
    }

    loadEvents() {
        this.events.loading = true;
        this.membersStats.fetchTimeline().then(({events}) => {
            this.events.data = events;
            this.events.loading = false;
        }, (error) => {
            this.events.error = error;
            this.events.loading = false;
        });
    }

    loadTopMembers() {
        this.topMembers.loading = true;
        let query = {
            filter: 'email_open_rate:-null',
            order: 'email_open_rate desc',
            limit: 10
        };
        this.store.query('member', query).then((result) => {
            this.topMembers.data = result;
            this.topMembers.loading = false;
        }, (error) => {
            this.topMembers.error = error;
            this.topMembers.loading = false;
        });
    }
}
<|endoftext|>


<commit_before>import {
  YAHOO_SEARCH_EXISTING_USERS,
  YAHOO_SEARCH_NEW_USERS,
} from './experimentConstants'

const features = {
  'test-feature': {
    defaultValue: false,
    rules: [
      {
        condition: {
          isTabTeamMember: true,
          env: 'local',
        },
        force: true,
      },
    ],
  },
}

features[YAHOO_SEARCH_EXISTING_USERS] = {
  defaultValue: false,
  rules: [
    {
      condition: {
        isTabTeamMember: true,
        env: 'local',
      },
      force: true,
    },
  ],
}

features[YAHOO_SEARCH_NEW_USERS] = {
  defaultValue: 'Google',
  rules: [
    {
      condition: {
        isTabTeamMember: true,
        env: 'local',
      },
      force: 'SearchForACause',
    },
  ],
}

export default features
<commit_msg>Set up test experiment<commit_after>import {
  YAHOO_SEARCH_EXISTING_USERS,
  YAHOO_SEARCH_NEW_USERS,
} from './experimentConstants'

const features = {
  'money-raised-exclamation-point': {
    defaultValue: false,
    rules: [
      {
        variations: [false, true],
        coverage: 0.4,
        condition: {
          v4BetaEnabled: true,
        },
      },
    ],
  },
}

features[YAHOO_SEARCH_EXISTING_USERS] = {
  defaultValue: false,
  rules: [
    {
      condition: {
        isTabTeamMember: true,
        env: 'local',
      },
      force: true,
    },
  ],
}

features[YAHOO_SEARCH_NEW_USERS] = {
  defaultValue: 'Google',
  rules: [
    {
      condition: {
        isTabTeamMember: true,
        env: 'local',
      },
      force: 'SearchForACause',
    },
  ],
}

export default features
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
/**
 * @fileOverview
 * instance controls from native
 *
 * - init bundle
 *
 * corresponded with the API of instance manager (framework.js)
 */

import Vm from '../../vm/index'
import { removeWeexPrefix } from '../../util/index'
import {
  defineFn,
  bootstrap,
  register
} from '../bundle/index'
import { updateActions } from './misc'

/**
 * Init an app by run code witgh data
 * @param  {object} app
 * @param  {string} code
 * @param  {object} data
 */
export function init (app, code, data, services) {
  console.debug('[JS Framework] Intialize an instance with:\n', data)
  let result

  // prepare app env methods
  const bundleDefine = (...args) => defineFn(app, ...args)
  const bundleBootstrap = (name, config, _data) => {
    result = bootstrap(app, name, config, _data || data)
    updateActions(app)
    app.doc.listener.createFinish()
    console.debug(`[JS Framework] After intialized an instance(${app.id})`)
  }
  const bundleVm = Vm
  /* istanbul ignore next */
  const bundleRegister = (...args) => register(app, ...args)
  /* istanbul ignore next */
  const bundleRender = (name, _data) => {
    result = bootstrap(app, name, {}, _data)
  }
  /* istanbul ignore next */
  const bundleRequire = name => _data => {
    result = bootstrap(app, name, {}, _data)
  }
  const bundleDocument = app.doc
  /* istanbul ignore next */
  const bundleRequireModule = name => app.requireModule(removeWeexPrefix(name))

  const weexGlobalObject = {
    config: app.options,
    define: bundleDefine,
    bootstrap: bundleBootstrap,
    requireModule: bundleRequireModule,
    document: bundleDocument,
    Vm: bundleVm
  }

  Object.freeze(weexGlobalObject)

  // prepare code
  let functionBody
  /* istanbul ignore if */
  if (typeof code === 'function') {
    // `function () {...}` -> `{...}`
    // not very strict
    functionBody = code.toString().substr(12)
  }
  /* istanbul ignore next */
  else if (code) {
    functionBody = code.toString()
  }
  // wrap IFFE and use strict mode
  functionBody = `(function(global){\n\n"use strict";\n\n ${functionBody} \n\n})(Object.create(this))`

  // run code and get result
  const { WXEnvironment } = global
  const timerAPIs = {}

  /* istanbul ignore if */
  if (WXEnvironment && WXEnvironment.platform !== 'Web') {
    // timer APIs polyfill in native
    const timer = app.requireModule('timer')
    Object.assign(timerAPIs, {
      setTimeout: (...args) => {
        const handler = function () {
          args[0](...args.slice(2))
        }

        let timerId, callbackId

        if (global.setTimeoutWeex && (typeof global.setTimeoutWeex === 'function')) {
          callbackId = app.doc.taskCenter.normalize(handler)
          timerId = global.setTimeoutWeex(app.id, callbackId, args[1])
          return timerId
        }
        else {
          timer.setTimeout(handler, args[1])
          return app.doc.taskCenter.callbackManager.lastCallbackId.toString()
        }
      },
      setInterval: (...args) => {
        const handler = function () {
          args[0](...args.slice(2))
        }

        let timerId, callbackId

        if (global.setIntervalWeex && (typeof global.setIntervalWeex === 'function')) {
          callbackId = app.doc.taskCenter.normalize(handler)
          timerId = global.setIntervalWeex(app.id, callbackId, args[1])
          return timerId
        }
        else {
          timer.setInterval(handler, args[1])
          return app.doc.taskCenter.callbackManager.lastCallbackId.toString()
        }
      },
      clearTimeout: (n) => {
        if (global.clearTimeoutWeex && (typeof global.clearTimeoutWeex === 'function')) {
          global.clearTimeoutWeex(n)
        }
        else {
          timer.clearTimeout(n)
        }
      },
      clearInterval: (n) => {
        if (global.clearIntervalWeex && (typeof global.clearIntervalWeex === 'function')) {
          global.clearIntervalWeex(n)
        }
        else {
          timer.clearInterval(n)
        }
      }
    })
  }
  // run code and get result
  const globalObjects = Object.assign({
    define: bundleDefine,
    require: bundleRequire,
    bootstrap: bundleBootstrap,
    register: bundleRegister,
    render: bundleRender,
    __weex_define__: bundleDefine, // alias for define
    __weex_bootstrap__: bundleBootstrap, // alias for bootstrap
    __weex_document__: bundleDocument,
    __weex_require__: bundleRequireModule,
    __weex_viewmodel__: bundleVm,
    weex: weexGlobalObject
  }, timerAPIs, services)
  if (!callFunctionNative(globalObjects, functionBody)) {
    // If failed to compile functionBody on native side,
    // fallback to callFunction.
    callFunction(globalObjects, functionBody)
  }

  return result
}

/**
 * Call a new function body with some global objects.
 * @param  {object} globalObjects
 * @param  {string} code
 * @return {any}
 */
function callFunction (globalObjects, body) {
  const globalKeys = []
  const globalValues = []
  for (const key in globalObjects) {
    globalKeys.push(key)
    globalValues.push(globalObjects[key])
  }
  globalKeys.push(body)

  const result = new Function(...globalKeys)
  return result(...globalValues)
}

/**
 * Call a new function generated on the V8 native side.
 * @param  {object} globalObjects
 * @param  {string} body
 * @return {boolean} return true if no error occurred.
 */
function callFunctionNative (globalObjects, body) {
  if (typeof compileAndRunBundle !== 'function') {
    return false
  }

  let fn = void 0
  let isNativeCompileOk = false
  let script = '(function ('
  const globalKeys = []
  const globalValues = []
  for (const key in globalObjects) {
    globalKeys.push(key)
    globalValues.push(globalObjects[key])
  }
  for (let i = 0; i < globalKeys.length - 1; ++i) {
    script += globalKeys[i]
    script += ','
  }
  script += globalKeys[globalKeys.length - 1]
  script += ') {'
  script += body
  script += '} )'

  try {
    const weex = globalObjects.weex || {}
    const config = weex.config || {}
    fn = compileAndRunBundle(script,
                             config.bundleUrl,
                             config.bundleDigest,
                             config.codeCachePath)
    if (fn && typeof fn === 'function') {
      fn(...globalValues)
      isNativeCompileOk = true
    }
  }
  catch (e) {
    console.error(e)
  }

  return isNativeCompileOk
}
<commit_msg>* [jsfm] revert commit call C++ timer instead of WxTimerModule with in weex jsfm<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
/**
 * @fileOverview
 * instance controls from native
 *
 * - init bundle
 *
 * corresponded with the API of instance manager (framework.js)
 */

import Vm from '../../vm/index'
import { removeWeexPrefix } from '../../util/index'
import {
  defineFn,
  bootstrap,
  register
} from '../bundle/index'
import { updateActions } from './misc'

/**
 * Init an app by run code witgh data
 * @param  {object} app
 * @param  {string} code
 * @param  {object} data
 */
export function init (app, code, data, services) {
  console.debug('[JS Framework] Intialize an instance with:\n', data)
  let result

  // prepare app env methods
  const bundleDefine = (...args) => defineFn(app, ...args)
  const bundleBootstrap = (name, config, _data) => {
    result = bootstrap(app, name, config, _data || data)
    updateActions(app)
    app.doc.listener.createFinish()
    console.debug(`[JS Framework] After intialized an instance(${app.id})`)
  }
  const bundleVm = Vm
  /* istanbul ignore next */
  const bundleRegister = (...args) => register(app, ...args)
  /* istanbul ignore next */
  const bundleRender = (name, _data) => {
    result = bootstrap(app, name, {}, _data)
  }
  /* istanbul ignore next */
  const bundleRequire = name => _data => {
    result = bootstrap(app, name, {}, _data)
  }
  const bundleDocument = app.doc
  /* istanbul ignore next */
  const bundleRequireModule = name => app.requireModule(removeWeexPrefix(name))

  const weexGlobalObject = {
    config: app.options,
    define: bundleDefine,
    bootstrap: bundleBootstrap,
    requireModule: bundleRequireModule,
    document: bundleDocument,
    Vm: bundleVm
  }

  Object.freeze(weexGlobalObject)

  // prepare code
  let functionBody
  /* istanbul ignore if */
  if (typeof code === 'function') {
    // `function () {...}` -> `{...}`
    // not very strict
    functionBody = code.toString().substr(12)
  }
  /* istanbul ignore next */
  else if (code) {
    functionBody = code.toString()
  }
  // wrap IFFE and use strict mode
  functionBody = `(function(global){\n\n"use strict";\n\n ${functionBody} \n\n})(Object.create(this))`

  // run code and get result
  const { WXEnvironment } = global
  const timerAPIs = {}

  /* istanbul ignore if */
  if (WXEnvironment && WXEnvironment.platform !== 'Web') {
    // timer APIs polyfill in native
    const timer = app.requireModule('timer')
    Object.assign(timerAPIs, {
      setTimeout: (...args) => {
        const handler = function () {
          args[0](...args.slice(2))
        }
        timer.setTimeout(handler, args[1])
        return app.doc.taskCenter.callbackManager.lastCallbackId.toString()
      },
      setInterval: (...args) => {
        const handler = function () {
          args[0](...args.slice(2))
        }
        timer.setInterval(handler, args[1])
        return app.doc.taskCenter.callbackManager.lastCallbackId.toString()
      },
      clearTimeout: (n) => {
        timer.clearTimeout(n)
      },
      clearInterval: (n) => {
        timer.clearInterval(n)
      }
    })
  }
  // run code and get result
  const globalObjects = Object.assign({
    define: bundleDefine,
    require: bundleRequire,
    bootstrap: bundleBootstrap,
    register: bundleRegister,
    render: bundleRender,
    __weex_define__: bundleDefine, // alias for define
    __weex_bootstrap__: bundleBootstrap, // alias for bootstrap
    __weex_document__: bundleDocument,
    __weex_require__: bundleRequireModule,
    __weex_viewmodel__: bundleVm,
    weex: weexGlobalObject
  }, timerAPIs, services)
  if (!callFunctionNative(globalObjects, functionBody)) {
    // If failed to compile functionBody on native side,
    // fallback to callFunction.
    callFunction(globalObjects, functionBody)
  }

  return result
}

/**
 * Call a new function body with some global objects.
 * @param  {object} globalObjects
 * @param  {string} code
 * @return {any}
 */
function callFunction (globalObjects, body) {
  const globalKeys = []
  const globalValues = []
  for (const key in globalObjects) {
    globalKeys.push(key)
    globalValues.push(globalObjects[key])
  }
  globalKeys.push(body)

  const result = new Function(...globalKeys)
  return result(...globalValues)
}

/**
 * Call a new function generated on the V8 native side.
 * @param  {object} globalObjects
 * @param  {string} body
 * @return {boolean} return true if no error occurred.
 */
function callFunctionNative (globalObjects, body) {
  if (typeof compileAndRunBundle !== 'function') {
    return false
  }

  let fn = void 0
  let isNativeCompileOk = false
  let script = '(function ('
  const globalKeys = []
  const globalValues = []
  for (const key in globalObjects) {
    globalKeys.push(key)
    globalValues.push(globalObjects[key])
  }
  for (let i = 0; i < globalKeys.length - 1; ++i) {
    script += globalKeys[i]
    script += ','
  }
  script += globalKeys[globalKeys.length - 1]
  script += ') {'
  script += body
  script += '} )'

  try {
    const weex = globalObjects.weex || {}
    const config = weex.config || {}
    fn = compileAndRunBundle(script,
                             config.bundleUrl,
                             config.bundleDigest,
                             config.codeCachePath)
    if (fn && typeof fn === 'function') {
      fn(...globalValues)
      isNativeCompileOk = true
    }
  }
  catch (e) {
    console.error(e)
  }

  return isNativeCompileOk
}
<|endoftext|>


<commit_before>'uses strict';

window.snippetSupport=(function() {

var sampleName = '';

function processFilesWithSnippets() {
  var xhr=new XMLHttpRequest();
  xhr.responseType='json';
  xhr.open('GET', '../sample_support_metadata.json');
  xhr.onload=function() {
    sampleName = this.response.sample;
    var snippetsCount=this.response.files_with_snippets.length;
    for (var i=0; i<snippetsCount; i++) {
      var filename = this.response.files_with_snippets[i];
      var last = false;
      if (i==snippetsCount-1) {
        last = true;
      }
      getFileContents(filename, function(content) {
        extractSnippets(content, filename)
        if (last) {
          prettyPrint();
        }
      });
    }
  };
  xhr.send();
}

function getFileContents(filename, callback) {
  var xhr=new XMLHttpRequest();
  xhr.open('GET', '../'+filename);
  xhr.onload=function() {
    callback(this.responseText);
  };
  xhr.send();
}

function addSnippet(snippetName, snippet) {
  var pre = document.createElement('pre');
  pre.classList.add('prettyprint');
  pre.innerText=snippet.content;
  var h2 = document.createElement('h2');
  h2.innerText=snippetName;
  var linkToGithub = document.createElement('span');
  var githubUrl='https://github.com/GoogleChrome/chrome-app-samples/tree/master/'+
    sampleName+'/'+snippet.filename+'#L'+snippet.startLine+'-L'+snippet.endLine;
  linkToGithub.innerHTML=''+snippet.filename+
      ' lines '+snippet.startLine+' to '+snippet.endLine+'';
  h2.appendChild(linkToGithub)
  var div = document.createElement('div');
  div.classList.add('snippet');
  div.appendChild(h2);
  div.appendChild(pre);
  document.querySelector('.snippets').appendChild(div);
}

function extractSnippets(content, filename) {
  var lines=content.split('\n');
  var linesCount=lines.length;
  var reStart=/^\s*\/\/\s+@corecode_begin\s*([^ ]*)\s*$/;
  var reStop=/^\s*\/\/\s+@corecode_end\s*([^ ]*)\s*$/;
  var reSpaces=/^(\s*)/;
  var snippets={};
  var openSnippets={};
  var indentation={};
  var exec;
  for (var line=0; line<linesCount; line++) {
    exec=reStart.exec(lines[line]);
    if (exec && exec.length>1) {
      var snippetName = exec[1];
      // save the indentation
      var indent = reSpaces.exec(lines[line])[1].length;
      indentation[snippetName] = indent;
      openSnippets[snippetName] = snippetName;
      snippets[snippetName]={"content": "", "filename": filename,
      "startLine": line+2};
    } else {
      exec=reStop.exec(lines[line]);
      if (exec && exec.length>1) {
        snippets[snippetKey].endLine=line;
        delete openSnippets[exec[1]];
      } else {
        for (var snippetKey in openSnippets) {
          var indent = indentation[snippetKey];
          var strippedLine=lines[line];
          // make sure we are not stripping non-whitespaces
          if (/^\s*$/.test(lines[line].substr(0, indent))) {
            strippedLine=lines[line].substr(indent);
          }
          snippets[snippetKey].content+=strippedLine+'\n';
        }
      }
    }
  }

  for (var snippetName in snippets) {
    addSnippet(snippetName, snippets[snippetName]);
  }
}

return {
    "processFilesWithSnippets": processFilesWithSnippets
  }

})();

document.addEventListener('DOMContentLoaded', function() {
  window.snippetSupport.processFilesWithSnippets();
});
<commit_msg>show manifest relevant keys in "show source" window<commit_after>'uses strict';

window.snippetSupport=(function() {

var sampleName = '';

function processFilesWithSnippets() {
  var xhr=new XMLHttpRequest();
  xhr.responseType='json';
  xhr.open('GET', '../sample_support_metadata.json');
  xhr.onload=function() {
    sampleName = this.response.sample;

    // extract from manifest:
    extractFromManifest();

    //extract from files with core snippets:
    var snippetsCount=this.response.files_with_snippets.length;
    for (var i=0; i<snippetsCount; i++) {
      var filename = this.response.files_with_snippets[i];
      var last = false;
      if (i==snippetsCount-1) {
        last = true;
      }
      getFileContents(filename, function(content) {
        extractSnippets(content, filename)
        if (last) {
          prettyPrint();
        }
      });
    }
  };
  xhr.send();
}

function extractFromManifest(content) {
  var manifest = chrome.runtime.getManifest();
  // remove common keys
  delete manifest.key
  delete manifest.name
  delete manifest.description
  delete manifest.manifest_version
  delete manifest.app
  delete manifest.version
  var note="// these are only some of the keys relevant to this sample\n"+
    "// for the complete manifest, click in the 'manifest.json' link above\n";
  addSnippet('Relevant manifest keys',
    { 'filename': 'manifest.json',
      'content': note+JSON.stringify(manifest, null, 2)
    });
}

function getFileContents(filename, callback) {
  var xhr=new XMLHttpRequest();
  xhr.open('GET', '../'+filename);
  xhr.onload=function() {
    callback(this.responseText);
  };
  xhr.send();
}

function addSnippet(snippetName, snippet) {
  var pre = document.createElement('pre');
  pre.classList.add('prettyprint');
  pre.innerText=snippet.content;
  var h2 = document.createElement('h2');
  h2.innerText=snippetName;
  var linkToGithub = document.createElement('span');
  var githubUrl='https://github.com/GoogleChrome/chrome-app-samples/tree/master/'+
    sampleName+'/'+snippet.filename;
  if (snippet.startLine) {
    githubUrl+='#L'+snippet.startLine+'-L'+snippet.endLine;
  }
  var githubUrlHTML = ''+snippet.filename;
  if (snippet.startLine) {
    githubUrlHTML += ' lines '+snippet.startLine+' to '+snippet.endLine;
  }
  githubUrlHTML += '';
  linkToGithub.innerHTML = githubUrlHTML;
  h2.appendChild(linkToGithub)
  var div = document.createElement('div');
  div.classList.add('snippet');
  div.appendChild(h2);
  div.appendChild(pre);
  document.querySelector('.snippets').appendChild(div);
}

function extractSnippets(content, filename) {
  var lines=content.split('\n');
  var linesCount=lines.length;
  var reStart=/^\s*\/\/\s+@corecode_begin\s*([^ ]*)\s*$/;
  var reStop=/^\s*\/\/\s+@corecode_end\s*([^ ]*)\s*$/;
  var reSpaces=/^(\s*)/;
  var snippets={};
  var openSnippets={};
  var indentation={};
  var exec;
  for (var line=0; line<linesCount; line++) {
    exec=reStart.exec(lines[line]);
    if (exec && exec.length>1) {
      var snippetName = exec[1];
      // save the indentation
      var indent = reSpaces.exec(lines[line])[1].length;
      indentation[snippetName] = indent;
      openSnippets[snippetName] = snippetName;
      snippets[snippetName] = {"content": "", "filename": filename,
        "startLine": line+2};
    } else {
      exec=reStop.exec(lines[line]);
      if (exec && exec.length>1) {
        snippets[snippetKey].endLine=line;
        delete openSnippets[exec[1]];
      } else {
        for (var snippetKey in openSnippets) {
          var indent = indentation[snippetKey];
          var strippedLine=lines[line];
          // make sure we are not stripping non-whitespaces
          if (/^\s*$/.test(lines[line].substr(0, indent))) {
            strippedLine=lines[line].substr(indent);
          }
          snippets[snippetKey].content+=strippedLine+'\n';
        }
      }
    }
  }

  for (var snippetName in snippets) {
    addSnippet(snippetName, snippets[snippetName]);
  }
}

return {
    "processFilesWithSnippets": processFilesWithSnippets
  }

})();

document.addEventListener('DOMContentLoaded', function() {
  window.snippetSupport.processFilesWithSnippets();
});
<|endoftext|>


<commit_before>import { ReactiveVar } from 'meteor/reactive-var';
import { Clients } from '/imports/api/clients/clients';

import './clientDeleteReason.html';

const reasons = [
  { required: true, text: 'Housed by CARS (include agency/program)' },
  { required: false, text: 'Housed externally' },
  { required: false, text: 'Unreachable' },
  { required: false, text: 'Insufficient contact information' },
  { required: false, text: 'Client maxed out referral offers' },
  { required: false, text: 'Client no longer interested in services' },
  { required: true, text: 'Other (specify)' },
].map(({ text, required }) => ({
  id: text.replace(/\s+/g, '_').toLowerCase(),
  text,
  required,
}));

const reasonsHash = reasons.reduce((acc, reason) => ({ ...acc, [reason.id]: reason }), {});

Template.clientDeleteReason.onCreated(function clientDeleteReasonOnCreated() {
  this.removalDetails = new ReactiveVar(reasons[0].required);
});

Template.clientDeleteReason.helpers({
  showRemovalDetails() {
    if (Template.instance()) return Template.instance().removalDetails.get();
    return false;
  },
  reasonsList() {
    return reasons;
  },
});

Template.clientDeleteReason.events({
  'change #removalReason'(event, tmpl) {
    const reasonId = event.target.value;
    tmpl.removalDetails.set(reasonsHash[reasonId].required);
  },
  'click .removeFromHousingList'(evt, tmpl) {
    const clientId = tmpl.data.client._id;
    const remarks = $('#removalRemarks').val();
    const date = $('#removalDate').val();
    const reasonId = $('#removalReason').val();

    if (remarks.trim().length === 0 && reasonsHash[reasonId].required) {
      Bert.alert('Remarks are required', 'danger', 'growl-top-right');
      $('#removalRemarks').focus();
      return;
    }
    if (date.trim().length === 0) {
      Bert.alert('Removal Date required', 'danger', 'growl-top-right');
      $('#removalDate').focus();
      return;
    }
    const reason = reasonsHash[reasonId];
    let removeReasons = reason.text;
    if (reason.required) removeReasons = `${removeReasons} | ${remarks}`;
    removeReasons = `${removeReasons} | ${date}`;
    Meteor.call('ignoreMatchProcess', clientId, true, removeReasons, (err, res) => {
      if (err) {
        Bert.alert(err.reason || err.error, 'danger', 'growl-top-right');
      } else {
        Bert.alert('Client removed for the matching process', 'success', 'growl-top-right');
        // We simulate update in client-side collection
        // Sadly, this cannot be done in meteor call (isSimulation)
        Clients._collection.update(clientId, { $set: { // eslint-disable-line
          'eligibleClient.ignoreMatchProcess': res.ignoreMatchProcess,
          'eligibleClient.remarks': res.remarks,
        } });
      }
    });
  },
});

Template.clientDeleteReason.onRendered(() => {
  $('.js-datepicker').datetimepicker({
    format: 'MM-DD-YYYY',
  });
  $('.removalReason').select2({
    placeholder: 'Select reason',
    allowClear: true,
    theme: 'classic',
    // tags: true,
    // createTag: (params) => {
    //   const term = $.trim(params.term);

    //   if (term === '') return null;

    //   return {
    //     id: term.replace(/\s+/g, '_').toLowerCase(),
    //     text: term,
    //     newTag: true, // add additional parameters
    //   };
    // },
  });
});
<commit_msg>Removal unreachable fix<commit_after>import { ReactiveVar } from 'meteor/reactive-var';
import { Clients } from '/imports/api/clients/clients';

import './clientDeleteReason.html';

const reasons = [
  { required: true, text: 'Housed by CARS (include agency/program)' },
  { required: false, text: 'Housed externally' },
  { required: false, text: 'Unreachable' },
  { required: false, text: 'Insufficient contact information' },
  { required: false, text: 'Client maxed out referral offers' },
  { required: false, text: 'Client no longer interested in services' },
  { required: true, text: 'Other (specify)' },
].map(({ text, required }) => ({
  id: text.replace(/\s+/g, '_').toLowerCase(),
  text,
  required,
}));

const reasonsHash = reasons.reduce((acc, reason) => ({ ...acc, [reason.id]: reason }), {});

Template.clientDeleteReason.onCreated(function clientDeleteReasonOnCreated() {
  this.removalDetails = new ReactiveVar(reasons[0].required);
});

Template.clientDeleteReason.helpers({
  showRemovalDetails() {
    if (Template.instance()) return Template.instance().removalDetails.get();
    return false;
  },
  reasonsList() {
    return reasons;
  },
});

Template.clientDeleteReason.events({
  'change #removalReason'(event, tmpl) {
    const reasonId = event.target.value;
    tmpl.removalDetails.set(reasonsHash[reasonId].required);
  },
  'click .removeFromHousingList'(evt, tmpl) {
    const clientId = tmpl.data.client._id;
    const remarks = $('#removalRemarks').val();
    const date = $('#removalDate').val();
    const reasonId = $('#removalReason').val();

    if (reasonsHash[reasonId].required && remarks.trim().length === 0) {
      Bert.alert('Remarks are required', 'danger', 'growl-top-right');
      $('#removalRemarks').focus();
      return;
    }
    if (date.trim().length === 0) {
      Bert.alert('Removal Date required', 'danger', 'growl-top-right');
      $('#removalDate').focus();
      return;
    }
    const reason = reasonsHash[reasonId];
    let removeReasons = reason.text;
    if (reason.required) removeReasons = `${removeReasons} | ${remarks}`;
    removeReasons = `${removeReasons} | ${date}`;
    Meteor.call('ignoreMatchProcess', clientId, true, removeReasons, (err, res) => {
      if (err) {
        Bert.alert(err.reason || err.error, 'danger', 'growl-top-right');
      } else {
        Bert.alert('Client removed for the matching process', 'success', 'growl-top-right');
        // We simulate update in client-side collection
        // Sadly, this cannot be done in meteor call (isSimulation)
        Clients._collection.update(clientId, { $set: { // eslint-disable-line
          'eligibleClient.ignoreMatchProcess': res.ignoreMatchProcess,
          'eligibleClient.remarks': res.remarks,
        } });
      }
    });
  },
});

Template.clientDeleteReason.onRendered(() => {
  $('.js-datepicker').datetimepicker({
    format: 'MM-DD-YYYY',
  });
  $('.removalReason').select2({
    placeholder: 'Select reason',
    allowClear: true,
    theme: 'classic',
    // tags: true,
    // createTag: (params) => {
    //   const term = $.trim(params.term);

    //   if (term === '') return null;

    //   return {
    //     id: term.replace(/\s+/g, '_').toLowerCase(),
    //     text: term,
    //     newTag: true, // add additional parameters
    //   };
    // },
  });
});
<|endoftext|>


<commit_before>

function sectionImage(images) {
  let bgImage = _.find(images, (image) => {
    return image.fileLabel === "1:1";
  });

  if (!bgImage) {
    bgImage = images[0];
  }

  if (bgImage) {
    bgImage = bgImage.url;
  } else {
    bgImage = "";
  }

  return bgImage;
}

export default sectionImage;
<commit_msg>lint imports/util/sections<commit_after>

function sectionImage(images) {
  let bgImage = _.find(images, (image) => (
    image.fileLabel === "1:1"
  ));

  if (!bgImage) {
    bgImage = images[0];
  }

  if (bgImage) {
    bgImage = bgImage.url;
  } else {
    bgImage = "";
  }

  return bgImage;
}

export default sectionImage;
<|endoftext|>