<commit_before>
/**
 * @author Angus Sawyer
 */

import { BufferGeometry } from '../../../../three.js/src/core/BufferGeometry';
import { Float32BufferAttribute } from '../../../../three.js/src/core/BufferAttribute';
import { Vector3 } from '../../../../three.js/src/math/Vector3';

function TerrainMeshGeometry( x, y, resolution, meshData, offsets, transform ) {

	BufferGeometry.call( this );

	this.type = 'TerrainMeshGeometry';

	// buffers

	const indices = [];
	const vertices = [];
	const uvs = [];
	const normals = [];

	const dataView = new DataView( meshData, 0 );

	// const centerX = dataView.getFloat64( 0, true );
	// const centerY = dataView.getFloat64( 8, true );
	// const centerZ = dataView.getFloat64( 16, true );

	const minZ = dataView.getFloat32( 24, true );
	const maxZ = dataView.getFloat32( 28, true );
	const rangeZ = maxZ - minZ;

	// vertex count
	const vCount = dataView.getUint32( 88, true );

	const uArray = _decode( new Uint16Array( meshData, 92, vCount ) );
	const vArray = _decode( new Uint16Array( meshData, 92 + vCount * 2, vCount ) );
	const hArray = _decode( new Uint16Array( meshData, 92 + vCount * 4, vCount ) );

	const offsetX = - offsets.x;
	const offsetY = - offsets.y;
	const offsetZ = minZ - offsets.z;

	const xAxis = new Vector3( 1, 0, 0 );

	var i;
	var v3 = new Vector3(); // tmp for normal decoding

	// generate vertices and uvs

	for ( i = 0; i < vCount; i++ ) {

		const u = uArray[ i ] / 32767;
		const v = vArray[ i ] / 32767;

		const coords = transform.forward( { x: x + u * resolution, y: y + v * resolution } );

		vertices.push( coords.x + offsetX );
		vertices.push( coords.y + offsetY );

		vertices.push( hArray[ i ] / 32767 * rangeZ + offsetZ );

		uvs.push ( u, v );

	}

	const indexDataOffset = 88 + 4 + vCount * 6; // need to fix alignment

	var indexElementSize = vCount > 65536 ? 4: 2;

	const triangleCount = dataView.getUint32( indexDataOffset, true );

	const iArray = new Uint16Array( meshData, indexDataOffset + 4, triangleCount * 3 );

	var highest = 0;

	for ( i = 0; i < iArray.length; i++ ) {

		const code = iArray[ i ];

		indices[ i ] = highest - code;

		if ( code === 0 ) {

			++highest;

		}

	}

	var nextStart = indexDataOffset + 4 + ( triangleCount * 3 * indexElementSize );

	// skip edge vertex descriptors

	for ( i = 0; i < 4; i++ ) {

		const edgeVertexCount = dataView.getInt32( nextStart, true );

		nextStart += 4 + edgeVertexCount * indexElementSize;

	}

	/*

	const extentionId = dataView.getUint8( nextStart, true );
	const extentionLength = dataView.getUint32( nextStart + 1, true );

	console.log( 'Exention', extentionId, extentionLength, vCount * 2 );

	*/

	// read oct encoded normals

	const octNormals = new Uint8Array( meshData, nextStart + 5, vCount * 2 );

	for ( i = 0; i < vCount * 2; ) {

		_decodeOct( ( octNormals[ i++ ] / 255 ) * 2 - 1, ( octNormals[ i++ ] / 255 ) * 2 - 1 );

	}

	//	console.log( normals );

	// build geometry

	this.setIndex( indices );

	this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
	//this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );

	this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );

	this.computeBoundingBox();
	this.computeVertexNormals();

	function _decode( tArray ) {

		// zig zag and delta decode
		var value = 0;

		tArray.forEach( function ( deltaValue, index, array ) {

			value += ( deltaValue >> 1 ) ^ ( - ( deltaValue & 1 ) );
			array[ index ] = value;

		} );

		return tArray;

	}

	function _decodeOct ( xOct, yOct ) {

		v3.x = xOct;
		v3.y = yOct;
		v3.z = 1 - ( Math.abs( xOct ) + Math.abs( yOct ) );

		if ( v3.z < 0) {

			const x = v3.x;

			v3.x = ( 1.0 - Math.abs( v3.y ) ) * _signNotZero( x );
			v3.y = ( 1.0 - Math.abs( x ) ) * _signNotZero( v3.y );

		}

		v3.normalize();

		// v3.x *= Math.cos( 52 * Math.PI / 180 );

		v3.applyAxisAngle( xAxis, Math.PI / 4 );

		v3.normalize();

		normals.push( v3.x, v3.y, v3.z );

	}

	function _signNotZero ( value ) {

		return value < 0.0 ? -1.0 : 1.0;

	}

}

TerrainMeshGeometry.prototype = Object.create( BufferGeometry.prototype );

export { TerrainMeshGeometry };
<commit_msg>approximate reference frame shift for pre encoded normals<commit_after>
/**
 * @author Angus Sawyer
 */

import { BufferGeometry } from '../../../../three.js/src/core/BufferGeometry';
import { Float32BufferAttribute } from '../../../../three.js/src/core/BufferAttribute';
import { Vector3 } from '../../../../three.js/src/math/Vector3';
import { Quaternion } from '../../../../three.js/src/math/Quaternion';

function TerrainMeshGeometry( x, y, resolution, meshData, offsets, transform ) {

	BufferGeometry.call( this );

	this.type = 'TerrainMeshGeometry';

	// buffers

	const indices = [];
	const vertices = [];
	const uvs = [];
	const normals = [];

	const dataView = new DataView( meshData, 0 );

	const centerX = dataView.getFloat64( 0, true );
	const centerY = dataView.getFloat64( 8, true );
	const centerZ = dataView.getFloat64( 16, true );

	const up = new Vector3( centerX, centerY, centerZ ).normalize();

	const quaternion = new Quaternion().setFromUnitVectors( up, new Vector3( 0, 0, 1 ) );

	const minZ = dataView.getFloat32( 24, true );
	const maxZ = dataView.getFloat32( 28, true );
	const rangeZ = maxZ - minZ;

	// vertex count
	const vCount = dataView.getUint32( 88, true );

	const uArray = _decode( new Uint16Array( meshData, 92, vCount ) );
	const vArray = _decode( new Uint16Array( meshData, 92 + vCount * 2, vCount ) );
	const hArray = _decode( new Uint16Array( meshData, 92 + vCount * 4, vCount ) );

	const offsetX = - offsets.x;
	const offsetY = - offsets.y;
	const offsetZ = minZ - offsets.z;

	var i;
	var v3 = new Vector3(); // tmp for normal decoding

	// generate vertices and uvs

	for ( i = 0; i < vCount; i++ ) {

		const u = uArray[ i ] / 32767;
		const v = vArray[ i ] / 32767;

		const coords = transform.forward( { x: x + u * resolution, y: y + v * resolution } );

		vertices.push( coords.x + offsetX );
		vertices.push( coords.y + offsetY );

		vertices.push( hArray[ i ] / 32767 * rangeZ + offsetZ );

		uvs.push ( u, v );

	}

	const indexDataOffset = 88 + 4 + vCount * 6; // need to fix alignment

	var indexElementSize = vCount > 65536 ? 4: 2;

	const triangleCount = dataView.getUint32( indexDataOffset, true );

	const iArray = new Uint16Array( meshData, indexDataOffset + 4, triangleCount * 3 );

	var highest = 0;

	for ( i = 0; i < iArray.length; i++ ) {

		const code = iArray[ i ];

		indices[ i ] = highest - code;

		if ( code === 0 ) {

			++highest;

		}

	}

	var nextStart = indexDataOffset + 4 + ( triangleCount * 3 * indexElementSize );

	// skip edge vertex descriptors

	for ( i = 0; i < 4; i++ ) {

		const edgeVertexCount = dataView.getInt32( nextStart, true );

		nextStart += 4 + edgeVertexCount * indexElementSize;

	}

	/*

	const extentionId = dataView.getUint8( nextStart, true );
	const extentionLength = dataView.getUint32( nextStart + 1, true );

	console.log( 'Exention', extentionId, extentionLength, vCount * 2 );

	*/

	// read oct encoded normals

	const octNormals = new Uint8Array( meshData, nextStart + 5, vCount * 2 );

	for ( i = 0; i < vCount * 2; ) {

		_decodeOct( ( octNormals[ i++ ] / 255 ) * 2 - 1, ( octNormals[ i++ ] / 255 ) * 2 - 1 );

	}

	// build geometry

	this.setIndex( indices );

	this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
	this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );

	this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );

	this.computeBoundingBox();
	//this.computeVertexNormals();

	function _decode( tArray ) {

		// zig zag and delta decode
		var value = 0;

		tArray.forEach( function ( deltaValue, index, array ) {

			value += ( deltaValue >> 1 ) ^ ( - ( deltaValue & 1 ) );
			array[ index ] = value;

		} );

		return tArray;

	}

	function _decodeOct ( xOct, yOct ) {

		v3.x = xOct;
		v3.y = yOct;
		v3.z = 1 - ( Math.abs( xOct ) + Math.abs( yOct ) );

		if ( v3.z < 0) {

			const x = v3.x;

			v3.x = ( 1.0 - Math.abs( v3.y ) ) * _signNotZero( x );
			v3.y = ( 1.0 - Math.abs( x ) ) * _signNotZero( v3.y );

		}

		// approximate transformation from ECRF to local refrence frame
		v3.applyQuaternion( quaternion );
		v3.normalize();

		normals.push( v3.y, v3.x, v3.z );

	}

	function _signNotZero ( value ) {

		return value < 0.0 ? -1.0 : 1.0;

	}

}

TerrainMeshGeometry.prototype = Object.create( BufferGeometry.prototype );

export { TerrainMeshGeometry };
<|endoftext|>


<commit_before>import Component from '@ember/component'
import { computed } from '@ember/object';
import { alias } from '@ember/object/computed';
import { get, set } from '@ember/object';
import { inject as service } from '@ember/service';
import { satisfies } from 'shared/utils/parse-version';
import { observer } from '@ember/object';
import ACC from 'shared/mixins/alert-child-component';
import { sortableNumericSuffix } from 'shared/utils/util';

const M_CONFIG = {
  type: 'clusterRoleTemplateBinding',
  clusterId: '',
  name: '',
  subjectKind: '',
  subjectName: '',
  roleTemplateId: '',
};

