<commit_before>/**
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you 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.
 */

/*
 * NOTE!
 * If you remove/rename a plugin from these lists, add the old value to the STALE_PLUGINS list at the end.
 * That way, it will be automatically removed on prepare.
 * */

var DEFAULT_PLUGINS = [
    'org.apache.cordova.file',
    'org.apache.cordova.inappbrowser',
    'org.apache.cordova.network-information',
    'org.apache.cordova.statusbar',
    'org.apache.cordova.labs.keyboard',
    'org.chromium.common',
    'org.chromium.runtime',
    'org.chromium.storage',
    'org.chromium.navigation',
    'org.chromium.bootstrap',
    'org.chromium.i18n',
    'org.chromium.polyfill.customevent',
    'org.chromium.polyfill.xhr_features',
    'org.chromium.polyfill.blob_constructor',
];

var PLUGIN_MAP = {
  'alarms': ['org.chromium.alarms', 'org.chromium.storage'],
  'audioCapture': ['org.chromium.audiocapture'],
  'background': [],
  'fileSystem': ['org.chromium.filesystem', 'org.chromium.filechooser'],
  'fullscreen': [],
  'gcm': ['org.chromium.gcm', 'org.chromium.storage'],
  'geolocation': ['org.apache.cordova.geolocation'],
  'identity': ['org.chromium.identity'],
  'idle': ['org.chromium.idle'],
  'notifications': ['org.chromium.notifications', 'org.chromium.storage'],
  'payments': ['com.google.payments'],
  'power': ['org.chromium.power'],
  'pushMessaging': ['org.chromium.pushmessaging', 'org.chromium.identity'],
  'socket': ['org.chromium.socket'],
  'storage': ['org.chromium.storage'],
  'syncFileSystem': ['org.chromium.syncfilesystem', 'org.chromium.storage', 'org.chromium.identity'],
  'system.cpu': ['org.chromium.system.cpu'],
  'system.display': ['org.chromium.system.display'],
  'system.memory': ['org.chromium.system.memory'],
  'system.network': ['org.chromium.system.network'],
  'system.storage': ['org.chromium.system.storage'],
  'unlimitedStorage': [],
  'videoCapture': ['org.chromium.videocapture'],
};

var STALE_PLUGINS = [];

var ENGINE_MAP = {
  'crosswalk': ['org.apache.cordova.engine.crosswalk'],
  'system': []
};

function mapPermissionsToPlugins(knownPermissionsMap, requestedPermissionsList) {
  // We have to create three lists:
  // 1. Permissions your app has requested and we know about (install these plugins)
  // 2. Permissions your app has requested and we do not know about (warn about these)
  // 3. Permissions your app has not requested (uninstall these plugins)
  var ret = {
    toInstall: [],
    toUninstall: [],
    unknown: [],
  };

  var knownPermissionsList = Object.keys(knownPermissionsMap);
  requestedPermissionsList = requestedPermissionsList.slice(); // deep copy so we can modify in-place

  requestedPermissionsList.forEach(function(requestedPermission) {
    // Is this permission known?
    var idx = knownPermissionsList.indexOf(requestedPermission);
    if (idx != -1) {
      ret.toInstall = ret.toInstall.concat(knownPermissionsMap[requestedPermission]);
      // Remove from the list of known permissions, so that at the end of this we have all known permissions that arent requested
      knownPermissionsList.splice(idx,1);
    } else {
      ret.unknown.push(requestedPermission);
    }
  });
  // Uninstall whatever is left, since it was not requested
  knownPermissionsList.forEach(function(permission) {
    ret.toUninstall = ret.toUninstall.concat(knownPermissionsMap[permission]);
  });
  // Final step, bit of a hack, remove duplicate plugins from toUninstall list that exist in toInstall
  // e.g. syncFS depends on identity.  So, even if identity isn't in your manifest, don't uninstal it if you have syncFS
  // The way we handle this is to add org.chromium.identity to the list of plugins to install for the syncFS permission
  // so, the last thing to do is subtract the plugins to install from the plugins to not install, since there can be overlap.
  ret.toUninstall = ret.toUninstall.filter(function(plugin) {
    return ret.toInstall.indexOf(plugin) == -1;
  });

  return ret;
}

module.exports = function analyseManifest(manifest, options) {
  options = options || {};
  var ret = {
    appId: undefined,
    whitelist: [],
    permissions: [],
    pluginsToBeInstalled: [],
    pluginsToBeNotInstalled: [],
    pluginsNotRecognized: [],
  };

  (manifest.permissions || []).forEach(function(permission) {
    if (typeof permission === "object") {
      ret.permissions = ret.permissions.concat(Object.keys(permission));
    } else if (permission === "<all_urls>") {
      ret.whitelist.push("*");
    } else {
      var matchPatternParts = /([^:]+:\/\/[^\/]+)(\/.*)$/.exec(permission);
      if (matchPatternParts) {
        // Disregard paths in host permissions: path is required, but
        // <scheme>://<host>/<any path> should translate to <scheme>://<host>/*
        ret.whitelist.push(matchPatternParts[1] + "/*");
      } else {
        ret.permissions.push(permission);
      }
    }
  });

  var pluginsForPermissions = mapPermissionsToPlugins(PLUGIN_MAP, ret.permissions);
  var pluginsForEngines = mapPermissionsToPlugins(ENGINE_MAP, [options.webview || manifest.webview || "crosswalk"]);

  ret.pluginsToBeInstalled = pluginsForPermissions.toInstall.concat(pluginsForEngines.toInstall).concat(DEFAULT_PLUGINS);
  ret.pluginsToBeNotInstalled = pluginsForPermissions.toUninstall.concat(pluginsForEngines.toUninstall).concat(STALE_PLUGINS);
  ret.pluginsNotRecognized = pluginsForPermissions.unknown;

  // This should happen rarely
  pluginsForEngines.unknown.forEach(function(unknownEngine) {
    console.warn('Engine not supported by cca: ' + unknownEngine + ' (skipping)');
  });

  if (manifest.key) {
    ret.appId = require('./chrome-app-key-to-id')(manifest.key);
  } else {
    ret.appId = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
  }

  return ret;
};
<commit_msg>Adding support to auto-install chrome.socket.udp plugin<commit_after>/**
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you 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.
 */

/*
 * NOTE!
 * If you remove/rename a plugin from these lists, add the old value to the STALE_PLUGINS list at the end.
 * That way, it will be automatically removed on prepare.
 * */

var DEFAULT_PLUGINS = [
    'org.apache.cordova.file',
    'org.apache.cordova.inappbrowser',
    'org.apache.cordova.network-information',
    'org.apache.cordova.statusbar',
    'org.apache.cordova.labs.keyboard',
    'org.chromium.common',
    'org.chromium.runtime',
    'org.chromium.storage',
    'org.chromium.navigation',
    'org.chromium.bootstrap',
    'org.chromium.i18n',
    'org.chromium.polyfill.customevent',
    'org.chromium.polyfill.xhr_features',
    'org.chromium.polyfill.blob_constructor',
];

var PLUGIN_MAP = {
  'alarms': ['org.chromium.alarms', 'org.chromium.storage'],
  'audioCapture': ['org.chromium.audiocapture'],
  'background': [],
  'fileSystem': ['org.chromium.filesystem', 'org.chromium.filechooser'],
  'fullscreen': [],
  'gcm': ['org.chromium.gcm', 'org.chromium.storage'],
  'geolocation': ['org.apache.cordova.geolocation'],
  'identity': ['org.chromium.identity'],
  'idle': ['org.chromium.idle'],
  'notifications': ['org.chromium.notifications', 'org.chromium.storage'],
  'payments': ['com.google.payments'],
  'power': ['org.chromium.power'],
  'pushMessaging': ['org.chromium.pushmessaging', 'org.chromium.identity'],
  'socket': ['org.chromium.socket'],
  'storage': ['org.chromium.storage'],
  'syncFileSystem': ['org.chromium.syncfilesystem', 'org.chromium.storage', 'org.chromium.identity'],
  'system.cpu': ['org.chromium.system.cpu'],
  'system.display': ['org.chromium.system.display'],
  'system.memory': ['org.chromium.system.memory'],
  'system.network': ['org.chromium.system.network'],
  'system.storage': ['org.chromium.system.storage'],
  'unlimitedStorage': [],
  'videoCapture': ['org.chromium.videocapture'],
};

var STALE_PLUGINS = [];

var ENGINE_MAP = {
  'crosswalk': ['org.apache.cordova.engine.crosswalk'],
  'system': []
};

var SOCKETS_MAP = {
  'udp': ['org.chromium.sockets.udp'],
  //'tcp': ['org.chromium.sockets.tcp'],
  //'tcpServer': ['org.chromium.sockets.tcpServer'],
};

function mapPermissionsToPlugins(knownPermissionsMap, requestedPermissionsList) {
  // We have to create three lists:
  // 1. Permissions your app has requested and we know about (install these plugins)
  // 2. Permissions your app has requested and we do not know about (warn about these)
  // 3. Permissions your app has not requested (uninstall these plugins)
  var ret = {
    toInstall: [],
    toUninstall: [],
    unknown: [],
  };

  var knownPermissionsList = Object.keys(knownPermissionsMap);
  requestedPermissionsList = requestedPermissionsList.slice(); // deep copy so we can modify in-place

  requestedPermissionsList.forEach(function(requestedPermission) {
    // Is this permission known?
    var idx = knownPermissionsList.indexOf(requestedPermission);
    if (idx != -1) {
      ret.toInstall = ret.toInstall.concat(knownPermissionsMap[requestedPermission]);
      // Remove from the list of known permissions, so that at the end of this we have all known permissions that arent requested
      knownPermissionsList.splice(idx,1);
    } else {
      ret.unknown.push(requestedPermission);
    }
  });
  // Uninstall whatever is left, since it was not requested
  knownPermissionsList.forEach(function(permission) {
    ret.toUninstall = ret.toUninstall.concat(knownPermissionsMap[permission]);
  });
  // Final step, bit of a hack, remove duplicate plugins from toUninstall list that exist in toInstall
  // e.g. syncFS depends on identity.  So, even if identity isn't in your manifest, don't uninstal it if you have syncFS
  // The way we handle this is to add org.chromium.identity to the list of plugins to install for the syncFS permission
  // so, the last thing to do is subtract the plugins to install from the plugins to not install, since there can be overlap.
  ret.toUninstall = ret.toUninstall.filter(function(plugin) {
    return ret.toInstall.indexOf(plugin) == -1;
  });

  return ret;
}

