<commit_before>//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Animated page change core logic and sequence handlers
//>>label: Transition Core
//>>group: Transitions
//>>css.structure: ../css/structure/jquery.mobile.transition.css
//>>css.theme: ../css/themes/default/jquery.mobile.theme.css

define( [ "jquery", "./jquery.mobile.core" ], function( jQuery ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, window, undefined ) {

	$.mobile.TransitionHandler = function( sequential ) {
		// Default to sequential
		if ( sequential === undefined ) {
			sequential = true;
		}

		this.sequential = sequential;
	};

	$.extend($.mobile.TransitionHandler.prototype, {
		cleanFrom: function( $from, name ) {
			$from
				.removeClass( $.mobile.activePageClass + " out in reverse " + name )
				.height( "" );
		},

		doneIn: function( $from, $to, name, reverse, toScroll, deferred ) {
				if ( !this.sequential ) {

					if ( $from ) {
						this.cleanFrom( $from, name );
					}
				}

				$to.removeClass( "out in reverse " + name ).height( "" );

				this.toggleViewportClass( name );

				// In some browsers (iOS5), 3D transitions block the ability to scroll to the desired location during transition
				// This ensures we jump to that spot after the fact, if we aren't there already.
				if ( $.mobile.window.scrollTop() !== toScroll ) {
					this.scrollPage( toScroll );
				}

			deferred.resolve( name, reverse, $to, $from, true );
		},

		doneOut: function( $from, $to, name, reverse, toScroll, deferred, toPreClass, screenHeight, reverseClass, none ) {

			if ( $from && this.sequential ) {
				this.cleanFrom( $from, name );
			}

			this.startIn( $from, $to, name, reverse, toScroll, deferred, toPreClass, screenHeight, reverseClass, none );
		},

		scrollPage: function( toScroll ) {
			// By using scrollTo instead of silentScroll, we can keep things better in order
			// Just to be precautios, disable scrollstart listening like silentScroll would
			$.event.special.scrollstart.enabled = false;

			window.scrollTo( 0, toScroll );

			// reenable scrollstart listening like silentScroll would
			setTimeout( function() {
				$.event.special.scrollstart.enabled = true;
			}, 150 );
		},

		startIn: function( $from, $to, name, reverse, toScroll, deferred, toPreClass, screenHeight, reverseClass, none ) {

			// Prevent flickering in phonegap container: see comments at #4024 regarding iOS
			$to.css( "z-index", -10 );

			$to.addClass( $.mobile.activePageClass + toPreClass );

			// Send focus to page as it is now display: block
			$.mobile.focusPage( $to );

			// Set to page height
			$to.height( screenHeight + toScroll );

			this.scrollPage( toScroll );

			// Restores visibility of the new page: added together with $to.css( "z-index", -10 );
			$to.css( "z-index", "" );

			if ( !none ) {
				$to.animationComplete( $.proxy(function() {
					this.doneIn( $from, $to, name, reverse, toScroll, deferred );
				}, this));
			}

			$to
				.removeClass( toPreClass )
				.addClass( name + " in" + reverseClass );

			if ( none ) {
				this.doneIn( $from, $to, name, reverse, toScroll, deferred );
			}

		},

		toggleViewportClass: function( name ) {
				$.mobile.pageContainer.toggleClass( "ui-mobile-viewport-transitioning viewport-" + name );
		},

		transition: function( name, reverse, $to, $from ) {
			// TODO temporary
			var self = this;

			var deferred = new $.Deferred(),
				reverseClass = reverse ? " reverse" : "",
				active	= $.mobile.urlHistory.getActive(),
				toScroll = active.lastScroll || $.mobile.defaultHomeScroll,
				screenHeight = $.mobile.getScreenHeight(),
				maxTransitionOverride = $.mobile.maxTransitionWidth !== false && $.mobile.window.width() > $.mobile.maxTransitionWidth,
				none = !$.support.cssTransitions || maxTransitionOverride || !name || name === "none" || Math.max( $.mobile.window.scrollTop(), toScroll ) > $.mobile.getMaxScrollForTransition(),
				toPreClass = " ui-page-pre-in";

            var startOut = function() {
                // if it's not sequential, call the doneOut transition to start the TO page animating in simultaneously
                if ( !self.sequential ) {
                    self.doneOut($from, $to, name, reverse, toScroll, deferred, toPreClass, screenHeight, reverseClass, none );
                }
                else {
                    $from.animationComplete(function() {
						self.doneOut( $from, $to, name, reverse, toScroll, deferred, toPreClass, screenHeight, reverseClass, none );
					});
                }

                // Set the from page's height and start it transitioning out
                // Note: setting an explicit height helps eliminate tiling in the transitions
                $from
                    .height( screenHeight + $.mobile.window.scrollTop() )
                    .addClass( name + " out" + reverseClass );
            };

			self.toggleViewportClass( name );

			if ( $from && !none ) {
				startOut();
			} else {
				self.doneOut( $from, $to, name, reverse, toScroll, deferred, toPreClass, screenHeight, reverseClass, none );
			}

			return deferred.promise();
		}
	});

// generate the handlers from the above
var sequentialHandler = new $.mobile.TransitionHandler(),
	simultaneousHandler = new $.mobile.TransitionHandler( false ),
	defaultGetMaxScrollForTransition = function() {
		return $.mobile.getScreenHeight() * 3;
	};

// Make our transition handler the public default.
$.mobile.defaultTransitionHandler = sequentialHandler;

//transition handler dictionary for 3rd party transitions
$.mobile.transitionHandlers = {
	"default": $.mobile.defaultTransitionHandler,
	"sequential": sequentialHandler,
	"simultaneous": simultaneousHandler
};

$.mobile.transitionFallbacks = {};

// If transition is defined, check if css 3D transforms are supported, and if not, if a fallback is specified
$.mobile._maybeDegradeTransition = function( transition ) {
		if ( transition && !$.support.cssTransform3d && $.mobile.transitionFallbacks[ transition ] ) {
			transition = $.mobile.transitionFallbacks[ transition ];
		}

		return transition;
};

// Set the getMaxScrollForTransition to default if no implementation was set by user
$.mobile.getMaxScrollForTransition = $.mobile.getMaxScrollForTransition || defaultGetMaxScrollForTransition;
})( jQuery, this );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
<commit_msg>extract startOut<commit_after>//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Animated page change core logic and sequence handlers
//>>label: Transition Core
//>>group: Transitions
//>>css.structure: ../css/structure/jquery.mobile.transition.css
//>>css.theme: ../css/themes/default/jquery.mobile.theme.css

define( [ "jquery", "./jquery.mobile.core" ], function( jQuery ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, window, undefined ) {

	$.mobile.TransitionHandler = function( sequential ) {
		// Default to sequential
		if ( sequential === undefined ) {
			sequential = true;
		}

		this.sequential = sequential;
	};

	$.extend($.mobile.TransitionHandler.prototype, {
		cleanFrom: function( $from, name ) {
			$from
				.removeClass( $.mobile.activePageClass + " out in reverse " + name )
				.height( "" );
		},

		doneIn: function( $from, $to, name, reverse, toScroll, deferred ) {
				if ( !this.sequential ) {

					if ( $from ) {
						this.cleanFrom( $from, name );
					}
				}

				$to.removeClass( "out in reverse " + name ).height( "" );

				this.toggleViewportClass( name );

				// In some browsers (iOS5), 3D transitions block the ability to scroll to the desired location during transition
				// This ensures we jump to that spot after the fact, if we aren't there already.
				if ( $.mobile.window.scrollTop() !== toScroll ) {
					this.scrollPage( toScroll );
				}

			deferred.resolve( name, reverse, $to, $from, true );
		},

		doneOut: function( $from, $to, name, reverse, toScroll, deferred, toPreClass, screenHeight, reverseClass, none ) {

			if ( $from && this.sequential ) {
				this.cleanFrom( $from, name );
			}

			this.startIn( $from, $to, name, reverse, toScroll, deferred, toPreClass, screenHeight, reverseClass, none );
		},

		scrollPage: function( toScroll ) {
			// By using scrollTo instead of silentScroll, we can keep things better in order
			// Just to be precautios, disable scrollstart listening like silentScroll would
			$.event.special.scrollstart.enabled = false;

			window.scrollTo( 0, toScroll );

			// reenable scrollstart listening like silentScroll would
			setTimeout( function() {
				$.event.special.scrollstart.enabled = true;
			}, 150 );
		},

		startIn: function( $from, $to, name, reverse, toScroll, deferred, toPreClass, screenHeight, reverseClass, none ) {

			// Prevent flickering in phonegap container: see comments at #4024 regarding iOS
			$to.css( "z-index", -10 );

			$to.addClass( $.mobile.activePageClass + toPreClass );

			// Send focus to page as it is now display: block
			$.mobile.focusPage( $to );

			// Set to page height
			$to.height( screenHeight + toScroll );

			this.scrollPage( toScroll );

			// Restores visibility of the new page: added together with $to.css( "z-index", -10 );
			$to.css( "z-index", "" );

			if ( !none ) {
				$to.animationComplete( $.proxy(function() {
					this.doneIn( $from, $to, name, reverse, toScroll, deferred );
				}, this));
			}

			$to
				.removeClass( toPreClass )
				.addClass( name + " in" + reverseClass );

			if ( none ) {
				this.doneIn( $from, $to, name, reverse, toScroll, deferred );
			}

		},

		startOut: function( $from, $to, name, reverse, toScroll, deferred, toPreClass, screenHeight, reverseClass, none ) {
            // if it's not sequential, call the doneOut transition to start the TO page animating in simultaneously
            if ( !this.sequential ) {
                this.doneOut( $from, $to, name, reverse, toScroll, deferred, toPreClass, screenHeight, reverseClass, none );
            } else {
                $from.animationComplete($.proxy(function() {
					this.doneOut( $from, $to, name, reverse, toScroll, deferred, toPreClass, screenHeight, reverseClass, none );
				}, this));
            }

            // Set the from page's height and start it transitioning out
            // Note: setting an explicit height helps eliminate tiling in the transitions
            $from
                .height( screenHeight + $.mobile.window.scrollTop() )
                .addClass( name + " out" + reverseClass );
        },

		toggleViewportClass: function( name ) {
				$.mobile.pageContainer.toggleClass( "ui-mobile-viewport-transitioning viewport-" + name );
		},

		transition: function( name, reverse, $to, $from ) {
			// TODO temporary
			var self = this;

			var deferred = new $.Deferred(),
				reverseClass = reverse ? " reverse" : "",
				active	= $.mobile.urlHistory.getActive(),
				toScroll = active.lastScroll || $.mobile.defaultHomeScroll,
				screenHeight = $.mobile.getScreenHeight(),
				maxTransitionOverride = $.mobile.maxTransitionWidth !== false && $.mobile.window.width() > $.mobile.maxTransitionWidth,
				none = !$.support.cssTransitions || maxTransitionOverride || !name || name === "none" || Math.max( $.mobile.window.scrollTop(), toScroll ) > $.mobile.getMaxScrollForTransition(),
				toPreClass = " ui-page-pre-in";

			self.toggleViewportClass( name );

			if ( $from && !none ) {
				self.startOut( $from, $to, name, reverse, toScroll, deferred, toPreClass, screenHeight, reverseClass, none );
			} else {
				self.doneOut( $from, $to, name, reverse, toScroll, deferred, toPreClass, screenHeight, reverseClass, none );
			}

			return deferred.promise();
		}
	});

// generate the handlers from the above
var sequentialHandler = new $.mobile.TransitionHandler(),
	simultaneousHandler = new $.mobile.TransitionHandler( false ),
	defaultGetMaxScrollForTransition = function() {
		return $.mobile.getScreenHeight() * 3;
	};

// Make our transition handler the public default.
$.mobile.defaultTransitionHandler = sequentialHandler;

//transition handler dictionary for 3rd party transitions
$.mobile.transitionHandlers = {
	"default": $.mobile.defaultTransitionHandler,
	"sequential": sequentialHandler,
	"simultaneous": simultaneousHandler
};

$.mobile.transitionFallbacks = {};

// If transition is defined, check if css 3D transforms are supported, and if not, if a fallback is specified
$.mobile._maybeDegradeTransition = function( transition ) {
		if ( transition && !$.support.cssTransform3d && $.mobile.transitionFallbacks[ transition ] ) {
			transition = $.mobile.transitionFallbacks[ transition ];
		}

		return transition;
};

// Set the getMaxScrollForTransition to default if no implementation was set by user
$.mobile.getMaxScrollForTransition = $.mobile.getMaxScrollForTransition || defaultGetMaxScrollForTransition;
})( jQuery, this );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
<|endoftext|>


