<commit_before>'use strict'; // eslint-disable-line

const fs = require('fs');
const assert = require('assert');
const uuid = require('uuid');
const level = require('level');
const sublevel = require('level-sublevel');

const Logger = require('werelogs').Logger;

const constants = require('../../../constants');
const errors = require('../../../errors');
const storageUtils = require('../../utils');
const rpc = require('../../../network/rpc/rpc');
const levelNet = require('../../../network/rpc/level-net');

const WGM = require('../../../versioning/WriteGatheringManager');
const WriteCache = require('../../../versioning/WriteCache');
const VRP = require('../../../versioning/VersioningRequestProcessor');

const ROOT_DB = 'rootDB';
const SYNC_OPTIONS = { sync: true };
const SUBLEVEL_SEP = '::';

class MetadataFileServer {

    /**
     * Construct a metadata server
     *
     * @param {Object} params - constructor params
     * @param {Number} params.port - TCP port that listens to incoming
     *   connections
     * @param {String} params.path - local path where the root
     *   database is stored
     * @param {String} [params.bindAddress='localhost'] - address
     * bound to the socket
     * @param {Number} [params.streamMaxPendingAck] - max number of
     *   in-flight output stream packets sent to the client without an
     *   ack received yet
     * @param {Number} [params.streamAckTimeoutMs] - timeout for
     *   receiving an ack after an output stream packet is sent to the
     *   client
     * @param {Boolean} [params.restEnabled=false] - set to
     *   <tt>true</tt> to enable a debug HTTP interface for accessing
     *   raw metadata info (based on JSON-enabled POST
     *   requests/responses mapping socket.io transfers)
     * @param {Number} [params.restPort] - if <tt>restEnabled</tt> is
     *   <tt>true</tt>, set the port to which the interface listens to
     * @param {Object} [params.log] - logging configuration
     */
    constructor(params) {
        assert.notStrictEqual(params.path, undefined);
        assert.notStrictEqual(params.port, undefined);
        assert(params.versioning && params.versioning.replicationGroupId);
        this.path = params.path;
        this.port = params.port;
        this.bindAddress = params.bindAddress || 'localhost';
        this.streamMaxPendingAck = params.streamMaxPendingAck;
        this.streamAckTimeoutMs = params.streamAckTimeoutMs;
        this.versioning = params.versioning;
        this.restEnabled = params.restEnabled;
        this.restPort = params.restPort;
        this.setupLogging(params.log);
        this.servers = [];
        this.services = [];
    }

    setupLogging(config) {
        let options = undefined;
        if (config !== undefined) {
            options = {
                level: config.logLevel,
                dump: config.dumpLevel,
            };
        }
        this.logger = new Logger('MetadataFileServer', options);
    }

    genUUIDIfNotExists() {
        const uuidFile = `${this.path}/uuid`;

        try {
            fs.accessSync(uuidFile, fs.F_OK | fs.R_OK);
        } catch (e) {
            if (e.code === 'ENOENT') {
                const v = uuid.v4();
                const fd = fs.openSync(uuidFile, 'w');
                fs.writeSync(fd, v.toString());
                fs.closeSync(fd);
            } else {
                throw e;
            }
        }
    }

    printUUID() {
        const uuidFile = `${this.path}/uuid`;
        const uuidValue = fs.readFileSync(uuidFile);
        this.logger.info(`This deployment's identifier is ${uuidValue}`);
    }

    /**
     * Start the metadata server and listen to incoming connections
     *
     * @return {undefined}
     */
    startServer() {
        fs.accessSync(this.path, fs.F_OK | fs.R_OK | fs.W_OK);
        storageUtils.setDirSyncFlag(this.path, this.logger);

        this.initMetadataService();

        this.logger.info('starting metadata file backend server');
        /* We start a server that will serve the sublevel capable
           db to clients */
        this.server = new rpc.RPCServer(
            { logger: this.logger,
              streamMaxPendingAck: this.streamMaxPendingAck,
              streamAckTimeoutMs: this.streamAckTimeoutMs });
        this.server.listen(this.port, this.bindAddress);
        this.servers.push(this.server);

        if (this.restEnabled) {
            this.logger.info(`starting REST server on port ${this.restPort}`);
            this.restServer = new rpc.RESTServer({ logger: this.logger });
            this.restServer.listen(this.restPort, this.bindAddress);
            this.servers.push(this.restServer);
        }

        this.servers.forEach(server => {
            server.registerServices.apply(server, this.services);
        });

        this.genUUIDIfNotExists();
        this.printUUID();
    }

    initMetadataService() {
        // all metadata operations executed by leveldb go through the
        // /metadata namespace
        const namespace = `${constants.metadataFileNamespace}/metadata`;
        this.logger.info(`creating RPC service at ${namespace}`);
        const dbService = new levelNet.LevelDbService({
            rootDb: sublevel(level(`${this.path}/${ROOT_DB}`)),
            namespace,
            logger: this.logger,
        });
        this.services.push(dbService);

        /* provide an API compatible with MetaData API */
        const metadataAPI = {
            get: (request, logger, callback) => {
                const dbPath = request.db.split(SUBLEVEL_SEP);
                const subDb = dbService.lookupSubLevel(dbPath);
                subDb.get(request.key, (err, data) => {
                    if (err && err.notFound) {
                        return callback(errors.ObjNotFound);
                    }
                    return callback(err, data);
                });
            },
            list: (request, logger, callback) => {
                const dbPath = request.db.split(SUBLEVEL_SEP);
                const subDb = dbService.lookupSubLevel(dbPath);
                const stream = subDb.createReadStream(request.params);
                const res = [];
                let done = false;
                stream.on('data', data => res.push(data));
                stream.on('error', err => {
                    if (done === false) {
                        done = true;
                        callback(err);
                    }
                });
                stream.on('end', () => {
                    if (done === false) {
                        done = true;
                        callback(null, res);
                    }
                });
            },
            batch: (request, logger, callback) => {
                const dbPath = request.db.split(SUBLEVEL_SEP);
                const subDb = dbService.lookupSubLevel(dbPath);
                subDb.batch(request.array, SYNC_OPTIONS,
                            err => callback(err));
            },
        };

        Object.keys(metadataAPI).forEach(k => {
            metadataAPI[k] = metadataAPI[k].bind(dbService);
        });

        const wgm = new WGM(metadataAPI);
        const writeCache = new WriteCache(wgm);
        const vrp = new VRP(writeCache, wgm, this.versioning);

        dbService.registerAsyncAPI({
            put: (env, key, value, options, cb) => {
                const dbName = env.subLevel.join(SUBLEVEL_SEP);
                vrp.put({ db: dbName, key, value, options },
                        env.requestLogger, cb);
            },
            del: (env, key, options, cb) => {
                const dbName = env.subLevel.join(SUBLEVEL_SEP);
                vrp.del({ db: dbName, key, options },
                        env.requestLogger, cb);
            },
            get: (env, key, options, cb) => {
                const dbName = env.subLevel.join(SUBLEVEL_SEP);
                vrp.get({ db: dbName, key, options },
                        env.requestLogger, cb);
            },
        });
        dbService.registerSyncAPI({
            createReadStream:
            (env, options) => env.subDb.createReadStream(options),
        });
    }
}

module.exports = MetadataFileServer;
<commit_msg>Expose UUID through the Metadata service<commit_after>'use strict'; // eslint-disable-line

const fs = require('fs');
const assert = require('assert');
const uuid = require('uuid');
const level = require('level');
const sublevel = require('level-sublevel');

const Logger = require('werelogs').Logger;

const constants = require('../../../constants');
const errors = require('../../../errors');
const storageUtils = require('../../utils');
const rpc = require('../../../network/rpc/rpc');
const levelNet = require('../../../network/rpc/level-net');

const WGM = require('../../../versioning/WriteGatheringManager');
const WriteCache = require('../../../versioning/WriteCache');
const VRP = require('../../../versioning/VersioningRequestProcessor');

const ROOT_DB = 'rootDB';
const SYNC_OPTIONS = { sync: true };
const SUBLEVEL_SEP = '::';

class MetadataFileServer {

    /**
     * Construct a metadata server
     *
     * @param {Object} params - constructor params
     * @param {Number} params.port - TCP port that listens to incoming
     *   connections
     * @param {String} params.path - local path where the root
     *   database is stored
     * @param {String} [params.bindAddress='localhost'] - address
     * bound to the socket
     * @param {Number} [params.streamMaxPendingAck] - max number of
     *   in-flight output stream packets sent to the client without an
     *   ack received yet
     * @param {Number} [params.streamAckTimeoutMs] - timeout for
     *   receiving an ack after an output stream packet is sent to the
     *   client
     * @param {Boolean} [params.restEnabled=false] - set to
     *   <tt>true</tt> to enable a debug HTTP interface for accessing
     *   raw metadata info (based on JSON-enabled POST
     *   requests/responses mapping socket.io transfers)
     * @param {Number} [params.restPort] - if <tt>restEnabled</tt> is
     *   <tt>true</tt>, set the port to which the interface listens to
     * @param {Object} [params.log] - logging configuration
     */
    constructor(params) {
        assert.notStrictEqual(params.path, undefined);
        assert.notStrictEqual(params.port, undefined);
        assert(params.versioning && params.versioning.replicationGroupId);
        this.path = params.path;
        this.port = params.port;
        this.bindAddress = params.bindAddress || 'localhost';
        this.streamMaxPendingAck = params.streamMaxPendingAck;
        this.streamAckTimeoutMs = params.streamAckTimeoutMs;
        this.versioning = params.versioning;
        this.restEnabled = params.restEnabled;
        this.restPort = params.restPort;
        this.setupLogging(params.log);
        this.servers = [];
        this.services = [];
    }

    setupLogging(config) {
        let options = undefined;
        if (config !== undefined) {
            options = {
                level: config.logLevel,
                dump: config.dumpLevel,
            };
        }
        this.logger = new Logger('MetadataFileServer', options);
    }

