<commit_before>import { emit, prop, state, vdom } from '../../../src/index';
import component from '../../lib/component';

const { boolean, number } = prop;

describe('events (on*)', function () {
  it('should not duplicate listeners', function () {
    const myel = component({
      properties: {
        test: number({ default: 0 })
      },
      created (elem) {
        elem._test = 0;
      },
      render (elem) {
        vdom('div', {
          onevent () {
            elem._test++;
          }
        }, elem.test);
      }
    });

    const el = myel();
    const shadowDiv = el.shadowRoot.children[0];

    // Ensures that it rendered.
    expect(shadowDiv.textContent).to.equal('0');
    expect(el._test).to.equal(0);

    // Trigger the handler.
    emit(shadowDiv, 'event');

    // Ensure the event fired.
    expect(el._test).to.equal(1);

    // Re-render.
    state(el, { test: el.test + 1 });
    expect(shadowDiv.textContent).to.equal('1');
    emit(shadowDiv, 'event');
    expect(el._test).to.equal(2);

    state(el, { test: el.test + 1 });
    expect(shadowDiv.textContent).to.equal('2');
    emit(shadowDiv, 'event');
    expect(el._test).to.equal(3);
  });

  it('should not trigger events bubbled from descendants', function () {
    let called = false;
    const test = () => called = true;
    const myel = component({
      render () {
        vdom('div', { ontest: test }, vdom.bind(null, 'span'));
      }
    })();

    emit(myel.querySelector('span'), 'test');
    expect(called).to.equal(false);
  });

  it('should not fail for listeners that are not functions', function () {
    const myel = component({
      render () {
        vdom('div', { ontest: null });
      }
    })();
    emit(myel.shadowRoot.firstChild, 'test');
  });

  describe('built-in / custom', function () {
    let count, div, el;

    function inc () {
      ++count;
    }

    beforeEach(function () {
      count = 0;
      el = component({
        properties: {
          unbind: boolean()
        },
        render (elem) {
          if (elem.unbind) {
            vdom('div');
          } else {
            vdom('div', { onclick: inc, ontest: inc });
          }
        }
      })();
      div = el.shadowRoot.firstChild;
    });

    describe('built-in', function () {
      it('binding', function () {
        expect(div.onclick).to.be.a('function');
      });

      it('triggering via function', function () {
        div.onclick();
        expect(count).to.equal(1);
      });

      it('triggering via dispatchEvent()', function () {
        emit(div, 'click');
        expect(count).to.equal(1);
      });

      it('unbinding', function () {
        state(el, { unbind: true });
        expect(div.onclick).to.equal(null);
      });
    });

    describe('custom', function () {
      it('binding', function () {
        expect(div.ontest).to.equal(undefined);
      });

      it('triggering via dispatchEvent()', function () {
        emit(div, 'test');
        expect(count).to.equal(1);
      });

      it('unbinding', function () {
        state(el, { unbind: true });
        emit(div, 'test');
        expect(count).to.equal(0);
      });
    });
  });
});
<commit_msg>Fix test that was incorrectly trying to query for a shadow node from the host node.<commit_after>import { emit, prop, state, vdom } from '../../../src/index';
import component from '../../lib/component';

const { boolean, number } = prop;

describe('events (on*)', function () {
  it('should not duplicate listeners', function () {
    const myel = component({
      properties: {
        test: number({ default: 0 })
      },
      created (elem) {
        elem._test = 0;
      },
      render (elem) {
        vdom('div', {
          onevent () {
            elem._test++;
          }
        }, elem.test);
      }
    });

    const el = myel();
    const shadowDiv = el.shadowRoot.children[0];

    // Ensures that it rendered.
    expect(shadowDiv.textContent).to.equal('0');
    expect(el._test).to.equal(0);

    // Trigger the handler.
    emit(shadowDiv, 'event');

    // Ensure the event fired.
    expect(el._test).to.equal(1);

    // Re-render.
    state(el, { test: el.test + 1 });
    expect(shadowDiv.textContent).to.equal('1');
    emit(shadowDiv, 'event');
    expect(el._test).to.equal(2);

    state(el, { test: el.test + 1 });
    expect(shadowDiv.textContent).to.equal('2');
    emit(shadowDiv, 'event');
    expect(el._test).to.equal(3);
  });

  it('should not trigger events bubbled from descendants', function () {
    let called = false;
    const test = () => called = true;
    const myel = component({
      render () {
        vdom('div', { ontest: test }, vdom.bind(null, 'span'));
      }
    })();
    emit(myel.shadowRoot.querySelector('span'), 'test');
    expect(called).to.equal(false);
  });

  it('should not fail for listeners that are not functions', function () {
    const myel = component({
      render () {
        vdom('div', { ontest: null });
      }
    })();
    emit(myel.shadowRoot.firstChild, 'test');
  });

  describe('built-in / custom', function () {
    let count, div, el;

    function inc () {
      ++count;
    }

    beforeEach(function () {
      count = 0;
      el = component({
        properties: {
          unbind: boolean()
        },
        render (elem) {
          if (elem.unbind) {
            vdom('div');
          } else {
            vdom('div', { onclick: inc, ontest: inc });
          }
        }
      })();
      div = el.shadowRoot.firstChild;
    });

    describe('built-in', function () {
      it('binding', function () {
        expect(div.onclick).to.be.a('function');
      });

      it('triggering via function', function () {
        div.onclick();
        expect(count).to.equal(1);
      });

      it('triggering via dispatchEvent()', function () {
        emit(div, 'click');
        expect(count).to.equal(1);
      });

      it('unbinding', function () {
        state(el, { unbind: true });
        expect(div.onclick).to.equal(null);
      });
    });

    describe('custom', function () {
      it('binding', function () {
        expect(div.ontest).to.equal(undefined);
      });

      it('triggering via dispatchEvent()', function () {
        emit(div, 'test');
        expect(count).to.equal(1);
      });

      it('unbinding', function () {
        state(el, { unbind: true });
        emit(div, 'test');
        expect(count).to.equal(0);
      });
    });
  });
});
<|endoftext|>


<commit_before>/* Project specific Javascript goes here. */
<commit_msg>Fixing export download button<commit_after>/* Project specific Javascript goes here. */
if (!$) {
    $ = django.jQuery;
}

download_file = function(pk) {
  $('input[name="_selected_action"]').removeAttr('checked');
  $('input[name="_selected_action"][value="{}"]'.replace('{}', pk)).attr('checked', 'checked');
  $('select[name="action"]').val('download');
  $('button[type="submit"][name="index"]').click();
  $('input[name="_selected_action"]').removeAttr('checked');
};
<|endoftext|>


<commit_before>'use strict';

var uniq = require('array-uniq');
var assert = require('assert');
var difference = require('interset/difference');
var cuid = require('cuid');

var SCHEMA_BRAND = '$schemaBrand-' + cuid();
var allowedMethods = [
    'GET', 'POST', 'PUT', 'DELETE'
];
var allowedHttpRequestKeys = [
    'method', 'query', 'headers', 'body'
];
var allowedHttpResponseKeys = [
    'statusCode', 'headers', 'body'
];
var validStringOptions = [
    'minLength', 'maxLength'
];
var validStructoptions = [
    'additionalProperties'
];

var V = {
    struct: struct,
    enum: $enum,
    string: string,
    email: email,
    number: number,
    union: union,
    object: object,
    'null': $null,
    http: {
        Request: HttpRequest,
        Response: HttpResponse
    }
};

module.exports = V;

function SchemaBrand(obj) {
    Object.defineProperty(obj, '$schemaBrand', {
        writable: false,
        enumerable: false,
        configurable: true,
        value: SCHEMA_BRAND
    });

    return obj;
}

function isSchemaBranded(o) {
    return o.$schemaBrand === SCHEMA_BRAND;
}

function struct(props, options) {
    var keys = Object.keys(props);

    assert(keys.length > 0, 'props is required');

    var values = keys.map(function toValue(k) {
        return props[k];
    });
    var notBranded = values.filter(function isBranded(v) {
        return !isSchemaBranded(v);
    });

    assert(notBranded.length === 0,
        'expected all props to be schemas');

    if (options) {
        assert(typeof options === 'object',
            'options arg must be an object');

        var oKeys = Object.keys(options);

        assert(oKeys.length > 0 &&
            difference(oKeys, validStructoptions).length === 0,
            'expected only valid options');

        assert(!('additionalProperties' in options) ||
            typeof options.additionalProperties === 'boolean',
            'expected additionalProperties to be a boolean');
    }

    return SchemaBrand({
        'type': 'object',
        properties: props,
        required: keys,
        additionalProperties:
            (options && 'additionalProperties' in options) ?
                options.additionalProperties : false
    });
}

function $enum(xs) {
    assert(Array.isArray(xs) && xs.length > 0,
        'xs is required');

    var types = xs.map(function toTypeOf(x) {
        return typeof x;
    });
    var uniqueTypes = uniq(types);

    assert(uniqueTypes.length === 1, 'must have unique types');

    return SchemaBrand({
        'type': uniqueTypes[0],
        'enum': xs
    });
}