<commit_before>var oPolls = [{
    "_id": "1",
    "group": "VoteIt team",
    "category": "ion-beer",
    "question": "Should we limit the radius ?",
    "choices": [{
        "text": "Yes",
        "userIds": [

        ],
        "votes": 5
    }, {
        "text": "No",
        "userIds": [

        ],
        "votes": 2
    }, {
        "text": "Just for the demo",
        "userIds": [

        ],
        "votes": 2
    }],
    "center": {
        "lat": '80.96441261702967',
        "lng": '39.814570672728664'
    },
    "radius": 500,
    "timeout": null,
    "active": true,
    "totalVotes": 9
}, {
    "_id": "2",
    "group": "VoteIt team",
    "category": "ion-beer",
    "question": "UI Theme, Red or Green ?",
    "choices": [{
        "text": "Red",
        "userIds": [

        ],
        "votes": 4
    }, {
        "text": "Green",
        "userIds": [

        ],
        "votes": 1
    }, {
        "text": "Other Color",
        "userIds": [

        ],
        "votes": 3
    }],
    "center": {
        "lat": null,
        "lng": null
    },
    "radius": 500,
    "timeout": null,
    "active": false,
    "totalVotes": 8,
    "selected": "Red"
}, {
    "_id": "3",
    "group": "VoteIt team",
    "category": "ion-beer",
    "question": "Android or IOS ?",
    "choices": [{
        "text": "Android",
        "userIds": [

        ],
        "votes": 14
    }, {
        "text": "IOS",
        "userIds": [

        ],
        "votes": 15
    }, {
        "text": "Phonegap",
        "userIds": [

        ],
        "votes": 23
    }],
    "center": {
        "lat": null,
        "lng": null
    },
    "radius": 500,
    "timeout": null,
    "totalVotes": 52,
    "selected": "Phonegap"
}, {
    "_id": "4",
    "group": "Ninja Coders",
    "category": "ion-social-tux",
    "question": "Which framework is the best",
    "choices": [{
        "text": "AngularJs",
        "userIds": [],
        "votes": 23
    }, {
        "text": "Ember",
        "userIds": [],
        "votes": 22
    }, {
        "text": "Backbone",
        "userIds": [],
        "votes": 67
    }],
    "center": {
        "lat": null,
        "lng": null
    },
    "radius": 500,
    "timeout": null,
    "active": false,
    "totalVotes": 112,
    "selected": "AngularJs"
}, {
    "_id": "5",
    "group": "Mobility Inovation",
    "category": "ion-speakerphone",
    "question": "Who should win the Proximithon ?",
    "choices": [{
        "text": "Vote It !",
        "userIds": [

        ],
        "votes": 64
    }, {
        "text": "Other team",
        "userIds": [

        ],
        "votes": 0
    }],
    "center": {
        "lat": null,
        "lng": null
    },
    "radius": 500,
    "timeout": null,
    "active": false,
    "totalVotes": 64
}];<commit_msg>asdfaf<commit_after>var oPolls = [{
    "_id": "1",
    "group": "VoteIt team",
    "category": "ion-beer",
    "question": "Should we limit the radius ?",
    "choices": [{
        "text": "Yes",
        "userIds": [

        ],
        "votes": 5
    }, {
        "text": "No",
        "userIds": [

        ],
        "votes": 2
    }, {
        "text": "Just for the demo",
        "userIds": [

        ],
        "votes": 2
    }],
    "center": {
        "lat": '80.96441261702967',
        "lng": '39.814570672728664'
    },
    "radius": 500,
    "timeout": null,
    "active": true,
    "totalVotes": 9
}, {
    "_id": "2",
    "group": "VoteIt team",
    "category": "ion-beer",
    "question": "UI Theme, Red or Green ?",
    "choices": [{
        "text": "Red",
        "userIds": [

        ],
        "votes": 4
    }, {
        "text": "Green",
        "userIds": [

        ],
        "votes": 1
    }, {
        "text": "Other Color",
        "userIds": [

        ],
        "votes": 3
    }],
    "center": {
        "lat": null,
        "lng": null
    },
    "radius": 500,
    "timeout": null,
    "active": false,
    "totalVotes": 8,
    "selected": "Red"
}, {
    "_id": "3",
    "group": "VoteIt team",
    "category": "ion-beer",
    "question": "Android or IOS ?",
    "choices": [{
        "text": "Android",
        "userIds": [

        ],
        "votes": 14
    }, {
        "text": "IOS",
        "userIds": [

        ],
        "votes": 15
    }, {
        "text": "Phonegap",
        "userIds": [

        ],
        "votes": 23
    }],
    "center": {
        "lat": null,
        "lng": null
    },
    "radius": 500,
    "timeout": null,
    "totalVotes": 52,
    "selected": "Phonegap"
}, {
    "_id": "4",
    "group": "Ninja Coders",
    "category": "ion-social-tux",
    "question": "Which framework is the best",
    "choices": [{
        "text": "AngularJs",
        "userIds": [],
        "votes": 23
    }, {
        "text": "Ember",
        "userIds": [],
        "votes": 22
    }, {
        "text": "Backbone",
        "userIds": [],
        "votes": 67
    }],
    "center": {
        "lat": null,
        "lng": null
    },
    "radius": 500,
    "timeout": null,
    "active": false,
    "totalVotes": 112,
    "selected": "AngularJs"
}, {
    "_id": "5",
    "group": "Mobility Inovation",
    "category": "ion-speakerphone",
    "question": "Who should win the Proximithon ?",
    "choices": [{
        "text": "Vote It !",
        "userIds": [

        ],
        "votes": 64
    }, {
        "text": "Other team",
        "userIds": [

        ],
        "votes": 0
    }],
    "center": {
        "lat": null,
        "lng": null
    },
    "radius": 500,
    "timeout": null,
    "active": false,
    "totalVotes": 64
}, {
    "_id": "6",
    "group": "My friends",
    "category": "ion-speakerphone",
    "question": "Who is your favorite super-hero?",
    "choices": [{
        "text": "Superman",
        "userIds": [

        ],
        "votes": 5
    }, {
        "text": "Batman",
        "userIds": [

        ],
        "votes": 2
    }, {
        "text": "Spider-Man",
        "userIds": [

        ],
        "votes": 3
    }, {
        "text": "Wolverine",
        "userIds": [

        ],
        "votes": 10
    }],
    "center": {
        "lat": null,
        "lng": null
    },
    "radius": 500,
    "timeout": null,
    "active": false,
    "totalVotes": 20
}, {
    "_id": "7",
    "group": "Mobility Inovation",
    "category": "ion-speakerphone",
    "question": "Where do u want to eat lunch?",
    "choices": [{
        "text": "Motorola",
        "userIds": [

        ],
        "votes": 5
    }, {
        "text": "AudioCodes",
        "userIds": [

        ],
        "votes": 2
    }, {
        "text": "Food Court ",
        "userIds": [

        ],
        "votes": 3
    }, {
        "text": "Order Take-Away",
        "userIds": [

        ],
        "votes": 10
    }],
    "center": {
        "lat": null,
        "lng": null
    },
    "radius": 500,
    "timeout": null,
    "active": false,
    "totalVotes": 20
}];<|endoftext|>


<commit_before>import MatomoTracker from '@datapunt/matomo-tracker-js'
import { getEnvironment } from '../../../shared/environment'
// eslint-disable-next-line import/no-cycle
import trackEvents from './trackEvents'
// eslint-disable-next-line import/no-cycle
import trackViews from './trackViews'
import { authCustomDimensions, viewCustomDimensions } from './customDimensions'
import { MATOMO_CONFIG } from './constants'

// Execute Matomo actions
const matomoMiddleware = ({ getState }) => next => action => {
  const nextAction = action

  // Initialize connection with Matomo
  const MatomoInstance = new MatomoTracker({
    urlBase: 'https://analytics.data.amsterdam.nl/',
    siteId: MATOMO_CONFIG[getEnvironment(window.location.hostname)].SITE_ID,
  })

  const actionsToMatomo = []
  if (trackViews[action.type]) {
    actionsToMatomo.push(trackViews[action.type])
  }
  if (trackEvents[action.type]) {
    actionsToMatomo.push(trackEvents[action.type])
  }

  if (actionsToMatomo.length) {
    const { firstAction, location, query, tracking } = action.meta || {}
    const state = getState()

    const { href } = window.location
    const { title } = window.document

    if (tracking || location) {
      const customDimensions = [
        ...authCustomDimensions(state),
        ...viewCustomDimensions(query, state),
      ]

      actionsToMatomo.forEach(matomoAction => {
        MatomoInstance.track({
          data: matomoAction({
            tracking,
            firstAction,
            query,
            state,
            title,
            href,
          }),
          href,
          title,
          customDimensions,
        })
      })
    }
  }
  next(nextAction)
}

export default matomoMiddleware
<commit_msg>Use baseurl from config<commit_after>import MatomoTracker from '@datapunt/matomo-tracker-js'
import { getEnvironment } from '../../../shared/environment'
// eslint-disable-next-line import/no-cycle
import trackEvents from './trackEvents'
// eslint-disable-next-line import/no-cycle
import trackViews from './trackViews'
import { authCustomDimensions, viewCustomDimensions } from './customDimensions'
import { MATOMO_CONFIG } from './constants'