    genUUIDIfNotExists() {
        const uuidFile = `${this.path}/uuid`;

        try {
            fs.accessSync(uuidFile, fs.F_OK | fs.R_OK);
        } catch (e) {
            if (e.code === 'ENOENT') {
                const v = uuid.v4();
                const fd = fs.openSync(uuidFile, 'w');
                fs.writeSync(fd, v.toString());
                fs.closeSync(fd);
            } else {
                throw e;
            }
        }
    }

    readUUID() {
        return fs.readFileSync(`${this.path}/uuid`, 'ascii');
    }

    printUUID() {
        const uuidValue = this.readUUID();
        this.logger.info(`This deployment's identifier is ${uuidValue}`);
    }

    /**
     * Start the metadata server and listen to incoming connections
     *
     * @return {undefined}
     */
    startServer() {
        fs.accessSync(this.path, fs.F_OK | fs.R_OK | fs.W_OK);
        storageUtils.setDirSyncFlag(this.path, this.logger);

        this.initMetadataService();

        this.logger.info('starting metadata file backend server');
        /* We start a server that will serve the sublevel capable
           db to clients */
        this.server = new rpc.RPCServer(
            { logger: this.logger,
              streamMaxPendingAck: this.streamMaxPendingAck,
              streamAckTimeoutMs: this.streamAckTimeoutMs });
        this.server.listen(this.port, this.bindAddress);
        this.servers.push(this.server);

        if (this.restEnabled) {
            this.logger.info(`starting REST server on port ${this.restPort}`);
            this.restServer = new rpc.RESTServer({ logger: this.logger });
            this.restServer.listen(this.restPort, this.bindAddress);
            this.servers.push(this.restServer);
        }

        this.servers.forEach(server => {
            server.registerServices.apply(server, this.services);
        });

        this.genUUIDIfNotExists();
        this.printUUID();
    }

    initMetadataService() {
        // all metadata operations executed by leveldb go through the
        // /metadata namespace
        const namespace = `${constants.metadataFileNamespace}/metadata`;
        this.logger.info(`creating RPC service at ${namespace}`);
        const dbService = new levelNet.LevelDbService({
            rootDb: sublevel(level(`${this.path}/${ROOT_DB}`)),
            namespace,
            logger: this.logger,
        });
        this.services.push(dbService);

        /* provide an API compatible with MetaData API */
        const metadataAPI = {
            get: (request, logger, callback) => {
                const dbPath = request.db.split(SUBLEVEL_SEP);
                const subDb = dbService.lookupSubLevel(dbPath);
                subDb.get(request.key, (err, data) => {
                    if (err && err.notFound) {
                        return callback(errors.ObjNotFound);
                    }
                    return callback(err, data);
                });
            },
            list: (request, logger, callback) => {
                const dbPath = request.db.split(SUBLEVEL_SEP);
                const subDb = dbService.lookupSubLevel(dbPath);
                const stream = subDb.createReadStream(request.params);
                const res = [];
                let done = false;
                stream.on('data', data => res.push(data));
                stream.on('error', err => {
                    if (done === false) {
                        done = true;
                        callback(err);
                    }
                });
                stream.on('end', () => {
                    if (done === false) {
                        done = true;
                        callback(null, res);
                    }
                });
            },
            batch: (request, logger, callback) => {
                const dbPath = request.db.split(SUBLEVEL_SEP);
                const subDb = dbService.lookupSubLevel(dbPath);
                subDb.batch(request.array, SYNC_OPTIONS,
                            err => callback(err));
            },
        };

        Object.keys(metadataAPI).forEach(k => {
            metadataAPI[k] = metadataAPI[k].bind(dbService);
        });

        const wgm = new WGM(metadataAPI);
        const writeCache = new WriteCache(wgm);
        const vrp = new VRP(writeCache, wgm, this.versioning);

        dbService.registerAsyncAPI({
            put: (env, key, value, options, cb) => {
                const dbName = env.subLevel.join(SUBLEVEL_SEP);
                vrp.put({ db: dbName, key, value, options },
                        env.requestLogger, cb);
            },
            del: (env, key, options, cb) => {
                const dbName = env.subLevel.join(SUBLEVEL_SEP);
                vrp.del({ db: dbName, key, options },
                        env.requestLogger, cb);
            },
            get: (env, key, options, cb) => {
                const dbName = env.subLevel.join(SUBLEVEL_SEP);
                vrp.get({ db: dbName, key, options },
                        env.requestLogger, cb);
            },
        });
        dbService.registerSyncAPI({
            createReadStream:
            (env, options) => env.subDb.createReadStream(options),
            getUUID: () => this.readUUID(),
        });
    }
}

module.exports = MetadataFileServer;
<|endoftext|>


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

exports.store = {

  mixinCallback: function(){

    this.addType('integer_array', this.toArrayCastTypes('integer'), {
      migration:{
        integerArray: 'integer[]'
      },

      operators:{
        default: 'in',
        'in': {
          method: function(attr, value, query, cond){
            query.whereRaw(Utils.getAttributeName(this, cond) + " @> ARRAY[?]::integer[]", [value]);
          },

          nullify_empty_array: true,
          on: {
            'all': false,
            'number': true,
            'array': function(attr, value, query, cond){
              query.whereRaw(Utils.getAttributeName(this, cond) + " && ?::integer[]", [value]);
            },
            'attribute': function(attr, value, query, cond){
              query.whereRaw(Utils.getAttributeName(this, cond) + " @> ARRAY[" + Utils.getAttributeName(this, value, true) + "]::integer[]");
            }
          }
        }
      }
    });

  }
};
<commit_msg>integer array parseInt added<commit_after>var Utils = require('../../../utils');

exports.store = {

  mixinCallback: function(){

    this.addType('integer_array', this.toArrayCastTypes('integer'), {
      migration:{
        integerArray: 'integer[]'
      },

      operators:{
        default: 'in',
        'in': {
          method: function(attr, value, query, cond){
            query.whereRaw(Utils.getAttributeName(this, cond) + " @> ARRAY[?]::integer[]", [value]);
          },

          nullify_empty_array: true,
          on: {
            'all': false,
            'number': true,
            'string': true,
            'array': function(attr, value, query, cond){
              value = value.map(function(i){return parseInt(i, 10);});
              query.whereRaw(Utils.getAttributeName(this, cond) + " && ?::integer[]", [value]);
            },
            'attribute': function(attr, value, query, cond){
              query.whereRaw(Utils.getAttributeName(this, cond) + " @> ARRAY[" + Utils.getAttributeName(this, value, true) + "]::integer[]");
            }
          }
        }
      }
    });

  }
};
<|endoftext|>


<commit_before>var lumensWall = angular.module('lumensWall');

lumensWall.controller('createAccountController', function($scope, $state, $http, $rootScope, Account) {
  if ($rootScope.currentUser.account_id) {
    event.preventDefault();
    $state.go('dashboard');
  }
  $scope.userData = {};
  $scope.linkData = {};
  $scope.tempUser = {};
  $scope.statusMsg = {};

  $scope.init = function() {
    $scope.userData.id = $rootScope.currentUser.id;
    $scope.userData.email = $rootScope.currentUser.email;
    $scope.userData.token = $rootScope.currentUser.token;
    $scope.userSeed = "aa";
    $scope.userAcct = "aa";
  };

  $scope.createAccount = function() {
    Account.create($scope.userData)
    .success(function(data) {

      //console.log(data);
      data.content.data.authenticated = true;
      $scope.userSeed = data.content.data.seed;
      $scope.userAcct = data.content.data.account_id;
      // $scope.tempUser = data.content.data;
      var user = data.content.data;
      user.seed = "";
      localUser = JSON.stringify(user);
      //console.log(user);
      // console.log($scope.userSeed);

      // Set the stringified user data into local storage
      localStorage.setItem('user', localUser);

                // The user's authenticated state gets flipped to
                // true so we can now show parts of the UI that rely
                // on the user being logged in
                $rootScope.authenticated = true;

                $rootScope.currentUser = user;
                // $scope.userSeed = $scope.tempUser.seed;
                // $scope.userAcct = $scope.tempUser.account_id;

                angular.element('.mb-control-success').triggerHandler('click');

              })
    .error(function(data) {
      console.log(data);
      $scope.statusMsg = {};
      $scope.statusMsg.type = 'alert-danger';
      $scope.statusMsg.content = data.content.message;
        // angular.element('.mb-control-error').triggerHandler('click');
    });
  };

  $scope.linkAccount = function() {
    $scope.linkData.id = $rootScope.currentUser.id;
    $scope.linkData.email = $rootScope.currentUser.email;
    $scope.linkData.token = $rootScope.currentUser.token;

    Account.link($scope.linkData)
    .success(function(data) {

      //console.log(data);
      data.content.data.authenticated = true;
      $scope.userSeed = data.content.data.seed;
      $scope.userAcct = data.content.data.account_id;
      // $scope.tempUser = data.content.data;
      var user = data.content.data;
      user.seed = "";
      localUser = JSON.stringify(user);
      //console.log(user);
      //console.log($scope.userSeed);

      // Set the stringified user data into local storage
      localStorage.setItem('user', localUser);

                // The user's authenticated state gets flipped to
                // true so we can now show parts of the UI that rely
                // on the user being logged in
                $rootScope.authenticated = true;

                $rootScope.currentUser = user;
                // $scope.userSeed = $scope.tempUser.seed;
                // $scope.userAcct = $scope.tempUser.account_id;

      angular.element('.mb-control-link-success').triggerHandler('click');
      $scope.linkData = {};

      })
    .error(function(data) {
      // console.log(data);
				// Display Error
        // angular.element('.mb-control-error').triggerHandler('click');
      $scope.statusMsg = {};
      $scope.statusMsg.type = 'alert-danger';
      $scope.statusMsg.content = data.content.message;
      $scope.linkData = {};
    });
  };

  $scope.closeAlert = function() {
    $scope.statusMsg = {};
  };

});<commit_msg>modified link and create account functions<commit_after>var lumensWall = angular.module('lumensWall');

