<commit_before>/** @file
 * GUI-related functions
 *
 * @author Marcel Bollmann
 * @date January 2012
 */

var gui = {
    activeSpinner: null,
    keepaliveRequest: null,
    editKeyboard: null,
    serverNotices: {},

    initialize: function() {
	this._addKeyboardShortcuts();
	this.addToggleEvents($$('.clappable'));
	this._activateKeepalive();
        this._defineDateParsers();
    },

    /* Function: addToggleEvents

       Enable clappable div containers.

       Adds onClick events to the .clapp element in each .clappable
       container that toggle the visibility of its contents.  Also,
       automatically hides all contents of .starthidden containers.
    */
    addToggleEvents: function(objects) {
        if(typeof(objects.each) != "function")
            objects = new Array(objects);

	objects.each(function (clappable) {
            var clapper, content;

            // add toggle event
            clapper = clappable.getElement('.clapp');
            content = clappable.getElement('div');
            if (clapper !== null) {
                clapper.removeEvents();
		clapper.addEvent('click', function () {
                    clappable.toggleClass('clapp-hidden');
                    content.toggle();
		});
            }
            // hide content by default, if necessary
            if (clappable.hasClass('starthidden')) {
                clappable.addClass('clapp-hidden');
		content.hide();
            }
	});
    },

    /* Function: _addKeyboardShortcuts

       Sets up keyboard shortcuts used within the application.
     */
    _addKeyboardShortcuts: function() {
	this.editKeyboard = new Keyboard({
	    active: true,
	    events: {
		'ctrl+s': function(e) {
		    e.stop();
		    if(edit!==null && edit.editorModel!==null) {
			edit.editorModel.saveData();
		    }
		}
		/* ,
		'alt+left': function(e) {
		    e.stop();
		    if(edit!==null && edit.editorModel!==null) {
			edit.editorModel.displayPreviousPage();
		    }
		},
		'alt+right': function(e) {
		    e.stop();
		    if(edit!==null && edit.editorModel!==null) {
			edit.editorModel.displayNextPage();
			edit.editorModel.focusFirstElement();
		    }
		} */
	    }
	});

    },

    /* Function: _activateKeepalive

       Sets up a periodical server request with the sole purpose of
       keeping the connection alive, i.e., telling the server that the
       user is still active (and has not, e.g., closed the browser
       window without logging out).
    */
    _activateKeepalive: function() {
	if(userdata.name != undefined) {
	    this.keepaliveRequest = new Request.JSON({
		url: 'request.php?do=keepalive',
		method: 'get',
		initialDelay: 60000,
		delay: 60000,
		limit: 60000,
                onSuccess: function(status, text) {
                    if (status && status.notice) {
                        this.processServerNotice(status.notice);
                    }
                }.bind(this)
	    });
	    this.keepaliveRequest.startTimer();
	}
    },

    /* Function: processServerNotice

       Checks whether a server notice has been show before, and
       displays a notice if appropriate.  Notices shown this way
       don't close automatically.

       Parameters:
         text - Notice text
     */
    processServerNotice: function(text) {
        if (this.serverNotices[text])
            return;  // already processed
        this.showNotice('notice', text, true);
        this.serverNotices[text] = true;
    },

    /* Function: changeTab

       Selects a new tab.

       Shows the content div corresponding to the selected menu item,
       while hiding all others and highlighting the correct menu
       button.

       Parameters:
        tabName - Internal name of the tab to be selected
    */
    changeTab: function(tabName) {
	var contentBox, tabButton, activeTab, i;

	// hide all tabs
	contentBox = $$(".content");
	for (i = 0; i < contentBox.length; i++) {
            contentBox[i].setStyle("display", "none");
	}

	// select correct tab button
	tabButton = $$(".tabButton");
	for (i = 0; i < tabButton.length; i++) {
            if (tabButton[i].id === tabName + "TabButton") {
		tabButton[i].set("active", "true");
            } else {
		tabButton[i].set("active", "false");
            }
	}

	// show active tab
	activeTab = $(tabName + "Div");
	if (activeTab === null) {
            alert(tabName + " tab not implemented!");
	}
	activeTab.setStyle("display", "block");
    },

    /* Function: showNotice

       Displays a floating notice, e.g., to indicate success.

       Parameters:
         ntype - Type of the notice ('ok' or 'error')
         message - String to appear in the notice
         keepopen - If true, notice stays open (defaults to false)
    */
    showNotice: function(ntype, message, keepopen) {
	new mBox.Notice({
	    type: ntype,
	    position: {x: 'right'},
	    content: message,
            neverClose: (keepopen || false)
	});
    },

    /* Function: confirm

       Presents a confirmation dialog with yes/no buttons to the user.

       Parameters:
         message - String to appear in the dialog
         action - Callback function on confirmation
         danger - If true, 'yes' button is displayed in red instead of green
     */
    confirm: function(message, action, danger) {
        new mBox.Modal.Confirm({
            content: message,
            confirmAction: action,
            onOpen: function() {
                this.footerContainer.getElement('.mBoxConfirmButtonSubmit')
                    .addClass('mform')
                    .removeClass('button_green')
                    .addClass((danger ? 'button_red' : 'button_green'))
                    .set('html', 'Ja, bestätigen');
                this.footerContainer.getElement('.mBoxConfirmButtonCancel')
                    .addClass('mform')
                    .set('html', 'Nein, abbrechen');
            }
        }).open();
    },

    /* Function: disableScrolling

       Disable scrolling for the page.
    */
    disableScrolling: function() {
        document.getElement('body').setStyle('overflow', 'hidden');
    },

    /* Function: enableScrolling

       Enable scrolling for the page.
    */
    enableScrolling: function() {
        document.getElement('body').setStyle('overflow', 'visible');
    },

    /* Function: showSpinner

       Displays a "loading" spinner.

       Parameters:
        options - An object which may contain the following options:
	           * message - Message to display (default: none)
    */
    showSpinner: function(options) {
	var options = options || {};
	var spinmsg = options.message || null;

        this.disableScrolling();
	$('overlay').show();
	$('spin-overlay').show();
	this.activeSpinner = new Spinner($('spin-overlay'),
					 {message: spinmsg});
	this.activeSpinner.show();
    },

    /* Function: hideSpinner

       Hides the currently displayed spinner.
    */
    hideSpinner: function() {
	if(this.activeSpinner !== undefined && this.activeSpinner !== null) {
	    this.activeSpinner.hide();
	    $('overlay').hide();
	    $('spin-overlay').hide();
	}
        this.enableScrolling();
    },

    /* Function: showInfoDialog

       Displays a modal dialog containing an informational message.

       Parameters:
         message - Message to display
         title - (optional) Title of the dialog window
     */
    showInfoDialog: function(message, title) {
	new mBox.Modal({
	    title: title,
	    content: message,
            addClass: {wrapper: 'InfoDialog'},
	    buttons: [ {title: "Schließen", addClass: "mform button_green"} ]
	}).open();
    },

    /* Function: showTextDialog

       Displays a modal dialog that optionally includes a textarea for
       longer warnings, errors, etc.

       Parameters:
        title - Title of the dialog window
        message - First line of text in the dialog
	textarea - Content of the textarea; if empty, the textarea will
	           not be displayed, and the dialog will consist of the
		   message only; if this is an array, its elements will
		   be appended to the textarea separated by line breaks
    */
    showTextDialog: function(title, message, textarea) {
	var content;
	if(textarea===undefined || textarea=='') {
	    content = message;
	}
	else {
	    content = $('genericTextMsgPopup');
	    content.getElement('p').empty().appendText(message);
	    content.getElement('textarea').empty();
	    if(typeOf(textarea) == 'array') {
		Array.each(textarea, function(item, idx) {
		    content.getElement('textarea').appendText(item + '\n');
		});
	    }
	    else {
		content.getElement('textarea').appendText(textarea);
	    }
	}

	new mBox.Modal({
	    title: title,
	    content: content,
            addClass: {wrapper: 'TextDialog'},
	    closeOnBodyClick: false,
	    closeOnEsc: false,
	    buttons: [ {title: "Schließen", addClass: "mform button_green"} ]
	}).open();
    },

    /* Function: _defineDateParsers

       Registers date parsers for our custom date formats.
     */
    _defineDateParsers: function() {
        Date.defineParser("%d.%m.%Y, %H:%M");
        Date.defineParser({
            re: /([hH]eute|[gG]estern|[vV]orgestern), (\d\d):(\d\d)/,
            handler: function (bits) {
                var date = new Date();
                if(bits[1].toUpperCase() === "GESTERN")
                    date.decrement('day', 1);
                else if(bits[1].toUpperCase() === "VORGESTERN")
                    date.decrement('day', 2);
                date.set('hours', bits[2]);
                date.set('minutes', bits[3]);
                return date;
            }
        });
    },

    /* Function: formatDateString

       Takes a date string or Date object and re-formats it for
       display within the GUI.

       Parameters:
         date - A date in string format, or as a Date object
     */
    formatDateString: function(date) {
        var format_string = '';
        var date_strings = ['Heute', 'Gestern', 'Vorgestern'];
        var now = Date.now();
        if(!(date instanceof Date))
            date = new Date(date);
        if(!date.isValid())
            return "";
        if(date.diff(now) > 2)
            format_string += "%d.%m.%Y";
        else
            format_string += date_strings[date.diff(now)];
        format_string += ", %H:%M";
        return date.format(format_string);
    }
}

/** Perform initialization. Adds JavaScript events to interactive
 * navigation elements, e.g.\ clappable div containers, and selects
 * the default tab.
 */
function onLoad() {
    gui.initialize();

    // default item defined in content.php, variable set in gui.php
    gui.changeTab(default_tab);
}

function onBeforeUnload() {
    if (typeof edit!="undefined" && edit.editorModel!==null) {
	var chl = edit.editorModel.changedLines.length;
	if (chl>0) {
	    var zeile = (chl>1) ? "Zeilen" : "Zeile";
	    return ("Im geöffneten Dokument gibt es noch ungespeicherte Änderungen in "+chl+" "+zeile+", die verloren gehen, wenn Sie fortfahren.");
	}
    }
}
<commit_msg>Minor GUI fixes.<commit_after>/** @file
 * GUI-related functions
 *
 * @author Marcel Bollmann
 * @date January 2012
 */

