<commit_before>'use strict';

import gulp from 'gulp';
import gutil from 'gulp-util';
import gulpLoadPlugins from 'gulp-load-plugins';
import browserSync from 'browser-sync';
import LiveServer from 'gulp-live-server';
import sass from 'gulp-sass';
import concat from 'gulp-concat';
import replace from 'gulp-replace';
import header from 'gulp-header';
import footer from 'gulp-footer';
import del from 'del';
import source from 'vinyl-source-stream';
import merge from 'merge-stream';
import buffer from 'vinyl-buffer';
import babelify from 'babelify';
import reactify from 'reactify';
import browserify from 'browserify';
import uglify from 'gulp-uglify';
import cssnano from 'gulp-cssnano';
import rename from 'gulp-rename';
import sourcemaps from 'gulp-sourcemaps';
import inject from 'gulp-inject';
import yargs from 'yargs';
import rev from 'gulp-rev';
import glob from 'glob';
import envify from 'envify/custom';
import jasmine from 'gulp-jasmine';
import jasmineReporters from 'jasmine-reporters';
import jasmineTerminalReporter from 'jasmine-terminal-reporter';
import eventStream from 'event-stream';
import {Converter} from 'csvtojson';
import fs from 'fs';

const clientDir = 'app';
const serverDir = 'server';

const buildDir = 'build';
const publishDir = 'dist';

const $ = gulpLoadPlugins({
  rename: {
    'gulp-expect-file': 'expect'
  }
});

const reload = browserSync.reload;
const argv = yargs.argv;

const vendorStyles = [
  'node_modules/font-awesome/css/font-awesome.min.css',
  'node_modules/font-awesome/css/font-awesome.css.map',
  'node_modules/font-awesome/fonts/fontawesome*{.eot,.svg,.ttf,.woff,.woff2,.otf}',
  'node_modules/normalize.css/normalize.css'
];

gulp.task('clean', () => {
  del.sync([`${publishDir}`, `${buildDir}`, `${clientDir}/data/*.json`]);
});

function lint(files, options) {
  return () => {
    return gulp.src(files)
      .pipe(reload({stream: true, once: true}))
      .pipe($.eslint(options))
      .pipe($.eslint.format('compact'))
      .pipe($.if(!browserSync.active, $.eslint.failOnError()));
  };
}

gulp.task('lint:client', lint(`${clientDir}/**/*.jsx`));
gulp.task('lint:server', lint(`./${serverDir}/server.js`));
gulp.task('lint:step-templates', () => {
  return gulp.src('./step-templates/*.json')
    .pipe($.expect({ errorOnFailure: true, silent: true }, glob.sync('step-templates/*.json')));
});

gulp.task('tests', [], () => {
  return gulp.src('./spec/*-tests.js')
  // gulp-jasmine works on filepaths so you can't have any plugins before it
    .pipe(jasmine({
      includeStackTrace: false,
      reporter: [ new jasmineReporters.JUnitXmlReporter(), new jasmineTerminalReporter() ]
    }))
    .on('error', function(){
      process.exit(1);
    });
});

function humanize(categoryId){

  switch(categoryId){
    case 'aspnet': return 'ASP.NET';
    case 'aws': return 'AWS';
    case 'clickonce': return 'ClickOnce';
    case 'edgecast': return 'EdgeCast';
    case 'elmah': return 'ELMAH';
    case 'entityframework': return 'Entity Framework';
    case 'filesystem': return 'File System';
    case 'github': return 'GitHub';
    case 'ghostinspector': return 'Ghost Inspector';
    case 'hipchat': return 'HipChat';
    case 'hockeyapp': return 'HockeyApp';
    case 'http': return 'HTTP';
    case 'iis': return 'IIS';
    case 'microsoft-teams': return 'Microsoft Teams';
    case 'netscaler': return 'NetScaler';
    case 'newrelic': return 'New Relic';
    case 'nunit': return 'NUnit';
    case 'pagerduty': return 'PagerDuty';
    case 'ravendb': return 'RavenDB';
    case 'rabbitmq': return 'RabbitMQ';
    case 'readyroll': return 'ReadyRoll';
    case 'sharepoint': return 'SharePoint';
    case 'solarwinds': return 'SolarWinds';
    case 'sql': return 'SQL Server';
    case 'ssl': return 'SSL';
    case 'statuspage': return 'StatusPage';
    case 'teamcity': return 'TeamCity';
    case 'webdeploy': return 'Web Deploy';
    case 'xml': return 'XML';
    default: return categoryId[0].toUpperCase() + categoryId.substr(1).toLowerCase();
  }
}

function provideMissingData() {

  return eventStream.map(function(file, cb) {

      var fileContent = file.contents.toString();
      var template = JSON.parse(fileContent);
      var pathParts = file.path.split('\\');
      var fileName = pathParts[pathParts.length - 1];

      if (!template.HistoryUrl) {
        template.HistoryUrl = "https://github.com/OctopusDeploy/Library/commits/master/step-templates/" + fileName;
      }

      if (!template.Website) {
        template.Website = "/step-templates/" + template.Id;
      }

      var categoryId = template.Category;
      if (!categoryId) {
        categoryId = 'other';
      }

      categoryId = categoryId.toLowerCase();

      template.Category = humanize(categoryId);

      if (!template.Logo) {
        var logo = fs.readFileSync("./step-templates/logos/" + categoryId + ".png");
        template.Logo = new Buffer(logo).toString('base64');
      }

      file.contents = new Buffer(JSON.stringify(template));

      cb(null, file);
  });
}

gulp.task('step-templates', ['lint:step-templates', 'tests'], () => {
  return gulp.src('./step-templates/*.json')
    .pipe(provideMissingData())
    .pipe(concat('step-templates.json', {newLine: ','}))
    .pipe(header('{"items": ['))
    .pipe(footer(']}'))
    .pipe(argv.production ? gulp.dest(`${publishDir}/app/services`) : gulp.dest(`${buildDir}/app/services`));
});

gulp.task('styles:vendor', () => {
  return gulp.src(vendorStyles, {base: 'node_modules/'})
    .pipe(argv.production ? gulp.dest(`${publishDir}/public/styles/vendor`) : gulp.dest(`${buildDir}/public/styles/vendor`));
});

gulp.task('styles:client', () => {
  return gulp.src(`${clientDir}/content/styles/main.scss`)
    .pipe(sass().on('error', sass.logError))
    .pipe($.if(argv.production, sourcemaps.init({loadMaps: true})))
    .pipe($.if(argv.production, cssnano())).on('error', gutil.log)
    .pipe($.if(argv.production, rename({suffix: '.min'})))
    .pipe($.if(argv.production, rev()))
    .pipe($.if(argv.production, sourcemaps.write('.')))
    .pipe(argv.production ? gulp.dest(`${publishDir}/public/styles`) : gulp.dest(`${buildDir}/public/styles`));
});

gulp.task('images', () => {
  return gulp.src(`${clientDir}/content/images/**/*{.png,.gif,.jpeg,.jpg,.bmp}`)
    .pipe(argv.production ? gulp.dest(`${publishDir}/public/images`) : gulp.dest(`${buildDir}/public/images`));
});

gulp.task('copy:app', () => {
  return gulp.src(`${clientDir}/**/*{.jsx,.js}`)
    .pipe(argv.production ? gulp.dest(`${publishDir}/app`) : gulp.dest(`${buildDir}/app`));
});

gulp.task('copy:configs', () => {
  return gulp.src(['./package.json', './web.config', './IISNode.yml'])
    .pipe(argv.production ? gulp.dest(`${publishDir}`) : gulp.dest(`${buildDir}`));
});

gulp.task('scripts', ['lint:client'], () => {
  return browserify({
    entries: `./${clientDir}/Browser.jsx`,
    extensions: ['.jsx', '.js'],
    debug: true
  })
    .transform(babelify)
    .transform(reactify)
    .transform(envify({'_': 'purge', 'NODE_ENV': argv.production ? 'production' : 'development'}), {global: true})
    .bundle()
    .pipe(source('app.js'))
    .pipe(buffer())
    .pipe($.if(argv.production, sourcemaps.init({loadMaps: true})))
    .pipe($.if(argv.production, uglify())).on('error', gutil.log)
    .pipe($.if(argv.production, rename({suffix: '.min'})))
    .pipe($.if(argv.production, rev()))
    .pipe($.if(argv.production, sourcemaps.write('.')))
    .pipe(argv.production ? gulp.dest(`${publishDir}/public/scripts`) : gulp.dest(`${buildDir}/public/scripts`));
});

gulp.task('build:client', ['step-templates', 'copy:app', 'scripts', 'styles:client', 'styles:vendor', 'images'], () => {
  let vendorSources = gulp.src(vendorStyles, {base: 'node_modules/'});

let sources = argv.production
  ? gulp.src([`${publishDir}/public/**/*.js`, `${publishDir}/public/**/*.css*`, `!${publishDir}/public/**/vendor{,/**}`], {read: false})
  : gulp.src([`${buildDir}/public/**/*.js`, `${buildDir}/public/**/*.css*`, `!${buildDir}/public/**/vendor{,/**}`], {read: false});

return gulp.src(`${serverDir}/views/index.jade`)
  .pipe(inject(vendorSources, {relative: false, name: 'vendor', ignorePath: 'node_modules', addPrefix: 'styles/vendor'}))
  .pipe(inject(sources, {relative: false, ignorePath: `${argv.production ? `${publishDir}` : `${buildDir}`}/public`}))
  .pipe(argv.production ? gulp.dest(`${publishDir}/views`) : gulp.dest(`${buildDir}/views`));
});

gulp.task('build:server', ['lint:server'], () => {
  return gulp.src([`./${serverDir}/server.js`])
    .pipe($.babel())
    .pipe(argv.production ? gulp.dest(`${publishDir}`) : gulp.dest(`${buildDir}`));
});

gulp.task('build', ['build:server', 'build:client', 'copy:configs']);

gulp.task('watch', ['clean', 'build'], () => {
  let server = LiveServer(`${buildDir}/server.js`);
server.start();

browserSync.init(null, {
  proxy: 'http://localhost:9000'
});

gulp.watch(`${clientDir}/**/*.jade`, ['build:client']);
gulp.watch(`${clientDir}/**/*.jsx`, ['scripts', 'copy:app']);
gulp.watch(`${clientDir}/content/styles/**/*.scss`, ['styles:client']);
gulp.watch('step-templates/*.json', ['step-templates']);

gulp.watch(`${buildDir}/**/*.*`).on('change', reload);
});

gulp.task('default', ['clean', 'build']);
<commit_msg>Add Linux to humanize function<commit_after>'use strict';

