<commit_before>// Copyright 2018, Google, Inc.
// Licensed under the Apache License, Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

const {
  dialogflow,
  BasicCard,
  Image,
  SimpleResponse,
} = require('actions-on-google');
const functions = require('firebase-functions');
const fetch = require('isomorphic-fetch');

const URL = 'https://raw.githubusercontent.com/actions-on-google/dialogflow-quotes-nodejs/blob/master/quotes.json';
const BACKGROUND_IMAGE = 'https://lh3.googleusercontent.com/t53m5nzjMl2B_9Qhwc81tuwyA2dBEc7WqKPlzZJ9syPUkt9VR8lu4Kq8heMjJevW3GVv9ekRWntyqXIBKEhc5i7v-SRrTan_=s688';

const app = dialogflow({debug: true});

// Retrieve data from the external API.
app.intent('Default Welcome Intent', (conv) => {
  // Note: Moving this fetch call outside of the app intent callback will
  // cause it to become a global var (i.e. it's value will be cached across
  // function executions).
  return fetch(URL)
    .then((response) => {
      if (response.status < 200 || response.status >= 300) {
        throw new Error(response.statusText);
      } else {
        return response.json();
      }
    })
    .then((json) => {
      // Grab random quote data from JSON.
      const data = json.data[Math.floor(Math.random() * json.data.length)];
      const randomQuote =
        data.quotes[Math.floor(Math.random() * data.quotes.length)];
      conv.close(new SimpleResponse({
        text: json.info,
        speech: `${data.author}, from Google ` +
          `Developer Relations once said... ${randomQuote}`,
      }));
      if (conv.screen) {
        conv.close(new BasicCard({
          text: randomQuote,
          title: `${data.author} once said...`,
          image: new Image({
            url: BACKGROUND_IMAGE,
            alt: 'DevRel Quote',
          }),
        }));
      }
    });
});

exports.quotes = functions.https.onRequest(app);
<commit_msg>Update API URL to hosted file on GitHub<commit_after>// Copyright 2018, Google, Inc.
// Licensed under the Apache License, Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

const {
  dialogflow,
  BasicCard,
  Image,
  SimpleResponse,
} = require('actions-on-google');
const functions = require('firebase-functions');
const fetch = require('isomorphic-fetch');

const URL = 'https://raw.githubusercontent.com/actions-on-google/dialogflow-quotes-nodejs/master/quotes.json';
const BACKGROUND_IMAGE = 'https://lh3.googleusercontent.com/t53m5nzjMl2B_9Qhwc81tuwyA2dBEc7WqKPlzZJ9syPUkt9VR8lu4Kq8heMjJevW3GVv9ekRWntyqXIBKEhc5i7v-SRrTan_=s688';

const app = dialogflow({debug: true});

// Retrieve data from the external API.
app.intent('Default Welcome Intent', (conv) => {
  // Note: Moving this fetch call outside of the app intent callback will
  // cause it to become a global var (i.e. it's value will be cached across
  // function executions).
  return fetch(URL)
    .then((response) => {
      if (response.status < 200 || response.status >= 300) {
        throw new Error(response.statusText);
      } else {
        return response.json();
      }
    })
    .then((json) => {
      // Grab random quote data from JSON.
      const data = json.data[Math.floor(Math.random() * json.data.length)];
      const randomQuote =
        data.quotes[Math.floor(Math.random() * data.quotes.length)];
      conv.close(new SimpleResponse({
        text: json.info,
        speech: `${data.author}, from Google ` +
          `Developer Relations once said... ${randomQuote}`,
      }));
      if (conv.screen) {
        conv.close(new BasicCard({
          text: randomQuote,
          title: `${data.author} once said...`,
          image: new Image({
            url: BACKGROUND_IMAGE,
            alt: 'DevRel Quote',
          }),
        }));
      }
    });
});

exports.quotes = functions.https.onRequest(app);
<|endoftext|>


<commit_before>const fs = require('fs');
const uuidv1 = require('uuid/v1');
const cors = require('cors')({origin: true});
const vision = require('@google-cloud/vision');
const {Datastore} = require('@google-cloud/datastore');
const ffmpegPath = require('@ffmpeg-installer/ffmpeg').path;
const ffmpeg = require('fluent-ffmpeg');
const {google} = require('googleapis');

ffmpeg.setFfmpegPath(ffmpegPath);
const visionClient = new vision.v1p3beta1.ImageAnnotatorClient();
const datastore = new Datastore();

async function getGoogleAPIAuthentication() {
    const auth = new google.auth.GoogleAuth({ scopes: ['https://www.googleapis.com/auth/drive'] });
    return await auth.getClient();
}

// Makes an ffmpeg command return a promise.
function promisifyCommand(command) {
    return new Promise((resolve, reject) => {
        command.on('end', resolve).on('error', reject).run();
    });
}

async function writeFileAsync(path, buffer) {
    return new Promise((resolve, reject) => {
        fs.writeFile(path, buffer, (err) => {
            if(err) {
                reject(err);
            } else {
                resolve();
            }
        });
    });
}

function addSecurityHeaders(res) {
    res.headers['X-Frame-Options'] = 'SAMEORIGIN';
}

exports.saveAudioSuggestions = async (req, res) => {
    addSecurityHeaders(res);
    return cors(req, res, async () => {
        // convert base64 body to blob of webm
        const nodeBuffer = Buffer.from(req.body, 'base64');
        // convert to mp3
        const fileName = uuidv1();
        const tempLocalPath = `/tmp/${fileName}.webm`;
        const targetTempFilePath =  `/tmp/${fileName}.mp3`;
        await writeFileAsync(tempLocalPath, nodeBuffer);
        const command = new ffmpeg(tempLocalPath).toFormat('mp3').save(targetTempFilePath);
        await promisifyCommand(command);
        // upload to drive
        const drive = google.drive({version: 'v3', auth: await getGoogleAPIAuthentication()});
        const createResponse = (await drive.files.create({
            requestBody: {
                parents: [ process.env['AUDIO_FOLDER_ID'] ],
                mimeType: 'audio/mp3',
                name: `${fileName}.mp3`
            },
            media: {
                mimeType: 'audio/mp3',
                body: fs.createReadStream(targetTempFilePath),
            }
        }));
        const fileId = createResponse.data.id;
        const file = (await drive.files.get({
            fileId: fileId,
            fields: 'webContentLink'
        })).data;
        console.log(`Audio saved to ${file.webContentLink}.`);
        res.status(200).send(file.webContentLink);
    });
};

async function saveFeedback(spreadsheetId, sheetTitle, data) {
    const sheets = google.sheets({version: 'v4', auth: await getGoogleAPIAuthentication()});
    // find spreadsheet
    const spreadsheet = (await sheets.spreadsheets.get({spreadsheetId: spreadsheetId, fields: 'sheets(properties.title)'})).data;
    if(!spreadsheet) {
        throw new Error("Spreadsheet not found");
    }
    // find sheet
    const sheet = spreadsheet.sheets.find(sh => sh.properties.title === sheetTitle);
    if(!sheet) {
        // sheet does not exist - create it
        await sheets.spreadsheets.batchUpdate({ spreadsheetId: spreadsheetId, requestBody: {
                "requests": [ {
                    "addSheet": {
                        "properties": {
                            "title": sheetTitle,
                            "sheetType": "GRID"
                        }
                    }
                } ]
            } })
    }
    // append data to sheet
    await sheets.spreadsheets.values.append({
        spreadsheetId: spreadsheetId,
        range: sheetTitle + '!A1',
        valueInputOption: 'RAW',
        requestBody: { values: [data] }
    });
}

exports.addSuggestions = async (req, res) => {
    addSecurityHeaders(res);
    return cors(req, res, async () => {
        await saveFeedback(process.env['SUGGESTIONS_SPREADSHEET'], req.body.native_language, [
            req.body.language || '',
            req.body.native_language || '',
            req.body.english_word || '',
            req.body.primary_word || '',
            req.body.translation || '',
            req.body.transliteration || '',
            req.body.sound_link || '',
            new Date()
        ]);
        res.status(200).send("Translation suggestions saved.");
    });
};

exports.addFeedback = async (req, res) => {
    addSecurityHeaders(res);
    return cors(req, res, async () => {
        await saveFeedback(process.env['FEEDBACK_SPREADSHEET'], req.body.native_language, [
            req.body.language || '',
            req.body.native_language || '',
            req.body.english_word || '',
            req.body.primary_word || '',
            req.body.translation || '',
            req.body.transliteration || '',
            req.body.sound_link || '',
            req.body.types ? req.body.types.join(', ') : '',
            req.body.content || '',
            new Date()
        ]);
        res.status(200).send("Feedback saved.");
    });
};

exports.getTranslations = async (req, res) => {
    addSecurityHeaders(res);
    return cors(req, res, async () => {
        const english_words = req.body.english_words || [];
        const primary_language = req.body.primary_language || '';
        const target_language = req.body.target_language || '';
        const promises = english_words.map(async english_word => {
            const wordKey = datastore.key(['Translation', english_word]);
            const translations = await datastore.get(wordKey);
            return { word: english_word, translations: translations && translations.length > 0 ? translations[0] : null };
        });
        Promise.all(promises).then(docs => {
            const translations = docs.map(x => createTranslationResponseForApp(x, primary_language, target_language));
            res.status(200).send(translations);
        }).catch(function(error) {
            console.log("Internal server error", error);
            res.status(500).send(error)
        });
    });
};

function createTranslationResponseForApp(data, primary_language, target_language) {
    const primaryTranslation = data && data.translations ? data.translations[primary_language] : null;
    const targetTranslation = data && data.translations ? data.translations[target_language] : null;
    return {
        english_word: data.word,
        primary_word: primaryTranslation ? primaryTranslation.translation || '' : '',
        translation: targetTranslation ? targetTranslation.translation || '' : '',
        transliteration: targetTranslation ? targetTranslation.transliteration || '' : '',
        sound_link: targetTranslation ? targetTranslation.sound_link || '' : ''
    };
}

exports.visionAPI = async (req, res) => {
    addSecurityHeaders(res);
    return cors(req, res, async () => {
        try {
            const requestVision = {
                image: {content: Buffer.from(req.body, 'base64')},
                features: [{type: 'LABEL_DETECTION', maxResults: 10}, {type: 'SAFE_SEARCH_DETECTION'}]
            };
            visionClient.annotateImage(requestVision)
                .then(response => {
                    res.status(200).send(response && response.length > 0 ? response[0] : null);
                    return "200"
                })
                .catch(err => {
                    console.error(err);
                    res.status(500).send(err);
                });
        } catch (err) {
            console.log(`Unable to detect objects: ${err}`)
            res.status(500).send(err);
        }
    });
};<commit_msg>Fixed setting headers in functions.<commit_after>const fs = require('fs');
const uuidv1 = require('uuid/v1');
const cors = require('cors')({origin: true});
const vision = require('@google-cloud/vision');
const {Datastore} = require('@google-cloud/datastore');
const ffmpegPath = require('@ffmpeg-installer/ffmpeg').path;
const ffmpeg = require('fluent-ffmpeg');
const {google} = require('googleapis');

ffmpeg.setFfmpegPath(ffmpegPath);
const visionClient = new vision.v1p3beta1.ImageAnnotatorClient();
const datastore = new Datastore();

async function getGoogleAPIAuthentication() {
    const auth = new google.auth.GoogleAuth({ scopes: ['https://www.googleapis.com/auth/drive'] });
    return await auth.getClient();
}

// Makes an ffmpeg command return a promise.
function promisifyCommand(command) {
    return new Promise((resolve, reject) => {
        command.on('end', resolve).on('error', reject).run();
    });
}

async function writeFileAsync(path, buffer) {
    return new Promise((resolve, reject) => {
        fs.writeFile(path, buffer, (err) => {
            if(err) {
                reject(err);
            } else {
                resolve();
            }
        });
    });
}

function addSecurityHeaders(res) {
    res.set('X-Frame-Options', 'SAMEORIGIN');
}