lumensWall.controller('createAccountController', function($scope, $state, $http, $rootScope, Account) {
  // if ($rootScope.currentUser.account_id) {
  //   event.preventDefault();
  //   $state.go('dashboard');
  // }
  $scope.userData = {};
  $scope.linkData = {};
  $scope.tempUser = {};
  $scope.statusMsg = {};

  $scope.init = function() {
    $scope.userData.id = $rootScope.currentUser.id;
    $scope.userData.email = $rootScope.currentUser.email;
    $scope.userData.token = $rootScope.currentUser.token;
    $scope.userSeed = "aa";
    $scope.userAcct = "aa";
  };

  $scope.createAccount = function() {
    Account.create($scope.userData)
    .success(function(data) {

      //console.log(data);
      data.content.data.authenticated = true;

      // store seed to display in browser
      $scope.userSeed = data.content.data.seed;
      $scope.userAcct = data.content.data.account_id;

      // set the currently active account
      if (data.content.data.accounts.length > 0) {
        data.content.data.currentAccount = data.content.data.accounts[0].account_id;
      }

      var user = data.content.data;
      user.seed = "";
      user.account_id = "";
      localUser = JSON.stringify(user);

      // Set the stringified user data into local storage
      localStorage.setItem('user', localUser);

      $rootScope.authenticated = true;

      $rootScope.currentUser = user;
      console.log("currentUser", $rootScope.currentUser);

      angular.element('.mb-control-success').triggerHandler('click');

    })
    .error(function(data) {
      console.log(data);
      $scope.statusMsg = {};
      $scope.statusMsg.type = 'alert-danger';
      $scope.statusMsg.content = data.content.message;

    });
  };

  $scope.linkAccount = function() {
    $scope.linkData.id = $rootScope.currentUser.id;
    $scope.linkData.email = $rootScope.currentUser.email;
    $scope.linkData.token = $rootScope.currentUser.token;

    Account.link($scope.linkData)
    .success(function(data) {

      data.content.data.authenticated = true;
      $scope.userSeed = data.content.data.seed;
      $scope.userAcct = data.content.data.account_id;

      var user = data.content.data;
      user.seed = "";
      localUser = JSON.stringify(user);

      // Set the stringified user data into local storage
      localStorage.setItem('user', localUser);

      $rootScope.authenticated = true;

      $rootScope.currentUser = user;

      angular.element('.mb-control-link-success').triggerHandler('click');
      $scope.linkData = {};

      })
    .error(function(data) {

      $scope.statusMsg = {};
      $scope.statusMsg.type = 'alert-danger';
      $scope.statusMsg.content = data.content.message;
      $scope.linkData = {};
    });
  };

  $scope.closeAlert = function() {
    $scope.statusMsg = {};
  };

});<|endoftext|>


<commit_before>'use strict';

//01."text" 在 python_to_blockly.js实现

//02.str('Hello') + str('Mixly') 在 python_to_blockly.js实现

//03.int(str('123'))这种形式的，在math.js实现
function numConvert(mode) {
    function converter(py2block, func, args, keywords, starargs, kwargs, node) {
        if ((mode != 'b' && args.length != 1) || (mode == 'b' && args.length != 2)) {
            throw new Error("Incorrect number of arguments");
        }
        var paramblock = py2block.convert(args[0]);
        if (args[0]._astname == "Call" && args[0].func._astname == "Name" && py2block.Name_str(args[0].func) == "str") {
            paramblock = py2block.convert(args[0].args[0]);
        }else if(args[0]._astname == "Call" && args[0].func._astname == "Name" && py2block.Name_str(args[0].func) == "input"){
            if(pbc.board == pbc.MIXPY) {
                paramblock = py2block.convert(args[0].args[0]);
                return block("inout_type_input", func.lineno, {
                    "DIR": "float"
                }, {
                    'VAR': paramblock
                }, {
                    "inline": "true"
                });
            }
        }
        return block("text_to_number", func.lineno, {
            'TOWHAT': mode
        }, {
            'VAR': paramblock,
        }, {
            "inline": "false"
        });
    }
    return converter;
}

pbc.globalFunctionD['float'] = numConvert('float');
pbc.globalFunctionD['bytes'] = numConvert('b');

pbc.globalFunctionD['chr'] = function (py2block, func, args, keywords, starargs, kwargs, node) {
    if (args.length != 1) {
        throw new Error("Incorrect number of arguments");
    }
    var numblock = py2block.convert(args[0]);
    return block("ascii_to_char", func.lineno, {}, {
            'VAR': numblock,
        }, {
            "inline": "false"
        });
}

pbc.globalFunctionD['ord'] = function (py2block, func, args, keywords, starargs, kwargs, node) {
    if (args.length != 1) {
        throw new Error("Incorrect number of arguments");
    }
    var numblock = py2block.convert(args[0]);
    return block("char_to_ascii", func.lineno, {}, {
            'VAR': numblock,
        }, {
            "inline": "false"
        });
}

pbc.globalFunctionD['str'] = function (py2block, func, args, keywords, starargs, kwargs, node) {
    if (args.length != 1) {
        throw new Error("Incorrect number of arguments");
    }
    var numblock = py2block.convert(args[0]);
    return block("number_to_text", func.lineno, {}, {
            'VAR': numblock,
        }, {
            "inline": "false"
        });
}

pbc.globalFunctionD['len'] = function (py2block, func, args, keywords, starargs, kwargs, node) {
    if (args.length != 1) {
        throw new Error("Incorrect number of arguments");
    }
    var numblock = py2block.convert(args[0]);
    return block("text_length", func.lineno, {}, {
            'VAR': numblock,
        }, {
            "inline": "false"
        });
}

// 'mixly'[0]这种形式的，在python_to_blockly.js中实现

pbc.moduleFunctionD.get('random')['choice'] = function (py2block, func, args, keywords, starargs, kwargs, node){
    if (args.length !== 1) {
        throw new Error("Incorrect number of arguments");
    }
    var argblock = py2block.convert(args[0]);
    var argAstname = args[0]._astname;
    if(args[0]._astname == "Call" && args[0].func._astname == "Name" && py2block.Name_str(args[0].func) == "str"){
        argblock = py2block.convert(args[0].args[0]);
        argAstname = "Str";
    }
    if(argAstname == "Str"){
        return block('text_random_char', func.lineno, {}, {
            'VAR':argblock
        }, {
            "inline": "true"
        });
    }else{
        return block('lists_get_random_item', func.lineno, {}, {
            'LIST':argblock
        }, {
            "inline": "true"
        });
    }
}

//str('123') == str('234')这种形式的，在python_to_blockly.js中实现

function startEndWithStr(mode){
    function converter(py2block, func, args, keywords, starargs, kwargs, node){
        if (args.length !== 1) {
            throw new Error("Incorrect number of arguments");
        }
        var objblock = py2block.convert(func.value);
        if(func.value._astname == "Call" && func.value.func._astname == "Name" && py2block.Name_str(func.value.func) == "str"){
            objblock = py2block.convert(func.value.args[0]);
        }
        var argblock = py2block.convert(args[0]);
        if(args[0]._astname == "Call" && args[0].func._astname == "Name" && py2block.Name_str(args[0].func) == "str"){
            argblock = py2block.convert(args[0].args[0]);
        }
        return block('text_equals_starts_ends', func.lineno, {
            'DOWHAT':mode
        }, {
            'STR1':objblock,
            'STR2':argblock
        }, {
            "inline": "true"
        });
    }
    return converter;
}

pbc.objectFunctionD.get('startswith')['Str'] = startEndWithStr('startswith');
pbc.objectFunctionD.get('endswith')['Str'] = startEndWithStr('endswith');

// 'mixly'[0:8]这种形式的，在python_to_blockly.js中实现
function strTitle(mode){
    function converter(py2block, func, args, keywords, starargs, kwargs, node) {
        if (args.length !== 0) {
            throw new Error("Incorrect number of arguments");
        }
        var textblock = py2block.convert(func.value);
        return block("text_capital", func.lineno, {
            'TEXT_CAPITAL': mode,
        }, {
            "VAR": textblock,
        }, {
            "inline": "true"
        });
    }
    return converter;
}
pbc.objectFunctionD.get('title')['Str'] = strTitle('title');
pbc.objectFunctionD.get('lower')['Str'] = strTitle('lower');

function strencode(mode){
    function converter(py2block, func, args, keywords, starargs, kwargs, node) {
        if (args.length !== 1) {
            throw new Error("Incorrect number of arguments");
        }
        var textblock = py2block.convert(func.value);
        return block("text_to_number", func.lineno, {
            'TOWHAT': mode,
        }, {
            "VAR": textblock,
        }, {
            "inline": "true"
        });
    }
    return converter;
}
pbc.objectFunctionD.get('encode')['Str'] = strencode('b');

function textStrip(mode){
    function converter(py2block, func, args, keywords, starargs, kwargs, node) {
        if (args.length !== 0) {
            throw new Error("Incorrect number of arguments");
        }
        var objblock = py2block.convert(func.value);
        return block("text_strip", func.lineno, {
            'STRIP': mode,
        }, {
            "VAR": objblock,
        }, {
            "inline": "true"
        });
    }
    return converter;
}

pbc.objectFunctionD.get('strip')['Str'] = textStrip('strip');
pbc.objectFunctionD.get('lstrip')['Str'] = textStrip('lstrip');
pbc.objectFunctionD.get('rstrip')['Str'] =  textStrip('rstrip');

function textAlign(mode){
    function converter(py2block, func, args, keywords, starargs, kwargs, node) {
        if (args.length !== 2) {
            throw new Error("Incorrect number of arguments");
        }
        var objblock = py2block.convert(func.value);
        var argblock1 = py2block.convert(args[0]);
        var argblock2 = py2block.convert(args[1]);
        return block("text_center", func.lineno, {
            'TEXT_CENTER': mode,
        }, {
            "VAR": objblock,
            "WID": argblock1,
            "Symbol": argblock2
        }, {
            "inline": "true"
        });
    }
    return converter;
}

pbc.objectFunctionD.get('ljust')['Str'] = textAlign('ljust');
pbc.objectFunctionD.get('center')['Str'] = textAlign('center');
pbc.objectFunctionD.get('rjust')['Str'] =  textAlign('rjust');

