<commit_before>#!/usr/bin/env node
var OverScrap = require('../dist/overScrap.min');

if(process.argv.length < 3){
  console.error('Not enough arguments')
  console.error('\t./bin/overscrap-cli.js <Battle tag> [ region [ game mode ]]')
  console.error('if not provided, region defaults to `eu` and game mode to `competitive`')
  process.exit(1);
}

var overScrap = new OverScrap();
console.log(`Looking up data for ${process.argv[2]} on realm '${process.argv[3] || 'default'}' for the '${process.argv[4] || 'default'}' mode `)
overScrap.loadDataFromProfile(process.argv[2], process.argv[3], process.argv[4]).then(data => {
  console.log(data);
})
.catch(err => {
  console.log('Oops ... something went wrong.')
  console.log(`${err.message.substring(0, 100)} ...`)
  if(err.message.startsWith('404')){
    console.log('Could not find the page, there\'s probably an issue with the Battle tag, region or game modes provided. Please double check them, retry, and submit a report if it still fails =)' )
  }
  process.exit(2)
})
<commit_msg>[CLI]Pretty print the result<commit_after>#!/usr/bin/env node
var OverScrap = require('../dist/overScrap.min');

if(process.argv.length < 3){
  console.error('Not enough arguments')
  console.error('\t./bin/overscrap-cli.js <Battle tag> [ region [ game mode ]]')
  console.error('if not provided, region defaults to `eu` and game mode to `competitive`')
  process.exit(1);
}

var overScrap = new OverScrap();
console.log(`Looking up data for ${process.argv[2]} on realm '${process.argv[3] || 'default'}' for the '${process.argv[4] || 'default'}' mode `)
overScrap.loadDataFromProfile(process.argv[2], process.argv[3], process.argv[4]).then(data => {
  console.log(JSON.stringify(data, null, 2));
})
.catch(err => {
  console.log('Oops ... something went wrong.')
  console.log(`${err.message.substring(0, 100)} ...`)
  if(err.message.startsWith('404')){
    console.log('Could not find the page, there\'s probably an issue with the Battle tag, region or game modes provided. Please double check them, retry, and submit a report if it still fails =)' )
  }
  process.exit(2)
})
<|endoftext|>