export default Component.extend(ACC, {
  globalStore: service(),
  memberArray:     alias('cluster.clusterRoleTemplateBindings'),
  memberConfig:    M_CONFIG,

  primaryResource: alias('cluster'),
  cluster: null,
  config: alias('cluster.googleKubernetesEngineConfig'),

  step: 1,
  errors: null,

  zones: null,
  versions: null,
  machineTypes: null,

  init() {
    this._super(...arguments);

    window.gke = this;

    let config = get(this, 'cluster.googleKubernetesEngineConfig');
    if ( !config ) {
      config = this.get('globalStore').createRecord({
        type: 'googleKubernetesEngineConfig',
        diskSizeGb: 100,
        enableAlphaFeature: false,
        nodeCount: 3,
        machineType: 'n1-standard-1',
        zone: 'us-central1-f',
        clusterIpv4Cidr: '',
      });

      set(this, 'cluster.googleKubernetesEngineConfig', config);
    }
  },

  actions: {
    checkServiceAccount() {
      set(this, 'errors', []);
      set(this, 'step', 2);

      this.fetchZones().then(() => {
        this.fetchVersions().then(() => {
          this.fetchMachineTypes().then(() => {
            set(this, 'step', 3);
          });
        });
      }).catch((xhr) => {
        set(this, 'errors', [xhr.body.error]);
        set(this, 'step', 1);
      });
    },
  },

  fetchZones() {
    return get(this, 'globalStore').rawRequest({
      url: 'gkeZones',
      method: 'POST',
      data: {
        credentials: get(this, 'config.credential'),
        projectId: get(this, 'config.projectId'),
      }
    }).then((xhr) => {
      const out = xhr.body.items;
      set(this, 'zones', out);
      return out;
    }).catch((xhr) => {
      set(this, 'errors', [xhr.body.error]);
      set(this, 'step', 1);
    });
  },

  fetchVersions() {
    return get(this, 'globalStore').rawRequest({
      url: 'gkeVersions',
      method: 'POST',
      data: {
        credentials: get(this, 'config.credential'),
        projectId: get(this, 'config.projectId'),
        zone: get(this, 'config.zone'),
      }
    }).then((xhr) => {
      const out = xhr.body;
      set(this, 'versions', out);
      return out;
    }).catch((xhr) => {
      set(this, 'errors', [xhr.body.error]);
      set(this, 'step', 1);
    });
  },

  fetchMachineTypes() {
    return get(this, 'globalStore').rawRequest({
      url: 'gkeMachineTypes',
      method: 'POST',
      data: {
        credentials: get(this, 'config.credential'),
        projectId: get(this, 'config.projectId'),
        zone: get(this, 'config.zone'),
      }
    }).then((xhr) => {
      const out = xhr.body.items;
      set(this, 'machineTypes', out);
      return out;
    }).catch((xhr) => {
      set(this, 'errors', [xhr.body.error]);
      set(this, 'step', 1);
    });
  },

  credentialChanged: observer('config.credential', function() {
    const str = get(this, 'config.credential');
    if ( str ) {
      try {
        const obj = JSON.parse(str);
        // Note: this is a Google project id, not ours.
        const projectId = obj.project_id;
        set(this, 'config.projectId', projectId);
      } catch (e) {
      }
    }
  }),

  zoneChanged: observer('config.zone','zones.[]', function() {
    const zones = get(this, 'zones')||[];
    const currentZone = zones.findBy('name', get(this, 'config.zone'));
    if ( !currentZone || currentZone.status.toLowerCase() !== 'up' ) {
      const newZone = zones.filter((x) => x.name.startsWith('us-')).find((x) => x.status.toLowerCase() === 'up');
      if ( newZone ) {
        set(this, 'config.zone', newZone.name);
      }
    }

    this.fetchVersions();
    this.fetchMachineTypes();
  }),

  zoneChoices: computed('zones.[]', function() {
    let out = get(this,'zones').slice();

    out.forEach((obj) => {
      set(obj, 'sortName', sortableNumericSuffix(obj.name));
      set(obj, 'displayName', obj.name + ' (' + obj.description + ')');
      set(obj, 'disabled', obj.status.toLowerCase() !== 'up');
    });

    return out.sortBy('sortName')
  }),

  machineTypeChanged: observer('config.machineTypes','machineTypes.[]', function() {
    const types = get(this, 'machineTypes')||[];
    const current = types.findBy('name', get(this, 'config.machineType'));
    if ( !current ) {
      set(this, 'config.machineType', get(types, 'firstObject.name'));
    }
  }),

  machineChoices: computed('machineTypes.[]', function() {
    let out = (get(this,'machineTypes')||[]).slice();

    out.forEach((obj) => {
      set(obj, 'sortName', sortableNumericSuffix(obj.name));
      set(obj, 'displayName', obj.name + ' (' + obj.description + ')');
    });

    return out.sortBy('sortName')
  }),

  versionChanged: observer('config.masterVersion','versions.validMasterVersions[]', function() {
    const versions = get(this, 'versions.validMasterVersions')||[];
    const current = versions.findBy('name', get(this, 'config.masterVersion'));
    if ( !current ) {
      set(this, 'config.masterVersion', get(versions, 'firstObject'));
    }
  }),

  versionChoices: computed('config.validMasterVersions.[]', function() {
    const versions = get(this, 'versions');
    if ( !versions ) {
      return [];
    }

    let out = versions.validMasterVersions.slice();

    out = out.filter((v) => {
      return satisfies(v.replace(/-.*/,''), '>=1.8.0');
    });

    return out.map((v) => {
      return {value: v}
    });
  }),

  didSave() {
    const pr = get(this, 'primaryResource');
    return pr.waitForCondition('BackingNamespaceCreated').then(() => {
      return this.alertChildDidSave().then(() => {
        return pr;
      });
    });
  },

  doneSaving() {
    this.transitionToRoute('clusters.index');
  },
});
<commit_msg>More GKE<commit_after>import Component from '@ember/component'
import { computed } from '@ember/object';
import { alias } from '@ember/object/computed';
import { get, set } from '@ember/object';
import { inject as service } from '@ember/service';
import { satisfies } from 'shared/utils/parse-version';
import { observer } from '@ember/object';
import ACC from 'shared/mixins/alert-child-component';
import { sortableNumericSuffix } from 'shared/utils/util';
import { reject } from 'rsvp';

const M_CONFIG = {
  type: 'clusterRoleTemplateBinding',
  clusterId: '',
  name: '',
  subjectKind: '',
  subjectName: '',
  roleTemplateId: '',
};

export default Component.extend(ACC, {
  globalStore: service(),
  memberArray:     alias('cluster.clusterRoleTemplateBindings'),
  memberConfig:    M_CONFIG,

  primaryResource: alias('cluster'),
  cluster: null,
  config: alias('cluster.googleKubernetesEngineConfig'),

  step: 1,
  errors: null,

  zones: null,
  versions: null,
  machineTypes: null,

  init() {
    this._super(...arguments);

    window.gke = this;

    let config = get(this, 'cluster.googleKubernetesEngineConfig');
    if ( !config ) {
      config = this.get('globalStore').createRecord({
        type: 'googleKubernetesEngineConfig',
        diskSizeGb: 100,
        enableAlphaFeature: false,
        nodeCount: 3,
        machineType: 'n1-standard-1',
        zone: 'us-central1-f',
        clusterIpv4Cidr: '',
      });

      set(this, 'cluster.googleKubernetesEngineConfig', config);
    }
  },

  actions: {
    checkServiceAccount() {
      set(this, 'errors', []);
      set(this, 'step', 2);

      return this.fetchZones().then(() => {
        return this.fetchVersions().then(() => {
          return this.fetchMachineTypes().then(() => {
            set(this, 'step', 3);
          });
        });
      }).catch((xhr) => {
        set(this, 'step', 1);
      });
    },
  },

  fetchZones() {
    return get(this, 'globalStore').rawRequest({
      url: 'gkeZones',
      method: 'POST',
      data: {
        credentials: get(this, 'config.credential'),
        projectId: get(this, 'config.projectId'),
      }
    }).then((xhr) => {
      const out = xhr.body.items;
      set(this, 'zones', out);
      return out;
    }).catch((xhr) => {
      set(this, 'errors', [xhr.body.error]);
      return reject();
    });
  },

  fetchVersions() {
    return get(this, 'globalStore').rawRequest({
      url: 'gkeVersions',
      method: 'POST',
      data: {
        credentials: get(this, 'config.credential'),
        projectId: get(this, 'config.projectId'),
        zone: get(this, 'config.zone'),
      }
    }).then((xhr) => {
      const out = xhr.body;
      set(this, 'versions', out);
      return out;
    }).catch((xhr) => {
      set(this, 'errors', [xhr.body.error]);
      return reject();
    });
  },

  fetchMachineTypes() {
    return get(this, 'globalStore').rawRequest({
      url: 'gkeMachineTypes',
      method: 'POST',
      data: {
        credentials: get(this, 'config.credential'),
        projectId: get(this, 'config.projectId'),
        zone: get(this, 'config.zone'),
      }
    }).then((xhr) => {
      const out = xhr.body.items;
      set(this, 'machineTypes', out);
      return out;
    }).catch((xhr) => {
      set(this, 'errors', [xhr.body.error]);
      return reject();
    });
  },

  credentialChanged: observer('config.credential', function() {
    const str = get(this, 'config.credential');
    if ( str ) {
      try {
        const obj = JSON.parse(str);
        // Note: this is a Google project id, not ours.
        const projectId = obj.project_id;
        set(this, 'config.projectId', projectId);
      } catch (e) {
      }
    }
  }),

  zoneChanged: observer('config.zone','zones.[]', function() {
    const zones = get(this, 'zones')||[];
    const currentZone = zones.findBy('name', get(this, 'config.zone'));
    if ( !currentZone || currentZone.status.toLowerCase() !== 'up' ) {
      const newZone = zones.filter((x) => x.name.startsWith('us-')).find((x) => x.status.toLowerCase() === 'up');
      if ( newZone ) {
        set(this, 'config.zone', newZone.name);
      }
    }

    if ( get(this, 'step') >= 3 ) {
      this.fetchVersions();
      this.fetchMachineTypes();
    }
  }),

  zoneChoices: computed('zones.[]', function() {
    let out = (get(this,'zones')||[]).slice();

    out.forEach((obj) => {
      set(obj, 'sortName', sortableNumericSuffix(obj.name));
      set(obj, 'displayName', obj.name + ' (' + obj.description + ')');
      set(obj, 'disabled', obj.status.toLowerCase() !== 'up');
    });

    return out.sortBy('sortName')
  }),

  machineTypeChanged: observer('config.machineTypes','machineTypes.[]', function() {
    const types = get(this, 'machineTypes')||[];
    const current = types.findBy('name', get(this, 'config.machineType'));
    if ( !current ) {
      set(this, 'config.machineType', get(types, 'firstObject.name'));
    }
  }),

  machineChoices: computed('machineTypes.[]', function() {
    let out = (get(this,'machineTypes')||[]).slice();

    out.forEach((obj) => {
      set(obj, 'sortName', sortableNumericSuffix(obj.name));
      set(obj, 'displayName', obj.name + ' (' + obj.description + ')');
    });

    return out.sortBy('sortName')
  }),

  versionChanged: observer('config.masterVersion','versions.validMasterVersions[]', function() {
    const versions = get(this, 'versions.validMasterVersions')||[];
    const current = versions.findBy('name', get(this, 'config.masterVersion'));
    if ( !current ) {
      set(this, 'config.masterVersion', get(versions, 'firstObject'));
    }
  }),

  versionChoices: computed('config.validMasterVersions.[]', function() {
    const versions = get(this, 'versions');
    if ( !versions ) {
      return [];
    }

    let out = versions.validMasterVersions.slice();

    out = out.filter((v) => {
      return satisfies(v.replace(/-.*/,''), '>=1.8.0');
    });

    return out.map((v) => {
      return {value: v}
    });
  }),

  didSave() {
    const pr = get(this, 'primaryResource');
    return pr.waitForCondition('BackingNamespaceCreated').then(() => {
      return this.alertChildDidSave().then(() => {
        return pr;
      });
    });
  },

  doneSaving() {
    this.transitionToRoute('clusters.index');
  },
});
<|endoftext|>


<commit_before>'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};

/**
* @name bind2vind
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/ndarray/base/bind2vind}
*/
setReadOnly( ns, 'bind2vind', require( '@stdlib/types/ndarray/base/bind2vind' ) );

