<commit_before>'use strict';

var csvImport = angular.module('ngCsvImport', []);

csvImport.directive('ngCsvImport', function() {
	return {
		restrict: 'E',
		transclude: true,
		replace: true,
		scope:{
			content:'=?',
			header: '=?',
			headerVisible: '=?',
			separator: '=?',
			separatorVisible: '=?',
			result: '=?',
			encoding: '=?',
			encodingVisible: '=?',
			accept: '=?',
			mdButtonClass: '@?',
			mdInputClass: '@?',
			mdButtonTitle: '@?',
			mdSvgIcon: '@?'
		},
		template: function(element, attrs) {
			var material = angular.isDefined(attrs.material);
			var multiple = angular.isDefined(attrs.multiple);
			return '
'+
		  	'

Header
<input type="checkbox" ng-model="header">
'+
			'

Encoding
{{encoding}}
'+
			'
'+
			'
Seperator
'+
			'<input class="separator-input" type="text" ng-change="changeSeparator" ng-model="separator">'+
			'
'+
			'
' +
			'<input class="btn cta gray" type="file" '+ (multiple ? 'multiple' : '') +' accept="{{accept}}"/>' +
			(material ? '<md-button ng-click="onClick($event)" class="_md md-button {{mdButtonClass}}"><md-icon md-svg-icon="{{mdSvgIcon}}"></md-icon> {{mdButtonTitle}}</md-button><md-input-container style="margin:0;"><input type="text" class="_md md-input-readable md-input {{mdInputClass}}" ng-click="onClick($event)" ng-model="filename"></md-input-container>' : '') +
			'
'+
			'
';
		},
		link: function(scope, element, attrs) {
			scope.separatorVisible = !!scope.separatorVisible;
			scope.headerVisible = !!scope.headerVisible;
			scope.material = angular.isDefined(attrs.material);
			scope.multiple = angular.isDefined(attrs.multiple);
			if (scope.multiple) {
				throw new Error("Multiple attribute is not supported yet.");
			}
			var input = angular.element(element[0].querySelector('input[type="file"]'));
			var inputContainer = angular.element(element[0].querySelector('md-input-container'));

			if (scope.material && input) {
				input.removeClass("ng-show");
				input.addClass("ng-hide");
				if (inputContainer) {
					var errorSpacer = angular.element(inputContainer[0].querySelector('div.md-errors-spacer'));
					if (errorSpacer) {
						errorSpacer.remove();
					}
				}
				scope.onClick = function() {
					input.click();
				};
			}

			angular.element(element[0].querySelector('.separator-input')).on('keyup', function(e) {
				if ( scope.content != null ) {
					var content = {
						csv: scope.content,
						header: scope.header,
						separator: e.target.value,
						encoding: scope.encoding
					};
					scope.result = csvToJSON(content);
					scope.$apply();
				}
			});

			element.on('change', function(onChangeEvent) {
				var reader = new FileReader();
				scope.filename = onChangeEvent.target.files[0].name;
				reader.onload = function(onLoadEvent) {
					scope.$apply(function() {
						var content = {
							csv: onLoadEvent.target.result.replace(/\r\n|\r/g,'\n'),
							header: scope.header,
							separator: scope.separator
						};
						scope.content = content.csv;
						scope.result = csvToJSON(content);
						scope.result.filename = scope.filename;
					});
				};

				if ( (onChangeEvent.target.type === "file") && (onChangeEvent.target.files != null || onChangeEvent.srcElement.files != null) )  {
					reader.readAsText((onChangeEvent.srcElement || onChangeEvent.target).files[0], scope.encoding);
				} else {
					if ( scope.content != null ) {
						var content = {
							csv: scope.content,
							header: !scope.header,
							separator: scope.separator
						};
						scope.result = csvToJSON(content);
					}
				}
			});

			var csvToJSON = function(content) {
				var lines=content.csv.split('\n');
				var result = [];
				var start = 0;
				var columnCount = lines[0].split(content.separator).length;

				var headers = [];
				if (content.header) {
					headers=lines[0].split(content.separator);
					start = 1;
				}

				for (var i=start; i<lines.length; i++) {
					var obj = {};
					var currentline=lines[i].split(new RegExp(content.separator+'(?![^"]*"(?:(?:[^"]*"){2})*[^"]*$)'));
					if ( currentline.length === columnCount ) {
						if (content.header) {
							for (var j=0; j<headers.length; j++) {
								obj[headers[j]] = currentline[j];
							}
						} else {
							for (var k=0; k<currentline.length; k++) {
								obj[k] = currentline[k];
							}
						}
						result.push(obj);
					}
				}
				return result;
			};
		}
	};
});<commit_msg>added templates in js<commit_after>'use strict';

var csvImport = angular.module('ngCsvImport', []);

csvImport.directive('ngCsvImport', function() {
	return {
		restrict: 'E',
		transclude: true,
		replace: true,
		scope:{
			content:'=?',
			header: '=?',
			headerVisible: '=?',
			separator: '=?',
			separatorVisible: '=?',
			result: '=?',
			encoding: '=?',
			encodingVisible: '=?',
			accept: '=?',
			mdButtonClass: '@?',
			mdInputClass: '@?',
			mdButtonTitle: '@?',
			mdSvgIcon: '@?'
		},
		template: function(element, attrs) {
			var material = angular.isDefined(attrs.material);
			var multiple = angular.isDefined(attrs.multiple);
			return '
'+
		  	'

Header
' +
		  	(material ? '<input type="checkbox" ng-model="header">
' :
		  		'<md-switch class="ng-csv-import-header-switch" ng-model="header"></md-switch>') +
			'

Encoding
{{encoding}}
'+
			'
'+
			'
Seperator
'+
			'<input class="separator-input ' + (material ? '_md md-input' : '')  + ' " type="text" ng-change="changeSeparator" ng-model="separator">'+
			'
'+
			'
' +
			'<input class="btn cta gray" type="file" '+ (multiple ? 'multiple' : '') +' accept="{{accept}}"/>' +
			(material ? '<md-button ng-click="onClick($event)" class="_md md-button {{mdButtonClass}}"><md-icon md-svg-icon="{{mdSvgIcon}}"></md-icon> {{mdButtonTitle}}</md-button><md-input-container style="margin:0;"><input type="text" class="_md md-input-readable md-input {{mdInputClass}}" ng-click="onClick($event)" ng-model="filename"></md-input-container>' : '') +
			'
'+
			'
';
		},
		link: function(scope, element, attrs) {
			scope.separatorVisible = !!scope.separatorVisible;
			scope.headerVisible = !!scope.headerVisible;
			scope.material = angular.isDefined(attrs.material);
			scope.multiple = angular.isDefined(attrs.multiple);
			if (scope.multiple) {
				throw new Error("Multiple attribute is not supported yet.");
			}
			var input = angular.element(element[0].querySelector('input[type="file"]'));
			var inputContainer = angular.element(element[0].querySelector('md-input-container'));

			if (scope.material && input) {
				input.removeClass("ng-show");
				input.addClass("ng-hide");
				if (inputContainer) {
					var errorSpacer = angular.element(inputContainer[0].querySelector('div.md-errors-spacer'));
					if (errorSpacer) {
						errorSpacer.remove();
					}
				}
				scope.onClick = function() {
					input.click();
				};
			}

			angular.element(element[0].querySelector('.separator-input')).on('keyup', function(e) {
				if ( scope.content != null ) {
					var content = {
						csv: scope.content,
						header: scope.header,
						separator: e.target.value,
						encoding: scope.encoding
					};
					scope.result = csvToJSON(content);
					scope.$apply();
				}
			});

			element.on('change', function(onChangeEvent) {
				var reader = new FileReader();
				scope.filename = onChangeEvent.target.files[0].name;
				reader.onload = function(onLoadEvent) {
					scope.$apply(function() {
						var content = {
							csv: onLoadEvent.target.result.replace(/\r\n|\r/g,'\n'),
							header: scope.header,
							separator: scope.separator
						};
						scope.content = content.csv;
						scope.result = csvToJSON(content);
						scope.result.filename = scope.filename;
					});
				};

				if ( (onChangeEvent.target.type === "file") && (onChangeEvent.target.files != null || onChangeEvent.srcElement.files != null) )  {
					reader.readAsText((onChangeEvent.srcElement || onChangeEvent.target).files[0], scope.encoding);
				} else {
					if ( scope.content != null ) {
						var content = {
							csv: scope.content,
							header: !scope.header,
							separator: scope.separator
						};
						scope.result = csvToJSON(content);
					}
				}
			});

			var csvToJSON = function(content) {
				var lines=content.csv.split('\n');
				var result = [];
				var start = 0;
				var columnCount = lines[0].split(content.separator).length;

				var headers = [];
				if (content.header) {
					headers=lines[0].split(content.separator);
					start = 1;
				}

				for (var i=start; i<lines.length; i++) {
					var obj = {};
					var currentline=lines[i].split(new RegExp(content.separator+'(?![^"]*"(?:(?:[^"]*"){2})*[^"]*$)'));
					if ( currentline.length === columnCount ) {
						if (content.header) {
							for (var j=0; j<headers.length; j++) {
								obj[headers[j]] = currentline[j];
							}
						} else {
							for (var k=0; k<currentline.length; k++) {
								obj[k] = currentline[k];
							}
						}
						result.push(obj);
					}
				}
				return result;
			};
		}
	};
});<|endoftext|>


<commit_before>function Muppet(age, hobby) {
  this.age = age;
  this.hobby = hobby;

  this.answerNanny = function(){
	return "Everything's cool!";
  }
}

function SwedishChef(age, hobby, mood) {
  Muppet.call(this, age, hobby);
  this.mood = mood;

  this.cook = function() {
    return "Mmmm soup!";
  }
}

SwedishChef.prototype = new Muppet();

describe("About inheritance", function() {
  beforeEach(function(){
    this.muppet = new Muppet(2, "coding");
  	this.swedishChef = new SwedishChef(2, "cooking", "chillin");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.swedishChef.cook()).toEqual(FILL_ME_IN);
  });

  it("should be able to call a method on the base object", function() {
    expect(this.swedishChef.answerNanny()).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.swedishChef.age).toEqual(FILL_ME_IN);
    expect(this.swedishChef.hobby).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.swedishChef.mood).toEqual(FILL_ME_IN);
  });
});

