<commit_before>/*
Copyright 2016 First People's Cultural Council

Licensed 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.
*/
import React, { Component, PropTypes } from 'react'
import Immutable, { Map } from 'immutable'
import provide from 'react-redux-provide'
import selectn from 'selectn'

import PromiseWrapper from 'views/components/Document/PromiseWrapper'

import ProviderHelpers from 'common/ProviderHelpers'
import DocumentListView from 'views/components/Document/DocumentListView'
import DocumentListViewDatatable from 'views/components/Document/DocumentListViewDatatable'
import DataListView from 'views/pages/explore/dialect/learn/base/data-list-view'
import IntlService from 'views/services/intl'

const intl = IntlService.instance
/**
 * List view for categories
 */
@provide
class ListView extends DataListView {
  static defaultProps = {
    DISABLED_SORT_COLS: ['state', 'parent'],
    DEFAULT_PAGE: 1,
    DEFAULT_PAGE_SIZE: 100,
    DEFAULT_LANGUAGE: 'english',
    DEFAULT_SORT_COL: 'fv:custom_order',
    DEFAULT_SORT_TYPE: 'asc',
    dialect: null,
    filter: new Map(),
    gridListView: false,
    gridCols: 4,
    useDatatable: false,
  }

  static propTypes = {
    properties: PropTypes.object.isRequired,
    windowPath: PropTypes.string.isRequired,
    splitWindowPath: PropTypes.array.isRequired,
    pushWindowPath: PropTypes.func.isRequired,
    computeLogin: PropTypes.object.isRequired,
    fetchDialect2: PropTypes.func.isRequired,
    fetchCategories: PropTypes.func.isRequired,
    computeDialect2: PropTypes.object.isRequired,
    dialect: PropTypes.object,
    computeCategories: PropTypes.object.isRequired,
    routeParams: PropTypes.object.isRequired,
    categoriesPath: PropTypes.string.isRequired,
    filter: PropTypes.object,
    data: PropTypes.string,
    gridListView: PropTypes.bool,
    gridCols: PropTypes.number,
    action: PropTypes.func,

    DISABLED_SORT_COLS: PropTypes.array,
    DEFAULT_PAGE: PropTypes.number,
    DEFAULT_PAGE_SIZE: PropTypes.number,
    DEFAULT_SORT_COL: PropTypes.string,
    DEFAULT_SORT_TYPE: PropTypes.string,
    useDatatable: PropTypes.bool,
  }

  constructor(props, context) {
    super(props, context)

    this.state = {
      columns: [
        {
          name: 'title',
          title: intl.trans('category', 'Category', 'first'),
          render: (v, data, cellProps) => v,
        },
        {
          name: 'parent',
          title: intl.trans('views.pages.explore.dialect.learn.words.parent_category', 'Parent Category', 'words'),
          render: (v, data, cellProps) => {
            const parentCategory = selectn('contextParameters.parentDoc.title', data)
            return parentCategory === 'Shared Categories' ? '' : parentCategory
          },
        },
      ],
      sortInfo: {
        uiSortOrder: [],
        currentSortCols: this.props.DEFAULT_SORT_COL,
        currentSortType: this.props.DEFAULT_SORT_TYPE,
      },
      pageInfo: {
        page: this.props.DEFAULT_PAGE,
        pageSize: this.props.DEFAULT_PAGE_SIZE,
      },
    }

    // Bind methods to 'this'
    ;[
      '_onNavigateRequest',
      '_onEntryNavigateRequest',
      '_handleRefetch',
      '_handleSortChange',
      '_handleColumnOrderChange',
      '_resetColumns',
    ].forEach((method) => (this[method] = this[method].bind(this)))
  }
  // NOTE: DataListView calls `fetchData`
  fetchData(newProps) {
    if (newProps.dialect === null) {
      newProps.fetchDialect2(newProps.routeParams.dialect_path)
    }
    this._fetchListViewData(
      newProps,
      newProps.DEFAULT_PAGE,
      newProps.DEFAULT_PAGE_SIZE,
      newProps.DEFAULT_SORT_TYPE,
      newProps.DEFAULT_SORT_COL
    )
  }

  _onEntryNavigateRequest(item) {
    if (this.props.action) {
      this.props.action(item)
    } else {
      this.props.pushWindowPath(
        `/${this.props.routeParams.theme}${item.path.replace('Dictionary', `words/categories/${item.uid}`)}`
      )
    }
  }

  _fetchListViewData(props, pageIndex, pageSize, sortOrder, sortBy) {
    let currentAppliedFilter = ''

    if (props.filter.has('currentAppliedFilter')) {
      currentAppliedFilter = Object.values(props.filter.get('currentAppliedFilter').toJS()).join('')
    }

    props.fetchCategories(
      this.props.categoriesPath,
      `${currentAppliedFilter}&currentPageIndex=${pageIndex -
        1}&pageSize=${pageSize}&sortOrder=${sortOrder}&sortBy=${sortBy}`
    )
  }

  render() {
    const computeEntities = Immutable.fromJS([
      {
        id: this.props.categoriesPath,
        entity: this.props.computeCategories,
      },
      {
        id: this.props.routeParams.dialect_path,
        entity: this.props.computeDialect2,
      },
    ])

    const computeCategories = ProviderHelpers.getEntry(this.props.computeCategories, this.props.categoriesPath)
    const computeDialect2 = ProviderHelpers.getEntry(this.props.computeDialect2, this.props.routeParams.dialect_path)

    const DocumentView = this.props.useDatatable ? (
      <DocumentListViewDatatable
        objectDescriptions="categories"
        type="FVCategory"
        data={computeCategories}
        gridCols={this.props.gridCols}
        gridListView={this.props.gridListView}
        refetcher={this._handleRefetch}
        onSortChange={this._handleSortChange}
        onSelectionChange={this._onEntryNavigateRequest}
        page={this.state.pageInfo.page}
        pageSize={this.state.pageInfo.pageSize}
        onColumnOrderChange={this._handleColumnOrderChange}
        columns={this.state.columns}
        sortInfo={this.state.sortInfo.uiSortOrder}
        className="browseDataGrid"
        dialect={selectn('response', computeDialect2)}
      />
    ) : (
      <DocumentListView
        objectDescriptions="categories"
        type="FVCategory"
        data={computeCategories}
        gridCols={this.props.gridCols}
        gridListView={this.props.gridListView}
        refetcher={this._handleRefetch}
        onSortChange={this._handleSortChange}
        onSelectionChange={this._onEntryNavigateRequest}
        page={this.state.pageInfo.page}
        pageSize={this.state.pageInfo.pageSize}
        onColumnOrderChange={this._handleColumnOrderChange}
        columns={this.state.columns}
        sortInfo={this.state.sortInfo.uiSortOrder}
        className="browseDataGrid"
        dialect={selectn('response', computeDialect2)}
      />
    )
    return (
      <PromiseWrapper renderOnError computeEntities={computeEntities}>
        {selectn('response.entries', computeCategories) && DocumentView}
      </PromiseWrapper>
    )
  }
}
export default ListView
<commit_msg>Reduxed: `.../learn/words/categories-list-view.js`<commit_after>/*
Copyright 2016 First People's Cultural Council

Licensed 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.
*/
import React, { PropTypes } from 'react'
import Immutable, { Map } from 'immutable'

// REDUX
import { connect } from 'react-redux'
// REDUX: actions/dispatch/func
import { fetchCategories } from 'providers/redux/reducers/fvCategory'
import { fetchDialect2 } from 'providers/redux/reducers/fvDialect'
import { pushWindowPath } from 'providers/redux/reducers/windowPath'

import selectn from 'selectn'

import PromiseWrapper from 'views/components/Document/PromiseWrapper'

import ProviderHelpers from 'common/ProviderHelpers'
import DocumentListView from 'views/components/Document/DocumentListView'
import DocumentListViewDatatable from 'views/components/Document/DocumentListViewDatatable'
import DataListView from 'views/pages/explore/dialect/learn/base/data-list-view'
import IntlService from 'views/services/intl'

const intl = IntlService.instance
/**
 * List view for categories
 */

const { bool, array, func, number, object, string } = PropTypes
class ListView extends DataListView {
  static propTypes = {
    action: func,
    categoriesPath: string.isRequired,
    data: string,
    DEFAULT_PAGE: number,
    DEFAULT_PAGE_SIZE: number,
    DEFAULT_SORT_COL: string,
    DEFAULT_SORT_TYPE: string,
    dialect: object,
    DISABLED_SORT_COLS: array,
    filter: object,
    gridCols: number,
    gridListView: bool,
    routeParams: object.isRequired,
    useDatatable: bool,

    // REDUX: reducers/state
    computeCategories: object.isRequired,
    computeDialect2: object.isRequired,
    computeLogin: object.isRequired,
    properties: object.isRequired,
    splitWindowPath: array.isRequired,
    windowPath: string.isRequired,
    // REDUX: actions/dispatch/func
    fetchCategories: func.isRequired,
    fetchDialect2: func.isRequired,
    pushWindowPath: func.isRequired,
  }
  static defaultProps = {
    DISABLED_SORT_COLS: ['state', 'parent'],
    DEFAULT_PAGE: 1,
    DEFAULT_PAGE_SIZE: 100,
    DEFAULT_LANGUAGE: 'english',
    DEFAULT_SORT_COL: 'fv:custom_order',
    DEFAULT_SORT_TYPE: 'asc',
    dialect: null,
    filter: new Map(),
    gridListView: false,
    gridCols: 4,
    useDatatable: false,
  }