pbc.objectFunctionD.get('split')['Str'] = function converter(py2block, func, args, keywords, starargs, kwargs, node) {
        if (args.length !== 1) {
            throw new Error("Incorrect number of arguments");
        }
        var objblock = py2block.convert(func.value);
        var argblock = py2block.convert(args[0]);
        return block("text_split", func.lineno, {
        }, {
            "VAR": objblock,
            "VAL": argblock
        }, {
            "inline": "true"
        });
    }

pbc.objectFunctionD.get('replace')['Str'] = function converter(py2block, func, args, keywords, starargs, kwargs, node) {
        if (args.length !== 2) {
            throw new Error("Incorrect number of arguments");
        }
        var objblock = py2block.convert(func.value);
        var argblock1 = py2block.convert(args[0]);
        var argblock2 = py2block.convert(args[1]);
        return block("text_replace", func.lineno, {
        }, {
            "VAR": objblock,
            "STR1": argblock1,
            "STR2": argblock2
        }, {
            "inline": "true"
        });
    }

pbc.objectFunctionD.get('find')['Str'] = function converter(py2block, func, args, keywords, starargs, kwargs, node) {
        if (args.length !== 1) {
            throw new Error("Incorrect number of arguments");
        }
        var objblock = py2block.convert(func.value);
        var argblock = py2block.convert(args[0]);
        return block("text_find", func.lineno, {
        }, {
            "VAR": objblock,
            "STR": argblock
        }, {
            "inline": "true"
        });
    }

pbc.objectFunctionD.get('format')['Str'] = function converter(py2block, func, args, keywords, starargs, kwargs, node) {
        var objblock = py2block.convert(func.value);
        var d = py2block.convertElements("ADD", args);
        d['VAR'] = objblock;
        return block("text_format_noreturn", node.lineno, {
        }, d, {
            "inline": "true",
        }, {
            "@items":args.length
        });
    }<commit_msg>fix text_strip converter<commit_after>'use strict';

//01."text" 在 python_to_blockly.js实现

//02.str('Hello') + str('Mixly') 在 python_to_blockly.js实现

//03.int(str('123'))这种形式的，在math.js实现
function numConvert(mode) {
    function converter(py2block, func, args, keywords, starargs, kwargs, node) {
        if ((mode != 'b' && args.length != 1) || (mode == 'b' && args.length != 2)) {
            throw new Error("Incorrect number of arguments");
        }
        var paramblock = py2block.convert(args[0]);
        if (args[0]._astname == "Call" && args[0].func._astname == "Name" && py2block.Name_str(args[0].func) == "str") {
            paramblock = py2block.convert(args[0].args[0]);
        }else if(args[0]._astname == "Call" && args[0].func._astname == "Name" && py2block.Name_str(args[0].func) == "input"){
            if(pbc.board == pbc.MIXPY) {
                paramblock = py2block.convert(args[0].args[0]);
                return block("inout_type_input", func.lineno, {
                    "DIR": "float"
                }, {
                    'VAR': paramblock
                }, {
                    "inline": "true"
                });
            }
        }
        return block("text_to_number", func.lineno, {
            'TOWHAT': mode
        }, {
            'VAR': paramblock,
        }, {
            "inline": "false"
        });
    }
    return converter;
}

pbc.globalFunctionD['float'] = numConvert('float');
pbc.globalFunctionD['bytes'] = numConvert('b');

pbc.globalFunctionD['chr'] = function (py2block, func, args, keywords, starargs, kwargs, node) {
    if (args.length != 1) {
        throw new Error("Incorrect number of arguments");
    }
    var numblock = py2block.convert(args[0]);
    return block("ascii_to_char", func.lineno, {}, {
            'VAR': numblock,
        }, {
            "inline": "false"
        });
}

pbc.globalFunctionD['ord'] = function (py2block, func, args, keywords, starargs, kwargs, node) {
    if (args.length != 1) {
        throw new Error("Incorrect number of arguments");
    }
    var numblock = py2block.convert(args[0]);
    return block("char_to_ascii", func.lineno, {}, {
            'VAR': numblock,
        }, {
            "inline": "false"
        });
}

pbc.globalFunctionD['str'] = function (py2block, func, args, keywords, starargs, kwargs, node) {
    if (args.length != 1) {
        throw new Error("Incorrect number of arguments");
    }
    var numblock = py2block.convert(args[0]);
    return block("number_to_text", func.lineno, {}, {
            'VAR': numblock,
        }, {
            "inline": "false"
        });
}

pbc.globalFunctionD['len'] = function (py2block, func, args, keywords, starargs, kwargs, node) {
    if (args.length != 1) {
        throw new Error("Incorrect number of arguments");
    }
    var numblock = py2block.convert(args[0]);
    return block("text_length", func.lineno, {}, {
            'VAR': numblock,
        }, {
            "inline": "false"
        });
}

// 'mixly'[0]这种形式的，在python_to_blockly.js中实现

pbc.moduleFunctionD.get('random')['choice'] = function (py2block, func, args, keywords, starargs, kwargs, node){
    if (args.length !== 1) {
        throw new Error("Incorrect number of arguments");
    }
    var argblock = py2block.convert(args[0]);
    var argAstname = args[0]._astname;
    if(args[0]._astname == "Call" && args[0].func._astname == "Name" && py2block.Name_str(args[0].func) == "str"){
        argblock = py2block.convert(args[0].args[0]);
        argAstname = "Str";
    }
    if(argAstname == "Str"){
        return block('text_random_char', func.lineno, {}, {
            'VAR':argblock
        }, {
            "inline": "true"
        });
    }else{
        return block('lists_get_random_item', func.lineno, {}, {
            'LIST':argblock
        }, {
            "inline": "true"
        });
    }
}

//str('123') == str('234')这种形式的，在python_to_blockly.js中实现

function startEndWithStr(mode){
    function converter(py2block, func, args, keywords, starargs, kwargs, node){
        if (args.length !== 1) {
            throw new Error("Incorrect number of arguments");
        }
        var objblock = py2block.convert(func.value);
        if(func.value._astname == "Call" && func.value.func._astname == "Name" && py2block.Name_str(func.value.func) == "str"){
            objblock = py2block.convert(func.value.args[0]);
        }
        var argblock = py2block.convert(args[0]);
        if(args[0]._astname == "Call" && args[0].func._astname == "Name" && py2block.Name_str(args[0].func) == "str"){
            argblock = py2block.convert(args[0].args[0]);
        }
        return block('text_equals_starts_ends', func.lineno, {
            'DOWHAT':mode
        }, {
            'STR1':objblock,
            'STR2':argblock
        }, {
            "inline": "true"
        });
    }
    return converter;
}

pbc.objectFunctionD.get('startswith')['Str'] = startEndWithStr('startswith');
pbc.objectFunctionD.get('endswith')['Str'] = startEndWithStr('endswith');

// 'mixly'[0:8]这种形式的，在python_to_blockly.js中实现
function strTitle(mode){
    function converter(py2block, func, args, keywords, starargs, kwargs, node) {
        if (args.length !== 0) {
            throw new Error("Incorrect number of arguments");
        }
        var textblock = py2block.convert(func.value);
        return block("text_capital", func.lineno, {
            'TEXT_CAPITAL': mode,
        }, {
            "VAR": textblock,
        }, {
            "inline": "true"
        });
    }
    return converter;
}
pbc.objectFunctionD.get('title')['Str'] = strTitle('title');
pbc.objectFunctionD.get('lower')['Str'] = strTitle('lower');

function strencode(mode){
    function converter(py2block, func, args, keywords, starargs, kwargs, node) {
        if (args.length !== 1) {
            throw new Error("Incorrect number of arguments");
        }
        var textblock = py2block.convert(func.value);
        return block("text_to_number", func.lineno, {
            'TOWHAT': mode,
        }, {
            "VAR": textblock,
        }, {
            "inline": "true"
        });
    }
    return converter;
}
pbc.objectFunctionD.get('encode')['Str'] = strencode('b');

function textStrip(mode){
    function converter(py2block, func, args, keywords, starargs, kwargs, node) {
        if (args.length !== 0) {
            throw new Error("Incorrect number of arguments");
        }
        var objblock = py2block.convert(func.value);
        return block("text_strip", func.lineno, {
            'TOWHAT': mode,
        }, {
            "VAR": objblock,
        }, {
            "inline": "true"
        });
    }
    return converter;
}

pbc.objectFunctionD.get('strip')['Str'] = textStrip('strip');
pbc.objectFunctionD.get('lstrip')['Str'] = textStrip('lstrip');
pbc.objectFunctionD.get('rstrip')['Str'] =  textStrip('rstrip');

function textAlign(mode){
    function converter(py2block, func, args, keywords, starargs, kwargs, node) {
        if (args.length !== 2) {
            throw new Error("Incorrect number of arguments");
        }
        var objblock = py2block.convert(func.value);
        var argblock1 = py2block.convert(args[0]);
        var argblock2 = py2block.convert(args[1]);
        return block("text_center", func.lineno, {
            'TEXT_CENTER': mode,
        }, {
            "VAR": objblock,
            "WID": argblock1,
            "Symbol": argblock2
        }, {
            "inline": "true"
        });
    }
    return converter;
}

pbc.objectFunctionD.get('ljust')['Str'] = textAlign('ljust');
pbc.objectFunctionD.get('center')['Str'] = textAlign('center');
pbc.objectFunctionD.get('rjust')['Str'] =  textAlign('rjust');

pbc.objectFunctionD.get('split')['Str'] = function converter(py2block, func, args, keywords, starargs, kwargs, node) {
        if (args.length !== 1) {
            throw new Error("Incorrect number of arguments");
        }
        var objblock = py2block.convert(func.value);
        var argblock = py2block.convert(args[0]);
        return block("text_split", func.lineno, {
        }, {
            "VAR": objblock,
            "VAL": argblock
        }, {
            "inline": "true"
        });
    }

pbc.objectFunctionD.get('replace')['Str'] = function converter(py2block, func, args, keywords, starargs, kwargs, node) {
        if (args.length !== 2) {
            throw new Error("Incorrect number of arguments");
        }
        var objblock = py2block.convert(func.value);
        var argblock1 = py2block.convert(args[0]);
        var argblock2 = py2block.convert(args[1]);
        return block("text_replace", func.lineno, {
        }, {
            "VAR": objblock,
            "STR1": argblock1,
            "STR2": argblock2
        }, {
            "inline": "true"
        });
    }