// http://javascript.crockford.com/prototypal.html
Object.prototype.beget = function () {
  function F() {}
  F.prototype = this;
  return new F();
}

function Gonzo(age, hobby, trick) {
  Muppet.call(this, age, hobby);
  this.trick = trick;

  this.doTrick = function() {
    return this.trick;
  }
}

//no longer need to call the Muppet (base type) constructor
Gonzo.prototype = Muppet.prototype.beget();
//note: if you're wondering how this line affects the below tests, the answer is that it doesn't.
//however, it does do something interesting -- it makes this work:
//  var g = new Gonzo(...);
//  g instanceOf Muppet //true

describe("About Crockford's inheritance improvement", function() {
  beforeEach(function(){
    this.gonzo = new Gonzo(3, "daredevil performer", "eat a tire");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.gonzo.doTrick()).toEqual(FILL_ME_IN);
  });

  it("should be able to call a method on the base object", function() {
    expect(this.gonzo.answerNanny()).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.gonzo.age).toEqual(FILL_ME_IN);
    expect(this.gonzo.hobby).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.gonzo.trick).toEqual(FILL_ME_IN);
  });
});
<commit_msg>tests within the "Thinking about Inheritance section are passing.<commit_after>function Muppet(age, hobby) {
  this.age = age;
  this.hobby = hobby;

  this.answerNanny = function(){
	return "Everything's cool!";
  }
}

function SwedishChef(age, hobby, mood) {
  Muppet.call(this, age, hobby);
  this.mood = mood;

  this.cook = function() {
    return "Mmmm soup!";
  }
}

SwedishChef.prototype = new Muppet();

describe("About inheritance", function() {
  beforeEach(function(){
    this.muppet = new Muppet(2, "coding");
  	this.swedishChef = new SwedishChef(2, "cooking", "chillin");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.swedishChef.cook()).toEqual("Mmmm soup!");
  });

  it("should be able to call a method on the base object", function() {
    expect(this.swedishChef.answerNanny()).toEqual("Everything's cool!");
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.swedishChef.age).toEqual(2);
    expect(this.swedishChef.hobby).toEqual("cooking");
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.swedishChef.mood).toEqual("chillin");
  });
});

// http://javascript.crockford.com/prototypal.html
Object.prototype.beget = function () {
  function F() {}
  F.prototype = this;
  return new F();
}

function Gonzo(age, hobby, trick) {
  Muppet.call(this, age, hobby);
  this.trick = trick;

  this.doTrick = function() {
    return this.trick;
  }
}

//no longer need to call the Muppet (base type) constructor
Gonzo.prototype = Muppet.prototype.beget();
//note: if you're wondering how this line affects the below tests, the answer is that it doesn't.
//however, it does do something interesting -- it makes this work:
//  var g = new Gonzo(...);
//  g instanceOf Muppet //true

describe("About Crockford's inheritance improvement", function() {
  beforeEach(function(){
    this.gonzo = new Gonzo(3, "daredevil performer", "eat a tire");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.gonzo.doTrick()).toEqual(FILL_ME_IN);
  });

  it("should be able to call a method on the base object", function() {
    expect(this.gonzo.answerNanny()).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.gonzo.age).toEqual(FILL_ME_IN);
    expect(this.gonzo.hobby).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.gonzo.trick).toEqual(FILL_ME_IN);
  });
});
<|endoftext|>


<commit_before>import React from 'react'

import { State, RESULTS_CHANGED, RESULT_CLICKED, VALUES_CHANGED } from './state'

import { Results as RawResults } from '../ui/Results';

class Response extends React.Component {
  constructor(props) {
    super(props)
    this.state = { results: this._state().getResults() || {} };
    this.onResultsChange = this.onResultsChange.bind(this)
  }

  _state() {
    return State.ns(this.props.namespace);
  }

  componentDidMount() {
    this._state().registerListener(RESULTS_CHANGED, this.onResultsChange);
    this._state().registerListener(VALUES_CHANGED, this.onResultsChange);
  }

  componentWillUnmount() {
    this._state().unregisterListener(RESULTS_CHANGED, this.onResultsChange);
    this._state().unregisterListener(VALUES_CHANGED, this.onResultsChange);
  }

  onResultsChange() {
    this.setState({ results: this._state().getResults() || {} });
  }

  render() {
    const { children, Placeholder } = this.props;
    const results = this.state.results;
    const time = results.time;
    const error = this._state().getError();

    if (!time && !error) {
      return Placeholder ? <Placeholder /> : null;
    }

    const propsForChildren = { ...results, error };
    const childrenWithResults = React.Children.map(children, c => {
      if (React.isValidElement(c)) {
        return React.cloneElement(c, propsForChildren);
      }
      return null;
    });

    return
{childrenWithResults}
;
  }
}

Response.defaultProps = {
  namespace: 'default',
}

const Results = props => {
  const { results, error, namespace = "default", showImages } = props;

  if (!results && !error) {
    return null;
  }
  const resultClicked = url =>
    State.ns(namespace).notify(RESULT_CLICKED, url);
  return (
    <RawResults
      data={{ searchResponse: props }}
      resultClicked={resultClicked}
      showImages={showImages}
    />
  );
};

class Summary extends React.Component {
  constructor(props) {
    super(props)
    this.onValuesChange = this.onValuesChange.bind(this)
    this._state = this._state.bind(this)
  }

  _state() {
    return State.ns(this.props.namespace);
  }

  componentDidMount() {
    this._state().registerListener(RESULTS_CHANGED, this.onValuesChange);
  }

  componentWillUnmount() {
    this._state().unregisterListener(RESULTS_CHANGED, this.onValuesChange);
  }

  onValuesChange() {
    this.setState(this._state().getResults() || {});
  }

  render() {
    const values = this._state().getValues();
    const responseValues = this._state().getResponseValues();
    const { time, totalResults, error } = this.props;
    const text = responseValues["q"] || values["q"];

    if (error) {
      return null;
    }

    const page = parseInt(values.page, 10);
    const pageNumber = page && page > 1 ? `Page ${page} of ` : "";
    const runOverride = e => {
      e.preventDefault();
      this._state().setValues({ q: values["q"], "q.override": "true" }, true);
    };
    const override = responseValues["q"] &&
      responseValues["q"].toLowerCase() !== values["q"].toLowerCase()
      ?
          {`search instead for `}
           {values["q"]}

      : null;

    return (

          {`${pageNumber}${totalResults} results for `}
          "{text}"
          {" "}

        {`(${time}) `}
        {override}

    )
  }
}

Summary.defaultProps = {
  namespace: 'default'
}

const pageNumbers = (page, totalPages) => {
  const pages = []

  let i = 2
  while (i >= 0) {
    if (page - i > 0) {
      pages.push(page-i)
    }
    i--
  }

  i = 1
  while (pages.length < 5 && page + i <= totalPages) {
    pages.push(page+i)
    i++
  }

  i = 3
  while (pages.length < 5 && page - i > 0) {
    pages.unshift(page-i)
    i++
  }
  return pages
}

const RawPaginator = ({ resultsPerPage, page, totalResults, setPage, pageFn }) => {
  if (totalResults <= resultsPerPage) {
    return null
  }

  const totalPages = Math.ceil(totalResults/resultsPerPage)
  if (totalPages === 0) {
    return null
  }

  const pages = pageNumbers(page, totalPages).map(p =>
    <Page key={p} page={p} currentPage={page} setPage={setPage}>{p}</Page>
  )

  const prevPage = () => {
    if (page === 1) {
      return
    }
    setPage(page-1)
  }

  const nextPage = () => {
    if (page === totalPages) {
      return
    }
    setPage(page+1)
  }

  return (

<

      {pages}

>

  )
}

const Page = ({ currentPage, page, setPage, children }) => (

 setPage(page)}>{ children }

)

class Paginator extends React.Component {
  render() {
    if (this.props.error) {
      return null;
    }
    const _state = State.ns(this.props.namespace);
    const setPage = (page) => {
      window.scrollTo(0, 0);
      _state.setValues({page: ""+page}, true);
    }
    const values = _state.getValues();

    const page = values.page ? parseInt(values.page, 10) : 1;
    const resultsPerPage = parseInt(values.resultsPerPage, 10)
    const totalResultsInt = parseInt(this.props.totalResults, 10)

    return <RawPaginator setPage={setPage} page={page} resultsPerPage={resultsPerPage} totalResults={totalResultsInt} />
  }
}

Paginator.defaultProps = {
  namespace: 'default'
}

export { Response, Summary, Results, Paginator };
<commit_msg>paginator: have sane default value when resultsPerPage is not set<commit_after>import React from 'react'

import { State, RESULTS_CHANGED, RESULT_CLICKED, VALUES_CHANGED } from './state'

import { Results as RawResults } from '../ui/Results';

class Response extends React.Component {
  constructor(props) {
    super(props)
    this.state = { results: this._state().getResults() || {} };
    this.onResultsChange = this.onResultsChange.bind(this)
  }

  _state() {
    return State.ns(this.props.namespace);
  }

  componentDidMount() {
    this._state().registerListener(RESULTS_CHANGED, this.onResultsChange);
    this._state().registerListener(VALUES_CHANGED, this.onResultsChange);
  }

  componentWillUnmount() {
    this._state().unregisterListener(RESULTS_CHANGED, this.onResultsChange);
    this._state().unregisterListener(VALUES_CHANGED, this.onResultsChange);
  }

  onResultsChange() {
    this.setState({ results: this._state().getResults() || {} });
  }

  render() {
    const { children, Placeholder } = this.props;
    const results = this.state.results;
    const time = results.time;
    const error = this._state().getError();

    if (!time && !error) {
      return Placeholder ? <Placeholder /> : null;
    }

    const propsForChildren = { ...results, error };
    const childrenWithResults = React.Children.map(children, c => {
      if (React.isValidElement(c)) {
        return React.cloneElement(c, propsForChildren);
      }
      return null;
    });

    return
{childrenWithResults}
;
  }
}

Response.defaultProps = {
  namespace: 'default',
}