  constructor(props, context) {
    super(props, context)

    this.state = {
      columns: [
        {
          name: 'title',
          title: intl.trans('category', 'Category', 'first'),
          render: (v /*, data, cellProps*/) => v,
        },
        {
          name: 'parent',
          title: intl.trans('views.pages.explore.dialect.learn.words.parent_category', 'Parent Category', 'words'),
          render: (v, data /*, cellProps*/) => {
            const parentCategory = selectn('contextParameters.parentDoc.title', data)
            return parentCategory === 'Shared Categories' ? '' : parentCategory
          },
        },
      ],
      sortInfo: {
        uiSortOrder: [],
        currentSortCols: this.props.DEFAULT_SORT_COL,
        currentSortType: this.props.DEFAULT_SORT_TYPE,
      },
      pageInfo: {
        page: this.props.DEFAULT_PAGE,
        pageSize: this.props.DEFAULT_PAGE_SIZE,
      },
    }

    // Bind methods to 'this'
    ;[
      '_onNavigateRequest',
      '_onEntryNavigateRequest',
      '_handleRefetch',
      '_handleSortChange',
      '_handleColumnOrderChange',
      '_resetColumns',
    ].forEach((method) => (this[method] = this[method].bind(this)))
  }
  // NOTE: DataListView calls `fetchData`
  fetchData(newProps) {
    if (newProps.dialect === null) {
      newProps.fetchDialect2(newProps.routeParams.dialect_path)
    }
    this._fetchListViewData(
      newProps,
      newProps.DEFAULT_PAGE,
      newProps.DEFAULT_PAGE_SIZE,
      newProps.DEFAULT_SORT_TYPE,
      newProps.DEFAULT_SORT_COL
    )
  }

  _onEntryNavigateRequest(item) {
    if (this.props.action) {
      this.props.action(item)
    } else {
      this.props.pushWindowPath(
        `/${this.props.routeParams.theme}${item.path.replace('Dictionary', `words/categories/${item.uid}`)}`
      )
    }
  }

  _fetchListViewData(props, pageIndex, pageSize, sortOrder, sortBy) {
    let currentAppliedFilter = ''

    if (props.filter.has('currentAppliedFilter')) {
      currentAppliedFilter = Object.values(props.filter.get('currentAppliedFilter').toJS()).join('')
    }

    props.fetchCategories(
      this.props.categoriesPath,
      `${currentAppliedFilter}&currentPageIndex=${pageIndex -
        1}&pageSize=${pageSize}&sortOrder=${sortOrder}&sortBy=${sortBy}`
    )
  }

  render() {
    const computeEntities = Immutable.fromJS([
      {
        id: this.props.categoriesPath,
        entity: this.props.computeCategories,
      },
      {
        id: this.props.routeParams.dialect_path,
        entity: this.props.computeDialect2,
      },
    ])

    const computeCategories = ProviderHelpers.getEntry(this.props.computeCategories, this.props.categoriesPath)
    const computeDialect2 = ProviderHelpers.getEntry(this.props.computeDialect2, this.props.routeParams.dialect_path)

    const DocumentView = this.props.useDatatable ? (
      <DocumentListViewDatatable
        objectDescriptions="categories"
        type="FVCategory"
        data={computeCategories}
        gridCols={this.props.gridCols}
        gridListView={this.props.gridListView}
        refetcher={this._handleRefetch}
        onSortChange={this._handleSortChange}
        onSelectionChange={this._onEntryNavigateRequest}
        page={this.state.pageInfo.page}
        pageSize={this.state.pageInfo.pageSize}
        onColumnOrderChange={this._handleColumnOrderChange}
        columns={this.state.columns}
        sortInfo={this.state.sortInfo.uiSortOrder}
        className="browseDataGrid"
        dialect={selectn('response', computeDialect2)}
      />
    ) : (
      <DocumentListView
        objectDescriptions="categories"
        type="FVCategory"
        data={computeCategories}
        gridCols={this.props.gridCols}
        gridListView={this.props.gridListView}
        refetcher={this._handleRefetch}
        onSortChange={this._handleSortChange}
        onSelectionChange={this._onEntryNavigateRequest}
        page={this.state.pageInfo.page}
        pageSize={this.state.pageInfo.pageSize}
        onColumnOrderChange={this._handleColumnOrderChange}
        columns={this.state.columns}
        sortInfo={this.state.sortInfo.uiSortOrder}
        className="browseDataGrid"
        dialect={selectn('response', computeDialect2)}
      />
    )
    return (
      <PromiseWrapper renderOnError computeEntities={computeEntities}>
        {selectn('response.entries', computeCategories) && DocumentView}
      </PromiseWrapper>
    )
  }
}

// REDUX: reducers/state
const mapStateToProps = (state /*, ownProps*/) => {
  const { fvCategory, fvDialect, navigation, nuxeo, windowPath } = state

  const { properties } = navigation
  const { computeLogin } = nuxeo
  const { computeCategories } = fvCategory
  const { computeDialect2 } = fvDialect
  const { splitWindowPath, _windowPath } = windowPath

  return {
    computeCategories,
    computeDialect2,
    computeLogin,
    properties,
    splitWindowPath,
    windowPath: _windowPath,
  }
}