pbc.objectFunctionD.get('find')['Str'] = function converter(py2block, func, args, keywords, starargs, kwargs, node) {
        if (args.length !== 1) {
            throw new Error("Incorrect number of arguments");
        }
        var objblock = py2block.convert(func.value);
        var argblock = py2block.convert(args[0]);
        return block("text_find", func.lineno, {
        }, {
            "VAR": objblock,
            "STR": argblock
        }, {
            "inline": "true"
        });
    }

pbc.objectFunctionD.get('format')['Str'] = function converter(py2block, func, args, keywords, starargs, kwargs, node) {
        var objblock = py2block.convert(func.value);
        var d = py2block.convertElements("ADD", args);
        d['VAR'] = objblock;
        return block("text_format_noreturn", node.lineno, {
        }, d, {
            "inline": "true",
        }, {
            "@items":args.length
        });
    }<|endoftext|>


<commit_before>import React from "react";
import ImmutablePropTypes from "react-immutable-proptypes";
import { AgGridReact } from "ag-grid-react";
import "ag-grid/dist/styles/ag-grid.css";
import "ag-grid/dist/styles/ag-theme-balham.css";

import { LoadingOverlay } from "./LoadingOverlay";
import { SampleNameRenderer } from "./renderers/SampleNameRenderer";

const localeText = window.PAGE.i18n.agGrid;

export class Table extends React.Component {
  containerStyle = {
    boxSizing: "border-box",
    height: 600,
    width: "100%"
  };
  frameworkComponents = { LoadingOverlay, SampleNameRenderer };

  constructor(props) {
    super(props);

    const { fields, entries } = props;
    this.state = {
      fields,
      entries
    };
  }

  /*
  Allow access to the grids API
   */
  onGridReady = params => {
    this.api = params.api;
    this.columnApi = params.columnApi;
  };

  componentWillReceiveProps(nextProps) {
    /*
    Since entries is an immutable data source, this will only do a quick check!
    Therefore should be fast.
     */
    if (!nextProps.entries.equals(this.state.entries)) {
      this.setState({ entries: nextProps.entries });
    }
  }

  render() {
    return (

        <AgGridReact
          enableSorting={true}
          localeText={localeText}
          columnDefs={this.state.fields.toJS()}
          rowData={this.state.entries.toJS()}
          deltaRowDataMode={true}
          getRowNodeId={data => data.code}
          frameworkComponents={this.frameworkComponents}
          loadingOverlayComponent="LoadingOverlay"
          onGridReady={this.onGridReady}
        />

    );
  }
}

Table.propTypes = {
  fields: ImmutablePropTypes.list.isRequired,
  entries: ImmutablePropTypes.list
};
<commit_msg>Fields and entries do not need to be kept in state.<commit_after>import React from "react";
import ImmutablePropTypes from "react-immutable-proptypes";
import { AgGridReact } from "ag-grid-react";
import "ag-grid/dist/styles/ag-grid.css";
import "ag-grid/dist/styles/ag-theme-balham.css";

import { LoadingOverlay } from "./LoadingOverlay";
import { SampleNameRenderer } from "./renderers/SampleNameRenderer";

const localeText = window.PAGE.i18n.agGrid;

export class Table extends React.Component {
  containerStyle = {
    boxSizing: "border-box",
    height: 600,
    width: "100%"
  };
  frameworkComponents = { LoadingOverlay, SampleNameRenderer };

  constructor(props) {
    super(props);
  }

  /*
  Allow access to the grids API
   */
  onGridReady = params => {
    this.api = params.api;
    this.columnApi = params.columnApi;
  };

  render() {
    return (

        <AgGridReact
          enableSorting={true}
          localeText={localeText}
          columnDefs={this.props.fields.toJS()}
          rowData={this.props.entries.toJS()}
          deltaRowDataMode={true}
          getRowNodeId={data => data.code}
          frameworkComponents={this.frameworkComponents}
          loadingOverlayComponent="LoadingOverlay"
          onGridReady={this.onGridReady}
        />

    );
  }
}

Table.propTypes = {
  fields: ImmutablePropTypes.list.isRequired,
  entries: ImmutablePropTypes.list
};
<|endoftext|>


<commit_before>/* global d3, moment */
var url = hqImport('hqwebapp/js/initial_page_data').reverse;

function AdolescentWomenController($scope, $routeParams, $location, $filter, demographicsService,
                                             locationsService, userLocationId, storageService) {
    var vm = this;
    if (Object.keys($location.search()).length === 0) {
        $location.search(storageService.getKey('search'));
    } else {
        storageService.setKey('search', $location.search());
    }
    vm.userLocationId = userLocationId;
    vm.filtersData = $location.search();
    vm.label = "Adolescent Girls (11-14 years)";
    vm.step = $routeParams.step;
    vm.steps = {
        'map': {route: '/adolescent_girls/map', label: 'Map View'},
        'chart': {route: '/adolescent_girls/chart', label: 'Chart View'},
    };
    vm.data = {
        legendTitle: 'Number of Women',
    };
    vm.chartData = null;
    vm.top_five = [];
    vm.bottom_five = [];
    vm.selectedLocations = [];
    vm.all_locations = [];
    vm.location_type = null;
    vm.loaded = false;
    vm.filters = ['age', 'gender'];

    vm.rightLegend = {
        info: 'Total number of adolescent girls who are enrolled for Anganwadi Services',
    };

    vm.message = storageService.getKey('message') || false;

    $scope.$watch(function() {
        return vm.selectedLocations;
    }, function (newValue, oldValue) {
        if (newValue === oldValue || !newValue || newValue.length === 0) {
            return;
        }

        var isAWCSelected = (newValue.length === 6);
        if (isAWCSelected) {
            var supervisor = newValue[3];
            $location.search('location_id', supervisor.location_id);
            $location.search('selectedLocationLevel', 3);
            $location.search('location_name', supervisor.name);
            storageService.setKey('message', true);
            setTimeout(function() {
                storageService.setKey('message', false);
            }, 3000);
        }
        return newValue;
    }, true);

    vm.templatePopup = function(loc, row) {
        var valid = $filter('indiaNumbers')(row ? row.valid : 0);
        var all = $filter('indiaNumbers')(row ? row.all : 0);
        var percent = row ? d3.format('.2%')(row.valid / (row.all || 1)) : "N/A";
        return '
' +
            '
' + loc.properties.name + '
' +
            '
Number of adolescent girls (11 - 14 years) who are enrolled for Anganwadi Services: ' + valid + '' +
            '
Total number of adolescent girls (11 - 14 years) who are registered: ' + all + '' +
            '
Percentage of registered adolescent girls (11 - 14 years) who are enrolled for Anganwadi Services: ' + percent + '' +
            '
';
    };

    vm.loadData = function () {
        var loc_type = 'National';
        if (vm.location) {
            if (vm.location.location_type === 'supervisor') {
                loc_type = "Sector";
            } else {
                loc_type = vm.location.location_type.charAt(0).toUpperCase() + vm.location.location_type.slice(1);
            }
        }

        if (vm.location && _.contains(['block', 'supervisor', 'awc'], vm.location.location_type)) {
            vm.mode = 'sector';
            vm.steps['map'].label = loc_type + ' View';
        } else {
            vm.mode = 'map';
            vm.steps['map'].label = 'Map View: ' + loc_type;
        }

        vm.myPromise = demographicsService.getAdolescentGirlsData(vm.step, vm.filtersData).then(function(response) {
            if (vm.step === "map") {
                vm.data.mapData = response.data.report_data;
            } else if (vm.step === "chart") {
                vm.chartData = response.data.report_data.chart_data;
                vm.all_locations = response.data.report_data.all_locations;
                vm.top_five = response.data.report_data.top_five;
                vm.bottom_five = response.data.report_data.bottom_five;
                vm.location_type = response.data.report_data.location_type;
                vm.chartTicks = vm.chartData[0].values.map(function(d) { return d.x; });
                var max = Math.ceil(d3.max(vm.chartData, function(line) {
                    return d3.max(line.values, function(d) {
                        return d.y;
                    });
                }));
                var min = Math.ceil(d3.min(vm.chartData, function(line) {
                    return d3.min(line.values, function(d) {
                        return d.y;
                    });
                }));
                var range = max - min;
                vm.chartOptions.chart.forceY = [
                    (min - range/10) < 0 ? 0 : (min - range/10),
                    (max + range/10),
                ];
            }
        });
    };

    vm.init = function() {
        var locationId = vm.filtersData.location_id || vm.userLocationId;
        if (!vm.userLocationId || !locationId || locationId === 'all') {
            vm.loadData();
            vm.loaded = true;
            return;
        }
        locationsService.getLocation(locationId).then(function(location) {
            vm.location = location;
            vm.loadData();
            vm.loaded = true;
        });
    };

    vm.init();

    $scope.$on('filtersChange', function() {
        vm.loadData();
    });

    vm.moveToLocation = function(loc, index) {
        if (loc === 'national') {
            $location.search('location_id', '');
            $location.search('selectedLocationLevel', -1);
            $location.search('location_name', '');
        } else {
            $location.search('location_id', loc.location_id);
            $location.search('selectedLocationLevel', index);
            $location.search('location_name', loc.name);
        }
    };

    vm.chartOptions = {
        chart: {
            type: 'lineChart',
            height: 450,
            width: 1100,
            margin: {
                top: 20,
                right: 60,
                bottom: 60,
                left: 80,
            },
            x: function (d) {
                return d.x;
            },
            y: function (d) {
                return d.y;
            },
            color: d3.scale.category10().range(),
            useInteractiveGuideline: true,
            clipVoronoi: false,
            tooltips: true,
            xAxis: {
                axisLabel: '',
                showMaxMin: true,
                tickFormat: function (d) {
                    return d3.time.format('%b %Y')(new Date(d));
                },
                tickValues: function () {
                    return vm.chartTicks;
                },
                axisLabelDistance: -100,
            },

            yAxis: {
                axisLabel: '',
                tickFormat: function (d) {
                    return d3.format(",")(d);
                },
                axisLabelDistance: 20,
                forceY: [0],
            },
            callback: function (chart) {
                var tooltip = chart.interactiveLayer.tooltip;
                tooltip.contentGenerator(function (d) {

                    var day = _.find(vm.chartData[0].values, function(num) { return d3.time.format('%b %Y')(new Date(num['x'])) === d.value;});
                    return vm.tooltipContent(d.value, day);
                });
                return chart;
            },
        },
        caption: {
            enable: true,
            html: ' Total number of adolescent girls who are enrolled for Anganwadi Services',
            css: {
                'text-align': 'center',
                'margin': '0 auto',
                'width': '900px',
            },
        },
    };

    vm.tooltipContent = function (monthName, day) {
        return "
" + monthName + "

"
            + "
Number of adolescent girls (11 - 14 years) who are enrolled for Anganwadi Services: " + $filter('indiaNumbers')(day.y) + "
"
            + "
Total number of adolescent girls (11 - 14 years) who are registered: " + $filter('indiaNumbers')(day.all) + "
"
            + "
Percentage of registered adolescent girls (11 - 14 years) who are enrolled for Anganwadi Services: " + d3.format('.2%')(day.y / (day.all || 1)) + "
";
    };

    vm.showAllLocations = function () {
        return vm.all_locations.length < 10;
    };
}

