<commit_before>window.deprecationWorkflow = window.deprecationWorkflow || {};
window.deprecationWorkflow.config = {
  workflow: [
    { handler: "throw", matchMessage: "Depending on arrays using a dependent key ending with `@each` is deprecated. Please refactor from `Ember.computed('data.@each', function() {});` to `Ember.computed('data.[]', function() {})`." },
    { handler: "throw", matchMessage: "Depending on arrays using a dependent key ending with `@each` is deprecated. Please refactor from `Ember.observer('data.@each', function() {});` to `Ember.computed('data.[]', function() {})`." },
    { handler: "throw", matchMessage: "Depending on arrays using a dependent key ending with `@each` is deprecated. Please refactor from `Ember.computed('mappedData.@each', function() {});` to `Ember.computed('mappedData.[]', function() {})`." },
    { handler: "throw", matchMessage: "Depending on arrays using a dependent key ending with `@each` is deprecated. Please refactor from `Ember.computed('renderedData.@each', function() {});` to `Ember.computed('renderedData.[]', function() {})`." },
    { handler: "throw", matchMessage: "the component:nf-graph test module is implicitly running in unit test mode, which will change to integration test mode by default in an upcoming version of ember-test-helpers. Add `unit: true` or a `needs:[]` list to explicitly opt in to unit test mode." },
    { handler: "throw", matchMessage: "the component:nf-horizontal-line test module is implicitly running in unit test mode, which will change to integration test mode by default in an upcoming version of ember-test-helpers. Add `unit: true` or a `needs:[]` list to explicitly opt in to unit test mode." },
    { handler: "throw", matchMessage: "the component:nf-vertical-line test module is implicitly running in unit test mode, which will change to integration test mode by default in an upcoming version of ember-test-helpers. Add `unit: true` or a `needs:[]` list to explicitly opt in to unit test mode." },
    { handler: "silence", matchMessage: "Using the same function as getter and setter is deprecated." },
    { handler: "throw", matchMessage: "Depending on arrays using a dependent key ending with `@each` is deprecated. Please refactor from `Ember.computed('xUniqueData.@each', function() {});` to `Ember.computed('xUniqueData.[]', function() {})`." },
    { handler: "throw", matchMessage: "Depending on arrays using a dependent key ending with `@each` is deprecated. Please refactor from `Ember.computed('yUniqueData.@each', function() {});` to `Ember.computed('yUniqueData.[]', function() {})`." }
  ]
};
<commit_msg>remove fixed deprecations<commit_after>window.deprecationWorkflow = window.deprecationWorkflow || {};
window.deprecationWorkflow.config = {
  workflow: [
    { handler: "silence", matchMessage: "Using the same function as getter and setter is deprecated." }
  ]
};
<|endoftext|>


<commit_before>import React from 'react';
import MobileTearSheet from './MobileTearSheet';
import {Table, TableBody, TableRow, TableRowColumn} from 'material-ui/Table';
import { List, ListItem } from 'material-ui/List';
import Divider from 'material-ui/Divider';
import Subheader from 'material-ui/Subheader';
import Chip from 'material-ui/Chip';

const styles = {
  chip: {
    margin: 4,
  },
  wrapper: {
    display: 'flex',
    flexWrap: 'wrap',
		justifyContent: 'center'
  },
};

export default class Container extends React.Component {

	handleAction = () => {
		this.props.action();
	};

  render() {
		let ActionList = this.props.action ? (

				<Divider />
				<ListItem primaryText={this.props.actionName} onTouchTap={this.handleAction} />

		) : null;
		let PlayerTable = this.props.player ? (
			<MobileTearSheet>
				<List>
					<ListItem primaryText={'name = ' + this.props.player.name} />
					<ListItem primaryText={'deck size = ' + this.props.player.deckSize} />
					<ListItem primaryText={'a=' + this.props.player.resource.action +
																 ' b=' + this.props.player.resource.buy +
																 ' c=' + this.props.player.resource.coin +
																 ' p=' + this.props.player.resource.potion} />
					<Divider />
					<Subheader>Discard</Subheader>

					{this.props.player.discard.map(function(card, index) {
						return <Chip key={index} style={styles.chip} onTouchTap={this.props._clickCard.bind(null, 'discard', index)} backgroundColor={card.sel ? "#9DC3C1" : null}>{card.name}</Chip>;
					}, this)}

					<Divider />
					<Subheader>Played</Subheader>

					{this.props.player.inPlay.map(function(card, index) {
						return <Chip key={index} style={styles.chip} onTouchTap={this.props._clickCard.bind(null, 'in_play', index)} backgroundColor={card.sel ? "#9DC3C1" : null}>{card.name}</Chip>;
					}, this)}

					<Divider />
					<Subheader>Hand</Subheader>

					{this.props.player.hand.map(function(card, index) {
						return <Chip key={index} style={styles.chip} onTouchTap={this.props._clickCard.bind(null, 'in_hand', index)} backgroundColor={card.sel ? "#9DC3C1" : null}>{card.name}</Chip>;
					}, this)}

					{ActionList}
				</List>
			</MobileTearSheet>
		) : null;
		let PlayerTables = PlayerTable || this.props.players ? (

				{PlayerTable}
				{this.props.players.map(function(player, index) {
					return <MobileTearSheet key={index}>
								   <List>
										 <ListItem primaryText={'name = ' + player.name} onTouchTap={this.props._rec.bind(null, player.spot)}/>
										 <ListItem primaryText={'deck size = ' + player.deckSize} />
										 <ListItem primaryText={'discard top = ' + player.discardTop} />
										 <ListItem primaryText={'hand size = ' + player.handSize} />
										 <ListItem primaryText={'a=' + player.resource.action +
																						' b=' + player.resource.buy +
																						' c=' + player.resource.coin +
																						' p=' + player.resource.potion} />
										 <Divider />
										 <Subheader>Played</Subheader>

										 {player.inPlay.map(function(card, index) {
											 return <Chip key={index} style={styles.chip} backgroundColor={card.sel ? "#9DC3C1" : null}>{card.name}</Chip>;
										 })}

									 </List>
								 </MobileTearSheet>;
				}, this)}

		) : null;

		let PileTable = this.props.piles ? (
			<MobileTearSheet>

				{this.props.piles.map(function(pile, index) {
					return <Chip key={index}
											 style={styles.chip}
											 onTouchTap={this.props._clickCard.bind(null, 'buy', pile.name)}
											 backgroundColor={pile.sel ? "#9DC3C1" : null}>{pile.name} {pile.amt}</Chip>;
				}, this)}

			</MobileTearSheet>
		) : null;
		let UserTable = Object.keys(this.props.users).length ? (
			<MobileTearSheet>
				<List>
				{Object.keys(this.props.users).map(function(key, index) {
					var user = this.props.users[key];
					return <ListItem primaryText={user.name} secondaryText={user.type ? "player" : "spec"} key={index} />;
				}, this)}
				</List>
			</MobileTearSheet>
		) : null;
		let GameTable = PileTable || UserTable ? (

				{PileTable}
				{UserTable}

		) : null;
    return (

				{PlayerTables}
				{GameTable}

		)
  }
};<commit_msg>removed undefined/null resources<commit_after>import React from 'react';
import MobileTearSheet from './MobileTearSheet';
import {Table, TableBody, TableRow, TableRowColumn} from 'material-ui/Table';
import { List, ListItem } from 'material-ui/List';
import Divider from 'material-ui/Divider';
import Subheader from 'material-ui/Subheader';
import Chip from 'material-ui/Chip';

const styles = {
  chip: {
    margin: 4,
  },
  wrapper: {
    display: 'flex',
    flexWrap: 'wrap',
		justifyContent: 'center'
  },
};

export default class Container extends React.Component {

	handleAction = () => {
		this.props.action();
	};

  render() {
		let ActionList = this.props.action ? (

				<Divider />
				<ListItem primaryText={this.props.actionName} onTouchTap={this.handleAction} />

		) : null;
		let PlayerTable = this.props.player ? (
			<MobileTearSheet>
				<List>
					<ListItem primaryText={'name = ' + this.props.player.name} />
					{this.props.player.deckSize ? <ListItem primaryText={'deck size = ' + this.props.player.deckSize} /> : null}
					{Object.keys(this.props.player.resource).length ? (
					<ListItem primaryText={'a=' + this.props.player.resource.action +
																 ' b=' + this.props.player.resource.buy +
																 ' c=' + this.props.player.resource.coin +
																 ' p=' + this.props.player.resource.potion} />
					) : null}
					<Divider />
					<Subheader>Discard</Subheader>

					{this.props.player.discard.map(function(card, index) {
						return <Chip key={index} style={styles.chip} onTouchTap={this.props._clickCard.bind(null, 'discard', index)} backgroundColor={card.sel ? "#9DC3C1" : null}>{card.name}</Chip>;
					}, this)}

					<Divider />
					<Subheader>Played</Subheader>

					{this.props.player.inPlay.map(function(card, index) {
						return <Chip key={index} style={styles.chip} onTouchTap={this.props._clickCard.bind(null, 'in_play', index)} backgroundColor={card.sel ? "#9DC3C1" : null}>{card.name}</Chip>;
					}, this)}

					<Divider />
					<Subheader>Hand</Subheader>

					{this.props.player.hand.map(function(card, index) {
						return <Chip key={index} style={styles.chip} onTouchTap={this.props._clickCard.bind(null, 'in_hand', index)} backgroundColor={card.sel ? "#9DC3C1" : null}>{card.name}</Chip>;
					}, this)}

					{ActionList}
				</List>
			</MobileTearSheet>
		) : null;
		let PlayerTables = PlayerTable || this.props.players ? (

				{PlayerTable}
				{this.props.players.map(function(player, index) {
					return <MobileTearSheet key={index}>
								   <List>
										 <ListItem primaryText={'name = ' + player.name} onTouchTap={this.props._rec.bind(null, player.spot)}/>

										 {player.deckSize ? <ListItem primaryText={'deck size = ' + player.deckSize} /> : null}
										 {player.discardTop ? <ListItem primaryText={'discard top = ' + player.discardTop} /> : null}
										 {player.handSize ? <ListItem primaryText={'hand size = ' + player.handSize} /> : null}
										 {Object.keys(player.resource).length ? (
										 <ListItem primaryText={'a=' + player.resource.action +
																						' b=' + player.resource.buy +
																						' c=' + player.resource.coin +
																						' p=' + player.resource.potion} />
										 ) : null}
										 <Divider />
										 <Subheader>Played</Subheader>

										 {player.inPlay.map(function(card, index) {
											 return <Chip key={index} style={styles.chip} backgroundColor={card.sel ? "#9DC3C1" : null}>{card.name}</Chip>;
										 })}

									 </List>
								 </MobileTearSheet>;
				}, this)}

		) : null;

		let PileTable = this.props.piles ? (
			<MobileTearSheet>

				{this.props.piles.map(function(pile, index) {
					return <Chip key={index}
											 style={styles.chip}
											 onTouchTap={this.props._clickCard.bind(null, 'buy', pile.name)}
											 backgroundColor={pile.sel ? "#9DC3C1" : null}>{pile.name} {pile.amt}</Chip>;
				}, this)}

			</MobileTearSheet>
		) : null;
		let UserTable = Object.keys(this.props.users).length ? (
			<MobileTearSheet>
				<List>
				{Object.keys(this.props.users).map(function(key, index) {
					var user = this.props.users[key];
					return <ListItem primaryText={user.name} secondaryText={user.type ? "player" : "spec"} key={index} />;
				}, this)}
				</List>
			</MobileTearSheet>
		) : null;
		let GameTable = PileTable || UserTable ? (

				{PileTable}
				{UserTable}

		) : null;
    return (

				{PlayerTables}
				{GameTable}

		)
  }
};<|endoftext|>


<commit_before>/*
 * This allows Ruby-esque code to be written and compiled to JS
 *
 * unless (true) do
 *   return;
 * end
 * elif (true) do
 *   print(true or false == true)
 * end
 *
 * will compile to
 *
 * if (!true) {
 *   return;
 * }
 * else if (true) {
 *   console.log(true || false === true)
 * }
 */