// REDUX: actions/dispatch/func
const mapDispatchToProps = {
  fetchCategories,
  fetchDialect2,
  pushWindowPath,
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(ListView)
<|endoftext|>


<commit_before>// Copyright 2014-2015, Renasar Technologies Inc.
/* jshint node: true */

'use strict';

var childProcess = require('child_process'),
    di = require('di');

module.exports = SnmpFactory;

di.annotate(SnmpFactory, new di.Provide('JobUtils.Snmptool'));
di.annotate(SnmpFactory, new di.Inject(
            'Q',
            'Promise',
            '_',
            'Assert',
            'JobUtils.SnmpParser'
));

function SnmpFactory(Q, Promise, _, assert, parser) {
    function SnmpTool(host, community) {
        this.host = host;
        this.community = community;
        this.mibNameMap = {};
    }

    SnmpTool.prototype.walk = function(oid) {
        var self = this;

        if (oid) {
            return Q.nfcall(
                childProcess.exec, '/usr/bin/snmpwalk -Oq -v2c -c ' +
                    self.community + ' ' + self.host + ' ' + oid,
                    {maxBuffer: 2 * 1024 * 1024});
        } else {
            var missing = _.map({ host: self.host,
                                  community: self.community,
                                  oid: oid },
                function(argValue, argName) {
                    if (!argValue) {
                        return argName;
                    }
            });
            var error = new Error("Missing required arguments: " + missing);
            return Q.reject(error);
        }
    };

    SnmpTool.prototype.get = function(oid) {
        var self = this;

        if (oid) {
            return Q.nfcall(
                childProcess.exec, '/usr/bin/snmpget -Oq -v2c -c ' +
                    self.community + ' ' + self.host + ' ' + oid);
        } else {
            var missing = _.map({ host: self.host,
                                  community: self.community,
                                  oid: oid },
                function(argValue, argName) {
                    if (!argValue) {
                        return argName;
                    }
            });
            var error = new Error("Missing required arguments: " + missing);
            return Q.reject(error);
        }
    };

    SnmpTool.prototype.getnext = function(oid) {
        var self = this;

        if (oid) {
            return Q.nfcall(
                childProcess.exec, '/usr/bin/snmpgetnext -Oq -v2c -c ' +
                    self.community + ' ' + self.host + ' ' + oid);
        } else {
            var missing = _.map({ host: self.host,
                                  community: self.community,
                                  oid: oid },
                function(argValue, argName) {
                    if (!argValue) {
                        return argName;
                    }
            });
            var error = new Error("Missing required arguments: " + missing);
            return Q.reject(error);
        }
    };

    SnmpTool.prototype.ping = function() {
        return this.get('SNMPv2-MIB::sysDescr.0');
    };

    SnmpTool.prototype.collectHostSnmp = function(oids) {
        var self = this;
        assert.arrayOfString(oids, "User specified OIDs");

        return Promise.map(oids, function (oid) {
            return self.walk(oid)
            .then(function (results) {
                return _.map(results[0].trim().split('\n'), function (result) {
                    var parsed = parser.parseSnmpData(result.trim());
                    var out = {
                        source: oid,
                        value: {}
                    };
                    out.value[parsed.oid] = parsed.value;
                    return out;
                });
            });
        });
    };

    return SnmpTool;
}
<commit_msg>Migrate snmp tool to use core ChildProcess library. Add bulkget/bulkwalk commands<commit_after>// Copyright 2014-2015, Renasar Technologies Inc.
/* jshint node: true */

'use strict';

var childProcess = require('child_process'),
    di = require('di');

module.exports = SnmpFactory;

di.annotate(SnmpFactory, new di.Provide('JobUtils.Snmptool'));
di.annotate(SnmpFactory, new di.Inject(
            'Assert',
            'JobUtils.SnmpParser',
            'ChildProcess',
            'Promise',
            '_'
));
function SnmpFactory(assert, parser, ChildProcess, Promise, _) {
    function SnmpTool(host, community) {
        this.host = host;
        this.community = community;
    }

    SnmpTool.prototype.runCommand = function(command, oid) {
        if (!oid) {
            var missing = _.map({ host: this.host,
                                  community: this.community,
                                  oid: oid },
                function(argValue, argName) {
                    if (!argValue) {
                        return argName;
                    }
            });
            var error = new Error("Missing required arguments: " + missing);
            return Promise.reject(error);
        }
        var args = ['-Oq', '-v2c', '-c', this.community, this.host, oid];
        var childProcess = new ChildProcess(command, args);
        return childProcess.run();
    };

    SnmpTool.prototype.walk = function(oid) {
        return this.runCommand('/usr/bin/snmpwalk', oid);
    };

    SnmpTool.prototype.get = function(oid) {
        return this.runCommand('/usr/bin/snmpget', oid);
    };

    SnmpTool.prototype.getnext = function(oid) {
        return this.runCommand('/usr/bin/snmpgetnext', oid);
    };

    SnmpTool.prototype.bulkget = function(oid) {
        return this.runCommand('/usr/bin/snmpbulkget', oid);
    };

    SnmpTool.prototype.bulkwalk = function(oid) {
        return this.runCommand('/usr/bin/snmpbulkwalk', oid);
    };

    SnmpTool.prototype.ping = function() {
        return this.get('SNMPv2-MIB::sysDescr.0');
    };

    SnmpTool.prototype.collectHostSnmp = function(oids) {
        var self = this;
        assert.arrayOfString(oids, "User specified OIDs");

        return Promise.map(oids, function (oid) {
            return self.walk(oid)
            .then(function (results) {
                return _.map(results.stdout.trim().split('\n'), function (result) {
                    var parsed = parser.parseSnmpData(result.trim());
                    var out = {
                        source: oid,
                        value: {}
                    };
                    out.value[parsed.oid] = parsed.value;
                    return out;
                });
            });
        });
    };

    return SnmpTool;
}
<|endoftext|>


<commit_before>(function() {

  QUnit.module('fabric.Gradient');

  function createGradient() {
    return new fabric.Gradient({
      coords: {
        x1: 0,
        y1: 10,
        x2: 100,
        y2: 200,
      },
      colorStops: [
        { offset: 0, color: 'red' },
        { offset: 1, color: 'green' }
      ]
    });
  }

  test('constructor', function() {
    ok(fabric.Gradient);

    var gradient = createGradient();
    ok(gradient instanceof fabric.Gradient, 'should inherit from fabric.Gradient');
  });

  test('properties', function() {
    var gradient = createGradient();

    equal(gradient.coords.x1, 0);
    equal(gradient.coords.y1, 10);
    equal(gradient.coords.x2, 100);
    equal(gradient.coords.y2, 200);

    equal(gradient.colorStops[0].offset, 0);
    equal(gradient.colorStops[0].color, 'red');

    equal(gradient.colorStops[1].offset, 1);
    equal(gradient.colorStops[1].color, 'green');
  });

  test('toObject', function() {
    var gradient = createGradient();

    ok(typeof gradient.toObject == 'function');

    var object = gradient.toObject();

    equal(object.coords.x1, gradient.coords.x1);
    equal(object.coords.x2, gradient.coords.x2);
    equal(object.coords.y1, gradient.coords.y1);
    equal(object.coords.y2, gradient.coords.y2);

    equal(object.colorStops, gradient.colorStops);
  });

  test('toLive', function() {
    var gradient = createGradient();

    ok(typeof gradient.toLive == 'function');
  });

  test('fromElement', function() {
    ok(typeof fabric.Gradient.fromElement == 'function');

    var element = fabric.document.createElement('linearGradient');
    var stop1 = fabric.document.createElement('stop');
    var stop2 = fabric.document.createElement('stop');

    stop1.setAttribute('offset', '0%');
    stop1.setAttribute('stop-color', 'white');

    stop2.setAttribute('offset', '100%');
    stop2.setAttribute('stop-color', 'black');

    element.appendChild(stop1);
    element.appendChild(stop2);

    var object = new fabric.Object({ width: 100, height: 100 });
    var gradient = fabric.Gradient.fromElement(element, object);

    ok(gradient instanceof fabric.Gradient);

    // TODO: need to double check these values

    equal(gradient.coords.x1, 0);
    equal(gradient.coords.y1, 0);

    //equal(gradient.coords.x2, 100);
    //equal(gradient.coords.y2, 100);

    equal(gradient.colorStops[0].offset, 1);
    equal(gradient.colorStops[1].offset, 0);

    equal(gradient.colorStops[0].color, 'rgb(0,0,0)');
    equal(gradient.colorStops[1].color, 'rgb(255,255,255)');
  });

  test('forObject', function() {
    ok(typeof fabric.Gradient.forObject == 'function');

    var object = new fabric.Object({ width: 50, height: 50 });

    var gradient = fabric.Gradient.forObject(object, {
      coords: {
        x1: 10,
        y1: 10,
        x2: 20,
        y2: 20,
      },
      colorStops: [
        { offset: 0, color: 'red' },
        { offset: 0.5, color: 'green' },
        { offset: 1, color: 'blue' }
      ]
    });

    ok(gradient instanceof fabric.Gradient);

    // TODO: need to double check these values

    equal(gradient.coords.x1, 10);
    equal(gradient.coords.y1, 10);

    equal(gradient.coords.x2, 20);
    equal(gradient.coords.y2, 20);
  });

})();<commit_msg>Add more tests to gradient (distinguish between linearGradient and radialGradient)<commit_after>(function() {

  QUnit.module('fabric.Gradient');

  function createLinearGradient() {
    return new fabric.Gradient({
      type: 'linear',
      coords: {
        x1: 0,
        y1: 10,
        x2: 100,
        y2: 200,
      },
      colorStops: [
        { offset: 0, color: 'red', opacity: 0 },
        { offset: 1, color: 'green' }
      ]
    });
  }

  function createRadialGradient() {
    return new fabric.Gradient({
      type: 'radial',
      coords: {
        x1: 0,
        y1: 10,
        x2: 100,
        y2: 200,
        r1: 0,
        r2: 50
      },
      colorStops: [
        { offset: 0, color: 'red' },
        { offset: 1, color: 'green', opacity: 0 }
      ]
    });
  }

  test('constructor linearGradient', function() {
    ok(fabric.Gradient);

    var gradient = createLinearGradient();
    ok(gradient instanceof fabric.Gradient, 'should inherit from fabric.Gradient');
  });

  test('constructor radialGradient', function() {
    ok(fabric.Gradient);

    var gradient = createRadialGradient();
    ok(gradient instanceof fabric.Gradient, 'should inherit from fabric.Gradient');
  });

  test('properties linearGradient', function() {
    var gradient = createLinearGradient();

    equal(gradient.coords.x1, 0);
    equal(gradient.coords.y1, 10);
    equal(gradient.coords.x2, 100);
    equal(gradient.coords.y2, 200);

    equal(gradient.type, 'linear');

    equal(gradient.colorStops[0].offset, 0);
    equal(gradient.colorStops[0].color, 'red');
    equal(gradient.colorStops[0].opacity, 0);

    equal(gradient.colorStops[1].offset, 1);
    equal(gradient.colorStops[1].color, 'green');
    ok(!('opacity' in gradient.colorStops[1]));
  });

  test('properties radialGradient', function() {
    var gradient = createRadialGradient();

    equal(gradient.coords.x1, 0);
    equal(gradient.coords.y1, 10);
    equal(gradient.coords.x2, 100);
    equal(gradient.coords.y2, 200);
    equal(gradient.coords.r1, 0);
    equal(gradient.coords.r2, 50);

    equal(gradient.type, 'radial');

    equal(gradient.colorStops[0].offset, 0);
    equal(gradient.colorStops[0].color, 'red');
    ok(!('opacity' in gradient.colorStops[0]));

    equal(gradient.colorStops[1].offset, 1);
    equal(gradient.colorStops[1].color, 'green');
    equal(gradient.colorStops[1].opacity, 0);
  });

  test('toObject linearGradient', function() {
    var gradient = createLinearGradient();

    ok(typeof gradient.toObject == 'function');

    var object = gradient.toObject();

    equal(object.coords.x1, gradient.coords.x1);
    equal(object.coords.x2, gradient.coords.x2);
    equal(object.coords.y1, gradient.coords.y1);
    equal(object.coords.y2, gradient.coords.y2);

    equal(object.type, gradient.type);

    equal(object.colorStops, gradient.colorStops);
  });

  test('toObject radialGradient', function() {
    var gradient = createRadialGradient();

    ok(typeof gradient.toObject == 'function');

    var object = gradient.toObject();

    equal(object.coords.x1, gradient.coords.x1);
    equal(object.coords.x2, gradient.coords.x2);
    equal(object.coords.y1, gradient.coords.y1);
    equal(object.coords.y2, gradient.coords.y2);
    equal(object.coords.r1, gradient.coords.r1);
    equal(object.coords.r2, gradient.coords.r2);

    equal(object.type, gradient.type);

    equal(object.colorStops, gradient.colorStops);
  });

  test('toLive linearGradient', function() {
    var gradient = createLinearGradient();

    ok(typeof gradient.toLive == 'function');
  });

  test('toLive radialGradient', function() {
    var gradient = createRadialGradient();

    ok(typeof gradient.toLive == 'function');
  });

  test('fromElement linearGradient', function() {
    ok(typeof fabric.Gradient.fromElement == 'function');

    var element = fabric.document.createElement('linearGradient');
    var stop1 = fabric.document.createElement('stop');
    var stop2 = fabric.document.createElement('stop');

    stop1.setAttribute('offset', '0%');
    stop1.setAttribute('stop-color', 'white');

    stop2.setAttribute('offset', '100%');
    stop2.setAttribute('stop-color', 'black');
    stop2.setAttribute('stop-opacity', '0');

    element.appendChild(stop1);
    element.appendChild(stop2);

    var object = new fabric.Object({ width: 100, height: 100 });
    var gradient = fabric.Gradient.fromElement(element, object);

    ok(gradient instanceof fabric.Gradient);

    // TODO: need to double check these values

    equal(gradient.coords.x1, 0);
    equal(gradient.coords.y1, 0);

    //equal(gradient.coords.x2, 100);
    //equal(gradient.coords.y2, 100);

    equal(gradient.colorStops[0].offset, 1);
    equal(gradient.colorStops[1].offset, 0);

    equal(gradient.colorStops[0].color, 'rgb(0,0,0)');
    equal(gradient.colorStops[1].color, 'rgb(255,255,255)');

    equal(gradient.colorStops[0].opacity, 0);
  });

  test('fromElement radialGradient', function() {
    ok(typeof fabric.Gradient.fromElement == 'function');

    var element = fabric.document.createElement('radialGradient');
    var stop1 = fabric.document.createElement('stop');
    var stop2 = fabric.document.createElement('stop');

    stop1.setAttribute('offset', '0%');
    stop1.setAttribute('stop-color', 'white');

    stop2.setAttribute('offset', '100%');
    stop2.setAttribute('stop-color', 'black');

    element.appendChild(stop1);
    element.appendChild(stop2);

    var object = new fabric.Object({ width: 100, height: 100 });
    var gradient = fabric.Gradient.fromElement(element, object);

    ok(gradient instanceof fabric.Gradient);

    // TODO: need to double check these values

    equal(gradient.coords.x1, 0);
    equal(gradient.coords.y1, 0);

    //equal(gradient.coords.x2, 100);
    //equal(gradient.coords.y2, 100);

    equal(gradient.colorStops[0].offset, 1);
    equal(gradient.colorStops[1].offset, 0);

    equal(gradient.colorStops[0].color, 'rgb(0,0,0)');
    equal(gradient.colorStops[1].color, 'rgb(255,255,255)');
  });

  test('forObject linearCradient', function() {
    ok(typeof fabric.Gradient.forObject == 'function');

    var object = new fabric.Object({ width: 50, height: 50 });

    var gradient = fabric.Gradient.forObject(object, {
      coords: {
        x1: 10,
        y1: 10,
        x2: 20,
        y2: 20,
      },
      colorStops: [
        { offset: 0, color: 'red', opacity: 1 },
        { offset: 0.5, color: 'green', opacity: 0},
        { offset: 1, color: 'blue', opacity: 0.5 }
      ]
    });

    ok(gradient instanceof fabric.Gradient);

    equal(gradient.type, 'linear');

    // TODO: need to double check these values

    equal(gradient.coords.x1, 10);
    equal(gradient.coords.y1, 10);

    equal(gradient.coords.x2, 20);
    equal(gradient.coords.y2, 20);

    equal(gradient.colorStops[0].offset, 0);
    equal(gradient.colorStops[1].offset, 0.5);
    equal(gradient.colorStops[2].offset, 1);

    equal(gradient.colorStops[0].color, 'red');
    equal(gradient.colorStops[1].color, 'green');
    equal(gradient.colorStops[2].color, 'blue');

    equal(gradient.colorStops[0].opacity, 1);
    equal(gradient.colorStops[1].opacity, 0);
    equal(gradient.colorStops[2].opacity, 0.5);
  });

  test('forObject radialGradient', function() {
    ok(typeof fabric.Gradient.forObject == 'function');

    var object = new fabric.Object({ width: 50, height: 50 });

    var gradient = fabric.Gradient.forObject(object, {
      type: 'radial',
      coords: {
        x1: 10,
        y1: 10,
        x2: 20,
        y2: 20,
        r1: 0,
        r2: 10
      },
      colorStops: [
        { offset: 0, color: 'red', opacity: 1 },
        { offset: 0.5, color: 'green', opacity: 0},
        { offset: 1, color: 'blue', opacity: 0.5 }
      ]
    });

    ok(gradient instanceof fabric.Gradient);

    equal(gradient.type, 'radial');

    // TODO: need to double check these values

    equal(gradient.coords.x1, 10);
    equal(gradient.coords.y1, 10);

    equal(gradient.coords.x2, 20);
    equal(gradient.coords.y2, 20);

    equal(gradient.coords.r1, 0);
    equal(gradient.coords.r2, 10);

    equal(gradient.colorStops[0].offset, 0);
    equal(gradient.colorStops[1].offset, 0.5);
    equal(gradient.colorStops[2].offset, 1);

    equal(gradient.colorStops[0].color, 'red');
    equal(gradient.colorStops[1].color, 'green');
    equal(gradient.colorStops[2].color, 'blue');

    equal(gradient.colorStops[0].opacity, 1);
    equal(gradient.colorStops[1].opacity, 0);
    equal(gradient.colorStops[2].opacity, 0.5);
  });

})();<|endoftext|>


<commit_before>
module.exports = get

var GET = require("./request.js").GET
  , fs = require("graceful-fs")
  , npm = require("../../npm.js")
  , path = require("path")
  , log = require("../log.js")
  , mkdir = require("../mkdir-p.js")
  , cacheStat = null

function get (project, version, timeout, nofollow, staleOk, cb) {
  if (typeof cb !== "function") cb = staleOk, staleOk = false
  if (typeof cb !== "function") cb = nofollow, nofollow = false
  if (typeof cb !== "function") cb = timeout, timeout = -1
  if (typeof cb !== "function") cb = version, version = null
  if (typeof cb !== "function") cb = project, project = null
  if (typeof cb !== "function") {
    throw new Error("No callback provided to registry.get")
  }

  if ( process.env.COMP_CWORD !== undefined
    && process.env.COMP_LINE !== undefined
    && process.env.COMP_POINT !== undefined
    ) timeout = Math.max(timeout, 60000)

  var uri = []
  uri.push(project || "")
  if (version) uri.push(version)
  uri = uri.join("/")

  // /-/all is special.
  // It uses timestamp-based caching and partial updates,
  // because it is a monster.
  if (uri === "/-/all") {
    return requestAll(cb)
  }

  var cache = path.join(npm.cache, uri, ".cache.json")
  fs.stat(cache, function (er, stat) {
    if (!er) fs.readFile(cache, function (er, data) {
      try { data = JSON.parse(data) }
      catch (ex) { data = null }
      get_(uri, timeout, cache, stat, data, nofollow, staleOk, cb)
    })
    else get_(uri, timeout, cache, null, null, nofollow, staleOk, cb)
  })
}

function requestAll (cb) {
  var cache = path.join(npm.cache, "/-/all", ".cache.json")

  mkdir(path.join(npm.cache, "-", "all"), function (er) {
    fs.readFile(cache, function (er, data) {
      if (er) return requestAll_(0, {}, cb)
      try {
        data = JSON.parse(data)
      } catch (ex) {
        fs.writeFile(cache, "{}", function (er) {
          if (er) return cb(new Error("Broken cache. "
                                     +"Please run 'npm cache clean' "
                                     +"and try again."))
          return requestAll_(0, {}, cb)
        })
      }
      var t = +data._updated || 0
      requestAll_(t, data, cb)
    })
  })
}

function requestAll_ (c, data, cb) {
  // use the cache and update in the background if it's not too old
  if (Date.now() - c < 60000) {
    cb(null, data)
    cb = function () {}
  }

  var uri = "/-/all/since?stale=update_after&startkey=" + c

  if (c === 0) {
    log.warn("Building the local index for the first time, please be patient")
    uri = "/-/all"
  }

  var cache = path.join(npm.cache, "-/all", ".cache.json")
  GET(uri, function (er, updates, _, res) {
    if (er) return cb(er, data)
    var headers = res.headers
      , updated = Date.parse(headers.date)
    Object.keys(updates).forEach(function (p) {
      data[p] = updates[p]
    })
    data._updated = updated
    fs.writeFile( cache, JSON.stringify(data)
                , function (er) {
      delete data._updated
      return cb(er, data)
    })
  })
}

function get_ (uri, timeout, cache, stat, data, nofollow, staleOk, cb) {
  var etag
  if (data && data._etag) etag = data._etag
  if (timeout && timeout > 0 && stat && data) {
    if ((Date.now() - stat.mtime.getTime())/1000 < timeout) {
      log.verbose("not expired, no request", "registry.get " +uri)
      delete data._etag
      return cb(null, data, JSON.stringify(data), {statusCode:304})
    }
    if (staleOk) {
      log.verbose("staleOk, background update", "registry.get " +uri)
      delete data._etag
      process.nextTick(cb.bind( null, null, data, JSON.stringify(data)
                              , {statusCode: 304} ))
      cb = function () {}
    }
  }

  GET(uri, etag, nofollow, function (er, remoteData, raw, response) {
    // if we get an error talking to the registry, but we have it
    // from the cache, then just pretend we got it.
    if (er && cache && data && !data.error) {
      er = null
      response = {statusCode: 304}
    }

    if (response) {
      log.silly([response.statusCode, response.headers], "get cb")
      if (response.statusCode === 304 && etag) {
        remoteData = data
        log.verbose(uri+" from cache", "etag")
      }
    }

    data = remoteData
    if (!data) {
      er = new Error("failed to fetch from registry: " + uri)
    }

    if (er) return cb(er, data, raw, response)

    // just give the write the old college try.  if it fails, whatever.
    function saved () {
      delete data._etag
      cb(er, data, raw, response)
    }

    saveToCache(cache, data, saved)
  })
}

function saveToCache (cache, data, saved) {
  if (cacheStat) {
    return saveToCache_(cache, data, cacheStat.uid, cacheStat.gid, saved)
  }
  fs.stat(npm.cache, function (er, st) {
    if (er) {
      return fs.stat(process.env.HOME || "", function (er, st) {
        // if this fails, oh well.
        if (er) return saved()
        cacheStat = st
        return saveToCache(cache, data, saved)
      })
    }
    cacheStat = st || { uid: null, gid: null }
    return saveToCache(cache, data, saved)
  })
}

function saveToCache_ (cache, data, uid, gid, saved) {
  mkdir(path.dirname(cache), npm.modes.exec, uid, gid, function (er) {
    if (er) return saved()
    fs.writeFile(cache, JSON.stringify(data), function (er) {
      if (er || uid === null || gid === null) {
        return saved()
      }
      fs.chown(cache, uid, gid, saved)
    })
  })
}
<commit_msg>http faiure: Use original error, not a new one<commit_after>
module.exports = get

var GET = require("./request.js").GET
  , fs = require("graceful-fs")
  , npm = require("../../npm.js")
  , path = require("path")
  , log = require("../log.js")
  , mkdir = require("../mkdir-p.js")
  , cacheStat = null

function get (project, version, timeout, nofollow, staleOk, cb) {
  if (typeof cb !== "function") cb = staleOk, staleOk = false
  if (typeof cb !== "function") cb = nofollow, nofollow = false
  if (typeof cb !== "function") cb = timeout, timeout = -1
  if (typeof cb !== "function") cb = version, version = null
  if (typeof cb !== "function") cb = project, project = null
  if (typeof cb !== "function") {
    throw new Error("No callback provided to registry.get")
  }

  if ( process.env.COMP_CWORD !== undefined
    && process.env.COMP_LINE !== undefined
    && process.env.COMP_POINT !== undefined
    ) timeout = Math.max(timeout, 60000)

  var uri = []
  uri.push(project || "")
  if (version) uri.push(version)
  uri = uri.join("/")

  // /-/all is special.
  // It uses timestamp-based caching and partial updates,
  // because it is a monster.
  if (uri === "/-/all") {
    return requestAll(cb)
  }

  var cache = path.join(npm.cache, uri, ".cache.json")
  fs.stat(cache, function (er, stat) {
    if (!er) fs.readFile(cache, function (er, data) {
      try { data = JSON.parse(data) }
      catch (ex) { data = null }
      get_(uri, timeout, cache, stat, data, nofollow, staleOk, cb)
    })
    else get_(uri, timeout, cache, null, null, nofollow, staleOk, cb)
  })
}

function requestAll (cb) {
  var cache = path.join(npm.cache, "/-/all", ".cache.json")

  mkdir(path.join(npm.cache, "-", "all"), function (er) {
    fs.readFile(cache, function (er, data) {
      if (er) return requestAll_(0, {}, cb)
      try {
        data = JSON.parse(data)
      } catch (ex) {
        fs.writeFile(cache, "{}", function (er) {
          if (er) return cb(new Error("Broken cache. "
                                     +"Please run 'npm cache clean' "
                                     +"and try again."))
          return requestAll_(0, {}, cb)
        })
      }
      var t = +data._updated || 0
      requestAll_(t, data, cb)
    })
  })
}

function requestAll_ (c, data, cb) {
  // use the cache and update in the background if it's not too old
  if (Date.now() - c < 60000) {
    cb(null, data)
    cb = function () {}
  }

  var uri = "/-/all/since?stale=update_after&startkey=" + c

  if (c === 0) {
    log.warn("Building the local index for the first time, please be patient")
    uri = "/-/all"
  }

  var cache = path.join(npm.cache, "-/all", ".cache.json")
  GET(uri, function (er, updates, _, res) {
    if (er) return cb(er, data)
    var headers = res.headers
      , updated = Date.parse(headers.date)
    Object.keys(updates).forEach(function (p) {
      data[p] = updates[p]
    })
    data._updated = updated
    fs.writeFile( cache, JSON.stringify(data)
                , function (er) {
      delete data._updated
      return cb(er, data)
    })
  })
}

function get_ (uri, timeout, cache, stat, data, nofollow, staleOk, cb) {
  var etag
  if (data && data._etag) etag = data._etag
  if (timeout && timeout > 0 && stat && data) {
    if ((Date.now() - stat.mtime.getTime())/1000 < timeout) {
      log.verbose("not expired, no request", "registry.get " +uri)
      delete data._etag
      return cb(null, data, JSON.stringify(data), {statusCode:304})
    }
    if (staleOk) {
      log.verbose("staleOk, background update", "registry.get " +uri)
      delete data._etag
      process.nextTick(cb.bind( null, null, data, JSON.stringify(data)
                              , {statusCode: 304} ))
      cb = function () {}
    }
  }

  GET(uri, etag, nofollow, function (er, remoteData, raw, response) {
    // if we get an error talking to the registry, but we have it
    // from the cache, then just pretend we got it.
    if (er && cache && data && !data.error) {
      er = null
      response = {statusCode: 304}
    }

    if (response) {
      log.silly([response.statusCode, response.headers], "get cb")
      if (response.statusCode === 304 && etag) {
        remoteData = data
        log.verbose(uri+" from cache", "etag")
      }
    }

    data = remoteData
    if (!data) {
      er = er || new Error("failed to fetch from registry: " + uri)
    }

    if (er) return cb(er, data, raw, response)

    // just give the write the old college try.  if it fails, whatever.
    function saved () {
      delete data._etag
      cb(er, data, raw, response)
    }

    saveToCache(cache, data, saved)
  })
}

function saveToCache (cache, data, saved) {
  if (cacheStat) {
    return saveToCache_(cache, data, cacheStat.uid, cacheStat.gid, saved)
  }
  fs.stat(npm.cache, function (er, st) {
    if (er) {
      return fs.stat(process.env.HOME || "", function (er, st) {
        // if this fails, oh well.
        if (er) return saved()
        cacheStat = st
        return saveToCache(cache, data, saved)
      })
    }
    cacheStat = st || { uid: null, gid: null }
    return saveToCache(cache, data, saved)
  })
}

function saveToCache_ (cache, data, uid, gid, saved) {
  mkdir(path.dirname(cache), npm.modes.exec, uid, gid, function (er) {
    if (er) return saved()
    fs.writeFile(cache, JSON.stringify(data), function (er) {
      if (er || uid === null || gid === null) {
        return saved()
      }
      fs.chown(cache, uid, gid, saved)
    })
  })
}
<|endoftext|>


<commit_before>describe("folderManager", function() {
    var scope,
        response_data,
        $httpBackend;
    beforeEach(angular.mock.module("feedhoos"));
    beforeEach(angular.mock.inject(function($rootScope, _$httpBackend_) {
        scope = $rootScope.$new();
        $httpBackend = _$httpBackend_;
        $httpBackend.expect("GET", "/folder/list/")
            .respond('[{"rating": 1, "type": "folder", "id": 1, "title": "title1"}, {"rating": 5, "type": "folder", "id": 2, "title": "title2"}, {"rating": 0, "type": "folder", "id": 3, "title": "title3"}]');
        response_data = [
            {"rating": 1, "type": "folder", "id": 1, "title": "title1"},
            {"rating": 5, "type": "folder", "id": 2, "title": "title2"},
            {"rating": 0, "type": "folder", "id": 3, "title": "title3"}
        ];
    }));

    it('should set', inject(function(folderManager) {
        folderManager.set(scope, function() {});
        $httpBackend.flush();
        expect(folderManager.data).toEqual(response_data);
    }));

    it('should defalt title is ---', inject(function(folderManager) {
        folderManager.set(scope, function() {});
        $httpBackend.flush();
        expect(folderManager.get_title(0)).toEqual('---');
    }));

    it('should title', inject(function(folderManager) {
        folderManager.set(scope, function() {});
        $httpBackend.flush();
        expect(folderManager.get_title(2)).toEqual('title2');
    }));
});
<commit_msg>add test for folderManager::get_title_by_feed_id()<commit_after>describe("folderManager", function() {
    var scope,
        response_data,
        defalt_id,
        $httpBackend;
    beforeEach(angular.mock.module("feedhoos"));
    beforeEach(angular.mock.inject(function($rootScope, _$httpBackend_) {
        scope = $rootScope.$new();
        defalt_id = 0;
        $httpBackend = _$httpBackend_;
        $httpBackend.expect("GET", "/folder/list/")
            .respond('[{"rating": 1, "type": "folder", "id": 1, "title": "title1"}, {"rating": 5, "type": "folder", "id": 2, "title": "title2"}, {"rating": 0, "type": "folder", "id": 3, "title": "title3"}]');
        response_data = [
            {"rating": 1, "type": "folder", "id": 1, "title": "title1"},
            {"rating": 5, "type": "folder", "id": 2, "title": "title2"},
            {"rating": 0, "type": "folder", "id": 3, "title": "title3"}
        ];
    }));

    it('should set', inject(function(folderManager) {
        folderManager.set(scope, function() {});
        $httpBackend.flush();
        expect(folderManager.data).toEqual(response_data);
    }));

    it('should defalt title is ---', inject(function(folderManager) {
        folderManager.set(scope, function() {});
        $httpBackend.flush();
        expect(folderManager.get_title(0)).toEqual('---');
    }));

    it('should title', inject(function(folderManager) {
        folderManager.set(scope, function() {});
        $httpBackend.flush();
        expect(folderManager.get_title(2)).toEqual('title2');
    }));

    it('should get_title_by_feed_id', inject(function(folderManager, bookmarkManager) {
        $httpBackend.expect("GET", "/bookmark/list/")
            .respond('{' +
                '"0": {"rating": 6, "folder_id": 0},' +
                '"1": {"rating": 3, "folder_id": 1},' +
                '"2": {"rating": 0, "folder_id": 0},' +
                '"3": {"rating": 0, "folder_id": 2},' +
                '"4": {"rating": 3, "folder_id": 0},' +
                '"5": {"rating": 0, "folder_id": 0},' +
                '"6": {"rating": 5, "folder_id": 0},' +
                '"7": {"rating": 1, "folder_id": 2}' +
            '}');
        folderManager.set(scope, function() {});
        bookmarkManager.set(scope, function() {});
        $httpBackend.flush();
        expect(folderManager.get_title_by_feed_id(2)).toEqual('---');
        expect(folderManager.get_title_by_feed_id(1)).toEqual('title1');
    }));
});
<|endoftext|>


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {
"use strict";

var XHTML_NS = "http://www.w3.org/1999/xhtml";

exports.createElement = function(tag, ns) {
    return document.createElementNS ?
           document.createElementNS(ns || XHTML_NS, tag) :
           document.createElement(tag);
};

exports.setText = function(elem, text) {
    if (elem.innerText !== undefined) {
        elem.innerText = text;
    }
    if (elem.textContent !== undefined) {
        elem.textContent = text;
    }
};

exports.hasCssClass = function(el, name) {
    var classes = el.className.split(/\s+/g);
    return classes.indexOf(name) !== -1;
};

/*
* Add a CSS class to the list of classes on the given node
*/
exports.addCssClass = function(el, name) {
    if (!exports.hasCssClass(el, name)) {
        el.className += " " + name;
    }
};

/*
* Remove a CSS class from the list of classes on the given node
*/
exports.removeCssClass = function(el, name) {
    var classes = el.className.split(/\s+/g);
    while (true) {
        var index = classes.indexOf(name);
        if (index == -1) {
            break;
        }
        classes.splice(index, 1);
    }
    el.className = classes.join(" ");
};

exports.toggleCssClass = function(el, name) {
    var classes = el.className.split(/\s+/g), add = true;
    while (true) {
        var index = classes.indexOf(name);
        if (index == -1) {
            break;
        }
        add = false;
        classes.splice(index, 1);
    }
    if(add)
        classes.push(name);

    el.className = classes.join(" ");
    return add;
};

/*
 * Add or remove a CSS class from the list of classes on the given node
 * depending on the value of <tt>include</tt>
 */
exports.setCssClass = function(node, className, include) {
    if (include) {
        exports.addCssClass(node, className);
    } else {
        exports.removeCssClass(node, className);
    }
};

exports.hasCssString = function(id, doc) {
    var index = 0, sheets;
    doc = doc || document;

    if (doc.createStyleSheet && (sheets = doc.styleSheets)) {
        while (index < sheets.length)
            if (sheets[index++].owningElement.id === id) return true;
    } else if ((sheets = doc.getElementsByTagName("style"))) {
        while (index < sheets.length)
            if (sheets[index++].id === id) return true;
    }

    return false;
};

exports.importCssString = function importCssString(cssText, id, doc) {
    doc = doc || document;
    // If style is already imported return immediately.
    if (id && exports.hasCssString(id, doc))
        return null;

    var style;

    if (doc.createStyleSheet) {
        style = doc.createStyleSheet();
        style.cssText = cssText;
        if (id)
            style.owningElement.id = id;
    } else {
        style = doc.createElementNS
            ? doc.createElementNS(XHTML_NS, "style")
            : doc.createElement("style");

        style.appendChild(doc.createTextNode(cssText));
        if (id)
            style.id = id;

        var head = doc.getElementsByTagName("head")[0] || doc.documentElement;
        head.appendChild(style);
    }
};

exports.importCssStylsheet = function(uri, doc) {
    if (doc.createStyleSheet) {
        doc.createStyleSheet(uri);
    } else {
        var link = exports.createElement('link');
        link.rel = 'stylesheet';
        link.href = uri;

        var head = doc.getElementsByTagName("head")[0] || doc.documentElement;
        head.appendChild(link);
    }
};

exports.getInnerWidth = function(element) {
    return (
        parseInt(exports.computedStyle(element, "paddingLeft"), 10) +
        parseInt(exports.computedStyle(element, "paddingRight"), 10) +
        element.clientWidth
    );
};

exports.getInnerHeight = function(element) {
    return (
        parseInt(exports.computedStyle(element, "paddingTop"), 10) +
        parseInt(exports.computedStyle(element, "paddingBottom"), 10) +
        element.clientHeight
    );
};

if (window.pageYOffset !== undefined) {
    exports.getPageScrollTop = function() {
        return window.pageYOffset;
    };

    exports.getPageScrollLeft = function() {
        return window.pageXOffset;
    };
}
else {
    exports.getPageScrollTop = function() {
        return document.body.scrollTop;
    };

    exports.getPageScrollLeft = function() {
        return document.body.scrollLeft;
    };
}

if (window.getComputedStyle)
    exports.computedStyle = function(element, style) {
        if (style)
            return (window.getComputedStyle(element, "") || {})[style] || "";
        return window.getComputedStyle(element, "") || {};
    };
else
    exports.computedStyle = function(element, style) {
        if (style)
            return element.currentStyle[style];
        return element.currentStyle;
    };

exports.scrollbarWidth = function(document) {

    var inner = exports.createElement("p");
    inner.style.width = "100%";
    inner.style.minWidth = "0px";
    inner.style.height = "200px";

    var outer = exports.createElement("div");
    var style = outer.style;

    style.position = "absolute";
    style.left = "-10000px";
    style.overflow = "hidden";
    style.width = "200px";
    style.minWidth = "0px";
    style.height = "150px";

    outer.appendChild(inner);

    var body = document.body || document.documentElement;
    body.appendChild(outer);

    var noScrollbar = inner.offsetWidth;

    style.overflow = "scroll";
    var withScrollbar = inner.offsetWidth;

    if (noScrollbar == withScrollbar) {
        withScrollbar = outer.clientWidth;
    }

    body.removeChild(outer);

    return noScrollbar-withScrollbar;
};

/*
 * Optimized set innerHTML. This is faster than plain innerHTML if the element
 * already contains a lot of child elements.
 *
 * See http://blog.stevenlevithan.com/archives/faster-than-innerhtml for details
 */
exports.setInnerHtml = function(el, innerHtml) {
    var element = el.cloneNode(false);//document.createElement("div");
    element.innerHTML = innerHtml;
    el.parentNode.replaceChild(element, el);
    return element;
};

exports.setInnerText = function(el, innerText) {
    var document = el.ownerDocument;
    if (document.body && "textContent" in document.body)
        el.textContent = innerText;
    else
        el.innerText = innerText;

};

exports.getInnerText = function(el) {
    var document = el.ownerDocument;
    if (document.body && "textContent" in document.body)
        return el.textContent;
    else
         return el.innerText || el.textContent || "";
};

exports.getParentWindow = function(document) {
    return document.defaultView || document.parentWindow;
};

});
<commit_msg>#1202 scrollbar size is wrong when too broad selector is used<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {
"use strict";