AdolescentWomenController.$inject = ['$scope', '$routeParams', '$location', '$filter', 'demographicsService', 'locationsService', 'userLocationId', 'storageService'];

window.angular.module('icdsApp').directive('adolescentGirls', function() {
    return {
        restrict: 'E',
        templateUrl: url('icds-ng-template', 'map-chart'),
        bindToController: true,
        scope: {
            data: '=',
        },
        controller: AdolescentWomenController,
        controllerAs: '$ctrl',
    };
});
<commit_msg>added missing change to the report<commit_after>/* global d3, moment */
var url = hqImport('hqwebapp/js/initial_page_data').reverse;

function AdolescentWomenController($scope, $routeParams, $location, $filter, demographicsService,
                                             locationsService, userLocationId, storageService) {
    var vm = this;
    if (Object.keys($location.search()).length === 0) {
        $location.search(storageService.getKey('search'));
    } else {
        storageService.setKey('search', $location.search());
    }
    vm.userLocationId = userLocationId;
    vm.filtersData = $location.search();
    vm.label = "Adolescent Girls (11-14 years)";
    vm.step = $routeParams.step;
    vm.steps = {
        'map': {route: '/adolescent_girls/map', label: 'Map View'},
        'chart': {route: '/adolescent_girls/chart', label: 'Chart View'},
    };
    vm.data = {
        legendTitle: 'Number of Women',
    };
    vm.chartData = null;
    vm.top_five = [];
    vm.bottom_five = [];
    vm.selectedLocations = [];
    vm.all_locations = [];
    vm.location_type = null;
    vm.loaded = false;
    vm.filters = ['age', 'gender'];

    vm.rightLegend = {
        info: 'Total number of adolescent girls who are enrolled for Anganwadi Services',
    };

    vm.message = storageService.getKey('message') || false;

    $scope.$watch(function() {
        return vm.selectedLocations;
    }, function (newValue, oldValue) {
        if (newValue === oldValue || !newValue || newValue.length === 0) {
            return;
        }

        var isAWCSelected = (newValue.length === 6);
        if (isAWCSelected) {
            var supervisor = newValue[3];
            $location.search('location_id', supervisor.location_id);
            $location.search('selectedLocationLevel', 3);
            $location.search('location_name', supervisor.name);
            storageService.setKey('message', true);
            setTimeout(function() {
                storageService.setKey('message', false);
            }, 3000);
        }
        return newValue;
    }, true);

    vm.templatePopup = function(loc, row) {
        var valid = $filter('indiaNumbers')(row ? row.valid : 0);
        var all = $filter('indiaNumbers')(row ? row.all : 0);
        var percent = row ? d3.format('.2%')(row.valid / (row.all || 1)) : "N/A";
        return '
' +
            '
' + loc.properties.name + '
' +
            '
Number of adolescent girls (11 - 14 years) who are enrolled for Anganwadi Services: ' + valid + '' +
            '
Total number of adolescent girls (11 - 14 years) who are registered: ' + all + '' +
            '
Percentage of registered adolescent girls (11 - 14 years) who are enrolled for Anganwadi Services: ' + percent + '' +
            '
';
    };

    vm.loadData = function () {
        var loc_type = 'National';
        if (vm.location) {
            if (vm.location.location_type === 'supervisor') {
                loc_type = "Sector";
            } else {
                loc_type = vm.location.location_type.charAt(0).toUpperCase() + vm.location.location_type.slice(1);
            }
        }

        if (vm.location && _.contains(['block', 'supervisor', 'awc'], vm.location.location_type)) {
            vm.mode = 'sector';
            vm.steps['map'].label = loc_type + ' View';
        } else {
            vm.mode = 'map';
            vm.steps['map'].label = 'Map View: ' + loc_type;
        }

        vm.myPromise = demographicsService.getAdolescentGirlsData(vm.step, vm.filtersData).then(function(response) {
            if (vm.step === "map") {
                vm.data.mapData = response.data.report_data;
            } else if (vm.step === "chart") {
                vm.chartData = response.data.report_data.chart_data;
                vm.all_locations = response.data.report_data.all_locations;
                vm.top_five = response.data.report_data.top_five;
                vm.bottom_five = response.data.report_data.bottom_five;
                vm.location_type = response.data.report_data.location_type;
                vm.chartTicks = vm.chartData[0].values.map(function(d) { return d.x; });
                var max = Math.ceil(d3.max(vm.chartData, function(line) {
                    return d3.max(line.values, function(d) {
                        return d.y;
                    });
                }));
                var min = Math.ceil(d3.min(vm.chartData, function(line) {
                    return d3.min(line.values, function(d) {
                        return d.y;
                    });
                }));
                var range = max - min;
                vm.chartOptions.chart.forceY = [
                    (min - range/10) < 0 ? 0 : (min - range/10),
                    (max + range/10),
                ];
            }
        });
    };

    vm.init = function() {
        var locationId = vm.filtersData.location_id || vm.userLocationId;
        if (!locationId || ["all", "null", "undefined"].indexOf(locationId) >= 0) {
            vm.loadData();
            vm.loaded = true;
            return;
        }
        locationsService.getLocation(locationId).then(function(location) {
            vm.location = location;
            vm.loadData();
            vm.loaded = true;
        });
    };

    vm.init();

    $scope.$on('filtersChange', function() {
        vm.loadData();
    });

    vm.moveToLocation = function(loc, index) {
        if (loc === 'national') {
            $location.search('location_id', '');
            $location.search('selectedLocationLevel', -1);
            $location.search('location_name', '');
        } else {
            $location.search('location_id', loc.location_id);
            $location.search('selectedLocationLevel', index);
            $location.search('location_name', loc.name);
        }
    };

    vm.chartOptions = {
        chart: {
            type: 'lineChart',
            height: 450,
            width: 1100,
            margin: {
                top: 20,
                right: 60,
                bottom: 60,
                left: 80,
            },
            x: function (d) {
                return d.x;
            },
            y: function (d) {
                return d.y;
            },
            color: d3.scale.category10().range(),
            useInteractiveGuideline: true,
            clipVoronoi: false,
            tooltips: true,
            xAxis: {
                axisLabel: '',
                showMaxMin: true,
                tickFormat: function (d) {
                    return d3.time.format('%b %Y')(new Date(d));
                },
                tickValues: function () {
                    return vm.chartTicks;
                },
                axisLabelDistance: -100,
            },

            yAxis: {
                axisLabel: '',
                tickFormat: function (d) {
                    return d3.format(",")(d);
                },
                axisLabelDistance: 20,
                forceY: [0],
            },
            callback: function (chart) {
                var tooltip = chart.interactiveLayer.tooltip;
                tooltip.contentGenerator(function (d) {

                    var day = _.find(vm.chartData[0].values, function(num) { return d3.time.format('%b %Y')(new Date(num['x'])) === d.value;});
                    return vm.tooltipContent(d.value, day);
                });
                return chart;
            },
        },
        caption: {
            enable: true,
            html: ' Total number of adolescent girls who are enrolled for Anganwadi Services',
            css: {
                'text-align': 'center',
                'margin': '0 auto',
                'width': '900px',
            },
        },
    };

    vm.tooltipContent = function (monthName, day) {
        return "
" + monthName + "

"
            + "
Number of adolescent girls (11 - 14 years) who are enrolled for Anganwadi Services: " + $filter('indiaNumbers')(day.y) + "
"
            + "
Total number of adolescent girls (11 - 14 years) who are registered: " + $filter('indiaNumbers')(day.all) + "
"
            + "
Percentage of registered adolescent girls (11 - 14 years) who are enrolled for Anganwadi Services: " + d3.format('.2%')(day.y / (day.all || 1)) + "
";
    };

    vm.showAllLocations = function () {
        return vm.all_locations.length < 10;
    };
}

AdolescentWomenController.$inject = ['$scope', '$routeParams', '$location', '$filter', 'demographicsService', 'locationsService', 'userLocationId', 'storageService'];

window.angular.module('icdsApp').directive('adolescentGirls', function() {
    return {
        restrict: 'E',
        templateUrl: url('icds-ng-template', 'map-chart'),
        bindToController: true,
        scope: {
            data: '=',
        },
        controller: AdolescentWomenController,
        controllerAs: '$ctrl',
    };
});
<|endoftext|>


<commit_before>'use strict'
const db = require('./../db').db
const StatisticsQuery = require('./StatisticsQuery')

/**
 * A class representing a rescue query
 */
class SystemStatisticsQuery extends StatisticsQuery {
  /**
   * Create a sequelize rescue query from a set of parameters
   * @constructor
   * @param params
   * @param connection
   */
  constructor (params, connection) {
    super(params, connection)

    this._query.attributes = [
      'system',
      [this.count, 'count']
    ]

    this._query.attributes = this._query.attributes.concat(this.compare('Rescue', this.comparators))

    this._query.group = ['system']
  }

