<commit_before>'use strict';

const Assert = require('chai').assert;
const request = require('../support/request');
const sdapi = require('../support/sdapi');
const github = require('../support/github');
const { defineSupportCode } = require('cucumber');

const TIMEOUT = 240 * 1000;

defineSupportCode(({ Before, Given, When, Then }) => {
    Before({
        tags: '@gitflow',
        timeout: TIMEOUT
    }, function hook() {
        this.branch = 'darrenBranch';
        this.repoOrg = this.testOrg;
        this.repoName = 'functional-git';

        // Reset shared information
        this.pullRequestNumber = null;
        this.pipelineId = null;

        return request({ // TODO : perform this in the before-hook for all func tests
            method: 'GET',
            url: `${this.instance}/${this.namespace}/auth/token?api_token=${this.apiToken}`,
            followAllRedirects: true,
            json: true
        }).then((response) => {
            this.jwt = response.body.token;
        }).then(() =>
            github.cleanUpRepository(this.gitToken, this.branch, this.repoOrg,
                this.repoName)
        );
    });

    Given(/^an existing pipeline$/, {
        timeout: TIMEOUT
    }, function step() {
        return request({
            uri: `${this.instance}/${this.namespace}/pipelines`,
            method: 'POST',
            auth: {
                bearer: this.jwt
            },
            body: {
                checkoutUrl: `git@${this.scmHostname}:${this.repoOrg}/${this.repoName}.git#master`
            },
            json: true
        }).then((response) => {
            Assert.oneOf(response.statusCode, [409, 201]);

            if (response.statusCode === 201) {
                this.pipelineId = response.body.id;
            } else {
                const str = response.body.message;
                const id = str.split(': ')[1];

                this.pipelineId = id;
            }
        });
    });

    Given(/^an existing pull request targeting the pipeline's branch$/, {
        timeout: TIMEOUT
    }, function step() {
        const branch = this.branch;
        const token = this.gitToken;

        return github.createBranch(token, branch, this.repoOrg, this.repoName)
            .then(() => github.createFile(token, branch, this.repoOrg, this.repoName))
            .then(() =>
                github.createPullRequest(token, branch, this.repoOrg, this.repoName)
            )
            .then((data) => {
                this.pullRequestNumber = data.number;
                this.sha = data.head.sha;
            })
            .catch((err) => {
                // throws an error if a PR already exists, so this is fine
                Assert.strictEqual(err.code, 422);
            });
    });

    When(/^a pull request is opened$/, { timeout: TIMEOUT }, function step() {
        const branch = this.branch;
        const token = this.gitToken;

        return github.createBranch(token, branch, this.repoOrg, this.repoName)
            .then(() => github.createFile(token, branch, this.repoOrg, this.repoName))
            .then(() =>
                github.createPullRequest(token, branch, this.repoOrg, this.repoName)
            )
            .then((data) => {
                this.pullRequestNumber = data.number;
                this.sha = data.head.sha;
            });
    });

    When(/^it is targeting the pipeline's branch$/, () => null);

    When(/^the pull request is closed$/, {
        timeout: TIMEOUT
    }, function step() {
        return this.promiseToWait(3) // Wait for the build to be enabled before moving forward
            .then(() =>
                sdapi.searchForBuild({
                    instance: this.instance,
                    pipelineId: this.pipelineId,
                    pullRequestNumber: this.pullRequestNumber,
                    sha: this.sha,
                    desiredStatus: ['RUNNING', 'SUCCESS', 'FAILURE']
                })
            ).then((buildData) => {
                this.previousBuildId = buildData.id;
            }).then(() => github.closePullRequest(this.gitToken, this.repoOrg, this.repoName,
                this.pullRequestNumber)
            );
    });

    When(/^new changes are pushed to that pull request$/, {
        timeout: TIMEOUT
    }, function step() {
        return this.promiseToWait(3) // Find & save the previous build
            .then(() =>
                sdapi.searchForBuild({
                    instance: this.instance,
                    pipelineId: this.pipelineId,
                    pullRequestNumber: this.pullRequestNumber,
                    sha: this.sha,
                    desiredStatus: ['QUEUED', 'RUNNING', 'SUCCESS', 'FAILURE']
                }).then((buildData) => {
                    this.previousBuildId = buildData.id;
                })
            )
            .then(() => github.createFile(this.gitToken, this.branch, this.repoOrg,
                this.repoName));
    });

    When(/^a new commit is pushed$/, () => null);

    When(/^it is against the pipeline's branch$/, { timeout: TIMEOUT }, function step() {
        this.testBranch = 'master';

        return github.createFile(this.gitToken, this.testBranch, this.repoOrg, this.repoName);
    });

    Then(/^a new build from `main` should be created to test that change$/, {
        timeout: TIMEOUT
    }, function step() {
        return this.promiseToWait(8)
            .then(() => sdapi.searchForBuild({
                instance: this.instance,
                pipelineId: this.pipelineId,
                pullRequestNumber: this.pullRequestNumber
            }))
            .then((data) => {
                const build = data;

                Assert.oneOf(build.status, ['QUEUED', 'RUNNING', 'SUCCESS']);
                this.jobId = build.jobId;
            });
    });

    Then(/^the build should know they are in a pull request/, function step() {
        return request({
            json: true,
            method: 'GET',
            uri: `${this.instance}/${this.namespace}/jobs/${this.jobId}`
        })
            .then((response) => {
                Assert.strictEqual(response.statusCode, 200);
                Assert.match(response.body.name, /^PR-(.*)$/);
            });
    });

    Then(/^any existing builds should be stopped$/, {
        timeout: TIMEOUT
    }, function step() {
        const desiredStatus = ['ABORTED', 'SUCCESS'];

        return sdapi.waitForBuildStatus({
            buildId: this.previousBuildId,
            instance: this.instance,
            desiredStatus
        }).then((buildData) => {
            // TODO: save the status so the next step can verify the github status
            Assert.oneOf(buildData.status, desiredStatus);
        });
    });

    Then(/^the GitHub status should be updated to reflect the build's status$/, function step() {
        return github.getStatus(this.gitToken, this.repoOrg, this.repoName, this.sha)
            .then((data) => {
                Assert.oneOf(data.state, ['success', 'pending']);
            });
    });
});
<commit_msg>fix: bump the wait time<commit_after>'use strict';

const Assert = require('chai').assert;
const request = require('../support/request');
const sdapi = require('../support/sdapi');
const github = require('../support/github');
const { defineSupportCode } = require('cucumber');

const TIMEOUT = 240 * 1000;

defineSupportCode(({ Before, Given, When, Then }) => {
    Before({
        tags: '@gitflow',
        timeout: TIMEOUT
    }, function hook() {
        this.branch = 'darrenBranch';
        this.repoOrg = this.testOrg;
        this.repoName = 'functional-git';

        // Reset shared information
        this.pullRequestNumber = null;
        this.pipelineId = null;

        return request({ // TODO : perform this in the before-hook for all func tests
            method: 'GET',
            url: `${this.instance}/${this.namespace}/auth/token?api_token=${this.apiToken}`,
            followAllRedirects: true,
            json: true
        }).then((response) => {
            this.jwt = response.body.token;
        }).then(() =>
            github.cleanUpRepository(this.gitToken, this.branch, this.repoOrg,
                this.repoName)
        );
    });

    Given(/^an existing pipeline$/, {
        timeout: TIMEOUT
    }, function step() {
        return request({
            uri: `${this.instance}/${this.namespace}/pipelines`,
            method: 'POST',
            auth: {
                bearer: this.jwt
            },
            body: {
                checkoutUrl: `git@${this.scmHostname}:${this.repoOrg}/${this.repoName}.git#master`
            },
            json: true
        }).then((response) => {
            Assert.oneOf(response.statusCode, [409, 201]);

            if (response.statusCode === 201) {
                this.pipelineId = response.body.id;
            } else {
                const str = response.body.message;
                const id = str.split(': ')[1];

                this.pipelineId = id;
            }
        });
    });

    Given(/^an existing pull request targeting the pipeline's branch$/, {
        timeout: TIMEOUT
    }, function step() {
        const branch = this.branch;
        const token = this.gitToken;

        return github.createBranch(token, branch, this.repoOrg, this.repoName)
            .then(() => github.createFile(token, branch, this.repoOrg, this.repoName))
            .then(() =>
                github.createPullRequest(token, branch, this.repoOrg, this.repoName)
            )
            .then((data) => {
                this.pullRequestNumber = data.number;
                this.sha = data.head.sha;
            })
            .catch((err) => {
                // throws an error if a PR already exists, so this is fine
                Assert.strictEqual(err.code, 422);
            });
    });

    When(/^a pull request is opened$/, { timeout: TIMEOUT }, function step() {
        const branch = this.branch;
        const token = this.gitToken;

        return github.createBranch(token, branch, this.repoOrg, this.repoName)
            .then(() => github.createFile(token, branch, this.repoOrg, this.repoName))
            .then(() =>
                github.createPullRequest(token, branch, this.repoOrg, this.repoName)
            )
            .then((data) => {
                this.pullRequestNumber = data.number;
                this.sha = data.head.sha;
            });
    });

    When(/^it is targeting the pipeline's branch$/, () => null);

    When(/^the pull request is closed$/, {
        timeout: TIMEOUT
    }, function step() {
        return this.promiseToWait(3) // Wait for the build to be enabled before moving forward
            .then(() =>
                sdapi.searchForBuild({
                    instance: this.instance,
                    pipelineId: this.pipelineId,
                    pullRequestNumber: this.pullRequestNumber,
                    sha: this.sha,
                    desiredStatus: ['RUNNING', 'SUCCESS', 'FAILURE']
                })
            ).then((buildData) => {
                this.previousBuildId = buildData.id;
            }).then(() => github.closePullRequest(this.gitToken, this.repoOrg, this.repoName,
                this.pullRequestNumber)
            );
    });

    When(/^new changes are pushed to that pull request$/, {
        timeout: TIMEOUT
    }, function step() {
        return this.promiseToWait(15) // Find & save the previous build
            .then(() =>
                sdapi.searchForBuild({
                    instance: this.instance,
                    pipelineId: this.pipelineId,
                    pullRequestNumber: this.pullRequestNumber,
                    sha: this.sha,
                    desiredStatus: ['QUEUED', 'RUNNING', 'SUCCESS', 'FAILURE']
                }).then((buildData) => {
                    this.previousBuildId = buildData.id;
                })
            )
            .then(() => github.createFile(this.gitToken, this.branch, this.repoOrg,
                this.repoName));
    });

    When(/^a new commit is pushed$/, () => null);

    When(/^it is against the pipeline's branch$/, { timeout: TIMEOUT }, function step() {
        this.testBranch = 'master';

        return github.createFile(this.gitToken, this.testBranch, this.repoOrg, this.repoName);
    });

    Then(/^a new build from `main` should be created to test that change$/, {
        timeout: TIMEOUT
    }, function step() {
        return this.promiseToWait(8)
            .then(() => sdapi.searchForBuild({
                instance: this.instance,
                pipelineId: this.pipelineId,
                pullRequestNumber: this.pullRequestNumber
            }))
            .then((data) => {
                const build = data;

                Assert.oneOf(build.status, ['QUEUED', 'RUNNING', 'SUCCESS']);
                this.jobId = build.jobId;
            });
    });

    Then(/^the build should know they are in a pull request/, function step() {
        return request({
            json: true,
            method: 'GET',
            uri: `${this.instance}/${this.namespace}/jobs/${this.jobId}`
        })
            .then((response) => {
                Assert.strictEqual(response.statusCode, 200);
                Assert.match(response.body.name, /^PR-(.*)$/);
            });
    });

    Then(/^any existing builds should be stopped$/, {
        timeout: TIMEOUT
    }, function step() {
        const desiredStatus = ['ABORTED', 'SUCCESS'];

        return sdapi.waitForBuildStatus({
            buildId: this.previousBuildId,
            instance: this.instance,
            desiredStatus
        }).then((buildData) => {
            // TODO: save the status so the next step can verify the github status
            Assert.oneOf(buildData.status, desiredStatus);
        });
    });

    Then(/^the GitHub status should be updated to reflect the build's status$/, function step() {
        return github.getStatus(this.gitToken, this.repoOrg, this.repoName, this.sha)
            .then((data) => {
                Assert.oneOf(data.state, ['success', 'pending']);
            });
    });
});
<|endoftext|>


