<commit_before>import qw from 'js-utils/qw';
const gulp = require('gulp');

const $ = require('lazyreq')(require, {
	newer: 'gulp-newer',
	cached: 'gulp-cached',
	babel: 'gulp-babel',
	eslint: 'gulp-eslint',
});

gulp.task('build', () =>
	gulp.src('./src/**/*.js')
		.pipe($.newer('./build'))
		.pipe($.babel({
			sourceMaps: 'inline',
		}))
		.pipe(gulp.dest('./build'))
);

gulp.task('lint', () =>
	gulp.src(['./src/**/*.js', './gulpfile.babel.js'])
		.pipe($.cached('lint'))
		.pipe($.eslint())
		.pipe($.eslint.format())
		.pipe($.eslint.failAfterError())
);

gulp.task('watch', () => {
	gulp.watch('./src/**/*.js', qw('build lint'));
});
<commit_msg>use es6 modules/imports in gulpfile<commit_after>import qw from 'js-utils/qw';
import gulp from 'gulp';
import lazyReq from 'lazyreq';

const $ = lazyReq(require, {
	newer: 'gulp-newer',
	cached: 'gulp-cached',
	babel: 'gulp-babel',
	eslint: 'gulp-eslint',
});

gulp.task('build', () =>
	gulp.src('./src/**/*.js')
		.pipe($.newer('./build'))
		.pipe($.babel({
			sourceMaps: 'inline',
		}))
		.pipe(gulp.dest('./build'))
);

gulp.task('lint', () =>
	gulp.src(['./src/**/*.js', './gulpfile.babel.js'])
		.pipe($.cached('lint'))
		.pipe($.eslint())
		.pipe($.eslint.format())
		.pipe($.eslint.failAfterError())
);

gulp.task('watch', () => {
	gulp.watch('./src/**/*.js', qw('build lint'));
});
<|endoftext|>


<commit_before>import config from '../../config';
import { deleteEntireWaysEpic, REQUEST_OSM_CHANGE_SUCCESS } from './osm';
import { editRoadIdEpic } from './roads';
/**
 * constants
 */
export const FETCH_WAY_TASK = 'FETCH_WAY_TASK';
export const FETCH_NEXT_WAY_TASK = 'FETCH_NEXT_WAY_TASK';
export const FETCH_WAY_TASK_SUCCESS = 'FETCH_WAY_TASK_SUCCESS';
export const FETCH_WAY_TASK_ERROR = 'FETCH_WAY_TASK_ERROR';
export const FETCH_WAY_TASK_COUNT = 'FETCH_WAY_TASK_COUNT';
export const FETCH_WAY_TASK_COUNT_SUCCESS = 'FETCH_WAY_TASK_COUNT_SUCCESS';
export const FETCH_WAY_TASK_COUNT_ERROR = 'FETCH_WAY_TASK_COUNT_ERROR';
export const MARK_WAY_TASK_PENDING = 'MARK_WAY_TASK_PENDING';
export const MARK_WAY_TASK_PENDING_SUCCESS = 'MARK_WAY_TASK_PENDING_SUCCESS';
export const MARK_WAY_TASK_PENDING_ERROR = 'MARK_WAY_TASK_PENDING_ERROR';
export const SKIP_TASK = 'SKIP_TASK';
export const SELECT_NEXT_WAY_TASK_PROVINCE = 'SELECT_NEXT_WAY_TASK_PROVINCE';
export const DEDUPE_WAY_TASK = 'DEDUPE_WAY_TASK';
export const DEDUPE_WAY_TASK_SUCCESS = 'DEDUPE_WAY_TASK_SUCCESS';
export const DEDUPE_WAY_TASK_ERROR = 'DEDUPE_WAY_TASK_ERROR';

/**
 * action creators
 */
export const fetchWayTask = (id) => ({ type: FETCH_WAY_TASK, id });
export const fetchNextWayTask = () => ({ type: FETCH_NEXT_WAY_TASK });
export const fetchWayTaskSuccess = (id, updatedAt, geoJSON) => ({
  type: FETCH_WAY_TASK_SUCCESS,
  id,
  updatedAt,
  geoJSON
});
export const fetchWayTaskError = (error) => ({ type: FETCH_WAY_TASK_ERROR, error: error });
export const fetchWayTaskCount = () => ({ type: FETCH_WAY_TASK_COUNT });
export const fetchWayTaskCountSuccess = count => ({ type: FETCH_WAY_TASK_COUNT_SUCCESS, count });
export const fetchWayTaskCountError = count => ({ type: FETCH_WAY_TASK_COUNT_ERROR });
export const markWayTaskPending = () => ({ type: MARK_WAY_TASK_PENDING });
export const markWayTaskPendingSuccess = () => ({ type: MARK_WAY_TASK_PENDING_SUCCESS });
export const markWayTaskPendingError = () => ({ type: MARK_WAY_TASK_PENDING_ERROR });
export const skipTask = id => ({ type: SKIP_TASK, id });
export const selectWayTaskProvince = (provinceId) => ({ type: SELECT_NEXT_WAY_TASK_PROVINCE, selectedProvince: provinceId });
export const dedupeWayTask = (taskId, wayIds, wayIdToKeep, dedupeId) => ({ type: DEDUPE_WAY_TASK, taskId: taskId, wayIdsToDelete: wayIds, wayIdToKeep: wayIdToKeep, dedupeIdToApply: dedupeId });
export const dedupeWayTaskSuccess = () => ({ type: DEDUPE_WAY_TASK_SUCCESS });
export const dedupeWayTaskError = (error) => ({ type: DEDUPE_WAY_TASK_ERROR, error: error });

function getBoundaryType (allAdmins, selected) {
  const districtIds = allAdmins.districts.district.map(d => d.id);
  const provinceIds = allAdmins.provinces.province.map(p => p.id);
  if (districtIds.indexOf(selected) !== -1) {
    return 'district';
  } else if (provinceIds.indexOf(selected) !== -1) {
    return 'province';
  } else {
    return null;
  }
}

export const fetchNextWayTaskEpic = () => (dispatch, getState) => {
  dispatch(fetchNextWayTask());

  const skipped = getState().waytasks.skipped;
  const selectedBoundary = getState().waytasks.selectedProvince;
  let allBoundaries, boundaryType;
  if (selectedBoundary) {
    allBoundaries = getState().provinces.data;
    boundaryType = getBoundaryType(allBoundaries, selectedBoundary);
  }
  let params = {};
  if (skipped.length) params['skip'] = skipped;
  if (selectedBoundary) params[boundaryType] = selectedBoundary;

  let url = `${config.api}/tasks/next`;
  if (Object.keys(params).length) {
    url = url + '?' + Object.keys(params).map(key => `${key}=${params[key]}`).join('&');
  }

  return fetch(url)
    .then(response => {
      if (response.status === 404) {
        throw new Error('No tasks remaining');
      } else if (response.status >= 400) {
        throw new Error(response.statusText);
      }
      return response.json();
    })
    .then(json => {
      json.data.features.forEach(feature => {
        feature.properties._id = feature.meta.id;
        feature.properties.province = json.boundary;
      });
      dispatch(fetchWayTaskCountEpic());
      return dispatch(fetchWayTaskSuccess(json.id, json.updated_at, json.data));
    }, e => {
      console.error('Error requesting task', e);
      return dispatch(fetchWayTaskError(e));
    });
};

export const fetchWayTaskEpic = taskId => (dispatch, getState) => {
  dispatch(fetchWayTask(taskId));

  return fetch(`${config.api}/tasks/${taskId}`)
    .then(response => {
      if (response.status >= 400) {
        throw new Error(response.statusText);
      }
      return response.json();
    })
    .then(({ id, data }) => {
      data.features.forEach(feature => {
        feature.properties._id = feature.meta.id;
      });
      return dispatch(fetchWayTaskSuccess(id, data.updated_at, data));
    }, e => {
      console.error('Error reloading task', e);
      return dispatch(fetchWayTaskError());
    });
};

export const fetchWayTaskCountEpic = () => (dispatch, getState) => {
  dispatch(fetchWayTaskCount());
  const selectedProvince = getState().waytasks.selectedProvince;
  const url = selectedProvince ? `${config.api}/tasks/count?province=${selectedProvince}` : `${config.api}/tasks/count`;

  fetch(url)
    .then(response => {
      if (response.status >= 400) {
        throw new Error(response.statusText);
      }
      return response.json();
    })
    .then(({ count }) => {
      dispatch(fetchWayTaskCountSuccess(count));
    }, e => {
      console.error('Error requesting task count', e);
      dispatch(fetchWayTaskCountError());
    });
};

export const markWayTaskPendingEpic = wayIds => dispatch => {
  dispatch(markWayTaskPending());

  return fetch(`${config.api}/tasks/pending`, {
    method: 'PUT',
    body: new Blob([JSON.stringify({ way_ids: wayIds })], { type: 'application/json' })
  })
    .then(response => {
      if (response.status >= 400) {
        console.error('Error marking task as pending', response.statusText);
        dispatch(markWayTaskPendingError());
      }

      dispatch(markWayTaskPendingSuccess());
    });
};

export const dedupeWayTaskEpic = (taskId, wayIds, wayIdToKeep, dedupeId) => (dispatch, getState) => {
  dispatch(dedupeWayTask(taskId, wayIds, wayIdToKeep, dedupeId));
  // delete ways
  dispatch(deleteEntireWaysEpic(taskId, wayIds))
    .then(() => {
      dispatch(editRoadIdEpic(wayIdToKeep, dedupeId))
        .then(() => { dispatch(dedupeWayTaskSuccess); })
        .catch((err) => { dispatch(dedupeWayTaskError(err)); });
    });
};
/**
 * reducer
 */
export default (
  state = {
    status: 'complete',
    countStatus: 'complete',
    id: null,
    geoJSON: null,
    skipped: [],
    provinces: [],
    selectedProvince: null,
    dedupeTaskId: null,
    wayIdsToDelete: [],
    dedupeIdToApply: null,
    wayIdToKeep: null,
    osmChangeTaskId: null
  },
  action
) => {
  if (action.type === FETCH_WAY_TASK) {
    return Object.assign({}, state, {
      status: 'pending'
    });
  } else if (action.type === FETCH_NEXT_WAY_TASK) {
    return Object.assign({}, state, {
      status: 'pending'
    });
  } else if (action.type === FETCH_WAY_TASK_SUCCESS) {
    return Object.assign({}, state, {
      geoJSON: action.geoJSON,
      id: action.id,
      updatedAt: action.updatedAt,
      status: 'complete'
    });
  } else if (action.type === FETCH_WAY_TASK_ERROR) {
    return Object.assign({}, state, {
      status: action.error.message === 'No tasks remaining' ? 'No tasks remaining' : 'error'
    });
  } else if (action.type === FETCH_WAY_TASK_COUNT) {
    return Object.assign({}, state, {
      taskCount: action.count,
      countStatus: 'pending'
    });
  } else if (action.type === FETCH_WAY_TASK_COUNT_SUCCESS) {
    return Object.assign({}, state, {
      taskCount: action.count,
      countStatus: 'complete'
    });
  } else if (action.type === FETCH_WAY_TASK_COUNT_ERROR) {
    return Object.assign({}, state, {
      countStatus: 'error'
    });
  } else if (action.type === SKIP_TASK) {
    return Object.assign({}, state, {
      skipped: state.skipped.concat(action.id)
    });
  } else if (action.type === SELECT_NEXT_WAY_TASK_PROVINCE) {
    return Object.assign({}, state, {
      selectedProvince: action.selectedProvince
    });
  } else if (action.type === DEDUPE_WAY_TASK) {
    return Object.assign({}, state, {
      dedupeTaskId: action.taskId,
      wayIdsToDelete: action.wayIdsToDelete,
      dedupeIdToApply: action.dedupeIdToApply,
      wayIdToKeep: action.wayIdToKeep
    });
  } else if (action.type === REQUEST_OSM_CHANGE_SUCCESS) {
    return Object.assign({}, state, {
      osmChangeTaskId: action.taskId
    });
  }

  return state;
};
<commit_msg>fetch count correctly for currently selected boundary<commit_after>import config from '../../config';
import { deleteEntireWaysEpic, REQUEST_OSM_CHANGE_SUCCESS } from './osm';
import { editRoadIdEpic } from './roads';
/**
 * constants
 */