const Results = props => {
  const { results, error, namespace = "default", showImages } = props;

  if (!results && !error) {
    return null;
  }
  const resultClicked = url =>
    State.ns(namespace).notify(RESULT_CLICKED, url);
  return (
    <RawResults
      data={{ searchResponse: props }}
      resultClicked={resultClicked}
      showImages={showImages}
    />
  );
};

class Summary extends React.Component {
  constructor(props) {
    super(props)
    this.onValuesChange = this.onValuesChange.bind(this)
    this._state = this._state.bind(this)
  }

  _state() {
    return State.ns(this.props.namespace);
  }

  componentDidMount() {
    this._state().registerListener(RESULTS_CHANGED, this.onValuesChange);
  }

  componentWillUnmount() {
    this._state().unregisterListener(RESULTS_CHANGED, this.onValuesChange);
  }

  onValuesChange() {
    this.setState(this._state().getResults() || {});
  }

  render() {
    const values = this._state().getValues();
    const responseValues = this._state().getResponseValues();
    const { time, totalResults, error } = this.props;
    const text = responseValues["q"] || values["q"];

    if (error) {
      return null;
    }

    const page = parseInt(values.page, 10);
    const pageNumber = page && page > 1 ? `Page ${page} of ` : "";
    const runOverride = e => {
      e.preventDefault();
      this._state().setValues({ q: values["q"], "q.override": "true" }, true);
    };
    const override = responseValues["q"] &&
      responseValues["q"].toLowerCase() !== values["q"].toLowerCase()
      ?
          {`search instead for `}
           {values["q"]}

      : null;

    return (

          {`${pageNumber}${totalResults} results for `}
          "{text}"
          {" "}

        {`(${time}) `}
        {override}

    )
  }
}

Summary.defaultProps = {
  namespace: 'default'
}

const pageNumbers = (page, totalPages) => {
  const pages = []

  let i = 2
  while (i >= 0) {
    if (page - i > 0) {
      pages.push(page-i)
    }
    i--
  }

  i = 1
  while (pages.length < 5 && page + i <= totalPages) {
    pages.push(page+i)
    i++
  }

  i = 3
  while (pages.length < 5 && page - i > 0) {
    pages.unshift(page-i)
    i++
  }
  return pages
}

const RawPaginator = ({ resultsPerPage, page, totalResults, setPage, pageFn }) => {
  if (totalResults <= resultsPerPage) {
    return null
  }

  const totalPages = Math.ceil(totalResults/resultsPerPage)
  if (totalPages === 0) {
    return null
  }

  const pages = pageNumbers(page, totalPages).map(p =>
    <Page key={p} page={p} currentPage={page} setPage={setPage}>{p}</Page>
  )

  const prevPage = () => {
    if (page === 1) {
      return
    }
    setPage(page-1)
  }

  const nextPage = () => {
    if (page === totalPages) {
      return
    }
    setPage(page+1)
  }

  return (

<

      {pages}

>

  )
}

const Page = ({ currentPage, page, setPage, children }) => (

 setPage(page)}>{ children }

)

class Paginator extends React.Component {
  render() {
    if (this.props.error) {
      return null;
    }
    const _state = State.ns(this.props.namespace);
    const setPage = (page) => {
      window.scrollTo(0, 0);
      _state.setValues({page: ""+page}, true);
    }
    const values = _state.getValues();

    const page = values.page ? parseInt(values.page, 10) : 1;
    const resultsPerPage = values.resultsPerPage ? parseInt(values.resultsPerPage, 10) : 10;
    const totalResultsInt = parseInt(this.props.totalResults, 10)

    return <RawPaginator setPage={setPage} page={page} resultsPerPage={resultsPerPage} totalResults={totalResultsInt} />
  }
}

Paginator.defaultProps = {
  namespace: 'default'
}

export { Response, Summary, Results, Paginator };
<|endoftext|>


<commit_before>async function serverDockerStuff(args) {
/*
description("The VB6 style docker control communicates with this")
base_component_id("server_docker_stuff")
load_once_from_file(true)
only_run_on_server(true)
*/

    var message = ""
    var msg = function(m) {
        console.log(m)
        message += (m + "\n")
    }
    //
    // On Mac Docker doesn't seem to expose itself via a port by default, so we did
    // this:
    // docker run -d -v /var/run/docker.sock:/var/run/docker.sock -p 127.0.0.1:1234:1234 bobrik/socat TCP-LISTEN:1234,fork UNIX-CONNECT:/var/run/docker.sock
    // export DOCKER_HOST=tcp://localhost:1234
    //
    // Based on this URL:
    // https://github.com/docker/for-mac/issues/770
    //
    var host = 'host.docker.internal'
    var port = 1234
    if (args.host && (args.host.length > 0)) {
        host = args.host
    }
    if (args.port && (args.port > 0)) {
        port = args.port
    }
    var Docker = require('dockerode')
    console.log("//var docker = require('dockerode')")

    var dockerEngine = new Docker({
                host: host,
                port: port,
                version: 'v1.25'
                });

    if (args.create) {
        //await dockerEngine.commit({
                          //      change: 'CMD ["node",  "src/electron.js",   "--runapp",   "demo_timer",   "--nogui",   "true",   "--deleteonexit",   "true",   "--locked",    "false"]'
                          //   }) --= e3b1bd7239df zubairq/yazz2

        try {
            var runningContainers               = await dockerEngine.listContainers()
            var yazzRunningContainerDetails     = null
            var oldRunningAppContainerDetails   = null
            var yazzRunningContainerId          = null
            var yazzRunningContainer               = null

            msg("Checking running containers")
            for (var ewr=0;ewr < runningContainers.length;ewr ++) {
                if (runningContainers[ewr].Image == "zubairq/yazz") {
                    yazzRunningContainerDetails = runningContainers[ewr]
                }
                if (runningContainers[ewr].Image == args.image_name) {
                    oldRunningAppContainerDetails = runningContainers[ewr]
                }
            }

            msg("Checking running app container...")
            if (oldRunningAppContainerDetails != null) {
                msg("    Found and stopping app container: " + oldRunningAppContainerDetails.Id + " for image " + args.image_name)
                await dockerEngine.getContainer(oldRunningAppContainerDetails.Id).stop()
            }
            msg("...Checked.")

            msg("Checking running yazz container...")
            if (yazzRunningContainerDetails != null) {
                yazzRunningContainerId = yazzRunningContainerDetails.Id
                msg("Yazz container found with ID: " + yazzRunningContainerId)
            } else {
                msg("Yazz container NOT found.")
                msg("Creating ...")
                var cc = await dockerEngine.run(     "zubairq/yazz")
                yazzRunningContainerId = cc.Id
                msg("Created with ID " + yazzRunningContainerId + " ...")
            }
            msg("...Checked.")

            yazzRunningContainer = dockerEngine.getContainer( yazzRunningContainerId );

            await yazzRunningContainer.commit({
                changes: 'CMD ["node",  "src/electron.js",   "--runapp",   "demo_timer",   "--nogui",   "true",   "--deleteonexit",   "true",   "--locked",    "false"]'
                ,
                repo: args.image_name
            })

            console.log("args.docker_local_port: " + args.docker_local_port)
            await dockerEngine.run(     args.image_name,
                                   [],
                                   undefined,
                                   {
                                        "HostConfig": {
                                            "PortBindings": {
                                                "80/tcp": [
                                                    {
                                                        "HostPort": args.docker_local_port   //Map container to a random unused port.
                                                    }
                                                ]
                                            }
                                        }
                                    })
        } catch ( err ) {

            msg(err)
        }

        console.log(  message  )
        return {message: message}

    } else {

        var runningContainers = await dockerEngine.listContainers()
        return runningContainers
    }

}
<commit_msg>output for docker save works<commit_after>async function serverDockerStuff(args) {
/*
description("The VB6 style docker control communicates with this")
base_component_id("server_docker_stuff")
load_once_from_file(true)
only_run_on_server(true)
*/

    var message = ""
    var msg = function(m) {
        console.log(m)
        message += (m + "\n")
    }
    //
    // On Mac Docker doesn't seem to expose itself via a port by default, so we did
    // this:
    // docker run -d -v /var/run/docker.sock:/var/run/docker.sock -p 127.0.0.1:1234:1234 bobrik/socat TCP-LISTEN:1234,fork UNIX-CONNECT:/var/run/docker.sock
    // export DOCKER_HOST=tcp://localhost:1234
    //
    // Based on this URL:
    // https://github.com/docker/for-mac/issues/770
    //
    var host = 'host.docker.internal'
    var port = 1234
    if (args.host && (args.host.length > 0)) {
        host = args.host
    }
    if (args.port && (args.port > 0)) {
        port = args.port
    }
    var Docker = require('dockerode')
    console.log("//var docker = require('dockerode')")

    var dockerEngine = new Docker({
                host: host,
                port: port,
                version: 'v1.25'
                });

    if (args.create) {
        //await dockerEngine.commit({
                          //      change: 'CMD ["node",  "src/electron.js",   "--runapp",   "demo_timer",   "--nogui",   "true",   "--deleteonexit",   "true",   "--locked",    "false"]'
                          //   }) --= e3b1bd7239df zubairq/yazz2

        try {
            var runningContainers               = await dockerEngine.listContainers()
            var yazzRunningContainerDetails     = null
            var oldRunningAppContainerDetails   = null
            var yazzRunningContainerId          = null
            var yazzRunningContainer               = null

            msg("Checking running containers")
            for (var ewr=0;ewr < runningContainers.length;ewr ++) {
                if (runningContainers[ewr].Image == "zubairq/yazz") {
                    yazzRunningContainerDetails = runningContainers[ewr]
                }
                if (runningContainers[ewr].Image == args.image_name) {
                    oldRunningAppContainerDetails = runningContainers[ewr]
                }
            }

            msg("Checking running app container...")
            if (oldRunningAppContainerDetails != null) {
                msg("    Found and stopping app container: " + oldRunningAppContainerDetails.Id + " for image " + args.image_name)
                await dockerEngine.getContainer(oldRunningAppContainerDetails.Id).stop()
            }
            msg("...Checked.")

            msg("Checking running yazz container...")
            if (yazzRunningContainerDetails != null) {
                yazzRunningContainerId = yazzRunningContainerDetails.Id
                msg("Yazz container found with ID: " + yazzRunningContainerId)
            } else {
                msg("Yazz container NOT found.")
                msg("Creating ...")
                var cc = await dockerEngine.run(     "zubairq/yazz")
                yazzRunningContainerId = cc.Id
                msg("Created with ID " + yazzRunningContainerId + " ...")
            }
            msg("...Checked.")

            yazzRunningContainer = dockerEngine.getContainer( yazzRunningContainerId );

            await yazzRunningContainer.commit({
                changes: 'CMD ["node",  "src/electron.js",   "--runapp",   "demo_timer",   "--nogui",   "true",   "--deleteonexit",   "true",   "--locked",    "false"]'
                ,
                repo: args.image_name
            })

            msg("args.docker_local_port: " + args.docker_local_port)
            msg("Running app: " + args.image_name)
             dockerEngine.run(     args.image_name,
                                   [],
                                   undefined,
                                   {
                                        "HostConfig": {
                                            "PortBindings": {
                                                "80/tcp": [
                                                    {
                                                        "HostPort": args.docker_local_port   //Map container to a random unused port.
                                                    }
                                                ]
                                            }
                                        }
                                    })
            msg("Done app: " + args.image_name)
        } catch ( err ) {

            msg(err)
        }

        return {message: message}

    } else {

        var runningContainers = await dockerEngine.listContainers()
        return runningContainers
    }

}
<|endoftext|>