<commit_before>// 500px featured photos
const features = ["popular", "highest_rated", "upcoming",
  "editors", "fresh_today", "fresh_yesterday", "fresh_week"];

export default features;
<commit_msg>Code styling<commit_after>// 500px featured photos
const features = [
  "popular",
  "highest_rated",
  "upcoming",
  "editors",
  "fresh_today",
  "fresh_yesterday",
  "fresh_week"
];

export default features;
<|endoftext|>


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

class HelpCommand extends Command {
  constructor(bot) {
    super(bot);
    this.props.help = {
      name: 'help',
      description: 'you all need some help',
      usage: 'help [command]',
    };
    this.props.conf.aliases = ['support'];
  }
  run(msg, args) {
    let commandName = args[0];
    if (!commandName) {
      let commands = this.bot.commands;
      let commandsForEveryone = commands.filter(e => !e.conf.permLevel || e.conf.permLevel === 0);
      let commandsForAdmin = commands.filter(e => e.conf.permLevel === 1);
      let commandsForOwner = commands.filter(e => e.conf.permLevel === 2);

      let embed = new this.embed()
      .setColor('#84F139')
      .setTitle(`Commands List`)
      .setDescription(`Use \`${this.bot.prefix}help <command>\` for details\n\u200B`)
      .setFooter(this.bot.user.username, this.bot.user.avatarURL)
      .addField('__Public__', commandsForEveryone.map(command => {
        let help = command.help;
        return `\`${help.name}\`: ${help.summary || help.description}`;
      }).join('\n'));

      if (msg.client.permissions(msg) > 0 && commandsForAdmin.size) {
        embed.addField('__Admin__', commandsForAdmin.map(command => {
          let help = command.help;
          return `\`${help.name}\`: ${help.summary || help.description}`;
        }).join('\n'));
      }
      if (msg.client.permissions(msg) > 1 && commandsForOwner.size) {
        embed.addField('__Owner__', commandsForOwner.map(command => {
          let help = command.help;
          return `\`${help.name}\`: ${help.summary || help.description}`;
        }).join('\n'));
      }

      return msg.channel.sendEmbed(embed);
    } else if (commandName) {
      let command = this.bot.commands.get(commandName) || (this.bot.aliases.has(commandName) ? this.bot.commands.get(this.bot.aliases.get(commandName)) : null);
      if (!command) return this.commandError(msg, `Command \`${commandName}\` doesn't exist`);

      let embed = new this.embed()
      .setColor('#84F139')
      .setTitle(`Command  \`${command.help.name}\``)
      .setDescription(`${command.help.description || command.help.summary}\n\u200B`)
      .setFooter(this.bot.user.username, this.bot.user.avatarURL)
      .addField('Usage', [
        '```js',
        `${this.bot.prefix}${command.help.usage}`,
        '```',
      ].join('\n'));

      if (command.conf.aliases && command.conf.aliases.length) embed.addField('Aliases', command.conf.aliases.map(e => `\`${e}\``).join(', '), true);
      if (command.help.examples && command.help.examples.length) {
        embed.addField('Examples', command.help.examples.map(e => `\`${this.bot.prefix}${e}\``).join('\n'), true);
      }
      embed.addField('Permission', `${this._permLevelToWord(command.conf.permLevel)}\n\u200B`);

      return msg.channel.sendEmbed(embed);
    }
  }
}

module.exports = HelpCommand;
<commit_msg>Update Command: help - remove codeblock in command usage<commit_after>const Command = require('../Command');

class HelpCommand extends Command {
  constructor(bot) {
    super(bot);
    this.props.help = {
      name: 'help',
      description: 'you all need some help',
      usage: 'help [command]',
    };
    this.props.conf.aliases = ['support'];
  }
  run(msg, args) {
    let commandName = args[0];
    if (!commandName) {
      let commands = this.bot.commands;
      let commandsForEveryone = commands.filter(e => !e.conf.permLevel || e.conf.permLevel === 0);
      let commandsForAdmin = commands.filter(e => e.conf.permLevel === 1);
      let commandsForOwner = commands.filter(e => e.conf.permLevel === 2);

      let embed = new this.embed()
      .setColor('#84F139')
      .setTitle(`Commands List`)
      .setDescription(`Use \`${this.bot.prefix}help <command>\` for details\n\u200B`)
      .setFooter(this.bot.user.username, this.bot.user.avatarURL)
      .addField('__Public__', commandsForEveryone.map(command => {
        let help = command.help;
        return `\`${help.name}\`: ${help.summary || help.description}`;
      }).join('\n'));

      if (msg.client.permissions(msg) > 0 && commandsForAdmin.size) {
        embed.addField('__Admin__', commandsForAdmin.map(command => {
          let help = command.help;
          return `\`${help.name}\`: ${help.summary || help.description}`;
        }).join('\n'));
      }
      if (msg.client.permissions(msg) > 1 && commandsForOwner.size) {
        embed.addField('__Owner__', commandsForOwner.map(command => {
          let help = command.help;
          return `\`${help.name}\`: ${help.summary || help.description}`;
        }).join('\n'));
      }

      return msg.channel.sendEmbed(embed);
    } else if (commandName) {
      let command = this.bot.commands.get(commandName) || (this.bot.aliases.has(commandName) ? this.bot.commands.get(this.bot.aliases.get(commandName)) : null);
      if (!command) return this.commandError(msg, `Command \`${commandName}\` doesn't exist`);

      let embed = new this.embed()
      .setColor('#84F139')
      .setTitle(`Command  \`${command.help.name}\``)
      .setDescription(`${command.help.description || command.help.summary}\n\u200B`)
      .setFooter(this.bot.user.username, this.bot.user.avatarURL)
      .addField('Usage', `${this.bot.prefix}${command.help.usage}`);

      if (command.conf.aliases && command.conf.aliases.length) embed.addField('Aliases', command.conf.aliases.map(e => `\`${e}\``).join(', '), true);
      if (command.help.examples && command.help.examples.length) {
        embed.addField('Examples', command.help.examples.map(e => `\`${this.bot.prefix}${e}\``).join('\n'), true);
      }
      embed.addField('Permission', `${this._permLevelToWord(command.conf.permLevel)}\n\u200B`);

      return msg.channel.sendEmbed(embed);
    }
  }
}

module.exports = HelpCommand;
<|endoftext|>


<commit_before>// claslite.js
// Copyright 2010 Carnegie Institution for Science and Michael Geary
// Use under any Open Source license:
// http://www.opensource.org/licenses/