/**
* @name ind2sub
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/ndarray/base/ind2sub}
*/
setReadOnly( ns, 'ind2sub', require( '@stdlib/types/ndarray/base/ind2sub' ) );

/**
* @name isColumnMajor
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/ndarray/base/is-column-major}
*/
setReadOnly( ns, 'isColumnMajor', require( '@stdlib/types/ndarray/base/is-column-major' ) );

/**
* @name isRowMajor
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/ndarray/base/is-row-major}
*/
setReadOnly( ns, 'isRowMajor', require( '@stdlib/types/ndarray/base/is-row-major' ) );

/**
* @name iterationOrder
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/ndarray/base/iteration-order}
*/
setReadOnly( ns, 'iterationOrder', require( '@stdlib/types/ndarray/base/iteration-order' ) );

/**
* @name maxViewBufferIndex
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/ndarray/base/max-view-buffer-index}
*/
setReadOnly( ns, 'maxViewBufferIndex', require( '@stdlib/types/ndarray/base/max-view-buffer-index' ) );

/**
* @name minViewBufferIndex
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/ndarray/base/min-view-buffer-index}
*/
setReadOnly( ns, 'minViewBufferIndex', require( '@stdlib/types/ndarray/base/min-view-buffer-index' ) );

/**
* @name numel
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/ndarray/base/numel}
*/
setReadOnly( ns, 'numel', require( '@stdlib/types/ndarray/base/numel' ) );

/**
* @name shape2strides
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/ndarray/base/shape2strides}
*/
setReadOnly( ns, 'shape2strides', require( '@stdlib/types/ndarray/base/shape2strides' ) );

/**
* @name strides2offset
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/ndarray/base/strides2offset}
*/
setReadOnly( ns, 'strides2offset', require( '@stdlib/types/ndarray/base/strides2offset' ) );

/**
* @name sub2ind
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/ndarray/base/sub2ind}
*/
setReadOnly( ns, 'sub2ind', require( '@stdlib/types/ndarray/base/sub2ind' ) );

/**
* @name ndarray2array
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/ndarray/base/to-array}
*/
setReadOnly( ns, 'ndarray2array', require( '@stdlib/types/ndarray/base/ndarray2array' ) );

/**
* @name vind2bind
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/ndarray/base/vind2bind}
*/
setReadOnly( ns, 'vind2bind', require( '@stdlib/types/ndarray/base/vind2bind' ) );

// EXPORTS //

module.exports = ns;
<commit_msg>Update namespace<commit_after>'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};

/**
* @name bind2vind
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/ndarray/base/bind2vind}
*/
setReadOnly( ns, 'bind2vind', require( '@stdlib/types/ndarray/base/bind2vind' ) );

/**
* @name ind2sub
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/ndarray/base/ind2sub}
*/
setReadOnly( ns, 'ind2sub', require( '@stdlib/types/ndarray/base/ind2sub' ) );

/**
* @name isColumnMajor
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/ndarray/base/is-column-major}
*/
setReadOnly( ns, 'isColumnMajor', require( '@stdlib/types/ndarray/base/is-column-major' ) );

/**
* @name isRowMajor
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/ndarray/base/is-row-major}
*/
setReadOnly( ns, 'isRowMajor', require( '@stdlib/types/ndarray/base/is-row-major' ) );

/**
* @name iterationOrder
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/ndarray/base/iteration-order}
*/
setReadOnly( ns, 'iterationOrder', require( '@stdlib/types/ndarray/base/iteration-order' ) );

/**
* @name maxViewBufferIndex
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/ndarray/base/max-view-buffer-index}
*/
setReadOnly( ns, 'maxViewBufferIndex', require( '@stdlib/types/ndarray/base/max-view-buffer-index' ) );

/**
* @name minViewBufferIndex
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/ndarray/base/min-view-buffer-index}
*/
setReadOnly( ns, 'minViewBufferIndex', require( '@stdlib/types/ndarray/base/min-view-buffer-index' ) );

/**
* @name minmaxViewBufferIndex
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/ndarray/base/minmax-view-buffer-index}
*/
setReadOnly( ns, 'minmaxViewBufferIndex', require( '@stdlib/types/ndarray/base/minmax-view-buffer-index' ) );

/**
* @name numel
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/ndarray/base/numel}
*/
setReadOnly( ns, 'numel', require( '@stdlib/types/ndarray/base/numel' ) );

/**
* @name shape2strides
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/ndarray/base/shape2strides}
*/
setReadOnly( ns, 'shape2strides', require( '@stdlib/types/ndarray/base/shape2strides' ) );

/**
* @name strides2offset
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/ndarray/base/strides2offset}
*/
setReadOnly( ns, 'strides2offset', require( '@stdlib/types/ndarray/base/strides2offset' ) );

/**
* @name sub2ind
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/ndarray/base/sub2ind}
*/
setReadOnly( ns, 'sub2ind', require( '@stdlib/types/ndarray/base/sub2ind' ) );

/**
* @name ndarray2array
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/ndarray/base/to-array}
*/
setReadOnly( ns, 'ndarray2array', require( '@stdlib/types/ndarray/base/ndarray2array' ) );

/**
* @name vind2bind
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/ndarray/base/vind2bind}
*/
setReadOnly( ns, 'vind2bind', require( '@stdlib/types/ndarray/base/vind2bind' ) );

// EXPORTS //

module.exports = ns;
<|endoftext|>


<commit_before>function init(shipit) {
    require('@tryghost/deploy')(shipit);

    shipit.initConfig({
        default: {
            yarn: true,
            workspace: './',
            deployTo: '/opt/gscan/',
            ignores: ['.git', '.gitkeep', '.gitignore', '.eslintrc.js', '.eslintcache', 'node_modules', '/test', '/app/public/.eslintrc.js']
        },
        staging: {
            servers: process.env.STG_USER + '@' + process.env.STG_SERVER,
            sharedLinks: [{
                name: 'node_modules',
                type: 'directory'
            }, {
                name: 'uploads',
                type: 'directory'
            }, {
                name: 'config.staging.json',
                type: 'file'
            }]
        },
        production: {
            servers: process.env.PRD_USER + '@' + process.env.PRD_SERVER,
            sharedLinks: [{
                name: 'node_modules',
                type: 'directory'
            }, {
                name: 'uploads',
                type: 'directory'
            }, {
                name: 'config.production.json',
                type: 'file'
            }]
        }
    });
}
module.exports = init;
<commit_msg>Update shipitfile.js for server array<commit_after>function parseServerList(env) {
    var user = env === 'staging' ? process.env.STG_USER : process.env.PRD_USER;
    var server = env === 'staging' ? process.env.STG_SERVER : process.env.PRD_SERVER;
    try {
        var srvConfig = JSON.parse(server);
        srvConfig = srvConfig.map(function (item) {
            return user + '@' + item;
        });
        return srvConfig;
    } catch (e) {
        return user + '@' + server;
    }
}

function init(shipit) {
    require('@tryghost/deploy')(shipit);

    var srv = parseServerList(shipit.environment);
    var configFile = 'config.' + shipit.environment + '.json';

    shipit.initConfig({
        default: {
            yarn: true,
            workspace: './',
            deployTo: '/opt/gscan/',
            ignores: ['.git', '.gitkeep', '.gitignore', '.eslintrc.js', '.eslintcache', 'node_modules', '/test', '/app/public/.eslintrc.js'],
            sharedLinks: [{
                name: 'node_modules',
                type: 'directory'
            },  {
                name: 'uploads',
                type: 'directory'
            },  {
                name: configFile,
                type: 'file'
            }],
            yarn: true
        },
        staging: {
            servers: srv
        },
        production: {
            servers: srv
        }
    });
}
module.exports = init;
<|endoftext|>


<commit_before>'use strict';

var tableName = "Species";

module.exports = {
  up: function (queryInterface, Sequelize) {
    return queryInterface.removeIndex(tableName, 'species_type_label_bg')
      .then(function () {
        return queryInterface.removeIndex(tableName, 'species_type_label_en')
          .then(function () {
            return queryInterface.addIndex(tableName, ['labelBg'])
              .then(function () {
                return queryInterface.addIndex(tableName, ['labelEn']);
              })
          })
      });
  },

  down: function (queryInterface, Sequelize) {
    return queryInterface.removeIndex(tableName, ['labelBg'])
      .then(function () {
        return queryInterface.removeIndex(tableName, ['labelEn'])
          .then(function () {
            return queryInterface.addIndex(tableName, ['labelBg'],
              { indexName: 'species_type_label_bg', indicesType: 'UNIQUE' })
          })
          .then(function () {
            return queryInterface.addIndex(tableName, ['labelEn'],
              { indexName: 'species_type_label_en', indicesType: 'UNIQUE' });
          });
      });
  }
};
<commit_msg>fix migration for species unique indexes<commit_after>'use strict';

var tableName = "Species";

module.exports = {
  up: function (queryInterface, Sequelize) {
    return queryInterface.removeIndex(tableName, "species_type_label_bg")
      .then(function () {
        return queryInterface.addIndex(tableName, {
          "unique": false,
          "fields": ["type", "labelBg"]
        });
      })
      .then(function () {
        return queryInterface.removeIndex(tableName, "species_type_label_en");
      })
      .then(function () {
        return queryInterface.addIndex(tableName, {
          "unique": false,
          "fields": ["type", "labelEn"]
        });
      })
  },

  down: function (queryInterface, Sequelize) {
    return queryInterface.removeIndex(tableName, "species_type_label_bg")
      .then(function () {
        return queryInterface.addIndex(tableName, {
          "unique": true,
          "fields": ["type", "labelBg"]
        });
      })
      .then(function () {
        return queryInterface.removeIndex(tableName, "species_type_label_en");
      })
      .then(function () {
        return queryInterface.addIndex(tableName, {
          "unique": true,
          "fields": ["type", "labelEn"]
        });
      })
  }
};
<|endoftext|>


<commit_before>export const sampleRows = [
  ['testing-posts', 'Testing Posts', 'test', 'test, post', 'published'],
  ['testing-posts2', 'Testing Posts 2', 'test2', 'test2, post', 'published']
];
<commit_msg>add document sample to components' fixtures<commit_after>export const sampleRows = [
  ['testing-posts', 'Testing Posts', 'test', 'test, post', 'published'],
  ['testing-posts2', 'Testing Posts 2', 'test2', 'test2, post', 'published']
];

export const doc = {
  "id": "the-revenant",
  "collection_name": "movies",
  "body": "A frontiersman on a fur trading expedition in the 1820s fights.",
  "meta": {
    "layout": "default",
    "title": "The Revenant",
    "path": 'the-revenant.md'
  }
};
<|endoftext|>


<commit_before>'use strict';

var EventModel = require('../models/event-model');

module.exports = function(app) {
  var api = '/api/0_0_1/data';

  // CREATE
  app.post(api, function(req, res) {
    var newEvent = new EventModel(req.body);
    newEvent.save(function(err, dbResponse) {
      if (err) return res.status(500).json(err);
      return res.status(200).json(dbResponse);
    });
  });

  //READ
  app.get(api, function(req, res) {
    EventModel.find({}, function(err, dbResponse) {
      if (err) return res.status(500).json(err);
      return res.status(200).json(dbResponse);
    });
  });

  // UPDATE
  app.put(api + '/:id', function(req, res) {
    var data = req.body;
    delete data._id;
    EventModel.findOneAndUpdate({ '_id': req.params.id }, data, function(err, resNote) {
      if (err) {
        return res.status(500).json(err);
      }
      return res.status(202).json(resNote);
    });
  });

  // DELETE
  app.delete(api + '/:id', function(req, res) {
    EventModel.remove({ '_id': req.params.id }, function(err) {
      if (err) {
        return res.status(500).json(err);
      }
      return res.status(200).json({
        'message': 'deleted'
      });
    });
  });

};<commit_msg>Protect the GET route, and find only those sites that correspond to the user<commit_after>'use strict';