var gui = {
    activeSpinner: null,
    keepaliveRequest: null,
    editKeyboard: null,
    serverNotices: {},

    initialize: function() {
	this._addKeyboardShortcuts();
	this.addToggleEvents($$('.clappable'));
	this._activateKeepalive();
        this._defineDateParsers();
    },

    /* Function: addToggleEvents

       Enable clappable div containers.

       Adds onClick events to the .clapp element in each .clappable
       container that toggle the visibility of its contents.  Also,
       automatically hides all contents of .starthidden containers.
    */
    addToggleEvents: function(objects) {
        if(typeof(objects.each) != "function")
            objects = new Array(objects);

	objects.each(function (clappable) {
            var clapper, content;

            // add toggle event
            clapper = clappable.getElement('.clapp');
            content = clappable.getElement('div');
            if (clapper !== null) {
                clapper.removeEvents();
		clapper.addEvent('click', function () {
                    clappable.toggleClass('clapp-hidden');
                    content.toggle();
		});
            }
            // hide content by default, if necessary
            if (clappable.hasClass('starthidden')) {
                clappable.addClass('clapp-hidden');
		content.hide();
            }
	});
    },
    /* Function: _addKeyboardShortcuts

       Sets up keyboard shortcuts used within the application.
     */
    _addKeyboardShortcuts: function() {
	this.editKeyboard = new Keyboard({
	    active: true,
	    events: {
		'ctrl+s': function(e) {
		    e.stop();
		    if(edit!==null && edit.editorModel!==null) {
			edit.editorModel.saveData();
		    }
		}
		/* ,
		'alt+left': function(e) {
		    e.stop();
		    if(edit!==null && edit.editorModel!==null) {
			edit.editorModel.displayPreviousPage();
		    }
		},
		'alt+right': function(e) {
		    e.stop();
		    if(edit!==null && edit.editorModel!==null) {
			edit.editorModel.displayNextPage();
			edit.editorModel.focusFirstElement();
		    }
		} */
	    }
	});
    },

    /* Function: _activateKeepalive

       Sets up a periodical server request with the sole purpose of
       keeping the connection alive, i.e., telling the server that the
       user is still active (and has not, e.g., closed the browser
       window without logging out).
    */
    _activateKeepalive: function() {
	if(userdata.name != undefined) {
	    this.keepaliveRequest = new Request.JSON({
		url: 'request.php?do=keepalive',
		method: 'get',
		initialDelay: 1000,
		delay: 60000,
		limit: 60000,
                onSuccess: function(status, text) {
                    if (status && status.notices) {
                        Array.each(status.notices,
                                   this.processServerNotice.bind(this));
                    }
                }.bind(this)
	    });
	    this.keepaliveRequest.startTimer();
	}
    },

    /* Function: processServerNotice

       Checks whether a server notice has been shown before, and
       displays a notice if appropriate.  Notices shown this way
       don't close automatically.

       Parameters:
         text - Notice as {id: 0, text: "", type: ""}
     */
    processServerNotice: function(notice) {
        if (this.serverNotices[notice.id])
            return;  // already processed
        if (notice.type == 'alert')
            this.showNotice('notice', notice.text, true);
        this.serverNotices[notice.id] = true;
    },

    /* Function: changeTab

       Selects a new tab.

       Shows the content div corresponding to the selected menu item,
       while hiding all others and highlighting the correct menu
       button.

       Parameters:
        tabName - Internal name of the tab to be selected
    */
    changeTab: function(tabName) {
	var contentBox, tabButton, activeTab, i;

	// hide all tabs
	contentBox = $$(".content");
	for (i = 0; i < contentBox.length; i++) {
            contentBox[i].setStyle("display", "none");
	}

	// select correct tab button
	tabButton = $$(".tabButton");
	for (i = 0; i < tabButton.length; i++) {
            if (tabButton[i].id === tabName + "TabButton") {
		tabButton[i].set("active", "true");
            } else {
		tabButton[i].set("active", "false");
            }
	}

	// show active tab
	activeTab = $(tabName + "Div");
	if (activeTab === null) {
            alert(tabName + " tab not implemented!");
	}
	activeTab.setStyle("display", "block");
    },

    /* Function: showNotice

       Displays a floating notice, e.g., to indicate success.

       Parameters:
         ntype - Type of the notice ('ok' or 'error')
         message - String to appear in the notice
         keepopen - If true, notice stays open (defaults to false)
    */
    showNotice: function(ntype, message, keepopen) {
	new mBox.Notice({
	    type: ntype,
	    position: {x: 'right'},
	    content: new Element('span', {text: message}),
            neverClose: (keepopen || false)
	});
    },

    /* Function: confirm

       Presents a confirmation dialog with yes/no buttons to the user.

       Parameters:
         message - String to appear in the dialog
         action - Callback function on confirmation
         danger - If true, 'yes' button is displayed in red instead of green
     */
    confirm: function(message, action, danger) {
        new mBox.Modal.Confirm({
            content: message,
            confirmAction: action,
            onOpen: function() {
                this.footerContainer.getElement('.mBoxConfirmButtonSubmit')
                    .addClass('mform')
                    .removeClass('button_green')
                    .addClass((danger ? 'button_red' : 'button_green'))
                    .set('html', 'Ja, bestätigen');
                this.footerContainer.getElement('.mBoxConfirmButtonCancel')
                    .addClass('mform')
                    .set('html', 'Nein, abbrechen');
            }
        }).open();
    },

    /* Function: disableScrolling

       Disable scrolling for the page.
    */
    disableScrolling: function() {
        document.getElement('body').setStyle('overflow', 'hidden');
    },

    /* Function: enableScrolling

       Enable scrolling for the page.
    */
    enableScrolling: function() {
        document.getElement('body').setStyle('overflow', 'visible');
    },

    /* Function: showSpinner

       Displays a "loading" spinner.

       Parameters:
        options - An object which may contain the following options:
	           * message - Message to display (default: none)
    */
    showSpinner: function(options) {
	var options = options || {};
	var spinmsg = options.message || null;

        this.disableScrolling();
	$('overlay').show();
	$('spin-overlay').show();
	this.activeSpinner = new Spinner($('spin-overlay'),
					 {message: spinmsg});
	this.activeSpinner.show();
    },

    /* Function: hideSpinner

       Hides the currently displayed spinner.
    */
    hideSpinner: function() {
	if(this.activeSpinner !== undefined && this.activeSpinner !== null) {
	    this.activeSpinner.hide();
	    $('overlay').hide();
	    $('spin-overlay').hide();
	}
        this.enableScrolling();
    },

    /* Function: showInfoDialog

       Displays a modal dialog containing an informational message.

       Parameters:
         message - Message to display
         title - (optional) Title of the dialog window
     */
    showInfoDialog: function(message, title) {
	new mBox.Modal({
	    title: title,
	    content: message,
            addClass: {wrapper: 'InfoDialog'},
	    buttons: [ {title: "Schließen", addClass: "mform button_green"} ]
	}).open();
    },

    /* Function: showTextDialog

       Displays a modal dialog that optionally includes a textarea for
       longer warnings, errors, etc.

       Parameters:
        title - Title of the dialog window
        message - First line of text in the dialog
	textarea - Content of the textarea; if empty, the textarea will
	           not be displayed, and the dialog will consist of the
		   message only; if this is an array, its elements will
		   be appended to the textarea separated by line breaks
    */
    showTextDialog: function(title, message, textarea) {
	var content;
	if(textarea===undefined || textarea=='') {
	    content = message;
	}
	else {
	    content = $('genericTextMsgPopup');
	    content.getElement('p').empty().appendText(message);
	    content.getElement('textarea').empty();
	    if(typeOf(textarea) == 'array') {
		Array.each(textarea, function(item, idx) {
		    content.getElement('textarea').appendText(item + '\n');
		});
	    }
	    else {
		content.getElement('textarea').appendText(textarea);
	    }
	}

	new mBox.Modal({
	    title: title,
	    content: content,
            addClass: {wrapper: 'TextDialog'},
	    closeOnBodyClick: false,
	    closeOnEsc: false,
	    buttons: [ {title: "Schließen", addClass: "mform button_green"} ]
	}).open();
    },

    /* Function: _defineDateParsers

       Registers date parsers for our custom date formats.
     */
    _defineDateParsers: function() {
        Date.defineParser("%Y-%m-%d %H:%M:%S");
        Date.defineParser("%d.%m.%Y, %H:%M");
        Date.defineParser({
            re: /([hH]eute|[gG]estern|[vV]orgestern), (\d\d):(\d\d)/,
            handler: function (bits) {
                var date = new Date();
                if(bits[1].toUpperCase() === "GESTERN")
                    date.decrement('day', 1);
                else if(bits[1].toUpperCase() === "VORGESTERN")
                    date.decrement('day', 2);
                date.set('hours', bits[2]);
                date.set('minutes', bits[3]);
                return date;
            }
        });
    },

    /* Function: formatDateString

       Takes a date string or Date object and re-formats it for
       display within the GUI.

       Parameters:
         date - A date in string format, or as a Date object
     */
    formatDateString: function(date) {
        var format_string = '';
        var date_strings = ['Heute', 'Gestern', 'Vorgestern'];
        var now = Date.now();
        if(!(date instanceof Date))
            date = new Date(date);
        if(!date.isValid())
            return "";
        if(date.diff(now) > 2)
            format_string += "%d.%m.%Y";
        else
            format_string += date_strings[date.diff(now)];
        format_string += ", %H:%M";
        return date.format(format_string);
    }
}

/** Perform initialization. Adds JavaScript events to interactive
 * navigation elements, e.g.\ clappable div containers, and selects
 * the default tab.
 */
function onLoad() {
    gui.initialize();

    // default item defined in content.php, variable set in gui.php
    gui.changeTab(default_tab);
}

function onBeforeUnload() {
    if (typeof edit!="undefined" && edit.editorModel!==null) {
	var chl = edit.editorModel.changedLines.length;
	if (chl>0) {
	    var zeile = (chl>1) ? "Zeilen" : "Zeile";
	    return ("Im geöffneten Dokument gibt es noch ungespeicherte Änderungen in "+chl+" "+zeile+", die verloren gehen, wenn Sie fortfahren.");
	}
    }
}
<|endoftext|>


<commit_before>const gulp = require('gulp');

// const clean    = require('./clean');
const root     = require("./root");
const backend  = require("./backend");
const frontend = require("./frontend");
const inc = require('./inc');

module.exports = gulp.series(
    ...[
        // clean,
        inc,
        root,
        ...(process.argv.indexOf('--backend') > -1 ? [backend] : []),
        frontend
    ]
);
<commit_msg>do not inc on build<commit_after>const gulp = require('gulp');

// const clean    = require('./clean');
const root     = require("./root");
const backend  = require("./backend");
const frontend = require("./frontend");

module.exports = gulp.series(
    ...[
        // clean,
        root,
        ...(process.argv.indexOf('--backend') > -1 ? [backend] : []),
        frontend
    ]
);
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var es = require("event-stream")
var $ = require('gulp-load-plugins')({
  pattern: ['gulp-*', 'main-bower-files', 'uglify-save-license', 'del']
});

var connect = require('gulp-connect');

function handleError(err) {
  console.error(err.toString());
  this.emit('end');
}

gulp.task('styles', ['wiredep'],  function () {
  return gulp.src([
    'src/{app,components}/**/*.less',
    '!src/{app,components}/**/_*.less'
  ])
    .pipe($.less({
      paths: [
        'src/bower_components',
        'src/app',
        'src/components'
      ]
    }))
    .on('error', handleError)
    .pipe($.autoprefixer('last 1 version'))
    .pipe(gulp.dest('.tmp'))
    .pipe($.size());
});

gulp.task('scripts', function () {
  return gulp.src('src/{app,components}/**/*.js')
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.size());
});

gulp.task('partials', function () {
  return gulp.src('src/{app,components}/**/*.html')
    .pipe($.minifyHtml({
      empty: true,
      spare: true,
      quotes: true
    }))
    .pipe($.ngHtml2js({
      moduleName: 'civicClient'
    }))
    .pipe(gulp.dest('.tmp'))
    .pipe($.size());
});

gulp.task('html', ['styles', 'scripts', 'partials'], function () {
  var htmlFilter = $.filter('*.html');
  var jsFilter = $.filter('**/*.js');
  var cssFilter = $.filter('**/*.css');
  var assets;

  return gulp.src('src/*.html')
    .pipe($.inject(
      gulp.src('.tmp/{app,components}/**/*.js'),
      {
        starttag: '<!-- inject:partials -->',
        addRootSlash: false,
        addPrefix: '../'
      }))
    .pipe(assets = $.useref.assets())
    .pipe($.rev())
    .pipe(jsFilter)
    .pipe($.ngAnnotate())
    .pipe($.uglify({preserveComments: $.uglifySaveLicense}))
    .pipe(jsFilter.restore())
    .pipe(cssFilter)
    .pipe($.replace('/bower_components/bootstrap/fonts','/assets/fonts'))
    .pipe($.replace(/url\('ui-grid\.(.*?)'\)/g,'url(\'/assets/fonts/ui-grid.$1\')'))
    .pipe($.csso())
    .pipe(cssFilter.restore())
    .pipe(assets.restore())
    .pipe($.useref())
    .pipe($.revReplace())
    .pipe(htmlFilter)
    .pipe($.minifyHtml({
      empty: true,
      spare: true,
      quotes: true
    }))
    .pipe(htmlFilter.restore())
    .pipe(gulp.dest('dist'))
    .pipe($.size());
});