var XHTML_NS = "http://www.w3.org/1999/xhtml";

exports.createElement = function(tag, ns) {
    return document.createElementNS ?
           document.createElementNS(ns || XHTML_NS, tag) :
           document.createElement(tag);
};

exports.setText = function(elem, text) {
    if (elem.innerText !== undefined) {
        elem.innerText = text;
    }
    if (elem.textContent !== undefined) {
        elem.textContent = text;
    }
};

exports.hasCssClass = function(el, name) {
    var classes = el.className.split(/\s+/g);
    return classes.indexOf(name) !== -1;
};

/*
* Add a CSS class to the list of classes on the given node
*/
exports.addCssClass = function(el, name) {
    if (!exports.hasCssClass(el, name)) {
        el.className += " " + name;
    }
};

/*
* Remove a CSS class from the list of classes on the given node
*/
exports.removeCssClass = function(el, name) {
    var classes = el.className.split(/\s+/g);
    while (true) {
        var index = classes.indexOf(name);
        if (index == -1) {
            break;
        }
        classes.splice(index, 1);
    }
    el.className = classes.join(" ");
};

exports.toggleCssClass = function(el, name) {
    var classes = el.className.split(/\s+/g), add = true;
    while (true) {
        var index = classes.indexOf(name);
        if (index == -1) {
            break;
        }
        add = false;
        classes.splice(index, 1);
    }
    if(add)
        classes.push(name);

    el.className = classes.join(" ");
    return add;
};