export const FETCH_WAY_TASK = 'FETCH_WAY_TASK';
export const FETCH_NEXT_WAY_TASK = 'FETCH_NEXT_WAY_TASK';
export const FETCH_WAY_TASK_SUCCESS = 'FETCH_WAY_TASK_SUCCESS';
export const FETCH_WAY_TASK_ERROR = 'FETCH_WAY_TASK_ERROR';
export const FETCH_WAY_TASK_COUNT = 'FETCH_WAY_TASK_COUNT';
export const FETCH_WAY_TASK_COUNT_SUCCESS = 'FETCH_WAY_TASK_COUNT_SUCCESS';
export const FETCH_WAY_TASK_COUNT_ERROR = 'FETCH_WAY_TASK_COUNT_ERROR';
export const MARK_WAY_TASK_PENDING = 'MARK_WAY_TASK_PENDING';
export const MARK_WAY_TASK_PENDING_SUCCESS = 'MARK_WAY_TASK_PENDING_SUCCESS';
export const MARK_WAY_TASK_PENDING_ERROR = 'MARK_WAY_TASK_PENDING_ERROR';
export const SKIP_TASK = 'SKIP_TASK';
export const SELECT_NEXT_WAY_TASK_PROVINCE = 'SELECT_NEXT_WAY_TASK_PROVINCE';
export const DEDUPE_WAY_TASK = 'DEDUPE_WAY_TASK';
export const DEDUPE_WAY_TASK_SUCCESS = 'DEDUPE_WAY_TASK_SUCCESS';
export const DEDUPE_WAY_TASK_ERROR = 'DEDUPE_WAY_TASK_ERROR';

/**
 * action creators
 */
export const fetchWayTask = (id) => ({ type: FETCH_WAY_TASK, id });
export const fetchNextWayTask = () => ({ type: FETCH_NEXT_WAY_TASK });
export const fetchWayTaskSuccess = (id, updatedAt, geoJSON) => ({
  type: FETCH_WAY_TASK_SUCCESS,
  id,
  updatedAt,
  geoJSON
});
export const fetchWayTaskError = (error) => ({ type: FETCH_WAY_TASK_ERROR, error: error });
export const fetchWayTaskCount = () => ({ type: FETCH_WAY_TASK_COUNT });
export const fetchWayTaskCountSuccess = count => ({ type: FETCH_WAY_TASK_COUNT_SUCCESS, count });
export const fetchWayTaskCountError = count => ({ type: FETCH_WAY_TASK_COUNT_ERROR });
export const markWayTaskPending = () => ({ type: MARK_WAY_TASK_PENDING });
export const markWayTaskPendingSuccess = () => ({ type: MARK_WAY_TASK_PENDING_SUCCESS });
export const markWayTaskPendingError = () => ({ type: MARK_WAY_TASK_PENDING_ERROR });
export const skipTask = id => ({ type: SKIP_TASK, id });
export const selectWayTaskProvince = (provinceId) => ({ type: SELECT_NEXT_WAY_TASK_PROVINCE, selectedProvince: provinceId });
export const dedupeWayTask = (taskId, wayIds, wayIdToKeep, dedupeId) => ({ type: DEDUPE_WAY_TASK, taskId: taskId, wayIdsToDelete: wayIds, wayIdToKeep: wayIdToKeep, dedupeIdToApply: dedupeId });
export const dedupeWayTaskSuccess = () => ({ type: DEDUPE_WAY_TASK_SUCCESS });
export const dedupeWayTaskError = (error) => ({ type: DEDUPE_WAY_TASK_ERROR, error: error });

function getBoundaryType (allAdmins, selected) {
  const districtIds = allAdmins.districts.district.map(d => d.id);
  const provinceIds = allAdmins.provinces.province.map(p => p.id);
  if (districtIds.indexOf(selected) !== -1) {
    return 'district';
  } else if (provinceIds.indexOf(selected) !== -1) {
    return 'province';
  } else {
    return null;
  }
}

export const fetchNextWayTaskEpic = () => (dispatch, getState) => {
  dispatch(fetchNextWayTask());

  const skipped = getState().waytasks.skipped;
  const selectedBoundary = getState().waytasks.selectedProvince;
  let allBoundaries, boundaryType;
  if (selectedBoundary) {
    allBoundaries = getState().provinces.data;
    boundaryType = getBoundaryType(allBoundaries, selectedBoundary);
  }
  let params = {};
  if (skipped.length) params['skip'] = skipped;
  if (selectedBoundary) params[boundaryType] = selectedBoundary;

  let url = `${config.api}/tasks/next`;
  if (Object.keys(params).length) {
    url = url + '?' + Object.keys(params).map(key => `${key}=${params[key]}`).join('&');
  }

  return fetch(url)
    .then(response => {
      if (response.status === 404) {
        throw new Error('No tasks remaining');
      } else if (response.status >= 400) {
        throw new Error(response.statusText);
      }
      return response.json();
    })
    .then(json => {
      json.data.features.forEach(feature => {
        feature.properties._id = feature.meta.id;
        feature.properties.province = json.boundary;
      });
      dispatch(fetchWayTaskCountEpic());
      return dispatch(fetchWayTaskSuccess(json.id, json.updated_at, json.data));
    }, e => {
      console.error('Error requesting task', e);
      return dispatch(fetchWayTaskError(e));
    });
};

export const fetchWayTaskEpic = taskId => (dispatch, getState) => {
  dispatch(fetchWayTask(taskId));

  return fetch(`${config.api}/tasks/${taskId}`)
    .then(response => {
      if (response.status >= 400) {
        throw new Error(response.statusText);
      }
      return response.json();
    })
    .then(({ id, data }) => {
      data.features.forEach(feature => {
        feature.properties._id = feature.meta.id;
      });
      return dispatch(fetchWayTaskSuccess(id, data.updated_at, data));
    }, e => {
      console.error('Error reloading task', e);
      return dispatch(fetchWayTaskError());
    });
};

export const fetchWayTaskCountEpic = () => (dispatch, getState) => {
  dispatch(fetchWayTaskCount());
  const selectedBoundary = getState().waytasks.selectedProvince;
  let allBoundaries, boundaryType;
  if (selectedBoundary) {
    allBoundaries = getState().provinces.data;
    boundaryType = getBoundaryType(allBoundaries, selectedBoundary);
  }

  const url = selectedBoundary ? `${config.api}/tasks/count?${boundaryType}=${selectedBoundary}` : `${config.api}/tasks/count`;

  fetch(url)
    .then(response => {
      if (response.status >= 400) {
        throw new Error(response.statusText);
      }
      return response.json();
    })
    .then(({ count }) => {
      dispatch(fetchWayTaskCountSuccess(count));
    }, e => {
      console.error('Error requesting task count', e);
      dispatch(fetchWayTaskCountError());
    });
};

export const markWayTaskPendingEpic = wayIds => dispatch => {
  dispatch(markWayTaskPending());

  return fetch(`${config.api}/tasks/pending`, {
    method: 'PUT',
    body: new Blob([JSON.stringify({ way_ids: wayIds })], { type: 'application/json' })
  })
    .then(response => {
      if (response.status >= 400) {
        console.error('Error marking task as pending', response.statusText);
        dispatch(markWayTaskPendingError());
      }

      dispatch(markWayTaskPendingSuccess());
    });
};

export const dedupeWayTaskEpic = (taskId, wayIds, wayIdToKeep, dedupeId) => (dispatch, getState) => {
  dispatch(dedupeWayTask(taskId, wayIds, wayIdToKeep, dedupeId));
  // delete ways
  dispatch(deleteEntireWaysEpic(taskId, wayIds))
    .then(() => {
      dispatch(editRoadIdEpic(wayIdToKeep, dedupeId))
        .then(() => { dispatch(dedupeWayTaskSuccess); })
        .catch((err) => { dispatch(dedupeWayTaskError(err)); });
    });
};
/**
 * reducer
 */
export default (
  state = {
    status: 'complete',
    countStatus: 'complete',
    id: null,
    geoJSON: null,
    skipped: [],
    provinces: [],
    selectedProvince: null,
    dedupeTaskId: null,
    wayIdsToDelete: [],
    dedupeIdToApply: null,
    wayIdToKeep: null,
    osmChangeTaskId: null
  },
  action
) => {
  if (action.type === FETCH_WAY_TASK) {
    return Object.assign({}, state, {
      status: 'pending'
    });
  } else if (action.type === FETCH_NEXT_WAY_TASK) {
    return Object.assign({}, state, {
      status: 'pending'
    });
  } else if (action.type === FETCH_WAY_TASK_SUCCESS) {
    return Object.assign({}, state, {
      geoJSON: action.geoJSON,
      id: action.id,
      updatedAt: action.updatedAt,
      status: 'complete'
    });
  } else if (action.type === FETCH_WAY_TASK_ERROR) {
    return Object.assign({}, state, {
      status: action.error.message === 'No tasks remaining' ? 'No tasks remaining' : 'error'
    });
  } else if (action.type === FETCH_WAY_TASK_COUNT) {
    return Object.assign({}, state, {
      taskCount: action.count,
      countStatus: 'pending'
    });
  } else if (action.type === FETCH_WAY_TASK_COUNT_SUCCESS) {
    return Object.assign({}, state, {
      taskCount: action.count,
      countStatus: 'complete'
    });
  } else if (action.type === FETCH_WAY_TASK_COUNT_ERROR) {
    return Object.assign({}, state, {
      countStatus: 'error'
    });
  } else if (action.type === SKIP_TASK) {
    return Object.assign({}, state, {
      skipped: state.skipped.concat(action.id)
    });
  } else if (action.type === SELECT_NEXT_WAY_TASK_PROVINCE) {
    return Object.assign({}, state, {
      selectedProvince: action.selectedProvince
    });
  } else if (action.type === DEDUPE_WAY_TASK) {
    return Object.assign({}, state, {
      dedupeTaskId: action.taskId,
      wayIdsToDelete: action.wayIdsToDelete,
      dedupeIdToApply: action.dedupeIdToApply,
      wayIdToKeep: action.wayIdToKeep
    });
  } else if (action.type === REQUEST_OSM_CHANGE_SUCCESS) {
    return Object.assign({}, state, {
      osmChangeTaskId: action.taskId
    });
  }

  return state;
};
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow strict
 */