var SessionModel = require('../models/session-model');

module.exports = function(app, jwtAuth) {

  var api = '/api/0_0_1/data';

  // CREATE
  app.post(api, function(req, res) {
    var newEvent = new SessionModel(req.body);
    newEvent.save(function(err, dbResponse) {
      if (err) return res.status(500).json(err);
      return res.status(200).json(dbResponse);
    });
  });

  //READ
  app.get(api, jwtAuth, function(req, res) {
    SessionModel.find({ url: req.user.url }, function(err, dbResponse) {
      if (err) return res.status(500).json(err);
      return res.status(200).json(dbResponse);
    });
  });

  // UPDATE
  app.put(api + '/:id', function(req, res) {
    var data = req.body;
    delete data._id;
    SessionModel.findOneAndUpdate({ '_id': req.params.id }, data, function(err, dbResponse) {
      if (err) {
        return res.status(500).json(err);
      }
      return res.status(202).json(dbResponse);
    });
  });

  // DELETE
  app.delete(api + '/:id', function(req, res) {
    SessionModel.remove({ '_id': req.params.id }, function(err) {
      if (err) {
        return res.status(500).json(err);
      }
      return res.status(200).json({
        'message': 'deleted'
      });
    });
  });

};<|endoftext|>


<commit_before>var d = new Date();

document.getElementById("id_logic_level_version").innerHTML="Business level version" + d.getFullYear() + "." + d.getMonth() + "." + d.getDate() + ".0";

var constraints = {audio:false, video:{facingMode:"environment"}};
navigator.mediaDevices.getUserMedia(constraints).then(on_success).catch(on_error);

var video = document.getElementById("id_video");

function on_success(stream)
{
    video.srcObject = stream;
}

function on_error(error)
{
    alert("Error");
}<commit_msg>take picture<commit_after>var d = new Date();

document.getElementById("id_logic_level_version").innerHTML="Business level version" + d.getFullYear() + "." + d.getMonth() + "." + d.getDate() + ".0";

var constraints = {audio:false, video:{facingMode:"environment"}};
navigator.mediaDevices.getUserMedia(constraints).then(on_success).catch(on_error);

var video = document.getElementById("id_video");
video.addEventListener("touchstart", snap);

function on_success(stream)
{
    video.srcObject = stream;
}

function on_error(error)
{
    alert("Error");
}

function snap()
{
    var canvas = document.getElementById("id_canvas");
    var context = canvas.getContext("2D");
    context.drawImage(video, 0, 0, 640, 480);

}
<|endoftext|>


<commit_before>/**
 * Created by Kun on 6/28/2015.
 */

var express = require("express");
var Q = require('q');
var router = express.Router();

router.get('/redis/SetState/:cookie/:username/:page', function(req, res) {
    client.hset(req.params.cookie,"Username",req.params.username,"Page" ,reg.params.page,function (error, result) {
        if (error !== null) {
            console.log("error: " + error);
            res.send("error: " + error);
        }
        else {
            console.log(res);
            res.send(res);
        }
    });
});

<commit_msg>IM-87 session state: key=cookie, value=hashset(Username:username,Page:page)<commit_after>/**
 * Created by Kun on 6/28/2015.
 */

var express = require("express");
var Q = require('q');
var router = express.Router();

router.get('/redis/SetState/:cookie/:username/:page', function(req, res) {
    client.hmset(req.params.cookie,"Username",req.params.username,"Page" ,reg.params.page,function (error, result) {
        if (error !== null) {
            console.log("error: " + error);
            res.send("error: " + error);
        }
        else {
            console.log(res);
            res.send(res);
        }
    });
});

<|endoftext|>


<commit_before>var inherit;
(function (global, exports) {

    /**
     *
     * @param {Object} classDefinition The definition for the prototype methods
     * @param {Function} [baseClass] The prototype to inherit from
     *
     * @return {Function} returns a constructor function describing the class
     */
    inherit = function (classDefinition, baseClass) {
        baseClass = baseClass || Object;

        var newClass = function () {
            if (this.ctor) {
                this.ctor.apply(this, arguments);
            }
        };

        if (baseClass.constructor == Function) {

            function Inheritance() {
            }

            Inheritance.prototype = baseClass.prototype;

            newClass.prototype = new Inheritance();
            newClass.prototype.constructor = classDefinition;
            newClass.prototype.base = baseClass.prototype;

        } else {
            newClass.prototype = baseClass;
            newClass.prototype.constructor = classDefinition;
            newClass.prototype.base = baseClass;
        }

        for (var publicMethod in classDefinition) {
            if (classDefinition.hasOwnProperty(publicMethod)) {
                var baseFunction = newClass.prototype[publicMethod];
                newClass.prototype[publicMethod] = classDefinition[publicMethod];
                newClass.prototype[publicMethod].baseImplementation = baseFunction;
            }
        }

        newClass.prototype.callBase = inherit.callBase;

        return newClass;

    };

    inherit.callBase = function () {
        var args = Array.prototype.slice.call(arguments);

        if (args.length == 0) {
            // use arguments from call
            args = Array.prototype.slice.call(arguments.callee.caller.arguments);
        }

        return arguments.callee.caller.baseImplementation.apply(this, args);
    };

    /**
     *
     * @param classDefinition The definition for the prototype methods
     *
     * @return {Function} returns a constructor function describing the class
     */
    Function.prototype.inherit = function (classDefinition) {
        return inherit(classDefinition, this);
    };

    Function.prototype.callBase = function () {
        var args = Array.prototype.slice.call(arguments);
        var that = args.shift();

        if (that && that.base) {
            var caller = arguments.callee.caller;

            if (this == caller) {
                return this.baseImplementation.apply(that, args);
            } else {
                return this.apply(that, args);
            }
        } else {
            throw "base not definied";
        }
    };

    /**
     * @property {Function} base class
     */
    inherit.Base = inherit({
        ctor: function () {
        }
    });

    exports.inherit = inherit;

})(this, typeof exports === "undefined" ? this : exports);<commit_msg>implementes baseImplementation only for functions<commit_after>var inherit;

(function (global, exports) {

    /**
     *
     * @param {Object} classDefinition The definition for the prototype methods
     * @param {Function} [baseClass] The prototype to inherit from
     *
     * @return {Function} returns a constructor function describing the class
     */
    inherit = function (classDefinition, baseClass) {
        baseClass = baseClass || Object;

        var newClass = function () {
            if (this.ctor) {
                this.ctor.apply(this, arguments);
            }
        };

        if (baseClass.constructor == Function) {

            function Inheritance() {
            }

            Inheritance.prototype = baseClass.prototype;

            newClass.prototype = new Inheritance();
            newClass.prototype.constructor = classDefinition;
            newClass.prototype.base = baseClass.prototype;

        } else {
            newClass.prototype = baseClass;
            newClass.prototype.constructor = classDefinition;
            newClass.prototype.base = baseClass;
        }

        for (var publicMethod in classDefinition) {
            if (classDefinition.hasOwnProperty(publicMethod)) {
                var baseFunction = newClass.prototype[publicMethod];
                newClass.prototype[publicMethod] = classDefinition[publicMethod];

                if (baseFunction instanceof Function) {
                    newClass.prototype[publicMethod].baseImplementation = baseFunction;
                }
            }
        }

        newClass.prototype.callBase = inherit.callBase;

        return newClass;

    };

    inherit.callBase = function () {
        // get arguments
        var args = Array.prototype.slice.call(arguments);

        if (args.length == 0) {
            // use arguments from call
            args = Array.prototype.slice.call(arguments.callee.caller.arguments);
        }

        return arguments.callee.caller.baseImplementation.apply(this, args);
    };

    /**
     *
     * @param classDefinition The definition for the prototype methods
     *
     * @return {Function} returns a constructor function describing the class
     */
    Function.prototype.inherit = function (classDefinition) {
        return inherit(classDefinition, this);
    };

    Function.prototype.callBase = function () {
        var args = Array.prototype.slice.call(arguments);
        var that = args.shift();

        if (that && that.base) {
            var caller = arguments.callee.caller;

            if (this == caller) {
                return this.baseImplementation.apply(that, args);
            } else {
                return this.apply(that, args);
            }
        } else {
            throw "base not definied";
        }
    };

    /**
     * @property {Function} base class
     */
    inherit.Base = inherit({
        ctor: function () {
        }
    });

    exports.inherit = inherit;

})(this, typeof exports === "undefined" ? this : exports);

<|endoftext|>


<commit_before>var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('records.db');
var check;
var fs = require('fs');
var obj = JSON.parse(fs.readFileSync('MockData', 'utf8'));

// Write the callback function
function handleFile(err, data) {
  if (err) throw err
    obj = JSON.parse(data)

  console.log(obj);

    // You can now play with your datas
}

// db.serialize(function() {

//   db.run("CREATE TABLE if not exists lorem (info TEXT)");
//   var stmt = db.prepare("INSERT INTO lorem VALUES (?)");
//   for (var i = 0; i < 10; i++) {
//       stmt.run("Ipsum " + i);
//   }
//   stmt.finalize();

//   db.each("SELECT rowid AS id, info FROM lorem", function(err, row) {
//       console.log(row.id + ": " + row.info);
//   });

// });

// db.all("SELECT * FROM lorem", function(err, rows){
// 	console.log(rows, "HIIII");
// });

// db.close();

//Perform SELECT Operation
//db.all("SELECT * from blah blah blah where this="+that,function(err,rows){
//rows contain values while errors, well you can figure out.
//});

//Perform INSERT operation.
//db.run("INSERT into table_name(col1,col2,col3) VALUES (val1,val2,val3)");

//Perform DELETE operation
//db.run("DELETE * from table_name where condition");

//Perform UPDATE operation
//db.run("UPDATE table_name where condition");<commit_msg>--adding file type<commit_after>var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('records.db');
var check;
var fs = require('fs');
var obj = JSON.parse(fs.readFileSync('MockData.json', 'utf8'));

// Write the callback function
function handleFile(err, data) {
  if (err) throw err
    obj = JSON.parse(data)

  console.log(obj);

    // You can now play with your datas
}

// db.serialize(function() {

//   db.run("CREATE TABLE if not exists lorem (info TEXT)");
//   var stmt = db.prepare("INSERT INTO lorem VALUES (?)");
//   for (var i = 0; i < 10; i++) {
//       stmt.run("Ipsum " + i);
//   }
//   stmt.finalize();

//   db.each("SELECT rowid AS id, info FROM lorem", function(err, row) {
//       console.log(row.id + ": " + row.info);
//   });

// });

// db.all("SELECT * FROM lorem", function(err, rows){
// 	console.log(rows, "HIIII");
// });

// db.close();

//Perform SELECT Operation
//db.all("SELECT * from blah blah blah where this="+that,function(err,rows){
//rows contain values while errors, well you can figure out.
//});

//Perform INSERT operation.
//db.run("INSERT into table_name(col1,col2,col3) VALUES (val1,val2,val3)");

//Perform DELETE operation
//db.run("DELETE * from table_name where condition");

//Perform UPDATE operation
//db.run("UPDATE table_name where condition");<|endoftext|>


<commit_before>const express = require('express');
const router = express.Router();
const passport = require('passport');
const mongoose = require('mongoose');
const jwt = require('../../helpers/jwt');
const formatError = require('../../helpers/errors.js').formatError;