import gulp from 'gulp';
import gutil from 'gulp-util';
import gulpLoadPlugins from 'gulp-load-plugins';
import browserSync from 'browser-sync';
import LiveServer from 'gulp-live-server';
import sass from 'gulp-sass';
import concat from 'gulp-concat';
import replace from 'gulp-replace';
import header from 'gulp-header';
import footer from 'gulp-footer';
import del from 'del';
import source from 'vinyl-source-stream';
import merge from 'merge-stream';
import buffer from 'vinyl-buffer';
import babelify from 'babelify';
import reactify from 'reactify';
import browserify from 'browserify';
import uglify from 'gulp-uglify';
import cssnano from 'gulp-cssnano';
import rename from 'gulp-rename';
import sourcemaps from 'gulp-sourcemaps';
import inject from 'gulp-inject';
import yargs from 'yargs';
import rev from 'gulp-rev';
import glob from 'glob';
import envify from 'envify/custom';
import jasmine from 'gulp-jasmine';
import jasmineReporters from 'jasmine-reporters';
import jasmineTerminalReporter from 'jasmine-terminal-reporter';
import eventStream from 'event-stream';
import {Converter} from 'csvtojson';
import fs from 'fs';

const clientDir = 'app';
const serverDir = 'server';

const buildDir = 'build';
const publishDir = 'dist';

const $ = gulpLoadPlugins({
  rename: {
    'gulp-expect-file': 'expect'
  }
});

const reload = browserSync.reload;
const argv = yargs.argv;

const vendorStyles = [
  'node_modules/font-awesome/css/font-awesome.min.css',
  'node_modules/font-awesome/css/font-awesome.css.map',
  'node_modules/font-awesome/fonts/fontawesome*{.eot,.svg,.ttf,.woff,.woff2,.otf}',
  'node_modules/normalize.css/normalize.css'
];

gulp.task('clean', () => {
  del.sync([`${publishDir}`, `${buildDir}`, `${clientDir}/data/*.json`]);
});

function lint(files, options) {
  return () => {
    return gulp.src(files)
      .pipe(reload({stream: true, once: true}))
      .pipe($.eslint(options))
      .pipe($.eslint.format('compact'))
      .pipe($.if(!browserSync.active, $.eslint.failOnError()));
  };
}

gulp.task('lint:client', lint(`${clientDir}/**/*.jsx`));
gulp.task('lint:server', lint(`./${serverDir}/server.js`));
gulp.task('lint:step-templates', () => {
  return gulp.src('./step-templates/*.json')
    .pipe($.expect({ errorOnFailure: true, silent: true }, glob.sync('step-templates/*.json')));
});

gulp.task('tests', [], () => {
  return gulp.src('./spec/*-tests.js')
  // gulp-jasmine works on filepaths so you can't have any plugins before it
    .pipe(jasmine({
      includeStackTrace: false,
      reporter: [ new jasmineReporters.JUnitXmlReporter(), new jasmineTerminalReporter() ]
    }))
    .on('error', function(){
      process.exit(1);
    });
});

function humanize(categoryId){

  switch(categoryId){
    case 'aspnet': return 'ASP.NET';
    case 'aws': return 'AWS';
    case 'clickonce': return 'ClickOnce';
    case 'edgecast': return 'EdgeCast';
    case 'elmah': return 'ELMAH';
    case 'entityframework': return 'Entity Framework';
    case 'filesystem': return 'File System';
    case 'github': return 'GitHub';
    case 'ghostinspector': return 'Ghost Inspector';
    case 'hipchat': return 'HipChat';
    case 'hockeyapp': return 'HockeyApp';
    case 'http': return 'HTTP';
    case 'iis': return 'IIS';
    case 'linux': return 'Linux';
    case 'microsoft-teams': return 'Microsoft Teams';
    case 'netscaler': return 'NetScaler';
    case 'newrelic': return 'New Relic';
    case 'nunit': return 'NUnit';
    case 'pagerduty': return 'PagerDuty';
    case 'ravendb': return 'RavenDB';
    case 'rabbitmq': return 'RabbitMQ';
    case 'readyroll': return 'ReadyRoll';
    case 'sharepoint': return 'SharePoint';
    case 'solarwinds': return 'SolarWinds';
    case 'sql': return 'SQL Server';
    case 'ssl': return 'SSL';
    case 'statuspage': return 'StatusPage';
    case 'teamcity': return 'TeamCity';
    case 'webdeploy': return 'Web Deploy';
    case 'xml': return 'XML';
    default: return categoryId[0].toUpperCase() + categoryId.substr(1).toLowerCase();
  }
}

function provideMissingData() {

  return eventStream.map(function(file, cb) {

      var fileContent = file.contents.toString();
      var template = JSON.parse(fileContent);
      var pathParts = file.path.split('\\');
      var fileName = pathParts[pathParts.length - 1];

      if (!template.HistoryUrl) {
        template.HistoryUrl = "https://github.com/OctopusDeploy/Library/commits/master/step-templates/" + fileName;
      }

      if (!template.Website) {
        template.Website = "/step-templates/" + template.Id;
      }

      var categoryId = template.Category;
      if (!categoryId) {
        categoryId = 'other';
      }

      categoryId = categoryId.toLowerCase();

      template.Category = humanize(categoryId);

      if (!template.Logo) {
        var logo = fs.readFileSync("./step-templates/logos/" + categoryId + ".png");
        template.Logo = new Buffer(logo).toString('base64');
      }

      file.contents = new Buffer(JSON.stringify(template));

      cb(null, file);
  });
}

gulp.task('step-templates', ['lint:step-templates', 'tests'], () => {
  return gulp.src('./step-templates/*.json')
    .pipe(provideMissingData())
    .pipe(concat('step-templates.json', {newLine: ','}))
    .pipe(header('{"items": ['))
    .pipe(footer(']}'))
    .pipe(argv.production ? gulp.dest(`${publishDir}/app/services`) : gulp.dest(`${buildDir}/app/services`));
});

gulp.task('styles:vendor', () => {
  return gulp.src(vendorStyles, {base: 'node_modules/'})
    .pipe(argv.production ? gulp.dest(`${publishDir}/public/styles/vendor`) : gulp.dest(`${buildDir}/public/styles/vendor`));
});

gulp.task('styles:client', () => {
  return gulp.src(`${clientDir}/content/styles/main.scss`)
    .pipe(sass().on('error', sass.logError))
    .pipe($.if(argv.production, sourcemaps.init({loadMaps: true})))
    .pipe($.if(argv.production, cssnano())).on('error', gutil.log)
    .pipe($.if(argv.production, rename({suffix: '.min'})))
    .pipe($.if(argv.production, rev()))
    .pipe($.if(argv.production, sourcemaps.write('.')))
    .pipe(argv.production ? gulp.dest(`${publishDir}/public/styles`) : gulp.dest(`${buildDir}/public/styles`));
});

gulp.task('images', () => {
  return gulp.src(`${clientDir}/content/images/**/*{.png,.gif,.jpeg,.jpg,.bmp}`)
    .pipe(argv.production ? gulp.dest(`${publishDir}/public/images`) : gulp.dest(`${buildDir}/public/images`));
});

gulp.task('copy:app', () => {
  return gulp.src(`${clientDir}/**/*{.jsx,.js}`)
    .pipe(argv.production ? gulp.dest(`${publishDir}/app`) : gulp.dest(`${buildDir}/app`));
});

gulp.task('copy:configs', () => {
  return gulp.src(['./package.json', './web.config', './IISNode.yml'])
    .pipe(argv.production ? gulp.dest(`${publishDir}`) : gulp.dest(`${buildDir}`));
});

gulp.task('scripts', ['lint:client'], () => {
  return browserify({
    entries: `./${clientDir}/Browser.jsx`,
    extensions: ['.jsx', '.js'],
    debug: true
  })
    .transform(babelify)
    .transform(reactify)
    .transform(envify({'_': 'purge', 'NODE_ENV': argv.production ? 'production' : 'development'}), {global: true})
    .bundle()
    .pipe(source('app.js'))
    .pipe(buffer())
    .pipe($.if(argv.production, sourcemaps.init({loadMaps: true})))
    .pipe($.if(argv.production, uglify())).on('error', gutil.log)
    .pipe($.if(argv.production, rename({suffix: '.min'})))
    .pipe($.if(argv.production, rev()))
    .pipe($.if(argv.production, sourcemaps.write('.')))
    .pipe(argv.production ? gulp.dest(`${publishDir}/public/scripts`) : gulp.dest(`${buildDir}/public/scripts`));
});

gulp.task('build:client', ['step-templates', 'copy:app', 'scripts', 'styles:client', 'styles:vendor', 'images'], () => {
  let vendorSources = gulp.src(vendorStyles, {base: 'node_modules/'});

let sources = argv.production
  ? gulp.src([`${publishDir}/public/**/*.js`, `${publishDir}/public/**/*.css*`, `!${publishDir}/public/**/vendor{,/**}`], {read: false})
  : gulp.src([`${buildDir}/public/**/*.js`, `${buildDir}/public/**/*.css*`, `!${buildDir}/public/**/vendor{,/**}`], {read: false});

return gulp.src(`${serverDir}/views/index.jade`)
  .pipe(inject(vendorSources, {relative: false, name: 'vendor', ignorePath: 'node_modules', addPrefix: 'styles/vendor'}))
  .pipe(inject(sources, {relative: false, ignorePath: `${argv.production ? `${publishDir}` : `${buildDir}`}/public`}))
  .pipe(argv.production ? gulp.dest(`${publishDir}/views`) : gulp.dest(`${buildDir}/views`));
});

gulp.task('build:server', ['lint:server'], () => {
  return gulp.src([`./${serverDir}/server.js`])
    .pipe($.babel())
    .pipe(argv.production ? gulp.dest(`${publishDir}`) : gulp.dest(`${buildDir}`));
});

gulp.task('build', ['build:server', 'build:client', 'copy:configs']);

gulp.task('watch', ['clean', 'build'], () => {
  let server = LiveServer(`${buildDir}/server.js`);
server.start();

browserSync.init(null, {
  proxy: 'http://localhost:9000'
});

gulp.watch(`${clientDir}/**/*.jade`, ['build:client']);
gulp.watch(`${clientDir}/**/*.jsx`, ['scripts', 'copy:app']);
gulp.watch(`${clientDir}/content/styles/**/*.scss`, ['styles:client']);
gulp.watch('step-templates/*.json', ['step-templates']);

gulp.watch(`${buildDir}/**/*.*`).on('change', reload);
});

gulp.task('default', ['clean', 'build']);
<|endoftext|>


<commit_before>import corodvaExec from 'cordova/exec'
import isUndefined from 'lodash/isUndefined'

/**
 * Base config object.
 * @typedef {Object} BaseConfig
 * @property {string} [id=TESTING_AD_ID] - Ad Unit ID
 * @property {boolean} [isTesting=false] - Receiving test ad
 * @property {boolean} [autoShow=false] - Auto show ad when loaded
 *
 * @property {boolean|null} [forChild=null]
 * Child-directed setting.
 * Default is not calling `tagForChildDirectedTreatment`.
 * Set to `true` for `tagForChildDirectedTreatment(true)`.
 * Set to `false` for `tagForChildDirectedTreatment(false)`.
 * @see https://firebase.google.com/docs/admob/android/targeting#child-directed_setting
 *
 * @property {boolean|null} [forFamily=null]
 * Designed for Families setting.
 * Android-only.
 * Default is not calling `setIsDesignedForFamilies`.
 * Set to `true` for `setIsDesignedForFamilies(true)`.
 * Set to `false` for `setIsDesignedForFamilies(false)`.
 * @see https://firebase.google.com/docs/admob/android/targeting#designed_for_families_setting
 *
 * @property {Array<number>|null} [location=null]
 * Location targeting.
 * It accept an array in the form of `[latitude, longitude]`.
 * Android-only.
 * Default is not calling `setLatitude` and `setLongitude`.
 */