exports.saveAudioSuggestions = async (req, res) => {
    addSecurityHeaders(res);
    return cors(req, res, async () => {
        // convert base64 body to blob of webm
        const nodeBuffer = Buffer.from(req.body, 'base64');
        // convert to mp3
        const fileName = uuidv1();
        const tempLocalPath = `/tmp/${fileName}.webm`;
        const targetTempFilePath =  `/tmp/${fileName}.mp3`;
        await writeFileAsync(tempLocalPath, nodeBuffer);
        const command = new ffmpeg(tempLocalPath).toFormat('mp3').save(targetTempFilePath);
        await promisifyCommand(command);
        // upload to drive
        const drive = google.drive({version: 'v3', auth: await getGoogleAPIAuthentication()});
        const createResponse = (await drive.files.create({
            requestBody: {
                parents: [ process.env['AUDIO_FOLDER_ID'] ],
                mimeType: 'audio/mp3',
                name: `${fileName}.mp3`
            },
            media: {
                mimeType: 'audio/mp3',
                body: fs.createReadStream(targetTempFilePath),
            }
        }));
        const fileId = createResponse.data.id;
        const file = (await drive.files.get({
            fileId: fileId,
            fields: 'webContentLink'
        })).data;
        console.log(`Audio saved to ${file.webContentLink}.`);
        res.status(200).send(file.webContentLink);
    });
};

async function saveFeedback(spreadsheetId, sheetTitle, data) {
    const sheets = google.sheets({version: 'v4', auth: await getGoogleAPIAuthentication()});
    // find spreadsheet
    const spreadsheet = (await sheets.spreadsheets.get({spreadsheetId: spreadsheetId, fields: 'sheets(properties.title)'})).data;
    if(!spreadsheet) {
        throw new Error("Spreadsheet not found");
    }
    // find sheet
    const sheet = spreadsheet.sheets.find(sh => sh.properties.title === sheetTitle);
    if(!sheet) {
        // sheet does not exist - create it
        await sheets.spreadsheets.batchUpdate({ spreadsheetId: spreadsheetId, requestBody: {
                "requests": [ {
                    "addSheet": {
                        "properties": {
                            "title": sheetTitle,
                            "sheetType": "GRID"
                        }
                    }
                } ]
            } })
    }
    // append data to sheet
    await sheets.spreadsheets.values.append({
        spreadsheetId: spreadsheetId,
        range: sheetTitle + '!A1',
        valueInputOption: 'RAW',
        requestBody: { values: [data] }
    });
}

exports.addSuggestions = async (req, res) => {
    addSecurityHeaders(res);
    return cors(req, res, async () => {
        await saveFeedback(process.env['SUGGESTIONS_SPREADSHEET'], req.body.native_language, [
            req.body.language || '',
            req.body.native_language || '',
            req.body.english_word || '',
            req.body.primary_word || '',
            req.body.translation || '',
            req.body.transliteration || '',
            req.body.sound_link || '',
            new Date()
        ]);
        res.status(200).send("Translation suggestions saved.");
    });
};

exports.addFeedback = async (req, res) => {
    addSecurityHeaders(res);
    return cors(req, res, async () => {
        await saveFeedback(process.env['FEEDBACK_SPREADSHEET'], req.body.native_language, [
            req.body.language || '',
            req.body.native_language || '',
            req.body.english_word || '',
            req.body.primary_word || '',
            req.body.translation || '',
            req.body.transliteration || '',
            req.body.sound_link || '',
            req.body.types ? req.body.types.join(', ') : '',
            req.body.content || '',
            new Date()
        ]);
        res.status(200).send("Feedback saved.");
    });
};

exports.getTranslations = async (req, res) => {
    addSecurityHeaders(res);
    return cors(req, res, async () => {
        const english_words = req.body.english_words || [];
        const primary_language = req.body.primary_language || '';
        const target_language = req.body.target_language || '';
        const promises = english_words.map(async english_word => {
            const wordKey = datastore.key(['Translation', english_word]);
            const translations = await datastore.get(wordKey);
            return { word: english_word, translations: translations && translations.length > 0 ? translations[0] : null };
        });
        Promise.all(promises).then(docs => {
            const translations = docs.map(x => createTranslationResponseForApp(x, primary_language, target_language));
            res.status(200).send(translations);
        }).catch(function(error) {
            console.log("Internal server error", error);
            res.status(500).send(error)
        });
    });
};

function createTranslationResponseForApp(data, primary_language, target_language) {
    const primaryTranslation = data && data.translations ? data.translations[primary_language] : null;
    const targetTranslation = data && data.translations ? data.translations[target_language] : null;
    return {
        english_word: data.word,
        primary_word: primaryTranslation ? primaryTranslation.translation || '' : '',
        translation: targetTranslation ? targetTranslation.translation || '' : '',
        transliteration: targetTranslation ? targetTranslation.transliteration || '' : '',
        sound_link: targetTranslation ? targetTranslation.sound_link || '' : ''
    };
}

exports.visionAPI = async (req, res) => {
    addSecurityHeaders(res);
    return cors(req, res, async () => {
        try {
            const requestVision = {
                image: {content: Buffer.from(req.body, 'base64')},
                features: [{type: 'LABEL_DETECTION', maxResults: 10}, {type: 'SAFE_SEARCH_DETECTION'}]
            };
            visionClient.annotateImage(requestVision)
                .then(response => {
                    res.status(200).send(response && response.length > 0 ? response[0] : null);
                    return "200"
                })
                .catch(err => {
                    console.error(err);
                    res.status(500).send(err);
                });
        } catch (err) {
            console.log(`Unable to detect objects: ${err}`)
            res.status(500).send(err);
        }
    });
};<|endoftext|>


<commit_before>"use strict";

/*global nodeca, _*/

// stdlib
var fs   = require('fs');
var path = require('path');

// 3rd-party
var Mincer = require('mincer');
var nib    = require('nib');

// NLib
var HashTree = require('nlib').Support.HashTree;

// internal
var compression = require('./assets/compression');

////////////////////////////////////////////////////////////////////////////////

function get_compilable(filters, env) {
  var result = [];

  env.eachLogicalPath(filters, function (logicalPath) {
    result.push(logicalPath);
  });

  return result;
}

////////////////////////////////////////////////////////////////////////////////

module.exports = function (next) {
  var files, ignore_list, env, manifest, assets_root;

  assets_root = path.resolve(nodeca.runtime.apps[0].root, 'public/assets');
  env         = new Mincer.Environment(nodeca.runtime.assets_path);
  files       = ['lib.js', 'app.js', '*/app.js', 'app.css', '*/app.css', 'modernizr.custom.js'];
  ignore_list = [/^faye-browser/];

  // function that mathces any non-js or non-css files
  files.push(function nonAsset(logicalPath) {
    var extname = path.extname(logicalPath),
        ignore  = _.any(ignore_list, function (re) {
          return re.test(logicalPath);
        });

    return !(ignore || /\.(js|css)$/.test(extname));
  });

  // Provide some helpers to EJS and Stylus
  env.registerHelper({
    asset_path: function (pathname) {
      var asset = this.environment.findAsset(pathname);
      return asset ? ("/assets/" + asset.digestPath) : null;
    },
    version: function () {
      return nodeca.runtime.version;
    },
    env: function () {
      return nodeca.runtime.env;
    },
    config: function (part) {
      return !part ? nodeca.config : HashTree.get(nodeca.config, part);
    }
  });

  // Add some funky stuff to Stylus
  Mincer.StylusEngine.registerConfigurator(function (style) {
    style.use(nib());
    style.define('import-dir', require('../stylus/import-dir'));
  });

  // fill in paths
  env.appendPath(path.resolve(__dirname, '../../node_modules/faye/browser'));
  env.appendPath(path.resolve(__dirname, '../../../nlib/node_modules/pointer/browser'));
  env.appendPath(path.resolve(__dirname, '../../../nlib/node_modules/babelfish/browser'));
  env.appendPath('assets/js');
  env.appendPath('assets/css');
  env.appendPath('assets/vendor');

  // set up compressors
  env.jsCompressor  = compression.js;
  env.cssCompressor = compression.css;

  // once environment is configured,
  // it can be replaced with 'static' cache version
  env         = env.index;
  manifest    = new Mincer.Manifest(env, assets_root);

  // compile manifest
  manifest.compile(get_compilable(files, env), function (err, data) {
    if (err) {
      next(err);
      return;
    }

    nodeca.runtime.assets = {environment: env, manifest: data};
    next();
  });
};
<commit_msg>Add some more files for re-rendering<commit_after>"use strict";

/*global nodeca, _*/

// stdlib
var fs   = require('fs');
var path = require('path');

// 3rd-party
var Mincer = require('mincer');
var nib    = require('nib');

// NLib
var HashTree = require('nlib').Support.HashTree;

// internal
var compression = require('./assets/compression');

////////////////////////////////////////////////////////////////////////////////

function get_compilable(filters, env) {
  var result = [];

  env.eachLogicalPath(filters, function (logicalPath) {
    result.push(logicalPath);
  });

  console.log(result);
  return result;
}

////////////////////////////////////////////////////////////////////////////////

module.exports = function (next) {
  var files, ignore_list, env, manifest, assets_root;

  assets_root = path.resolve(nodeca.runtime.apps[0].root, 'public/assets');
  env         = new Mincer.Environment(nodeca.runtime.assets_path);
  files       = ['lib.js', 'app.js', '*/app.js', 'app.css', '*/app.css', 'modernizr.custom.js'];
  ignore_list = [/^faye-browser/, /\.jade$/];

  files.push('*/app.js', '*/app.css');
  files.push('**/api.js', '**/i18n/*.js', 'views/**.js');

  // function that mathces any non-js or non-css files
  files.push(function nonAsset(logicalPath) {
    var extname = path.extname(logicalPath),
        ignore  = _.any(ignore_list, function (re) {
          return re.test(logicalPath);
        });

    return !(ignore || /\.(js|css)$/.test(extname));
  });

  // Provide some helpers to EJS and Stylus
  env.registerHelper({
    asset_path: function (pathname) {
      var asset = this.environment.findAsset(pathname);
      return asset ? ("/assets/" + asset.digestPath) : null;
    },
    version: function () {
      return nodeca.runtime.version;
    },
    env: function () {
      return nodeca.runtime.env;
    },
    config: function (part) {
      return !part ? nodeca.config : HashTree.get(nodeca.config, part);
    }
  });

  // Add some funky stuff to Stylus
  Mincer.StylusEngine.registerConfigurator(function (style) {
    style.use(nib());
    style.define('import-dir', require('../stylus/import-dir'));
  });

  // fill in paths
  env.appendPath(path.resolve(__dirname, '../../node_modules/faye/browser'));
  env.appendPath(path.resolve(__dirname, '../../../nlib/node_modules/pointer/browser'));
  env.appendPath(path.resolve(__dirname, '../../../nlib/node_modules/babelfish/browser'));
  env.appendPath('assets/js');
  env.appendPath('assets/css');
  env.appendPath('assets/vendor');
  env.appendPath('system');
  env.appendPath('views');

  // set up compressors
  env.jsCompressor  = compression.js;
  env.cssCompressor = compression.css;

  // once environment is configured,
  // it can be replaced with 'static' cache version
  env         = env.index;
  manifest    = new Mincer.Manifest(env, assets_root);

  // compile manifest
  manifest.compile(get_compilable(files, env), function (err, data) {
    if (err) {
      next(err);
      return;
    }

    nodeca.runtime.assets = {environment: env, manifest: data};
    next();
  });
};
<|endoftext|>


<commit_before>// Copyright 2010 Steven Dee. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

goog.provide('jsprettify.example');

goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('jsprettify.prettifyStr');

jsprettify.example.doJsprettifyExample = function() {
  var input = goog.dom.$('input');
  var output = goog.dom.$('output');
  var updateText = function(e) {
    if (e)
      e.stopPropagation();
    goog.dom.setTextContent(output, jsprettify.prettifyStr(input.value));
  };
  updateText();
  goog.events.listen(input, goog.events.EventType.KEYUP, updateText);
};

window['doJsprettifyExample'] = jsprettify.example.doJsprettifyExample;
<commit_msg>Fix a compiler warning by explicitly passing null.<commit_after>// Copyright 2010 Steven Dee. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