// Execute Matomo actions
const matomoMiddleware = ({ getState }) => next => action => {
  const nextAction = action

  // Initialize connection with Matomo
  const MatomoInstance = new MatomoTracker({
    urlBase: MATOMO_CONFIG.BASE_URL,
    siteId: MATOMO_CONFIG[getEnvironment(window.location.hostname)].SITE_ID,
  })

  const actionsToMatomo = []
  if (trackViews[action.type]) {
    actionsToMatomo.push(trackViews[action.type])
  }
  if (trackEvents[action.type]) {
    actionsToMatomo.push(trackEvents[action.type])
  }

  if (actionsToMatomo.length) {
    const { firstAction, location, query, tracking } = action.meta || {}
    const state = getState()

    const { href } = window.location
    const { title } = window.document

    if (tracking || location) {
      const customDimensions = [
        ...authCustomDimensions(state),
        ...viewCustomDimensions(query, state),
      ]

      actionsToMatomo.forEach(matomoAction => {
        MatomoInstance.track({
          data: matomoAction({
            tracking,
            firstAction,
            query,
            state,
            title,
            href,
          }),
          href,
          title,
          customDimensions,
        })
      })
    }
  }
  next(nextAction)
}

export default matomoMiddleware
<|endoftext|>


<commit_before>// @flow

import os from 'os';
import path from 'path';
import { green } from 'chalk';
import { sshConnect, sshExec } from '../util/ssh';
import { fileExists, unlink } from '../util/fs';
import { printErrors } from '../printErrors';

import typeof Yargs from 'yargs';
import type { BaseArgs } from '.';

export const command = 'logout';
export const description =
  'Invalidate the authentication token in $HOME/.lagoon-token and delete the file';

export function builder(yargs: Yargs) {
  return yargs.usage(`$0 ${command} - ${description}`).options({
    identity: {
      describe: 'Path to identity (private key)',
      type: 'string',
      alias: 'i',
    },
  });
}

type Args = BaseArgs & {
  argv: {
    identity: string,
  },
};

export async function handler({ clog, cerr, argv }: Args): Promise<number> {
  if (argv.identity != null && !await fileExists(argv.identity)) {
    return printErrors(cerr, 'File does not exist at identity option path!');
  }

  let connection;

  try {
    connection = await sshConnect({
      identity: argv.identity,
    });
  } catch (err) {
    return printErrors(cerr, err);
  }

  await sshExec(connection, 'logout');
  const tokenFilePath = path.join(os.homedir(), '.lagoon-token');
  if (await fileExists(tokenFilePath)) {
    await unlink(tokenFilePath);
  }

  clog(green('Logged out successfully.'));

  // Be responsible and close the connection after our transaction.
  connection.end();

  return 0;
}
<commit_msg>Don't connect to auth server in logout<commit_after>// @flow

import os from 'os';
import path from 'path';
import { green } from 'chalk';
import { sshConnect, sshExec } from '../util/ssh';
import { fileExists, unlink } from '../util/fs';
import { printErrors } from '../printErrors';

import typeof Yargs from 'yargs';
import type { BaseArgs } from '.';

export const command = 'logout';
export const description =
  'Delete the authentication token in $HOME/.lagoon-token';

export function builder(yargs: Yargs) {
  return yargs.usage(`$0 ${command} - ${description}`);
}

export async function handler({ clog }: BaseArgs): Promise<number> {
  const tokenFilePath = path.join(os.homedir(), '.lagoon-token');
  if (await fileExists(tokenFilePath)) {
    await unlink(tokenFilePath);
  }

  clog(green('Logged out successfully.'));

  return 0;
}
<|endoftext|>


<commit_before>var webpack = require('webpack')
var autoprefixer = require('autoprefixer')
var CompressionPlugin = require('compression-webpack-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var env = process.env.NODE_ENV
var isProduction = env === 'production'
console.log('Building for ' + env + '...')

var commonPlugins = [
  new webpack.DefinePlugin({
    'process.env': {
      BROWSER: JSON.stringify(true),
      NODE_ENV: JSON.stringify(env)
    }
  }),
  new ExtractTextPlugin('bundle.css', { allChunks: true })
]
var productionPlugins = [
  new webpack.optimize.OccurenceOrderPlugin(),
  new webpack.optimize.DedupePlugin(),
  new webpack.optimize.UglifyJsPlugin({
    compress: { warnings: false }
  }),
  new CompressionPlugin({
    asset: '[path].gz[query]',
    algorithm: 'gzip',
    test: /\.js$|\.html|\.css$/,
    threshold: 256
  })
]

module.exports = {
  devtool: isProduction ? 'cheap-module-source-map' : 'eval',
  entry: [
    '/www/src/client.js'
  ],
  output: {
    path: '/www/static',
    filename: 'bundle.js'
  },
  watchOptions: {
    poll: true // needed for watching in docker
  },
  plugins: isProduction
    ? commonPlugins.concat(productionPlugins)
    : commonPlugins,
  resolve: {
    extensions: ['', '.js']
  },
  postcss: [ autoprefixer({ browsers: ['last 2 versions'] }) ],
  module: {
    loaders: [
      {
        test: /\.js$/,
        loaders: ['babel'],
        exclude: /node_modules/
      },
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract('style', 'css', 'postcss')
      }
    ]
  }
}
<commit_msg>WWW: Remove comments from bundle.js<commit_after>var webpack = require('webpack')
var autoprefixer = require('autoprefixer')
var CompressionPlugin = require('compression-webpack-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var env = process.env.NODE_ENV
var isProduction = env === 'production'
console.log('Building for ' + env + '...')

var commonPlugins = [
  new webpack.DefinePlugin({
    'process.env': {
      BROWSER: JSON.stringify(true),
      NODE_ENV: JSON.stringify(env)
    }
  }),
  new ExtractTextPlugin('bundle.css', { allChunks: true })
]
var productionPlugins = [
  new webpack.optimize.OccurenceOrderPlugin(),
  new webpack.optimize.DedupePlugin(),
  new webpack.optimize.UglifyJsPlugin({
    comments: false,
    compress: {
      warnings: false
    }
  }),
  new CompressionPlugin({
    asset: '[path].gz[query]',
    algorithm: 'gzip',
    test: /\.js$|\.html|\.css$/,
    threshold: 256
  })
]

module.exports = {
  devtool: isProduction ? 'cheap-module-source-map' : 'eval',
  entry: {
    bundle: '/www/src/client.js'
  },
  output: {
    path: '/www/static',
    filename: 'bundle.js'
  },
  watchOptions: {
    poll: true // needed for watching in docker
  },
  plugins: isProduction
    ? commonPlugins.concat(productionPlugins)
    : commonPlugins,
  resolve: {
    extensions: ['', '.js']
  },
  postcss: [ autoprefixer({ browsers: ['last 2 versions'] }) ],
  module: {
    loaders: [
      {
        test: /\.js$/,
        loaders: ['babel'],
        exclude: /node_modules/
      },
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract('style', 'css', 'postcss')
      }
    ]
  }
}
<|endoftext|>