/*
    api routes

    authenticate via basic auth against /api/authenticate and receive a JWT

    afterwards, call endpoints with JWT in Header ("Authorization" : "Bearer <token>")
    Also see supplied postman collection in /stuff/ for how to construct the Authorization Header
*/

router.post('/', passport.authenticate('basic', { session: false }), function(req, res, next) {
  // console.log(req.body);
  jwt.issueToken(req.user)
  .then(token => {
    res.status(200).json({code: 200, status: 'success', data: {token: token}});
  })
  .catch(err => {
    console.log(`auth error: ${req.body.username}`);
    res.status(500).json({code: 500, status: 'error', errors: [{err}]});
  });
});

router.post('/email', function(req, res, next) {
  // console.log(req.body);
  const User = mongoose.model('User');
  User.findByEmailPassword(req.body.email, req.body.password, (err, user) => {

    // TODO: implement.

    jwt.issueToken(user)
  .then(token => {
    res.status(200).json({code: 200, status: 'success', data: {token: token}});
  })
  .catch(err => {
    console.log(`auth error via email/pw: ${JSON.stringify(err)}`);
    res.status(500).json({code: 500, status: 'error', errors: [{err}]});
  });

  });

});

module.exports = router;
<commit_msg>be more verbose on authentication via email<commit_after>const express = require('express');
const router = express.Router();
const passport = require('passport');
const mongoose = require('mongoose');
const jwt = require('../../helpers/jwt');
const formatError = require('../../helpers/errors.js').formatError;

/*
    api routes

    authenticate via basic auth against /api/authenticate and receive a JWT

    afterwards, call endpoints with JWT in Header ("Authorization" : "Bearer <token>")
    Also see supplied postman collection in /stuff/ for how to construct the Authorization Header
*/

router.post('/', passport.authenticate('basic', { session: false }), function(req, res, next) {
  // console.log(req.body);
  jwt.issueToken(req.user)
  .then(token => {
    res.status(200).json({code: 200, status: 'success', data: {token: token}});
  })
  .catch(err => {
    console.log(`auth error: ${req.body.username}`);
    res.status(500).json({code: 500, status: 'error', errors: [{err}]});
  });
});

router.post('/email', function(req, res, next) {
  // console.log(req.body);
  const User = mongoose.model('User');
  User.findByEmailPassword(req.body.email, req.body.password, (err, user) => {
    if (!user) {res.status(500).json({ code: 500, status: 'error', errors: [{ error: 'user not found.' }] });
    } else {
      jwt.issueToken(user)
      .then(token => {
        res.status(200).json({code: 200, status: 'success', data: {token: token}});
      })
      .catch(err => {
        console.log(`auth error via email/pw: ${JSON.stringify(err)}`);
        res.status(500).json({code: 500, status: 'error', errors: [{err}]});
      });
    }
  });

});

module.exports = router;
<|endoftext|>


<commit_before>'use strict';

var async = require('async');

var logger = require.main.logger;
var config = require.main.config;

var Router = require('express').Router;
var router = new Router();

var ensureAuthenticated = require('../api').ensureAuthenticated;
var getRequestHeaders = require('../api').getRequestHeaders;
var traverson = require('traverson');

module.exports = router;

router.get('', ensureAuthenticated, getRepositories);

router.get('/:repositoryId/report',
  ensureAuthenticated,
  extractRepository,
  generateReport);

function getRepositories(req, res) {
  logger.trace('getRepositories');

  loadRepositories(req, function(err, repositories) {
    if (err) {
      return res.status(500).json({
        message: 'error requesting repository list'
      });
    }
    return res.json(repositories);
  });
}

function generateReport(req, res) {
  logger.trace('generateReport');

  var user = req.user;
  var repo = req.repository;
  var from = req.query.from;

  loadRepositoryIssues(user, repo, from, function(error, issues) {
    if (error) {
      return res.status(400).json(error);
    }
    return res.json(issues);
  });
}

function loadRepositories(req, fetchedCb) {
  logger.trace('loadRepositories');

  var user = req.user;

  if (user.repositories && user.repositories.length > 0) {
    return fetchedCb(null, user.repositories);
  }

  traverson.from('https://api.github.com')
  .json()
  .follow('current_user_repositories_url')
  .withRequestOptions({ headers: getRequestHeaders(user) })
  .getResource(function(error, resource) {
    if (error) {
      return fetchedCb(error);
    }

    var repositories = [];

    for (var i = 0; i < resource.length; i++) {
      var repo = {
        id: resource[i].id,
        name: resource[i].name,
        fullName: resource[i].full_name,
        description: resource[i].description,
        createdAt: resource[i].created_at,
        updatedAt: resource[i].updated_at,
        issuesUrl: resource[i].issues_url,
        reportUrl: config.server.baseUrl + req.originalUrl + '/' + resource[i].id + '/report{?from}'
      };
      repositories.push(repo);
    }

    user.repositories = repositories;
    return fetchedCb(null, repositories);
  });
}

function loadRepositoryIssues(user, repository, from, issuesLoadedCb) {
  loadFullPaginatedResource(user, repository.issuesUrl, { state: 'all', since: from }, function(error, issues) {
    if (error) {
      return issuesLoadedCb(error);
    }

    logger.debug('loadFullPaginatedResource returned ' + issues.length + ' issues');

    var relevant = { };

    async.each(issues, function(issue, doneCb) {
      // skip pull-requests
      if ('pull_request' in issue) {
        return doneCb();
      }

      loadInvolvedUsers(user, issue.events_url, function(err, involvedUsers) {
        logger.trace('loadInvolvedUsers for ' + issue.title + ' returned');

        if (err) {
          return doneCb(err);
        }

        var relevantParts = {
          title: issue.title,
          description: issue.body,
          labels: issue.labels,
          state: issue.state,
          assignee: (issue.assignee && {
            id: issue.assignee.id,
            login: issue.assignee.login
          }) || 'unassigned',
          createdAt: issue.created_at,
          lastUpdate: issue.updated_at,
          closedAt: issue.closed_at,
          involvedUsers: []
        };

        // remove the assignee from the involved users list
        for (var i = 0; i < involvedUsers.length; i++) {
          if (involvedUsers[i].id === relevantParts.assignee.id) {
            relevantParts.involvedUsers = involvedUsers.splice(i, 1);
            break;
          }
        }

        var milestone = (issue.milestone && issue.milestone.title) || 'unassigned';

        if (!(milestone in relevant)) {
          relevant[milestone] = [];
        }

        relevant[milestone].push(relevantParts);

        logger.trace('exiting async.each for ' + issue.title);
        return doneCb();
      });
    }, function(err) {
      logger.trace('loadRepositoryIssues exit');
      issuesLoadedCb(err, relevant);
    });
  });
}

function loadInvolvedUsers(user, issueEventsUrl, usersFetchedCb) {
  loadFullPaginatedResource(user, issueEventsUrl, {}, function(error, events) {
    if (error) {
      return usersFetchedCb(error);
    }

    var mentionedUsers = [];
    for (var i = 0; i < events.length; i++) {
      var update = events[i];
      if (update.event === 'mentioned' && update.actor) {
        var mentioned = {
          id: update.actor.id,
          name: update.actor.login
        };
        var alreadyIn = false;
        for (var j = 0; j < mentionedUsers.length; j++) {
          if (mentionedUsers[j].id === mentioned.id) {
            alreadyIn = true;
            break;
          }
        }
        if (!alreadyIn) {
          mentionedUsers.push(mentioned);
        }
      }
    }
    usersFetchedCb(null, mentionedUsers);
  });
}

function loadFullPaginatedResource(user, link, queryOptions, fetchedCb, previousItems) {
  logger.trace('loadFullPaginatedResource', link, queryOptions);

  var items = previousItems || [];

  traverson.from(link)
  .withRequestOptions({
    headers: getRequestHeaders(user),
    qs: queryOptions
  })
  .get(function(error, response) {
    if (error) {
      return fetchedCb(error);
    }
    items = items.concat(JSON.parse(response.body));

    var links = parseLinkHeader(response.headers['link']);

    if (!links || !links.last || link === links.last || !links.next || links.next === '') {
      return fetchedCb(null, items);
    } else {
      // there are more pages to fetch!
      return loadFullPaginatedResource(user, links.next, queryOptions, fetchedCb, items);
    }
  });
}

var linkHeaderRegex = /^<(http[s]?:\/\/[a-z0-9\.]+\/.*?)>; rel="([a-z0-9]+)"$/i;

function parseLinkHeader(linkHeader) {
  logger.trace('parseLinkHeader', linkHeader);

  if (!linkHeader) {
    return null;
  }

  var links = {};

  if (linkHeader && typeof linkHeader === 'string') {
    var linkSegments = linkHeader.split(', ');

    for (var i = 0; i < linkSegments.length; i++) {
      var match = linkHeaderRegex.exec(linkSegments[i]);
      if (match) {
        links[match[2]] = match[1];
      }
    }
  }

  return links;
}

// middleware
function extractRepository(req, res, next) {
  logger.trace('extractRepository');

  if (!req.params.repositoryId) {
    return next();
  }

  var repositoryId = parseInt(req.params.repositoryId, 10);
  if (isNaN(repositoryId)) {
    return next({
      message: 'malformed repositoryId'
    });
  }

  if (!req.user.repositories) {
    return loadRepositories(req, function(error) {
      if (error) {
        return next(error);
      }
      return extractRepository(req, res, next);
    });
  }
  var repos = req.user.repositories;
  for (var i = 0; i < repos.length; i++) {
    if (repos[i].id === repositoryId) {
      req.repository = repos[i];
      return next();
    }
  }
  return next({
    message: 'invalid repositoryId'
  });
}
<commit_msg>Added issueId and number to the issue objects returned by the report<commit_after>'use strict';

var async = require('async');

var logger = require.main.logger;
var config = require.main.config;

var Router = require('express').Router;
var router = new Router();

var ensureAuthenticated = require('../api').ensureAuthenticated;
var getRequestHeaders = require('../api').getRequestHeaders;
var traverson = require('traverson');

module.exports = router;

router.get('', ensureAuthenticated, getRepositories);

router.get('/:repositoryId/report',
  ensureAuthenticated,
  extractRepository,
  generateReport);

function getRepositories(req, res) {
  logger.trace('getRepositories');

  loadRepositories(req, function(err, repositories) {
    if (err) {
      return res.status(500).json({
        message: 'error requesting repository list'
      });
    }
    return res.json(repositories);
  });
}

function generateReport(req, res) {
  logger.trace('generateReport');

  var user = req.user;
  var repo = req.repository;
  var from = req.query.from;

  loadRepositoryIssues(user, repo, from, function(error, issues) {
    if (error) {
      return res.status(400).json(error);
    }
    return res.json(issues);
  });
}

function loadRepositories(req, fetchedCb) {
  logger.trace('loadRepositories');

  var user = req.user;

  if (user.repositories && user.repositories.length > 0) {
    return fetchedCb(null, user.repositories);
  }

  traverson.from('https://api.github.com')
  .json()
  .follow('current_user_repositories_url')
  .withRequestOptions({ headers: getRequestHeaders(user) })
  .getResource(function(error, resource) {
    if (error) {
      return fetchedCb(error);
    }

    var repositories = [];

    for (var i = 0; i < resource.length; i++) {
      var repo = {
        id: resource[i].id,
        name: resource[i].name,
        fullName: resource[i].full_name,
        description: resource[i].description,
        createdAt: resource[i].created_at,
        updatedAt: resource[i].updated_at,
        issuesUrl: resource[i].issues_url,
        reportUrl: config.server.baseUrl + req.originalUrl + '/' + resource[i].id + '/report{?from}'
      };
      repositories.push(repo);
    }

    user.repositories = repositories;
    return fetchedCb(null, repositories);
  });
}