(function() {

	var app;
	var layout = {
		sidebarWidth: 350
	};

	var monthNames = [
		'January', 'February', 'March', 'April', 'May', 'June',
		'July', 'August', 'September', 'October', 'November', 'December'
	];
	S.extend( $.fn.mColorPicker.defaults, {
		imageFolder: 'images/mColorPicker/'
	});
	S.extend( $.fn.mColorPicker.init, {
		replace: '.color-picker',
		showLogo: false
	});

	$().ready( initUI );

	function initUI() {
		initVars();
		initTabs();
		initRangeInputs();
		initDateSelectors();
		initLegends();
		initSizer();
		resize();
		initMap();
		$('#outermost').show();
		resize();
	}

	function initVars() {
		app = {
			$window: $(window),
			$main: $('#main'),
			$tabs: $('#tabs'),
			$sidebarOuter: $('#sidebar-outer'),
			$sidebar: $('#sidebar'),
			$mapwrap: $('#mapwrap'),
			_: null
		};
	}

	function initTabs() {
		app.tabs = S.Tabs({
			parent: '#tabs',
			panels: '#sidebar',
			tabs: {
				location: 'Location',
				forestcover: 'Forest Cover',
				forestchange: 'Forest Change',
				help: 'Help'
			},
			click: function( id ) {
				//$('#sidebar').html( this.tabs[id] );
			}
		});

		app.tabs.select( 'location' );
	}

	function initRangeInputs() {
		$("input:range").rangeinput();
	}

	function initDateSelectors() {
		var options = [];
		for( var year = 2000;  year <= 2010;  ++year ) {
			for( var month = 1;  month <= 12;  ++month ) {
				options.push(
					'<option value="', year, '-', padDigits( month, 2 ), '">',
						monthNames[ month - 1 ], ' ', year,
					'</option>'
				);
			}
		}
		$('select.forestchange-date').html( options.join('') );
	}

	function padDigits( value, digits ) {
		return ( '' + ( value + 100000000 ) ).slice( -digits );
	}

	function initLegends() {
		addLegend( '#deforestation-legend' );
		addLegend( '#disturbance-legend' );
	}

	function addLegend( legend ) {
		var colors = [ '#FF0000', '#FF4400', '#FF8800', '#FFCC00', '#FFFF00' ];
		$.S(
			'
',
				colors.map( function( color, i ) {
					return S(
						'
',
						'
',
						'
',
							i == 0 ? 'Recent' : i == colors.length - 1 ? 'Oldest' : '',
						'
',
						'
',
						'
'
					)
				}).join(''),
			'
'
		).appendTo( legend );
	}

	function initMap() {
		app.map = new S.Map( app.$mapwrap );
		app.map.fitBounds( -26, -80, 5, -35 );
		// HACK FOR V2 MAPS API:
		setTimeout( function() {
			app.map.fitBounds( -26, -80, 5, -35 );
		}, 100 );
		// END HACK

		app.map.geoclick({
			form: '#location-search-form',
			input: '#location-search-input',
			list: '#location-results-list',
			onclick: function() {
				app.tabs.select( 'location' );
			}
		});

		app.map.addLayer({
			minZoom: 6,
			maxZoom: 14,
			//tiles: 'http://claslite.geary.joyeurs.com/tiles/peru_redd_2007_mosaic_frac_tif/{Z}/{X}/{Y}.png'
			tiles: 'http://claslite.geary.joyeurs.com/tiles/peru_redd_2009_peru_redd_forestcover_geotiff_rgb/{Z}/{X}/{Y}.png'
		});
	}

	function initSizer() {
		$(window).resize( resize );
	}

	function resize() {
		var ww = app.$window.width(), wh = app.$window.height();
		app.$main.css({ height: wh - app.$main.offset().top });
		app.$mapwrap.css({ width: ww - layout.sidebarWidth - 1 });
		app.map && app.map.resize();
	}

})();
<commit_msg>Zoom in on sample image temporarily<commit_after>// claslite.js
// Copyright 2010 Carnegie Institution for Science and Michael Geary
// Use under any Open Source license:
// http://www.opensource.org/licenses/

(function() {

	var app;
	var layout = {
		sidebarWidth: 350
	};

	var monthNames = [
		'January', 'February', 'March', 'April', 'May', 'June',
		'July', 'August', 'September', 'October', 'November', 'December'
	];
	S.extend( $.fn.mColorPicker.defaults, {
		imageFolder: 'images/mColorPicker/'
	});
	S.extend( $.fn.mColorPicker.init, {
		replace: '.color-picker',
		showLogo: false
	});

	$().ready( initUI );

	function initUI() {
		initVars();
		initTabs();
		initRangeInputs();
		initDateSelectors();
		initLegends();
		initSizer();
		resize();
		initMap();
		$('#outermost').show();
		resize();
	}

	function initVars() {
		app = {
			$window: $(window),
			$main: $('#main'),
			$tabs: $('#tabs'),
			$sidebarOuter: $('#sidebar-outer'),
			$sidebar: $('#sidebar'),
			$mapwrap: $('#mapwrap'),
			_: null
		};
	}

	function initTabs() {
		app.tabs = S.Tabs({
			parent: '#tabs',
			panels: '#sidebar',
			tabs: {
				location: 'Location',
				forestcover: 'Forest Cover',
				forestchange: 'Forest Change',
				help: 'Help'
			},
			click: function( id ) {
				//$('#sidebar').html( this.tabs[id] );
			}
		});

		app.tabs.select( 'location' );
	}

	function initRangeInputs() {
		$("input:range").rangeinput();
	}

	function initDateSelectors() {
		var options = [];
		for( var year = 2000;  year <= 2010;  ++year ) {
			for( var month = 1;  month <= 12;  ++month ) {
				options.push(
					'<option value="', year, '-', padDigits( month, 2 ), '">',
						monthNames[ month - 1 ], ' ', year,
					'</option>'
				);
			}
		}
		$('select.forestchange-date').html( options.join('') );
	}

	function padDigits( value, digits ) {
		return ( '' + ( value + 100000000 ) ).slice( -digits );
	}

	function initLegends() {
		addLegend( '#deforestation-legend' );
		addLegend( '#disturbance-legend' );
	}

	function addLegend( legend ) {
		var colors = [ '#FF0000', '#FF4400', '#FF8800', '#FFCC00', '#FFFF00' ];
		$.S(
			'
',
				colors.map( function( color, i ) {
					return S(
						'
',
						'
',
						'
',
							i == 0 ? 'Recent' : i == colors.length - 1 ? 'Oldest' : '',
						'
',
						'
',
						'
'
					)
				}).join(''),
			'
'
		).appendTo( legend );
	}

	function initMap() {
		//var bounds = [ -26, -80, 5, -35 ];
		var bounds = [ -13.186159, -70.962916, -10.960249, -68.705582 ];
		app.map = new S.Map( app.$mapwrap );
		app.map.fitBounds.apply( app.map, bounds );
		// HACK FOR V2 MAPS API:
		setTimeout( function() {
			app.map.fitBounds.apply( app.map, bounds );
		}, 100 );
		// END HACK

		app.map.geoclick({
			form: '#location-search-form',
			input: '#location-search-input',
			list: '#location-results-list',
			onclick: function() {
				app.tabs.select( 'location' );
			}
		});

		app.map.addLayer({
			minZoom: 6,
			maxZoom: 14,
			//tiles: 'http://claslite.geary.joyeurs.com/tiles/peru_redd_2007_mosaic_frac_tif/{Z}/{X}/{Y}.png'
			tiles: 'http://claslite.geary.joyeurs.com/tiles/peru_redd_2009_peru_redd_forestcover_geotiff_rgb/{Z}/{X}/{Y}.png'
		});
	}

	function initSizer() {
		$(window).resize( resize );
	}

	function resize() {
		var ww = app.$window.width(), wh = app.$window.height();
		app.$main.css({ height: wh - app.$main.offset().top });
		app.$mapwrap.css({ width: ww - layout.sidebarWidth - 1 });
		app.map && app.map.resize();
	}

})();
<|endoftext|>


<commit_before><commit_msg>Add playlist features<commit_after><|endoftext|>


<commit_before>var RTCPeerConnection = window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
var RTCSessionDescription = window.RTCSessionDescription || window.mozRTCSessionDescription;
navigator.getUserMedia = navigator.getUserMedia ||
                         navigator.webkitGetUserMedia ||
                         navigator.mozGetUserMedia ||
                         navigator.msGetUserMedia;
var config = {
  "iceServers": [{"urls": "stun:stun.l.google.com:19302"}]
};
var pc = new RTCPeerConnection(config);

var sora = new Sora({"host": "127.0.0.1", "port": 5000, "path": "signaling"});
var connection = sora.connection(onSuccess, onError);

function onSuccess() {
  connection.connect({"role": "upstream", "channelId": "sora"});
  navigator.getUserMedia({video: true, audio: true}, function(stream) {
    var localVideo = document.getElementById("local-video");
    localVideo.src = window.URL.createObjectURL(stream);
    localVideo.play();
    connection.offer(function(message) {
      pc.addStream(stream);
      pc.setRemoteDescription(new RTCSessionDescription(message), function() {
        pc.createAnswer(function(answer) {
          pc.setLocalDescription(answer, function() {
            pc.onicecandidate = function(event) {
              if (event.candidate === null) {
                connection.candidate(pc.localDescription.sdp);
              }
            }
          }, onError);
        }, onError);
      }, onError);
    });
  }, onError);
}

function onError(error) {
  console.warn(error);
}
<commit_msg>順番問題を修正する<commit_after>var RTCPeerConnection = window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
var RTCSessionDescription = window.RTCSessionDescription || window.mozRTCSessionDescription;
navigator.getUserMedia = navigator.getUserMedia ||
                         navigator.webkitGetUserMedia ||
                         navigator.mozGetUserMedia ||
                         navigator.msGetUserMedia;
var config = {
  "iceServers": [{"urls": "stun:stun.l.google.com:19302"}]
};
var pc = new RTCPeerConnection(config);

var sora = new Sora({"host": "127.0.0.1", "port": 5000, "path": "signaling"});
var connection = sora.connection(onSuccess, onError);

function onSuccess() {
  navigator.getUserMedia({video: true, audio: true}, function(stream) {
    var localVideo = document.getElementById("local-video");
    localVideo.src = window.URL.createObjectURL(stream);
    localVideo.play();
    connection.connect({"role": "upstream", "channelId": "sora"});
    connection.offer(function(message) {
      pc.addStream(stream);
      pc.setRemoteDescription(new RTCSessionDescription(message), function() {
        pc.createAnswer(function(answer) {
          pc.setLocalDescription(answer, function() {
            pc.onicecandidate = function(event) {
              if (event.candidate === null) {
                connection.candidate(pc.localDescription.sdp);
              }
            }
          }, onError);
        }, onError);
      }, onError);
    });
  }, onError);
}

function onError(error) {
  console.warn(error);
}
<|endoftext|>


<commit_before>'use strict';