<commit_before>var FT=FT||{};
FT.Adapters=FT.Adapters||{};
FT.Adapters.Prototype = {

  // Load
  loaded: function(callback) {
    document.observe('dom:loaded', callback);
  },

  // Attributes
  attr: function(element, name, value) {
    if(value) {
      $(element).writeAttribute(name, value);
    } else {
      return $(element).readAttribute(name);
    }
  },
  css: function(element, css) {
    $(element).setStyle(css);
  },
  addClass: function(element, class_name) {
    $(element).addClassName(class_name);
  },
  hasClass: function(element, class_name) {
    return $(element).hasClassName(class_name);
  },
  removeClass: function(element, class_name) {
    $(element).removeClassName(class_name);
  },
  text: function(element) {
    return element.innerText;
  },

  // Selection/Traversal
  find_by_id: function(id) {
    return $(id);
  },
  find: function(parent_or_selector, selector) {
    return (selector ? $(parent_or_selector).select(selector) : $$(parent_or_selector))||[];
  },
  match: function(element, selector) {
    return $(element).match(selector);
  },
  next: function(element, selector) {
    return $(element).next(selector);
  },
  previous: function(element, selector) {
    return $(element).previous(selector);
  },
  up: function(element, selector) {
    return $(element).up(selector);
  },

  // Manipulation
  hide: function(element) {
    var element = $(element);
    element && element.hide();
  },
  show: function(element) {
    var element = $(element);
    element && element.show();
  },
  visible: function(element) {
    return $(element).visible();
  },
  clone: function(element) {
    // IE copies events bound via attachEvent when
    // using cloneNode. Calling detachEvent on the
    // clone will also remove the events from the orignal
    // In order to get around this, we use innerHTML.
    var clone;
    if(Prototype.Browser.IE) {
      clone = element.clone(false);
      clone.innerHTML = element.innerHTML;

      // innerHTML still copies all kinds of custom attributes over in IE.
      (function(element) {
        var attributes = element.attributes,
            children = element.childNodes;
        if(attributes) {
          for(var i=0, ii=attributes.length; i<ii; i++) {
            if(attributes[i]) {
              var attr = attributes[i].nodeName;
              if(('_prototypeUID' == attr) ||
                 (/^jQuery/.test(attr))) {
                FT.debug('removing "' + attr + '"');
                element.removeAttribute(attr);
              }
            }
          }
        }
        if(children) {
          for(var i=0, ii=children.length; i<ii; i++) {
            arguments.callee(children[i]);
          }
        }
      })(clone);
    } else {
      clone = element.cloneNode(true);
    }
    return clone;
  },
  insert_after: function(reference, element) {
    reference.insert({'after':element});
  },
  prependTo: function(reference, html) {
    return $(reference).insert({top: html});
  },
  replace: function(element, html) {
    return $(element).update(html);
  },

  // Forms
  serialize: function(form) {
    return $(form).serialize();
  },
  activate: function(element) {
    $(element).select();
  },
  assign: function(controls, value) {
    var control = controls[0];
    if(control) {
      switch(control.nodeName.toUpperCase()) {
        case 'INPUT':
        case 'TEXTAREA':
          $(control).setValue(value);
          break;

        case 'SELECT':
          var options = control.options;
          var option;
          for(var i=0;i<options.length;i++) {
            option = options[i];
            if(option.value == value) {
              option.selected = true;
              return;
            }
          }
          break;
      }
    }
  },

  // Events
  delegate: function(parent, event_name, selector, callback) {
    $(parent).observe(event_name, function(e) {
      if(e.element().match(selector)) {
        window.console.log([event_name, e.element(), selector]);
        callback(e);
      }
    });
  },
  on: function(element, event_name, callback) {
    $(element).observe(event_name, callback);
  },
  stop: function(event) {
    Event.stop(event);
  },
  fire: function(element, event_name, args) {
    $(element).fire(event_name, args);
  },
  target: function(event) {
    return event.element();
  },

  // Ajax
  xhr: function(url, method, params, args) {
    args = args || {};
    args.asynchronous = true;
    args.evalScripts = true;
    args.method = method;
    args.parameters = params;
    new Ajax.Request(url, args);
  }
}
<commit_msg>[fix] Fixed a bug with the `fire` method in the Prototype Adapter (5m)<commit_after>var FT=FT||{};
FT.Adapters=FT.Adapters||{};
FT.Adapters.Prototype = {

  // Load
  loaded: function(callback) {
    document.observe('dom:loaded', callback);
  },

  // Attributes
  attr: function(element, name, value) {
    if(value) {
      $(element).writeAttribute(name, value);
    } else {
      return $(element).readAttribute(name);
    }
  },
  css: function(element, css) {
    $(element).setStyle(css);
  },
  addClass: function(element, class_name) {
    $(element).addClassName(class_name);
  },
  hasClass: function(element, class_name) {
    return $(element).hasClassName(class_name);
  },
  removeClass: function(element, class_name) {
    $(element).removeClassName(class_name);
  },
  text: function(element) {
    return element.innerText;
  },

  // Selection/Traversal
  find_by_id: function(id) {
    return $(id);
  },
  find: function(parent_or_selector, selector) {
    return (selector ? $(parent_or_selector).select(selector) : $$(parent_or_selector))||[];
  },
  match: function(element, selector) {
    return $(element).match(selector);
  },
  next: function(element, selector) {
    return $(element).next(selector);
  },
  previous: function(element, selector) {
    return $(element).previous(selector);
  },
  up: function(element, selector) {
    return $(element).up(selector);
  },

  // Manipulation
  hide: function(element) {
    var element = $(element);
    element && element.hide();
  },
  show: function(element) {
    var element = $(element);
    element && element.show();
  },
  visible: function(element) {
    return $(element).visible();
  },
  clone: function(element) {
    // IE copies events bound via attachEvent when
    // using cloneNode. Calling detachEvent on the
    // clone will also remove the events from the orignal
    // In order to get around this, we use innerHTML.
    var clone;
    if(Prototype.Browser.IE) {
      clone = element.clone(false);
      clone.innerHTML = element.innerHTML;

      // innerHTML still copies all kinds of custom attributes over in IE.
      (function(element) {
        var attributes = element.attributes,
            children = element.childNodes;
        if(attributes) {
          for(var i=0, ii=attributes.length; i<ii; i++) {
            if(attributes[i]) {
              var attr = attributes[i].nodeName;
              if(('_prototypeUID' == attr) ||
                 (/^jQuery/.test(attr))) {
                FT.debug('removing "' + attr + '"');
                element.removeAttribute(attr);
              }
            }
          }
        }
        if(children) {
          for(var i=0, ii=children.length; i<ii; i++) {
            arguments.callee(children[i]);
          }
        }
      })(clone);
    } else {
      clone = element.cloneNode(true);
    }
    return clone;
  },
  insert_after: function(reference, element) {
    reference.insert({'after':element});
  },
  prependTo: function(reference, html) {
    return $(reference).insert({top: html});
  },
  replace: function(element, html) {
    return $(element).update(html);
  },

  // Forms
  serialize: function(form) {
    return $(form).serialize();
  },
  activate: function(element) {
    $(element).select();
  },
  assign: function(controls, value) {
    var control = controls[0];
    if(control) {
      switch(control.nodeName.toUpperCase()) {
        case 'INPUT':
        case 'TEXTAREA':
          $(control).setValue(value);
          break;

        case 'SELECT':
          var options = control.options;
          var option;
          for(var i=0;i<options.length;i++) {
            option = options[i];
            if(option.value == value) {
              option.selected = true;
              return;
            }
          }
          break;
      }
    }
  },

  // Events
  delegate: function(parent, event_name, selector, callback) {
    $(parent).observe(event_name, function(e) {
      if(e.element().match(selector)) {
        window.console.log([event_name, e.element(), selector]);
        callback(e);
      }
    });
  },
  on: function(element, event_name, callback) {
    $(element).observe(event_name, callback);
  },
  stop: function(event) {
    Event.stop(event);
  },
  fire: function(element, event_name, args) {
    if(toString.call(element) === '[object Array]') element = element[0];
    $(element).fire(event_name, args);
  },
  target: function(event) {
    return event.element();
  },

  // Ajax
  xhr: function(url, method, params, args) {
    args = args || {};
    args.asynchronous = true;
    args.evalScripts = true;
    args.method = method;
    args.parameters = params;
    new Ajax.Request(url, args);
  }
}
<|endoftext|>


<commit_before>/*jslint node: true, white: true */
var fs = require('fs'),
	util = require('util'),
	EventEmitter = require('events').EventEmitter,
	async = require('async'),
	exec = require("child_process").exec,
	debug = require('debug')('rpi-gpio');

var PATH = '/sys/devices/virtual';
var PINS = {
	v1: {
		// 1: 3.3v
		// 2: 5v
		'3': 0,
		// 4: 5v
		'5': 1,
		// 6: ground
		'7': 4,
		'8': 14,
		// 9: ground
		'10': 15,
		'11': 17,
		'12': 18,
		'13': 21,
		// 14: ground
		'15': 22,
		'16': 23,
		// 17: 3.3v
		'18': 24,
		'19': 10,
		// 20: ground
		'21': 9,
		'22': 25,
		'23': 11,
		'24': 8,
		// 25: ground
		'26': 7
	},
	v2: {
		// 1: 3.3v
		// 2: 5v
		'3': 2,
		// 4: 5v
		'5': 3,
		// 6: ground
		'7': 4,
		'8': 14,
		// 9: ground
		'10': 15,
		'11': 17,
		'12': 18,
		'13': 27,
		// 14: ground
		'15': 22,
		'16': 23,
		// 17: 3.3v
		'18': 24,
		'19': 10,
		// 20: ground
		'21': 9,
		'22': 25,
		'23': 11,
		'24': 8,
		// 25: ground
		'26': 7,

		// Model B+ pins
		// 27: ID_SD
		// 28: ID_SC
		'29': 5,
		// 30: ground
		'31': 6,
		'32': 12,
		'33': 13,
		// 34: ground
		'35': 19,
		'36': 16,
		'37': 26,
		'38': 20,
		// 39: ground
		'40': 21
	}
};

function setDirection(pin, direction, cb) {
	debug('set direction %s on pin %d', direction.toUpperCase(), pin);
	fs.writeFile(PATH + '/gpio' + pin + '/direction', direction, function (err) {
		if(cb) {
			return cb(err);
		}
	});
}

function exportPin(pin, cb) {
	debug('export pin %d', pin);
	exec("gpio-admin export " + pin, cb);
}

function unexportPin(pin, cb) {
	debug('unexport pin %d', pin);
	fs.unwatchFile(PATH + '/gpio' + pin + '/value');
	exec("gpio-admin unexport " + pin, cb);
}

function isExported(pin, cb) {
	fs.exists(PATH + '/gpio' + pin, function (exists) {
		return cb(null, exists);
	});
}

function Gpio() {
	var self = this,
		currentPins,
		exportedInputPins = {},
		exportedOutputPins = {},
		getPinForCurrentMode,
		pollFrequency = 5007,
		bcmChannels = [
			3,
			5,
			7,
			8,
			10,
			11,
			12,
			13,
			15,
			16,
			18,
			19,
			21,
			22,
			23,
			24,
			26,
			29,
			31,
			32,
			33,
			35,
			36,
			37,
			38,
			40
		];

	self.DIR_IN = 'in';
	self.DIR_OUT = 'out';
	self.MODE_RPI = 'mode_rpi';
	self.MODE_BCM = 'mode_bcm';

	// Private functions requring access to state
	function setRaspberryVersion(cb) {
		if(currentPins) {
			return cb(null);
		}

		fs.readFile('/proc/cpuinfo', 'utf8', function (err, data) {
			if(err) {
				return cb(err);
			}

			// Match the last 4 digits of the number following "Revision:"
			var match = data.match(/Revision\s*:\s*[0-9a-f]*([0-9a-f]{4})/);
			var revisionNumber = parseInt(match[1], 16);
			var pinVersion = (revisionNumber < 4) ? 'v1' : 'v2';

			debug(
				'seen hardware revision %d; using pin mode %s',
				revisionNumber,
				pinVersion
			);

			currentPins = PINS[pinVersion];

			return cb(null);
		});
	}

	function getPinRpi(channel) {
		return currentPins[channel].toString();
	}

	function getPinBcm(channel) {
		var parsedChannel = parseInt(channel, 10);
		return bcmChannels.indexOf(parsedChannel) !== -1 ? channel : null;
	}

	function createListener(channel, pin) {
		var channelPath = PATH + '/gpio' + pin;// + '/value';

		debug('listen for pin %d at ' + channelPath, pin);

		fs.watchFile(
		    channelPath,
		    {
		        persistent: true,
		        interval: pollFrequency
		    },
		    function (current, previous) {
		        console.log('Event created at ' + channelPath);
		        if((current && previous) && current.mtime > previous.mtime) {
		            self.read(channel, function (err, value) {
		                debug(
		                    'failed to read value after a change on channel %d:' + err,
		                    channel
		                );
		                self.emit('change', channel, value);
		            });
		        }
		    }
		);
	}

	/**
	 * Set pin reference mode. Defaults to 'mode_rpi'.
	 *
	 * @param {string} mode Pin reference mode, 'mode_rpi' or 'mode_bcm'
	 */
	self.setMode = function (mode) {
		if(mode === self.MODE_RPI) {
			getPinForCurrentMode = getPinRpi;
		} else if(mode === self.MODE_BCM) {
			getPinForCurrentMode = getPinBcm;
		} else {
			throw new Error('Cannot set invalid mode');
		}

		self.emit('modeChange', mode);
	};

	/**
	 * Set a custom polling frequency for watching pin changes
	 *
	 * @param {number} value The frequency to poll at, in milliseconds
	 */
	self.setPollFrequency = function (value) {
		if(typeof value === 'number') {
			pollFrequency = value;
		}
	};

	/**
	 * Setup a channel for use as an input or output
	 *
	 * @param {number}   channel   Reference to the pin in the current mode's schema
	 * @param {string}   direction The pin direction, either 'in' or 'out'
	 * @param {function} onSetup   Optional callback
	 */
	self.setup = function (channel, direction, onSetup /*err*/ ) {
		if(arguments.length === 2 && typeof direction === 'function') {
			onSetup = direction;
			direction = self.DIR_OUT;
		}

		direction = direction || self.DIR_OUT;
		onSetup = onSetup || function () {
			return;
		};

		if(!channel) {
			return process.nextTick(function () {
				onSetup(new Error('Channel must be a number'));
			});
		}

		if(direction !== self.DIR_IN && direction !== self.DIR_OUT) {
			return process.nextTick(function () {
				onSetup(new Error('Cannot set invalid direction'));
			});
		}

		var pinForSetup;
		async.waterfall([
			setRaspberryVersion,
			function (next) {
				pinForSetup = getPinForCurrentMode(channel);
				if(!pinForSetup) {
					return next(new Error('Channel ' + channel + ' does not map to a GPIO pin'));
				}
				debug('set up pin %d', pinForSetup);
				isExported(pinForSetup, next);
			},
			function (isExported, next) {
				if(isExported) {
					return unexportPin(pinForSetup, next);
				}
				return next(null);
			},
			function (next) {
				exportPin(pinForSetup, next);
			},
			function (next) {
				self.emit('export', channel);
				createListener.call(self, channel, pinForSetup);

				if(direction === self.DIR_IN) {
					exportedInputPins[pinForSetup] = true;
				} else {
					exportedOutputPins[pinForSetup] = true;
				}

				setDirection(pinForSetup, direction, next);
			}.bind(self)
		], onSetup);
	};

	/**
	 * Write a value to a channel
	 *
	 * @param {number}   channel The channel to write to
	 * @param {boolean}  value   If true, turns the channel on, else turns off
	 * @param {function} cb      Optional callback
	 */
	self.write = self.output = function (channel, value, cb /*err*/ ) {
		var pin = getPinForCurrentMode(channel);

		if(!exportedOutputPins[pin]) {
			var message;
			if(exportedInputPins[pin]) {
				message = 'Pin ' + pin + ' (Channel ' + channel + ') has been exported for input so cannot be written to';
			} else {
				message = 'Pin ' + pin + ' (Channel ' + channel + ') has not been exported';
			}

			return process.nextTick(function () {
				cb(new Error(message));
			});
		}

		value = (!!value && value !== '0') ? '1' : '0';
		fs.writeFile(PATH + '/gpio' + pin + '/value', value, cb || function () {
			return;
		});
	};

	/**
	 * Read a value from a channel
	 *
	 * @param {number}   channel The channel to read from
	 * @param {function} cb      Callback which receives the channel's boolean value
	 */
	self.read = self.input = function (channel, cb /*err,value*/ ) {
		var pin = getPinForCurrentMode(channel);

		if(!exportedInputPins[pin]) {
			return process.nextTick(function () {
				cb(new Error('Pin ' + pin + ' (Channel ' + channel + ') has not been exported'));
			});
		}

		fs.readFile(PATH + '/gpio' + pin + '/value', 'utf-8', function (err, data) {
			data = (data.toString()).trim() || '0';
			return cb(err, data === '1');
		});
	};

	/**
	 * Unexport any pins setup by this module
	 *
	 * @param {function} cb Optional callback
	 */
	self.destroy = function (cb) {
		var tasks = Object.keys(exportedOutputPins)
			.concat(Object.keys(exportedInputPins))
			.map(function (pin) {
				return function (done) {
					unexportPin(pin, done);
				};
			});

		async.parallel(tasks, cb);
	};

	/**
	 * Reset the state of the module
	 */
	self.reset = function () {
		exportedOutputPins = {};
		exportedInputPins = {};
		self.removeAllListeners();

		currentPins = undefined;
		getPinForCurrentMode = getPinRpi;
		pollFrequency = 5007;
	};

	// Init
	EventEmitter.call(self);
	self.reset();
}
util.inherits(Gpio, EventEmitter);