/**
 * @ignore
 */
export function exec(method, args) {
  return new Promise((resolve, reject) => {
    corodvaExec(resolve, reject, 'AdMob', method, args)
  })
}

/**
 * @ignore
 */
export function isFunction(x) {
  return typeof x === 'function'
}

function isString(x) {
  return typeof x === 'string'
}

/**
 * @ignore
 */
export function wrapCallbacks(p, successCallback, failureCallback) {
  if (isFunction(successCallback)) {
    p = p.then(successCallback) // eslint-disable-line no-param-reassign
  }
  if (isFunction(failureCallback)) {
    p = p.catch(failureCallback) // eslint-disable-line no-param-reassign
  }
  return p
}

function boolean2string(x) {
  if (x === null) {
    return ''
  }
  if (x === true) {
    return 'yes'
  }
  if (x === false) {
    return 'no'
  }
  return x
}

/**
 * @ignore
 */
export function translateOptions(options) {
  /* eslint-disable no-console */
  const opts = {}
  if (!isUndefined(options.forChild)) {
    opts.forChild = boolean2string(options.forChild)
    if (isString(options.forChild)) {
      console.warn(
        '`forChild` will not accept string in future, pass boolean instead',
      )
    }
  }
  if (!isUndefined(options.forFamily)) {
    opts.forFamily = boolean2string(options.forFamily)
    if (isString(options.forFamily)) {
      console.warn(
        '`forFamily` will not accept string in future, pass boolean instead',
      )
    }
  }
  /* eslint-enable no-console */
  return {
    ...options,
    ...opts,
  }
}

/**
 * @ignore
 */
export function buildEvents(adType, eventKeys) {
  return eventKeys.reduce((acc, eventKey) => {
    acc[eventKey] = `admob.${adType}.events.${eventKey}`
    return acc
  }, {})
}
<commit_msg>Fix option `adSize` not exist bug<commit_after>import corodvaExec from 'cordova/exec'
import isUndefined from 'lodash/isUndefined'

/**
 * Base config object.
 * @typedef {Object} BaseConfig
 * @property {string} [id=TESTING_AD_ID] - Ad Unit ID
 * @property {boolean} [isTesting=false] - Receiving test ad
 * @property {boolean} [autoShow=false] - Auto show ad when loaded
 *
 * @property {boolean|null} [forChild=null]
 * Child-directed setting.
 * Default is not calling `tagForChildDirectedTreatment`.
 * Set to `true` for `tagForChildDirectedTreatment(true)`.
 * Set to `false` for `tagForChildDirectedTreatment(false)`.
 * @see https://firebase.google.com/docs/admob/android/targeting#child-directed_setting
 *
 * @property {boolean|null} [forFamily=null]
 * Designed for Families setting.
 * Android-only.
 * Default is not calling `setIsDesignedForFamilies`.
 * Set to `true` for `setIsDesignedForFamilies(true)`.
 * Set to `false` for `setIsDesignedForFamilies(false)`.
 * @see https://firebase.google.com/docs/admob/android/targeting#designed_for_families_setting
 *
 * @property {Array<number>|null} [location=null]
 * Location targeting.
 * It accept an array in the form of `[latitude, longitude]`.
 * Android-only.
 * Default is not calling `setLatitude` and `setLongitude`.
 */

/**
 * @ignore
 */
export function exec(method, args) {
  return new Promise((resolve, reject) => {
    corodvaExec(resolve, reject, 'AdMob', method, args)
  })
}

/**
 * @ignore
 */
export function isFunction(x) {
  return typeof x === 'function'
}

function isString(x) {
  return typeof x === 'string'
}

/**
 * @ignore
 */
export function wrapCallbacks(p, successCallback, failureCallback) {
  if (isFunction(successCallback)) {
    p = p.then(successCallback) // eslint-disable-line no-param-reassign
  }
  if (isFunction(failureCallback)) {
    p = p.catch(failureCallback) // eslint-disable-line no-param-reassign
  }
  return p
}

function boolean2string(x) {
  if (x === null) {
    return ''
  }
  if (x === true) {
    return 'yes'
  }
  if (x === false) {
    return 'no'
  }
  return x
}

/**
 * @ignore
 */
export function translateOptions(options) {
  /* eslint-disable no-console */
  const opts = {}
  if (!isUndefined(options.forChild)) {
    opts.forChild = boolean2string(options.forChild)
    if (isString(options.forChild)) {
      console.warn(
        '`forChild` will not accept string in future, pass boolean instead',
      )
    }
  }
  if (!isUndefined(options.forFamily)) {
    opts.forFamily = boolean2string(options.forFamily)
    if (isString(options.forFamily)) {
      console.warn(
        '`forFamily` will not accept string in future, pass boolean instead',
      )
    }
  }
  /* eslint-enable no-console */
  return {
    ...options,
    ...opts,
    // TODO update native implementation using `size`
    adSize: options.size,
  }
}

/**
 * @ignore
 */
export function buildEvents(adType, eventKeys) {
  return eventKeys.reduce((acc, eventKey) => {
    acc[eventKey] = `admob.${adType}.events.${eventKey}`
    return acc
  }, {})
}
<|endoftext|>


<commit_before>var Argo = Argo || {};