<commit_before>app.controller("ListingController", ["$scope", "$uibModal", "ListingService", "AlertService",  function($scope, $uibModal,ListingService, AlertService) {
	$scope.editedListing = {};
	$scope.alerts = [];
	$scope.listings = [];

	/**
	 * opens new listing modal and adds sends listing to the listing API
	 */

	$scope.openListingModal = function() {
		var ListingModalInstance = $uibModal.open({
			templateUrl: "../../js/views/newlisting-modal.php",
			controller: "ListingModal",
			resolve: {
				listing: function() {
					return ($scope.listing);
				}
			}
		});
		ListingModalInstance.result.then(function(listing) {
			$scope.listing = listing;
			ListingService.create(listing)
					.then(function(reply) {
						if(reply.status === 200) {
							$scope.alerts[0] = {type: "success", msg: reply.message};
						} else {
							$scope.alerts[0] = {type: "danger", msg: reply.message};
						}
					});
		}, function() {
			$scope.listing = {};
		});
	};

	/**
	 * sets which listing is being edited and activates the editing form
	 *
	 * @param listing the listing to be edited
	 */

	$scope.setEditedListing = function() {
		$scope.isEditing = true;
	};

	/**
	 * cancels editing doesn't change listing being edited
	 */
	$scope.cancelEditing = function() {
		$scope.editedListing = {};
		$scope.isEditing = false;
	};

	/**
	 * fulfills the promise from retrieving all the listings from the listing API
	 */
	$scope.getListings = function() {
		ListingService.all()
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.listings = result.data.data;
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});
	};
	/**
	 * creates a listing and sends it to the listing API
	 *
	 * @param listing the listing to send
	 * @param validated true is angular validated the form, false if not
	 */
	$scope.createListing = function(listing, validated) {
		if(validated === true) {
			ListingService.create(listing)
					.then(function(result) {
						if(result.data.status === 200) {
							$scope.alerts[0] = {type: "success", msg: result.data.message};
						} else {
							$scope.alerts[0] = {type: "danger", msg: result.data.message};
						}
					});
		}
	};

	///**
	// * fulfills the promise from retrieving the listing by Id from the listing API
	// */
	//$scope.getListings = function() {
	//	ListingService.fetchId()
	//			.then(function(result) {
	//				if(result.data.status === 200) {
	//					$scope.listings = result.data.data;
	//				} else {
	//					$scope.alerts[0] = {type: "danger", msg: result.data.message};
	//				}
	//			});
	//};

	////fulfills the promise from retrieving the listing by org id
	//$scope.getListingsByOrgId = function(orgId, validated) {
	//	if(validated === true) {
	//		ListingService.fetchOrgId(orgId)
	//				.then(function(result) {
	//					if(result.data.status === 200) {
	//						$scope.listings = result.data.data;
	//					} else {
	//						$scope.alerts[0] = {type: "danger", msg: result.data.message};
	//					}
	//				});
	//	}
	//};

	////fulfills the promise from retrieving the listings by parent id
	//$scope.getListingByParentId = function(parentId, validated) {
	//	if(validated === true) {
	//	ListingService.fetchParentId(parentId)
	//			.then(function(result) {
	//				if(result.data.status === 200) {
	//					$scope.listings = result.data.data;
	//				} else {
	//					$scope.alerts[0] = {type: "danger", msg: result.data.message};
	//				}
	//			});
	//	}
	//};

	////fulfills the promise from retrieving the listings by post time
	//$scope.getListingByPostTime = function(postTime, validated) {
	//	if(validated === true) {
	//		ListingService.fetchPostTime(postTime)
	//				.then(function(result) {
	//					if(result.data.status === 200) {
	//						$scope.listings = result.data.data;
	//					} else {
	//						$scope.alerts[0] = {type: "danger", msg: result.data.message};
	//					}
	//				});
	//	}
	//};

	////fulfills the promise from retrieving the listings by Type Id
	//$scope.getListingByTypeId = function(typeId, validated) {
	//	if(validated === true) {
	//		ListingService.fetchTypeId(typeId)
	//				.then(function(result) {
	//					if(result.data.status === 200) {
	//						$scope.listings = result.data.data;
	//					} else {
	//						$scope.alerts[0] = {type: "danger", msg: result.data.message};
	//					}
	//				});
	//	}
	//};

	/**
	 * updates a listing and sends it to the listing API
	 *
	 * @param listing the listing to send
	 * @param validated true is angular validated the form, false if not
	 */
	$scope.updateListing = function(listing, validated) {
		if(validated === true && $scope.isEditing === true) {
			ListingService.update(listing.listingId, listing)
					.then(function(result) {
						if(result.data.status === 200) {
							$scope.alerts[0] = {type: "success", msg: result.data.message};
						} else {
							$scope.alerts[0] = {type: "danger", msg: result.data.message};
						}
					});
		}
	};

	/**
	 * deletes a listing and sends it to the listing API if the user confirms deletion
	 *
	 * @param listingId the listing id of the listing to be deleted
	 */
	$scope.deleteListing = function(listingId) {
		//create a modal instance to prompt the user if she/he is sure they want to delete the listing
		var message = "Are you sure you want to delete this listing?";

		var modalHtml = '
' + message + '

<button class="btn btn-primary" ng-click="yes()">Yes</button><button class="btn btn-warning" ng-click="no()">No</button>
';

		var modalInstance = $uibModad.open({
			template: modalHtml,
			controller: ModalInstanceCtrl
		});

		//if the user clicked yes, delete the listing
		modalInstance.result.then(function() {
			ListingService.destroy(listingId)
					.then(function(result) {
						if(result.data.status === 200) {
							$scope.alerts[0] = {type: "success", msg: result.data.message};
						} else {
							$scope.alerts[0] = {type: "danger", msg: result.data.message};
						}
					})
		});
	};

	////subscribe to the delete channel; this will delete from the listings array on demand
	//Pusher.subscribe("listing", "delete", function(listing){
	//	for(var i = 0; i < $scope.listings.length; i++) {
	//		if($scope.listings[i].listingId ===listing.listingId) {
	//			$scope.listings.splice(i, 1);
	//			break;
	//		}
	//	}
	//});

	////subscribe to the new channel; this will add to the listings array on demand
	//Pusher.subscribe("listing", "new", function(listing){
	//	$scope.listings.push(listing);
	//});

	////subscribe to the update channel; this will update the listings array on demand
	//Pusher.subscribe("listing", "update", function(listing){
	//	for(var i = 0; i < $scope.listings.length; i++) {
	//		if($scope.listings[i].listingId === listing.listingId) {
	//			$scope.listings[i] = listing;
	//			break;
	//		}
	//	}
	//});

	////when the window is closed/reloaded, gracefully close the channel
	//$scope.$on("$destroy", function() {
	//	Pusher.unsubscribe("listings");
	//});

	//load the array on first view
	if($scope.listings.length === 0) {
		$scope.linstings = $scope.getListings();
	}
}]);