module.exports = new Gpio();
<commit_msg>Switched to using WiringPi's GPIO utility instead of gpio-admin<commit_after>/*jslint node: true, white: true */
var fs = require('fs'),
	util = require('util'),
	EventEmitter = require('events').EventEmitter,
	async = require('async'),
	exec = require("child_process").exec,
	debug = require('debug')('rpi-gpio');

var PATH = '/sys/class/gpio';
var PINS = {
	v1: {
		// 1: 3.3v
		// 2: 5v
		'3': 0,
		// 4: 5v
		'5': 1,
		// 6: ground
		'7': 4,
		'8': 14,
		// 9: ground
		'10': 15,
		'11': 17,
		'12': 18,
		'13': 21,
		// 14: ground
		'15': 22,
		'16': 23,
		// 17: 3.3v
		'18': 24,
		'19': 10,
		// 20: ground
		'21': 9,
		'22': 25,
		'23': 11,
		'24': 8,
		// 25: ground
		'26': 7
	},
	v2: {
		// 1: 3.3v
		// 2: 5v
		'3': 2,
		// 4: 5v
		'5': 3,
		// 6: ground
		'7': 4,
		'8': 14,
		// 9: ground
		'10': 15,
		'11': 17,
		'12': 18,
		'13': 27,
		// 14: ground
		'15': 22,
		'16': 23,
		// 17: 3.3v
		'18': 24,
		'19': 10,
		// 20: ground
		'21': 9,
		'22': 25,
		'23': 11,
		'24': 8,
		// 25: ground
		'26': 7,

		// Model B+ pins
		// 27: ID_SD
		// 28: ID_SC
		'29': 5,
		// 30: ground
		'31': 6,
		'32': 12,
		'33': 13,
		// 34: ground
		'35': 19,
		'36': 16,
		'37': 26,
		'38': 20,
		// 39: ground
		'40': 21
	}
};

function exportPin(pin, cb, direction) {
	debug('export pin %d', pin);
	var exportCommand = "gpio export " + pin + " " + direction;

	exec(exportCommand, {}, function () {
        cb();
    });
}

function unexportPin(pin, cb) {
	debug('unexport pin %d', pin);

	var unexportCommand = "gpio unexport " + pin;

	fs.unwatchFile(PATH + '/gpio' + pin + '/value');
	exec(unexportCommand, {}, function () {
		cb();
	});
}

function isExported(pin, cb) {
	fs.exists(PATH + '/gpio' + pin, function (exists) {
		return cb(null, exists);
	});
}

function Gpio() {
	var self = this,
		currentPins,
		exportedInputPins = {},
		exportedOutputPins = {},
		getPinForCurrentMode,
		pollFrequency = 5007,
		bcmChannels = [
			3,
			5,
			7,
			8,
			10,
			11,
			12,
			13,
			15,
			16,
			18,
			19,
			21,
			22,
			23,
			24,
			26,
			29,
			31,
			32,
			33,
			35,
			36,
			37,
			38,
			40
		];

	self.DIR_IN = 'in';
	self.DIR_OUT = 'out';
	self.MODE_RPI = 'mode_rpi';
	self.MODE_BCM = 'mode_bcm';

	// Private functions requring access to state
	function setRaspberryVersion(cb) {
		if(currentPins) {
			return cb(null);
		}

		fs.readFile('/proc/cpuinfo', 'utf8', function (err, data) {
			if(err) {
				return cb(err);
			}

			// Match the last 4 digits of the number following "Revision:"
			var match = data.match(/Revision\s*:\s*[0-9a-f]*([0-9a-f]{4})/);
			var revisionNumber = parseInt(match[1], 16);
			var pinVersion = (revisionNumber < 4) ? 'v1' : 'v2';

			debug(
				'seen hardware revision %d; using pin mode %s',
				revisionNumber,
				pinVersion
			);

			currentPins = PINS[pinVersion];

			return cb(null);
		});
	}

	function getPinRpi(channel) {
		return currentPins[channel].toString();
	}

	function getPinBcm(channel) {
		var parsedChannel = parseInt(channel, 10);
		return bcmChannels.indexOf(parsedChannel) !== -1 ? channel : null;
	}

	function createListener(channel, pin) {
		var channelPath = PATH + '/gpio' + pin + '/value';

		debug('listen for pin %d at ' + channelPath, pin);

		fs.watchFile(
		    channelPath,
		    {
		        persistent: true,
		        interval: pollFrequency
		    },
		    function (current, previous) {
		        console.log('Event created at ' + channelPath);
		        //if((current && previous) && current.mtime > previous.mtime) {
		            self.read(channel, function (err, value) {
		                debug(
		                    'failed to read value after a change on channel %d:' + err,
		                    channel
		                );
		                self.emit('change', channel, value);
		            });
		        //}
		    }
		);
	}

	/**
	 * Set pin reference mode. Defaults to 'mode_rpi'.
	 *
	 * @param {string} mode Pin reference mode, 'mode_rpi' or 'mode_bcm'
	 */
	self.setMode = function (mode) {
		if(mode === self.MODE_RPI) {
			getPinForCurrentMode = getPinRpi;
		} else if(mode === self.MODE_BCM) {
			getPinForCurrentMode = getPinBcm;
		} else {
			throw new Error('Cannot set invalid mode');
		}

		self.emit('modeChange', mode);
	};

	/**
	 * Set a custom polling frequency for watching pin changes
	 *
	 * @param {number} value The frequency to poll at, in milliseconds
	 */
	self.setPollFrequency = function (value) {
		if(typeof value === 'number') {
			pollFrequency = value;
		}
	};

	/**
	 * Setup a channel for use as an input or output
	 *
	 * @param {number}   channel   Reference to the pin in the current mode's schema
	 * @param {string}   direction The pin direction, either 'in' or 'out'
	 * @param {function} onSetup   Optional callback
	 */
	self.setup = function (channel, direction, onSetup /*err*/ ) {
		if(arguments.length === 2 && typeof direction === 'function') {
			onSetup = direction;
			direction = self.DIR_OUT;
		}

		direction = direction || self.DIR_OUT;
		onSetup = onSetup || function () {
			return;
		};

		if(!channel) {
			return process.nextTick(function () {
				onSetup(new Error('Channel must be a number'));
			});
		}

		if(direction !== self.DIR_IN && direction !== self.DIR_OUT) {
			return process.nextTick(function () {
				onSetup(new Error('Cannot set invalid direction'));
			});
		}

		var pinForSetup;
		async.waterfall([
			setRaspberryVersion,
			function (next) {
				pinForSetup = getPinForCurrentMode(channel);
				if(!pinForSetup) {
					return next(new Error('Channel ' + channel + ' does not map to a GPIO pin'));
				}
				debug('set up pin %d', pinForSetup);
				isExported(pinForSetup, next);
			},
			function (isExported, next) {
				if(isExported) {
					return unexportPin(pinForSetup, next);
				}
				return next(null);
			},
			function (next) {
				exportPin(pinForSetup, next, direction);
			},
			function (next) {
				self.emit('export', channel);
				createListener.call(self, channel, pinForSetup);

				if(direction === self.DIR_IN) {
					exportedInputPins[pinForSetup] = true;
				} else {
					exportedOutputPins[pinForSetup] = true;
				}

				return next(null);
			}.bind(self)
		], onSetup);
	};

	/**
	 * Write a value to a channel
	 *
	 * @param {number}   channel The channel to write to
	 * @param {boolean}  value   If true, turns the channel on, else turns off
	 * @param {function} cb      Optional callback
	 */
	self.write = self.output = function (channel, value, cb /*err*/ ) {
		var pin = getPinForCurrentMode(channel);

		if(!exportedOutputPins[pin]) {
			var message;
			if(exportedInputPins[pin]) {
				message = 'Pin ' + pin + ' (Channel ' + channel + ') has been exported for input so cannot be written to';
			} else {
				message = 'Pin ' + pin + ' (Channel ' + channel + ') has not been exported';
			}

			return process.nextTick(function () {
				cb(new Error(message));
			});
		}

		value = (!!value && value !== '0') ? '1' : '0';
		fs.writeFile(PATH + '/gpio' + pin + '/value', value, cb || function () {
			return;
		});
	};

	/**
	 * Read a value from a channel
	 *
	 * @param {number}   channel The channel to read from
	 * @param {function} cb      Callback which receives the channel's boolean value
	 */
	self.read = self.input = function (channel, cb /*err,value*/ ) {
		var pin = getPinForCurrentMode(channel);

		if(!exportedInputPins[pin]) {
			return process.nextTick(function () {
				cb(new Error('Pin ' + pin + ' (Channel ' + channel + ') has not been exported'));
			});
		}

		fs.readFile(PATH + '/gpio' + pin + '/value', 'utf-8', function (err, data) {
			data = (data.toString()).trim() || '0';
			return cb(err, data === '1');
		});
	};

	/**
	 * Unexport any pins setup by this module
	 *
	 * @param {function} cb Optional callback
	 */
	self.destroy = function (cb) {
		var tasks = Object.keys(exportedOutputPins)
			.concat(Object.keys(exportedInputPins))
			.map(function (pin) {
				return function (done) {
					unexportPin(pin, done);
				};
			});

		async.parallel(tasks, cb);
	};

	/**
	 * Reset the state of the module
	 */
	self.reset = function () {
		exportedOutputPins = {};
		exportedInputPins = {};
		self.removeAllListeners();

		currentPins = undefined;
		getPinForCurrentMode = getPinRpi;
		pollFrequency = 5007;
	};

	// Init
	EventEmitter.call(self);
	self.reset();
}
util.inherits(Gpio, EventEmitter);