function loadRepositoryIssues(user, repository, from, issuesLoadedCb) {
  loadFullPaginatedResource(user, repository.issuesUrl, { state: 'all', since: from }, function(error, issues) {
    if (error) {
      return issuesLoadedCb(error);
    }

    logger.debug('loadFullPaginatedResource returned ' + issues.length + ' issues');

    var relevant = { };

    async.each(issues, function(issue, doneCb) {
      // skip pull-requests
      if ('pull_request' in issue) {
        return doneCb();
      }

      loadInvolvedUsers(user, issue.events_url, function(err, involvedUsers) {
        logger.trace('loadInvolvedUsers for ' + issue.title + ' returned');

        if (err) {
          return doneCb(err);
        }

        var relevantParts = {
          title: issue.title,
          id: issue.id,
          number: issue.number,
          description: issue.body,
          labels: issue.labels,
          state: issue.state,
          assignee: (issue.assignee && {
            id: issue.assignee.id,
            login: issue.assignee.login
          }) || 'unassigned',
          createdAt: issue.created_at,
          lastUpdate: issue.updated_at,
          closedAt: issue.closed_at,
          involvedUsers: []
        };

        // remove the assignee from the involved users list
        for (var i = 0; i < involvedUsers.length; i++) {
          if (involvedUsers[i].id === relevantParts.assignee.id) {
            relevantParts.involvedUsers = involvedUsers.splice(i, 1);
            break;
          }
        }

        var milestone = (issue.milestone && issue.milestone.title) || 'unassigned';

        if (!(milestone in relevant)) {
          relevant[milestone] = [];
        }

        relevant[milestone].push(relevantParts);

        logger.trace('exiting async.each for ' + issue.title);
        return doneCb();
      });
    }, function(err) {
      logger.trace('loadRepositoryIssues exit');
      issuesLoadedCb(err, relevant);
    });
  });
}

function loadInvolvedUsers(user, issueEventsUrl, usersFetchedCb) {
  loadFullPaginatedResource(user, issueEventsUrl, {}, function(error, events) {
    if (error) {
      return usersFetchedCb(error);
    }

    var mentionedUsers = [];
    for (var i = 0; i < events.length; i++) {
      var update = events[i];
      if (update.event === 'mentioned' && update.actor) {
        var mentioned = {
          id: update.actor.id,
          name: update.actor.login
        };
        var alreadyIn = false;
        for (var j = 0; j < mentionedUsers.length; j++) {
          if (mentionedUsers[j].id === mentioned.id) {
            alreadyIn = true;
            break;
          }
        }
        if (!alreadyIn) {
          mentionedUsers.push(mentioned);
        }
      }
    }
    usersFetchedCb(null, mentionedUsers);
  });
}

function loadFullPaginatedResource(user, link, queryOptions, fetchedCb, previousItems) {
  logger.trace('loadFullPaginatedResource', link, queryOptions);

  var items = previousItems || [];

  traverson.from(link)
  .withRequestOptions({
    headers: getRequestHeaders(user),
    qs: queryOptions
  })
  .get(function(error, response) {
    if (error) {
      return fetchedCb(error);
    }
    items = items.concat(JSON.parse(response.body));

    var links = parseLinkHeader(response.headers['link']);

    if (!links || !links.last || link === links.last || !links.next || links.next === '') {
      return fetchedCb(null, items);
    } else {
      // there are more pages to fetch!
      return loadFullPaginatedResource(user, links.next, queryOptions, fetchedCb, items);
    }
  });
}

var linkHeaderRegex = /^<(http[s]?:\/\/[a-z0-9\.]+\/.*?)>; rel="([a-z0-9]+)"$/i;

function parseLinkHeader(linkHeader) {
  logger.trace('parseLinkHeader', linkHeader);

  if (!linkHeader) {
    return null;
  }

  var links = {};

  if (linkHeader && typeof linkHeader === 'string') {
    var linkSegments = linkHeader.split(', ');

    for (var i = 0; i < linkSegments.length; i++) {
      var match = linkHeaderRegex.exec(linkSegments[i]);
      if (match) {
        links[match[2]] = match[1];
      }
    }
  }

  return links;
}

// middleware
function extractRepository(req, res, next) {
  logger.trace('extractRepository');

  if (!req.params.repositoryId) {
    return next();
  }

  var repositoryId = parseInt(req.params.repositoryId, 10);
  if (isNaN(repositoryId)) {
    return next({
      message: 'malformed repositoryId'
    });
  }

  if (!req.user.repositories) {
    return loadRepositories(req, function(error) {
      if (error) {
        return next(error);
      }
      return extractRepository(req, res, next);
    });
  }
  var repos = req.user.repositories;
  for (var i = 0; i < repos.length; i++) {
    if (repos[i].id === repositoryId) {
      req.repository = repos[i];
      return next();
    }
  }
  return next({
    message: 'invalid repositoryId'
  });
}
<|endoftext|>


<commit_before>// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// @ts-nocheck
// TODO(crbug.com/1011811): Enable TypeScript compiler checks

import * as Common from '../common/common.js';
import * as Components from '../components/components.js';
import * as Host from '../host/host.js';
import * as SDK from '../sdk/sdk.js';  // eslint-disable-line no-unused-vars
import * as UI from '../ui/ui.js';

export class SignedExchangeInfoView extends UI.Widget.VBox {
  /**
   * @param {!SDK.NetworkRequest.NetworkRequest} request
   */
  constructor(request) {
    super();
    const signedExchangeInfo = request.signedExchangeInfo();
    console.assert(signedExchangeInfo);

    this.registerRequiredCSS('network/signedExchangeInfoView.css');
    this.element.classList.add('signed-exchange-info-view');

    const root = new UI.TreeOutline.TreeOutlineInShadow();
    root.registerRequiredCSS('network/signedExchangeInfoTree.css');
    root.element.classList.add('signed-exchange-info-tree');
    root.setFocusable(false);
    root.makeDense();
    root.expandTreeElementsWhenArrowing = true;
    this.element.appendChild(root.element);

    /** @type {!Map<number|undefined, !Set<string>>} */
    const errorFieldSetMap = new Map();

    if (signedExchangeInfo.errors && signedExchangeInfo.errors.length) {
      const errorMessagesCategory = new Category(root, Common.UIString.UIString('Errors'));
      for (const error of signedExchangeInfo.errors) {
        const fragment = createDocumentFragment();
        fragment.appendChild(UI.Icon.Icon.create('smallicon-error', 'prompt-icon'));
        fragment.createChild('div', 'error-log').textContent = error.message;
        errorMessagesCategory.createLeaf(fragment);
        if (error.errorField) {
          let errorFieldSet = errorFieldSetMap.get(error.signatureIndex);
          if (!errorFieldSet) {
            errorFieldSet = new Set();
            errorFieldSetMap.set(error.signatureIndex, errorFieldSet);
          }
          errorFieldSet.add(error.errorField);
        }
      }
    }

    const titleElement = createDocumentFragment();
    titleElement.createChild('div', 'header-name').textContent = Common.UIString.UIString('Signed HTTP exchange');
    const learnMoreNode = UI.XLink.XLink.create(
        'https://github.com/WICG/webpackage', Common.UIString.UIString('Learn\xa0more'), 'header-toggle');
    titleElement.appendChild(learnMoreNode);
    const headerCategory = new Category(root, titleElement);
    if (signedExchangeInfo.header) {
      const header = signedExchangeInfo.header;
      const redirectDestination = request.redirectDestination();
      const requestURLElement = this._formatHeader(Common.UIString.UIString('Request URL'), header.requestUrl);
      if (redirectDestination) {
        const viewRequestLink = Components.Linkifier.Linkifier.linkifyRevealable(redirectDestination, 'View request');
        viewRequestLink.classList.add('header-toggle');
        requestURLElement.appendChild(viewRequestLink);
      }
      headerCategory.createLeaf(requestURLElement);
      headerCategory.createLeaf(
          this._formatHeader(Common.UIString.UIString('Response code'), header.responseCode + ''));
      headerCategory.createLeaf(
          this._formatHeader(Common.UIString.UIString('Header integrity hash'), header.headerIntegrity));

      this._responseHeadersItem =
          headerCategory.createLeaf(this._formatHeader(Common.UIString.UIString('Response headers'), ''));
      const responseHeaders = header.responseHeaders;
      for (const name in responseHeaders) {
        const headerTreeElement = new UI.TreeOutline.TreeElement(this._formatHeader(name, responseHeaders[name]));
        headerTreeElement.selectable = false;
        this._responseHeadersItem.appendChild(headerTreeElement);
      }
      this._responseHeadersItem.expand();

      for (let i = 0; i < header.signatures.length; ++i) {
        const errorFieldSet = errorFieldSetMap.get(i) || new Set();
        const signature = header.signatures[i];
        const signatureCategory = new Category(root, Common.UIString.UIString('Signature'));
        signatureCategory.createLeaf(this._formatHeader(Common.UIString.UIString('Label'), signature.label));
        signatureCategory.createLeaf(this._formatHeaderForHexData(
            Common.UIString.UIString('Signature'), signature.signature,
            errorFieldSet.has(Protocol.Network.SignedExchangeErrorField.SignatureSig)));

        if (signature.certUrl) {
          const certURLElement = this._formatHeader(
              Common.UIString.UIString('Certificate URL'), signature.certUrl,
              errorFieldSet.has(Protocol.Network.SignedExchangeErrorField.SignatureCertUrl));
          if (signature.certificates) {
            const viewCertLink = certURLElement.createChild('span', 'devtools-link header-toggle');
            viewCertLink.textContent = Common.UIString.UIString('View certificate');
            viewCertLink.addEventListener(
                'click',
                Host.InspectorFrontendHost.InspectorFrontendHostInstance.showCertificateViewer.bind(
                    null, signature.certificates),
                false);
          }
          signatureCategory.createLeaf(certURLElement);
        }
        signatureCategory.createLeaf(this._formatHeader(
            Common.UIString.UIString('Integrity'), signature.integrity,
            errorFieldSet.has(Protocol.Network.SignedExchangeErrorField.SignatureIntegrity)));
        if (signature.certSha256) {
          signatureCategory.createLeaf(this._formatHeaderForHexData(
              Common.UIString.UIString('Certificate SHA256'), signature.certSha256,
              errorFieldSet.has(Protocol.Network.SignedExchangeErrorField.SignatureCertSha256)));
        }
        signatureCategory.createLeaf(this._formatHeader(
            Common.UIString.UIString('Validity URL'), signature.validityUrl,
            errorFieldSet.has(Protocol.Network.SignedExchangeErrorField.SignatureValidityUrl)));
        signatureCategory.createLeaf().title = this._formatHeader(
            Common.UIString.UIString('Date'), new Date(1000 * signature.date).toUTCString(),
            errorFieldSet.has(Protocol.Network.SignedExchangeErrorField.SignatureTimestamps));
        signatureCategory.createLeaf().title = this._formatHeader(
            Common.UIString.UIString('Expires'), new Date(1000 * signature.expires).toUTCString(),
            errorFieldSet.has(Protocol.Network.SignedExchangeErrorField.SignatureTimestamps));
      }
    }
    if (signedExchangeInfo.securityDetails) {
      const securityDetails = signedExchangeInfo.securityDetails;
      const securityCategory = new Category(root, Common.UIString.UIString('Certificate'));
      securityCategory.createLeaf(this._formatHeader(Common.UIString.UIString('Subject'), securityDetails.subjectName));
      securityCategory.createLeaf(this._formatHeader(
          Common.UIString.UIString('Valid from'), new Date(1000 * securityDetails.validFrom).toUTCString()));
      securityCategory.createLeaf(this._formatHeader(
          Common.UIString.UIString('Valid until'), new Date(1000 * securityDetails.validTo).toUTCString()));
      securityCategory.createLeaf(this._formatHeader(Common.UIString.UIString('Issuer'), securityDetails.issuer));
    }
  }