define(['ol', 'toolbar', 'layermanager', 'geojson', 'sidebar', 'query', 'search', 'print', 'permalink', 'measure', 'geolocation', 'api', 'cesium', 'ows', 'cesiumjs', 'bootstrap', 'datasource_selector'],

    function(ol, toolbar, layermanager, geojson) {
        var module = angular.module('hs', [
            'hs.toolbar',
            'hs.layermanager',
            'hs.query',
            'hs.search', 'hs.print', 'hs.permalink',
            'hs.datasource_selector',
            'hs.geolocation',
            'hs.cesium',
            'hs.sidebar',
            'hs.ows'
        ]);

        module.directive('hs', ['hs.map.service', 'Core', '$compile', '$timeout', function(OlMap, Core, $compile, $timeout) {
            return {
                templateUrl: hsl_path + 'hslayers.html',
                link: function(scope, element) {
                    angular.element('.page-content', element).append($compile('

')(scope));
                    $timeout(function() {
                        Core.fullScreenMap(element)
                    }, 0);
                }
            };
        }]);

        module.directive('hs.aboutproject', function() {
            function link(scope,element,attrs) {
                setTimeout(function(){
                    $('#about-dialog').modal('show');
                }, 1500);
            }
            return {
                templateUrl: './about.html?bust=' + gitsha,
                link: link
            };
        });

        function getHostname() {
            var url = window.location.href
            var urlArr = url.split("/");
            var domain = urlArr[2];
            return urlArr[0] + "//" + domain;
        };

        module.value('config', {
            terrain_provider: 'http://gis.lesprojekt.cz/cts/tilesets/rostenice_dmp1g/',
            terrain_providers: [{
                title: 'Local terrain',
                url: 'http://gis.lesprojekt.cz/cts/tilesets/rostenice_dmp1g/',
                active: true
            }, {
                title: 'EU-DEM',
                url: 'https://assets.agi.com/stk-terrain/v1/tilesets/world/tiles',
                active: false
            }],
            default_layers: [
                new ol.layer.Tile({
                    source: new ol.source.OSM(),
                    title: "OpenStreetMap",
                    base: true,
                    visible: false,
                    minimumTerrainLevel: 15
                }),
               new ol.layer.Tile({
                    title: "Open-Land-Use (WMS)",
                    source: new ol.source.TileWMS({
                        url: 'http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/dima/maps/olu/openlandusemap.map',
                        params: {
                            LAYERS: 'olu_bbox_srid',
                            FORMAT: "image/png",
                            INFO_FORMAT: "text/html",
                            minimumTerrainLevel: 15
                        },
                        crossOrigin: null
                    }),
                    legends: ['http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/dima/maps/3d_olu/openlandusemap.map&service=WMS&request=GetLegendGraphic&layer=olu_bbox_srid&version=1.3.0&format=image/png&sld_version=1.1.0'],
                    maxResolution: 8550,
                    visible: false,
                    opacity: 0.7
                }),
                new ol.layer.Tile({
                    title: "Slope (in degrees)",
                    source: new ol.source.TileWMS({
                        url: 'http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/dima/maps/3d_olu/rostenice.map',
                        params: {
                            LAYERS: 'slope',
                            FORMAT: "image/png",
                            INFO_FORMAT: "text/html",
                            minimumTerrainLevel: 14
                        },
                        crossOrigin: null
                    }),
                    legends: ['http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/dima/maps/3d_olu/rostenice.map&service=WMS&request=GetLegendGraphic&layer=slope&version=1.3.0&format=image/png&sld_version=1.1.0'],
                    maxResolution: 8550,
                    visible: false,
                    opacity: 0.7
                }),
                new ol.layer.Tile({
                    title: "Slope orientation",
                    source: new ol.source.TileWMS({
                        url: 'http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/dima/maps/3d_olu/rostenice.map',
                        params: {
                            LAYERS: 'orientation',
                            FORMAT: "image/png",
                            INFO_FORMAT: "text/html",
                            minimumTerrainLevel: 14
                        },
                        crossOrigin: null
                    }),
                    legends: ['http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/dima/maps/3d_olu/rostenice.map&service=WMS&request=GetLegendGraphic&layer=orientation&version=1.3.0&format=image/png&sld_version=1.1.0'],
                    maxResolution: 8550,
                    visible: false,
                    opacity: 0.7
                }),
                new ol.layer.Tile({
                    title: "Normalized difference vegetation index (NDVI) ",
                    source: new ol.source.TileWMS({
                        url: 'http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/dima/maps/3d_olu/rostenice.map',
                        params: {
                            LAYERS: 'ndvi_rostenice',
                            FORMAT: "image/png",
                            INFO_FORMAT: "text/html",
                            minimumTerrainLevel: 14
                        },
                        crossOrigin: null
                    }),
                    legends: ['http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/dima/maps/3d_olu/rostenice.map&service=WMS&request=GetLegendGraphic&layer=ndvi_rostenice&version=1.3.0&format=image/png&sld_version=1.1.0'],
                    maxResolution: 8550,
                    visible: false,
                    opacity: 0.7
                }),
                new ol.layer.Tile({
                    title: "Compound topographic index (CTI)",
                    source: new ol.source.TileWMS({
                        url: 'http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/dima/maps/3d_olu/rostenice.map',
                        params: {
                            LAYERS: 'cti_rostenice',
                            FORMAT: "image/png",
                            INFO_FORMAT: "text/html",
                            minimumTerrainLevel: 14
                        },
                        crossOrigin: null
                    }),
                    legends: ['http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/dima/maps/3d_olu/rostenice.map&service=WMS&request=GetLegendGraphic&layer=cti_rostenice&version=1.3.0&format=image/png&sld_version=1.1.0'],
                    maxResolution: 8550,
                    visible: false,
                    opacity: 0.7
                }),
                new ol.layer.Tile({
                    title: "Yield potential Rostenice",
                    source: new ol.source.TileWMS({
                        url: 'http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/dima/maps/3d_olu/rostenice.map',
                        params: {
                            LAYERS: 'yield_potential',
                            FORMAT: "image/png",
                            INFO_FORMAT: "text/html",
                            minimumTerrainLevel: 14
                        },
                        crossOrigin: null
                    }),
                    legends: ['http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/dima/maps/3d_olu/rostenice.map&service=WMS&request=GetLegendGraphic&layer=yield_potential&version=1.3.0&format=image/png&sld_version=1.1.0'],
                    maxResolution: 8550,
                    visible: true,
                    opacity: 0.7
                }),
                new ol.layer.Tile({
                    title: "Machinery tracklines",
                    source: new ol.source.TileWMS({
                        url: 'http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/dima/maps/3d_olu/rostenice.map',
                        params: {
                            LAYERS: 'machinery_tracklines_average_slope',
                            FORMAT: "image/png",
                            INFO_FORMAT: "text/html",
                            minimumTerrainLevel: 14
                        },
                        crossOrigin: null
                    }),
                    legends: ['http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/dima/maps/3d_olu/rostenice.map&service=WMS&request=GetLegendGraphic&layer=machinery_tracklines_average_slope&version=1.3.0&format=image/png&sld_version=1.1.0'],
                    maxResolution: 8550,
                    visible: true,
                    opacity: 0.8
                })

            ],
            project_name: 'erra/map',
            datasources: [
                {
                    title: "Datasets",
                    url: "http://otn-dev.intrasoft-intl.com/otnServices-1.0/platform/ckanservices/datasets",
                    language: 'eng',
                    type: "ckan",
                    download: true
                }, {
                    title: "Services",
                    url: "http://cat.ccss.cz/csw/",
                    language: 'eng',
                    type: "micka",
                    code_list_url: 'http://www.whatstheplan.eu/php/metadata/util/codelists.php?_dc=1440156028103&language=eng&page=1&start=0&limit=25&filter=%5B%7B%22property%22%3A%22label%22%7D%5D'
                }, {
                    title: "Hub layers",
                    url: "http://opentnet.eu/php/metadata/csw/",
                    language: 'eng',
                    type: "micka",
                    code_list_url: 'http://opentnet.eu/php/metadata/util/codelists.php?_dc=1440156028103&language=eng&page=1&start=0&limit=25&filter=%5B%7B%22property%22%3A%22label%22%7D%5D'
                }
            ],
            hostname: {
                "default": {
                    "title": "Default",
                    "type": "default",
                    "editable": false,
                    "url": getHostname()
                }
            },
            'catalogue_url': "/php/metadata/csw",
            'compositions_catalogue_url': "/php/metadata/csw",
            status_manager_url: '/wwwlibs/statusmanager2/index.php',
            default_view: new ol.View({
                center: ol.proj.transform([16.8290202, 49.0751890], 'EPSG:4326', 'EPSG:3857'), //Latitude longitude    to Spherical Mercator
                zoom: 15,
                units: "m"
            })
        });

        module.controller('Main', ['$scope', '$compile', '$element', 'Core', 'hs.map.service', 'config',
            function($scope, $compile, $element, Core, OlMap, config) {
                if (console) console.log("Main called");
                $scope.hsl_path = hsl_path; //Get this from hslayers.js file
                $scope.Core = Core;

                Core.singleDatasources = true;
                Core.panelEnabled('compositions', true);
                Core.panelEnabled('status_creator', false);

                $scope.$on('infopanel.updated', function(event) {});

                function createAboutDialog() {
                    var el = angular.element('

');
                    $("#hs-dialog-area").append(el);
                    $compile(el)($scope);
                }
                createAboutDialog();
            }
        ]);

        return module;
    });
<commit_msg>New terrain layer for rostenice<commit_after>'use strict';

define(['ol', 'toolbar', 'layermanager', 'geojson', 'sidebar', 'query', 'search', 'print', 'permalink', 'measure', 'geolocation', 'api', 'cesium', 'ows', 'cesiumjs', 'bootstrap', 'datasource_selector'],

    function(ol, toolbar, layermanager, geojson) {
        var module = angular.module('hs', [
            'hs.toolbar',
            'hs.layermanager',
            'hs.query',
            'hs.search', 'hs.print', 'hs.permalink',
            'hs.datasource_selector',
            'hs.geolocation',
            'hs.cesium',
            'hs.sidebar',
            'hs.ows'
        ]);

        module.directive('hs', ['hs.map.service', 'Core', '$compile', '$timeout', function(OlMap, Core, $compile, $timeout) {
            return {
                templateUrl: hsl_path + 'hslayers.html',
                link: function(scope, element) {
                    angular.element('.page-content', element).append($compile('

')(scope));
                    $timeout(function() {
                        Core.fullScreenMap(element)
                    }, 0);
                }
            };
        }]);

        module.directive('hs.aboutproject', function() {
            function link(scope,element,attrs) {
                setTimeout(function(){
                    $('#about-dialog').modal('show');
                }, 1500);
            }
            return {
                templateUrl: './about.html?bust=' + gitsha,
                link: link
            };
        });

        function getHostname() {
            var url = window.location.href
            var urlArr = url.split("/");
            var domain = urlArr[2];
            return urlArr[0] + "//" + domain;
        };

        module.value('config', {
            terrain_provider: 'http://gis.lesprojekt.cz/cts/tilesets/rostenice_dmp1g/',
            terrain_providers: [{
                title: 'Local surface model',
                url: 'http://gis.lesprojekt.cz/cts/tilesets/rostenice_dmp1g/',
                active: true
            }, {
                title: 'Local terrain model',
                url: 'http://gis.lesprojekt.cz/cts/tilesets/rostenice_dmr5g/',
                active: false
            }, {
                title: 'EU-DEM',
                url: 'https://assets.agi.com/stk-terrain/v1/tilesets/world/tiles',
                active: false
            }],
            default_layers: [
                new ol.layer.Tile({
                    source: new ol.source.OSM(),
                    title: "OpenStreetMap",
                    base: true,
                    visible: false,
                    minimumTerrainLevel: 15
                }),
               new ol.layer.Tile({
                    title: "Open-Land-Use (WMS)",
                    source: new ol.source.TileWMS({
                        url: 'http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/dima/maps/olu/openlandusemap.map',
                        params: {
                            LAYERS: 'olu_bbox_srid',
                            FORMAT: "image/png",
                            INFO_FORMAT: "text/html",
                            minimumTerrainLevel: 15
                        },
                        crossOrigin: null
                    }),
                    legends: ['http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/dima/maps/3d_olu/openlandusemap.map&service=WMS&request=GetLegendGraphic&layer=olu_bbox_srid&version=1.3.0&format=image/png&sld_version=1.1.0'],
                    maxResolution: 8550,
                    visible: false,
                    opacity: 0.7
                }),
                new ol.layer.Tile({
                    title: "Slope (in degrees)",
                    source: new ol.source.TileWMS({
                        url: 'http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/dima/maps/3d_olu/rostenice.map',
                        params: {
                            LAYERS: 'slope',
                            FORMAT: "image/png",
                            INFO_FORMAT: "text/html",
                            minimumTerrainLevel: 14
                        },
                        crossOrigin: null
                    }),
                    legends: ['http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/dima/maps/3d_olu/rostenice.map&service=WMS&request=GetLegendGraphic&layer=slope&version=1.3.0&format=image/png&sld_version=1.1.0'],
                    maxResolution: 8550,
                    visible: false,
                    opacity: 0.7
                }),
                new ol.layer.Tile({
                    title: "Slope orientation",
                    source: new ol.source.TileWMS({
                        url: 'http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/dima/maps/3d_olu/rostenice.map',
                        params: {
                            LAYERS: 'orientation',
                            FORMAT: "image/png",
                            INFO_FORMAT: "text/html",
                            minimumTerrainLevel: 14
                        },
                        crossOrigin: null
                    }),
                    legends: ['http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/dima/maps/3d_olu/rostenice.map&service=WMS&request=GetLegendGraphic&layer=orientation&version=1.3.0&format=image/png&sld_version=1.1.0'],
                    maxResolution: 8550,
                    visible: false,
                    opacity: 0.7
                }),
                new ol.layer.Tile({
                    title: "Normalized difference vegetation index (NDVI) ",
                    source: new ol.source.TileWMS({
                        url: 'http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/dima/maps/3d_olu/rostenice.map',
                        params: {
                            LAYERS: 'ndvi_rostenice',
                            FORMAT: "image/png",
                            INFO_FORMAT: "text/html",
                            minimumTerrainLevel: 14
                        },
                        crossOrigin: null
                    }),
                    legends: ['http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/dima/maps/3d_olu/rostenice.map&service=WMS&request=GetLegendGraphic&layer=ndvi_rostenice&version=1.3.0&format=image/png&sld_version=1.1.0'],
                    maxResolution: 8550,
                    visible: false,
                    opacity: 0.7
                }),
                new ol.layer.Tile({
                    title: "Compound topographic index (CTI)",
                    source: new ol.source.TileWMS({
                        url: 'http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/dima/maps/3d_olu/rostenice.map',
                        params: {
                            LAYERS: 'cti_rostenice',
                            FORMAT: "image/png",
                            INFO_FORMAT: "text/html",
                            minimumTerrainLevel: 14
                        },
                        crossOrigin: null
                    }),
                    legends: ['http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/dima/maps/3d_olu/rostenice.map&service=WMS&request=GetLegendGraphic&layer=cti_rostenice&version=1.3.0&format=image/png&sld_version=1.1.0'],
                    maxResolution: 8550,
                    visible: false,
                    opacity: 0.7
                }),
                new ol.layer.Tile({
                    title: "Yield potential Rostenice",
                    source: new ol.source.TileWMS({
                        url: 'http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/dima/maps/3d_olu/rostenice.map',
                        params: {
                            LAYERS: 'yield_potential',
                            FORMAT: "image/png",
                            INFO_FORMAT: "text/html",
                            minimumTerrainLevel: 14
                        },
                        crossOrigin: null
                    }),
                    legends: ['http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/dima/maps/3d_olu/rostenice.map&service=WMS&request=GetLegendGraphic&layer=yield_potential&version=1.3.0&format=image/png&sld_version=1.1.0'],
                    maxResolution: 8550,
                    visible: true,
                    opacity: 0.7
                }),
                new ol.layer.Tile({
                    title: "Machinery tracklines",
                    source: new ol.source.TileWMS({
                        url: 'http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/dima/maps/3d_olu/rostenice.map',
                        params: {
                            LAYERS: 'machinery_tracklines_average_slope',
                            FORMAT: "image/png",
                            INFO_FORMAT: "text/html",
                            minimumTerrainLevel: 14
                        },
                        crossOrigin: null
                    }),
                    legends: ['http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/dima/maps/3d_olu/rostenice.map&service=WMS&request=GetLegendGraphic&layer=machinery_tracklines_average_slope&version=1.3.0&format=image/png&sld_version=1.1.0'],
                    maxResolution: 8550,
                    visible: true,
                    opacity: 0.8
                })

            ],
            project_name: 'erra/map',
            datasources: [
                {
                    title: "Datasets",
                    url: "http://otn-dev.intrasoft-intl.com/otnServices-1.0/platform/ckanservices/datasets",
                    language: 'eng',
                    type: "ckan",
                    download: true
                }, {
                    title: "Services",
                    url: "http://cat.ccss.cz/csw/",
                    language: 'eng',
                    type: "micka",
                    code_list_url: 'http://www.whatstheplan.eu/php/metadata/util/codelists.php?_dc=1440156028103&language=eng&page=1&start=0&limit=25&filter=%5B%7B%22property%22%3A%22label%22%7D%5D'
                }, {
                    title: "Hub layers",
                    url: "http://opentnet.eu/php/metadata/csw/",
                    language: 'eng',
                    type: "micka",
                    code_list_url: 'http://opentnet.eu/php/metadata/util/codelists.php?_dc=1440156028103&language=eng&page=1&start=0&limit=25&filter=%5B%7B%22property%22%3A%22label%22%7D%5D'
                }
            ],
            hostname: {
                "default": {
                    "title": "Default",
                    "type": "default",
                    "editable": false,
                    "url": getHostname()
                }
            },
            'catalogue_url': "/php/metadata/csw",
            'compositions_catalogue_url': "/php/metadata/csw",
            status_manager_url: '/wwwlibs/statusmanager2/index.php',
            default_view: new ol.View({
                center: ol.proj.transform([16.8290202, 49.0751890], 'EPSG:4326', 'EPSG:3857'), //Latitude longitude    to Spherical Mercator
                zoom: 15,
                units: "m"
            })
        });

        module.controller('Main', ['$scope', '$compile', '$element', 'Core', 'hs.map.service', 'config',
            function($scope, $compile, $element, Core, OlMap, config) {
                if (console) console.log("Main called");
                $scope.hsl_path = hsl_path; //Get this from hslayers.js file
                $scope.Core = Core;

                Core.singleDatasources = true;
                Core.panelEnabled('compositions', true);
                Core.panelEnabled('status_creator', false);

                $scope.$on('infopanel.updated', function(event) {});

                function createAboutDialog() {
                    var el = angular.element('

');
                    $("#hs-dialog-area").append(el);
                    $compile(el)($scope);
                }
                createAboutDialog();
            }
        ]);

        return module;
    });
<|endoftext|>


<commit_before>export default function Promise(executor) {
  var state = {
    callbacks: [],
    self: this,
    status: 'pending'
  };

  setTriggers(state);

  this.then = then.bind(null, state);

  executor(state.resolveTrigger, state.rejectTrigger);
}

function callTrigger(state, triggerState, resolveTrigger, rejectTrigger, arg) {
  var then = {},
      thenResult;

  if (triggerState.called) {
    return;
  }

  if (arg === state.self) {
    return rejectTrigger(new TypeError('Cannot resolve a promise with itself as the value'));
  }

  if (isObject(arg) && ('then' in arg)) {
    then = tryCatch(() => arg.then);
  }

  if (typeof then.value === 'function') {
    setTriggers(state);
    thenResult = tryCatch(then.value.bind(arg), state.resolveTrigger, state.rejectTrigger);
    if (thenResult.error) {
      rejectTrigger(thenResult.error);
    }
  } else if (then.error) {
    rejectTrigger(then.error);
  } else {
    resolveTrigger(arg);
  }

  triggerState.called = true;
}

function isObject(value) {
  var type = typeof value;
  return value !== null && (type === 'object' || type === 'function');
}

function reject(state, triggerState, message) {
  if (triggerState.called || state.status !== 'pending') {
    return;
  }

  runRejectors(state.callbacks, message);

  state.message = message;
  state.status = 'rejected';
  triggerState.called = true;
}

function resolve(state, value) {
  if (state.status !== 'pending') {
    return;
  }

  state.value = value;
  state.status = 'resolved';

  runResolvers(state.callbacks, value);
}

function runRejectors(rejectors, message) {
  setTimeout(function() {
    rejectors.forEach(runCallback.bind(null, 'reject', message));
  }, 0);
}

function runCallback(type, arg, data) {
  var { rejectCallback, resolveCallback, rejectTrigger, resolveTrigger } = data,
      isResolving = (type === 'resolve'),
      callback = isResolving ? resolveCallback : rejectCallback,
      trigger = isResolving ? resolveTrigger : rejectTrigger,
      cbReturn,
      error;

  if (callback) {
    cbReturn = tryCatch(callback, arg);
    if (cbReturn.hasOwnProperty('value')) {
      resolveTrigger(cbReturn.value);
    } else {
      rejectTrigger(cbReturn.error);
    }
  } else {
    trigger(arg);
  }
}

function runResolvers(resolvers, value) {
  setTimeout(function() {
    resolvers.forEach(runCallback.bind(null, 'resolve', value));
  }, 0);
}

function setTriggers(state) {
  var triggerState = {called: false};
  state.rejectTrigger = reject.bind(null, state, triggerState);
  state.resolveTrigger = callTrigger.bind(
    null, state, triggerState, resolve.bind(null, state), state.rejectTrigger
  );
}

function then(state, resolveCallback, rejectCallback) {
  var hasResolveFn = (typeof resolveCallback === 'function'),
      hasRejectFn = (typeof rejectCallback === 'function'),
      status = state.status,
      isResolved = (status === 'resolved'),
      isRejected = (status === 'rejected'),
      data = {};

  data.resolveCallback = hasResolveFn ? resolveCallback : null;
  data.rejectCallback = hasRejectFn ? rejectCallback : null;

  if (isResolved) {
    runResolvers([data], state.value);
  } else if (isRejected) {
    runRejectors([data], state.message);
  } else {
    state.callbacks.push(data);
  }

  return new Promise(function(resolve, reject) {
    data.resolveTrigger = resolve;
    data.rejectTrigger = reject;
  });
}

// Do try...catch is own function since it causes de-optimizations.
// See: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers
function tryCatch(fn, ...args) {
  try {
    return {value: fn(...args)};
  } catch(error) {
    return {error};
  }
}
<commit_msg>Only reject when resolved thenable.then() throws if resolve() or reject() weren't called.<commit_after>export default function Promise(executor) {
  var state = {
    callbacks: [],
    self: this,
    status: 'pending'
  };

  setTriggers(state);

  this.then = then.bind(null, state);

  executor(state.resolveTrigger, state.rejectTrigger);
}

function callTrigger(state, triggerState, resolveTrigger, rejectTrigger, arg) {
  var then = {},
      thenResult,
      newTriggerState;

  if (triggerState.called) {
    return;
  }

  if (arg === state.self) {
    return rejectTrigger(new TypeError('Cannot resolve a promise with itself as the value'));
  }

  if (isObject(arg) && ('then' in arg)) {
    then = tryCatch(() => arg.then);
  }

  if (typeof then.value === 'function') {
    newTriggerState = setTriggers(state);
    thenResult = tryCatch(then.value.bind(arg), state.resolveTrigger, state.rejectTrigger);
    if (thenResult.error && !newTriggerState.called) {
      rejectTrigger(thenResult.error);
    }
  } else if (then.error) {
    rejectTrigger(then.error);
  } else {
    resolveTrigger(arg);
  }

  triggerState.called = true;
}

function isObject(value) {
  var type = typeof value;
  return value !== null && (type === 'object' || type === 'function');
}

function reject(state, triggerState, message) {
  if (triggerState.called || state.status !== 'pending') {
    return;
  }

  runRejectors(state.callbacks, message);

  state.message = message;
  state.status = 'rejected';
  triggerState.called = true;
}

function resolve(state, value) {
  if (state.status !== 'pending') {
    return;
  }

  state.value = value;
  state.status = 'resolved';

  runResolvers(state.callbacks, value);
}

function runRejectors(rejectors, message) {
  setTimeout(function() {
    rejectors.forEach(runCallback.bind(null, 'reject', message));
  }, 0);
}

function runCallback(type, arg, data) {
  var { rejectCallback, resolveCallback, rejectTrigger, resolveTrigger } = data,
      isResolving = (type === 'resolve'),
      callback = isResolving ? resolveCallback : rejectCallback,
      trigger = isResolving ? resolveTrigger : rejectTrigger,
      cbReturn,
      error;

  if (callback) {
    cbReturn = tryCatch(callback, arg);
    if (cbReturn.hasOwnProperty('value')) {
      resolveTrigger(cbReturn.value);
    } else {
      rejectTrigger(cbReturn.error);
    }
  } else {
    trigger(arg);
  }
}

function runResolvers(resolvers, value) {
  setTimeout(function() {
    resolvers.forEach(runCallback.bind(null, 'resolve', value));
  }, 0);
}

function setTriggers(state) {
  var triggerState = {called: false};
  state.rejectTrigger = reject.bind(null, state, triggerState);
  state.resolveTrigger = callTrigger.bind(
    null, state, triggerState, resolve.bind(null, state), state.rejectTrigger
  );

  return triggerState;
}

function then(state, resolveCallback, rejectCallback) {
  var hasResolveFn = (typeof resolveCallback === 'function'),
      hasRejectFn = (typeof rejectCallback === 'function'),
      status = state.status,
      isResolved = (status === 'resolved'),
      isRejected = (status === 'rejected'),
      data = {};

  data.resolveCallback = hasResolveFn ? resolveCallback : null;
  data.rejectCallback = hasRejectFn ? rejectCallback : null;

  if (isResolved) {
    runResolvers([data], state.value);
  } else if (isRejected) {
    runRejectors([data], state.message);
  } else {
    state.callbacks.push(data);
  }

  return new Promise(function(resolve, reject) {
    data.resolveTrigger = resolve;
    data.rejectTrigger = reject;
  });
}

// Do try...catch is own function since it causes de-optimizations.
// See: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers
function tryCatch(fn, ...args) {
  try {
    return {value: fn(...args)};
  } catch(error) {
    return {error};
  }
}
<|endoftext|>


<commit_before>/* Set the defaults for DataTables initialisation */
$.extend(true, $.fn.dataTable.defaults, {
  "sDom": "T<'row'<'col-xs-5 col-sm-6'l><'col-xs-7 col-sm-6 text-right'f>r>t<'row'<'col-xs-3 col-sm-4 col-md-5'i><'col-xs-9 col-sm-8 col-md-7 text-right'p>>",
  "sPaginationType": "bootstrap",
  "oLanguage": {
    "sLengthMenu": "_MENU_ records per page"
  },
  "fnInitComplete": function (oSettings, json) {
    var currentId = $(this).attr('id');
    if (currentId) {

      var thisLength = $('#' + currentId + '_length');
      var thisLengthLabel = $('#' + currentId + '_length label');
      var thisLengthSelect = $('#' + currentId + '_length label select');

      var thisFilter = $('#' + currentId + '_filter');
      var thisFilterLabel = $('#' + currentId + '_filter label');
      var thisFilterInput = $('#' + currentId + '_filter label input');

      // Re-arrange the records selection for a form-horizontal layout
      thisLength.addClass('form-group');
      thisLengthLabel.addClass('control-label col-xs-12 col-sm-8 col-md-10').attr('for', currentId + '_length_select').css('text-align', 'left').css('padding-left', '20%');
      thisLengthSelect.addClass('form-control input-sm').attr('id', currentId + '_length_select');
      thisLengthSelect.prependTo(thisLength).wrap('
');
      // Re-arrange the search input for a form-horizontal layout
      thisFilter.addClass('form-group');
      thisFilterLabel.addClass('control-label col-xs-4 col-sm-3 col-md-3').attr('for', currentId + '_filter_input');
      thisFilterInput.addClass('form-control input-sm').attr('id', currentId + '_filter_input');
      thisFilterInput.appendTo(thisFilter).wrap('
');
    }
  }
});

$.extend($.fn.dataTableExt.oStdClasses, {
  "sWrapper": "dataTables_wrapper form-horizontal centreon_table"
});

/* API method to get paging information */
$.fn.dataTableExt.oApi.fnPagingInfo = function (oSettings) {
  return {
    "iStart": oSettings._iDisplayStart,
    "iEnd": oSettings.fnDisplayEnd(),
    "iLength": oSettings._iDisplayLength,
    "iTotal": oSettings.fnRecordsTotal(),
    "iFilteredTotal": oSettings.fnRecordsDisplay(),
    "iPage": oSettings._iDisplayLength === -1 ? 0 : Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength),
    "iTotalPages": oSettings._iDisplayLength === -1 ? 0 : Math.ceil(oSettings.fnRecordsDisplay() / oSettings._iDisplayLength)
  };
};

/* Bootstrap style pagination control */
$.extend($.fn.dataTableExt.oPagination, {
  "bootstrap": {
    "fnInit": function (oSettings, nPaging, fnDraw) {
      var oLang = oSettings.oLanguage.oPaginate;
      var fnClickHandler = function (e) {
        e.preventDefault();
        if (oSettings.oApi._fnPageChange(oSettings, e.data.action)) {
          fnDraw(oSettings);
        }
      };

      $(nPaging).append(
       '
' +
        '

' +
        '

' +
        '

' +
        '

' +
       '
'
      );
      var els = $('a', nPaging);
      $(els[0]).bind('click.DT', { action: "first" }, fnClickHandler);
      $(els[1]).bind('click.DT', { action: "previous" }, fnClickHandler);
      $(els[2]).bind('click.DT', { action: "next" }, fnClickHandler);
      $(els[3]).bind('click.DT', { action: "last" }, fnClickHandler);
    },

    "fnUpdate": function (oSettings, fnDraw) {
      var iListLength = 5;
      var oPaging = oSettings.oInstance.fnPagingInfo();
      var an = oSettings.aanFeatures.p;
      var i, j, sClass, iStart, iEnd, iHalf = Math.floor(iListLength / 2);

        if (oPaging.iTotalPages < iListLength) { iStart = 1; iEnd = oPaging.iTotalPages; } else if (oPaging.iPage <= iHalf) { iStart = 1; iEnd = iListLength; } else if (oPaging.iPage >= oPaging.iTotalPages - iHalf) { iStart = oPaging.iTotalPages - iListLength + 1; iEnd = oPaging.iTotalPages; } else { iStart = oPaging.iPage - iHalf + 1; iEnd = iStart + iListLength - 1; }

        for (i = 0, iLen = an.length ; i < iLen ; i++) {
          // Remove the middle elements
          $('li:gt(1)', an[i]).filter(':not(.next,.last)').remove();

          // Add the new list items and their event handlers
          for (j = iStart; j <= iEnd; j++) {
            sClass = j == oPaging.iPage + 1 ? 'class="active"' : "";
            $("
' + j + "
").insertBefore($(".next,.last", an[i])[0]).bind("click", function (a) {
                a.preventDefault(); oSettings._iDisplayStart = (parseInt($("a", this).text(), 10) - 1) * oPaging.iLength; fnDraw(oSettings);
            });
          }

          // Add / remove disabled classes from the static elements
          if (oPaging.iPage === 0) {
            $(".first,.prev", an[i]).addClass("disabled");
          } else {
            $(".first,.prev", an[i]).removeClass("disabled");
          }

          if (oPaging.iPage === oPaging.iTotalPages - 1 || oPaging.iTotalPages === 0) {
            $(".next,.last", an[i]).addClass("disabled");
          } else {
            $(".next,.last", an[i]).removeClass("disabled");
          }
        }
    }
  }
});

/*
* TableTools Bootstrap compatibility
* Required TableTools 2.1+
*/
if ($.fn.DataTable.TableTools) {
  // Set the classes that TableTools uses to something suitable for Bootstrap
  // Set the classes that TableTools uses to something suitable for Bootstrap
  $.extend(true, $.fn.DataTable.TableTools.classes, {
    "container": "DTTT btn-group pull-right",
    "buttons": {
      "normal": "btn btn-default",
      "disabled": "disabled"
    },
    "collection": {
      "container": "DTTT_dropdown dropdown-menu",
      "buttons": {
        "normal": "",
        "disabled": "disabled"
      }
    },
    "print": {
      "info": "DTTT_print_info modal"
    },
    "select": {
      "row": "active"
    }
  });

  // Have the collection use a bootstrap compatible dropdown
  $.extend(true, $.fn.DataTable.TableTools.DEFAULTS.oTags, {
    "collection": {
      "container": "ul",
      "button": "li",
      "liner": "a"
    }
  });
}

// Moved to the bottom.
if ($.fn.DataTable.defaults) {
  $.extend($.fn.dataTable.defaults, {
    'bAutoWidth': false,
    'aLengthMenu': [[5, 10, 25, 50, 100], [5, 10, 25, 50, 100]],
    'iDisplayLength': 10,
    "bFilter": true
  });
}
<commit_msg>* Smaller pagination in listing pages<commit_after>/* Set the defaults for DataTables initialisation */
$.extend(true, $.fn.dataTable.defaults, {
  "sDom": "T<'row'<'col-xs-5 col-sm-6'l><'col-xs-7 col-sm-6 text-right'f>r>t<'row'<'col-xs-3 col-sm-4 col-md-5'i><'col-xs-9 col-sm-8 col-md-7 text-right'p>>",
  "sPaginationType": "bootstrap",
  "oLanguage": {
    "sLengthMenu": "_MENU_ records per page"
  },
  "fnInitComplete": function (oSettings, json) {
    var currentId = $(this).attr('id');
    if (currentId) {

      var thisLength = $('#' + currentId + '_length');
      var thisLengthLabel = $('#' + currentId + '_length label');
      var thisLengthSelect = $('#' + currentId + '_length label select');

      var thisFilter = $('#' + currentId + '_filter');
      var thisFilterLabel = $('#' + currentId + '_filter label');
      var thisFilterInput = $('#' + currentId + '_filter label input');

      // Re-arrange the records selection for a form-horizontal layout
      thisLength.addClass('form-group');
      thisLengthLabel.addClass('control-label col-xs-12 col-sm-8 col-md-10').attr('for', currentId + '_length_select').css('text-align', 'left').css('padding-left', '20%');
      thisLengthSelect.addClass('form-control input-sm').attr('id', currentId + '_length_select');
      thisLengthSelect.prependTo(thisLength).wrap('
');
      // Re-arrange the search input for a form-horizontal layout
      thisFilter.addClass('form-group');
      thisFilterLabel.addClass('control-label col-xs-4 col-sm-3 col-md-3').attr('for', currentId + '_filter_input');
      thisFilterInput.addClass('form-control input-sm').attr('id', currentId + '_filter_input');
      thisFilterInput.appendTo(thisFilter).wrap('
');
    }
  }
});

$.extend($.fn.dataTableExt.oStdClasses, {
  "sWrapper": "dataTables_wrapper form-horizontal centreon_table"
});

/* API method to get paging information */
$.fn.dataTableExt.oApi.fnPagingInfo = function (oSettings) {
  return {
    "iStart": oSettings._iDisplayStart,
    "iEnd": oSettings.fnDisplayEnd(),
    "iLength": oSettings._iDisplayLength,
    "iTotal": oSettings.fnRecordsTotal(),
    "iFilteredTotal": oSettings.fnRecordsDisplay(),
    "iPage": oSettings._iDisplayLength === -1 ? 0 : Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength),
    "iTotalPages": oSettings._iDisplayLength === -1 ? 0 : Math.ceil(oSettings.fnRecordsDisplay() / oSettings._iDisplayLength)
  };
};

/* Bootstrap style pagination control */
$.extend($.fn.dataTableExt.oPagination, {
  "bootstrap": {
    "fnInit": function (oSettings, nPaging, fnDraw) {
      var oLang = oSettings.oLanguage.oPaginate;
      var fnClickHandler = function (e) {
        e.preventDefault();
        if (oSettings.oApi._fnPageChange(oSettings, e.data.action)) {
          fnDraw(oSettings);
        }
      };

      $(nPaging).append(
       '
' +
        '

' +
        '

' +
        '

' +
        '

' +
       '
'
      );
      var els = $('a', nPaging);
      $(els[0]).bind('click.DT', { action: "first" }, fnClickHandler);
      $(els[1]).bind('click.DT', { action: "previous" }, fnClickHandler);
      $(els[2]).bind('click.DT', { action: "next" }, fnClickHandler);
      $(els[3]).bind('click.DT', { action: "last" }, fnClickHandler);
    },

    "fnUpdate": function (oSettings, fnDraw) {
      var iListLength = 5;
      var oPaging = oSettings.oInstance.fnPagingInfo();
      var an = oSettings.aanFeatures.p;
      var i, j, sClass, iStart, iEnd, iHalf = Math.floor(iListLength / 2);

        if (oPaging.iTotalPages < iListLength) { iStart = 1; iEnd = oPaging.iTotalPages; } else if (oPaging.iPage <= iHalf) { iStart = 1; iEnd = iListLength; } else if (oPaging.iPage >= oPaging.iTotalPages - iHalf) { iStart = oPaging.iTotalPages - iListLength + 1; iEnd = oPaging.iTotalPages; } else { iStart = oPaging.iPage - iHalf + 1; iEnd = iStart + iListLength - 1; }

        for (i = 0, iLen = an.length ; i < iLen ; i++) {
          // Remove the middle elements
          $('li:gt(1)', an[i]).filter(':not(.next,.last)').remove();

          // Add the new list items and their event handlers
          for (j = iStart; j <= iEnd; j++) {
            sClass = j == oPaging.iPage + 1 ? 'class="active"' : "";
            $("
' + j + "
").insertBefore($(".next,.last", an[i])[0]).bind("click", function (a) {
                a.preventDefault(); oSettings._iDisplayStart = (parseInt($("a", this).text(), 10) - 1) * oPaging.iLength; fnDraw(oSettings);
            });
          }

          // Add / remove disabled classes from the static elements
          if (oPaging.iPage === 0) {
            $(".first,.prev", an[i]).addClass("disabled");
          } else {
            $(".first,.prev", an[i]).removeClass("disabled");
          }

          if (oPaging.iPage === oPaging.iTotalPages - 1 || oPaging.iTotalPages === 0) {
            $(".next,.last", an[i]).addClass("disabled");
          } else {
            $(".next,.last", an[i]).removeClass("disabled");
          }
        }
    }
  }
});

/*
* TableTools Bootstrap compatibility
* Required TableTools 2.1+
*/
if ($.fn.DataTable.TableTools) {
  // Set the classes that TableTools uses to something suitable for Bootstrap
  // Set the classes that TableTools uses to something suitable for Bootstrap
  $.extend(true, $.fn.DataTable.TableTools.classes, {
    "container": "DTTT btn-group pull-right",
    "buttons": {
      "normal": "btn btn-default",
      "disabled": "disabled"
    },
    "collection": {
      "container": "DTTT_dropdown dropdown-menu",
      "buttons": {
        "normal": "",
        "disabled": "disabled"
      }
    },
    "print": {
      "info": "DTTT_print_info modal"
    },
    "select": {
      "row": "active"
    }
  });

  // Have the collection use a bootstrap compatible dropdown
  $.extend(true, $.fn.DataTable.TableTools.DEFAULTS.oTags, {
    "collection": {
      "container": "ul",
      "button": "li",
      "liner": "a"
    }
  });
}

// Moved to the bottom.
if ($.fn.DataTable.defaults) {
  $.extend($.fn.dataTable.defaults, {
    'bAutoWidth': false,
    'aLengthMenu': [[5, 10, 25, 50, 100], [5, 10, 25, 50, 100]],
    'iDisplayLength': 10,
    "bFilter": true
  });
}
<|endoftext|>


<commit_before>// big numbers

// load math.js and create an instance
// the default type of numbers is configured as big numbers
var mathjs = require('../index'),
    math = mathjs({
      number: {
        defaultType: 'number' // Choose from: 'number' (default), 'bignumber'
      }
    });

/**
 * Helper function to output a value in the console. Value will be formatted.
 * @param {*} value
 */
function print (value) {
  console.log(math.format(value));
}

console.log('round-off errors with numbers');
print(math.add(0.1, 0.2));    // Number, 0.30000000000000004
print(math.divide(0.3, 0.2)); // Number, 1.4999999999999998
console.log();

console.log('no round-off errors with big numbers');
print(math.add(math.bignumber(0.1), math.bignumber(0.2)));     // BigNumber, 0.3
print(math.divide(math.bignumber(0.3), math.bignumber(0.2)));  // BigNumber, 1.5
console.log();

console.log('create big numbers from strings when exceeding the range of a number');
print(math.bignumber(1.2e+500));    // BigNumber, Infinity      WRONG
print(math.bignumber('1.2e+500'));  // BigNumber, 1.2e+500
console.log();

<commit_msg>more examples added for big numbers<commit_after>// big numbers

// load math.js and create an instance
// the default type of numbers is configured as big numbers
var mathjs = require('../index'),
    math = mathjs({
      number: {
        defaultType: 'number' // Choose from: 'number' (default), 'bignumber'
      }
    });

/**
 * Helper function to output a value in the console. Value will be formatted.
 * @param {*} value
 */
function print (value) {
  console.log(math.format(value));
}

console.log('round-off errors with numbers');
print(math.add(0.1, 0.2));    // Number, 0.30000000000000004
print(math.divide(0.3, 0.2)); // Number, 1.4999999999999998
console.log();

console.log('no round-off errors with big numbers');
print(math.add(math.bignumber(0.1), math.bignumber(0.2)));     // BigNumber, 0.3
print(math.divide(math.bignumber(0.3), math.bignumber(0.2)));  // BigNumber, 1.5
console.log();

console.log('create big numbers from strings when exceeding the range of a number');
print(math.bignumber(1.2e+500));    // BigNumber, Infinity      WRONG
print(math.bignumber('1.2e+500'));  // BigNumber, 1.2e+500
console.log();

// one can work conveniently with big numbers using the expression parser.
// note though that big numbers are only supported in arithmetic functions
console.log('use big numbers in the expression parser');
math.eval('0.1 + 0.2'); // BigNumber, 0.3
math.eval('0.3 / 0.2'); // BigNumber, 1.5
console.log();
<|endoftext|>


<commit_before>// DecentCMS (c) 2014 Bertrand Le Roy, under MIT. See LICENSE.txt for licensing details.
'use strict';

/**
 * @description
 * A rendering strategy that uses templates files, going through view engines.
 * @param {object} scope The scope.
 * @constructor
 */
function TemplateRenderingStrategy(scope) {
  var fs = require('fs');
  var path = require('path');

  this.scope = scope;
  var fileResolver = scope.require('file-resolution');
  var shapeHelper = scope.require('shape');
  var viewEngines = scope.getServices('view-engine');
  var extensionExpression = '(' + viewEngines
      .map(function(viewEngine) {return viewEngine.extension;})
      .join('|') + ')';
  var viewEngineMap = {};
  for (var i = 0; i < viewEngines.length; i++) {
    viewEngineMap[viewEngines[i].extension] = viewEngines[i];
  }
  var shapeTemplates = scope.shapeTemplates = scope.shapeTemplates || {};

  /**
   * Uses templates to recursively render shapes into HTML.
   *
   * The method resolves templates based on module and theme dependencies
   * and priorities.
   *
   * Each shape can also have a list of alternate template names that
   * will take precedence over the shape name to resolve a template name,
   * if found.
   *
   * @param {object} context The context.
   * @param {object} context.shape The shape to render.
   * @param {string} [context.shapeName]
   * The name of the shape to render.
   * If not specified, `context.shape.meta.type` will be used,
   * and if that is not found, 'zone' is used.
   * @param {object} context.renderStream The render stream.
   * @param {Function} done The callback.
   */
  this.render = function(context, done) {
    var shape = context.shape;
    var renderer = context.renderStream;
    var temp = shapeHelper.temp(shape);
    if (temp.html) {
      renderer.write(temp.html);
      return done();
    }
    var shapeName = context.shapeName;
    if (!shapeName) {
      var meta = shapeHelper.meta(shape);
      shapeName = meta.type || (meta.type = 'zone');
    }
    var alternates = shapeHelper.alternates(shape).slice();
    alternates.push(shapeName);
    for (var i = 0; i < alternates.length; i++) {
      var alternate = alternates[i];
      var template = shapeTemplates[alternate];
      if (!template) {
        var templatePath = fileResolver.resolve(
          'views', new RegExp(alternate + '\\.' + extensionExpression));
        if (templatePath) {
          var extension = path.extname(templatePath).substr(1);
          var viewEngine = viewEngineMap[extension];
          viewEngine.load(templatePath, function onTemplateLoaded(template) {
            shapeTemplates[alternate] = template;
            template(shape, renderer, done);
          });
          return;
        }
      }
      else {
        shapeTemplates[alternate] = template;
        template(shape, renderer, done);
        return;
      }
    }
    done(new Error('Template for ' + alternate + ' not found.'));
  };
}
TemplateRenderingStrategy.service = 'rendering-strategy';
TemplateRenderingStrategy.scope = 'shell';
TemplateRenderingStrategy.feature = 'template-rendering-strategy';
TemplateRenderingStrategy.dependencies = ['decent-core-io'];

module.exports = TemplateRenderingStrategy;<commit_msg>Remove unused variable<commit_after>// DecentCMS (c) 2014 Bertrand Le Roy, under MIT. See LICENSE.txt for licensing details.
'use strict';

/**
 * @description
 * A rendering strategy that uses templates files, going through view engines.
 * @param {object} scope The scope.
 * @constructor
 */
function TemplateRenderingStrategy(scope) {
  var path = require('path');

  this.scope = scope;
  var fileResolver = scope.require('file-resolution');
  var shapeHelper = scope.require('shape');
  var viewEngines = scope.getServices('view-engine');
  var extensionExpression = '(' + viewEngines
      .map(function(viewEngine) {return viewEngine.extension;})
      .join('|') + ')';
  var viewEngineMap = {};
  for (var i = 0; i < viewEngines.length; i++) {
    viewEngineMap[viewEngines[i].extension] = viewEngines[i];
  }
  var shapeTemplates = scope.shapeTemplates = scope.shapeTemplates || {};

  /**
   * Uses templates to recursively render shapes into HTML.
   *
   * The method resolves templates based on module and theme dependencies
   * and priorities.
   *
   * Each shape can also have a list of alternate template names that
   * will take precedence over the shape name to resolve a template name,
   * if found.
   *
   * @param {object} context The context.
   * @param {object} context.shape The shape to render.
   * @param {string} [context.shapeName]
   * The name of the shape to render.
   * If not specified, `context.shape.meta.type` will be used,
   * and if that is not found, 'zone' is used.
   * @param {object} context.renderStream The render stream.
   * @param {Function} done The callback.
   */
  this.render = function(context, done) {
    var shape = context.shape;
    var renderer = context.renderStream;
    var temp = shapeHelper.temp(shape);
    if (temp.html) {
      renderer.write(temp.html);
      return done();
    }
    var shapeName = context.shapeName;
    if (!shapeName) {
      var meta = shapeHelper.meta(shape);
      shapeName = meta.type || (meta.type = 'zone');
    }
    var alternates = shapeHelper.alternates(shape).slice();
    alternates.push(shapeName);
    for (var i = 0; i < alternates.length; i++) {
      var alternate = alternates[i];
      var template = shapeTemplates[alternate];
      if (!template) {
        var templatePath = fileResolver.resolve(
          'views', new RegExp(alternate + '\\.' + extensionExpression));
        if (templatePath) {
          var extension = path.extname(templatePath).substr(1);
          var viewEngine = viewEngineMap[extension];
          viewEngine.load(templatePath, function onTemplateLoaded(template) {
            shapeTemplates[alternate] = template;
            template(shape, renderer, done);
          });
          return;
        }
      }
      else {
        shapeTemplates[alternate] = template;
        template(shape, renderer, done);
        return;
      }
    }
    done(new Error('Template for ' + alternate + ' not found.'));
  };
}
TemplateRenderingStrategy.service = 'rendering-strategy';
TemplateRenderingStrategy.scope = 'shell';
TemplateRenderingStrategy.feature = 'template-rendering-strategy';
TemplateRenderingStrategy.dependencies = ['decent-core-io'];

module.exports = TemplateRenderingStrategy;<|endoftext|>


<commit_before>#!/usr/bin/env

/**
 * This is an example of SUGO-Actor
 * @see https://github.com/realglobe-Inc/sugo-actor
 */
'use strict'

const sugoActor = require('sugo-actor')
const co = require('co')

const CLOUD_URL = 'http://localhost:3000'
co(function * () {
  let actor = sugoActor(`${CLOUD_URL}/actors`, {
    /** Name to identify this actor on the cloud */
    key: 'my-actor-01',
    /** Modules to provide */
    modules: {
      // Example of a simple call-return function module
      tableTennis: {
        ping (pong = 'default pong!') {
          return co(function * () {
            /* ... */
            return `"${pong}" from actor!` // Return to the remote caller
          })
        }
      },
      // Load plugin module
      timeBomb: require('./example-time-bomb-module')({})
    }
  })
  yield actor.connect() // Connect to cloud server
}).catch((err) => console.error(err))
<commit_msg>Update example-actor.js<commit_after>#!/usr/bin/env

/**
 * This is an example of SUGO-Actor
 * @see https://github.com/realglobe-Inc/sugo-actor
 */
'use strict'

const sugoActor = require('sugo-actor')
const { Module } = sugoActor
const co = require('co')

const CLOUD_URL = 'http://localhost:3000'
co(function * () {
  let actor = sugoActor(`${CLOUD_URL}/actors`, {
    /** Name to identify this actor on the cloud */
    key: 'my-actor-01',
    /** Modules to provide */
    modules: {
      // Example of a simple call-return function module
      tableTennis: new Module({
        ping (pong = 'default pong!') {
          return co(function * () {
            /* ... */
            return `"${pong}" from actor!` // Return to the remote caller
          })
        }
      })
      // Load plugin module
      timeBomb: require('./example-time-bomb-module')({})
    }
  })
  yield actor.connect() // Connect to cloud server
}).catch((err) => console.error(err))
<|endoftext|>