goog.provide('jsprettify.example');

goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('jsprettify.prettifyStr');

jsprettify.example.doJsprettifyExample = function() {
  var input = goog.dom.$('input');
  var output = goog.dom.$('output');
  var updateText = function(e) {
    if (e)
      e.stopPropagation();
    goog.dom.setTextContent(output, jsprettify.prettifyStr(input.value));
  };
  updateText(null);
  goog.events.listen(input, goog.events.EventType.KEYUP, updateText);
};

window['doJsprettifyExample'] = jsprettify.example.doJsprettifyExample;
<|endoftext|>


<commit_before>/*!
 * Scriptme.Interpreter
 * Copyright(c) 2012-2013 Delmo Carrozzo <dcardev@gmail.com>
 * MIT Licensed
 */

 /**
  * Module dependencies.
  */
var fs = require('fs')
  , XRegExp = require('xregexp').XRegExp
  , Renderer = require('./renderer')
  , beautify = require('js-beautify').js_beautify
  , Node = require('./node')
  , async = require('async');

/**
 * Initialize a new Interpreter.
 *
 */
var Interpreter = module.exports = function Interpreter() {
	var self = this;

	self.tmpl = "";
	self.output = "";
	self.nodes = [];
	self.regex = {

	};

	return self;
};

Interpreter.prototype.constructor = Interpreter;

/**
 * getter/setter template
 *
 * @param {String} value
 */
Interpreter.prototype.template = function(value) {
	var self = this;
	if (value == undefined) {
		return self.tmpl;
	}

	self.tmpl = value;

	return self;
};

/**
 * Render the current template with `options`
 *
 * TODO: Please optimize this
 *
 * @param {Object} options
 * @param {Function} fn
 *
 * @see Interpreter.template
 */
Interpreter.prototype.render = function(options, fn) {
	var self = this;

	if (options && typeof options === 'function') {
		fn = options;
		options = {};
	}

	if (!self.tmpl || self.tmpl == '') {
		fn && fn(null, '');
		return;
	}

	var tmpl = self.tmpl;

	var regexLib = {
		doubleQuotedString			: /"([^\\"\n]|\\.)*"/g,
		singleQuotedString			: /'([^\\'\n]|\\.)*'/g,
		string                      : /(["'])(?:\\\1|.)*?\1/,
		block: {
			  init: '((\r\n|\n)[\s\t]*)?<\\!js'
			, end: '\\!>([\s\t]*(\r\n|\n))?'
		}
	};

	var fieldValue = 'value'
	  , fieldName = 'name'
	  , renderer = new Renderer();;

	if (XRegExp.version[0] === '2') {
		fieldValue = 'name';
		fieldName = 'value';
	}

	var nodes = [];

	var blocks = XRegExp.matchRecursive(
		tmpl,
		regexLib.block.init,
		regexLib.block.end, 'gi', {
	    valueNames: ['between', null, 'match', null]
	});

	var pos = 0, qnodes = [];

	while (match = XRegExp.exec(tmpl, regexLib.string, pos)) {
		//console.log(match);
	    qnodes.push( { start:match.index, end: match.index + match[0].length, match: match[0] } );
	    pos = match.index + match[0].length;
	}

	for (var i = 0; i < blocks.length; i++) {
		var b = blocks[i];
		var type = b[fieldName];
		var value = b[fieldValue]

		switch(type.toLowerCase()) {
			case 'match':

				var inQuotes = qnodes.some(function(item){
					return item.start < b.start && item.end > b.end;
				});

				if (inQuotes) {
					throw new Error('Block in quotes at index: ' + b.start)
				}

				nodes.push(new Node({
					type: 'jsblock',
					start: b.start,
					end: b.end,
					content: b[fieldValue]
				}));

			break;
			case 'between':
				var paramRegex = new XRegExp('\\!\\[(?<param>[a-zA-Z0-9]+)\\]', 'gi');
				var varRegex = new XRegExp('\\!\\!(?<param>[a-zA-Z0-9\.\\[\\]]+)', 'gi');

				var out = renderer.response(value);

				/*
				var output = XRegExp.replace(value, paramRegex, function(match, m, s) {

					var inQuotes = qnodes.some(function(item){
						return item.start < s && (s + m.length) > b.end;
					});

					if (inQuotes) {
						return '" + context.' + m + ' + "';
					} else {
						return 'context.' + match.param;
					}
				});*/

				out = XRegExp.replace(out, paramRegex, function(match) {
				    return '" + (context.' + match.param + ' || "") + "';
				});

				out = XRegExp.replace(out, varRegex, function(match) {
				    return '" + (' + match.param + ' || "") + "';
				});

				//console.log(out);
				//console.log(output);
				nodes.push(new Node({
					type: 'renderer',
					start: b.start,
					end: b.end,
					content: out
				}));

			break;
			default:
				nodes.push(new Node({
					type: 'undefined',
					start: b.start,
					end: b.end,
					content: b[fieldValue]
				}));

		};
	}

	var renderer = '';

	nodes.forEach(function(n){
		renderer += n.content;
	});

	fn(null, renderer);

	/*
	async.waterfall(
		[
			// clean the new lines
			function(callback) {
				cleanNewlines(self.tmpl, callback);
			},

			// render the blocks
			reanderBlocks,

			// replace the params context
			reanderParamContext,

			// replace the vars
			reanderVars,
		],
		// render complete
	    function(err, output) {
	        fn(err, output);
	    }

	);*/

	return self;
};

/**
 * Clean de new lines outside blocks of `input`
 *
 * @param {String} input
 */
function cleanNewlines(input, fn) {
	var target = input;

	// clean de new lines in the block end
	var beRegex = new XRegExp('(?<be>\\!>)([\s\t]*(\r\n|\n))', 'gi');
	var biRegex = new XRegExp('((\r\n|\n)[\s\t]*)(?<bi><\\!js)', 'gi');

	target = XRegExp.replace(target, beRegex, function(match) {
	    return match.be;
	});

	target = XRegExp.replace(target, biRegex, function(match) {
	    return match.bi;
	});

	fn && fn(null, target)
}

/**
 * Make the blocks of `input`
 *
 *@param {String} input
 */
function reanderBlocks(input, fn) {
	var output = ''
	  , renderer = new Renderer();

	/*
	 * possible BUG in XRegExp ?
	 * map the 'name' into 'value' and the 'value' into 'name'
	 */
	var fieldValue = 'name',
		fieldName = 'value';

	var results = XRegExp.matchRecursive(input, '<\\!js', '\\!>', 'gi', {
	    valueNames: ['between', null, 'match', null]
	});

	for (var i = 0; i < results.length; i++) {
		var a = results[i][fieldName];

		switch(a.toLowerCase()) {
			case 'between':
				output += renderer.response(results[i][fieldValue]);
			break;
			default:
				output += results[i][fieldValue];
		};

	};

	fn && fn(null, output);
}

/**
 * Replace the params context into `input`
 *
 * @params {String} input
 */
function reanderParamContext(input, fn) {
	var output = '';

	var paramRegex = new XRegExp('\\!\\[(?<param>[a-zA-Z0-9]+)\\]', 'gi');

	output = XRegExp.replace(input, paramRegex, function(match) {
	    return '" + (context.' + match.param + ' || "") + "';
	});

	fn && fn(null, output);
}

/**
 * Replace the vars into `input`
 *
 * @params {String} input
 */
function reanderVars(input, fn) {
	var output = '';

	var varRegex = new XRegExp('\\!\\!(?<param>[a-zA-Z0-9\.\\[\\]]+)', 'gi');

	output = XRegExp.replace(input, varRegex, function(match) {
	    return '" + (' + match.param + ' || "") + "';
	});

	fn && fn(null, output);
}<commit_msg>fix bug<commit_after>/*!
 * Scriptme.Interpreter
 * Copyright(c) 2012-2013 Delmo Carrozzo <dcardev@gmail.com>
 * MIT Licensed
 */

 /**
  * Module dependencies.
  */
var fs = require('fs')
  , XRegExp = require('xregexp').XRegExp
  , Renderer = require('./renderer')
  , beautify = require('js-beautify').js_beautify
  , Node = require('./node')
  , async = require('async');

/**
 * Initialize a new Interpreter.
 *
 */
var Interpreter = module.exports = function Interpreter() {
	var self = this;

	self.tmpl = "";
	self.output = "";
	self.nodes = [];
	self.regex = {

	};

	return self;
};

Interpreter.prototype.constructor = Interpreter;

/**
 * getter/setter template
 *
 * @param {String} value
 */
Interpreter.prototype.template = function(value) {
	var self = this;
	if (value == undefined) {
		return self.tmpl;
	}

	self.tmpl = value;

	return self;
};

/**
 * Render the current template with `options`
 *
 * TODO: Please optimize this
 *
 * @param {Object} options
 * @param {Function} fn
 *
 * @see Interpreter.template
 */
Interpreter.prototype.render = function(options, fn) {
	var self = this;

	if (options && typeof options === 'function') {
		fn = options;
		options = {};
	}

	if (!self.tmpl || self.tmpl == '') {
		fn && fn(null, '');
		return;
	}

	var tmpl = self.tmpl;

	var regexLib = {
		doubleQuotedString			: /"([^\\"\n]|\\.)*"/g,
		singleQuotedString			: /'([^\\'\n]|\\.)*'/g,
		string                      : /(["'])(?:\\\1|.)*?\1/,
		block: {
			  init: '((\r\n|\n)[\s\t]*)?<\\!js'
			, end: '\\!>([\s\t]*(\r\n|\n))?'
		}
	};

	var fieldValue = 'value'
	  , fieldName = 'name'
	  , renderer = new Renderer();;

	if (XRegExp.version[0] === '2') {
		fieldValue = 'name';
		fieldName = 'value';
	}

	var nodes = [];

	var blocks = XRegExp.matchRecursive(
		tmpl,
		regexLib.block.init,
		regexLib.block.end, 'gi', {
	    valueNames: ['between', null, 'match', null]
	});

	var pos = 0, qnodes = [];

	while (match = XRegExp.exec(tmpl, regexLib.string, pos)) {
		//console.log(match);
	    qnodes.push( { start:match.index, end: match.index + match[0].length, match: match[0] } );
	    pos = match.index + match[0].length;
	}

	for (var i = 0; i < blocks.length; i++) {
		var b = blocks[i];
		var type = b[fieldName];
		var value = b[fieldValue]

		switch(type.toLowerCase()) {
			case 'match':

				var inQuotes = qnodes.some(function(item){
					return item.start < b.start && item.end > b.end;
				});

				if (inQuotes) {
					throw new Error('Block in quotes at index: ' + b.start)
				}

				nodes.push(new Node({
					type: 'jsblock',
					start: b.start,
					end: b.end,
					content: b[fieldValue]
				}));

			break;
			case 'between':
				var paramRegex = new XRegExp('\\!\\[(?<param>[a-zA-Z0-9\.]+)\\]', 'gi');
				var varRegex = new XRegExp('\\!\\!(?<param>[a-zA-Z0-9\.\\[\\]]+)', 'gi');

				var out = renderer.response(value);

				/*
				var output = XRegExp.replace(value, paramRegex, function(match, m, s) {

					var inQuotes = qnodes.some(function(item){
						return item.start < s && (s + m.length) > b.end;
					});

					if (inQuotes) {
						return '" + context.' + m + ' + "';
					} else {
						return 'context.' + match.param;
					}
				});*/

				out = XRegExp.replace(out, paramRegex, function(match) {
				    return '" + (context.' + match.param + ' || "") + "';
				});

				out = XRegExp.replace(out, varRegex, function(match) {
				    return '" + (' + match.param + ' || "") + "';
				});

				//console.log(out);
				//console.log(output);
				nodes.push(new Node({
					type: 'renderer',
					start: b.start,
					end: b.end,
					content: out
				}));

			break;
			default:
				nodes.push(new Node({
					type: 'undefined',
					start: b.start,
					end: b.end,
					content: b[fieldValue]
				}));

		};
	}

	var renderer = '';

	nodes.forEach(function(n){
		renderer += n.content;
	});

	fn(null, renderer);

	/*
	async.waterfall(
		[
			// clean the new lines
			function(callback) {
				cleanNewlines(self.tmpl, callback);
			},

			// render the blocks
			reanderBlocks,

			// replace the params context
			reanderParamContext,

			// replace the vars
			reanderVars,
		],
		// render complete
	    function(err, output) {
	        fn(err, output);
	    }

	);*/

	return self;
};

