<commit_before>// The admin bar module implements Apostrophe's admin bar at the top of the screen. Any module
// can register a button (or more than one) for this bar by calling the `add` method of this
// module. Buttons can also be grouped into dropdown menus and restricted to those with
// particular permissions. [apostrophe-pieces](../apostrophe-pieces/index.html) automatically
// takes advantage of this module.
//
// On the browser side there are also conveniences to implement jQuery handlers for these
// menu items.
var _ = require('@sailshq/lodash');
module.exports = {
  alias: 'adminBar',
  // Push the assets and the browser call to create the browser-side singleton
  // that provides `apos.adminBar.link`. Most server-side initialization happens
  // in `self.modulesReady` rather than here.
  afterConstruct: function(self) {
    self.pushAssets();
  },
  construct: function(self, options) {
    self.items = [];
    self.groups = [];
    self.groupLabels = {};
    // Add an item to the admin bar.
    //
    // The name argument becomes the value of the `data-apos-admin-bar-item`
    // attribute of the admin bar item.
    //
    // `permission` should be a permission name such as `admin`
    // (the user must be a full admin) or `edit-apostrophe-event`
    // (the user can create events and edit their own). If
    // `permission` is null then being logged in is
    // good enough to see the item. (Securing your actual routes that
    // respond to these items is up to you.)
    //
    // Usually just one admin bar item per module makes sense, so it's
    // common to pass `self.__meta.name` (the module's name) as the name argument.
    //
    // For example, the pieces module does this:
    //
    // ```
    // self.apos.adminBar.add(self.__meta.name, self.pluralLabel, 'edit')
    // ```
    //
    // If you have an `events` module that subclasses pieces, then this
    // creates an admin bar item with a data-apos-admin-item="events" attribute.
    //
    // Browser side, you can call `apos.adminBar.link('item-name', function() { ...})`
    // to conveniently set up an event handler that fires when this button is clicked.
    // Or, if you wish to create an ordinary link, you can pass the `href` option
    // as part of the `options` object (fourth argument).
    //
    // You can use the `after` option to specify an admin bar item name
    // this item should appear immediately following.
    self.add = function(name, label, permission, options) {
      var index;
      var item = {
        name: name,
        label: label,
        permission: permission,
        options: options || {}
      };
      if (options && options.after) {
        index = _.findIndex(self.items, { name: options.after });
        if (index !== -1) {
          self.items.splice(index + 1, 0, item);
          return;
        }
      }
      self.items.push(item);
    };
    // Group several menu items together in the interface (currently
    // implemented as a dropdown menu). If `items` is an array of menu
    // item names, then the group's label is the same as the label of
    // the first item. If you wish the label to differ from the label
    // of the first item, instead pass an object with a `label` property
    // and an `items` property.
    self.group = function(items) {
      self.groups.push(items);
    };
    self.addHelpers({
      // Render the admin bar. If the user is not able to see any items,
      // nothing is rendered
      output: function() {
        // Find the subset of admin bar items this user is permitted to see
        var user = self.apos.templates.contextReq.user;
        if (!user) {
          return '';
        }
        var items = _.filter(self.items, function(item) {
          return self.itemIsVisible(self.apos.templates.contextReq, item);
        });
        if (!items.length) {
          return '';
        }
        // Find the combined items and group them up into menus.
        // groupedItems becomes an array that mixes standalone
        // admin bar items with menus.
        var groupedItems = [];
        var menu = false;
        _.each(items, function(item, i) {
          if (menu) {
            // We are already building up a grouped menu, but stop doing that
            // if this next item isn't part of it
            if (item.menuLeader === menu.leader.name) {
              menu.items.push(item);
              return;
            } else {
              menu = false;
            }
          }
          // Only build a menu if there are at least two items after filtering
          // for permissions
          if ((item.menuLeader === item.name) && (items[i + 1] && items[i + 1].menuLeader === item.name)) {
            menu = {
              menu: true,
              items: [ item ],
              leader: item,
              label: self.groupLabels[item.name] || item.label
            };
            groupedItems.push(menu);
          } else {
            groupedItems.push(item);
          }
        });
        return self.partial('adminBar', { items: groupedItems });
      }
    });
    // Like the assets module, we wait as long as humanly possible
    // to lock down the list of admin bar items, so that other modules
    // can bicker amongst themselves even during the `modulesReady` stage.
    // When we get to `afterInit`, we can no longer wait! Order and
    // group the admin bar items.
    self.afterInit = function() {
      self.orderItems();
      self.groupItems();
    };
    // Implement the `order` option. This insertion sort results
    // in putting everything otherwise unspecified at the end, as desired.
    // Items with the `last: true` option are moved to the end before the
    // explicit order is applied.
    //
    // Called by `afterInit`
    self.orderItems = function() {
      // Items with a preference to go last go last...
      var moving = [];
      while (true) {
        var moveIndex = _.findIndex(self.items, function(item) {
          return item.options.last;
        });
        if (moveIndex === -1) {
          break;
        }
        moving.push(self.items[moveIndex]);
        self.items.splice(moveIndex, 1);
      }
      self.items = self.items.concat(moving);
      // ... But then explicit order kicks in
      _.each(self.options.order || [], function(name) {
        var item = _.find(self.items, { name: name });
        if (item) {
          self.items = [ item ].concat(_.filter(self.items, function(item) {
            return item.name !== name;
          }));
        }
      });
    };
    // Marks items that have been grouped via the `groups` option — or via
    // `group` calls from modules, combined with the `addGroups` option —
    // with a `menuLeader` property and ensures that the items in a group
    // are consecutive in the order. We'll figure out the final menus at
    // render time so we can handle it properly if an individual
    // user only sees one of them, etc. Called by `afterInit`
    self.groupItems = function() {
      // Implement the groups and addGroups options. Mark the grouped items with a
      // `menuLeader` property.
      _.each(self.options.groups || self.groups.concat(self.options.addGroups || []), function(group) {
        if (group.label) {
          self.groupLabels[group.items[0]] = group.label;
          group = group.items;
        }
        _.each(group, function(name, groupIndex) {
          var item = _.find(self.items, { name: name });
          if (item) {
            item.menuLeader = group[0];
          } else {
            return;
          }
          // Make sure the submenu items wind up following the leader
          // in self.items in the appropriate order
          if (name !== item.menuLeader) {
            var indexLeader = _.findIndex(self.items, { name: item.menuLeader });
            if (indexLeader === -1) {
              throw new Error('Admin bar grouping error: no match for ' + item.menuLeader + ' in menu item ' + item.name);
            }
            var indexMe = _.findIndex(self.items, { name: name });
            if (indexMe !== (indexLeader + groupIndex)) {
              // Swap ourselves into the right position following our leader
              if (indexLeader + groupIndex < indexMe) {
                indexMe++;
              }
              self.items.splice(indexLeader + groupIndex, 0, item);
              self.items.splice(indexMe, 1);
            }
          }
        });
      });
    };
    self.pushAssets = function() {
      self.pushAsset('script', 'user', { when: 'user' });
      options.browser = options.browser || {};
      var closeDelay = (self.options.closeDelay || self.options.closeDelay === 0 ? self.apos.launder.integer(self.options.closeDelay) : null);
      _.extend(options.browser, {
        openOnLoad: (!!(typeof self.options.openOnLoad === 'undefined' || self.options.openOnLoad)),
        openOnHomepageLoad: (!!(typeof self.options.openOnHomepageLoad === 'undefined' || self.options.openOnHomepageLoad)),
        closeDelay: typeof closeDelay === 'number' ? closeDelay : 3000
      });
      self.apos.push.browserCall('user', 'apos.create(?, ?)', self.__meta.name, options.browser);
    };

    // Determine if the specified admin bar item object should
    // be rendered or not, for the given req; based on item.permission
    // if any. `req.user` is guaranteed to exist at this point.
    self.itemIsVisible = function(req, item) {
      if (!item.permission) {
        // Being logged in is good enough to see this
        return true;
      }
      return self.apos.permissions.can(req, item.permission);
    };
  }
};
<commit_msg>Add documentation for new configuration options<commit_after>// The admin bar module implements Apostrophe's admin bar at the top of the screen. Any module
// can register a button (or more than one) for this bar by calling the `add` method of this
// module. Buttons can also be grouped into dropdown menus and restricted to those with
// particular permissions. [apostrophe-pieces](../apostrophe-pieces/index.html) automatically
// takes advantage of this module.
//
// The admin bar slides out on all pages by default. It's possible to modify this behavior
// by adding one of the following options in app.js:
// ```
// modules: {
//   'apostrophe-admin-bar': {
//     openOnLoad: false,
//     openOnHomepageLoad: true,
//     closeDelay: 5000
//   },
//   .... more modules ...
// }
// ```
// In the above example, the admin bar stays closed on all sub pages of the site, but opens on the
// homepage and stays open for 5 seconds (default is 3 seconds).
// `closeDelay` is a global configuration and changes both the homepage and all subpages.
//
// On the browser side there are also conveniences to implement jQuery handlers for these
// menu items.