  get comparators () {
    return [{
      fields: ['outcome'],
      options: [
        ['success', 'success'],
        ['failure', 'failure'],
        ['invalid', 'invalid'],
        ['other', 'other']
      ]
    },{
      fields: ['codeRed', 'platform', 'outcome'],
      options: [
        ['codered', true, null],
        ['coderedsuccess', true, null, 'success'],
        ['coderedfailure', true, null, 'failure'],
        ['pccodered', true, 'pc'],
        ['pccoderedsuccess', true, 'pc', 'success'],
        ['pccoderedfailure', true, 'pc', 'failure'],
        ['pscodered', true, 'ps'],
        ['pscoderedsuccess', true, 'ps', 'success'],
        ['pscoderedfailure', true, 'ps', 'failure'],
        ['xbcodered', true, 'xb'],
        ['xbcoderedsuccess', true, 'xb', 'success'],
        ['xbcoderedfailure', true, 'xb', 'failure']
      ]
    },{
      fields: ['platform', 'outcome'],
      options: [
        ['pc', 'pc'],
        ['pcsucess', 'pc', 'success'],
        ['pcfailure', 'pc', 'failure'],
        ['ps', 'ps'],
        ['pssuccess', 'ps', 'success'],
        ['psfailure', 'ps', 'failure'],
        ['xb', 'xb'],
        ['xbsuccess', 'xb', 'success'],
        ['xbfailure', 'xb', 'failure']
      ],
    }]
  }

  get count () {
    return db.fn('COUNT', 'system')
  }
}

module.exports = SystemStatisticsQuery<commit_msg>Fix mispelled statistics property<commit_after>'use strict'
const db = require('./../db').db
const StatisticsQuery = require('./StatisticsQuery')

/**
 * A class representing a rescue query
 */
class SystemStatisticsQuery extends StatisticsQuery {
  /**
   * Create a sequelize rescue query from a set of parameters
   * @constructor
   * @param params
   * @param connection
   */
  constructor (params, connection) {
    super(params, connection)

    this._query.attributes = [
      'system',
      [this.count, 'count']
    ]

    this._query.attributes = this._query.attributes.concat(this.compare('Rescue', this.comparators))

    this._query.group = ['system']
  }

  get comparators () {
    return [{
      fields: ['outcome'],
      options: [
        ['success', 'success'],
        ['failure', 'failure'],
        ['invalid', 'invalid'],
        ['other', 'other']
      ]
    },{
      fields: ['codeRed', 'platform', 'outcome'],
      options: [
        ['codered', true, null],
        ['coderedsuccess', true, null, 'success'],
        ['coderedfailure', true, null, 'failure'],
        ['pccodered', true, 'pc'],
        ['pccoderedsuccess', true, 'pc', 'success'],
        ['pccoderedfailure', true, 'pc', 'failure'],
        ['pscodered', true, 'ps'],
        ['pscoderedsuccess', true, 'ps', 'success'],
        ['pscoderedfailure', true, 'ps', 'failure'],
        ['xbcodered', true, 'xb'],
        ['xbcoderedsuccess', true, 'xb', 'success'],
        ['xbcoderedfailure', true, 'xb', 'failure']
      ]
    },{
      fields: ['platform', 'outcome'],
      options: [
        ['pc', 'pc'],
        ['pcsuccess', 'pc', 'success'],
        ['pcfailure', 'pc', 'failure'],
        ['ps', 'ps'],
        ['pssuccess', 'ps', 'success'],
        ['psfailure', 'ps', 'failure'],
        ['xb', 'xb'],
        ['xbsuccess', 'xb', 'success'],
        ['xbfailure', 'xb', 'failure']
      ],
    }]
  }

  get count () {
    return db.fn('COUNT', 'system')
  }
}

module.exports = SystemStatisticsQuery<|endoftext|>


<commit_before>/**
 * LightController
 *
 * @description :: Server-side logic for rdocs-light
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */
var Promise = require('bluebird');

module.exports = {
  /**
  * @api {get} api/light/packages/:name/versions/:version/topics/:function Request Topic Information for Rdocs light
  * @apiName Get Topic in package (latest version which contains the topic)
  * @apiGroup Light
  *
  * @apiParam   {String}   name                          Name of the package
  * @apiParam   {String}   function                      Name of the topic
  * @apiParam   {String}   version                       Version of the package {optional}
  *
  * @apiSuccess {String}   name                          Name of this topic
  * @apiSuccess {String}   title                         Title of the topic
  * @apiSuccess {String}   description                   Description of the topic
  * @apiSuccess {String}   url                           The Url to `self`
  * @apiSuccess {Object}   package_version               Informations about the version of the package
  * @apiSuccess {String}   package_version.url           Url to this version
  * @apiSuccess {String}   package_version.package_name  Name of the package of this version
  * @apiSuccess {String}   package_version.version       String describing the version of the package
  * @apiSuccess {Object[]} anchors                       Anchors shown at the bottom of the widget
  * @apiSuccess {String}   anchors.title                 The title to be shown
  * @apiSuccess {String}   anchors.anchor                The Html-anchor linking to the section
  */
  topicSearch: function(req,res) {
    var packageName = req.param('name'),
        topic_name = req.param('function'),
        version = req.param('version');

    if (topic_name.endsWith('.html')) topic_name = topic_name.replace('.html', '');
    var key = 'light_' + packageName;
    var latest_version = undefined;
    const packageVersionWhere = {
      package_name: packageName,
    }
    if(version){
      key += '_' + version;
      packageVersionWhere.version = version;
    }
    key += '_' + topic_name;

    RedisService.getJSONFromCache(key, res, RedisService.DAILY, function() {
      return Topic.findAll({
        where: {name: topic_name},
        include: [{
          model: PackageVersion,
          as: 'package_version',
          where: packageVersionWhere,
          include: [
            { model: Package, as: 'package', attributes: ['name', 'latest_version_id', 'type_id' ]},
          ]
        },
        {model: Argument, as: 'arguments', attributes: ['name', 'description', 'topic_id'], separate:true },
        {model: Section, as: 'sections', attributes: ['name', 'description', 'topic_id'], separate:true },
        {model: Tag, as: 'keywords', attributes: ['name']},
        {model: Alias, as: 'aliases', attributes: ['name', 'topic_id'], separate: true },
        ]
      }).then(function(topicInstances) {
        if(topicInstances === null) {
          return Topic.findByAliasInPackage(packageName, topic, version).then(function(topicInstances) {
            if(!topicInstances) return null;
            else return topicInstances.sort(PackageService.compareVersions('desc', function(topic) {
            return topic.package_version.version }))[0];
          });
        }
        else return topicInstances.sort(PackageService.compareVersions('desc', function(topic) {
            return topic.package_version.version }))[0];
      }).then(function(topic){
        if(topic === undefined || topic === null) return null;
        return TopicService.processHrefs(topic, false);
      }).then(function(topic) {
        var part = {};
        if(topic !== null){
          part.name = topic.name;
          part.title = topic.title;
          part.description = topic.description;
          part.url = 'https:' + process.env.BASE_URL + topic.package_version.uri + '/topics/' + topic_name;
          part.package_version = {
            package_name: topic.package_version.package_name,
            version: topic.package_version.version,
            url: 'https:' + process.env.BASE_URL + topic.package_version.uri,
          };

          part.anchors = [];
          LightService.addAnchorItem(part.anchors, topic.keywords, "keywords", "kywrds");
          LightService.addAnchorItem(part.anchors, topic.usage, "usage", "usg");
          LightService.addAnchorItem(part.anchors, topic.arguments, "arguments", "argmnts");
          LightService.addAnchorItem(part.anchors, topic.details, "details", "dtls");
          LightService.addAnchorItem(part.anchors, topic.value, "value", "vl");
          LightService.addAnchorItem(part.anchors, topic.note, "note", "nt");
          LightService.addAnchorItem(part.anchors, topic.sections, "sections", "sctns");
          LightService.addAnchorItem(part.anchors, topic.references, "references", "rfrncs");
          LightService.addAnchorItem(part.anchors, topic.seealso, "see also", "sls");
          // LightService.addAnchorItem(part.anchors, topic.aliases, "aliases", "alss");
          LightService.addAnchorItem(part.anchors, topic.examples, "examples", "exmpls");

        }
        return part;
      });
    })
    .then(function(topic){
      return res.json(topic);
    })
    .catch(function(err) {
      return res.negotiate(err);
    });
  },

  /**
  * @api {get} api/light/packages/:name Request Package Information for Rdocs light
  * @apiName Get Package
  * @apiGroup Light
  *
  * @apiParam   {String}   name               Name of the package
  * @apiParam   {String}   version            Version of the package {optional}
  *
  * @apiSuccess {String}   name               Package name
  * @apiSuccess {String}   url                Url to the package
  * @apiSuccess {Object}   version            Information about the version of the package
  * @apiSuccess {String}   version.version    String describing the latest version of the package
  * @apiSuccess {String}   version.url        Url to the version
  * @apiSuccess {String}   title              Title of the latest version
  * @apiSuccess {String}   description        Description of the latest package version
  * @apiSuccess {Object[]} anchors            Anchors shown at the bottom of the widget
  * @apiSuccess {String}   anchors.title      The title to be shown
  * @apiSuccess {String}   anchors.anchor     The Html-anchor linking to the section
  */
  packageSearch: function(req, res) {
    var packageName = req.param('name');
    var version = req.param('version');

    if (packageName.endsWith('.html')) packageName = packageName.replace('.html', '');
    var key = 'light_' + packageName;
    var latest_version = undefined;
    if(version){
      key += '_' + version;
      latest_version = {
        latest_version: {
          version: version
        }
      }
    }

    RedisService.getJSONFromCache(key, res, RedisService.DAILY, function() {
      return Promise.resolve(latest_version || Package.getLatestVersionNumber(packageName))
        .then(function(version){
          if(!version) return null;

          var prefix = "rpackages/unarchived/" + packageName + "/" + version.latest_version.version + "/" + "vignettes/";
          var params = {
            Bucket: process.env.AWS_BUCKET,
            Delimiter: '/',
            Prefix: prefix
          };

          var vignettesPromise = s3.listObjects(params).promise();

          var packagePromise = Package.findOne({
            include:[{
              model:PackageVersion,
              as:'versions',
              required:true,
              include: [
                { model: Topic, as: 'topics',
                  attributes: ['package_version_id', 'name', 'title', 'id'],
                  separate: true }
              ],
              where:{
                version: version.latest_version.version
              }
            }],
            where:{
              name:packageName
            }
          });
          return Promise.join(vignettesPromise, packagePromise, function(vignettes, package){
            if(!package)
              return {};
            package.version = package.versions[0];
            var version = {};
            version.package_name = package.name;
            version.url = 'https:' + process.env.BASE_URL + package.uri;
            version.version = {
              version: package.version.version,
              url: 'https:' + process.env.BASE_URL + package.version.uri
            };
            version.title = package.version.title;
            version.description = package.version.description;

            version.anchors = [];
            LightService.addAnchorItem(version.anchors, package.version.readmemd, "readme", "readme");
            LightService.addAnchorItem(version.anchors, package.version.topics, "topics", "functions");
            LightService.addAnchorItem(version.anchors, vignettes.Contents, "vignettes", "vignettes");
            LightService.addAnchorItem(version.anchors, [true], "downloads", "downloads");
            LightService.addAnchorItem(version.anchors, [true], "details", "details");

            return version;
          });
        });
    })
    .then(function(version){
      return res.json(version);
    })
    .catch(function(err) {
      return res.negotiate(err);
    });

  }
}
<commit_msg>fix return value for unknown package<commit_after>/**
 * LightController
 *
 * @description :: Server-side logic for rdocs-light
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */
var Promise = require('bluebird');