gulp.task('images', function () {
  return gulp.src('src/assets/images/**/*')
    .pipe($.cache($.imagemin({
      optimizationLevel: 3,
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/assets/images'))
    .pipe($.size());
});

  gulp.task('fonts', function () {
    return es.concat(
      gulp.src($.mainBowerFiles()),
      gulp.src('src/assets/fonts/**/*')
    )
      .pipe($.filter('**/*.{eot,svg,ttf,woff}'))
      .pipe($.flatten())
      .pipe(gulp.dest('dist/assets/fonts'))
      .pipe($.size());
  });

gulp.task('misc', function () {
  return gulp.src('src/**/*.ico')
    .pipe(gulp.dest('dist'))
    .pipe($.size());
});

gulp.task('clear-cache', function() {
  $.cache.clearAll();
});

gulp.task('clean', function (done) {
  $.del(['.tmp', 'dist'], done);
});

gulp.task('build', ['html', 'images', 'fonts', 'misc']);
<commit_msg>temporarily turning off function name compression for dist builds until I debug the issue<commit_after>'use strict';

var gulp = require('gulp');
var es = require("event-stream")
var $ = require('gulp-load-plugins')({
  pattern: ['gulp-*', 'main-bower-files', 'uglify-save-license', 'del']
});

var connect = require('gulp-connect');

function handleError(err) {
  console.error(err.toString());
  this.emit('end');
}

gulp.task('styles', ['wiredep'],  function () {
  return gulp.src([
    'src/{app,components}/**/*.less',
    '!src/{app,components}/**/_*.less'
  ])
    .pipe($.less({
      paths: [
        'src/bower_components',
        'src/app',
        'src/components'
      ]
    }))
    .on('error', handleError)
    .pipe($.autoprefixer('last 1 version'))
    .pipe(gulp.dest('.tmp'))
    .pipe($.size());
});

gulp.task('scripts', function () {
  return gulp.src('src/{app,components}/**/*.js')
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.size());
});

gulp.task('partials', function () {
  return gulp.src('src/{app,components}/**/*.html')
    .pipe($.minifyHtml({
      empty: true,
      spare: true,
      quotes: true
    }))
    .pipe($.ngHtml2js({
      moduleName: 'civicClient'
    }))
    .pipe(gulp.dest('.tmp'))
    .pipe($.size());
});

gulp.task('html', ['styles', 'scripts', 'partials'], function () {
  var htmlFilter = $.filter('*.html');
  var jsFilter = $.filter('**/*.js');
  var cssFilter = $.filter('**/*.css');
  var assets;

  return gulp.src('src/*.html')
    .pipe($.inject(
      gulp.src('.tmp/{app,components}/**/*.js'),
      {
        starttag: '<!-- inject:partials -->',
        addRootSlash: false,
        addPrefix: '../'
      }))
    .pipe(assets = $.useref.assets())
    .pipe($.rev())
    .pipe(jsFilter)
    .pipe($.ngAnnotate())
    .pipe($.uglify({preserveComments: $.uglifySaveLicense, mangle: false}))
    .pipe(jsFilter.restore())
    .pipe(cssFilter)
    .pipe($.replace('/bower_components/bootstrap/fonts','/assets/fonts'))
    .pipe($.replace(/url\('ui-grid\.(.*?)'\)/g,'url(\'/assets/fonts/ui-grid.$1\')'))
    .pipe($.csso())
    .pipe(cssFilter.restore())
    .pipe(assets.restore())
    .pipe($.useref())
    .pipe($.revReplace())
    .pipe(htmlFilter)
    .pipe($.minifyHtml({
      empty: true,
      spare: true,
      quotes: true
    }))
    .pipe(htmlFilter.restore())
    .pipe(gulp.dest('dist'))
    .pipe($.size());
});

gulp.task('images', function () {
  return gulp.src('src/assets/images/**/*')
    .pipe($.cache($.imagemin({
      optimizationLevel: 3,
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/assets/images'))
    .pipe($.size());
});

  gulp.task('fonts', function () {
    return es.concat(
      gulp.src($.mainBowerFiles()),
      gulp.src('src/assets/fonts/**/*')
    )
      .pipe($.filter('**/*.{eot,svg,ttf,woff}'))
      .pipe($.flatten())
      .pipe(gulp.dest('dist/assets/fonts'))
      .pipe($.size());
  });

gulp.task('misc', function () {
  return gulp.src('src/**/*.ico')
    .pipe(gulp.dest('dist'))
    .pipe($.size());
});

gulp.task('clear-cache', function() {
  $.cache.clearAll();
});

gulp.task('clean', function (done) {
  $.del(['.tmp', 'dist'], done);
});

gulp.task('build', ['html', 'images', 'fonts', 'misc']);
<|endoftext|>


<commit_before>/**
* Flags
*/
var blockLinks = 0, // block default link action
	devNotice = 0;  // show dev notice

if (devNotice) console.log("Do things that relate to hacker news.");

function addDataToStore( postObjectArray ) {
	// save object to local storage
	chrome.storage.local.set(postObjectArray, function() {
		// Send message to background script
		chrome.runtime.sendMessage(postObjectArray);
		// print out to the console for now
		console.log(postObjectArray);
	});
}

// takes a post link and returns its comment url
function getCommentURL( linkToPost ) {
	var postCell,
		postRow,
		commentRow,
		commentLink,
		commentURL;

	postCell = linkToPost.parentNode;  // get table cell of link
	postRow = postCell.parentNode;	// get table row of link
	commentRow = postRow.nextElementSibling;  // go to next row (containing comment)

	// check if next row was found
	if( commentRow ) {
		commentLink = commentRow.querySelector("a:last-child"),  // get the last link in that row
		commentURL = commentLink.getAttribute("href");	// get the href attribute of comment link

		// return comment url
		return commentURL;
	}
}

function nodelistToArray( nodelist ) {
	var array = [];

	for (var i = 0; i < nodelist.length; i++ ) {
		var postObject,  // to be filled with post object later
			currentPost = nodelist[i],  // the node for the current post
			postURL = currentPost.getAttribute("href"),  // URL for current post link
			discussionURL = getCommentURL(currentPost);  // pass to function; get comment URL

		// Create post object
		postObject = {
			"linkURL": currentPost,
			"discussionURL": discussionURL
		}

		// add if it's not a "more" link
		if( postObject.discussionURL ) array.push( postObject );
	}

	return array;
}

var linkList,
	linkArray;

// grab all links including "more" link and convert to array of objects
linkList = document.querySelectorAll( "td.title a" );
linkArray = nodelistToArray( linkList );
// save this array to storage
addDataToStore( linkArray );

// remove the last element ("more" link)
linkArray.splice(31, 1);<commit_msg>Create object to be saved.<commit_after>/**
* Flags
*/
var blockLinks = 0, // block default link action
	devNotice = 0;  // show dev notice

if (devNotice) console.log("Do things that relate to hacker news.");

function addDataToStore( postObjectArray ) {
	// create object to be saved from arg
	var savableOject = {
		"posts": postObjectArray
	}

	// save object to local storage
	chrome.storage.local.set(savableOject, function() {
		// Send message to background script
		chrome.runtime.sendMessage(savableOject);
		// print out to the console for now
		console.log(savableOject);
	});
}

// takes a post link and returns its comment url
function getCommentURL( linkToPost ) {
	var postCell,
		postRow,
		commentRow,
		commentLink,
		commentURL;

	postCell = linkToPost.parentNode;  // get table cell of link
	postRow = postCell.parentNode;	// get table row of link
	commentRow = postRow.nextElementSibling;  // go to next row (containing comment)

	// check if next row was found
	if( commentRow ) {
		commentLink = commentRow.querySelector("a:last-child"),  // get the last link in that row
		commentURL = commentLink.getAttribute("href");	// get the href attribute of comment link

		// return comment url
		return commentURL;
	}
}

function nodelistToArray( nodelist ) {
	var array = [];

	for (var i = 0; i < nodelist.length; i++ ) {
		var postObject,  // to be filled with post object later
			currentPost = nodelist[i],  // the node for the current post
			postURL = currentPost.getAttribute("href"),  // URL for current post link
			discussionURL = getCommentURL(currentPost);  // pass to function; get comment URL

		// Create post object
		postObject = {
			"linkURL": currentPost,
			"discussionURL": discussionURL
		}

		// add if it's not a "more" link
		if( postObject.discussionURL ) array.push( postObject );
	}

	return array;
}

var linkList,
	linkArray;

// grab all links including "more" link and convert to array of objects
linkList = document.querySelectorAll( "td.title a" );
linkArray = nodelistToArray( linkList );
// save this array to storage
addDataToStore( linkArray );

// remove the last element ("more" link)
linkArray.splice(31, 1);<|endoftext|>


<commit_before>(function( $ ) {

    $.fn.fanoos = function(options) {

      var settings = $.extend({ // These are the defaults.
        animationClass: 'animated', // css animation univetsal class
        duration: 1000, // css animation duration (ms)
        offset: 0, // offset form top of the image
        delay: 0 // delay on playing animation
      }, options );

      var elementList = []; // a global list of fanoos elements

      function init() { // init function: gets all elements who need fanoos to animate them

        var elementNumber = 0; // start point of list

        $('.fanoos').each(function() { // for all fanoos element

          if ( $(this).attr('data-fanoos-id') == null || $(this).attr('data-fanoos-id').length == 0) { // if element didn't have a data-fanoos-id
            var fanoosId = 'fanoosElement' + elementNumber; // create a fanoos ID
            $(this).attr('data-fanoos-id', 'fanoosElement' + elementNumber); // and add it to data-fanoos-id
          } else {
            var fanoosId = $(this).attr('data-fanoos-id'); // or just use the one it has
          };

          if ( typeof $(this).attr('data-fanoos-offset') !== typeof undefined && $(this).attr('data-fanoos-offset') !== false ) { // if element had a data-fanoos-offset
            settings.offset = parseInt( $(this).attr('data-fanoos-offset') ); // update settings
          };

          if ( typeof $(this).attr('data-fanoos-delay') !== typeof undefined && $(this).attr('data-fanoos-offset') !== false ) { // if element had a data-fanoos-delay
            settings.delay = parseInt( Math.abs($(this).attr('data-fanoos-delay')) ); // update settings
          };

          if ( typeof $(this).attr('data-fanoos-duration') !== typeof undefined && $(this).attr('data-fanoos-duration') !== false ) { // if element had a data-fanoos-duration
            settings.duration = parseInt( Math.abs($(this).attr('data-fanoos-duration')) ); // update settings
          };

          $(this).addClass(settings.animationClass).css({
            'animation-play-state': 'paused',
            'animation-duration': settings.duration + 'ms',
            'animation-delay': settings.delay + 'ms',
          }); // add animation class but don't let it play

          var element = { // create a fannos element
            'fanoosID' : fanoosId, // ID
            'offsetTop'  : Math.ceil($(this).offset().top) + settings.offset // position from top
          }

          elementList.push(element); // add elment to list

          elementNumber++; // go for next elment
        });

      }

      function run(element) { // run function: play element's css animation
        element.css("animation-play-state", "running"); // play the animation
      }

      function action(){ // action function: connect run funtion to real world

        var resultList = $.grep(elementList, function(e){ // a list of fanoos elements that should be played
          return e.offsetTop <= ($(window).scrollTop() + $(window).height()); // just when bottom of window reached element
        });

        if (resultList.length > 0) { // if result list had any elements in it
          for (var i = 0; i < resultList.length; i++) {
            run( $('[data-fanoos-id="' + resultList[i].fanoosID + '"]') ); // play them one by one
          }
        }

      }

      init(); // initiate fanoos

      $(window).scroll(function(){ // do action when scrolling
        action();
      });

      $( document ).ready(function(){ // do action when document is loaded
        action();
      });

    }
}( jQuery ));
<commit_msg>individuality bug fixed<commit_after>(function( $ ) {

    $.fn.fanoos = function(options) {

      var settings = $.extend({ // These are the defaults.
        animationClass: 'animated', // css animation univetsal class
        duration: 1000, // css animation duration (ms)
        offset: 0, // offset form top of the image
        delay: 0 // delay on playing animation
      }, options );

      var elementList = []; // a global list of fanoos elements

      function init() { // init function: gets all elements who need fanoos to animate them

        var elementNumber = 0; // start point of list

        $('.fanoos').each(function() { // for all fanoos element

          var tempSettings = { // These are the unique settings
            duration: settings.duration, // TEMP css animation duration (ms)
            offset: settings.offset, // TEMP offset form top of the image
            delay: settings.delay // TEMP delay on playing animation
          }

          if ( $(this).attr('data-fanoos-id') == null || $(this).attr('data-fanoos-id').length == 0) { // if element didn't have a data-fanoos-id
            var fanoosId = 'fanoosElement' + elementNumber; // create a fanoos ID
            $(this).attr('data-fanoos-id', 'fanoosElement' + elementNumber); // and add it to data-fanoos-id
          } else {
            var fanoosId = $(this).attr('data-fanoos-id'); // or just use the one it has
          };

          if ( typeof $(this).attr('data-fanoos-offset') !== typeof undefined && $(this).attr('data-fanoos-offset') !== false ) { // if element had a data-fanoos-offset
            tempSettings.offset = parseInt( $(this).attr('data-fanoos-offset') ); // update settings
          };

          if ( typeof $(this).attr('data-fanoos-delay') !== typeof undefined && $(this).attr('data-fanoos-offset') !== false ) { // if element had a data-fanoos-delay
            tempSettings.delay = parseInt( Math.abs($(this).attr('data-fanoos-delay')) ); // update settings
          };

          if ( typeof $(this).attr('data-fanoos-duration') !== typeof undefined && $(this).attr('data-fanoos-duration') !== false ) { // if element had a data-fanoos-duration
            tempSettings.duration = parseInt( Math.abs($(this).attr('data-fanoos-duration')) ); // update settings
          };

          $(this).addClass(settings.animationClass).css({
            'animation-play-state': 'paused',
            'animation-duration': tempSettings.duration + 'ms',
            'animation-delay': tempSettings.delay + 'ms',
          }); // add animation class but don't let it play

          var element = { // create a fannos element
            'fanoosID' : fanoosId, // ID
            'offsetTop'  : Math.ceil($(this).offset().top) + tempSettings.offset // position from top
          }

          elementList.push(element); // add elment to list

          elementNumber++; // go for next elment
        });

      }

      function run(element) { // run function: play element's css animation
        element.css("animation-play-state", "running"); // play the animation
      }

      function action(){ // action function: connect run funtion to real world

        var resultList = $.grep(elementList, function(e){ // a list of fanoos elements that should be played
          return e.offsetTop <= ($(window).scrollTop() + $(window).height()); // just when bottom of window reached element
        });

        if (resultList.length > 0) { // if result list had any elements in it
          for (var i = 0; i < resultList.length; i++) {
            run( $('[data-fanoos-id="' + resultList[i].fanoosID + '"]') ); // play them one by one
          }
        }

      }

      init(); // initiate fanoos

      $(window).scroll(function(){ // do action when scrolling
        action();
      });

      $( document ).ready(function(){ // do action when document is loaded
        action();
      });

    }
}( jQuery ));
<|endoftext|>


<commit_before>//-------------------------------------------
// kafe.plugin.carousel
//-------------------------------------------
kafe.plug({name:'carousel', version:'1.0.1', obj:(function($,K,undefined){

	// local variables
	var
		_DEBUG  = false,
		_prefix = K.idantite.non + 'Carousel',
		_all    = {}
	;

	// _refresh
	//-------------------------------------------
	function _refresh(c) {

		function none(e) { e.preventDefault(); }

		if (!c.wrap) {

			// précédent
			if (c.curr == 0) {
				c.$start
					.addClass(_prefix+'-Inactive')
					.off('click', c.startClick)
					.on('click',  none)
				;
				c.$previous
					.addClass(_prefix+'-Inactive')
					.off('click', c.previousClick)
					.on('click',  none)
				;
			} else {
				c.$start
					.removeClass(_prefix+'-Inactive')
					.off('click', c.startClick)
					.on('click',  c.startClick)
				;
				c.$previous
					.removeClass(_prefix+'-Inactive')
					.off('click', c.previousClick)
					.on('click',  c.previousClick)
				;
			}

			// next
			if (c.curr == (c.total-1)) {
				c.$next
					.addClass(_prefix+'-Inactive')
					.off('click', c.nextClick)
					.on('click',  none)
				;
				c.$end
					.addClass(_prefix+'-Inactive')
					.off('click', c.endClick)
					.on('click',  none)
				;
			} else {
				c.$next
					.removeClass(_prefix+'-Inactive')
					.off('click', c.nextClick)
					.on('click',  c.nextClick)
				;
				c.$end
					.removeClass(_prefix+'-Inactive')
					.off('click', c.endClick)
					.on('click',  c.endClick)
				;
			}
		}

		// position
		c.$position.html(c.curr+1);

		// status
		c.$status.html('');
		c.$statusNum.html('');
		for (var i=0; i<c.total; ++i) {
			if (i == c.curr) {
				c.$status.append(''+c.statusBullet+'');
				c.$statusNum.append(''+(i+1)+'');
			} else {
				if(!!c.statusLink) {
					c.$status.append(
						$('')
							.attr('href','#')
							.data(_prefix+'-itemid', i+1)
							.on('click',c.itemSimpleClick)
							.html(c.statusBullet)
					);
					c.$statusNum.append(
						$('')
							.attr('href','#')
							.data(_prefix+'-itemid', i+1)
							.on('click',c.itemSimpleClick)
							.html(i+1)
					);
				} else {
					c.$status.append(c.statusBullet);
					c.$statusNum.append(i+1);
				}
			}
		}
	}

	// _change (carousel, target_position)
	// do a position change
	//-------------------------------------------
	function _change(c, target) {

		if (!!c.changing) {
			return false;
		}
		if (target == c.curr) {
			return false;
		}
		c.changing = true;
		c.slideStopAuto();

		var callbackData = {
			action: (Number(target) == target) ? 'item' : target,
			source: {
				position: c.curr+1
			},
			target: {}
		};

		var way;

		// current li
		var $liCurr = c.$Main.children(':nth-child('+(c.curr+1)+')')

		// prev/next
		if (target == 'prev' || target == 'next') {

			way = (target == 'prev') ? -1 : 1;

			c.curr =
				(c.wrap) ?
					(c.curr == 0 && way == -1) ?
						(c.total-1)
						: ((c.curr + way) % c.total)
					: (c.curr + way)
			;

		// item
		} else {
			target == Number(target);

			way = (target < c.curr) ? -1 : 1;
			c.curr = target;
		}

		// new li
		var $liNew = c.$Main.children(':nth-child('+(c.curr+1)+')');

		// add callback data
		callbackData.source.obj      = $liCurr.get(0);
		callbackData.target.position = c.curr+1;
		callbackData.target.obj      = $liNew.get(0);

		if (!!c.preSwitchCallback) {
			c.preSwitchCallback(callbackData);
		}

		// transitions
		switch (c.transition) {

			// fade
			case 'fade':
				$liCurr.css('z-index',1);

				$liNew
					.css('z-index',2)
					.fadeIn(c.speed, function(){
						$liCurr.hide();
						c.changing = false;
					})
				;
			break;

			// move right-bottom > top-left
			/*
			case 'slideTopLeft':
				var height = c.$Main.height() + 'px';
				var width = c.$Main.width() + 'px';

				$liCurr.animate({
					top:  (way == 1) ? '-'+height : height,
					left: (way == 1) ? '-'+width  : width
				});

				$liNew
					.css('top',  (way == 1) ? height : '-'+height)
					.css('left', (way == 1) ? width  : '-'+width)
					.animate({
						top:  '0px',
						left: '0px'
					})
				;
			break;
			*/

			// slide horizontal
			case 'slideUp':
			case 'slideDown':
				way = (c.transition == 'slideDown') ? -way : way;

				var height = c.$Main.height() + 'px';

				$liCurr.animate(
					{ top: (way == 1) ? '-'+height : height},
					c.speed,
					function() { $(this).hide(); c.changing = false; }
				);

				$liNew
					.css({
						top:     (way == 1) ? height : '-'+height,
						display: 'block'
					})
					.animate({
						top: '0px'
					},c.speed)
				;
			break;

			// slide vertical
			case 'slideLeft':
			case 'slideRight':
			default:
				way = (c.transition == 'slideRight') ? -way : way;

				var width = c.$Main.width() + 'px';

				$liCurr.animate(
					{ left: (way == 1) ? '-'+width : width },
					c.speed,
					function() { $(this).hide(); c.changing = false; }
				);

				$liNew
					.css({
						left:     (way == 1) ? width : '-'+width,
						display: 'block'
					})
					.animate({
						left: '0px'
					},c.speed)
				;
			break;
		}

		_refresh(c);

		// éventuellement positionner dans le animate callback
		if (!!c.postSwitchCallback) {
			c.postSwitchCallback(callbackData);
		}

		c.slideStartAuto();
	}

	//-------------------------------------------
	// PUBLIC
	//-------------------------------------------
	var carousel  = {};

	// init (id/[see below])
	// initialize a new carousel
	//-------------------------------------------
	carousel.init = function() {
		var c = {};

		var options  = (arguments) ? arguments[0] : {};
		c.id         = options.id;
		c.wrap       = !!options.wrap;
		c.transition = (options.transition)      ? options.transition : 'slideLeft';
		c.speed      = (Number(options.speed))   ? Number(options.speed)   : 500;
		c.startId    = (Number(options.startId)) ? Number(options.startId) : 1;
		/*
		c.autostart  =
			(options.autostart) ? (
				(Number(options.autostart.start)) ?
					Number(options.autostart.start)
					: 3000)
				: undefined
		;*/
		c.autointerval =
			(options.autostart) ? (
				(Number(options.autostart.interval)) ?
					Number(options.autostart.interval)
					: 3000)
				: undefined
		;
		c.preSwitchCallback  = (typeof(options.preSwitchCallback)  == 'function') ? options.preSwitchCallback  : undefined;
		c.postSwitchCallback = (typeof(options.postSwitchCallback) == 'function') ? options.postSwitchCallback : undefined;
		c.statusLink         = !!options.statusLink;
		c.statusBullet       = (options.statusBullet) ? options.statusBullet : '•';

		// Liste
		c.$Main      = $('#'+c.id);
		if (!c.$Main.length) { return false; }

		c.$MainItems     = c.$Main.children();
		c.$MainFirstItem = c.$MainItems.eq(0);
		c.total          = c.$MainItems.length;

		// nav
		c.$all        = $('[data-'+_prefix+'-id="'+c.id+'"]');
		c.$nav        = c.$all.filter('[data-'+_prefix+'-action="nav"]');
		c.$start      = c.$all.filter('[data-'+_prefix+'-action="start"]');
		c.$previous   = c.$all.filter('[data-'+_prefix+'-action="prev"]');
		c.$next       = c.$all.filter('[data-'+_prefix+'-action="next"]');
		c.$end        = c.$all.filter('[data-'+_prefix+'-action="end"]');
		c.$items      = c.$all.filter('[data-'+_prefix+'-action="items"]');
		c.$itemsimple = c.$all.filter('[data-'+_prefix+'-action="item"]');
		c.$play       = c.$all.filter('[data-'+_prefix+'-action="play"]');
		c.$pause      = c.$all.filter('[data-'+_prefix+'-action="pause"]');

		// position
		c.$position  = c.$all.filter('[data-'+_prefix+'-action="position"]');
		c.$total     = c.$all.filter('[data-'+_prefix+'-action="total"]');
		c.$status    = c.$all.filter('[data-'+_prefix+'-action="status"]');
		c.$statusNum = c.$all.filter('[data-'+_prefix+'-action="status-num"]');

		// désactiver tout si un seul item
		if (c.total == 1) {
			c.$nav.addClass(_prefix+'-None');
			c.$previous.addClass(_prefix+'-None');
			c.$next.addClass(_prefix+'-None');
			c.$items.addClass(_prefix+'-None');
			c.$itemsimple.addClass(_prefix+'-None');
			c.$position.addClass(_prefix+'-None');
			c.$total.addClass(_prefix+'-None');
			c.$status.addClass(_prefix+'-None');
			c.$statusNum.addClass(_prefix+'-None');

		// sinon préparer carousel
		} else {

			// initial
			c.curr     = c.startId-1;
			c.changing = false;

			// general events
			c.startClick = function(e){
				e.preventDefault();
				_change(c, 0);
			};

			c.previousClick = function(e){
				e.preventDefault();
				_change(c, 'prev');
			};

			c.nextClick = function(e){
				e.preventDefault();
				_change(c, 'next');
			};

			c.endClick = function(e){
				e.preventDefault();
				_change(c, c.total-1);
			};

			c.itemSimpleClick = function(e){
				e.preventDefault();
				_change(c, $(this).data(_prefix+'-itemid') - 1);
			};

			c.playClick = function(e){
				e.preventDefault();
				c.AutoRunning = true;
				c.slideStartAuto();
			};

			c.pauseClick = function(e){
				e.preventDefault();
				c.AutoRunning = false;
				c.slideStopAuto();
			};

			c.slideStartAuto = function(){
				if (c.AutoRunning) {
					c.Timeout = setTimeout(function(){ _change(c, 'next', true); }, c.autointerval);
				}
			};

			c.slideStopAuto = function(){
				clearTimeout(c.Timeout);
				c.Timeout = undefined;
			};

			// on events
			c.$start.on('click',c.startClick)
			c.$previous.on('click',c.previousClick)
			c.$next.on('click',c.nextClick)
			c.$end.on('click',c.endClick)
			c.$itemsimple.on('click',c.itemSimpleClick);

			c.$items.children().each(function(i){
				$(this).on('click',function(e){
					e.preventDefault();
					_change(c, i);
				});
			});

			c.$play.on('click',c.playClick)
			c.$pause.on('click',c.pauseClick);

			c.$MainItems.on({
				mouseenter: c.slideStopAuto,
				mouseleave: c.slideStartAuto
			});

			// intialiser look
			c.$total.html(c.total);
			_refresh(c);

			c.$MainItems.hide();
			c.$Main.children(':nth-child('+c.startId+')').show();

			switch (c.transition) {
				// fade
				case 'fade':
				break;

				// move vertical
				case 'slideUp':
				case 'slideDown':
					c.$MainItems.css({
						left: '0px'
					});
					c.$MainFirstItem.css('top','0px');
				break;

				// move horizontal
				case 'slideLeft':
				case 'slideRight':
				default:
					c.$MainItems.css({
						top: '0px'
					});
					c.$MainFirstItem.css('left','0px');
				break;
			}

			// autostart
			if (c.autointerval != undefined) {
				c.AutoRunning = true;
				c.slideStartAuto();
			}

			// Ajouter à la liste
			_all[c.id] = c;
		}
	};

	// change (id, target_position)
	// manual change
	//-------------------------------------------
	carousel.change = function(id, target) {
		return _change(_all[id], (Number(target) == target) ? target-1 : target);
	};

	// debug only
	if (_DEBUG) {
		carousel.carousels = _all;
	}

	return carousel;

})(jQuery,kafe)});<commit_msg>[No message]<commit_after>//-------------------------------------------
// kafe.plugin.carousel
//-------------------------------------------
kafe.plug({name:'carousel', version:'1.0.1', obj:(function($,K,undefined){

	// local variables
	var
		_DEBUG  = false,
		_prefix = K.idantite.non + 'carousel',
		_all    = {}
	;

	// _refresh
	//-------------------------------------------
	function _refresh(c) {

		function none(e) { e.preventDefault(); }

		if (!c.wrap) {

			// précédent
			if (c.curr == 0) {
				c.$start
					.addClass(_prefix+'-Inactive')
					.off('click', c.startClick)
					.on('click',  none)
				;
				c.$previous
					.addClass(_prefix+'-Inactive')
					.off('click', c.previousClick)
					.on('click',  none)
				;
			} else {
				c.$start
					.removeClass(_prefix+'-Inactive')
					.off('click', c.startClick)
					.on('click',  c.startClick)
				;
				c.$previous
					.removeClass(_prefix+'-Inactive')
					.off('click', c.previousClick)
					.on('click',  c.previousClick)
				;
			}

			// next
			if (c.curr == (c.total-1)) {
				c.$next
					.addClass(_prefix+'-Inactive')
					.off('click', c.nextClick)
					.on('click',  none)
				;
				c.$end
					.addClass(_prefix+'-Inactive')
					.off('click', c.endClick)
					.on('click',  none)
				;
			} else {
				c.$next
					.removeClass(_prefix+'-Inactive')
					.off('click', c.nextClick)
					.on('click',  c.nextClick)
				;
				c.$end
					.removeClass(_prefix+'-Inactive')
					.off('click', c.endClick)
					.on('click',  c.endClick)
				;
			}
		}

		// position
		c.$position.html(c.curr+1);

		// status
		c.$status.html('');
		c.$statusNum.html('');
		for (var i=0; i<c.total; ++i) {
			if (i == c.curr) {
				c.$status.append(''+c.statusBullet+'');
				c.$statusNum.append(''+(i+1)+'');
			} else {
				if(!!c.statusLink) {
					c.$status.append(
						$('')
							.attr('href','#')
							.data(_prefix+'-itemid', i+1)
							.on('click',c.itemSimpleClick)
							.html(c.statusBullet)
					);
					c.$statusNum.append(
						$('')
							.attr('href','#')
							.data(_prefix+'-itemid', i+1)
							.on('click',c.itemSimpleClick)
							.html(i+1)
					);
				} else {
					c.$status.append(c.statusBullet);
					c.$statusNum.append(i+1);
				}
			}
		}
	}

	// _change (carousel, target_position)
	// do a position change
	//-------------------------------------------
	function _change(c, target) {

		if (!!c.changing) {
			return false;
		}
		if (target == c.curr) {
			return false;
		}
		c.changing = true;
		c.slideStopAuto();

		var callbackData = {
			action: (Number(target) == target) ? 'item' : target,
			source: {
				position: c.curr+1
			},
			target: {}
		};

		var way;

		// current li
		var $liCurr = c.$Main.children(':nth-child('+(c.curr+1)+')')

		// prev/next
		if (target == 'prev' || target == 'next') {

			way = (target == 'prev') ? -1 : 1;

			c.curr =
				(c.wrap) ?
					(c.curr == 0 && way == -1) ?
						(c.total-1)
						: ((c.curr + way) % c.total)
					: (c.curr + way)
			;

		// item
		} else {
			target = Number(target);

			way = (target < c.curr) ? -1 : 1;
			c.curr = target;
		}

		// new li
		var $liNew = c.$Main.children(':nth-child('+(c.curr+1)+')');

		// add callback data
		callbackData.source.obj      = $liCurr.get(0);
		callbackData.target.position = c.curr+1;
		callbackData.target.obj      = $liNew.get(0);

		if (!!c.preSwitchCallback) {
			c.preSwitchCallback(callbackData);
		}

		// transitions
		switch (c.transition) {

			// fade
			case 'fade':
				$liCurr.css('z-index',1);

				$liNew
					.css('z-index',2)
					.fadeIn(c.speed, function(){
						$liCurr.hide();
						c.changing = false;
					})
				;
			break;

			// move right-bottom > top-left
			/*
			case 'slideTopLeft':
				var height = c.$Main.height() + 'px';
				var width = c.$Main.width() + 'px';

				$liCurr.animate({
					top:  (way == 1) ? '-'+height : height,
					left: (way == 1) ? '-'+width  : width
				});

				$liNew
					.css('top',  (way == 1) ? height : '-'+height)
					.css('left', (way == 1) ? width  : '-'+width)
					.animate({
						top:  '0px',
						left: '0px'
					})
				;
			break;
			*/

			// slide horizontal
			case 'slideUp':
			case 'slideDown':
				way = (c.transition == 'slideDown') ? -way : way;

				var height = c.$Main.height() + 'px';

				$liCurr.animate(
					{ top: (way == 1) ? '-'+height : height},
					c.speed,
					function() { $(this).hide(); c.changing = false; }
				);

				$liNew
					.css({
						top:     (way == 1) ? height : '-'+height,
						display: 'block'
					})
					.animate({
						top: '0px'
					},c.speed)
				;
			break;

			// slide vertical
			case 'slideLeft':
			case 'slideRight':
			default:
				way = (c.transition == 'slideRight') ? -way : way;

				var width = c.$Main.width() + 'px';

				$liCurr.animate(
					{ left: (way == 1) ? '-'+width : width },
					c.speed,
					function() { $(this).hide(); c.changing = false; }
				);

				$liNew
					.css({
						left:     (way == 1) ? width : '-'+width,
						display: 'block'
					})
					.animate({
						left: '0px'
					},c.speed)
				;
			break;
		}

		_refresh(c);

		// éventuellement positionner dans le animate callback
		if (!!c.postSwitchCallback) {
			c.postSwitchCallback(callbackData);
		}

		c.slideStartAuto();
	}

	//-------------------------------------------
	// PUBLIC
	//-------------------------------------------
	var carousel  = {};

	// init (id/[see below])
	// initialize a new carousel
	//-------------------------------------------
	carousel.init = function() {
		var c = {};

		var options  = (arguments) ? arguments[0] : {};
		c.id         = options.id;
		c.wrap       = !!options.wrap;
		c.transition = (options.transition)      ? options.transition : 'slideLeft';
		c.speed      = (Number(options.speed))   ? Number(options.speed)   : 500;
		c.startId    = (Number(options.startId)) ? Number(options.startId) : 1;
		/*
		c.autostart  =
			(options.autostart) ? (
				(Number(options.autostart.start)) ?
					Number(options.autostart.start)
					: 3000)
				: undefined
		;*/
		c.autointerval =
			(options.autostart) ? (
				(Number(options.autostart.interval)) ?
					Number(options.autostart.interval)
					: 3000)
				: undefined
		;
		c.preSwitchCallback  = (typeof(options.preSwitchCallback)  == 'function') ? options.preSwitchCallback  : undefined;
		c.postSwitchCallback = (typeof(options.postSwitchCallback) == 'function') ? options.postSwitchCallback : undefined;
		c.statusLink         = !!options.statusLink;
		c.statusBullet       = (options.statusBullet) ? options.statusBullet : '•';

		// Liste
		c.$Main      = $('#'+c.id);
		if (!c.$Main.length) { return false; }

		c.$MainItems     = c.$Main.children();
		c.$MainFirstItem = c.$MainItems.eq(0);
		c.total          = c.$MainItems.length;

		// nav
		c.$all        = $('[data-'+_prefix+'-id="'+c.id+'"]');
		c.$nav        = c.$all.filter('[data-'+_prefix+'-action="nav"]');
		c.$start      = c.$all.filter('[data-'+_prefix+'-action="start"]');
		c.$previous   = c.$all.filter('[data-'+_prefix+'-action="prev"]');
		c.$next       = c.$all.filter('[data-'+_prefix+'-action="next"]');
		c.$end        = c.$all.filter('[data-'+_prefix+'-action="end"]');
		c.$items      = c.$all.filter('[data-'+_prefix+'-action="items"]');
		c.$itemsimple = c.$all.filter('[data-'+_prefix+'-action="item"]');
		c.$play       = c.$all.filter('[data-'+_prefix+'-action="play"]');
		c.$pause      = c.$all.filter('[data-'+_prefix+'-action="pause"]');

		// position
		c.$position  = c.$all.filter('[data-'+_prefix+'-action="position"]');
		c.$total     = c.$all.filter('[data-'+_prefix+'-action="total"]');
		c.$status    = c.$all.filter('[data-'+_prefix+'-action="status"]');
		c.$statusNum = c.$all.filter('[data-'+_prefix+'-action="status-num"]');

		// désactiver tout si un seul item
		if (c.total == 1) {
			c.$nav.addClass(_prefix+'-None');
			c.$previous.addClass(_prefix+'-None');
			c.$next.addClass(_prefix+'-None');
			c.$items.addClass(_prefix+'-None');
			c.$itemsimple.addClass(_prefix+'-None');
			c.$position.addClass(_prefix+'-None');
			c.$total.addClass(_prefix+'-None');
			c.$status.addClass(_prefix+'-None');
			c.$statusNum.addClass(_prefix+'-None');

		// sinon préparer carousel
		} else {

			// initial
			c.curr     = c.startId-1;
			c.changing = false;

			// general events
			c.startClick = function(e){
				e.preventDefault();
				_change(c, 0);
			};

			c.previousClick = function(e){
				e.preventDefault();
				_change(c, 'prev');
			};

			c.nextClick = function(e){
				e.preventDefault();
				_change(c, 'next');
			};

			c.endClick = function(e){
				e.preventDefault();
				_change(c, c.total-1);
			};

			c.itemSimpleClick = function(e){
				e.preventDefault();
				_change(c, $(this).data(_prefix+'-itemid') - 1);
			};

			c.playClick = function(e){
				e.preventDefault();
				c.AutoRunning = true;
				c.slideStartAuto();
			};

			c.pauseClick = function(e){
				e.preventDefault();
				c.AutoRunning = false;
				c.slideStopAuto();
			};

			c.slideStartAuto = function(){
				if (c.AutoRunning) {
					c.Timeout = setTimeout(function(){ _change(c, 'next', true); }, c.autointerval);
				}
			};

			c.slideStopAuto = function(){
				clearTimeout(c.Timeout);
				c.Timeout = undefined;
			};

			// on events
			c.$start.on('click',c.startClick)
			c.$previous.on('click',c.previousClick)
			c.$next.on('click',c.nextClick)
			c.$end.on('click',c.endClick)
			c.$itemsimple.on('click',c.itemSimpleClick);

			c.$items.children().each(function(i){
				$(this).on('click',function(e){
					e.preventDefault();
					_change(c, i);
				});
			});

			c.$play.on('click',c.playClick)
			c.$pause.on('click',c.pauseClick);

			c.$MainItems.on({
				mouseenter: c.slideStopAuto,
				mouseleave: c.slideStartAuto
			});

			// intialiser look
			c.$total.html(c.total);
			_refresh(c);

			c.$MainItems.hide();
			c.$Main.children(':nth-child('+c.startId+')').show();

			switch (c.transition) {
				// fade
				case 'fade':
				break;

				// move vertical
				case 'slideUp':
				case 'slideDown':
					c.$MainItems.css({
						left: '0px'
					});
					c.$MainFirstItem.css('top','0px');
				break;

				// move horizontal
				case 'slideLeft':
				case 'slideRight':
				default:
					c.$MainItems.css({
						top: '0px'
					});
					c.$MainFirstItem.css('left','0px');
				break;
			}

			// autostart
			if (c.autointerval != undefined) {
				c.AutoRunning = true;
				c.slideStartAuto();
			}

			// Ajouter à la liste
			_all[c.id] = c;
		}
	};

	// change (id, target_position)
	// manual change
	//-------------------------------------------
	carousel.change = function(id, target) {
		return _change(_all[id], (Number(target) == target) ? target-1 : target);
	};

	// debug only
	if (_DEBUG) {
		carousel.carousels = _all;
	}

	return carousel;

})(jQuery,kafe)});<|endoftext|>


<commit_before>'use strict';

var kafka = require('kafka-node');
var Consumer = kafka.Consumer;
var Offset = kafka.Offset;
var Client = kafka.Client;
var topic = 'topic1';

var client = new Client('localhost:2181');
var topics = [
    {topic: topic, partition: 0}
];
var options = { autoCommit: false, fetchMaxWaitMs: 1000, fetchMaxBytes: 1024 * 1024 };

var consumer = new Consumer(client, topics, options);
var offset = new Offset(client);

consumer.on('message', function (message) {
  console.log(message);
});

consumer.on('error', function (err) {
  console.log('error', err);
});

/*
* If consumer get `offsetOutOfRange` event, fetch data from the smallest(oldest) offset
*/
consumer.on('offsetOutOfRange', function (topic) {
  topic.maxNum = 2;
  offset.fetch([topic], function (err, offsets) {
    if (err) {
      return console.error(err);
    }
    var min = Math.min(offsets[topic.topic][topic.partition]);
    consumer.setOffset(topic.topic, topic.partition, min);
  });
});
<commit_msg>Solving linter findings<commit_after>const Kafka = require("kafka-node");

const client = new Kafka.Client("localhost:2181");
const topics = [{ topic: "topic1", partition: 0 }];
const options = { autoCommit: false, fetchMaxWaitMs: 1000, fetchMaxBytes: 1024 * 1024 };

const consumer = new Kafka.Consumer(client, topics, options);
const offset = new Kafka.Offset(client);

consumer.on("message", (message) => {
    console.log(message);
});

consumer.on("error", (err) => {
    console.log("error", err);
});

/*
* If consumer get `offsetOutOfRange` event, fetch data from the smallest(oldest) offset
*/
consumer.on("offsetOutOfRange", (t) => {
    const topic = t;
    topic.maxNum = 2;

    offset.fetch([topic], (err, offsets) => {
        if (err) {
            console.error(err);
        }

        const min = Math.min(offsets[topic.topic][topic.partition]);
        consumer.setOffset(topic.topic, topic.partition, min);
    });
});
<|endoftext|>


<commit_before>/*
* This code is for the PowerTokens project.
* OAuth2 flow adapted from sample code from JeremiahLee
* Uses Fetch & Fitbit Web API
*/

//VARIOUS KEYS and AUTH IDS needed
var fbTok;
var clientID = 'YOUR_ID_HERE';
var callback = 'YOUR_WEBSITE_HERE';
var authURI = 'https://www.fitbit.com/oauth2/authorize';
var authTokenReq = 'https://api.fitbit.com/oauth2/token';

// Implementing 'Implicit Auth in OATH2.0'
if (!window.location.hash){
	window.location.replace( authURI+'?response_type=token'+'&client_id='+clientID
		+'&redirect_uri='+callback+'&scope=activity');
} else{
    var fragmentQueryParameters = {};
    window.location.hash.slice(1).replace(
        new RegExp("([^?=&]+)(=([^&]*))?", "g"),
        function($0, $1, $2, $3) { fragmentQueryParameters[$1] = $3; }
    );

    fbTok = fragmentQueryParameters.access_token;
}

// HANDLE the response from FITBIT API (expect JSON)
var processResponse = function(response){
	if (!response.ok){
		throw new Error('Fitbit API request failed' + response);
	}
	var contentType = response.headers.get('content-type')
	if(contentType && contentType.indexOf("application/json") !== -1){
		document.querySelector('h2').textContent = 'JSON recieved!';
		return response.json();
	}else{
		throw new Error('JSON expected but received'+contentType);
	}
}

// HANDLE the data from an /ACTIVITY api endpoint - summary data
var processActivity = function(activity){
	document.getElementById('activityHeader').textContent = 'Fitbit - GET Activity';
	prettyAct = JSON.stringify(activity, null, 2);
	console.log(prettyAct)

	//these are the three "elements" of data returned in the activity summary
	best = JSON.stringify(activity["best"], null, 2);
	lifetime = JSON.stringify(activity["best"], null, 2);
	tracker = JSON.stringify(activity["tracker"], null, 2);

	var display = document.getElementById('display');
	display.textContent = best;
}

//HANDLE data from /Activity/Date api endpoint - get actual step count data
var processActivityWithDate = function(activity){
        //get GOALS (default 10K)
        var goalSteps = activity["goals"]["steps"];

        //get STEPS BY ACTIVITY
        var activitySteps = {};
        var actArray = activity["activities"];
        var len = actArray.length;
        for ( var i = 0; i < len; i++){
                var id = actArray[i]["logId"];
                var steps = actArray[i]["steps"];
                console.log(id+ ': '+steps);
                activitySteps[id] = steps;
        }
        var activityStepsStr = JSON.stringify(activitySteps, null, 2);

        //get SUMMARY STEPS TODAY
        var sumSteps = activity["summary"]["steps"];

        //print out the data (buggy, need to figure out how to print new lines in javascript!)
        var newpara = document.createElement("p");
        var br = document.createElement("br");
        newpara.append( 'Goal Steps:' +goalSteps);
        newpara.append(br);
        newpara.append( 'Steps by Activity: ' + activityStepsStr);
        newpara.append(br);
        newpara.append( 'Summary (total) Steps Today: '+ sumSteps);

        var nextHeader = document.getElementById("otherHeader");
        document.body.insertBefore(newpara, nextHeader);

//      console.log(JSON.stringify(activity, null, 2));
}

// Now, actually go forth and FETCH Activity Summary data
var activityURL = 'https://api.fitbit.com/1/user/-/activities.json';
fetch( activityURL,
	{
		headers: new Headers({
			'Authorization': 'Bearer ' + fbTok
		}),
		mode: 'cors',
		method: 'GET'
	}
	).then(processResponse)
	.then(processActivity)
	.catch(function(error){ console.log(error);});

//go forth and fetch Daily Activity Data (much more detail)
var date = '2017-10-10';
var activityWithDateUrl = 'https://api.fitbit.com/1/user/-/activities/date/'+date+'.json';
fetch( activityWithDateUrl,
        {
                headers: new Headers({
                        'Authorization': 'Bearer ' + fbTok
                }),
                mode: 'cors',
                method: 'GET'
        }
        ).then(processResponse)
        .then(processActivityWithDate)
        .catch(function(error){ console.log(error);});
<commit_msg>update fitbit.js <commit_after>/*
* This code is for the PowerTokens project.
* OAuth2 flow adapted from sample code from JeremiahLee
* Uses Fetch & Fitbit Web API
*/

//VARIOUS KEYS and AUTH IDS needed
var fbTok;
var clientID = 'YOUR_ID_HERE';
var callback = 'YOUR_WEBSITE_HERE';
var authURI = 'https://www.fitbit.com/oauth2/authorize';
var authTokenReq = 'https://api.fitbit.com/oauth2/token';

// Implementing 'Implicit Auth in OATH2.0'
if (!window.location.hash){
	window.location.replace( authURI+'?response_type=token'+'&client_id='+clientID
		+'&redirect_uri='+callback+'&scope=activity');
} else{
    var fragmentQueryParameters = {};
    window.location.hash.slice(1).replace(
        new RegExp("([^?=&]+)(=([^&]*))?", "g"),
        function($0, $1, $2, $3) { fragmentQueryParameters[$1] = $3; }
    );

    fbTok = fragmentQueryParameters.access_token;
}

// HANDLE the response from FITBIT API (expect JSON)
var processResponse = function(response){
	if (!response.ok){
		throw new Error('Fitbit API request failed' + response);
	}
	var contentType = response.headers.get('content-type')
	if(contentType && contentType.indexOf("application/json") !== -1){
		document.querySelector('h2').textContent = 'JSON recieved!';
		return response.json();
	}else{
		throw new Error('JSON expected but received'+contentType);
	}
}

// HANDLE the data from an /ACTIVITY api endpoint - summary data
var processActivity = function(activity){
	document.getElementById('activityHeader').textContent = 'Fitbit - GET Activity';
	prettyAct = JSON.stringify(activity, null, 2);
	console.log(prettyAct)

	//these are the three "elements" of data returned in the activity summary
	best = JSON.stringify(activity["best"], null, 2);
	lifetime = JSON.stringify(activity["best"], null, 2);
	tracker = JSON.stringify(activity["tracker"], null, 2);

	var display = document.getElementById('display');
	display.textContent = best;
}

//HANDLE data from /Activity/Date api endpoint - get actual step count data
var processActivityWithDate = function(activity){
        //get GOALS (default 10K)
        var goalSteps = activity["goals"]["steps"];

        //get STEPS BY ACTIVITY
        var activitySteps = {};
        var actArray = activity["activities"];
        var len = actArray.length;
        for ( var i = 0; i < len; i++){
                var id = actArray[i]["logId"];
                var steps = actArray[i]["steps"];
                console.log(id+ ': '+steps);
                activitySteps[id] = steps;
        }
        var activityStepsStr = JSON.stringify(activitySteps, null, 2);

        //get SUMMARY STEPS TODAY
        var sumSteps = activity["summary"]["steps"];

        //print out the data (buggy, need to figure out how to print new lines in javascript!)
        var newpara = document.createElement("p");
        var dataStr = 'Goal Steps:' +goalSteps + '
'
        	+ 'Steps by Activity: ' + activityStepsStr + '
'
        	+ 'Summary (total) Steps Today: '+ sumSteps + '
';
	newpara.innerHTML = dataStr;

        var nextHeader = document.getElementById("otherHeader");
        document.body.insertBefore(newpara, nextHeader);
//      console.log(JSON.stringify(activity, null, 2));
}

// Now, actually go forth and FETCH Activity Summary data
var activityURL = 'https://api.fitbit.com/1/user/-/activities.json';
fetch( activityURL,
	{
		headers: new Headers({
			'Authorization': 'Bearer ' + fbTok
		}),
		mode: 'cors',
		method: 'GET'
	}
	).then(processResponse)
	.then(processActivity)
	.catch(function(error){ console.log(error);});

//go forth and fetch Daily Activity Data (much more detail)
var date = '2017-10-10';
var activityWithDateUrl = 'https://api.fitbit.com/1/user/-/activities/date/'+date+'.json';
fetch( activityWithDateUrl,
        {
                headers: new Headers({
                        'Authorization': 'Bearer ' + fbTok
                }),
                mode: 'cors',
                method: 'GET'
        }
        ).then(processResponse)
        .then(processActivityWithDate)
        .catch(function(error){ console.log(error);});
<|endoftext|>


<commit_before>describe("About Functions", function() {

  it("should declare functions", function() {

    function add(a, b) {
      return a + b;
    }

    expect(add(1, 2)).toBe(3);
  });

  it("should know internal variables override outer variables", function () {
    var message = "Outer";

    function getMessage() {
      return message;
    }

    function overrideMessage() {
      var message = "Inner";
      return message;
    }

    expect(getMessage()).toBe('Outer');
    expect(overrideMessage()).toBe('Inner');
    expect(message).toBe('Outer');
  });

  it("should have lexical scoping", function () {
    var variable = "top-level";
    function parentfunction() {
        var variable = "local";
      function childfunction() {
          return variable;
      }
      return childfunction();
    }
    expect(parentfunction()).toBe(FILL_ME_IN);
  });

  it("should use lexical scoping to synthesise functions", function () {

    function makeIncreaseByFunction(increaseByAmount) {
      return function (numberToIncrease) {
        return numberToIncrease + increaseByAmount;
      };
    }

    var increaseBy3 = makeIncreaseByFunction(3);
    var increaseBy5 = makeIncreaseByFunction(5);

    expect(increaseBy3(10) + increaseBy5(10)).toBe(FILL_ME_IN);
  });

  it("should allow extra function arguments", function () {

    function returnFirstArg(firstArg) {
      return firstArg;
    }

    expect(returnFirstArg("first", "second", "third")).toBe(FILL_ME_IN);

    function returnSecondArg(firstArg, secondArg) {
      return secondArg;
    }

    expect(returnSecondArg("only give first arg")).toBe(FILL_ME_IN);

    function returnAllArgs() {
      var argsArray = [];
      for (var i = 0; i < arguments.length; i += 1) {
        argsArray.push(arguments[i]);
      }
      return argsArray.join(",");
    }

    expect(returnAllArgs("first", "second", "third")).toBe(FILL_ME_IN);
  });

  it("should pass functions as values", function () {

    var appendRules = function (name) {
      return name + " rules!";
    };

    var appendDoubleRules = function (name) {
      return name + " totally rules!";
    };

    var praiseSinger = { givePraise: appendRules };
    expect(praiseSinger.givePraise("John")).toBe(FILL_ME_IN);

    praiseSinger.givePraise = appendDoubleRules;
    expect(praiseSinger.givePraise("Mary")).toBe(FILL_ME_IN);

  });

  it("should use function body as a string", function () {
    var add = new Function("a", "b", "return a + b;");
    expect(add(1, 2)).toBe(FILL_ME_IN);

    var multiply = function (a, b) {
      //An internal comment
      return a * b;
    };
    expect(multiply.toString()).toBe(FILL_ME_IN);
  });
});
<commit_msg>fix lexical scoping<commit_after>describe("About Functions", function() {

  it("should declare functions", function() {

    function add(a, b) {
      return a + b;
    }

    expect(add(1, 2)).toBe(3);
  });

  it("should know internal variables override outer variables", function () {
    var message = "Outer";

    function getMessage() {
      return message;
    }

    function overrideMessage() {
      var message = "Inner";
      return message;
    }

    expect(getMessage()).toBe('Outer');
    expect(overrideMessage()).toBe('Inner');
    expect(message).toBe('Outer');
  });

  it("should have lexical scoping", function () {
    var variable = "top-level";
    function parentfunction() {
        var variable = "local";
      function childfunction() {
          return variable;
      }
      return childfunction();
    }
    expect(parentfunction()).toBe('local');
  });

  it("should use lexical scoping to synthesise functions", function () {

    function makeIncreaseByFunction(increaseByAmount) {
      return function (numberToIncrease) {
        return numberToIncrease + increaseByAmount;
      };
    }

    var increaseBy3 = makeIncreaseByFunction(3);
    var increaseBy5 = makeIncreaseByFunction(5);

    expect(increaseBy3(10) + increaseBy5(10)).toBe(FILL_ME_IN);
  });

  it("should allow extra function arguments", function () {

    function returnFirstArg(firstArg) {
      return firstArg;
    }

    expect(returnFirstArg("first", "second", "third")).toBe(FILL_ME_IN);

    function returnSecondArg(firstArg, secondArg) {
      return secondArg;
    }

    expect(returnSecondArg("only give first arg")).toBe(FILL_ME_IN);

    function returnAllArgs() {
      var argsArray = [];
      for (var i = 0; i < arguments.length; i += 1) {
        argsArray.push(arguments[i]);
      }
      return argsArray.join(",");
    }

    expect(returnAllArgs("first", "second", "third")).toBe(FILL_ME_IN);
  });

  it("should pass functions as values", function () {

    var appendRules = function (name) {
      return name + " rules!";
    };

    var appendDoubleRules = function (name) {
      return name + " totally rules!";
    };

    var praiseSinger = { givePraise: appendRules };
    expect(praiseSinger.givePraise("John")).toBe(FILL_ME_IN);

    praiseSinger.givePraise = appendDoubleRules;
    expect(praiseSinger.givePraise("Mary")).toBe(FILL_ME_IN);

  });

  it("should use function body as a string", function () {
    var add = new Function("a", "b", "return a + b;");
    expect(add(1, 2)).toBe(FILL_ME_IN);

    var multiply = function (a, b) {
      //An internal comment
      return a * b;
    };
    expect(multiply.toString()).toBe(FILL_ME_IN);
  });
});
<|endoftext|>


<commit_before>var doc = require('./doc'),
    isList = require('./isList'),
    getTargets = require('./getTargets')(doc.document),
    flocProto = [];

function Floc(items){
    this.push.apply(this, items);
}
Floc.prototype = flocProto;
flocProto.constructor = Floc;

function floc(target){
    var instance = getTargets(target);

    if(!isList(instance)){
        if(instance){
            instance = [instance];
        }else{
            instance = [];
        }
    }
    return new Floc(instance);
}

for(var key in doc){
    if(typeof doc[key] === 'function'){
        floc[key] = doc[key];
        flocProto[key] = (function(key){
            // This is also extremely dodgy and fast
            return function(a,b,c,d,e,f){
                var result = doc[key](this, a,b,c,d,e,f);

                if(result !== doc && isList(result)){
                    return floc(result);
                }
                return result;
            };
        }(key));
    }
}
flocProto.on = function(events, target, callback){
    var proxy = this;
    if(typeof target === 'function'){
        callback = target;
        target = this;
        proxy = null;
    }
    doc.on(events, target, callback, proxy);
    return this;
};

flocProto.off = function(events, target, callback){
    var reference = this;
    if(typeof target === 'function'){
        callback = target;
        target = this;
        reference = null;
    }
    doc.off(events, target, callback, reference);
    return this;
};

module.exports = floc;<commit_msg>Fixed self-returning functions in fluent api<commit_after>var doc = require('./doc'),
    isList = require('./isList'),
    getTargets = require('./getTargets')(doc.document),
    flocProto = [];

function Floc(items){
    this.push.apply(this, items);
}
Floc.prototype = flocProto;
flocProto.constructor = Floc;

function floc(target){
    var instance = getTargets(target);

    if(!isList(instance)){
        if(instance){
            instance = [instance];
        }else{
            instance = [];
        }
    }
    return new Floc(instance);
}

var returnsSelf = 'addClass removeClass append prepend'.split(' ');

for(var key in doc){
    if(typeof doc[key] === 'function'){
        floc[key] = doc[key];
        flocProto[key] = (function(key){
            var instance = this;
            // This is also extremely dodgy and fast
            return function(a,b,c,d,e,f){
                var result = doc[key](this, a,b,c,d,e,f);

                if(result !== doc && isList(result)){
                    return floc(result);
                }
                if(returnsSelf.indexOf(key) >=0){
                    return instance;
                }
                return result;
            };
        }(key));
    }
}
flocProto.on = function(events, target, callback){
    var proxy = this;
    if(typeof target === 'function'){
        callback = target;
        target = this;
        proxy = null;
    }
    doc.on(events, target, callback, proxy);
    return this;
};

flocProto.off = function(events, target, callback){
    var reference = this;
    if(typeof target === 'function'){
        callback = target;
        target = this;
        reference = null;
    }
    doc.off(events, target, callback, reference);
    return this;
};

flocProto.addClass = function(className){
    doc.addClass(this, className);
    return this;
};

flocProto.removeClass = function(className){
    doc.removeClass(this, className);
    return this;
};

module.exports = floc;<|endoftext|>


<commit_before>"use strict";

require("ssl-root-cas").inject();

var request = require("superagent");

module.exports.handler = function (event, context, callback) {
  if(context.done === undefined) {
    console.log(arguments);
    return;
  }

  var banks;
  var assessments = [];
  var outstanding = 0;

  function attachToBank(bank, map) {
    console.log("attachToBank", bank.id, map);
    bank.assessments = map[bank.id] || [];
    console.log(bank.id, bank.assessments);
    for(var i in bank.childNodes) {
      attachToBank(bank.childNodes[i], map);
    }
  }

  function attachAssessments() {
    console.log("attachAssessments");
    var map = {};
    for(var i in assessments) {
      var assessment = assessments[i];
      map[assessment.bankId] = map[assessment.bankId] || [];
      map[assessment.bankId].push(assessment);
    }
    console.log(map);
    for(i in banks) {
      attachToBank(banks[i], map);
    }
  }

  /**
   * Fetches the resource at the `thing` subpath of QBank's API.  Calls function
   * `success` when the resource is received.  Keeps track of how many requests
   * are still waiting to be received; once all requests are finished, calls the
   * context's `succeed` function with the bank hierarchy as the return value.
   */
  function get(thing, success) {
    ++outstanding;
    console.log("Getting " + thing + ", " + outstanding + " requests");

    request.
      get("https://qbank-clix-dev.mit.edu/api/v1/assessment/" + thing).
      set("Accept", "application/json").
      then((response) => {
        console.log("Received", thing);
        success(response);
        // We need to decrement-and-check *after* we call the success function,
        // as that function may add more work to do.
        --outstanding;
        console.log(outstanding + " requests left");
        if(outstanding == 0) {
          console.log("Succeeding", banks, assessments);
          attachAssessments();
          context.succeed(banks);
        }
      }, function () {
        console.log("Failed to GET resource", thing, arguments);
        context.fail();
      });
  }

  /**
   * Gets the details for a single bank, such as title, description, etc.
   * Updates the bank in-place.
   */
  function getBankDetails(bank) {
    console.log("getBankDetails", bank.id);
    get("hierarchies/nodes/" + bank.id, (response) => {
      var details = JSON.parse(response.text);

      // The detailed object we get back contains a `childNodes` key with an
      // empty array value, which conflicts with the real `childNodes` value
      // already in the hierarchy.  We preserve the correct value by assigning
      // it to the newly-received object, *then* assign the new object's entries
      // to the original.

      details.childNodes = bank.childNodes;
      Object.assign(bank, details);
    });
  }

  /**
   * Given a hierarchy of banks with no details (title, etc.), recursively walks
   * the hiearchy, requesting details each bank.
   */
  function recursivelyGetBankDetails(bank) {
    for(var i in bank.childNodes) {
      var child = bank.childNodes[i];
      getBankDetails(child);
      recursivelyGetBankDetails(child);
    }
  }

  /**
   * Gets the hierarchy of banks appearing under the given root bank.  The
   * hierarchy includes only IDs, not details such as title.
   */
  function getChildren(bank) {
    console.log("getChildren", bank.id);
    get("hierarchies/nodes/" + bank.id + "/children?descendants=10", (response) => {
      console.log("inserting children...");
      bank.childNodes = JSON.parse(response.text);
      for(var i in bank.childNodes) {
        recursivelyGetBankDetails(bank.childNodes[i]);
      }
      console.log("done inserting children");
    });
  }

  function getAssessments(bank) {
    console.log("getAssessments", bank.id);
    get("banks/" + bank.id + "/assessments", (response) => {
      var arr = JSON.parse(response.text);
      console.log(arr);
      assessments = assessments.concat(arr);
    });
  }

  // Get the root banks and start filling in the hierarchy and details.
  get("hierarchies/roots", (response) => {
    console.log("Received roots");
    banks = JSON.parse(response.text);
    console.log("Parsed roots");
    for(var i in banks) {
      getChildren(banks[i]);
      getAssessments(banks[i]);
    }
    console.log("Requested children");
  });
};
<commit_msg>Removed logging<commit_after>"use strict";

require("ssl-root-cas").inject();

var request = require("superagent");

module.exports.handler = function (event, context, callback) {
  if(context.done === undefined) {
    console.log(arguments);
    return;
  }

  var banks;
  var assessments = [];
  var outstanding = 0;

  function attachToBank(bank, map) {
    bank.assessments = map[bank.id] || [];
    for(var i in bank.childNodes) {
      attachToBank(bank.childNodes[i], map);
    }
  }

  function attachAssessments() {
    var map = {};
    for(var i in assessments) {
      var assessment = assessments[i];
      map[assessment.bankId] = map[assessment.bankId] || [];
      map[assessment.bankId].push(assessment);
    }
    for(i in banks) {
      attachToBank(banks[i], map);
    }
  }

  /**
   * Fetches the resource at the `thing` subpath of QBank's API.  Calls function
   * `success` when the resource is received.  Keeps track of how many requests
   * are still waiting to be received; once all requests are finished, calls the
   * context's `succeed` function with the bank hierarchy as the return value.
   */
  function get(thing, success) {
    ++outstanding;
    console.log("Getting " + thing + ", " + outstanding + " requests");

    request.
      get("https://qbank-clix-dev.mit.edu/api/v1/assessment/" + thing).
      set("Accept", "application/json").
      then((response) => {
        console.log("Received", thing);
        success(response);
        // We need to decrement-and-check *after* we call the success function,
        // as that function may add more work to do.
        --outstanding;
        console.log(outstanding + " requests left");
        if(outstanding == 0) {
          console.log("Succeeding", banks, assessments);
          attachAssessments();
          context.succeed(banks);
        }
      }, function () {
        console.log("Failed to GET resource", thing, arguments);
        context.fail();
      });
  }

  /**
   * Gets the details for a single bank, such as title, description, etc.
   * Updates the bank in-place.
   */
  function getBankDetails(bank) {
    get("hierarchies/nodes/" + bank.id, (response) => {
      var details = JSON.parse(response.text);

      // The detailed object we get back contains a `childNodes` key with an
      // empty array value, which conflicts with the real `childNodes` value
      // already in the hierarchy.  We preserve the correct value by assigning
      // it to the newly-received object, *then* assign the new object's entries
      // to the original.

      details.childNodes = bank.childNodes;
      Object.assign(bank, details);
    });
  }

  /**
   * Given a hierarchy of banks with no details (title, etc.), recursively walks
   * the hiearchy, requesting details each bank.
   */
  function recursivelyGetBankDetails(bank) {
    for(var i in bank.childNodes) {
      var child = bank.childNodes[i];
      getBankDetails(child);
      recursivelyGetBankDetails(child);
    }
  }

  /**
   * Gets the hierarchy of banks appearing under the given root bank.  The
   * hierarchy includes only IDs, not details such as title.
   */
  function getChildren(bank) {
    get("hierarchies/nodes/" + bank.id + "/children?descendants=10", (response) => {
      bank.childNodes = JSON.parse(response.text);
      for(var i in bank.childNodes) {
        recursivelyGetBankDetails(bank.childNodes[i]);
      }
    });
  }

  function getAssessments(bank) {
    get("banks/" + bank.id + "/assessments", (response) => {
      var arr = JSON.parse(response.text);
      assessments = assessments.concat(arr);
    });
  }

  // Get the root banks and start filling in the hierarchy and details.
  get("hierarchies/roots", (response) => {
    banks = JSON.parse(response.text);
    for(var i in banks) {
      getChildren(banks[i]);
      getAssessments(banks[i]);
    }
  });
};
<|endoftext|>


<commit_before>
var path = require('path');
var fs = require('fs');

function unixifyPath(filepath) {
	if (process.platform === 'win32') {
		return filepath.replace(/\\/g, '/');
	} else {
		return filepath;
	}
};

function formatTwoDigists(number) {
	if (number < 10) {
		return '0' + number;
	} else {
		return number;
	}
}

function formatTimestamp(date) {
	var str = date.getFullYear();
	str += formatTwoDigists(date.getMonth() + 1);
	str += formatTwoDigists(date.getDate());
	str += formatTwoDigists(date.getHours());
	str += formatTwoDigists(date.getMinutes());
	str += formatTwoDigists(date.getSeconds());
	return str;
}

function optionalValue(value, defaultValue) {
	defaultValue = defaultValue || '-';
	return value ? value : defaultValue;
}

function formatField(label, attr, separator) {
	separator = separator || ': ';
	var str = '';

	if (attr) {
		str = label + separator + attr + '\n';
	}
	return str;
}

function formatLabeledList(label, list) {
	list = list || [];
	var str = '';

	for(var i in list) {
		str += formatField(label, list[i]);
	}
	return str;
}

function formatFileList(options) {
	var str = '';

	if (options.files && options.files.length > 0) {
		str += '\n%files\n';
		if (options.defaultFilemode || options.defaultUsername || options.defaultGroupname || options.defaultDirmode) {
			str += '%defattr('
				+ optionalValue(options.defaultFilemode) + ','
				+ optionalValue(options.defaultUsername) + ','
				+ optionalValue(options.defaultGroupname) + ','
				+ optionalValue(options.defaultDirmode) + ')\n';
		}
		for (var i in options.files) {
			var rpmFile = options.files[i];
//			if (!rpmFile.noRecursion) {
				if (rpmFile.filemode || rpmFile.username || rpmFile.groupname) {
					str += '%attr('
						+ optionalValue(rpmFile.filemode) + ','
						+ optionalValue(rpmFile.username) + ','
						+ optionalValue(rpmFile.groupname) + ') ';
				}
				str += '"' + unixifyPath(path.join(path.sep, rpmFile.dest, rpmFile.path)) + '"\n';
//			} else {
//				str += '%dir "' + unixifyPath(path.join(path.sep, rpmFile.dest + rpmFile.path)) + '"\n';
//			}
		}
	}

	return str;
}

function readScriptlet(label, scriptFile) {
	var src = '';
	if (scriptFile) {
		var options = {
			encoding: scriptFile.encoding || 'utf8'
		};
		var data = fs.readFileSync(scriptFile.src, options);
		src += label + '\n';
		src += data.trim() + '\n\n';
	}
	return src;
}

/**
 * Provides utility methods to execute a command
 * @module exec
 */
module.exports = function(options, callback) {
//	grunt.verbose.writeln('Writing SPEC basic section...');

	// FIXME the following macro definition should not be needed if the --define command line parameter is taken into account by rpmbuild
	var src = '%define   _topdir ' + path.join(process.cwd(), options.destination) + '\n\n';

	src += formatField('Name', options.name);
	src += formatField('Version', options.version);
	src += 'Release: ';
        if (options.release === true) {
                src += '1\n';
        } else if (options.release) {
                src += options.release + '\n';
	} else {
		src += 'SNAPSHOT' + formatTimestamp(new Date()) + '\n';
	}

	src += formatField('URL', options.homepage);
	src += formatField('Summary', options.summary);
	src += formatField('License', optionalValue(options.license, options.licenses && options.licenses[0] && options.licenses[0].type));
	src += formatField('Distribution', options.distribution);
	src += formatField('Vendor', options.vendor);
	src += formatField('Group', options.group);
	src += formatField('Provides', options.provides);
	src += formatLabeledList('Requires', options.requires);
	src += formatField('autoprov', 'yes');
	src += formatField('autoreq', 'yes');
	src += formatField('\n%description', options.description, '\n');

//	grunt.verbose.writeln('Writing SPEC files section...');
	src += formatFileList(options);

//	grunt.verbose.writeln('Writing SPEC scriptlet section...');
	src += readScriptlet('\n%pretrans', options.preTransaction);
	src += readScriptlet('\n%pre', options.preInstall);
	src += readScriptlet('\n%post', options.postInstall);
	src += readScriptlet('\n%triggerin', options.triggerInstall);
	src += readScriptlet('\n%triggerun', options.triggerUninstall);
	src += readScriptlet('\n%preun', options.preUninstall);
	src += readScriptlet('\n%postun', options.postUninstall);
	src += readScriptlet('\n%triggerpostun', options.triggerPostUninstall);
	src += readScriptlet('\n%posttrans', options.postTransaction);

	fs.writeFile(options.specFilepath, src, callback);
};
<commit_msg>Use default options for autoprov and autoreq<commit_after>
var path = require('path');
var fs = require('fs');

function unixifyPath(filepath) {
	if (process.platform === 'win32') {
		return filepath.replace(/\\/g, '/');
	} else {
		return filepath;
	}
};

function formatTwoDigists(number) {
	if (number < 10) {
		return '0' + number;
	} else {
		return number;
	}
}

function formatTimestamp(date) {
	var str = date.getFullYear();
	str += formatTwoDigists(date.getMonth() + 1);
	str += formatTwoDigists(date.getDate());
	str += formatTwoDigists(date.getHours());
	str += formatTwoDigists(date.getMinutes());
	str += formatTwoDigists(date.getSeconds());
	return str;
}

function optionalValue(value, defaultValue) {
	defaultValue = defaultValue || '-';
	return value ? value : defaultValue;
}

function formatField(label, attr, separator) {
	separator = separator || ': ';
	var str = '';

	if (attr) {
		str = label + separator + attr + '\n';
	}
	return str;
}

function formatLabeledList(label, list) {
	list = list || [];
	var str = '';

	for(var i in list) {
		str += formatField(label, list[i]);
	}
	return str;
}

function formatFileList(options) {
	var str = '';

	if (options.files && options.files.length > 0) {
		str += '\n%files\n';
		if (options.defaultFilemode || options.defaultUsername || options.defaultGroupname || options.defaultDirmode) {
			str += '%defattr('
				+ optionalValue(options.defaultFilemode) + ','
				+ optionalValue(options.defaultUsername) + ','
				+ optionalValue(options.defaultGroupname) + ','
				+ optionalValue(options.defaultDirmode) + ')\n';
		}
		for (var i in options.files) {
			var rpmFile = options.files[i];
//			if (!rpmFile.noRecursion) {
				if (rpmFile.filemode || rpmFile.username || rpmFile.groupname) {
					str += '%attr('
						+ optionalValue(rpmFile.filemode) + ','
						+ optionalValue(rpmFile.username) + ','
						+ optionalValue(rpmFile.groupname) + ') ';
				}
				str += '"' + unixifyPath(path.join(path.sep, rpmFile.dest, rpmFile.path)) + '"\n';
//			} else {
//				str += '%dir "' + unixifyPath(path.join(path.sep, rpmFile.dest + rpmFile.path)) + '"\n';
//			}
		}
	}

	return str;
}

function readScriptlet(label, scriptFile) {
	var src = '';
	if (scriptFile) {
		var options = {
			encoding: scriptFile.encoding || 'utf8'
		};
		var data = fs.readFileSync(scriptFile.src, options);
		src += label + '\n';
		src += data.trim() + '\n\n';
	}
	return src;
}

/**
 * Provides utility methods to execute a command
 * @module exec
 */
module.exports = function(options, callback) {
//	grunt.verbose.writeln('Writing SPEC basic section...');

	// FIXME the following macro definition should not be needed if the --define command line parameter is taken into account by rpmbuild
	var src = '%define   _topdir ' + path.join(process.cwd(), options.destination) + '\n\n';

	src += formatField('Name', options.name);
	src += formatField('Version', options.version);
	src += 'Release: ';
        if (options.release === true) {
                src += '1\n';
        } else if (options.release) {
                src += options.release + '\n';
	} else {
		src += 'SNAPSHOT' + formatTimestamp(new Date()) + '\n';
	}

	src += formatField('URL', options.homepage);
	src += formatField('Summary', options.summary);
	src += formatField('License', optionalValue(options.license, options.licenses && options.licenses[0] && options.licenses[0].type));
	src += formatField('Distribution', options.distribution);
	src += formatField('Vendor', options.vendor);
	src += formatField('Group', options.group);
	src += formatField('Provides', options.provides);
	src += formatLabeledList('Requires', options.requires);
	src += formatField('autoprov', options.autoprov);
	src += formatField('autoreq', options.autoreq);
	src += formatField('\n%description', options.description, '\n');

//	grunt.verbose.writeln('Writing SPEC files section...');
	src += formatFileList(options);

//	grunt.verbose.writeln('Writing SPEC scriptlet section...');
	src += readScriptlet('\n%pretrans', options.preTransaction);
	src += readScriptlet('\n%pre', options.preInstall);
	src += readScriptlet('\n%post', options.postInstall);
	src += readScriptlet('\n%triggerin', options.triggerInstall);
	src += readScriptlet('\n%triggerun', options.triggerUninstall);
	src += readScriptlet('\n%preun', options.preUninstall);
	src += readScriptlet('\n%postun', options.postUninstall);
	src += readScriptlet('\n%triggerpostun', options.triggerPostUninstall);
	src += readScriptlet('\n%posttrans', options.postTransaction);

	fs.writeFile(options.specFilepath, src, callback);
};
<|endoftext|>