var _ = require('@sailshq/lodash');
module.exports = {
  alias: 'adminBar',
  // Push the assets and the browser call to create the browser-side singleton
  // that provides `apos.adminBar.link`. Most server-side initialization happens
  // in `self.modulesReady` rather than here.
  afterConstruct: function(self) {
    self.pushAssets();
  },
  construct: function(self, options) {
    self.items = [];
    self.groups = [];
    self.groupLabels = {};
    // Add an item to the admin bar.
    //
    // The name argument becomes the value of the `data-apos-admin-bar-item`
    // attribute of the admin bar item.
    //
    // `permission` should be a permission name such as `admin`
    // (the user must be a full admin) or `edit-apostrophe-event`
    // (the user can create events and edit their own). If
    // `permission` is null then being logged in is
    // good enough to see the item. (Securing your actual routes that
    // respond to these items is up to you.)
    //
    // Usually just one admin bar item per module makes sense, so it's
    // common to pass `self.__meta.name` (the module's name) as the name argument.
    //
    // For example, the pieces module does this:
    //
    // ```
    // self.apos.adminBar.add(self.__meta.name, self.pluralLabel, 'edit')
    // ```
    //
    // If you have an `events` module that subclasses pieces, then this
    // creates an admin bar item with a data-apos-admin-item="events" attribute.
    //
    // Browser side, you can call `apos.adminBar.link('item-name', function() { ...})`
    // to conveniently set up an event handler that fires when this button is clicked.
    // Or, if you wish to create an ordinary link, you can pass the `href` option
    // as part of the `options` object (fourth argument).
    //
    // You can use the `after` option to specify an admin bar item name
    // this item should appear immediately following.
    self.add = function(name, label, permission, options) {
      var index;
      var item = {
        name: name,
        label: label,
        permission: permission,
        options: options || {}
      };
      if (options && options.after) {
        index = _.findIndex(self.items, { name: options.after });
        if (index !== -1) {
          self.items.splice(index + 1, 0, item);
          return;
        }
      }
      self.items.push(item);
    };
    // Group several menu items together in the interface (currently
    // implemented as a dropdown menu). If `items` is an array of menu
    // item names, then the group's label is the same as the label of
    // the first item. If you wish the label to differ from the label
    // of the first item, instead pass an object with a `label` property
    // and an `items` property.
    self.group = function(items) {
      self.groups.push(items);
    };
    self.addHelpers({
      // Render the admin bar. If the user is not able to see any items,
      // nothing is rendered
      output: function() {
        // Find the subset of admin bar items this user is permitted to see
        var user = self.apos.templates.contextReq.user;
        if (!user) {
          return '';
        }
        var items = _.filter(self.items, function(item) {
          return self.itemIsVisible(self.apos.templates.contextReq, item);
        });
        if (!items.length) {
          return '';
        }
        // Find the combined items and group them up into menus.
        // groupedItems becomes an array that mixes standalone
        // admin bar items with menus.
        var groupedItems = [];
        var menu = false;
        _.each(items, function(item, i) {
          if (menu) {
            // We are already building up a grouped menu, but stop doing that
            // if this next item isn't part of it
            if (item.menuLeader === menu.leader.name) {
              menu.items.push(item);
              return;
            } else {
              menu = false;
            }
          }
          // Only build a menu if there are at least two items after filtering
          // for permissions
          if ((item.menuLeader === item.name) && (items[i + 1] && items[i + 1].menuLeader === item.name)) {
            menu = {
              menu: true,
              items: [ item ],
              leader: item,
              label: self.groupLabels[item.name] || item.label
            };
            groupedItems.push(menu);
          } else {
            groupedItems.push(item);
          }
        });
        return self.partial('adminBar', { items: groupedItems });
      }
    });
    // Like the assets module, we wait as long as humanly possible
    // to lock down the list of admin bar items, so that other modules
    // can bicker amongst themselves even during the `modulesReady` stage.
    // When we get to `afterInit`, we can no longer wait! Order and
    // group the admin bar items.
    self.afterInit = function() {
      self.orderItems();
      self.groupItems();
    };
    // Implement the `order` option. This insertion sort results
    // in putting everything otherwise unspecified at the end, as desired.
    // Items with the `last: true` option are moved to the end before the
    // explicit order is applied.
    //
    // Called by `afterInit`
    self.orderItems = function() {
      // Items with a preference to go last go last...
      var moving = [];
      while (true) {
        var moveIndex = _.findIndex(self.items, function(item) {
          return item.options.last;
        });
        if (moveIndex === -1) {
          break;
        }
        moving.push(self.items[moveIndex]);
        self.items.splice(moveIndex, 1);
      }
      self.items = self.items.concat(moving);
      // ... But then explicit order kicks in
      _.each(self.options.order || [], function(name) {
        var item = _.find(self.items, { name: name });
        if (item) {
          self.items = [ item ].concat(_.filter(self.items, function(item) {
            return item.name !== name;
          }));
        }
      });
    };
    // Marks items that have been grouped via the `groups` option — or via
    // `group` calls from modules, combined with the `addGroups` option —
    // with a `menuLeader` property and ensures that the items in a group
    // are consecutive in the order. We'll figure out the final menus at
    // render time so we can handle it properly if an individual
    // user only sees one of them, etc. Called by `afterInit`
    self.groupItems = function() {
      // Implement the groups and addGroups options. Mark the grouped items with a
      // `menuLeader` property.
      _.each(self.options.groups || self.groups.concat(self.options.addGroups || []), function(group) {
        if (group.label) {
          self.groupLabels[group.items[0]] = group.label;
          group = group.items;
        }
        _.each(group, function(name, groupIndex) {
          var item = _.find(self.items, { name: name });
          if (item) {
            item.menuLeader = group[0];
          } else {
            return;
          }
          // Make sure the submenu items wind up following the leader
          // in self.items in the appropriate order
          if (name !== item.menuLeader) {
            var indexLeader = _.findIndex(self.items, { name: item.menuLeader });
            if (indexLeader === -1) {
              throw new Error('Admin bar grouping error: no match for ' + item.menuLeader + ' in menu item ' + item.name);
            }
            var indexMe = _.findIndex(self.items, { name: name });
            if (indexMe !== (indexLeader + groupIndex)) {
              // Swap ourselves into the right position following our leader
              if (indexLeader + groupIndex < indexMe) {
                indexMe++;
              }
              self.items.splice(indexLeader + groupIndex, 0, item);
              self.items.splice(indexMe, 1);
            }
          }
        });
      });
    };
    self.pushAssets = function() {
      self.pushAsset('script', 'user', { when: 'user' });
      options.browser = options.browser || {};
      var closeDelay = (self.options.closeDelay || self.options.closeDelay === 0 ? self.apos.launder.integer(self.options.closeDelay) : null);
      _.extend(options.browser, {
        openOnLoad: (!!(typeof self.options.openOnLoad === 'undefined' || self.options.openOnLoad)),
        openOnHomepageLoad: (!!(typeof self.options.openOnHomepageLoad === 'undefined' || self.options.openOnHomepageLoad)),
        closeDelay: typeof closeDelay === 'number' ? closeDelay : 3000
      });
      self.apos.push.browserCall('user', 'apos.create(?, ?)', self.__meta.name, options.browser);
    };

    // Determine if the specified admin bar item object should
    // be rendered or not, for the given req; based on item.permission
    // if any. `req.user` is guaranteed to exist at this point.
    self.itemIsVisible = function(req, item) {
      if (!item.permission) {
        // Being logged in is good enough to see this
        return true;
      }
      return self.apos.permissions.can(req, item.permission);
    };
  }
};
<|endoftext|>


<commit_before>
var users = [
    { name: 'tj' },
    { name: 'tim' }
];