module.exports = {
  /**
  * @api {get} api/light/packages/:name/versions/:version/topics/:function Request Topic Information for Rdocs light
  * @apiName Get Topic in package (latest version which contains the topic)
  * @apiGroup Light
  *
  * @apiParam   {String}   name                          Name of the package
  * @apiParam   {String}   function                      Name of the topic
  * @apiParam   {String}   version                       Version of the package {optional}
  *
  * @apiSuccess {String}   name                          Name of this topic
  * @apiSuccess {String}   title                         Title of the topic
  * @apiSuccess {String}   description                   Description of the topic
  * @apiSuccess {String}   url                           The Url to `self`
  * @apiSuccess {Object}   package_version               Informations about the version of the package
  * @apiSuccess {String}   package_version.url           Url to this version
  * @apiSuccess {String}   package_version.package_name  Name of the package of this version
  * @apiSuccess {String}   package_version.version       String describing the version of the package
  * @apiSuccess {Object[]} anchors                       Anchors shown at the bottom of the widget
  * @apiSuccess {String}   anchors.title                 The title to be shown
  * @apiSuccess {String}   anchors.anchor                The Html-anchor linking to the section
  */
  topicSearch: function(req,res) {
    var packageName = req.param('name'),
        topic_name = req.param('function'),
        version = req.param('version');

    if (topic_name.endsWith('.html')) topic_name = topic_name.replace('.html', '');
    var key = 'light_' + packageName;
    var latest_version = undefined;
    const packageVersionWhere = {
      package_name: packageName,
    }
    if(version){
      key += '_' + version;
      packageVersionWhere.version = version;
    }
    key += '_' + topic_name;

    RedisService.getJSONFromCache(key, res, RedisService.DAILY, function() {
      return Topic.findAll({
        where: {name: topic_name},
        include: [{
          model: PackageVersion,
          as: 'package_version',
          where: packageVersionWhere,
          include: [
            { model: Package, as: 'package', attributes: ['name', 'latest_version_id', 'type_id' ]},
          ]
        },
        {model: Argument, as: 'arguments', attributes: ['name', 'description', 'topic_id'], separate:true },
        {model: Section, as: 'sections', attributes: ['name', 'description', 'topic_id'], separate:true },
        {model: Tag, as: 'keywords', attributes: ['name']},
        {model: Alias, as: 'aliases', attributes: ['name', 'topic_id'], separate: true },
        ]
      }).then(function(topicInstances) {
        if(topicInstances === null) {
          return Topic.findByAliasInPackage(packageName, topic, version).then(function(topicInstances) {
            if(!topicInstances) return null;
            else return topicInstances.sort(PackageService.compareVersions('desc', function(topic) {
            return topic.package_version.version }))[0];
          });
        }
        else return topicInstances.sort(PackageService.compareVersions('desc', function(topic) {
            return topic.package_version.version }))[0];
      }).then(function(topic){
        if(topic === undefined || topic === null) return null;
        return TopicService.processHrefs(topic, false);
      }).then(function(topic) {
        var part = {};
        if(topic !== null){
          part.name = topic.name;
          part.title = topic.title;
          part.description = topic.description;
          part.url = 'https:' + process.env.BASE_URL + topic.package_version.uri + '/topics/' + topic_name;
          part.package_version = {
            package_name: topic.package_version.package_name,
            version: topic.package_version.version,
            url: 'https:' + process.env.BASE_URL + topic.package_version.uri,
          };

          part.anchors = [];
          LightService.addAnchorItem(part.anchors, topic.keywords, "keywords", "kywrds");
          LightService.addAnchorItem(part.anchors, topic.usage, "usage", "usg");
          LightService.addAnchorItem(part.anchors, topic.arguments, "arguments", "argmnts");
          LightService.addAnchorItem(part.anchors, topic.details, "details", "dtls");
          LightService.addAnchorItem(part.anchors, topic.value, "value", "vl");
          LightService.addAnchorItem(part.anchors, topic.note, "note", "nt");
          LightService.addAnchorItem(part.anchors, topic.sections, "sections", "sctns");
          LightService.addAnchorItem(part.anchors, topic.references, "references", "rfrncs");
          LightService.addAnchorItem(part.anchors, topic.seealso, "see also", "sls");
          // LightService.addAnchorItem(part.anchors, topic.aliases, "aliases", "alss");
          LightService.addAnchorItem(part.anchors, topic.examples, "examples", "exmpls");

        }
        return part;
      });
    })
    .then(function(topic){
      return res.json(topic);
    })
    .catch(function(err) {
      return res.negotiate(err);
    });
  },

  /**
  * @api {get} api/light/packages/:name Request Package Information for Rdocs light
  * @apiName Get Package
  * @apiGroup Light
  *
  * @apiParam   {String}   name               Name of the package
  * @apiParam   {String}   version            Version of the package {optional}
  *
  * @apiSuccess {String}   name               Package name
  * @apiSuccess {String}   url                Url to the package
  * @apiSuccess {Object}   version            Information about the version of the package
  * @apiSuccess {String}   version.version    String describing the latest version of the package
  * @apiSuccess {String}   version.url        Url to the version
  * @apiSuccess {String}   title              Title of the latest version
  * @apiSuccess {String}   description        Description of the latest package version
  * @apiSuccess {Object[]} anchors            Anchors shown at the bottom of the widget
  * @apiSuccess {String}   anchors.title      The title to be shown
  * @apiSuccess {String}   anchors.anchor     The Html-anchor linking to the section
  */
  packageSearch: function(req, res) {
    var packageName = req.param('name');
    var version = req.param('version');

    if (packageName.endsWith('.html')) packageName = packageName.replace('.html', '');
    var key = 'light_' + packageName;
    var latest_version = undefined;
    if(version){
      key += '_' + version;
      latest_version = {
        latest_version: {
          version: version
        }
      }
    }

    RedisService.getJSONFromCache(key, res, RedisService.DAILY, function() {
      return Promise.resolve(latest_version || Package.getLatestVersionNumber(packageName))
        .then(function(version){
          if(!version) return {};

          var prefix = "rpackages/unarchived/" + packageName + "/" + version.latest_version.version + "/" + "vignettes/";
          var params = {
            Bucket: process.env.AWS_BUCKET,
            Delimiter: '/',
            Prefix: prefix
          };

          var vignettesPromise = s3.listObjects(params).promise();

          var packagePromise = Package.findOne({
            include:[{
              model:PackageVersion,
              as:'versions',
              required:true,
              include: [
                { model: Topic, as: 'topics',
                  attributes: ['package_version_id', 'name', 'title', 'id'],
                  separate: true }
              ],
              where:{
                version: version.latest_version.version
              }
            }],
            where:{
              name:packageName
            }
          });
          return Promise.join(vignettesPromise, packagePromise, function(vignettes, package){
            if(!package)
              return {};
            package.version = package.versions[0];
            var version = {};
            version.package_name = package.name;
            version.url = 'https:' + process.env.BASE_URL + package.uri;
            version.version = {
              version: package.version.version,
              url: 'https:' + process.env.BASE_URL + package.version.uri
            };
            version.title = package.version.title;
            version.description = package.version.description;

            version.anchors = [];
            LightService.addAnchorItem(version.anchors, package.version.readmemd, "readme", "readme");
            LightService.addAnchorItem(version.anchors, package.version.topics, "topics", "functions");
            LightService.addAnchorItem(version.anchors, vignettes.Contents, "vignettes", "vignettes");
            LightService.addAnchorItem(version.anchors, [true], "downloads", "downloads");
            LightService.addAnchorItem(version.anchors, [true], "details", "details");

            return version;
          });
        });
    })
    .then(function(version){
      return res.json(version);
    })
    .catch(function(err) {
      return res.negotiate(err);
    });

  }
}
<|endoftext|>


<commit_before>import { User } from '../models/user';
import { chain, prop, concat } from 'ramda';

export default function renderAllPhotos(req, res) {
  return User.find({ photos: { $ne: null } })
  .then((users) => {
    const urls = concat(
      chain(prop('editedPhoto'), users),
      chain(prop('photos'), users));
    return res.render('images', { images: urls });
  });
}
<commit_msg>Restrict it to sharable photos<commit_after>import { User } from '../models/user';
import { chain, prop, concat } from 'ramda';

export default function renderAllPhotos(req, res) {
  return User.find({ photos: { $ne: null }, state: 'APPROVED' })
  .then((users) => {
    const urls = concat(
      chain(prop('editedPhoto'), users),
      chain(prop('photos'), users));
    return res.render('images', { images: urls });
  });
}
<|endoftext|>