//embedded modal instance controller to create deletion prompt
var ModalInstanceCtrl = function($scope,  $uibModalInstance) {
	$scope.yes = function() {
		$uibModalInstance.close();
	};

	$scope.no = function() {
		$uibModalInstance.dismiss('cancel');
	};
};<commit_msg>added method in service to open listing detail modal https://app.asana.com/0/60990639151493/70723740973486<commit_after>app.controller("ListingController", ["$scope", "$uibModal", "ListingService", "AlertService",  function($scope, $uibModal,ListingService, AlertService) {
	$scope.editedListing = {};
	$scope.alerts = [];
	$scope.listings = [];

	/**
	 * opens detail listing modal and allows user to update listing as claimed or not claimed
	 */

	$scope.openListingDetailModal = function() {
		var ListingDetailModalInstance = $uibModal.open({
			templateUrl: "../../js/views/listing-detailview-modal.php",
			controller: "ListingDetailModal",
			resolve: {
				listing: function() {
					return ($scope.listing);
				}
			}
		});

		ListingDetailModalInstance.result.then(function(listing) {
			$scope.listing = listing;
			ListingService.create(listing)
					.then(function(reply) {
						if(reply.status === 200) {
							AlertService.addAlert({type: "success", msg: reply.message});
						} else {
							AlertService.addAlert({type: "danger", msg: reply.message});
						}
					});
		}, function() {
			$scope.listing = {};
		});
	};

	/**
	 * opens new listing modal and adds sends listing to the listing API
	 */

	$scope.openListingModal = function() {
		var ListingModalInstance = $uibModal.open({
			templateUrl: "../../js/views/newlisting-modal.php",
			controller: "ListingModal",
			resolve: {
				listing: function() {
					return ($scope.listing);
				}
			}
		});
		ListingModalInstance.result.then(function(listing) {
			$scope.listing = listing;
			ListingService.create(listing)
					.then(function(reply) {
						if(reply.status === 200) {
							$scope.alerts[0] = {type: "success", msg: reply.message};
						} else {
							$scope.alerts[0] = {type: "danger", msg: reply.message};
						}
					});
		}, function() {
			$scope.listing = {};
		});
	};

	/**
	 * sets which listing is being edited and activates the editing form
	 *
	 * @param listing the listing to be edited
	 */

	$scope.setEditedListing = function() {
		$scope.isEditing = true;
	};

	/**
	 * cancels editing doesn't change listing being edited
	 */
	$scope.cancelEditing = function() {
		$scope.editedListing = {};
		$scope.isEditing = false;
	};

	/**
	 * fulfills the promise from retrieving all the listings from the listing API
	 */
	$scope.getListings = function() {
		ListingService.all()
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.listings = result.data.data;
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});
	};
	/**
	 * creates a listing and sends it to the listing API
	 *
	 * @param listing the listing to send
	 * @param validated true is angular validated the form, false if not
	 */
	$scope.createListing = function(listing, validated) {
		if(validated === true) {
			ListingService.create(listing)
					.then(function(result) {
						if(result.data.status === 200) {
							$scope.alerts[0] = {type: "success", msg: result.data.message};
						} else {
							$scope.alerts[0] = {type: "danger", msg: result.data.message};
						}
					});
		}
	};

	///**
	// * fulfills the promise from retrieving the listing by Id from the listing API
	// */
	//$scope.getListings = function() {
	//	ListingService.fetchId()
	//			.then(function(result) {
	//				if(result.data.status === 200) {
	//					$scope.listings = result.data.data;
	//				} else {
	//					$scope.alerts[0] = {type: "danger", msg: result.data.message};
	//				}
	//			});
	//};

	////fulfills the promise from retrieving the listing by org id
	//$scope.getListingsByOrgId = function(orgId, validated) {
	//	if(validated === true) {
	//		ListingService.fetchOrgId(orgId)
	//				.then(function(result) {
	//					if(result.data.status === 200) {
	//						$scope.listings = result.data.data;
	//					} else {
	//						$scope.alerts[0] = {type: "danger", msg: result.data.message};
	//					}
	//				});
	//	}
	//};

	////fulfills the promise from retrieving the listings by parent id
	//$scope.getListingByParentId = function(parentId, validated) {
	//	if(validated === true) {
	//	ListingService.fetchParentId(parentId)
	//			.then(function(result) {
	//				if(result.data.status === 200) {
	//					$scope.listings = result.data.data;
	//				} else {
	//					$scope.alerts[0] = {type: "danger", msg: result.data.message};
	//				}
	//			});
	//	}
	//};

	////fulfills the promise from retrieving the listings by post time
	//$scope.getListingByPostTime = function(postTime, validated) {
	//	if(validated === true) {
	//		ListingService.fetchPostTime(postTime)
	//				.then(function(result) {
	//					if(result.data.status === 200) {
	//						$scope.listings = result.data.data;
	//					} else {
	//						$scope.alerts[0] = {type: "danger", msg: result.data.message};
	//					}
	//				});
	//	}
	//};

	////fulfills the promise from retrieving the listings by Type Id
	//$scope.getListingByTypeId = function(typeId, validated) {
	//	if(validated === true) {
	//		ListingService.fetchTypeId(typeId)
	//				.then(function(result) {
	//					if(result.data.status === 200) {
	//						$scope.listings = result.data.data;
	//					} else {
	//						$scope.alerts[0] = {type: "danger", msg: result.data.message};
	//					}
	//				});
	//	}
	//};

	/**
	 * updates a listing and sends it to the listing API
	 *
	 * @param listing the listing to send
	 * @param validated true is angular validated the form, false if not
	 */
	$scope.updateListing = function(listing, validated) {
		if(validated === true && $scope.isEditing === true) {
			ListingService.update(listing.listingId, listing)
					.then(function(result) {
						if(result.data.status === 200) {
							$scope.alerts[0] = {type: "success", msg: result.data.message};
						} else {
							$scope.alerts[0] = {type: "danger", msg: result.data.message};
						}
					});
		}
	};

	/**
	 * deletes a listing and sends it to the listing API if the user confirms deletion
	 *
	 * @param listingId the listing id of the listing to be deleted
	 */
	$scope.deleteListing = function(listingId) {
		//create a modal instance to prompt the user if she/he is sure they want to delete the listing
		var message = "Are you sure you want to delete this listing?";

		var modalHtml = '
' + message + '

<button class="btn btn-primary" ng-click="yes()">Yes</button><button class="btn btn-warning" ng-click="no()">No</button>
';

		var modalInstance = $uibModad.open({
			template: modalHtml,
			controller: ModalInstanceCtrl
		});

		//if the user clicked yes, delete the listing
		modalInstance.result.then(function() {
			ListingService.destroy(listingId)
					.then(function(result) {
						if(result.data.status === 200) {
							$scope.alerts[0] = {type: "success", msg: result.data.message};
						} else {
							$scope.alerts[0] = {type: "danger", msg: result.data.message};
						}
					})
		});
	};

	////subscribe to the delete channel; this will delete from the listings array on demand
	//Pusher.subscribe("listing", "delete", function(listing){
	//	for(var i = 0; i < $scope.listings.length; i++) {
	//		if($scope.listings[i].listingId ===listing.listingId) {
	//			$scope.listings.splice(i, 1);
	//			break;
	//		}
	//	}
	//});

	////subscribe to the new channel; this will add to the listings array on demand
	//Pusher.subscribe("listing", "new", function(listing){
	//	$scope.listings.push(listing);
	//});

	////subscribe to the update channel; this will update the listings array on demand
	//Pusher.subscribe("listing", "update", function(listing){
	//	for(var i = 0; i < $scope.listings.length; i++) {
	//		if($scope.listings[i].listingId === listing.listingId) {
	//			$scope.listings[i] = listing;
	//			break;
	//		}
	//	}
	//});

	////when the window is closed/reloaded, gracefully close the channel
	//$scope.$on("$destroy", function() {
	//	Pusher.unsubscribe("listings");
	//});

	//load the array on first view
	if($scope.listings.length === 0) {
		$scope.linstings = $scope.getListings();
	}
}]);

//embedded modal instance controller to create deletion prompt
var ModalInstanceCtrl = function($scope,  $uibModalInstance) {
	$scope.yes = function() {
		$uibModalInstance.close();
	};

	$scope.no = function() {
		$uibModalInstance.dismiss('cancel');
	};
};<|endoftext|>


<commit_before>const aggQuery = () => ({
  histogram: {
    field: 'income.latest.total',
    script: 'Math.log10(_value)',
    interval: 0.5,
    extended_bounds: {
      min: 0,
      max: 9,
    },
  },
  aggs: {
    total_income: {
      sum: {
        field: 'income.latest.total',
      },
    },
  },
})

const parseResponse = aggregation => {
  const buckets = aggregation.buckets.map(x => ({
    id: `${x.key}`,
    key: `${x.key}`,
    name: `Min. £${Math.round(Math.pow(10, x.key))}`,
    count: x.doc_count,
    sumIncome: x.total_income.value,
  }))
  return {
    buckets,
  }
}

module.exports = {
  aggQuery,
  parseResponse,
}
<commit_msg>fix(aggregate): amend latest income field<commit_after>const LATEST_INCOME_FIELD = 'financial.latest.income'

const aggQuery = () => ({
  histogram: {
    field: LATEST_INCOME_FIELD,
    script: 'Math.log10(_value)',
    interval: 0.5,
    extended_bounds: {
      min: 0,
      max: 9,
    },
  },
  aggs: {
    total_income: {
      sum: {
        field: LATEST_INCOME_FIELD,
      },
    },
  },
})

const parseResponse = aggregation => {
  const buckets = aggregation.buckets.map(x => ({
    id: `${x.key}`,
    key: `${x.key}`,
    name: `Min. £${Math.round(Math.pow(10, x.key))}`,
    count: x.doc_count,
    sumIncome: x.total_income.value,
  }))
  return {
    buckets,
  }
}

module.exports = {
  aggQuery,
  parseResponse,
}
<|endoftext|>


<commit_before>var App = require('./application');

module.exports.app    = App;

module.exports = function(Obj, cb){
	if(Obj){
		App(Obj, function(err, app){
			if(err) return cb(err, Obj);
			else return cb(null, app);
		});
	} else {
		return cb({type:'!No READ Item'}, Obj);
	}
};
<commit_msg>Read modification<commit_after>var App = require('./application');

module.exports.app    = App;

module.exports = function(Obj, cb){
	if(Obj){
		if(Obj.user){
			App({user:Obj.user}, function(err, app){
				if(err) return cb(err, Obj);
				else return cb(null, app);
			});
		} else {
			App({_id:Obj.id}, function(err, app){
				if(err) return cb(err, Obj);
				else return cb(null, app);
			});
		}
	} else {
		return cb({type:'!No READ Item'}, Obj);
	}
};
<|endoftext|>


<commit_before>'use strict';

var Actions = require('../constants/Actions');
var _ = require('lodash');
var NavigationActions = require('./NavigationActions');
var SearchUtils = require('../lib/search-utils');