import type { ObjMap } from '../jsutils/ObjMap';
import { GraphQLSchema } from '../type/schema';
import { GraphQLDirective } from '../type/directives';
import type { GraphQLNamedType } from '../type/definition';
import {
  GraphQLObjectType,
  GraphQLInterfaceType,
  GraphQLUnionType,
  GraphQLEnumType,
  GraphQLInputObjectType,
  GraphQLList,
  GraphQLNonNull,
  isListType,
  isNonNullType,
  isScalarType,
  isObjectType,
  isInterfaceType,
  isUnionType,
  isEnumType,
  isInputObjectType,
} from '../type/definition';
import { isSpecifiedScalarType } from '../type/scalars';
import { isIntrospectionType } from '../type/introspection';

/**
 * Sort GraphQLSchema.
 */
export function lexicographicSortSchema(schema: GraphQLSchema): GraphQLSchema {
  const cache = Object.create(null);

  const schemaConfig = schema.toConfig();
  const sortMaybeType = maybeType => maybeType && sortNamedType(maybeType);
  return new GraphQLSchema({
    ...schemaConfig,
    types: sortTypes(schemaConfig.types),
    directives: sortByName(schemaConfig.directives).map(sortDirective),
    query: sortMaybeType(schemaConfig.query),
    mutation: sortMaybeType(schemaConfig.mutation),
    subscription: sortMaybeType(schemaConfig.subscription),
  });

  function sortDirective(directive) {
    const config = directive.toConfig();
    return new GraphQLDirective({
      ...config,
      locations: sortBy(config.locations, x => x),
      args: sortArgs(config.args),
    });
  }

  function sortArgs(args) {
    return sortObjMap(args, arg => ({
      ...arg,
      type: sortType(arg.type),
    }));
  }

  function sortFields(fieldsMap) {
    return sortObjMap(fieldsMap, field => ({
      ...field,
      type: sortType(field.type),
      args: sortArgs(field.args),
    }));
  }

  function sortInputFields(fieldsMap) {
    return sortObjMap(fieldsMap, field => ({
      ...field,
      type: sortType(field.type),
    }));
  }

  function sortType(type) {
    if (isListType(type)) {
      return new GraphQLList(sortType(type.ofType));
    } else if (isNonNullType(type)) {
      return new GraphQLNonNull(sortType(type.ofType));
    }
    return sortNamedType(type);
  }

  function sortTypes<T: GraphQLNamedType>(arr: Array<T>): Array<T> {
    return sortByName(arr).map(sortNamedType);
  }

  function sortNamedType<T: GraphQLNamedType>(type: T): T {
    if (isSpecifiedScalarType(type) || isIntrospectionType(type)) {
      return type;
    }

    let sortedType = cache[type.name];
    if (!sortedType) {
      sortedType = sortNamedTypeImpl(type);
      cache[type.name] = sortedType;
    }
    return ((sortedType: any): T);
  }

  function sortNamedTypeImpl(type) {
    if (isScalarType(type)) {
      return type;
    } else if (isObjectType(type)) {
      const config = type.toConfig();
      return new GraphQLObjectType({
        ...config,
        interfaces: () => sortTypes(config.interfaces),
        fields: () => sortFields(config.fields),
      });
    } else if (isInterfaceType(type)) {
      const config = type.toConfig();
      return new GraphQLInterfaceType({
        ...config,
        fields: () => sortFields(config.fields),
      });
    } else if (isUnionType(type)) {
      const config = type.toConfig();
      return new GraphQLUnionType({
        ...config,
        types: () => sortTypes(config.types),
      });
    } else if (isEnumType(type)) {
      const config = type.toConfig();
      return new GraphQLEnumType({
        ...config,
        values: sortObjMap(config.values),
      });
    } else if (isInputObjectType(type)) {
      const config = type.toConfig();
      return new GraphQLInputObjectType({
        ...config,
        fields: () => sortInputFields(config.fields),
      });
    }
    throw new Error(`Unknown type: "${type}"`);
  }
}

function sortObjMap<T, R>(map: ObjMap<T>, sortValueFn?: T => R): ObjMap<R> {
  const sortedMap = Object.create(null);
  const sortedKeys = sortBy(Object.keys(map), x => x);
  for (const key of sortedKeys) {
    const value = map[key];
    sortedMap[key] = sortValueFn ? sortValueFn(value) : value;
  }
  return sortedMap;
}

function sortByName<T: { +name: string }>(array: $ReadOnlyArray<T>): Array<T> {
  return sortBy(array, obj => obj.name);
}