/*
 * Add or remove a CSS class from the list of classes on the given node
 * depending on the value of <tt>include</tt>
 */
exports.setCssClass = function(node, className, include) {
    if (include) {
        exports.addCssClass(node, className);
    } else {
        exports.removeCssClass(node, className);
    }
};

exports.hasCssString = function(id, doc) {
    var index = 0, sheets;
    doc = doc || document;

    if (doc.createStyleSheet && (sheets = doc.styleSheets)) {
        while (index < sheets.length)
            if (sheets[index++].owningElement.id === id) return true;
    } else if ((sheets = doc.getElementsByTagName("style"))) {
        while (index < sheets.length)
            if (sheets[index++].id === id) return true;
    }

    return false;
};

exports.importCssString = function importCssString(cssText, id, doc) {
    doc = doc || document;
    // If style is already imported return immediately.
    if (id && exports.hasCssString(id, doc))
        return null;

    var style;

    if (doc.createStyleSheet) {
        style = doc.createStyleSheet();
        style.cssText = cssText;
        if (id)
            style.owningElement.id = id;
    } else {
        style = doc.createElementNS
            ? doc.createElementNS(XHTML_NS, "style")
            : doc.createElement("style");

        style.appendChild(doc.createTextNode(cssText));
        if (id)
            style.id = id;

        var head = doc.getElementsByTagName("head")[0] || doc.documentElement;
        head.appendChild(style);
    }
};