function string(expected, options) {
    function check() {
        assert(expected === undefined ||
            typeof expected === 'string',
            'expectedValue must be string');
        assert(options === undefined ||
            (typeof options === 'object' && options !== null),
            'expected options to be an object');

        if (options) {
            var keys = Object.keys(options);

            assert(!options || (
                keys.length > 0 &&
                difference(keys, validStringOptions).length === 0
            ), 'expected only valid option keys');

            assert(!options ||
                !('maxLength' in options) ||
                (typeof options.maxLength === 'number' &&
                options.maxLength > 0),
                'expected options.maxLength to be positive'
            );

            assert(!options ||
                !('minLength' in options) ||
                (typeof options.minLength === 'number' &&
                options.minLength > 0),
                'expected options.minLength to be positive'
            );
        }
    }

    if (typeof expected === 'object' && expected !== null) {
        options = expected;
        expected = undefined;
    }

    check();

    var doc = SchemaBrand({
        'type': 'string'
    });

    if (expected !== undefined) {
        doc.enum = [expected];
    }
    if (options && options.maxLength) {
        doc.maxLength = options.maxLength;
    }
    if (options && options.minLength) {
        doc.minLength = options.minLength;
    }

    return doc;
}

function email() {
    return SchemaBrand({
        type: 'string',
        format: 'email'
    });
}

function number(expected) {
    assert(expected === undefined ||
        typeof expected === 'number',
        'expectedValue must be a number');

    var doc = SchemaBrand({
        'type': 'number'
    });

    if (expected !== undefined) {
        doc.enum = [expected];
    }

    return doc;
}

function union(records) {
    assert(Array.isArray(records) && records.length > 0,
        'records must be non-empty array');

    var notBranded = records.filter(function isBranded(v) {
        return !isSchemaBranded(v);
    });

    assert(notBranded.length === 0,
        'expected all records to be schemas');

    return SchemaBrand({
        'oneOf': records
    });
}

function object(item) {
    assert(item, 'expected item argument');
    assert(item && isSchemaBranded(item),
        'expected item to be a schema');

    return SchemaBrand({
        'type': 'object',
        'additionalProperties': item
    });
}

function $null() {
    return SchemaBrand({
        type: 'null'
    });
}

function HttpRequest(req) {
    assert(req, 'req is required');

    var keys = Object.keys(req);

    assert(keys &&
        keys.length > 0 &&
        difference(keys, allowedHttpRequestKeys).length === 0,
        'expected only valid HttpRequest properties');

    assert(req.method &&
        typeof req.method === 'string' &&
        allowedMethods.indexOf(req.method) > -1,
        'req.method must be valid HTTP method'
    );

    assert(!req.query || typeof req.query === 'object',
        'req.query must be an object');

    assert(!req.headers || typeof req.headers === 'object',
        'req.headers must be an object');

    assert(!req.body || typeof req.body === 'object',
        'req.body must be an object');

    var opts = {
        method: V.string(req.method),
        url: V.string(),
        httpVersion: V.string(),
        query: req.query ?
            V.struct(req.query) :
            V.object(V.string()),
        headers: req.headers ?
            V.struct(req.headers, {
                additionalProperties: true
            }) :
            V.object(V.string())
    };

    if (req.body) {
        opts.body = V.struct(req.body);
    }

    return V.struct(opts);
}

function HttpResponse(res) {
    assert(res, 'res is required');

    var keys = Object.keys(res);

    assert(keys &&
        keys.length > 0 &&
        difference(keys, allowedHttpResponseKeys).length === 0,
        'expected only valid HttpResponse properties');

    assert(res.statusCode &&
        typeof res.statusCode === 'number' &&
        res.statusCode >= 100 &&
        res.statusCode <= 999,
        'req.statusCode must be a valid HTTP statusCode');

    assert(!res.headers || typeof res.headers === 'object',
        'res.headers must be an object');

    assert(!res.body || typeof res.body === 'object',
        'res.body must be an object');

    var opts = {
        statusCode: V.number(res.statusCode),
        headers: res.headers ?
            V.struct(res.headers) :
            V.object(V.string())
    };

    if (res.body) {
        opts.body = isSchemaBranded(res.body) ?
            res.body : V.struct(res.body);
    }

    return V.struct(opts);
}
<commit_msg>add HttpTypedError to schema-ast<commit_after>'use strict';

var uniq = require('array-uniq');
var assert = require('assert');
var difference = require('interset/difference');
var cuid = require('cuid');

var SCHEMA_BRAND = '$schemaBrand-' + cuid();
var allowedMethods = [
    'GET', 'POST', 'PUT', 'DELETE'
];
var allowedHttpRequestKeys = [
    'method', 'query', 'headers', 'body'
];
var allowedHttpResponseKeys = [
    'statusCode', 'headers', 'body'
];
var validStringOptions = [
    'minLength', 'maxLength'
];
var validStructoptions = [
    'additionalProperties'
];

var V = {
    struct: struct,
    enum: $enum,
    string: string,
    email: email,
    number: number,
    union: union,
    object: object,
    'null': $null,
    http: {
        Request: HttpRequest,
        Response: HttpResponse,
        TypedError: HttpTypedError
    }
};

module.exports = V;

function SchemaBrand(obj) {
    Object.defineProperty(obj, '$schemaBrand', {
        writable: false,
        enumerable: false,
        configurable: true,
        value: SCHEMA_BRAND
    });

    return obj;
}

function isSchemaBranded(o) {
    return o.$schemaBrand === SCHEMA_BRAND;
}

function struct(props, options) {
    var keys = Object.keys(props);

    assert(keys.length > 0, 'props is required');

    var values = keys.map(function toValue(k) {
        return props[k];
    });
    var notBranded = values.filter(function isBranded(v) {
        return !isSchemaBranded(v);
    });

    assert(notBranded.length === 0,
        'expected all props to be schemas');

    if (options) {
        assert(typeof options === 'object',
            'options arg must be an object');

        var oKeys = Object.keys(options);

        assert(oKeys.length > 0 &&
            difference(oKeys, validStructoptions).length === 0,
            'expected only valid options');

        assert(!('additionalProperties' in options) ||
            typeof options.additionalProperties === 'boolean',
            'expected additionalProperties to be a boolean');
    }

    return SchemaBrand({
        'type': 'object',
        properties: props,
        required: keys,
        additionalProperties:
            (options && 'additionalProperties' in options) ?
                options.additionalProperties : false
    });
}

function $enum(xs) {
    assert(Array.isArray(xs) && xs.length > 0,
        'xs is required');

    var types = xs.map(function toTypeOf(x) {
        return typeof x;
    });
    var uniqueTypes = uniq(types);

    assert(uniqueTypes.length === 1, 'must have unique types');

    return SchemaBrand({
        'type': uniqueTypes[0],
        'enum': xs
    });
}

function string(expected, options) {
    function check() {
        assert(expected === undefined ||
            typeof expected === 'string',
            'expectedValue must be string');
        assert(options === undefined ||
            (typeof options === 'object' && options !== null),
            'expected options to be an object');

        if (options) {
            var keys = Object.keys(options);

            assert(!options || (
                keys.length > 0 &&
                difference(keys, validStringOptions).length === 0
            ), 'expected only valid option keys');

            assert(!options ||
                !('maxLength' in options) ||
                (typeof options.maxLength === 'number' &&
                options.maxLength > 0),
                'expected options.maxLength to be positive'
            );

            assert(!options ||
                !('minLength' in options) ||
                (typeof options.minLength === 'number' &&
                options.minLength > 0),
                'expected options.minLength to be positive'
            );
        }
    }

    if (typeof expected === 'object' && expected !== null) {
        options = expected;
        expected = undefined;
    }

    check();

    var doc = SchemaBrand({
        'type': 'string'
    });

    if (expected !== undefined) {
        doc.enum = [expected];
    }
    if (options && options.maxLength) {
        doc.maxLength = options.maxLength;
    }
    if (options && options.minLength) {
        doc.minLength = options.minLength;
    }

    return doc;
}

function email() {
    return SchemaBrand({
        type: 'string',
        format: 'email'
    });
}

function number(expected) {
    assert(expected === undefined ||
        typeof expected === 'number',
        'expectedValue must be a number');

    var doc = SchemaBrand({
        'type': 'number'
    });

    if (expected !== undefined) {
        doc.enum = [expected];
    }

    return doc;
}

function union(records) {
    assert(Array.isArray(records) && records.length > 0,
        'records must be non-empty array');

    var notBranded = records.filter(function isBranded(v) {
        return !isSchemaBranded(v);
    });

    assert(notBranded.length === 0,
        'expected all records to be schemas');

    return SchemaBrand({
        'oneOf': records
    });
}

function object(item) {
    assert(item, 'expected item argument');
    assert(item && isSchemaBranded(item),
        'expected item to be a schema');

    return SchemaBrand({
        'type': 'object',
        'additionalProperties': item
    });
}

function $null() {
    return SchemaBrand({
        type: 'null'
    });
}