module.exports = new Gpio();
<|endoftext|>


<commit_before>
/**
 * @author Anakeen
 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License
 */

var notalone=true;
function completechoice(index,tattrid,tattrv,winfo) {
  var rvalue;
  for (i=0; i< tattrid.length; i++) {
      if (tattrv[index][i]) {
      if  (tattrv[index][i].substring(0,1) != '?')  {
	if (winfo.document.getElementById(tattrid[i])) {
	  rvalue = tattrv[index][i].replace(/\\n/g,'\n');
	  ec_setIValue(winfo,winfo.document.getElementById(tattrid[i]),rvalue);
	  winfo.document.getElementById(tattrid[i]).style.backgroundColor='[COLOR_C8]';
	  sendEvent(winfo.document.getElementById(tattrid[i]),"change");
	  // This condition is for IE which does not send event in this case
	  if(winfo.document.getElementById(tattrid[i]).onchange){
	      eval(winfo.document.getElementById(tattrid[i]).onchange);
	  }
	} else {
	  rvalue = tattrv[index][i].replace(/\\n/g,'\n');
	  if (! ec_setIValuePlus(winfo,tattrid[i],rvalue)) {
	      if ((tattrid[i].substring(0,1) !='?') && (tattrid[i]!='')) {
	    if (notalone) alert('[TEXT:Attribute not found]'+'['+tattrid[i]+']'+winfo.name);
	      }
	  }
	}

      } else {
	if ((tattrv[index][i].length > 1) &&
	    ((winfo.document.getElementById(tattrid[i]).value == "") || (winfo.document.getElementById(tattrid[i]).value == " "))) {
	  rvalue = tattrv[index][i].substring(1).replace(/\\n/g,'\n');
	  winfo.document.getElementById(tattrid[i]).value = rvalue;
	  winfo.document.getElementById(tattrid[i]).style.backgroundColor='[COLOR_C8]';
	  sendEvent(winfo.document.getElementById(tattrid[i]),"change");
	  // This condition is for IE which does not send event in this case
	  if(winfo.document.getElementById(tattrid[i]).onchange){
          eval(winfo.document.getElementById(tattrid[i]).onchange);
      }
	}
      }
      }
  }
  winfo.disableReadAttribute();

  return;

}

var isNetscape = navigator.appName=="Netscape";

function completechoices() {
    var cvalues = new Array();
    for (i=0; i< tattrid.length; i++) {
      cvalues[i] ="";
    }
    senum = document.getElementById('schoose');
    for (c=0; c< senum.length; c++) {
      if (senum.options[c].selected) {
	index= senum.options[c].value;
	for (i=0; i< tattrid.length; i++) {
	  with (winfo.document.getElementById(tattrid[i])) {
	    if (tattrv[index][i] != "") {
	      cvalues[i] += tattrv[index][i];
	       cvalues[i] += "\n";
	      style.backgroundColor='[COLOR_C8]';
	    }
	    //       style.fontWeight='bold';
	  }
	}
      }
    }
    for (i=0; i< tattrid.length; i++) {
      if (cvalues[i][0] != '?')
	// delete last CR
	winfo.document.getElementById(tattrid[i]).value = cvalues[i].substring(0,cvalues[i].length-1);
    }
    winfo.disableReadAttribute();
}

function autoClose() {
  // see if only one possibility
  if (tattrv.length == 1) {
     completechoice(0,tattrid,tattrv,winfo);
     setTimeout('self.close()',200); // must be set in next event loop cause Mozilla crash sometimes
  }

}

function ec_setIValue(winfo,i,v) {
  if (i) {

    if (i.tagName == "INPUT") {
      if ((i.type=='radio')||(i.type=='checkbox')) {
	var oi=i.checked;
	if (v=='0') v=false;
	i.checked=v;

	if (v && (i.type=='radio')) winfo.changeCheckClasses(i,false);
	if (v && (i.type=='checkbox')) {
	  if (oi != v)  i.onclick.apply(i,[]);
	  //	  winfo.changeCheckBoolClasses(i,false);
	}
      }
      else i.value=v;
    }
    else if (i.tagName == "TEXTAREA")  i.value=v;
    else  if (i.tagName == "SELECT") {
      for (var k=0;k<i.options.length;k++) {
	if (i.options[k].value == v) i.selectedIndex=k;
      }
    }
  }
  ec_setIValuePlus(winfo,i.id,v);
}