/**
 * Clean de new lines outside blocks of `input`
 *
 * @param {String} input
 */
function cleanNewlines(input, fn) {
	var target = input;

	// clean de new lines in the block end
	var beRegex = new XRegExp('(?<be>\\!>)([\s\t]*(\r\n|\n))', 'gi');
	var biRegex = new XRegExp('((\r\n|\n)[\s\t]*)(?<bi><\\!js)', 'gi');

	target = XRegExp.replace(target, beRegex, function(match) {
	    return match.be;
	});

	target = XRegExp.replace(target, biRegex, function(match) {
	    return match.bi;
	});

	fn && fn(null, target)
}

/**
 * Make the blocks of `input`
 *
 *@param {String} input
 */
function reanderBlocks(input, fn) {
	var output = ''
	  , renderer = new Renderer();

	/*
	 * possible BUG in XRegExp ?
	 * map the 'name' into 'value' and the 'value' into 'name'
	 */
	var fieldValue = 'name',
		fieldName = 'value';

	var results = XRegExp.matchRecursive(input, '<\\!js', '\\!>', 'gi', {
	    valueNames: ['between', null, 'match', null]
	});

	for (var i = 0; i < results.length; i++) {
		var a = results[i][fieldName];

		switch(a.toLowerCase()) {
			case 'between':
				output += renderer.response(results[i][fieldValue]);
			break;
			default:
				output += results[i][fieldValue];
		};

	};

	fn && fn(null, output);
}

/**
 * Replace the params context into `input`
 *
 * @params {String} input
 */
function reanderParamContext(input, fn) {
	var output = '';

	var paramRegex = new XRegExp('\\!\\[(?<param>[a-zA-Z0-9]+)\\]', 'gi');

	output = XRegExp.replace(input, paramRegex, function(match) {
	    return '" + (context.' + match.param + ' || "") + "';
	});

	fn && fn(null, output);
}

/**
 * Replace the vars into `input`
 *
 * @params {String} input
 */
function reanderVars(input, fn) {
	var output = '';

	var varRegex = new XRegExp('\\!\\!(?<param>[a-zA-Z0-9\.\\[\\]]+)', 'gi');

	output = XRegExp.replace(input, varRegex, function(match) {
	    return '" + (' + match.param + ' || "") + "';
	});

	fn && fn(null, output);
}<|endoftext|>


<commit_before>$(document).ready(function(){
    $('.action-delete').hover(function(){
        $(this).next().fadeIn('fast');
    },function(){
        $(this).next().fadeOut('fast');
    });
    $('#theDashboardMenu ul li').click(function(){
        $('#theDashboardMenu ul li').toggle();
    });
    $('.save').hover(function(){
        $(this).find('.the-categories-menu').fadeIn('fast');
    },function(){
        $(this).find('.the-categories-menu').fadeOut('fast');
    });
});
$(window).scroll(function() {

    var currentScroll = $('html').scrollTop() || $('body').scrollTop();
    if($(window).width() <= 600){
        top_margin = 270;
    }else{
        top_margin = 200;
    }
    $('.dashboard-feedback').each(function(){
        var top_offset = $(this).offset().top;
        var bot_offset = $(this).height() + top_offset - currentScroll;

        console.log('element : ' + $(this).index() + ' | current :' +currentScroll + ' | top offset :' + top_offset + ' | bot_offset :' + bot_offset);

        var add_margin = 40 + currentScroll - top_offset;
        if((currentScroll >= top_offset) && (bot_offset >= top_margin)){
            console.log('boom!' + $(this).index());
            $(this).find('.feedback-action-menu').css('top',add_margin);
        }else{
            $(this).find('.feedback-action-menu').css('top',0);
        }
    });

});<commit_msg>removed toggle list<commit_after>$(document).ready(function(){
    $('.action-delete').hover(function(){
        $(this).next().fadeIn('fast');
    },function(){
        $(this).next().fadeOut('fast');
    });

    $('.save').hover(function(){
        $(this).find('.the-categories-menu').fadeIn('fast');
    },function(){
        $(this).find('.the-categories-menu').fadeOut('fast');
    });
});
$(window).scroll(function() {

    var currentScroll = $('html').scrollTop() || $('body').scrollTop();
    if($(window).width() <= 600){
        top_margin = 270;
    }else{
        top_margin = 200;
    }
    $('.dashboard-feedback').each(function(){
        var top_offset = $(this).offset().top;
        var bot_offset = $(this).height() + top_offset - currentScroll;

        console.log('element : ' + $(this).index() + ' | current :' +currentScroll + ' | top offset :' + top_offset + ' | bot_offset :' + bot_offset);

        var add_margin = 40 + currentScroll - top_offset;
        if((currentScroll >= top_offset) && (bot_offset >= top_margin)){
            console.log('boom!' + $(this).index());
            $(this).find('.feedback-action-menu').css('top',add_margin);
        }else{
            $(this).find('.feedback-action-menu').css('top',0);
        }
    });

});
<|endoftext|>


<commit_before>var pomelo = require('pomelo');
var areaService = require('./app/services/areaService');
var instanceManager = require('./app/services/instanceManager');
var scene = require('./app/domain/area/scene');
var instancePool = require('./app/domain/area/instancePool');
var dataApi = require('./app/util/dataApi');
var routeUtil = require('./app/util/routeUtil');
var playerFilter = require('./app/servers/area/filter/playerFilter');
var ChatService = require('./app/services/chatService');
var sync = require('pomelo-sync-plugin');

/**
 * Init app for client
 */
var app = pomelo.createApp();
app.set('name', 'lord of pomelo');

// Configure for production enviroment
app.configure('production', function() {
	// enable the system monitor modules
	app.enable('systemMonitor');
});

// configure for global
app.configure('production|development', function() {
  app.before(pomelo.filters.toobusy());
	app.enable('systemMonitor');
	//var sceneInfo = require('./app/modules/sceneInfo');
	var onlineUser = require('./app/modules/onlineUser');
	if(typeof app.registerAdmin === 'function'){
		//app.registerAdmin(sceneInfo, {app: app});
		app.registerAdmin(onlineUser, {app: app});
	}
	//Set areasIdMap, a map from area id to serverId.
	if (app.serverType !== 'master') {
		var areas = app.get('servers').area;
		var areaIdMap = {};
		for(var id in areas){
			areaIdMap[areas[id].area] = areas[id].id;
		}
		app.set('areaIdMap', areaIdMap);
	}
	// proxy configures
	app.set('proxyConfig', {
		cacheMsg: true,
		interval: 30,
		lazyConnection: true,
		enableRpcLog: true
	});

	// remote configures
	app.set('remoteConfig', {
		cacheMsg: true,
		interval: 30
	});

	// route configures
	app.route('area', routeUtil.area);
	app.route('connector', routeUtil.connector);

	app.loadConfig('mysql', app.getBase() + '/../shared/config/mysql.json');
	app.filter(pomelo.filters.timeout());
});

// Configure for auth server
app.configure('production|development', 'auth', function() {
	// load session congfigures
	app.set('session', require('./config/session.json'));
});

// Configure for area server
app.configure('production|development', 'area', function(){
  app.before(pomelo.filters.toobusy(10));
	app.filter(pomelo.filters.serial());
	app.before(playerFilter());

	//Load scene server and instance server
	var server = app.curServer;
	if(server.instance){
		instancePool.init(require('./config/instance.json'));
		app.areaManager = instancePool;
	}else{
		scene.init(dataApi.area.findById(server.area));
		app.areaManager = scene;
	}

	//Init areaService
	areaService.init();
});

app.configure('production|development', 'manager', function(){
	var events = pomelo.events;

	app.event.on(events.ADD_SERVERS, instanceManager.addServers);

	app.event.on(events.REMOVE_SERVERS, instanceManager.removeServers);
});

// Configure database
app.configure('production|development', 'area|auth|connector|master', function() {
	var dbclient = require('./app/dao/mysql/mysql').init(app);
	app.set('dbclient', dbclient);
	// app.load(pomelo.sync, {path:__dirname + '/app/dao/mapping', dbclient: dbclient});
  app.use(sync, {sync: {path:__dirname + '/app/dao/mapping', dbclient: dbclient}});
});

app.configure('production|development', 'connector', function(){
	var dictionary = app.components['__dictionary__'];
	var dict = null;
	if(!!dictionary){
		dict = dictionary.getDict();
	}

	app.set('connectorConfig',
		{
			connector : pomelo.connectors.hybridconnector,
			heartbeat : 30,
			useDict : true,
			useProtobuf : true,
			handshake : function(msg, cb){
				cb(null, {});
			}
		});
});

app.configure('production|development', 'gate', function(){
	app.set('connectorConfig',
		{
			connector : pomelo.connectors.hybridconnector,
		});
});
// Configure for chat server
app.configure('production|development', 'chat', function() {
	app.set('chatService', new ChatService(app));
});

//start
app.start();

// Uncaught exception handler
process.on('uncaughtException', function(err) {
	console.error(' Caught exception: ' + err.stack);
});
<commit_msg>modify toobusy lag to 60ms<commit_after>var pomelo = require('pomelo');
var areaService = require('./app/services/areaService');
var instanceManager = require('./app/services/instanceManager');
var scene = require('./app/domain/area/scene');
var instancePool = require('./app/domain/area/instancePool');
var dataApi = require('./app/util/dataApi');
var routeUtil = require('./app/util/routeUtil');
var playerFilter = require('./app/servers/area/filter/playerFilter');
var ChatService = require('./app/services/chatService');
var sync = require('pomelo-sync-plugin');

/**
 * Init app for client
 */
var app = pomelo.createApp();
app.set('name', 'lord of pomelo');

// Configure for production enviroment
app.configure('production', function() {
	// enable the system monitor modules
	app.enable('systemMonitor');
});

// configure for global
app.configure('production|development', function() {
  app.before(pomelo.filters.toobusy(60));
	app.enable('systemMonitor');
	//var sceneInfo = require('./app/modules/sceneInfo');
	var onlineUser = require('./app/modules/onlineUser');
	if(typeof app.registerAdmin === 'function'){
		//app.registerAdmin(sceneInfo, {app: app});
		app.registerAdmin(onlineUser, {app: app});
	}
	//Set areasIdMap, a map from area id to serverId.
	if (app.serverType !== 'master') {
		var areas = app.get('servers').area;
		var areaIdMap = {};
		for(var id in areas){
			areaIdMap[areas[id].area] = areas[id].id;
		}
		app.set('areaIdMap', areaIdMap);
	}
	// proxy configures
	app.set('proxyConfig', {
		cacheMsg: true,
		interval: 30,
		lazyConnection: true,
		enableRpcLog: true
	});

	// remote configures
	app.set('remoteConfig', {
		cacheMsg: true,
		interval: 30
	});

	// route configures
	app.route('area', routeUtil.area);
	app.route('connector', routeUtil.connector);

	app.loadConfig('mysql', app.getBase() + '/../shared/config/mysql.json');
	app.filter(pomelo.filters.timeout());
});

// Configure for auth server
app.configure('production|development', 'auth', function() {
	// load session congfigures
	app.set('session', require('./config/session.json'));
});

// Configure for area server
app.configure('production|development', 'area', function(){
  // app.before(pomelo.filters.toobusy(10));
	app.filter(pomelo.filters.serial());
	app.before(playerFilter());

	//Load scene server and instance server
	var server = app.curServer;
	if(server.instance){
		instancePool.init(require('./config/instance.json'));
		app.areaManager = instancePool;
	}else{
		scene.init(dataApi.area.findById(server.area));
		app.areaManager = scene;
	}

	//Init areaService
	areaService.init();
});