module.exports = function analyseManifest(manifest, options) {
  options = options || {};
  var ret = {
    appId: undefined,
    whitelist: [],
    permissions: [],
    pluginsToBeInstalled: [],
    pluginsToBeNotInstalled: [],
    pluginsNotRecognized: [],
  };

  (manifest.permissions || []).forEach(function(permission) {
    if (typeof permission === "object") {
      ret.permissions = ret.permissions.concat(Object.keys(permission));
    } else if (permission === "<all_urls>") {
      ret.whitelist.push("*");
    } else {
      var matchPatternParts = /([^:]+:\/\/[^\/]+)(\/.*)$/.exec(permission);
      if (matchPatternParts) {
        // Disregard paths in host permissions: path is required, but
        // <scheme>://<host>/<any path> should translate to <scheme>://<host>/*
        ret.whitelist.push(matchPatternParts[1] + "/*");
      } else {
        ret.permissions.push(permission);
      }
    }
  });

  var pluginsForPermissions = mapPermissionsToPlugins(PLUGIN_MAP, ret.permissions);
  var pluginsForEngines = mapPermissionsToPlugins(ENGINE_MAP, [options.webview || manifest.webview || "crosswalk"]);
  var pluginsForSockets = mapPermissionsToPlugins(SOCKETS_MAP, Object.keys(manifest.sockets || {}));

  ret.pluginsToBeInstalled = [].concat.apply([], [
      pluginsForPermissions.toInstall,
      pluginsForEngines.toInstall,
      pluginsForSockets.toInstall,
      DEFAULT_PLUGINS
    ]);
  ret.pluginsToBeNotInstalled = [].concat.apply([], [
      pluginsForPermissions.toUninstall,
      pluginsForEngines.toUninstall,
      pluginsForSockets.toUninstall,
      STALE_PLUGINS
    ]);
  ret.pluginsNotRecognized = pluginsForPermissions.unknown.concat(pluginsForSockets.unknown);

  // This should happen rarely
  pluginsForEngines.unknown.forEach(function(unknownEngine) {
    console.warn('Engine not supported by cca: ' + unknownEngine + ' (skipping)');
  });

  if (manifest.key) {
    ret.appId = require('./chrome-app-key-to-id')(manifest.key);
  } else {
    ret.appId = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
  }

  return ret;
};
<|endoftext|>


<commit_before>// Import dependecies
var express = require('express');
var fs = require('fs');
var request = require('request');
var cheerio = require('cheerio');

// Initilize express app
var app =  express();

// Scraping happens here - Routes HTTP GET requests to the specified path with the specified callback functions.
app.get('/scrape', function(req, res){

    // The URL we'll be scraping from
    url = 'http://www.imdb.com/title/tt1229340/';

    // Request call structure - Parameter 1 = Our URL
    // Parameter 2 - callback function with 3 parameters
    request(url, function(error, response, html){

        // First check if there's any errors
        if (!error) {

            // Next utilize cheerio to give us jQuery functionality on returned HTML
            var $ = cheerio.load(html);

            // Define the variables we want to capture
            var title, release, rating;
            var json = {title: "", release: "", rating: ""};

            // Title and year are in the header class so...
            $('.header').filter(function() {

                // Store the filtered data in variable for easy viewing
                var data = $(this);

                // In the DOM, the title is in the first child element of the header tag.
                title = data.child.first().text();

                // Store title in JSON object
                json.title = title;

                // In the DOM, the year is the last child element of the header tag.
                year = data.child.last().text();

                // Store year in JSON object
                json.year = year;
            })

            // Rating is in .star-box-giga-star class so...
            $('.star-box-giga-star').filter(function() {

                // Store the filtered data in variable for easy viewing
                var data = $(this);

                // The .star-box-giga-star class was exactly where we wanted it to be.
                // To get the rating, we can simply just get the .text(), no need to traverse the DOM any further
                rating = data.text();

                // Store rating in JSON object
                json.rating = rating;
            })
        }

    // Write JSON variable to the file system
    // The parameters for this writefile function are (filename, data, callback)
    fs.writeFile('output.json', JSON.stringify(json, null, 4), function(err) {
        console.log("File sucessfully written");
    })

    // Send message to browser since this app does not have a UI
    res.send("Check your files!");

    });
});

app.listen(8080);
console.log("Server initilizes at port 8080");

// Modularlize our code (exporting our functions)
exports = module.exports = app;

<commit_msg>Fixed cheerio children property<commit_after>// Import dependecies
var express = require('express');
var fs = require('fs');
var request = require('request');
var cheerio = require('cheerio');

// Initilize express app
var app =  express();

// Scraping happens here - Routes HTTP GET requests to the specified path with the specified callback functions.
app.get('/scrape', function(req, res){

    // The URL we'll be scraping from
    url = 'http://www.imdb.com/title/tt1229340/';

    // Request call structure - Parameter 1 = Our URL
    // Parameter 2 - callback function with 3 parameters
    request(url, function(error, response, html){

        // First check if there's any errors
        if (!error) {

            // Next utilize cheerio to give us jQuery functionality on returned HTML
            var $ = cheerio.load(html);

            // Define the variables we want to capture
            var title, release, rating;
            var json = {title: "", release: "", rating: ""};

            // Title and year are in the header class so...
            $('.header').filter(function() {

                // Store the filtered data in variable for easy viewing
                var data = $(this);

                // In the DOM, the title is in the first child element of the header tag.
                title = data.children().first().text();

                // Store title in JSON object
                json.title = title;

                // In the DOM, the year is the last child element of the header tag.
                year = data.children().last().text();

                // Store year in JSON object
                json.year = year;
            })

            // Rating is in .star-box-giga-star class so...
            $('.star-box-giga-star').filter(function() {

                // Store the filtered data in variable for easy viewing
                var data = $(this);

                // The .star-box-giga-star class was exactly where we wanted it to be.
                // To get the rating, we can simply just get the .text(), no need to traverse the DOM any further
                rating = data.text();

                // Store rating in JSON object
                json.rating = rating;
            })
        }

    // Write JSON variable to the file system
    // The parameters for this writefile function are (filename, data, callback)
    fs.writeFile('output.json', JSON.stringify(json, null, 4), function(err) {
        console.log("File sucessfully written");
    })

    // Send message to browser since this app does not have a UI
    res.send("Check your files!");

    });
});

app.listen(8080);
console.log("Server initilizes at port 8080");

// Modularlize our code (exporting our functions)
exports = module.exports = app;

<|endoftext|>


<commit_before>import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';

export default class ApplicationRoute extends Route {

  @service('remotestorage') storage;
  @service localData;
  @service logger;
  @service coms;

  async beforeModel (transition) {
    super.beforeModel(...arguments);

    await this.storage.ensureReadiness();
    await this.localData.setDefaultValues();
    await this.coms.instantiateAccountsAndChannels();
    this.coms.setupListeners();

    if (!this.coms.onboardingComplete &&
        !transition.intent.url.includes('add-account')) {
      this.transitionTo('welcome');
    }

    // See a list of allowed types in logger.js
    // Add or remove all your log types here:
    // this.logger.add('message');
    // this.logger.remove('join');
    // this.logger.disable();
    // this.logger.enable();
  }

  @action
  leaveChannel (channel) {
    this.coms.removeChannel(channel.name);

    // Switch to last channel if the channel parted was currently open
    if (channel.visible) {
      let lastChannel = this.coms.sortedChannels.lastObject;
      this.transitionTo('channel', lastChannel);
    }
  }

}
<commit_msg>Fix application route logic<commit_after>import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';
import { isPresent } from '@ember/utils';

export default class ApplicationRoute extends Route {

  @service('remotestorage') storage;
  @service localData;
  @service logger;
  @service coms;

  async beforeModel (transition) {
    super.beforeModel(...arguments);

    await this.storage.ensureReadiness();
    await this.localData.setDefaultValues();
    await this.coms.instantiateAccountsAndChannels();
    this.coms.setupListeners();

    if (isPresent(transition.intent.url) &&
        transition.intent.url.includes('add-account')) {
      return;
    }

    if (!this.coms.onboardingComplete) {
      this.transitionTo('welcome');
    }

    // See a list of allowed types in logger.js
    // Add or remove all your log types here:
    // this.logger.add('message');
    // this.logger.remove('join');
    // this.logger.disable();
    // this.logger.enable();
  }

  @action
  leaveChannel (channel) {
    this.coms.removeChannel(channel.name);

    // Switch to last channel if the channel parted was currently open
    if (channel.visible) {
      let lastChannel = this.coms.sortedChannels.lastObject;
      this.transitionTo('channel', lastChannel);
    }
  }

}
<|endoftext|>


<commit_before>var request = require('request');
var ee = require('events').EventEmitter;
var util = require('util');
var qs = require('querystring');