function ec_setIValuePlus(winfo,iid,v) {
    var iid0= iid+'0';
    var i=0;
    var oi=winfo.document.getElementById(iid0);
    var ret=false;

    while (oi) {
      if (oi) {
	if ((oi.type=='radio')||(oi.type=='checkbox')) {
	  if (oi.value==v) {
	    oi.checked=true;
	    oi.onclick.apply(oi,[]);
	    ret=true;
	  }
	}
      }
      i++;
      iid0=iid+i.toString();
      oi=winfo.document.getElementById(iid0);
    }
    return ret;
}
<commit_msg>Multiple DocId in Array in IE [ closes #728 ]<commit_after>
/**
 * @author Anakeen
 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License
 */

var notalone=true;
function completechoice(index,tattrid,tattrv,winfo) {
  var rvalue;
  for (i=0; i< tattrid.length; i++) {
      if (tattrv[index][i]) {
      if  (tattrv[index][i].substring(0,1) != '?')  {
	if (winfo.document.getElementById(tattrid[i])) {
	  rvalue = tattrv[index][i].replace(/\\n/g,'\n');
	  ec_setIValue(winfo,winfo.document.getElementById(tattrid[i]),rvalue);
	  winfo.document.getElementById(tattrid[i]).style.backgroundColor='[COLOR_C8]';
	  sendEvent(winfo.document.getElementById(tattrid[i]),"change");
	  // This condition is for IE which does not send event in this case
	  if(isIE && winfo.document.getElementById(tattrid[i]).onchange){
	      eval(winfo.document.getElementById(tattrid[i]).onchange);
	  }
	} else {
	  rvalue = tattrv[index][i].replace(/\\n/g,'\n');
	  if (! ec_setIValuePlus(winfo,tattrid[i],rvalue)) {
	      if ((tattrid[i].substring(0,1) !='?') && (tattrid[i]!='')) {
	    if (notalone) alert('[TEXT:Attribute not found]'+'['+tattrid[i]+']'+winfo.name);
	      }
	  }
	}

      } else {
	if ((tattrv[index][i].length > 1) &&
	    ((winfo.document.getElementById(tattrid[i]).value == "") || (winfo.document.getElementById(tattrid[i]).value == " "))) {
	  rvalue = tattrv[index][i].substring(1).replace(/\\n/g,'\n');
	  winfo.document.getElementById(tattrid[i]).value = rvalue;
	  winfo.document.getElementById(tattrid[i]).style.backgroundColor='[COLOR_C8]';
	  sendEvent(winfo.document.getElementById(tattrid[i]),"change");
	  // This condition is for IE which does not send event in this case
	  if(isIE && winfo.document.getElementById(tattrid[i]).onchange){
          eval(winfo.document.getElementById(tattrid[i]).onchange);
      }
	}
      }
      }
  }
  winfo.disableReadAttribute();

  return;

}

var isNetscape = navigator.appName=="Netscape";

function completechoices() {
    var cvalues = new Array();
    for (i=0; i< tattrid.length; i++) {
      cvalues[i] ="";
    }
    senum = document.getElementById('schoose');
    for (c=0; c< senum.length; c++) {
      if (senum.options[c].selected) {
	index= senum.options[c].value;
	for (i=0; i< tattrid.length; i++) {
	  with (winfo.document.getElementById(tattrid[i])) {
	    if (tattrv[index][i] != "") {
	      cvalues[i] += tattrv[index][i];
	       cvalues[i] += "\n";
	      style.backgroundColor='[COLOR_C8]';
	    }
	    //       style.fontWeight='bold';
	  }
	}
      }
    }
    for (i=0; i< tattrid.length; i++) {
      if (cvalues[i][0] != '?')
	// delete last CR
	winfo.document.getElementById(tattrid[i]).value = cvalues[i].substring(0,cvalues[i].length-1);
    }
    winfo.disableReadAttribute();
}

function autoClose() {
  // see if only one possibility
  if (tattrv.length == 1) {
     completechoice(0,tattrid,tattrv,winfo);
     setTimeout('self.close()',200); // must be set in next event loop cause Mozilla crash sometimes
  }

}

function ec_setIValue(winfo,i,v) {
  if (i) {

    if (i.tagName == "INPUT") {
      if ((i.type=='radio')||(i.type=='checkbox')) {
	var oi=i.checked;
	if (v=='0') v=false;
	i.checked=v;

	if (v && (i.type=='radio')) winfo.changeCheckClasses(i,false);
	if (v && (i.type=='checkbox')) {
	  if (oi != v)  i.onclick.apply(i,[]);
	  //	  winfo.changeCheckBoolClasses(i,false);
	}
      }
      else i.value=v;
    }
    else if (i.tagName == "TEXTAREA")  i.value=v;
    else  if (i.tagName == "SELECT") {
      for (var k=0;k<i.options.length;k++) {
	if (i.options[k].value == v) i.selectedIndex=k;
      }
    }
  }
  ec_setIValuePlus(winfo,i.id,v);
}

function ec_setIValuePlus(winfo,iid,v) {
    var iid0= iid+'0';
    var i=0;
    var oi=winfo.document.getElementById(iid0);
    var ret=false;

    while (oi) {
      if (oi) {
	if ((oi.type=='radio')||(oi.type=='checkbox')) {
	  if (oi.value==v) {
	    oi.checked=true;
	    oi.onclick.apply(oi,[]);
	    ret=true;
	  }
	}
      }
      i++;
      iid0=iid+i.toString();
      oi=winfo.document.getElementById(iid0);
    }
    return ret;
}
<|endoftext|>


<commit_before>"use strict";

/*
 * Sticky anchor areas
 * Copyright 2013 Robin Poort
 * http://www.robinpoort.com
 */

;(function($) {

    $.stickyAnchorArea = function(element, options) {

        var defaults = {},
            plugin = this;

        plugin.settings = {}

        var $element = $(element),
            element = element;

        plugin.init = function() {

            plugin.settings = $.extend({}, defaults, options);

            // Test if the browser supports position fixed by testing the top offset of a fixed element
            $('

').prependTo('body');
            var theOffset = $('#canBrowserhandleFixedPosition').offset().top;
            if( theOffset >= 100 ) { theOffset = true } else { theOffset = false }
            $('#canBrowserhandleFixedPosition').remove();

            // Variables
            var stickyElement = $(element),
                stickyElementHeight = $(element).outerHeight(),
                stickyElementZindex = $(element).css('z-index'),
                urlHash = window.location.hash;

            // Variables for scrollFrom
            if ( plugin.settings.scrollFrom ) {
                var scrollFromContainer = plugin.settings.scrollFrom;
            }

            // Variables for ScrollUntil
            if ( plugin.settings.scrollUntil ) {
                var scrollUntilContainer = plugin.settings.scrollUntil;
            }

            // Custom functions
            $.fn.fixedPosition = function(scrollFromHeight, stickyElementWidth) {
                this.css({'position' : 'fixed', 'top' : scrollFromHeight, 'height' : 'auto', 'width' : stickyElementWidth});
            }
            $.fn.unFixedPosition = function() {
                this.removeAttr('style');
            }

            // Add div to all sticky elements
            stickyElement.wrap('

');

            function makeSticky() {
                var scrollTop = Math.ceil( $(window).scrollTop()),
                    stickyElementParent = stickyElement.parent('.stickAround'),
                    stickyElementOffset = Math.ceil(stickyElement.parent('.stickAround').offset().top),
                    stickyElementHeight = $(element).outerHeight(),
                    stickyElementWidth = stickyElementParent.width(),
                    scrollFromHeight = '0',
                    windowHeight = $(window).height();

                // Variables for scrollFrom
                if ( plugin.settings.scrollFrom ) {
                    var scrollFromHeight = Math.ceil( $(scrollFromContainer).outerHeight()),
                        scrollUntilNewTop = scrollTop + scrollFromHeight;
                }

                // Variables for ScrollUntil
                if ( plugin.settings.scrollUntil ) {
                    if ( plugin.settings.scrollFrom && scrollFromHeight <= windowHeight ) {
                        var scrollUntil = (Math.ceil( $(scrollUntilContainer).offset().top)) - scrollFromHeight,
                            scrollUntilPosition = (scrollUntil - stickyElementOffset + (scrollFromHeight - stickyElementHeight) );
                    } else {
                        var scrollUntil = Math.ceil( $(scrollUntilContainer).offset().top),
                            scrollUntilPosition = (scrollUntil - stickyElementOffset - stickyElementHeight);
                    }
                }

                // Give the surrounding div the height of the element
                if ( !stickyElementParent.hasClass('child-to-tall') ) {
                    stickyElementParent.css({ 'position' : 'relative', 'height' : stickyElementHeight, 'z-index' : stickyElementZindex });
                }

                // Already sticking element taller than viewport?
                if ( stickyElementHeight >= windowHeight && stickyElement.css('position') == 'fixed' ) {
                    var stickyTopOffset = stickyElement.offset().top;
                    stickyElementParent.css('position', 'static').addClass('child-to-tall');
                    stickyElement.css({'position': 'absolute', 'top' : stickyTopOffset }).addClass('to-tall');
                }
                // Sticky element taller than viewport and scrolltop smaller than the offset of our stickAround container?
                else if ( scrollTop <= stickyElementParent.offset().top && stickyElementHeight >= windowHeight ) {
                    stickyElement.unFixedPosition();
                    if ( stickyElement.hasClass('child-to-tall') ) {
                        stickyElement.removeClass('child-to-tall');
                    }
                }
                // Keep already sticking elements in "fake fixed position" when scrolling to the top
                else if ( scrollTop < stickyElement.offset().top && stickyElementHeight >= windowHeight && stickyElement.css('position') == 'absolute' ) {
                    stickyElement.css({'position': 'absolute', 'top' : scrollTop }).addClass('to-tall');
                }
                // remove classes when viewport is large enough again
                else if ( stickyElementHeight < windowHeight ) {
                    if ( stickyElementParent.hasClass('child-to-tall') ) {
                        stickyElementParent.removeClass('child-to-tall');
                    }
                    if ( stickyElement.hasClass('to-tall') ) {
                        stickyElement.removeClass('to-tall');
                    }
                }
                // Make elements sticky when element is smaller than viewport height
                if ( !stickyElement.hasClass('to-tall') ) {

                    // Make element sticky
                    if ( scrollTop > stickyElementOffset || stickyElementOffset == 0) {
                        $(element).fixedPosition(scrollFromHeight, stickyElementWidth);
                    }

                    // scrollFrom
                    if ( plugin.settings.scrollFrom ) {
                        if ( scrollFromHeight <= windowHeight ) {
                            if ( stickyElementOffset <= scrollUntilNewTop ) {
                                stickyElement.fixedPosition(scrollFromHeight, stickyElementWidth);
                            }
                            if ( stickyElementOffset > scrollUntilNewTop ) {
                                stickyElement.unFixedPosition();
                            }
                        } else if ( scrollTop > stickyElementOffset) {
                            stickyElement.fixedPosition(0, stickyElementWidth);
                        }
                    }

                    // Make element unsticky
                    if ( scrollTop < stickyElementOffset && stickyElementOffset != 0 && ( !plugin.settings.scrollFrom || !plugin.settings.scrollFrom ) ) {
                        stickyElement.unFixedPosition();
                    } else if ( scrollTop < stickyElementOffset && scrollFromHeight >= windowHeight) {
                        stickyElement.unFixedPosition();
                    }

                    // Stickyness when scrollUntil is used
                    if ( plugin.settings.scrollUntil ) {
                        if ( scrollTop > (scrollUntil - stickyElementHeight) ) {
                            stickyElement.css({'position' : 'absolute', 'top' : scrollUntilPosition });
                        }
                        if ( scrollTop > scrollUntil ) {
                            stickyElement.unFixedPosition();
                        }
                    }

                }

            }

            // Fix the anchor linking with multiple sticky areas on top of each other

            if ( plugin.settings.scrollFrom && ( $(scrollFromContainer).height() <= $(window).height() ) ) {
                var stickyElementOffset = stickyElementHeight + $(scrollFromContainer).height();
            }
            if ( plugin.settings.scrollFrom && ( $(scrollFromContainer).height() > $(window).height() ) ) {
                var stickyElementOffset = 0;
            } else {
                var stickyElementOffset = stickyElementHeight;
            }

            // Run function initially and on events
            $(window).on('ready resize scroll', function() {
                makeSticky();
            });

            // Check the position of elements in the markup
            $.fn.isAfter = function(elem) {
                if(typeof(elem) == "string") elem = $(elem);
                return this.add(elem).index(elem) == 0;
            }

            // Create empty anchors array
            var elements = [];

            // The function to call for adding divs
            function addAnchorDiv(elem) {
                if( $(elem).isAfter(stickyElement)) {

                    var elemClean = elem.replace('#', '');

                    // Check if the current anchor was already processed
                    if($.inArray(elemClean, elements) == -1)
                    {
                        $(elem).before('
');

                        // Add current anchor to array
                        elements.push(elemClean);
                    }
                }
            }

            if( theOffset == true ) {

                // The URL method
                addAnchorDiv(urlHash);

                // Per link method
                $('a[href*=#]:not([href=#])').each(function() {

                    var target = $(this).prop('hash');

                    // Add items
                    $(target).each(function() {
                        // Add extra div code
                        addAnchorDiv(target);
                    });
                });
            }
        }

        plugin.init();

    }

    // add the plugin to the jQuery.fn object
    $.fn.stickyAnchorArea = function(options) {

        // iterate through the DOM elements we are attaching the plugin to
        return this.each(function() {

            // if plugin has not already been attached to the element
            if (undefined == $(this).data('stickyAnchorArea')) {

                // create a new instance of the plugin
                // pass the DOM element and the user-provided options as arguments
                var plugin = new $.stickyAnchorArea(this, options);

                // in the jQuery version of the element
                // store a reference to the plugin object
                // you can later access the plugin and its methods and properties like
                // element.data('stickyAnchorArea').publicMethod(arg1, arg2, ... argn) or
                // element.data('stickyAnchorArea').settings.propertyName
                $(this).data('stickyAnchorArea', plugin);

            }

        });
    }

})(jQuery);<commit_msg>working on anchor linking<commit_after>"use strict";

/*
 * Sticky anchor areas
 * Copyright 2013 Robin Poort
 * http://www.robinpoort.com
 */

;(function($) {

    $.stickyAnchorArea = function(element, options) {

        var defaults = {},
            plugin = this;

        plugin.settings = {}

        var $element = $(element),
            element = element;

        plugin.init = function() {

            plugin.settings = $.extend({}, defaults, options);

            // Test if the browser supports position fixed by testing the top offset of a fixed element
            $('

').prependTo('body');
            var theOffset = $('#canBrowserhandleFixedPosition').offset().top;
            if( theOffset >= 100 ) { theOffset = true } else { theOffset = false }
            $('#canBrowserhandleFixedPosition').remove();

            // Variables
            var stickyElement = $(element),
                stickyElementHeight = $(element).outerHeight(),
                stickyElementZindex = $(element).css('z-index'),
                urlHash = window.location.hash;

            // Variables for scrollFrom
            if ( plugin.settings.scrollFrom ) {
                var scrollFromContainer = plugin.settings.scrollFrom;
            }

            // Variables for ScrollUntil
            if ( plugin.settings.scrollUntil ) {
                var scrollUntilContainer = plugin.settings.scrollUntil;
            }

            // Custom functions
            $.fn.fixedPosition = function(scrollFromHeight, stickyElementWidth) {
                this.css({'position' : 'fixed', 'top' : scrollFromHeight, 'height' : 'auto', 'width' : stickyElementWidth});
            }
            $.fn.unFixedPosition = function() {
                this.removeAttr('style');
            }

            // Add div to all sticky elements
            stickyElement.wrap('

');

            function makeSticky() {
                var scrollTop = Math.ceil( $(window).scrollTop()),
                    stickyElementParent = stickyElement.parent('.stickAround'),
                    stickyElementOffset = Math.ceil(stickyElement.parent('.stickAround').offset().top),
                    stickyElementHeight = $(element).outerHeight(),
                    stickyElementWidth = stickyElementParent.width(),
                    scrollFromHeight = '0',
                    windowHeight = $(window).height();

                // Variables for scrollFrom
                if ( plugin.settings.scrollFrom ) {
                    var scrollFromHeight = Math.ceil( $(scrollFromContainer).outerHeight()),
                        scrollUntilNewTop = scrollTop + scrollFromHeight;
                }

                // Variables for ScrollUntil
                if ( plugin.settings.scrollUntil ) {
                    if ( plugin.settings.scrollFrom && scrollFromHeight <= windowHeight ) {
                        var scrollUntil = (Math.ceil( $(scrollUntilContainer).offset().top)) - scrollFromHeight,
                            scrollUntilPosition = (scrollUntil - stickyElementOffset + (scrollFromHeight - stickyElementHeight) );
                    } else {
                        var scrollUntil = Math.ceil( $(scrollUntilContainer).offset().top),
                            scrollUntilPosition = (scrollUntil - stickyElementOffset - stickyElementHeight);
                    }
                }

                // Give the surrounding div the height of the element
                if ( !stickyElementParent.hasClass('child-to-tall') ) {
                    stickyElementParent.css({ 'position' : 'relative', 'height' : stickyElementHeight, 'z-index' : stickyElementZindex });
                }

                // Sticky element taller than viewport?
                if ( stickyElementHeight >= windowHeight ) {
                    var stickyTopOffset = stickyElement.offset().top;
                    stickyElementParent.addClass('child-to-tall');
                    stickyElement.addClass('to-tall');
                }

                // Already sticking element taller than viewport?
                if ( stickyElementHeight >= windowHeight && stickyElement.css('position') == 'fixed' ) {
                    var stickyTopOffset = stickyElement.offset().top;
                    stickyElementParent.css('position', 'static').addClass('child-to-tall');
                    stickyElement.css({'position': 'absolute', 'top' : stickyTopOffset }).addClass('to-tall');
                }
                // Sticky element taller than viewport and scrolltop smaller than the offset of our stickAround container?
                else if ( scrollTop <= stickyElementParent.offset().top && stickyElementHeight >= windowHeight ) {
                    stickyElement.unFixedPosition();
                    if ( stickyElement.hasClass('child-to-tall') ) {
                        stickyElement.removeClass('child-to-tall');
                    }
                }
                // Keep already sticking elements in "fake fixed position" when scrolling to the top
                else if ( scrollTop < stickyElement.offset().top && stickyElementHeight >= windowHeight && stickyElement.css('position') == 'absolute' ) {
                    stickyElement.css({'position': 'absolute', 'top' : scrollTop }).addClass('to-tall');
                }
                // remove classes when viewport is large enough again
                else if ( stickyElementHeight < windowHeight ) {
                    if ( stickyElementParent.hasClass('child-to-tall') ) {
                        stickyElementParent.removeClass('child-to-tall');
                    }
                    if ( stickyElement.hasClass('to-tall') ) {
                        stickyElement.removeClass('to-tall');
                    }
                }
                // Make elements sticky when element is smaller than viewport height
                if ( !stickyElement.hasClass('to-tall') ) {

                    // Make element sticky
                    if ( scrollTop > stickyElementOffset || stickyElementOffset == 0) {
                        $(element).fixedPosition(scrollFromHeight, stickyElementWidth);
                    }

                    // scrollFrom
                    if ( plugin.settings.scrollFrom ) {
                        if ( scrollFromHeight <= windowHeight ) {
                            if ( stickyElementOffset <= scrollUntilNewTop ) {
                                stickyElement.fixedPosition(scrollFromHeight, stickyElementWidth);
                            }
                            if ( stickyElementOffset > scrollUntilNewTop ) {
                                stickyElement.unFixedPosition();
                            }
                        } else if ( scrollTop > stickyElementOffset) {
                            stickyElement.fixedPosition(0, stickyElementWidth);
                        }
                    }

                    // Make element unsticky
                    if ( scrollTop < stickyElementOffset && stickyElementOffset != 0 && ( !plugin.settings.scrollFrom || !plugin.settings.scrollFrom ) ) {
                        stickyElement.unFixedPosition();
                    } else if ( scrollTop < stickyElementOffset && scrollFromHeight >= windowHeight) {
                        stickyElement.unFixedPosition();
                    }

                    // Stickyness when scrollUntil is used
                    if ( plugin.settings.scrollUntil ) {
                        if ( scrollTop > (scrollUntil - stickyElementHeight) ) {
                            stickyElement.css({'position' : 'absolute', 'top' : scrollUntilPosition });
                        }
                        if ( scrollTop > scrollUntil ) {
                            stickyElement.unFixedPosition();
                        }
                    }

                }

            }

            // Run function initially and on events
            $(window).on('ready resize scroll', function() {
                makeSticky();
            });

            // Check the position of elements in the markup
            $.fn.isAfter = function(elem) {
                if(typeof(elem) == "string") elem = $(elem);
                return this.add(elem).index(elem) == 0;
            }

            // set the offset of the element
            if ( plugin.settings.scrollFrom ) {
                var scrollFromHeight = $(scrollFromContainer).outerHeight();
                if ( scrollFromHeight > $(window).height ) {
                    var stickyElementOffset = 0;
                } else {
                    var stickyElementOffset = stickyElementHeight + $(scrollFromContainer).outerHeight();
                }
            } else {
                var stickyElementOffset = stickyElementHeight;
            }

            // Create empty anchors array
            var elements = [];

            // The function to call for adding divs
            function addAnchorDiv(elem) {
                if( $(elem).isAfter(stickyElement)) {

                    var elemClean = elem.replace('#', '');

                    // Check if the current anchor was already processed
                    if($.inArray(elemClean, elements) == -1)
                    {
                        $(elem).before('
');

                        // Add current anchor to array
                        elements.push(elemClean);
                    }
                }
            }

            if( theOffset == true ) {

                // The URL method
                addAnchorDiv(urlHash);

                // Per link method
                $('a[href*=#]:not([href=#])').each(function() {

                    var target = $(this).prop('hash');

                    // Add items
                    $(target).each(function() {
                        // Add extra div code
                        addAnchorDiv(target);
                    });
                });
            }
        }

        plugin.init();

    }

    // add the plugin to the jQuery.fn object
    $.fn.stickyAnchorArea = function(options) {

        // iterate through the DOM elements we are attaching the plugin to
        return this.each(function() {

            // if plugin has not already been attached to the element
            if (undefined == $(this).data('stickyAnchorArea')) {

                // create a new instance of the plugin
                // pass the DOM element and the user-provided options as arguments
                var plugin = new $.stickyAnchorArea(this, options);

                // in the jQuery version of the element
                // store a reference to the plugin object
                // you can later access the plugin and its methods and properties like
                // element.data('stickyAnchorArea').publicMethod(arg1, arg2, ... argn) or
                // element.data('stickyAnchorArea').settings.propertyName
                $(this).data('stickyAnchorArea', plugin);

            }

        });
    }

})(jQuery);<|endoftext|>


<commit_before>(function () {
    angular
        .module('summary')
        .controller('SummaryInterfaceController', controller);

    controller.$inject = ['ChartService'];

    /* jshint ignore:start */
    function controller(ChartService) {
        const vm = this;
        vm.changeTab = changeTab;
        vm.registerTab = registerTab;
        vm.unregisterTab = unregisterTab;
        vm.getChartsData = getChartsData;
        vm.reloadTabs = reloadTabs;
        const tabs = [];

        function changeTab(tabName, chartsData) {
            if (tabs.find(t => t.name === tabName))
                tabs.find(t => t.name === tabName).reload(chartsData);
        }

        function reloadTabs(chartsData) {
            tabs.forEach(t => t.reload(chartsData));
        }

        function registerTab(tab) {
            tabs.push(tab);
        }

        function unregisterTab(tab) {
            _.remove(tabs, tab);
        }

        async function getChartsData(researchEntity, refresh = true) {
            const res = await ChartService.getData(researchEntity, [
                'journalsByYear',
                'conferencesByYear',
                'booksByYear',
                'bookChaptersByYear',
                'disseminationTalksByYear',
                'scientificTalksByYear',
                'documentsByType',
                'filteredAffiliatedJournalsByYear',
                'filteredAffiliatedConferencesByYear',
                'filteredAffiliatedBooksByYear',
                'filteredAffiliatedBookChaptersByYear',
                'filteredNotAffiliatedJournalsByYear',
                'filteredNotAffiliatedConferencesByYear',
                'filteredNotAffiliatedBooksByYear',
                'filteredNotAffiliatedBookChaptersByYear',
                'hindexPerYear',
                'citationsPerYear',
                'citationsPerDocumentYear',
                'totalIfPerYear',
                'totalSjrPerYear',
                'totalSnipPerYear',
                'chartDataDate'
            ], refresh && researchEntity.id !== 1);
            return res[0];
        }
    }

    /* jshint ignore:end */
})();
<commit_msg>Refactor<commit_after>(function () {
    angular
        .module('summary')
        .controller('SummaryInterfaceController', controller);

    controller.$inject = ['ChartService'];

    /* jshint ignore:start */
    function controller(ChartService) {
        const vm = this;
        vm.changeTab = changeTab;
        vm.registerTab = registerTab;
        vm.unregisterTab = unregisterTab;
        vm.getChartsData = getChartsData;
        vm.reloadTabs = reloadTabs;
        const tabs = [];

        function changeTab(tabName, chartsData) {
            if (tabs.find(t => t.name === tabName))
                tabs.find(t => t.name === tabName).reload(chartsData);
        }

        function reloadTabs(chartsData) {
            tabs.forEach(t => t.reload(chartsData));
        }

        function registerTab(tab) {
            tabs.push(tab);
        }

        function unregisterTab(tab) {
            _.remove(tabs, tab);
        }

        async function getChartsData(researchEntity, refresh = true) {
            const res = await ChartService.getData(researchEntity, [
                'journalsByYear',
                'conferencesByYear',
                'booksByYear',
                'bookChaptersByYear',
                'disseminationTalksByYear',
                'scientificTalksByYear',
                'documentsByType',
                'filteredAffiliatedJournalsByYear',
                'filteredAffiliatedConferencesByYear',
                'filteredAffiliatedBooksByYear',
                'filteredAffiliatedBookChaptersByYear',
                'filteredNotAffiliatedJournalsByYear',
                'filteredNotAffiliatedConferencesByYear',
                'filteredNotAffiliatedBooksByYear',
                'filteredNotAffiliatedBookChaptersByYear',
                'hindexPerYear',
                'citationsPerYear',
                'citationsPerDocumentYear',
                'totalIfPerYear',
                'totalSjrPerYear',
                'totalSnipPerYear',
                'chartDataDate'
            ], refresh && researchEntity.type !== 'Institute');
            return res[0];
        }
    }

    /* jshint ignore:end */
})();
<|endoftext|>