exports.importCssStylsheet = function(uri, doc) {
    if (doc.createStyleSheet) {
        doc.createStyleSheet(uri);
    } else {
        var link = exports.createElement('link');
        link.rel = 'stylesheet';
        link.href = uri;

        var head = doc.getElementsByTagName("head")[0] || doc.documentElement;
        head.appendChild(link);
    }
};

exports.getInnerWidth = function(element) {
    return (
        parseInt(exports.computedStyle(element, "paddingLeft"), 10) +
        parseInt(exports.computedStyle(element, "paddingRight"), 10) +
        element.clientWidth
    );
};

exports.getInnerHeight = function(element) {
    return (
        parseInt(exports.computedStyle(element, "paddingTop"), 10) +
        parseInt(exports.computedStyle(element, "paddingBottom"), 10) +
        element.clientHeight
    );
};

if (window.pageYOffset !== undefined) {
    exports.getPageScrollTop = function() {
        return window.pageYOffset;
    };

    exports.getPageScrollLeft = function() {
        return window.pageXOffset;
    };
}
else {
    exports.getPageScrollTop = function() {
        return document.body.scrollTop;
    };

    exports.getPageScrollLeft = function() {
        return document.body.scrollLeft;
    };
}

if (window.getComputedStyle)
    exports.computedStyle = function(element, style) {
        if (style)
            return (window.getComputedStyle(element, "") || {})[style] || "";
        return window.getComputedStyle(element, "") || {};
    };