var Omegle = function()
	{
		ee.call(this);
		var useragent = 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0';
		var url = 'http://front1.omegle.com';
		var gotID = false;
		var isConnected = false;
		var _this = this;
		this.id='';
		this.count=0;

		this.randID = function(){
			var charset='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
			var str='';
			for(i=0; i<8; ++i)
				str+=charset.charAt(Math.floor((Math.random() * (charset.length+1))));
			return str;
		}

		getResponse = function(path, data, callback, method='POST'){
			var qsArr = ['/status','/start'];
			var options = {
			  url: url+path,
			  headers: {
				'User-Agent': useragent,
				'Connection': 'k_thisp-alive',
				'Referer' : 'http://www.omegle.com',
				'Origin' :'http://www.omegle.com',
				'Host' : url,
				'Content-Type': 'application/x-www-form-urlencoded',
				'Content-Length' : 0
			  },
			  method: method
			};
			if (qsArr.indexOf(path)>-1)
			{
				options['qs'] = data;
			}
			else
			{
				options.headers['Content-Length'] = qs.stringify(data).length;
				options['form'] = qs.stringify(data);
			}
			try
			{
				request(options, function (error, response, body) {
				  if (!error && response.statusCode == 200) {
					//if(path=='/events')console.log(options.qs)
					return callback(body,null);
				  }
				  else
				  {
					console.log('Error: '+ path +'\t'+error);
					return callback(false,error);
				  }
				});
			}
			catch (e)
			{
				console.log('Error sending request: ' + e);
				return callback(false,e);
			}
		}

		this.connect=function(){
			this.updateServer();
			var data = {
				rcs: 1,
				firstevents: 1,
				lang: 'en',
				group: 'unmon',
				randid: _this.randID,
				spid:''
				};
			getResponse('/start',data, function(body,error){
				if(body)
				{
					_this.id=JSON.parse(body).clientID;
					_this.emit('gotID', _this.id);
					emitEvents(JSON.parse(body).events)
					gotID = true;
					_this.getEvents();
				}
				else
					_this.emit('omerror', error);
			});

		}

		this.getEvents=function(){
			var data={id:_this.id};

			getResponse('/events',data, function(events,error){
				if(events)
				{
					var ev = JSON.parse(events);
					//console.log('Events: '+ev[0][0]);
					emitEvents(ev);
					if(gotID)
						_this.getEvents();
				}
				else
				{
					_this.emit('omerror', error);
					if(gotID)
						_this.getEvents();
				}
			});
		}

		var emitEvents = function(ev){

			for(i=0;i<ev.length;++i)
			{
				var a = ev[i][0];
				if(a=='waiting')
					_this.emit('waiting');
				else if(a=='connected')
				{
					_this.emit('connected');
					isConnected = true;
				}
				else if(a=='error')
				{
					_this.emit('error', ev[i][1]);
					isConnected = false;
					gotID = false;
				}
				else if(a=='connectionDied')
				{
					_this.emit('connectionDied');
					isConnected = false;
					gotID = false;
				}
				else if(a=='antinudeBanned')
				{
					_this.emit('antinudeBanned');
					isConnected = false;
					gotID = false;
				}
				else if(a=='typing')
					_this.emit('typing');
				else if(a=='stoppedTyping')
					_this.emit('stoppedTyping');
				else if(a=='gotMessage')
				{
					_this.emit('stoppedTyping');
					_this.emit('gotMessage',ev[i][1]);
				}
				else if(a=='strangerDisconnected')
				{
					_this.emit('strangerDisconnected');
					isConnected = false;
					gotID = false;
				}
			}

		}

		this.updateServer=function(){
			getResponse('/status',{nocache:Math.random(),randid:_this.randID()},function(statusBody,error){
				if(statusBody)
				{
					url='http://'+JSON.parse(statusBody).servers[0];
					_this.emit('serverUpdated', url);
				}
				else
					_this.emit('omerror', 'Couldn\'t get server list. '+ error);
			},'GET');
		}

		this.send = function(msg,callback){
			var data={msg:msg,id:_this.id};
			getResponse('/send',data, function(body,error){
				if(body)
				{
					if(body!='win')
						_this.emit('omerror', 'Couldn\'t send the message. Response from server: '+ body);
				}
				else
					_this.emit('omerror', error);

				if(callback)
					callback(body);
			});
		}

		this.startTyping = function(callback){
			var data={id:_this.id};
			getResponse('/typing',data, function(body,error){
				if(body)
				{
					if(body!='win')
						_this.emit('omerror', 'Couldn\'t send the typing event. Response from server: '+ body);
				}
				else
					_this.emit('omerror', error);

				if(callback)
					callback(body);
			});
		}

		this.stopTyping = function(callback){
			var data={id:_this.id};
			getResponse('/stoppedtyping',data, function(body,error){
				if(body)
				{
					if(body!='win')
						_this.emit('omerror', 'Couldn\'t send the stoppedtyping event. Response from server: '+ body);
				}
				else
					_this.emit('omerror', error);

				if(callback)
					callback(body);
			});
		}

	}

util.inherits(Omegle, ee);

module.exports = Omegle;<commit_msg>Added stopLookingForCommonLikes() / slfcl()<commit_after>var request = require('request');
var ee = require('events').EventEmitter;
var util = require('util');
var qs = require('querystring');

var Omegle = function()
	{
		ee.call(this);
		var useragent = 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0';
		var url = 'http://front1.omegle.com';
		var gotID = false;
		var isConnected = false;
		var _this = this;
		this.id='';
		this.count=0;

		this.randID = function(){
			var charset='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
			var str='';
			for(i=0; i<8; ++i)
				str+=charset.charAt(Math.floor((Math.random() * (charset.length+1))));
			return str;
		}

		getResponse = function(path, data, callback, method='POST'){
			var qsArr = ['/status','/start'];
			var options = {
			  url: url+path,
			  headers: {
				'User-Agent': useragent,
				'Connection': 'k_thisp-alive',
				'Referer' : 'http://www.omegle.com',
				'Origin' :'http://www.omegle.com',
				'Host' : url,
				'Content-Type': 'application/x-www-form-urlencoded',
				'Content-Length' : 0
			  },
			  method: method
			};
			if (qsArr.indexOf(path)>-1)
			{
				options['qs'] = data;
			}
			else
			{
				options.headers['Content-Length'] = qs.stringify(data).length;
				options['form'] = qs.stringify(data);
			}
			try
			{
				request(options, function (error, response, body) {
				  if (!error && response.statusCode == 200) {
					//if(path=='/events')console.log(options.qs)
					return callback(body,null);
				  }
				  else
				  {
					console.log('Error: '+ path +'\t'+error);
					return callback(false,error);
				  }
				});
			}
			catch (e)
			{
				console.log('Error sending request: ' + e);
				return callback(false,e);
			}
		}

		this.connect=function(){
			this.updateServer();
			var data = {
				rcs: 1,
				firstevents: 1,
				lang: 'en',
				group: 'unmon',
				randid: _this.randID,
				spid:''
				};
			getResponse('/start',data, function(body,error){
				if(body)
				{
					_this.id=JSON.parse(body).clientID;
					_this.emit('gotID', _this.id);
					emitEvents(JSON.parse(body).events)
					gotID = true;
					_this.getEvents();
				}
				else
					_this.emit('omerror', error);
			});

		}

		this.getEvents=function(){
			var data={id:_this.id};

			getResponse('/events',data, function(events,error){
				if(events)
				{
					var ev = JSON.parse(events);
					//console.log('Events: '+ev);
					emitEvents(ev);
					if(gotID)
						_this.getEvents();
				}
				else
				{
					_this.emit('omerror', error);
					if(gotID)
						_this.getEvents();
				}
			});
		}

		var emitEvents = function(ev){

			for(i=0;i<ev.length;++i)
			{
				var a = ev[i][0];
				if(a=='waiting')
					_this.emit('waiting');
				else if(a=='connected')
				{
					_this.emit('connected');
					isConnected = true;
				}
				else if(a=='error')
				{
					_this.emit('error', ev[i][1]);
					isConnected = false;
					gotID = false;
				}
				else if(a=='connectionDied')
				{
					_this.emit('connectionDied');
					isConnected = false;
					gotID = false;
				}
				else if(a=='antinudeBanned')
				{
					_this.emit('antinudeBanned');
					isConnected = false;
					gotID = false;
				}
				else if(a=='typing')
					_this.emit('typing');
				else if(a=='stoppedTyping')
					_this.emit('stoppedTyping');
				else if(a=='gotMessage')
				{
					_this.emit('stoppedTyping');
					_this.emit('gotMessage',ev[i][1]);
				}
				else if(a=='strangerDisconnected')
				{
					_this.emit('strangerDisconnected');
					isConnected = false;
					gotID = false;
				}
			}

		}

		this.updateServer=function(){
			getResponse('/status',{nocache:Math.random(),randid:_this.randID()},function(statusBody,error){
				if(statusBody)
				{
					url='http://'+JSON.parse(statusBody).servers[0];
					_this.emit('serverUpdated', url);
				}
				else
					_this.emit('omerror', 'Couldn\'t get server list. '+ error);
			},'GET');
		}

		this.send = function(msg,callback){
			var data={msg:msg,id:_this.id};
			getResponse('/send',data, function(body,error){
				if(body)
				{
					if(body!='win')
						_this.emit('omerror', 'Couldn\'t send the message. Response from server: '+ body);
				}
				else
					_this.emit('omerror', error);

				if(callback)
					callback(body);
			});
		}

		this.startTyping = function(callback){
			var data={id:_this.id};
			getResponse('/typing',data, function(body,error){
				if(body)
				{
					if(body!='win')
						_this.emit('omerror', 'Couldn\'t send the typing event. Response from server: '+ body);
				}
				else
					_this.emit('omerror', error);

				if(callback)
					callback(body);
			});
		}

		this.stopTyping = function(callback){
			var data={id:_this.id};
			getResponse('/stoppedtyping',data, function(body,error){
				if(body)
				{
					if(body!='win')
						_this.emit('omerror', 'Couldn\'t send the stoppedtyping event. Response from server: '+ body);
				}
				else
					_this.emit('omerror', error);

				if(callback)
					callback(body);
			});
		}

		this.stopLookingForCommonLikes = function(callback){
			var data={id:_this.id};
			getResponse('/stoplookingforcommonlikes',data, function(body,error){
				if(body)
				{
					if(body!='win')
						_this.emit('omerror', 'Something went wrong. Response from server: '+ body);
				}
				else
					_this.emit('omerror', error);

				if(callback)
					callback(body);
			});
		}

		this.slfcl = this.stopLookingForCommonLikes;
	}