function sortBy<T>(array: $ReadOnlyArray<T>, mapToKey: T => string): Array<T> {
  return array.slice().sort((obj1, obj2) => {
    const key1 = mapToKey(obj1);
    const key2 = mapToKey(obj2);
    return key1.localeCompare(key2);
  });
}
<commit_msg>Remove excessive cache inside lexicographicSortSchema (#1681)<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow strict
 */

import objectValues from '../polyfills/objectValues';
import keyValMap from '../jsutils/keyValMap';
import type { ObjMap } from '../jsutils/ObjMap';
import { GraphQLSchema } from '../type/schema';
import { GraphQLDirective } from '../type/directives';
import type { GraphQLNamedType } from '../type/definition';
import {
  GraphQLObjectType,
  GraphQLInterfaceType,
  GraphQLUnionType,
  GraphQLEnumType,
  GraphQLInputObjectType,
  GraphQLList,
  GraphQLNonNull,
  isListType,
  isNonNullType,
  isScalarType,
  isObjectType,
  isInterfaceType,
  isUnionType,
  isEnumType,
  isInputObjectType,
} from '../type/definition';
import { isIntrospectionType } from '../type/introspection';

/**
 * Sort GraphQLSchema.
 */
export function lexicographicSortSchema(schema: GraphQLSchema): GraphQLSchema {
  const schemaConfig = schema.toConfig();
  const typeMap = keyValMap(
    sortByName(schemaConfig.types),
    type => type.name,
    sortNamedType,
  );

  return new GraphQLSchema({
    ...schemaConfig,
    types: objectValues(typeMap),
    directives: sortByName(schemaConfig.directives).map(sortDirective),
    query: replaceMaybeType(schemaConfig.query),
    mutation: replaceMaybeType(schemaConfig.mutation),
    subscription: replaceMaybeType(schemaConfig.subscription),
  });

  function replaceType(type) {
    if (isListType(type)) {
      return new GraphQLList(replaceType(type.ofType));
    } else if (isNonNullType(type)) {
      return new GraphQLNonNull(replaceType(type.ofType));
    }
    return replaceNamedType(type);
  }

  function replaceNamedType<T: GraphQLNamedType>(type: T): T {
    return ((typeMap[type.name]: any): T);
  }

  function replaceMaybeType(maybeType) {
    return maybeType && replaceNamedType(maybeType);
  }

  function sortDirective(directive) {
    const config = directive.toConfig();
    return new GraphQLDirective({
      ...config,
      locations: sortBy(config.locations, x => x),
      args: sortArgs(config.args),
    });
  }

  function sortArgs(args) {
    return sortObjMap(args, arg => ({
      ...arg,
      type: replaceType(arg.type),
    }));
  }

  function sortFields(fieldsMap) {
    return sortObjMap(fieldsMap, field => ({
      ...field,
      type: replaceType(field.type),
      args: sortArgs(field.args),
    }));
  }

  function sortInputFields(fieldsMap) {
    return sortObjMap(fieldsMap, field => ({
      ...field,
      type: replaceType(field.type),
    }));
  }

  function sortTypes<T: GraphQLNamedType>(arr: Array<T>): Array<T> {
    return sortByName(arr).map(replaceNamedType);
  }

  function sortNamedType(type) {
    if (isScalarType(type) || isIntrospectionType(type)) {
      return type;
    } else if (isObjectType(type)) {
      const config = type.toConfig();
      return new GraphQLObjectType({
        ...config,
        interfaces: () => sortTypes(config.interfaces),
        fields: () => sortFields(config.fields),
      });
    } else if (isInterfaceType(type)) {
      const config = type.toConfig();
      return new GraphQLInterfaceType({
        ...config,
        fields: () => sortFields(config.fields),
      });
    } else if (isUnionType(type)) {
      const config = type.toConfig();
      return new GraphQLUnionType({
        ...config,
        types: () => sortTypes(config.types),
      });
    } else if (isEnumType(type)) {
      const config = type.toConfig();
      return new GraphQLEnumType({
        ...config,
        values: sortObjMap(config.values),
      });
    } else if (isInputObjectType(type)) {
      const config = type.toConfig();
      return new GraphQLInputObjectType({
        ...config,
        fields: () => sortInputFields(config.fields),
      });
    }
    throw new Error(`Unknown type: "${type}"`);
  }
}

function sortObjMap<T, R>(map: ObjMap<T>, sortValueFn?: T => R): ObjMap<R> {
  const sortedMap = Object.create(null);
  const sortedKeys = sortBy(Object.keys(map), x => x);
  for (const key of sortedKeys) {
    const value = map[key];
    sortedMap[key] = sortValueFn ? sortValueFn(value) : value;
  }
  return sortedMap;
}

function sortByName<T: { +name: string }>(array: $ReadOnlyArray<T>): Array<T> {
  return sortBy(array, obj => obj.name);
}

function sortBy<T>(array: $ReadOnlyArray<T>, mapToKey: T => string): Array<T> {
  return array.slice().sort((obj1, obj2) => {
    const key1 = mapToKey(obj1);
    const key2 = mapToKey(obj2);
    return key1.localeCompare(key2);
  });
}
<|endoftext|>


<commit_before>const gulp = require('gulp')
const blok = require('gulp-blok')
const watch = require('gulp-watch')
const sass = require('gulp-sass')
const sassGlob = require('gulp-sass-glob')
const browserSync = require('browser-sync')
const source = require('vinyl-source-stream')
const webpack = require('webpack')
const gulpWebpack = require('gulp-webpack')
const reload = browserSync.reload
const config = require('./config.js')
const fs = require('fs')
const rename = require('gulp-rename')

if (config.blok.domain == 'INSERT_YOUR_DOMAIN') {
  config.blok.domain = 'ac0e600a.me.storyblok.com'
}

if (config.blok.themeId == 'INSERT_SPACE_ID') {
  config.blok.themeId = '40288'
}

gulp.task('deploy:dev', function () {
  return gulp.src('./views/**/*')
    .pipe(blok(config.blok))
})

gulp.task('deploy:live', function () {
  config.environment = 'live'

  return gulp.src('./views/**/*')
    .pipe(blok(config.blok))
})

gulp.task('styles:below', function () {
  return gulp.src('source/scss/below.scss')
    .pipe(sassGlob())
    .pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
    .pipe(gulp.dest('./views/assets/css/'))
    .pipe(browserSync.stream())
})

gulp.task('styles:above', function () {
  return gulp.src('source/scss/above.scss')
    .pipe(sassGlob())
    .pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
    .pipe(gulp.dest('./views/assets/css/'))
    .pipe(browserSync.stream())
    .pipe(rename('_above_fold_css.liquid'))
    .pipe(gulp.dest('./views/components/'))
})

gulp.task('scripts', function () {
  return gulp.src('source/js/scripts.js')
    .pipe(gulpWebpack({
      output: {
        filename: 'scripts.js',
      },
      module: {
        loaders: [{
          test: /\.js$/,
          loader: 'babel-loader'
        }]
      },
      plugins: [
        new webpack.optimize.UglifyJsPlugin({
          compress: {
            warnings: false,
          },
          output: {
            comments: false,
          }
        })
      ]
    }, webpack))
    .pipe(gulp.dest('views/assets/js'))
    .pipe(browserSync.stream())
})

gulp.task('browsersync', function () {
  browserSync({
    port: 4440,
    serveStatic: ['./views'],
    proxy: {
      target: 'http://' + config.blok.domain + '/_quickstart?quickstart=' + config.blok.quickstartToken,
      reqHeaders: function () {
        return {
          'accept-encoding': 'identity',
          'agent': false,
          'browsersyncblok': true,
          'storyblokenv': config.blok.environment
        }
      }
    },
    reloadDelay: 1000,
    notify: true,
    open: true,
    logLevel: 'silent'
  })

  gulp.watch('views/**/*.liquid').on('change', function (e) {
    if (e.path.indexOf('_above_fold_css.liquid') <= -1) {
      reload()
    }
  })
  gulp.watch(['source/scss/components/above/**/*.scss', 'source/scss/components/elements/**/*.scss'], ['styles:above'])
  gulp.watch('source/scss/components/below/**/*.scss', ['styles:below'])
  gulp.watch('source/js/**/*.js', ['scripts'])
})

gulp.task('default', ['styles:above', 'styles:below', 'scripts', 'browsersync'], function () {
  return watch('./views/**/*')
    .pipe(blok(config.blok))
})
<commit_msg>fixes style task<commit_after>const gulp = require('gulp')
const blok = require('gulp-blok')
const watch = require('gulp-watch')
const sass = require('gulp-sass')
const sassGlob = require('gulp-sass-glob')
const browserSync = require('browser-sync')
const source = require('vinyl-source-stream')
const webpack = require('webpack')
const gulpWebpack = require('gulp-webpack')
const reload = browserSync.reload
const config = require('./config.js')
const fs = require('fs')
const rename = require('gulp-rename')

if (config.blok.domain == 'INSERT_YOUR_DOMAIN') {
  config.blok.domain = 'ac0e600a.me.storyblok.com'
}

if (config.blok.themeId == 'INSERT_SPACE_ID') {
  config.blok.themeId = '40288'
}

gulp.task('deploy:dev', function () {
  return gulp.src('./views/**/*')
    .pipe(blok(config.blok))
})

gulp.task('deploy:live', function () {
  config.environment = 'live'

  return gulp.src('./views/**/*')
    .pipe(blok(config.blok))
})

gulp.task('styles:below', function () {
  return gulp.src('source/scss/below.scss')
    .pipe(sassGlob())
    .pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
    .pipe(gulp.dest('./views/assets/css/'))
    .pipe(browserSync.stream())
})

gulp.task('styles:above', function () {
  return gulp.src('source/scss/above.scss')
    .pipe(sassGlob())
    .pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
    .pipe(gulp.dest('./views/assets/css/'))
    .pipe(browserSync.stream())
    .pipe(rename('_above_fold_css.liquid'))
    .pipe(gulp.dest('./views/components/'))
})

gulp.task('scripts', function () {
  return gulp.src('source/js/scripts.js')
    .pipe(gulpWebpack({
      output: {
        filename: 'scripts.js',
      },
      module: {
        loaders: [{
          test: /\.js$/,
          loader: 'babel-loader'
        }]
      },
      plugins: [
        new webpack.optimize.UglifyJsPlugin({
          compress: {
            warnings: false,
          },
          output: {
            comments: false,
          }
        })
      ]
    }, webpack))
    .pipe(gulp.dest('views/assets/js'))
    .pipe(browserSync.stream())
})

gulp.task('browsersync', function () {
  browserSync({
    port: 4440,
    serveStatic: ['./views'],
    proxy: {
      target: 'http://' + config.blok.domain + '/_quickstart?quickstart=' + config.blok.quickstartToken,
      reqHeaders: function () {
        return {
          'accept-encoding': 'identity',
          'agent': false,
          'browsersyncblok': true,
          'storyblokenv': config.blok.environment
        }
      }
    },
    reloadDelay: 1000,
    notify: true,
    open: true,
    logLevel: 'silent'
  })

  gulp.watch('views/**/*.liquid').on('change', function (e) {
    if (e.path.indexOf('_above_fold_css.liquid') <= -1) {
      reload()
    }
  })

  gulp.watch(['source/scss/_variables.scss'], ['styles:above', 'styles:below'])
  gulp.watch(['source/scss/above.scss', 'source/scss/components/above/**/*.scss', 'source/scss/components/elements/**/*.scss'], ['styles:above'])
  gulp.watch(['source/scss/below.scss', 'source/scss/components/below/**/*.scss'], ['styles:below'])
  gulp.watch('source/js/**/*.js', ['scripts'])
})

gulp.task('default', ['styles:above', 'styles:below', 'scripts', 'browsersync'], function () {
  return watch('./views/**/*')
    .pipe(blok(config.blok))
})
<|endoftext|>


<commit_before>import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { propType } from 'graphql-anywhere'
import styled from 'styled-components'

import constants from 'v2/styles/constants'

import blockLightboxFragment from 'v2/components/BlockLightbox/fragments/blockLightbox'

import Box from 'v2/components/UI/Box'
import Title from 'v2/components/UI/Head/components/Title'
import BlockLightboxContentPane from 'v2/components/BlockLightbox/components/BlockLightboxContentPane'
import BlockLightboxMetadataPane from 'v2/components/BlockLightbox/components/BlockLightboxMetadataPane'

const Container = styled(Box).attrs({
  flexDirection: ['column', 'row', 'row'],
  height: ['unset', '100%', '100%'],
  display: ['block', 'flex', 'flex'],
})``

export default class BlockLightbox extends PureComponent {
  static propTypes = {
    block: propType(blockLightboxFragment).isRequired,
    context: PropTypes.oneOf(['MODAL', 'PAGE']),
    layout: PropTypes.oneOf(['DEFAULT', 'FULLSCREEN']),
    children: PropTypes.node,
  }

  static defaultProps = {
    layout: 'DEFAULT',
    context: 'PAGE',
    children: null,
  }

  render() {
    const { block, layout, context, children, ...rest } = this.props

    return (
      <Container {...rest}>
        {block.title && <Title>{block.title}</Title>}

        <BlockLightboxContentPane block={block} layout={layout}>
          {children}
        </BlockLightboxContentPane>

        {layout === 'DEFAULT' && (
          <BlockLightboxMetadataPane
            block={block}
            pt={context === 'MODAL' ? constants.topBarHeight : undefined}
          />
        )}
      </Container>
    )
  }
}
<commit_msg>Unescape block title<commit_after>import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { propType } from 'graphql-anywhere'
import styled from 'styled-components'
import { unescape } from 'underscore'

import constants from 'v2/styles/constants'

import blockLightboxFragment from 'v2/components/BlockLightbox/fragments/blockLightbox'

import Box from 'v2/components/UI/Box'
import Title from 'v2/components/UI/Head/components/Title'
import BlockLightboxContentPane from 'v2/components/BlockLightbox/components/BlockLightboxContentPane'
import BlockLightboxMetadataPane from 'v2/components/BlockLightbox/components/BlockLightboxMetadataPane'

const Container = styled(Box).attrs({
  flexDirection: ['column', 'row', 'row'],
  height: ['unset', '100%', '100%'],
  display: ['block', 'flex', 'flex'],
})``

export default class BlockLightbox extends PureComponent {
  static propTypes = {
    block: propType(blockLightboxFragment).isRequired,
    context: PropTypes.oneOf(['MODAL', 'PAGE']),
    layout: PropTypes.oneOf(['DEFAULT', 'FULLSCREEN']),
    children: PropTypes.node,
  }

  static defaultProps = {
    layout: 'DEFAULT',
    context: 'PAGE',
    children: null,
  }

  render() {
    const { block, layout, context, children, ...rest } = this.props

    return (
      <Container {...rest}>
        {block.title && <Title>{unescape(block.title)}</Title>}

        <BlockLightboxContentPane block={block} layout={layout}>
          {children}
        </BlockLightboxContentPane>

        {layout === 'DEFAULT' && (
          <BlockLightboxMetadataPane
            block={block}
            pt={context === 'MODAL' ? constants.topBarHeight : undefined}
          />
        )}
      </Container>
    )
  }
}
<|endoftext|>


<commit_before>/**
 * Created by admin on 4/21/2016.
 */
var recognition = new webkitSpeechRecognition();
recognition.interimResults = false;
recognition.onresult = function(event) {
    alert((event.results[0])[0].transcript);
    console.log(event)
}
recognition.lang = "en-GB";

recognition.start();<commit_msg>poprawka speech<commit_after>/**
 * Created by admin on 4/21/2016.
 */
/*var recognition = new webkitSpeechRecognition();
recognition.interimResults = false;
recognition.onresult = function(event) {
    alert((event.results[0])[0].transcript);
    console.log(event)
}
recognition.lang = "en-GB";

recognition.start();*/<|endoftext|>


<commit_before><commit_msg>Fixed Travis errors<commit_after><|endoftext|>


<commit_before>const AWS = require("aws-sdk");

function sendSnsEvent(topicArn, subject, message) {
    return new Promise((resolve, reject) => {
        const sns = new AWS.SNS();

        sns.publish({
            Message: JSON.stringify(message),
            Subject: subject,
            TopicArn: topicArn
        }, err => {
            if(err) {
                reject(`Failed to send SNS ${err}`);
            }

            resolve();
        });
    });
}

module.exports.handleRequest = (event, context, callback) => {
    const result = JSON.parse(event.Records[0].Sns.Message);
    const snsFailureTopic = process.env.failureSnsTopic;
    const snsCompleteTopic = process.env.completeSnsTopic;

    const accountId = process.env.accountId;
    const region = process.env.region;

    const snsFailureTopicArn = `arn:aws:sns:${region}:${accountId}:${snsFailureTopic}`;
    const snsCompleteTopicArn = `arn:aws:sns:${region}:${accountId}:${snsCompleteTopic}`;

    sendSnsEvent(snsCompleteTopicArn, `SITE RESULT: ${result.url}`, result)
      .then(() => {
          if(result.success) {
              console.log('Site monitor ok, nothing to do');
              return new Promise(resolve => resolve());
          }

          console.log('Site monitor fail, sending to failure SNS');
          return sendSnsEvent(snsFailureTopicArn, `SITE FAIL: ${result.url}`, result.errorMessage || result);
      })
      .then(() => callback())
      .catch(callback);
};
<commit_msg>debug<commit_after>const AWS = require("aws-sdk");

function sendSnsEvent(topicArn, subject, message) {
    return new Promise((resolve, reject) => {
        const sns = new AWS.SNS();

        sns.publish({
            Message: JSON.stringify(message),
            Subject: subject,
            TopicArn: topicArn
        }, err => {
            if(err) {
                reject(`Failed to send SNS ${err}`);
            }

            resolve();
        });
    });
}

module.exports.handleRequest = (event, context, callback) => {
    const result = JSON.parse(event.Records[0].Sns.Message);
    const snsFailureTopic = process.env.failureSnsTopic;
    const snsCompleteTopic = process.env.completeSnsTopic;

    const accountId = process.env.accountId;
    const region = process.env.region;

    const snsFailureTopicArn = `arn:aws:sns:${region}:${accountId}:${snsFailureTopic}`;
    const snsCompleteTopicArn = `arn:aws:sns:${region}:${accountId}:${snsCompleteTopic}`;

    const topicsToSendTo = [
        snsCompleteTopicArn,
        ...(result.success ? [] : [snsFailureTopicArn])
    ];

    console.log(`Handling request for ${result.url}, success: ${result.success}, sendingToTopics: ${topicsToSendTo.join(', ')}`);

    sendSnsEvent(snsCompleteTopicArn, `SITE RESULT: ${result.url}`, result)
      .then(() => {
          if(result.success) {
              console.log('Site monitor ok, nothing to do');
              return new Promise(resolve => resolve());
          }

          console.log('Site monitor fail, sending to failure SNS');
          return sendSnsEvent(snsFailureTopicArn, `SITE FAIL: ${result.url}`, result.errorMessage || result);
      })
      .then(() => callback())
      .catch(callback);
};
<|endoftext|>


<commit_before>/**
 * Created by windy on 2017/3/13.
 * 数值微调器
 */
BI.NumberEditor = BI.inherit(BI.Widget, {
    _defaultConfig: function () {
        return BI.extend(BI.NumberEditor.superclass._defaultConfig.apply(this, arguments), {
            baseCls: "bi-number-editor bi-border bi-focus-shadow",
            validationChecker: function () {
                return true;
            },
            valueFormatter: function (v) {
                return v;
            },
            value: 0,
            allowBlank: false,
            errorText: "",
            step: 1
        });
    },

    _init: function () {
        BI.NumberEditor.superclass._init.apply(this, arguments);
        var self = this, o = this.options;
        this.editor = BI.createWidget({
            type: "bi.sign_editor",
            height: o.height,
            allowBlank: o.allowBlank,
            value: o.valueFormatter(o.value),
            validationChecker: o.validationChecker,
            errorText: o.errorText
        });
        this.editor.on(BI.TextEditor.EVENT_CHANGE, function () {
            o.value = BI.parseFloat(this.getValue());
            self.fireEvent(BI.NumberEditor.EVENT_CHANGE);
        });
        this.editor.on(BI.TextEditor.EVENT_CONFIRM, function () {
            this.setValue(BI.parseFloat(this.getValue()));
            self.fireEvent(BI.NumberEditor.EVENT_CONFIRM);
        });
        this.topBtn = BI.createWidget({
            type: "bi.icon_button",
            forceNotSelected: true,
            trigger: "lclick,",
            cls: "add-up-font top-button bi-border-left bi-list-item-active2 icon-size-12"
        });
        this.topBtn.on(BI.IconButton.EVENT_CHANGE, function () {
            self._finetuning(o.step);
            self.fireEvent(BI.NumberEditor.EVENT_CHANGE);
            self.fireEvent(BI.NumberEditor.EVENT_CONFIRM);
        });
        this.bottomBtn = BI.createWidget({
            type: "bi.icon_button",
            trigger: "lclick,",
            forceNotSelected: true,
            cls: "minus-down-font bottom-button bi-border-left bi-list-item-active2 icon-size-12"
        });
        this.bottomBtn.on(BI.IconButton.EVENT_CHANGE, function () {
            self._finetuning(-o.step);
            self.fireEvent(BI.NumberEditor.EVENT_CHANGE);
            self.fireEvent(BI.NumberEditor.EVENT_CONFIRM);
        });
        BI.createWidget({
            type: "bi.htape",
            element: this,
            items: [this.editor, {
                el: {
                    type: "bi.grid",
                    columns: 1,
                    rows: 2,
                    items: [{
                        column: 0,
                        row: 0,
                        el: this.topBtn
                    }, {
                        column: 0,
                        row: 1,
                        el: this.bottomBtn
                    }]
                },
                width: 23
            }]
        });
    },

    focus: function () {
        this.editor.focus();
    },

    // 微调
    _finetuning: function (add) {
        var v = BI.parseFloat(this.getValue());
        this.setValue(v.add(add));
    },

    setUpEnable: function (v) {
        this.topBtn.setEnable(!!v);
    },

    setDownEnable: function (v) {
        this.bottomBtn.setEnable(!!v);
    },

    getValue: function () {
        return this.options.value;
    },

    setValue: function (v) {
        var o = this.options;
        o.value = v;
        this.editor.setValue(o.valueFormatter(v));
    }

});
BI.NumberEditor.EVENT_CONFIRM = "EVENT_CONFIRM";
BI.NumberEditor.EVENT_CHANGE = "EVENT_CHANGE";
BI.shortcut("bi.number_editor", BI.NumberEditor);<commit_msg>update<commit_after>/**
 * Created by windy on 2017/3/13.
 * 数值微调器
 */
BI.NumberEditor = BI.inherit(BI.Widget, {
    _defaultConfig: function () {
        return BI.extend(BI.NumberEditor.superclass._defaultConfig.apply(this, arguments), {
            baseCls: "bi-number-editor bi-border bi-focus-shadow",
            validationChecker: function () {
                return true;
            },
            valueFormatter: function (v) {
                return v;
            },
            value: 0,
            allowBlank: false,
            errorText: "",
            step: 1
        });
    },

    _init: function () {
        BI.NumberEditor.superclass._init.apply(this, arguments);
        var self = this, o = this.options;
        this.editor = BI.createWidget({
            type: "bi.sign_editor",
            height: o.height,
            allowBlank: o.allowBlank,
            value: o.valueFormatter(o.value),
            validationChecker: o.validationChecker,
            errorText: o.errorText
        });
        this.editor.on(BI.TextEditor.EVENT_CHANGE, function () {
            o.value = BI.parseFloat(this.getValue());
            self.fireEvent(BI.NumberEditor.EVENT_CHANGE);
        });
        this.editor.on(BI.TextEditor.EVENT_CONFIRM, function () {
            this.setValue(BI.parseFloat(this.getValue()));
            self.fireEvent(BI.NumberEditor.EVENT_CONFIRM);
        });
        this.topBtn = BI.createWidget({
            type: "bi.icon_button",
            forceNotSelected: true,
            trigger: "lclick,",
            cls: "add-up-font top-button bi-border-left bi-list-item-active2 icon-size-12"
        });
        this.topBtn.on(BI.IconButton.EVENT_CHANGE, function () {
            self._finetuning(o.step);
            self.fireEvent(BI.NumberEditor.EVENT_CHANGE);
            self.fireEvent(BI.NumberEditor.EVENT_CONFIRM);
        });
        this.bottomBtn = BI.createWidget({
            type: "bi.icon_button",
            trigger: "lclick,",
            forceNotSelected: true,
            cls: "minus-down-font bottom-button bi-border-left bi-list-item-active2 icon-size-12"
        });
        this.bottomBtn.on(BI.IconButton.EVENT_CHANGE, function () {
            self._finetuning(-o.step);
            self.fireEvent(BI.NumberEditor.EVENT_CHANGE);
            self.fireEvent(BI.NumberEditor.EVENT_CONFIRM);
        });
        BI.createWidget({
            type: "bi.htape",
            element: this,
            items: [this.editor, {
                el: {
                    type: "bi.grid",
                    columns: 1,
                    rows: 2,
                    items: [{
                        column: 0,
                        row: 0,
                        el: this.topBtn
                    }, {
                        column: 0,
                        row: 1,
                        el: this.bottomBtn
                    }]
                },
                width: 23
            }]
        });
    },

    focus: function () {
        this.editor.focus();
    },

    // 微调
    _finetuning: function (add) {
        var v = BI.parseFloat(this.getValue());
        this.setValue(BI.add(v, add));
    },

    setUpEnable: function (v) {
        this.topBtn.setEnable(!!v);
    },

    setDownEnable: function (v) {
        this.bottomBtn.setEnable(!!v);
    },

    getValue: function () {
        return this.options.value;
    },

    setValue: function (v) {
        var o = this.options;
        o.value = v;
        this.editor.setValue(o.valueFormatter(v));
    }

});
BI.NumberEditor.EVENT_CONFIRM = "EVENT_CONFIRM";
BI.NumberEditor.EVENT_CHANGE = "EVENT_CHANGE";
BI.shortcut("bi.number_editor", BI.NumberEditor);<|endoftext|>


<commit_before>function SplashScreenAssistant() {
	/* this is the creator function for your scene assistant object. It will be passed all the
	   additional parameters (after the scene name) that were passed to pushScene. The reference
	   to the scene controller (this.controller) has not be established yet, so any initialization
	   that needs the scene controller should be done in the setup function below.

	   Also declaring variables here.

	   */

	this.appVersion = "1.0.0";
	this.vendor = "Us";
	this.appName = "My App";
}

SplashScreenAssistant.prototype.setup = function() {
	/* this function is for setup tasks that have to happen when the scene is first created */

	/* use Mojo.View.render to render view templates and add them to the scene, if needed. */

	/* setup widgets here */

	/* add event handlers to listen to events from widgets */
	Mojo.Log.info("Splash Screen Loaded!");

	// This code is in the setup function
	// Reading version number from appinfo.json file
	var file = Mojo.appPath + 'appinfo.json';
	Mojo.Log.info("The file to read is: %s", file);
	var fileAJAX = new Ajax.Request(file, {
		method: 'get',
		parameters: '',
		evalJSON: 'force',
		onSuccess: this.fileReadCallback.bind(this),
		onFailure: this.fileReadErrorCallback.bind(this)
		});
}

SplashScreenAssistant.prototype.activate = function(event) {
	/* put in event handlers here that should only be in effect when this scene is active. For
	   example, key handlers that are observing the document */
}

SplashScreenAssistant.prototype.deactivate = function(event) {
	/* remove any event handlers you added in activate and do any other cleanup that should happen before
	   this scene is popped or another scene is pushed on top */
}

SplashScreenAssistant.prototype.cleanup = function(event) {
	/* this function should do any cleanup needed before the scene is destroyed as
	   a result of being popped off the scene stack */

}

SplashScreenAssistant.prototype.fileReadCallback = function(transport) {
   this.appVersion = transport.responseJSON.version;	// Get app version
   this.vendor = transport.responseJSON.vendor;			// Get who made app
   this.appName = transport.responseJSON.title;			// Get program title

   // Get tags $(); e.g. $("appName") get tags named: "appName"
   $("splash_screen_appName").insert(this.appName);
   $("splash_screen_vendor").insert(this.vendor);
   $("splash_screen_appVersion").insert(this.appVersion);

   Mojo.Log.info("Starting timer!");
   this.nextScreen.bind(this).delay(5);
};

SplashScreenAssistant.prototype.fileReadErrorCallback = function(error){
	Mojo.Log.error("Was unable to read the file. Error message is as follows: %s", error);
}

SplashScreenAssistant.prototype.nextScreen = function() {
	this.controller.stageController.popScene("splash-screen");	// Unload the splash-screen from memory
	this.controller.stageController.pushScene("home-screen");
}
<commit_msg>Do not allow the menu to be pressed during startup.<commit_after>function SplashScreenAssistant() {
	/* this is the creator function for your scene assistant object. It will be passed all the
	   additional parameters (after the scene name) that were passed to pushScene. The reference
	   to the scene controller (this.controller) has not be established yet, so any initialization
	   that needs the scene controller should be done in the setup function below.

	   Also declaring variables here.

	   */

	this.appVersion = "1.0.0";
	this.vendor = "Us";
	this.appName = "My App";
}

SplashScreenAssistant.prototype.setup = function() {
	/* this function is for setup tasks that have to happen when the scene is first created */

	/* use Mojo.View.render to render view templates and add them to the scene, if needed. */

	/* setup widgets here */
	/* Create the Application Menu @ the top left of the screen */
	this.controller.setupWidget(Mojo.Menu.appMenu,
								{omitDefaultItems: true},
								undefined);

	/* add event handlers to listen to events from widgets */
	Mojo.Log.info("Splash Screen Loaded!");

	// This code is in the setup function
	// Reading version number from appinfo.json file
	var file = Mojo.appPath + 'appinfo.json';
	Mojo.Log.info("The file to read is: %s", file);
	var fileAJAX = new Ajax.Request(file, {
		method: 'get',
		parameters: '',
		evalJSON: 'force',
		onSuccess: this.fileReadCallback.bind(this),
		onFailure: this.fileReadErrorCallback.bind(this)
		});
}

SplashScreenAssistant.prototype.activate = function(event) {
	/* put in event handlers here that should only be in effect when this scene is active. For
	   example, key handlers that are observing the document */
}

SplashScreenAssistant.prototype.deactivate = function(event) {
	/* remove any event handlers you added in activate and do any other cleanup that should happen before
	   this scene is popped or another scene is pushed on top */
}

SplashScreenAssistant.prototype.cleanup = function(event) {
	/* this function should do any cleanup needed before the scene is destroyed as
	   a result of being popped off the scene stack */

}

SplashScreenAssistant.prototype.fileReadCallback = function(transport) {
   this.appVersion = transport.responseJSON.version;	// Get app version
   this.vendor = transport.responseJSON.vendor;			// Get who made app
   this.appName = transport.responseJSON.title;			// Get program title

   // Get tags $(); e.g. $("appName") get tags named: "appName"
   $("splash_screen_appName").insert(this.appName);
   $("splash_screen_vendor").insert(this.vendor);
   $("splash_screen_appVersion").insert(this.appVersion);

   Mojo.Log.info("Starting timer!");
   this.nextScreen.bind(this).delay(5);
};

SplashScreenAssistant.prototype.fileReadErrorCallback = function(error){
	Mojo.Log.error("Was unable to read the file. Error message is as follows: %s", error);
}

SplashScreenAssistant.prototype.nextScreen = function() {
	this.controller.stageController.popScene("splash-screen");	// Unload the splash-screen from memory
	this.controller.stageController.pushScene("home-screen");
}
<|endoftext|>


<commit_before>define( ["app", "scribbler"], function( app, scribbler ) {
  var container = document.getElementById( 'buttons-container' );
  var buttons = {
    "Toggle auto-rotate": function() {
      app.spin = !app.spin;
    },
    "Toggle carving": function() {
      app.carve = !app.carve;
      app.reset();
    },
    "Load depth image": function() {
      scribbler.clear();
      scribbler.loadImage( "/js/textures/depth.png" );
    },
    "Clear canvas": function() {
      scribbler.clear();
    }
  };

  for ( var b in buttons ) {
    var button = document.createElement( 'button' );
    button.innerHTML = b;
    button.addEventListener( "click", buttons[b] );
    container.appendChild( button );
  }
} );
<commit_msg>Use correct path for depth image<commit_after>define( ["app", "scribbler"], function( app, scribbler ) {
  var container = document.getElementById( 'buttons-container' );
  var buttons = {
    "Toggle auto-rotate": function() {
      app.spin = !app.spin;
    },
    "Toggle carving": function() {
      app.carve = !app.carve;
      app.reset();
    },
    "Load depth image": function() {
      scribbler.clear();
      scribbler.loadImage( "js/textures/depth.png" );
    },
    "Clear canvas": function() {
      scribbler.clear();
    }
  };

  for ( var b in buttons ) {
    var button = document.createElement( 'button' );
    button.innerHTML = b;
    button.addEventListener( "click", buttons[b] );
    container.appendChild( button );
  }
} );
<|endoftext|>


<commit_before>// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
angular.module('starter', [ 'ionic'])

.run(function($ionicPlatform , $rootScope, $http, webService) {
      $ionicPlatform.ready(function() {

            // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
            // for form inputs)
            if(window.cordova && window.cordova.plugins.Keyboard) {
              cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
            }
            if(window.StatusBar) {
              StatusBar.styleDefault();
            }

            var db = new PouchDB('callersDB');

            //////// phone call trap works anywhere in the code, but must be insdie $ionicPlatform.ready(...)
            PhoneCallTrap.onCall(function(state) {

                // console.log('logging state: ..');
                // console.log(Object.keys(state));
                // console.log(state.state);
                // console.log(state.number);

                switch (state.state) {
                    case "RINGING":
                        alert("Phone is ringing: " + state.number);

                        try {

                            db.on('error', function (err) { console.log('debug error: ' + err); });

                            // incoming_number = state.number

                            params = {
                                incoming_number : state.number,
                                webService      : webService,
                                http            : $http
                            }

                            db.query(function  (doc) {

                                console.log('INITIALIZING PouchDB');

                                // Check if we have the incoming number in the database
                                if(doc.phone == params.incoming_number){

                                    console.log('Found the document: ' + doc._id);

                                    /////////  Couldn't make the factory working inside the query
                                    ////////   gives me error everytime
                                    // params.webService.get()
                                    //     .success(function  (data, status, headers, config) {
                                    //         console.log('loggging web service: ');
                                    //         console.log('Got response from server');
                                    //         console.log(status);
                                    //         // console.log(response);
                                    //     })
                                    //     .error(function  (data, status, headers, config) {
                                    //         console.log('Error on Webservice');
                                    //         console.log(status);
                                    //     })

                                    console.log('Invoking a web service .. ');
                                    var promise = params.http.get('http://localhost:1337/users')

                                    promise
                                        .success(function  (data, status, headers, config) {
                                            console.log('loggging web service: ');
                                            console.log('Got response from server');
                                            console.log(status);
                                            // console.log(response);
                                        })
                                        .error(function  (data, status, headers, config) {
                                            console.log('Error on Webservice');
                                            console.log(status);
                                        })

                                    }
                            });

                        } catch(e) {
                            console.log('PouchDB Error caught: ' + e);
                        }

                        break;
                    case "OFFHOOK":
                        console.log("Phone is off-hook");
                        break;

                    case "IDLE":
                        console.log("Phone is idle");
                        break;
                    }
            });

      });

})

.controller('myController',['$scope','$ionicPopup','webService',function ( $scope , $ionicPopup , webService) {

    $scope.data = {
        showDelete : false,
        showReorder : false,
        listCanSwipe : true,
    };

    var db = new PouchDB('callersDB');

    db.allDocs({
                include_docs: true,
                attachments: true
            }).then(function (result) {
                console.log('Getting all fields');

                $scope.$apply(function  () {
                    $scope.$broadcast('getAll',result.rows)
                    console.log('Broadcating');
                    // $scope .test = 'test value'
                });

            }).catch(function (err) {
              console.log('Error' + err);
            });

    $scope.$on('getAll' , function(event,items) {
        console.log('ITEMS POPULATED TYPE AND VALUE');
        console.log(items);
        $scope.items = items
    });

    $scope.$on('updateContacts' , function(event,items) {
        console.log('Contacts update');
        console.log(items);
        $scope.items = items
    });

    $scope.removeContact = function (item) {

        console.log('Incoming value: ' + item);
        console.log(Object.keys(item)); //["id", "key", "value", "doc", "$$hashKey"]

        console.log(item.id);
        console.log(item.key);
        console.log(item.doc.phone);

        db.get(item.id).then(function  (element) {
            console.log('Removing .. ' + element);
            console.log(Object.keys(element));
            db.remove(element);
        }).then(function  (result) {
            console.log('Removed with DB response: ' + result);
        }).catch(function  (err) {
            console.error('Error on removing contact: ' + err);
        })

       //     db.remove(entry.doc._id , entry.doc._rev , function  (entry){
       //         //{"status":404,"name":"not_found","message":"missing"}

    }

    $scope.addContact = function  () {

            $scope.user_input = {};

            $ionicPopup.show({
                  title: 'Data Entry',
                  templateUrl: 'inputForm.html',
                  subTitle: 'Please enter user Data',
                  scope: $scope,

                  buttons: [
                      {
                        text: '<b>Save</b>',
                        type: 'button-positive',
                        onTap: function(e) {
                          if ($scope.user_input){
                              var user_input = $scope.user_input

                              db.put( {_id:user_input.name , phone: user_input.phone}).then( function (item) {
                                              console.log('A document inserted. ');

                                              console.log('a new item inserted: ' + item);

                                              // only id and revision are returned from a put/post operation
                                              // either we manually add the values we want to show in the list
                                              // or, make a get operation from DB to retreive all the fields
                                              // we want --> I'll go for the first
                                              item.doc = {
                                                            phone : user_input.phone,
                                                            _id   : item.id,
                                                         }

                                              // We have to broadcase it inside an apply service,
                                              // that's because we are inside an async operation
                                              $scope.$apply(function () {
                                                  $scope.items.push(item)
                                                  $scope.$broadcast('updateContacts',$scope.items)
                                              })
                                          }).catch(function (err) {
                                            console.log('Error on Puch: ' , err);
                                          })
                          }
                      } // End of "onTap"
                      },

                      { text: 'Cancel',
                        type: 'button-assertive'
                      },
                   ]
            })
            .then(function(res) {
              console.log('Popup window result: ',res);
            });
    };

}])

.factory('webService',['$http', '$q', function ($http, $q) {
    console.log('Calling a webserive from factory: ');

    req = {
         method: 'GET',
         url: 'http://www.google.com',
         headers: {
             'Access-Control-Allow-Origin' : '*',
  			 'Access-Control-Allow-Methods' : 'POST, GET, OPTIONS, PUT',
            //  'Content-Type': 'application/json',
			//  'Accept': 'application/json'
         }
         //data: { test: 'test' }
        }
    var myFactory = {}
    myFactory.get = function  () {
        // return $http(req)
        return $http.get('http://www.google.com')
    }
    return myFactory

    // return $http(req)

    // console.log('Google Returend ..' + returned.$$state);
    // console.log('Google Returend ..' + returned.success);
    // console.log('Google Returend ..' + returned.error);
    // return returned
}])
<commit_msg>Adding webservice, addDevice functionality for add device button on the interface, and, trapping the call on application pause<commit_after>// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
angular.module('starter', [ 'ionic'])

.run(function($ionicPlatform , $rootScope, $http, webService) {
      $ionicPlatform.ready(function() {

            // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
            // for form inputs)
            if(window.cordova && window.cordova.plugins.Keyboard) {
              cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
            }
            if(window.StatusBar) {
              StatusBar.styleDefault();
            }

            var db = new PouchDB('callersDB');

            //////// phone call trap works anywhere in the code, but must be insdie $ionicPlatform.ready(...)
            PhoneCallTrap.onCall(function(state) {

                switch (state.state) {
                    case "RINGING":
                        alert("Phone is ringing: " + state.number);

                        try {
                            // Event handler on any database error
                            db.on('error', function (err) { console.log('debug error: ' + err); });

                            params = {
                                incoming_number : state.number,
                                webService      : webService,
                                http            : $http
                            }

                            db.query(function  (doc) {

                                console.log('INITIALIZING PouchDB');

                                // Check if we have the incoming number in the database
                                if(doc.phone == params.incoming_number){

                                    console.log('Found the document: ' + doc._id);

                                    /// works
                                    params.webService.get()
                                        .success(function  (data, status, headers, config) {
                                            console.log('Got response from server');
                                            console.log(data);
                                            console.log(status);

                                        })
                                        .error(function  (data, status, headers, config) {
                                            console.log('Error on Webservice');
                                            console.log(data);
                                            console.log(status);
                                        })

                                    /// works
                                    // var promise = params.http.get('http://192.168.0.3:1337/users')
                                    //
                                    // promise
                                    //     .success(function  (data, status, headers, config) {
                                    //         console.log('loggging web service: ');
                                    //         console.log('Got response from server');
                                    //         console.log(status);
                                    //         // console.log(response);
                                    //     })
                                    //     .error(function  (data, status, headers, config) {
                                    //         console.log('Error on Webservice');
                                    //         console.log(status); // 0 for error, 200 for success
                                    //     })

                                    }
                            });

                        } catch(e) {
                            console.log('PouchDB Error caught: ' + e);
                        }

                        break;
                    case "OFFHOOK":
                        console.log("Phone is off-hook");
                        break;

                    case "IDLE":
                        console.log("Phone is idle");
                        break;
                    }
            });

      });

      $ionicPlatform.on('pause', function() {
                 alert("App Is Paused");

                 var db = new PouchDB('callersDB');

                 //////// phone call trap works anywhere in the code, but must be insdie $ionicPlatform.ready(...)
                 PhoneCallTrap.onCall(function(state) {

                     switch (state.state) {
                         case "RINGING":
                             alert("Phone is ringing: " + state.number);

                             try {
                                 // Event handler on any database error
                                 db.on('error', function (err) { console.log('debug error: ' + err); });

                                 params = {
                                     incoming_number : state.number,
                                     webService      : webService,
                                     http            : $http
                                 }

                                 db.query(function  (doc) {

                                     console.log('INITIALIZING PouchDB');

                                     // Check if we have the incoming number in the database
                                     if(doc.phone == params.incoming_number){

                                         console.log('Found the document: ' + doc._id);

                                         /// works
                                         params.webService.get()
                                             .success(function  (data, status, headers, config) {
                                                 console.log('Got response from server');
                                                 console.log(data);
                                                 console.log(status);

                                             })
                                             .error(function  (data, status, headers, config) {
                                                 console.log('Error on Webservice');
                                                 console.log(data);
                                                 console.log(status);
                                             })

                                         /// works
                                         // var promise = params.http.get('http://192.168.0.3:1337/users')
                                         //
                                         // promise
                                         //     .success(function  (data, status, headers, config) {
                                         //         console.log('loggging web service: ');
                                         //         console.log('Got response from server');
                                         //         console.log(status);
                                         //         // console.log(response);
                                         //     })
                                         //     .error(function  (data, status, headers, config) {
                                         //         console.log('Error on Webservice');
                                         //         console.log(status); // 0 for error, 200 for success
                                         //     })

                                         }
                                 });

                             } catch(e) {
                                 console.log('PouchDB Error caught: ' + e);
                             }

                             break;
                         case "OFFHOOK":
                             console.log("Phone is off-hook");
                             break;

                         case "IDLE":
                             console.log("Phone is idle");
                             break;
                         }
                 });

              });

})

.controller('myController',['$scope','$ionicPopup','webService',function ( $scope , $ionicPopup , webService) {

    $scope.data = {
        showDelete : false,
        showReorder : false,
        listCanSwipe : true,
    };

    var db = new PouchDB('callersDB');

    db.allDocs({
                include_docs: true,
                attachments: true
            }).then(function (result) {
                console.log('Getting all fields');

                $scope.$apply(function  () {
                    $scope.$broadcast('getAll',result.rows)
                    console.log('Broadcating');
                    // $scope .test = 'test value'
                });

            }).catch(function (err) {
              console.log('Error' + err);
            });

    $scope.$on('getAll' , function(event,items) {
        console.log('ITEMS POPULATED TYPE AND VALUE');
        console.log(items);
        $scope.items = items
    });

    $scope.$on('updateContacts' , function(event,items) {
        console.log('Contacts update');
        console.log(items);
        $scope.items = items
    });

    webService.get()
        .success(function  (data, status, headers, config) {
            console.log('Got response from server');

        })
        .error(function  (data, status, headers, config) {
            console.log('Error on Webservice');
            console.log(data);
            console.log(status);
        })

    $scope.removeContact = function (item) {

        console.log('Incoming value: ' + item);
        console.log(Object.keys(item)); //["id", "key", "value", "doc", "$$hashKey"]

        console.log(item.id);
        console.log(item.key);
        console.log(item.doc.phone);

        db.get(item.id).then(function  (element) {
            console.log('Removing .. ' + element);
            console.log(Object.keys(element));
            db.remove(element);
        }).then(function  (result) {
            console.log('Removed with DB response: ' + result);
        }).catch(function  (err) {
            console.error('Error on removing contact: ' + err);
        })

       //     db.remove(entry.doc._id , entry.doc._rev , function  (entry){
       //         //{"status":404,"name":"not_found","message":"missing"}

    }

    $scope.addContact = function  () {

            $scope.user_input = {};

            $ionicPopup.show({
                  title: 'Data Entry',
                  templateUrl: 'inputForm.html',
                  subTitle: 'Please enter user Data',
                  scope: $scope,

                  buttons: [
                      {
                        text: '<b>Save</b>',
                        type: 'button-positive',
                        onTap: function(e) {
                          if ($scope.user_input){
                              var user_input = $scope.user_input

                              db.put( {_id:user_input.name , phone: user_input.phone}).then( function (item) {
                                              console.log('A document inserted. ');

                                              console.log('a new item inserted: ' + item);

                                              // only id and revision are returned from a put/post operation
                                              // either we manually add the values we want to show in the list
                                              // or, make a get operation from DB to retreive all the fields
                                              // we want --> I'll go for the first
                                              item.doc = {
                                                            phone : user_input.phone,
                                                            _id   : item.id,
                                                         }

                                              // We have to broadcase it inside an apply service,
                                              // that's because we are inside an async operation
                                              $scope.$apply(function () {
                                                  $scope.items.push(item)
                                                  $scope.$broadcast('updateContacts',$scope.items)
                                              })
                                          }).catch(function (err) {
                                            console.log('Error on Puch: ' , err);
                                          })
                          }
                      } // End of "onTap"
                      },

                      { text: 'Cancel',
                        type: 'button-assertive'
                      },
                   ]
            })
            .then(function(res) {
              console.log('Popup window result: ',res);
            });
    };

    $scope.addDevice = function  () {

        $scope.device = {};

        $ionicPopup.show({
            title    : 'Raspberry Pi Device',
            //templateUrl : 'deviceIP.html',
            template : '<input type="text" placeholder="192.168.0.3" ng-model="device.ip">',
            subTitle : "Enter the IP address",
            scope    : $scope,

            buttons : [
                {
                    text : "<b>Save</b>",
                    type : "button-calm",
                    onTap: function  (event) {

                        var db = new PouchDB('DeviceDB');

                        db.get('deviceIp',function  (err , doc) {
                            if(!err){
                                db.put({
                                    _id :'deviceIp',
                                    _rev: doc._rev,  // must be added in updates
                                    ip  : $scope.device.ip
                                },function  (error , response) {
                                    if(! error){
                                        console.log('device ip insert/update is done.');
                                        console.log(response);
                                    } else {
                                        console.log('Devicd error: ' + error);
                                    }
                                })
                            } else {
                                console.log('Cant get an element from DB: ' + err);
                                console.log('putting a value in device IP ...');
                                db.put({
                                    _id :'deviceIp',
                                    ip  : $scope.device.ip
                                },function  (err,response) {
                                    if(!err){
                                        console.log('successfully put document ..' + response);
                                    } else {
                                        console.log('Problem putting a document .. ');
                                    }
                                })
                            }
                        })

                    },
                },
                {
                    text : 'Cancel',
                    type : 'button-royal',
                }]

        }).then(function(res) {
          console.log('Popup window result: ',res);
        });
    }

}])

.factory('webService',['$http', '$q', function ($http, $q) {

    console.log('Calling a webserive from factory: ');
    console.log('Getting device IP from DB, DeviceDB');

    var db = new PouchDB('DeviceDB');

    // Default values if not filled by user from popup menu
    var myFactory = {}
    var ip = '192.168.0.3'
    var port = '1337'
    var location = '/'

    db.get('deviceIp',function  (err , doc) {
        if(!err){
            console.log('Got a device IP');
            console.log(doc);
            console.log(doc._id);
            ip = doc.ip
        } else {
            console.log('Cant get IP address from DeviceDB');
        }
    })

    var URL = 'http://' + ip + ':' +port + location

    req = {
         method: 'GET',
         url: URL,
         headers: {
             'Access-Control-Allow-Origin' : '*',
  			 'Access-Control-Allow-Methods' : 'POST, GET, OPTIONS, PUT',
            //  'Content-Type': 'application/json',
			//  'Accept': 'application/json'
         }
         //data: { test: 'test' }
        }

    myFactory.get = function  () {
        // return $http(req)
        return $http.get(URL)
    }
    return myFactory
}])
<|endoftext|>


<commit_before>'use strict';

/* global cordova */

define(function(require) {
    var PositionRecorder = require('./position-recorder');
    var positionUtils = require('./position-utils');
    var records = require('records');

    var SESSION_PREFIX = 'track-';

    /**
     * Extend a geoJSON object as a record and wrap it in an annotation
     *
     * @param geoJSON {Object} a geoJSON object
     * @param editorId {String} an editor id
     * @param groupId {String} a group id
     * @param name {String} a record name
     * @returns {Object} an annotation
     */
    var geoJSONAsAnnotation = function(geoJSON, editorId, groupId, name) {
        var record;
        var annotation;

        // Add the mandatory properties for the record
        record = geoJSON;
        record.properties = record.properties || {};
        record.name = name;
        record.properties.editor = editorId;
        record.properties.fields = [];

        // Wrap the record as an annotation
        annotation =  {
            record: geoJSON,
            type: editorId,
            isSynced: false,
            editorGroup: groupId
        };

        return annotation;
    };

    /**
     * The position recorders are stored using a combined key groupId plus editorId
     * this is a helper function to store them under that scheme.
     * @returns {Object} exporting the get, getAll, put and remove functions
     */
    var PositionRecorders = function() {
        var recorders = {};

        var makeId = function(editorId, groupId) {
            return groupId + '#' + editorId;
        };

        /**
         * Returns the list of recorders
         * @returns {Object} list of {PositionRecorder} sessions
         */
        var getAll = function() {
            return recorders;
        };

        /**
         * Get the position recorder stored in the combined keys
         * @param editorId {String} an editor id
         * @param groupId {String} a group id
         * @returns {PositionRecorder} a position recorder
         */
        var get = function(editorId, groupId) {
            return recorders[makeId(editorId, groupId)];
        };

        /**
         * Put a position recorder in the combined keys
         * @param recorder
         * @param editorId {String} an editor id
         * @param groupId {String} a group id
         */
        var put = function(recorder, editorId, groupId) {
            recorders[makeId(editorId, groupId)] = recorder;
        };

        /**
         * Remove a position recorder stored in that combined keys
         * @param editorId {String} an editor id
         * @param groupId {String} a group id
         */
        var remove = function(editorId, groupId) {
            delete recorders[makeId(editorId, groupId)];
        };

        return {
            get: get,
            getAll: getAll,
            put: put,
            remove: remove
        };
    };

    /**
     * A function to store and handle the position recorders
     * @returns {Object} exporting the startRecorder, pauseRecorder, stopRecorder
     * and getRecorders functions
     */
    var PositionRecordersManager = function() {
        var recorders = new PositionRecorders();

        /**
         * Return the position recorders registered
         * @returns {Object} of {PositionRecorder} recorders
         */
        var getRecorders = function(editorId, groupId) {
            return recorders.getAll();
        };

        /**
         * Return the position recorders registered
         * @returns {Object} of {PositionRecorder} recorders
         */
        var getRecorder = function(editorId, groupId) {
            return recorders.get(editorId, groupId);
        };

        /**
         * Start or continue a position recorder
         * @param editorId {String} an editor id
         * @param groupId {String} a group id
         * @returns {PositionRecorder} a position recorded recording
         */
        var startRecorder = function(editorId, groupId) {
            var recorder;
            recorder = recorders.get(editorId, groupId);

            if (!recorder) {
                recorder = new PositionRecorder();
                recorders.put(recorder, editorId, groupId);
            }

            if (!recorder.isRecording()) {
                recorder.startRecording();
            }

            return recorder;
        };

        /**
         * Pause a position recorder
         * @param editorId {String} an editor id
         * @param groupId {String} a group id
         * @returns {PositionRecorder} a position recorded recording
         */
        var pauseRecorder = function(editorId, groupId) {
            var recorder;
            recorder = recorders.get(editorId, groupId);

            if (recorder) {
                recorder.stopRecording();
            }

            return recorder;
        };

        /**
         * Save the positions of the position recorder as a record
         * @param recorder {PositionRecorder} a position recorder
         * @param editorId {String} an editor id
         * @param groupId {String} a group id
         */
        var saveRecorder = function(editorId, groupId, recordName) {
            var positions = [];
            var geoJSON;
            var annotation;
            var recorder = recorders.get(editorId, groupId);

            if (recorder) {
                positions = recorder.getRecordedPositions();
            }
            else {
                console.warn('Not recorder found (' + editorId + ', ' + groupId + ')');
            }

            if (positions.length > 0) {
                if (positions.length == 1) {
                    geoJSON = positionUtils.
                        positionToGeoJSONPoint(positions[0], true);
                }
                else {
                    geoJSON = positionUtils
                        .positionsToLineString(positions, true);
                }

                annotation = geoJSONAsAnnotation(
                    geoJSON, SESSION_PREFIX + editorId, groupId, recordName);

                records.saveAnnotation(undefined, annotation);

            }
            else {
                console.warn('0 Positions recorded');
            }
        };

        /**
         * Stops a position recorder
         * @param editorId {String} an editor id
         * @param groupId {String} a group id
         * @returns {PositionRecorder} a position recorded recording
         */
        var stopRecorder = function(editorId, groupId) {
            var recorder;

            recorder = recorders.get(editorId, groupId);

            if (recorder) {
                recorder.stopRecording();
            }

            return recorder;
        };

        var disposeRecorder = function(editorId, groupId) {
            stopRecorder(editorId, groupId);
            recorders.remove(editorId, groupId);
        };

        return {
            startRecorder: startRecorder,
            pauseRecorder: pauseRecorder,
            stopRecorder: stopRecorder,
            getRecorders: getRecorders,
            getRecorder: getRecorder,
            saveRecorder: saveRecorder,
            disposeRecorder: disposeRecorder
        };
    };

    return {
        PositionRecordersManager: new PositionRecordersManager()
    };
});
<commit_msg>Update documentation<commit_after>'use strict';

/* global cordova */

define(function(require) {
    var PositionRecorder = require('./position-recorder');
    var positionUtils = require('./position-utils');
    var records = require('records');

    var SESSION_PREFIX = 'track-';

    /**
     * Extend a geoJSON object as a record and wrap it in an annotation
     *
     * @param geoJSON {Object} a geoJSON object
     * @param editorId {String} an editor id
     * @param groupId {String} a group id
     * @param name {String} a record name
     * @returns {Object} an annotation
     */
    var geoJSONAsAnnotation = function(geoJSON, editorId, groupId, name) {
        var record;
        var annotation;

        // Add the mandatory properties for the record
        record = geoJSON;
        record.properties = record.properties || {};
        record.name = name;
        record.properties.editor = editorId;
        record.properties.fields = [];

        // Wrap the record as an annotation
        annotation =  {
            record: geoJSON,
            type: editorId,
            isSynced: false,
            editorGroup: groupId
        };

        return annotation;
    };

    /**
     * The position recorders are stored using a combined key groupId plus editorId
     * this is a helper function to store them under that scheme.
     * @returns an instance of {PositionRecorders}
     */
    var PositionRecorders = function() {
        var recorders = {};

        var makeId = function(editorId, groupId) {
            return groupId + '#' + editorId;
        };

        /**
         * Returns the list of recorders
         * @returns {Object} list of {PositionRecorder} sessions
         */
        var getAll = function() {
            return recorders;
        };

        /**
         * Get the position recorder stored in the combined keys
         * @param editorId {String} an editor id
         * @param groupId {String} a group id
         * @returns {PositionRecorder} a position recorder
         */
        var get = function(editorId, groupId) {
            return recorders[makeId(editorId, groupId)];
        };

        /**
         * Put a position recorder in the combined keys
         * @param recorder
         * @param editorId {String} an editor id
         * @param groupId {String} a group id
         */
        var put = function(recorder, editorId, groupId) {
            recorders[makeId(editorId, groupId)] = recorder;
        };

        /**
         * Remove a position recorder stored in that combined keys
         * @param editorId {String} an editor id
         * @param groupId {String} a group id
         */
        var remove = function(editorId, groupId) {
            delete recorders[makeId(editorId, groupId)];
        };

        return {
            get: get,
            getAll: getAll,
            put: put,
            remove: remove
        };
    };

    /**
     * A function to store and handle the position recorders
     * @returns an instance of {PositionRecordersManager}
     */
    var PositionRecordersManager = function() {
        var recorders = new PositionRecorders();

        /**
         * Return the position recorders registered
         * @returns {Object} of {PositionRecorder} recorders
         */
        var getRecorders = function(editorId, groupId) {
            return recorders.getAll();
        };

        /**
         * Return the position recorders registered
         * @returns {Object} of {PositionRecorder} recorders
         */
        var getRecorder = function(editorId, groupId) {
            return recorders.get(editorId, groupId);
        };

        /**
         * Start or continue a position recorder
         * @param editorId {String} an editor id
         * @param groupId {String} a group id
         * @returns {PositionRecorder} a position recorded recording
         */
        var startRecorder = function(editorId, groupId) {
            var recorder;
            recorder = recorders.get(editorId, groupId);

            if (!recorder) {
                recorder = new PositionRecorder();
                recorders.put(recorder, editorId, groupId);
            }

            if (!recorder.isRecording()) {
                recorder.startRecording();
            }

            return recorder;
        };

        /**
         * Pause a position recorder
         * @param editorId {String} an editor id
         * @param groupId {String} a group id
         * @returns {PositionRecorder} a position recorded recording
         */
        var pauseRecorder = function(editorId, groupId) {
            var recorder;
            recorder = recorders.get(editorId, groupId);

            if (recorder) {
                recorder.stopRecording();
            }

            return recorder;
        };

        /**
         * Save the positions of the position recorder as a record
         * @param recorder {PositionRecorder} a position recorder
         * @param editorId {String} an editor id
         * @param groupId {String} a group id
         */
        var saveRecorder = function(editorId, groupId, recordName) {
            var positions = [];
            var geoJSON;
            var annotation;
            var recorder = recorders.get(editorId, groupId);

            if (recorder) {
                positions = recorder.getRecordedPositions();
            }
            else {
                console.warn('Not recorder found (' + editorId + ', ' + groupId + ')');
            }

            if (positions.length > 0) {
                if (positions.length == 1) {
                    geoJSON = positionUtils.
                        positionToGeoJSONPoint(positions[0], true);
                }
                else {
                    geoJSON = positionUtils
                        .positionsToLineString(positions, true);
                }

                annotation = geoJSONAsAnnotation(
                    geoJSON, SESSION_PREFIX + editorId, groupId, recordName);

                records.saveAnnotation(undefined, annotation);

            }
            else {
                console.warn('0 Positions recorded');
            }
        };

        /**
         * Stops a position recorder
         * @param editorId {String} an editor id
         * @param groupId {String} a group id
         * @returns {PositionRecorder} a position recorded recording
         */
        var stopRecorder = function(editorId, groupId) {
            var recorder;

            recorder = recorders.get(editorId, groupId);

            if (recorder) {
                recorder.stopRecording();
            }

            return recorder;
        };

        /**
         * Dispose a recorder
         * @param editorId {String} an editor id
         * @param groupId {String} a group id
         */
        var disposeRecorder = function(editorId, groupId) {
            stopRecorder(editorId, groupId);
            recorders.remove(editorId, groupId);
        };

        return {
            startRecorder: startRecorder,
            pauseRecorder: pauseRecorder,
            stopRecorder: stopRecorder,
            getRecorders: getRecorders,
            getRecorder: getRecorder,
            saveRecorder: saveRecorder,
            disposeRecorder: disposeRecorder
        };
    };

    return {
        PositionRecordersManager: new PositionRecordersManager()
    };
});
<|endoftext|>