else
    exports.computedStyle = function(element, style) {
        if (style)
            return element.currentStyle[style];
        return element.currentStyle;
    };

exports.scrollbarWidth = function(document) {
    var inner = exports.createElement("ace_inner");
    inner.style.width = "100%";
    inner.style.minWidth = "0px";
    inner.style.height = "200px";
    inner.style.display = "block";

    var outer = exports.createElement("ace_outer");
    var style = outer.style;

    style.position = "absolute";
    style.left = "-10000px";
    style.overflow = "hidden";
    style.width = "200px";
    style.minWidth = "0px";
    style.height = "150px";
    style.display = "block";

    outer.appendChild(inner);

    var body = document.documentElement;
    body.appendChild(outer);

    var noScrollbar = inner.offsetWidth;

    style.overflow = "scroll";
    var withScrollbar = inner.offsetWidth;

    if (noScrollbar == withScrollbar) {
        withScrollbar = outer.clientWidth;
    }

    body.removeChild(outer);

    return noScrollbar-withScrollbar;
};

/*
 * Optimized set innerHTML. This is faster than plain innerHTML if the element
 * already contains a lot of child elements.
 *
 * See http://blog.stevenlevithan.com/archives/faster-than-innerhtml for details
 */
exports.setInnerHtml = function(el, innerHtml) {
    var element = el.cloneNode(false);//document.createElement("div");
    element.innerHTML = innerHtml;
    el.parentNode.replaceChild(element, el);
    return element;
};

exports.setInnerText = function(el, innerText) {
    var document = el.ownerDocument;
    if (document.body && "textContent" in document.body)
        el.textContent = innerText;
    else
        el.innerText = innerText;

};

exports.getInnerText = function(el) {
    var document = el.ownerDocument;
    if (document.body && "textContent" in document.body)
        return el.textContent;
    else
         return el.innerText || el.textContent || "";
};

exports.getParentWindow = function(document) {
    return document.defaultView || document.parentWindow;
};

});
<|endoftext|>


<commit_before>// establish Debug level before using logFactory
import Xen from '../../components/xen/xen.js';
Xen.Debug.level = ((new URL(document.location)).searchParams.has('log')) ? 3 : 0;