<commit_before>frappe.pages['data-import-tool'].onload = function(wrapper) {
	wrapper.app_page = frappe.ui.make_app_page({
		parent: wrapper,
		title: __("Data Import / Export Tool"),
		icon: "icon-upload"
	});

	// check permission for import
	if(!((frappe.boot.user.can_import && frappe.boot.user.can_import.length) ||
		user_roles.indexOf("System Manager")!==-1)) {
			frappe.show_not_permitted("data-import-tool");
			return false;
		}

	$(wrapper).find('.layout-main-section').append('
1. Download Template
\

\

Download a template for importing a table.
\

\

\
					<select class="form-control" style="width: 200px" name="dit-doctype">\
					</select>

\
					\
					    <input type="checkbox" name="dit-with-data"> Download with data\
					\

Export all rows in CSV fields for re-upload. This is ideal for bulk-editing.
\

\

\

\

\

\

\

\

2. Import Data
\

Attach .csv file to import data
\

\

\

\

\

Help: Importing non-English data in Microsoft Excel
\

While uploading non English files ensure that the encoding is UTF-8.
\

\

In Excel, save the file in CSV (Comma Delimited) format
\

Open this saved file in Notepad
\

Click on File -> Save As
\

File Name: <your filename>.csv
\
						Save as type: Text Documents (*.txt)
\
						Encoding: UTF-8\

\

Click on Save
\

\

\

');

	$select = $(wrapper).find('[name="dit-doctype"]');

	frappe.messages.waiting($(wrapper).find(".dit-progress-area").toggle(false),
		"Performing hardcore import process....", 100);

	// load doctypes
	frappe.call({
		method: 'frappe.core.page.data_import_tool.data_import_tool.get_doctypes',
		callback: function(r) {
			$select.add_options(['Select...'].concat(r.message));
			wrapper.doctypes = r.message;
			wrapper.set_route_options();
		}
	});

	wrapper.set_route_options = function() {
		if(frappe.route_options
			&& frappe.route_options.doctype
			&& in_list(wrapper.doctypes, frappe.route_options.doctype)) {
				$select.val(frappe.route_options.doctype).change();
				frappe.route_options = null;
		}
	}

	// check if template with_data is allowed
	var validate_download_with_data = function(doctype, verbose) {
		// if no export permission, uncheck with data
		var with_data = $('[name="dit-with-data"]').prop("checked");
		if(with_data && !frappe.model.can_export(doctype)) {
			$('[name="dit-with-data"]').prop("checked", false);
			with_data = false;

			if(verbose) {
				msgprint(__("You are not allowed to export the data of: {0}. Downloading empty template.", [doctype]));
			}
		}
		return with_data;
	};

	wrapper.add_template_download_link = function(doctype) {
		return $('')
			.html(doctype)
			.data('doctype', doctype)
			.data('all_doctypes', "No")
			.click(function() {
				var doctype = $(this).data('doctype');
				var parent_doctype = $('[name="dit-doctype"]').val();
				var with_data = validate_download_with_data(parent_doctype || doctype, true);
				window.location.href = repl(frappe.request.url
					+ '?cmd=%(cmd)s&doctype=%(doctype)s'
					+ '&parent_doctype=%(parent_doctype)s'
					+ '&with_data=%(with_data)s'
					+ '&all_doctypes=%(all_doctypes)s',
					{
						cmd: 'frappe.core.page.data_import_tool.exporter.get_template',
						doctype: doctype,
						parent_doctype: parent_doctype,
						with_data: with_data ? 'Yes' : 'No',
						all_doctypes: $(this).data('all_doctypes')
					});
			})
			.appendTo('#dit-download');
	}

	// load options
	$select.change(function() {
		var val = $(this).val()
		if(val!='Select...') {
			$('#dit-download').empty().removeClass("hide");

			frappe.model.with_doctype(val, function() {
				validate_download_with_data(val);

				// get options
				return frappe.call({
					method: 'frappe.core.page.data_import_tool.data_import_tool.get_doctype_options',
					args: {doctype: val},
					callback: function(r) {
						$('
 Download
').appendTo('#dit-download');
						var with_data = $('[name="dit-with-data"]:checked').length ? 'Yes' : 'No';
						// download link
						$.each(r.message, function(i, v) {
							if(i==0)
								$('Main Table:
').appendTo('#dit-download');
							if(i==1)
								$('
Child Tables:
').appendTo('#dit-download');

							wrapper.add_template_download_link(v);
							$('#dit-download').append('
');
						});

						if(r.message.length > 1) {
							$('
All Tables (Main + Child Tables):
').appendTo('#dit-download');
							var link = wrapper
								.add_template_download_link(r.message[0])
								.data('all_doctypes', "Yes")
						}
					}
				})
			});
		}
	});

	var write_messages = function(r) {
		$(wrapper).find(".dit-progress-area").toggle(false);
		$("#dit-output").empty();

		$.each(r.messages, function(i, v) {
			var $p = $('

').html(frappe.markdown(v)).appendTo('#dit-output');
			$("
").appendTo('#dit-output');
			if(v.substr(0,5)=='Error') {
				$p.css('color', 'red');
			} else if(v.substr(0,8)=='Inserted') {
				$p.css('color', 'green');
			} else if(v.substr(0,7)=='Updated') {
				$p.css('color', 'green');
			} else if(v.substr(0,5)=='Valid') {
				$p.css('color', '#777');
			}
		});
	}

	var onerror = function(r) {
		r.messages = $.map(r.message.messages, function(v) {
			var msg = v.replace("Inserted", "Valid")
				.replace("Updated", "Valid").split("<");
			if (msg.length > 1) {
				v = msg[0] + (msg[1].split(">").slice(-1)[0]);
			} else {
				v = msg[0];
			}
			return v;
		});

		r.messages = ["
Import Failed!
"]
			.concat(r.messages);

		write_messages(r);
	};

	// upload
	frappe.upload.make({
		parent: $('#dit-upload-area'),
		args: {
			method: 'frappe.core.page.data_import_tool.importer.upload'
		},
		onerror: onerror,
		callback: function(attachment, r) {
			if(r.message.error) {
				onerror(r);
			} else {
				// replace links if error has occured
				r.messages = ["
Import Successful!
"].
					concat(r.message.messages)

				write_messages(r);
			}
		}
	});

	// add overwrite option
	var $submit_btn = $('#dit-upload-area button.btn-upload')
		.html(' ' + __("Upload and Import"));

	$('<input type="checkbox" name="overwrite"> Overwrite\

If you are uploading a child table (for example Item Price), the all the entries of that table will be deleted (for that parent record) and new entries will be made.

')
		.insertBefore($submit_btn);

	// add submit option
	$('<input type="checkbox" name="_submit"> Submit\

If you are inserting new records (overwrite not checked) \
			and if you have submit permission, the record will be submitted.

')
		.insertBefore($submit_btn);

	// add ignore option
	$('<input type="checkbox" name="ignore_encoding_errors"> Ignore Encoding Errors

')
		.insertBefore($submit_btn);

	// rename button
	$('#dit-upload-area button.btn-upload')
		.click(function() {
			$('#dit-output').empty();
			$(wrapper).find(".dit-progress-area").toggle(true);
		});
}

frappe.pages['data-import-tool'].onshow = function(wrapper) {
	wrapper.set_route_options && wrapper.set_route_options();
}
<commit_msg>[fix] [ux] [minor] data import<commit_after>frappe.pages['data-import-tool'].onload = function(wrapper) {
	wrapper.app_page = frappe.ui.make_app_page({
		parent: wrapper,
		title: __("Data Import / Export Tool"),
		icon: "icon-upload"
	});

	// check permission for import
	if(!((frappe.boot.user.can_import && frappe.boot.user.can_import.length) ||
		user_roles.indexOf("System Manager")!==-1)) {
			frappe.show_not_permitted("data-import-tool");
			return false;
		}

	$(wrapper).find('.layout-main-section').append('
1. Download Template
\

\

Download a template for importing a table.
\

\

\
					<select class="form-control" style="width: 200px" name="dit-doctype">\
					</select>

\
					\
					    <input type="checkbox" name="dit-with-data"> Download with data\
					\

Export all rows in CSV fields for re-upload. This is ideal for bulk-editing.
\

\

\

\

\

\

\

\

2. Import Data
\

Attach .csv file to import data
\

\

\

\

\

Help: Importing non-English data in Microsoft Excel
\

While uploading non English files ensure that the encoding is UTF-8.
\

\

In Excel, save the file in CSV (Comma Delimited) format
\

Open this saved file in Notepad
\

Click on File -> Save As
\

File Name: <your filename>.csv
\
						Save as type: Text Documents (*.txt)
\
						Encoding: UTF-8\

\

Click on Save
\

\

\

');

	$select = $(wrapper).find('[name="dit-doctype"]');

	frappe.messages.waiting($(wrapper).find(".dit-progress-area").toggle(false),
		"Performing hardcore import process....", 100);

	// load doctypes
	frappe.call({
		method: 'frappe.core.page.data_import_tool.data_import_tool.get_doctypes',
		callback: function(r) {
			$select.add_options(['Select...'].concat(r.message));
			wrapper.doctypes = r.message;
			wrapper.set_route_options();
		}
	});

	wrapper.set_route_options = function() {
		if(frappe.route_options
			&& frappe.route_options.doctype
			&& in_list(wrapper.doctypes, frappe.route_options.doctype)) {
				$select.val(frappe.route_options.doctype).change();
				frappe.route_options = null;
		}
	}

	// check if template with_data is allowed
	var validate_download_with_data = function(doctype, verbose) {
		// if no export permission, uncheck with data
		var with_data = $('[name="dit-with-data"]').prop("checked");
		if(with_data && !frappe.model.can_export(doctype)) {
			$('[name="dit-with-data"]').prop("checked", false);
			with_data = false;

			if(verbose) {
				msgprint(__("You are not allowed to export the data of: {0}. Downloading empty template.", [doctype]));
			}
		}
		return with_data;
	};

	wrapper.add_template_download_link = function(doctype) {
		return $('')
			.html(doctype)
			.data('doctype', doctype)
			.data('all_doctypes', "No")
			.click(function() {
				var doctype = $(this).data('doctype');
				var parent_doctype = $('[name="dit-doctype"]').val();
				var with_data = validate_download_with_data(parent_doctype || doctype, true);
				window.location.href = repl(frappe.request.url
					+ '?cmd=%(cmd)s&doctype=%(doctype)s'
					+ '&parent_doctype=%(parent_doctype)s'
					+ '&with_data=%(with_data)s'
					+ '&all_doctypes=%(all_doctypes)s',
					{
						cmd: 'frappe.core.page.data_import_tool.exporter.get_template',
						doctype: doctype,
						parent_doctype: parent_doctype,
						with_data: with_data ? 'Yes' : 'No',
						all_doctypes: $(this).data('all_doctypes')
					});
			})
			.appendTo('#dit-download');
	}

	// load options
	$select.change(function() {
		var val = $(this).val()
		if(val!='Select...') {
			$('#dit-download').empty().removeClass("hide");

			frappe.model.with_doctype(val, function() {
				validate_download_with_data(val);

				// get options
				return frappe.call({
					btn: this,
					method: 'frappe.core.page.data_import_tool.data_import_tool.get_doctype_options',
					args: {doctype: val},
					callback: function(r) {
						$('
 Download
').appendTo('#dit-download');
						var with_data = $('[name="dit-with-data"]:checked').length ? 'Yes' : 'No';
						// download link
						$.each(r.message, function(i, v) {
							if(i==0)
								$('Main Table:
').appendTo('#dit-download');
							if(i==1)
								$('
Child Tables:
').appendTo('#dit-download');

							wrapper.add_template_download_link(v);
							$('#dit-download').append('
');
						});

						if(r.message.length > 1) {
							$('
All Tables (Main + Child Tables):
').appendTo('#dit-download');
							var link = wrapper
								.add_template_download_link(r.message[0])
								.data('all_doctypes', "Yes")
						}
					}
				})
			});
		}
	});

	var write_messages = function(r) {
		$(wrapper).find(".dit-progress-area").toggle(false);
		$("#dit-output").empty();

		$.each(r.messages, function(i, v) {
			var $p = $('

').html(frappe.markdown(v)).appendTo('#dit-output');
			$("
").appendTo('#dit-output');
			if(v.substr(0,5)=='Error') {
				$p.css('color', 'red');
			} else if(v.substr(0,8)=='Inserted') {
				$p.css('color', 'green');
			} else if(v.substr(0,7)=='Updated') {
				$p.css('color', 'green');
			} else if(v.substr(0,5)=='Valid') {
				$p.css('color', '#777');
			}
		});
	}

	var onerror = function(r) {
		r.messages = $.map(r.message.messages, function(v) {
			var msg = v.replace("Inserted", "Valid")
				.replace("Updated", "Valid").split("<");
			if (msg.length > 1) {
				v = msg[0] + (msg[1].split(">").slice(-1)[0]);
			} else {
				v = msg[0];
			}
			return v;
		});

		r.messages = ["
Import Failed!
"]
			.concat(r.messages);

		write_messages(r);
	};

	// upload
	frappe.upload.make({
		parent: $('#dit-upload-area'),
		args: {
			method: 'frappe.core.page.data_import_tool.importer.upload'
		},
		onerror: onerror,
		callback: function(attachment, r) {
			if(r.message.error) {
				onerror(r);
			} else {
				// replace links if error has occured
				r.messages = ["
Import Successful!
"].
					concat(r.message.messages)

				write_messages(r);
			}
		}
	});

	// add overwrite option
	var $submit_btn = $('#dit-upload-area button.btn-upload')
		.html(' ' + __("Upload and Import"));

	$('<input type="checkbox" name="overwrite"> Overwrite\

If you are uploading a child table (for example Item Price), the all the entries of that table will be deleted (for that parent record) and new entries will be made.

')
		.insertBefore($submit_btn);

	// add submit option
	$('<input type="checkbox" name="_submit"> Submit\

If you are inserting new records (overwrite not checked) \
			and if you have submit permission, the record will be submitted.

')
		.insertBefore($submit_btn);

	// add ignore option
	$('<input type="checkbox" name="ignore_encoding_errors"> Ignore Encoding Errors

')
		.insertBefore($submit_btn);

	// rename button
	$('#dit-upload-area button.btn-upload')
		.click(function() {
			$('#dit-output').empty();
			$(wrapper).find(".dit-progress-area").toggle(true);
		});
}

frappe.pages['data-import-tool'].onshow = function(wrapper) {
	wrapper.set_route_options && wrapper.set_route_options();
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

(function() {
    'use strict';

    var DIR         = process.cwd(),
        fs          = require('fs'),
        exec        = require('child_process').exec,

        Util        = require('util-io'),

        argv        = require('minimist')(process.argv.slice(2)),

        tryRequire  = require('../lib/tryRequire'),

        Info        = tryRequire(DIR + '/package', {log: true});

    if (Info)
        start(argv._[0]);

    function start(versionNew) {
        var isV         = /^v/.test(versionNew),
            version     = 'v' + Info.version,
            name        = 'ChangeLog',

            gitTempl    = 'git log {{ version }}..HEAD --pretty=format:"- %s" --grep {{ category }} | sed  \'s/{{ category }}//g\'',

            gitFix      = Util.render(gitTempl, {
               category : 'fix' ,
               version  : version
            }),

            gitFeature  = Util.render(gitTempl, {
               category: 'feature',
               version  : version
            });

        if (!isV && versionNew)
            versionNew  = 'v' + versionNew;

        fs.readFile(name, 'utf8', function(error, fileData) {
            Util.exec.parallel([
                Util.exec.with(exec, gitFix),
                Util.exec.with(exec, gitFeature),
                ], function(error, fixData, featureData) {
                    var fix, feature,
                        DATA        = 0,
                        STD_ERR     = 1,
                        date        = Util.getShortDate(),
                        head        = date + ', ' + versionNew + '\n\n',
                        data        = '';

                    if (!error) {
                        fix         = fixData[DATA];
                        feature     = featureData[DATA];
                    }

                    if (fix || feature) {
                        data        = head;

                        if (fix) {
                            data    += 'fix:'       + '\n';
                            data    += fix          + '\n';
                        }

                        if (feature) {
                            data    += 'feature:'   + '\n';
                            data    += feature      + '\n';
                        }

                        if (fileData)
                            data        += '\n\n' + fileData;
                    }

                    error   = error || fixData[STD_ERR] || featureData[STD_ERR];

                    if (error)
                        console.error(error);
                    else if (!data)
                        console.log('No new feature and fix commits from', version);
                    else if (!versionNew)
                        console.log(data);
                    else
                        fs.writeFile(name, data, function(error) {
                                var msg = 'changelog: done';

                                console.log(error || msg);
                            });
                });
        });
    }
})();
<commit_msg>feature(changelog) head: if !versionNew put empty string<commit_after>#!/usr/bin/env node

(function() {
    'use strict';

    var DIR         = process.cwd(),
        fs          = require('fs'),
        exec        = require('child_process').exec,

        Util        = require('util-io'),

        argv        = require('minimist')(process.argv.slice(2)),

        tryRequire  = require('../lib/tryRequire'),

        Info        = tryRequire(DIR + '/package', {log: true});

    if (Info)
        start(argv._[0]);

    function start(versionNew) {
        var isV         = /^v/.test(versionNew),
            version     = 'v' + Info.version,
            name        = 'ChangeLog',

            gitTempl    = 'git log {{ version }}..HEAD --pretty=format:"- %s" --grep {{ category }} | sed  \'s/{{ category }}//g\'',

            gitFix      = Util.render(gitTempl, {
               category : 'fix' ,
               version  : version
            }),

            gitFeature  = Util.render(gitTempl, {
               category: 'feature',
               version  : version
            });

        if (!isV && versionNew)
            versionNew  = 'v' + versionNew;

        fs.readFile(name, 'utf8', function(error, fileData) {
            Util.exec.parallel([
                Util.exec.with(exec, gitFix),
                Util.exec.with(exec, gitFeature),
                ], function(error, fixData, featureData) {
                    var fix, feature,
                        DATA        = 0,
                        STD_ERR     = 1,
                        date        = Util.getShortDate(),
                        head        = date + ', ' + (versionNew || '') + '\n\n',
                        data        = '';

                    if (!error) {
                        fix         = fixData[DATA];
                        feature     = featureData[DATA];
                    }

                    if (fix || feature) {
                        data        = head;

                        if (fix) {
                            data    += 'fix:'       + '\n';
                            data    += fix          + '\n';
                        }

                        if (feature) {
                            data    += 'feature:'   + '\n';
                            data    += feature      + '\n';
                        }

                        if (fileData)
                            data        += '\n\n' + fileData;
                    }

                    error   = error || fixData[STD_ERR] || featureData[STD_ERR];

                    if (error)
                        console.error(error);
                    else if (!data)
                        console.log('No new feature and fix commits from', version);
                    else if (!versionNew)
                        console.log(data);
                    else
                        fs.writeFile(name, data, function(error) {
                                var msg = 'changelog: done';

                                console.log(error || msg);
                            });
                });
        });
    }
})();
<|endoftext|>


<commit_before>const path = require('path');
const Dropbox = require('dropbox');
const mongoose = require('mongoose');
const moment = require('moment');

require('dotenv').config({ path: path.join(__dirname, '/../variables.env') });

mongoose.connect(process.env.DATABASE);
mongoose.Promise = global.Promise;

const dbx = new Dropbox({ accessToken: process.env.DROPBOX_TOKEN });
const Snapshot = require('../models/Snapshot');

async function loadData(snapshots, mostRecent) {
  try {
    console.log('Checking files for new snapshots...');
    const newSnapshots = [];
    snapshots.forEach((snapshot) => {
      if (moment(snapshot.date).isAfter(mostRecent)) {
        newSnapshots.push(snapshot);
      }
    });
    if (newSnapshots.length === 0) {
      console.log('No new snapshots.');
      process.exit();
    }
    console.log(`Uploading ${newSnapshots.length} snapshots...`);
    await Snapshot.insertMany(newSnapshots);
    console.log('Uploading data complete!\n');
    process.exit();
  } catch (e) {
    console.log(e);
    process.exit();
  }
}

async function getData(sharedLinks) {
  try {
    const snapshots = [];
    await Promise.all(sharedLinks.map(async (sharedLink) => {
      const file = await dbx.sharingGetSharedLinkFile({ url: sharedLink.url });
      const data = JSON.parse(file.fileBinary);
      const dailySnapshots = data.snapshots;
      dailySnapshots.map(dailySnapshot => snapshots.push(dailySnapshot));
    }));
    return snapshots;
  } catch (e) {
    console.log(e);
    process.exit();
  }
}

async function getDropboxList(mostRecent) {
  try {
    const recentFile = moment(mostRecent).subtract(1, 'day').format('YYYY-MM-DD');
    const response = await dbx.filesListFolder({ path: '/apps/reporter-app' });
    const entries = response.entries.sort((a, b) => new Date(b.name.split('-reporter')[0]) - new Date(a.name.split('-reporter')[0]));

    const paths = [];
    entries.forEach((entry) => {
      const fileDate = entry.name.split('-reporter')[0];
      if (moment(fileDate).isSameOrAfter(recentFile)) {
        paths.push(entry.path_lower);
      }
    });
    console.log(`${paths.length} new ${paths.length === 1 ? 'file' : 'files'} in dropbox.`);
    return paths;
  } catch (e) {
    console.log(e);
    process.exit();
  }
}

async function findNewestSnapshot() {
  try {
    const mostRecentSnap = await Snapshot
      .find()
      .sort({ date: -1 })
      .limit(1);

    let mostRecentSnapDate;
    if (mostRecentSnap.length > 1) {
      mostRecentSnapDate = mostRecentSnap[0].date;
      const mostRecentFormated = moment(mostRecentSnap[0].date).format('LLL');
      console.log(`\nThe latest snapshot in your database is from ${mostRecentFormated}.`);
    } else {
      mostRecentSnapDate = new Date('2000-01-01');
      console.log('\nNo snapshots found in database.');
    }
    return mostRecentSnapDate;
  } catch (e) {
    console.log(e);
    process.exit();
  }
}

async function update() {
  const mostRecent = await findNewestSnapshot();
  const pathList = await getDropboxList(mostRecent);
  const sharedLinks = [];
  await Promise.all(pathList.map(async (path) => {
    const sharedLink = await dbx.sharingCreateSharedLink({ path });
    sharedLinks.push(sharedLink);
  }));
  const snapshots = await getData(sharedLinks);
  await loadData(snapshots, mostRecent);
  process.exit();
}

update();
<commit_msg>When I said >, I meant === 😅<commit_after>const path = require('path');
const Dropbox = require('dropbox');
const mongoose = require('mongoose');
const moment = require('moment');

require('dotenv').config({ path: path.join(__dirname, '/../variables.env') });

mongoose.connect(process.env.DATABASE);
mongoose.Promise = global.Promise;

const dbx = new Dropbox({ accessToken: process.env.DROPBOX_TOKEN });
const Snapshot = require('../models/Snapshot');

async function loadData(snapshots, mostRecent) {
  try {
    console.log('Checking files for new snapshots...');
    const newSnapshots = [];
    snapshots.forEach((snapshot) => {
      if (moment(snapshot.date).isAfter(mostRecent)) {
        newSnapshots.push(snapshot);
      }
    });
    if (newSnapshots.length === 0) {
      console.log('No new snapshots. You’re up to date!\n');
      process.exit();
    }
    console.log(`Uploading ${newSnapshots.length} snapshots...`);
    await Snapshot.insertMany(newSnapshots);
    console.log('Uploading data complete!\n');
    process.exit();
  } catch (e) {
    console.log(e);
    process.exit();
  }
}

async function getData(sharedLinks) {
  try {
    const snapshots = [];
    await Promise.all(sharedLinks.map(async (sharedLink) => {
      const file = await dbx.sharingGetSharedLinkFile({ url: sharedLink.url });
      const data = JSON.parse(file.fileBinary);
      const dailySnapshots = data.snapshots;
      dailySnapshots.map(dailySnapshot => snapshots.push(dailySnapshot));
    }));
    return snapshots;
  } catch (e) {
    console.log(e);
    process.exit();
  }
}

async function getDropboxList(mostRecent) {
  try {
    const recentFile = moment(mostRecent).subtract(1, 'day').format('YYYY-MM-DD');
    const response = await dbx.filesListFolder({ path: '/apps/reporter-app' });
    const entries = response.entries.sort((a, b) => new Date(b.name.split('-reporter')[0]) - new Date(a.name.split('-reporter')[0]));

    const paths = [];
    entries.forEach((entry) => {
      const fileDate = entry.name.split('-reporter')[0];
      if (moment(fileDate).isSameOrAfter(recentFile)) {
        paths.push(entry.path_lower);
      }
    });
    console.log(`${paths.length} new ${paths.length === 1 ? 'file' : 'files'} in dropbox.`);
    return paths;
  } catch (e) {
    console.log(e);
    process.exit();
  }
}

async function findNewestSnapshot() {
  try {
    const mostRecentSnap = await Snapshot
      .find()
      .sort({ date: -1 })
      .limit(1);

    let mostRecentSnapDate;
    if (mostRecentSnap.length === 1) {
      mostRecentSnapDate = mostRecentSnap[0].date;
      const mostRecentFormated = moment(mostRecentSnap[0].date).format('LLL');
      console.log(`\nThe latest snapshot in your database is from ${mostRecentFormated}.`);
    } else {
      mostRecentSnapDate = new Date('2000-01-01');
      console.log('\nNo snapshots found in database.');
    }
    return mostRecentSnapDate;
  } catch (e) {
    console.log(e);
    process.exit();
  }
}

async function update() {
  const mostRecent = await findNewestSnapshot();
  const pathList = await getDropboxList(mostRecent);
  const sharedLinks = [];
  await Promise.all(pathList.map(async (path) => {
    const sharedLink = await dbx.sharingCreateSharedLink({ path });
    sharedLinks.push(sharedLink);
  }));
  const snapshots = await getData(sharedLinks);
  await loadData(snapshots, mostRecent);
  process.exit();
}

update();
<|endoftext|>


<commit_before>import * as t from 'constants/ActionTypes';
import { comicManagers } from 'services';
import { addRecentComic, updateReadingRecord } from 'actions/ConfigActions';
import { replaceChapterCache } from 'actions';

export const initComicManager = ({site, chapterID, readingChapterID}) => {
	return (dispatch, getState) => {
		let comicManager = comicManagers.selectComicManager(site);

		comicManager.getComic(chapterID).then(comicInfo => {
			const {
				comicID,
				comicName,
				coverImage,
				chapters,
				latestChapter
			} = comicInfo;

			if (chapterID === readingChapterID) {
				return;
			}

			dispatch({type: t.CLEAR_COMIC_IMAGES});

			addRecentComic({comicID, coverImage, comicName, latestChapter})(dispatch);
			updateReadingRecord({comicID, chapterID})(dispatch);
			replaceChapterCache({comicID, chapters});

			dispatch({
				type: t.SET_COMIC_NAME,
				comicName: comicName
			});

			dispatch({
				type: t.INIT_COMIC_MANAGER,
				comicManager: comicManager,
				chapters: chapters,
				comicID: comicID
			});

			const { readingRecord } = getState().config;

			/* load last read chapter */
			if (typeof readingRecord[comicID] !== 'undefined') {
				const { _id, _rev, ...readingComicRecord } = readingRecord[comicID];
				const reverseRecordMap = Object.keys(readingComicRecord).reduce((prev, cur) => {
					return {...prev, [readingComicRecord[cur]]: cur};
				}, {});
				const lastChapterID = reverseRecordMap[Math.max(...Object.keys(reverseRecordMap))];
				chapterID = lastChapterID;
			}

			comicManager.getChapterImages(chapterID).then(images => {
				let chapterItem = chapters.find(item => item.chapterID == chapterID);

				dispatch({
					type: t.SWITCH_CHAPTER,
					readingChapters: [chapterItem],
					readingImages: [images],
					appBarTitle: chapterItem.title,
					readingChapterID: chapterID
				});
			});
		});
	};
};

export const switchChapter = (chapterItem) => {
	return dispatch => {
		dispatch({type: t.SWITCH_CHAPTER_REQUEST, chapterItem});
	};
};
<commit_msg>Load first chapter if hasn't read yet<commit_after>import * as t from 'constants/ActionTypes';
import { comicManagers } from 'services';
import { addRecentComic, updateReadingRecord } from 'actions/ConfigActions';
import { replaceChapterCache } from 'actions';

export const initComicManager = ({site, chapterID, readingChapterID}) => {
	return (dispatch, getState) => {
		let comicManager = comicManagers.selectComicManager(site);

		comicManager.getComic(chapterID).then(comicInfo => {
			const {
				comicID,
				comicName,
				coverImage,
				chapters,
				latestChapter
			} = comicInfo;

			if (chapterID === readingChapterID) {
				return;
			}

			dispatch({type: t.CLEAR_COMIC_IMAGES});
			replaceChapterCache({comicID, chapters});

			dispatch({
				type: t.SET_COMIC_NAME,
				comicName: comicName
			});

			dispatch({
				type: t.INIT_COMIC_MANAGER,
				comicManager: comicManager,
				chapters: chapters,
				comicID: comicID
			});

			const { readingRecord } = getState().config;

			/* load last read chapter */
			if (typeof readingRecord[comicID] !== 'undefined') {
				const { _id, _rev, ...readingComicRecord } = readingRecord[comicID];
				const reverseRecordMap = Object.keys(readingComicRecord).reduce((prev, cur) => {
					return {...prev, [readingComicRecord[cur]]: cur};
				}, {});
				const lastChapterID = reverseRecordMap[Math.max(...Object.keys(reverseRecordMap))];

				chapterID = lastChapterID;
			} else {
				// start from first chapter
				chapterID = chapters[chapters.length-1].chapterID;
			}

			comicManager.getChapterImages(chapterID).then(images => {
				let chapterItem = chapters.find(item => item.chapterID == chapterID);

				updateReadingRecord({comicID, chapterID})(dispatch);
				addRecentComic({comicID, coverImage, comicName, latestChapter})(dispatch);

				dispatch({
					type: t.SWITCH_CHAPTER,
					readingChapters: [chapterItem],
					readingImages: [images],
					appBarTitle: chapterItem.title,
					readingChapterID: chapterID
				});
			});
		});
	};
};

export const switchChapter = (chapterItem) => {
	return dispatch => {
		dispatch({type: t.SWITCH_CHAPTER_REQUEST, chapterItem});
	};
};
<|endoftext|>


<commit_before>/*jslint browser: true*/

function MProgress(styles) {
    this.el = document.createElement('div');

    this.styles = {
        position: 'fixed',
        width: '0%',
        height: '2px',
        top: '0',
        left: '0',
        right: '0',
        background: 'red',
        transition: 'width 0.5s'
    };
    for (var key in styles) {
        this.styles[key] = styles[key];
    }
    for(var key in this.styles) {
        this.el.style[key] = this.styles[key];
    }

    this.random = function (min, max) {
        return Math.random() * (max - min) + min;
    };
    return this;
}

MProgress.prototype.interval = function (interval) {
    this.intervalID = setInterval(function () {
        this.increase();
    }.bind(this), interval || 500);
    return this;
};

MProgress.prototype.show = function () {
    document.getElementsByTagName('body')[0].appendChild(this.el);
    return this;
};

MProgress.prototype.hide = function () {
    this.set(100);
    setTimeout(this.remove.bind(this), 500);
    return this;
};

MProgress.prototype.remove = function () {
    if(this.intervalID) {
        clearInterval(this.intervalID);
    }
    this.el.parentNode.removeChild(this.el);
    return this;
};

MProgress.prototype.set = function (val) {
    this.el.style.width = val + '%';
    return this;
};

MProgress.prototype.get = function () {
    return parseFloat(this.el.style.width.split('%')[0]);
};

MProgress.prototype.increase = function (val) {
    if(!val) {
        val = this.random(0, (100 - this.get()) / 25);
    }
    this.set(Math.min(this.get() + val, 99.9));
    return this;
};
<commit_msg>Add default z-index of 100<commit_after>/*jslint browser: true*/

function MProgress(styles) {
    this.el = document.createElement('div');

    this.styles = {
        position: 'fixed',
        width: '0%',
        height: '2px',
        top: '0',
        left: '0',
        right: '0',
        zIndex: '100',
        background: 'red',
        transition: 'width 0.5s'
    };
    for (var key in styles) {
        this.styles[key] = styles[key];
    }
    for(var key in this.styles) {
        this.el.style[key] = this.styles[key];
    }

    this.random = function (min, max) {
        return Math.random() * (max - min) + min;
    };
    return this;
}

MProgress.prototype.interval = function (interval) {
    this.intervalID = setInterval(function () {
        this.increase();
    }.bind(this), interval || 500);
    return this;
};

MProgress.prototype.show = function () {
    document.getElementsByTagName('body')[0].appendChild(this.el);
    return this;
};

MProgress.prototype.hide = function () {
    this.set(100);
    setTimeout(this.remove.bind(this), 500);
    return this;
};

MProgress.prototype.remove = function () {
    if(this.intervalID) {
        clearInterval(this.intervalID);
    }
    this.el.parentNode.removeChild(this.el);
    return this;
};

MProgress.prototype.set = function (val) {
    this.el.style.width = val + '%';
    return this;
};

MProgress.prototype.get = function () {
    return parseFloat(this.el.style.width.split('%')[0]);
};

MProgress.prototype.increase = function (val) {
    if(!val) {
        val = this.random(0, (100 - this.get()) / 25);
    }
    this.set(Math.min(this.get() + val, 99.9));
    return this;
};
<|endoftext|>


<commit_before>'use strict';

var config       = require('../config')
  , models       = require('../models')
  , lib          = require('../lib')
  , render       = lib.render
  , logger       = lib.logger
  , getEmailHTML = lib.getEmailHTML
  , getEmailText = lib.getEmailText
  , sendgrid     = require('sendgrid')(config.sendgrid.apikey)
  ;

module.exports.init = function(app) {
  app.get('/contact', getContact);
  app.post('/contact', postContact);

  app.get('/thank-you', getThankYou);
};

function getContact(req, res) {
  render(res, 'contact', {
    pageTitle: 'Request a Quote',
    showFooterCTA: false,
    metaDescription: 'Contact the freelance developer for a free quote and website consultation.',
    preMessage: req.query.consultation ? "Hi Will,\n\nPlease contact me ASAP for a free 1/2 hour consultation! \n\n(tell me more about your project here...)" : ''
  });
}

function postContact(req, res) {
  var formIsValid = false
    , formValues  = req.body.contact;

  var lead = new models.Lead({
    name: formValues.name,
    email: formValues.email,
    message: formValues.message,
    host: req.get('host')
  });

  lead.save(function(err, lead) {
    if (err) {
      return res.redirect('/contact'); // prevent serving a cached version of this page
    } else {

      var mailHelper = require('sendgrid').mail;
      var from_email = new mailHelper.Email(config.serverEmail);
      var to_email = new mailHelper.Email(config.adminEmail);
      var subject = 'Contact request from: ' + lead.name;

      var textContent = new mailHelper.Content("text/plain", getEmailText('contact', lead));
      var htmlContent = new mailHelper.Content("text/html", getEmailHTML('contact', lead));

      var mail = new mailHelper.Mail(from_email, subject, to_email, textContent);
      mail.addContent(htmlContent);

      var reply_email = new mailHelper.Email(lead.email)
      mail.setReplyTo(reply_email);

      var request = sendgrid.emptyRequest({
        method: 'POST',
        path: '/v3/mail/send',
        body: mail.toJSON(),
      });

      sendgrid.API(request, function(err, response) {
        if (err) {
          logger.error(err);
        }

        return res.redirect('/thank-you');
      });
    }
  });
}

function getThankYou(req, res) {
  // facebook conversion tracker
  var facebookConversionTracker = "";

  render(res, 'thanks', {
    pageTitle: 'Thank You',
    showFooterCTA: false,
    headerJS: config.env == 'production' ? facebookConversionTracker : false
  });
}
<commit_msg>cleaner consultation message<commit_after>'use strict';

var config       = require('../config')
  , models       = require('../models')
  , lib          = require('../lib')
  , render       = lib.render
  , logger       = lib.logger
  , getEmailHTML = lib.getEmailHTML
  , getEmailText = lib.getEmailText
  , sendgrid     = require('sendgrid')(config.sendgrid.apikey)
  ;

module.exports.init = function(app) {
  app.get('/contact', getContact);
  app.post('/contact', postContact);

  app.get('/thank-you', getThankYou);
};

function getContact(req, res) {
  var wantsConsultation = req.query.consultation == '1';
  var metaDescription = 'Contact the freelance developer for a free quote and website consultation.';
  var preMessage = '';

  if(wantsConsultation) {
    preMessage = "Hi Will,\n\nPlease contact me ASAP for a free 1/2 hour consultation! \n\n(tell me more about your project here...)";
  }

  render(res, 'contact', {
    pageTitle: 'Request a Quote',
    showFooterCTA: false,
    metaDescription: metaDescription,
    preMessage: preMessage
  });
}

function postContact(req, res) {
  var formIsValid = false
    , formValues  = req.body.contact;

  var lead = new models.Lead({
    name: formValues.name,
    email: formValues.email,
    message: formValues.message,
    host: req.get('host')
  });

  lead.save(function(err, lead) {
    if (err) {
      return res.redirect('/contact'); // prevent serving a cached version of this page
    } else {

      var mailHelper = require('sendgrid').mail;
      var from_email = new mailHelper.Email(config.serverEmail);
      var to_email = new mailHelper.Email(config.adminEmail);
      var subject = 'Contact request from: ' + lead.name;

      var textContent = new mailHelper.Content("text/plain", getEmailText('contact', lead));
      var htmlContent = new mailHelper.Content("text/html", getEmailHTML('contact', lead));

      var mail = new mailHelper.Mail(from_email, subject, to_email, textContent);
      mail.addContent(htmlContent);

      var reply_email = new mailHelper.Email(lead.email)
      mail.setReplyTo(reply_email);

      var request = sendgrid.emptyRequest({
        method: 'POST',
        path: '/v3/mail/send',
        body: mail.toJSON(),
      });

      sendgrid.API(request, function(err, response) {
        if (err) {
          logger.error(err);
        }

        return res.redirect('/thank-you');
      });
    }
  });
}

function getThankYou(req, res) {
  // facebook conversion tracker
  var facebookConversionTracker = "";

  render(res, 'thanks', {
    pageTitle: 'Thank You',
    showFooterCTA: false,
    headerJS: config.env == 'production' ? facebookConversionTracker : false
  });
}
<|endoftext|>


<commit_before>/* jshint node:true */
'use strict';

var fs = require('fs');
var glob = require('glob');
var Promise = require('promise');
var sprintf = require('sprintf');

var globForFile;
var readFile;
var getFile;

getFile = function getFile(filePath) {
  return globForFile(filePath)
    .then(readFile)
    .then(function returnPromise(file) {
      return file;
    })
    .catch (function catchErr(err) {
      var errMsg = sprintf('### Error: %s', err);
      //console.error(errMsg);

      return errMsg;
    });
};

globForFile = function globForFile(file) {
  return Promise.denodeify(glob)(file);
};

readFile = function readFile(file) {
  var promise = new Promise(function(resolve, reject) {
    fs.readFile(file.path || file[0], 'utf8', function(err, res) {
      if (err) reject(err);
      if (! !! res) reject("File empty");
      else resolve(res);
    });
  });

  return promise;
};

(function run() {
  // If (require.main === module), this module was
  // called directly like via the cli.
  // If (require.main !== module), this module was
  // "require'd" like var gll = require('./getLastLine');
  if (require.main === module)
    getFile( !! process.argv[2] ? process.argv[2] : '/Users/wkseymou/projects/chroma/chroma-manager/chroma_ui_new/static/chroma_ui/*.map')
    .then(function(response) {
      console.log('### response: \n\t%s', response);
    })
      .done();
})();

module.exports = {
  getFile: getFile
};
<commit_msg>Wrapped in an iffy<commit_after>(function () {
  /* jshint node:true */

  'use strict';

  var fs = require('fs');
  var glob = require('glob');
  var Promise = require('promise');
  var sprintf = require('sprintf');

  var globForFile;
  var readFile;
  var getFile;

  getFile = function getFile (filePath) {
    return globForFile(filePath)
      .then(readFile)
      .then(function returnPromise (file) {
        return file;
      })
      .catch(function catchErr (err) {
      var errMsg = sprintf('### Error: %s', err);
      //console.error(errMsg);

      return errMsg;
    });
  };

  globForFile = function globForFile (file) {
    return Promise.denodeify(glob)(file);
  };

  readFile = function readFile (file) {
    var promise = new Promise(function (resolve, reject) {
      fs.readFile(file.path || file[0], 'utf8', function (err, res) {
        if (err) reject(err);
        if (!!!res) reject("File empty");
        else resolve(res);
      });
    });

    return promise;
  };

  (function run () {
    // If (require.main === module), this module was
    // called directly like via the cli.
    // If (require.main !== module), this module was
    // "require'd" like var gll = require('./getLastLine');
    if (require.main === module)
      getFile(!!process.argv[2] ? process.argv[2] : '/Users/wkseymou/projects/chroma/chroma-manager/chroma_ui_new/static/chroma_ui/*.map')
        .then(function (response) {
          console.log('### response: \n\t%s', response);
        })
        .done();
  })();

  module.exports = {
    getFile: getFile
  };
})();

<|endoftext|>


<commit_before>
frappe.provide('frappe.views');

frappe.views.ListGroupBy = class ListGroupBy {
	constructor(opts) {
		$.extend(this, opts);
		this.make_wrapper();

		this.user_settings = frappe.get_user_settings(this.doctype);
		this.group_by_fields = ['assigned_to'];
		if(this.user_settings.group_by_fields) {
			this.group_by_fields = this.group_by_fields.concat(this.user_settings.group_by_fields);
		}
		this.render_group_by_items();
		this.make_group_by_fields_modal();
		this.setup_dropdown();
		this.setup_filter_by();
	}

	make_group_by_fields_modal() {
		let d = new frappe.ui.Dialog ({
			title: __("Select Filters"),
			fields: this.get_group_by_dropdown_fields()
		});
		d.set_primary_action("Save", ({ group_by_fields }) => {
			frappe.model.user_settings.save(this.doctype, 'group_by_fields', group_by_fields || null);
			this.group_by_fields = group_by_fields ? ['assigned_to', ...group_by_fields] : ['assigned_to'];
			this.render_group_by_items();
			d.hide();
		});

		this.page.sidebar.find(".add-list-group-by a ").on("click", () => {
			d.show();
		});
	}

	make_wrapper() {
		this.$wrapper = this.sidebar.sidebar.find('.list-group-by');
		let html = `

				${__('Filter By')}

					${__("Add Fields")}

		`;
		this.$wrapper.html(html);
	}

	render_group_by_items() {
		let get_item_html = (fieldname) => {
			let label = fieldname === 'assigned_to'
				? __('Assigned To')
				: frappe.meta.get_label(this.doctype, fieldname);

			return `

						${__(label)}

							${__("Loading...")}

`;
		};
		let html = this.group_by_fields.map(get_item_html).join('');
		this.$wrapper.find('.list-group-by-fields').html(html);
	}

	setup_dropdown() {
		this.$wrapper.on('click', '.group-by-field', (e)=> {
			let dropdown = $(e.currentTarget).find('.group-by-dropdown');
			let fieldname = $(e.currentTarget).find('a').attr('data-fieldname');
			this.get_group_by_count(fieldname).then(field_count_list => {
				if (field_count_list.length) {
					this.render_dropdown_items(field_count_list, dropdown);
					this.sidebar.setup_dropdown_search(dropdown, '.group-by-value');
				} else {
					dropdown.find('.group-by-loading').hide();
				}
			});
		});
	}

	get_group_by_dropdown_fields() {
		let group_by_fields = [];
		let fields = this.list_view.meta.fields.filter((f)=> ["Select", "Link"].includes(f.fieldtype));
		group_by_fields.push({
			label: __(this.doctype),
			fieldname: 'group_by_fields',
			fieldtype: 'MultiCheck',
			columns: 2,
			options: fields
				.map(df => ({
					label: __(df.label),
					value: df.fieldname,
					checked: this.group_by_fields.includes(df.fieldname)
				}))
		});
		return group_by_fields;
	}

	get_group_by_count(field) {
		let current_filters = this.list_view.get_filters_for_args();

		// remove filter of the current field
		current_filters = current_filters.filter((f_arr) => !f_arr.includes(field === 'assigned_to' ? '_assign': field));

		let args =  {
			doctype: this.doctype,
			current_filters: current_filters,
			field: field,
		};

		return frappe.call('frappe.desk.listview.get_group_by_count', args).then((r) => {
			let field_counts = r.message || [];
			field_counts = field_counts.filter(f => f.count !== 0);
			if (field === 'assigned_to') {
				field_counts = field_counts.filter(f => !['Guest', 'Administrator'].includes(f.name));
			}
			return field_counts;
		});
	}

	render_dropdown_items(fields, dropdown) {
		let get_dropdown_html = (field) => {
			let label = field.name == null ? __('Not Specified') : field.name;
			if (label === frappe.session.user) {
				label = __('Me');
			}
			let value = field.name == null ? '' : encodeURIComponent(field.name);

			return `

					${label}
					${field.count}

`;
		};
		let standard_html = `

				<input type="text" placeholder="${__('Search')}" class="form-control dropdown-search-input input-xs">

		`;
		let dropdown_html = standard_html + fields.map(get_dropdown_html).join('');
		dropdown.html(dropdown_html);
	}

	setup_filter_by() {
		this.$wrapper.on('click', '.group-by-item', (e) => {
			let $target = $(e.currentTarget);
			let fieldname = $target.parents('.group-by-field').find('a').data('fieldname');
			let value = decodeURIComponent($target.data('value').trim());
			fieldname = fieldname === 'assigned_to' ? '_assign': fieldname;

			this.list_view.filter_area.remove(fieldname);

			let operator = '=';
			if (value === '') {
				operator = 'is';
				value = 'not set';
			}
			if (fieldname === '_assign') {
				operator = 'like';
				value = `%${value}%`;
			}

			this.list_view.filter_area.add(this.doctype, fieldname, operator, value);
		});
	}

};<commit_msg>refactor: filters can be reapplied from dropdown<commit_after>
frappe.provide('frappe.views');

frappe.views.ListGroupBy = class ListGroupBy {
	constructor(opts) {
		$.extend(this, opts);
		this.make_wrapper();

		this.user_settings = frappe.get_user_settings(this.doctype);
		this.group_by_fields = ['assigned_to'];
		if(this.user_settings.group_by_fields) {
			this.group_by_fields = this.group_by_fields.concat(this.user_settings.group_by_fields);
		}
		this.render_group_by_items();
		this.make_group_by_fields_modal();
		this.setup_dropdown();
		this.setup_filter_by();
	}

	make_group_by_fields_modal() {
		let d = new frappe.ui.Dialog ({
			title: __("Select Filters"),
			fields: this.get_group_by_dropdown_fields()
		});
		d.set_primary_action("Save", ({ group_by_fields }) => {
			frappe.model.user_settings.save(this.doctype, 'group_by_fields', group_by_fields || null);
			this.group_by_fields = group_by_fields ? ['assigned_to', ...group_by_fields] : ['assigned_to'];
			this.render_group_by_items();
			d.hide();
		});

		this.page.sidebar.find(".add-list-group-by a ").on("click", () => {
			d.show();
		});
	}

	make_wrapper() {
		this.$wrapper = this.sidebar.sidebar.find('.list-group-by');
		let html = `

				${__('Filter By')}

					${__("Add Fields")}

		`;
		this.$wrapper.html(html);
	}

	render_group_by_items() {
		let get_item_html = (fieldname) => {
			let label = fieldname === 'assigned_to'
				? __('Assigned To')
				: frappe.meta.get_label(this.doctype, fieldname);

			return `

						${__(label)}

							${__("Loading...")}

`;
		};
		let html = this.group_by_fields.map(get_item_html).join('');
		this.$wrapper.find('.list-group-by-fields').html(html);
	}

	setup_dropdown() {
		this.$wrapper.on('click', '.group-by-field', (e)=> {
			let dropdown = $(e.currentTarget).find('.group-by-dropdown');
			let fieldname = $(e.currentTarget).find('a').attr('data-fieldname');
			this.get_group_by_count(fieldname).then(field_count_list => {
				if (field_count_list.length) {
					this.render_dropdown_items(field_count_list, dropdown);
					this.sidebar.setup_dropdown_search(dropdown, '.group-by-value');
				} else {
					dropdown.find('.group-by-loading').hide();
				}
			});
		});
	}

	get_group_by_dropdown_fields() {
		let group_by_fields = [];
		let fields = this.list_view.meta.fields.filter((f)=> ["Select", "Link"].includes(f.fieldtype));
		group_by_fields.push({
			label: __(this.doctype),
			fieldname: 'group_by_fields',
			fieldtype: 'MultiCheck',
			columns: 2,
			options: fields
				.map(df => ({
					label: __(df.label),
					value: df.fieldname,
					checked: this.group_by_fields.includes(df.fieldname)
				}))
		});
		return group_by_fields;
	}

	get_group_by_count(field) {
		let current_filters = this.list_view.get_filters_for_args();

		// remove filter of the current field
		current_filters = current_filters.filter((f_arr) => !f_arr.includes(field === 'assigned_to' ? '_assign': field));

		let args =  {
			doctype: this.doctype,
			current_filters: current_filters,
			field: field,
		};

		return frappe.call('frappe.desk.listview.get_group_by_count', args).then((r) => {
			let field_counts = r.message || [];
			field_counts = field_counts.filter(f => f.count !== 0);
			if (field === 'assigned_to') {
				field_counts = field_counts.filter(f => !['Guest', 'Administrator'].includes(f.name));
			}
			return field_counts;
		});
	}

	render_dropdown_items(fields, dropdown) {
		let get_dropdown_html = (field) => {
			let label = field.name == null ? __('Not Specified') : field.name;
			if (label === frappe.session.user) {
				label = __('Me');
			}
			let value = field.name == null ? '' : encodeURIComponent(field.name);

			return `

					${label}
					${field.count}

`;
		};
		let standard_html = `

				<input type="text" placeholder="${__('Search')}" class="form-control dropdown-search-input input-xs">

		`;
		let dropdown_html = standard_html + fields.map(get_dropdown_html).join('');
		dropdown.html(dropdown_html);
	}

	setup_filter_by() {
		this.$wrapper.on('click', '.group-by-item', (e) => {
			let $target = $(e.currentTarget);
			let fieldname = $target.parents('.group-by-field').find('a').data('fieldname');
			let value = decodeURIComponent($target.data('value').trim());
			fieldname = fieldname === 'assigned_to' ? '_assign': fieldname;

			return this.list_view.filter_area.remove(fieldname)
				.then(() => {
					let operator = '=';
					if (value === '') {
						operator = 'is';
						value = 'not set';
					}
					if (fieldname === '_assign') {
						operator = 'like';
						value = `%${value}%`;
					}

					return this.list_view.filter_area.add(this.doctype, fieldname, operator, value);
				});
		});
	}

};<|endoftext|>


<commit_before>(function(){
	// The following is borrowed wholesale from shoestring
	// https://github.com/filamentgroup/shoestring/blob/master/src/core/ready.js
	function onReady( callback ){
		if( ready && callback ){
			callback.call( document );
		} else if( callback ){
			readyQueue.push( callback );
		} else {
			runReady();
		}

		return [document];
	}

	// Empty and exec the ready queue
	var ready = false,
			readyQueue = [],
			runReady = function(){
				if( !ready ){
					while( readyQueue.length ){
						readyQueue.shift().call( document );
					}
					ready = true;
				}
			};

	// Quick IE8 shiv
	if( !window.addEventListener ){
		window.addEventListener = function( evt, cb ){
			return window.attachEvent( "on" + evt, cb );
		};
	}

	// If DOM is already ready at exec time, depends on the browser.
	// From: https://github.com/mobify/mobifyjs/blob/526841be5509e28fc949038021799e4223479f8d/src/capture.js#L128
	if (document.attachEvent ? document.readyState === "complete" : document.readyState !== "loading") {
		runReady();
	} else {
		if( !document.addEventListener ){
			document.attachEvent( "DOMContentLoaded", runReady );
			document.attachEvent( "onreadystatechange", runReady );
		} else {
			document.addEventListener( "DOMContentLoaded", runReady, false );
			document.addEventListener( "readystatechange", runReady, false );
		}
		window.addEventListener( "load", runReady, false );
	}

	// end domready code

	function sendSize(){
		window
			.parent
			.postMessage('{ "iframeheight" : ' +
									document.documentElement.offsetHeight +
									'}', "*");
	}

	window.addEventListener("message", function( event ){
		// same host check
		var origin = event.origin || event.originalEvent.origin;
		var allowedOrigin = new RegExp( "https?:\/\/" + location.host );
		if( !origin.match( allowedOrigin ) ){
			return;
		}

		var data = event.data || event.originalEvent.data;
		var body =	document.querySelector("body");

		// use the passed information to populate the page
		body.innerHTML = data.html;

		// wait until everything loads to calc the height and communicate it
		// TODO it would be better to bind to the load of the styles at least
		onReady(sendSize);
	}, false);

	var minInterval = 300;
	var resized = false;
	window.addEventListener("resize", function(){
		if(resized){ return; }
		sendSize();
		resized = true;
		setTimeout(function(){ resized = false; }, minInterval);
	});
})();
<commit_msg>whitepsace<commit_after>(function(){
	// The following is borrowed wholesale from shoestring
	// https://github.com/filamentgroup/shoestring/blob/master/src/core/ready.js
	function onReady( callback ){
		if( ready && callback ){
			callback.call( document );
		} else if( callback ){
			readyQueue.push( callback );
		} else {
			runReady();
		}

		return [document];
	}

	// Empty and exec the ready queue
	var ready = false,
			readyQueue = [],
			runReady = function(){
				if( !ready ){
					while( readyQueue.length ){
						readyQueue.shift().call( document );
					}
					ready = true;
				}
			};

	// Quick IE8 shiv
	if( !window.addEventListener ){
		window.addEventListener = function( evt, cb ){
			return window.attachEvent( "on" + evt, cb );
		};
	}

	// If DOM is already ready at exec time, depends on the browser.
	// From: https://github.com/mobify/mobifyjs/blob/526841be5509e28fc949038021799e4223479f8d/src/capture.js#L128
	if (document.attachEvent ? document.readyState === "complete" : document.readyState !== "loading") {
		runReady();
	} else {
		if( !document.addEventListener ){
			document.attachEvent( "DOMContentLoaded", runReady );
			document.attachEvent( "onreadystatechange", runReady );
		} else {
			document.addEventListener( "DOMContentLoaded", runReady, false );
			document.addEventListener( "readystatechange", runReady, false );
		}
		window.addEventListener( "load", runReady, false );
	}

	// end domready code

	function sendSize(){
		window
			.parent
			.postMessage('{ "iframeheight" : ' +
									document.documentElement.offsetHeight +
									'}', "*");
	}

	window.addEventListener("message", function( event ){
		// same host check
		var origin = event.origin || event.originalEvent.origin;
		var allowedOrigin = new RegExp( "https?:\/\/" + location.host );
		if( !origin.match( allowedOrigin ) ){
			return;
		}

		var data = event.data || event.originalEvent.data;
		var body = document.querySelector("body");

		// use the passed information to populate the page
		body.innerHTML = data.html;

		// wait until everything loads to calc the height and communicate it
		// TODO it would be better to bind to the load of the styles at least
		onReady(sendSize);
	}, false);

	var minInterval = 300;
	var resized = false;
	window.addEventListener("resize", function(){
		if(resized){ return; }
		sendSize();
		resized = true;
		setTimeout(function(){ resized = false; }, minInterval);
	});
})();
<|endoftext|>


<commit_before>/*jshint strict:true node:true es5:true onevar:true laxcomma:true laxbreak:true eqeqeq:true immed:true latedef:true*/
(function () {
  "use strict";

  var fs = require('fs')
    , Future = require('future')
    , future = Future.create()
    , semver = require('semver')
    , forEachAsync = require('forEachAsync')
    , npm = require('npm')
    , path = require('path')
    , reNoMaxVer = /^\s*>=?\s*[^<>=\s]+\s*$/
    ;

  function prettyVer(ver) {
    return semver.validRange(ver).replace(/-\s+/g, ' ').replace(/-$/, '') || '*';
  }

  function fixDeps(deps) {
    var depsObj = {}
      ;

    if (!Array.isArray(deps)) {
      if ('object' === typeof deps) {
        return deps;
      }

      console.error('dependencies or browserDependencies was neither array nor object:');
      console.error(deps);
      console.error('Replacing with empty object: {}');
      return {};
    }

    deps.forEach(function (dep) {
      var depParts = dep.split('@')
        ;

      depsObj[depParts[0]] = prettyVer(depParts[1]);
    });

    return depsObj;
  }

  function promoteVersion(ver) {
    var vers = semver.parse(ver)
      ;

    if (Number(vers[1])) {
      return '>=' + ver + ' <' + (Number(vers[1]) + 1);
    }

    if (Number(vers[2])) {
      return '>=' + ver + ' < 0.' + (Number(vers[2]) + 1);
    }

    return  '=0.0.' + vers[3];
  }

  // prefer cli value over package.json value
  // add max if not present
  function getSafeVer(orig, current) {
    var name = orig.split('@').shift()
      , origVer = orig.split('@').pop()
      , curVer = current.split('@').pop()
      , version
      ;

    if (origVer) {
      version = origVer;
    } else {
      version = curVer;
    }

    version = version.replace(/v/g, '');

    // find >= without
    if (reNoMaxVer.test(version)) {
      version = curVer.replace(/>=?/g, ' ');
      return prettyVer(promoteVersion(version));
    }

    // already has more than one
    // TODO might be max-only (no min)
    if (/[~<>]=?/.test(version)) {
      return prettyVer(version);
    }

    if ('*' === version) {
      version = curVer;
    }
    return prettyVer('~' + (curVer));
  }

  function installEach(next, nameAndVer) {
    /*jshint validthis:true*/
    var deps = this
      ;

    //npm.commands.view([nameAndVer], function (err, mapByVersion) {
    npm.commands.install([nameAndVer], function (err, arr, obj, str) {
      var pkgName = nameAndVer.split('@').shift().trim()
        , safeVer
        , installed
        , installedDetails
        ;

      if (err) {
        console.error(err);
        return;
      }

      arr.some(function (details) {
        if (details[0].match(pkgName)) {
          installed = details[0];
          return true;
        }
      });
      Object.keys(obj).some(function (dir) {
        if (installed === obj[dir].what) {
          installedDetails = obj[dir];
          return true;
        }
      });

      if (!installedDetails) {
        console.error(pkgName, installed, obj);
      }

      safeVer = getSafeVer(nameAndVer, installedDetails.what);
      deps[pkgName] = safeVer;

      next();
    });
  }

  function addDeps(names) {
    var pkg
      , deps
      ;

    // fix unsafe version schemes
    function addLaxVersions(name) {
      var version = deps[name]
        ;

      delete deps[name];
      name = name.trim();
      version = version.trim();
      deps[name] = version;

      // fix invalid versions (including *)
      if ('*' === version || !semver.validRange(version)) {
        console.error('invalid version for', name, '@', version, 'assuming ', name, '@ *');
        version = '';
      }

      // fix any >= entries without <
      if (!version || reNoMaxVer.test(version)) {
        console.error('bad version:', name, version);
        // avoid duplicates
        if (names.every(function (_name) {
          return name.trim() !== _name.trim();
        })) {
          if (version) {
            names.push(name + '@' + prettyVer(version));
          } else {
            names.push(name);
          }
        }
      }
    }

    try {
      pkg = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'package.json')));
    } catch(e) {
      pkg = {
          name: process.cwd().split('/').pop()
        , version: '0.1.0'
        , maintainers: []
        , dependencies: {}
        , devDependencies: {}
      };
      console.error(e);
    }

    if (pkg.dependencies && Object.keys(pkg.dependencies).length) {
      deps = pkg.dependencies = fixDeps(pkg.dependencies);
    } else if (pkg.browserDependencies && Object.keys(pkg.browserDependencies).length) {
      deps = pkg.browserDependencies = fixDeps(pkg.browserDependencies);
    } else {
      deps = pkg.dependencies = {};
    }

    Object.keys(deps).forEach(addLaxVersions);
    names.forEach(function (nameAndVer, i) {
      var parts = nameAndVer.split('@')
        , name = parts.shift()
        , ver = prettyVer(parts.pop() || '*')
        ;

      names[i] = name.trim() + '@' + ver.trim();
    });

    forEachAsync(names, installEach, deps).then(function () {
      fs.writeFile('package.json', JSON.stringify(pkg, null, '  '), 'utf8', function (err) {
        if (err) {
          console.error(err);
        }

        console.log(deps);
      });
    });
  }

  function onNpmReady() {
    var pkgs = Array.prototype.splice.call(process.argv, 2)
      ;

    /*
    if (pkgs.length < 2) {
      pkgs.push('futures@ ~v1.9');
      pkgs.push('sequence @ 2.x');
    }
    */

    addDeps(pkgs);
  }

  npm.load({ loglevel: 'silent' }, onNpmReady);
  future.when(onNpmReady);

  module.exports = function (arr) {
    if (!Array.isArray(arr)) {
      arr = Array.prototype.slice.call(arguments);
    }
    future.when(function () {
      addDeps(arr);
      return Future.create().fulfill();
    });
  };
}());
<commit_msg>fixed missing executable bit and shebang for steve-add<commit_after>#!/usr/bin/env node
/*jshint strict:true node:true es5:true onevar:true laxcomma:true laxbreak:true eqeqeq:true immed:true latedef:true*/
(function () {
  "use strict";

  var fs = require('fs')
    , Future = require('future')
    , future = Future.create()
    , semver = require('semver')
    , forEachAsync = require('forEachAsync')
    , npm = require('npm')
    , path = require('path')
    , reNoMaxVer = /^\s*>=?\s*[^<>=\s]+\s*$/
    ;

  function prettyVer(ver) {
    return semver.validRange(ver).replace(/-\s+/g, ' ').replace(/-$/, '') || '*';
  }

  function fixDeps(deps) {
    var depsObj = {}
      ;

    if (!Array.isArray(deps)) {
      if ('object' === typeof deps) {
        return deps;
      }

      console.error('dependencies or browserDependencies was neither array nor object:');
      console.error(deps);
      console.error('Replacing with empty object: {}');
      return {};
    }

    deps.forEach(function (dep) {
      var depParts = dep.split('@')
        ;

      depsObj[depParts[0]] = prettyVer(depParts[1]);
    });

    return depsObj;
  }

  function promoteVersion(ver) {
    var vers = semver.parse(ver)
      ;

    if (Number(vers[1])) {
      return '>=' + ver + ' <' + (Number(vers[1]) + 1);
    }

    if (Number(vers[2])) {
      return '>=' + ver + ' < 0.' + (Number(vers[2]) + 1);
    }

    return  '=0.0.' + vers[3];
  }

  // prefer cli value over package.json value
  // add max if not present
  function getSafeVer(orig, current) {
    var name = orig.split('@').shift()
      , origVer = orig.split('@').pop()
      , curVer = current.split('@').pop()
      , version
      ;

    if (origVer) {
      version = origVer;
    } else {
      version = curVer;
    }

    version = version.replace(/v/g, '');

    // find >= without
    if (reNoMaxVer.test(version)) {
      version = curVer.replace(/>=?/g, ' ');
      return prettyVer(promoteVersion(version));
    }

    // already has more than one
    // TODO might be max-only (no min)
    if (/[~<>]=?/.test(version)) {
      return prettyVer(version);
    }

    if ('*' === version) {
      version = curVer;
    }
    return prettyVer('~' + (curVer));
  }

  function installEach(next, nameAndVer) {
    /*jshint validthis:true*/
    var deps = this
      ;

    //npm.commands.view([nameAndVer], function (err, mapByVersion) {
    npm.commands.install([nameAndVer], function (err, arr, obj, str) {
      var pkgName = nameAndVer.split('@').shift().trim()
        , safeVer
        , installed
        , installedDetails
        ;

      if (err) {
        console.error(err);
        return;
      }

      arr.some(function (details) {
        if (details[0].match(pkgName)) {
          installed = details[0];
          return true;
        }
      });
      Object.keys(obj).some(function (dir) {
        if (installed === obj[dir].what) {
          installedDetails = obj[dir];
          return true;
        }
      });

      if (!installedDetails) {
        console.error(pkgName, installed, obj);
      }

      safeVer = getSafeVer(nameAndVer, installedDetails.what);
      deps[pkgName] = safeVer;

      next();
    });
  }

  function addDeps(names) {
    var pkg
      , deps
      ;

    // fix unsafe version schemes
    function addLaxVersions(name) {
      var version = deps[name]
        ;

      delete deps[name];
      name = name.trim();
      version = version.trim();
      deps[name] = version;

      // fix invalid versions (including *)
      if ('*' === version || !semver.validRange(version)) {
        console.error('invalid version for', name, '@', version, 'assuming ', name, '@ *');
        version = '';
      }

      // fix any >= entries without <
      if (!version || reNoMaxVer.test(version)) {
        console.error('bad version:', name, version);
        // avoid duplicates
        if (names.every(function (_name) {
          return name.trim() !== _name.trim();
        })) {
          if (version) {
            names.push(name + '@' + prettyVer(version));
          } else {
            names.push(name);
          }
        }
      }
    }

    try {
      pkg = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'package.json')));
    } catch(e) {
      pkg = {
          name: process.cwd().split('/').pop()
        , version: '0.1.0'
        , maintainers: []
        , dependencies: {}
        , devDependencies: {}
      };
      console.error(e);
    }

    if (pkg.dependencies && Object.keys(pkg.dependencies).length) {
      deps = pkg.dependencies = fixDeps(pkg.dependencies);
    } else if (pkg.browserDependencies && Object.keys(pkg.browserDependencies).length) {
      deps = pkg.browserDependencies = fixDeps(pkg.browserDependencies);
    } else {
      deps = pkg.dependencies = {};
    }

    Object.keys(deps).forEach(addLaxVersions);
    names.forEach(function (nameAndVer, i) {
      var parts = nameAndVer.split('@')
        , name = parts.shift()
        , ver = prettyVer(parts.pop() || '*')
        ;

      names[i] = name.trim() + '@' + ver.trim();
    });

    forEachAsync(names, installEach, deps).then(function () {
      fs.writeFile('package.json', JSON.stringify(pkg, null, '  '), 'utf8', function (err) {
        if (err) {
          console.error(err);
        }

        console.log(deps);
      });
    });
  }

  function onNpmReady() {
    var pkgs = Array.prototype.splice.call(process.argv, 2)
      ;

    /*
    if (pkgs.length < 2) {
      pkgs.push('futures@ ~v1.9');
      pkgs.push('sequence @ 2.x');
    }
    */

    addDeps(pkgs);
  }

  npm.load({ loglevel: 'silent' }, onNpmReady);
  future.when(onNpmReady);

  module.exports = function (arr) {
    if (!Array.isArray(arr)) {
      arr = Array.prototype.slice.call(arguments);
    }
    future.when(function () {
      addDeps(arr);
      return Future.create().fulfill();
    });
  };
}());
<|endoftext|>


<commit_before>"use strict";

module.exports.index = (req, res) => {
	res.render('contact');
};

module.exports.new = (req, res) => {

	console.log(">>>>>>>>>>>>>>>>>>>", req.body);
	const obj = new Contact({
		name: req.body.name,
		email: req.body.email,
		message: req.body.message
	});

	obj.save((err, obj) => {
		if (err) throw err;
		console.log(obj);
		res.render('contacted', { name: req.body.name });
	});
};
<commit_msg>added require Contact model in Contact controller)<commit_after>"use strict";

const Contact = require('../models/contacts');

module.exports.index = (req, res) => {
	res.render('contact');
};

module.exports.new = (req, res) => {

	console.log(">>>>>>>>>>>>>>>>>>>", req.body);
	const obj = new Contact({
		name: req.body.name,
		email: req.body.email,
		message: req.body.message
	});

	obj.save((err, obj) => {
		if (err) throw err;
		console.log(obj);
		res.render('contacted', { name: req.body.name });
	});
};
<|endoftext|>


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 *
 * Copyright (c) 2009 Aptana, Inc.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * ***** END LICENSE BLOCK ***** */

ActiveController = {};

ActiveController.logging = false;

ActiveController.create = function create(actions,methods)
{
    var klass = function klass(container,params){
        this.container = container || ActiveController.createDefaultContainer();
        this.renderTarget = this.container;
        this.layoutRendered = false;
        if(this.layout && typeof(this.layout.view) === 'function')
        {
            this.layout.view = ActiveSupport.bind(this.layout.view,this);
        }
        this.params = params || {};
        this.scope = new ActiveEvent.ObservableHash({});
        this.initialize();
    };
    ActiveSupport.extend(klass,ClassMethods);
    for(var action_name in actions || {})
    {
        if(typeof(actions[action_name]) == 'function')
        {
            ActiveController.createAction(klass,action_name,actions[action_name]);
        }
        else
        {
            //plain old property
            klass.prototype[action_name] = actions[action_name];
        }
    }
    ActiveSupport.extend(klass.prototype,InstanceMethods);
    ActiveSupport.extend(klass.prototype,methods || {});
    ActiveEvent.extend(klass);
    return klass;
};

ActiveController.createDefaultContainer = function createDefaultContainer()
{
    var global_context = ActiveSupport.getGlobalContext();
    var div = global_context.document.createElement('div');
    if(!global_context.document.body)
    {
        return ActiveSupport.throwError(Errors.BodyNotAvailable);
    }
    global_context.document.body.appendChild(div);
    return div;
};

ActiveController.createAction = function createAction(klass,action_name,action)
{
    klass.prototype[action_name] = function action_wrapper(){
        this.notify('beforeCall',action_name,this.params);
        if(this.layout && !this.layoutRendered && this.layout.view)
        {
            this.layoutRendered = true;
            this.layout.target = this.container;
            var layout = this.render(this.layout);
            if(layout && layout.renderTarget)
            {
                this.renderTarget = layout.renderTarget;
            }
        }
        ActiveSupport.bind(action,this)();
        this.notify('afterCall',action_name,this.params);
    };
};

var InstanceMethods = {
    initialize: function initialize()
    {

    },
    get: function get(key)
    {
        return this.scope.get(key);
    },
    set: function set(key,value)
    {
        return this.scope.set(key,value);
    },
    render: function render(params)
    {
        var args = this.renderArgumentsFromRenderParams(params);
        var response = args.stopped ? null : ActiveView.render.apply(ActiveView,args);
        return response;
    },
    renderArgumentsFromRenderParams: function renderArgumentsFromRenderParams(params)
    {
        if(typeof(params) !== 'object')
        {
            return ActiveSupport.throwError(Errors.InvalidRenderParams);
        }
        var args = [null,this.renderTarget,this.scope];
        for(var flag_name in params || {})
        {
            if(!RenderFlags[flag_name])
            {
                if(ActiveController.logging)
                {
                    ActiveSupport.log('ActiveController: render() failed with params:',params);
                }
                return ActiveSupport.throwError(Errors.UnknownRenderFlag,flag_name);
            }
            ActiveSupport.bind(RenderFlags[flag_name],this)(params[flag_name],args);
        }
        return args;
    }
};
ActiveController.InstanceMethods = InstanceMethods;

var RenderFlags = {
    view: function view(view_class,args)
    {
        if(typeof(view_class) === 'string')
        {
            var klass = ActiveSupport.getClass(view_class);
            if(!klass)
            {
                return ActiveSupport.throwError(Errors.ViewDoesNotExist,view_class);
            }
            args[0] = klass;
        }
        else
        {
            args[0] = view_class;
        }
    },
    text: function text(text,args)
    {
        args[0] = text;
    },
    target: function target(target,args)
    {
        args[1] = target;
    },
    scope: function scope(scope,args)
    {
        args[2] = scope;
    }
};
ActiveController.RenderFlags = RenderFlags;

var ClassMethods = {
    createAction: function wrapAction(action_name,action)
    {
        return ActiveController.createAction(this,action_name,action);
    }
};
ActiveController.ClassMethods = ClassMethods;

var Errors = {
    BodyNotAvailable: ActiveSupport.createError('Controller could not attach to a DOM element, no container was passed and document.body is not available'),
    InvalidRenderParams: ActiveSupport.createError('The parameter passed to render() was not an object.'),
    UnknownRenderFlag: ActiveSupport.createError('The following render flag does not exist: '),
    ViewDoesNotExist: ActiveSupport.createError('The specified view does not exist: ')
};
ActiveController.Errors = Errors;<commit_msg>simplified render / layout<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 *
 * Copyright (c) 2009 Aptana, Inc.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * ***** END LICENSE BLOCK ***** */

ActiveController = {};

ActiveController.logging = false;

ActiveController.create = function create(actions,methods)
{
    var klass = function klass(container,parent,params){
        this.container = container;
        this.setRenderTarget(this.container);
        this.parent = parent;
        this.children = [];
        this.params = params || {};
        this.scope = new ActiveEvent.ObservableHash({});
        this.initialize();
    };
    ActiveSupport.extend(klass,ClassMethods);
    for(var action_name in actions || {})
    {
        if(typeof(actions[action_name]) == 'function')
        {
            ActiveController.createAction(klass,action_name,actions[action_name]);
        }
        else
        {
            //plain old property
            klass.prototype[action_name] = actions[action_name];
        }
    }
    ActiveSupport.extend(klass.prototype,InstanceMethods);
    ActiveSupport.extend(klass.prototype,methods || {});
    ActiveEvent.extend(klass);
    return klass;
};

ActiveController.createDefaultContainer = function createDefaultContainer()
{
    var global_context = ActiveSupport.getGlobalContext();
    var div = ActiveView.Builder.div();
    if(!global_context.document.body)
    {
        return ActiveSupport.throwError(Errors.BodyNotAvailable);
    }
    global_context.document.body.appendChild(div);
    return div;
};

ActiveController.createAction = function createAction(klass,action_name,action)
{
    klass.prototype[action_name] = function action_wrapper(){
        this.notify('beforeCall',action_name,this.params);
        this.renderLayout();
        ActiveSupport.bind(action,this)();
        this.notify('afterCall',action_name,this.params);
    };
};

var InstanceMethods = {
    initialize: function initialize()
    {

    },
    get: function get(key)
    {
        return this.scope.get(key);
    },
    set: function set(key,value)
    {
        return this.scope.set(key,value);
    },
    render: function render(params)
    {
        if(typeof(params) !== 'object')
        {
            return ActiveSupport.throwError(Errors.InvalidRenderParams);
        }
        for(var flag_name in params || {})
        {
            if(!RenderFlags[flag_name])
            {
                if(ActiveController.logging)
                {
                    ActiveSupport.log('ActiveController: render() failed with params:',params);
                }
                return ActiveSupport.throwError(Errors.UnknownRenderFlag,flag_name);
            }
            ActiveSupport.bind(RenderFlags[flag_name],this)(params[flag_name],params);
        }
        return params;
    },
    getRenderTarget: function getRenderTarget()
    {
        return this.renderTarget;
    },
    setRenderTarget: function setRenderTarget(target)
    {
        this.renderTarget = target;
    },
    renderLayout: function renderLayout()
    {
        if(this.layout && !this.layoutRendered && typeof(this.layout) == 'function')
        {
            this.layoutRendered = true;
            this.container.innerHtml = '';
            this.container.appendChild(this.layout.bind(this)());
        }
    }
};
ActiveController.InstanceMethods = InstanceMethods;

var RenderFlags = {
    view: function view(view_class,params)
    {
        if(typeof(view_class) === 'string')
        {
            var klass = ActiveSupport.getClass(view_class);
            if(!klass)
            {
                return ActiveSupport.throwError(Errors.ViewDoesNotExist,view_class);
            }
        }
        else
        {
            klass = view_class;
        }
        var response = ActiveView.render(klass,params.scope || this.scope);
        var container = params.target || this.getRenderTarget();
        if(container)
        {
            container.innerHTML = '';
            container.appendChild(response);
        }
    },
    text: function text(text,params)
    {
        var container = params.target || this.getRenderTarget();
        if(container)
        {
            container.innerHTML = text;
        }
    },
    target: function target(target,params)
    {
        //target only available for text + view, needs no processing
    },
    scope: function scope(scope,params)
    {
        //scope only available for text + view, needs no processing
    }
};
ActiveController.RenderFlags = RenderFlags;

var ClassMethods = {
    createAction: function wrapAction(action_name,action)
    {
        return ActiveController.createAction(this,action_name,action);
    }
};
ActiveController.ClassMethods = ClassMethods;

var Errors = {
    BodyNotAvailable: ActiveSupport.createError('Controller could not attach to a DOM element, no container was passed and document.body is not available'),
    InvalidRenderParams: ActiveSupport.createError('The parameter passed to render() was not an object.'),
    UnknownRenderFlag: ActiveSupport.createError('The following render flag does not exist: '),
    ViewDoesNotExist: ActiveSupport.createError('The specified view does not exist: ')
};
ActiveController.Errors = Errors;<|endoftext|>