app.configure('production|development', 'manager', function(){
	var events = pomelo.events;

	app.event.on(events.ADD_SERVERS, instanceManager.addServers);

	app.event.on(events.REMOVE_SERVERS, instanceManager.removeServers);
});

// Configure database
app.configure('production|development', 'area|auth|connector|master', function() {
	var dbclient = require('./app/dao/mysql/mysql').init(app);
	app.set('dbclient', dbclient);
	// app.load(pomelo.sync, {path:__dirname + '/app/dao/mapping', dbclient: dbclient});
  app.use(sync, {sync: {path:__dirname + '/app/dao/mapping', dbclient: dbclient}});
});

app.configure('production|development', 'connector', function(){
	var dictionary = app.components['__dictionary__'];
	var dict = null;
	if(!!dictionary){
		dict = dictionary.getDict();
	}

	app.set('connectorConfig',
		{
			connector : pomelo.connectors.hybridconnector,
			heartbeat : 30,
			useDict : true,
			useProtobuf : true,
			handshake : function(msg, cb){
				cb(null, {});
			}
		});
});

app.configure('production|development', 'gate', function(){
	app.set('connectorConfig',
		{
			connector : pomelo.connectors.hybridconnector,
		});
});
// Configure for chat server
app.configure('production|development', 'chat', function() {
	app.set('chatService', new ChatService(app));
});

//start
app.start();

// Uncaught exception handler
process.on('uncaughtException', function(err) {
	console.error(' Caught exception: ' + err.stack);
});
<|endoftext|>


<commit_before>var
  _ = require('underscore'),
  highlightLib = require('highlight.js'),
  marked = require('marked');

function highlight(code) {
  return code ? highlightLib.highlightAuto('' + code).value : '';
}

var markedConfig = {
  gfm: true,
  smartypants: true,
  highlight: highlight
};

marked.setOptions(markedConfig);

module.exports = {
  marked: markedConfig,
  helpers: {
    highlight: highlight,
    log: function (item) {
      console.log(item);
    },
    marked: function(content) {
      return content ? marked('' + content) : '';
    },
    isShortable: function(content) {
      return content && content.indexOf('.') > 0 && content.substr(content.indexOf('.') + 1).length > 0;
    },
    shorten: function(content) {
      if (content && content.indexOf('.') > 0) {
        var substr = content.substr(content.indexOf('.') + 1);

        if (substr.length > 0) {
          return content.substr(0, content.indexOf('.')) + '...';
        }
      }

      return content;
    },
    is: function(resource, method, target) {
      return _.contains(method.is, target) || _.contains(resource.is, target);
    },
    isSecuredBy: function(method, name, type) {
      if (method.securedBy) {
        var flag = false;

        _.each(method.securedBy, function(securedBy) {
          if (securedBy == name || securedBy[name]) {
            if (type != null && securedBy[name].type && securedBy[name].type == type) {
              flag = true;
            }
            else {
              flag = true;
            }
          }
        })
      }

      return flag;
    },
    contentLessShorten: function(content) {
      if (content && content.indexOf('.')) {
        return content.substr(content.indexOf('.') + 1);
      }
      else {
        return content;
      }
    }
  }
};
<commit_msg>Removed dirty logging used for template dev<commit_after>var
  _ = require('underscore'),
  highlightLib = require('highlight.js'),
  marked = require('marked');

function highlight(code) {
  return code ? highlightLib.highlightAuto('' + code).value : '';
}

var markedConfig = {
  gfm: true,
  smartypants: true,
  highlight: highlight
};

marked.setOptions(markedConfig);

module.exports = {
  marked: markedConfig,
  helpers: {
    highlight: highlight,
    marked: function(content) {
      return content ? marked('' + content) : '';
    },
    isShortable: function(content) {
      return content && content.indexOf('.') > 0 && content.substr(content.indexOf('.') + 1).length > 0;
    },
    shorten: function(content) {
      if (content && content.indexOf('.') > 0) {
        var substr = content.substr(content.indexOf('.') + 1);

        if (substr.length > 0) {
          return content.substr(0, content.indexOf('.')) + '...';
        }
      }

      return content;
    },
    is: function(resource, method, target) {
      return _.contains(method.is, target) || _.contains(resource.is, target);
    },
    isSecuredBy: function(method, name, type) {
      if (method.securedBy) {
        var flag = false;

        _.each(method.securedBy, function(securedBy) {
          if (securedBy == name || securedBy[name]) {
            if (type != null && securedBy[name].type && securedBy[name].type == type) {
              flag = true;
            }
            else {
              flag = true;
            }
          }
        })
      }

      return flag;
    },
    contentLessShorten: function(content) {
      if (content && content.indexOf('.')) {
        return content.substr(content.indexOf('.') + 1);
      }
      else {
        return content;
      }
    }
  }
};
<|endoftext|>


<commit_before>const dwarfNames = require('./names');

/**
 * Return first and last characters of the given name.
 *
 * @example
 *
 *  'Garrett' => ['g', 't']
 *  'Caira' => ['c', 'a']
 *
 * @private
 * @param {string} name
 * @return {string[]}
 */

function getNameLetters(name) {
    const [first] = name.toLowerCase().split('').slice(0, -1);
    const [last] = name.toLowerCase().split('').slice(-1);

    return [first, last];
}

/**
 * Are all passed names valid? (string of length > 0);
 *
 * @param {string[]} names - Names to validate.
 * @return {boolean}
 */

function validNames(...names) {
    return names.every(name => typeof name === 'string' && name.length);
}

/**
 * Dwarfinate a name name of the given kind (first name or last name).
 *
 * @private
 * @param {string} name - Name to dwarfinate.
 * @param {string} kind - Kind of name to dwarfinate (first or last).
 * @return {string} - Dwarfinated name.
 */

function dwarfName(name, kind = 'first') {
    const [first, last] = getNameLetters(name);
    return [dwarfNames[kind].start[first], dwarfNames[kind].end[last]].join('');
}

/**
 * Dwarfinate someone's full name.
 *
 * @example
 *
 *  'Garrett Parrott' => 'Marvi Goldgrip'
 *  'Caira Doo' => 'Urdar Ironstrike'
 *
 * @public
 * @param {string} first - First name to dwarfinate.
 * @return {string} name - Surname to dwarfinate.
 */

module.exports = function dwarfinate(firstName, lastName) {
    if (validNames(firstName, lastName)) {
        return [dwarfName(firstName, 'first'), dwarfName(lastName, 'last')].join(' ');
    } else {
        throw `Invalid names "${firstName}" and "${lastName}" given!`;
    }
};
<commit_msg>Code cleanups.<commit_after>const dwarfNames = require('./names');

/**
 * Return first and last characters of the given name.
 *
 * @example
 *
 *  'Garrett' => ['g', 't']
 *  'Caira' => ['c', 'a']
 *
 * @private
 * @param {string} name
 * @return {string[]}
 */

function getNameLetters(name) {
    const [first] = name.toLowerCase().split('').slice(0, 1);
    const [last] = name.toLowerCase().split('').slice(-1);
    return [first, last];
}

/**
 * Are all passed names valid? (string of length > 0);
 *
 * @private
 * @param {string[]} names - Names to validate.
 * @return {boolean}
 */

function validNames(...names) {
    return names.every(name => typeof name === 'string' && name.length);
}

/**
 * Dwarfinate a name name of the given kind (first name or last name).
 *
 * @private
 * @param {string} name - Name to dwarfinate.
 * @param {string} kind - Kind of name to dwarfinate (first or last).
 * @return {string} - Dwarfinated name.
 */

function dwarfName(name, kind = 'first') {
    const [first, last] = getNameLetters(name);
    return [dwarfNames[kind].start[first], dwarfNames[kind].end[last]].join('');
}

/**
 * Dwarfinate someone's first and last names.
 *
 * @example
 *
 *  'Garrett Parrott' => 'Marvi Goldgrip'
 *  'Caira Doo' => 'Urdar Ironstrike'
 *
 * @public
 * @param {string} first - First name to dwarfinate.
 * @param {string} last - Last name to dwarfinate.
 * @return {string} - Joined dwarfinated name.
 */

module.exports = function dwarfinate(first, last) {
    if (validNames(first, last)) {
        return [dwarfName(first, 'first'), dwarfName(last, 'last')].join(' ');
    } else {
        throw `Invalid names "${first}" and "${last}" given!`;
    }
};
<|endoftext|>