function HttpRequest(req) {
    assert(req, 'req is required');

    var keys = Object.keys(req);

    assert(keys &&
        keys.length > 0 &&
        difference(keys, allowedHttpRequestKeys).length === 0,
        'expected only valid HttpRequest properties');

    assert(req.method &&
        typeof req.method === 'string' &&
        allowedMethods.indexOf(req.method) > -1,
        'req.method must be valid HTTP method'
    );

    assert(!req.query || typeof req.query === 'object',
        'req.query must be an object');

    assert(!req.headers || typeof req.headers === 'object',
        'req.headers must be an object');

    assert(!req.body || typeof req.body === 'object',
        'req.body must be an object');

    var opts = {
        method: V.string(req.method),
        url: V.string(),
        httpVersion: V.string(),
        query: req.query ?
            V.struct(req.query) :
            V.object(V.string()),
        headers: req.headers ?
            V.struct(req.headers, {
                additionalProperties: true
            }) :
            V.object(V.string())
    };

    if (req.body) {
        opts.body = V.struct(req.body);
    }

    return V.struct(opts);
}

function HttpResponse(res) {
    assert(res, 'res is required');

    var keys = Object.keys(res);

    assert(keys &&
        keys.length > 0 &&
        difference(keys, allowedHttpResponseKeys).length === 0,
        'expected only valid HttpResponse properties');

    assert(res.statusCode &&
        typeof res.statusCode === 'number' &&
        res.statusCode >= 100 &&
        res.statusCode <= 999,
        'req.statusCode must be a valid HTTP statusCode');

    assert(!res.headers || typeof res.headers === 'object',
        'res.headers must be an object');

    assert(!res.body || typeof res.body === 'object',
        'res.body must be an object');

    var opts = {
        statusCode: V.number(res.statusCode),
        headers: res.headers ?
            V.struct(res.headers) :
            V.object(V.string())
    };

    if (res.body) {
        opts.body = isSchemaBranded(res.body) ?
            res.body : V.struct(res.body);
    }

    return V.struct(opts);
}

function HttpTypedError(typedError) {
    assert(typedError, 'typedError is required');

    var keys = Object.keys(typedError);

    assert(keys &&
        keys.length > 0,
        'expected typedError to have properties');
    assert(typeof typedError.type === 'string',
        'expected `typedError.type` to be a string');
    assert(typeof typedError.statusCode === 'number',
        'expected `typedError.statusCode` to be a number');

    var opts = {
        type: V.string(typedError.type),
        name: V.string(),
        message: V.string(),
        statusCode: V.number(typedError.statusCode)
    };

    return HttpResponse({
        statusCode: typedError.statusCode,
        body: opts
    });
}
<|endoftext|>


<commit_before>import {default as Immutable} from "immutable";
import {default as React, PropTypes} from "react";
import {
  AppBar,
  LeftNav,
  MenuItem,
} from "material-ui";

require("normalize.css");

class ReactRoot extends React.Component {

  static get propTypes () {
    return {
      topPaths: PropTypes.object.isRequired,
      children: PropTypes.element.isRequired,
    };
  }

  constructor(...args) {
    super(...args);
  }

  getMenuItemsFromTopPaths (topPaths) {
    return new Immutable.List([
      { type: MenuItem.Types.SUBHEADER, text: "Top Paths" },
    ]).concat(topPaths.map(topPath => {
      // /#ZmFjZWJvb2svcmVhY3QsIGFuZ3VsYXIvYW5ndWxhci5qcw==
      const hash = topPath.match(/\/?#(.+)/)[1]; // ZmFjZWJvb2svcmVhY3QsIGFuZ3VsYXIvYW5ndWxhci5qcw==
      const text = atob(hash) // facebook/react, angular/angular.js
        .split(/,\s+/) // ["facebook/react", "angular/angular.js"]
        .map(ownerRepoStr => ownerRepoStr.match(/\/(\S+)/)[1]) // [react, angular.js]
        .join(", "); // react, angular.js

      return {
        route: topPath,
        text: text,
      };
    })).toJS();
  }

  render () {
    const {props, state} = this;
    const menuItems = this.getMenuItemsFromTopPaths(props.topPaths);

    return (

        <AppBar
          title="Xrossref"
          iconClassNameRight="muidocs-icon-navigation-expand-more"
          onLeftIconButtonTouchTap={() => this.refs.leftNav.toggle()}
        />
        <LeftNav ref="leftNav"
          docked={false}
          isInitiallyOpen={false}
          menuItems={menuItems}
        />
        {props.children}

    );
  }
}

export default ReactRoot;
<commit_msg>feat(ReactRoot): add Credits MenuItem<commit_after>import {default as Immutable} from "immutable";
import {default as React, PropTypes} from "react";
import {
  AppBar,
  LeftNav,
  MenuItem,
} from "material-ui";

require("normalize.css");

class ReactRoot extends React.Component {

  static get propTypes () {
    return {
      topPaths: PropTypes.object.isRequired,
      children: PropTypes.element.isRequired,
    };
  }

  constructor(...args) {
    super(...args);
  }