function user(app){
    app.get('/.:format?', function(req, res, next){
        switch (req.params.format) {
            case 'json':
                var body = JSON.stringify(users);
                res.writeHead(200, {
                    'Content-Type': 'application/json',
                    'Content-Length': body.length
                });
                res.end(body);
                break;
            default:
                 var body = '
'
                    + users.map(function(user){ return '
' + user.name + '
'; }).join('\n')
                    + '
';
                res.writeHead(200, {
                    'Content-Type': 'text/html',
                    'Content-Length': body.length
                });
                res.end(body);

        }

    });

    app.get('/:id.:format', function(req, res, next){
        var user = users[req.params.id];
        if (user && req.params.format === 'json') {
            user = JSON.stringify(user);
            res.writeHead(200, {
                'Content-Type': 'application/json',
                'Content-Length': user.length
            });
            res.end(user);
        } else {
            // When true is passed, provide control
            // back to middleware, skipping route
            // match attemps
            next(true);
        }
    });

    app.get('/:id/:op?', function(req, res){
        var body = users[req.params.id]
            ? users[req.params.id].name
            : 'User ' + req.params.id + ' does not exist';
        body = (req.params.op || 'view') + 'ing ' + body;
        res.writeHead(200, {
            'Content-Type': 'text/html',
            'Content-Length': body.length
        });
        res.end(body, 'utf8');
    });
}

function main(app){
    app.get('/', function(req, res){
        var examples = [
            '/users',
            '/users.json',
            '/users/0 (or /users/0/view)',
            '/users/0/edit'
            '/users/0.json'
        ];
        var body = 'Visit one of the following:
'
            + examples.map(function(str){ return '
' + str + '
' }).join('\n')
            + '
';
        res.writeHead(200, {
            'Content-Type': 'text/html',
            'Content-Length': body.length
        });
        res.end(body, 'utf8');
    });
}

var connect = require('./../../lib/connect');

var server = connect.createServer(
    connect.logger({ buffer: true })
);

server.use("/users/", connect.router(user));
server.use(connect.router(main));
server.listen(3000);
console.log('Connect server listening on port 3000');
<commit_msg>fix router example<commit_after>
var users = [
    { name: 'tj' },
    { name: 'tim' }
];

function user(app){
    app.get('/.:format?', function(req, res, next){
        switch (req.params.format) {
            case 'json':
                var body = JSON.stringify(users);
                res.writeHead(200, {
                    'Content-Type': 'application/json',
                    'Content-Length': body.length
                });
                res.end(body);
                break;
            default:
                 var body = '
'
                    + users.map(function(user){ return '
' + user.name + '
'; }).join('\n')
                    + '
';
                res.writeHead(200, {
                    'Content-Type': 'text/html',
                    'Content-Length': body.length
                });
                res.end(body);

        }

    });

    app.get('/:id.:format', function(req, res, next){
        var user = users[req.params.id];
        if (user && req.params.format === 'json') {
            user = JSON.stringify(user);
            res.writeHead(200, {
                'Content-Type': 'application/json',
                'Content-Length': user.length
            });
            res.end(user);
        } else {
            // When true is passed, provide control
            // back to middleware, skipping route
            // match attemps
            next(true);
        }
    });

    app.get('/:id/:op?', function(req, res){
        var body = users[req.params.id]
            ? users[req.params.id].name
            : 'User ' + req.params.id + ' does not exist';
        body = (req.params.op || 'view') + 'ing ' + body;
        res.writeHead(200, {
            'Content-Type': 'text/html',
            'Content-Length': body.length
        });
        res.end(body, 'utf8');
    });
}

function main(app){
    app.get('/', function(req, res){
        var examples = [
            '/users',
            '/users.json',
            '/users/0 (or /users/0/view)',
            '/users/0/edit',
            '/users/0.json'
        ];
        var body = 'Visit one of the following:
'
            + examples.map(function(str){ return '
' + str + '
' }).join('\n')
            + '
';
        res.writeHead(200, {
            'Content-Type': 'text/html',
            'Content-Length': body.length
        });
        res.end(body, 'utf8');
    });
}

var connect = require('./../../lib/connect');

var server = connect.createServer(
    connect.logger({ buffer: true })
);

server.use("/users/", connect.router(user));
server.use(connect.router(main));
server.listen(3000);
console.log('Connect server listening on port 3000');
<|endoftext|>


<commit_before>/**
 * Created by hesk on 12/21/2014.
 */
var keystone = require('keystone'),
    async = require('async'),
    _ = require('underscore'),
    License = keystone.list('License'),
    utils = require('keystone-utils');

exports = module.exports = function (req, res) {

    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');

    var license = {
            status: false,
            createdAt: false,
            licensePerson: false,
            brandingRemoval: false,
            wwwSiteURL: false,
            licenseStatusLive: false,
            licenseHash: false,
            key: false
        },
        isError = false,
        message = "",
        Q = {},
        local = {handle: false};

    /**
     *
     * @param Query
     * @param checkArr
     * @returns {*}
     */
    var input_checker = function (Query, checkArr) {
        _.each(checkArr, function (paramname) {
            if (!Query[paramname]) throw Error(paramname + " is missing.");
        });
        return Query;
    }
    /**
     * async method run business logic
     */
    async.series([
        function (next) {
            try {
                console.log('------------------------------------------------------------');
                console.log(req.query);
                console.log('------------------------------------------------------------');
                Q = input_checker(req.query, ['domain', 'key']);
                next();
            } catch (e) {
                return next({message: e.message});
            }
        },

        function (next) {
            console.log('[api.app.checklicense]  - Check license...');
            console.log('------------------------------------------------------------');

            License.model.findOne()
                .where('key', Q.key)
                .exec(function (err, data) {

                    if (err) {
                        console.log('[api.app.checklicense]  - First Line Error...');
                        console.log('------------------------------------------------------------');
                        return next({message: err.message});
                    }

                    if (!data) {
                        console.log('[api.app.checklicense]  - license not found...');
                        console.log('------------------------------------------------------------');
                        return next({message: 'license not found'});
                    }

                    //   license = _.extend(data, license);
                    console.log('[api.app.checklicense]  - before ..', data);
                    console.log('------------------------------------------------------------');
                    license = _.extend(license, data._doc);
                    local.handle = data;

                    console.log('[api.app.checklicense]  - result after..', license);
                    console.log('------------------------------------------------------------');

                    if (license.siteURL != Q.domain)
                        return next({message: 'license is validated but domain name is not matched'});
                    if (!license.licenseStatusLive)
                        return next({message: 'license is not alive'});

                    return next();
                });

        },

        function (next) {
            try {

                var time = new Date();
                local.handle.checked = time.getTime();
                local.handle.save(function (err, doc) {

                    if (err) {
                        return next({message: e.message});
                    }

                    if (doc) {

                        console.log('[api.app.checklicense]  - result ..', doc);
                        console.log('------------------------------------------------------------');

                        return next();
                    }

                });

            } catch (e) {
                console.log('------------------------------------------------------------');
                return next({message: e.message});
            }
        },
        function (next) {

            return res.apiResponse({
                success: true,
                timestamp: new Date().getTime(),
                license_detail: license
            });
        }
    ], function (err) {
        if (err) {
            console.log('[api.app.checklicense]  - verify your license failed.', err);
            console.log('------------------------------------------------------------');

            return res.apiResponse({
                success: false,
                session: false,
                message: (err && err.message ? err.message : false) || 'Sorry, there was an error from verifying your license, please try again.'
            });
        }
    });
};
<commit_msg>fix<commit_after>/**
 * Created by hesk on 12/21/2014.
 */
var keystone = require('keystone'),
    async = require('async'),
    _ = require('underscore'),
    License = keystone.list('License'),
    utils = require('keystone-utils');

exports = module.exports = function (req, res) {

    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');

    var license = {
            status: false,
            createdAt: false,
            licensePerson: false,
            brandingRemoval: false,
            wwwSiteURL: false,
            licenseStatusLive: false,
            licenseHash: false,
            key: false
        },
        isError = false,
        message = "",
        Q = {},
        local = {handle: false};

    /**
     *
     * @param Query
     * @param checkArr
     * @returns {*}
     */
    var input_checker = function (Query, checkArr) {
        _.each(checkArr, function (paramname) {
            if (!Query[paramname]) throw Error(paramname + " is missing.");
        });
        return Query;
    }
    /**
     * async method run business logic
     */
    async.series([
        function (next) {
            try {
                console.log('------------------------------------------------------------');
                console.log(req.body);
                console.log('------------------------------------------------------------');
                Q = input_checker(req.body, ['domain', 'key']);
                next();
            } catch (e) {
                return next({message: e.message});
            }
        },

        function (next) {
            console.log('[api.app.checklicense]  - Check license...');
            console.log('------------------------------------------------------------');

            License.model.findOne()
                .where('key', Q.key)
                .exec(function (err, data) {

                    if (err) {
                        console.log('[api.app.checklicense]  - First Line Error...');
                        console.log('------------------------------------------------------------');
                        return next({message: err.message});
                    }

                    if (!data) {
                        console.log('[api.app.checklicense]  - license not found...');
                        console.log('------------------------------------------------------------');
                        return next({message: 'license not found'});
                    }

                    //   license = _.extend(data, license);
                    console.log('[api.app.checklicense]  - before ..', data);
                    console.log('------------------------------------------------------------');
                    license = _.extend(license, data._doc);
                    local.handle = data;

                    console.log('[api.app.checklicense]  - result after..', license);
                    console.log('------------------------------------------------------------');

                    if (license.siteURL != Q.domain)
                        return next({message: 'license is validated but domain name is not matched'});
                    if (!license.licenseStatusLive)
                        return next({message: 'license is not alive'});

                    return next();
                });

        },

        function (next) {
            try {

                var time = new Date();
                local.handle.checked = time.getTime();
                local.handle.save(function (err, doc) {

                    if (err) {
                        return next({message: e.message});
                    }

                    if (doc) {

                        console.log('[api.app.checklicense]  - result ..', doc);
                        console.log('------------------------------------------------------------');

                        return next();
                    }

                });

            } catch (e) {
                console.log('------------------------------------------------------------');
                return next({message: e.message});
            }
        },
        function (next) {

            return res.apiResponse({
                success: true,
                timestamp: new Date().getTime(),
                license_detail: license
            });
        }
    ], function (err) {
        if (err) {
            console.log('[api.app.checklicense]  - verify your license failed.', err);
            console.log('------------------------------------------------------------');

            return res.apiResponse({
                success: false,
                session: false,
                message: (err && err.message ? err.message : false) || 'Sorry, there was an error from verifying your license, please try again.'
            });
        }
    });
};
<|endoftext|>


<commit_before>// Vogue - Client
// Copyright (c) 2011 Andrew Davey (andrew@equin.co.uk)
(function () {
  var script,
      hop = Object.prototype.hasOwnProperty,
      head = document.getElementsByTagName("head")[0];

  function vogue() {
    var stylesheets,
        socket = io.connect(script.rootUrl);

    /**
     * Watch for all available stylesheets.
     */
    function watchAllStylesheets() {
      var href;
      for (href in stylesheets) {
        if (hop.call(stylesheets, href)) {
          socket.emit("watch", {
            href: href
          });
        }
      }
    }

    /**
     * Reload a stylesheet.
     *
     * @param {String} href The URL of the stylesheet to be reloaded.
     */
    function reloadStylesheet(href) {
      var newHref = stylesheets[href].href +
            (href.indexOf("?") >= 0 ? "&" : "?") +
            "_vogue_nocache=" + (new Date).getTime(),
          stylesheet;
      // Check if the appropriate DOM Node is there.
      if (!stylesheets[href].setAttribute) {
        // Create the link.
        stylesheet = document.createElement("link");
        stylesheet.setAttribute("rel", "stylesheet");
        stylesheet.setAttribute("href", newHref);
        head.appendChild(stylesheet);

        // Update the reference to the newly created link.
        stylesheets[href] = stylesheet;
      } else {
        // Update the href to the new URL.
        stylesheets[href].href = newHref;
      }
    }

    /**
     * Handle messages from socket.io, and load the appropriate stylesheet.
     *
     * @param message Socket.io message object.
     * @param message.href The url of the stylesheet to be loaded.
     */
    function handleMessage(message) {
      reloadStylesheet(message.href);
    }

    /**
     * Fetch all the local stylesheets from the page.
     *
     * @returns {Object} The list of local stylesheets keyed by their base URL.
     */
    function getLocalStylesheets() {

      /**
       * Checks if the stylesheet is local.
       *
       * @param {Object} link The link to check for.
       * @returns {Boolean}
       */
      function isLocalStylesheet(link) {
        var href, i, isExternal = true;
        if (link.getAttribute("rel") !== "stylesheet") {
          return false;
        }
        href = link.href;

        for (i = 0; i < script.bases.length; i += 1) {
          if (href.indexOf(script.bases[i]) > -1) {
            isExternal = false;
            break;
          }
        }

        return !(isExternal && href.match(/^https?:/));
      }

      /**
       * Checks if the stylesheet's media attribute is 'print'
       *
       * @param (Object) link The stylesheet element to check.
       * @returns (Boolean)
       */
      function isPrintStylesheet(link) {
        return link.getAttribute("media") === "print";
      }

      /**
       * Get the link's base URL.
       *
       * @param {String} href The URL to check.
       * @returns {String|Boolean} The base URL, or false if no matches found.
       */
      function getBase(href) {
        var base, j;
        for (j = 0; j < script.bases.length; j += 1) {
          base = script.bases[j];
          if (href.indexOf(base) > -1) {
            return href.substr(base.length);
          }
        }
        return false;
      }

      function getProperty(property) {
        return this[property];
      }

      var stylesheets = {},
          reImport = /@import\s+url\(["']?([^"'\)]+)["']?\)/g,
          links = document.getElementsByTagName("link"),
          link, href, matches, content, i, m;

      // Go through all the links in the page, looking for stylesheets.
      for (i = 0, m = links.length; i < m; i += 1) {
        link = links[i];
        if (isPrintStylesheet(link)) continue;
        if (!isLocalStylesheet(link)) continue;
        // Link is local, get the base URL.
        href = getBase(link.href);
        if (href !== false) {
          stylesheets[href] = link;
        }
      }

      // Go through all the style tags, looking for @import tags.
      links = document.getElementsByTagName("style");
      for (i = 0, m = links.length; i < m; i += 1) {
        if (isPrintStylesheet(links[i])) continue;
        content = links[i].text || links[i].textContent;
        while ((matches = reImport.exec(content))) {
          link = {
            rel: "stylesheet",
            href: matches[1],
            getAttribute: getProperty
          };
          if (isLocalStylesheet(link)) {
            // Link is local, get the base URL.
            href = getBase(link.href);
            if (href !== false) {
              stylesheets[href] = link;
            }
          }
        }
      }
      return stylesheets;
    }

    stylesheets = getLocalStylesheets();
    socket.on("connect", watchAllStylesheets);
    socket.on("update", handleMessage);
  }

  /**
   * Load a script into the page, and call a callback when it is loaded.
   *
   * @param {String} src The URL of the script to be loaded.
   * @param {Function} loadedCallback The function to be called when the script is loaded.
   */
  function loadScript(src, loadedCallback) {
    var script = document.createElement("script");
    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", src);

    // Call the callback when the script is loaded.
    script.onload = loadedCallback;
    script.onreadystatechange = function () {
      if (this.readyState === "complete" || this.readyState === "loaded") {
        loadedCallback();
      }
    };

    head.appendChild(script);
  }

  /**
   * Load scripts into the page, and call a callback when they are loaded.
   *
   * @param {Array} scripts The scripts to be loaded.
   * @param {Function} loadedCallback The function to be called when all the scripts have loaded.
   */
  function loadScripts(scripts, loadedCallback) {
    var srcs = [], property, count, i, src,
        countDown = function () {
          count -= 1;
          if (!count) {
            loadedCallback();
          }
        };

    for (property in scripts) {
      if (!(property in window)) {
        srcs.push(scripts[property]);
      }
    }

    count = srcs.length;
    if (!count) {
      loadedCallback();
    }

    for (i = 0; i < srcs.length; i += 1) {
      src = srcs[i];
      loadScript(src, countDown);
    }
  }

  /**
   * Fetches the info for the vogue client.
   */
  function getScriptInfo() {
    var bases = [ document.location.protocol + "//" + document.location.host ],
        scripts, src, rootUrl, baseMatch;
    if (typeof window.__vogue__ === "undefined") {
      scripts = document.getElementsByTagName("script");
      // The last parsed script will be our script.
      src = scripts[scripts.length - 1].getAttribute("src");
      rootUrl = src.match(/^https?\:\/\/(.*?)\//)[0];
      // There is an optional base argument, that can be used.
      baseMatch = src.match(/\bbase=(.*)(&|$)/);

      if (baseMatch) {
        bases = bases.concat(baseMatch[1].split(","));
      }
      return {
        rootUrl: rootUrl,
        bases: bases
      };
    } else {
      window.__vogue__.bases = bases;
      return window.__vogue__;
    }
  }

  /**
   * Fetches the port from the URL.
   *
   * @param {String} url URL to get the port from
   * @returns {Number} The port number, or 80 if no port number found or is invalid.
   */
  function getPort(url) {
    // URL may contain the port number after the second colon.
    // http://domain:1234/
    var index = url.indexOf(":", 6); // skipping 6 characters to ignore first colon
    return index < 0 ? 80 : parseInt(url.substr(index + 1), 10);
  }

  script = getScriptInfo();
  loadScripts({
    io: script.rootUrl + "socket.io/socket.io.js"
  }, vogue);
}());
<commit_msg>fix getScriptInfo to specifically find vogue-client.js instead of assuming it's the last entry in scripts array<commit_after>// Vogue - Client
// Copyright (c) 2011 Andrew Davey (andrew@equin.co.uk)
(function () {
  var script,
      hop = Object.prototype.hasOwnProperty,
      head = document.getElementsByTagName("head")[0];

  function vogue() {
    var stylesheets,
        socket = io.connect(script.rootUrl);

    /**
     * Watch for all available stylesheets.
     */
    function watchAllStylesheets() {
      var href;
      for (href in stylesheets) {
        if (hop.call(stylesheets, href)) {
          socket.emit("watch", {
            href: href
          });
        }
      }
    }

    /**
     * Reload a stylesheet.
     *
     * @param {String} href The URL of the stylesheet to be reloaded.
     */
    function reloadStylesheet(href) {
      var newHref = stylesheets[href].href +
            (href.indexOf("?") >= 0 ? "&" : "?") +
            "_vogue_nocache=" + (new Date).getTime(),
          stylesheet;
      // Check if the appropriate DOM Node is there.
      if (!stylesheets[href].setAttribute) {
        // Create the link.
        stylesheet = document.createElement("link");
        stylesheet.setAttribute("rel", "stylesheet");
        stylesheet.setAttribute("href", newHref);
        head.appendChild(stylesheet);

        // Update the reference to the newly created link.
        stylesheets[href] = stylesheet;
      } else {
        // Update the href to the new URL.
        stylesheets[href].href = newHref;
      }
    }

    /**
     * Handle messages from socket.io, and load the appropriate stylesheet.
     *
     * @param message Socket.io message object.
     * @param message.href The url of the stylesheet to be loaded.
     */
    function handleMessage(message) {
      reloadStylesheet(message.href);
    }

    /**
     * Fetch all the local stylesheets from the page.
     *
     * @returns {Object} The list of local stylesheets keyed by their base URL.
     */
    function getLocalStylesheets() {

      /**
       * Checks if the stylesheet is local.
       *
       * @param {Object} link The link to check for.
       * @returns {Boolean}
       */
      function isLocalStylesheet(link) {
        var href, i, isExternal = true;
        if (link.getAttribute("rel") !== "stylesheet") {
          return false;
        }
        href = link.href;

        for (i = 0; i < script.bases.length; i += 1) {
          if (href.indexOf(script.bases[i]) > -1) {
            isExternal = false;
            break;
          }
        }

        return !(isExternal && href.match(/^https?:/));
      }

      /**
       * Checks if the stylesheet's media attribute is 'print'
       *
       * @param (Object) link The stylesheet element to check.
       * @returns (Boolean)
       */
      function isPrintStylesheet(link) {
        return link.getAttribute("media") === "print";
      }

      /**
       * Get the link's base URL.
       *
       * @param {String} href The URL to check.
       * @returns {String|Boolean} The base URL, or false if no matches found.
       */
      function getBase(href) {
        var base, j;
        for (j = 0; j < script.bases.length; j += 1) {
          base = script.bases[j];
          if (href.indexOf(base) > -1) {
            return href.substr(base.length);
          }
        }
        return false;
      }

      function getProperty(property) {
        return this[property];
      }

      var stylesheets = {},
          reImport = /@import\s+url\(["']?([^"'\)]+)["']?\)/g,
          links = document.getElementsByTagName("link"),
          link, href, matches, content, i, m;

      // Go through all the links in the page, looking for stylesheets.
      for (i = 0, m = links.length; i < m; i += 1) {
        link = links[i];
        if (isPrintStylesheet(link)) continue;
        if (!isLocalStylesheet(link)) continue;
        // Link is local, get the base URL.
        href = getBase(link.href);
        if (href !== false) {
          stylesheets[href] = link;
        }
      }

      // Go through all the style tags, looking for @import tags.
      links = document.getElementsByTagName("style");
      for (i = 0, m = links.length; i < m; i += 1) {
        if (isPrintStylesheet(links[i])) continue;
        content = links[i].text || links[i].textContent;
        while ((matches = reImport.exec(content))) {
          link = {
            rel: "stylesheet",
            href: matches[1],
            getAttribute: getProperty
          };
          if (isLocalStylesheet(link)) {
            // Link is local, get the base URL.
            href = getBase(link.href);
            if (href !== false) {
              stylesheets[href] = link;
            }
          }
        }
      }
      return stylesheets;
    }

    stylesheets = getLocalStylesheets();
    socket.on("connect", watchAllStylesheets);
    socket.on("update", handleMessage);
  }

  /**
   * Load a script into the page, and call a callback when it is loaded.
   *
   * @param {String} src The URL of the script to be loaded.
   * @param {Function} loadedCallback The function to be called when the script is loaded.
   */
  function loadScript(src, loadedCallback) {
    var script = document.createElement("script");
    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", src);

    // Call the callback when the script is loaded.
    script.onload = loadedCallback;
    script.onreadystatechange = function () {
      if (this.readyState === "complete" || this.readyState === "loaded") {
        loadedCallback();
      }
    };

    head.appendChild(script);
  }

  /**
   * Load scripts into the page, and call a callback when they are loaded.
   *
   * @param {Array} scripts The scripts to be loaded.
   * @param {Function} loadedCallback The function to be called when all the scripts have loaded.
   */
  function loadScripts(scripts, loadedCallback) {
    var srcs = [], property, count, i, src,
        countDown = function () {
          count -= 1;
          if (!count) {
            loadedCallback();
          }
        };

    for (property in scripts) {
      if (!(property in window)) {
        srcs.push(scripts[property]);
      }
    }

    count = srcs.length;
    if (!count) {
      loadedCallback();
    }

    for (i = 0; i < srcs.length; i += 1) {
      src = srcs[i];
      loadScript(src, countDown);
    }
  }

  /**
   * Fetches the info for the vogue client.
   */
  function getScriptInfo() {
    var bases = [ document.location.protocol + "//" + document.location.host ],
        scripts, src, rootUrl, baseMatch;
    if (typeof window.__vogue__ === "undefined") {
      scripts = document.getElementsByTagName("script");
      for (var i=0; i < scripts.length; i++) {
        src = scripts[i].getAttribute("src");
        if (src.slice(-15) == 'vogue-client.js') break;
      }
      rootUrl = src.match(/^https?\:\/\/(.*?)\//)[0];
      // There is an optional base argument, that can be used.
      baseMatch = src.match(/\bbase=(.*)(&|$)/);

      if (baseMatch) {
        bases = bases.concat(baseMatch[1].split(","));
      }
      return {
        rootUrl: rootUrl,
        bases: bases
      };
    } else {
      window.__vogue__.bases = bases;
      return window.__vogue__;
    }
  }

  /**
   * Fetches the port from the URL.
   *
   * @param {String} url URL to get the port from
   * @returns {Number} The port number, or 80 if no port number found or is invalid.
   */
  function getPort(url) {
    // URL may contain the port number after the second colon.
    // http://domain:1234/
    var index = url.indexOf(":", 6); // skipping 6 characters to ignore first colon
    return index < 0 ? 80 : parseInt(url.substr(index + 1), 10);
  }

  script = getScriptInfo();
  loadScripts({
    io: script.rootUrl + "socket.io/socket.io.js"
  }, vogue);
}());
<|endoftext|>


<commit_before>'use strict';

var Node = require('../node');

var TYPE = 'deprecated-sql-function';

var PARAMS = {
    function_name: Node.PARAM.STRING(),
    primary_source: Node.PARAM.NODE(Node.GEOMETRY.ANY),
    secondary_source: Node.PARAM.NULLABLE(Node.PARAM.NODE(Node.GEOMETRY.ANY)),
    function_args: Node.PARAM.NULLABLE(Node.PARAM.ARRAY())
};

var DeprecatedSqlFunction = Node.create(TYPE, PARAMS, { cache: true });

module.exports = DeprecatedSqlFunction;

var postgresFunctionTemplate = Node.template([
    'SELECT * FROM {{=it.fnName}}(',
    '    $primaryQuery${{=it.primarySourceQuery}}$primaryQuery$,',
    '    {{? it.secondarySourceQuery !== null}}$secondaryQuery${{=it.secondarySourceQuery}}$secondaryQuery$,{{?}}',
    '    {{? it.fnExtraArgs !== null}}{{=it.fnExtraArgs}},{{?}}',
    '    $tableName${{=it.tableName}}$tableName$,',
    '    $operation${{=it.operation}}$operation$',
    ')'
].join('\n'));

DeprecatedSqlFunction.prototype.sql = function() {
    return 'SELECT * FROM ' + this.getTargetTable();
};

DeprecatedSqlFunction.prototype.createTableSql = function() {
    return this.tableSql('create');
};

DeprecatedSqlFunction.prototype.populateTableSql = function() {
    return this.tableSql('populate');
};

DeprecatedSqlFunction.prototype.tableSql = function(operation) {
    return postgresFunctionTemplate({
        fnName: this.function_name,
        primarySourceQuery: this.primary_source.getQuery(),
        secondarySourceQuery: (this.secondary_source !== null ? this.secondary_source.getQuery() : null),
        fnExtraArgs: (this.function_args !== null ? this.function_args.join(',') : null),
        tableName: this.getTargetTable(),
        operation: operation
    });
};
<commit_msg>Add support for text/numeric arguments<commit_after>'use strict';

var Node = require('../node');

var TYPE = 'deprecated-sql-function';

var PARAMS = {
    function_name: Node.PARAM.STRING(),
    primary_source: Node.PARAM.NODE(Node.GEOMETRY.ANY),
    secondary_source: Node.PARAM.NULLABLE(Node.PARAM.NODE(Node.GEOMETRY.ANY)),
    function_args: Node.PARAM.NULLABLE(Node.PARAM.ARRAY())
};

var DeprecatedSqlFunction = Node.create(TYPE, PARAMS, { cache: true });

module.exports = DeprecatedSqlFunction;

var postgresFunctionTemplate = Node.template([
    'SELECT * FROM {{=it.fnName}}(',
    '    $primaryQuery${{=it.primarySourceQuery}}$primaryQuery$,',
    '    {{? it.secondarySourceQuery !== null}}$secondaryQuery${{=it.secondarySourceQuery}}$secondaryQuery$,{{?}}',
    '    {{? it.fnExtraArgs !== null}}{{=it.fnExtraArgs}},{{?}}',
    '    $tableName${{=it.tableName}}$tableName$,',
    '    $operation${{=it.operation}}$operation$',
    ')'
].join('\n'));

DeprecatedSqlFunction.prototype.sql = function() {
    return 'SELECT * FROM ' + this.getTargetTable();
};

DeprecatedSqlFunction.prototype.createTableSql = function() {
    return this.tableSql('create');
};

DeprecatedSqlFunction.prototype.populateTableSql = function() {
    return this.tableSql('populate');
};

DeprecatedSqlFunction.prototype.tableSql = function(operation) {
    var functionArgs = this.function_args === null ? null :
        this.function_args
            .map(function(arg, index) {
                return Number.isFinite(arg) ? arg : '$arg' + index + '$' + arg + '$arg' + index + '$';
            })
            .join(',');

    return postgresFunctionTemplate({
        fnName: this.function_name,
        primarySourceQuery: this.primary_source.getQuery(),
        secondarySourceQuery: (this.secondary_source !== null ? this.secondary_source.getQuery() : null),
        fnExtraArgs: functionArgs,
        tableName: this.getTargetTable(),
        operation: operation
    });
};
<|endoftext|>


<commit_before>var AjaxForms = {

  init: function() {
    this.set_elements();
    this.addedit_links();
    this.addedit_submission();
    this.delete_no_form();
    this.filter_select();
    if (this.$filter_form.length) {
      this.filter_submission();
      var callback = function(params){
        AjaxForms.filter_submission();
      }
      this.grind = new Grinder(callback);
    }
  },

  set_elements: function() {
    this.$addedit_form = $('.js-addedit-form');
    this.$filter_form = $('.js-filter-form');
  },

  addedit_links: function() {
    this.$addedit_form.on('click', '.js-add-link, .js-edit-link', function(ev) {
      ev.preventDefault();
      var $this = $(this);
      var $parent = $this.closest('.js-addedit-form');
      var $wrapper = $parent.find('.js-addedit-form-wrapper');

      // scroll to the last column of the tbody, where the form will start
      Admin.scroll_to($parent.find("tbody tr:last-child"), 90);

      $.get($this.attr('href'), function(data){
        // check to see if the content is hidden and slide it down if it is.
        if ($wrapper.is(":hidden")) {
          // replace the content of the form area and initiate the chosen and fileinputer
          $wrapper.html(data).find(".select select").fae_chosen({ width: '300px' });
          $wrapper.find(".input.file").fileinputer({delete_class: "icon-delete_x file_input-delete"});
          $wrapper.slideDown();
        } else {
          // if it is visible, replace its content by retaining height
          $wrapper.height($wrapper.height());

          // replace the content of the form area and then remove that height and then chosen and then fileinputer
          $wrapper.html(data).css("height", "").find(".select select").fae_chosen();
          $wrapper.find(".input.file").fileinputer({delete_class: "icon-delete_x file_input-delete"});
        }

        Admin.init_date_picker();
        Admin.init_daterange_picker();
        Admin.init_slugger();

        $wrapper.find(".hint").hinter();
      });
    });
  },

  addedit_submission: function() {
    this.$addedit_form.on('ajax:success', function(evt, data, status, xhr){

      $target = $(evt.target);

      // ignore calls not returning html
      if (data !== ' ' && $(data)[0]) {
        var $this = $(this);
        var $parent = $this.parent();
        // we're manipulating the return so let's store in a var and keep 'data' intact
        var html = data;

        // remotipart returns data inside textarea, let's grab it from there
        if ($(html)[0].localName === 'textarea') {
          html = $(data)[0].value;
        }

        if ($(html)[1] && $(html)[1].className === 'main_content-section-area') {
          // we're returning the table, replace everything

          var $form_wrapper = $(this).find('.js-addedit-form-wrapper');

          // if there's a form wrap, slide it up before replacing content
          if ($form_wrapper.length) {
            $form_wrapper.slideUp(function(){
              AjaxForms.addedit_replace_and_reinit($this, $(html)[1].innerHTML, $target);
            });
          } else {
            AjaxForms.addedit_replace_and_reinit($this, $(html)[1].innerHTML, $target);
          }

          if (!$target.hasClass("js-delete-link")) {
            Admin.scroll_to($parent);
          }
        } else if ($(html)[0].className === 'form_content-wrapper') {
          // we're returning the form due to an error, just replace the form
          $this.find('.form_content-wrapper').replaceWith(html);
          $this.find('.select select').fae_chosen();
          $this.find(".input.file").fileinputer({delete_class: "icon-delete_x file_input-delete"});

          Admin.scroll_to($this.find('.js-addedit-form-wrapper'));
        }

        AjaxForms.init();
        Admin.fade_notices();

      } else if ($target.hasClass("js-asset-delete-link")) {
        // handle remove asset links
        $target.parent().fadeOut('fast', function() {
          $(this).next('.asset-inputs').fadeIn('fast');
        });
      }
    });
  },

  addedit_replace_and_reinit: function($this, html, $target) {
    $this.html(html)
      .find(".select select").fae_chosen();

    Admin.sortable();
  },

  filter_submission: function() {
    var _this = this;
    _this.$filter_form
      .on('ajax:success', function(evt, data, status, xhr){
        $(this).next('table').replaceWith($(data).find('table').first());
        var cookie_name = $(this).data('cookie-key');
        if (cookie_name != false) {
          $.cookie(cookie_name, JSON.stringify(data));
        }
      })
      .on('click', '.js-reset-btn', function(ev) {
        var form = $(this).closest('form')[0];
        form.reset();
        $(form).find('select').val('').trigger('chosen:updated');
        // reset hashies
        window.location.hash = ''
      })
      .on('change', 'select', function() {
        _this.$filter_form.submit();
      });
  },

  // persist filter options
  filter_select: function(){
    var _this = this;
    $('.js-filter-form .table-filter-group').on('change', function(){
      if ($(this).data('cookie-key') != false) {
        if ($('.table-filter-group').data('remember-filter') == true) {
          var key = $(this).find('select').attr('id').split('filter_')[1];
          var value = $(this).find('option:selected').val();

          _this.grind.update(key, value, false, true);
        }
      }
    });
  },

  delete_no_form: function() {
    // on deletes that don't exist in a form like file upload area
    $('.js-asset-delete-link').on('ajax:success', function(){
      var $this = $(this);
      if (!$this.closest('.js-addedit-form-wrapper').length) {
        var $parent = $this.closest('.asset-actions');
        var $inputs = $parent.next('.asset-inputs');
        $parent.fadeOut(function(){
          $inputs.fadeIn();
        });
      }
    });
  }
};<commit_msg>got you cookies... got you...<commit_after>var AjaxForms = {

  init: function() {
    this.set_elements();
    this.addedit_links();
    this.addedit_submission();
    this.delete_no_form();
    if (this.$filter_form.length) {
      this.filter_select();
      this.filter_submission();
      var callback = function(params){
        AjaxForms.set_filter_cookie(params);
      }
      this.grind = new Grinder(callback);
    }
  },

  set_elements: function() {
    this.$addedit_form = $('.js-addedit-form');
    this.$filter_form = $('.js-filter-form');
  },

  addedit_links: function() {
    this.$addedit_form.on('click', '.js-add-link, .js-edit-link', function(ev) {
      ev.preventDefault();
      var $this = $(this);
      var $parent = $this.closest('.js-addedit-form');
      var $wrapper = $parent.find('.js-addedit-form-wrapper');

      // scroll to the last column of the tbody, where the form will start
      Admin.scroll_to($parent.find("tbody tr:last-child"), 90);

      $.get($this.attr('href'), function(data){
        // check to see if the content is hidden and slide it down if it is.
        if ($wrapper.is(":hidden")) {
          // replace the content of the form area and initiate the chosen and fileinputer
          $wrapper.html(data).find(".select select").fae_chosen({ width: '300px' });
          $wrapper.find(".input.file").fileinputer({delete_class: "icon-delete_x file_input-delete"});
          $wrapper.slideDown();
        } else {
          // if it is visible, replace its content by retaining height
          $wrapper.height($wrapper.height());

          // replace the content of the form area and then remove that height and then chosen and then fileinputer
          $wrapper.html(data).css("height", "").find(".select select").fae_chosen();
          $wrapper.find(".input.file").fileinputer({delete_class: "icon-delete_x file_input-delete"});
        }

        Admin.init_date_picker();
        Admin.init_daterange_picker();
        Admin.init_slugger();

        $wrapper.find(".hint").hinter();
      });
    });
  },

  addedit_submission: function() {
    this.$addedit_form.on('ajax:success', function(evt, data, status, xhr){

      $target = $(evt.target);

      // ignore calls not returning html
      if (data !== ' ' && $(data)[0]) {
        var $this = $(this);
        var $parent = $this.parent();
        // we're manipulating the return so let's store in a var and keep 'data' intact
        var html = data;

        // remotipart returns data inside textarea, let's grab it from there
        if ($(html)[0].localName === 'textarea') {
          html = $(data)[0].value;
        }

        if ($(html)[1] && $(html)[1].className === 'main_content-section-area') {
          // we're returning the table, replace everything

          var $form_wrapper = $(this).find('.js-addedit-form-wrapper');

          // if there's a form wrap, slide it up before replacing content
          if ($form_wrapper.length) {
            $form_wrapper.slideUp(function(){
              AjaxForms.addedit_replace_and_reinit($this, $(html)[1].innerHTML, $target);
            });
          } else {
            AjaxForms.addedit_replace_and_reinit($this, $(html)[1].innerHTML, $target);
          }

          if (!$target.hasClass("js-delete-link")) {
            Admin.scroll_to($parent);
          }
        } else if ($(html)[0].className === 'form_content-wrapper') {
          // we're returning the form due to an error, just replace the form
          $this.find('.form_content-wrapper').replaceWith(html);
          $this.find('.select select').fae_chosen();
          $this.find(".input.file").fileinputer({delete_class: "icon-delete_x file_input-delete"});

          Admin.scroll_to($this.find('.js-addedit-form-wrapper'));
        }

        AjaxForms.init();
        Admin.fade_notices();

      } else if ($target.hasClass("js-asset-delete-link")) {
        // handle remove asset links
        $target.parent().fadeOut('fast', function() {
          $(this).next('.asset-inputs').fadeIn('fast');
        });
      }
    });
  },

  addedit_replace_and_reinit: function($this, html, $target) {
    $this.html(html)
      .find(".select select").fae_chosen();

    Admin.sortable();
  },

  filter_submission: function() {
    var _this = this;
    _this.$filter_form
      .on('ajax:success', function(evt, data, status, xhr){
        $(this).next('table').replaceWith($(data).find('table').first());
      })
      .on('click', '.js-reset-btn', function(ev) {
        var form = $(this).closest('form')[0];
        form.reset();
        $(form).find('select').val('').trigger('chosen:updated');
        // reset hashies
        window.location.hash = ''
      })
      .on('change', 'select', function() {
        _this.$filter_form.submit();
      });
  },

  set_filter_cookie: function(params) {
    var cookie_name = $(this).data('cookie-key');
    if (cookie_name != false) {
      console.log(params);
      $.cookie(cookie_name, JSON.stringify(params));
    }
  },

  // persist filter options
  filter_select: function(){
    var _this = this;
    $('.js-filter-form .table-filter-group').on('change', function(){
      if ($(this).data('cookie-key') != false) {
        if ($('.table-filter-group').data('remember-filter') == true) {
          var key = $(this).find('select').attr('id').split('filter_')[1];
          var value = $(this).find('option:selected').val();

          _this.grind.update(key, value, false, true);
        }
      }
    });
  },

  delete_no_form: function() {
    // on deletes that don't exist in a form like file upload area
    $('.js-asset-delete-link').on('ajax:success', function(){
      var $this = $(this);
      if (!$this.closest('.js-addedit-form-wrapper').length) {
        var $parent = $this.closest('.asset-actions');
        var $inputs = $parent.next('.asset-inputs');
        $parent.fadeOut(function(){
          $inputs.fadeIn();
        });
      }
    });
  }
};<|endoftext|>


<commit_before>const ServiceErrorPathMapping = [
  {
    match: /^id$/,
    name: "Service ID"
  },
  {
    match: /^instances$/,
    name: "Instances"
  },
  {
    match: /^cpus$/,
    name: "CPUs"
  },
  {
    match: /^mem$/,
    name: "Memory"
  },
  {
    match: /^env\.\*$/,
    name: "Environment variables"
  },

  //
  // Volumes
  //
  {
    match: /^container\.volumes\.[0-9]+\.containerPath$/,
    name: "Volume container path"
  },
  {
    match: /^container\.volumes\.[0-9]+\..*size$/,
    name: "Volume size"
  },
  {
    match: /^container\.volumes\.[0-9]+\.hostPath$/,
    name: "Volume host path"
  },
  {
    match: /^container\.volumes\.[0-9]+\.mode$/,
    name: "Volume mode"
  },

  //
  // Networking (Host)
  //
  {
    match: /^portDefinitions\.[0-9]+\.name$/,
    name: "Service endpoint names"
  },
  {
    match: /^portDefinitions\.[0-9]+\.port$/,
    name: "Service endpoint host ports"
  },
  {
    match: /^portDefinitions\.[0-9]+\.labels\.VIP_/,
    name: "Service endpoint host ports"
  },

  //
  // Networking (Bridge)
  //
  {
    match: /^container\.docker\.portMappings\.[0-9]+\.name/,
    name: "Service endpoint names"
  },
  {
    match: /^container\.docker\.portMappings\.[0-9]+\.containerPort/,
    name: "Service endpoint container ports"
  },
  {
    match: /^container\.docker\.portMappings\.[0-9]+\.hostPort/,
    name: "Service endpoint host ports"
  },

  //
  // Health checks
  //
  {
    match: /^healthChecks\.[0-9]+\.gracePeriodSeconds/,
    name: "Health check grace periods"
  },
  {
    match: /^healthChecks\.[0-9]+\.intervalSeconds/,
    name: "Health check intervals"
  },
  {
    match: /^healthChecks\.[0-9]+\.timeoutSeconds/,
    name: "Health check timeouts"
  },
  {
    match: /^healthChecks\.[0-9]+\.maxConsecutiveFailures/,
    name: "Health check max failures"
  }
];

module.exports = ServiceErrorPathMapping;
<commit_msg>feat(ServiceErrorPathMapping): mark names for translation<commit_after>import { i18nMark } from "@lingui/react";

const ServiceErrorPathMapping = [
  {
    match: /^id$/,
    name: i18nMark("Service ID")
  },
  {
    match: /^instances$/,
    name: i18nMark("Instances")
  },
  {
    match: /^cpus$/,
    name: i18nMark("CPUs")
  },
  {
    match: /^mem$/,
    name: i18nMark("Memory")
  },
  {
    match: /^env\.\*$/,
    name: i18nMark("Environment variables")
  },

  //
  // Volumes
  //
  {
    match: /^container\.volumes\.[0-9]+\.containerPath$/,
    name: i18nMark("Volume container path")
  },
  {
    match: /^container\.volumes\.[0-9]+\..*size$/,
    name: i18nMark("Volume size")
  },
  {
    match: /^container\.volumes\.[0-9]+\.hostPath$/,
    name: i18nMark("Volume host path")
  },
  {
    match: /^container\.volumes\.[0-9]+\.mode$/,
    name: i18nMark("Volume mode")
  },

  //
  // Networking (Host)
  //
  {
    match: /^portDefinitions\.[0-9]+\.name$/,
    name: i18nMark("Service endpoint names")
  },
  {
    match: /^portDefinitions\.[0-9]+\.port$/,
    name: i18nMark("Service endpoint host ports")
  },
  {
    match: /^portDefinitions\.[0-9]+\.labels\.VIP_/,
    name: i18nMark("Service endpoint host ports")
  },

  //
  // Networking (Bridge)
  //
  {
    match: /^container\.docker\.portMappings\.[0-9]+\.name/,
    name: i18nMark("Service endpoint names")
  },
  {
    match: /^container\.docker\.portMappings\.[0-9]+\.containerPort/,
    name: i18nMark("Service endpoint container ports")
  },
  {
    match: /^container\.docker\.portMappings\.[0-9]+\.hostPort/,
    name: i18nMark("Service endpoint host ports")
  },

  //
  // Health checks
  //
  {
    match: /^healthChecks\.[0-9]+\.gracePeriodSeconds/,
    name: i18nMark("Health check grace periods")
  },
  {
    match: /^healthChecks\.[0-9]+\.intervalSeconds/,
    name: i18nMark("Health check intervals")
  },
  {
    match: /^healthChecks\.[0-9]+\.timeoutSeconds/,
    name: i18nMark("Health check timeouts")
  },
  {
    match: /^healthChecks\.[0-9]+\.maxConsecutiveFailures/,
    name: i18nMark("Health check max failures")
  }
];

module.exports = ServiceErrorPathMapping;
<|endoftext|>


<commit_before>import _ from 'lodash';
import {rankedByLetterGrade, hasLetterGrade} from '../helpers/SortHelpers';

// eg see http://www.somerville.k12.ma.us/sites/default/files/SHS_2018-2019%20Program%20of%20Studies%20Final%20-%20Jan%2010%202018.pdf

// This doesn't work exactly, since multiple sections may match
// (eg, multiple course enrollments in math, and only one has a grade).
//
// So as a heuristic, match courses first, then look at those with grades,
// and then take the lowest grade (since the idea here is to help educators
// find where students would benefit from more supports).
export function firstMatchWithGrades(assignments, patterns) {
  const matchingAssignments = matchingAssignmentsByPattern(assignments, patterns);
  const matchingAssignmentsWithGrades = matchingAssignments.filter(assignment => {
    return hasLetterGrade(assignment.grade_letter);
  });
  const sortedMatchingAssignments = _.sortBy(matchingAssignmentsWithGrades, assignment => {
    return rankedByLetterGrade(assignment.grade_letter);
  });
  return _.last(sortedMatchingAssignments);
}

export function firstMatch(assignments, patterns) {
  return _.first(matchingAssignmentsByPattern(assignments, patterns));
}

function matchingAssignmentsByPattern(assignments, patterns) {
  return assignments.filter(assignment => {
    const text = assignment.section.course_description;
    return _.some(patterns, pattern => text.indexOf(pattern) !== -1);
  });
}

export const REDIRECT = [
  'REDIRECT'
];

export const ADVISORY = [
  'Advisory'
];

export const ACADEMIC_SUPPORT = [
  'ACADEMIC SUPPORT'
];

export const CREDIT_RECOVERY = [
  'CREDIT RECOVERY'
];

export const STUDY_SKILLS = [
  'STUDY SKILLS'
];

const ENGLISH = [
  'ENGLISH',
  'READING FOUNDATIONS',
  'CREATIVE WRITING'
];

const CORE_ELL_IN_PLACE_OF_ENGLISH = [
  'ESL'
];

// Depending on the persective, courses might be considered ELL or
// within another department (eg, "ESL - Semester SS" would be ESL if asking
// which department "owns" the course, or would be Social Studies if asking
// for a student's grade in a particular type of subject).
const ELL = CORE_ELL_IN_PLACE_OF_ENGLISH.concat([
  'ALCS - GENERAL SUPPORT',
  'GOAL PROGRAM DAILY SEMINAR',
  'ACADEMIC LITERACY'
]);

 // core ELL classes are considered part of the English dept. in the levels UI
export const ENGLISH_OR_CORE_ELL = CORE_ELL_IN_PLACE_OF_ENGLISH.concat(ENGLISH);

export const SOCIAL_STUDIES = [
  'HISTORY',
  'GOVT and POLITICS AP',
  'AMERICAN IDENTITIES HONORS',
  'CURRENT EVENTS',
  'GOVT and POLITICS'
];

export const MATH = [
  'GEOMETRY',
  'ALGEBRA',
  'MATH',
  'PRECALCULUS',
  'STATISTICS',
  'CALCULUS',
  'DATA ANALYSIS'
];

export const SCIENCE = [
  'BIOLOGY',
  'PHYSICS',
  'CHEMISTRY',
  'PHYSIOLOGY',
  'HUMAN BEHAVIOR',
  'OCEANOGRAPHY',
  'PSYCHOLOGY',
  'ENVIRONMENTAL SCIENCE AP',
  'ENVIRONMENTAL SCIENCE',
  'BIOTECHNOLOGY',
  'ASTRONOMY'
];

const BUSINESS = [
  'ACCOUNTING',
  'ENTREPRENEURSHIP',
  'MARKETING',
  'PRACTICAL LAW',
  'FINANCE',
];

const WORLD_LANGUAGES = [
  'FRENCH',
  'PORTUGUESE',
  'SPANISH',
  'ITALIAN'
];

const HEALTH = [
  'HEALTH',
  'FITNESS EDUCATION',
  'TEAM ACTIVITIES PE',
  'DANCE',
  'WEIGHT TRAINING',
  'COMPETITIVE ACTIVITIES PE',
  'SPORTS MEDICINE',
  'FOUNDATION PHYS ED',
  'NON-COMPET PE'
];

const MUSIC = [
  'PIANO',
  'BAND',
  'TEAM ACTIVITIES PE',
  'CHORUS',
  'ORCHESTRA',
  'MUSIC',
  'GUITAR',
  'DRUM LINE',
  'PERCUSSION'
];

const ART = [
  'ART',
  'CERAMICS',
  'PHOTOGRAPHY',
  'FILM',
  'GRAPHIC COMM',
  'CALLIGRAPHY',
  'DRAMA WORKSHOP',
  'ARCHITECTURAL DRAWING'
];

const CTE = [];
const LIBRARY = [];
const PHYSICAL_EDUCATION = [];

// const ENROOT = [
//   'ENROOT'
// ];

// const PATH_PROGRAM = [
//   'PATH PROGRAM ROSTER',
//   'PATH PROGRAM SUPPORT'
// ];

// const OTHER_SUPPORT = [
//   'STUDENT MENTOR',
//   'TRANSITION SKILLS',
//   'GRADUATION PLAN'
// ];

// const ENGINEERING = [
//   'COMPUTER SCIENCE',
//   'ELECTRICAL',
//   'ENGINEERING',
//   'MACHINE TECH',
//   'AUTO TECHNOLOGY',
//   'METAL FABRICATION',
//   'COMPUTER ASST DRAFTING'
// ];

// const LIFE_SKILLS = [
//   'ADAPTIVE LIFE SKILLS',
//   'LIFE SKILLS PRE-WORK',
//   'LIFE SKILLS SOCIAL SCIENCE',
//   'LIFE SKILLS READING',
//   'LIFE SKILLS - semester'
// ];

// const OTHER = [
//   'JOURNALISM',
//   'TV/MEDIA PROD',
//   'Extended Learning Program',
//   'CHILD DEVELOPMENT',
//   'INTERNSHIP',
//   'VOC',
//   'DENTAL',
//   'CARPENTRY',
//   'COSMETOLOGY',
//   'COMPUTER PRIN/REP'
// ];

const SPECIAL_PROGRAMS = []
  .concat(REDIRECT)
  .concat(ADVISORY)
  .concat(ACADEMIC_SUPPORT)
  .concat(CREDIT_RECOVERY);

const SPECIAL_EDUCATION = []
  .concat(STUDY_SKILLS);

export function labelDepartmentKey(assignment) {
  const text = assignment.section.course_description;

  if (matches(text, ENGLISH)) return 'english';
  if (matches(text, MATH)) return 'math';
  if (matches(text, SCIENCE)) return 'science';
  if (matches(text, SOCIAL_STUDIES)) return 'social_studies';

  if (matches(text, ART)) return 'art';
  if (matches(text, BUSINESS)) return 'business';
  if (matches(text, CTE)) return 'cte';
  if (matches(text, ELL)) return 'ell';
  if (matches(text, HEALTH)) return 'health';
  if (matches(text, LIBRARY)) return 'library';
  if (matches(text, MUSIC)) return 'music';
  if (matches(text, HEALTH)) return 'health';
  if (matches(text, PHYSICAL_EDUCATION)) return 'physical_education';
  if (matches(text, SPECIAL_EDUCATION)) return 'special_education';
  if (matches(text, WORLD_LANGUAGES)) return 'world_languages';
  if (matches(text, SPECIAL_PROGRAMS)) return 'special_programs';

  return 'unknown';
}

function matches(text, patterns) {
  return _.some(patterns, pattern => text.indexOf(pattern) !== -1);
}
<commit_msg>WIP improving ELL course matching<commit_after>import _ from 'lodash';
import {rankedByLetterGrade, hasLetterGrade} from '../helpers/SortHelpers';

// eg see http://www.somerville.k12.ma.us/sites/default/files/SHS_2018-2019%20Program%20of%20Studies%20Final%20-%20Jan%2010%202018.pdf

// This doesn't work exactly, since multiple sections may match
// (eg, multiple course enrollments in math, and only one has a grade).
//
// So as a heuristic, match courses first, then look at those with grades,
// and then take the lowest grade (since the idea here is to help educators
// find where students would benefit from more supports).
export function firstMatchWithGrades(assignments, patterns) {
  const matchingAssignments = matchingAssignmentsByPattern(assignments, patterns);
  const matchingAssignmentsWithGrades = matchingAssignments.filter(assignment => {
    return hasLetterGrade(assignment.grade_letter);
  });
  const sortedMatchingAssignments = _.sortBy(matchingAssignmentsWithGrades, assignment => {
    return rankedByLetterGrade(assignment.grade_letter);
  });
  return _.last(sortedMatchingAssignments);
}

export function firstMatch(assignments, patterns) {
  return _.first(matchingAssignmentsByPattern(assignments, patterns));
}

function matchingAssignmentsByPattern(assignments, patterns) {
  return assignments.filter(assignment => {
    const text = assignment.section.course_description;
    return _.some(patterns, pattern => text.indexOf(pattern) !== -1);
  });
}

export const REDIRECT = [
  'REDIRECT'
];

export const ADVISORY = [
  'Advisory'
];

export const ACADEMIC_SUPPORT = [
  'ACADEMIC SUPPORT'
];

export const CREDIT_RECOVERY = [
  'CREDIT RECOVERY'
];

export const STUDY_SKILLS = [
  'STUDY SKILLS'
];

const ENGLISH = [
  'ENGLISH',
  'READING FOUNDATIONS',
  'CREATIVE WRITING'
];

const CORE_ELL_IN_PLACE_OF_ENGLISH = [
  /^ESL$/ // full exact match only
];

// Depending on the persective, courses might be considered ELL or
// within another department (eg, "ESL - Semester SS" would be ESL if asking
// which department "owns" the course, or would be Social Studies if asking
// for a student's grade in a particular type of subject).
//
// core ELL classes are considered part of the English dept. in the levels UI
// others are considered part of another department
export const ENGLISH_OR_CORE_ELL = CORE_ELL_IN_PLACE_OF_ENGLISH.concat(ENGLISH);

export const SOCIAL_STUDIES = [
  'HISTORY',
  'GOVT and POLITICS AP',
  'AMERICAN IDENTITIES HONORS',
  'CURRENT EVENTS',
  'GOVT and POLITICS',
  'ESL - Semester SS'
];

export const MATH = [
  'GEOMETRY',
  'ALGEBRA',
  'MATH',
  'PRECALCULUS',
  'STATISTICS',
  'CALCULUS',
  'DATA ANALYSIS'
];

export const SCIENCE = [
  'BIOLOGY',
  'PHYSICS',
  'CHEMISTRY',
  'PHYSIOLOGY',
  'HUMAN BEHAVIOR',
  'OCEANOGRAPHY',
  'PSYCHOLOGY',
  'ENVIRONMENTAL SCIENCE',
  'BIOTECHNOLOGY',
  'ASTRONOMY'
];

<|endoftext|>