module.exports.keys = [
  {
    alias: /\b(print\()\b/g,
    translation: 'console.log('
  },
  {
    alias: /\b(elif\s?\()/g,
    translation: 'else if ('
  },
  {
    alias: /\b(or)\b/g,
    translation: '||'
  },
  {
    alias: /\s(\=\=)\s/g,
    translation: ' === '
  },
  {
    alias: /\b(and)\b/g,
    translation: '&&'
  },
  {
    alias: /\b(def)\b/g,
    translation: 'function'
  },
  {
    alias: /\b(unless\s?\()/g,
    translation: 'if (!'
  },
  {
    alias: /\b(is)\b/g,
    translation: '==='
  },
  {
    alias: /\b(do)\b/g,
    translation: '{'
  },
  {
    alias: /\b(end)\b/g,
    translation: '}'
  },
  {
    alias: /\b(next)\b/g,
    translation: 'continue'
  }
]
<commit_msg>Update rubyish.flavor.config.js<commit_after>/*
 * This allows Ruby-esque code to be written and compiled to JS
 *
 * unless (true) do
 *   return;
 * end
 * elsif (true) do
 *   print(true or false == true)
 * end
 *
 * will compile to
 *
 * if (!true) {
 *   return;
 * }
 * else if (true) {
 *   console.log(true || false === true)
 * }
 */

module.exports.keys = [
  {
    alias: /\b(print\()\b/g,
    translation: 'console.log('
  },
  {
    alias: /\b(elsif\s?\()/g,
    translation: 'else if ('
  },
  {
    alias: /\b(or)\b/g,
    translation: '||'
  },
  {
    alias: /\s(\=\=)\s/g,
    translation: ' === '
  },
  {
    alias: /\b(and)\b/g,
    translation: '&&'
  },
  {
    alias: /\b(def)\b/g,
    translation: 'function'
  },
  {
    alias: /\b(unless\s?\()/g,
    translation: 'if (!'
  },
  {
    alias: /\b(is)\b/g,
    translation: '==='
  },
  {
    alias: /\b(do)\b/g,
    translation: '{'
  },
  {
    alias: /\b(end)\b/g,
    translation: '}'
  },
  {
    alias: /\b(next)\b/g,
    translation: 'continue'
  }
]
<|endoftext|>


<commit_before>// Generated on 2014-03-25 using generator-angular 0.4.0
'use strict';
var LIVERELOAD_PORT = 35729;

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {
  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

  // load custom tasks
  grunt.loadTasks('tasks');

  // configurable paths
  var yeomanConfig = {
    lib: 'app/bower_components',
    app: 'app',
    dist: 'dist',
    tmp: '.tmp'
  };

  try {
    yeomanConfig.app = require('./bower.json').appPath || yeomanConfig.app;
  } catch (e) {
  }

  grunt.initConfig({
    yeoman: yeomanConfig,
    local: {
      // default values used when local-config.json is not loaded
      home: './',
      jbossweb: '../servers/ups-server/target/ag-push'
    },
    less: {
      main: {
        options: {
          paths: ['<%= yeoman.lib %>']
        },
        src: '<%= yeoman.app %>/styles/main.less',
        dest: '<%= yeoman.tmp %>/styles/main.css'
      },
      account: {
        options: {
          paths: ['<%= yeoman.lib %>']
        },
        src: '<%= yeoman.app %>/styles/account.less',
        dest: '<%= yeoman.tmp %>/styles/account.css'
      },
      login: {
        options: {
          paths: ['<%= yeoman.lib %>']
        },
        src: '<%= yeoman.app %>/styles/login.less',
        dest: '<%= yeoman.tmp %>/styles/login.css'
      }
    },
    watch: {
      options: {
        nospawn: true
      },
      less: {
        files: '<%= yeoman.app %>/styles/*.less',
        tasks: ['less', 'newer:copy:jbossweb']
      },
      livereload: {
        options: {
          livereload: LIVERELOAD_PORT
        },
        files: [
          '<%= yeoman.app %>/**/*.html',
          '{<%= yeoman.app %>,<%= yeoman.tmp %>}/snippets/**',
          '{<%= yeoman.app %>,<%= yeoman.tmp %>}/components/{,*/}*.{html,js}',
          '{<%= yeoman.app %>,<%= yeoman.tmp %>}/components/**/*.{html,js}',
          '{<%= yeoman.app %>,<%= yeoman.tmp %>}/styles/{,*/}*.css',
          '{<%= yeoman.app %>,<%= yeoman.tmp %>}/scripts/{,*/}*.js',
          '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ],
        tasks: [ 'newer:copy:jbossweb' ]
      }
    },
    autoprefixer: {
      options: ['last 1 version'],
      dist: {
        files: [
          {
            expand: true,
            cwd: '.tmp/styles/',
            src: '{,*/}*.css',
            dest: '.tmp/styles/'
          }
        ]
      }
    },
    clean: {
      dist: {
        files: [
          {
            dot: true,
            src: [
              '.tmp',
              '<%= yeoman.dist %>/*',
              '!<%= yeoman.dist %>/.git*'
            ]
          }
        ]
      },
      jbosswebDist: {
        options: {
          'force': true
        },
        src: [
          '<%= local.jbossweb %>/*',
          '!<%= local.jbossweb %>/config',
          '!<%= local.jbossweb %>/WEB-INF',
          '!<%= local.jbossweb %>/META-INF'
        ]
      },
      server: '.tmp'
    },
    jshint: {
      options: {
        jshintrc: '.jshintrc'
      },
      all: [
        'Gruntfile.js',
        '<%= yeoman.app %>/scripts/{,*/}*.js'
      ]
    },
    filerev: {
      dist: {
        src: [
          '<%= yeoman.dist %>/scripts/{,*/}*.js',
          '<%= yeoman.dist %>/styles/{,*/}*.css',
          '<%= yeoman.dist %>/img/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },
    useminPrepare: {
      html: [
        '<%= yeoman.app %>/index.html'
      ],
      options: {
        dest: '<%= yeoman.dist %>'
      }
    },
    usemin: {
      html: ['<%= yeoman.dist %>/**/*.html'],
      css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
      options: {
        dirs: ['<%= yeoman.dist %>']
      }
    },
    htmlmin: {
      dist: {
        options: {
          /*removeCommentsFromCDATA: true,
           // https://github.com/yeoman/grunt-usemin/issues/44
           //collapseWhitespace: true,
           collapseBooleanAttributes: true,
           removeAttributeQuotes: true,
           removeRedundantAttributes: true,
           useShortDoctype: true,
           removeEmptyAttributes: true,
           removeOptionalTags: true*/
        },
        files: [
          {
            expand: true,
            cwd: '<%= yeoman.app %>',
            src: [
              '*.html',
              'dialogs/*.html',
              'directives/*.html'
            ],
            dest: '<%= yeoman.dist %>'
          }
        ]
      }
    },
    // Put files not handled in other tasks here
    copy: {
      // we need to put patternfly fonts to the correct destination
      // ( https://github.com/patternfly/patternfly/issues/20 )
      fonts: {
        files: [
          {
            expand: true,
            dot: true,
            cwd: '<%= yeoman.lib %>/font-awesome/fonts/',
            dest: '<%= yeoman.tmp %>/fonts/',
            src: [ '**' ]
          },
          {
            expand: true,
            dot: true,
            cwd: '<%= yeoman.lib %>/patternfly/dist/fonts/',
            dest: '<%= yeoman.tmp %>/fonts/',
            src: [ '**' ]
          },
          {
            expand: true,
            dot: true,
            cwd: '<%= yeoman.app %>/styles/fonts/exo2/',
            dest: '<%= yeoman.tmp %>/fonts/',
            src: [ '**', '!*.less', '!*.txt' ]
          }
        ]
      },
      misc: {
        files: [
          {
            expand: true,
            dot: true,
            cwd: '<%= yeoman.lib %>/zeroclipboard/dist/',
            dest: '<%= yeoman.tmp %>/img/',
            src: [ 'ZeroClipboard.swf' ]
          }
        ]
      },
      dist: {
        files: [
          {
            expand: true,
            dot: true,
            cwd: '<%= yeoman.app %>',
            dest: '<%= yeoman.dist %>',
            src: [
              'components/**',
              'snippets/**',
              '*.{ico,txt}',
              '*.json',
              'img/{,*/}*.{webp,gif,png,jpg,svg}'
            ]
          },
          {
            expand: true,
            cwd: '<%= yeoman.tmp %>',
            dest: '<%= yeoman.dist %>',
            src: [
              '**',
              '!styles/compiled-less.css'
            ]
          }
        ]
      },
      nofilerev: {
        files: [
          {
            expand: true,
            dot: true,
            cwd: '<%= yeoman.dist %>/styles',
            dest: '<%= yeoman.dist %>/styles/',
            src: [
              'account.*.css',
              'login.*.css'
            ],
            rename: function(dest, src) {
              var renamed = dest + src.replace(/\..+\.css$/,'.css');
              console.log(renamed);
              return renamed;
            }
          }
        ]
      },
      jbossweb: {
        files: [
          {
            expand: true,
            cwd: '<%= yeoman.tmp %>',
            dest: '<%= local.jbossweb %>',
            src: [ '**', '!**/*.txt', '!**/*.less' ]
          },
          {
            expand: true,
            cwd: '<%= yeoman.app %>',
            dest: '<%= local.jbossweb %>',
            src: [ '**', '!**/*.txt' ]
          }
        ]
      },
      jbosswebDist: {
        files: [
          {
            expand: true,
            cwd: '<%= yeoman.dist %>',
            dest: '<%= local.jbossweb %>',
            src: [ '**', '!**/*.txt' ]
          }
        ]
      }
    },
    concurrent: {
      server: [

      ],
      test: [

      ],
      dist: [
        'copy:styles',
        'imagemin',
        'htmlmin'
      ]
    },
    ngmin: {
      dist: {
        files: [
          {
            expand: true,
            cwd: '<%= yeoman.dist %>/scripts',
            src: '*.js',
            dest: '<%= yeoman.dist %>/scripts'
          }
        ]
      }
    },
    uglify: {
      options: {
        mangle: false,
        compress: true,
        report: true
      }
    },
    cssmin: {
      options: {
        report: 'min'
      }
    },
    ngtemplates:  {
      upsConsole: {
        src: [
          'components/**.html',
          'directives/**.html',
          'views/**.html',
          'views/dialogs/**.html',
          'views/include/**.html'
        ],
        cwd: '<%= yeoman.app %>',
        dest: '<%= yeoman.tmp %>/ngtemplates/templates.js',
        options:    {
          usemin: 'scripts/templates.js'
        }
      }
    },
    bower: {
      install: {
        options: {
          targetDir: 'app/bower-components/'
        }
      }
    },
    compress: {
      main: {
        options: {
          archive: 'dist/npm-ups-admin-ui.tgz',
          mode: 'tgz'
        },
        files: [{
          src: ['.tmp/concat/scripts/modules.js'],
          dest: 'ups-admin-ui/js',
          filter: 'isFile',
          flatten: true,
          expand: true
        }, {
          src: ['.tmp/concat/scripts/scripts.js'],
          dest: 'ups-admin-ui/js',
          filter: 'isFile',
          flatten: true,
          expand: true
        }, {
          src: ['.tmp/ngtemplates/templates.js'],
          dest: 'ups-admin-ui/js',
          filter: 'isFile',
          flatten: true,
          expand: true
        }, {
          src: ['package.json'],
          dest: 'ups-admin-ui/',
          filter: 'isFile',
          flatten: true,
          expand: true
        }]
      }
    }
  });

  grunt.registerTask('server', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build']);
    }

    grunt.task.run([
      'initLocalConfig',
      'clean:server',
      'concurrent:server',
      'less',
      'copy:fonts',
      'copy:misc',
      'copy:jbossweb',
      'autoprefixer',
      'watch'
    ]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'concurrent:test',
    'autoprefixer'
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    'less',
    'copy:fonts',
    'copy:misc',
    'useminPrepare',
    'ngtemplates',
    'htmlmin',
    'concat',
    'cssmin',
    'ngmin:dist',
    'uglify',
    'copy:dist',
    'filerev',
    'copy:nofilerev',
    'usemin',
    'compress'
  ]);

  grunt.registerTask('default', [
    'jshint',
    'test',
    'build'
  ]);

  grunt.registerTask('dist', [
    'bower:install',
    'default'
  ]);

  grunt.registerTask('jbosswebDist', [
    'initLocalConfig',
    'dist',
    'clean:jbosswebDist',
    'copy:jbosswebDist'
  ]);

  grunt.registerTask('jboss_web', ['copy:jbossweb']);
};
<commit_msg>add all the templates<commit_after>// Generated on 2014-03-25 using generator-angular 0.4.0
'use strict';
var LIVERELOAD_PORT = 35729;

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {
  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

  // load custom tasks
  grunt.loadTasks('tasks');

  // configurable paths
  var yeomanConfig = {
    lib: 'app/bower_components',
    app: 'app',
    dist: 'dist',
    tmp: '.tmp'
  };

  try {
    yeomanConfig.app = require('./bower.json').appPath || yeomanConfig.app;
  } catch (e) {
  }

  grunt.initConfig({
    yeoman: yeomanConfig,
    local: {
      // default values used when local-config.json is not loaded
      home: './',
      jbossweb: '../servers/ups-server/target/ag-push'
    },
    less: {
      main: {
        options: {
          paths: ['<%= yeoman.lib %>']
        },
        src: '<%= yeoman.app %>/styles/main.less',
        dest: '<%= yeoman.tmp %>/styles/main.css'
      },
      account: {
        options: {
          paths: ['<%= yeoman.lib %>']
        },
        src: '<%= yeoman.app %>/styles/account.less',
        dest: '<%= yeoman.tmp %>/styles/account.css'
      },
      login: {
        options: {
          paths: ['<%= yeoman.lib %>']
        },
        src: '<%= yeoman.app %>/styles/login.less',
        dest: '<%= yeoman.tmp %>/styles/login.css'
      }
    },
    watch: {
      options: {
        nospawn: true
      },
      less: {
        files: '<%= yeoman.app %>/styles/*.less',
        tasks: ['less', 'newer:copy:jbossweb']
      },
      livereload: {
        options: {
          livereload: LIVERELOAD_PORT
        },
        files: [
          '<%= yeoman.app %>/**/*.html',
          '{<%= yeoman.app %>,<%= yeoman.tmp %>}/snippets/**',
          '{<%= yeoman.app %>,<%= yeoman.tmp %>}/components/{,*/}*.{html,js}',
          '{<%= yeoman.app %>,<%= yeoman.tmp %>}/components/**/*.{html,js}',
          '{<%= yeoman.app %>,<%= yeoman.tmp %>}/styles/{,*/}*.css',
          '{<%= yeoman.app %>,<%= yeoman.tmp %>}/scripts/{,*/}*.js',
          '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ],
        tasks: [ 'newer:copy:jbossweb' ]
      }
    },
    autoprefixer: {
      options: ['last 1 version'],
      dist: {
        files: [
          {
            expand: true,
            cwd: '.tmp/styles/',
            src: '{,*/}*.css',
            dest: '.tmp/styles/'
          }
        ]
      }
    },
    clean: {
      dist: {
        files: [
          {
            dot: true,
            src: [
              '.tmp',
              '<%= yeoman.dist %>/*',
              '!<%= yeoman.dist %>/.git*'
            ]
          }
        ]
      },
      jbosswebDist: {
        options: {
          'force': true
        },
        src: [
          '<%= local.jbossweb %>/*',
          '!<%= local.jbossweb %>/config',
          '!<%= local.jbossweb %>/WEB-INF',
          '!<%= local.jbossweb %>/META-INF'
        ]
      },
      server: '.tmp'
    },
    jshint: {
      options: {
        jshintrc: '.jshintrc'
      },
      all: [
        'Gruntfile.js',
        '<%= yeoman.app %>/scripts/{,*/}*.js'
      ]
    },
    filerev: {
      dist: {
        src: [
          '<%= yeoman.dist %>/scripts/{,*/}*.js',
          '<%= yeoman.dist %>/styles/{,*/}*.css',
          '<%= yeoman.dist %>/img/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },
    useminPrepare: {
      html: [
        '<%= yeoman.app %>/index.html'
      ],
      options: {
        dest: '<%= yeoman.dist %>'
      }
    },
    usemin: {
      html: ['<%= yeoman.dist %>/**/*.html'],
      css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
      options: {
        dirs: ['<%= yeoman.dist %>']
      }
    },
    htmlmin: {
      dist: {
        options: {
          /*removeCommentsFromCDATA: true,
           // https://github.com/yeoman/grunt-usemin/issues/44
           //collapseWhitespace: true,
           collapseBooleanAttributes: true,
           removeAttributeQuotes: true,
           removeRedundantAttributes: true,
           useShortDoctype: true,
           removeEmptyAttributes: true,
           removeOptionalTags: true*/
        },
        files: [
          {
            expand: true,
            cwd: '<%= yeoman.app %>',
            src: [
              '*.html',
              'dialogs/*.html',
              'directives/*.html'
            ],
            dest: '<%= yeoman.dist %>'
          }
        ]
      }
    },
    // Put files not handled in other tasks here
    copy: {
      // we need to put patternfly fonts to the correct destination
      // ( https://github.com/patternfly/patternfly/issues/20 )
      fonts: {
        files: [
          {
            expand: true,
            dot: true,
            cwd: '<%= yeoman.lib %>/font-awesome/fonts/',
            dest: '<%= yeoman.tmp %>/fonts/',
            src: [ '**' ]
          },
          {
            expand: true,
            dot: true,
            cwd: '<%= yeoman.lib %>/patternfly/dist/fonts/',
            dest: '<%= yeoman.tmp %>/fonts/',
            src: [ '**' ]
          },
          {
            expand: true,
            dot: true,
            cwd: '<%= yeoman.app %>/styles/fonts/exo2/',
            dest: '<%= yeoman.tmp %>/fonts/',
            src: [ '**', '!*.less', '!*.txt' ]
          }
        ]
      },
      misc: {
        files: [
          {
            expand: true,
            dot: true,
            cwd: '<%= yeoman.lib %>/zeroclipboard/dist/',
            dest: '<%= yeoman.tmp %>/img/',
            src: [ 'ZeroClipboard.swf' ]
          }
        ]
      },
      dist: {
        files: [
          {
            expand: true,
            dot: true,
            cwd: '<%= yeoman.app %>',
            dest: '<%= yeoman.dist %>',
            src: [
              'components/**',
              'snippets/**',
              '*.{ico,txt}',
              '*.json',
              'img/{,*/}*.{webp,gif,png,jpg,svg}'
            ]
          },
          {
            expand: true,
            cwd: '<%= yeoman.tmp %>',
            dest: '<%= yeoman.dist %>',
            src: [
              '**',
              '!styles/compiled-less.css'
            ]
          }
        ]
      },
      nofilerev: {
        files: [
          {
            expand: true,
            dot: true,
            cwd: '<%= yeoman.dist %>/styles',
            dest: '<%= yeoman.dist %>/styles/',
            src: [
              'account.*.css',
              'login.*.css'
            ],
            rename: function(dest, src) {
              var renamed = dest + src.replace(/\..+\.css$/,'.css');
              console.log(renamed);
              return renamed;
            }
          }
        ]
      },
      jbossweb: {
        files: [
          {
            expand: true,
            cwd: '<%= yeoman.tmp %>',
            dest: '<%= local.jbossweb %>',
            src: [ '**', '!**/*.txt', '!**/*.less' ]
          },
          {
            expand: true,
            cwd: '<%= yeoman.app %>',
            dest: '<%= local.jbossweb %>',
            src: [ '**', '!**/*.txt' ]
          }
        ]
      },
      jbosswebDist: {
        files: [
          {
            expand: true,
            cwd: '<%= yeoman.dist %>',
            dest: '<%= local.jbossweb %>',
            src: [ '**', '!**/*.txt' ]
          }
        ]
      }
    },
    concurrent: {
      server: [

      ],
      test: [

      ],
      dist: [
        'copy:styles',
        'imagemin',
        'htmlmin'
      ]
    },
    ngmin: {
      dist: {
        files: [
          {
            expand: true,
            cwd: '<%= yeoman.dist %>/scripts',
            src: '*.js',
            dest: '<%= yeoman.dist %>/scripts'
          }
        ]
      }
    },
    uglify: {
      options: {
        mangle: false,
        compress: true,
        report: true
      }
    },
    cssmin: {
      options: {
        report: 'min'
      }
    },
    ngtemplates:  {
      upsConsole: {
        src: [
          'components/**/**.html',
          'directives/**.html',
          'dialogs/**.html'
        ],
        cwd: '<%= yeoman.app %>',
        dest: '<%= yeoman.tmp %>/ngtemplates/templates.js',
        options:    {
          usemin: 'scripts/templates.js'
        }
      }
    },
    bower: {
      install: {
        options: {
          targetDir: 'app/bower-components/'
        }
      }
    },
    compress: {
      main: {
        options: {
          archive: 'dist/npm-ups-admin-ui.tgz',
          mode: 'tgz'
        },
        files: [{
          src: ['.tmp/concat/scripts/modules.js'],
          dest: 'ups-admin-ui/js',
          filter: 'isFile',
          flatten: true,
          expand: true
        }, {
          src: ['.tmp/concat/scripts/scripts.js'],
          dest: 'ups-admin-ui/js',
          filter: 'isFile',
          flatten: true,
          expand: true
        }, {
          src: ['.tmp/ngtemplates/templates.js'],
          dest: 'ups-admin-ui/js',
          filter: 'isFile',
          flatten: true,
          expand: true
        }, {
          src: ['package.json'],
          dest: 'ups-admin-ui/',
          filter: 'isFile',
          flatten: true,
          expand: true
        }]
      }
    }
  });

  grunt.registerTask('server', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build']);
    }

    grunt.task.run([
      'initLocalConfig',
      'clean:server',
      'concurrent:server',
      'less',
      'copy:fonts',
      'copy:misc',
      'copy:jbossweb',
      'autoprefixer',
      'watch'
    ]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'concurrent:test',
    'autoprefixer'
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    'less',
    'copy:fonts',
    'copy:misc',
    'useminPrepare',
    'ngtemplates',
    'htmlmin',
    'concat',
    'cssmin',
    'ngmin:dist',
    'uglify',
    'copy:dist',
    'filerev',
    'copy:nofilerev',
    'usemin',
    'compress'
  ]);

  grunt.registerTask('default', [
    'jshint',
    'test',
    'build'
  ]);

  grunt.registerTask('dist', [
    'bower:install',
    'default'
  ]);

  grunt.registerTask('jbosswebDist', [
    'initLocalConfig',
    'dist',
    'clean:jbosswebDist',
    'copy:jbosswebDist'
  ]);

  grunt.registerTask('jboss_web', ['copy:jbossweb']);
};
<|endoftext|>


<commit_before>class Tiger {
  constructor() {
    this.r = 250;
    this.x = 50;
    this.y = height - this.r + 20;
    this.vy = 0;
    this.gravity = 3;
  }

  jump() {
    if (this.y == height - this.r) {
      this.vy = -70;
    }
  }

  hits(obstacle) {
    let x1 = this.x + this.r * 0.5;
    let y1 = this.y + this.r * 0.5;
    let x2 = obstacle.x + obstacle.r * 0.5;
    let y2 = obstacle.y + obstacle.r * 0.5;
    return collideCircleCircle(x1, y1, this.r, x2, y2, obstacle.r);
  }

  move() {
    this.y += this.vy;
    this.vy += this.gravity;
    this.y = constrain(this.y, 0, height - this.r);
  }

  show() {
    image(tigerImg, this.x, this.y, this.r, this.r);
  }
}
<commit_msg>gravity fix<commit_after>class Tiger {
  constructor() {
    this.r = 250;
    this.x = 50;
    this.y = height - this.r - 20;
    this.vy = 0;
    this.gravity = 3;
  }

  jump() {
    if (this.y == height - this.r) {
      this.vy = -60;
    }
  }

  hits(obstacle) {
    let x1 = this.x + this.r * 0.5;
    let y1 = this.y + this.r * 0.5;
    let x2 = obstacle.x + obstacle.r * 0.5;
    let y2 = obstacle.y + obstacle.r * 0.5;
    return collideCircleCircle(x1, y1, this.r, x2, y2, obstacle.r);
  }

  move() {
    this.y += this.vy;
    this.vy += this.gravity;
    this.y = constrain(this.y, 0, height - this.r);
  }

  show() {
    image(tigerImg, this.x, this.y, this.r, this.r);
  }
}
<|endoftext|>


<commit_before>/* eslint-disable react/forbid-prop-types */
/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */
import React, { useCallback, useMemo } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { View } from 'react-native';

import { ToggleBar, DataTablePageView, SearchBar, PageButton } from '../widgets';
import { DataTable, DataTableRow, DataTableHeaderRow } from '../widgets/DataTable';
import { SearchForm } from '../widgets/modals/SearchForm';
import { PatientHistoryModal } from '../widgets/modals/PatientHistory';
import { FormControl } from '../widgets/FormControl';
import { ModalContainer } from '../widgets/modals/ModalContainer';

import { recordKeyExtractor, getItemLayout } from './dataTableUtilities';
import { createPrescription } from '../navigation/actions';

import { UIDatabase } from '../database';
import { getFormInputConfig } from '../utilities/formInputConfigs';

import { PatientActions } from '../actions/PatientActions';
import { PrescriberActions } from '../actions/PrescriberActions';
import { InsuranceActions } from '../actions/InsuranceActions';
import { DispensaryActions } from '../actions/DispensaryActions';

import {
  selectDataSetInUse,
  selectSortedData,
  selectLookupModalOpen,
} from '../selectors/dispensary';
import { selectPrescriberModalOpen, selectCanEditPrescriber } from '../selectors/prescriber';
import { selectInsuranceModalOpen, selectCanEditInsurancePolicy } from '../selectors/insurance';
import { selectPatientModalOpen, selectCanEditPatient } from '../selectors/patient';

import globalStyles from '../globalStyles';
import { dispensingStrings } from '../localization';

const Dispensing = ({
  data,
  columns,
  isAscending,
  sortKey,
  searchTerm,
  usingPatientsDataSet,
  usingPrescribersDataSet,

  // Misc. Callbacks
  filter,
  sort,
  gotoPrescription,
  switchDataset,

  // Dispensary lookup API callbacks
  lookupRecord,
  cancelLookupRecord,

  // Dispensary lookup API variables
  isLookupModalOpen,

  // Patient variable
  patientEditModalOpen,
  currentPatient,
  patientHistoryModalOpen,
  canEditPatient,

  // Patient callback
  editPatient,
  createPatient,
  cancelPatientEdit,
  savePatient,
  viewPatientHistory,

  // Prescriber variables
  currentPrescriber,
  prescriberModalOpen,
  canEditPrescriber,

  // Prescriber callbacks
  editPrescriber,
  createPrescriber,
  cancelPrescriberEdit,
  savePrescriber,

  // Insurance variables
  insuranceModalOpen,
  selectedInsurancePolicy,
  canEditInsurancePolicy,
  isCreatingInsurancePolicy,
  // Insurance callbacks
  cancelInsuranceEdit,
  saveInsurancePolicy,
}) => {
  const getCellCallbacks = colKey => {
    switch (colKey) {
      case 'dispense':
        return gotoPrescription;
      case 'patientHistory':
        return viewPatientHistory;
      case 'patientEdit':
        return editPatient;
      case 'prescriberEdit':
        return editPrescriber;
      default:
        return null;
    }
  };

  const renderRow = useCallback(
    listItem => {
      const { item, index } = listItem;
      const rowKey = recordKeyExtractor(item);
      return (
        <DataTableRow
          rowData={data[index]}
          rowKey={rowKey}
          getCallback={getCellCallbacks}
          columns={columns}
          rowIndex={index}
        />
      );
    },
    [data]
  );

  const renderHeader = useCallback(
    () => (
      <DataTableHeaderRow
        columns={columns}
        isAscending={isAscending}
        sortKey={sortKey}
        onPress={sort}
      />
    ),
    [sortKey, isAscending, columns]
  );

  const toggles = useMemo(
    () => [
      {
        text: dispensingStrings.patients,
        onPress: switchDataset,
        isOn: usingPatientsDataSet,
      },
      {
        text: dispensingStrings.prescribers,
        onPress: switchDataset,
        isOn: usingPrescribersDataSet,
      },
    ],
    [usingPatientsDataSet, usingPrescribersDataSet, switchDataset]
  );

  const newRecordText = useMemo(
    () =>
      usingPatientsDataSet
        ? `${dispensingStrings.new_patient}`
        : `${dispensingStrings.new} ${dispensingStrings.prescriber}`,
    [usingPatientsDataSet]
  );
  const lookupRecordText = useMemo(
    () =>
      usingPatientsDataSet
        ? `${dispensingStrings.lookup_patient}`
        : `${dispensingStrings.lookup_prescriber}`,
    [usingPatientsDataSet]
  );

  const newRecordAction = useMemo(() => (usingPatientsDataSet ? createPatient : createPrescriber), [
    usingPatientsDataSet,
  ]);
  const lookupRecordAction = useMemo(() => lookupRecord, []);

  const { pageTopSectionContainer } = globalStyles;
  return (
    <>
      <DataTablePageView>
        <View style={pageTopSectionContainer}>
          <ToggleBar toggles={toggles} />
          <SearchBar
            onChangeText={filter}
            value={searchTerm}
            viewStyle={localStyles.searchBar}
            placeholder={dispensingStrings.search_by_last_name_first_name}
          />
          <PageButton text={newRecordText} onPress={newRecordAction} style={localStyles.button} />
          <PageButton
            text={lookupRecordText}
            onPress={lookupRecordAction}
            style={localStyles.button}
          />
        </View>
        <DataTable
          data={data}
          renderRow={renderRow}
          renderHeader={renderHeader}
          keyExtractor={recordKeyExtractor}
          getItemLayout={getItemLayout}
        />
      </DataTablePageView>
      <ModalContainer
        title={`${dispensingStrings.patient_detail}`}
        noCancel
        fullScreen
        isVisible={patientEditModalOpen}
      >
        <FormControl
          isDisabled={!canEditPatient}
          onSave={savePatient}
          onCancel={cancelPatientEdit}
          inputConfig={getFormInputConfig('patient', currentPatient)}
        />
      </ModalContainer>
      <ModalContainer
        title={`${dispensingStrings.prescriber} ${dispensingStrings.details}`}
        noCancel
        fullScreen
        isVisible={prescriberModalOpen}
      >
        <FormControl
          isDisabled={!canEditPrescriber}
          onSave={savePrescriber}
          onCancel={cancelPrescriberEdit}
          inputConfig={getFormInputConfig('prescriber', currentPrescriber)}
        />
      </ModalContainer>
      <ModalContainer
        title={`${dispensingStrings.insurance_policy}`}
        noCancel
        fullScreen
        isVisible={insuranceModalOpen}
      >
        <FormControl
          isDisabled={!canEditInsurancePolicy}
          confirmOnSave={!canEditPatient}
          confirmText={dispensingStrings.confirm_new_policy}
          onSave={saveInsurancePolicy}
          onCancel={cancelInsuranceEdit}
          inputConfig={getFormInputConfig(
            'insurancePolicy',
            isCreatingInsurancePolicy ? null : selectedInsurancePolicy
          )}
        />
      </ModalContainer>
      <ModalContainer
        title={`${dispensingStrings.patient} ${dispensingStrings.history} - ${currentPatient?.name}`}
        onClose={cancelPatientEdit}
        fullScreen
        isVisible={patientHistoryModalOpen}
      >
        <PatientHistoryModal />
      </ModalContainer>
      <ModalContainer
        title={
          usingPatientsDataSet
            ? `${dispensingStrings.lookup_patient}`
            : `${dispensingStrings.lookup_prescriber}`
        }
        onClose={cancelLookupRecord}
        fullScreen
        isVisible={isLookupModalOpen}
      >
        <SearchForm />
      </ModalContainer>
    </>
  );
};

const localStyles = {
  searchBar: {
    borderBottomWidth: 1,
    flexDirection: 'row',
    alignItems: 'center',
    marginHorizontal: 5,
    flex: 1,
    flexGrow: 1,
  },
  button: {
    marginHorizontal: 2.5,
  },
};

const mapStateToProps = state => {
  const { patient, prescriber, insurance, dispensary } = state;
  const { sortKey, isAscending, searchTerm, columns } = dispensary;

  const isLookupModalOpen = selectLookupModalOpen(state);

  const { currentPatient } = patient;
  const { currentPrescriber } = prescriber;
  const { isCreatingInsurancePolicy, selectedInsurancePolicy } = insurance;

  const prescriberModalOpen = selectPrescriberModalOpen(state);
  const canEditPrescriber = selectCanEditPrescriber(state);
  const canEditPatient = selectCanEditPatient(state);
  const canEditInsurancePolicy = selectCanEditInsurancePolicy(state);
  const [patientEditModalOpen, patientHistoryModalOpen] = selectPatientModalOpen(state);
  const insuranceModalOpen = selectInsuranceModalOpen(state);
  const data = selectSortedData(state);

  const [usingPatientsDataSet, usingPrescribersDataSet] = selectDataSetInUse(state);

  return {
    usingPatientsDataSet,
    usingPrescribersDataSet,
    data,
    sortKey,
    isAscending,
    searchTerm,
    columns,
    // Dispensary lookup API
    isLookupModalOpen,
    // Patient
    patientEditModalOpen,
    currentPatient,
    patientHistoryModalOpen,
    canEditPatient,
    // Prescriber
    currentPrescriber,
    prescriberModalOpen,
    canEditPrescriber,
    // Insurance
    insuranceModalOpen,
    selectedInsurancePolicy,
    canEditInsurancePolicy,
    isCreatingInsurancePolicy,
  };
};

const mapDispatchToProps = dispatch => ({
  gotoPrescription: patientID => dispatch(createPrescription(patientID)),

  filter: searchTerm => dispatch(DispensaryActions.filter(searchTerm)),
  sort: sortKey => dispatch(DispensaryActions.sort(sortKey)),
  switchDataset: () => dispatch(DispensaryActions.switchDataSet()),

  lookupRecord: () => dispatch(DispensaryActions.openLookupModal()),
  cancelLookupRecord: () => dispatch(DispensaryActions.closeLookupModal()),

  editPatient: patient => dispatch(PatientActions.editPatient(UIDatabase.get('Name', patient))),
  createPatient: () => dispatch(PatientActions.createPatient()),
  cancelPatientEdit: () => dispatch(PatientActions.closeModal()),
  savePatient: patientDetails => dispatch(PatientActions.patientUpdate(patientDetails)),
  viewPatientHistory: rowKey =>
    dispatch(PatientActions.viewPatientHistory(UIDatabase.get('Name', rowKey))),

  editPrescriber: prescriber =>
    dispatch(PrescriberActions.editPrescriber(UIDatabase.get('Prescriber', prescriber))),
  createPrescriber: () => dispatch(PrescriberActions.createPrescriber()),
  cancelPrescriberEdit: () => dispatch(PrescriberActions.closeModal()),
  savePrescriber: prescriberDetails =>
    dispatch(PrescriberActions.updatePrescriber(prescriberDetails)),

  cancelInsuranceEdit: () => dispatch(InsuranceActions.cancel()),
  saveInsurancePolicy: policyDetails => dispatch(InsuranceActions.update(policyDetails)),
});

export const DispensingPage = connect(mapStateToProps, mapDispatchToProps)(Dispensing);

Dispensing.defaultProps = {
  currentPatient: null,
  currentPrescriber: null,
  selectedInsurancePolicy: null,
  canEditPrescriber: false,
};

Dispensing.propTypes = {
  data: PropTypes.object.isRequired,
  columns: PropTypes.array.isRequired,
  isAscending: PropTypes.bool.isRequired,
  sortKey: PropTypes.string.isRequired,
  sort: PropTypes.func.isRequired,
  searchTerm: PropTypes.string.isRequired,
  filter: PropTypes.func.isRequired,
  switchDataset: PropTypes.func.isRequired,
  lookupRecord: PropTypes.func.isRequired,
  cancelLookupRecord: PropTypes.func.isRequired,
  isLookupModalOpen: PropTypes.bool.isRequired,
  gotoPrescription: PropTypes.func.isRequired,
  editPatient: PropTypes.func.isRequired,
  patientEditModalOpen: PropTypes.bool.isRequired,
  createPatient: PropTypes.func.isRequired,
  savePatient: PropTypes.func.isRequired,
  cancelPatientEdit: PropTypes.func.isRequired,
  currentPatient: PropTypes.object,
  canEditPatient: PropTypes.bool.isRequired,
  currentPrescriber: PropTypes.object,
  canEditPrescriber: PropTypes.bool,
  editPrescriber: PropTypes.func.isRequired,
  createPrescriber: PropTypes.func.isRequired,
  cancelPrescriberEdit: PropTypes.func.isRequired,
  savePrescriber: PropTypes.func.isRequired,
  prescriberModalOpen: PropTypes.bool.isRequired,
  usingPatientsDataSet: PropTypes.bool.isRequired,
  usingPrescribersDataSet: PropTypes.bool.isRequired,
  patientHistoryModalOpen: PropTypes.bool.isRequired,
  selectedInsurancePolicy: PropTypes.object,
  insuranceModalOpen: PropTypes.bool.isRequired,
  canEditInsurancePolicy: PropTypes.bool.isRequired,
  cancelInsuranceEdit: PropTypes.func.isRequired,
  isCreatingInsurancePolicy: PropTypes.bool.isRequired,
  saveInsurancePolicy: PropTypes.func.isRequired,
  viewPatientHistory: PropTypes.func.isRequired,
};
<commit_msg>Refresh the Dispensary page when the name changes - read only<commit_after>/* eslint-disable react/forbid-prop-types */
/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */
import React, { useCallback, useMemo } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { View } from 'react-native';

import { ToggleBar, DataTablePageView, SearchBar, PageButton } from '../widgets';
import { DataTable, DataTableRow, DataTableHeaderRow } from '../widgets/DataTable';
import { SearchForm } from '../widgets/modals/SearchForm';
import { PatientHistoryModal } from '../widgets/modals/PatientHistory';
import { FormControl } from '../widgets/FormControl';
import { ModalContainer } from '../widgets/modals/ModalContainer';

import { recordKeyExtractor, getItemLayout } from './dataTableUtilities';
import { createPrescription } from '../navigation/actions';
import { useNavigationFocus, useSyncListener } from '../hooks';

import { UIDatabase } from '../database';
import { getFormInputConfig } from '../utilities/formInputConfigs';

import { PatientActions } from '../actions/PatientActions';
import { PrescriberActions } from '../actions/PrescriberActions';
import { InsuranceActions } from '../actions/InsuranceActions';
import { DispensaryActions } from '../actions/DispensaryActions';

import {
  selectDataSetInUse,
  selectSortedData,
  selectLookupModalOpen,
} from '../selectors/dispensary';
import { selectPrescriberModalOpen, selectCanEditPrescriber } from '../selectors/prescriber';
import { selectInsuranceModalOpen, selectCanEditInsurancePolicy } from '../selectors/insurance';
import { selectPatientModalOpen, selectCanEditPatient } from '../selectors/patient';

import globalStyles from '../globalStyles';
import { dispensingStrings } from '../localization';

const Dispensing = ({
  data,
  columns,
  isAscending,
  sortKey,
  searchTerm,
  usingPatientsDataSet,
  usingPrescribersDataSet,

  // Misc. Callbacks
  filter,
  sort,
  gotoPrescription,
  navigation,
  refreshData,
  switchDataset,

  // Dispensary lookup API callbacks
  lookupRecord,
  cancelLookupRecord,

  // Dispensary lookup API variables
  isLookupModalOpen,

  // Patient variable
  patientEditModalOpen,
  currentPatient,
  patientHistoryModalOpen,
  canEditPatient,

  // Patient callback
  editPatient,
  createPatient,
  cancelPatientEdit,
  savePatient,
  viewPatientHistory,

  // Prescriber variables
  currentPrescriber,
  prescriberModalOpen,
  canEditPrescriber,

  // Prescriber callbacks
  editPrescriber,
  createPrescriber,
  cancelPrescriberEdit,
  savePrescriber,

  // Insurance variables
  insuranceModalOpen,
  selectedInsurancePolicy,
  canEditInsurancePolicy,
  isCreatingInsurancePolicy,

  // Insurance callbacks
  cancelInsuranceEdit,
  saveInsurancePolicy,
}) => {
  // Custom hook to refresh data on this page when becoming the head of the stack again.
  useNavigationFocus(navigation, refreshData);
  useSyncListener(refreshData, 'Name');

  const getCellCallbacks = colKey => {
    switch (colKey) {
      case 'dispense':
        return gotoPrescription;
      case 'patientHistory':
        return viewPatientHistory;
      case 'patientEdit':
        return editPatient;
      case 'prescriberEdit':
        return editPrescriber;
      default:
        return null;
    }
  };

  const renderRow = useCallback(
    listItem => {
      const { item, index } = listItem;
      const rowKey = recordKeyExtractor(item);
      return (
        <DataTableRow
          rowData={data[index]}
          rowKey={rowKey}
          getCallback={getCellCallbacks}
          columns={columns}
          rowIndex={index}
        />
      );
    },
    [data]
  );

  const renderHeader = useCallback(
    () => (
      <DataTableHeaderRow
        columns={columns}
        isAscending={isAscending}
        sortKey={sortKey}
        onPress={sort}
      />
    ),
    [sortKey, isAscending, columns]
  );

  const toggles = useMemo(
    () => [
      {
        text: dispensingStrings.patients,
        onPress: switchDataset,
        isOn: usingPatientsDataSet,
      },
      {
        text: dispensingStrings.prescribers,
        onPress: switchDataset,
        isOn: usingPrescribersDataSet,
      },
    ],
    [usingPatientsDataSet, usingPrescribersDataSet, switchDataset]
  );

  const newRecordText = useMemo(
    () =>
      usingPatientsDataSet
        ? `${dispensingStrings.new_patient}`
        : `${dispensingStrings.new} ${dispensingStrings.prescriber}`,
    [usingPatientsDataSet]
  );
  const lookupRecordText = useMemo(
    () =>
      usingPatientsDataSet
        ? `${dispensingStrings.lookup_patient}`
        : `${dispensingStrings.lookup_prescriber}`,
    [usingPatientsDataSet]
  );

  const newRecordAction = useMemo(() => (usingPatientsDataSet ? createPatient : createPrescriber), [
    usingPatientsDataSet,
  ]);
  const lookupRecordAction = useMemo(() => lookupRecord, []);

  const { pageTopSectionContainer } = globalStyles;
  return (
    <>
      <DataTablePageView>
        <View style={pageTopSectionContainer}>
          <ToggleBar toggles={toggles} />
          <SearchBar
            onChangeText={filter}
            value={searchTerm}
            viewStyle={localStyles.searchBar}
            placeholder={dispensingStrings.search_by_last_name_first_name}
          />
          <PageButton text={newRecordText} onPress={newRecordAction} style={localStyles.button} />
          <PageButton
            text={lookupRecordText}
            onPress={lookupRecordAction}
            style={localStyles.button}
          />
        </View>
        <DataTable
          data={data}
          renderRow={renderRow}
          renderHeader={renderHeader}
          keyExtractor={recordKeyExtractor}
          getItemLayout={getItemLayout}
        />
      </DataTablePageView>
      <ModalContainer
        title={`${dispensingStrings.patient_detail}`}
        noCancel
        fullScreen
        isVisible={patientEditModalOpen}
      >
        <FormControl
          isDisabled={!canEditPatient}
          onSave={savePatient}
          onCancel={cancelPatientEdit}
          inputConfig={getFormInputConfig('patient', currentPatient)}
        />
      </ModalContainer>
      <ModalContainer
        title={`${dispensingStrings.prescriber} ${dispensingStrings.details}`}
        noCancel
        fullScreen
        isVisible={prescriberModalOpen}
      >
        <FormControl
          isDisabled={!canEditPrescriber}
          onSave={savePrescriber}
          onCancel={cancelPrescriberEdit}
          inputConfig={getFormInputConfig('prescriber', currentPrescriber)}
        />
      </ModalContainer>
      <ModalContainer
        title={`${dispensingStrings.insurance_policy}`}
        noCancel
        fullScreen
        isVisible={insuranceModalOpen}
      >
        <FormControl
          isDisabled={!canEditInsurancePolicy}
          confirmOnSave={!canEditPatient}
          confirmText={dispensingStrings.confirm_new_policy}
          onSave={saveInsurancePolicy}
          onCancel={cancelInsuranceEdit}
          inputConfig={getFormInputConfig(
            'insurancePolicy',
            isCreatingInsurancePolicy ? null : selectedInsurancePolicy
          )}
        />
      </ModalContainer>
      <ModalContainer
        title={`${dispensingStrings.patient} ${dispensingStrings.history} - ${currentPatient?.name}`}
        onClose={cancelPatientEdit}
        fullScreen
        isVisible={patientHistoryModalOpen}
      >
        <PatientHistoryModal />
      </ModalContainer>
      <ModalContainer
        title={
          usingPatientsDataSet
            ? `${dispensingStrings.lookup_patient}`
            : `${dispensingStrings.lookup_prescriber}`
        }
        onClose={cancelLookupRecord}
        fullScreen
        isVisible={isLookupModalOpen}
      >
        <SearchForm />
      </ModalContainer>
    </>
  );
};

const localStyles = {
  searchBar: {
    borderBottomWidth: 1,
    flexDirection: 'row',
    alignItems: 'center',
    marginHorizontal: 5,
    flex: 1,
    flexGrow: 1,
  },
  button: {
    marginHorizontal: 2.5,
  },
};

const mapStateToProps = state => {
  const { patient, prescriber, insurance, dispensary } = state;
  const { sortKey, isAscending, searchTerm, columns } = dispensary;

  const isLookupModalOpen = selectLookupModalOpen(state);

  const { currentPatient } = patient;
  const { currentPrescriber } = prescriber;
  const { isCreatingInsurancePolicy, selectedInsurancePolicy } = insurance;

  const prescriberModalOpen = selectPrescriberModalOpen(state);
  const canEditPrescriber = selectCanEditPrescriber(state);
  const canEditPatient = selectCanEditPatient(state);
  const canEditInsurancePolicy = selectCanEditInsurancePolicy(state);
  const [patientEditModalOpen, patientHistoryModalOpen] = selectPatientModalOpen(state);
  const insuranceModalOpen = selectInsuranceModalOpen(state);
  const data = selectSortedData(state);

  const [usingPatientsDataSet, usingPrescribersDataSet] = selectDataSetInUse(state);

  return {
    usingPatientsDataSet,
    usingPrescribersDataSet,
    data,
    sortKey,
    isAscending,
    searchTerm,
    columns,
    // Dispensary lookup API
    isLookupModalOpen,
    // Patient
    patientEditModalOpen,
    currentPatient,
    patientHistoryModalOpen,
    canEditPatient,
    // Prescriber
    currentPrescriber,
    prescriberModalOpen,
    canEditPrescriber,
    // Insurance
    insuranceModalOpen,
    selectedInsurancePolicy,
    canEditInsurancePolicy,
    isCreatingInsurancePolicy,
  };
};

const mapDispatchToProps = dispatch => ({
  gotoPrescription: patientID => dispatch(createPrescription(patientID)),

  filter: searchTerm => dispatch(DispensaryActions.filter(searchTerm)),
  sort: sortKey => dispatch(DispensaryActions.sort(sortKey)),
  refreshData: () => dispatch(DispensaryActions.refresh()),
  switchDataset: () => dispatch(DispensaryActions.switchDataSet()),

  lookupRecord: () => dispatch(DispensaryActions.openLookupModal()),
  cancelLookupRecord: () => dispatch(DispensaryActions.closeLookupModal()),

  editPatient: patient => dispatch(PatientActions.editPatient(UIDatabase.get('Name', patient))),
  createPatient: () => dispatch(PatientActions.createPatient()),
  cancelPatientEdit: () => dispatch(PatientActions.closeModal()),
  savePatient: patientDetails => dispatch(PatientActions.patientUpdate(patientDetails)),
  viewPatientHistory: rowKey =>
    dispatch(PatientActions.viewPatientHistory(UIDatabase.get('Name', rowKey))),

  editPrescriber: prescriber =>
    dispatch(PrescriberActions.editPrescriber(UIDatabase.get('Prescriber', prescriber))),
  createPrescriber: () => dispatch(PrescriberActions.createPrescriber()),
  cancelPrescriberEdit: () => dispatch(PrescriberActions.closeModal()),
  savePrescriber: prescriberDetails =>
    dispatch(PrescriberActions.updatePrescriber(prescriberDetails)),

  cancelInsuranceEdit: () => dispatch(InsuranceActions.cancel()),
  saveInsurancePolicy: policyDetails => dispatch(InsuranceActions.update(policyDetails)),
});

export const DispensingPage = connect(mapStateToProps, mapDispatchToProps)(Dispensing);

Dispensing.defaultProps = {
  currentPatient: null,
  currentPrescriber: null,
  selectedInsurancePolicy: null,
  canEditPrescriber: false,
};

Dispensing.propTypes = {
  data: PropTypes.object.isRequired,
  columns: PropTypes.array.isRequired,
  isAscending: PropTypes.bool.isRequired,
  sortKey: PropTypes.string.isRequired,
  sort: PropTypes.func.isRequired,
  searchTerm: PropTypes.string.isRequired,
  filter: PropTypes.func.isRequired,
  navigation: PropTypes.object.isRequired,
  refreshData: PropTypes.func.isRequired,
  switchDataset: PropTypes.func.isRequired,
  lookupRecord: PropTypes.func.isRequired,
  cancelLookupRecord: PropTypes.func.isRequired,
  isLookupModalOpen: PropTypes.bool.isRequired,
  gotoPrescription: PropTypes.func.isRequired,
  editPatient: PropTypes.func.isRequired,
  patientEditModalOpen: PropTypes.bool.isRequired,
  createPatient: PropTypes.func.isRequired,
  savePatient: PropTypes.func.isRequired,
  cancelPatientEdit: PropTypes.func.isRequired,
  currentPatient: PropTypes.object,
  canEditPatient: PropTypes.bool.isRequired,
  currentPrescriber: PropTypes.object,
  canEditPrescriber: PropTypes.bool,
  editPrescriber: PropTypes.func.isRequired,
  createPrescriber: PropTypes.func.isRequired,
  cancelPrescriberEdit: PropTypes.func.isRequired,
  savePrescriber: PropTypes.func.isRequired,
  prescriberModalOpen: PropTypes.bool.isRequired,
  usingPatientsDataSet: PropTypes.bool.isRequired,
  usingPrescribersDataSet: PropTypes.bool.isRequired,
  patientHistoryModalOpen: PropTypes.bool.isRequired,
  selectedInsurancePolicy: PropTypes.object,
  insuranceModalOpen: PropTypes.bool.isRequired,
  canEditInsurancePolicy: PropTypes.bool.isRequired,
  cancelInsuranceEdit: PropTypes.func.isRequired,
  isCreatingInsurancePolicy: PropTypes.bool.isRequired,
  saveInsurancePolicy: PropTypes.func.isRequired,
  viewPatientHistory: PropTypes.func.isRequired,
};
<|endoftext|>


<commit_before>import axios from 'axios'
import pickBy from 'lodash/pickBy'

/**
 * coindeskParser - Parses CoindDesk ticker data.
 *
 * @param {object} data Ticker data
 * @returns {object} Price data from Coinbase
 */
function coindeskParser(data) {
  const { bpi } = data
  return Object.keys(bpi).reduce((acc, next) => {
    acc[next] = bpi[next].rate_float
    return acc
  }, {})
}

/**
 * bitstampParser - Parses Bitstamp ticker data.
 *
 * @param {string} currency Currency name
 * @param {object} data Ticker data
 * @returns {object} Price data from Bitstamp
 */
function bitstampParser(currency, data) {
  return {
    [currency]: data.data.last,
  }
}

/**
 * krakenParser - Parses Kraken ticker data.
 *
 * @param {string} currency Currency name
 * @param {object} data Ticker data
 * @returns {object} Price data from Kraken
 */
function krakenParser(currency, data) {
  const tickerData = data.data.result
  // kraken has weird resulting tickers format like XXBTZUSD
  // so we just pick first key of the result
  const rate = tickerData[Object.keys(tickerData)[0]].c[0]
  return {
    [currency]: rate,
  }
}

/**
 * bitfinexParser - Parses Bitfinex ticker data.
 *
 * @param {string} currency Currency name
 * @param {object} data Ticker data
 * @returns {object} Price data from Bitfinex
 */
function bitfinexParser(currency, data) {
  return {
    [currency]: data.data.last_price,
  }
}

/**
 * createConfig - Creates provider config for the specified `coin` and `currency`.
 *
 * @param {('BTC'|'LTC')} coin Crypto currency of interest
 * @param {string} currency Fiat currency of interest
 * @returns {object} Config object
 */
function createConfig(coin, currency) {
  const scheme =
    (process && process.env.HOT) || (window.env && window.env.HOT) ? '/proxy/' : 'https://'

  const formatUrl = url => `${scheme}${url}`

  const KRAKEN_FORMAT = {
    BTC: 'XBT',
    LTC: 'LTC',
  }
  const config = {
    coinbase: {
      coins: ['BTC', 'LTC'],
      name: 'Coinbase',
      id: 'coinbase',
      apiUrl: formatUrl(`api.coinbase.com/v2/exchange-rates?currency=${coin}`),
      parser: response => response.data.data.rates,
    },
    bitstamp: {
      name: 'Bitstamp',
      id: 'bitstamp',
      coins: ['BTC', 'LTC'],
      currencies: ['USD', 'EUR'],
      apiUrl: formatUrl(`www.bitstamp.net/api/v2/ticker/${coin}${currency}/`),
      parser: bitstampParser.bind(null, currency),
    },
    kraken: {
      name: 'Kraken',
      id: 'kraken',
      coins: ['BTC', 'LTC'],
      currencies: ['EUR', 'USD', 'CAD', 'GBP', 'JPY'],
      apiUrl: formatUrl(`api.kraken.com/0/public/Ticker?pair=${KRAKEN_FORMAT[coin]}${currency}`),
      parser: krakenParser.bind(null, currency),
    },
    bitfinex: {
      name: 'Bitfinex',
      id: 'bitfinex',
      coins: ['BTC'],
      currencies: ['USD', 'EUR'],
      apiUrl: formatUrl(`api.bitfinex.com/v1/pubticker//${coin}${currency}/`),
      parser: bitfinexParser.bind(null, currency),
    },
    coindesk: {
      disabled: true,
      coins: ['BTC'],
      name: 'Coindesk',
      apiUrl: formatUrl(`api.coindesk.com/v1/bpi/currentprice/${coin}.json`),
      parser: coindeskParser,
    },
  }
  // remove disabled providers as well as ones that don't support requested currency or coin
  return pickBy(
    config,
    ({ disabled, coins, currencies }) =>
      !disabled &&
      (!coin || coins.includes(coin)) &&
      (!currencies || !currency || currencies.includes(currency))
  )
}

/**
 * requestTicker - Returns ticker for the specified `coin` and `currency` using `provider`.
 *
 * @param {string} provider Provider of interest
 * @param {('BTC'|'LTC')} coin Crypto currency of interest
 * @param {string} currency  Fiat currency of interest
 * @returns {Promise} Promise that resolves to {[currency]:rate} Object. Or empty object
 * if something went wrong
 */
export async function requestTicker(provider, coin, currency) {
  const config = createConfig(coin, currency)
  const { apiUrl, parser } = config[provider] || {}

  if (!(apiUrl && parser)) {
    return {}
  }

  return await axios
    .get(apiUrl)
    .then(parser)
    .catch(() => ({}))
}

/**
 * getSupportedProviders - Get list of supported providers for the specified `coin` and `currency`
 * if called with undefined `coin` and/or `currency` - returns all enabled providers.
 *
 * @param {('BTC'|'LTC')} coin Crypto currency of interest
 * @param {string} currency Fiat currency of interest
 * @returns {object} Details of supported rate providers
 */
export function getSupportedProviders(coin, currency) {
  return createConfig(coin, currency)
}

/**
 * requestTickerWithFallback - Returns ticker for the specified `coin` and `currency` using `provider`
 * falls back to `fallback` if operation was unsuccessful.
 *
 * @param {string} provider Provider of interest
 * @param {('BTC'|'LTC')} coin Crypto currency of interest
 * @param {string} currency Fiat currency of interest
 * @param {string} fallback Fallback provider name
 * @returns {Promise} Promise that resolves to {[currency]:rate} Object. Or empty object if something went wrong
 */
export async function requestTickerWithFallback(provider, coin, currency, fallback = 'coinbase') {
  const result = await requestTicker(provider, coin, currency)

  if (!result[currency] && provider !== fallback) {
    return await requestTicker(fallback, coin, currency)
  }
  return result
}
<commit_msg>fix(walet): ensure fallback when ticker provider is unavailable<commit_after>import axios from 'axios'
import pickBy from 'lodash/pickBy'
import uniq from 'lodash/uniq'
import { mainLog } from '@zap/utils/log'

/**
 * coindeskParser - Parses CoindDesk ticker data.
 *
 * @param {object} data Ticker data
 * @returns {object} Price data from Coinbase
 */
function coindeskParser(data) {
  const { bpi } = data
  return Object.keys(bpi).reduce((acc, next) => {
    acc[next] = bpi[next].rate_float
    return acc
  }, {})
}

/**
 * bitstampParser - Parses Bitstamp ticker data.
 *
 * @param {string} currency Currency name
 * @param {object} data Ticker data
 * @returns {object} Price data from Bitstamp
 */
function bitstampParser(currency, data) {
  return {
    [currency]: data.data.last,
  }
}

/**
 * krakenParser - Parses Kraken ticker data.
 *
 * @param {string} currency Currency name
 * @param {object} data Ticker data
 * @returns {object} Price data from Kraken
 */
function krakenParser(currency, data) {
  const tickerData = data.data.result
  // kraken has weird resulting tickers format like XXBTZUSD
  // so we just pick first key of the result
  const rate = tickerData[Object.keys(tickerData)[0]].c[0]
  return {
    [currency]: rate,
  }
}

/**
 * bitfinexParser - Parses Bitfinex ticker data.
 *
 * @param {string} currency Currency name
 * @param {object} data Ticker data
 * @returns {object} Price data from Bitfinex
 */
function bitfinexParser(currency, data) {
  return {
    [currency]: data.data.last_price,
  }
}

/**
 * createConfig - Creates provider config for the specified `coin` and `currency`.
 *
 * @param {('BTC'|'LTC')} coin Crypto currency of interest
 * @param {string} currency Fiat currency of interest
 * @returns {object} Config object
 */
function createConfig(coin, currency) {
  const scheme =
    (process && process.env.HOT) || (window.env && window.env.HOT) ? '/proxy/' : 'https://'

  const formatUrl = url => `${scheme}${url}`

  const KRAKEN_FORMAT = {
    BTC: 'XBT',
    LTC: 'LTC',
  }
  const config = {
    coinbase: {
      coins: ['BTC', 'LTC'],
      name: 'Coinbase',
      id: 'coinbase',
      apiUrl: formatUrl(`api.coinbase.com/v2/exchange-rates?currency=${coin}`),
      parser: response => response.data.data.rates,
    },
    bitstamp: {
      name: 'Bitstamp',
      id: 'bitstamp',
      coins: ['BTC', 'LTC'],
      currencies: ['USD', 'EUR'],
      apiUrl: formatUrl(`www.bitstamp.net/api/v2/ticker/${coin}${currency}/`),
      parser: bitstampParser.bind(null, currency),
    },
    kraken: {
      name: 'Kraken',
      id: 'kraken',
      coins: ['BTC', 'LTC'],
      currencies: ['EUR', 'USD', 'CAD', 'GBP', 'JPY'],
      apiUrl: formatUrl(`api.kraken.com/0/public/Ticker?pair=${KRAKEN_FORMAT[coin]}${currency}`),
      parser: krakenParser.bind(null, currency),
    },
    bitfinex: {
      name: 'Bitfinex',
      id: 'bitfinex',
      coins: ['BTC'],
      currencies: ['USD', 'EUR'],
      apiUrl: formatUrl(`api.bitfinex.com/v1/pubticker//${coin}${currency}/`),
      parser: bitfinexParser.bind(null, currency),
    },
    coindesk: {
      disabled: true,
      coins: ['BTC'],
      name: 'Coindesk',
      apiUrl: formatUrl(`api.coindesk.com/v1/bpi/currentprice/${coin}.json`),
      parser: coindeskParser,
    },
  }
  // remove disabled providers as well as ones that don't support requested currency or coin
  return pickBy(
    config,
    ({ disabled, coins, currencies }) =>
      !disabled &&
      (!coin || coins.includes(coin)) &&
      (!currencies || !currency || currencies.includes(currency))
  )
}

/**
 * requestTicker - Returns ticker for the specified `coin` and `currency` using `provider`.
 *
 * @param {string} provider Provider of interest
 * @param {('BTC'|'LTC')} coin Crypto currency of interest
 * @param {string} currency  Fiat currency of interest
 * @returns {Promise} Promise that resolves to {[currency]:rate} Object. Or empty object
 * if something went wrong
 */
export async function requestTicker(provider, coin, currency) {
  mainLog.info('Fetching %s/%s ticker from %s', coin, currency, provider)
  const config = createConfig(coin, currency)
  const { apiUrl, parser } = config[provider] || {}

  if (!(apiUrl && parser)) {
    return {}
  }

  return await axios
    .get(apiUrl)
    .then(parser)
    .catch(() => ({}))
}

/**
 * getSupportedProviders - Get list of supported providers for the specified `coin` and `currency`
 * if called with undefined `coin` and/or `currency` - returns all enabled providers.
 *
 * @param {('BTC'|'LTC')} coin Crypto currency of interest
 * @param {string} currency Fiat currency of interest
 * @returns {object} Details of supported rate providers
 */
export function getSupportedProviders(coin, currency) {
  return createConfig(coin, currency)
}

/**
 * requestTickerWithFallback - Returns ticker for the specified `coin` and `currency` using `provider`
 * falls back to `fallback` if operation was unsuccessful.
 *
 * @param {string} provider Provider of interest
 * @param {('BTC'|'LTC')} coin Crypto currency of interest
 * @param {string} currency Fiat currency of interest
 * @returns {Promise} Promise that resolves to {[currency]:rate} Object. Or empty object if something went wrong
 */
export async function requestTickerWithFallback(provider, coin, currency) {
  const fallbackProviders = Object.keys(getSupportedProviders(coin, currency))
  const allProviders = uniq([provider].concat(fallbackProviders))

  // Try each provider sequentially until we get a result.
  let result = {}
  for await (const currentProvider of allProviders) {
    result = await requestTicker(currentProvider, coin, currency)

    // If we got the result we were looking for abort early.
    if (result[currency]) {
      break
    }
    // Otherwise warn arn move onto the next provider.
    mainLog.warn('Unable to fetch %s/%s ticker from %s', coin, currency, currentProvider)
  }

  return result
}
<|endoftext|>


<commit_before>(function (purchasing, $, undefined) {
    purchasing.loadTableTools = false;

    purchasing.startup = function () {
        $('input[type=checkbox]').tzCheckbox({ labels: ['Yes', 'No'] });

        if (window.Configuration.LoadTableTools) {
            $(".dt-table, .datatable").dataTable({ "bJQueryUI": false,
                "sPaginationType": "full_numbers",
                "iDisplayLength": window.Configuration.DataTablesPageSize,
                "sDom": 'T<"clear">lfrtip',
                "oTableTools": {
                    "sSwfPath": window.Configuration.TableToolsSwf,
                    "aButtons": ["copy", "xls", "print"]
                }
            });
        } else {
            $(".dt-table, .datatable").dataTable({ "bJQueryUI": false, "sPaginationType": "full_numbers", "iDisplayLength": window.Configuration.DataTablesPageSize });
        }
        $(".button, .text_btn, button").button();
        $('input[type="datetime"]').datepicker();
        $('input.datepicker').datepicker();

        initUservoice();
        konami(function () {
            $("#carty").show();
        });
    };

    function initUservoice() {
        var uv = document.createElement('script'); uv.type = 'text/javascript'; uv.async = true;
        uv.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'widget.uservoice.com/39iNhpJPwlSkFDpX5Ajxw.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(uv, s);
    }

    function konami(callback) {
        var code = "38,38,40,40,37,39,37,39,66,65";
        var kkeys = [];

        $(window).on('keydown', function (e) {
            kkeys.push(e.keyCode);
            while (kkeys.length > code.split(',').length) {
                kkeys.shift();
            }
            if (kkeys.toString().indexOf(code) >= 0) {
                $(this).unbind('keydown', arguments.callee);
                callback(e);
            }
        });
    }
} (window.purchasing = window.purchasing || {}, jQuery));

if (typeof console == "undefined") { //Define the console as a backup for browsers without console
    window.console = {
        log: function () { }
    };
}

$(function () {//run the page load startup code
    purchasing.startup();
});<commit_msg>Added google analytics async code, but it's not called & needs num<commit_after>(function (purchasing, $, undefined) {
    purchasing.loadTableTools = false;

    purchasing.startup = function () {
        $('input[type=checkbox]').tzCheckbox({ labels: ['Yes', 'No'] });

        if (window.Configuration.LoadTableTools) {
            $(".dt-table, .datatable").dataTable({ "bJQueryUI": false,
                "sPaginationType": "full_numbers",
                "iDisplayLength": window.Configuration.DataTablesPageSize,
                "sDom": 'T<"clear">lfrtip',
                "oTableTools": {
                    "sSwfPath": window.Configuration.TableToolsSwf,
                    "aButtons": ["copy", "xls", "print"]
                }
            });
        } else {
            $(".dt-table, .datatable").dataTable({ "bJQueryUI": false, "sPaginationType": "full_numbers", "iDisplayLength": window.Configuration.DataTablesPageSize });
        }
        $(".button, .text_btn, button").button();
        $('input[type="datetime"]').datepicker();
        $('input.datepicker').datepicker();

        initUservoice();
        konami(function () {
            $("#carty").show();
        });
    };

    function initUservoice() {
        var uv = document.createElement('script'); uv.type = 'text/javascript'; uv.async = true;
        uv.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'widget.uservoice.com/39iNhpJPwlSkFDpX5Ajxw.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(uv, s);
    }

    function initGoogleAnalytics() {
        var _gaq = [['_setAccount', 'UA-XXXXX-X'], ['_trackPageview']];
        (function (d, t) {
            var g = d.createElement(t), s = d.getElementsByTagName(t)[0];
            g.src = ('https:' == location.protocol ? '//ssl' : '//www') + '.google-analytics.com/ga.js';
            s.parentNode.insertBefore(g, s);
        } (document, 'script'));
    }

    function konami(callback) {
        var code = "38,38,40,40,37,39,37,39,66,65";
        var kkeys = [];

        $(window).on('keydown', function (e) {
            kkeys.push(e.keyCode);
            while (kkeys.length > code.split(',').length) {
                kkeys.shift();
            }
            if (kkeys.toString().indexOf(code) >= 0) {
                $(this).unbind('keydown', arguments.callee);
                callback(e);
            }
        });
    }
} (window.purchasing = window.purchasing || {}, jQuery));

if (typeof console == "undefined") { //Define the console as a backup for browsers without console
    window.console = {
        log: function () { }
    };
}

$(function () {//run the page load startup code
    purchasing.startup();
});<|endoftext|>


<commit_before>const crypto = require('crypto');
const got = require('got');

module.exports = {
  setNewValue,
};

async function setNewValue(currentFileContent, upgrade) {
  try {
    logger.debug(`bazel.setNewValue: ${upgrade.newVersion}`);
    let newDef;
    if (upgrade.depType === 'git_repository') {
      newDef = upgrade.def.replace(
        /tag = "[^"]+"/,
        `tag = "${upgrade.newVersion}"`
      );
    } else if (upgrade.depType === 'http_archive') {
      const [, shortRepo] = upgrade.repo.split('/');
      const newUrl = `https://github.com/${upgrade.repo}/releases/download/${
        upgrade.newVersion
      }/${shortRepo}-${upgrade.newVersion}.tar.gz`;
      const file = (await got(newUrl, { encoding: null })).body;
      const hash = crypto
        .createHash('sha256')
        .update(file)
        .digest('hex');
      newDef = upgrade.def.replace(/url = "[^"]+"/, `url = "${newUrl}"`);
      newDef = newDef.replace(/sha256 = "[^"]+"/, `sha256 = "${hash}"`);
    }
    logger.debug({ oldDef: upgrade.def, newDef });
    const existingDef = new RegExp(
      `${upgrade.depType}\\([^\\)]+name = "${upgrade.depName}"[^\\)]+\\)`
    );
    return currentFileContent.replace(existingDef, newDef);
  } catch (err) {
    logger.info({ err }, 'Error setting new bazel WORKSPACE version');
    return null;
  }
}
<commit_msg>fix: remove extraneous newline in bazel replacements<commit_after>const crypto = require('crypto');
const got = require('got');

module.exports = {
  setNewValue,
};

async function setNewValue(currentFileContent, upgrade) {
  try {
    logger.debug(`bazel.setNewValue: ${upgrade.newVersion}`);
    let newDef;
    if (upgrade.depType === 'git_repository') {
      newDef = upgrade.def.replace(
        /tag = "[^"]+"/,
        `tag = "${upgrade.newVersion}"`
      );
    } else if (upgrade.depType === 'http_archive') {
      const [, shortRepo] = upgrade.repo.split('/');
      const newUrl = `https://github.com/${upgrade.repo}/releases/download/${
        upgrade.newVersion
      }/${shortRepo}-${upgrade.newVersion}.tar.gz`;
      const file = (await got(newUrl, { encoding: null })).body;
      const hash = crypto
        .createHash('sha256')
        .update(file)
        .digest('hex');
      newDef = upgrade.def.replace(/url = "[^"]+"/, `url = "${newUrl}"`);
      newDef = newDef.replace(/sha256 = "[^"]+"/, `sha256 = "${hash}"`);
    }
    logger.debug({ oldDef: upgrade.def, newDef });
    const existingDef = new RegExp(
      `${upgrade.depType}\\([^\\)]+name = "${upgrade.depName}"[^\\)]+\\)\n`
    );
    return currentFileContent.replace(existingDef, newDef);
  } catch (err) {
    logger.info({ err }, 'Error setting new bazel WORKSPACE version');
    return null;
  }
}
<|endoftext|>


<commit_before>'use strict'

jasmine.JQuery = function() {}

jasmine.JQuery.browserTagCaseIndependentHtml = function(html) {
  var div = document.createElement('div')
  div.innerHTML = html
  return div.innerHTML
}

jasmine.JQuery.elementToString = function(element) {
  if (element instanceof HTMLElement) {
    return element.outerHTML
  } else {
    return element.html()
  }
}

jasmine.JQuery.matchersClass = {}

var jQueryMatchers = {
  toHaveClass: function(className) {
    if (this.actual instanceof HTMLElement) {
      return this.actual.classList.contains(className)
    } else {
      return this.actual.hasClass(className)
    }
  },

  toBeVisible: function() {
    if (this.actual instanceof HTMLElement) {
      return this.actual.offsetWidth !== 0 || this.actual.offsetHeight !== 0
    } else {
      return this.actual.is(':visible')
    }
  },

  toBeHidden: function() {
    if (this.actual instanceof HTMLElement) {
      return this.actual.offsetWidth === 0 && this.actual.offsetHeight === 0
    } else {
      return this.actual.is(':hidden')
    }
  },

  toBeSelected: function() {
    if (this.actual instanceof HTMLElement) {
      return this.actual.selected
    } else {
      return this.actual.is(':selected')
    }
  },

  toBeChecked: function() {
    if (this.actual instanceof HTMLElement) {
      return this.actual.checked
    } else {
      return this.actual.is(':checked')
    }
  },

  toBeEmpty: function() {
    if (this.actual instanceof HTMLElement) {
      return this.actual.innerHTML === ''
    } else {
      return this.actual.is(':empty')
    }
  },

  toExist: function() {
    if (this.actual instanceof HTMLElement) {
      return true
    } else if (this.actual) {
      return this.actual.size() > 0
    } else {
      return false
    }
  },

  toHaveAttr: function(attributeName, expectedAttributeValue) {
    var actualAttributeValue
    if (this.actual instanceof HTMLElement) {
      actualAttributeValue = this.actual.getAttribute(attributeName)
    } else {
      actualAttributeValue = this.actual.attr(attributeName)
    }

    return hasProperty(actualAttributeValue, expectedAttributeValue)
  },

  toHaveId: function(id) {
    if (this.actual instanceof HTMLElement) {
      return this.actual.getAttribute('id') == id
    } else {
      return this.actual.attr('id') == id
    }
  },

  toHaveHtml: function(html) {
    var actualHTML
    if (this.actual instanceof HTMLElement) {
      actualHTML = this.actual.innerHTML
    } else {
      actualHTML = this.actual.html()
    }

    return actualHTML == jasmine.JQuery.browserTagCaseIndependentHtml(html)
  },

  toHaveText: function(text) {
    var actualText
    if (this.actual instanceof HTMLElement) {
      actualText = this.actual.textContent
    } else {
      actualText = this.actual.text()
    }

    if (text && typeof text.test === 'function') {
      return text.test(actualText)
    } else {
      return actualText == text
    }
  },

  toHaveValue: function(value) {
    if (this.actual instanceof HTMLElement) {
      return this.actual.value == value
    } else {
      return this.actual.val() == value
    }
  },

  toHaveData: function(key, expectedValue) {
    if (this.actual instanceof HTMLElement) {
      return hasProperty(this.actual.dataset[key], expectedValue)
    } else {
      return hasProperty(this.actual.data(key), expectedValue)
    }
  },

  toMatchSelector: function(selector) {
    if (this.actual instanceof HTMLElement) {
      return this.actual.matches(selector)
    } else {
      return this.actual.is(selector)
    }
  },

  toContain: function(selector) {
    if (this.actual instanceof HTMLElement) {
      return !!this.actual.querySelector(selector)
    } else {
      return this.actual.find(selector).size() > 0
    }
  },

  toBeDisabled: function(selector){
    if (this.actual instanceof HTMLElement) {
      return this.actual.disabled
    } else {
      return this.actual.is(':disabled')
    }
  },

  // tests the existence of a specific event binding
  toHandle: function(eventName) {
    var events = this.actual.data("events")
    return events && events[eventName].length > 0
  },

  // tests the existence of a specific event binding + handler
  toHandleWith: function(eventName, eventHandler) {
    var stack = this.actual.data("events")[eventName]
    var i
    for (i = 0; i < stack.length; i++) {
      if (stack[i].handler == eventHandler) {
        return true
      }
    }
    return false
  }
}

var hasProperty = function(actualValue, expectedValue) {
  if (expectedValue === undefined) {
    return actualValue !== undefined
  }
  return actualValue == expectedValue
}

var bindMatcher = function(methodName) {
  var builtInMatcher = jasmine.Matchers.prototype[methodName]

  jasmine.JQuery.matchersClass[methodName] = function() {
    if (this.actual && this.actual.jquery || this.actual instanceof HTMLElement) {
      var result = jQueryMatchers[methodName].apply(this, arguments)
      this.actual = jasmine.JQuery.elementToString(this.actual)
      return result
    }

    if (builtInMatcher) {
      return builtInMatcher.apply(this, arguments)
    }

    return false
  }
}

for(var methodName in jQueryMatchers) {
  bindMatcher(methodName)
}

beforeEach(function() {
  this.addMatchers(jasmine.JQuery.matchersClass)
})
<commit_msg>Handle dashes in keys in toHaveData matcher<commit_after>'use strict'

jasmine.JQuery = function() {}

jasmine.JQuery.browserTagCaseIndependentHtml = function(html) {
  var div = document.createElement('div')
  div.innerHTML = html
  return div.innerHTML
}

jasmine.JQuery.elementToString = function(element) {
  if (element instanceof HTMLElement) {
    return element.outerHTML
  } else {
    return element.html()
  }
}

jasmine.JQuery.matchersClass = {}

var jQueryMatchers = {
  toHaveClass: function(className) {
    if (this.actual instanceof HTMLElement) {
      return this.actual.classList.contains(className)
    } else {
      return this.actual.hasClass(className)
    }
  },

  toBeVisible: function() {
    if (this.actual instanceof HTMLElement) {
      return this.actual.offsetWidth !== 0 || this.actual.offsetHeight !== 0
    } else {
      return this.actual.is(':visible')
    }
  },

  toBeHidden: function() {
    if (this.actual instanceof HTMLElement) {
      return this.actual.offsetWidth === 0 && this.actual.offsetHeight === 0
    } else {
      return this.actual.is(':hidden')
    }
  },

  toBeSelected: function() {
    if (this.actual instanceof HTMLElement) {
      return this.actual.selected
    } else {
      return this.actual.is(':selected')
    }
  },

  toBeChecked: function() {
    if (this.actual instanceof HTMLElement) {
      return this.actual.checked
    } else {
      return this.actual.is(':checked')
    }
  },

  toBeEmpty: function() {
    if (this.actual instanceof HTMLElement) {
      return this.actual.innerHTML === ''
    } else {
      return this.actual.is(':empty')
    }
  },

  toExist: function() {
    if (this.actual instanceof HTMLElement) {
      return true
    } else if (this.actual) {
      return this.actual.size() > 0
    } else {
      return false
    }
  },

  toHaveAttr: function(attributeName, expectedAttributeValue) {
    var actualAttributeValue
    if (this.actual instanceof HTMLElement) {
      actualAttributeValue = this.actual.getAttribute(attributeName)
    } else {
      actualAttributeValue = this.actual.attr(attributeName)
    }

    return hasProperty(actualAttributeValue, expectedAttributeValue)
  },

  toHaveId: function(id) {
    if (this.actual instanceof HTMLElement) {
      return this.actual.getAttribute('id') == id
    } else {
      return this.actual.attr('id') == id
    }
  },

  toHaveHtml: function(html) {
    var actualHTML
    if (this.actual instanceof HTMLElement) {
      actualHTML = this.actual.innerHTML
    } else {
      actualHTML = this.actual.html()
    }

    return actualHTML == jasmine.JQuery.browserTagCaseIndependentHtml(html)
  },

  toHaveText: function(text) {
    var actualText
    if (this.actual instanceof HTMLElement) {
      actualText = this.actual.textContent
    } else {
      actualText = this.actual.text()
    }

    if (text && typeof text.test === 'function') {
      return text.test(actualText)
    } else {
      return actualText == text
    }
  },

  toHaveValue: function(value) {
    if (this.actual instanceof HTMLElement) {
      return this.actual.value == value
    } else {
      return this.actual.val() == value
    }
  },

  toHaveData: function(key, expectedValue) {
    if (this.actual instanceof HTMLElement) {
      var camelCaseKey
      for (var part of key.split('-')) {
        if (camelCaseKey) {
          camelCaseKey += part[0].toUpperCase() + part.substring(1)
        } else {
          camelCaseKey = part
        }
      }
      return hasProperty(this.actual.dataset[camelCaseKey], expectedValue)
    } else {
      return hasProperty(this.actual.data(key), expectedValue)
    }
  },

  toMatchSelector: function(selector) {
    if (this.actual instanceof HTMLElement) {
      return this.actual.matches(selector)
    } else {
      return this.actual.is(selector)
    }
  },

  toContain: function(selector) {
    if (this.actual instanceof HTMLElement) {
      return !!this.actual.querySelector(selector)
    } else {
      return this.actual.find(selector).size() > 0
    }
  },

  toBeDisabled: function(selector){
    if (this.actual instanceof HTMLElement) {
      return this.actual.disabled
    } else {
      return this.actual.is(':disabled')
    }
  },

  // tests the existence of a specific event binding
  toHandle: function(eventName) {
    var events = this.actual.data("events")
    return events && events[eventName].length > 0
  },

  // tests the existence of a specific event binding + handler
  toHandleWith: function(eventName, eventHandler) {
    var stack = this.actual.data("events")[eventName]
    var i
    for (i = 0; i < stack.length; i++) {
      if (stack[i].handler == eventHandler) {
        return true
      }
    }
    return false
  }
}

var hasProperty = function(actualValue, expectedValue) {
  if (expectedValue === undefined) {
    return actualValue !== undefined
  }
  return actualValue == expectedValue
}

var bindMatcher = function(methodName) {
  var builtInMatcher = jasmine.Matchers.prototype[methodName]

  jasmine.JQuery.matchersClass[methodName] = function() {
    if (this.actual && this.actual.jquery || this.actual instanceof HTMLElement) {
      var result = jQueryMatchers[methodName].apply(this, arguments)
      this.actual = jasmine.JQuery.elementToString(this.actual)
      return result
    }

    if (builtInMatcher) {
      return builtInMatcher.apply(this, arguments)
    }

    return false
  }
}

for(var methodName in jQueryMatchers) {
  bindMatcher(methodName)
}

beforeEach(function() {
  this.addMatchers(jasmine.JQuery.matchersClass)
})
<|endoftext|>


<commit_before>import React from 'react'

import ComponentRenderer from './src/components/component-renderer-with-pagination'

export default {
  replaceComponentRenderer: ({ props, loader }) => {
    if (props.layout) {
      return null
    }

    return <ComponentRenderer {...props} loader={loader} />
  }
}
<commit_msg>Correctly convert to pure ES6.<commit_after>import React from 'react'

import ComponentRenderer from './src/components/component-renderer-with-pagination'

export const replaceComponentRenderer = ({ props, loader }) => {
  if (props.layout) {
    return null
  }

  return <ComponentRenderer {...props} loader={loader} />
}
<|endoftext|>


<commit_before>const Debug = require('debug')
const path = require('path')
const globalDirs = require('global-dirs')
const { drawBox } = require('@prisma/sdk/dist/drawBox')
const isInstalledGlobally = require('is-installed-globally')
const debug = Debug('preinstall')

const BOLD = '\u001b[1m'
const WHITE_BRIGHT = '\u001b[37;1m'
const RESET = '\u001b[0m'

// returns { pkgManager: 'yarn' | 'npm', pkgPath: string } | null
function isPackageInstalledGlobally(name) {
  try {
    const pkgPath = require.resolve(path.join(globalDirs.yarn.packages, `${name}/package.json`))
    return { pkgManager: 'yarn', pkgPath }
  } catch (_) {
    try {
      const pkgPath = require.resolve(path.join(globalDirs.npm.packages, `${name}/package.json`))
      return { pkgManager: 'npm', pkgPath }
    } catch (_) {
      //
    }
  }
  return null
}

function prismaIsInstalledGlobally() {
  const prismaInstalledGlobally = isPackageInstalledGlobally('prisma')
  console.log({ prismaInstalledGlobally })
  if (prismaInstalledGlobally) {
    return {
      ...prismaInstalledGlobally,
      name: 'prisma',
    }
  }

  const prisma2InstalledGlobally = isPackageInstalledGlobally('prisma2')
  if (prisma2InstalledGlobally) {
    return {
      ...prisma2InstalledGlobally,
      name: 'prisma2',
    }
  }

  return null
}

const b = str => BOLD + str + RESET
const white = str => WHITE_BRIGHT + str + RESET

// When running in npx, npm puts this package into a /_npx/ folder. Tested on Win, Mac, Linux
if (__dirname.includes('_npx')) {
  process.exit(0)
}

if (!isInstalledGlobally) {
  process.exit(0)
}

const installedGlobally = prismaIsInstalledGlobally()
debug({ installedGlobally })
if (!installedGlobally) {
  process.exit(0)
}

const pkg = require(installedGlobally.pkgPath)
const parts = pkg.version.split('-')
const isAlpha = parts.length > 1 ? parts[1].split('.') === 'alpha' : false

let message
if (installedGlobally.name === 'prisma2') {
  message = `
The package ${white('prisma2')} has been renamed to ${white('@prisma/cli')}.

Please uninstall ${white('prisma2')} globally first.
Then install ${white('@prisma/cli')} to continue using ${b('Prisma 2.0')}:

   # Uninstall old CLI
   ${white(installedGlobally.pkgManager === 'yarn' ? 'yarn global remove prisma2' : 'npm uninstall -g prisma2')}

   # Install new CLI
   ${white(`npm install @prisma/cli${isAlpha ? '@alpha' : ''} --save-dev`)}

   # Invoke via npx
   ${white('npx prisma --help')}

Learn more here: https://pris.ly/preview025
`
} else {
  message = `
You seem to have a global installation of Prisma 1 package ${white('prisma')}.
As Prisma 2 uses the same executable ${white('prisma')}, this would lead to a conflict.
We created a new Prisma 1 package ${white('prisma1')} with the executable ${white('prisma1')}
to work around this that you can keep using for Prisma 1.

   # Uninstall old Prisma 1 CLI
   ${white(installedGlobally.pkgManager === 'yarn' ? 'yarn global remove prisma2' : 'npm uninstall -g prisma2')}

   # Install new Prisma 1 CLI
   ${white(installedGlobally.pkgManager === 'yarn' ? 'yarn global add prisma1' : 'npm install -g prisma1')}

   # Use the Prisma 1 CLI
   prisma1 --help

Then you can install Prisma 2:

   # Install Prisma 2 CLI
   ${white(`npm install @prisma/cli${isAlpha ? '@alpha' : ''} --save-dev`)}

   # Invoke via npx
   ${white('npx prisma --help')}

Learn more here: https://pris.ly/prisma1
`
}

console.error(drawBox({ str: message, verticalPadding: 1, horizontalPadding: 3 }))
process.exit(1)
<commit_msg>cleanup<commit_after>const Debug = require('debug')
const path = require('path')
const globalDirs = require('global-dirs')
const { drawBox } = require('@prisma/sdk/dist/drawBox')
const isInstalledGlobally = require('is-installed-globally')
const debug = Debug('preinstall')

const BOLD = '\u001b[1m'
const WHITE_BRIGHT = '\u001b[37;1m'
const RESET = '\u001b[0m'

// returns { pkgManager: 'yarn' | 'npm', pkgPath: string } | null
function isPackageInstalledGlobally(name) {
  try {
    const pkgPath = require.resolve(path.join(globalDirs.yarn.packages, `${name}/package.json`))
    return { pkgManager: 'yarn', pkgPath }
  } catch (_) {
    try {
      const pkgPath = require.resolve(path.join(globalDirs.npm.packages, `${name}/package.json`))
      return { pkgManager: 'npm', pkgPath }
    } catch (_) {
      //
    }
  }
  return null
}

function prismaIsInstalledGlobally() {
  const prismaInstalledGlobally = isPackageInstalledGlobally('prisma')
  if (prismaInstalledGlobally) {
    return {
      ...prismaInstalledGlobally,
      name: 'prisma',
    }
  }

  const prisma2InstalledGlobally = isPackageInstalledGlobally('prisma2')
  if (prisma2InstalledGlobally) {
    return {
      ...prisma2InstalledGlobally,
      name: 'prisma2',
    }
  }

  return null
}

const b = str => BOLD + str + RESET
const white = str => WHITE_BRIGHT + str + RESET

// When running in npx, npm puts this package into a /_npx/ folder. Tested on Win, Mac, Linux
if (__dirname.includes('_npx')) {
  process.exit(0)
}

if (!isInstalledGlobally) {
  process.exit(0)
}

const installedGlobally = prismaIsInstalledGlobally()
debug({ installedGlobally })
if (!installedGlobally) {
  process.exit(0)
}

const pkg = require(installedGlobally.pkgPath)
const parts = pkg.version.split('-')
const isAlpha = parts.length > 1 ? parts[1].split('.') === 'alpha' : false

let message
if (installedGlobally.name === 'prisma2') {
  message = `
The package ${white('prisma2')} has been renamed to ${white('@prisma/cli')}.

Please uninstall ${white('prisma2')} globally first.
Then install ${white('@prisma/cli')} to continue using ${b('Prisma 2.0')}:

   # Uninstall old CLI
   ${white(installedGlobally.pkgManager === 'yarn' ? 'yarn global remove prisma2' : 'npm uninstall -g prisma2')}

   # Install new CLI
   ${white(`npm install @prisma/cli${isAlpha ? '@alpha' : ''} --save-dev`)}

   # Invoke via npx
   ${white('npx prisma --help')}

Learn more here: https://pris.ly/preview025
`
} else {
  message = `
You seem to have a global installation of Prisma 1 package ${white('prisma')}.
As Prisma 2 uses the same executable ${white('prisma')}, this would lead to a conflict.
We created a new Prisma 1 package ${white('prisma1')} with the executable ${white('prisma1')}
to work around this that you can keep using for Prisma 1.

   # Uninstall old Prisma 1 CLI
   ${white(installedGlobally.pkgManager === 'yarn' ? 'yarn global remove prisma2' : 'npm uninstall -g prisma2')}

   # Install new Prisma 1 CLI
   ${white(installedGlobally.pkgManager === 'yarn' ? 'yarn global add prisma1' : 'npm install -g prisma1')}

   # Use the Prisma 1 CLI
   prisma1 --help

Then you can install Prisma 2:

   # Install Prisma 2 CLI
   ${white(`npm install @prisma/cli${isAlpha ? '@alpha' : ''} --save-dev`)}

   # Invoke via npx
   ${white('npx prisma --help')}

Learn more here: https://pris.ly/prisma1
`
}

console.error(drawBox({ str: message, verticalPadding: 1, horizontalPadding: 3 }))
process.exit(1)
<|endoftext|>