module.exports = {
    loadTopHairfies: function (context, params) {
        return context.hairfieApi
            .get('/tops/hairfies', { query: { limit: 5 } })
            .then(function (hairfies) {
                context.dispatch(Actions.RECEIVE_TOP_HAIRFIES, hairfies);
            });
    },
    loadHairfie: function (context, id) {
        return context.hairfieApi
            .get('/hairfies/'+id)
            .then(function (hairfie) {
                context.dispatch(Actions.RECEIVE_HAIRFIE, hairfie);
            });
    },
    loadBusinessTopHairfies: function (context, businessId) {
        var query = {
            'filter[where][businessId]': businessId,
            'filter[order]': 'createdAt DESC',
            'filter[limit]': 10
        };

        return context.hairfieApi
            .get('/hairfies', { query: query })
            .then(function (hairfies) {
                context.dispatch(Actions.RECEIVE_BUSINESS_TOP_HAIRFIES, {
                    businessId: businessId,
                    hairfies: hairfies
                });
            });
    },
    loadBusinessHairfies: function (context, params) {
        var params = _.merge({}, { page: 1, pageSize: 12 }, params);

        var query = {
            'filter[where][businessId]': params.businessId,
            'filter[order]': 'createdAt DESC',
            'filter[skip]': (params.page - 1) * params.pageSize,
            'filter[limit]': params.pageSize
        };

        return  context.hairfieApi
            .get('/hairfies', { query: query })
            .then(function (hairfies) {
                context.dispatch(Actions.RECEIVE_BUSINESS_HAIRFIES, {
                    businessId: params.businessId,
                    hairfies: hairfies
                });
            });
    },
    submitSearch: function (context, search) {
        var search = _.merge({ address: 'Paris, France' }, search);
        var params = SearchUtils.searchToRouteParams(search);

        return context.executeAction(NavigationActions.navigate, {
            route: 'hairfie_search',
            params: params.path,
            query: params.query
        });
    },
    loadSearchResult: function (context, search) {
        var query = { pageSize: 12 };
        query.page = search.page;
        if (search.location) {
            query.location = [
                search.location.lat,
                search.location.lng
            ].join(',');
            query.radius = search.radius;
        }
        if (search.bounds) {
            query.bounds = [
                search.bounds.southWest.lat,
                search.bounds.southWest.lng,
                search.bounds.northEast.lat,
                search.bounds.northEast.lng
            ].join(',');
        }

        _.forEach(search.tags, function (tag, i) {
            query['tags['+i+']'] = tag;
        });
        if (search.priceMin) query.priceMin = search.priceMin;
        if (search.priceMax) query.priceMin = search.priceMax;

        return context.hairfieApi
            .get('/hairfies/search', { query: query })
            .then(function (result) {
                context.dispatch(Actions.RECEIVE_HAIRFIE_SEARCH_RESULT, {
                    search: search,
                    result: result
                });
            });
    }
};
<commit_msg>Correct PriceMin -> PriceMax<commit_after>'use strict';

var Actions = require('../constants/Actions');
var _ = require('lodash');
var NavigationActions = require('./NavigationActions');
var SearchUtils = require('../lib/search-utils');

module.exports = {
    loadTopHairfies: function (context, params) {
        return context.hairfieApi
            .get('/tops/hairfies', { query: { limit: 5 } })
            .then(function (hairfies) {
                context.dispatch(Actions.RECEIVE_TOP_HAIRFIES, hairfies);
            });
    },
    loadHairfie: function (context, id) {
        return context.hairfieApi
            .get('/hairfies/'+id)
            .then(function (hairfie) {
                context.dispatch(Actions.RECEIVE_HAIRFIE, hairfie);
            });
    },
    loadBusinessTopHairfies: function (context, businessId) {
        var query = {
            'filter[where][businessId]': businessId,
            'filter[order]': 'createdAt DESC',
            'filter[limit]': 10
        };

        return context.hairfieApi
            .get('/hairfies', { query: query })
            .then(function (hairfies) {
                context.dispatch(Actions.RECEIVE_BUSINESS_TOP_HAIRFIES, {
                    businessId: businessId,
                    hairfies: hairfies
                });
            });
    },
    loadBusinessHairfies: function (context, params) {
        var params = _.merge({}, { page: 1, pageSize: 12 }, params);

        var query = {
            'filter[where][businessId]': params.businessId,
            'filter[order]': 'createdAt DESC',
            'filter[skip]': (params.page - 1) * params.pageSize,
            'filter[limit]': params.pageSize
        };

        return  context.hairfieApi
            .get('/hairfies', { query: query })
            .then(function (hairfies) {
                context.dispatch(Actions.RECEIVE_BUSINESS_HAIRFIES, {
                    businessId: params.businessId,
                    hairfies: hairfies
                });
            });
    },
    submitSearch: function (context, search) {
        var search = _.merge({ address: 'Paris, France' }, search);
        var params = SearchUtils.searchToRouteParams(search);

        return context.executeAction(NavigationActions.navigate, {
            route: 'hairfie_search',
            params: params.path,
            query: params.query
        });
    },
    loadSearchResult: function (context, search) {
        var query = { pageSize: 12 };
        query.page = search.page;
        if (search.location) {
            query.location = [
                search.location.lat,
                search.location.lng
            ].join(',');
            query.radius = search.radius;
        }
        if (search.bounds) {
            query.bounds = [
                search.bounds.southWest.lat,
                search.bounds.southWest.lng,
                search.bounds.northEast.lat,
                search.bounds.northEast.lng
            ].join(',');
        }

        _.forEach(search.tags, function (tag, i) {
            query['tags['+i+']'] = tag;
        });
        if (search.priceMin) query.priceMin = search.priceMin;
        if (search.priceMax) query.priceMax = search.priceMax;

        return context.hairfieApi
            .get('/hairfies/search', { query: query })
            .then(function (result) {
                context.dispatch(Actions.RECEIVE_HAIRFIE_SEARCH_RESULT, {
                    search: search,
                    result: result
                });
            });
    }
};
<|endoftext|>


<commit_before>/**
* Copyright 2012-2017, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Axes = require('../../plots/cartesian/axes');
var attributes = require('./attributes');

module.exports = function hoverPoints(pointData, xval, yval) {
    var cd = pointData.cd;
    var trace = cd[0].trace;
    var geo = pointData.subplot;

    var pt, i, j, isInside;

    for(i = 0; i < cd.length; i++) {
        pt = cd[i];
        isInside = false;

        if(pt._polygons) {
            for(j = 0; j < pt._polygons.length; j++) {
                if(pt._polygons[j].contains([xval, yval])) {
                    isInside = !isInside;
                }
                // for polygons that cross antimeridian as xval is in [-180, 180]
                if(pt._polygons[j].contains([xval + 360, yval])) {
                    isInside = !isInside;
                }
            }

            if(isInside) break;
        }
    }

    if(!isInside || !pt) return;

    pointData.x0 = pointData.x1 = pointData.xa.c2p(pt.ct);
    pointData.y0 = pointData.y1 = pointData.ya.c2p(pt.ct);

    pointData.index = pt.index;
    pointData.location = pt.loc;
    pointData.z = pt.z;

    makeHoverInfo(pointData, trace, pt, geo.mockAxis);

    return [pointData];
};

function makeHoverInfo(pointData, trace, pt, axis) {
    var hoverinfo = pt.hi || trace.hoverinfo;

    var parts = (hoverinfo === 'all') ?
        attributes.hoverinfo.flags :
        hoverinfo.split('+');

    var hasName = (parts.indexOf('name') !== -1);
    var hasLocation = (parts.indexOf('location') !== -1);
    var hasZ = (parts.indexOf('z') !== -1);
    var hasText = (parts.indexOf('text') !== -1);
    var hasIdAsNameLabel = !hasName && hasLocation;

    var text = [];

    function formatter(val) {
        return Axes.tickText(axis, axis.c2l(val), 'hover').text;
    }

    if(hasIdAsNameLabel) {
        pointData.nameOverride = pt.loc;
    } else {
        if(hasName) pointData.nameOverride = trace.name;
        if(hasLocation) text.push(pt.loc);
    }

    if(hasZ) text.push(formatter(pt.z));
    if(hasText) {
        var tx;

        if(pt.tx) tx = pt.tx;
        else if(trace.text) tx = trace.text;

        if(!Array.isArray(tx)) text.push(tx);
    }

    pointData.extraText = text.join('
');
}
<commit_msg>use extractOption in choropleth hover<commit_after>/**
* Copyright 2012-2017, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');
var Axes = require('../../plots/cartesian/axes');
var attributes = require('./attributes');

module.exports = function hoverPoints(pointData, xval, yval) {
    var cd = pointData.cd;
    var trace = cd[0].trace;
    var geo = pointData.subplot;

    var pt, i, j, isInside;

    for(i = 0; i < cd.length; i++) {
        pt = cd[i];
        isInside = false;

        if(pt._polygons) {
            for(j = 0; j < pt._polygons.length; j++) {
                if(pt._polygons[j].contains([xval, yval])) {
                    isInside = !isInside;
                }
                // for polygons that cross antimeridian as xval is in [-180, 180]
                if(pt._polygons[j].contains([xval + 360, yval])) {
                    isInside = !isInside;
                }
            }

            if(isInside) break;
        }
    }

    if(!isInside || !pt) return;

    pointData.x0 = pointData.x1 = pointData.xa.c2p(pt.ct);
    pointData.y0 = pointData.y1 = pointData.ya.c2p(pt.ct);

    pointData.index = pt.index;
    pointData.location = pt.loc;
    pointData.z = pt.z;

    makeHoverInfo(pointData, trace, pt, geo.mockAxis);

    return [pointData];
};

function makeHoverInfo(pointData, trace, pt, axis) {
    var hoverinfo = pt.hi || trace.hoverinfo;

    var parts = (hoverinfo === 'all') ?
        attributes.hoverinfo.flags :
        hoverinfo.split('+');

    var hasName = (parts.indexOf('name') !== -1);
    var hasLocation = (parts.indexOf('location') !== -1);
    var hasZ = (parts.indexOf('z') !== -1);
    var hasText = (parts.indexOf('text') !== -1);
    var hasIdAsNameLabel = !hasName && hasLocation;

    var text = [];

    function formatter(val) {
        return Axes.tickText(axis, axis.c2l(val), 'hover').text;
    }

    if(hasIdAsNameLabel) {
        pointData.nameOverride = pt.loc;
    } else {
        if(hasName) pointData.nameOverride = trace.name;
        if(hasLocation) text.push(pt.loc);
    }

    if(hasZ) text.push(formatter(pt.z));
    if(hasText) {
        var tx = Lib.extractOption(pt, trace, 'tx', 'text');
        if(tx && tx !== '') text.push(tx);
    }

    pointData.extraText = text.join('
');
}
<|endoftext|>


<commit_before>// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/

/**
 * Disable the eslint "strict" and "no-commonjs" rules, since this is a script
 * that runs in node without any babel support, so it's not not a module
 * implicitly running in strict mode, and we can't use the import syntax.
 */
/* eslint-disable strict */
/* eslint-disable import/no-commonjs */

/* eslint-disable global-require */

'use strict';

require('babel-polyfill');
require('babel-register')();

const { logger } = require('./logging');
const semver = require('semver');
const checkDependencies = require('check-dependencies');
const VALID_NODE_VERSION_RANGE = require('../package.json').engines.node;