<commit_before>var GameController = function(args) {
  this.pelletCount = 0;
  this.keyStates = {
    up: false,
    down: false,
    left: false,
    right: false
  }
  this.pacMoveInterval = false;

  this.pacCanvas = args.pacCanvas;
  this.blinkyCanvas = args.blinkyCanvas;
  this.inkyCanvas = args.inkyCanvas;
  this.pinkyCanvas = args.pinkyCanvas;
  this.clydeCanvas = args.clydeCanvas;
  this.boardCanvas = args.boardCanvas;
  this.pelletCanvas = args.pelletCanvas;

  this.pac = new Actor(ACTOR_ARGS.pac);
  this.blinky = new Ghost(ACTOR_ARGS.blinky);
  this.inky = new Ghost(ACTOR_ARGS.inky);
  this.pinky = new Ghost(ACTOR_ARGS.pinky);
  this.clyde = new Ghost(ACTOR_ARGS.clyde);

  this.gameBoard = args.gameBoard;
  this.actorBoard = args.actorBoard;

  this.drawPellets();
  drawBorders(this.boardCanvas.context);

  this.pacCanvas.renderPac(this.pac);

  addEventListener("keydown", this.handleKeyDown.bind(this));
  addEventListener("keyup", this.handleKeyUp.bind(this));

  setInterval(function() {
    this.moveGhost("b");
    this.moveGhost("i");
    this.moveGhost("p");
    this.moveGhost("c");
  }.bind(this), GHOST_MOVE_DELAY);
}
GameController.prototype.drawPellets = function() {
  this.pelletCanvas.clearRect({
    x: 0,
    y: 0,
    w: BOARD_WIDTH,
    h: BOARD_HEIGHT
  });
  this.gameBoard.board.matrix.forEach(function(row, rIndex) {
    row.forEach(function(col, cIndex) {
      if(col == ".") {
        this.pelletCanvas.drawRect({
          color: PELLET_COLOR,
          x: (8 * cIndex) + 3,
          y: (8 * rIndex) + 27,
          w: 2,
          h: 2
        });
      }
      else if(col == "o") {
        this.pelletCanvas.drawCircle({
          x: (8 * cIndex) + 4,
          y: (8 * rIndex) + 28,
          rad: 4
        });
      }
      else if(col == "-") {
        this.pelletCanvas.drawRect({
          color: PELLET_COLOR,
          x: 8 * cIndex,
          y: (8 * rIndex) + 29,
          w: 8,
          h: 2
        });
      }
    }.bind(this));
  }.bind(this));

  var score = this.pelletCount.toString();
  if(score.length == 1) {
    score = "0" + score;
  }
  this.boardCanvas.drawText({
    text: score,
    col: 4 - score.length,
    row: 2
  });
};
GameController.prototype.moveActor = function() {
  this.pacCanvas.clearRect(this.pac.getClearDimensions());
  var coords = {
    x: this.pac.x,
    y: this.pac.y
  }

  var newDirection = false;
  for(var prop in this.keyStates) {
    if(this.keyStates.hasOwnProperty(prop) && this.keyStates[prop]) {
      newDirection = prop;
      break;
    }
  }

  var collision;
  if(this.keyStates[this.pac.direction] === false && newDirection) {
    collision = this.gameBoard.predictCollision(coords, newDirection);
    if(collision != "door" && collision != "wall") {
      this.pac.direction = newDirection;
    }
  }

  collision = this.gameBoard.predictCollision(coords, this.pac.direction);
  if(collision == "wall" || collision == "door") {
    clearInterval(this.pacMoveInterval);
    this.pacMoveInterval = false;
  }
  else {
    var coords = this.actorBoard.find("m");

    this.pac.move();
    if(this.pac.x < 0) {
      this.pac.x = BOARD_WIDTH;
    }
    else if(this.pac.x > BOARD_WIDTH) {
      this.pac.x = 0;
    }

    var newCoords = Board.convertToTile({
      x: this.pac.x,
      y: this.pac.y
    });

    this.updateActorBoard({
      coords: coords,
      newCoords: newCoords,
      name: "m",
      actor: "pac"
    });
  }
  this.pac.moveTowardCenter();
  this.updatePellets();

  this.pacCanvas.renderPac(this.pac);
};
GameController.prototype.moveGhost = function(name) {
  var ghost;
  switch(name) {
    case "b": ghost = "blinky"; break;
    case "i": ghost = "inky"; break;
    case "p": ghost = "pinky"; break;
    case "c": ghost = "clyde"; break;
  }
  this[ghost + "Canvas"].clearRect(this[ghost].getClearDimensions());

  switch(this[ghost].movementMode) {
    case "house":
      if(this[ghost].y + 8 >= HOUSE_BOTTOM || this[ghost].y - 5 <= HOUSE_TOP) {
        this[ghost].direction = oppositeDirection(this[ghost].direction);
      }
    break;
    case "exitting":
      this[ghost].exitHouse();
      if(this[ghost].movementMode == "scatter") {
        this.setNextDirection(ghost);
      }
    break;
    case "scatter":
      if(this[ghost].isCentered()) {
        this.setNextDirection(ghost);
      }
    break;
    case "chase":
      var coords = Board.convertToTile({
        x: this.pac.x,
        y: this.pac.y
      });
      var ghostCoords = Board.convertToTile({
        x: this[ghost].x,
        y: this[ghost].y
      });
      var blinkyCoords = Board.convertToTile({
        x: this.blinky.x,
        y: this.blinky.y
      });
      this[ghost].targetTile = Ghost[ghost + "Target"]({
        coords: coords,
        direction: this.pac.direction,
        ghost: ghostCoords,
        blinky: blinkyCoords
      });
      if(this[ghost].isCentered()) {
        this.setNextDirection(ghost);
      }
    break;
  }

  this[ghost].move();
  if(this[ghost].x < 0) {
    this[ghost].x = BOARD_WIDTH;
  }
  else if(this[ghost].x > BOARD_WIDTH) {
    this[ghost].x = 0;
  }
  this[ghost + "Canvas"].renderGhost(this[ghost]);
};
GameController.prototype.updateActorBoard = function(args) {
  if(args.coords.x != args.newCoords.x || args.coords.y != args.newCoords.y) {
    this.actorBoard.setCell({
      x: args.coords.x,
      y: args.coords.y,
      value: " "
    });
    this.actorBoard.setCell({
      x: args.newCoords.x,
      y: args.newCoords.y,
      value: args.name
    });
  }
};
GameController.prototype.handleKeyDown = function(event) {
  var keyPressed = keyCodes[event.keyCode];
  if(keyPressed) {
    event.preventDefault();
    if(this.keyStates[keyPressed] === false) {
      this.keyStates[keyPressed] = true;
      if(this.pacMoveInterval === false) {
        this.pacMoveInterval = setInterval(this.moveActor.bind(this), this.pac.speed);
      }
    }
  }
};
GameController.prototype.handleKeyUp = function(event) {
  var keyPressed = keyCodes[event.keyCode];
  if(keyPressed) {
    event.preventDefault();
    this.keyStates[keyPressed] = false;
  }
};
GameController.prototype.setNextDirection = function(ghost) {
  var currentTile = Board.convertToTile({
    x: this[ghost].x,
    y: this[ghost].y
  });
  var adjacentTiles = this.gameBoard.getAdjacentTiles({
    x: this[ghost].x,
    y: this[ghost].y
  });
  adjacentTiles[oppositeDirection(this[ghost].direction)] = undefined;

  var emptyTiles = this.gameBoard.getEmptyTiles(adjacentTiles);
  var nextTile = this.gameBoard.getClosestTile({
    tiles: emptyTiles,
    target: this[ghost].targetTile
  });

  if(nextTile) {
    if(nextTile.x < currentTile.x) {
      this[ghost].direction = "left";
    }
    else if(nextTile.x > currentTile.x) {
      this[ghost].direction = "right";
    }
    else if(nextTile.y < currentTile.y) {
      this[ghost].direction = "up";
    }
    else if(nextTile.y > currentTile.y) {
      this[ghost].direction = "down";
    }
  }
};
GameController.prototype.updatePellets = function() {
  var coords = Board.convertToTile({
    x: this.pac.x,
    y: this.pac.y
  });
  var tile = this.gameBoard.getCell(coords);

  if(tile == "." || tile == "o") {
    this.gameBoard.setCell({
      x: coords.x,
      y: coords.y,
      value: " "
    });
    this.pelletCount++;
    if(this.inky.movementMode == "house") {
      this.inky.handlePelletCount(this.pelletCount);
    }
    if(this.clyde.movementMode == "house") {
      this.clyde.handlePelletCount(this.pelletCount);
    }
    this.drawPellets();

    var score = this.pelletCount.toString();
    if(score.length == 1) {
      score = "0" + score;
    }
    this.boardCanvas.drawText({
      text: score,
      col: 4 - score.length,
      row: 2
    });
    drawBorders(this.boardCanvas.context);
  }
};
<commit_msg>Add lives prop to GameController<commit_after>var GameController = function(args) {
  this.pelletCount = 0;
  this.lives = 2;
  this.keyStates = {
    up: false,
    down: false,
    left: false,
    right: false
  }
  this.pacMoveInterval = false;

  this.pacCanvas = args.pacCanvas;
  this.blinkyCanvas = args.blinkyCanvas;
  this.inkyCanvas = args.inkyCanvas;
  this.pinkyCanvas = args.pinkyCanvas;
  this.clydeCanvas = args.clydeCanvas;
  this.boardCanvas = args.boardCanvas;
  this.pelletCanvas = args.pelletCanvas;

  this.pac = new Actor(ACTOR_ARGS.pac);
  this.blinky = new Ghost(ACTOR_ARGS.blinky);
  this.inky = new Ghost(ACTOR_ARGS.inky);
  this.pinky = new Ghost(ACTOR_ARGS.pinky);
  this.clyde = new Ghost(ACTOR_ARGS.clyde);

  this.gameBoard = args.gameBoard;
  this.actorBoard = args.actorBoard;

  this.drawPellets();
  drawBorders(this.boardCanvas.context);

  this.pacCanvas.renderPac(this.pac);

  addEventListener("keydown", this.handleKeyDown.bind(this));
  addEventListener("keyup", this.handleKeyUp.bind(this));

  setInterval(function() {
    this.moveGhost("b");
    this.moveGhost("i");
    this.moveGhost("p");
    this.moveGhost("c");
  }.bind(this), GHOST_MOVE_DELAY);
}
GameController.prototype.drawPellets = function() {
  this.pelletCanvas.clearRect({
    x: 0,
    y: 0,
    w: BOARD_WIDTH,
    h: BOARD_HEIGHT
  });
  this.gameBoard.board.matrix.forEach(function(row, rIndex) {
    row.forEach(function(col, cIndex) {
      if(col == ".") {
        this.pelletCanvas.drawRect({
          color: PELLET_COLOR,
          x: (8 * cIndex) + 3,
          y: (8 * rIndex) + 27,
          w: 2,
          h: 2
        });
      }
      else if(col == "o") {
        this.pelletCanvas.drawCircle({
          x: (8 * cIndex) + 4,
          y: (8 * rIndex) + 28,
          rad: 4
        });
      }
      else if(col == "-") {
        this.pelletCanvas.drawRect({
          color: PELLET_COLOR,
          x: 8 * cIndex,
          y: (8 * rIndex) + 29,
          w: 8,
          h: 2
        });
      }
    }.bind(this));
  }.bind(this));

  var score = this.pelletCount.toString();
  if(score.length == 1) {
    score = "0" + score;
  }
  this.boardCanvas.drawText({
    text: score,
    col: 4 - score.length,
    row: 2
  });
};
GameController.prototype.moveActor = function() {
  this.pacCanvas.clearRect(this.pac.getClearDimensions());
  var coords = {
    x: this.pac.x,
    y: this.pac.y
  }

  var newDirection = false;
  for(var prop in this.keyStates) {
    if(this.keyStates.hasOwnProperty(prop) && this.keyStates[prop]) {
      newDirection = prop;
      break;
    }
  }

  var collision;
  if(this.keyStates[this.pac.direction] === false && newDirection) {
    collision = this.gameBoard.predictCollision(coords, newDirection);
    if(collision != "door" && collision != "wall") {
      this.pac.direction = newDirection;
    }
  }

  collision = this.gameBoard.predictCollision(coords, this.pac.direction);
  if(collision == "wall" || collision == "door") {
    clearInterval(this.pacMoveInterval);
    this.pacMoveInterval = false;
  }
  else {
    var coords = this.actorBoard.find("m");

    this.pac.move();
    if(this.pac.x < 0) {
      this.pac.x = BOARD_WIDTH;
    }
    else if(this.pac.x > BOARD_WIDTH) {
      this.pac.x = 0;
    }

    var newCoords = Board.convertToTile({
      x: this.pac.x,
      y: this.pac.y
    });

    this.updateActorBoard({
      coords: coords,
      newCoords: newCoords,
      name: "m",
      actor: "pac"
    });
  }
  this.pac.moveTowardCenter();
  this.updatePellets();

  this.pacCanvas.renderPac(this.pac);
};
GameController.prototype.moveGhost = function(name) {
  var ghost;
  switch(name) {
    case "b": ghost = "blinky"; break;
    case "i": ghost = "inky"; break;
    case "p": ghost = "pinky"; break;
    case "c": ghost = "clyde"; break;
  }
  this[ghost + "Canvas"].clearRect(this[ghost].getClearDimensions());

  switch(this[ghost].movementMode) {
    case "house":
      if(this[ghost].y + 8 >= HOUSE_BOTTOM || this[ghost].y - 5 <= HOUSE_TOP) {
        this[ghost].direction = oppositeDirection(this[ghost].direction);
      }
    break;
    case "exitting":
      this[ghost].exitHouse();
      if(this[ghost].movementMode == "scatter") {
        this.setNextDirection(ghost);
      }
    break;
    case "scatter":
      if(this[ghost].isCentered()) {
        this.setNextDirection(ghost);
      }
    break;
    case "chase":
      var coords = Board.convertToTile({
        x: this.pac.x,
        y: this.pac.y
      });
      var ghostCoords = Board.convertToTile({
        x: this[ghost].x,
        y: this[ghost].y
      });
      var blinkyCoords = Board.convertToTile({
        x: this.blinky.x,
        y: this.blinky.y
      });
      this[ghost].targetTile = Ghost[ghost + "Target"]({
        coords: coords,
        direction: this.pac.direction,
        ghost: ghostCoords,
        blinky: blinkyCoords
      });
      if(this[ghost].isCentered()) {
        this.setNextDirection(ghost);
      }
    break;
  }

  this[ghost].move();
  if(this[ghost].x < 0) {
    this[ghost].x = BOARD_WIDTH;
  }
  else if(this[ghost].x > BOARD_WIDTH) {
    this[ghost].x = 0;
  }
  this[ghost + "Canvas"].renderGhost(this[ghost]);
};
GameController.prototype.updateActorBoard = function(args) {
  if(args.coords.x != args.newCoords.x || args.coords.y != args.newCoords.y) {
    this.actorBoard.setCell({
      x: args.coords.x,
      y: args.coords.y,
      value: " "
    });
    this.actorBoard.setCell({
      x: args.newCoords.x,
      y: args.newCoords.y,
      value: args.name
    });
  }
};
GameController.prototype.handleKeyDown = function(event) {
  var keyPressed = keyCodes[event.keyCode];
  if(keyPressed) {
    event.preventDefault();
    if(this.keyStates[keyPressed] === false) {
      this.keyStates[keyPressed] = true;
      if(this.pacMoveInterval === false) {
        this.pacMoveInterval = setInterval(this.moveActor.bind(this), this.pac.speed);
      }
    }
  }
};
GameController.prototype.handleKeyUp = function(event) {
  var keyPressed = keyCodes[event.keyCode];
  if(keyPressed) {
    event.preventDefault();
    this.keyStates[keyPressed] = false;
  }
};
GameController.prototype.setNextDirection = function(ghost) {
  var currentTile = Board.convertToTile({
    x: this[ghost].x,
    y: this[ghost].y
  });
  var adjacentTiles = this.gameBoard.getAdjacentTiles({
    x: this[ghost].x,
    y: this[ghost].y
  });
  adjacentTiles[oppositeDirection(this[ghost].direction)] = undefined;

  var emptyTiles = this.gameBoard.getEmptyTiles(adjacentTiles);
  var nextTile = this.gameBoard.getClosestTile({
    tiles: emptyTiles,
    target: this[ghost].targetTile
  });

  if(nextTile) {
    if(nextTile.x < currentTile.x) {
      this[ghost].direction = "left";
    }
    else if(nextTile.x > currentTile.x) {
      this[ghost].direction = "right";
    }
    else if(nextTile.y < currentTile.y) {
      this[ghost].direction = "up";
    }
    else if(nextTile.y > currentTile.y) {
      this[ghost].direction = "down";
    }
  }
};
GameController.prototype.updatePellets = function() {
  var coords = Board.convertToTile({
    x: this.pac.x,
    y: this.pac.y
  });
  var tile = this.gameBoard.getCell(coords);

  if(tile == "." || tile == "o") {
    this.gameBoard.setCell({
      x: coords.x,
      y: coords.y,
      value: " "
    });
    this.pelletCount++;
    if(this.inky.movementMode == "house") {
      this.inky.handlePelletCount(this.pelletCount);
    }
    if(this.clyde.movementMode == "house") {
      this.clyde.handlePelletCount(this.pelletCount);
    }
    this.drawPellets();

    var score = this.pelletCount.toString();
    if(score.length == 1) {
      score = "0" + score;
    }
    this.boardCanvas.drawText({
      text: score,
      col: 4 - score.length,
      row: 2
    });
    drawBorders(this.boardCanvas.context);
  }
};
<|endoftext|>