  /**
   * @param {string} name
   * @param {string} value
   * @param {boolean=} highlighted
   * @return {!DocumentFragment}
   */
  _formatHeader(name, value, highlighted) {
    const fragment = createDocumentFragment();
    const nameElement = fragment.createChild('div', 'header-name');
    nameElement.textContent = name + ': ';
    fragment.createChild('span', 'header-separator');
    const valueElement = fragment.createChild('div', 'header-value source-code');
    valueElement.textContent = value;
    if (highlighted) {
      nameElement.classList.add('error-field');
      valueElement.classList.add('error-field');
    }
    return fragment;
  }

  /**
   * @param {string} name
   * @param {string} value
   * @param {boolean=} highlighted
   * @return {!DocumentFragment}
   */
  _formatHeaderForHexData(name, value, highlighted) {
    const fragment = createDocumentFragment();
    const nameElement = fragment.createChild('div', 'header-name');
    nameElement.textContent = name + ': ';
    fragment.createChild('span', 'header-separator');
    const valueElement = fragment.createChild('div', 'header-value source-code hex-data');
    valueElement.textContent = value.replace(/(.{2})/g, '$1 ');
    if (highlighted) {
      nameElement.classList.add('error-field');
      valueElement.classList.add('error-field');
    }
    return fragment;
  }
}

/**
 * @unrestricted
 */
export class Category extends UI.TreeOutline.TreeElement {
  /**
   * @param {!UI.TreeOutline.TreeOutline} root
   * @param {(string|!Node)=} title
   */
  constructor(root, title) {
    super(title, true);
    this.selectable = false;
    this.toggleOnClick = true;
    this.expanded = true;
    root.appendChild(this);
  }

  /**
   * @param {(string|!Node)=} title
   */
  createLeaf(title) {
    const leaf = new UI.TreeOutline.TreeElement(title);
    leaf.selectable = false;
    this.appendChild(leaf);
    return leaf;
  }
}
<commit_msg>[ts] Type-check network/SignedExchangeInfoView.js with TypeScript<commit_after>// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import * as Common from '../common/common.js';
import * as Components from '../components/components.js';
import * as Host from '../host/host.js';
import * as SDK from '../sdk/sdk.js';  // eslint-disable-line no-unused-vars
import * as UI from '../ui/ui.js';

export class SignedExchangeInfoView extends UI.Widget.VBox {
  /**
   * @param {!SDK.NetworkRequest.NetworkRequest} request
   */
  constructor(request) {
    super();
    console.assert(request.signedExchangeInfo() !== null);
    /** @type {!Protocol.Network.SignedExchangeInfo} */
    const signedExchangeInfo = /** @type {!Protocol.Network.SignedExchangeInfo} */ (request.signedExchangeInfo());

    this.registerRequiredCSS('network/signedExchangeInfoView.css');
    this.element.classList.add('signed-exchange-info-view');

    const root = new UI.TreeOutline.TreeOutlineInShadow();
    root.registerRequiredCSS('network/signedExchangeInfoTree.css');
    root.element.classList.add('signed-exchange-info-tree');
    root.setFocusable(false);
    root.makeDense();
    root.expandTreeElementsWhenArrowing = true;
    this.element.appendChild(root.element);

    /** @type {!Map<number|undefined, !Set<string>>} */
    const errorFieldSetMap = new Map();

    if (signedExchangeInfo.errors && signedExchangeInfo.errors.length) {
      const errorMessagesCategory = new Category(root, Common.UIString.UIString('Errors'));
      for (const error of signedExchangeInfo.errors) {
        const fragment = document.createDocumentFragment();
        fragment.appendChild(UI.Icon.Icon.create('smallicon-error', 'prompt-icon'));
        fragment.createChild('div', 'error-log').textContent = error.message;
        errorMessagesCategory.createLeaf(fragment);
        if (error.errorField) {
          let errorFieldSet = errorFieldSetMap.get(error.signatureIndex);
          if (!errorFieldSet) {
            errorFieldSet = new Set();
            errorFieldSetMap.set(error.signatureIndex, errorFieldSet);
          }
          errorFieldSet.add(error.errorField);
        }
      }
    }

    const titleElement = document.createDocumentFragment();
    titleElement.createChild('div', 'header-name').textContent = Common.UIString.UIString('Signed HTTP exchange');
    const learnMoreNode = UI.XLink.XLink.create(
        'https://github.com/WICG/webpackage', Common.UIString.UIString('Learn\xa0more'), 'header-toggle');
    titleElement.appendChild(learnMoreNode);
    const headerCategory = new Category(root, titleElement);
    if (signedExchangeInfo.header) {
      const header = signedExchangeInfo.header;
      const redirectDestination = request.redirectDestination();
      const requestURLElement = this._formatHeader(Common.UIString.UIString('Request URL'), header.requestUrl);
      if (redirectDestination) {
        const viewRequestLink = Components.Linkifier.Linkifier.linkifyRevealable(redirectDestination, 'View request');
        viewRequestLink.classList.add('header-toggle');
        requestURLElement.appendChild(viewRequestLink);
      }
      headerCategory.createLeaf(requestURLElement);
      headerCategory.createLeaf(
          this._formatHeader(Common.UIString.UIString('Response code'), header.responseCode + ''));
      headerCategory.createLeaf(
          this._formatHeader(Common.UIString.UIString('Header integrity hash'), header.headerIntegrity));

      this._responseHeadersItem =
          headerCategory.createLeaf(this._formatHeader(Common.UIString.UIString('Response headers'), ''));
      const responseHeaders = header.responseHeaders;
      for (const name in responseHeaders) {
        const headerTreeElement = new UI.TreeOutline.TreeElement(this._formatHeader(name, responseHeaders[name]));
        headerTreeElement.selectable = false;
        this._responseHeadersItem.appendChild(headerTreeElement);
      }
      this._responseHeadersItem.expand();

      for (let i = 0; i < header.signatures.length; ++i) {
        const errorFieldSet = errorFieldSetMap.get(i) || new Set();
        const signature = header.signatures[i];
        const signatureCategory = new Category(root, Common.UIString.UIString('Signature'));
        signatureCategory.createLeaf(this._formatHeader(Common.UIString.UIString('Label'), signature.label));
        signatureCategory.createLeaf(this._formatHeaderForHexData(
            Common.UIString.UIString('Signature'), signature.signature,
            errorFieldSet.has(Protocol.Network.SignedExchangeErrorField.SignatureSig)));

        if (signature.certUrl) {
          const certURLElement = this._formatHeader(
              Common.UIString.UIString('Certificate URL'), signature.certUrl,
              errorFieldSet.has(Protocol.Network.SignedExchangeErrorField.SignatureCertUrl));
          if (signature.certificates) {
            const viewCertLink = certURLElement.createChild('span', 'devtools-link header-toggle');
            viewCertLink.textContent = Common.UIString.UIString('View certificate');
            viewCertLink.addEventListener(
                'click',
                Host.InspectorFrontendHost.InspectorFrontendHostInstance.showCertificateViewer.bind(
                    null, signature.certificates),
                false);
          }
          signatureCategory.createLeaf(certURLElement);
        }
        signatureCategory.createLeaf(this._formatHeader(
            Common.UIString.UIString('Integrity'), signature.integrity,
            errorFieldSet.has(Protocol.Network.SignedExchangeErrorField.SignatureIntegrity)));
        if (signature.certSha256) {
          signatureCategory.createLeaf(this._formatHeaderForHexData(
              Common.UIString.UIString('Certificate SHA256'), signature.certSha256,
              errorFieldSet.has(Protocol.Network.SignedExchangeErrorField.SignatureCertSha256)));
        }
        signatureCategory.createLeaf(this._formatHeader(
            Common.UIString.UIString('Validity URL'), signature.validityUrl,
            errorFieldSet.has(Protocol.Network.SignedExchangeErrorField.SignatureValidityUrl)));
        signatureCategory.createLeaf().title = this._formatHeader(
            Common.UIString.UIString('Date'), new Date(1000 * signature.date).toUTCString(),
            errorFieldSet.has(Protocol.Network.SignedExchangeErrorField.SignatureTimestamps));
        signatureCategory.createLeaf().title = this._formatHeader(
            Common.UIString.UIString('Expires'), new Date(1000 * signature.expires).toUTCString(),
            errorFieldSet.has(Protocol.Network.SignedExchangeErrorField.SignatureTimestamps));
      }
    }
    if (signedExchangeInfo.securityDetails) {
      const securityDetails = signedExchangeInfo.securityDetails;
      const securityCategory = new Category(root, Common.UIString.UIString('Certificate'));
      securityCategory.createLeaf(this._formatHeader(Common.UIString.UIString('Subject'), securityDetails.subjectName));
      securityCategory.createLeaf(this._formatHeader(
          Common.UIString.UIString('Valid from'), new Date(1000 * securityDetails.validFrom).toUTCString()));
      securityCategory.createLeaf(this._formatHeader(
          Common.UIString.UIString('Valid until'), new Date(1000 * securityDetails.validTo).toUTCString()));
      securityCategory.createLeaf(this._formatHeader(Common.UIString.UIString('Issuer'), securityDetails.issuer));
    }
  }

  /**
   * @param {string} name
   * @param {string} value
   * @param {boolean=} highlighted
   * @return {!DocumentFragment}
   */
  _formatHeader(name, value, highlighted) {
    const fragment = document.createDocumentFragment();
    const nameElement = fragment.createChild('div', 'header-name');
    nameElement.textContent = name + ': ';
    fragment.createChild('span', 'header-separator');
    const valueElement = fragment.createChild('div', 'header-value source-code');
    valueElement.textContent = value;
    if (highlighted) {
      nameElement.classList.add('error-field');
      valueElement.classList.add('error-field');
    }
    return fragment;
  }

  /**
   * @param {string} name
   * @param {string} value
   * @param {boolean=} highlighted
   * @return {!DocumentFragment}
   */
  _formatHeaderForHexData(name, value, highlighted) {
    const fragment = document.createDocumentFragment();
    const nameElement = fragment.createChild('div', 'header-name');
    nameElement.textContent = name + ': ';
    fragment.createChild('span', 'header-separator');
    const valueElement = fragment.createChild('div', 'header-value source-code hex-data');
    valueElement.textContent = value.replace(/(.{2})/g, '$1 ');
    if (highlighted) {
      nameElement.classList.add('error-field');
      valueElement.classList.add('error-field');
    }
    return fragment;
  }
}

/**
 * @unrestricted
 */
export class Category extends UI.TreeOutline.TreeElement {
  /**
   * @param {!UI.TreeOutline.TreeOutline} root
   * @param {(string|!Node)=} title
   */
  constructor(root, title) {
    super(title, true);
    this.selectable = false;
    this.toggleOnClick = true;
    this.expanded = true;
    root.appendChild(this);
  }