const handleDepsCheckFailed = result => {
  logger.error('Dependency checks failed.');
  result.error.forEach(err => logger.error(err));
  process.exit(1);
};

const handleTaskFailed = err => {
  logger.error('Build failed.');
  logger.error(err);
  process.exit(1);
};

const checkNodeVersion = version => {
  // Strip out the 'v' in version, since `process.version`
  // returns `v5.8.0`.
  version = version.replace(/v/g, '');

  if (!semver.satisfies(version, VALID_NODE_VERSION_RANGE)) {
    /* eslint-disable quotes */
    logger.error(`*****\n` +
                 `You are currently running node v${version}. Your version of node ` +
                 `must satisfy ${VALID_NODE_VERSION_RANGE}, or else strange things ` +
                 `could happen. Please upgrade your version of node, or use a ` +
                 `node version manager, like nvm:\n` +
                 `https://github.com/creationix/nvm\n` +
                 `*****\n`);
    /* eslint-enable quotes */
  }
};

const handleDepsCheckSucceeded = () => {
  const argv = process.argv;
  const tasks = require('./tasks').default;
  const handlers = {
    '--build-deps': () => tasks.buildDeps(),
    '--build': () => tasks.build(),
    '--serve': () => tasks.serve(),
    '--run': args => tasks.run(args),
    '--run-dev': args => tasks.runDev(args),
    '--package': () => tasks.package(),
    '--test': args => tasks.test(args),
  };
  main(argv, tasks, handlers, handleTaskFailed);
};

function main(argv, tasks, handlers, catcher) {
  const outstanding = [];

  for (const handler of Object.entries(handlers)) {
    const command = handler[0];
    const runner = handler[1];
    if (~argv.indexOf(command)) {
      const args = argv.slice(1 + argv.indexOf(command));
      outstanding.push(runner(args));
    }
  }

  checkNodeVersion(process.version);

  return Promise.all(outstanding).then(null, catcher);
}

// This is a script that runs in node without any babel support.
module.exports = main;

// Only auto-run `checkDependencies` if this is *not* imported as a module.
// If `require.main` is `module`, then this is ran as a script.
if (require.main === module) {
  checkDependencies(result => {
    if (!result.depsWereOk) {
      handleDepsCheckFailed(result);
    } else {
      handleDepsCheckSucceeded();
    }
  });
}
<commit_msg>Check node version before anything else when running a build script<commit_after>// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/

/**
 * Disable the eslint "strict" and "no-commonjs" rules, since this is a script
 * that runs in node without any babel support, so it's not not a module
 * implicitly running in strict mode, and we can't use the import syntax.
 */
/* eslint-disable strict */
/* eslint-disable import/no-commonjs */

/* eslint-disable global-require */

'use strict';

require('babel-polyfill');
require('babel-register')();

const { logger } = require('./logging');
const semver = require('semver');
const checkDependencies = require('check-dependencies');
const VALID_NODE_VERSION_RANGE = require('../package.json').engines.node;

const handleDepsCheckFailed = result => {
  logger.error('Dependency checks failed.');
  result.error.forEach(err => logger.error(err));
  process.exit(1);
};

const handleTaskFailed = err => {
  logger.error('Build failed.');
  logger.error(err);
  process.exit(1);
};

const checkNodeVersion = version => {
  // Strip out the 'v' in version, since `process.version`
  // returns `v5.8.0`.
  version = version.replace(/v/g, '');

  if (!semver.satisfies(version, VALID_NODE_VERSION_RANGE)) {
    /* eslint-disable quotes */
    logger.error(`*****\n` +
                 `You are currently running node v${version}. Your version of node ` +
                 `must satisfy ${VALID_NODE_VERSION_RANGE}, or else strange things ` +
                 `could happen. Please upgrade your version of node, or use a ` +
                 `node version manager, like nvm:\n` +
                 `https://github.com/creationix/nvm\n` +
                 `*****\n`);
    /* eslint-enable quotes */
  }
};

const handleDepsCheckSucceeded = () => {
  const argv = process.argv;
  const tasks = require('./tasks').default;
  const handlers = {
    '--build-deps': () => tasks.buildDeps(),
    '--build': () => tasks.build(),
    '--serve': () => tasks.serve(),
    '--run': args => tasks.run(args),
    '--run-dev': args => tasks.runDev(args),
    '--package': () => tasks.package(),
    '--test': args => tasks.test(args),
  };
  main(argv, tasks, handlers, handleTaskFailed);
};

function main(argv, tasks, handlers, catcher) {
  const outstanding = [];

  for (const handler of Object.entries(handlers)) {
    const command = handler[0];
    const runner = handler[1];
    if (~argv.indexOf(command)) {
      const args = argv.slice(1 + argv.indexOf(command));
      outstanding.push(runner(args));
    }
  }

  return Promise.all(outstanding).then(null, catcher);
}

// This is a script that runs in node without any babel support.
module.exports = main;

// Only auto-run `checkDependencies` if this is *not* imported as a module.
// If `require.main` is `module`, then this is ran as a script.
if (require.main === module) {
  checkNodeVersion(process.version);
  checkDependencies(result => {
    if (!result.depsWereOk) {
      handleDepsCheckFailed(result);
    } else {
      handleDepsCheckSucceeded();
    }
  });
}
<|endoftext|>


<commit_before>'use strict';

const storageManager = require('./../StorageManager'),
    Container = require('./../model/Container'),
    ResponseHeader = require('./../model/ResponseHeader');

class LeaseContainer {
    constructor() {
    }
    // LeaseTests.cs:7813
    // List Containers returns wrong values, is not yet integrated with leases.
    process(req, res, containerName) {
        const container = new Container(containerName, req.headers, req.rawHeaders)
        storageManager.leaseContainer(container)
            .then((result) => {
                res.set(new ResponseHeader(result.props));
                res.status(result.statusCode).send();
            })
            .catch((e) => {
                res.status(e.statusCode || 500).send(e.message);
                if (!e.statusCode) throw e;
            });
    }
}

module.exports = new LeaseContainer();<commit_msg>removed debug comments<commit_after>'use strict';

const storageManager = require('./../StorageManager'),
    Container = require('./../model/Container'),
    ResponseHeader = require('./../model/ResponseHeader');

class LeaseContainer {
    constructor() {
    }
    process(req, res, containerName) {
        const container = new Container(containerName, req.headers, req.rawHeaders)
        storageManager.leaseContainer(container)
            .then((result) => {
                res.set(new ResponseHeader(result.props));
                res.status(result.statusCode).send();
            })
            .catch((e) => {
                res.status(e.statusCode || 500).send(e.message);
                if (!e.statusCode) throw e;
            });
    }
}

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


<commit_before>import RavenLogger from 'meteor/flowkey:raven';
import { Meteor } from 'meteor/meteor';

const ravenOptions = {};

export const ravenLogger = new RavenLogger({
  publicDSN: Meteor.settings.public.sentryPublicDSN,
  shouldCatchConsoleError: true, // default true
  trackUser: true, // default false
}, ravenOptions);
<commit_msg>Make raven use optional<commit_after>import RavenLogger from 'meteor/flowkey:raven';
import { Meteor } from 'meteor/meteor';

const ravenOptions = {};

const enabled = Meteor.settings.public.sentryPublicDSN && Meteor.settings.public.sentryPublicDSN.length > 0;

export const ravenLogger = enabled ? new RavenLogger({
  publicDSN: Meteor.settings.public.sentryPublicDSN,
  shouldCatchConsoleError: true, // default true
  trackUser: true, // default false
}, ravenOptions) : { log: (error) => { console.log(error); } };
<|endoftext|>


<commit_before>app.controller('SignoutController', ["$scope", "$window", "SignoutService", function($scope, $window, SignoutService) {
	SignoutService.signout()
		.then(function() {
			$window.location = ".";
		});
}]);

<commit_msg>writing signin-controller<commit_after>app.controller('SignoutController', ["$scope", "SignoutService", function($scope,  SignoutService) {
	SignoutService.signout()
		.then(function() {

		});
}]);

<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * 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.
 * =============================================================================
 */

/** Get the domain of the user's email

  @param {!object}
    github enables querying for PR and also create issue using rest endpoint
    username has the login username of the Pull Request Event
  @return {string} Return the domain name of the user's email. Empty string if not found
*/

const get_email_domain = async ({github, username}) => {
  const user = await github.rest.users.getByUsername({
    username
  });
  if (user.status >= 400) {
    console.log(user);
    throw `Error Getting user data for ${username}`;
  }
  const email = user.data.email;
  let domain = "";
  if (email && email.lastIndexOf("@") != -1)
    domain = email.substring(email.lastIndexOf("@") +1);
  console.log(domain);
  return domain;
};

/** For trusted parters like Intel, we want to auto-run tests and mark the PR as ready to pull
    This allows us to reduce the delay to external partners
    Add Labels - kokoro:force-run, ready to pull
    The PR is also assigned to specific teams to fast track review
    Additional reviewers can be added manually based on PR contents
  @param {!object}
    github enables querying for PR and also create issue using rest endpoint
    context has the commit message details in the payload
  @return {string} Returns the message with labels attached and assignees added
*/
const filter_action = async ({github, context, domain}) => {
  const labels = ['kokoro:force-run', 'ready to pull'];

  let assignees = [];
  const title = context.payload.pull_request && context.payload.pull_request.title;
  const onednn_assignees = ['penpornk'];
  if (title && title.toLowerCase().includes("onednn"))
    assignees = onednn_assignees;
  const intel_windows_assignees = ['nitins17', 'learning-to-play'];
  if (title && title.toLowerCase().includes('intel') &&
      title.toLowerCase().includes('windows') && domain.includes('intel.com'))
    assignees = intel_windows_assignees;
  const apple_silicon_assignees = ['penpornk', 'nitins17'];
  if (title && title.toLowerCase().includes('apple') &&
      title.toLowerCase().includes('silicon') && domain.includes('apple.com'))
    assignees = apple_silicon_assignees;
  if (title && title.toLowerCase().includes('nvidia') &&
      domain.includes('nvidia.com')) {
    if (title.toLowerCase().includes('jax')) {
      assignees.push('hawkinsp', 'yashk2810', 'skye');
    }
    if (title.toLowerCase().includes('xla') ||
        title.toLowerCase().includes('gpu')) {
      assignees.push('cheshire', 'gcforster', 'reedwm', 'chsigg');
    }
    if (title.toLowerCase().includes('tf')) {
      assignees.push('rohan100jain', 'bfontain', 'penpornk');
    }
  }

  const resp_label = await github.rest.issues.addLabels({
    issue_number: context.issue.number,
    owner: context.repo.owner,
    repo: context.repo.repo,
    labels: labels
  });
  if (resp_label.status >= 400) {
    console.log(resp_label);
    throw "Error adding labels to PR";
  }
  if (assignees.length > 0) {
    const resp_assign = await github.rest.issues.addAssignees({
      issue_number: context.issue.number,
      owner: context.repo.owner,
      repo: context.repo.repo,
      assignees: assignees
    });
    if (resp_assign.status >= 400) {
      console.log(resp_assign);
      throw "Error adding assignee to PR";
    }
  }
  return `PR Updated successfully with Labels: ${labels} with Assignees: ${assignees}`;
};