(function(A, $) {
  // Update _ templates to be like mustache
  _.templateSettings = {
    interpolate : /\{\{(.+?)\}\}/g
  };

  // A Legend for all of the layers
  A.LegendView = Backbone.View.extend({
    initialize: function(){
      this.render();
    },
    events: {
      'change .argo-legend-checkbox': 'toggleVisibility'
    },
    render: function(){
      var $markup = $('

');

      this.collection.each(function(model, i) {
        var checked = model.get('visible') ? 'checked="checked"' : '';

        if (model.get('legend') !== false) {
          $markup.append('
' +
            '
' +
              '
'+model.get('title')+'
' +
              '
'+model.get('description')+'
' +
            '
' +
            '
' +
              '<input id="argo-'+model.get('id')+'" data-layerid="'+model.get('id')+'" ' +
                checked+' class="argo-legend-checkbox" type="checkbox"></input>' +
              ''+model.get('title')+'' +
            '
' +
          '
');
        }
      });

      this.$el.append($markup);
    },
    toggleVisibility: function(evt) {
      var $cbox = $(evt.target),
          id = $cbox.attr('data-layerid');

      if ($cbox.is(':checked')) {
        this.collection.get(id).set('visible', true);
      } else {
        this.collection.get(id).set('visible', false);
      }
    }
  });

  // A view for stylable GeoJson layers
  A.LayerView = Backbone.View.extend({
    initialize: function(){
      var self = this,
          url = self.model.get('url'),
          type = self.model.get('type') || 'jsonp',
          getGeoJsonFunction = type === 'geoserver' ?
            self.getGeoJsonFromGeoServer : self.getGeoJson;

      // Cache the popup template
      if (self.model.has('popupContent')) {
        self.popupTemplate = _.template(self.model.get('popupContent'));
      }

      getGeoJsonFunction.call(this, url, self.model.toJSON(), function(geoJson) {
        if (geoJson) {
          self.layer = L.geoJson(geoJson, {
            pointToLayer: function (feature, latlng) {
              return new L.CircleMarker(latlng);
            },
            onEachFeature: function(feature, layer) {
              var style = self.getStyleRule(feature.properties),
                  popupContent = self.getPopupContent(feature.properties);

              if (style) {
                // Only clickable if there is popup content; convert to bool
                style.clickable = !!popupContent;

                // Set the style manually since so I can use popupContent to set clickable
                layer.setStyle(style);

                // Handle radius for circle marker
                if (layer.setRadius && style.radius) {
                  layer.setRadius(style.radius);
                }

                // Init the popup
                if (popupContent) {
                  layer.bindPopup(popupContent);
                }
              } else {
                layer.setStyle({
                  fill: false,
                  stroke: false
                });
              }
            }
          });

          self.render();
        } else {
          console.error('GeoJSON could not be retrieved from: ', url);
        }
      });

      // Rerender on model change
      self.model.bind('change', self.render, self);
    },

    getGeoServerCallbackName: function(id) {
      // Get rid of any invalid characters for a JS var
      var safeId = id.replace(/[^\w\d]/g, ''),
          callbackName = 'ArgoJsonpCallback_' + safeId + '_' + $.expando + '_' + $.now();

      return callbackName;
    },

    getGeoJsonFromGeoServer: function(url, options, callback) {
      var callbackName = this.getGeoServerCallbackName(options.id);

      // Fetch the GeoJson from GeoServer
      $.ajax({
        url: url + '&format_options=callback:' + callbackName,
        dataType: 'jsonp',
        jsonpCallback: callbackName,
        success: callback
      });
    },
    getGeoJson: function(url, options, callback) {
      // Fetch the GeoJson using the given type
      $.ajax({
        url: url,
        dataType: options.type,
        success: callback
      });
    },
    // Get the style rule for this feature by evaluating the condition option
    getStyleRule: function(properties) {
      var self = this,
          rules = self.model.get('rules'),
          i, condition;

      for (i=0; i<rules.length; i++) {
        // Replace the template with the property variable, not the value.
        // this is so we don't have to worry about strings vs nums.
        condition = _.template(rules[i].condition)(properties);

        // Simpler code plus a trusted source; negligible performance hit
        if (eval(condition)) {
          return rules[i].style;
        }
      }
      return null;
    },
    // Get the popup content and replace the variable
    getPopupContent: function(properties) {
      return this.popupTemplate ? this.popupTemplate(properties) : null;
    },
    render: function(){
      // Adds or removes the layer based on visibility
      this.options.map.closePopup();
      if (this.model.get('visible') && !this.options.map.hasLayer(this.layer)) {
        this.options.map.addLayer(this.layer);
      }
      if (!this.model.get('visible') && this.options.map.hasLayer(this.layer)) {
        this.options.map.removeLayer(this.layer);
      }
    }
  });

  // A view for maps with a legend and stylable GeoJson layers
  A.MapView = Backbone.View.extend({
    initialize: function() {
      var self = this,
          i, layerModel,
          // Base layer config is optional
          baseLayerConfig = self.options.baseLayer || {},
          // Default to Mapbox Streets
          baseLayerUrl = baseLayerConfig.url || 'http://{s}.tiles.mapbox.com/v3/mapbox.mapbox-streets/{z}/{x}/{y}.png',
          baseLayerAttr = baseLayerConfig.attribution ||
            '© OpenStreetMap contributors, CC-BY-SA. Terms & Feedback';
          baseTile = new L.TileLayer(baseLayerUrl, {attribution: baseLayerAttr});

      // Init the map
      self.map = new L.Map(self.el, self.options.map);
      self.map.addLayer(baseTile);
      // Remove default prefix
      self.map.attributionControl.setPrefix('');

      // Cache the layers views
      self.layers = {};

      // Init all of the layers
      this.collection.each(function(model, i) {
        self.layers[model.get('id')] = new A.LayerView({
          map: self.map,
          model: model
        });
      });
    }
  });
})(Argo, jQuery);<commit_msg>clean up the default base layer logic<commit_after>var Argo = Argo || {};

(function(A, $) {
  // Update _ templates to be like mustache
  _.templateSettings = {
    interpolate : /\{\{(.+?)\}\}/g
  };

  // A Legend for all of the layers
  A.LegendView = Backbone.View.extend({
    initialize: function(){
      this.render();
    },
    events: {
      'change .argo-legend-checkbox': 'toggleVisibility'
    },
    render: function(){
      var $markup = $('

');

      this.collection.each(function(model, i) {
        var checked = model.get('visible') ? 'checked="checked"' : '';

        if (model.get('legend') !== false) {
          $markup.append('
' +
            '
' +
              '
'+model.get('title')+'
' +
              '
'+model.get('description')+'
' +
            '
' +
            '
' +
              '<input id="argo-'+model.get('id')+'" data-layerid="'+model.get('id')+'" ' +
                checked+' class="argo-legend-checkbox" type="checkbox"></input>' +
              ''+model.get('title')+'' +
            '
' +
          '
');
        }
      });

      this.$el.append($markup);
    },
    toggleVisibility: function(evt) {
      var $cbox = $(evt.target),
          id = $cbox.attr('data-layerid');

      if ($cbox.is(':checked')) {
        this.collection.get(id).set('visible', true);
      } else {
        this.collection.get(id).set('visible', false);
      }
    }
  });

  // A view for stylable GeoJson layers
  A.LayerView = Backbone.View.extend({
    initialize: function(){
      var self = this,
          url = self.model.get('url'),
          type = self.model.get('type') || 'jsonp',
          getGeoJsonFunction = type === 'geoserver' ?
            self.getGeoJsonFromGeoServer : self.getGeoJson;

      // Cache the popup template
      if (self.model.has('popupContent')) {
        self.popupTemplate = _.template(self.model.get('popupContent'));
      }

      getGeoJsonFunction.call(this, url, self.model.toJSON(), function(geoJson) {
        if (geoJson) {
          self.layer = L.geoJson(geoJson, {
            pointToLayer: function (feature, latlng) {
              return new L.CircleMarker(latlng);
            },
            onEachFeature: function(feature, layer) {
              var style = self.getStyleRule(feature.properties),
                  popupContent = self.getPopupContent(feature.properties);

              if (style) {
                // Only clickable if there is popup content; convert to bool
                style.clickable = !!popupContent;

                // Set the style manually since so I can use popupContent to set clickable
                layer.setStyle(style);

                // Handle radius for circle marker
                if (layer.setRadius && style.radius) {
                  layer.setRadius(style.radius);
                }

                // Init the popup
                if (popupContent) {
                  layer.bindPopup(popupContent);
                }
              } else {
                layer.setStyle({
                  fill: false,
                  stroke: false
                });
              }
            }
          });

          self.render();
        } else {
          console.error('GeoJSON could not be retrieved from: ', url);
        }
      });

      // Rerender on model change
      self.model.bind('change', self.render, self);
    },

    getGeoServerCallbackName: function(id) {
      // Get rid of any invalid characters for a JS var
      var safeId = id.replace(/[^\w\d]/g, ''),
          callbackName = 'ArgoJsonpCallback_' + safeId + '_' + $.expando + '_' + $.now();

      return callbackName;
    },

    getGeoJsonFromGeoServer: function(url, options, callback) {
      var callbackName = this.getGeoServerCallbackName(options.id);

      // Fetch the GeoJson from GeoServer
      $.ajax({
        url: url + '&format_options=callback:' + callbackName,
        dataType: 'jsonp',
        jsonpCallback: callbackName,
        success: callback
      });
    },
    getGeoJson: function(url, options, callback) {
      // Fetch the GeoJson using the given type
      $.ajax({
        url: url,
        dataType: options.type,
        success: callback
      });
    },
    // Get the style rule for this feature by evaluating the condition option
    getStyleRule: function(properties) {
      var self = this,
          rules = self.model.get('rules'),
          i, condition;

      for (i=0; i<rules.length; i++) {
        // Replace the template with the property variable, not the value.
        // this is so we don't have to worry about strings vs nums.
        condition = _.template(rules[i].condition)(properties);

        // Simpler code plus a trusted source; negligible performance hit
        if (eval(condition)) {
          return rules[i].style;
        }
      }
      return null;
    },
    // Get the popup content and replace the variable
    getPopupContent: function(properties) {
      return this.popupTemplate ? this.popupTemplate(properties) : null;
    },
    render: function(){
      // Adds or removes the layer based on visibility
      this.options.map.closePopup();
      if (this.model.get('visible') && !this.options.map.hasLayer(this.layer)) {
        this.options.map.addLayer(this.layer);
      }
      if (!this.model.get('visible') && this.options.map.hasLayer(this.layer)) {
        this.options.map.removeLayer(this.layer);
      }
    }
  });

  // A view for maps with a legend and stylable GeoJson layers
  A.MapView = Backbone.View.extend({
    initialize: function() {
      var self = this,
          i, layerModel,
          // Base layer config is optional, default to Mapbox Streets
          baseLayerConfig = _.extend({
            url: 'http://{s}.tiles.mapbox.com/v3/mapbox.mapbox-streets/{z}/{x}/{y}.png',
            attribution: '© OpenStreetMap contributors, CC-BY-SA. Terms & Feedback'
          }, self.options.baseLayer),
          baseLayer = new L.TileLayer(baseLayerConfig.url, baseLayerConfig);

      // Init the map
      self.map = new L.Map(self.el, self.options.map);
      self.map.addLayer(baseLayer);
      // Remove default prefix
      self.map.attributionControl.setPrefix('');

      // Cache the layers views
      self.layers = {};

      // Init all of the layers
      this.collection.each(function(model, i) {
        self.layers[model.get('id')] = new A.LayerView({
          map: self.map,
          model: model
        });
      });
    }
  });
})(Argo, jQuery);<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const gulp = require('gulp');
const del = require('del');
const babel = require('gulp-babel');

const config = {
  src: 'src',
  dest: 'generators',
}

gulp.task('clean', () => del(config.dest));

gulp.task('compile', gulp.series('clean', () => {
  return gulp.src(path.join(config.src, '**'), {
      dot: true
    })
    .pipe(babel({
      presets: ['es2015'],
      ignore: [
        '**/templates/**',
        '**/*.json',
      ],
    }))
    .pipe(gulp.dest(config.dest));
}));
<commit_msg>conform to aslant<commit_after>const path = require('path');
const gulp = require('gulp');
const del = require('del');
const babel = require('gulp-babel');

const config = {
  src: 'src',
  dest: 'generators',
};

gulp.task('clean', () => del(config.dest));

gulp.task('compile', gulp.series('clean', () => {
  return gulp.src(path.join(config.src, '**'), {dot: true})
    .pipe(babel({
      presets: ['es2015'],
      ignore: [
        '**/templates/**',
        '**/*.json',
      ],
    }))
    .pipe(gulp.dest(config.dest));
}));
<|endoftext|>


<commit_before>import Cell from './vr/cell.js';
import Chunk from './vr/chunk.js';
import Tile from './vr/tile.js';
import Avatar from './vr/avatar.js';

export default class World {
	constructor() {
		var scene = new THREE.Scene(),
            camera = new THREE.PerspectiveCamera(72, window.innerWidth / window.innerHeight, 30, 340000 ),
            renderer = new THREE.WebGLRenderer(),
			mobile = app.mobile,
			self = this,
            sunGeom = new THREE.OctahedronGeometry( 3000, 0),
            material = new THREE.MeshBasicMaterial( {color: 0xffffff, opacity: 0.9, transparent: true} ),
            sun = new THREE.Mesh(sunGeom, material ),
            light = new THREE.PointLight(0xffffff, 1.1, 400000 ),
            panelMat = new THREE.MeshLambertMaterial({ color: 0xe1e1e1 }),
            cellGeometry = new THREE.CylinderGeometry(192, 192, 128, 6),
            cell = null,
            x = 0,
            y = 0,
            r = 4000;

            renderer.setSize( window.innerWidth, window.innerHeight );
			document.body.appendChild( renderer.domElement );
			renderer.domElement.setAttribute("id", "viewport");

			this.three = {
				sun: sun,
				scene: scene,
				chunks: [],
				camera: camera,
				renderer: renderer
			};

			window.three = this.three;
    	scene.add(light);
			scene.fog = new THREE.FogExp2(0xffffff, 0.00001);
			light.position.set(0, 60000, -32000);
			renderer.setClearColor(0x2B7CA1);

			camera.position.z = 15;
			this.skybox = null;

			function render (last) {
				var sys = app,
					camera = three.camera,
					delta = ((Date.now() - last) / 10000),
					time = (Date.now() / 4600),
					image = "";

				if (!! sys.userInput) {
					sys.userInput.update(delta);
				}
				if (sys.sendUpdatePacket == 30) { // send image
					image = "image uri";
					sys.sendUpdatePacket = 0;
				}

				sys.sendUpdatePacket += 1;
				if (sys.sendUpdatePacket %2 == 0 && sys.mode == "vr") {
					socket.emit('user update','{"user":"'+sys.username+'","position": {"x":'+camera.position.x+',"y":'+camera.position.y+',"z":'+camera.position.z+'},'
						+'"quaternion":{"x":'+camera.quaternion.x+',"y":'+camera.quaternion.y+',"z":'+camera.quaternion.z+',"w":'+camera.quaternion.w+'}}');

				}

				sun.rotation.x += 0.0025;
				sun.rotation.y += 0.005;
				sys.world.skybox.position.set(camera.position.x, camera.position.y, camera.position.z);
				renderer.render(scene, camera);
				last = Date.now();
				requestAnimationFrame( function () { render(last); } );
			};

			var skyTexture = THREE.ImageUtils.loadTexture("/images/data-sky-neon-3.jpg", null, function () {
				var skybox = new THREE.Object3D(), // used to use larger jpeg version sunset-5.jpg
				    skyboxFace = null,
				    skyboxSideMat = new THREE.MeshBasicMaterial({
				        map: skyTexture,
								side: 1,
								fog: false,
                color: 0xffffff // too dark.. not dark enough? 0x60daff//  0x80faff too green
				    }),
					x = 0;
				skybox = new THREE.Mesh(new THREE.OctahedronGeometry(300000, 4), skyboxSideMat);
				self.skybox = skybox;
				skybox.add(three.sun);
				three.sun.position.set(0, 18000, -24000);
				three.scene.add(skybox);
				skybox.position.set(three.camera.position.x, 0, three.camera.position.z);
				skyTexture.needsUpdate = true;

				render(0);
			});

			var configure = {
				 baseURL: 'https://vpylon.net',
				 timeout: 1000,
				 headers: {'x-access-token': localStorage.getItem("token")}
			};

			//load cells
			axios.get('/api/cells/all', configure)
				.then(function (response) {
					app.cells = response.data;
					app.cells.forEach(function (userCell){
						var cell = new Cell(userCell.cell);
					});
				})
				.catch(function (response) {
					console.log(response);
				});

				function loadChunks (coords, phase) {
					var max = app.mobile ? 3 : (window.innerWidth > 2100 ?  7  : 4);
					var cellWidth = 3 + phase, // app.mobile ? 3 : (window.innerWidth > 2000 ?  7  : 5),
					    chunk = null,
					 x = coords[0] - phase,
					 y = coords[1] - phase;

					while (x <= phase) {
					  while (y <= phase) {
							if (Math.abs(x) == coords[0]+phase || Math.abs(y) == coords[1]+phase) {
						    chunk = new Chunk([x, 0, y], mobile);
						    chunk.mesh.updateMatrix();
						    app.chunks.push(chunk);
								three.scene.add(chunk.mesh);
							}

					    y++;
					  }
						y = coords[1]-phase;
						x++;
					}

					phase ++;
					if (phase < max) {
						setTimeout(function () {loadChunks(coords, phase); }, 1000)
					}

				}

				loadChunks ([0,0,0], 0);

			//baseMesh = new THREE.Mesh(base, baseMaterial);
			//scene.add(baseMesh);
//			var groundGeom = new THREE.PlaneGeometry(100000, 100000, 12, 12);
//			var groundMat = new THREE.MeshBasicMaterial({color: 0xf0f0f0});
//			var ground = new THREE.Mesh(groundGeom, groundMat);
//			ground.rotateX(Math.PI / 2);
//			three.scene.add(ground);
    }

};
<commit_msg>Almost finished implementing 'Chunk Buffering' for terrain / world<commit_after>import Cell from './vr/cell.js';
import Chunk from './vr/chunk.js';
import Tile from './vr/tile.js';
import Avatar from './vr/avatar.js';

export default class World {
	constructor() {
		var scene = new THREE.Scene(),
            camera = new THREE.PerspectiveCamera(72, window.innerWidth / window.innerHeight, 30, 340000 ),
            renderer = new THREE.WebGLRenderer(),
			mobile = app.mobile,
			self = this,
            sunGeom = new THREE.OctahedronGeometry( 3000, 0),
            material = new THREE.MeshBasicMaterial( {color: 0xffffff, opacity: 0.9, transparent: true} ),
            sun = new THREE.Mesh(sunGeom, material ),
            light = new THREE.PointLight(0xffffff, 1.1, 400000 ),
            panelMat = new THREE.MeshLambertMaterial({ color: 0xe1e1e1 }),
            cellGeometry = new THREE.CylinderGeometry(192, 192, 128, 6),
            cell = null,
            x = 0,
            y = 0,
            r = 4000;

            renderer.setSize( window.innerWidth, window.innerHeight );
			document.body.appendChild( renderer.domElement );
			renderer.domElement.setAttribute("id", "viewport");

			this.three = {
				sun: sun,
				scene: scene,
				chunks: [],
				camera: camera,
				renderer: renderer
			};

			window.three = this.three;
    	scene.add(light);
			scene.fog = new THREE.FogExp2(0xffffff, 0.00001);
			light.position.set(0, 60000, -32000);
			renderer.setClearColor(0x2B7CA1);

			camera.position.z = 15;
			this.skybox = null;

			function render (last) {
				var sys = app,
					camera = three.camera,
					delta = ((Date.now() - last) / 10000),
					time = (Date.now() / 4600),
					image = "";

				if (!! sys.userInput) {
					sys.userInput.update(delta);
				}
				if (sys.sendUpdatePacket == 30) { // send image
					image = "image uri";
					sys.sendUpdatePacket = 0;
				}

				sys.sendUpdatePacket += 1;
				if (sys.sendUpdatePacket %2 == 0 && sys.mode == "vr") {
					socket.emit('user update','{"user":"'+sys.username+'","position": {"x":'+camera.position.x+',"y":'+camera.position.y+',"z":'+camera.position.z+'},'
						+'"quaternion":{"x":'+camera.quaternion.x+',"y":'+camera.quaternion.y+',"z":'+camera.quaternion.z+',"w":'+camera.quaternion.w+'}}');

				}

				sun.rotation.x += 0.0025;
				sun.rotation.y += 0.005;
				sys.world.skybox.position.set(camera.position.x, camera.position.y, camera.position.z);
				renderer.render(scene, camera);
				last = Date.now();
				requestAnimationFrame( function () { render(last); } );
			};

			var skyTexture = THREE.ImageUtils.loadTexture("/images/data-sky-neon-3.jpg", null, function () {
				var skybox = new THREE.Object3D(), // used to use larger jpeg version sunset-5.jpg
				    skyboxFace = null,
				    skyboxSideMat = new THREE.MeshBasicMaterial({
				        map: skyTexture,
								side: 1,
								fog: false,
                color: 0xffffff // too dark.. not dark enough? 0x60daff//  0x80faff too green
				    }),
					x = 0;
				skybox = new THREE.Mesh(new THREE.OctahedronGeometry(300000, 4), skyboxSideMat);
				self.skybox = skybox;
				skybox.add(three.sun);
				three.sun.position.set(0, 18000, -24000);
				three.scene.add(skybox);
				skybox.position.set(three.camera.position.x, 0, three.camera.position.z);
				skyTexture.needsUpdate = true;

				render(0);
			});

			var configure = {
				 baseURL: 'https://vpylon.net',
				 timeout: 1000,
				 headers: {'x-access-token': localStorage.getItem("token")}
			};

			//load cells
			axios.get('/api/cells/all', configure)
				.then(function (response) {
					app.cells = response.data;
					app.cells.forEach(function (userCell){
						var cell = new Cell(userCell.cell);
					});
				})
				.catch(function (response) {
					console.log(response);
				});

				function bufferChunks () {
						var chunks = app.chunks,
								chunk = null,
								c = 0,
								coords = app.chunkCoords,
								lastCoords = app.lastChunkCoords,
								moveDir = [coords[0]-lastCoords[0], coords[1] - lastCoords[1]];
								viewDistance = app.mobile ? 3 : (window.innerWidth > 2100 ?  7  : 4),
								endCoords = [coords[0]+viewDistance, coords[1]+viewDistance],
								x = coords[0]-viewDistance,
								y = coords[1]-viewDistance;

						if (coords[0] != lastCoords[0] || coords[1] != lastCoords[1] || coords[2] != lastCoords[2]) {
								// remove old chunks
								for (c in chunks) {
									chunk = chunks[c];
									if (chunk.coords[0] < coords[0] - viewDistance || chunk.coords[0] > coords[0] + viewDistance ||
											chunk.coords[1] < coords[1] - viewDistance || chunk.coords[1] > coords[1] + viewDistance) {
											// remove this chunk
											three.scene.remove(chunk.mesh);
											chunks.splice(c, 1);
									}
								}
								// load new chunks

											if (moveDir[0] > 1 ) {
													if (moveDir[1] > 1) {

													} else if (moveDir[1] == 0) {

													} else {

													}
											} else if (moveDir[0] == 0) {
													if (moveDir[1] > 1) {

													} else if (moveDir[1] == 0) {

													} else {

													}
											} else {
													if (moveDir[1] > 1) {

													} else if (moveDir[1] == 0) {

													} else {

													}
											}
						}

						lastCoords[0] = coords[0];
						lastCoords[1] = coords[1];
						lastCoords[2] = coords[2];
						setTimeout(function () { bufferChunks(); }, 1000);
				}

				function loadChunks (coords, phase) {
					var max = app.mobile ? 3 : (window.innerWidth > 2100 ?  7  : 4);
					var cellWidth = 3 + phase, // app.mobile ? 3 : (window.innerWidth > 2000 ?  7  : 5),
					    chunk = null,
					 x = coords[0] - phase,
					 y = coords[1] - phase;

					while (x <= phase) {
					  while (y <= phase) {
							if (Math.abs(x) == coords[0]+phase || Math.abs(y) == coords[1]+phase) {
						    chunk = new Chunk([x, 0, y], mobile);
						    chunk.mesh.updateMatrix();
						    app.chunks.push(chunk);
								three.scene.add(chunk.mesh);
							}

					    y++;
					  }
						y = coords[1]-phase;
						x++;
					}

					phase ++;
					if (phase < max) {
						setTimeout(function () { loadChunks(coords, phase); }, 1000)
					} else {
						setTimeout(function () { bufferChunks() })
					}

				}

				loadChunks ([0,0,0], 0);

			//baseMesh = new THREE.Mesh(base, baseMaterial);
			//scene.add(baseMesh);
//			var groundGeom = new THREE.PlaneGeometry(100000, 100000, 12, 12);
//			var groundMat = new THREE.MeshBasicMaterial({color: 0xf0f0f0});
//			var ground = new THREE.Mesh(groundGeom, groundMat);
//			ground.rotateX(Math.PI / 2);
//			three.scene.add(ground);
    }

};
<|endoftext|>


<commit_before>// Future versions of Hyper may add additional config options,
// which will not automatically be merged into this file.
// See https://hyper.is#cfg for all currently supported options.

module.exports = {
  config: {
    // Choose either "stable" for receiving highly polished,
    // or "canary" for less polished but more frequent updates
    updateChannel: 'stable',

    // default font size in pixels for all tabs
    fontSize: 12,

    // font family with optional fallbacks
    fontFamily: '"SF Mono", Menlo, "DejaVu Sans Mono", Consolas, "Lucida Console", monospace',

    // terminal cursor background color and opacity (hex, rgb, hsl, hsv, hwb or cmyk)
    cursorColor: 'rgba(248,28,229,0.8)', // I failed to set a 45deg from bottom-left to top-right cyan to blue gradient.

    // `BEAM` for |, `UNDERLINE` for _, `BLOCK` for █
    cursorShape: 'BLOCK',

    // set to true for blinking cursor
    cursorBlink: false, // I tried to set it to `true`, but when I did, I couldn't see the cursor. After waiting a bit, it seems caused by the blinking cycle starting at blinked-out and restarting at each cursor position change.

    // color of the text
    foregroundColor: '#fff',

    // terminal background color
    backgroundColor: '#000',

    // border color (window, tabs)
    borderColor: '#333',

    // custom css to embed in the main window
    css: '',

    // custom css to embed in the terminal window
    termCSS: '',
//    termCSS: '
//	cursorColor
//	{
//		background: rgba(0,255,255,1);
//		//background: -moz-linear-gradient(45deg, rgba(0,255,255,1) 0%, rgba(0,0,255,1) 100%);
//		//background: -webkit-gradient(left bottom, right top, color-stop(0%, rgba(0,255,255,1)), color-stop(100%, rgba(0,0,255,1)));
//		//background: -webkit-linear-gradient(45deg, rgba(0,255,255,1) 0%, rgba(0,0,255,1) 100%);
//		//background: -o-linear-gradient(45deg, rgba(0,255,255,1) 0%, rgba(0,0,255,1) 100%);
//		//background: -ms-linear-gradient(45deg, rgba(0,255,255,1) 0%, rgba(0,0,255,1) 100%);
//		background: linear-gradient(45deg, rgba(0,255,255,1) 0%, rgba(0,0,255,1) 100%);
//		//filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00ffff', endColorstr='#0000ff', GradientType=1 );
//
//		//-webkit-background-clip: text;
//		background-clip: text;
//
//		//-webkit-text-fill-color: transparent;
//		color: rgba(0,0,0,0);
//	}
//	',

    // set to `true` (without backticks) if you're using a Linux setup that doesn't show native menus
    // default: `false` on Linux, `true` on Windows (ignored on macOS)
    showHamburgerMenu: '',

    // set to `false` if you want to hide the minimize, maximize and close buttons
    // additionally, set to `'left'` if you want them on the left, like in Ubuntu
    // default: `true` on windows and Linux (ignored on macOS)
    showWindowControls: '',

    // custom padding (css format, i.e.: `top right bottom left`)
    padding: '12px 14px',

    // the full list. if you're going to provide the full color palette,
    // including the 6 x 6 color cubes and the grayscale map, just provide
    // an array here instead of a color map object
    colors: {
      black: '#000000',
      red: '#ff0000',
      green: '#33ff00',
      yellow: '#ffff00',
      blue: '#0066ff',
      magenta: '#cc00ff',
      cyan: '#00ffff',
      white: '#d0d0d0',
      lightBlack: '#808080',
      lightRed: '#ff0000',
      lightGreen: '#33ff00',
      lightYellow: '#ffff00',
      lightBlue: '#0066ff',
      lightMagenta: '#cc00ff',
      lightCyan: '#00ffff',
      lightWhite: '#ffffff'
    },

    // the shell to run when spawning a new session (i.e. /usr/local/bin/fish)
    // if left empty, your system's login shell will be used by default
    //
    // Windows
    // - Make sure to use a full path if the binary name doesn't work
    // - Remove `--login` in shellArgs
    //
    // Bash on Windows
    // - Example: `C:\\Windows\\System32\\bash.exe`
    //
    // Powershell on Windows
    // - Example: `C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`
    shell: '',

    // for setting shell arguments (i.e. for using interactive shellArgs: ['-i'])
    // by default ['--login'] will be used
    shellArgs: ['--login'],

    // for environment variables
    env: {},

    // set to false for no bell
    bell: 'SOUND',

    // if true, selected text will automatically be copied to the clipboard
    copyOnSelect: false

    // if true, on right click selected text will be copied or pasted if no
    // selection is present (true by default on Windows)
    // quickEdit: true

    // URL to custom bell
    // bellSoundURL: 'http://example.com/bell.mp3',

    // for advanced config flags please refer to https://hyper.is/#cfg
  },

  // a list of plugins to fetch and install from npm
  // format: [@org/]project[#version]
  // examples:
  //   `hyperpower`
  //   `@company/project`
  //   `project#1.0.1`
  plugins: [],

  // in development, you can create a directory under
  // `~/.hyper_plugins/local/` and include it here
  // to load it and avoid it being `npm install`ed
  localPlugins: [],

  keymaps: {
    // Example
    // 'window:devtools': 'cmd+alt+o',
  }
};
<commit_msg>.hyper.js updated:   +  Cursor color set to my Omnicom OS default 45 degree from bottom-left to top-right cyan to blue cursor color gradient!!   +  Padding set   +  hyperborder plugin added   +  hyper-alt-click plugin added   +  hyperterm-cursor plugin added   +  hyperterm-final-say plugin added<commit_after>// Future versions of Hyper may add additional config options,
// which will not automatically be merged into this file.
// See https://hyper.is#cfg for all currently supported options.

module.exports = {
  config: {
    // Choose either "stable" for receiving highly polished,
    // or "canary" for less polished but more frequent updates
    updateChannel: 'stable',

    // default font size in pixels for all tabs
    fontSize: 12,

    // font family with optional fallbacks
    fontFamily: '"SF Mono", Menlo, "DejaVu Sans Mono", Consolas, "Lucida Console", monospace',

    // terminal cursor background color and opacity (hex, rgb, hsl, hsv, hwb or cmyk)
    cursorColor: 'rgba(255,255,255,0)', // 'rgba(248,28,229,0.8)',

    // `BEAM` for |, `UNDERLINE` for _, `BLOCK` for █
    cursorShape: 'BLOCK',

    // set to true for blinking cursor
    cursorBlink: false, // I tried to set it to `true`, but when I did, I couldn't see the cursor. After waiting a bit, it seems caused by the blinking cycle starting at blinked-out and restarting at each cursor position change.

    // color of the text
    foregroundColor: 'rgb(255,255,255)', // '#fff',

    // terminal background color
    backgroundColor: 'rgb(0,0,0)', // '#000',

    // border color (window, tabs)
    borderColor: '#333',

    // custom css to embed in the main window
    css: '',

    // custom css to embed in the terminal window
    termCSS: `
	.cursor-node {
		background: rgba(0,255,255,1);
		//background: -moz-linear-gradient(45deg, rgba(0,255,255,1) 0%, rgba(0,0,255,1) 100%);
		//background: -webkit-gradient(left bottom, right top, color-stop(0%, rgba(0,255,255,1)), color-stop(100%, rgba(0,0,255,1)));
		//background: -webkit-linear-gradient(45deg, rgba(0,255,255,1) 0%, rgba(0,0,255,1) 100%);
		//background: -o-linear-gradient(45deg, rgba(0,255,255,1) 0%, rgba(0,0,255,1) 100%);
		//background: -ms-linear-gradient(45deg, rgba(0,255,255,1) 0%, rgba(0,0,255,1) 100%);
		background: linear-gradient(45deg, rgba(0,255,255,1) 0%, rgba(0,0,255,1) 100%);
		//filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00ffff', endColorstr='#0000ff', GradientType=1 );

		//-webkit-background-clip: text;
		background-clip: text;

		//-webkit-text-fill-color: transparent;
		color: rgba(0,0,0,0);

		//-moz-text-stroke: 1px white;
		//-webkit-text-stroke: 1px white;
		//-o-text-stroke: 1px white;
		//-ms-text-stroke: 1px white;
		text-stroke: 1px rgba(255,255,255,1);
		text-shadow: -1px -1px 0 rgba(255,255,255,1), 1px -1px 0 rgba(255,255,255,1), -1px 1px 0 rgba(255,255,255,1), 1px 1px 0 rgba(255,255,255,1);
	}

	`,

    // set to `true` (without backticks) if you're using a Linux setup that doesn't show native menus
    // default: `false` on Linux, `true` on Windows (ignored on macOS)
    showHamburgerMenu: '',

    // set to `false` if you want to hide the minimize, maximize and close buttons
    // additionally, set to `'left'` if you want them on the left, like in Ubuntu
    // default: `true` on windows and Linux (ignored on macOS)
    showWindowControls: '',

    // custom padding (css format, i.e.: `top right bottom left`)
    padding: '0 0 0 4px',

    // the full list. if you're going to provide the full color palette,
    // including the 6 x 6 color cubes and the grayscale map, just provide
    // an array here instead of a color map object
    colors: {
      black: '#000000',
      red: '#ff0000',
      green: '#33ff00',
      yellow: '#ffff00',
      blue: '#0066ff',
      magenta: '#cc00ff',
      cyan: '#00ffff',
      white: '#d0d0d0',
      lightBlack: '#808080',
      lightRed: '#ff0000',
      lightGreen: '#33ff00',
      lightYellow: '#ffff00',
      lightBlue: '#0066ff',
      lightMagenta: '#cc00ff',
      lightCyan: '#00ffff',
      lightWhite: '#ffffff'
    },

    // the shell to run when spawning a new session (i.e. /usr/local/bin/fish)
    // if left empty, your system's login shell will be used by default
    //
    // Windows
    // - Make sure to use a full path if the binary name doesn't work
    // - Remove `--login` in shellArgs
    //
    // Bash on Windows
    // - Example: `C:\\Windows\\System32\\bash.exe`
    //
    // Powershell on Windows
    // - Example: `C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`
    shell: '',

    // for setting shell arguments (i.e. for using interactive shellArgs: ['-i'])
    // by default ['--login'] will be used
    shellArgs: ['--login'],

    // for environment variables
    env: {},

    // set to false for no bell
    bell: 'SOUND',

    // if true, selected text will automatically be copied to the clipboard
    copyOnSelect: false

    // if true, on right click selected text will be copied or pasted if no
    // selection is present (true by default on Windows)
    // quickEdit: true

    // URL to custom bell
    // bellSoundURL: 'http://example.com/bell.mp3',

    // for advanced config flags please refer to https://hyper.is/#cfg
    //hyperBorder: {
    //  borderColors: ['#fc1da7', '#fba506'],
    //  borderWidth: '2.69%', // (i) Icon dimensions: 512px^2; Icon pict width stroke incl: 446px; Icon pict stroke width or height: 12px; 12 / 446 * 100 = 2.6905829596412556
    //  borderAngle: '45deg'
    //}
 },

  // a list of plugins to fetch and install from npm
  // format: [@org/]project[#version]
  // examples:
  //   `hyperpower`
  //   `@company/project`
  //   `project#1.0.1`
  plugins: [
    //"hyperpower",
    //'hyperyellow',
    'hyperborder',
    'hyper-alt-click',
    //'hyperterm-crosshair',
    'hyperterm-cursor',
    'hyperterm-final-say'
  ],

  // in development, you can create a directory under
  // `~/.hyper_plugins/local/` and include it here
  // to load it and avoid it being `npm install`ed
  localPlugins: [],

  keymaps: {
    // Example
    // 'window:devtools': 'cmd+alt+o',
  }
};
<|endoftext|>


<commit_before>var selectorGraphs = Selector()
    .callback(function(d){
        $('#'+selectorGraphs.type()).html(d.name);
        $('#dimensions input[name='+selectorGraphs.type()+']').val(d.id).trigger('change');
        $('#modal-selector').modal('hide');
    });

function select_dimension_graph(id) {
  d3.select("#modal-selector-content").call(selectorGraphs.type(id));
  $('#modal-selector').modal('show');
}

function deactivate_dimension_graph(id) {
  $(id).siblings("button").html('Select');
  $(id).siblings("input").val("all").trigger('change');
}

dataviva.requireAttrs(['datasets'], function() {

    for (dataset in dataviva.datasets) {
        $('#datasets').append( $('<option value="'+dataset+'">'+dataviva.dictionary[dataset]+'</option>'));
    }

    $('#datasets').on('change', function() {
        $('#datasets #dataset-empty-option').remove();
        var dataset = this.value;

        $('#dimensions').empty();
        dataviva.datasets[dataset].dimensions.forEach(function(dimension, index) {
                var div = $("

").addClass("form-group"),
                label = $("").attr("for", dimension.id).addClass("control-label"),
                deactivate_button = $("<button></button>").attr("for", dimension.id).addClass("btn btn-xs btn-white pull-right")
                                        .html(dataviva.dictionary['deactivate'])
                                        .attr("onclick", "deactivate_dimension_graph(this)"),
                selector_button = $("<button></button>").attr("id", dimension.id).addClass("btn btn-block btn-outline btn-primary")
                                        .attr("onclick", "select_dimension_graph(id);")
                                        .html(dataviva.dictionary['select']);

                filter = $("<input></input>").attr("type", "hidden").attr("name", dimension.id).attr("id", 'filter'+index).val('all');

                label.html(dataviva.dictionary[dimension.id]);

                filter.change(function() {
                  $.ajax({
                        method: "GET",
                        url: "/" + lang + "/build_graph/views/" + dataset +"/" +
                            $('#dimensions #filter0').val() + "/" +
                            ($('#dimensions #filter1').val() == 'all' ? 'all' : $('#dimensions #filter1')[0].name) + "/" +
                            ($('#dimensions #filter2').val() == 'all' ? 'all' : $('#dimensions #filter2')[0].name),
                        data: {
                                filter1: $('#dimensions #filter1').val(),
                                filter2: $('#dimensions #filter2').val()
                            },
                        success: function (builds) {
                            for (i in builds) {
                                console.log(builds[i]);
                            }
                        }
                    });
                });

                if (dimension.name == 'School') {
                    div.append(filter)
                } else {
                    div.append(filter).append(label).append(deactivate_button).append(selector_button)
                }

                $('#dimensions').append(div);
        });
    });
});

<commit_msg>Creates titles selector in build_graphs<commit_after>var selectorGraphs = Selector()
    .callback(function(d){
        $('#'+selectorGraphs.type()).html(d.name);
        $('#dimensions input[name='+selectorGraphs.type()+']').val(d.id).trigger('change');
        $('#modal-selector').modal('hide');
    });

function select_dimension_graph(id) {
  d3.select("#modal-selector-content").call(selectorGraphs.type(id));
  $('#modal-selector').modal('show');
}

function deactivate_dimension_graph(id) {
  $(id).siblings("button").html('Select');
  $(id).siblings("input").val("all").trigger('change');
}

dataviva.requireAttrs(['datasets'], function() {

    for (dataset in dataviva.datasets) {
        $('#datasets').append( $('<option value="'+dataset+'">'+dataviva.dictionary[dataset]+'</option>'));
    }

    $('#datasets').on('change', function() {
        $('#datasets #dataset-empty-option').remove();
        var dataset = this.value;

        $('#dimensions').empty();
        dataviva.datasets[dataset].dimensions.forEach(function(dimension, index) {
                var div = $("

").addClass("form-group"),
                label = $("").attr("for", dimension.id).addClass("control-label"),
                deactivate_button = $("<button></button>").attr("for", dimension.id).addClass("btn btn-xs btn-white pull-right")
                                        .html(dataviva.dictionary['deactivate'])
                                        .attr("onclick", "deactivate_dimension_graph(this)"),
                selector_button = $("<button></button>").attr("id", dimension.id).addClass("btn btn-block btn-outline btn-primary")
                                        .attr("onclick", "select_dimension_graph(id);")
                                        .html(dataviva.dictionary['select']);

                filter = $("<input></input>").attr("type", "hidden").attr("name", dimension.id).attr("id", 'filter'+index).val('all');

                label.html(dataviva.dictionary[dimension.id]);

                filter.change(function() {
                      $.ajax({
                            method: "GET",
                            url: "/" + lang + "/build_graph/views/" + dataset +"/" +
                                $('#dimensions #filter0').val() + "/" +
                                ($('#dimensions #filter1').val() == 'all' ? 'all' : $('#dimensions #filter1')[0].name) + "/" +
                                ($('#dimensions #filter2').val() == 'all' ? 'all' : $('#dimensions #filter2')[0].name),
                            data: {
                                    filter1: $('#dimensions #filter1').val(),
                                    filter2: $('#dimensions #filter2').val()
                                },
                            success: function (builds) {

                                console.log(builds)
                                //('#titles').empty()
                                if(builds.builds.length > 0){
                                    //console.log(builds);
                                    builds.builds.sort(function(build1, build2){
                                            return ((build1["title"] < build2["title"]) ? -1 :
                                                ((build1["title"] > build2["title"]) ? 1 : 0));
                                    })
                                    titles = {};
                                    result = [];
                                    for (var i = 0; i< builds.builds.length ; i++) {
                                        if(builds.builds[i].title != null){
                                            title = builds.builds[i].title.replace(/\s\(.*\)/g, '');
                                            if(! (title in titles)){
                                                titles[title] = 1;
                                                result.push(title);
                                            }else{
                                                titles[title]+=1;
                                            }
                                        }
                                    }
                                    $('#titles').empty()
                                    var div = $("

").addClass("form-group").attr("id", "titles");
                                    select = $("<select></select>").addClass("form-control").attr("id", 'titles'),
                                    label = $("").attr("for", "titles").addClass("control-label"),
                                    label.html("Options");

                                    for(var i = 0; i<result.length ; i++){
                                        option = $('<option value="'+i+'">'+result[i]+'</option>')
                                        select.append(option);
                                    }

                                    div.append(label).append(select);

                                    $('#dimensions').append(div);

                                //select.chenge()
                            }
                        }
                    });

                });

                if (dimension.name == 'School') {
                    div.append(filter)
                } else {
                    div.append(filter).append(label).append(deactivate_button).append(selector_button)
                }

                $('#dimensions').append(div);
        });
    });
});

<|endoftext|>


<commit_before>define(['Ti/_/lang', 'Tizen/_/Package/PackageInformation', 'Ti/_/Evented'], function(lang, PackageInformation, Evented) {

	function onError (e, callback) {
		callback({
			code: e.code,
			success: false,
			error: e.type + ': ' + e.message
		});
	}

	var listening;

	return lang.mixProps(require.mix({}, Evented), {

		install: function(path /*DOMString*/, callback /*PackageProgressCallback*/) {
			return tizen.package.install(path, {
				onprogress: callback && function(id, progress) {
					callback({
						code: 0,
						success: true,
						id: id,
						progress: progress,
						onprogress: true,
						oncomplette: false
					});
				},
				oncomplette: callback && function(id) {
					callback({
						code: 0,
						success: true,
						id: id,
						progress: 100,
						onprogress: false,
						oncomplette: true
					});
				}

			}, callback && function(e) {
				onError(e, callback);
			});
		},

		uninstall: function(id /*PackageId*/, progressCallback /*PackageProgressCallback*/) {
			return tizen.package.uninstall(id, {
				onprogress: callback && function(id, progress) {
					callback({
						code: 0,
						success: true,
						id: id,
						progress: progress,
						onprogress: true,
						oncomplette: false
					});
				},
				oncomplette: callback && function(id) {
					callback({
						code: 0,
						success: true,
						id: id,
						onprogress: false,
						oncomplette: true
					});
				}

			}, callback && function(e) {
				onError(e, callback);
			});
		},

		getPackagesInfo: function(callback /*PackageInformationArraySuccessCallback*/) {
			return tizen.package.getPackagesInfo(callback && function(informationArray) {
				var result = [],
					i = 0,
					length = informationArray.length;
				for (; i < length; i++) {
					result.push(new PackageInformation(void 0, informationArray[i]));
				}

				callback({
					code: 0,
					success: true,
					informationArray: result
				});

			}, callback && function(e) {
				onError(e, callback);
			});
		},

		getPackageInfo: function(id /*PackageId*/) {
			var packageInfo = izen.package.getPackageInfo(id);
			return new PackageInformation(void 0, packageInfo);
		},

		addEventListener: function() {
			var self = this;
			Evented.addEventListener.apply(this, arguments);
			if (! listening) {
				tizen.package.setPackageInfoEventListener({
					oninstalled: function(info) {
						self.fireEvent('packageinstalled', {
							info: new PackageInformation(void 0, info)
						});
					},
					onupdated: function(info) {
						self.fireEvent('packageupdated', {
							info: new PackageInformation(void 0, info)
						});
					},
					onuninstalled: function(id) {
						self.fireEvent('packageuninstalled', {
							id: id
						});
					}
				});
			}
		}

	}, true);
});<commit_msg>Tizen 2.1 wrapper: fixing optional parameters: Package<commit_after>define(['Ti/_/lang', 'Tizen/_/Package/PackageInformation', 'Ti/_/Evented'], function(lang, PackageInformation, Evented) {

	function onError (e, callback) {
		callback({
			code: e.code,
			success: false,
			error: e.type + ': ' + e.message
		});
	}

	var listening;

	return lang.mixProps(require.mix({}, Evented), {

		install: function(path /*DOMString*/, callback /*PackageProgressCallback*/) {
			return tizen.package.install(path, {
				onprogress: callback && function(id, progress) {
					callback({
						code: 0,
						success: true,
						id: id,
						progress: progress,
						onprogress: true,
						oncomplette: false
					});
				},
				oncomplette: callback && function(id) {
					callback({
						code: 0,
						success: true,
						id: id,
						progress: 100,
						onprogress: false,
						oncomplette: true
					});
				}

			}, callback && function(e) {
				onError(e, callback);
			});
		},

		uninstall: function(id /*PackageId*/, progressCallback /*PackageProgressCallback*/) {
			return tizen.package.uninstall(id, {
				onprogress: callback && function(id, progress) {
					callback({
						code: 0,
						success: true,
						id: id,
						progress: progress,
						onprogress: true,
						oncomplette: false
					});
				},
				oncomplette: callback && function(id) {
					callback({
						code: 0,
						success: true,
						id: id,
						onprogress: false,
						oncomplette: true
					});
				}

			}, callback && function(e) {
				onError(e, callback);
			});
		},

		getPackagesInfo: function(callback /*PackageInformationArraySuccessCallback*/) {
			return tizen.package.getPackagesInfo(callback && function(informationArray) {
				var result = [],
					i = 0,
					length = informationArray.length;
				for (; i < length; i++) {
					result.push(new PackageInformation(void 0, informationArray[i]));
				}

				callback({
					code: 0,
					success: true,
					informationArray: result
				});

			}, callback && function(e) {
				onError(e, callback);
			});
		},

		getPackageInfo: function(id /*PackageId*/) {
			// Tizen distinguishes between undefined parameter (this gives an error) and missing parameter (correct).
			var args = [];
			(typeof id !== 'undefined') && args.push(id);
			var packageInfo = tizen.package.getPackageInfo.apply(tizen.package, args);
			return new PackageInformation(void 0, packageInfo);
		},

		addEventListener: function() {
			var self = this;
			Evented.addEventListener.apply(this, arguments);
			if (! listening) {
				tizen.package.setPackageInfoEventListener({
					oninstalled: function(info) {
						self.fireEvent('packageinstalled', {
							info: new PackageInformation(void 0, info)
						});
					},
					onupdated: function(info) {
						self.fireEvent('packageupdated', {
							info: new PackageInformation(void 0, info)
						});
					},
					onuninstalled: function(id) {
						self.fireEvent('packageuninstalled', {
							id: id
						});
					}
				});
			}
		}

	}, true);
});<|endoftext|>


<commit_before>const Path = require('path')
const {createReadStream, realpathSync} = require('fs')
const {stat} = require('fs/promises')
const log = require('sepal/log').getLogger('filesystem')

const resolvePath = (baseDir, path) => {
    const realBaseDir = realpathSync(baseDir)
    const absolutePath = realpathSync(Path.join(realBaseDir, path))
    const relativePath = Path.relative(realBaseDir, absolutePath)
    const isSubPath = !!relativePath && !relativePath.startsWith('..')
    return {
        absolutePath,
        relativePath,
        isSubPath
    }
}

const getSepalUser = request => {
    const sepalUser = request.headers['sepal-user']
    return sepalUser
        ? JSON.parse(sepalUser)
        : {}
}

const download = async (homeDir, ctx) => {
    const sepalUser = getSepalUser(ctx.request)
    if (sepalUser) {
        const username = sepalUser.username
        const {absolutePath: userHomeDir} = resolvePath(homeDir, username)
        const path = ctx.query.path
        const {absolutePath} = resolvePath(userHomeDir, path)
        const filename = Path.parse(absolutePath).base
        const stats = await stat(absolutePath)
        if (stats.isFile()) {
            log.debug(() => `Downloading: ${absolutePath}`)
            ctx.body = createReadStream(absolutePath)
            ctx.attachment(filename)
        } else {
            log.warn(() => `Cannot download non-file: ${absolutePath}`)
            ctx.response = 404
        }
    } else {
        log.warn(() => 'Cannot download: unauthenticated user')
        ctx.response.status = 401
    }
}

module.exports = {resolvePath, download}
<commit_msg>Fixed response status.<commit_after>const Path = require('path')
const {createReadStream, realpathSync} = require('fs')
const {stat} = require('fs/promises')
const log = require('sepal/log').getLogger('filesystem')

const resolvePath = (baseDir, path) => {
    const realBaseDir = realpathSync(baseDir)
    const absolutePath = realpathSync(Path.join(realBaseDir, path))
    const relativePath = Path.relative(realBaseDir, absolutePath)
    const isSubPath = !!relativePath && !relativePath.startsWith('..')
    return {
        absolutePath,
        relativePath,
        isSubPath
    }
}

const getSepalUser = request => {
    const sepalUser = request.headers['sepal-user']
    return sepalUser
        ? JSON.parse(sepalUser)
        : {}
}

const download = async (homeDir, ctx) => {
    const sepalUser = getSepalUser(ctx.request)
    if (sepalUser) {
        const username = sepalUser.username
        const {absolutePath: userHomeDir} = resolvePath(homeDir, username)
        const path = ctx.query.path
        const {absolutePath} = resolvePath(userHomeDir, path)
        const filename = Path.parse(absolutePath).base
        const stats = await stat(absolutePath)
        if (stats.isFile()) {
            log.debug(() => `Downloading: ${absolutePath}`)
            ctx.body = createReadStream(absolutePath)
            ctx.attachment(filename)
        } else {
            log.warn(() => `Cannot download non-file: ${absolutePath}`)
            ctx.response.status = 404
        }
    } else {
        log.warn(() => 'Cannot download: unauthenticated user')
        ctx.response.status = 401
    }
}

module.exports = {resolvePath, download}
<|endoftext|>


<commit_before>var FileBrowser = {
    // this is set automatically
    admin_media_prefix: '',
    // change this
    thumb_prefix: 'thumb_',
    no_thumb: 'filebrowser/img/no_thumb.gif',

    init: function() {
        // Deduce admin_media_prefix by looking at the <script>s in the
        // current document and finding the URL of *this* module.
        var scripts = document.getElementsByTagName('script');
        for (var i=0; i<scripts.length; i++) {
            if (scripts[i].src.match(/AddFileBrowser/)) {
                var idx = scripts[i].src.indexOf('filebrowser/js/AddFileBrowser');
                FileBrowser.admin_media_prefix = scripts[i].src.substring(0, idx);
                break;
            }
        }
    },
    // show FileBrowser
    show: function(id, path) {
        var href = path + "?pop=1";
        var id2=String(id).split(".").join("___");
        FBWindow = window.open(href, String(id2), 'height=600,width=840,resizable=yes,scrollbars=yes');
        FBWindow.focus();
    },
}

addEvent(window, 'load', FileBrowser.init);

<commit_msg>IE7 compatibility issue with addfilebrowser.js<commit_after>var FileBrowser = {
    // this is set automatically
    admin_media_prefix: '',
    // change this
    thumb_prefix: 'thumb_',
    no_thumb: 'filebrowser/img/no_thumb.gif',

    init: function() {
        // Deduce admin_media_prefix by looking at the <script>s in the
        // current document and finding the URL of *this* module.
        var scripts = document.getElementsByTagName('script');
        for (var i=0; i<scripts.length; i++) {
            if (scripts[i].src.match(/AddFileBrowser/)) {
                var idx = scripts[i].src.indexOf('filebrowser/js/AddFileBrowser');
                FileBrowser.admin_media_prefix = scripts[i].src.substring(0, idx);
                break;
            }
        }
    },
    // show FileBrowser
    show: function(id, path) {
        var href = path + "?pop=1";
        var id2=String(id).split(".").join("___");
        FBWindow = window.open(href, String(id2), 'height=600,width=840,resizable=yes,scrollbars=yes');
        FBWindow.focus();
    }
}

addEvent(window, 'load', FileBrowser.init);

<|endoftext|>


<commit_before>

/**
 * Provide a common method for plug-ins to check the version of DataTables being used, in order
 * to ensure compatibility.
 *  @param {string} sVersion Version string to check for, in the format "X.Y.Z". Note that the
 *    formats "X" and "X.Y" are also acceptable.
 *  @returns {boolean} true if this version of DataTables is greater or equal to the required
 *    version, or false if this version of DataTales is not suitable
 *  @static
 *  @dtopt API-Static
 *
 *  @example
 *    alert( $.fn.dataTable.fnVersionCheck( '1.9.0' ) );
 */
DataTable.fnVersionCheck = function( sVersion )
{
	/* This is cheap, but effective */
	var fnZPad = function (Zpad, count)
	{
		while(Zpad.length < count) {
			Zpad += '0';
		}
		return Zpad;
	};
	var aThis = DataTable.ext.sVersion.split('.');
	var aThat = sVersion.split('.');
	var sThis = '', sThat = '';

	for ( var i=0, iLen=aThat.length ; i<iLen ; i++ )
	{
		sThis += fnZPad( aThis[i], 3 );
		sThat += fnZPad( aThat[i], 3 );
	}

	return parseInt(sThis, 10) >= parseInt(sThat, 10);
};

/**
 * Check if a TABLE node is a DataTable table already or not.
 *  @param {node} nTable The TABLE node to check if it is a DataTable or not (note that other
 *    node types can be passed in, but will always return false).
 *  @returns {boolean} true the table given is a DataTable, or false otherwise
 *  @static
 *  @dtopt API-Static
 *
 *  @example
 *    var ex = document.getElementById('example');
 *    if ( ! $.fn.DataTable.fnIsDataTable( ex ) ) {
 *      $(ex).dataTable();
 *    }
 */
DataTable.fnIsDataTable = function ( nTable )
{
	var o = DataTable.settings;

	for ( var i=0 ; i<o.length ; i++ )
	{
		if ( o[i].nTable === nTable || o[i].nScrollHead === nTable || o[i].nScrollFoot === nTable )
		{
			return true;
		}
	}

	return false;
};

/**
 * Get all DataTable tables that have been initialised - optionally you can select to
 * get only currently visible tables.
 *  @param {boolean} [bVisible=false] Flag to indicate if you want all (default) or
 *    visible tables only.
 *  @returns {array} Array of TABLE nodes (not DataTable instances) which are DataTables
 *  @static
 *  @dtopt API-Static
 *
 *  @example
 *    var table = $.fn.dataTable.fnTables(true);
 *    if ( table.length > 0 ) {
 *      $(table).dataTable().fnAdjustColumnSizing();
 *    }
 */
DataTable.fnTables = function ( bVisible )
{
	var out = [];

	jQuery.each( DataTable.settings, function (i, o) {
		if ( !bVisible || (bVisible === true && $(o.nTable).is(':visible')) )
		{
			out.push( o.nTable );
		}
	} );

	return out;
};

<commit_msg>Update media/src/api/api.static.js<commit_after>
/**
 * Provide a common method for plug-ins to check the version of DataTables being used, in order
 * to ensure compatibility.
 *  @param {string} sVersion Version string to check for, in the format "X.Y.Z". Note that the
 *    formats "X" and "X.Y" are also acceptable.
 *  @returns {boolean} true if this version of DataTables is greater or equal to the required
 *    version, or false if this version of DataTales is not suitable
 *  @static
 *  @dtopt API-Static
 *
 *  @example
 *    alert( $.fn.dataTable.fnVersionCheck( '1.9.0' ) );
 */
DataTable.fnVersionCheck = function( sVersion )
{
	var aThis = DataTable.ext.sVersion.split('.');
	var aThat = sVersion.split('.');
	var iThis, sThat;

	for ( var i=0, iLen=aThat.length ; i<iLen ; i++ ){
		iThis = parseInt( aThis[i], 10 ) || 0;
		iThat = parseInt( aThat[i], 10 ) || 0;

		// Parts are the same, keep comparing
		if (iThis === iThat)
		{
			continue;
		}

		// Parts are different, return immediately
		return iThis > iThat;
	}
	return true;
};

/**
 * Check if a TABLE node is a DataTable table already or not.
 *  @param {node} nTable The TABLE node to check if it is a DataTable or not (note that other
 *    node types can be passed in, but will always return false).
 *  @returns {boolean} true the table given is a DataTable, or false otherwise
 *  @static
 *  @dtopt API-Static
 *
 *  @example
 *    var ex = document.getElementById('example');
 *    if ( ! $.fn.DataTable.fnIsDataTable( ex ) ) {
 *      $(ex).dataTable();
 *    }
 */
DataTable.fnIsDataTable = function ( nTable )
{
	var o = DataTable.settings;

	for ( var i=0 ; i<o.length ; i++ )
	{
		if ( o[i].nTable === nTable || o[i].nScrollHead === nTable || o[i].nScrollFoot === nTable )
		{
			return true;
		}
	}

	return false;
};

/**
 * Get all DataTable tables that have been initialised - optionally you can select to
 * get only currently visible tables.
 *  @param {boolean} [bVisible=false] Flag to indicate if you want all (default) or
 *    visible tables only.
 *  @returns {array} Array of TABLE nodes (not DataTable instances) which are DataTables
 *  @static
 *  @dtopt API-Static
 *
 *  @example
 *    var table = $.fn.dataTable.fnTables(true);
 *    if ( table.length > 0 ) {
 *      $(table).dataTable().fnAdjustColumnSizing();
 *    }
 */
DataTable.fnTables = function ( bVisible )
{
	var out = [];

	jQuery.each( DataTable.settings, function (i, o) {
		if ( !bVisible || (bVisible === true && $(o.nTable).is(':visible')) )
		{
			out.push( o.nTable );
		}
	} );

	return out;
};

<|endoftext|>