  getMenuItemsFromTopPaths (topPaths) {
    return new Immutable.List([
      {
        type: MenuItem.Types.LINK,
        payload: "https://github.com/tomchentw/xrossref#credits",
        text: "Credits",
      },
      { type: MenuItem.Types.SUBHEADER, text: "Top Paths" },
    ]).concat(topPaths.map(topPath => {
      // /#ZmFjZWJvb2svcmVhY3QsIGFuZ3VsYXIvYW5ndWxhci5qcw==
      const hash = topPath.match(/\/?#(.+)/)[1]; // ZmFjZWJvb2svcmVhY3QsIGFuZ3VsYXIvYW5ndWxhci5qcw==
      const text = atob(hash) // facebook/react, angular/angular.js
        .split(/,\s+/) // ["facebook/react", "angular/angular.js"]
        .map(ownerRepoStr => ownerRepoStr.match(/\/(\S+)/)[1]) // [react, angular.js]
        .join(", "); // react, angular.js

      return {
        route: topPath,
        text: text,
      };
    })).toJS();
  }

  render () {
    const {props, state} = this;
    const menuItems = this.getMenuItemsFromTopPaths(props.topPaths);

    return (

        <AppBar
          title="Xrossref"
          iconClassNameRight="muidocs-icon-navigation-expand-more"
          onLeftIconButtonTouchTap={() => this.refs.leftNav.toggle()}
        />
        <LeftNav ref="leftNav"
          docked={false}
          isInitiallyOpen={false}
          menuItems={menuItems}
        />
        {props.children}

    );
  }
}

export default ReactRoot;
<|endoftext|>


<commit_before>
"use strict";

var $ = require('jquery'),
    L = require('leaflet');

var zoom = require('./lib/mapUtil').ZOOM,
    SATELLITE = 'satellite',
    searchController = require('./searchController');

module.exports = {
    SATELLITE: SATELLITE,
    create: create,
    addTileLayer: addTileLayer,
    addGridLayer: addGridLayer
};

function create(options) {
    options = $.extend({
        domId: 'map'
    }, options);

    var mapOptions = {
        zoomControl: false,
        maxBounds: L.latLngBounds(config.bounds[0], config.bounds[1]).pad(4)
    };
    if (options.static) {
        mapOptions.dragging = false;
        mapOptions.touchZoom = false;
        mapOptions.scrollWheelZoom = false;
        mapOptions.doubleClickZoom = false;
        mapOptions.boxZoom = false;
    }

    var map = L.map(options.domId, mapOptions),
        zoomControl = L.control.zoom({position: 'bottomleft'}).addTo(map),
        $controlsContainer = $(zoomControl.getContainer()),
        bounds = getDomMapAttribute('bounds', options.domId),
        mapLocation = getDomMapAttribute('location', options.domId);

    if (bounds) {
        fitBounds(map, bounds);
    } else if (options.bounds) {
        map.fitBounds(options.bounds, {maxZoom: zoom.NEIGHBORHOOD});
    } else if (mapLocation) {
        map.setView(mapLocation, zoom.NEIGHBORHOOD);
    } else if (options.location && options.location.lat !== 0) {
        map.setView(options.location, zoom.NEIGHBORHOOD);
    } else {
        map.fitBounds(config.bounds);
    }

    initBaseMap(map, options);

    if (options.geolocation && navigator.geolocation) {
        initGeolocation($controlsContainer, map);
    }
    if (options.legend) {
        initLegend($controlsContainer, map);
    }
    if (options.search) {
        initLocationSearch($controlsContainer, map);
    }
    if (options.crosshairs) {
        initCrosshairs(options.domId);
    }
    if (options.static) {
        // We had to add zoomControl to find its container, but now remove it.
        zoomControl.removeFrom(map);
    }

    return map;
}

function fitBounds(map, bounds) {
    // GeoDjango bounds are [xmin, ymin, xmax, ymax]
    // Leaflet wants [ [ymin, xmin], [ymax, xmax] ]
    var b = [[bounds[1], bounds[0]], [bounds[3], bounds[2]]];
    map.fitBounds(b);
}

function isRetinaDevice() {
    return window.devicePixelRatio && window.devicePixelRatio > 1;
}

function initBaseMap(map, options) {
    var layerOptions =  {
            subdomains: 'abcd',
            maxZoom: zoom.MAX,
            attributon: '© OpenStreetMap ' +
                'contributors, © CartoDB'
        },
        satelliteUrl = 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
        strandardResUrl = 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png',
        retinaUrl = 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}@2x.png',
        url = options.baseMap === SATELLITE ? satelliteUrl :
            isRetinaDevice() ? retinaUrl : strandardResUrl;
    map.addLayer(new L.TileLayer(url, layerOptions));
}

function initGeolocation($controlsContainer, map) {
    var $button = $('');
    $controlsContainer.prepend($button);

    $button.on('click', function () {
        navigator.geolocation.getCurrentPosition(showPosition, showError);
    });

    function showPosition(position) {
        var center = L.latLng(position.coords.latitude, position.coords.longitude);
        map.setView(center, zoom.NEIGHBORHOOD);
    }

    function showError() {
        window.alert('Unable to show your location.');
    }
}

function initLocationSearch($controlsContainer, map) {
    searchController.create($controlsContainer, map);
}

function initLegend($controlsContainer, map) {
    var $button = $('?');
    $controlsContainer.prepend($button);
}

function initCrosshairs(domId) {
    var $map = $('#' + domId),
        $hHair = $('

'),
        $vHair = $('

');
    $map.append([$hHair, $vHair]);
}

function addTileLayer(map, url) {
    var tileUrl = url || getDomMapAttribute('tile-url'),
        layer = L.tileLayer(tileUrl, {
            minZoom: zoom.MIN,
            maxZoom: zoom.MAX
        }).addTo(map);
    return layer;
}

function addGridLayer(map, url) {
    var gridUrl = url || getDomMapAttribute('grid-url'),
        layer = L.utfGrid(gridUrl, {
            minZoom: zoom.MIN,
            maxZoom: zoom.MAX,
            useJsonP: false
        });
    map.addLayer(layer);
    return layer;
}

function getDomMapAttribute(dataAttName, domId) {
    domId = domId || 'map';
    var $map = $('#' + domId),
        value = $map.data(dataAttName);
    return value;
}
<commit_msg>Remove Leaflet Attribution<commit_after>
"use strict";

var $ = require('jquery'),
    L = require('leaflet');

var zoom = require('./lib/mapUtil').ZOOM,
    SATELLITE = 'satellite',
    searchController = require('./searchController');

module.exports = {
    SATELLITE: SATELLITE,
    create: create,
    addTileLayer: addTileLayer,
    addGridLayer: addGridLayer
};

function create(options) {
    options = $.extend({
        domId: 'map'
    }, options);

    var mapOptions = {
        attributionControl: false,
        zoomControl: false,
        maxBounds: L.latLngBounds(config.bounds[0], config.bounds[1]).pad(4)
    };
    if (options.static) {
        mapOptions.dragging = false;
        mapOptions.touchZoom = false;
        mapOptions.scrollWheelZoom = false;
        mapOptions.doubleClickZoom = false;
        mapOptions.boxZoom = false;
    }

    var map = L.map(options.domId, mapOptions),
        zoomControl = L.control.zoom({position: 'bottomleft'}).addTo(map),
        $controlsContainer = $(zoomControl.getContainer()),
        bounds = getDomMapAttribute('bounds', options.domId),
        mapLocation = getDomMapAttribute('location', options.domId);

    map.addControl(L.control.attribution({prefix: false}));

    if (bounds) {
        fitBounds(map, bounds);
    } else if (options.bounds) {
        map.fitBounds(options.bounds, {maxZoom: zoom.NEIGHBORHOOD});
    } else if (mapLocation) {
        map.setView(mapLocation, zoom.NEIGHBORHOOD);
    } else if (options.location && options.location.lat !== 0) {
        map.setView(options.location, zoom.NEIGHBORHOOD);
    } else {
        map.fitBounds(config.bounds);
    }

    initBaseMap(map, options);

    if (options.geolocation && navigator.geolocation) {
        initGeolocation($controlsContainer, map);
    }
    if (options.legend) {
        initLegend($controlsContainer, map);
    }
    if (options.search) {
        initLocationSearch($controlsContainer, map);
    }
    if (options.crosshairs) {
        initCrosshairs(options.domId);
    }
    if (options.static) {
        // We had to add zoomControl to find its container, but now remove it.
        zoomControl.removeFrom(map);
    }

    return map;
}

function fitBounds(map, bounds) {
    // GeoDjango bounds are [xmin, ymin, xmax, ymax]
    // Leaflet wants [ [ymin, xmin], [ymax, xmax] ]
    var b = [[bounds[1], bounds[0]], [bounds[3], bounds[2]]];
    map.fitBounds(b);
}

function isRetinaDevice() {
    return window.devicePixelRatio && window.devicePixelRatio > 1;
}

function initBaseMap(map, options) {
    var layerOptions =  {
            subdomains: 'abcd',
            maxZoom: zoom.MAX,
            attributon: '© OpenStreetMap ' +
                'contributors, © CartoDB'
        },
        satelliteUrl = 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
        strandardResUrl = 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png',
        retinaUrl = 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}@2x.png',
        url = options.baseMap === SATELLITE ? satelliteUrl :
            isRetinaDevice() ? retinaUrl : strandardResUrl;
    map.addLayer(new L.TileLayer(url, layerOptions));
}

function initGeolocation($controlsContainer, map) {
    var $button = $('');
    $controlsContainer.prepend($button);

    $button.on('click', function () {
        navigator.geolocation.getCurrentPosition(showPosition, showError);
    });

    function showPosition(position) {
        var center = L.latLng(position.coords.latitude, position.coords.longitude);
        map.setView(center, zoom.NEIGHBORHOOD);
    }

    function showError() {
        window.alert('Unable to show your location.');
    }
}

function initLocationSearch($controlsContainer, map) {
    searchController.create($controlsContainer, map);
}

function initLegend($controlsContainer, map) {
    var $button = $('?');
    $controlsContainer.prepend($button);
}

function initCrosshairs(domId) {
    var $map = $('#' + domId),
        $hHair = $('

'),
        $vHair = $('

');
    $map.append([$hHair, $vHair]);
}

function addTileLayer(map, url) {
    var tileUrl = url || getDomMapAttribute('tile-url'),
        layer = L.tileLayer(tileUrl, {
            minZoom: zoom.MIN,
            maxZoom: zoom.MAX
        }).addTo(map);
    return layer;
}

function addGridLayer(map, url) {
    var gridUrl = url || getDomMapAttribute('grid-url'),
        layer = L.utfGrid(gridUrl, {
            minZoom: zoom.MIN,
            maxZoom: zoom.MAX,
            useJsonP: false
        });
    map.addLayer(layer);
    return layer;
}

function getDomMapAttribute(dataAttName, domId) {
    domId = domId || 'map';
    var $map = $('#' + domId),
        value = $map.data(dataAttName);
    return value;
}
<|endoftext|>


<commit_before>var onSelectorViewCompiled = function() {};

function updateCompiledSelectorView(selection) {
  var hasText = selectionHasText(selection);
  var compiledSelector = hasText ? getCompiledSelector(selection) : '';
  onSelectorViewCompiled(compiledSelector);
}

function selectionHasText(selection) {
  return selection && selection.getText();
}

function onSelectionChange(event) {
  try {
    updateCompiledSelectorView(event.selection);
  } catch (e) {
    console.log('UNCAUGHT ERROR:', e);
  }
}

function addSelectionListener(editor, callback) {
  typeof callback === 'function' && (onSelectorViewCompiled = callback);
  return editor.onDidChangeSelectionRange(onSelectionChange);
}

module.exports.addSelectionListener = addSelectionListener;
<commit_msg>added comment<commit_after>var onSelectorViewCompiled = function() {};

function updateCompiledSelectorView(selection) {
  var hasText = selectionHasText(selection);
  var compiledSelector = hasText ? getCompiledSelector(selection) : '';
  onSelectorViewCompiled(compiledSelector);
}

function selectionHasText(selection) {
  return selection && selection.getText();
}

function onSelectionChange(event) {
  try {
    updateCompiledSelectorView(event.selection);
  } catch (e) {
    console.log('UNCAUGHT ERROR:', e);
  }
}

function addSelectionListener(editor, callback) {
  typeof callback === 'function' && (onSelectorViewCompiled = callback);
  return editor.onDidChangeSelectionRange(onSelectionChange);
}

// can only be used once the way it's set up now
module.exports.addSelectionListener = addSelectionListener;
<|endoftext|>


<commit_before>var paused = 0;

angular.module("gameApp", [])

    .controller("appController", ["$scope", "keyPressHandlerService", function($scope, keyPressHandlerService) {
      window.onload = function() {
        cast.receiver.logger.setLevelValue(0);
        window.castReceiverManager = cast.receiver.CastReceiverManager.getInstance();
        console.log('Starting Receiver Manager');

        // handler for the 'ready' event
        castReceiverManager.onReady = function(event) {
          console.log('Received Ready event: ' + JSON.stringify(event.data));
          window.castReceiverManager.setApplicationState('Application status is ready...');
        };

        // handler for 'senderconnected' event
        castReceiverManager.onSenderConnected = function(event) {
          console.log('Received Sender Connected event: ' + event.data);
          console.log(window.castReceiverManager.getSender(event.data).userAgent);
        };

        // handler for 'senderdisconnected' event
        castReceiverManager.onSenderDisconnected = function(event) {
          console.log('Received Sender Disconnected event: ' + event.data);
          if (window.castReceiverManager.getSenders().length == 0) {
            window.close();
          }
        };

        // handler for 'systemvolumechanged' event
        castReceiverManager.onSystemVolumeChanged = function(event) {
          console.log('Received System Volume Changed event: ' + event.data['level'] + ' ' +
              event.data['muted']);
        };

        // create a CastMessageBus to handle messages for a custom namespace
        window.messageBus =
          window.castReceiverManager.getCastMessageBus(
              'urn:x-cast:com.google.cast.sample.helloworld');

        // handler for the CastMessageBus message event
        window.messageBus.onMessage = function(event) {
          console.log('Message [' + event.senderId + ']: ' + event.data);
          // display the message from the sender
          displayText(event.data);

          if(event.data == 80) {
            if(paused == 1) {
              paused = 0;
              console.log ("play!")
            }
            else {
              console.log("pause!");
              paused = 1;
            }

          }

          keyPressHandlerService.keyPress(event.data);
          keyPressHandlerService.keyRelease(event.data);
          //keyPressHandlerService.keyPress == event.data;

          // inform all senders on the CastMessageBus of the incoming message event
          // sender message listener will be invoked
          window.messageBus.send(event.senderId, event.data);
        }

        // initialize the CastReceiverManager with an application status message
        window.castReceiverManager.start({statusText: 'Application is starting'});
        console.log('Receiver Manager started');
      };

      // utility function to display the text message in the input field
      function displayText(text) {
        console.log(text);
        document.getElementById('message').innerText = text;
        window.castReceiverManager.setApplicationState(text);
      };

      function triggerKeyDown() {
        var e = new KeyboardEvent('keydown', {'key': 'ArrowLeft', 'code': "ArrowLeft", 'keyCode': 38,'which':38});
        document.dispatchEvent(e);
          console.log(e);
      };

/*

        $scope.keydown = function(keyEvent) {
            if (!$scope.instructionsDisplayed) {
                $scope.instructionsDisplayed = true;
                return;
            }
            keyPressHandlerService.keyPress(keyEvent.key);
        };

        $scope.keyup = function(keyEvent) {
            keyPressHandlerService.keyRelease(keyEvent.key);
        };
*/
    }])

    .directive("centipedeGame", ["$interval", "gameService", "renderService", "graphicsEngineService", function($interval, gameService, renderService, graphicsEngineService) {
        return {
            restrict: 'A',
            template: '<canvas id="gameCanvas" width="600" height="640" left=50% setAttribute('style', "position: absolute;  left: 50%;margin-left:-400px; top: 50% margin-top:-300px; border:2px solid blue");style="border:1px solid #000000;"></canvas>',

            link: function(scope, element) {
                var intervalPromise;
                var animation = 0;
                var canvas = element.find('canvas')[0].getContext("2d");

                graphicsEngineService.initialise(canvas, 'App/img/graphics.png');
                gameService.initialise();

                function gameLoop() {

                    animation++;

                    if (animation == 4) {
                        animation = 0;
                    }

                   if(paused != 1) {
                      gameService.update(animation);
                      renderService.draw(animation);
                  }

                }

                intervalPromise = $interval(gameLoop, 50);

                scope.$on("$destroy", function() {
                    if (intervalPromise) {
                        $interval.cancel(intervalPromise);
                        intervalPromise = undefined;
                    }
                });
            }
        }
    }]);
<commit_msg>Update gameApp.js<commit_after>var paused = 0;

angular.module("gameApp", [])

    .controller("appController", ["$scope", "keyPressHandlerService", function($scope, keyPressHandlerService) {
      window.onload = function() {
        cast.receiver.logger.setLevelValue(0);
        window.castReceiverManager = cast.receiver.CastReceiverManager.getInstance();
        console.log('Starting Receiver Manager');

        // handler for the 'ready' event
        castReceiverManager.onReady = function(event) {
          console.log('Received Ready event: ' + JSON.stringify(event.data));
          window.castReceiverManager.setApplicationState('Application status is ready...');
        };

        // handler for 'senderconnected' event
        castReceiverManager.onSenderConnected = function(event) {
          console.log('Received Sender Connected event: ' + event.data);
          console.log(window.castReceiverManager.getSender(event.data).userAgent);
        };

        // handler for 'senderdisconnected' event
        castReceiverManager.onSenderDisconnected = function(event) {
          console.log('Received Sender Disconnected event: ' + event.data);
          if (window.castReceiverManager.getSenders().length == 0) {
            window.close();
          }
        };

        // handler for 'systemvolumechanged' event
        castReceiverManager.onSystemVolumeChanged = function(event) {
          console.log('Received System Volume Changed event: ' + event.data['level'] + ' ' +
              event.data['muted']);
        };

        // create a CastMessageBus to handle messages for a custom namespace
        window.messageBus =
          window.castReceiverManager.getCastMessageBus(
              'urn:x-cast:com.google.cast.sample.helloworld');

        // handler for the CastMessageBus message event
        window.messageBus.onMessage = function(event) {
          console.log('Message [' + event.senderId + ']: ' + event.data);
          // display the message from the sender
          displayText(event.data);

          if(event.data == 80) {
            if(paused == 1) {
              paused = 0;
              console.log ("play!")
            }
            else {
              console.log("pause!");
              paused = 1;
            }

          }

          keyPressHandlerService.keyPress(event.data);
          keyPressHandlerService.keyRelease(event.data);
          //keyPressHandlerService.keyPress == event.data;

          // inform all senders on the CastMessageBus of the incoming message event
          // sender message listener will be invoked
          window.messageBus.send(event.senderId, event.data);
        }

        // initialize the CastReceiverManager with an application status message
        window.castReceiverManager.start({statusText: 'Application is starting'});
        console.log('Receiver Manager started');
      };

      // utility function to display the text message in the input field
      function displayText(text) {
        console.log(text);
        document.getElementById('message').innerText = text;
        window.castReceiverManager.setApplicationState(text);
      };

      function triggerKeyDown() {
        var e = new KeyboardEvent('keydown', {'key': 'ArrowLeft', 'code': "ArrowLeft", 'keyCode': 38,'which':38});
        document.dispatchEvent(e);
          console.log(e);
      };

/*

        $scope.keydown = function(keyEvent) {
            if (!$scope.instructionsDisplayed) {
                $scope.instructionsDisplayed = true;
                return;
            }
            keyPressHandlerService.keyPress(keyEvent.key);
        };

        $scope.keyup = function(keyEvent) {
            keyPressHandlerService.keyRelease(keyEvent.key);
        };
*/
    }])

    .directive("centipedeGame", ["$interval", "gameService", "renderService", "graphicsEngineService", function($interval, gameService, renderService, graphicsEngineService) {
        return {
            restrict: 'A',
            template: '<canvas id="gameCanvas" width="600" height="640" left="300" style="border:1px solid #000000;"></canvas>',

            link: function(scope, element) {
                var intervalPromise;
                var animation = 0;
                var canvas = element.find('canvas')[0].getContext("2d");

                graphicsEngineService.initialise(canvas, 'App/img/graphics.png');
                gameService.initialise();

                function gameLoop() {

                    animation++;

                    if (animation == 4) {
                        animation = 0;
                    }

                   if(paused != 1) {
                      gameService.update(animation);
                      renderService.draw(animation);
                  }

                }

                intervalPromise = $interval(gameLoop, 50);

                scope.$on("$destroy", function() {
                    if (intervalPromise) {
                        $interval.cancel(intervalPromise);
                        intervalPromise = undefined;
                    }
                });
            }
        }
    }]);
<|endoftext|>


<commit_before>(function() {
    'use strict';

    /*
        '# commander.js'                                    + '\n'  +
        '# -----------'                                     + '\n'  +
        '# Module is part of Cloud Commander,'              + '\n'  +
        '# used for getting dir content.'                   + '\n'  +
        '# and forming html content'                        + '\n'  +
        '# http://cloudcmd.io'                              + '\n');
    */

    var fs                  = require('fs'),

        DIR                 = '../',
        DIR_SERVER          = DIR + 'server/',

        Util                = require(DIR           + 'util'),
        format              = require(DIR           + 'format'),
        users               = require(DIR_SERVER    + 'users'),

        WIN32               = process.platform === 'win32';

    exports.getDirContent = function(path, callback) {
        var isString = Util.isString(path);

        if (!isString)
            Util.exec(callback, 'First parameter should be a string');
        else
            fs.readdir(path, readDir.bind(null, {
                callback    : callback,
                path        : path
            }));
    };

    /**
     * Функция читает ссылку или выводит информацию об ошибке
     * @param pError
     * @param pFiles
     */
    function readDir(params, error, files) {
        var i, n, stats, filesData, fill, name, fileParams,
            p               = params,
            dirPath         = format.addSlashToEnd(p.path);

        if (error)
             Util.exec(p.callback, error);
        else {
            /* Получаем информацию о файлах */
            n           = files.length,
            stats       = {},

            filesData   = {
                files       : files,
                stats       : stats,
                callback    : p.callback,
                path        : p.path
            },

            fill        = fillJSON.bind(null, filesData);

            if (n)
                for (i = 0; i < n; i++) {
                    name        = dirPath + files[i],

                    fileParams  =  {
                        callback    : fill,
                        count       : n,
                        name        : files[i],
                        stats       : stats,
                    };

                    fs.lstat(name, onStat.bind(null, fileParams));
                }
            else
                fillJSON(filesData);
        }
    }

    /**
     * async getting file states
     * and putting it to stats object
     */
    function onStat(params, error, stat) {
        var n, keys, p       = params;

        if (!error)
            p.stats[p.name] = stat;
        else
            p.stats[p.name] = {
                'mode'          : 0,
                'size'          : 0,
                'isDirectory'   : Util.retFalse
            };

        keys    = Object.keys(p.stats);
        n       = keys.length;

        if (p.count === n)
            Util.exec(p.callback);
    }

    function parseStats(names, stats) {
        var files;

        Util.checkArgs(arguments, ['names', 'stats']);

        files = names.map(function(name) {
            var file, isDir, size, owner, mode, modeStr,
                stat    = stats[name];
                owner   = stat.uid;

            if (stat) {
                /* Переводим права доступа в 8-ричную систему */
                modeStr = Number(stat.mode).toString(8);
                mode    = Number(modeStr);
                isDir   = stat.isDirectory();
                size    = isDir ? 'dir' : stat.size;
            }

            file = {
                'name'  : name,
                'size'  : format.size(size),
                'owner' : owner,
                'mode'  : format.permissions.symbolic(mode)
            };

            return file;
        });

        return files;
    }

    /**
     * Function fill JSON by file stats
     *
     * @param params - { files, stats, path }
     */
    function fillJSON(params) {
        var p           = params,
            files,

            json        = {
                path    : '',
                files   : []
            };

        Util.checkArgs(arguments, ['params']);

        files       = parseStats(p.files, p.stats);
        json.files  = changeOrder(files);
        json.path   = format.addSlashToEnd(p.path);

        changeUIDToName(json, function(error) {
            p.callback(error, json);
        });
    }

    function changeUIDToName(json, callback) {
        if (WIN32)
            callback();
        else
            users.getNames(function(error, names) {
                var files = json.files;

                if (error)
                    callback(error);
                else
                    files.forEach(function(file) {
                        var owner   = file.owner;
                            owner   = names[owner];

                        if (owner)
                            file.owner   = owner;
                    });

                callback();
            });
    }

    function changeOrder(json) {
        var files   = [],
            dirs    = [],
            sorted  = [];

        json.forEach(function(current) {
            if (current.size === 'dir')
                dirs.push(current);
            else
                files.push(current);
        });

        sorted = dirs.concat(files);

        return sorted;
    }

})();
<commit_msg>chore(commander) rm " "<commit_after>(function() {
    'use strict';

    /*
        '# commander.js'                                    + '\n'  +
        '# -----------'                                     + '\n'  +
        '# Module is part of Cloud Commander,'              + '\n'  +
        '# used for getting dir content.'                   + '\n'  +
        '# and forming html content'                        + '\n'  +
        '# http://cloudcmd.io'                              + '\n');
    */

    var fs                  = require('fs'),

        DIR                 = '../',
        DIR_SERVER          = DIR + 'server/',

        Util                = require(DIR           + 'util'),
        format              = require(DIR           + 'format'),
        users               = require(DIR_SERVER    + 'users'),

        WIN32               = process.platform === 'win32';

    exports.getDirContent = function(path, callback) {
        var isString = Util.isString(path);

        if (!isString)
            Util.exec(callback, 'First parameter should be a string');
        else
            fs.readdir(path, readDir.bind(null, {
                callback    : callback,
                path        : path
            }));
    };

    /**
     * Функция читает ссылку или выводит информацию об ошибке
     * @param pError
     * @param pFiles
     */
    function readDir(params, error, files) {
        var i, n, stats, filesData, fill, name, fileParams,
            p               = params,
            dirPath         = format.addSlashToEnd(p.path);

        if (error)
             Util.exec(p.callback, error);
        else {
            /* Получаем информацию о файлах */
            n           = files.length,
            stats       = {},

            filesData   = {
                files       : files,
                stats       : stats,
                callback    : p.callback,
                path        : p.path
            },

            fill        = fillJSON.bind(null, filesData);

            if (n)
                for (i = 0; i < n; i++) {
                    name        = dirPath + files[i],

                    fileParams  =  {
                        callback    : fill,
                        count       : n,
                        name        : files[i],
                        stats       : stats,
                    };

                    fs.lstat(name, onStat.bind(null, fileParams));
                }
            else
                fillJSON(filesData);
        }
    }

    /**
     * async getting file states
     * and putting it to stats object
     */
    function onStat(params, error, stat) {
        var n, keys, p       = params;

        if (!error)
            p.stats[p.name] = stat;
        else
            p.stats[p.name] = {
                'mode'          : 0,
                'size'          : 0,
                'isDirectory'   : Util.retFalse
            };

        keys    = Object.keys(p.stats);
        n       = keys.length;

        if (p.count === n)
            Util.exec(p.callback);
    }

    function parseStats(names, stats) {
        var files;

        Util.checkArgs(arguments, ['names', 'stats']);

        files = names.map(function(name) {
            var file, isDir, size, owner, mode, modeStr,
                stat    = stats[name];
                owner   = stat.uid;

            if (stat) {
                /* Переводим права доступа в 8-ричную систему */
                modeStr = Number(stat.mode).toString(8);
                mode    = Number(modeStr);
                isDir   = stat.isDirectory();
                size    = isDir ? 'dir' : stat.size;
            }

            file = {
                'name'  : name,
                'size'  : format.size(size),
                'owner' : owner,
                'mode'  : format.permissions.symbolic(mode)
            };

            return file;
        });

        return files;
    }

    /**
     * Function fill JSON by file stats
     *
     * @param params - { files, stats, path }
     */
    function fillJSON(params) {
        var p       = params,
            files,

            json    = {
                path    : '',
                files   : []
            };

        Util.checkArgs(arguments, ['params']);

        files       = parseStats(p.files, p.stats);
        json.files  = changeOrder(files);
        json.path   = format.addSlashToEnd(p.path);

        changeUIDToName(json, function(error) {
            p.callback(error, json);
        });
    }

    function changeUIDToName(json, callback) {
        if (WIN32)
            callback();
        else
            users.getNames(function(error, names) {
                var files = json.files;

                if (error)
                    callback(error);
                else
                    files.forEach(function(file) {
                        var owner   = file.owner;
                            owner   = names[owner];

                        if (owner)
                            file.owner   = owner;
                    });

                callback();
            });
    }

    function changeOrder(json) {
        var files   = [],
            dirs    = [],
            sorted  = [];

        json.forEach(function(current) {
            if (current.size === 'dir')
                dirs.push(current);
            else
                files.push(current);
        });

        sorted = dirs.concat(files);

        return sorted;
    }

})();
<|endoftext|>


<commit_before>(function () {
    var acapela = null;
    var latest_version = 10.0;
    try {
        if (process.arch == 'ia32') {
            acapela = require('acapela/acapela.32');
        } else {
            acapela = require('acapela/acapela.64');
        }
    } catch (e) { }
    var extract = require('extract-zip');
    var request = require('request');
    var rimraf = require('rimraf');
    var fs = require('fs');
    var path = require('path');

    var tts = {
        exec: function () {
        },
        enabled: false
    };

    if (acapela) {
        tts.enabled = true;
        tts.acapela = acapela;
        var speaker = {
            listen: function (callback) {
                speaker.listeners = speaker.listeners || [];
                speaker.listeners.push(callback);
                if (!speaker.pinging) {
                    speaker.pinging = true;
                    setTimeout(speaker.ping, 100);
                }
            },
            ping: function () {
                // There is a callback on the native speak method, but I'm not smart
                // enough to figure out how to trigger a javascript callback from
                // a c callback, so I poll instead. Don't judge.
                var res = acapela.isSpeaking();
                if (res) {
                    setTimeout(speaker.ping, 50);
                } else {
                    speaker.pinging = false;
                    while (speaker.listeners && speaker.listeners.length > 0) {
                        var cb = speaker.listeners.shift();
                        cb();
                    }
                }
            }
        };
        var downloader = {
            download_file_to_location(url, file_path, progress) {
                var size = 0;
                request({
                    uri: url
                }, function (err, res, body) {
                  if(err) {
                    console.log("error downloading " + url);
                    console.log(err);
                    progress(null, null, "error downloading " + url);
                  } else {
                    console.log("got a response");
                    progress(null, null, "got a response");
                  }
                }).on('data', function (data) {
                    size = size + data.length;
                    progress(size, false, null);
                }).pipe(fs.createWriteStream(file_path)).on('close', function () {
                    progress(0, true, null);
                });
            },
            download_file: function(url, expected_size, percent_pre, percent_amount, done) {
                downloader.download_file_to_location(url, downloader.tmp_file, function (size, complete, error) {
                  if(error) {
                    console.log(error);
                  } else if(complete) {
                    done();
                  } else {
                    downloader.watcher({
                      percent: percent_pre + Math.min(1.0, size / expected_size) * percent_amount,
                      done: false
                    });
                  }
                });
            },
            assert_directory: function(dir, done) {
                fs.stat(dir, function(err, stats) {
                    if(err && err.errno === 34) {
                        fs.mkdir(dir, function() {
                            done();
                        });
                    } else {
                        done();
                    }
                });
            },
            unzip_file_to_location: function(file_path, dir, progress) {
                var entries = 0;
                downloader.assert_directory(dir, function () {
                    var full_path = path.resolve(dir);
                    console.log("unzipping to " + full_path);
                    extract(downloader.tmp_file, {
                        dir: full_path, onEntry: function () {
                            entries++;
                            progress(entries, false, null);
                        }
                    }, function (err) {
                        if (err) {
                            console.log("unzip error", err);
                        }
                        fs.unlink(downloader.tmp_file);
                        progress(0, true, null);
                    });
                });
            },
            unzip_file: function(language_dir, n_entries, percent_pre, percent_amount, done) {
                downloader.unzip_file_to_location(downloader.tmp_file, language_dir, function(entries, complete, error) {
                  if(error) {
                    console.log(error);
                  } else if(complete) {
                    done();
                  } else {
                    downloader.watcher({
                      percent: percent_pre + (Math.min(1.0, (entries / n_entries)) * percent_amount),
                      done: false
                    });
                  }
                });
            },
            download_voice: function (opts) {
                var dir_id = opts.voice_id.replace(/^acap:/, '');
                var base_dir = opts.base_dir || './data';
                var bin_dir = path.resolve(base_dir, 'bin');
                var data_dir = path.resolve(base_dir, 'data');
                var language_dir = path.resolve(base_dir, 'data', opts.language_dir);
                downloader.tmp_file = path.resolve(base_dir, 'tmp_download' + Math.round(Math.random() * 99999) + '.zip');
                downloader.watcher = downloader.watcher || function() { };

                fs.unlink(downloader.tmp_file, function () {
                    var assert_data_directory = function() {
                        console.log("asserting data directory");
                        downloader.assert_directory(data_dir, assert_bin_directory);
                    };
                    var assert_bin_directory = function() {
                        console.log("asserting bin directory");
                        downloader.assert_directory(bin_dir, function() {
                            console.log("checking for existing bin files");
                            fs.readdir(bin_dir, function(err, list) {
                                if(list.indexOf('Selector2.conf') !== -1) {
                                    fs.readFile(path.resolve(bin_dir, 'Selector2.conf'), 'utf-8', function(err, data) {
                                        // check version number
                                        console.log(data);
                                        var version = data.match(/Version=([\d_]+)/)[1];
                                        version = parseFloat(version.split(/_/).slice(0, 1).join('.'));
                                        check_for_binaries({version: version});
                                    });
                                } else {
                                    console.log("no bin version data found");
                                    check_for_binaries();
                                }
                            })
                        })
                    }
                    var check_for_binaries = function(data) {
                        // if binaries are defined and match, continue,
                        // otherwise download and unzip them
                        if(data && data.version == latest_version) {
                            console.log("binaries already in place");
                            download_language();
                        } else {
                            var download_binaries = function() {
                                console.log("downloading binaries...");
                                downloader.download_file(opts.binary_url, 0, 0, unzip_binaries);
                            };
                            var unzip_binaries = function() {
                                console.log("unzipping binaries...");
                                download_bin.unzip_file(bin_dir, 0, 0, download_language);
                            };
                            download_binaries();
                        }
                    };
                    var download_language = function () {
                        console.log('downloading language...');
                        downloader.download_file(opts.language_url, (5 * 1024 * 1024), 0, 0.10, unzip_language);
                    };
                    var unzip_language = function() {
                        console.log('unzipping language...');
                        downloader.unzip_file(language_dir, 10, 0.10, 0.05, download_voice);
                    };
                    var download_voice = function() {
                        console.log('downloading voice...');
                        downloader.download_file(opts.voice_url, (50 * 1024 * 1024), 0.15, 0.65, unzip_voice);
                    };
                    var unzip_voice = function() {
                        console.log('unzipping voice...');
                        downloader.unzip_file(language_dir, 20, 0.85, 0.15, done);
                    };
                    var done = function() {
                        downloader.watcher({
                            percent: 1.0,
                            done: true
                        });
                    };
                    assert_data_directory();
                });
            },
            delete_voice: function(opts) {
                var dir_id = opts.voice_id.replace(/^acap:/, '');
                var found_dir = null;
                var language_dir = path.resolve(opts.base_dir || './data', opts.language_dir);
                fs.readdir(language_dir, function(err, list) {
                    for(var idx = 0; idx < list.length; idx++) {
                        var fn = list[idx];
                        var re = new RegExp(dir_id + "[^A-Za-z]", 'i');
                        if(fn.match(re)) {
                            found_dir = fn;
                        }
                    }
                    if (found_dir) {
                        rimraf(language_dir + '/' + found_dir, function () {
                            if (opts.success) {
                                opts.success();
                            }
                        });
                    } else {
                        if (opts.success) {
                            opts.success({ message: "no matching directory found" });
                        }
                    }
                });
            },
            watch: function (callback) {
                downloader.watcher = callback;
            }
        };
        tts.exec = function (method, opts) {
            opts = opts || {};
            if (method == 'speakText') {
                speaker.listen(opts.success);
                if (!tts.voice_id_map) {
                    tts.getAvailableVoices();
                }
                if (tts.voice_id_map && tts.voice_id_map[opts.voice_id]) {
                    opts.voice_key = tts.voice_id_map[opts.voice_id];
                    acapela.openVoice(opts.voice_key);
                }
                if (opts.volume) {
                    opts.volume = Math.min(Math.max(0, opts.volume * 100), 150);
                }
                if (opts.rate) {
                    opts.rate = Math.min(Math.max(30, opts.rate * 100), 300);
                }
                if (opts.pitch) {
                    opts.pitch = Math.min(Math.max(50, opts.pitch * 100), 150);
                }
                opts.success = function (res) { };
            }
            var res = acapela[method](opts);
            if (res && res.ready !== false) {
                if (opts.success) {
                    opts.success(res);
                }
            } else {
                if (opts.error) {
                    opts.error({ error: "negative response to " + method });
                }
            }
        }
        var keys = ['init', 'status', 'getAvailableVoices', 'downloadVoice', 'deleteVoice', 'speakText', 'stopSpeakingText'];
        for (var idx = 0; idx < keys.length; idx++) {
            (function (method) {
                tts[method] = function (opts) {
                    tts.exec(method, opts);
                }
            })(keys[idx]);
        }
        tts.reload = function (opts) {
          var teardown = tts.exec('teardown');
          var init = tts.exec('init');
          if(opts && opts.success) {
            opts.success({
              teardown: teardown,
              setup: setup
            });
          }
        };
        tts.getAvailableVoices = function (opts) {
            opts = opts || {};
            console.log("getting available voices");
            var raw_list = acapela.getAvailableVoices();
            var new_list = [];
            tts.voice_id_map = {};
            for (var idx = 0; idx < raw_list.length; idx++) {
                var voice = raw_list[idx];
                voice.raw_voice_id = voice.voice_id;
                voice.voice_id = 'acap:' + voice.raw_voice_id.split(/[^A-Za-z-]/)[0];
                tts.voice_id_map[voice.voice_id] = voice.raw_voice_id;
                new_list.push(voice);
            }
            if (opts.success) {
                opts.success(new_list);
            }
        };
        tts.downloadVoice = function(opts) {
            downloader.watch(opts.progress || opts.success);
            downloader.download_voice(opts || {});
        };
        tts.deleteVoice = function(opts) {
            downloader.delete_voice(opts || {});
        };
        tts.download_file = function(url, file_path, progress) {
            downloader.download_file_to_location(url, file_path, progress);
        };
        tts.unzip_file = function(file_path, dir_path, progress) {
            downloader.unzip_file_to_location(file_path, dir_path, progress);
        };
    }

    module.exports = tts;
})();<commit_msg>don't hard-code version<commit_after>(function () {
    var acapela = null;
    try {
        if (process.arch == 'ia32') {
            acapela = require('acapela/acapela.32');
        } else {
            acapela = require('acapela/acapela.64');
        }
    } catch (e) { }
    var extract = require('extract-zip');
    var request = require('request');
    var rimraf = require('rimraf');
    var fs = require('fs');
    var path = require('path');

    var tts = {
        exec: function () {
        },
        enabled: false
    };

    if (acapela) {
        tts.enabled = true;
        tts.acapela = acapela;
        var speaker = {
            listen: function (callback) {
                speaker.listeners = speaker.listeners || [];
                speaker.listeners.push(callback);
                if (!speaker.pinging) {
                    speaker.pinging = true;
                    setTimeout(speaker.ping, 100);
                }
            },
            ping: function () {
                // There is a callback on the native speak method, but I'm not smart
                // enough to figure out how to trigger a javascript callback from
                // a c callback, so I poll instead. Don't judge.
                var res = acapela.isSpeaking();
                if (res) {
                    setTimeout(speaker.ping, 50);
                } else {
                    speaker.pinging = false;
                    while (speaker.listeners && speaker.listeners.length > 0) {
                        var cb = speaker.listeners.shift();
                        cb();
                    }
                }
            }
        };
        var downloader = {
            download_file_to_location(url, file_path, progress) {
                var size = 0;
                request({
                    uri: url
                }, function (err, res, body) {
                  if(err) {
                    console.log("error downloading " + url);
                    console.log(err);
                    progress(null, null, "error downloading " + url);
                  } else {
                    console.log("got a response");
                    progress(null, null, "got a response");
                  }
                }).on('data', function (data) {
                    size = size + data.length;
                    progress(size, false, null);
                }).pipe(fs.createWriteStream(file_path)).on('close', function () {
                    progress(0, true, null);
                });
            },
            download_file: function(url, expected_size, percent_pre, percent_amount, done) {
                downloader.download_file_to_location(url, downloader.tmp_file, function (size, complete, error) {
                  if(error) {
                    console.log(error);
                  } else if(complete) {
                    done();
                  } else {
                    downloader.watcher({
                      percent: percent_pre + Math.min(1.0, size / expected_size) * percent_amount,
                      done: false
                    });
                  }
                });
            },
            assert_directory: function(dir, done) {
                fs.stat(dir, function(err, stats) {
                    if(err && err.errno === 34) {
                        fs.mkdir(dir, function() {
                            done();
                        });
                    } else {
                        done();
                    }
                });
            },
            unzip_file_to_location: function(file_path, dir, progress) {
                var entries = 0;
                downloader.assert_directory(dir, function () {
                    var full_path = path.resolve(dir);
                    console.log("unzipping to " + full_path);
                    extract(downloader.tmp_file, {
                        dir: full_path, onEntry: function () {
                            entries++;
                            progress(entries, false, null);
                        }
                    }, function (err) {
                        if (err) {
                            console.log("unzip error", err);
                        }
                        fs.unlink(downloader.tmp_file);
                        progress(0, true, null);
                    });
                });
            },
            unzip_file: function(language_dir, n_entries, percent_pre, percent_amount, done) {
                downloader.unzip_file_to_location(downloader.tmp_file, language_dir, function(entries, complete, error) {
                  if(error) {
                    console.log(error);
                  } else if(complete) {
                    done();
                  } else {
                    downloader.watcher({
                      percent: percent_pre + (Math.min(1.0, (entries / n_entries)) * percent_amount),
                      done: false
                    });
                  }
                });
            },
            download_voice: function (opts) {
                var dir_id = opts.voice_id.replace(/^acap:/, '');
                var base_dir = opts.base_dir || './data';
                var bin_dir = path.resolve(base_dir, 'bin');
                var data_dir = path.resolve(base_dir, 'data');
                var language_dir = path.resolve(base_dir, 'data', opts.language_dir);
                downloader.tmp_file = path.resolve(base_dir, 'tmp_download' + Math.round(Math.random() * 99999) + '.zip');
                downloader.watcher = downloader.watcher || function() { };

                fs.unlink(downloader.tmp_file, function () {
                    var assert_data_directory = function() {
                        console.log("asserting data directory");
                        downloader.assert_directory(data_dir, assert_bin_directory);
                    };
                    var assert_bin_directory = function() {
                        console.log("asserting bin directory");
                        downloader.assert_directory(bin_dir, function() {
                            console.log("checking for existing bin files");
                            fs.readdir(bin_dir, function(err, list) {
                                if(list.indexOf('Selector2.conf') !== -1) {
                                    fs.readFile(path.resolve(bin_dir, 'Selector2.conf'), 'utf-8', function(err, data) {
                                        // check version number
                                        console.log(data);
                                        var version = data.match(/Version=([\d_]+)/)[1];
                                        version = parseFloat(version.split(/_/).slice(0, 1).join('.'));
                                        check_for_binaries({version: version});
                                    });
                                } else {
                                    console.log("no bin version data found");
                                    check_for_binaries();
                                }
                            })
                        })
                    }
                    var check_for_binaries = function(data) {
                        // if binaries are defined and match, continue,
                        // otherwise download and unzip them
                        if(data && opts.acapela_version && data.version == opts.acapela_version) {
                            console.log("binaries already in place");
                            download_language();
                        } else {
                            var download_binaries = function() {
                                console.log("downloading binaries...");
                                downloader.download_file(opts.binary_url, 0, 0, unzip_binaries);
                            };
                            var unzip_binaries = function() {
                                console.log("unzipping binaries...");
                                download_bin.unzip_file(bin_dir, 0, 0, download_language);
                            };
                            download_binaries();
                        }
                    };
                    var download_language = function () {
                        console.log('downloading language...');
                        downloader.download_file(opts.language_url, (5 * 1024 * 1024), 0, 0.10, unzip_language);
                    };
                    var unzip_language = function() {
                        console.log('unzipping language...');
                        downloader.unzip_file(language_dir, 10, 0.10, 0.05, download_voice);
                    };
                    var download_voice = function() {
                        console.log('downloading voice...');
                        downloader.download_file(opts.voice_url, (50 * 1024 * 1024), 0.15, 0.65, unzip_voice);
                    };
                    var unzip_voice = function() {
                        console.log('unzipping voice...');
                        downloader.unzip_file(language_dir, 20, 0.85, 0.15, done);
                    };
                    var done = function() {
                        downloader.watcher({
                            percent: 1.0,
                            done: true
                        });
                    };
                    assert_data_directory();
                });
            },
            delete_voice: function(opts) {
                var dir_id = opts.voice_id.replace(/^acap:/, '');
                var found_dir = null;
                var language_dir = path.resolve(opts.base_dir || './data', opts.language_dir);
                fs.readdir(language_dir, function(err, list) {
                    for(var idx = 0; idx < list.length; idx++) {
                        var fn = list[idx];
                        var re = new RegExp(dir_id + "[^A-Za-z]", 'i');
                        if(fn.match(re)) {
                            found_dir = fn;
                        }
                    }
                    if (found_dir) {
                        rimraf(language_dir + '/' + found_dir, function () {
                            if (opts.success) {
                                opts.success();
                            }
                        });
                    } else {
                        if (opts.success) {
                            opts.success({ message: "no matching directory found" });
                        }
                    }
                });
            },
            watch: function (callback) {
                downloader.watcher = callback;
            }
        };
        tts.exec = function (method, opts) {
            opts = opts || {};
            if (method == 'speakText') {
                speaker.listen(opts.success);
                if (!tts.voice_id_map) {
                    tts.getAvailableVoices();
                }
                if (tts.voice_id_map && tts.voice_id_map[opts.voice_id]) {
                    opts.voice_key = tts.voice_id_map[opts.voice_id];
                    acapela.openVoice(opts.voice_key);
                }
                if (opts.volume) {
                    opts.volume = Math.min(Math.max(0, opts.volume * 100), 150);
                }
                if (opts.rate) {
                    opts.rate = Math.min(Math.max(30, opts.rate * 100), 300);
                }
                if (opts.pitch) {
                    opts.pitch = Math.min(Math.max(50, opts.pitch * 100), 150);
                }
                opts.success = function (res) { };
            }
            var res = acapela[method](opts);
            if (res && res.ready !== false) {
                if (opts.success) {
                    opts.success(res);
                }
            } else {
                if (opts.error) {
                    opts.error({ error: "negative response to " + method });
                }
            }
        }
        var keys = ['init', 'status', 'getAvailableVoices', 'downloadVoice', 'deleteVoice', 'speakText', 'stopSpeakingText'];
        for (var idx = 0; idx < keys.length; idx++) {
            (function (method) {
                tts[method] = function (opts) {
                    tts.exec(method, opts);
                }
            })(keys[idx]);
        }
        tts.reload = function (opts) {
          var teardown = tts.exec('teardown');
          var init = tts.exec('init');
          if(opts && opts.success) {
            opts.success({
              teardown: teardown,
              setup: setup
            });
          }
        };
        tts.getAvailableVoices = function (opts) {
            opts = opts || {};
            console.log("getting available voices");
            var raw_list = acapela.getAvailableVoices();
            var new_list = [];
            tts.voice_id_map = {};
            for (var idx = 0; idx < raw_list.length; idx++) {
                var voice = raw_list[idx];
                voice.raw_voice_id = voice.voice_id;
                voice.voice_id = 'acap:' + voice.raw_voice_id.split(/[^A-Za-z-]/)[0];
                tts.voice_id_map[voice.voice_id] = voice.raw_voice_id;
                new_list.push(voice);
            }
            if (opts.success) {
                opts.success(new_list);
            }
        };
        tts.downloadVoice = function(opts) {
            downloader.watch(opts.progress || opts.success);
            downloader.download_voice(opts || {});
        };
        tts.deleteVoice = function(opts) {
            downloader.delete_voice(opts || {});
        };
        tts.download_file = function(url, file_path, progress) {
            downloader.download_file_to_location(url, file_path, progress);
        };
        tts.unzip_file = function(file_path, dir_path, progress) {
            downloader.unzip_file_to_location(file_path, dir_path, progress);
        };
    }

    module.exports = tts;
})();<|endoftext|>