module.exports = {
  filter: filter_action,
  get_email_domain
};
<commit_msg>Remove penpornk from NVIDIA TF reviewer list.<commit_after>/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * 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.
 * =============================================================================
 */

/** Get the domain of the user's email

  @param {!object}
    github enables querying for PR and also create issue using rest endpoint
    username has the login username of the Pull Request Event
  @return {string} Return the domain name of the user's email. Empty string if not found
*/

const get_email_domain = async ({github, username}) => {
  const user = await github.rest.users.getByUsername({
    username
  });
  if (user.status >= 400) {
    console.log(user);
    throw `Error Getting user data for ${username}`;
  }
  const email = user.data.email;
  let domain = "";
  if (email && email.lastIndexOf("@") != -1)
    domain = email.substring(email.lastIndexOf("@") +1);
  console.log(domain);
  return domain;
};

/** For trusted parters like Intel, we want to auto-run tests and mark the PR as ready to pull
    This allows us to reduce the delay to external partners
    Add Labels - kokoro:force-run, ready to pull
    The PR is also assigned to specific teams to fast track review
    Additional reviewers can be added manually based on PR contents
  @param {!object}
    github enables querying for PR and also create issue using rest endpoint
    context has the commit message details in the payload
  @return {string} Returns the message with labels attached and assignees added
*/
const filter_action = async ({github, context, domain}) => {
  const labels = ['kokoro:force-run', 'ready to pull'];

  let assignees = [];
  const title = context.payload.pull_request && context.payload.pull_request.title;
  const onednn_assignees = ['penpornk'];
  if (title && title.toLowerCase().includes("onednn"))
    assignees = onednn_assignees;
  const intel_windows_assignees = ['nitins17', 'learning-to-play'];
  if (title && title.toLowerCase().includes('intel') &&
      title.toLowerCase().includes('windows') && domain.includes('intel.com'))
    assignees = intel_windows_assignees;
  const apple_silicon_assignees = ['penpornk', 'nitins17'];
  if (title && title.toLowerCase().includes('apple') &&
      title.toLowerCase().includes('silicon') && domain.includes('apple.com'))
    assignees = apple_silicon_assignees;
  if (title && title.toLowerCase().includes('nvidia') &&
      domain.includes('nvidia.com')) {
    if (title.toLowerCase().includes('jax')) {
      assignees.push('hawkinsp', 'yashk2810', 'skye');
    }
    if (title.toLowerCase().includes('xla') ||
        title.toLowerCase().includes('gpu')) {
      assignees.push('cheshire', 'gcforster', 'reedwm', 'chsigg');
    }
    if (title.toLowerCase().includes('tf')) {
      assignees.push('rohan100jain', 'bfontain');
    }
  }

  const resp_label = await github.rest.issues.addLabels({
    issue_number: context.issue.number,
    owner: context.repo.owner,
    repo: context.repo.repo,
    labels: labels
  });
  if (resp_label.status >= 400) {
    console.log(resp_label);
    throw "Error adding labels to PR";
  }
  if (assignees.length > 0) {
    const resp_assign = await github.rest.issues.addAssignees({
      issue_number: context.issue.number,
      owner: context.repo.owner,
      repo: context.repo.repo,
      assignees: assignees
    });
    if (resp_assign.status >= 400) {
      console.log(resp_assign);
      throw "Error adding assignee to PR";
    }
  }
  return `PR Updated successfully with Labels: ${labels} with Assignees: ${assignees}`;
};

module.exports = {
  filter: filter_action,
  get_email_domain
};
<|endoftext|>


<commit_before>module.exports = {
  name: 'Get Song Lyrics',
  section: 'Other Stuff',

  subtitle (data) {
    const info = ['Title', 'Artist', 'Lyrics', 'URL']
    return `Get Lyrics - ${info[parseInt(data.info)]}`
  },

  variableStorage (data, varType) {
    const type = parseInt(data.storage)
    if (type !== varType) return
    const info = parseInt(data.info)
    let dataType = 'Unknown Song Type'
    switch (info) {
      case 0:
        dataType = 'Song Name'
        break
      case 1:
        dataType = 'Song Artist'
        break
      case 2:
        dataType = 'Song Lyrics'
        break
      case 3:
        dataType = 'Song URL'
        break
    }
    return ([data.varName, dataType])
  },

  fields: ['song', 'key', 'info', 'storage', 'varName'],

  html (isEvent, data) {
    return `

      Song to Search:

      <textarea id="song" rows="2" placeholder="Write a song name here or use variables..." style="width: 95%; font-family: monospace; white-space: nowrap; resize: none;"></textarea>

      API Key:

      <textarea id="key" rows="2" placeholder="Write your key. Get one from Genius." style="width: 95%; font-family: monospace; white-space: nowrap; resize: none;"></textarea>

      Source Info:

      <select id="info" class="round">
        <option value="0" selected>Song Title</option>
        <option value="1">Song Artist</option>
        <option value="2">Song Lyrics</option>
        <option value="3">Song URL</option>
      </select>

        Store In:

        <select id="storage" class="round" onchange="glob.variableChange(this, 'varNameContainer')">
          ${data.variables[0]}
        </select>

        Variable Name:

        <input id="varName" class="round" type="text">

        To get an API key, create a new app on https://genius.com/api-clients/new or check a tutorial by clicking here.

`
  },

  init () {
    const { glob, document } = this
    glob.variableChange(document.getElementById('storage'), 'varNameContainer')
  },

  action (cache) {
    const _this = this
    const data = cache.actions[cache.index]
    const info = parseInt(data.info)
    const geniustoken = this.evalMessage(data.key, cache)
    const songname = this.evalMessage(data.song, cache)

    const Mods = this.getMods()
    const analyrics = Mods.require('analyrics')

    analyrics.setToken(`${geniustoken}`)

    analyrics.getSong(`${songname}`, (song) => {
      let result
      switch (info) {
        case 0:
          result = song.title
          break
        case 1:
          result = song.artist
          break
        case 2:
          result = song.lyrics
          break
        case 3:
          result = song.url
          break
        default:
          break
      }
      if (result !== undefined) {
        const storage = parseInt(data.storage)
        const varName2 = _this.evalMessage(data.varName, cache)
        _this.storeValue(result, storage, varName2, cache)
      }
      _this.callNextAction(cache)
    })
  },

  mod () {}
}
<commit_msg>style(mods): useless template literals, datatypes (#572)<commit_after>module.exports = {
  name: 'Get Song Lyrics',
  section: 'Other Stuff',

  subtitle (data) {
    const info = ['Title', 'Artist', 'Lyrics', 'URL']
    return `Get Lyrics - ${info[parseInt(data.info)]}`
  },

  variableStorage (data, varType) {
    const type = parseInt(data.storage)
    if (type !== varType) return
    const info = parseInt(data.info)
    let dataType = 'Unknown Type'
    switch (info) {
      case 0:
        dataType = 'String'
        break
      case 1:
        dataType = 'String'
        break
      case 2:
        dataType = 'String'
        break
      case 3:
        dataType = 'URL'
        break
    }
    return ([data.varName, dataType])
  },

  fields: ['song', 'key', 'info', 'storage', 'varName'],

  html (isEvent, data) {
    return `

      Song to Search:

      <textarea id="song" rows="2" placeholder="Write a song name here or use variables..." style="width: 95%; font-family: monospace; white-space: nowrap; resize: none;"></textarea>

      API Key:

      <textarea id="key" rows="2" placeholder="Write your key. Get one from Genius." style="width: 95%; font-family: monospace; white-space: nowrap; resize: none;"></textarea>

      Source Info:

      <select id="info" class="round">
        <option value="0" selected>Song Title</option>
        <option value="1">Song Artist</option>
        <option value="2">Song Lyrics</option>
        <option value="3">Song URL</option>
      </select>

        Store In:

        <select id="storage" class="round" onchange="glob.variableChange(this, 'varNameContainer')">
          ${data.variables[0]}
        </select>

        Variable Name:

        <input id="varName" class="round" type="text">

        To get an API key, create a new app on https://genius.com/api-clients/new or check a tutorial by clicking here.

`
  },

  init () {
    const { glob, document } = this
    glob.variableChange(document.getElementById('storage'), 'varNameContainer')
  },

  action (cache) {
    const _this = this
    const data = cache.actions[cache.index]
    const info = parseInt(data.info)
    const geniustoken = this.evalMessage(data.key, cache)
    const songname = this.evalMessage(data.song, cache)

    const Mods = this.getMods()
    const analyrics = Mods.require('analyrics')

    analyrics.setToken(geniustoken)

    analyrics.getSong(songname, (song) => {
      let result
      switch (info) {
        case 0:
          result = song.title
          break
        case 1:
          result = song.artist
          break
        case 2:
          result = song.lyrics
          break
        case 3:
          result = song.url
          break
        default:
          break
      }
      if (result !== undefined) {
        const storage = parseInt(data.storage)
        const varName2 = _this.evalMessage(data.varName, cache)
        _this.storeValue(result, storage, varName2, cache)
      }
      _this.callNextAction(cache)
    })
  },

  mod () {}
}
<|endoftext|>