<commit_before>'use strict'

import {Component}          from 'react'
import {Link}               from 'react-router'
import DocumentTitle        from 'react-document-title'
import {bindActionCreators} from 'redux'
import {connect}            from 'react-redux'
import {BlogActions}       from '../datastore/Blog'
import {StatsActions}      from '../datastore/Stats'
import Image               from '../components/Image'
import Alert               from '../components/Alert'
import Header              from '../components/Header'
import EmbedYouTube        from '../components/EmbedYouTube'
import MultiVideoPlayer    from '../components/MultiVideoPlayer'
import MailchimpForm       from '../components/MailchimpForm'
import PostPreview         from '../components/PostPreview'
import {featuredApps}      from '../config'
import ModalVideo          from 'react-modal-video'

function mapStateToProps(state) {
  return {
    posts: state.blog.posts,
    stats: state.stats,
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(
    Object.assign({}, BlogActions, StatsActions),
    dispatch
  )
}

class HomePage extends Component {

  constructor(props) {
    super(props)

    this.state = {
      videoOpen: false,
      stats: this.props.stats,
      posts: this.props.posts
    }

    this.openModal = this.openModal.bind(this)
  }

  componentWillMount() {
    if (this.props.posts.length === 0) {
      this.props.fetchPosts()
    }
    this.props.fetchStats()
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.stats !== this.props.stats) {
      let stats = nextProps.stats
      if (stats.domains === 0) {
        stats.domains = 72000
      }
      this.setState({
        stats: stats,
      })
    }

    if (nextProps.posts !== this.props.posts) {
      this.setState({
        posts: nextProps.posts,
      })
    }
  }

  openModal() {
    this.setState({ videoOpen: true })
  }

  render() {
    const subscribeURL = '//blockstack.us14.list-manage.com/subscribe/post?u=394a2b5cfee9c4b0f7525b009&id=0e5478ae86'

    return (
      <DocumentTitle title="What is Blockstack?">

                What is Blockstack?

                Blockstack is a decentralized app ecosystem where users own and control their data. Blockstack{`'`}s platform helps entrepreneurs and engineers build these apps and deliver better end-user experiences.

              <Link to="install" className="btn btn-primary">Download Blockstack</Link>

                How it works

1

Explore a new world of decentralized apps

                        Join our community as we re-envision apps for social, gaming, finance, and everything in between.

For users

Discover the latest decentralized apps on the Blockstack platform.

Use your trusted ID across all your apps.

Share and manage your data how you want.

For developers

Join an active community driven by decentralized philosophy.

Distribute apps quickly with our development platform.

Get in early on building with Web 3.0 technology.

2

Truly own your data

                        Web corporations today assume complete ownership over your data and abuse it for their benefit. With Blockstack, we simplify data ownership and give you back control.

For users

Choose where to store your data, whether on a cloud provider or your own personal server.

Decide who has access to your data and when.

Relax knowing your data is end-to-end encrypted with keys that only you hold.

For developers

Build serverless apps easier than ever before.

Streamline your application code by using Blockstack auth and storage services.

Don't worry about data liability since users provide their encrypted data.

3

One identity, infinite apps.

                        Your Blockstack ID is your login for Blockstack apps. By verifying identities on other social platforms, users can be confident they're interacting with trusted people in their network. Under the hood, Blockstack creates a unique blockchain record for each user identity created.

For users

Log in to every app safely with the same account.

Quickly check that people you interact with are trustworthy.

Add verifications to your profile to increase your trust rating.

For developers

Take the pain out of managing user accounts.

Access meta information like social URLs, email addresses, and more.

Leverage an easy to use account search API to connect users to one another.

                Join the new internet

                We envision a decentralized internet where users take control of their own identity and data, without having to rely on intermediaries.

              <Link to="/install" className="btn btn-primary">Download Blockstack</Link>

Resources

Videos

Our video section is a great place to find past presentations, Q&A sessions with cofounders Muneeb & Ryan, and more.

                  <Link to="/videos" className="btn btn-outline-primary mt-3">Watch videos</Link>

Papers

Our whitepapers are the best place to start for a technical deep-dive into the Blockstack vision.

                  <Link to="/papers" className="btn btn-outline-primary mt-3">Read whitepapers</Link>

About Blockstack

Read about our history, values, and core team. Find out why we're a Public Benefit Corporation.

                  <Link to="/about" className="btn btn-outline-primary mt-3">About Blockstack</Link>

      </DocumentTitle>
    )
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(HomePage)
<commit_msg>what is blockstack step 3 title change<commit_after>'use strict'

import {Component}          from 'react'
import {Link}               from 'react-router'
import DocumentTitle        from 'react-document-title'
import {bindActionCreators} from 'redux'
import {connect}            from 'react-redux'
import {BlogActions}       from '../datastore/Blog'
import {StatsActions}      from '../datastore/Stats'
import Image               from '../components/Image'
import Alert               from '../components/Alert'
import Header              from '../components/Header'
import EmbedYouTube        from '../components/EmbedYouTube'
import MultiVideoPlayer    from '../components/MultiVideoPlayer'
import MailchimpForm       from '../components/MailchimpForm'
import PostPreview         from '../components/PostPreview'
import {featuredApps}      from '../config'
import ModalVideo          from 'react-modal-video'

function mapStateToProps(state) {
  return {
    posts: state.blog.posts,
    stats: state.stats,
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(
    Object.assign({}, BlogActions, StatsActions),
    dispatch
  )
}

class HomePage extends Component {

  constructor(props) {
    super(props)

    this.state = {
      videoOpen: false,
      stats: this.props.stats,
      posts: this.props.posts
    }

    this.openModal = this.openModal.bind(this)
  }

  componentWillMount() {
    if (this.props.posts.length === 0) {
      this.props.fetchPosts()
    }
    this.props.fetchStats()
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.stats !== this.props.stats) {
      let stats = nextProps.stats
      if (stats.domains === 0) {
        stats.domains = 72000
      }
      this.setState({
        stats: stats,
      })
    }

    if (nextProps.posts !== this.props.posts) {
      this.setState({
        posts: nextProps.posts,
      })
    }
  }

  openModal() {
    this.setState({ videoOpen: true })
  }

  render() {
    const subscribeURL = '//blockstack.us14.list-manage.com/subscribe/post?u=394a2b5cfee9c4b0f7525b009&id=0e5478ae86'

    return (
      <DocumentTitle title="What is Blockstack?">

                What is Blockstack?

                Blockstack is a decentralized app ecosystem where users own and control their data. Blockstack{`'`}s platform helps entrepreneurs and engineers build these apps and deliver better end-user experiences.

              <Link to="install" className="btn btn-primary">Download Blockstack</Link>

                How it works

1

Explore a new world of decentralized apps

                        Join our community as we re-envision apps for social, gaming, finance, and everything in between.

For users

Discover the latest decentralized apps on the Blockstack platform.

Use your trusted ID across all your apps.

Share and manage your data how you want.

For developers

Join an active community driven by decentralized philosophy.

Distribute apps quickly with our development platform.

Get in early on building with Web 3.0 technology.

2

Truly own your data

                        Web corporations today assume complete ownership over your data and abuse it for their benefit. With Blockstack, we simplify data ownership and give you back control.

For users

Choose where to store your data, whether on a cloud provider or your own personal server.

Decide who has access to your data and when.

Relax knowing your data is end-to-end encrypted with keys that only you hold.

For developers

Build serverless apps easier than ever before.

Streamline your application code by using Blockstack auth and storage services.

Don't worry about data liability since users provide their encrypted data.

3

Access infinite apps with a single account

                        Your Blockstack ID is your login for Blockstack apps. By verifying identities on other social platforms, users can be confident they're interacting with trusted people in their network. Under the hood, Blockstack creates a unique blockchain record for each user identity created.

For users

Log in to every app safely with the same account.

Quickly check that people you interact with are trustworthy.

Add verifications to your profile to increase your trust rating.

For developers

Take the pain out of managing user accounts.

Access meta information like social URLs, email addresses, and more.

Leverage an easy to use account search API to connect users to one another.

                Join the new internet

                We envision a decentralized internet where users take control of their own identity and data, without having to rely on intermediaries.

              <Link to="/install" className="btn btn-primary">Download Blockstack</Link>

Resources

Videos

Our video section is a great place to find past presentations, Q&A sessions with cofounders Muneeb & Ryan, and more.

                  <Link to="/videos" className="btn btn-outline-primary mt-3">Watch videos</Link>

Papers

Our whitepapers are the best place to start for a technical deep-dive into the Blockstack vision.

                  <Link to="/papers" className="btn btn-outline-primary mt-3">Read whitepapers</Link>

About Blockstack

Read about our history, values, and core team. Find out why we're a Public Benefit Corporation.

                  <Link to="/about" className="btn btn-outline-primary mt-3">About Blockstack</Link>

      </DocumentTitle>
    )
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(HomePage)
<|endoftext|>


<commit_before>const util = require('util')
const cp = require('child_process')
const fs = require('fs')
const path = require('path')
const { remote: { app } } = require('electron')

//const writeFile = util.promisify(fs.writeFile)

const TMP_FILE = `${app.getPath('userData')}/output.json`

/*async*/ function parse (filename) {
  return new Promise((resolve, reject) => {
    cp.exec(`rattletrap decode "${filename}" "${TMP_FILE}"`, function (error, stdout, stderr) {
      if (stderr) {
        reject(stderr)
      }

      const body = fs.readFileSync(path.resolve(TMP_FILE))

      resolve(JSON.parse(body))
    })
  })
  //const { stdout, stderr } = await exec(`${RT} decode ${filename} ${TMP_FILE}`)
}

function filter (tree) {
  return {
    playerStats: getPlayerStats(tree)
  }
}

function getPlayerStats (tree) {
  let players = tree.header.properties.value.PlayerStats.value.array_property

  players = players.map(player => {
    // TODO
    // const player = _.cloneDeep(player)

    player = getValues(player)
    player.Platform = player.Platform[player.Platform.length - 1]
    return player
  })

  return players
  //console.log(JSON.stringify(players, null, '\t'))
}

function getValues (o) {
  const mapped = {}

  o.keys.forEach(k => {
    const wrapped = o.value[k].value

    if (Object.keys(wrapped).length !== 1) {
      console.warn(`Expected a property to have one key, but it looks like:\n${JSON.stringify(wrapped)}`)
    }

    mapped[k] = wrapped[Object.keys(wrapped)[0]]
  })

  return mapped
}

const columns = [
  'Name', 'Team', /*'MVPs',*/ 'Pts', 'Goals', 'Assists', 'Saves', 'Shots'
]

const aliases = {
  Pts: 'Score'
}

function spreadsheet (games, delimiter = '\t') {
  const headers = columns.map(column => {
    return `"${column}"`
  }).join(delimiter)

  const players = games.map(playerStats => {
    return playerStats.sort((a, b) => {
      return (a.Team - b.Team) || (b.Score - a.Score)
    }).map(player => {
      return columns.map(column => {
        let prop = aliases[column]
        if (typeof prop === 'undefined') {
          prop = column
        }
        /*if (typeof value === 'undefined') {
        value = ''
      }*/
        const value = typeof player[prop] === 'undefined' ? '' : player[prop]
        return `"${value}"`
      }).join(delimiter)
    })
  })

  return [headers].concat(flatten(players)).join('\r\n')
}

const inputDirectory = process.argv[2]

module.exports = function (/*inputDirectory,*/inputFiles) {
  /*Promise.all(fs.readdirSync(path.resolve(inputDirectory))*/
  return Promise.all(inputFiles
    .filter(filename => !!filename.match(/\.replay$/))
    .map(f => path.resolve(/*inputDirectory,*/process.cwd, f))
    .map(parse))
    .then(results => {
      const gameStats = results
        .map(filter)
        .map(f => f.playerStats)
      return spreadsheet(gameStats)
    })

}

function flatten (arrays) {
  return arrays.reduce(
    ( acc, cur ) => acc.concat(cur),
    []
  );
}
<commit_msg>Parse files one at a time<commit_after>const util = require('util')
const cp = require('child_process')
const fs = require('fs')
const path = require('path')
const { remote: { app } } = require('electron')

//const writeFile = util.promisify(fs.writeFile)

const TMP_FILE = `${app.getPath('userData')}/output.json`

/*async*/ function parse (filename) {
  return new Promise((resolve, reject) => {
    cp.exec(`rattletrap decode "${filename}" "${TMP_FILE}"`, function (error, stdout, stderr) {
      if (stderr) {
        reject(stderr)
      }

      const body = fs.readFileSync(path.resolve(TMP_FILE))

      resolve(JSON.parse(body))
    })
  })
  //const { stdout, stderr } = await exec(`${RT} decode ${filename} ${TMP_FILE}`)
}

function filter (tree) {
  return {
    playerStats: getPlayerStats(tree)
  }
}

function getPlayerStats (tree) {
  let players = tree.header.properties.value.PlayerStats.value.array_property

  players = players.map(player => {
    // TODO
    // const player = _.cloneDeep(player)

    player = getValues(player)
    player.Platform = player.Platform[player.Platform.length - 1]
    return player
  })

  return players
  //console.log(JSON.stringify(players, null, '\t'))
}

function getValues (o) {
  const mapped = {}

  o.keys.forEach(k => {
    const wrapped = o.value[k].value

    if (Object.keys(wrapped).length !== 1) {
      console.warn(`Expected a property to have one key, but it looks like:\n${JSON.stringify(wrapped)}`)
    }

    mapped[k] = wrapped[Object.keys(wrapped)[0]]
  })

  return mapped
}

const columns = [
  'Name', 'Team', /*'MVPs',*/ 'Pts', 'Goals', 'Assists', 'Saves', 'Shots'
]

const aliases = {
  Pts: 'Score'
}

function spreadsheet (games, delimiter = '\t') {
  const headers = columns.map(column => {
    return `"${column}"`
  }).join(delimiter)

  const players = games.map(playerStats => {
    return playerStats.sort((a, b) => {
      return (a.Team - b.Team) || (b.Score - a.Score)
    }).map(player => {
      return columns.map(column => {
        let prop = aliases[column]
        if (typeof prop === 'undefined') {
          prop = column
        }
        /*if (typeof value === 'undefined') {
        value = ''
      }*/
        const value = typeof player[prop] === 'undefined' ? '' : player[prop]
        return `"${value}"`
      }).join(delimiter)
    })
  })

  return [headers].concat(flatten(players)).join('\r\n')
}

const inputDirectory = process.argv[2]

module.exports = function (/*inputDirectory,*/inputFiles) {
  /*Promise.all(fs.readdirSync(path.resolve(inputDirectory))*/

  const paths = inputFiles
    .filter(filename => !!filename.match(/\.replay$/))
    .map(f => path.resolve(/*inputDirectory,*/process.cwd, f))

    // Serially parse each path and add the results to an array that this
    // promise resolves with.
    const resultsPromise = paths.reduce((memo, path) => {
      return memo.then(results => {
        return parse(path)
          .then(singleResult => {
            results.push(singleResult)
            return Promise.resolve(results)
          })
      })
    }, Promise.resolve([]))

  return resultsPromise
    .then(results => {
      const gameStats = results
        .map(filter)
        .map(f => f.playerStats)
      return spreadsheet(gameStats)
    })

}

function flatten (arrays) {
  return arrays.reduce(
    ( acc, cur ) => acc.concat(cur),
    []
  );
}
<|endoftext|>


<commit_before>'use strict';

var ngApp = angular.module('jmp.carousel', []);

(function (app) {

    CarouselController.prototype.start = start;
    CarouselController.prototype.Carousel = Carousel;

	// Directive default options
	var defaultOptions = {
		rtl: false,
		loop: true,
		margin: 10,
		nav: true
	};

    app.directive('owlCarousel', ['$timeout', function($timeout) {
        return {
            restrict: 'EA',
            controller: CarouselController,
            scope: {
				owlCarousel: '=',
				owlInstance: '&'
            },
            transclude: true,
            template: '

',
            link: function (scope, element, attrs, controller) {
            	// Owl carousel options holder
				scope.options = {};

				// Owl Carousel
            	scope.carousel = null;

            	// Start owl carousel
				$timeout(function () { init(); });

                scope.$watch('owlCarousel', function (nval) {
                	if (nval) {
                		scope.options = setOptions(nval);
					}
				});

				scope.$on('$destroy', destroy);

                function init() {
                	scope.$apply(function () {
						scope.carousel = element.find('.owl-carousel');
						scope.carousel.owlCarousel(scope.options);
						controller.start(scope.carousel);

						if (scope.owlInstance) {
							scope.owlInstance({ $owl: controller.Carousel() });
						}
					});
                }
                function setOptions(o) {
                	var options = angular.extend({}, defaultOptions, 0);

                	if (o) {
                		for (var key in o) {
                			if (o.hasOwnProperty(key)) {
                				options[key] = o[key];
							}
						}
					}
					return options;
				}
				function destroy() {
                	var stage = element.find('.owl-stage');
					controller.Carousel().trigger('destroy.owl.carousel');

					if (stage.length) {
						stage.remove();
					}
				}
            }
        };
    }]);

    function CarouselController() {
        this.instance = {};
    }

    function start() {
        this.instance = arguments[0];
    }
    function Carousel() {
        var self = this;
        return {
            trigger: trigger
        };

		/**
		 * @param selector
		 * @param {[*]} speed
		 */
		function trigger(selector, speed) {
			// Allow to just input a number instead of an array
			if (!angular.isArray(speed)) {
				speed = [speed];
				arguments[1] = speed;
			}

            self.instance.trigger.apply(self.instance, arguments);
        }
    }
}(ngApp));
<commit_msg>fixed trigger method<commit_after>'use strict';

var ngApp = angular.module('jmp.carousel', []);

(function (app) {

    CarouselController.prototype.start = start;
    CarouselController.prototype.Carousel = Carousel;

	// Directive default options
	var defaultOptions = {
		rtl: false,
		loop: true,
		margin: 10,
		nav: true
	};

    app.directive('owlCarousel', ['$timeout', function($timeout) {
        return {
            restrict: 'EA',
            controller: CarouselController,
            scope: {
				owlCarousel: '=',
				owlInstance: '&'
            },
            transclude: true,
            template: '

',
            link: function (scope, element, attrs, controller) {
            	// Owl carousel options holder
				scope.options = {};

				// Owl Carousel
            	scope.carousel = null;

            	// Start owl carousel
				$timeout(function () { init(); });

                scope.$watch('owlCarousel', function (nval) {
                	if (nval) {
                		scope.options = setOptions(nval);
					}
				});

				scope.$on('$destroy', destroy);

                function init() {
                	scope.$apply(function () {
						scope.carousel = element.find('.owl-carousel');
						scope.carousel.owlCarousel(scope.options);
						controller.start(scope.carousel);

						if (scope.owlInstance) {
							scope.owlInstance({ $owl: controller.Carousel() });
						}
					});
                }
                function setOptions(o) {
                	var options = angular.extend({}, defaultOptions, 0);

                	if (o) {
                		for (var key in o) {
                			if (o.hasOwnProperty(key)) {
                				options[key] = o[key];
							}
						}
					}
					return options;
				}
				function destroy() {
                	var stage = element.find('.owl-stage');
					controller.Carousel().trigger('destroy.owl.carousel');

					if (stage.length) {
						stage.remove();
					}
				}
            }
        };
    }]);

    function CarouselController() {
        this.instance = {};
    }

    function start() {
        this.instance = arguments[0];
    }
    function Carousel() {
        var self = this;
        return {
            trigger: trigger
        };

		/**
		 * @param selector
		 * @param {[*]} speed
		 */
		function trigger(selector, speed) {
			// Allow to just input a number instead of an array
			if (!angular.isArray(speed)) {
				speed = [speed];
				arguments[1] = speed;
			}

			if (self.instance.hasOwnProperty('trigger')) {
				self.instance.trigger.apply(self.instance, arguments);
			}
        }
    }
}(ngApp));
<|endoftext|>


<commit_before>var eassApp = angular.module(
	"eassApp",
	[
		'ngAnimate'
	]
);

eassApp
.controller('HomeImgCtrl',
[
'$scope', '$timeout',
function($scope, $timeout)
{
	$scope.slides = [
		{name: 'renhold'},
		{name: 'kantine'},
		{name: 'vaktmesterservice'}
	];

	$scope.id = 1;

	$scope.to = null;

	$scope.change = function( id ) {
		$scope.id = id;

		$timeout.cancel($scope.to);
	};

	$scope.isCurrent = function (index) {
		return $scope.id === index;
	};

	$scope.reset = function() {
		$scope.to = $timeout($scope.tick, 2000);
	};

	$scope.tick = function () {
		if ( $scope.id == 2 ) {
			$scope.id = 0;
		} else {
			$scope.id++;
		}

		$scope.to = $timeout($scope.tick, 2000);
	};

	$scope.go = function( path ) {
		$timeout(function() {
			angular.element('#'+path).click();
		}, 0, false);
	};

	$scope.tick();
}
]
);

eassApp
.controller('SidebarPageCtrl',
[
'$scope', '$location', '$compile',
function($scope, $location, $compile)
{
	var headers = angular.element(".panel-body h3" );

	if ( headers.length <= 1 ) {
		// Nothing to partition
		return;
	}

	$scope.choices = [];

	var checkExisting = function( name ) {
		if ( $scope.choices.length == 0 ) return false;

		for ( var i=0; i<$scope.choices.length; i++ ) {
			if ( $scope.choices[i].id == name ) return true;
		}

		return false;
	};

	var i = 0;

	angular.forEach(headers, function(value, key){
		i++;

		var element = {
			id: angular.element(value).html().toLowerCase().replace(/[^a-z0-9]/gi,''),
			title: angular.element(value).html()
		};

		if ( !checkExisting(element.id) ) {
			$scope.choices.push(element);
		}

		var content = angular.element(value).nextUntil("h3").andSelf();

		var newhtml = '';

		var replace;

		for ( var j=0; j<content.length; j++ ) {
			newhtml += angular.element(content[j]).clone().wrap('
').parent().html();

			if ( j < content.length-1 ) {
				angular.element(content[j]).remove();

				delete content[j];
			} else {
				replace = content[j];
			}
		}

		newhtml = newhtml.replace('

', '
');

		angular.element(replace).replaceWith(
			$compile(
				'
'
				+ newhtml
				+ '
'
			)($scope)
		);
	});

	$scope.change = function( name ) {
		if ( $scope.id === name ) {
			return;
		} else {
			$scope.id = name;
		}

		$location.hash($scope.id);
	};

	$scope.isDeselected = function ( name ) {
		return $scope.id !== name && $scope.id != '';
	};

	$scope.isSelected = function ( name ) {
		return $scope.id === name;
	};

	$scope.id = $location.hash();

	if ( $scope.id == '' ) {
		$scope.change( $scope.choices[0].id );
	}
}
]
);

eassApp
.controller('SidebarPageListCtrl',
[
'$scope', '$location', '$compile', '$timeout',
function($scope, $location, $compile, $timeout)
{
	var list = angular.element(".panel-body ul li");

	if ( list.length <= 1 ) {
		// Nothing to partition
		return;
	}

	var headers = angular.element(".panel-body h4" );

	if ( headers.length <= 1 ) {
		// Nothing to partition
		return;
	}

	$scope.choices = [];

	angular.forEach(list, function(value, key) {
		$scope.choices.push(
			{
				id: angular.element(value).html().toLowerCase().replace(/[^a-z0-9]/gi,''),
				title: angular.element(value).html()
			}
		);
	});

	angular.element(".panel-body ul" ).remove();

	var i = 0;
	angular.forEach(headers, function(value, key) {
		i++;

		var element = {
			id: angular.element(value).html().toLowerCase().replace(/[^a-z0-9]/gi,''),
			title: angular.element(value).html()
		};

		var content = angular.element(value).nextUntil("h4").andSelf();

		var newhtml = '';

		var id;

		var replace;

		var name = '';

		var inner = '';

		for ( var j=0; j<content.length; j++ ) {
			var el = angular.element(content[j]);

			inner = el.clone().wrap('
').parent().html();

			if ( name == '' ) {
				elname = el.html().toLowerCase().replace(/[^a-z0-9]/gi,'');

				angular.forEach($scope.choices, function(value, key) {
					if ( elname == value.id ) {
						name = value.id;

						if ( el.context.localName != 'h4' ) {
							inner = '';
						}
					}
				});
			}

			newhtml += inner;

			if ( j < content.length-1 ) {
				angular.element(content[j]).remove();

				delete content[j];
			} else {
				replace = content[j];
			}
		}

		newhtml = newhtml.split('

').join('
');

		angular.element(replace).replaceWith(
			$compile(
				'
'
					+ newhtml
					+ '
'
				+ '
'
			)($scope)
		);
	});

	$scope.lines = function () {
		angular.element('hr.fullwidth').removeClass('ng-enter ng-enter-active').addClass('ng-leave-active');

		var el = angular.element('.kontakt-container:not(.am-slide-top):odd')
			.next('hr');

		el.removeClass('ng-leave ng-leave-active').addClass('ng-enter');

		$timeout(function(){
			el.addClass('ng-enter-active');
		}, 300);
	};

	$scope.change = function( name ) {
		angular.element('hr.fullwidth').removeClass('ng-enter ng-enter-active').addClass('ng-leave');

		if ( $scope.id === name ) {
			$scope.id = '';
		} else {
			$scope.id = name;
		}

		$location.hash($scope.id);

		$timeout($scope.lines, 300);
	};

	$scope.isDeselected = function ( name ) {
		return $scope.id !== name && $scope.id != '';
	};

	$scope.isSelected = function ( name ) {
		return $scope.id === name;
	};

	$scope.id = $location.hash();

	$timeout($scope.lines, 300);
}
]
);

eassApp
.controller('ContactCtrl',
[
'$scope',
function($scope) {
	$scope.id = '';

	$scope.change = function( name ) {
		if ( $scope.id === name ) {
			$scope.id = '';
		} else {
			$scope.id = name;
		}
	};

	$scope.isDeselected = function ( name ) {
		return $scope.id !== name && $scope.id != '';
	};

	$scope.isSelected = function ( name ) {
		return $scope.id === name;
	};
}
]
);
<commit_msg>trying to go even lower with 2 columns on contact<commit_after>var eassApp = angular.module(
	"eassApp",
	[
		'ngAnimate'
	]
);

eassApp
.controller('HomeImgCtrl',
[
'$scope', '$timeout',
function($scope, $timeout)
{
	$scope.slides = [
		{name: 'renhold'},
		{name: 'kantine'},
		{name: 'vaktmesterservice'}
	];

	$scope.id = 1;

	$scope.to = null;

	$scope.change = function( id ) {
		$scope.id = id;

		$timeout.cancel($scope.to);
	};

	$scope.isCurrent = function (index) {
		return $scope.id === index;
	};

	$scope.reset = function() {
		$scope.to = $timeout($scope.tick, 2000);
	};

	$scope.tick = function () {
		if ( $scope.id == 2 ) {
			$scope.id = 0;
		} else {
			$scope.id++;
		}

		$scope.to = $timeout($scope.tick, 2000);
	};

	$scope.go = function( path ) {
		$timeout(function() {
			angular.element('#'+path).click();
		}, 0, false);
	};

	$scope.tick();
}
]
);

eassApp
.controller('SidebarPageCtrl',
[
'$scope', '$location', '$compile',
function($scope, $location, $compile)
{
	var headers = angular.element(".panel-body h3" );

	if ( headers.length <= 1 ) {
		// Nothing to partition
		return;
	}

	$scope.choices = [];

	var checkExisting = function( name ) {
		if ( $scope.choices.length == 0 ) return false;

		for ( var i=0; i<$scope.choices.length; i++ ) {
			if ( $scope.choices[i].id == name ) return true;
		}

		return false;
	};

	var i = 0;

	angular.forEach(headers, function(value, key){
		i++;

		var element = {
			id: angular.element(value).html().toLowerCase().replace(/[^a-z0-9]/gi,''),
			title: angular.element(value).html()
		};

		if ( !checkExisting(element.id) ) {
			$scope.choices.push(element);
		}

		var content = angular.element(value).nextUntil("h3").andSelf();

		var newhtml = '';

		var replace;

		for ( var j=0; j<content.length; j++ ) {
			newhtml += angular.element(content[j]).clone().wrap('
').parent().html();

			if ( j < content.length-1 ) {
				angular.element(content[j]).remove();

				delete content[j];
			} else {
				replace = content[j];
			}
		}

		newhtml = newhtml.replace('

', '
');

		angular.element(replace).replaceWith(
			$compile(
				'
'
				+ newhtml
				+ '
'
			)($scope)
		);
	});

	$scope.change = function( name ) {
		if ( $scope.id === name ) {
			return;
		} else {
			$scope.id = name;
		}

		$location.hash($scope.id);
	};

	$scope.isDeselected = function ( name ) {
		return $scope.id !== name && $scope.id != '';
	};

	$scope.isSelected = function ( name ) {
		return $scope.id === name;
	};

	$scope.id = $location.hash();

	if ( $scope.id == '' ) {
		$scope.change( $scope.choices[0].id );
	}
}
]
);

eassApp
.controller('SidebarPageListCtrl',
[
'$scope', '$location', '$compile', '$timeout',
function($scope, $location, $compile, $timeout)
{
	var list = angular.element(".panel-body ul li");

	if ( list.length <= 1 ) {
		// Nothing to partition
		return;
	}

	var headers = angular.element(".panel-body h4" );

	if ( headers.length <= 1 ) {
		// Nothing to partition
		return;
	}

	$scope.choices = [];

	angular.forEach(list, function(value, key) {
		$scope.choices.push(
			{
				id: angular.element(value).html().toLowerCase().replace(/[^a-z0-9]/gi,''),
				title: angular.element(value).html()
			}
		);
	});

	angular.element(".panel-body ul" ).remove();

	var i = 0;
	angular.forEach(headers, function(value, key) {
		i++;

		var element = {
			id: angular.element(value).html().toLowerCase().replace(/[^a-z0-9]/gi,''),
			title: angular.element(value).html()
		};

		var content = angular.element(value).nextUntil("h4").andSelf();

		var newhtml = '';

		var id;

		var replace;

		var name = '';

		var inner = '';

		for ( var j=0; j<content.length; j++ ) {
			var el = angular.element(content[j]);

			inner = el.clone().wrap('
').parent().html();

			if ( name == '' ) {
				elname = el.html().toLowerCase().replace(/[^a-z0-9]/gi,'');

				angular.forEach($scope.choices, function(value, key) {
					if ( elname == value.id ) {
						name = value.id;

						if ( el.context.localName != 'h4' ) {
							inner = '';
						}
					}
				});
			}

			newhtml += inner;

			if ( j < content.length-1 ) {
				angular.element(content[j]).remove();

				delete content[j];
			} else {
				replace = content[j];
			}
		}

		newhtml = newhtml.split('

').join('
');

		angular.element(replace).replaceWith(
			$compile(
				'
'
					+ newhtml
					+ '
'
				+ '
'
			)($scope)
		);
	});

	$scope.lines = function () {
		angular.element('hr.fullwidth').removeClass('ng-enter ng-enter-active').addClass('ng-leave-active');

		var el = angular.element('.kontakt-container:not(.am-slide-top):odd')
			.next('hr');

		el.removeClass('ng-leave ng-leave-active').addClass('ng-enter');

		$timeout(function(){
			el.addClass('ng-enter-active');
		}, 300);
	};

	$scope.change = function( name ) {
		angular.element('hr.fullwidth').removeClass('ng-enter ng-enter-active').addClass('ng-leave');

		if ( $scope.id === name ) {
			$scope.id = '';
		} else {
			$scope.id = name;
		}

		$location.hash($scope.id);

		$timeout($scope.lines, 300);
	};

	$scope.isDeselected = function ( name ) {
		return $scope.id !== name && $scope.id != '';
	};

	$scope.isSelected = function ( name ) {
		return $scope.id === name;
	};

	$scope.id = $location.hash();

	$timeout($scope.lines, 300);
}
]
);

eassApp
.controller('ContactCtrl',
[
'$scope',
function($scope) {
	$scope.id = '';

	$scope.change = function( name ) {
		if ( $scope.id === name ) {
			$scope.id = '';
		} else {
			$scope.id = name;
		}
	};

	$scope.isDeselected = function ( name ) {
		return $scope.id !== name && $scope.id != '';
	};

	$scope.isSelected = function ( name ) {
		return $scope.id === name;
	};
}
]
);
<|endoftext|>


<commit_before>/* eslint-disable no-shadow */
import React, { Component } from 'react';
import { connect } from 'react-redux';
import styled from 'styled-components';
import {
  StyleSheet,
  RefreshControl,
  Share,
  ActivityIndicator,
} from 'react-native';
import { ListItem } from 'react-native-elements';
import ActionSheet from 'react-native-actionsheet';
import { RestClient } from 'api';
import {
  ViewContainer,
  LoadingRepositoryProfile,
  RepositoryProfile,
  MembersList,
  SectionList,
  ParallaxScroll,
  LoadingUserListItem,
  UserListItem,
  IssueListItem,
  LoadingMembersList,
  TopicsList,
} from 'components';
import {
  translate,
  openURLInView,
  toOldIssueFormat,
  toOldUserFormat,
} from 'utils';
import { colors, fonts } from 'config';

const mapStateToProps = (state, ownProps) => {
  const {
    auth: { user, locale },
    entities: { gqlRepos, users, repos },
    pagination: { REPOS_GET_CONTRIBUTORS },
  } = state;

  const params = ownProps.navigation.state.params;

  const repoId =
    params.repoId ||
    params.repository.url
      .replace('https://api.github.com/repos/', '')
      .toLowerCase();

  const repository = gqlRepos[repoId] || repos[repoId] || params.repository;

  const contributorsPagination = REPOS_GET_CONTRIBUTORS[repoId] || {
    ids: [],
    isFetching: true,
  };
  const contributors = contributorsPagination.ids.map(id => users[id]);

  return {
    username: user.login,
    contributors,
    contributorsPagination,
    repository,
    repoId,
    locale,
  };
};

const mapDispatchToProps = {
  getRepoById: RestClient.graphql.getRepo,
  getContributors: RestClient.repos.getContributors,
  starRepo: RestClient.activity.starRepo,
  unstarRepo: RestClient.activity.unstarRepo,
  watchRepo: RestClient.activity.watchRepo,
  unwatchRepo: RestClient.activity.unwatchRepo,
  forkRepo: RestClient.repos.fork,
};

const LoadingMembersContainer = styled.View`
  padding: 5px;
`;

const styles = StyleSheet.create({
  listTitle: {
    color: colors.black,
    ...fonts.fontPrimary,
  },
  listContainerStyle: {
    borderBottomColor: colors.greyLight,
    borderBottomWidth: 1,
  },
});

class Repository extends Component {
  props: {
    getRepoById: Function,
    getContributors: Function,
    starRepo: Function,
    unstarRepo: Function,
    watchRepo: Function,
    unwatchRepo: Function,
    forkRepo: Function,
    repository: Object,
    repoId: String,
    contributors: Array,
    contributorsPagination: Object,
    navigation: Object,
    username: string,
    locale: string,
  };

  state: {
    refreshing: boolean,
    isChangingStar: boolean,
    isChangingSubscription: boolean,
    hasError: boolean,
  };

  constructor(props) {
    super(props);
    this.state = {
      refreshing: false,
      isChangingStar: false,
      isChangingSubscription: false,
      hasError: false,
      errorMessage: '',
    };
  }

  componentDidMount() {
    const { repoId, getRepoById, getContributors } = this.props;

    getRepoById(repoId)
      .then(() => {
        getContributors(repoId);
      })
      .catch(error => {
        this.setState({ hasError: true, errorMessage: error });
      });
  }

  showMenuActionSheet = () => {
    this.ActionSheet.show();
  };

  handlePress = index => {
    const {
      repository,
      repoId,
      forkRepo,
      starRepo,
      unstarRepo,
      watchRepo,
      unwatchRepo,
      navigation,
      username,
    } = this.props;

    const showFork = repository.owner.login !== username;

    if (index === 0) {
      this.setState({ isChangingStar: true });
      if (repository.viewerHasStarred) {
        unstarRepo(repoId).then(() => this.setState({ isChangingStar: false }));
      } else {
        starRepo(repoId).then(() => this.setState({ isChangingStar: false }));
      }
    } else if (index === 1 && showFork) {
      forkRepo(repoId).then(() => {
        navigation.navigate('Repository', {
          repoId: `${username}/${repository.name}`,
        });
      });
    } else if ((index === 2 && showFork) || (index === 1 && !showFork)) {
      this.setState({ isChangingSubscription: true });
      if (repository.viewerSubscription === 'SUBSCRIBED') {
        unwatchRepo(repoId).then(() =>
          this.setState({ isChangingSubscription: false })
        );
      } else {
        watchRepo(repoId).then(() =>
          this.setState({ isChangingSubscription: false })
        );
      }
    } else if ((index === 3 && showFork) || (index === 2 && !showFork)) {
      this.shareRepository(repository);
    } else if ((index === 4 && showFork) || (index === 3 && !showFork)) {
      openURLInView(repository.webUrl);
    }
  };

  fetchRepoInfo = () => {
    const { repoId } = this.props;

    this.setState({ refreshing: true });
    Promise.all([
      this.props.getRepoById(repoId),
      this.props.getContributors(repoId, { forceRefresh: true }),
    ]).then(() => {
      this.setState({ refreshing: false });
    });
  };

  shareRepository = repository => {
    const { locale } = this.props;
    const title = translate('repository.main.shareRepositoryTitle', locale, {
      repoName: repository.name,
    });

    Share.share(
      {
        title,
        message: translate('repository.main.shareRepositoryMessage', locale, {
          repoName: repository.name,
          repoUrl: repository.webUrl,
        }),
        url: undefined,
      },
      {
        dialogTitle: title,
        excludedActivityTypes: [],
      }
    );
  };

  renderLoadingMembers = () => {
    if (this.props.contributorsPagination.nextPageUrl === null) {
      return null;
    }

    return (
      <LoadingMembersContainer>
        <ActivityIndicator animating size="small" />
      </LoadingMembersContainer>
    );
  };

  render() {
    const {
      repository,
      repoId,
      contributors,
      contributorsPagination,
      locale,
      navigation,
      username,
    } = this.props;
    const { refreshing, hasError } = this.state;

    const isPendingRepository =
      !repository || typeof repository.openPullRequestsPreview === 'undefined';

    const isPendingContributors =
      contributors.length === 0 && contributorsPagination.isFetching;

    const openPulls = isPendingRepository
      ? []
      : repository.openPullRequestsPreview.nodes;
    const openIssues = isPendingRepository
      ? []
      : repository.openIssuesPreview.nodes;

    const showFork =
      repository && repository.owner && repository.owner.login !== username;

    const repositoryActions = repository
      ? [
          repository.viewerHasStarred
            ? translate('repository.main.unstarAction', locale)
            : translate('repository.main.starAction', locale),
          repository.viewerSubscription === 'SUBSCRIBED'
            ? translate('repository.main.unwatchAction', locale)
            : translate('repository.main.watchAction', locale),
          translate('repository.main.shareAction', locale),
          translate('common.openInBrowser', locale),
        ]
      : [];

    const pullRequestCount =
      !isPendingRepository && repository.pullRequests
        ? repository.pullRequests.totalCount
        : 0;
    const pureIssuesCount =
      !isPendingRepository && repository.issues
        ? repository.issues.totalCount
        : 0;

    if (showFork) {
      repositoryActions.splice(
        1,
        0,
        translate('repository.main.forkAction', locale)
      );
    }

    const showReadMe = !isPendingRepository && repository.README !== null;

    return (
      <ViewContainer>
        <ParallaxScroll
          renderContent={() => {
            if (isPendingRepository) {
              return <LoadingRepositoryProfile locale={locale} />;
            }

            return (
              <RepositoryProfile
                repository={repository}
                isChangingStar={this.state.isChangingStar}
                isChangingSubscription={this.state.isChangingSubscription}
                navigation={navigation}
                hasError={hasError}
                locale={locale}
              />
            );
          }}
          refreshControl={
            <RefreshControl
              refreshing={refreshing}
              onRefresh={this.fetchRepoInfo}
            />
          }
          stickyTitle={isPendingRepository ? repoId : repository.name}
          showMenu={!isPendingRepository}
          menuAction={this.showMenuActionSheet}
          navigation={navigation}
          navigateBack
        >
          {!hasError &&
            !isPendingRepository &&
            repository.repositoryTopics &&
            repository.repositoryTopics.nodes.length > 0 && (
              <TopicsList
                title={translate('repository.main.topicsTitle', locale)}
                topics={repository.repositoryTopics.nodes.map(
                  topic => topic.topic.name
                )}
              />
            )}

          {!hasError &&
            isPendingRepository && (
              <SectionList
                title={translate('repository.main.ownerTitle', locale)}
              >
                <LoadingUserListItem />
              </SectionList>
            )}

          {!hasError &&
            !isPendingRepository && (
              <SectionList
                title={translate('repository.main.ownerTitle', locale)}
              >
                <UserListItem
                  user={toOldUserFormat(repository.owner)}
                  navigation={navigation}
                />
              </SectionList>
            )}

          {!hasError &&
            (isPendingRepository || isPendingContributors) && (
              <LoadingMembersList
                title={translate('repository.main.contributorsTitle', locale)}
              />
            )}

          {!hasError &&
            !isPendingContributors && (
              <MembersList
                title={translate('repository.main.contributorsTitle', locale)}
                members={contributors}
                noMembersMessage={translate(
                  'repository.main.noContributorsMessage',
                  locale
                )}
                navigation={navigation}
                onEndReached={() =>
                  this.props.getContributors(repoId, { loadMore: true })
                }
                onEndReachedThreshold={0.5}
                ListFooterComponent={this.renderLoadingMembers}
              />
            )}

          {!hasError && (
            <SectionList
              title={translate('repository.main.sourceTitle', locale)}
            >
              {showReadMe && (
                <ListItem
                  title={translate('repository.main.readMe', locale)}
                  leftIcon={{
                    name: 'book',
                    color: colors.grey,
                    type: 'octicon',
                  }}
                  titleStyle={styles.listTitle}
                  containerStyle={styles.listContainerStyle}
                  onPress={() =>
                    navigation.navigate('ReadMe', {
                      repository,
                    })
                  }
                  underlayColor={colors.greyLight}
                />
              )}
              <ListItem
                title={translate('repository.main.viewSource', locale)}
                titleStyle={styles.listTitle}
                containerStyle={styles.listContainerStyle}
                leftIcon={{
                  name: 'code',
                  color: colors.grey,
                  type: 'octicon',
                }}
                onPress={() =>
                  navigation.navigate('RepositoryCodeList', {
                    title: translate('repository.codeList.title', locale),
                    topLevel: true,
                    contentsUrl: `https://api.github.com/repos/${repoId}/contents`,
                  })
                }
                underlayColor={colors.greyLight}
                disabled={isPendingRepository}
              />
            </SectionList>
          )}

          {!hasError &&
            !isPendingRepository &&
            repository.hasIssuesEnabled && (
              <SectionList
                title={translate('repository.main.issuesTitle', locale)}
                noItems={openIssues.length === 0}
                noItemsMessage={
                  pureIssuesCount === 0
                    ? translate('repository.main.noIssuesMessage', locale)
                    : translate('repository.main.noOpenIssuesMessage', locale)
                }
                showButton
                buttonTitle={
                  pureIssuesCount > 0
                    ? translate('repository.main.viewAllButton', locale)
                    : translate('repository.main.newIssueButton', locale)
                }
                buttonAction={() => {
                  if (pureIssuesCount > 0) {
                    navigation.navigate('IssueList', {
                      title: translate('repository.issueList.title', locale),
                      type: 'issue',
                      issues: repository.issues.nodes.map(issue =>
                        toOldIssueFormat(issue)
                      ),
                    });
                  } else {
                    navigation.navigate('NewIssue', {
                      title: translate('issue.newIssue.title', locale),
                    });
                  }
                }}
              >
                {openIssues.map(item => (
                  <IssueListItem
                    key={item.id}
                    type="issue"
                    issue={toOldIssueFormat(item, repoId)}
                    navigation={navigation}
                  />
                ))}
              </SectionList>
            )}

          {!hasError &&
            !isPendingRepository && (
              <SectionList
                title={translate('repository.main.pullRequestTitle', locale)}
                noItems={openPulls.length === 0}
                noItemsMessage={
                  pullRequestCount === 0
                    ? translate('repository.main.noPullRequestsMessage', locale)
                    : translate(
                        'repository.main.noOpenPullRequestsMessage',
                        locale
                      )
                }
                showButton={pullRequestCount > 0}
                buttonTitle={translate('repository.main.viewAllButton', locale)}
                buttonAction={() =>
                  navigation.navigate('PullList', {
                    title: translate('repository.pullList.title', locale),
                    type: 'pull',
                    issues: repository.pullRequests.nodes.map(issue =>
                      toOldIssueFormat(issue)
                    ),
                  })
                }
              >
                {openPulls.map(item => (
                  <IssueListItem
                    key={item.id}
                    type="pull"
                    issue={toOldIssueFormat(item, repoId, true)}
                    navigation={navigation}
                    locale={locale}
                  />
                ))}
              </SectionList>
            )}
        </ParallaxScroll>

        <ActionSheet
          ref={o => {
            this.ActionSheet = o;
          }}
          title={translate('repository.main.repoActions', locale)}
          options={[...repositoryActions, translate('common.cancel', locale)]}
          cancelButtonIndex={repositoryActions.length}
          onPress={this.handlePress}
        />
      </ViewContainer>
    );
  }
}

export const RepositoryScreen = connect(mapStateToProps, mapDispatchToProps)(
  Repository
);
<commit_msg>fix: add missing parameters for the PullsList screen<commit_after>/* eslint-disable no-shadow */
import React, { Component } from 'react';
import { connect } from 'react-redux';
import styled from 'styled-components';
import {
  StyleSheet,
  RefreshControl,
  Share,
  ActivityIndicator,
} from 'react-native';
import { ListItem } from 'react-native-elements';
import ActionSheet from 'react-native-actionsheet';
import { RestClient } from 'api';
import {
  ViewContainer,
  LoadingRepositoryProfile,
  RepositoryProfile,
  MembersList,
  SectionList,
  ParallaxScroll,
  LoadingUserListItem,
  UserListItem,
  IssueListItem,
  LoadingMembersList,
  TopicsList,
} from 'components';
import {
  translate,
  openURLInView,
  toOldIssueFormat,
  toOldUserFormat,
} from 'utils';
import { colors, fonts } from 'config';

const mapStateToProps = (state, ownProps) => {
  const {
    auth: { user, locale },
    entities: { gqlRepos, users, repos },
    pagination: { REPOS_GET_CONTRIBUTORS },
  } = state;

  const params = ownProps.navigation.state.params;

  const repoId =
    params.repoId ||
    params.repository.url
      .replace('https://api.github.com/repos/', '')
      .toLowerCase();

  const repository = gqlRepos[repoId] || repos[repoId] || params.repository;

  const contributorsPagination = REPOS_GET_CONTRIBUTORS[repoId] || {
    ids: [],
    isFetching: true,
  };
  const contributors = contributorsPagination.ids.map(id => users[id]);

  return {
    username: user.login,
    contributors,
    contributorsPagination,
    repository,
    repoId,
    locale,
  };
};

const mapDispatchToProps = {
  getRepoById: RestClient.graphql.getRepo,
  getContributors: RestClient.repos.getContributors,
  starRepo: RestClient.activity.starRepo,
  unstarRepo: RestClient.activity.unstarRepo,
  watchRepo: RestClient.activity.watchRepo,
  unwatchRepo: RestClient.activity.unwatchRepo,
  forkRepo: RestClient.repos.fork,
};

const LoadingMembersContainer = styled.View`
  padding: 5px;
`;

const styles = StyleSheet.create({
  listTitle: {
    color: colors.black,
    ...fonts.fontPrimary,
  },
  listContainerStyle: {
    borderBottomColor: colors.greyLight,
    borderBottomWidth: 1,
  },
});

class Repository extends Component {
  props: {
    getRepoById: Function,
    getContributors: Function,
    starRepo: Function,
    unstarRepo: Function,
    watchRepo: Function,
    unwatchRepo: Function,
    forkRepo: Function,
    repository: Object,
    repoId: String,
    contributors: Array,
    contributorsPagination: Object,
    navigation: Object,
    username: string,
    locale: string,
  };

  state: {
    refreshing: boolean,
    isChangingStar: boolean,
    isChangingSubscription: boolean,
    hasError: boolean,
  };

  constructor(props) {
    super(props);
    this.state = {
      refreshing: false,
      isChangingStar: false,
      isChangingSubscription: false,
      hasError: false,
      errorMessage: '',
    };
  }

  componentDidMount() {
    const { repoId, getRepoById, getContributors } = this.props;

    getRepoById(repoId)
      .then(() => {
        getContributors(repoId);
      })
      .catch(error => {
        this.setState({ hasError: true, errorMessage: error });
      });
  }

  showMenuActionSheet = () => {
    this.ActionSheet.show();
  };

  handlePress = index => {
    const {
      repository,
      repoId,
      forkRepo,
      starRepo,
      unstarRepo,
      watchRepo,
      unwatchRepo,
      navigation,
      username,
    } = this.props;

    const showFork = repository.owner.login !== username;

    if (index === 0) {
      this.setState({ isChangingStar: true });
      if (repository.viewerHasStarred) {
        unstarRepo(repoId).then(() => this.setState({ isChangingStar: false }));
      } else {
        starRepo(repoId).then(() => this.setState({ isChangingStar: false }));
      }
    } else if (index === 1 && showFork) {
      forkRepo(repoId).then(() => {
        navigation.navigate('Repository', {
          repoId: `${username}/${repository.name}`,
        });
      });
    } else if ((index === 2 && showFork) || (index === 1 && !showFork)) {
      this.setState({ isChangingSubscription: true });
      if (repository.viewerSubscription === 'SUBSCRIBED') {
        unwatchRepo(repoId).then(() =>
          this.setState({ isChangingSubscription: false })
        );
      } else {
        watchRepo(repoId).then(() =>
          this.setState({ isChangingSubscription: false })
        );
      }
    } else if ((index === 3 && showFork) || (index === 2 && !showFork)) {
      this.shareRepository(repository);
    } else if ((index === 4 && showFork) || (index === 3 && !showFork)) {
      openURLInView(repository.webUrl);
    }
  };

  fetchRepoInfo = () => {
    const { repoId } = this.props;

    this.setState({ refreshing: true });
    Promise.all([
      this.props.getRepoById(repoId),
      this.props.getContributors(repoId, { forceRefresh: true }),
    ]).then(() => {
      this.setState({ refreshing: false });
    });
  };

  shareRepository = repository => {
    const { locale } = this.props;
    const title = translate('repository.main.shareRepositoryTitle', locale, {
      repoName: repository.name,
    });

    Share.share(
      {
        title,
        message: translate('repository.main.shareRepositoryMessage', locale, {
          repoName: repository.name,
          repoUrl: repository.webUrl,
        }),
        url: undefined,
      },
      {
        dialogTitle: title,
        excludedActivityTypes: [],
      }
    );
  };

  renderLoadingMembers = () => {
    if (this.props.contributorsPagination.nextPageUrl === null) {
      return null;
    }

    return (
      <LoadingMembersContainer>
        <ActivityIndicator animating size="small" />
      </LoadingMembersContainer>
    );
  };

  render() {
    const {
      repository,
      repoId,
      contributors,
      contributorsPagination,
      locale,
      navigation,
      username,
    } = this.props;
    const { refreshing, hasError } = this.state;

    const isPendingRepository =
      !repository || typeof repository.openPullRequestsPreview === 'undefined';

    const isPendingContributors =
      contributors.length === 0 && contributorsPagination.isFetching;

    const openPulls = isPendingRepository
      ? []
      : repository.openPullRequestsPreview.nodes;
    const openIssues = isPendingRepository
      ? []
      : repository.openIssuesPreview.nodes;

    const showFork =
      repository && repository.owner && repository.owner.login !== username;

    const repositoryActions = repository
      ? [
          repository.viewerHasStarred
            ? translate('repository.main.unstarAction', locale)
            : translate('repository.main.starAction', locale),
          repository.viewerSubscription === 'SUBSCRIBED'
            ? translate('repository.main.unwatchAction', locale)
            : translate('repository.main.watchAction', locale),
          translate('repository.main.shareAction', locale),
          translate('common.openInBrowser', locale),
        ]
      : [];

    const pullRequestCount =
      !isPendingRepository && repository.pullRequests
        ? repository.pullRequests.totalCount
        : 0;
    const pureIssuesCount =
      !isPendingRepository && repository.issues
        ? repository.issues.totalCount
        : 0;

    if (showFork) {
      repositoryActions.splice(
        1,
        0,
        translate('repository.main.forkAction', locale)
      );
    }

    const showReadMe = !isPendingRepository && repository.README !== null;

    return (
      <ViewContainer>
        <ParallaxScroll
          renderContent={() => {
            if (isPendingRepository) {
              return <LoadingRepositoryProfile locale={locale} />;
            }

            return (
              <RepositoryProfile
                repository={repository}
                isChangingStar={this.state.isChangingStar}
                isChangingSubscription={this.state.isChangingSubscription}
                navigation={navigation}
                hasError={hasError}
                locale={locale}
              />
            );
          }}
          refreshControl={
            <RefreshControl
              refreshing={refreshing}
              onRefresh={this.fetchRepoInfo}
            />
          }
          stickyTitle={isPendingRepository ? repoId : repository.name}
          showMenu={!isPendingRepository}
          menuAction={this.showMenuActionSheet}
          navigation={navigation}
          navigateBack
        >
          {!hasError &&
            !isPendingRepository &&
            repository.repositoryTopics &&
            repository.repositoryTopics.nodes.length > 0 && (
              <TopicsList
                title={translate('repository.main.topicsTitle', locale)}
                topics={repository.repositoryTopics.nodes.map(
                  topic => topic.topic.name
                )}
              />
            )}

          {!hasError &&
            isPendingRepository && (
              <SectionList
                title={translate('repository.main.ownerTitle', locale)}
              >
                <LoadingUserListItem />
              </SectionList>
            )}

          {!hasError &&
            !isPendingRepository && (
              <SectionList
                title={translate('repository.main.ownerTitle', locale)}
              >
                <UserListItem
                  user={toOldUserFormat(repository.owner)}
                  navigation={navigation}
                />
              </SectionList>
            )}

          {!hasError &&
            (isPendingRepository || isPendingContributors) && (
              <LoadingMembersList
                title={translate('repository.main.contributorsTitle', locale)}
              />
            )}

          {!hasError &&
            !isPendingContributors && (
              <MembersList
                title={translate('repository.main.contributorsTitle', locale)}
                members={contributors}
                noMembersMessage={translate(
                  'repository.main.noContributorsMessage',
                  locale
                )}
                navigation={navigation}
                onEndReached={() =>
                  this.props.getContributors(repoId, { loadMore: true })
                }
                onEndReachedThreshold={0.5}
                ListFooterComponent={this.renderLoadingMembers}
              />
            )}

          {!hasError && (
            <SectionList
              title={translate('repository.main.sourceTitle', locale)}
            >
              {showReadMe && (
                <ListItem
                  title={translate('repository.main.readMe', locale)}
                  leftIcon={{
                    name: 'book',
                    color: colors.grey,
                    type: 'octicon',
                  }}
                  titleStyle={styles.listTitle}
                  containerStyle={styles.listContainerStyle}
                  onPress={() =>
                    navigation.navigate('ReadMe', {
                      repository,
                    })
                  }
                  underlayColor={colors.greyLight}
                />
              )}
              <ListItem
                title={translate('repository.main.viewSource', locale)}
                titleStyle={styles.listTitle}
                containerStyle={styles.listContainerStyle}
                leftIcon={{
                  name: 'code',
                  color: colors.grey,
                  type: 'octicon',
                }}
                onPress={() =>
                  navigation.navigate('RepositoryCodeList', {
                    title: translate('repository.codeList.title', locale),
                    topLevel: true,
                    contentsUrl: `https://api.github.com/repos/${repoId}/contents`,
                  })
                }
                underlayColor={colors.greyLight}
                disabled={isPendingRepository}
              />
            </SectionList>
          )}

          {!hasError &&
            !isPendingRepository &&
            repository.hasIssuesEnabled && (
              <SectionList
                title={translate('repository.main.issuesTitle', locale)}
                noItems={openIssues.length === 0}
                noItemsMessage={
                  pureIssuesCount === 0
                    ? translate('repository.main.noIssuesMessage', locale)
                    : translate('repository.main.noOpenIssuesMessage', locale)
                }
                showButton
                buttonTitle={
                  pureIssuesCount > 0
                    ? translate('repository.main.viewAllButton', locale)
                    : translate('repository.main.newIssueButton', locale)
                }
                buttonAction={() => {
                  if (pureIssuesCount > 0) {
                    navigation.navigate('IssueList', {
                      title: translate('repository.issueList.title', locale),
                      type: 'issue',
                      issues: repository.issues.nodes.map(issue =>
                        toOldIssueFormat(issue)
                      ),
                    });
                  } else {
                    navigation.navigate('NewIssue', {
                      title: translate('issue.newIssue.title', locale),
                    });
                  }
                }}
              >
                {openIssues.map(item => (
                  <IssueListItem
                    key={item.id}
                    type="issue"
                    issue={toOldIssueFormat(item, repoId)}
                    navigation={navigation}
                  />
                ))}
              </SectionList>
            )}

          {!hasError &&
            !isPendingRepository && (
              <SectionList
                title={translate('repository.main.pullRequestTitle', locale)}
                noItems={openPulls.length === 0}
                noItemsMessage={
                  pullRequestCount === 0
                    ? translate('repository.main.noPullRequestsMessage', locale)
                    : translate(
                        'repository.main.noOpenPullRequestsMessage',
                        locale
                      )
                }
                showButton={pullRequestCount > 0}
                buttonTitle={translate('repository.main.viewAllButton', locale)}
                buttonAction={() =>
                  navigation.navigate('PullList', {
                    title: translate('repository.pullList.title', locale),
                    type: 'pull',
                    issues: repository.pullRequests.nodes.map(issue =>
                      toOldIssueFormat(issue, repoId, true)
                    ),
                  })
                }
              >
                {openPulls.map(item => (
                  <IssueListItem
                    key={item.id}
                    type="pull"
                    issue={toOldIssueFormat(item, repoId, true)}
                    navigation={navigation}
                    locale={locale}
                  />
                ))}
              </SectionList>
            )}
        </ParallaxScroll>

        <ActionSheet
          ref={o => {
            this.ActionSheet = o;
          }}
          title={translate('repository.main.repoActions', locale)}
          options={[...repositoryActions, translate('common.cancel', locale)]}
          cancelButtonIndex={repositoryActions.length}
          onPress={this.handlePress}
        />
      </ViewContainer>
    );
  }
}

export const RepositoryScreen = connect(mapStateToProps, mapDispatchToProps)(
  Repository
);
<|endoftext|>


<commit_before>'use strict';

var supercluster = require('./');
var v8 = require('v8');

var points = [];
for (var i = 0; i < 1000000; i++) {
    points.push({
        type: 'Feature',
        properties: {
            index: i
        },
        geometry: {
            type: 'Point',
            coordinates: [
                -180 + 360 * Math.random(),
                -80 + 160 * Math.random()
            ]
        }
    });
}

var size = v8.getHeapStatistics().used_heap_size;

var index = supercluster({log: true, maxZoom: 7}).load(points);

console.log('memory used: ' + Math.round((v8.getHeapStatistics().used_heap_size - size) / 1024) + ' KB');

index.getClusters([-180, -90, 180, 90], 0).map((f) => JSON.stringify(f.properties));
<commit_msg>more reliable benchmark<commit_after>'use strict';

// run this benchmark with:
// node --expose-gc bench.js

var supercluster = require('./');
var v8 = require('v8');

var points = [];
for (var i = 0; i < 1000000; i++) {
    points.push({
        type: 'Feature',
        properties: {
            index: i
        },
        geometry: {
            type: 'Point',
            coordinates: [
                -180 + 360 * Math.random(),
                -80 + 160 * Math.random()
            ]
        }
    });
}

global.gc();
var size = v8.getHeapStatistics().used_heap_size;

var index = supercluster({log: true, maxZoom: 6}).load(points);

global.gc();
console.log('memory used: ' + Math.round((v8.getHeapStatistics().used_heap_size - size) / 1024) + ' KB');

index.getClusters([-180, -90, 180, 90], 0).map((f) => JSON.stringify(f.properties));
<|endoftext|>


<commit_before>(function( $ ) {
  $.fn.activeScroll = function(options) {
    var settings = $.extend({
      animation: 200,
      class: "active",
      nav: "nav",
      navItem: "li",
      navLink: "a",
      sections: "section",
      threshold: -10,
    }, options);

    var $sections = $(this).find(settings.sections);
    var navItemSelector = settings.nav + " " + settings.navItem;
    var navLinkSelector = navItemSelector + " " + settings.navLink;
    var statePushed = false;

    // Init navagation links to animated scroll to sections
    $sections.each(function(i) {
      var $section = $sections.eq(i);
      var $link = $(navLinkSelector).eq(i);
      if ($link) {
        $link.click(function(e) {
          var href = $(this).attr("href");
          var isHash = href && href[0] === "#";
          var isVoid = href && href === "javascript:void(0)";
          if (isHash || isVoid) {
            event.preventDefault();

            if (isHash && window.history.pushState) {
              var newHash = window.location.hash.replace(window.location.hash, href);
              statePushed ?
                window.history.replaceState({}, "", newHash) :
                window.history.pushState({}, "", newHash);
              statePushed = true;
            }

            $("html, body").animate({
              scrollTop: $section.position().top + (settings.threshold + 1),
            });
          }
        });
      }
    });

    // Change navagation item classes when scrolling into new section
    $(window).scroll(function() {
      var windScroll = $(window).scrollTop();
      $sections.each(function(i) {
        if ($(this).position().top <= windScroll - settings.threshold) {
          $(navItemSelector + "." + settings.class).removeClass(settings.class);
          $(navLinkSelector).eq(i).closest(navItemSelector).addClass(settings.class);
        }
      });
    }).scroll();
  };
}( jQuery ));
<commit_msg>More precise link-section association<commit_after>(function( $ ) {
  $.fn.activeScroll = function(options) {
    var settings = $.extend({
      animation: 200,
      class: "active",
      nav: "nav",
      navItem: "li",
      navLink: "a",
      sections: "section",
      sectionIdAttr: "id",
      threshold: -10
    }, options);

    var navItemSelector = settings.nav + " " + settings.navItem;
    var navLinkSelector = navItemSelector + " " + settings.navLink;
    var statePushed = false;

    // Init navigation links so they animatedly scroll to sections
    var $sections = $(this).find(settings.sections).filter(function() {
      var $section = $(this);
      var id = $section.attr(settings.sectionIdAttr);

      if (!id)
        return false;

      var idStr = "#" + id;
      var $link = $(navLinkSelector + "[href='" + idStr + "']");

      if (!$link)
        return false;

      $link.click(function(e) {
        e.preventDefault();

        if (window.history.pushState) {
          var newLoc = window.location.hash.replace(window.location.hash, idStr);
          statePushed ?
            window.history.replaceState({}, "", newLoc) :
            window.history.pushState({}, "", newLoc);
          statePushed = true;
        }

        $("html, body").animate({
          scrollTop: $section.position().top + (settings.threshold + 1)
        });
      });

      $(this).prop("$link", $link);
      return true;
    });

    // Change navigation item classes when scrolling into new section
    $(window).scroll(function() {
      var windScroll = $(window).scrollTop();
      $sections.each(function() {
        if ($(this).position().top <= windScroll - settings.threshold) {
          $(navItemSelector + "." + settings.class).removeClass(settings.class);
          $(this).prop("$link").closest(navItemSelector).addClass(settings.class);
        }
      });
    }).scroll();
  };
}( jQuery ));
<|endoftext|>


<commit_before>'use strict';

var Node = require('../node');

var routingToSinglePointQueryTemplate = Node.getSqlTemplateFn('routing-to-single-point');

var TYPE = 'routing-to-single-point';
var PARAMS = {
    source: Node.PARAM.NODE(Node.GEOMETRY.POINT),
    mode: Node.PARAM.ENUM('car', 'walk', 'bicycle', 'public_transport'),
    destination_longitude: Node.PARAM.NUMBER(),
    destination_latitude: Node.PARAM.NUMBER(),
    units: Node.PARAM.ENUM('kilometers', 'miles'),
};

var RoutingToSinglePoint = Node.create(TYPE, PARAMS, { cache: true });

module.exports = RoutingToSinglePoint;
module.exports.TYPE = TYPE;
module.exports.PARAMS = PARAMS;

RoutingToSinglePoint.prototype.sql = function() {
    var template = routingToSinglePointQueryTemplate;

    return template({
        source: this.source.getQuery(),
        columns: this.source.getColumns(true).join(', '),
        destination_longitude: this.destination_longitude,
        destination_latitude: this.destination_latitude,
        mode: this.mode,
        mode_type:'shortest'
    });
};
<commit_msg>Made units to default to kilometres<commit_after>'use strict';

var Node = require('../node');

var routingToSinglePointQueryTemplate = Node.getSqlTemplateFn('routing-to-single-point');

var TYPE = 'routing-to-single-point';
var PARAMS = {
    source: Node.PARAM.NODE(Node.GEOMETRY.POINT),
    mode: Node.PARAM.ENUM('car', 'walk', 'bicycle', 'public_transport'),
    destination_longitude: Node.PARAM.NUMBER(),
    destination_latitude: Node.PARAM.NUMBER(),
    units: Node.PARAM.NULLABLE(Node.PARAM.ENUM('kilometers', 'miles'), 'kilometers')
};

var RoutingToSinglePoint = Node.create(TYPE, PARAMS, { cache: true });

module.exports = RoutingToSinglePoint;
module.exports.TYPE = TYPE;
module.exports.PARAMS = PARAMS;

RoutingToSinglePoint.prototype.sql = function() {
    var template = routingToSinglePointQueryTemplate;

    return template({
        source: this.source.getQuery(),
        columns: this.source.getColumns(true).join(', '),
        destination_longitude: this.destination_longitude,
        destination_latitude: this.destination_latitude,
        mode: this.mode,
        mode_type:'shortest'
    });
};
<|endoftext|>


<commit_before>/**
 * Copyright 2013-2017 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://jhipster.github.io/
 * for more information.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const util = require('util');
const chalk = require('chalk');
const generator = require('yeoman-generator');
const packagejs = require('../../package.json');
const semver = require('semver');
const _ = require('lodash');
const BaseGenerator = require('generator-jhipster/generators/generator-base');
const constant = require('./constant');
const prompts = require('./prompts');
const writeFiles = require('./files').writeFiles;

const JhipsterGenerator = generator.extend({});
util.inherits(JhipsterGenerator, BaseGenerator);

module.exports = JhipsterGenerator.extend({
    initializing: {
        readConfig() {
            this.jhipsterAppConfig = this.getJhipsterAppConfig();
            if (!this.jhipsterAppConfig) {
                this.error('Can\'t read .yo-rc.json');
            }
        },
        displayLogo() {
            // it's here to show that you can use functions from generator-jhipster
            // this function is in: generator-jhipster/generators/generator-base.js
            this.printJHipsterLogo();

            // Have Yeoman greet the user.
            this.log(`\nWelcome to the ${chalk.bold.yellow('JHipster pages')} generator! ${chalk.yellow(`v${packagejs.version}\n`)}`);
        },
        checkJhipster() {
            const jhipsterVersion = this.jhipsterAppConfig.jhipsterVersion;
            const minimumJhipsterVersion = packagejs.dependencies['generator-jhipster'];
            if (!semver.satisfies(jhipsterVersion, minimumJhipsterVersion)) {
                this.warning(`\nYour generated project used an old JHipster version (${jhipsterVersion})... you need at least (${minimumJhipsterVersion})\n`);
            }
        },
        setupconsts() {
            this.fields = [];
            this.fieldNamesUnderscored = [];
        }
    },

    prompting: {
        askForPageSetConfig: prompts.askForPageSetConfig,
        askForPageConfig: prompts.askForPageConfig,
        askForFormConfig: prompts.askForFormConfig,
        askForWorkflowConfig: prompts.askForWorkflowConfig
    },

    configuring: {
        writePageSetJson() {
            let toPath = `${constant.MODULES_PAGES_CONFIG_FILE}/${this.pageSet}.json`;
            // store information in a file for further use.
            if (!this.useConfigurationFile && (this.databaseType === 'sql' || this.databaseType === 'cassandra')) {
                this.changelogDate = this.dateFormatForLiquibase();
            }
            this.data = {};
            this.data.pages = this.pages;
            this.currentPage = {pageName: this.pageName, pageType: this.pageType};
            if(this.pageGlyphIcon || this.pageGlyphIcon === 'false') {
                this.currentPage.pageGlyphIcon = this.pageGlyphIcon;
            }
            if(this.fields) {
                this.currentPage.fields = this.fields;
            }
            this.pages.push(this.currentPage);
            this.data.changelogDate = this.changelogDate;
            this.fs.writeJSON(toPath, this.data, null, 4);
        },

        loadInMemoryData() {

            this.baseName = this.jhipsterAppConfig.baseName;
            this.packageName = this.jhipsterAppConfig.packageName;
            this.applicationType = this.jhipsterAppConfig.applicationType;
            this.packageFolder = this.jhipsterAppConfig.packageFolder;
            this.enableTranslation = this.jhipsterAppConfig.enableTranslation;
            this.authenticationType = this.jhipsterAppConfig.authenticationType;
            this.languages = this.jhipsterAppConfig.languages;
            this.mainClass = this.getMainClassName();

            this.loadFromServer = false;
            this.saveToServer = false;
            this.contactServer = false;

            if(this.pageType === 'loadFromServer' || this.pageType === 'loadAndSaveToServer' || this.pageType === 'table' || this.pageType === 'workflow') {
                this.loadFromServer = true;
            }

            if(this.pageType === 'saveToServer' || this.pageType === 'loadAndSaveToServer' || this.pageType === 'form' || this.pageType === 'workflow') {
                this.saveToServer = true;
            }

            if(this.loadFromServer === true || this.saveToServer === true) {
                this.contactServer = true;
            }

            this.pageSetSpinalCased = _.kebabCase(_.lowerFirst(this.pageSet));
            this.pageSetClass = _.upperFirst(_.camelCase(this.pageSet));
            this.pageSetAngularClass = this.pageSetClass;
            this.pageSetInstance = _.lowerFirst(this.pageSetClass);
            this.pageSetUrl = this.pageSetSpinalCased;
            this.pageSetApiUrl = this.pageSetSpinalCased;
            this.pageSetRouterState = _.lowerFirst(this.pageSetClass);
            this.pageSetFolder = this.pageSetSpinalCased;
            this.pageSetTranslation = this.pageSetSpinalCased;

            this.pages.forEach((page) => {
                page.pageNameKebabCased = _.kebabCase(_.lowerFirst(page.pageName));
                page.pageNameCamelCased = _.camelCase(page.pageName);
                page.pageUrl = page.pageNameKebabCased;
                page.pageNameTranslationKey = _.lowerFirst(page.pageName);
                page.pageAngularName = page.pageNameCamelCased;
                page.pageRouterState = _.lowerFirst(page.pageNameCamelCased);
                page.pageInstance = _.lowerFirst(page.pageNameCamelCased);
                page.pageClass = _.upperFirst(page.pageNameCamelCased);
                page.pageApiUrl = page.pageNameKebabCased;
                page.pageLoadInstance = page.pageInstance+'LoadVM';
                page.pageLoadClass = page.pageClass+'LoadVM';
                page.pageSaveInstance = page.pageInstance+'SaveVM';
                page.pageSaveClass = page.pageClass+'SaveVM';
                page.loadFromServer = false;
                page.saveToServer = false;
                page.contactServer = false;

                if(page.pageType === 'loadFromServer' || page.pageType === 'loadAndSaveToServer' || page.pageType === 'table' || page.pageType === 'workflow') {
                    page.loadFromServer = true;
                }

                if(page.pageType === 'saveToServer' || page.pageType === 'loadAndSaveToServer' || page.pageType === 'form' || page.pageType === 'workflow') {
                    page.saveToServer = true;
                }

                if(page.loadFromServer === true || page.saveToServer === true) {
                    page.contactServer = true;
                }

                if(page.pageName === this.pageName) {
                    this.pageNameKebabCased = page.pageNameKebabCased;
                    this.pageNameCamelCased = page.pageNameCamelCased;
                    this.pageUrl = page.pageUrl;
                    this.pageApiUrl = page.pageNameKebabCased;
                    this.pageNameTranslationKey = page.pageNameTranslationKey;
                    this.pageAngularName = page.pageAngularName;
                    this.pageRouterState = page.pageRouterState;
                    this.pageInstance = page.pageInstance ;
                    this.pageClass = page.pageClass ;
                    this.pageLoadInstance = page.pageLoadInstance ;
                    this.pageLoadClass = page.pageLoadClass ;
                    this.pageSaveInstance = page.pageSaveInstance ;
                    this.pageSaveClass = page.pageSaveClass ;
                }
            });

            this.fieldsContainInstant = false;
            this.fieldsContainZonedDateTime = false;
            this.fieldsContainLocalDate = false;
            this.fieldsContainBigDecimal = false;
            this.fieldsContainBlob = false;
            this.fieldsContainImageBlob = false;
            this.validation = false;

            this.fields.forEach((field) => {
                const nonEnumType = _.includes(['String', 'Integer', 'Long', 'Float', 'Double', 'BigDecimal',
                    'LocalDate', 'Instant', 'ZonedDateTime', 'Boolean', 'byte[]', 'ByteBuffer'], field.fieldType);
                if (!nonEnumType) {
                    field.fieldIsEnum = true;
                } else {
                    field.fieldIsEnum = false;
                }

                if (_.isUndefined(field.fieldInJavaBeanMethod)) {
                    // Handle the specific case when the second letter is capitalized
                    // See http://stackoverflow.com/questions/2948083/naming-convention-for-getters-setters-in-java
                    if (field.fieldName.length > 1) {
                        const firstLetter = field.fieldName.charAt(0);
                        const secondLetter = field.fieldName.charAt(1);
                        if (firstLetter === firstLetter.toLowerCase() && secondLetter === secondLetter.toUpperCase()) {
                            field.fieldInJavaBeanMethod = firstLetter.toLowerCase() + field.fieldName.slice(1);
                        } else {
                            field.fieldInJavaBeanMethod = _.upperFirst(field.fieldName);
                        }
                    } else {
                        field.fieldInJavaBeanMethod = _.upperFirst(field.fieldName);
                    }
                }

                if (_.isUndefined(field.fieldValidateRulesPatternJava)) {
                    field.fieldValidateRulesPatternJava = field.fieldValidateRulesPattern ?
                        field.fieldValidateRulesPattern.replace(/\\/g, '\\\\').replace(/"/g, '\\"') : field.fieldValidateRulesPattern;
                }

                if (_.isArray(field.fieldValidateRules) && field.fieldValidateRules.length >= 1) {
                    field.fieldValidate = true;
                } else {
                    field.fieldValidate = false;
                }

                if (field.fieldType === 'ZonedDateTime') {
                    this.fieldsContainZonedDateTime = true;
                } else if (field.fieldType === 'Instant') {
                    this.fieldsContainInstant = true;
                } else if (field.fieldType === 'LocalDate') {
                    this.fieldsContainLocalDate = true;
                } else if (field.fieldType === 'BigDecimal') {
                    this.fieldsContainBigDecimal = true;
                } else if (field.fieldType === 'byte[]' || field.fieldType === 'ByteBuffer') {
                    this.fieldsContainBlob = true;
                    if (field.fieldTypeBlobContent === 'image') {
                        this.fieldsContainImageBlob = true;
                    }
                }
                if (field.fieldValidate) {
                    this.validation = true;
                }
            });
        }
    },

    writing: writeFiles(),

    install() {
        let logMsg =
            `To install your dependencies manually, run: ${chalk.yellow.bold(`${this.clientPackageManager} install`)}`;

        if (this.clientFramework === 'angular1') {
            logMsg =
                `To install your dependencies manually, run: ${chalk.yellow.bold(`${this.clientPackageManager} install & bower install`)}`;
        }
        const injectDependenciesAndConstants = (err) => {
            if (err) {
                this.warning('Install of dependencies failed!');
                this.log(logMsg);
            } else if (this.clientFramework === 'angular1') {
                //this.spawnCommand('gulp', ['install']);
            }
        };
        const installConfig = {
            bower: this.clientFramework === 'angular1',
            npm: this.clientPackageManager !== 'yarn',
            yarn: this.clientPackageManager === 'yarn',
            callback: injectDependenciesAndConstants
        };
        if (this.options['skip-install']) {
            this.log(logMsg);
        } else {
            //this.installDependencies(installConfig);
        }
    },

    end() {
        this.log('End of pages generator');
    }
});
<commit_msg>fix link name<commit_after>/**
 * Copyright 2013-2017 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://jhipster.github.io/
 * for more information.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const util = require('util');
const chalk = require('chalk');
const generator = require('yeoman-generator');
const packagejs = require('../../package.json');
const semver = require('semver');
const _ = require('lodash');
const BaseGenerator = require('generator-jhipster/generators/generator-base');
const constant = require('./constant');
const prompts = require('./prompts');
const writeFiles = require('./files').writeFiles;

const JhipsterGenerator = generator.extend({});
util.inherits(JhipsterGenerator, BaseGenerator);

module.exports = JhipsterGenerator.extend({
    initializing: {
        readConfig() {
            this.jhipsterAppConfig = this.getJhipsterAppConfig();
            if (!this.jhipsterAppConfig) {
                this.error('Can\'t read .yo-rc.json');
            }
        },
        displayLogo() {
            // it's here to show that you can use functions from generator-jhipster
            // this function is in: generator-jhipster/generators/generator-base.js
            this.printJHipsterLogo();

            // Have Yeoman greet the user.
            this.log(`\nWelcome to the ${chalk.bold.yellow('JHipster pages')} generator! ${chalk.yellow(`v${packagejs.version}\n`)}`);
        },
        checkJhipster() {
            const jhipsterVersion = this.jhipsterAppConfig.jhipsterVersion;
            const minimumJhipsterVersion = packagejs.dependencies['generator-jhipster'];
            if (!semver.satisfies(jhipsterVersion, minimumJhipsterVersion)) {
                this.warning(`\nYour generated project used an old JHipster version (${jhipsterVersion})... you need at least (${minimumJhipsterVersion})\n`);
            }
        },
        setupconsts() {
            this.fields = [];
            this.fieldNamesUnderscored = [];
        }
    },

    prompting: {
        askForPageSetConfig: prompts.askForPageSetConfig,
        askForPageConfig: prompts.askForPageConfig,
        askForFormConfig: prompts.askForFormConfig,
        askForWorkflowConfig: prompts.askForWorkflowConfig
    },

    configuring: {
        writePageSetJson() {
            let toPath = `${constant.MODULES_PAGES_CONFIG_FILE}/${this.pageSet}.json`;
            // store information in a file for further use.
            if (!this.useConfigurationFile && (this.databaseType === 'sql' || this.databaseType === 'cassandra')) {
                this.changelogDate = this.dateFormatForLiquibase();
            }
            this.data = {};
            this.data.pages = this.pages;
            this.currentPage = {pageName: this.pageName, pageType: this.pageType};
            if(this.pageGlyphIcon || this.pageGlyphIcon === 'false') {
                this.currentPage.pageGlyphIcon = this.pageGlyphIcon;
            }
            if(this.fields) {
                this.currentPage.fields = this.fields;
            }
            this.pages.push(this.currentPage);
            this.data.changelogDate = this.changelogDate;
            this.fs.writeJSON(toPath, this.data, null, 4);
        },

        loadInMemoryData() {

            this.baseName = this.jhipsterAppConfig.baseName;
            this.packageName = this.jhipsterAppConfig.packageName;
            this.applicationType = this.jhipsterAppConfig.applicationType;
            this.packageFolder = this.jhipsterAppConfig.packageFolder;
            this.enableTranslation = this.jhipsterAppConfig.enableTranslation;
            this.authenticationType = this.jhipsterAppConfig.authenticationType;
            this.languages = this.jhipsterAppConfig.languages;
            this.mainClass = this.getMainClassName();

            this.loadFromServer = false;
            this.saveToServer = false;
            this.contactServer = false;

            if(this.pageType === 'loadFromServer' || this.pageType === 'loadAndSaveToServer' || this.pageType === 'table' || this.pageType === 'workflow') {
                this.loadFromServer = true;
            }

            if(this.pageType === 'saveToServer' || this.pageType === 'loadAndSaveToServer' || this.pageType === 'form' || this.pageType === 'workflow') {
                this.saveToServer = true;
            }

            if(this.loadFromServer === true || this.saveToServer === true) {
                this.contactServer = true;
            }

            this.pageSetSpinalCased = _.kebabCase(_.lowerFirst(this.pageSet));
            this.pageSetClass = _.upperFirst(_.camelCase(this.pageSet));
            this.pageSetAngularClass = this.pageSetClass;
            this.pageSetInstance = _.lowerFirst(this.pageSetClass);
            this.pageSetUrl = this.pageSetSpinalCased;
            this.pageSetApiUrl = this.pageSetSpinalCased;
            this.pageSetRouterState = _.lowerFirst(this.pageSetClass);
            this.pageSetFolder = this.pageSetSpinalCased;
            this.pageSetTranslation = this.pageSetSpinalCased;

            this.pages.forEach((page) => {
                page.pageNameKebabCased = _.kebabCase(_.lowerFirst(page.pageName));
                page.pageNameCamelCased = _.camelCase(page.pageName);
                page.pageUrl = page.pageNameKebabCased;
                page.pageAngularName = page.pageNameCamelCased;
                page.pageRouterState = _.lowerFirst(page.pageNameCamelCased);
                page.pageNameTranslationKey = this.pageSetRouterState+'-'+page.pageRouterState;
                page.pageInstance = _.lowerFirst(page.pageNameCamelCased);
                page.pageClass = _.upperFirst(page.pageNameCamelCased);
                page.pageApiUrl = page.pageNameKebabCased;
                page.pageLoadInstance = page.pageInstance+'LoadVM';
                page.pageLoadClass = page.pageClass+'LoadVM';
                page.pageSaveInstance = page.pageInstance+'SaveVM';
                page.pageSaveClass = page.pageClass+'SaveVM';
                page.loadFromServer = false;
                page.saveToServer = false;
                page.contactServer = false;

                if(page.pageType === 'loadFromServer' || page.pageType === 'loadAndSaveToServer' || page.pageType === 'table' || page.pageType === 'workflow') {
                    page.loadFromServer = true;
                }

                if(page.pageType === 'saveToServer' || page.pageType === 'loadAndSaveToServer' || page.pageType === 'form' || page.pageType === 'workflow') {
                    page.saveToServer = true;
                }

                if(page.loadFromServer === true || page.saveToServer === true) {
                    page.contactServer = true;
                }

                if(page.pageName === this.pageName) {
                    this.pageNameKebabCased = page.pageNameKebabCased;
                    this.pageNameCamelCased = page.pageNameCamelCased;
                    this.pageUrl = page.pageUrl;
                    this.pageApiUrl = page.pageNameKebabCased;
                    this.pageNameTranslationKey = page.pageNameTranslationKey;
                    this.pageAngularName = page.pageAngularName;
                    this.pageRouterState = page.pageRouterState;
                    this.pageInstance = page.pageInstance ;
                    this.pageClass = page.pageClass ;
                    this.pageLoadInstance = page.pageLoadInstance ;
                    this.pageLoadClass = page.pageLoadClass ;
                    this.pageSaveInstance = page.pageSaveInstance ;
                    this.pageSaveClass = page.pageSaveClass ;
                }
            });

            this.fieldsContainInstant = false;
            this.fieldsContainZonedDateTime = false;
            this.fieldsContainLocalDate = false;
            this.fieldsContainBigDecimal = false;
            this.fieldsContainBlob = false;
            this.fieldsContainImageBlob = false;
            this.validation = false;

            this.fields.forEach((field) => {
                const nonEnumType = _.includes(['String', 'Integer', 'Long', 'Float', 'Double', 'BigDecimal',
                    'LocalDate', 'Instant', 'ZonedDateTime', 'Boolean', 'byte[]', 'ByteBuffer'], field.fieldType);
                if (!nonEnumType) {
                    field.fieldIsEnum = true;
                } else {
                    field.fieldIsEnum = false;
                }

                if (_.isUndefined(field.fieldInJavaBeanMethod)) {
                    // Handle the specific case when the second letter is capitalized
                    // See http://stackoverflow.com/questions/2948083/naming-convention-for-getters-setters-in-java
                    if (field.fieldName.length > 1) {
                        const firstLetter = field.fieldName.charAt(0);
                        const secondLetter = field.fieldName.charAt(1);
                        if (firstLetter === firstLetter.toLowerCase() && secondLetter === secondLetter.toUpperCase()) {
                            field.fieldInJavaBeanMethod = firstLetter.toLowerCase() + field.fieldName.slice(1);
                        } else {
                            field.fieldInJavaBeanMethod = _.upperFirst(field.fieldName);
                        }
                    } else {
                        field.fieldInJavaBeanMethod = _.upperFirst(field.fieldName);
                    }
                }

                if (_.isUndefined(field.fieldValidateRulesPatternJava)) {
                    field.fieldValidateRulesPatternJava = field.fieldValidateRulesPattern ?
                        field.fieldValidateRulesPattern.replace(/\\/g, '\\\\').replace(/"/g, '\\"') : field.fieldValidateRulesPattern;
                }

                if (_.isArray(field.fieldValidateRules) && field.fieldValidateRules.length >= 1) {
                    field.fieldValidate = true;
                } else {
                    field.fieldValidate = false;
                }

                if (field.fieldType === 'ZonedDateTime') {
                    this.fieldsContainZonedDateTime = true;
                } else if (field.fieldType === 'Instant') {
                    this.fieldsContainInstant = true;
                } else if (field.fieldType === 'LocalDate') {
                    this.fieldsContainLocalDate = true;
                } else if (field.fieldType === 'BigDecimal') {
                    this.fieldsContainBigDecimal = true;
                } else if (field.fieldType === 'byte[]' || field.fieldType === 'ByteBuffer') {
                    this.fieldsContainBlob = true;
                    if (field.fieldTypeBlobContent === 'image') {
                        this.fieldsContainImageBlob = true;
                    }
                }
                if (field.fieldValidate) {
                    this.validation = true;
                }
            });
        }
    },

    writing: writeFiles(),

    install() {
        let logMsg =
            `To install your dependencies manually, run: ${chalk.yellow.bold(`${this.clientPackageManager} install`)}`;

        if (this.clientFramework === 'angular1') {
            logMsg =
                `To install your dependencies manually, run: ${chalk.yellow.bold(`${this.clientPackageManager} install & bower install`)}`;
        }
        const injectDependenciesAndConstants = (err) => {
            if (err) {
                this.warning('Install of dependencies failed!');
                this.log(logMsg);
            } else if (this.clientFramework === 'angular1') {
                //this.spawnCommand('gulp', ['install']);
            }
        };
        const installConfig = {
            bower: this.clientFramework === 'angular1',
            npm: this.clientPackageManager !== 'yarn',
            yarn: this.clientPackageManager === 'yarn',
            callback: injectDependenciesAndConstants
        };
        if (this.options['skip-install']) {
            this.log(logMsg);
        } else {
            //this.installDependencies(installConfig);
        }
    },

    end() {
        this.log('End of pages generator');
    }
});
<|endoftext|>