  /**
   * @param {(string|!Node)=} title
   */
  createLeaf(title) {
    const leaf = new UI.TreeOutline.TreeElement(title);
    leaf.selectable = false;
    this.appendChild(leaf);
    return leaf;
  }
}
<|endoftext|>


<commit_before>'use strict';

module.exports = {
	rules: {
		'no-await-in-loop': 'error',
		'no-compare-neg-zero': 'error',
		'no-cond-assign': 'error',
		'no-console': 'error',
		'no-constant-condition': 'error',
		'no-control-regex': 'error',
		'no-debugger': 'error',
		'no-dupe-args': 'error',
		'no-dupe-keys': 'error',
		'no-duplicate-case': 'error',
		'no-empty': 'error',
		'no-empty-character-class': 'error',
		'no-ex-assign': 'error',
		'no-extra-boolean-cast': 'error',
		'no-extra-parens': [
			'error',
			'all',
			{
				nestedBinaryExpressions: false,
				ignoreJSX: 'multi-line',
			}
		],
		'no-extra-semi': 'error',
		'no-func-assign': 'error',
		'no-inner-declarations': 'error',
		'no-invalid-regexp': 'error',
		'no-irregular-whitespace': 'error',
		'no-obj-calls': 'error',
		'no-prototype-builtins': 'off',
		'no-regex-spaces': 'error',
		'no-sparse-arrays': 'error',
		'no-template-curly-in-string': 'error',
		'no-unexpected-multiline': 'error',
		'no-unreachable': 'error',
		'no-unsafe-finally': 'error',
		'no-unsafe-negation': 'error',
		'use-isnan': 'error',
		'valid-jsdoc': 'warn',
		'valid-typeof': 'error',
	},
};
<commit_msg>Don't enforce valid JSDoc comments<commit_after>'use strict';

module.exports = {
	rules: {
		'no-await-in-loop': 'error',
		'no-compare-neg-zero': 'error',
		'no-cond-assign': 'error',
		'no-console': 'error',
		'no-constant-condition': 'error',
		'no-control-regex': 'error',
		'no-debugger': 'error',
		'no-dupe-args': 'error',
		'no-dupe-keys': 'error',
		'no-duplicate-case': 'error',
		'no-empty': 'error',
		'no-empty-character-class': 'error',
		'no-ex-assign': 'error',
		'no-extra-boolean-cast': 'error',
		'no-extra-parens': [
			'error',
			'all',
			{
				nestedBinaryExpressions: false,
				ignoreJSX: 'multi-line',
			}
		],
		'no-extra-semi': 'error',
		'no-func-assign': 'error',
		'no-inner-declarations': 'error',
		'no-invalid-regexp': 'error',
		'no-irregular-whitespace': 'error',
		'no-obj-calls': 'error',
		'no-prototype-builtins': 'off',
		'no-regex-spaces': 'error',
		'no-sparse-arrays': 'error',
		'no-template-curly-in-string': 'error',
		'no-unexpected-multiline': 'error',
		'no-unreachable': 'error',
		'no-unsafe-finally': 'error',
		'no-unsafe-negation': 'error',
		'use-isnan': 'error',
		'valid-jsdoc': 'off',
		'valid-typeof': 'error',
	},
};
<|endoftext|>


<commit_before>import React, { useState, useEffect } from 'react';
import app from '../Firebase';

const AuthContext = React.createContext();

/**
 * AuthProvider component that keeps track of the authentication status of the
 * current user. Allows global use of this status using React Context and should
 * be wrapped around the contents of the App component.
 */
const AuthProvider = (props) => {
  const [currentUser, setCurrentUser] = useState(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    // Set up listener that changes user status whenever it is updated.
    app.auth().onAuthStateChanged((user) => {
      setCurrentUser(user);
      setIsLoading(false);
    });
  }, []);

  if (isLoading) {
    return (
Loading...
 );
  }

  return (
    <AuthContext.Provider value={currentUser}>
      {props.children}
    </AuthContext.Provider>
  );
}

export { AuthContext, AuthProvider };
<commit_msg>Add TODO<commit_after>import React, { useState, useEffect } from 'react';
import app from '../Firebase';

const AuthContext = React.createContext();

/**
 * AuthProvider component that keeps track of the authentication status of the
 * current user. Allows global use of this status using React Context and should
 * be wrapped around the contents of the App component.
 */
const AuthProvider = (props) => {
  const [currentUser, setCurrentUser] = useState(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    // Set up listener that changes user status whenever it is updated.
    app.auth().onAuthStateChanged((user) => {
      setCurrentUser(user);
      setIsLoading(false);
    });
  }, []);

  if (isLoading) {
    // TODO (Issue #25): Page initially displays "Loading..." for testing
    // purposes, make this blank in the deployed build.
    return (
Loading...
 );
  }

  return (
    <AuthContext.Provider value={currentUser}>
      {props.children}
    </AuthContext.Provider>
  );
}

export { AuthContext, AuthProvider };
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { View, Text, ScrollView, TouchableOpacity, Hyperlink } from 'react-native';
import { Actions } from 'react-native-router-flux';
import Icon from 'react-native-vector-icons/MaterialIcons';
import axios from 'axios';
import {Item} from './';
import Costper from './Costper';
import ContainerSection from '../ContainerSection';
import LoginForm from '../LoginForm';

class ItemsList extends Component {

  constructor(props) {
    super(props);
    this.state = { data: [],
                   name: '',
                   price: '',
                   img_url: '',
                   star: '',
                   user_id: this.props.userId,
                   category_id: ''
                 };
    this.updateItemFunc = this.updateItemFunc.bind(this)

  }

  componentWillMount() {
    var myItem = this;
    axios.get('http://localhost:3000/users/'+this.state.user_id+'/items')
      .then(function(response) {
        myItem.setState({data: response.data})
      })
      .catch(function(error) {
        console.log(error)
      });
    }

    updateItemFunc(index){
      var thisItemsList = this

      return function(newCostper) {
        var data = thisItemsList.state.data
        var oldItem = data[index]
        oldItem.costper.costper = newCostper
        data[index] = oldItem
        thisItemsList.setState({ data: data })
        thisItemsList.sortList()
      }
    }

    sortList() {
      var newList = this.state.data.sort(function(a,b) {
        return b.costper.costper - a.costper.costper

      })
      this.setState({ data: newList })
    }

    render() {
      return (
      <View style={styles.container}>
        <ScrollView>
            <View >
            <View style={styles.contentcolumns} >
            {this.state.data.map((item, index) => {
              return(
                <View style={styles.rows}>
                  <View style={styles.itemInfoContainer}>

                  <Item key={item.id}
                    name={item.name}
                    price={item.price}
                    img_url={item.img_url}
                    star={item.star}
                    user_id={item.user_id}
                    item_id={item.id}
                    category_id={item.category_id}
                  />
                  <Costper key={item.costper.id}
                        costper = {item.costper.costper}
                        item_id = {item.costper.item_id}
                        updateItem={this.updateItemFunc(index)}
                  />
                  </View>
                </View>
              )})}
          </View>
        </View>
      </ScrollView>
        <View style={styles.footerStyle}>
          <TouchableOpacity onPress={() => Actions.addItem({ userId: this.state.user_id })}>
            <View style={styles.footerSubGroup}>
              <Icon size={40} style={{ color: 'white' }} name="add-circle"/>
              <Text style={styles.footerTextStyle}>Add Item</Text>
            </View>
          </TouchableOpacity>
        </View>
      </View>
      );
    }
}

const styles = ({
  container: {
    flex: 1,
  },
  rows: {
    flexDirection: 'column',
    justifyContent: 'space-around'
  },
  itemInfoContainer: {
    height: 100,
    justifyContent: 'space-around',
    borderColor: '#D3D3D3',
    borderWidth: 0.5,
    paddingTop: 20,
    paddingBottom: 10
  }
  footerStyle: {
    height: 60,
    position: 'relative',
    backgroundColor: "#16795B",
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center'
  },
  footerTextStyle: {
    color: 'white',
    fontSize: 13
  },
  footerSubGroup: {
    alignItems: 'center',
    justifyContent: 'center'
  }

});

export { ItemsList };
<commit_msg>Fixed error with comma in items list styling.<commit_after>import React, { Component } from 'react';
import { View, Text, ScrollView, TouchableOpacity, Hyperlink } from 'react-native';
import { Actions } from 'react-native-router-flux';
import Icon from 'react-native-vector-icons/MaterialIcons';
import axios from 'axios';
import {Item} from './';
import Costper from './Costper';
import ContainerSection from '../ContainerSection';
import LoginForm from '../LoginForm';

class ItemsList extends Component {

  constructor(props) {
    super(props);
    this.state = { data: [],
                   name: '',
                   price: '',
                   img_url: '',
                   star: '',
                   user_id: this.props.userId,
                   category_id: ''
                 };
    this.updateItemFunc = this.updateItemFunc.bind(this)

  }

  componentWillMount() {
    var myItem = this;
    axios.get('http://localhost:3000/users/'+this.state.user_id+'/items')
      .then(function(response) {
        myItem.setState({data: response.data})
      })
      .catch(function(error) {
        console.log(error)
      });
    }

    updateItemFunc(index){
      var thisItemsList = this

      return function(newCostper) {
        var data = thisItemsList.state.data
        var oldItem = data[index]
        oldItem.costper.costper = newCostper
        data[index] = oldItem
        thisItemsList.setState({ data: data })
        thisItemsList.sortList()
      }
    }

    sortList() {
      var newList = this.state.data.sort(function(a,b) {
        return b.costper.costper - a.costper.costper

      })
      this.setState({ data: newList })
    }

    render() {
      return (
      <View style={styles.container}>
        <ScrollView>
            <View >
            <View style={styles.contentcolumns} >
            {this.state.data.map((item, index) => {
              return(
                <View style={styles.rows}>
                  <View style={styles.itemInfoContainer}>

                  <Item key={item.id}
                    name={item.name}
                    price={item.price}
                    img_url={item.img_url}
                    star={item.star}
                    user_id={item.user_id}
                    item_id={item.id}
                    category_id={item.category_id}
                  />
                  <Costper key={item.costper.id}
                        costper = {item.costper.costper}
                        item_id = {item.costper.item_id}
                        updateItem={this.updateItemFunc(index)}
                  />
                  </View>
                </View>
              )})}
          </View>
        </View>
      </ScrollView>
        <View style={styles.footerStyle}>
          <TouchableOpacity onPress={() => Actions.addItem({ userId: this.state.user_id })}>
            <View style={styles.footerSubGroup}>
              <Icon size={40} style={{ color: 'white' }} name="add-circle"/>
              <Text style={styles.footerTextStyle}>Add Item</Text>
            </View>
          </TouchableOpacity>
        </View>
      </View>
      );
    }
}

const styles = ({
  container: {
    flex: 1,
  },
  rows: {
    flexDirection: 'column',
    justifyContent: 'space-around'
  },
  itemInfoContainer: {
    height: 100,
    justifyContent: 'space-around',
    borderColor: '#D3D3D3',
    borderWidth: 0.5,
    paddingTop: 20,
    paddingBottom: 10
  },
  footerStyle: {
    height: 60,
    position: 'relative',
    backgroundColor: "#16795B",
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center'
  },
  footerTextStyle: {
    color: 'white',
    fontSize: 13
  },
  footerSubGroup: {
    alignItems: 'center',
    justifyContent: 'center'
  }

});

export { ItemsList };
<|endoftext|>