// common shell resources are here
window.shellPath = '../..';
<commit_msg>default log level should be 2 (#1121)<commit_after>// establish Debug level before using logFactory
import Xen from '../../components/xen/xen.js';
Xen.Debug.level = ((new URL(document.location)).searchParams.has('log')) ? 2 : 0;

// common shell resources are here
window.shellPath = '../..';
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import {Point, Range} from 'atom';

import {toNativePathSep} from '../helpers';
import Marker from '../atom/marker';
import Decoration from '../atom/decoration';
import GithubDotcomMarkdown from './github-dotcom-markdown';
import Timeago from './timeago';

let count = 0;

export default class PullRequestCommentsView extends React.Component {
  static propTypes = {
    relay: PropTypes.shape({
      hasMore: PropTypes.func.isRequired,
      loadMore: PropTypes.func.isRequired,
      isLoading: PropTypes.func.isRequired,
    }).isRequired,
    commentThreads: PropTypes.arrayOf(PropTypes.shape({
      rootCommentId: PropTypes.string.isRequired,
      comments: PropTypes.arrayOf(PropTypes.object).isRequired,
    })),
    multiFilePatch: PropTypes.object.isRequired,
  }

  render() {
    return [...this.props.commentThreads].reverse().map(({rootCommentId, comments}) => {
      const rootComment = comments[0];
      if (!rootComment.position) {
        return null;
      }

      const nativePath = toNativePathSep(rootComment.path);
      const row = this.props.multiFilePatch.getBufferRowForDiffPosition(nativePath, rootComment.position);
      const point = new Point(row, 0);
      const range = new Range(point, point);
      // TODO: find way to re-use nodes by using same key. this count++ hack is in place to get the comments to show up
      // in the correct order after new pages of data are fetched. Test it by reducing the reviewCount to a small number
      return (
        <Marker key={`pr-comment-${rootCommentId + count++}`} bufferRange={range} invalidate="never">
          <Decoration type="block" position="after" className="github-PrCommentThread">
            {comments.map(comment => {
              return (
                <PullRequestCommentView
                  key={comment.id}
                  comment={comment}
                  switchToIssueish={this.props.switchToIssueish}
                />
              );
            })}
          </Decoration>
        </Marker>
      );
    });
  }
}

export class PullRequestCommentView extends React.Component {
  render() {
    const author = this.props.comment.author;
    const login = author ? author.login : 'someone';
    return (

          {login} commented{' '}

            <Timeago time={this.props.comment.createdAt} />

          <GithubDotcomMarkdown html={this.props.comment.bodyHTML} switchToIssueish={this.props.switchToIssueish} />

    );
  }
}
<commit_msg>Get rid of hack for ensuring comment threads appear in the right order<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import {Point, Range} from 'atom';

import {toNativePathSep} from '../helpers';
import Marker from '../atom/marker';
import Decoration from '../atom/decoration';
import GithubDotcomMarkdown from './github-dotcom-markdown';
import Timeago from './timeago';

export default class PullRequestCommentsView extends React.Component {
  static propTypes = {
    relay: PropTypes.shape({
      hasMore: PropTypes.func.isRequired,
      loadMore: PropTypes.func.isRequired,
      isLoading: PropTypes.func.isRequired,
    }).isRequired,
    commentThreads: PropTypes.arrayOf(PropTypes.shape({
      rootCommentId: PropTypes.string.isRequired,
      comments: PropTypes.arrayOf(PropTypes.object).isRequired,
    })),
    multiFilePatch: PropTypes.object.isRequired,
  }

  render() {
    return [...this.props.commentThreads].reverse().map(({rootCommentId, comments}) => {
      const rootComment = comments[0];
      if (!rootComment.position) {
        return null;
      }

      const nativePath = toNativePathSep(rootComment.path);
      const row = this.props.multiFilePatch.getBufferRowForDiffPosition(nativePath, rootComment.position);
      const point = new Point(row, 0);
      const range = new Range(point, point);
      // TODO: find way to re-use nodes by using same key. this count++ hack is in place to get the comments to show up
      // in the correct order after new pages of data are fetched. Test it by reducing the reviewCount to a small number
      return (
        <Marker key={`pr-comment-${rootCommentId}`} bufferRange={range} invalidate="never">
          <Decoration type="block" position="after" className="github-PrCommentThread">
            {comments.map(comment => {
              return (
                <PullRequestCommentView
                  key={comment.id}
                  comment={comment}
                  switchToIssueish={this.props.switchToIssueish}
                />
              );
            })}
          </Decoration>
        </Marker>
      );
    });
  }
}

export class PullRequestCommentView extends React.Component {
  render() {
    const author = this.props.comment.author;
    const login = author ? author.login : 'someone';
    return (

          {login} commented{' '}

            <Timeago time={this.props.comment.createdAt} />

          <GithubDotcomMarkdown html={this.props.comment.bodyHTML} switchToIssueish={this.props.switchToIssueish} />

    );
  }
}
<|endoftext|>


<commit_before>var config = require(__dirname+'/../../config/config.js');

/**
* @require Config
* @function setLastPaymentHash
* @description In order to poll Ripple REST for new payment notifications to
* the Gateway cold wallet, a starting-point transaction hash
* must be set.
*
* @param options
* @param options.hash Last transaction hash of the cold wallet address
* @params {function} callback
*/

module.exports = function(hash, callback){
  config.set('LAST_PAYMENT_HASH', hash);
  config.save(function(err){
    if (err) {
      callback(err, null);
    } else {
      callback(null, config.get('LAST_PAYMENT_HASH'));
    }
  });
};
<commit_msg>[BUG] take opts.hash instead of the hash object<commit_after>var config = require(__dirname+'/../../config/config.js');

/**
* @require Config
* @function setLastPaymentHash
* @description In order to poll Ripple REST for new payment notifications to
* the Gateway cold wallet, a starting-point transaction hash
* must be set.
*
* @param opts
* @param opts.hash Last transaction hash of the cold wallet address
* @params {function} callback
*/

module.exports = function(opts, callback){
  config.set('LAST_PAYMENT_HASH', opts.hash);
  config.save(function(err){
    if (err) {
      callback(err, null);
    } else {
      callback(null, config.get('LAST_PAYMENT_HASH'));
    }
  });
};
<|endoftext|>


<commit_before>'use strict';

var _         = require('underscore');
var npm       = require('npm');
var Client    = require('npm-registry-client');
var urlParser = require('github-url-from-git');
var npmconf   = require('npmconf');
var path      = require('path');
var config    = require('../config');
var store     = require('./store');
var utils      = require('./utils');

var Registry = module.exports = function (options) {
	this._client = null;
	this._options = options;
	this._domain = options.gitDomain ||
					config.defaultDomain;
	this._syncURL = this._options.registry +
					config.registry.dumpURL;
	this._cachePath = path.resolve(__dirname +
							'/../' +
							config.directory.cache);
};

Registry.prototype._sync = function (callback) {
	this._client.get(this._syncURL,
				config.registry,
				function (err, data) {
					if (err) { throw err; }

                    // remove _id and _tag
                    // from the response data
                    delete data._id;
                    delete data._etag;

					var packages = _.values(data);
                    store.update(utils.packageCleaner(packages));

					if (typeof callback === 'function') { callback(packages); }
				}
	);
};

Registry.prototype.init = function (callback) {
	var self = this;
	npmconf.load({}, function (err, conf) {
		if (err) { throw err; }
		conf.set('cache', self._cachePath);
		conf.set('always-auth', false);
		conf.set('strict-ssl', false);

		self._client = new Client(conf);
		self._sync(function (packages) {
			// start to regularly sync the packages
            setInterval(self._sync.bind(self), config.syncInterval);
            return callback();
		});
	});
};

Registry.prototype.packages = function (page, callback) {
    store.getPackages(page, function (err, packages) {
        if (err) {
            throw err;
        }
        //TODO: make this a DB operation!
        //packages.map(function (_package) {
        //if (_package.repository && _package.repository.url) {
        //_package.repository.webURL = urlParser(_package.repository.url, {extraBaseUrls: [self._domain]});
        //}
        //});
        callback(packages);
    });
};

Registry.prototype.packageInfo = function (name, callback) {
	this._client.get(this._options.registry + name,
		config.registry,
		function (err, data, raw, res) {
			if (err) { throw err; }
			callback(data);
		}
	);
};<commit_msg>enabled url parser back<commit_after>'use strict';

var _         = require('underscore');
var npm       = require('npm');
var Client    = require('npm-registry-client');
var urlParser = require('github-url-from-git');
var npmconf   = require('npmconf');
var path      = require('path');
var config    = require('../config');
var store     = require('./store');
var utils      = require('./utils');

var Registry = module.exports = function (options) {
	this._client = null;
	this._options = options;
	this._syncURL = this._options.registry +
					config.registry.dumpURL;
	this._cachePath = path.resolve(__dirname +
							'/../' +
							config.directory.cache);
	this._urlParserConfig = {
		extraBaseUrls: [options.gitDomain || config.defaultDomain]
	}
};

Registry.prototype._sync = function (callback) {
	this._client.get(this._syncURL,
				config.registry,
				function (err, data) {
					if (err) { throw err; }

                    // remove _id and _tag
                    // from the response data
                    delete data._id;
                    delete data._etag;

					var packages = _.values(data);
                    store.update(utils.packageCleaner(packages));

					if (typeof callback === 'function') { callback(packages); }
				}
	);
};

Registry.prototype.init = function (callback) {
	var self = this;
	npmconf.load({}, function (err, conf) {
		if (err) { throw err; }
		conf.set('cache', self._cachePath);
		conf.set('always-auth', false);
		conf.set('strict-ssl', false);

		self._client = new Client(conf);
		self._sync(function (packages) {
			// start to regularly sync the packages
            setInterval(self._sync.bind(self), config.syncInterval);
            return callback();
		});
	});
};

Registry.prototype.packages = function (page, callback) {
	var self = this;
    store.getPackages(page, function (err, packages) {
        if (err) {
            throw err;
        }
        //TODO: make this a DB operation!
        packages.map(function (pkg) {
	        if (pkg.repository && pkg.repository.url) {
	        	pkg.repository.webURL = urlParser(pkg.repository.url, self._urlParserConfig);
	        }
        }, this);
        callback(packages);
    });
};

Registry.prototype.packageInfo = function (name, callback) {
	this._client.get(this._options.registry + name,
		config.registry,
		function (err, data, raw, res) {
			if (err) { throw err; }
			callback(data);
		}
	);
};<|endoftext|>


<commit_before>/*
 * Copyright (c) 2011-2013, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

/*jslint anon:true, sloppy:true*/
/*global YUI*/

/**
 * @module ActionContextAddon
 */
YUI.add('mojito-intl-addon', function(Y, NAME) {

    /**
     * Access point: ac.intl.*
     * Internationalization addon
     * @class Intl.common
     */
    function IntlAddon(command, adapter, ac) {
        this.ac = ac;
    }

    IntlAddon.prototype = {

        namespace: 'intl',

        /**
         * Returns translated string.
         * @method lang
         * @param label {string} Optional. The initial label to be translated. If not provided, returns a copy of all resources.
         * @param args {string|Array|Object} optional parameters for the string
         * @return {string|Object} translated string for label or if no label was provided an object containing all resources.
         */
        lang: function(label, args) {
            var lang = this.ac.instance.closestLang || 'yuiRootLang',
                string;
            Y.Intl.setLang(this.ac.instance.controller, lang);
            string = Y.Intl.get(this.ac.instance.controller, label);
            if (string && args) {
                // simple string substitution
                return Y.Lang.sub(string, Y.Lang.isString(args) ? [args] : args);
            }
            return string;
        },

        /**
         * Returns local-specified date.
         * @method formatDate
         * @param {Date} date The initial date to be formatted.
         * @return {string} formatted data for language.
         */
        formatDate: function(date) {
            var lang = this.ac.instance.closestLang || 'yuiRootLang';
            //Y.log('Formatting date (' + date + ') in lang "' +
            //    lang + '"', 'debug', NAME);
            Y.Intl.setLang('datatype-date-format', lang);
            return Y.DataType.Date.format(date, {format: '%x'});
        }
    };

    Y.namespace('mojito.addons.ac').intl = IntlAddon;

}, '0.1.0', {requires: [
    'intl',
    'datatype-date',
    'mojito',
    'mojito-config-addon'
]});

<commit_msg>Made lang and formatDate methods independent of the previously set language.<commit_after>/*
 * Copyright (c) 2011-2013, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

/*jslint anon:true, sloppy:true, nomen: true*/
/*global YUI*/

/**
 * @module ActionContextAddon
 */
YUI.add('mojito-intl-addon', function(Y, NAME) {

    // Overwriting setLang such that yuiActiveLang is not set,
    // this prevents independent requests from interfering with each other.
    // Previously if one request set a valid language, a subsequent request with
    // an invalid language would end up using the previous language.
    var setLang = function (module) {
        //delete Y.Intl._mod(module).yuiActiveLang;
        return Y.Intl.setLang.apply(Y.Intl, arguments);
    };

    /**
     * Access point: ac.intl.*
     * Internationalization addon
     * @class Intl.common
     */
    function IntlAddon(command, adapter, ac) {
        this.ac = ac;
    }

    IntlAddon.prototype = {

        namespace: 'intl',

        /**
         * Returns translated string.
         * @method lang
         * @param label {string} Optional. The initial label to be translated. If not provided, returns a copy of all resources.
         * @param args {string|Array|Object} optional parameters for the string
         * @return {string|Object} translated string for label or if no label was provided an object containing all resources.
         */
        lang: function(label, args) {
            var lang = this.ac.instance.closestLang || 'yuiRootLang',
                module = this.ac.instance.controller,
                activeLang = Y.Intl._mod(module).yuiActiveLang,
                string;

            // Deleting the active lang in order to be independent of
            // previous languages set.
            delete Y.Intl._mod(module).yuiActiveLang;
            Y.Intl.setLang(module, lang);
            string = Y.Intl.get(module, label);
            Y.Intl._mod(module).yuiActiveLang = activeLang;
            if (string && args) {
                // simple string substitution
                return Y.Lang.sub(string, Y.Lang.isString(args) ? [args] : args);
            }
            return string;
        },

        /**
         * Returns local-specified date.
         * @method formatDate
         * @param {Date} date The initial date to be formatted.
         * @return {string} formatted data for language.
         */
        formatDate: function(date) {
            var lang = this.ac.instance.closestLang || 'en',
                module = 'datatype-date-format',
                activeLang = Y.Intl._mod(module).yuiActiveLang,
                formattedDate;

            // Deleting the active lang in order to be independent of
            // previous languages set.
            delete Y.Intl._mod(module).yuiActiveLang;
            Y.Intl.setLang(module, lang);
            formattedDate = Y.DataType.Date.format(date, {format: '%x'});
            Y.Intl._mod(module).yuiActiveLang = activeLang;
            return formattedDate;
        }
    };

    Y.namespace('mojito.addons.ac').intl = IntlAddon;

}, '0.1.0', {requires: [
    'intl',
    'datatype-date',
    'mojito',
    'mojito-config-addon'
]});

<|endoftext|>