<commit_before>var cp = require('child_process');
var path = require('path');
var fs = require('fs');
var zipper = require('zip-local');
var browserify = require('browserify');
var router = require('./router.js');

/*
 * packs the app into a zip file
 * @param job {Object}: the job specs
 * @return {Promise}: of the app descriptor {pckg, id}
 */
function pack(job) {
    return new Promise(function(resolve, reject) {

        browserify(job.app, {
            builtins: false,
            browserField: false,
            insertGlobalVars: {
                'process': undefined
            }
        })
        .external('fibers')
        .bundle(function (err, buffer) {
            if(err) {
                return reject(err);
            }

            var app_id = Date.now().toString();

            zipper.zip(buffer, "app_" + app_id + ".js", function(err, zipped) {
                if(err) {
                    return reject(err);
                }

                var packed_buff = zipped.compress().memory();
                resolve({
                    id: app_id,
                    pckg: packed_buff.toString('base64')
                });
            });
        });
    });
}

/*
 * unpacks a packed app from remote root
 * @param app {Object}: the app descriptor recived from remote root
 */
 function unpack(app) {
     return new Promise(function(resolve, reject) {
         // check if the unpaking directory exists
         var unpacks_dir = __dirname + '/../.unpacks/';
         fs.stat(unpacks_dir, function(err, stats) {
             if(err) {
                 try {
                    fs.mkdirSync(unpacks_dir);
                 }
                 catch(err) { return reject(err); }
             }

             var data = new Buffer(app.pckg, 'base64');

             zipper.unzip(data, function(err, unzipped) {
                 if(err) {
                     return reject(err);
                 }

                 unzipped.save(unpacks_dir, function(err) {
                     if(err) {
                         return reject(err);
                     }

                     resolve(unpacks_dir + "app_" + app.id + ".js");
                 });
             });
         });
     });
 }

 /*
  * divides the job processes over the specified hosts using round-robin divison
  * @param job {Object}: the job specs
  * @return {Object}: a job distribution plan
 */
 function divide(job) {

     var hosts = {};

     for(var host in job.hosts) {
         hosts[host] = {count: 0, max: job.hosts[host].max_procs}
     }

     // round-robin over the hosts and allocated processes numbers
     var hosts_list = Object.keys(hosts);
     var allocated = 0;
     var next = 0;
     var counter = 0;
     var overallocate = false;  // if true: hosts will be overallocated with processes to meet job.size
     while(allocated < job.size) {
         var host = hosts[hosts_list[next++ % hosts_list.length]];
         if(host.count != host.max || overallocate) {
             host.count++;
             allocated++;
             if(!overallocate) {
                 // if not in overallocate mode already, reset the counter to indicate allocation
                 counter = 0;
             }
         }
         else {
             counter++;
             // set the overallocate to true if gone through the list without allocation
             overallocate = (counter === hosts_list.length);
         }
     }

     var start_index = 0;
     // register the 0 index process to the local host if exists
     if(!!hosts["local"]) {
         hosts.local.start = 0;
         start_index += hosts.local.count;
     }
     // assign the rest of indecies to the rest of hosts
     for(var host in hosts) {
         if(host !== "local") {
             hosts[host].start = start_index;
            start_index += hosts[host].count;
        }
        delete hosts[host]["max"];
     }

     return hosts;
 }

/*
 * runs the given subjob on the local machine
 * @param subjob {Object}: subjob description
 */
function runLocally(subjob) {

    for(var i = 0; i < subjob.subsize; i++) {

        var rank = subjob.start + i;
        var jobInstance = cp.spawn('node', [subjob.app, subjob.size, rank], {
            stdio: [null, null, null, 'ipc']
        });

        // register a handler for instance's stdout data
        // reports back to the parent klyng process
        jobInstance.stdout.on('data', function(log) {
            log = log.toString().replace('\n', '');
            router.routeToParent({type: "process:stdout", data: {line: log}});
        });

        // register a handler for instance's stderr data
        // reports back to the parent klyng process
        jobInstance.stderr.on('data', function(elog) {
            elog = elog.toString().replace('\n', '');
            router.routeToParent({type: "process:stderr", data: {line: elog}});
        })

        // register a handler for instance exit event
        // reports back to the parent klyng process
        jobInstance.on('exit', function(code) {
            router.routeToParent({type: "process:exit", data: {code: code}});
        });

        // register a handler for instance's messages
        jobInstance.on('message', function(msg) {
            if(msg.type === 'klyng:msg') {
                router.routeTo(msg.header.to, msg);
            }
        });

        jobInstance.unref();

        router.setLocalChannel(rank, jobInstance);
    }
};

module.exports = {
    pack: pack,
    unpack: unpack,
    divide,
    runLocally: runLocally
};
<commit_msg>reported io stream data on line<commit_after>var cp = require('child_process');
var path = require('path');
var fs = require('fs');
var readline = require('readline');
var zipper = require('zip-local');
var browserify = require('browserify');
var router = require('./router.js');

/*
 * packs the app into a zip file
 * @param job {Object}: the job specs
 * @return {Promise}: of the app descriptor {pckg, id}
 */
function pack(job) {
    return new Promise(function(resolve, reject) {

        browserify(job.app, {
            builtins: false,
            browserField: false,
            insertGlobalVars: {
                'process': undefined
            }
        })
        .external('fibers')
        .bundle(function (err, buffer) {
            if(err) {
                return reject(err);
            }

            var app_id = Date.now().toString();

            zipper.zip(buffer, "app_" + app_id + ".js", function(err, zipped) {
                if(err) {
                    return reject(err);
                }

                var packed_buff = zipped.compress().memory();
                resolve({
                    id: app_id,
                    pckg: packed_buff.toString('base64')
                });
            });
        });
    });
}

/*
 * unpacks a packed app from remote root
 * @param app {Object}: the app descriptor recived from remote root
 */
 function unpack(app) {
     return new Promise(function(resolve, reject) {
         // check if the unpaking directory exists
         var unpacks_dir = __dirname + '/../.unpacks/';
         fs.stat(unpacks_dir, function(err, stats) {
             if(err) {
                 try {
                    fs.mkdirSync(unpacks_dir);
                 }
                 catch(err) { return reject(err); }
             }

             var data = new Buffer(app.pckg, 'base64');

             zipper.unzip(data, function(err, unzipped) {
                 if(err) {
                     return reject(err);
                 }

                 unzipped.save(unpacks_dir, function(err) {
                     if(err) {
                         return reject(err);
                     }

                     resolve(unpacks_dir + "app_" + app.id + ".js");
                 });
             });
         });
     });
 }

 /*
  * divides the job processes over the specified hosts using round-robin divison
  * @param job {Object}: the job specs
  * @return {Object}: a job distribution plan
 */
 function divide(job) {

     var hosts = {};

     for(var host in job.hosts) {
         hosts[host] = {count: 0, max: job.hosts[host].max_procs}
     }

     // round-robin over the hosts and allocated processes numbers
     var hosts_list = Object.keys(hosts);
     var allocated = 0;
     var next = 0;
     var counter = 0;
     var overallocate = false;  // if true: hosts will be overallocated with processes to meet job.size
     while(allocated < job.size) {
         var host = hosts[hosts_list[next++ % hosts_list.length]];
         if(host.count != host.max || overallocate) {
             host.count++;
             allocated++;
             if(!overallocate) {
                 // if not in overallocate mode already, reset the counter to indicate allocation
                 counter = 0;
             }
         }
         else {
             counter++;
             // set the overallocate to true if gone through the list without allocation
             overallocate = (counter === hosts_list.length);
         }
     }

     var start_index = 0;
     // register the 0 index process to the local host if exists
     if(!!hosts["local"]) {
         hosts.local.start = 0;
         start_index += hosts.local.count;
     }
     // assign the rest of indecies to the rest of hosts
     for(var host in hosts) {
         if(host !== "local") {
             hosts[host].start = start_index;
            start_index += hosts[host].count;
        }
        delete hosts[host]["max"];
     }

     return hosts;
 }

/*
 * runs the given subjob on the local machine
 * @param subjob {Object}: subjob description
 */
function runLocally(subjob) {

    for(var i = 0; i < subjob.subsize; i++) {

        var rank = subjob.start + i;
        var jobInstance = cp.spawn('node', [subjob.app, subjob.size, rank], {
            stdio: [null, null, null, 'ipc']
        });

        var stdoutRlInterface = readline.createInterface({input: jobInstance.stdout});
        var stderrRlInterface = readline.createInterface({input: jobInstance.stderr});

        // register a handler for instance's stdout data
        // reports back to the parent klyng process
        stdoutRlInterface.on('line', function(log) {
            router.routeToParent({type: "process:stdout", data: {line: log}});
        });

        // register a handler for instance's stderr data
        // reports back to the parent klyng process
        stderrRlInterface.on('line', function(elog) {
            router.routeToParent({type: "process:stderr", data: {line: elog}});
        })

        // register a handler for instance exit event
        // reports back to the parent klyng process
        jobInstance.on('exit', function(code) {
            router.routeToParent({type: "process:exit", data: {code: code}});
        });

        // register a handler for instance's messages
        jobInstance.on('message', function(msg) {
            if(msg.type === 'klyng:msg') {
                router.routeTo(msg.header.to, msg);
            }
        });

        jobInstance.unref();

        router.setLocalChannel(rank, jobInstance);
    }
};

module.exports = {
    pack: pack,
    unpack: unpack,
    divide,
    runLocally: runLocally
};
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

requirejs.config({
  baseUrl: "/vendor/",
  paths: {
    "inflector": "inflection-js/inflection.min",
    "jquery": "jquery/jquery.min",
    "ceci": "ceci/ceci",
    "ceci-ui": "ceci/ceci-ui",
    "ceci-cards": "ceci/ceci-cards",
    "ceci-app": "ceci/ceci-app",
    "ceci-utils": "ceci/ceci-utils",
    "jquery-ui": "jquery-ui/ui/minified/jquery-ui.min",
    "designer-keyboard": "/javascripts/designer-keyboard",
    "angular": "angular/angular.min"
  },
  shim: {
    "jquery-ui": {
      exports: "$",
      deps: ['jquery']
    },
    "togetherjs": {
      exports: "TogetherJS"
    }
  }
});