util.inherits(Omegle, ee);

module.exports = Omegle;<|endoftext|>


<commit_before>(function () {'use strict'; var USING_TEMPLATES = true; var MODULE_NAME = "formlyLumx"; var PREFIX = "lx";var FIELDS = [{ "name": "checkbox", "template": "
<input ng-model=\"model[options.key]\" type=\"checkbox\" ng-checked=\"::to.checked\" class=\"checkbox__input\">{{to.label}}{{::to.description}}
"}, {"name":
"date-picker", "template": "<lx-date-picker model=\"model[options.key]\" label=\"{{to.label}} {{::to.required ? \'*\' : \'\'}}\"></lx-date-picker>"}, {"name":
"flex", "template": "<formly-form fields=\"to.fields\" model=\"$parent.model\" form=\"::id\" root-el=\"div\" flex-container=\"{{::to.flex.container}}\" flex-align=\"{{::to.flex.align}}\" flex-gutter=\"{{::to.flex.gutter}}\"></formly-form>"}, {"name":
"input", "template": "<lx-text-field model=\"::model[options.key]\" icon=\"{{::to.icon}}\" fixed-label=\"::to.fixedLabel\" theme=\"{{::to.theme}}\" disabled=\"to.disabled\" label=\"{{to.label}} {{::to.required ? \'*\' : \'\'}}\" valid=\"options.formControl.$valid && options.formControl.$touched\" error=\"options.formControl.$invalid && options.formControl.$touched\"><input ng-model=\"model[options.key]\" type=\"{{::to.type}}\"></lx-text-field>"}, {"name":
"radio", "template": "

{{to.label}}

<input ng-model=\"$parent.model[$parent.options.key]\" id=\"{{::id + \'_\' + $index}}\" type=\"radio\" ng-disabled=\"::o.disabled\" class=\"radio-button__input\" ng-value=\"::o.value\" aria-labelledby=\"{{::id + \'_\' + $index + \'_radioButton\'}}\">{{::o.name}}{{::o.description}}

"}, {"name":
"select", "template": "

{{to.label}} {{::to.required ? \'*\' : \'\'}}
<lx-select ng-model=\"model[options.key]\" choices=\"to.options\" placeholder=\"{{::to.placeholder}}\" min-length=\"::to.minLength\" allow-clear=\"::to.allowClear\" ng-attr-multiple=\"{{::to.multiple}}\"><lx-select-selected>{{$selected[to.selected]}} {{::to.selected2 ? \' - \' + $selected[to.selected2] : \'\'}}</lx-select-selected><lx-select-choices>{{$choice[to.choice]}} {{::to.choice2 ? \' - \' + $choice[to.choice2] : \'\'}}</lx-select-choices></lx-select>
"}, {"name":
"switch", "template": "
<input ng-model=\"model[options.key]\" type=\"checkbox\" ng-checked=\"::to.checked\" class=\"switch__input\">{{to.label}}{{::to.description}}
"}, {"name":
"textarea", "template": "<lx-text-field model=\"::model[options.key]\" fixed-label=\"::to.fixedLabel\" icon=\"{{::to.icon}}\" theme=\"{{::to.theme}}\" label=\"{{to.label}} {{::to.required ? \'*\' : \'\'}}\" valid=\"options.formControl.$valid && options.formControl.$touched\" error=\"options.formControl.$invalid && options.formControl.$touched || options.validators\"><textarea ng-model=\"model[options.key]\">\n    </textarea></lx-text-field>"}, {"name":
"title", "template": "
{{to.title}}
"}]; var WRAPPERS = [{ "name": "wrapper-div", "template": "
<formly-transclude></formly-transclude>
"}, {"name":
"wrapper-errors", "template": "
<formly-transclude></formly-transclude>

{{::error.message}}

{{::to.pending || \'Checking...\'}}
"}, {"name":
"wrapper-flex-item", "template": "
<formly-transclude></formly-transclude>
"}];function _prefixer(name) { return PREFIX + '-' + name; } function _wrapperTemplateUrl(name) { return 'wrappers/formly-wrappers-' + _prefixer(name) + '.html'; } function _fieldTemplateUrl(name) { return 'fields/formly-fields-' + _prefixer(name) + '.html'; } angular.module(MODULE_NAME, ['formly']).config(setCustomTemplates).run(cacheLumXTemplates); 	/*@ngInject*/ 	function cacheLumXTemplates($templateCache) { 		if (USING_TEMPLATES) { 			angular.forEach(FIELDS, function (field) { 				$templateCache.put(_fieldTemplateUrl(field.name), field.template); 			}); 			angular.forEach(WRAPPERS, function (wrapper) { 				$templateCache.put(_wrapperTemplateUrl(wrapper.name), wrapper.template); 			});}} 	/*@ngInject*/ 	function setCustomTemplates(formlyConfigProvider) { 		if (USING_TEMPLATES) { 			var wrapperList = []; 			angular.forEach(WRAPPERS, function (wrapper) { 				wrapperList.push(_prefixer(wrapper.name)); 			}); 			angular.forEach(WRAPPERS, function (wrapper) { 				formlyConfigProvider.setWrapper({name: _prefixer(wrapper.name), templateUrl: _wrapperTemplateUrl(wrapper.name)});}); 			/* set types */ 			angular.forEach(FIELDS, function (field) { 			formlyConfigProvider.setType({ 				name: _prefixer(field.name), 				templateUrl: _fieldTemplateUrl(field.name), 				wrappers: wrapperList 				}); 			}); 		}}}());<commit_msg>updates<commit_after>(function () {'use strict'; var USING_TEMPLATES = true; var MODULE_NAME = "formlyLumx"; var PREFIX = "lx";var FIELDS = [{ "name": "checkbox", "template": "
<input ng-model=\"model[options.key]\" type=\"checkbox\" ng-checked=\"::to.checked\" class=\"checkbox__input\">{{to.label}}{{::to.description}}
"}, {"name":
"date-picker", "template": "<lx-date-picker model=\"model[options.key]\" label=\"{{to.label}} {{::to.required ? \'*\' : \'\'}}\"></lx-date-picker>"}, {"name":
"flex", "template": "<formly-form fields=\"to.fields\" model=\"$parent.model\" form=\"::id\" root-el=\"div\" flex-container=\"{{::to.flex.container}}\" flex-align=\"{{::to.flex.align}}\" flex-gutter=\"{{::to.flex.gutter}}\"></formly-form>"}, {"name":
"input", "template": "<lx-text-field model=\"::model[options.key]\" icon=\"{{::to.icon}}\" fixed-label=\"::to.fixedLabel\" theme=\"{{::to.theme}}\" disabled=\"to.disabled\" label=\"{{to.label}} {{::to.required ? \'*\' : \'\'}}\" valid=\"options.formControl.$valid && options.formControl.$touched\" error=\"options.formControl.$invalid && options.formControl.$touched\"><input ng-model=\"model[options.key]\" type=\"{{::to.type}}\"></lx-text-field>"}, {"name":
"radio", "template": "

{{to.label}}

<input ng-model=\"$parent.model[$parent.options.key]\" id=\"{{::id + \'_\' + $index}}\" type=\"radio\" ng-disabled=\"::o.disabled\" class=\"radio-button__input\" ng-value=\"::o.value\" aria-labelledby=\"{{::id + \'_\' + $index + \'_radioButton\'}}\">{{::o.name}}{{::o.description}}

"}, {"name":
"select", "template": "

{{to.label}} {{::to.required ? \'*\' : \'\'}}
<lx-select ng-model=\"model[options.key]\" choices=\"to.options\" placeholder=\"{{::to.placeholder}}\" min-length=\"::to.minLength\" allow-clear=\"::to.allowClear\" ng-attr-multiple=\"{{::to.multiple}}\"><lx-select-selected>{{$selected[to.selected]}} {{::to.selected2 ? \' - \' + $selected[to.selected2] : \'\'}}</lx-select-selected><lx-select-choices>{{$choice[to.choice]}} {{::to.choice2 ? \' - \' + $choice[to.choice2] : \'\'}}</lx-select-choices></lx-select>
"}, {"name":
"switch", "template": "
<input ng-model=\"model[options.key]\" type=\"checkbox\" ng-checked=\"::to.checked\" class=\"switch__input\">{{to.label}}{{::to.description}}
"}, {"name":
"textarea", "template": "<lx-text-field model=\"::model[options.key]\" fixed-label=\"::to.fixedLabel\" icon=\"{{::to.icon}}\" theme=\"{{::to.theme}}\" label=\"{{to.label}} {{::to.required ? \'*\' : \'\'}}\" valid=\"options.formControl.$valid && options.formControl.$touched\" error=\"options.formControl.$invalid && options.formControl.$touched || options.validators\"><textarea ng-model=\"model[options.key]\">\n    </textarea></lx-text-field>"}, {"name":
"title", "template": "
{{to.title}}
"}]; var WRAPPERS = [{ "name": "wrapper-div", "template": "
<formly-transclude></formly-transclude>
"}, {"name":
"wrapper-errors", "template": "
<formly-transclude></formly-transclude>

{{::error.message}}

{{::to.pending || \'Checking...\'}}
"}, {"name":
"wrapper-flex-item", "template": "
<formly-transclude></formly-transclude>
"}];function _prefixer(name) { return PREFIX + '-' + name; } function _wrapperTemplateUrl(name) { return 'wrappers/formly-wrappers-' + _prefixer(name) + '.html'; } function _fieldTemplateUrl(name) { return 'fields/formly-fields-' + _prefixer(name) + '.html'; } angular.module(MODULE_NAME, ['formly']).config(setCustomTemplates).run(cacheLumXTemplates); 	/*@ngInject*/ 	function cacheLumXTemplates($templateCache) { 		if (USING_TEMPLATES) { 			angular.forEach(FIELDS, function (field) { 				$templateCache.put(_fieldTemplateUrl(field.name), field.template); 			}); 			angular.forEach(WRAPPERS, function (wrapper) { 				$templateCache.put(_wrapperTemplateUrl(wrapper.name), wrapper.template); 			});}} 	/*@ngInject*/ 	function setCustomTemplates(formlyConfigProvider) { 		if (USING_TEMPLATES) { 			var wrapperList = []; 			angular.forEach(WRAPPERS, function (wrapper) { 				wrapperList.push(_prefixer(wrapper.name)); 			}); 			angular.forEach(WRAPPERS, function (wrapper) { 				formlyConfigProvider.setWrapper({name: _prefixer(wrapper.name), templateUrl: _wrapperTemplateUrl(wrapper.name)});}); 			/* set types */ 			angular.forEach(FIELDS, function (field) { 			formlyConfigProvider.setType({ 				name: _prefixer(field.name), 				templateUrl: _fieldTemplateUrl(field.name), 				wrappers: wrapperList 				}); 			}); 		}}}());<|endoftext|>


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

    if (!global.cloudcmd)
        return console.log(
             '# server.js'                                      + '\n'  +
             '# -----------'                                    + '\n'  +
             '# Module is part of Cloud Commander,'             + '\n'  +
             '# easy to use web server.'                        + '\n'  +
             '# http://cloudcmd.io'                             + '\n');

    var main                = global.cloudcmd.main,

        DIR                 = main.DIR,
        LIBDIR              = main.LIBDIR,
        SRVDIR              = main.SRVDIR,

        URL                 = main.url,
        Path                = main.path,
        Querystring         = main.querystring,

        Minify              = main.minify,
        CloudFunc           = main.cloudfunc,
        AppCache            = main.appcache,
        Socket              = main.socket,
        Console             = main.console,
        Terminal            = main.terminal,
        join                = main.srvrequire('join'),

        zlib                = main.zlib,
        http                = main.http,
        https               = main.https,
        Util                = main.util,
        express             = main.express,
        expressApp,
        files               = main.files,
        emptyHandler        = function(req, res, next) { Util.exec(next); },

        Server, Rest, Route;

        join                = join && Util.bind(join, beforeJoin) || emptyHandler;

    /* базовая инициализация  */
    function init(pAppCachProcessing) {
        var config = main.config;

        /* создаём файл app cache */
        if (config.appcache  && AppCache && config.server)
            Util.exec( pAppCachProcessing);
    }

    /**
     * start server function
     * @param pConfig
     * @param pProcessing {index, appcache, rest}
     */
    function start(options) {
        var redirectServer, port, ip, ssl, sslPort,
            HTTP        = 'http://',
            HTTPS       = 'https://',
            config      = main.config;

        if (!options)
            options = {};

        Rest    =   options.rest;
        Route   =   options.route;

        init(options.appcache);

        port    =   process.env.PORT            ||  /* c9           */
                    process.env.app_port        ||  /* nodester     */
                    process.env.VCAP_APP_PORT   ||  /* cloudfoundry */
                    config.port,
        ip      =   process.env.IP              ||  /* c9           */
                    config.ip                   ||
                    (main.WIN32 ? '127.0.0.1' : '0.0.0.0'),

        ssl     = options.ssl,
        sslPort = config.sslPort;

        /* server mode or testing mode */
        if (!config.server)
            Util.log('Cloud Commander testing mode');
        else
            if (!ssl)
                createServer(port, ip, HTTP);
            else {
                createRedirect(port, ip, HTTPS, sslPort);

                createServer(sslPort, ip, HTTP, ssl, function() {
                    Util.log('Could not use https port: ' + sslPort);
                    redirectServer.close();
                    Util.log('* Redirection http -> https removed');
                    createServer(port, ip);
                });
            }
    }

    function createRedirect(port, ip, protocol, sslPort) {
        var server = function(req, res) {
            var url,
                host        = req.headers.host,
                parsed      = URL.parse(host),
                hostName    = parsed.protocol;

            url             = protocol + hostName + sslPort + req.url;

            main.redirect({
                response: res,
                url: url
            });
        };

        Util.log('* Redirection http -> https is setted up');
        logServer(port, ip, protocol);

        http.createServer(server)
            .listen(port, ip);
    }

    function createServer(port, ip, protocol, ssl, callback) {
        var server, app;

        expressApp  = express.getApp([
            Rest,
            Route,
            join,
            controller
        ]);

        app         = expressApp || respond;

        if (ssl)
            server  =  https.createServer(ssl, app);
        else
            server  = http.createServer(app);

        server.on('error', function(error) {
            Util.log(error);
            Util.exec(callback, error);
        });

        server.listen(port, ip);

        logServer(port, ip, protocol);
        addSockets(server);
    }

    function logServer(port, ip, http) {
        Util.log('* Server running at ' + http + ip + ':' + port);
    }

    function addSockets(server) {
        var listen, msg,
            config  = main.config,
            status  = 'off';

        if (config.socket && Socket) {
            listen = Socket.listen(server);

            if (listen) {
                status = 'on';
                Console.init();
                Terminal.init();
            }
        }

        msg     = CloudFunc.formatMsg('sockets', '', status);

        Util.log(msg);
    }

    function respond(req, res) {
        var i, n, func,
            funcs = ([
                Rest,
                Route,
                join,
                controller
            ]);

        n = funcs.length;
        for (i = 0; i < n; i++) {
            func        = funcs[i];
            funcs[i]    = func.bind(null, req, res);
        }

        Util.loadOnLoad(funcs);
    }

    /**
     * Главная функция, через которую проихсодит
     * взаимодействие, обмен данными с клиентом
     * @param req - запрос клиента (Request)
     * @param res - ответ сервера (Response)
     */
    function controller(req, res) {
        var check, result,
            config      = main.config,
            isMin       = config.minify,
            parsedUrl   = URL.parse(req.url),
            query       = parsedUrl.search || '',
            path        = main.getPathName(req),
            name        = path;

        if (!expressApp)
            Util.log(req.method + ' ' + path + query);

        /* watching is file changed */
        if (config.appcache)
            AppCache.watch(name);

        name    = Path.join(DIR, name);
        check   = checkExtension(name);
        result  = isMin && check;

        Util.ifExec(!result,
            function(error, params) {
                var sendName = params && params.name || name;

                main.sendFile({
                    name        : sendName,
                    cache       : config.cache,
                    gzip        : true,
                    request     : req,
                    response    : res
                });
        }, function(callback) {
            Minify.optimize(name, {
                callback    : callback,
                returnName  : true
            });
        });
    }

    function minify(name, callback) {
        Minify.optimize(name, {
            callback    : callback
        });
    }

    function beforeJoin(names, callback) {
        var i, name, check, minName,
            func,
            funcs   = [],
            dir     = DIR,
            config  = main.config,
            n       = names.length;

        for (i = 0; i < n; i++) {
            name        = Path.join(dir, names[i]);
            names[i]    = name;

            if (config.minify) {
                check       = checkExtension(name);

                if (check) {
                    minName = Minify.getName(name);

                    if (name !== minName)
                        names[i]    = minName;
                }

                funcs.push(Util.bind(minify, name));
            }
        }

        func    = Util.retExec(callback, names);

        Util.ifExec(!config.minify, func, function(callback) {
            Util.asyncCall(funcs, callback);
        });
    }

    function checkExtension(name) {
        var ret;

        ret = Util.checkExtension(name, ['.js', '.css', '.html']);

        return ret;
    }

    exports.start           = start;

})();
<commit_msg>chore(server) rm unused vars<commit_after> (function() {
    'use strict';

    if (!global.cloudcmd)
        return console.log(
             '# server.js'                                      + '\n'  +
             '# -----------'                                    + '\n'  +
             '# Module is part of Cloud Commander,'             + '\n'  +
             '# easy to use web server.'                        + '\n'  +
             '# http://cloudcmd.io'                             + '\n');

    var main                = global.cloudcmd.main,

        DIR                 = main.DIR,
        URL                 = main.url,
        Path                = main.path,

        Minify              = main.minify,
        CloudFunc           = main.cloudfunc,
        AppCache            = main.appcache,
        Socket              = main.socket,
        Console             = main.console,
        Terminal            = main.terminal,
        join                = main.srvrequire('join'),

        http                = main.http,
        https               = main.https,
        Util                = main.util,
        express             = main.express,
        expressApp,
        emptyHandler        = function(req, res, next) { Util.exec(next); },

        Rest, Route;

        join                = join && Util.bind(join, beforeJoin) || emptyHandler;

    /* базовая инициализация  */
    function init(pAppCachProcessing) {
        var config = main.config;

        /* создаём файл app cache */
        if (config.appcache  && AppCache && config.server)
            Util.exec( pAppCachProcessing);
    }

    /**
     * start server function
     * @param pConfig
     * @param pProcessing {index, appcache, rest}
     */
    function start(options) {
        var redirectServer, port, ip, ssl, sslPort,
            HTTP        = 'http://',
            HTTPS       = 'https://',
            config      = main.config;

        if (!options)
            options = {};

        Rest    =   options.rest;
        Route   =   options.route;

        init(options.appcache);

        port    =   process.env.PORT            ||  /* c9           */
                    process.env.app_port        ||  /* nodester     */
                    process.env.VCAP_APP_PORT   ||  /* cloudfoundry */
                    config.port,
        ip      =   process.env.IP              ||  /* c9           */
                    config.ip                   ||
                    (main.WIN32 ? '127.0.0.1' : '0.0.0.0'),

        ssl     = options.ssl,
        sslPort = config.sslPort;

        /* server mode or testing mode */
        if (!config.server)
            Util.log('Cloud Commander testing mode');
        else
            if (!ssl)
                createServer(port, ip, HTTP);
            else {
                createRedirect(port, ip, HTTPS, sslPort);

                createServer(sslPort, ip, HTTP, ssl, function() {
                    Util.log('Could not use https port: ' + sslPort);
                    redirectServer.close();
                    Util.log('* Redirection http -> https removed');
                    createServer(port, ip);
                });
            }
    }

    function createRedirect(port, ip, protocol, sslPort) {
        var server = function(req, res) {
            var url,
                host        = req.headers.host,
                parsed      = URL.parse(host),
                hostName    = parsed.protocol;

            url             = protocol + hostName + sslPort + req.url;

            main.redirect({
                response: res,
                url: url
            });
        };

        Util.log('* Redirection http -> https is setted up');
        logServer(port, ip, protocol);

        http.createServer(server)
            .listen(port, ip);
    }

    function createServer(port, ip, protocol, ssl, callback) {
        var server, app;

        expressApp  = express.getApp([
            Rest,
            Route,
            join,
            controller
        ]);

        app         = expressApp || respond;

        if (ssl)
            server  =  https.createServer(ssl, app);
        else
            server  = http.createServer(app);

        server.on('error', function(error) {
            Util.log(error);
            Util.exec(callback, error);
        });

        server.listen(port, ip);

        logServer(port, ip, protocol);
        addSockets(server);
    }

    function logServer(port, ip, http) {
        Util.log('* Server running at ' + http + ip + ':' + port);
    }

    function addSockets(server) {
        var listen, msg,
            config  = main.config,
            status  = 'off';

        if (config.socket && Socket) {
            listen = Socket.listen(server);

            if (listen) {
                status = 'on';
                Console.init();
                Terminal.init();
            }
        }

        msg     = CloudFunc.formatMsg('sockets', '', status);

        Util.log(msg);
    }

    function respond(req, res) {
        var i, n, func,
            funcs = ([
                Rest,
                Route,
                join,
                controller
            ]);

        n = funcs.length;
        for (i = 0; i < n; i++) {
            func        = funcs[i];
            funcs[i]    = func.bind(null, req, res);
        }

        Util.loadOnLoad(funcs);
    }

    /**
     * Главная функция, через которую проихсодит
     * взаимодействие, обмен данными с клиентом
     * @param req - запрос клиента (Request)
     * @param res - ответ сервера (Response)
     */
    function controller(req, res) {
        var check, result,
            config      = main.config,
            isMin       = config.minify,
            parsedUrl   = URL.parse(req.url),
            query       = parsedUrl.search || '',
            path        = main.getPathName(req),
            name        = path;

        if (!expressApp)
            Util.log(req.method + ' ' + path + query);

        /* watching is file changed */
        if (config.appcache)
            AppCache.watch(name);

        name    = Path.join(DIR, name);
        check   = checkExtension(name);
        result  = isMin && check;

        Util.ifExec(!result,
            function(error, params) {
                var sendName = params && params.name || name;

                main.sendFile({
                    name        : sendName,
                    cache       : config.cache,
                    gzip        : true,
                    request     : req,
                    response    : res
                });
        }, function(callback) {
            Minify.optimize(name, {
                callback    : callback,
                returnName  : true
            });
        });
    }

    function minify(name, callback) {
        Minify.optimize(name, {
            callback    : callback
        });
    }

    function beforeJoin(names, callback) {
        var i, name, check, minName,
            func,
            funcs   = [],
            dir     = DIR,
            config  = main.config,
            n       = names.length;

        for (i = 0; i < n; i++) {
            name        = Path.join(dir, names[i]);
            names[i]    = name;

            if (config.minify) {
                check       = checkExtension(name);

                if (check) {
                    minName = Minify.getName(name);

                    if (name !== minName)
                        names[i]    = minName;
                }

                funcs.push(Util.bind(minify, name));
            }
        }

        func    = Util.retExec(callback, names);

        Util.ifExec(!config.minify, func, function(callback) {
            Util.asyncCall(funcs, callback);
        });
    }

    function checkExtension(name) {
        var ret;

        ret = Util.checkExtension(name, ['.js', '.css', '.html']);

        return ret;
    }

    exports.start           = start;

})();
<|endoftext|>


<commit_before>import d3 from 'd3'

function wrap (text, width) {
  text.each(function () {
    let text = d3.select(this)
    let words = text.text().split('').reverse()
    let word
    let line = []
    let sumLineNumber = words.length
    let lineNumber = 1
    let lineHeight = 1.1
    let tspan = text.text(null).append('tspan')
    while (words.length > 0) {
      word = words.pop()
      line.push(word)
      tspan.text(line.join(' '))
      if (tspan.node().getComputedTextLength() > width) {
        line.pop()
        tspan.text(line.join(' '))
        line = [word]
        var currentLineHeight = words.length === sumLineNumber - 1 ? -Math.ceil(sumLineNumber / 2, -1) : 1
        tspan = text.append('tspan')
          .attr({
            'x': 0,
            'dy': (currentLineHeight * lineNumber * lineHeight) + 'rem'
          })
          .text(word)
      }
    }
  })
}

function axisLabel () {
  var _width = 1
  var _height = 1
  var _fontSize = 14
  var _xLabel, _yLabel
  var _textLength = 5
  var _margin = {top: 0, right: 0, bottom: 30, left: 20}

  function chart (selection) {
    if (_xLabel) {
      var xAxisLabel = selection.select('.x.axis').selectAll('.label').data(_xLabel)
        .enter().append('g')
        .attr({
          'class': 'label',
          'transform': 'translate(' + (_width / 2) + ', ' + _margin.bottom + ')'
        })
        .style({
          'font-size': _fontSize
        })

      xAxisLabel.append('text').text(d => { return d })
    }

    if (_yLabel) {
      var yAxisLabel = selection.select('.y.axis').selectAll('.label').data(_yLabel)
        .enter().append('g')
        .attr({
          'class': 'label',
          'transform': 'translate(' + (-_margin.left) + ', ' + (_height / 2) + ')'
        })
        .style({
          'font-size': _fontSize
        })

      yAxisLabel.append('text').text(d => { return d })
        .style('transform', 'rotate(-90deg)')
        //.call(wrap, _textLength, 0, 0)
    }
  }

  chart.fontSize = function (value) {
    if (!arguments.length) {
      return _fontSize
    }

    _fontSize = value
    return chart
  }

  chart.width = function (value) {
    if (!arguments.length) {
      return _width
    }

    _width = value
    return chart
  }

  chart.height = function (value) {
    if (!arguments.length) {
      return _height
    }

    _height = value
    return chart
  }

  chart.fontSize = function (value) {
    if (!arguments.length) {
      return _fontSize
    }

    _fontSize = value
    return chart
  }

  chart.data = function (xValue, yValue) {
    if (!arguments.length) {
      return _xLabel
    }

    _xLabel = xValue ? [xValue] : null
    _yLabel = yValue ? [yValue] : null
    return chart
  }

  chart.margin = function (value) {
    if (!arguments.length) {
      return _margin
    }

    _margin = value
    return chart
  }

  return chart
}

export default axisLabel
<commit_msg>code standard.<commit_after>// import d3 from 'd3'

/*
function wrap (text, width) {
  text.each(function () {
    let text = d3.select(this)
    let words = text.text().split('').reverse()
    let word
    let line = []
    let sumLineNumber = words.length
    let lineNumber = 1
    let lineHeight = 1.1
    let tspan = text.text(null).append('tspan')
    while (words.length > 0) {
      word = words.pop()
      line.push(word)
      tspan.text(line.join(' '))
      if (tspan.node().getComputedTextLength() > width) {
        line.pop()
        tspan.text(line.join(' '))
        line = [word]
        var currentLineHeight = words.length === sumLineNumber - 1 ? -Math.ceil(sumLineNumber / 2, -1) : 1
        tspan = text.append('tspan')
          .attr({
            'x': 0,
            'dy': (currentLineHeight * lineNumber * lineHeight) + 'rem'
          })
          .text(word)
      }
    }
  })
}
*/

function axisLabel () {
  var _width = 1
  var _height = 1
  var _fontSize = 14
  var _xLabel, _yLabel
  // var _textLength = 5
  var _margin = {top: 0, right: 0, bottom: 30, left: 20}

  function chart (selection) {
    if (_xLabel) {
      var xAxisLabel = selection.select('.x.axis').selectAll('.label').data(_xLabel)
        .enter().append('g')
        .attr({
          'class': 'label',
          'transform': 'translate(' + (_width / 2) + ', ' + _margin.bottom + ')'
        })
        .style({
          'font-size': _fontSize
        })

      xAxisLabel.append('text').text(d => { return d })
    }

    if (_yLabel) {
      var yAxisLabel = selection.select('.y.axis').selectAll('.label').data(_yLabel)
        .enter().append('g')
        .attr({
          'class': 'label',
          'transform': 'translate(' + (-_margin.left) + ', ' + (_height / 2) + ')'
        })
        .style({
          'font-size': _fontSize
        })

      yAxisLabel.append('text').text(d => { return d })
        .style('transform', 'rotate(-90deg)')
        // .call(wrap, _textLength, 0, 0)
    }
  }

  chart.fontSize = function (value) {
    if (!arguments.length) {
      return _fontSize
    }

    _fontSize = value
    return chart
  }

  chart.width = function (value) {
    if (!arguments.length) {
      return _width
    }

    _width = value
    return chart
  }

  chart.height = function (value) {
    if (!arguments.length) {
      return _height
    }

    _height = value
    return chart
  }

  chart.fontSize = function (value) {
    if (!arguments.length) {
      return _fontSize
    }

    _fontSize = value
    return chart
  }

  chart.data = function (xValue, yValue) {
    if (!arguments.length) {
      return _xLabel
    }

    _xLabel = xValue ? [xValue] : null
    _yLabel = yValue ? [yValue] : null
    return chart
  }

  chart.margin = function (value) {
    if (!arguments.length) {
      return _margin
    }

    _margin = value
    return chart
  }

  return chart
}

export default axisLabel
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import Markdown from 'rsg-components/Markdown';
import Props from 'rsg-components/Props';
import Methods from 'rsg-components/Methods';
import Examples from 'rsg-components/Examples';
import ReactComponentRenderer from 'rsg-components/ReactComponent/ReactComponentRenderer';

export default function ReactComponent({
	component,
	sidebar,
}) {
	const { name, pathLine, examples } = component;
	const { description, props, methods } = component.props;
	return (
		<ReactComponentRenderer
			name={name}
			pathLine={pathLine}
			description={description && <Markdown text={description} />}
			props={props && <Props props={props} />}
			methods={methods && <Methods methods={methods} />}
			examples={examples && <Examples examples={examples} name={name} />}
			sidebar={sidebar}
		/>
	);
}

ReactComponent.propTypes = {
	component: PropTypes.object.isRequired,
	sidebar: PropTypes.bool,
};
<commit_msg>Fix: Fix empty public methods table (#281)<commit_after>import React, { PropTypes } from 'react';
import Markdown from 'rsg-components/Markdown';
import Props from 'rsg-components/Props';
import Methods from 'rsg-components/Methods';
import Examples from 'rsg-components/Examples';
import ReactComponentRenderer from 'rsg-components/ReactComponent/ReactComponentRenderer';

export default function ReactComponent({
	component,
	sidebar,
}) {
	const { name, pathLine, examples } = component;
	const { description, props, methods } = component.props;
	return (
		<ReactComponentRenderer
			name={name}
			pathLine={pathLine}
			description={description && <Markdown text={description} />}
			props={props && <Props props={props} />}
			methods={methods && methods.length && <Methods methods={methods} />}
			examples={examples && <Examples examples={examples} name={name} />}
			sidebar={sidebar}
		/>
	);
}

ReactComponent.propTypes = {
	component: PropTypes.object.isRequired,
	sidebar: PropTypes.bool,
};
<|endoftext|>


<commit_before>/* global Calendar, Pusher */
{
  'use strict';

  class GuiderAppointmentsCalendar extends Calendar {
    start(el) {
      this.config = {
        columnFormat: 'ddd D/M',
        defaultView: 'agendaDay',
        header: {
          right: 'agendaDay agendaWeek month today jumpToDate prev,next'
        },
        nowIndicator: true,
        slotDuration: '00:30:00',
        eventTextColor: '#fff',
        eventSources: [
          {
            url: '/appointments?mine'
          },
          {
            url: '/bookable_slots?mine',
            className: 'fc-bgevent--bookable-slot',
            rendering: 'background'
          }
        ]
      };

      super.start(el);

      this.guiderId = this.$el.data('guider-id');
      this.setupPusher();
    }

    setupPusher() {
      const channel = Pusher.instance.subscribe('telephone_appointment_planner');
      channel.bind(`${this.guiderId}`, this.handlePushEvent.bind(this));
    }

    handlePushEvent(payload) {
      const modal = $('#guider-appointment-calendar-update');

      modal.find('.modal-body').html(`

Appointment updated

Customer: ${payload['customer_name']}

Date/Time: ${payload['start']}

Guider: ${payload['guider_name']}

      `);

      this.$el.fullCalendar('removeEvents');
      this.$el.fullCalendar('refetchEvents');
      modal.modal('show');
    }

    eventRender(event, element, view) {
      if (event.source.rendering == 'background') {
        return;
      }

      if (view.type === 'agendaDay') {
        element.find('.fc-title').html(`

            ${event.title} | Phone: ${event.phone} | Memorable word: ${event.memorable_word}
            `);
      }

      if (event.status.indexOf('cancelled') > -1) {
        element.addClass('fc-event--cancelled');
      }
    }
  }

  window.GOVUKAdmin.Modules.GuiderAppointmentsCalendar = GuiderAppointmentsCalendar;
}
<commit_msg>Add 'list' view to guider's appointments page<commit_after>/* global Calendar, Pusher */
{
  'use strict';

  class GuiderAppointmentsCalendar extends Calendar {
    start(el) {
      this.config = {
        columnFormat: 'ddd D/M',
        defaultView: 'agendaDay',
        header: {
          right: 'listWeek agendaDay agendaWeek month today jumpToDate prev,next'
        },
        buttonText: {
          listWeek: 'List'
        },
        nowIndicator: true,
        slotDuration: '00:30:00',
        eventTextColor: '#fff',
        eventSources: [
          {
            url: '/appointments?mine'
          },
          {
            url: '/bookable_slots?mine',
            className: 'fc-bgevent--bookable-slot',
            rendering: 'background'
          }
        ]
      };

      super.start(el);

      this.guiderId = this.$el.data('guider-id');
      this.setupPusher();
    }

    setupPusher() {
      const channel = Pusher.instance.subscribe('telephone_appointment_planner');
      channel.bind(`${this.guiderId}`, this.handlePushEvent.bind(this));
    }

    handlePushEvent(payload) {
      const modal = $('#guider-appointment-calendar-update');

      modal.find('.modal-body').html(`

Appointment updated

Customer: ${payload['customer_name']}

Date/Time: ${payload['start']}

Guider: ${payload['guider_name']}

      `);

      this.$el.fullCalendar('removeEvents');
      this.$el.fullCalendar('refetchEvents');
      modal.modal('show');
    }

    eventRender(event, element, view) {
      if (event.source.rendering == 'background') {
        return;
      }

      if (view.type === 'agendaDay') {
        element.find('.fc-title').html(`

            ${event.title} | Phone: ${event.phone} | Memorable word: ${event.memorable_word}
            `);
      }

      if (event.status.indexOf('cancelled') > -1) {
        element.addClass('fc-event--cancelled');
      }
    }
  }

  window.GOVUKAdmin.Modules.GuiderAppointmentsCalendar = GuiderAppointmentsCalendar;
}
<|endoftext|>


<commit_before><commit_msg>setup basic webpack dev server<commit_after>var config = require("./webpack.config.js");
var webpack = require("webpack");
var webpackDevServer = require("webpack-dev-server");
config.entry.unshift("webpack-dev-server/client?http://localhost:8080/", "webpack/hot/dev-server");
var compiler = webpack(config);
var server = new webpackDevServer(compiler, {
  hot: true
});
server.listen(8080);
<|endoftext|>


<commit_before>import { inject as service } from '@ember/service';
import { isEmpty } from '@ember/utils';
import Route from '@ember/routing/route';
import { set, get } from '@ember/object';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';
import ModalHelper from 'hospitalrun/mixins/modal-helper';
import SetupUserRole from 'hospitalrun/mixins/setup-user-role';
import UnauthorizedError from 'hospitalrun/utils/unauthorized-error';
import { DEFAULT_LANGUAGE } from 'hospitalrun/services/language-preference';

const TRANSITION_AFTER_LOGIN = 'transitionAfterLogin';

let ApplicationRoute = Route.extend(ApplicationRouteMixin, ModalHelper, SetupUserRole, {
  database: service(),
  config: service(),
  session: service(),
  languagePreference: service(),
  shouldSetupUserRole: true,

  actions: {
    closeModal() {
      this.render('empty', {
        outlet: 'modal',
        into: 'application'
      });
    },

    error(reason, transition) {
      if (reason instanceof UnauthorizedError) {
        let intl = this.get('intl');
        let message = intl.t('application.messages.sessionExpired');
        let session = get(this, 'session');
        let title = intl.t('application.titles.sessionExpired');
        if (!isEmpty(transition)) {
          let sessionStore = session.get('store');
          let sessionData = session.get('data');
          let transitionName;
          if (transition.targetName) {
            transitionName = transition.targetName;
          } else {
            transitionName = transition;
          }
          set(sessionData, TRANSITION_AFTER_LOGIN, transitionName);
          sessionStore.persist(sessionData).then(() =>{
            this.displayAlert(title, message, 'unauthorizeSession');
          });
        } else {
          this.displayAlert(title, message, 'unauthorizeSession');
        }
      } else {
        this._super(reason);
      }
    },

    /**
     * Render a modal using the specifed path and optionally set a model.
     * @param modalPath the path to use for the controller and template.
     * @param model (optional) the model to set on the controller for the modal.
     */
    openModal(modalPath, model) {
      if (model) {
        set(this.controllerFor(modalPath), 'model', model);
      }
      this.renderModal(modalPath);
    },

    unauthorizeSession() {
      let session = get(this, 'session');
      if (get(session, 'isAuthenticated')) {
        session.invalidate();
      }
    },

    /**
     * Update an open modal using the specifed model.
     * @param modalPath the path to use for the controller and template.
     * @param model (optional) the model to set on the controller for the modal.
     */
    updateModal(modalPath, model) {
      set(this.controllerFor(modalPath), 'model', model);
    }
  },

  model(params, transition) {
    let session = get(this, 'session');
    let isAuthenticated = session && get(session, 'isAuthenticated');
    let config = get(this, 'config');
    let database = get(this, 'database');

    return config.setup().then(() => {
      let standAlone = config.get('standAlone');
      if (transition.targetName !== 'finishgauth' && transition.targetName !== 'login') {
        set(this, 'shouldSetupUserRole', true);
        if (isAuthenticated || standAlone) {
          return database.setup()
            .catch(() => {
              // Error thrown indicates missing auth, so invalidate session.
              session.invalidate();
            });
        }
      } else if (transition.targetName === 'login' && standAlone) {
        return database.createUsersDB();
      } else if (transition.targetName === 'finishgauth') {
        set(this, 'shouldSetupUserRole', false);
      }
    });
  },

  afterModel() {
    set(this.controllerFor('application'), 'allowSearch', false);
    $('#apploading').remove();

    // this enables page reloading support
    this.get('languagePreference').loadUserLanguagePreference();
  },

  renderModal(template) {
    this.render(template, {
      into: 'application',
      outlet: 'modal'
    });
  },

  sessionAuthenticated() {
    if (get(this, 'shouldSetupUserRole') === true) {
      this.setupUserRole();
    }
    let session = get(this, 'session');
    let sessionData = session.get('data');
    let transitionAfterLogin = get(sessionData, TRANSITION_AFTER_LOGIN);
    if (!isEmpty(transitionAfterLogin)) {
      let sessionStore = session.get('store');
      set(sessionData, 'transitionAfterLogin', null);
      sessionStore.persist(sessionData).then(() =>{
        this.transitionTo(transitionAfterLogin);
      });
    } else {
      this._super();
    }

    this.get('languagePreference').loadUserLanguagePreference();
  },
  sessionInvalidated() {
    this._super();
    this.get('languagePreference').setApplicationLanguage(DEFAULT_LANGUAGE);
  }
});
export default ApplicationRoute;
<commit_msg>Set default locale to 'en' on application<commit_after>import { inject as service } from '@ember/service';
import { isEmpty } from '@ember/utils';
import Route from '@ember/routing/route';
import { set, get } from '@ember/object';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';
import ModalHelper from 'hospitalrun/mixins/modal-helper';
import SetupUserRole from 'hospitalrun/mixins/setup-user-role';
import UnauthorizedError from 'hospitalrun/utils/unauthorized-error';
import { DEFAULT_LANGUAGE } from 'hospitalrun/services/language-preference';

const TRANSITION_AFTER_LOGIN = 'transitionAfterLogin';

let ApplicationRoute = Route.extend(ApplicationRouteMixin, ModalHelper, SetupUserRole, {
  database: service(),
  config: service(),
  session: service(),
  languagePreference: service(),
  shouldSetupUserRole: true,

  actions: {
    closeModal() {
      this.render('empty', {
        outlet: 'modal',
        into: 'application'
      });
    },

    error(reason, transition) {
      if (reason instanceof UnauthorizedError) {
        let intl = this.get('intl');
        let message = intl.t('application.messages.sessionExpired');
        let session = get(this, 'session');
        let title = intl.t('application.titles.sessionExpired');
        if (!isEmpty(transition)) {
          let sessionStore = session.get('store');
          let sessionData = session.get('data');
          let transitionName;
          if (transition.targetName) {
            transitionName = transition.targetName;
          } else {
            transitionName = transition;
          }
          set(sessionData, TRANSITION_AFTER_LOGIN, transitionName);
          sessionStore.persist(sessionData).then(() =>{
            this.displayAlert(title, message, 'unauthorizeSession');
          });
        } else {
          this.displayAlert(title, message, 'unauthorizeSession');
        }
      } else {
        this._super(reason);
      }
    },

    /**
     * Render a modal using the specifed path and optionally set a model.
     * @param modalPath the path to use for the controller and template.
     * @param model (optional) the model to set on the controller for the modal.
     */
    openModal(modalPath, model) {
      if (model) {
        set(this.controllerFor(modalPath), 'model', model);
      }
      this.renderModal(modalPath);
    },

    unauthorizeSession() {
      let session = get(this, 'session');
      if (get(session, 'isAuthenticated')) {
        session.invalidate();
      }
    },

    /**
     * Update an open modal using the specifed model.
     * @param modalPath the path to use for the controller and template.
     * @param model (optional) the model to set on the controller for the modal.
     */
    updateModal(modalPath, model) {
      set(this.controllerFor(modalPath), 'model', model);
    }
  },

  beforeModel() {
    let intl = this.get('intl');
    intl.setLocale('en');
  },

  model(params, transition) {
    let session = get(this, 'session');
    let isAuthenticated = session && get(session, 'isAuthenticated');
    let config = get(this, 'config');
    let database = get(this, 'database');

    return config.setup().then(() => {
      let standAlone = config.get('standAlone');
      if (transition.targetName !== 'finishgauth' && transition.targetName !== 'login') {
        set(this, 'shouldSetupUserRole', true);
        if (isAuthenticated || standAlone) {
          return database.setup()
            .catch(() => {
              // Error thrown indicates missing auth, so invalidate session.
              session.invalidate();
            });
        }
      } else if (transition.targetName === 'login' && standAlone) {
        return database.createUsersDB();
      } else if (transition.targetName === 'finishgauth') {
        set(this, 'shouldSetupUserRole', false);
      }
    });
  },

  afterModel() {
    set(this.controllerFor('application'), 'allowSearch', false);
    $('#apploading').remove();

    // this enables page reloading support
    this.get('languagePreference').loadUserLanguagePreference();
  },

  renderModal(template) {
    this.render(template, {
      into: 'application',
      outlet: 'modal'
    });
  },

  sessionAuthenticated() {
    if (get(this, 'shouldSetupUserRole') === true) {
      this.setupUserRole();
    }
    let session = get(this, 'session');
    let sessionData = session.get('data');
    let transitionAfterLogin = get(sessionData, TRANSITION_AFTER_LOGIN);
    if (!isEmpty(transitionAfterLogin)) {
      let sessionStore = session.get('store');
      set(sessionData, 'transitionAfterLogin', null);
      sessionStore.persist(sessionData).then(() =>{
        this.transitionTo(transitionAfterLogin);
      });
    } else {
      this._super();
    }

    this.get('languagePreference').loadUserLanguagePreference();
  },
  sessionInvalidated() {
    this._super();
    this.get('languagePreference').setApplicationLanguage(DEFAULT_LANGUAGE);
  }
});
export default ApplicationRoute;
<|endoftext|>


<commit_before>"use strict";

module.exports = orients;

var I = require("ancient-oak");

var ORIENTS = I({
  "1000": { h: -1 },
  "0100": { v: -1 },
  "0010": { v:  1 },
  "0001": { h:  1 },
  "0111": { v: -1 },
  "1011": { h:  1 },
  "1101": { h: -1 },
  "1110": { v:  1 },
  "0011": { h:  1 },
  "1100": { h: -1 },
  "1010": { v:  1 },
  "0101": { v: -1 },
  "1001": { next: true },
  "0110": { next: true }
});

function orients (pixels) {
  return pixels.map(function (row, y) {
    return row.map(function (_, x) {
      return ORIENTS(code(pixels, x, y));
    });
  });
}

function code (pixels, x, y) {
  return [value(x - 1, y - 1),
          value(x    , y - 1),
          value(x - 1, y    ),
          value(x    , y    )].join("");

  function value (x, y) {
    return (pixels(y) || I([]))(x) || 0;
  }
}
<commit_msg>ORIENTS is not a constant, orient is a function.<commit_after>"use strict";

module.exports = orients;

var I = require("ancient-oak");

var orient = I({
  "1000": { h: -1 },
  "0100": { v: -1 },
  "0010": { v:  1 },
  "0001": { h:  1 },
  "0111": { v: -1 },
  "1011": { h:  1 },
  "1101": { h: -1 },
  "1110": { v:  1 },
  "0011": { h:  1 },
  "1100": { h: -1 },
  "1010": { v:  1 },
  "0101": { v: -1 },
  "1001": { next: true },
  "0110": { next: true }
});

function orients (pixels) {
  return pixels.map(function (row, y) {
    return row.map(function (_, x) {
      return orient(code(pixels, x, y));
    });
  });
}

function code (pixels, x, y) {
  return [value(x - 1, y - 1),
          value(x    , y - 1),
          value(x - 1, y    ),
          value(x    , y    )].join("");

  function value (x, y) {
    return (pixels(y) || I([]))(x) || 0;
  }
}
<|endoftext|>


<commit_before>// Generated by CoffeeScript 1.6.2
(function() {
  var createPool, createServer;

  createServer = require('connect').createServer;

  createPool = require('./pool').createPool;

  exports.createServer = function(config, options) {
    var pool, server, _ref, _ref1;

    if (options == null) {
      options = {};
    }
    if ((_ref = options.size) == null) {
      options.size = 3;
    }
    if ((_ref1 = options.idle) == null) {
      options.idle = 15 * 60 * 1000;
    }
    pool = createPool(config, options);
    server = createServer(pool.proxy);
    server.on('close', function() {
      return pool.quit();
    });
    return server;
  };

}).call(this);
<commit_msg>ditto<commit_after>// Generated by CoffeeScript 1.6.2
(function() {
  var createPool, createServer;

  createServer = require('http').createServer;

  createPool = require('./pool').createPool;

  exports.createServer = function(config, options) {
    var pool, _ref, _ref1;

    if (options == null) {
      options = {};
    }
    if ((_ref = options.size) == null) {
      options.size = 3;
    }
    if ((_ref1 = options.idle) == null) {
      options.idle = 15 * 60 * 1000;
    }
    pool = createPool(config, options);
    return createServer(pool.proxy);
  };

}).call(this);
<|endoftext|>