requirejs(["/javascripts/application.js"]);
requirejs(["/javascripts/togetherjsSupport.js"]);
<commit_msg>Formatting in requireConfig<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

requirejs.config({
  baseUrl: "/vendor/",
  paths: {
    "inflector": "inflection-js/inflection.min",

    "jquery": "jquery/jquery.min",

    "ceci": "ceci/ceci",
    "ceci-ui": "ceci/ceci-ui",
    "ceci-cards": "ceci/ceci-cards",
    "ceci-app": "ceci/ceci-app",
    "ceci-utils": "ceci/ceci-utils",

    "jquery-ui": "jquery-ui/ui/minified/jquery-ui.min",

    "designer-keyboard": "/javascripts/designer-keyboard",
    "angular": "angular/angular.min"
  },
  shim: {
    "jquery-ui": {
      exports: "$",
      deps: ['jquery']
    },
    "togetherjs": {
      exports: "TogetherJS"
    }
  }
});

requirejs(["/javascripts/application.js"]);
requirejs(["/javascripts/togetherjsSupport.js"]);
<|endoftext|>


<commit_before>define([
	'jQuery-2.1.4.min',
	'underscore_1.3.3',
	'backbone_0.9.2',
  'bootstrap.min',
	'../../js/app/views/leftMenuView',
  '../../js/app/views/dashboardView',
  '../../js/app/views/pagesView',
  '../../js/app/views/postsView',
  '../../js/app/views/imageLibraryView',
  '../../js/app/views/imageAddNewView',
  '../../js/app/views/pagesAddNewView',
  '../../js/app/views/postsAddNewView',
  '../../js/app/views/fileLibraryView',
  '../../js/app/model/ImageUploadModel',
  '../../js/app/model/ImageUploadCollection',
  '../../js/app/model/PostModel',
  '../../js/app/model/PostCollection',
  '../../js/app/model/PostCategoryModel',
  '../../js/app/model/PostCategoryCollection',
  '../../js/app/model/FileUploadModel',
  '../../js/app/model/FileUploadCollection',
  '../../js/app/views/categoriesView',
  '../../js/app/model/PageModel',
  '../../js/app/model/PageCollection',
  '../../js/app/model/PageSectionModel',
  '../../js/app/model/PageSectionCollection',
  '../../js/app/views/sectionsView',
  'adminlte',
  'logs'
], function ($, _, Backbone, Bootstrap, LeftMenuView, DashboardView, PagesView, PostsView, ImageLibraryView, ImageAddNewView,
              PagesAddNewView, PostsAddNewView, FileLibraryView, ImageUploadModel, ImageUploadCollection, PostModel, PostsCollection,
              PostCategoryModel, PostCategoryCollection, FileUploadModel, FileUploadCollection, CategoriesView,
              PageModel, PagesCollection, PageSectionModel, PageSectionCollection, SectionsView,
              AdminLTE, Logs) {

  /*
  TO-DO:
  -tree-view menu on left menu bar isn't working exactly the way I want it to. When you click the Media drop-down, it opens,
  but when you click off of it, it doesn't necessaryily close. It should close when another link is clicked.

  */

  //Global Variables
  global = new Object(); //This is where all global variables will be stored.
  global.serverIp = "107.170.244.232";
  global.serverPort = "3000";
  var csrftoken = ""; //Will host the CSRF token for POST calls.

  //TinyMCE state.
  global.tinymce = new Object();
  global.tinymce.initialized = false;
  global.tinymce.currentModelIndex = null;
  global.tinymce.selectedImage = null;

  //debugger;

  detectBrowser(); //Log the current browser and OS being used.

  global.leftMenuView = new LeftMenuView();
  global.leftMenuView.render();

  //Initialize the dashboard
  global.dashboardView = new DashboardView();
  //debugger;
  global.dashboardView.render();

  global.pagesView = new PagesView();
  global.postsView = new PostsView();
  //pagesView.render();

  global.imageLibraryView = new ImageLibraryView();
  //imageLibraryView.render();

  global.imageAddNewView = new ImageAddNewView();

  global.pagesAddNewView = new PagesAddNewView();
  global.postsAddNewView = new PostsAddNewView();

  global.fileLibraryView = new FileLibraryView();

  global.categoriesView = new CategoriesView();

  //Generate the ImageUpload Collection if it hasn't been created yet.
  if(global.imageUploadCollection == undefined) {
    //debugger;
    global.imageUploadCollection = new ImageUploadCollection(); //Collection Instance
    global.imageUploadCollection.fetch();
  }

  //POST MODEL AND COLLECTION
  //Generate the Post Collection if it hasn't been created yet.
  if(global.postsCollection == undefined) {

    //Do I need this? CT 3-31-16
    global.postModel = new PostModel();

    global.postsCollection = new PostsCollection(); //Collection Instance
    global.postsCollection.fetch();
  }

  //POST CATEGORY MODEL AND COLLECTION
  //Generate the PostCategory Collection if it hasn't been created yet.
  if(global.postCategoryCollection == undefined) {
    //debugger;

    //Do I need this? CT 3-31-16
    global.postCategoryModel = new PostCategoryModel();

    global.postCategoryCollection = new PostCategoryCollection(); //Collection Instance
    global.postCategoryCollection.fetch();
  }

  //FILE UPLOAD MODEL AND COLLECTION
  if(global.fileUploadCollection == undefined) {
    //debugger;
    global.fileUploadCollection = new FileUploadCollection(); //Collection Instance
    global.fileUploadCollection.fetch();
  }

  //PAGE MODEL AND COLLECITON
  //Generate the Post Collection if it hasn't been created yet.
  if(global.pagesCollection == undefined) {

    //Do I need this? CT 3-31-16
    global.pageModel = new PageModel();

    global.pagesCollection = new PagesCollection(); //Collection Instance
    global.pagesCollection.fetch();
  }

  //PAGE SECTION MODEL AND COLLECTION
  //Generate the PageSection Collection if it hasn't been created yet.
  if(global.pageSectionCollection == undefined) {
    //debugger;

    //Do I need this? CT 3-31-16
    global.pageSectionModel = new PageSectionModel();

    global.pageSectionCollection = new PageSectionCollection(); //Collection Instance
    global.pageSectionCollection.fetch();
  }

  /*** BEGIN TESTING CODE ***/
  //debugger;

  /*** END TESTING CODE ***/

  log.push('Finished executing main_dashboard_app.js');

  /*** BEGIN GLOBAL FUNCTIONS ***/

  /*** END GLOBAL FUNCTIONS ***/
});
<commit_msg>adding and debugging Sections View.<commit_after>define([
	'jQuery-2.1.4.min',
	'underscore_1.3.3',
	'backbone_0.9.2',
  'bootstrap.min',
	'../../js/app/views/leftMenuView',
  '../../js/app/views/dashboardView',
  '../../js/app/views/pagesView',
  '../../js/app/views/postsView',
  '../../js/app/views/imageLibraryView',
  '../../js/app/views/imageAddNewView',
  '../../js/app/views/pagesAddNewView',
  '../../js/app/views/postsAddNewView',
  '../../js/app/views/fileLibraryView',
  '../../js/app/model/ImageUploadModel',
  '../../js/app/model/ImageUploadCollection',
  '../../js/app/model/PostModel',
  '../../js/app/model/PostCollection',
  '../../js/app/model/PostCategoryModel',
  '../../js/app/model/PostCategoryCollection',
  '../../js/app/model/FileUploadModel',
  '../../js/app/model/FileUploadCollection',
  '../../js/app/views/categoriesView',
  '../../js/app/model/PageModel',
  '../../js/app/model/PageCollection',
  '../../js/app/model/PageSectionModel',
  '../../js/app/model/PageSectionCollection',
  '../../js/app/views/sectionsView',
  'adminlte',
  'logs'
], function ($, _, Backbone, Bootstrap, LeftMenuView, DashboardView, PagesView, PostsView, ImageLibraryView, ImageAddNewView,
              PagesAddNewView, PostsAddNewView, FileLibraryView, ImageUploadModel, ImageUploadCollection, PostModel, PostsCollection,
              PostCategoryModel, PostCategoryCollection, FileUploadModel, FileUploadCollection, CategoriesView,
              PageModel, PagesCollection, PageSectionModel, PageSectionCollection, SectionsView,
              AdminLTE, Logs) {

  /*
  TO-DO:
  -tree-view menu on left menu bar isn't working exactly the way I want it to. When you click the Media drop-down, it opens,
  but when you click off of it, it doesn't necessaryily close. It should close when another link is clicked.

  */

  //Global Variables
  global = new Object(); //This is where all global variables will be stored.
  global.serverIp = "107.170.244.232";
  global.serverPort = "3000";
  var csrftoken = ""; //Will host the CSRF token for POST calls.

  //TinyMCE state.
  global.tinymce = new Object();
  global.tinymce.initialized = false;
  global.tinymce.currentModelIndex = null;
  global.tinymce.selectedImage = null;

  //debugger;

  detectBrowser(); //Log the current browser and OS being used.

  global.leftMenuView = new LeftMenuView();
  global.leftMenuView.render();

  //Initialize the dashboard
  global.dashboardView = new DashboardView();
  //debugger;
  global.dashboardView.render();

  global.pagesView = new PagesView();
  global.postsView = new PostsView();
  //pagesView.render();

  global.imageLibraryView = new ImageLibraryView();
  //imageLibraryView.render();

  global.imageAddNewView = new ImageAddNewView();

  global.pagesAddNewView = new PagesAddNewView();
  global.postsAddNewView = new PostsAddNewView();

  global.fileLibraryView = new FileLibraryView();

  global.categoriesView = new CategoriesView();
  global.sectionsView = new SectionsView();

  //Generate the ImageUpload Collection if it hasn't been created yet.
  if(global.imageUploadCollection == undefined) {
    //debugger;
    global.imageUploadCollection = new ImageUploadCollection(); //Collection Instance
    global.imageUploadCollection.fetch();
  }

  //POST MODEL AND COLLECTION
  //Generate the Post Collection if it hasn't been created yet.
  if(global.postsCollection == undefined) {

    //Do I need this? CT 3-31-16
    global.postModel = new PostModel();

    global.postsCollection = new PostsCollection(); //Collection Instance
    global.postsCollection.fetch();
  }

  //POST CATEGORY MODEL AND COLLECTION
  //Generate the PostCategory Collection if it hasn't been created yet.
  if(global.postCategoryCollection == undefined) {
    //debugger;

    //Do I need this? CT 3-31-16
    global.postCategoryModel = new PostCategoryModel();

    global.postCategoryCollection = new PostCategoryCollection(); //Collection Instance
    global.postCategoryCollection.fetch();
  }

  //FILE UPLOAD MODEL AND COLLECTION
  if(global.fileUploadCollection == undefined) {
    //debugger;
    global.fileUploadCollection = new FileUploadCollection(); //Collection Instance
    global.fileUploadCollection.fetch();
  }

  //PAGE MODEL AND COLLECITON
  //Generate the Post Collection if it hasn't been created yet.
  if(global.pagesCollection == undefined) {

    //Do I need this? CT 3-31-16
    global.pageModel = new PageModel();

    global.pagesCollection = new PagesCollection(); //Collection Instance
    global.pagesCollection.fetch();
  }

  //PAGE SECTION MODEL AND COLLECTION
  //Generate the PageSection Collection if it hasn't been created yet.
  if(global.pageSectionCollection == undefined) {
    //debugger;

    //Do I need this? CT 3-31-16
    global.pageSectionModel = new PageSectionModel();

    global.pageSectionCollection = new PageSectionCollection(); //Collection Instance
    global.pageSectionCollection.fetch();
  }

  /*** BEGIN TESTING CODE ***/
  //debugger;

  /*** END TESTING CODE ***/

  log.push('Finished executing main_dashboard_app.js');

  /*** BEGIN GLOBAL FUNCTIONS ***/

  /*** END GLOBAL FUNCTIONS ***/
});
<|endoftext|>