<commit_before>/**
 Klassi Automated Testing Tool
 Created by Larry Goddard
 */
/**
 Copyright © klassitech 2016 - Larry Goddard <larryg@klassitech.co.uk>

 Licensed under the Apache License, Version 2.0 (the 'License');
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an 'AS IS' BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
'use strict';
const path = require('path');
const program = require('commander');
const fs = require('fs-extra');
const pjson = require('./package.json');
const cucumber = require('cucumber');

function collectPaths(value, paths) {
  paths.push(value);
  return paths;
}

function parseRemoteArguments(argumentString) {
  if (!argumentString) {
    throw new Error('Expected an argumentString');
  }
  let argSplit = argumentString.split('/');
  let CONFIG = 0;
  let TAGS = 1;
  let parsed = {
    config: argSplit[CONFIG],
    tags: argSplit[TAGS]
  };
  return parsed;
}

let cp_path;
let envConfig;

/**
 * Create all the required files and folders needed for the framework to function correctly
 * @type {string}
 */
let reports = './reports';
let fileDnldFldr = './shared-objects/fileDnldFolder/';
let docsFolder = './shared-objects/docs';
let file = ('../shared-objects/docs/userAgent.txt');

fs.ensureDirSync(reports, function(err) {
  if (err) {
    console.log('The Reports Folder has NOT been created: ' + err.stack);
  }
});
fs.ensureDirSync(fileDnldFldr, function(err) {
  if (err) {
    console.log('The File Download Folder has NOT been created: ' + err.stack);
  }
});
fs.ensureDir(docsFolder, function(err) {
  if (err) {
    console.log('The Docs Folder has NOT been created: ' + err.stack);
  }
});
fs.ensureFileSync(file, function(err) {
  if (err) {
    console.log('The fileName has NOT been created: ' + err.stack);
  }
});

program
  .version(pjson.version)
  .description(pjson.description)
  .option(
    '-b, --browsers [optional]',
    'name of browsers to use. defaults to chrome',
    /(chrome|edge|FIREFOX|iexplorer|safari|tabletGalaxy|tabletiPad)$/i,
    'chrome'
  )
  .option('-c, --context <path>', 'contextual root path for project-specific features, steps, objects etc', './')
  .option('-d, --disableReport [optional]', 'Disables the auto opening the browser with test report')
  .option('-e, --email [optional]', 'email for sending reports to stakeholders')
  .option('-f, --featuresPath <path>', 'path to feature definitions. defaults to ./features',
    'features')
  .option('-F, --featuresFiles <path>', 'comma-separated list of feature files to run')
  .option('-g, --reportName [optional]', 'basename for report files e.g. use report for report.json', global.reportName)
  .option('-n, --environment [<path>]', 'name of environment to run the framework / test in. default to test', /^(dev|test|uat|preprod|prod)$/i, 'test')
  .option('-o, --sharedObjects <paths>', 'path to shared objects (repeatable). defaults to ./shared-objects', collectPaths, ['shared-objects'])
  .option('-p, --pageObjects <path>', 'path to page objects. defaults to ./page-objects', 'page-objects')
  .option('-r, --reports <path>', 'output path to save reports. defaults to ./reports', 'reports')
  .option('-s, --steps <path>', 'path to step definitions. defaults to ./step_definitions', 'step_definitions')
  .option('-t, --tags <tagname>', 'name of tag to run', collectPaths, [])
  .option('-u, --updateBaselineImage [optional]', 'automatically update the baseline image after a failed comparison')
  .option('-w, --remoteService [optional]', 'which remote browser service, if any, should be used e.g. browserstack', '' )
  .option('-x, --extraSettings [optional]', 'further piped configs split with pipes', '')
  .option('-a, --aces [optional]', 'the switch to change the relative path for nested tests folders'
  )
  .parse(process.argv);

program.on('--help', function() {
  console.log('For more details please visit https://github.com/larryg01/klassi-js#readme\n');
});

let settings = {
  aces: program.aces,
  projectRoot: program.context,
  reportName: program.reportName,
  browserName: program.browsers,
  disableReport: program.disableReport,
  updateBaselineImage: program.updateBaselineImage,
  defaultTimeout: '300000 * 1000', // 5 mins
  remoteService: program.remoteService
};

/**
 * Setting and Naming the Project Globally
 * @type {string}
 */
global.projectName = process.env.PROJECT_NAME || projectName;

/**
 * Setting and Naming the Project Report files Globally
 * @type {string}
 */
if (program.aces) {
  envConfig = require('./projects/' + projectName + '/test/configs/envConfig');
} else {
  envConfig = require('./projects/' + projectName + '/configs/envConfig');
}
let reportName = envConfig.reportName;
let projectReportName = envConfig.projectReportName;
global.reportName = process.env.REPORT_NAME || reportName;
global.projectReportName = process.env.PROJECT_REPORT_NAME || projectReportName;

if (program.remoteService && program.extraSettings) {
  let additionalSettings = parseRemoteArguments(program.extraSettings);
  settings.remoteConfig = additionalSettings.config;
  /* this approach supports a single string defining both the target config and tags
    e.g. 'win10-chrome/@tag1,@tag2'
   */
  if (additionalSettings.tags) {
    if (program.tags) {
      throw new Error('Cannot sent two types of tags - either use -x or -t');
    }
    // TODO: test this on multiple tags
    program.tags = additionalSettings.tags;
  }
}

function getProjectPath(objectName) {
  return path.resolve(settings.projectRoot + program[objectName]);
}

let paths = {
  pageObjects: getProjectPath('pageObjects'),
  reports: getProjectPath('reports'),
  featuresPath: getProjectPath('featuresPath'),
  sharedObjects: program.sharedObjects.map(function(item) {
    return path.resolve(settings.projectRoot + item);
  })
};

/**
 * expose settings and paths for global use
 * */
global.browserName = program.browsers;
global.settings = settings;
global.paths = paths;

/**
 * add helpers and making it global
 */
if (program.aces) {
  cp_path = './projects/' + projectName + '/test/settings/helpers.js';
  console.log(cp_path);
} else {
  cp_path = './projects/' + projectName + '/settings/helpers.js';
}
global.helpers = require(cp_path);

/**
 *  adding global date function
 */
global.date = require('./runtime/confSettings').currentDate();
global.dateTime = require('./runtime/confSettings').reportDate();

/**
 * store EnvName globally (used within world.js when building browser)
 */
global.envName = program.environment;

/**
 * rewrite command line switches for cucumber
 */
process.argv.splice(2, 100);

/**
 * specify the feature files folder (this must be the first argument for Cucumber)
 */
process.argv.push(paths.featuresPath);

/**
 * specify the feature files to be executed
 */
if (program.featureFile) {
  let splitFeatureFiles = program.featureFile.split(',');
  splitFeatureFiles.forEach(function(feature) {
    process.argv.push(feature);
  });
}

/**
 * add switch to tell cucumber to produce json report files
 */
// // single run report
// process.argv.push(
//   '-f',
//   '../../node_modules/cucumber-pretty',
//   '-f',
//   'json:' +
//     path.resolve(
//       __dirname,
//       paths.reports,
//       projectName + ' ' + settings.reportName + '-' + date + '.json'
//     )
// );

if (program.aces) {
  cp_path = '../../../node_modules/cucumber-pretty';
} else {
  cp_path = '../../node_modules/cucumber-pretty';
}
// process.argv.push(
//   '-f',
//   cp_path,
//   '-f',
//   'json:' +
//   path.resolve(
//     __dirname,
//     paths.reports,
//     projectName + ' ' + global.reportName + '-' + date + '.json'
//   )
// );

// multi run report
process.argv.push(
  '-f',
  cp_path,
  '-f',
  'json:' +
    path.resolve(global.paths.reports, browserName + '-' + dateTime + '.json')
); // getting the full JSON file report name

/**
 * add cucumber world as first required script (this sets up the globals)
 */
process.argv.push('-r', path.resolve(__dirname, './runtime/world.js'));

/**
 * add path to import step definitions
 */
process.argv.push('-r', path.resolve(program.steps));

/**
 * add tag to the scenarios
 */
if (program.tags) {
  process.argv.push('-t', program.tags);
}

/**
 * Add split to run multiple browsers from the command line
 */
if (program.browsers) {
  let splitBrowsers = program.browsers.split(',');
  splitBrowsers.forEach(function(browser) {
    process.argv.push('-b', browser);
  });
}

/**
 * add strict option (fail if there are any undefined or pending steps)
 */
process.argv.push('-S');

/**
 * execute cucumber Cli
 */
global.cucumber = cucumber;

let klassiCli = new (require('cucumber')).Cli({
  argv: process.argv,
  cwd: process.cwd(),
  stdout: process.stdout
});

new Promise(function(resolve, reject) {
  try {
    klassiCli.run(function(success) {
      resolve = success ? 0 : 1;
      function exitNow() {
        process.exit(resolve);
      }
      if (process.stdout.write('')) {
        exitNow();
      } else {
        /**
         * write() returned false, kernel buffer is not empty yet...
         */
        process.stdout.on('drain', exitNow);
      }
    });
  } catch (err) {
    console.log('cucumber integration has failed ' + err.message);
    reject(err);
    throw err;
  }
});
<commit_msg>updating run scripts - package.json<commit_after>/**
 Klassi Automated Testing Tool
 Created by Larry Goddard
 */
/**
 Copyright © klassitech 2016 - Larry Goddard <larryg@klassitech.co.uk>

 Licensed under the Apache License, Version 2.0 (the 'License');
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an 'AS IS' BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
'use strict';
const path = require('path');
const program = require('commander');
const fs = require('fs-extra');
const pjson = require('./package.json');
const cucumber = require('cucumber');

function collectPaths(value, paths) {
  paths.push(value);
  return paths;
}

function parseRemoteArguments(argumentString) {
  if (!argumentString) {
    throw new Error('Expected an argumentString');
  }
  let argSplit = argumentString.split('/');
  let CONFIG = 0;
  let TAGS = 1;
  let parsed = {
    config: argSplit[CONFIG],
    tags: argSplit[TAGS]
  };
  return parsed;
}

let cp_path;
let envConfig;

/**
 * Create all the required files and folders needed for the framework to function correctly
 * @type {string}
 */
let reports = './reports';
let fileDnldFldr = './shared-objects/fileDnldFolder/';
let docsFolder = './shared-objects/docs';
let file = ('../shared-objects/docs/userAgent.txt');

fs.ensureDirSync(reports, function(err) {
  if (err) {
    console.log('The Reports Folder has NOT been created: ' + err.stack);
  }
});
fs.ensureDirSync(fileDnldFldr, function(err) {
  if (err) {
    console.log('The File Download Folder has NOT been created: ' + err.stack);
  }
});
fs.ensureDir(docsFolder, function(err) {
  if (err) {
    console.log('The Docs Folder has NOT been created: ' + err.stack);
  }
});
fs.ensureFileSync(file, function(err) {
  if (err) {
    console.log('The fileName has NOT been created: ' + err.stack);
  }
});

program
  .version(pjson.version)
  .description(pjson.description)
  .option(
    '-b, --browsers [optional]',
    'name of browsers to use. defaults to chrome',
    /(chrome|edge|FIREFOX|iexplorer|safari|tabletGalaxy|tabletiPad)$/i,
    'chrome'
  )
  .option('-c, --context <path>', 'contextual root path for project-specific features, steps, objects etc', './')
  .option('-d, --disableReport [optional]', 'Disables the auto opening the browser with test report')
  .option('-e, --email [optional]', 'email for sending reports to stakeholders')
  .option('-f, --featuresPath <path>', 'path to feature definitions. defaults to ./features',
    'features')
  .option('-F, --featuresFiles <path>', 'comma-separated list of feature files to run')
  .option('-g, --reportName [optional]', 'basename for report files e.g. use report for report.json', global.reportName)
  .option('-n, --environment [<path>]', 'name of environment to run the framework / test in. default to test', /^(dev|test|uat|preprod|prod)$/i, 'test')
  .option('-o, --sharedObjects <paths>', 'path to shared objects (repeatable). defaults to ./shared-objects', collectPaths, ['shared-objects'])
  .option('-p, --pageObjects <path>', 'path to page objects. defaults to ./page-objects', 'page-objects')
  .option('-r, --reports <path>', 'output path to save reports. defaults to ./reports', 'reports')
  .option('-s, --steps <path>', 'path to step definitions. defaults to ./step_definitions', 'step_definitions')
  .option('-t, --tags <tagname>', 'name of tag to run', collectPaths, [])
  .option('-u, --updateBaselineImage [optional]', 'automatically update the baseline image after a failed comparison')
  .option('-w, --remoteService [optional]', 'which remote browser service, if any, should be used e.g. browserstack', '' )
  .option('-x, --extraSettings [optional]', 'further piped configs split with pipes', '')
  .option('-a, --aces [optional]', 'the switch to change the relative path for nested tests folders'
  )
  .parse(process.argv);

program.on('--help', function() {
  console.log('For more details please visit https://github.com/larryg01/klassi-js#readme\n');
});

let settings = {
  aces: program.aces,
  projectRoot: program.context,
  reportName: program.reportName,
  browserName: program.browsers,
  disableReport: program.disableReport,
  updateBaselineImage: program.updateBaselineImage,
  defaultTimeout: '300000 * 1000', // 5 mins
  remoteService: program.remoteService
};

/**
 * Setting and Naming the Project Globally
 * @type {string}
 */
global.projectName = process.env.PROJECT_NAME;

/**
 * Setting and Naming the Project Report files Globally
 * @type {string}
 */
if (program.aces) {
  envConfig = require('./projects/' + projectName + '/test/configs/envConfig');
} else {
  envConfig = require('./projects/' + projectName + '/configs/envConfig');
}
let reportName = envConfig.reportName;
let projectReportName = envConfig.projectReportName;
global.reportName = process.env.REPORT_NAME || reportName;
global.projectReportName = process.env.PROJECT_REPORT_NAME || projectReportName;

if (program.remoteService && program.extraSettings) {
  let additionalSettings = parseRemoteArguments(program.extraSettings);
  settings.remoteConfig = additionalSettings.config;
  /* this approach supports a single string defining both the target config and tags
    e.g. 'win10-chrome/@tag1,@tag2'
   */
  if (additionalSettings.tags) {
    if (program.tags) {
      throw new Error('Cannot sent two types of tags - either use -x or -t');
    }
    // TODO: test this on multiple tags
    program.tags = additionalSettings.tags;
  }
}

function getProjectPath(objectName) {
  return path.resolve(settings.projectRoot + program[objectName]);
}

let paths = {
  pageObjects: getProjectPath('pageObjects'),
  reports: getProjectPath('reports'),
  featuresPath: getProjectPath('featuresPath'),
  sharedObjects: program.sharedObjects.map(function(item) {
    return path.resolve(settings.projectRoot + item);
  })
};

/**
 * expose settings and paths for global use
 * */
global.browserName = program.browsers;
global.settings = settings;
global.paths = paths;

/**
 * add helpers and making it global
 */
if (program.aces) {
  cp_path = './projects/' + projectName + '/test/settings/helpers.js';
  console.log(cp_path);
} else {
  cp_path = './projects/' + projectName + '/settings/helpers.js';
}
global.helpers = require(cp_path);

/**
 *  adding global date function
 */
global.date = require('./runtime/confSettings').currentDate();
global.dateTime = require('./runtime/confSettings').reportDate();

/**
 * store EnvName globally (used within world.js when building browser)
 */
global.envName = program.environment;

/**
 * rewrite command line switches for cucumber
 */
process.argv.splice(2, 100);

/**
 * specify the feature files folder (this must be the first argument for Cucumber)
 */
process.argv.push(paths.featuresPath);

/**
 * specify the feature files to be executed
 */
if (program.featureFile) {
  let splitFeatureFiles = program.featureFile.split(',');
  splitFeatureFiles.forEach(function(feature) {
    process.argv.push(feature);
  });
}

/**
 * add switch to tell cucumber to produce json report files
 */
// // single run report
// process.argv.push(
//   '-f',
//   '../../node_modules/cucumber-pretty',
//   '-f',
//   'json:' +
//     path.resolve(
//       __dirname,
//       paths.reports,
//       projectName + ' ' + settings.reportName + '-' + date + '.json'
//     )
// );

if (program.aces) {
  cp_path = '../../../node_modules/cucumber-pretty';
} else {
  cp_path = '../../node_modules/cucumber-pretty';
}
// process.argv.push(
//   '-f',
//   cp_path,
//   '-f',
//   'json:' +
//   path.resolve(
//     __dirname,
//     paths.reports,
//     projectName + ' ' + global.reportName + '-' + date + '.json'
//   )
// );

// multi run report
process.argv.push(
  '-f',
  cp_path,
  '-f',
  'json:' +
    path.resolve(global.paths.reports, browserName + '-' + dateTime + '.json')
); // getting the full JSON file report name

/**
 * add cucumber world as first required script (this sets up the globals)
 */
process.argv.push('-r', path.resolve(__dirname, './runtime/world.js'));

/**
 * add path to import step definitions
 */
process.argv.push('-r', path.resolve(program.steps));

/**
 * add tag to the scenarios
 */
if (program.tags) {
  process.argv.push('-t', program.tags);
}

/**
 * Add split to run multiple browsers from the command line
 */
if (program.browsers) {
  let splitBrowsers = program.browsers.split(',');
  splitBrowsers.forEach(function(browser) {
    process.argv.push('-b', browser);
  });
}

/**
 * add strict option (fail if there are any undefined or pending steps)
 */
process.argv.push('-S');

/**
 * execute cucumber Cli
 */
global.cucumber = cucumber;

let klassiCli = new (require('cucumber')).Cli({
  argv: process.argv,
  cwd: process.cwd(),
  stdout: process.stdout
});

new Promise(function(resolve, reject) {
  try {
    klassiCli.run(function(success) {
      resolve = success ? 0 : 1;
      function exitNow() {
        process.exit(resolve);
      }
      if (process.stdout.write('')) {
        exitNow();
      } else {
        /**
         * write() returned false, kernel buffer is not empty yet...
         */
        process.stdout.on('drain', exitNow);
      }
    });
  } catch (err) {
    console.log('cucumber integration has failed ' + err.message);
    reject(err);
    throw err;
  }
});
<|endoftext|>


<commit_before>
/**
 * @ngdoc directive
 * @name ionRefresher
 * @module ionic
 * @restrict E
 * @parent ionic.directive:ionContent, ionic.directive:ionScroll
 * @description
 * Allows you to add pull-to-refresh to a scrollView.
 *
 * Place it as the first child of your {@link ionic.directive:ionContent} or
 * {@link ionic.directive:ionScroll} element.
 *
 * When refreshing is complete, $broadcast the 'scroll.refreshComplete' event
 * from your controller.
 *
 * @usage
 *
 * ```html
 * <ion-content ng-controller="MyController">
 *   <ion-refresher
 *     pulling-text="Pull to refresh..."
 *     on-refresh="doRefresh()">
 *   </ion-refresher>
 *   <ion-list>
 *     <ion-item ng-repeat="item in items"></ion-item>
 *   </ion-list>
 * </ion-content>
 * ```
 * ```js
 * angular.module('testApp', ['ionic'])
 * .controller('MyController', function($scope, $http) {
 *   $scope.items = [1,2,3];
 *   $scope.doRefresh = function() {
 *     $http.get('/new-items')
 *      .success(function(newItems) {
 *        $scope.items = newItems;
 *      })
 *      .finally(function() {
 *        // Stop the ion-refresher from spinning
 *        $scope.$broadcast('scroll.refreshComplete');
 *      });
 *   };
 * });
 * ```
 *
 * @param {expression=} on-refresh Called when the user pulls down enough and lets go
 * of the refresher.
 * @param {expression=} on-pulling Called when the user starts to pull down
 * on the refresher.
 * @param {string=} pulling-text The text to display while the user is pulling down.
 * @param {string=} pulling-icon The icon to display while the user is pulling down.
 * Default: 'ion-android-arrow-down'.
 * @param {string=} spinner The {@link ionic.directive:ionSpinner} icon to display
 * after user lets go of the refresher. The SVG {@link ionic.directive:ionSpinner}
 * is now the default, replacing rotating font icons. Set to `none` to disable both the
 * spinner and the icon.
 * @param {string=} refreshing-icon The font icon to display after user lets go of the
 * refresher. This is depreicated in favor of the SVG {@link ionic.directive:ionSpinner}.
 * @param {boolean=} disable-pulling-rotation Disables the rotation animation of the pulling
 * icon when it reaches its activated threshold. To be used with a custom `pulling-icon`.
 *
 */
IonicModule
.directive('ionRefresher', [function() {
  return {
    restrict: 'E',
    replace: true,
    require: ['?^$ionicScroll', 'ionRefresher'],
    controller: '$ionicRefresher',
    template:
    '
' +
      '
' +
        '
' +
          '' +
        '
' +
        '

' +
        '
' +
          '<ion-spinner ng-if="showSpinner" icon="{{spinner}}"></ion-spinner>' +
          '' +
        '
' +
        '

' +
      '
' +
    '
',
    link: function($scope, $element, $attrs, ctrls) {

      // JS Scrolling uses the scroll controller
      var scrollCtrl = ctrls[0],
          refresherCtrl = ctrls[1];
      if (!scrollCtrl || scrollCtrl.isNative()) {
        // Kick off native scrolling
        refresherCtrl.init();
      } else {
        $element[0].classList.add('js-scrolling');
        scrollCtrl._setRefresher(
          $scope,
          $element[0],
          refresherCtrl.getRefresherDomMethods()
        );

        $scope.$on('scroll.refreshComplete', function() {
          $scope.$evalAsync(function() {
            scrollCtrl.scrollView.finishPullToRefresh();
          });
        });
      }

    }
  };
}]);
<commit_msg>Fix small typo in docblock<commit_after>
/**
 * @ngdoc directive
 * @name ionRefresher
 * @module ionic
 * @restrict E
 * @parent ionic.directive:ionContent, ionic.directive:ionScroll
 * @description
 * Allows you to add pull-to-refresh to a scrollView.
 *
 * Place it as the first child of your {@link ionic.directive:ionContent} or
 * {@link ionic.directive:ionScroll} element.
 *
 * When refreshing is complete, $broadcast the 'scroll.refreshComplete' event
 * from your controller.
 *
 * @usage
 *
 * ```html
 * <ion-content ng-controller="MyController">
 *   <ion-refresher
 *     pulling-text="Pull to refresh..."
 *     on-refresh="doRefresh()">
 *   </ion-refresher>
 *   <ion-list>
 *     <ion-item ng-repeat="item in items"></ion-item>
 *   </ion-list>
 * </ion-content>
 * ```
 * ```js
 * angular.module('testApp', ['ionic'])
 * .controller('MyController', function($scope, $http) {
 *   $scope.items = [1,2,3];
 *   $scope.doRefresh = function() {
 *     $http.get('/new-items')
 *      .success(function(newItems) {
 *        $scope.items = newItems;
 *      })
 *      .finally(function() {
 *        // Stop the ion-refresher from spinning
 *        $scope.$broadcast('scroll.refreshComplete');
 *      });
 *   };
 * });
 * ```
 *
 * @param {expression=} on-refresh Called when the user pulls down enough and lets go
 * of the refresher.
 * @param {expression=} on-pulling Called when the user starts to pull down
 * on the refresher.
 * @param {string=} pulling-text The text to display while the user is pulling down.
 * @param {string=} pulling-icon The icon to display while the user is pulling down.
 * Default: 'ion-android-arrow-down'.
 * @param {string=} spinner The {@link ionic.directive:ionSpinner} icon to display
 * after user lets go of the refresher. The SVG {@link ionic.directive:ionSpinner}
 * is now the default, replacing rotating font icons. Set to `none` to disable both the
 * spinner and the icon.
 * @param {string=} refreshing-icon The font icon to display after user lets go of the
 * refresher. This is deprecated in favor of the SVG {@link ionic.directive:ionSpinner}.
 * @param {boolean=} disable-pulling-rotation Disables the rotation animation of the pulling
 * icon when it reaches its activated threshold. To be used with a custom `pulling-icon`.
 *
 */
IonicModule
.directive('ionRefresher', [function() {
  return {
    restrict: 'E',
    replace: true,
    require: ['?^$ionicScroll', 'ionRefresher'],
    controller: '$ionicRefresher',
    template:
    '
' +
      '
' +
        '
' +
          '' +
        '
' +
        '

' +
        '
' +
          '<ion-spinner ng-if="showSpinner" icon="{{spinner}}"></ion-spinner>' +
          '' +
        '
' +
        '

' +
      '
' +
    '
',
    link: function($scope, $element, $attrs, ctrls) {

      // JS Scrolling uses the scroll controller
      var scrollCtrl = ctrls[0],
          refresherCtrl = ctrls[1];
      if (!scrollCtrl || scrollCtrl.isNative()) {
        // Kick off native scrolling
        refresherCtrl.init();
      } else {
        $element[0].classList.add('js-scrolling');
        scrollCtrl._setRefresher(
          $scope,
          $element[0],
          refresherCtrl.getRefresherDomMethods()
        );

        $scope.$on('scroll.refreshComplete', function() {
          $scope.$evalAsync(function() {
            scrollCtrl.scrollView.finishPullToRefresh();
          });
        });
      }

    }
  };
}]);
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');

var SWITCH_SOURCEDIR = "--sourceDir", SWITCH_DESTINATIONDIR = "--destinationDir", SWITCH_OVERWRITE = "-overwrite";
var EXTENSION_MARKDOWN = /\.md$/;
var WRITE_PERMISSIONS = 0644;

var sourceDir, destinationDir, overwrite;

process.argv.forEach(function(arg) {
	if (arg.indexOf(SWITCH_SOURCEDIR) === 0 && arg.indexOf("=") !== -1) {
		sourceDir = arg.substring(arg.indexOf("=") + 1);
	} else if (arg.indexOf(SWITCH_DESTINATIONDIR) === 0 && arg.indexOf("=") !== -1) {
		destinationDir = arg.substring(arg.indexOf("=") + 1);
	} else if (arg.indexOf(SWITCH_OVERWRITE) === 0) {
		overwrite = true;
	}
});

if (!sourceDir || !destinationDir) {
	console.log("Usage: node markdownProcessor " + SWITCH_SOURCEDIR + "=<sourceDirectory> " + SWITCH_DESTINATIONDIR + "=<destinationDirectory> [" + SWITCH_OVERWRITE + "]");
	process.exit();
}

if (!fs.existsSync(sourceDir)) {
	console.log("Source directory does not exist: " + sourceDir);
	process.exit();
}

if (!fs.existsSync(destinationDir)) {
	console.log("Destination directory does not exist: " + destinationDir);
	process.exit();
}

var writeStat = fs.statSync(destinationDir);
var writeBlockSize = writeStat.blksize;

var filenames = fs.readdirSync(sourceDir);
filenames.forEach(function(current) {
	if (EXTENSION_MARKDOWN.test(current)) {
		var sourcePath = path.join(sourceDir, current);
		fs.open(sourcePath, "r", null, function(err, readFd) {
			if (readFd) {
				var readStat = fs.fstatSync(readFd);
				var readBlockSize = readStat.blksize;
				var fileSize = readStat.size;
				var buffer = new Buffer(fileSize);
				var totalReadCount = 0;
				do {
					var length = Math.min(readBlockSize, fileSize - totalReadCount);
					var readCount = fs.readSync(readFd, buffer, totalReadCount, length, null);
					if (!readCount) {
						break;
					}
					totalReadCount += readCount;
				} while (totalReadCount < fileSize);
				if (totalReadCount !== fileSize) {
					console.log("Failed to read the full content of file " + sourcePath);
				} else {
					var fileText = buffer.toString("utf8", 0, buffer.length); // TODO use marked to generate HTML

					var destinationPath = path.join(destinationDir, current);
					var writeFlags = overwrite ? "w" : "wx";
					fs.open(destinationPath, writeFlags, WRITE_PERMISSIONS, function(writeErr, writeFd) {
						if (writeFd) {
							var totalWriteCount = 0;
							do {
								length = Math.min(writeBlockSize, buffer.length - totalWriteCount);
								var writeCount = fs.writeSync(writeFd, buffer, totalWriteCount, length, null);
								if (!writeCount) {
									console.log("0-length write, running away" + destinationPath);
									break;
								}
								totalWriteCount += writeCount;
							} while (totalWriteCount < buffer.length);
							if (totalWriteCount !== buffer.length) {
								console.log("Failed to write the full content of file " + destinationPath);
							}
						}
						fs.close(writeFd);
					});
				}
			}
			fs.close(readFd);
		});
	}
});
<commit_msg>temporarily remove fs.close() invocations<commit_after>var fs = require('fs');
var path = require('path');

var SWITCH_SOURCEDIR = "--sourceDir", SWITCH_DESTINATIONDIR = "--destinationDir", SWITCH_OVERWRITE = "-overwrite";
var EXTENSION_MARKDOWN = /\.md$/;
var WRITE_PERMISSIONS = 0644;

var sourceDir, destinationDir, overwrite;

process.argv.forEach(function(arg) {
	if (arg.indexOf(SWITCH_SOURCEDIR) === 0 && arg.indexOf("=") !== -1) {
		sourceDir = arg.substring(arg.indexOf("=") + 1);
	} else if (arg.indexOf(SWITCH_DESTINATIONDIR) === 0 && arg.indexOf("=") !== -1) {
		destinationDir = arg.substring(arg.indexOf("=") + 1);
	} else if (arg.indexOf(SWITCH_OVERWRITE) === 0) {
		overwrite = true;
	}
});

if (!sourceDir || !destinationDir) {
	console.log("Usage: node markdownProcessor " + SWITCH_SOURCEDIR + "=<sourceDirectory> " + SWITCH_DESTINATIONDIR + "=<destinationDirectory> [" + SWITCH_OVERWRITE + "]");
	process.exit();
}

if (!fs.existsSync(sourceDir)) {
	console.log("Source directory does not exist: " + sourceDir);
	process.exit();
}

if (!fs.existsSync(destinationDir)) {
	console.log("Destination directory does not exist: " + destinationDir);
	process.exit();
}

var writeStat = fs.statSync(destinationDir);
var writeBlockSize = writeStat.blksize;

var filenames = fs.readdirSync(sourceDir);
filenames.forEach(function(current) {
	if (EXTENSION_MARKDOWN.test(current)) {
		var sourcePath = path.join(sourceDir, current);
		fs.open(sourcePath, "r", null, function(err, readFd) {
			if (readFd) {
				var readStat = fs.fstatSync(readFd);
				var readBlockSize = readStat.blksize;
				var fileSize = readStat.size;
				var buffer = new Buffer(fileSize);
				var totalReadCount = 0;
				do {
					var length = Math.min(readBlockSize, fileSize - totalReadCount);
					var readCount = fs.readSync(readFd, buffer, totalReadCount, length, null);
					if (!readCount) {
						break;
					}
					totalReadCount += readCount;
				} while (totalReadCount < fileSize);
				if (totalReadCount !== fileSize) {
					console.log("Failed to read the full content of file " + sourcePath);
				} else {
					var fileText = buffer.toString("utf8", 0, buffer.length); // TODO use marked to generate HTML

					var destinationPath = path.join(destinationDir, current);
					var writeFlags = overwrite ? "w" : "wx";
					fs.open(destinationPath, writeFlags, WRITE_PERMISSIONS, function(writeErr, writeFd) {
						if (writeFd) {
							var totalWriteCount = 0;
							do {
								length = Math.min(writeBlockSize, buffer.length - totalWriteCount);
								var writeCount = fs.writeSync(writeFd, buffer, totalWriteCount, length, null);
								if (!writeCount) {
									console.log("0-length write, running away" + destinationPath);
									break;
								}
								totalWriteCount += writeCount;
							} while (totalWriteCount < buffer.length);
							if (totalWriteCount !== buffer.length) {
								console.log("Failed to write the full content of file " + destinationPath);
							}
						}
//						fs.close(writeFd);
					});
				}
			}
//			fs.closeSync(readFd);
		});
	}
});
<|endoftext|>


<commit_before>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');
    gvm.studentId = $("#saveBtn").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.menuLanguage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("MenuLanguage");}, gvm);

    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.assessCompletementNumberToSubmit = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessCompletementNumberToSubmit");}, gvm);
    gvm.projectWeight = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectWeight");}, gvm);
    gvm.assessCompletementNumberSubmitted = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessCompletementNumberSubmitted");}, gvm);
    gvm.saveBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);
    gvm.cancelBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CancelBtn");}, gvm);
    gvm.documentScore = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DocumentScore");}, gvm);
    gvm.documentSubmit = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DocumentSubmit");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.documents = ko.observableArray([]);
    gvm.userData = ko.observableArray([]);

    gvm.addDocument = function(id,parentId, description, weight, pointType,score) {
        var doc = new Document(id,parentId,description,weight,pointType,score);
        gvm.documents.push(doc);
    };

    gvm.getAllData = function()
    {
        $.getJSON('/api/project/'+ gvm.projectId + '/documents/' + gvm.studentId, function(data) {
            $.each(data, function(i, item) {
                gvm.enterData(item);
                gvm.userData.push(item);
            });
        });
    };

    gvm.enterData = function(data)
    {
        gvm.documents().forEach(function(item) {
           if(data.document == item.parentId()) {
               item.id(data.id);
               item.score(data.score);
               item.notSubmitted(data.not_submitted);
               if (item.pointType() == "Ja/Nee") {
                   if (item.score() > 0) {
                       item.isChecked("yes");
                       item.score(100);
                   }
                   else {
                       item.isChecked("no");
                       item.score(0);
                   }
               }
           }
        });
        console.log(gvm.documents());
    };

    gvm.getDocumentsToSubmit = function() {
        $.getJSON('/api/project/'+ gvm.projectId + '/documents', function(data) {
            $.each(data, function(i, item) {
                var array = [];
                for(var i = 0; i < item.nr_documents; i++)
                {
                    array.push({id: 0,parentId: 0, nr: i, score: 0 });
                }
                gvm.addDocument(0, item.id, item.description, item.weight, item.point_type, 0, array, 0);
            });
            gvm.getAllData();
        });
    };

    gvm.changeNotSubmitted = function(data,parent) {
        console.log(data);
        console.log(parent);
    };

    gvm.clearStructure = function()
    {
        gvm.userData.destroyAll();
        gvm.documents.destroyAll();
    }
}

function Document(id,parentId,description ,weight,pointType, score, nrDocuments, notSubmitted, checked)
{
    var self = this;
    console.log(nrDocuments);
    self.documents = {
        id: ko.observable(id),
        parentId: ko.observable(parentId),
        description: ko.observable(description),
        pointType: ko.observable(pointType),
        weight: ko.observable(weight),
        score: ko.observable(score),
        isChecked: ko.observable(checked),
        nrDocuments: ko.observableArray(nrDocuments),
        notSubmitted: ko.observable(notSubmitted)
    }

    self.documents.checkedValue =  ko.computed({
        //return a formatted price
        read: function() {
            return self.documents.isChecked();
        },
        //if the value changes, make sure that we store a number back to price
        write: function(newValue) {
            self.documents.isChecked(newValue);
            if(self.documents.isChecked() == "yes")
            {
                self.documents.score(100);
            }
            else {
                self.documents.score(0);
            }
        },
        owner: this
    });

    return self.documents;
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getDocumentsToSubmit();

    $("#saveBtn").click(function() {
        $.ajax({
            type: "POST",
            url: "/api/documents/" + projectid + "/user/" + viewModel.studentId + "/save",
            data: ko.toJSON(viewModel.documents),
            success: function(){
                // TODO make multilangual and with modals
                alert("Saved document completeness to server");
                viewModel.clearStructure();
                viewModel.getProjectInfo();
                viewModel.getDocumentsToSubmit();
            }
        });
    });

    var url = '/assess/project/' + projectid + '/students';
    $("#cancelBtn").click(function()
    {
        window.location.href = url;
    });
}
<commit_msg>Grade documents<commit_after>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');
    gvm.studentId = $("#saveBtn").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.menuLanguage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("MenuLanguage");}, gvm);

    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.assessCompletementNumberToSubmit = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessCompletementNumberToSubmit");}, gvm);
    gvm.projectWeight = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectWeight");}, gvm);
    gvm.assessCompletementNumberSubmitted = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessCompletementNumberSubmitted");}, gvm);
    gvm.saveBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);
    gvm.cancelBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CancelBtn");}, gvm);
    gvm.documentScore = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DocumentScore");}, gvm);
    gvm.documentSubmit = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DocumentSubmit");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.documents = ko.observableArray([]);
    gvm.userData = ko.observableArray([]);

    gvm.addDocument = function(id,parentId, description, weight, pointType,score, nrDocuments, notSubmitted) {
        var doc = new Document(id,parentId,description,weight,pointType,score, nrDocuments, notSubmitted);
        gvm.documents.push(doc);
    };

    gvm.getAllData = function()
    {
        $.getJSON('/api/project/'+ gvm.projectId + '/documents/' + gvm.studentId, function(data) {
            $.each(data, function(i, item) {
                gvm.enterData(item);
                gvm.userData.push(item);
            });
        });
    };

    gvm.enterData = function(data)
    {
        gvm.documents().forEach(function(item) {
           if(data.document == item.parentId()) {
               item.id(data.id);
               item.score(data.score);
               item.notSubmitted(data.not_submitted);
               if (item.pointType() == "Ja/Nee") {
                   if (item.score() > 0) {
                       item.isChecked("yes");
                       item.score(100);
                   }
                   else {
                       item.isChecked("no");
                       item.score(0);
                   }
               }
           }
        });
        console.log(gvm.documents());
    };

    gvm.getDocumentsToSubmit = function() {
        $.getJSON('/api/project/'+ gvm.projectId + '/documents', function(data) {
            $.each(data, function(i, item) {
                var array = [];
                for(var i = 0; i < item.nr_documents; i++)
                {
                    array.push({id: 0,parentId: 0, nr: i, score: 0 });
                }
                gvm.addDocument(0, item.id, item.description, item.weight, item.point_type, 0, array, 0);
            });
            gvm.getAllData();
        });
    };

    gvm.changeNotSubmitted = function(data,parent) {
        console.log(data);
        console.log(parent);
    };

    gvm.clearStructure = function()
    {
        gvm.userData.destroyAll();
        gvm.documents.destroyAll();
    }
}

function Document(id,parentId,description ,weight,pointType, score, nrDocuments, notSubmitted, checked)
{
    var self = this;
    console.log(nrDocuments);
    self.documents = {
        id: ko.observable(id),
        parentId: ko.observable(parentId),
        description: ko.observable(description),
        pointType: ko.observable(pointType),
        weight: ko.observable(weight),
        score: ko.observable(score),
        isChecked: ko.observable(checked),
        nrDocuments: ko.observableArray(nrDocuments),
        notSubmitted: ko.observable(notSubmitted)
    }

    self.documents.checkedValue =  ko.computed({
        //return a formatted price
        read: function() {
            return self.documents.isChecked();
        },
        //if the value changes, make sure that we store a number back to price
        write: function(newValue) {
            self.documents.isChecked(newValue);
            if(self.documents.isChecked() == "yes")
            {
                self.documents.score(100);
            }
            else {
                self.documents.score(0);
            }
        },
        owner: this
    });

    return self.documents;
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getDocumentsToSubmit();

    $("#saveBtn").click(function() {
        $.ajax({
            type: "POST",
            url: "/api/documents/" + projectid + "/user/" + viewModel.studentId + "/save",
            data: ko.toJSON(viewModel.documents),
            success: function(){
                // TODO make multilangual and with modals
                alert("Saved document completeness to server");
                viewModel.clearStructure();
                viewModel.getProjectInfo();
                viewModel.getDocumentsToSubmit();
            }
        });
    });

    var url = '/assess/project/' + projectid + '/students';
    $("#cancelBtn").click(function()
    {
        window.location.href = url;
    });
}
<|endoftext|>


<commit_before>(function(app) {
  'use strict';

  var jCore = require('jcore');
  var helper = app.helper || require('../helper.js');
  var dom = app.dom || require('../dom.js');
  var CircuitElement = app.CircuitElement || require('../models/circuit-element.js');
  var Module = app.Module || require('./module.js');
  var ModuleWire = app.ModuleWire || require('./module-wire.js');
  var ModuleWireRelation = app.ModuleWireRelation || require('../relations/module-wire-relation.js');

  var Binding = function(props) {
    this.sourceModule = props.sourceModule;
    this.sourcePort = props.sourcePort;
    this.targetModule = props.targetModule;
    this.targetPort = props.targetPort;
  };

  Binding.prototype.bind = function() {
    var source = this.sourceModule.circuitElementMember(this.sourcePort.name());
    var target = this.targetModule.circuitElementMember(this.targetPort.name());
    CircuitElement.bind(source, target);
  };

  Binding.prototype.unbind = function() {
    var source = this.sourceModule.circuitElementMember(this.sourcePort.name());
    var target = this.targetModule.circuitElementMember(this.targetPort.name());
    CircuitElement.unbind(source, target);
  };

  var BindingList = helper.inherits(function() {
    BindingList.super_.call(this);
  }, helper.List);

  BindingList.prototype.equal = function(a, b) {
    return (a.sourceModule === b.sourceModule &&
            a.sourcePort === b.sourcePort &&
            b.targetModule === b.targetModule &&
            b.targetPort === b.targetPort);
  };

  var ModuleContainer = helper.inherits(function(props) {
    ModuleContainer.super_.call(this);

    this.modules = this.prop([]);
    this.bindingList = this.prop(new BindingList());
    this.element = this.prop(props.element);
    this.dragCount = this.prop(0);

    this.deleter = ModuleContainer.prototype.deleter.bind(this);
    this.fronter = ModuleContainer.prototype.fronter.bind(this);
    this.portToggler = ModuleContainer.prototype.portToggler.bind(this);
    this.dragStarter = ModuleContainer.prototype.dragStarter.bind(this);
    this.dragEnder = ModuleContainer.prototype.dragEnder.bind(this);
    this.dragPortPlugStarter = ModuleContainer.prototype.dragPortPlugStarter.bind(this);
    this.dragPortPlugMover = ModuleContainer.prototype.dragPortPlugMover.bind(this);
    this.dragPortPlugEnder = ModuleContainer.prototype.dragPortPlugEnder.bind(this);
  }, jCore.Component);

  ModuleContainer.prototype.retainerElement = function() {
    return dom.child(this.element(), 0);
  };

  ModuleContainer.prototype.wireContainerElement = function() {
    return dom.child(this.element(), 1);
  };

  ModuleContainer.prototype.contentElement = function() {
    return dom.child(this.element(), 2);
  };

  ModuleContainer.prototype.wireHandleContainerElement = function() {
    return dom.child(this.element(), 3);
  };

  ModuleContainer.prototype.lock = function(type, module, port, wire) {
    var relations = port.relations();

    var hasRelation = relations.some(function(relation) {
      return relation.consistsOf(type, module, port, wire);
    });

    if (hasRelation)
      return;

    var relation = new ModuleWireRelation({
      type: type,
      module: module,
      port: port,
      wire: wire
    });

    relations.push(relation);
    module.relations().push(relation);
  };

  ModuleContainer.prototype.unlock = function(type, module, port, wire) {
    var relations = port.relations();

    for (var i = relations.length - 1; i >= 0; i--) {
      var relation = relations[i];
      if (relation.consistsOf(type, module, port, wire)) {
        relations.splice(i, 1);
        var moduleRelations = module.relations();
        moduleRelations.splice(moduleRelations.indexOf(relation), 1);
        break;
      }
    }
  };

  ModuleContainer.prototype.bind = function(sourceModule, sourcePort, targetModule, targetPort) {
    var bindingList = this.bindingList();

    var binding = new Binding({
      sourceModule: sourceModule,
      sourcePort: sourcePort,
      targetModule: targetModule,
      targetPort: targetPort
    });

    if (bindingList.contains(binding))
      return;

    binding.bind();
    bindingList.add(binding);
  };

  ModuleContainer.prototype.unbind = function(sourceModule, sourcePort, targetModule, targetPort) {
    var bindingList = this.bindingList();

    var binding = new Binding({
      sourceModule: sourceModule,
      sourcePort: sourcePort,
      targetModule: targetModule,
      targetPort: targetPort
    });

    if (!bindingList.contains(binding))
      return;

    binding.unbind();
    bindingList.remove(binding);
  };

  ModuleContainer.prototype.redraw = function() {
    var modules = this.modules();
    var x = 0;
    var y = 0;

    modules.forEach(function(module) {
      var diagonalPoint = module.diagonalPoint();
      x = Math.max(diagonalPoint.x, x);
      y = Math.max(diagonalPoint.y, y);
    });

    var padding = 80;
    var translate = 'translate(' + (x - 1 + padding) + 'px, ' + (y - 1 + padding) + 'px)';

    dom.css(this.retainerElement(), {
      transform: translate,
      webkitTransform: translate
    });

    dom.toggleClass(this.element(), 'module-dragging', this.dragCount() > 0);

    dom.css(this.wireHandleContainerElement(), {
      zIndex: modules.length + 1
    });
  };

  ModuleContainer.prototype.loadModule = function(props) {
    var module = new Module(helper.extend({}, props, {
      deleter: this.deleter,
      fronter: this.fronter,
      portToggler: this.portToggler,
      dragStarter: this.dragStarter,
      dragEnder: this.dragEnder,
      dragPortPlugStarter: this.dragPortPlugStarter,
      dragPortPlugMover: this.dragPortPlugMover,
      dragPortPlugEnder: this.dragPortPlugEnder
    }));
    this.modules().push(module);
    this.updateZIndex();
    this.markDirty();
    module.parentElement(this.contentElement());
    module.redraw();
    return module.loadComponent().then(function() {
      return module;
    });
  };

  ModuleContainer.prototype.toFront = function(module) {
    var modules = this.modules();
    var index = modules.indexOf(module);

    if (index === -1)
      return;

    modules.splice(index, 1);
    modules.push(module);
  };

  ModuleContainer.prototype.updateZIndex = function() {
    this.modules().forEach(function(module, index) {
      module.zIndex(index);
    });
  };

  ModuleContainer.prototype.deleter = function(module) {
    var modules = this.modules();
    var index = modules.indexOf(module);

    if (index === -1)
      return;

    modules.splice(index, 1);
    this.updateZIndex();
    this.markDirty();
  };

  ModuleContainer.prototype.fronter = function(module) {
    this.toFront(module);
    this.updateZIndex();
  };

  ModuleContainer.prototype.portToggler = function() {
    // resize the element
    this.markDirty();
  };

  ModuleContainer.prototype.dragStarter = function() {
    this.dragCount(this.dragCount() + 1);
  };

  ModuleContainer.prototype.dragEnder = function() {
    this.dragCount(this.dragCount() - 1);
  };

  ModuleContainer.prototype.dragPortPlugStarter = function(module, port, context) {
    var position = module.plugPosition(port);
    var x = position.x;
    var y = position.y;
    var wire = new ModuleWire({
      sourceX: x,
      sourceY: y,
      targetX: x,
      targetY: y,
      handleType: port.type(),
      handleVisible: true,
      parentHandleElement: this.wireHandleContainerElement()
    });
    wire.parentElement(this.wireContainerElement());
    this.lock(ModuleContainer.LOCK_TYPE_PLUG, module, port, wire);
    context.x = x;
    context.y = y;
    context.wire = wire;
    context.type = port.type();
    context.targetModule = null;
    context.targetPort = null;
  };

  ModuleContainer.prototype.dragPortPlugMover = function(sourceModule, sourcePort, dx, dy, context) {
    var wire = context.wire;
    var x = context.x + dx;
    var y = context.y + dy;

    wire.targetX(x);
    wire.targetY(y);

    var modules = this.modules();
    var type = context.type;
    var currentTargetModule = context.targetModule;
    var currentTargetPort = context.targetPort;
    var targetModule = null;
    var targetPort = null;

    // search the target port-socket by the position of the dragging wire-handle
    for (var mi = modules.length - 1; mi >= 0; mi--) {
      var module = modules[mi];
      var ports = module.ports();
      for (var pi = ports.length - 1; pi >= 0; pi--) {
        var port = ports[pi];
        var position = module.socketPosition(port);
        if (Math.abs(x - position.x) > 18)
          break;
        if (Math.abs(y - position.y) > 18)
          continue;
        if (!port.visible())
          continue;
        if (!port.socketConnected() && type === port.type()) {
          targetModule = module;
          targetPort = port;
        } else if (module === currentTargetModule && port === currentTargetPort) {
          targetModule = currentTargetModule;
          targetPort = currentTargetPort;
        }
        break;
      }
      if (targetModule && targetPort)
        break;
    }

    if (targetModule === currentTargetModule && targetPort === currentTargetPort) {
      if (targetPort) {
        // fix the target position of the wire
        targetPort.markDirty();
      }
      return;
    }

    if (currentTargetModule && currentTargetPort) {
      // detach the wire-handle from the current target port-socket
      this.unlock(ModuleContainer.LOCK_TYPE_SOCKET, currentTargetModule, currentTargetPort, wire);
      wire.handleVisible(true);
      currentTargetPort.socketConnected(false);
    }

    if (targetModule && targetPort) {
      // attach the wire-handle to the target port-socket
      this.lock(ModuleContainer.LOCK_TYPE_SOCKET, targetModule, targetPort, wire);
      targetPort.socketConnected(true);
      wire.handleVisible(false);
    }

    context.targetModule = targetModule;
    context.targetPort = targetPort;
  };

  ModuleContainer.prototype.dragPortPlugEnder = function(sourceModule, sourcePort, context) {
    var targetModule = context.targetModule;
    var targetPort = context.targetPort;

    if (targetModule && targetPort)
      return;

    // remove the dragging wire
    var wire = context.wire;
    this.unlock(ModuleContainer.LOCK_TYPE_PLUG, sourceModule, sourcePort, wire);
    wire.parentElement(null);
  };

  ModuleContainer.LOCK_TYPE_PLUG = ModuleWireRelation.TYPE_SOURCE;
  ModuleContainer.LOCK_TYPE_SOCKET = ModuleWireRelation.TYPE_TARGET;

  if (typeof module !== 'undefined' && module.exports)
    module.exports = ModuleContainer;
  else
    app.ModuleContainer = ModuleContainer;
})(this.app || (this.app = {}));
<commit_msg>Don't attach module-wire to disabled port-socket<commit_after>(function(app) {
  'use strict';

  var jCore = require('jcore');
  var helper = app.helper || require('../helper.js');
  var dom = app.dom || require('../dom.js');
  var CircuitElement = app.CircuitElement || require('../models/circuit-element.js');
  var Module = app.Module || require('./module.js');
  var ModuleWire = app.ModuleWire || require('./module-wire.js');
  var ModuleWireRelation = app.ModuleWireRelation || require('../relations/module-wire-relation.js');

  var Binding = function(props) {
    this.sourceModule = props.sourceModule;
    this.sourcePort = props.sourcePort;
    this.targetModule = props.targetModule;
    this.targetPort = props.targetPort;
  };

  Binding.prototype.bind = function() {
    var source = this.sourceModule.circuitElementMember(this.sourcePort.name());
    var target = this.targetModule.circuitElementMember(this.targetPort.name());
    CircuitElement.bind(source, target);
  };

  Binding.prototype.unbind = function() {
    var source = this.sourceModule.circuitElementMember(this.sourcePort.name());
    var target = this.targetModule.circuitElementMember(this.targetPort.name());
    CircuitElement.unbind(source, target);
  };

  var BindingList = helper.inherits(function() {
    BindingList.super_.call(this);
  }, helper.List);

  BindingList.prototype.equal = function(a, b) {
    return (a.sourceModule === b.sourceModule &&
            a.sourcePort === b.sourcePort &&
            b.targetModule === b.targetModule &&
            b.targetPort === b.targetPort);
  };

  var ModuleContainer = helper.inherits(function(props) {
    ModuleContainer.super_.call(this);

    this.modules = this.prop([]);
    this.bindingList = this.prop(new BindingList());
    this.element = this.prop(props.element);
    this.dragCount = this.prop(0);

    this.deleter = ModuleContainer.prototype.deleter.bind(this);
    this.fronter = ModuleContainer.prototype.fronter.bind(this);
    this.portToggler = ModuleContainer.prototype.portToggler.bind(this);
    this.dragStarter = ModuleContainer.prototype.dragStarter.bind(this);
    this.dragEnder = ModuleContainer.prototype.dragEnder.bind(this);
    this.dragPortPlugStarter = ModuleContainer.prototype.dragPortPlugStarter.bind(this);
    this.dragPortPlugMover = ModuleContainer.prototype.dragPortPlugMover.bind(this);
    this.dragPortPlugEnder = ModuleContainer.prototype.dragPortPlugEnder.bind(this);
  }, jCore.Component);

  ModuleContainer.prototype.retainerElement = function() {
    return dom.child(this.element(), 0);
  };

  ModuleContainer.prototype.wireContainerElement = function() {
    return dom.child(this.element(), 1);
  };

  ModuleContainer.prototype.contentElement = function() {
    return dom.child(this.element(), 2);
  };

  ModuleContainer.prototype.wireHandleContainerElement = function() {
    return dom.child(this.element(), 3);
  };

  ModuleContainer.prototype.lock = function(type, module, port, wire) {
    var relations = port.relations();

    var hasRelation = relations.some(function(relation) {
      return relation.consistsOf(type, module, port, wire);
    });

    if (hasRelation)
      return;

    var relation = new ModuleWireRelation({
      type: type,
      module: module,
      port: port,
      wire: wire
    });

    relations.push(relation);
    module.relations().push(relation);
  };

  ModuleContainer.prototype.unlock = function(type, module, port, wire) {
    var relations = port.relations();

    for (var i = relations.length - 1; i >= 0; i--) {
      var relation = relations[i];
      if (relation.consistsOf(type, module, port, wire)) {
        relations.splice(i, 1);
        var moduleRelations = module.relations();
        moduleRelations.splice(moduleRelations.indexOf(relation), 1);
        break;
      }
    }
  };

  ModuleContainer.prototype.bind = function(sourceModule, sourcePort, targetModule, targetPort) {
    var bindingList = this.bindingList();

    var binding = new Binding({
      sourceModule: sourceModule,
      sourcePort: sourcePort,
      targetModule: targetModule,
      targetPort: targetPort
    });

    if (bindingList.contains(binding))
      return;

    binding.bind();
    bindingList.add(binding);
  };

  ModuleContainer.prototype.unbind = function(sourceModule, sourcePort, targetModule, targetPort) {
    var bindingList = this.bindingList();

    var binding = new Binding({
      sourceModule: sourceModule,
      sourcePort: sourcePort,
      targetModule: targetModule,
      targetPort: targetPort
    });

    if (!bindingList.contains(binding))
      return;

    binding.unbind();
    bindingList.remove(binding);
  };

  ModuleContainer.prototype.redraw = function() {
    var modules = this.modules();
    var x = 0;
    var y = 0;

    modules.forEach(function(module) {
      var diagonalPoint = module.diagonalPoint();
      x = Math.max(diagonalPoint.x, x);
      y = Math.max(diagonalPoint.y, y);
    });

    var padding = 80;
    var translate = 'translate(' + (x - 1 + padding) + 'px, ' + (y - 1 + padding) + 'px)';

    dom.css(this.retainerElement(), {
      transform: translate,
      webkitTransform: translate
    });

    dom.toggleClass(this.element(), 'module-dragging', this.dragCount() > 0);

    dom.css(this.wireHandleContainerElement(), {
      zIndex: modules.length + 1
    });
  };

  ModuleContainer.prototype.loadModule = function(props) {
    var module = new Module(helper.extend({}, props, {
      deleter: this.deleter,
      fronter: this.fronter,
      portToggler: this.portToggler,
      dragStarter: this.dragStarter,
      dragEnder: this.dragEnder,
      dragPortPlugStarter: this.dragPortPlugStarter,
      dragPortPlugMover: this.dragPortPlugMover,
      dragPortPlugEnder: this.dragPortPlugEnder
    }));
    this.modules().push(module);
    this.updateZIndex();
    this.markDirty();
    module.parentElement(this.contentElement());
    module.redraw();
    return module.loadComponent().then(function() {
      return module;
    });
  };

  ModuleContainer.prototype.toFront = function(module) {
    var modules = this.modules();
    var index = modules.indexOf(module);

    if (index === -1)
      return;

    modules.splice(index, 1);
    modules.push(module);
  };

  ModuleContainer.prototype.updateZIndex = function() {
    this.modules().forEach(function(module, index) {
      module.zIndex(index);
    });
  };

  ModuleContainer.prototype.deleter = function(module) {
    var modules = this.modules();
    var index = modules.indexOf(module);

    if (index === -1)
      return;

    modules.splice(index, 1);
    this.updateZIndex();
    this.markDirty();
  };

  ModuleContainer.prototype.fronter = function(module) {
    this.toFront(module);
    this.updateZIndex();
  };

  ModuleContainer.prototype.portToggler = function() {
    // resize the element
    this.markDirty();
  };

  ModuleContainer.prototype.dragStarter = function() {
    this.dragCount(this.dragCount() + 1);
  };

  ModuleContainer.prototype.dragEnder = function() {
    this.dragCount(this.dragCount() - 1);
  };

  ModuleContainer.prototype.dragPortPlugStarter = function(module, port, context) {
    var position = module.plugPosition(port);
    var x = position.x;
    var y = position.y;
    var wire = new ModuleWire({
      sourceX: x,
      sourceY: y,
      targetX: x,
      targetY: y,
      handleType: port.type(),
      handleVisible: true,
      parentHandleElement: this.wireHandleContainerElement()
    });
    wire.parentElement(this.wireContainerElement());
    this.lock(ModuleContainer.LOCK_TYPE_PLUG, module, port, wire);
    context.x = x;
    context.y = y;
    context.wire = wire;
    context.type = port.type();
    context.targetModule = null;
    context.targetPort = null;
  };

  ModuleContainer.prototype.dragPortPlugMover = function(sourceModule, sourcePort, dx, dy, context) {
    var wire = context.wire;
    var x = context.x + dx;
    var y = context.y + dy;

    wire.targetX(x);
    wire.targetY(y);

    var modules = this.modules();
    var type = context.type;
    var currentTargetModule = context.targetModule;
    var currentTargetPort = context.targetPort;
    var targetModule = null;
    var targetPort = null;

    // search the target port-socket by the position of the dragging wire-handle
    for (var mi = modules.length - 1; mi >= 0; mi--) {
      var module = modules[mi];
      var ports = module.ports();
      for (var pi = ports.length - 1; pi >= 0; pi--) {
        var port = ports[pi];
        var position = module.socketPosition(port);
        if (Math.abs(x - position.x) > 18)
          break;
        if (Math.abs(y - position.y) > 18)
          continue;
        if (!port.visible() || port.socketDisabled())
          continue;
        if (!port.socketConnected() && type === port.type()) {
          targetModule = module;
          targetPort = port;
        } else if (module === currentTargetModule && port === currentTargetPort) {
          targetModule = currentTargetModule;
          targetPort = currentTargetPort;
        }
        break;
      }
      if (targetModule && targetPort)
        break;
    }

    if (targetModule === currentTargetModule && targetPort === currentTargetPort) {
      if (targetPort) {
        // fix the target position of the wire
        targetPort.markDirty();
      }
      return;
    }

    if (currentTargetModule && currentTargetPort) {
      // detach the wire-handle from the current target port-socket
      this.unlock(ModuleContainer.LOCK_TYPE_SOCKET, currentTargetModule, currentTargetPort, wire);
      wire.handleVisible(true);
      currentTargetPort.socketConnected(false);
    }

    if (targetModule && targetPort) {
      // attach the wire-handle to the target port-socket
      this.lock(ModuleContainer.LOCK_TYPE_SOCKET, targetModule, targetPort, wire);
      targetPort.socketConnected(true);
      wire.handleVisible(false);
    }

    context.targetModule = targetModule;
    context.targetPort = targetPort;
  };

  ModuleContainer.prototype.dragPortPlugEnder = function(sourceModule, sourcePort, context) {
    var targetModule = context.targetModule;
    var targetPort = context.targetPort;

    if (targetModule && targetPort)
      return;

    // remove the dragging wire
    var wire = context.wire;
    this.unlock(ModuleContainer.LOCK_TYPE_PLUG, sourceModule, sourcePort, wire);
    wire.parentElement(null);
  };

  ModuleContainer.LOCK_TYPE_PLUG = ModuleWireRelation.TYPE_SOURCE;
  ModuleContainer.LOCK_TYPE_SOCKET = ModuleWireRelation.TYPE_TARGET;

  if (typeof module !== 'undefined' && module.exports)
    module.exports = ModuleContainer;
  else
    app.ModuleContainer = ModuleContainer;
})(this.app || (this.app = {}));
<|endoftext|>


<commit_before>
import { NativeModules } from 'react-native';

const { RNTensorflow } = NativeModules;

export default RNTensorflow;
<commit_msg>Add js delegation<commit_after>
import { NativeModules } from 'react-native';

const { RNTensorflow } = NativeModules;

class Tensorflow {

  setupForModel(modelFileName) {
    RNTensorflow.instantiateTensorflow(modelFileName)
  }

  feedWithDims(inputName, src, dims) {
    RNTensorflow.feed(inputName, src, dims);
  }

  feed(inputName, src) {
    RNTensorflow.feed(inputName, src);
  }

  run(outputNames) {
    RNTensorflow.run(outputNames);
  }

  runWithStats(outputNames) {
    RNTensorflow.run(outputNames, true);
  }

  fetch(outputName, outputSize) {
    return RNTensorflow.fetch(outputName, dst);
  }

  graph() {
    return RNTensorflow.graph();
  }

  graphOperation(operationName) {
    return RNTensorflow.graphOperation(operationName);
  }

  stats() {
    return RNTensorflow.getStatString();
  }

  close() {
    RNTensorflow.close();
  }
}

export default new Tensorflow();
<|endoftext|>


<commit_before>(function(app) {
  'use strict';

  var jCore = require('jcore');
  var helper = app.helper || require('../helper.js');
  var dom = app.dom || require('../dom.js');
  var CircuitElement = app.CircuitElement || require('../models/circuit-element.js');
  var Module = app.Module || require('./module.js');
  var ModuleWire = app.ModuleWire || require('./module-wire.js');
  var ModuleWireRelation = app.ModuleWireRelation || require('../relations/module-wire-relation.js');

  var ModuleWireRelationList = helper.inherits(function() {
    ModuleWireRelationList.super_.call(this);
  }, helper.List);

  var Binding = function(props) {
    this.sourceModule = props.sourceModule;
    this.sourcePort = props.sourcePort;
    this.targetModule = props.targetModule;
    this.targetPort = props.targetPort;
  };

  Binding.prototype.bind = function() {
    var source = this.sourceModule.circuitElementMember(this.sourcePort.name());
    var target = this.targetModule.circuitElementMember(this.targetPort.name());
    CircuitElement.bind(source, target);
  };

  Binding.prototype.unbind = function() {
    var source = this.sourceModule.circuitElementMember(this.sourcePort.name());
    var target = this.targetModule.circuitElementMember(this.targetPort.name());
    CircuitElement.unbind(source, target);
  };

  var BindingList = helper.inherits(function() {
    BindingList.super_.call(this);
  }, helper.List);

  BindingList.prototype.equal = function(a, b) {
    return (a.sourceModule === b.sourceModule &&
            a.sourcePort === b.sourcePort &&
            a.targetModule === b.targetModule &&
            a.targetPort === b.targetPort);
  };

  var ModuleContainer = helper.inherits(function(props) {
    ModuleContainer.super_.call(this);

    this.modules = this.prop([]);
    this.moduleWireRelationList = this.prop(new ModuleWireRelationList());
    this.bindingList = this.prop(new BindingList());
    this.element = this.prop(props.element);
    this.dragCount = this.prop(0);

    this.deleter = ModuleContainer.prototype.deleter.bind(this);
    this.fronter = ModuleContainer.prototype.fronter.bind(this);
    this.portToggler = ModuleContainer.prototype.portToggler.bind(this);
    this.dragStarter = ModuleContainer.prototype.dragStarter.bind(this);
    this.dragEnder = ModuleContainer.prototype.dragEnder.bind(this);
    this.dragPortPlugStarter = ModuleContainer.prototype.dragPortPlugStarter.bind(this);
    this.dragPortPlugMover = ModuleContainer.prototype.dragPortPlugMover.bind(this);
    this.dragPortPlugEnder = ModuleContainer.prototype.dragPortPlugEnder.bind(this);
    this.dragPortSocketStarter = ModuleContainer.prototype.dragPortSocketStarter.bind(this);
    this.dragPortSocketMover = ModuleContainer.prototype.dragPortSocketMover.bind(this);
    this.dragPortSocketEnder = ModuleContainer.prototype.dragPortSocketEnder.bind(this);
  }, jCore.Component);

  ModuleContainer.prototype.retainerElement = function() {
    return dom.child(this.element(), 0);
  };

  ModuleContainer.prototype.wireContainerElement = function() {
    return dom.child(this.element(), 1);
  };

  ModuleContainer.prototype.contentElement = function() {
    return dom.child(this.element(), 2);
  };

  ModuleContainer.prototype.wireHandleContainerElement = function() {
    return dom.child(this.element(), 3);
  };

  ModuleContainer.prototype.lock = function(type, module, port, wire) {
    var relations = port.relations();

    var hasRelation = relations.some(function(relation) {
      return relation.consistsOf(type, module, port, wire);
    });

    if (hasRelation)
      return;

    var relation = new ModuleWireRelation({
      type: type,
      module: module,
      port: port,
      wire: wire
    });

    relations.push(relation);
    module.relations().push(relation);
    this.moduleWireRelationList().add(relation);
  };

  ModuleContainer.prototype.unlock = function(type, module, port, wire) {
    var relations = port.relations();

    for (var i = relations.length - 1; i >= 0; i--) {
      var relation = relations[i];
      if (relation.consistsOf(type, module, port, wire)) {
        relations.splice(i, 1);
        var moduleRelations = module.relations();
        moduleRelations.splice(moduleRelations.indexOf(relation), 1);
        this.moduleWireRelationList().remove(relation);
        break;
      }
    }
  };

  ModuleContainer.prototype.bind = function(sourceModule, sourcePort, targetModule, targetPort) {
    var bindingList = this.bindingList();

    var binding = new Binding({
      sourceModule: sourceModule,
      sourcePort: sourcePort,
      targetModule: targetModule,
      targetPort: targetPort
    });

    if (bindingList.contains(binding))
      return;

    binding.bind();
    bindingList.add(binding);
  };

  ModuleContainer.prototype.unbind = function(sourceModule, sourcePort, targetModule, targetPort) {
    var bindingList = this.bindingList();

    var binding = new Binding({
      sourceModule: sourceModule,
      sourcePort: sourcePort,
      targetModule: targetModule,
      targetPort: targetPort
    });

    if (!bindingList.contains(binding))
      return;

    binding.unbind();
    bindingList.remove(binding);
  };

  ModuleContainer.prototype.redraw = function() {
    var modules = this.modules();
    var x = 0;
    var y = 0;

    modules.forEach(function(module) {
      var diagonalPoint = module.diagonalPoint();
      x = Math.max(diagonalPoint.x, x);
      y = Math.max(diagonalPoint.y, y);
    });

    var padding = 80;
    var translate = 'translate(' + (x - 1 + padding) + 'px, ' + (y - 1 + padding) + 'px)';

    dom.css(this.retainerElement(), {
      transform: translate,
      webkitTransform: translate
    });

    dom.toggleClass(this.element(), 'module-dragging', this.dragCount() > 0);

    dom.css(this.wireHandleContainerElement(), {
      zIndex: modules.length + 1
    });
  };

  ModuleContainer.prototype.loadModule = function(props) {
    var module = new Module(helper.extend({}, props, {
      deleter: this.deleter,
      fronter: this.fronter,
      portToggler: this.portToggler,
      dragStarter: this.dragStarter,
      dragEnder: this.dragEnder,
      dragPortPlugStarter: this.dragPortPlugStarter,
      dragPortPlugMover: this.dragPortPlugMover,
      dragPortPlugEnder: this.dragPortPlugEnder,
      dragPortSocketStarter: this.dragPortSocketStarter,
      dragPortSocketMover: this.dragPortSocketMover,
      dragPortSocketEnder: this.dragPortSocketEnder
    }));
    this.modules().push(module);
    this.updateZIndex();
    this.markDirty();
    module.parentElement(this.contentElement());
    module.redraw();
    return module.loadComponent().then(function() {
      return module;
    });
  };

  ModuleContainer.prototype.toFront = function(module) {
    var modules = this.modules();
    var index = modules.indexOf(module);

    if (index === -1)
      return;

    modules.splice(index, 1);
    modules.push(module);
  };

  ModuleContainer.prototype.updateZIndex = function() {
    this.modules().forEach(function(module, index) {
      module.zIndex(index);
    });
  };

  ModuleContainer.prototype.deleter = function(module) {
    var modules = this.modules();
    var index = modules.indexOf(module);

    if (index === -1)
      return;

    modules.splice(index, 1);
    this.updateZIndex();
    this.markDirty();
  };

  ModuleContainer.prototype.fronter = function(module) {
    this.toFront(module);
    this.updateZIndex();
  };

  ModuleContainer.prototype.portToggler = function() {
    // resize the element
    this.markDirty();
  };

  ModuleContainer.prototype.dragStarter = function() {
    this.dragCount(this.dragCount() + 1);
  };

  ModuleContainer.prototype.dragEnder = function() {
    this.dragCount(this.dragCount() - 1);
  };

  ModuleContainer.prototype.dragPortPlugStarter = function(module, port, context) {
    var position = module.plugPosition(port);
    var x = position.x;
    var y = position.y;
    var wire = new ModuleWire({
      sourceX: x,
      sourceY: y,
      targetX: x,
      targetY: y,
      handleType: port.type(),
      handleVisible: true,
      parentHandleElement: this.wireHandleContainerElement()
    });
    wire.parentElement(this.wireContainerElement());
    this.lock(ModuleContainer.LOCK_TYPE_PLUG, module, port, wire);
    context.x = x;
    context.y = y;
    context.wire = wire;
    context.type = port.type();
    context.targetModule = null;
    context.targetPort = null;
  };

  ModuleContainer.prototype.dragPortPlugMover = function(sourceModule, sourcePort, dx, dy, context) {
    var wire = context.wire;
    var x = context.x + dx;
    var y = context.y + dy;

    wire.targetX(x);
    wire.targetY(y);

    var modules = this.modules();
    var type = context.type;
    var currentTargetModule = context.targetModule;
    var currentTargetPort = context.targetPort;
    var targetModule = null;
    var targetPort = null;

    // search the target port-socket by the position of the dragging wire-handle
    for (var mi = modules.length - 1; mi >= 0; mi--) {
      var module = modules[mi];
      var ports = module.ports();
      for (var pi = ports.length - 1; pi >= 0; pi--) {
        var port = ports[pi];
        var position = module.socketPosition(port);
        if (Math.abs(x - position.x) > 18)
          break;
        if (Math.abs(y - position.y) > 18)
          continue;
        if (!port.visible() || port.socketDisabled())
          continue;
        if (!port.socketConnected() && type === port.type()) {
          targetModule = module;
          targetPort = port;
        } else if (module === currentTargetModule && port === currentTargetPort) {
          targetModule = currentTargetModule;
          targetPort = currentTargetPort;
        }
        break;
      }
      if (targetModule && targetPort)
        break;
    }

    if (targetModule === currentTargetModule && targetPort === currentTargetPort) {
      if (targetPort) {
        // fix the target position of the wire
        targetPort.markDirty();
      }
      return;
    }

    if (currentTargetModule && currentTargetPort) {
      this.unbind(sourceModule, sourcePort, currentTargetModule, currentTargetPort);
      // detach the wire-handle from the current target port-socket
      this.unlock(ModuleContainer.LOCK_TYPE_SOCKET, currentTargetModule, currentTargetPort, wire);
      wire.handleVisible(true);
      currentTargetPort.socketConnected(false);
    }

    if (targetModule && targetPort) {
      this.bind(sourceModule, sourcePort, targetModule, targetPort);
      // attach the wire-handle to the target port-socket
      this.lock(ModuleContainer.LOCK_TYPE_SOCKET, targetModule, targetPort, wire);
      targetPort.socketConnected(true);
      wire.handleVisible(false);
    }

    context.targetModule = targetModule;
    context.targetPort = targetPort;
  };

  ModuleContainer.prototype.dragPortPlugEnder = function(sourceModule, sourcePort, context) {
    var targetModule = context.targetModule;
    var targetPort = context.targetPort;

    if (targetModule && targetPort)
      return;

    // remove the dragging wire
    var wire = context.wire;
    this.unlock(ModuleContainer.LOCK_TYPE_PLUG, sourceModule, sourcePort, wire);
    wire.parentElement(null);
  };

  ModuleContainer.prototype.dragPortSocketStarter = function(module, port, context) {
    var relation = port.relations().filter(function(relation) {
      return (relation.type() === ModuleWireRelation.TYPE_TARGET);
    })[0];

    var wire = relation.wire();
    context.x = wire.targetX();
    context.y = wire.targetY();
    context.wire = wire;
    context.type = port.type();

    var binding = this.bindingList().toArray().filter(function(binding) {
      return (binding.targetModule === module && binding.targetPort === port);
    })[0];

    context.sourceModule = binding.sourceModule;
    context.sourcePort = binding.sourcePort;
    context.targetModule = module;
    context.targetPort = port;
  };

  ModuleContainer.prototype.dragPortSocketMover = function(targetModule, targetPort, dx, dy, context) {
    this.dragPortPlugMover(context.sourceModule, context.sourcePort, dx, dy, context);
  };

  ModuleContainer.prototype.dragPortSocketEnder = function(targetModule, targetPort, context) {
    this.dragPortPlugEnder(context.sourceModule, context.sourcePort, context);
  };

  ModuleContainer.LOCK_TYPE_PLUG = ModuleWireRelation.TYPE_SOURCE;
  ModuleContainer.LOCK_TYPE_SOCKET = ModuleWireRelation.TYPE_TARGET;

  if (typeof module !== 'undefined' && module.exports)
    module.exports = ModuleContainer;
  else
    app.ModuleContainer = ModuleContainer;
})(this.app || (this.app = {}));
<commit_msg>Add property to store dragging module-wires<commit_after>(function(app) {
  'use strict';

  var jCore = require('jcore');
  var helper = app.helper || require('../helper.js');
  var dom = app.dom || require('../dom.js');
  var CircuitElement = app.CircuitElement || require('../models/circuit-element.js');
  var Module = app.Module || require('./module.js');
  var ModuleWire = app.ModuleWire || require('./module-wire.js');
  var ModuleWireRelation = app.ModuleWireRelation || require('../relations/module-wire-relation.js');

  var ModuleWireRelationList = helper.inherits(function() {
    ModuleWireRelationList.super_.call(this);
  }, helper.List);

  var Binding = function(props) {
    this.sourceModule = props.sourceModule;
    this.sourcePort = props.sourcePort;
    this.targetModule = props.targetModule;
    this.targetPort = props.targetPort;
  };

  Binding.prototype.bind = function() {
    var source = this.sourceModule.circuitElementMember(this.sourcePort.name());
    var target = this.targetModule.circuitElementMember(this.targetPort.name());
    CircuitElement.bind(source, target);
  };

  Binding.prototype.unbind = function() {
    var source = this.sourceModule.circuitElementMember(this.sourcePort.name());
    var target = this.targetModule.circuitElementMember(this.targetPort.name());
    CircuitElement.unbind(source, target);
  };

  var BindingList = helper.inherits(function() {
    BindingList.super_.call(this);
  }, helper.List);

  BindingList.prototype.equal = function(a, b) {
    return (a.sourceModule === b.sourceModule &&
            a.sourcePort === b.sourcePort &&
            a.targetModule === b.targetModule &&
            a.targetPort === b.targetPort);
  };

  var ModuleContainer = helper.inherits(function(props) {
    ModuleContainer.super_.call(this);

    this.modules = this.prop([]);
    this.moduleWireRelationList = this.prop(new ModuleWireRelationList());
    this.bindingList = this.prop(new BindingList());
    this.element = this.prop(props.element);
    this.dragCount = this.prop(0);
    this.draggingWires = this.prop([]);

    this.deleter = ModuleContainer.prototype.deleter.bind(this);
    this.fronter = ModuleContainer.prototype.fronter.bind(this);
    this.portToggler = ModuleContainer.prototype.portToggler.bind(this);
    this.dragStarter = ModuleContainer.prototype.dragStarter.bind(this);
    this.dragEnder = ModuleContainer.prototype.dragEnder.bind(this);
    this.dragPortPlugStarter = ModuleContainer.prototype.dragPortPlugStarter.bind(this);
    this.dragPortPlugMover = ModuleContainer.prototype.dragPortPlugMover.bind(this);
    this.dragPortPlugEnder = ModuleContainer.prototype.dragPortPlugEnder.bind(this);
    this.dragPortSocketStarter = ModuleContainer.prototype.dragPortSocketStarter.bind(this);
    this.dragPortSocketMover = ModuleContainer.prototype.dragPortSocketMover.bind(this);
    this.dragPortSocketEnder = ModuleContainer.prototype.dragPortSocketEnder.bind(this);
  }, jCore.Component);

  ModuleContainer.prototype.retainerElement = function() {
    return dom.child(this.element(), 0);
  };

  ModuleContainer.prototype.wireContainerElement = function() {
    return dom.child(this.element(), 1);
  };

  ModuleContainer.prototype.contentElement = function() {
    return dom.child(this.element(), 2);
  };

  ModuleContainer.prototype.wireHandleContainerElement = function() {
    return dom.child(this.element(), 3);
  };

  ModuleContainer.prototype.lock = function(type, module, port, wire) {
    var relations = port.relations();

    var hasRelation = relations.some(function(relation) {
      return relation.consistsOf(type, module, port, wire);
    });

    if (hasRelation)
      return;

    var relation = new ModuleWireRelation({
      type: type,
      module: module,
      port: port,
      wire: wire
    });

    relations.push(relation);
    module.relations().push(relation);
    this.moduleWireRelationList().add(relation);
  };

  ModuleContainer.prototype.unlock = function(type, module, port, wire) {
    var relations = port.relations();

    for (var i = relations.length - 1; i >= 0; i--) {
      var relation = relations[i];
      if (relation.consistsOf(type, module, port, wire)) {
        relations.splice(i, 1);
        var moduleRelations = module.relations();
        moduleRelations.splice(moduleRelations.indexOf(relation), 1);
        this.moduleWireRelationList().remove(relation);
        break;
      }
    }
  };

  ModuleContainer.prototype.bind = function(sourceModule, sourcePort, targetModule, targetPort) {
    var bindingList = this.bindingList();

    var binding = new Binding({
      sourceModule: sourceModule,
      sourcePort: sourcePort,
      targetModule: targetModule,
      targetPort: targetPort
    });

    if (bindingList.contains(binding))
      return;

    binding.bind();
    bindingList.add(binding);
  };

  ModuleContainer.prototype.unbind = function(sourceModule, sourcePort, targetModule, targetPort) {
    var bindingList = this.bindingList();

    var binding = new Binding({
      sourceModule: sourceModule,
      sourcePort: sourcePort,
      targetModule: targetModule,
      targetPort: targetPort
    });

    if (!bindingList.contains(binding))
      return;

    binding.unbind();
    bindingList.remove(binding);
  };

  ModuleContainer.prototype.redraw = function() {
    var modules = this.modules();
    var x = 0;
    var y = 0;

    modules.forEach(function(module) {
      var diagonalPoint = module.diagonalPoint();
      x = Math.max(diagonalPoint.x, x);
      y = Math.max(diagonalPoint.y, y);
    });

    var padding = 80;
    var translate = 'translate(' + (x - 1 + padding) + 'px, ' + (y - 1 + padding) + 'px)';

    dom.css(this.retainerElement(), {
      transform: translate,
      webkitTransform: translate
    });

    dom.toggleClass(this.element(), 'module-dragging', this.dragCount() > 0);

    dom.css(this.wireHandleContainerElement(), {
      zIndex: modules.length + 1
    });
  };

  ModuleContainer.prototype.loadModule = function(props) {
    var module = new Module(helper.extend({}, props, {
      deleter: this.deleter,
      fronter: this.fronter,
      portToggler: this.portToggler,
      dragStarter: this.dragStarter,
      dragEnder: this.dragEnder,
      dragPortPlugStarter: this.dragPortPlugStarter,
      dragPortPlugMover: this.dragPortPlugMover,
      dragPortPlugEnder: this.dragPortPlugEnder,
      dragPortSocketStarter: this.dragPortSocketStarter,
      dragPortSocketMover: this.dragPortSocketMover,
      dragPortSocketEnder: this.dragPortSocketEnder
    }));
    this.modules().push(module);
    this.updateZIndex();
    this.markDirty();
    module.parentElement(this.contentElement());
    module.redraw();
    return module.loadComponent().then(function() {
      return module;
    });
  };

  ModuleContainer.prototype.toFront = function(module) {
    var modules = this.modules();
    var index = modules.indexOf(module);

    if (index === -1)
      return;

    modules.splice(index, 1);
    modules.push(module);
  };

  ModuleContainer.prototype.updateZIndex = function() {
    this.modules().forEach(function(module, index) {
      module.zIndex(index);
    });
  };

  ModuleContainer.prototype.deleter = function(module) {
    var modules = this.modules();
    var index = modules.indexOf(module);

    if (index === -1)
      return;

    modules.splice(index, 1);
    this.updateZIndex();
    this.markDirty();
  };

  ModuleContainer.prototype.fronter = function(module) {
    this.toFront(module);
    this.updateZIndex();
  };

  ModuleContainer.prototype.portToggler = function() {
    // resize the element
    this.markDirty();
  };

  ModuleContainer.prototype.dragStarter = function() {
    this.dragCount(this.dragCount() + 1);
  };

  ModuleContainer.prototype.dragEnder = function() {
    this.dragCount(this.dragCount() - 1);
  };

  ModuleContainer.prototype.dragPortPlugStarter = function(module, port, context) {
    var position = module.plugPosition(port);
    var x = position.x;
    var y = position.y;
    var wire = new ModuleWire({
      sourceX: x,
      sourceY: y,
      targetX: x,
      targetY: y,
      handleType: port.type(),
      handleVisible: true,
      parentHandleElement: this.wireHandleContainerElement()
    });
    wire.parentElement(this.wireContainerElement());
    this.lock(ModuleContainer.LOCK_TYPE_PLUG, module, port, wire);
    this.draggingWires().push(wire);
    context.x = x;
    context.y = y;
    context.wire = wire;
    context.type = port.type();
    context.targetModule = null;
    context.targetPort = null;
  };

  ModuleContainer.prototype.dragPortPlugMover = function(sourceModule, sourcePort, dx, dy, context) {
    var wire = context.wire;
    var x = context.x + dx;
    var y = context.y + dy;

    wire.targetX(x);
    wire.targetY(y);

    var modules = this.modules();
    var type = context.type;
    var currentTargetModule = context.targetModule;
    var currentTargetPort = context.targetPort;
    var targetModule = null;
    var targetPort = null;

    // search the target port-socket by the position of the dragging wire-handle
    for (var mi = modules.length - 1; mi >= 0; mi--) {
      var module = modules[mi];
      var ports = module.ports();
      for (var pi = ports.length - 1; pi >= 0; pi--) {
        var port = ports[pi];
        var position = module.socketPosition(port);
        if (Math.abs(x - position.x) > 18)
          break;
        if (Math.abs(y - position.y) > 18)
          continue;
        if (!port.visible() || port.socketDisabled())
          continue;
        if (!port.socketConnected() && type === port.type()) {
          targetModule = module;
          targetPort = port;
        } else if (module === currentTargetModule && port === currentTargetPort) {
          targetModule = currentTargetModule;
          targetPort = currentTargetPort;
        }
        break;
      }
      if (targetModule && targetPort)
        break;
    }

    if (targetModule === currentTargetModule && targetPort === currentTargetPort) {
      if (targetPort) {
        // fix the target position of the wire
        targetPort.markDirty();
      }
      return;
    }

    if (currentTargetModule && currentTargetPort) {
      this.unbind(sourceModule, sourcePort, currentTargetModule, currentTargetPort);
      // detach the wire-handle from the current target port-socket
      this.unlock(ModuleContainer.LOCK_TYPE_SOCKET, currentTargetModule, currentTargetPort, wire);
      wire.handleVisible(true);
      currentTargetPort.socketConnected(false);
    }

    if (targetModule && targetPort) {
      this.bind(sourceModule, sourcePort, targetModule, targetPort);
      // attach the wire-handle to the target port-socket
      this.lock(ModuleContainer.LOCK_TYPE_SOCKET, targetModule, targetPort, wire);
      targetPort.socketConnected(true);
      wire.handleVisible(false);
    }

    context.targetModule = targetModule;
    context.targetPort = targetPort;
  };

  ModuleContainer.prototype.dragPortPlugEnder = function(sourceModule, sourcePort, context) {
    var draggingWires = this.draggingWires();
    var wire = context.wire;
    var targetModule = context.targetModule;
    var targetPort = context.targetPort;

    draggingWires.splice(draggingWires.indexOf(wire), 1);

    if (targetModule && targetPort)
      return;

    // remove the dragging wire
    this.unlock(ModuleContainer.LOCK_TYPE_PLUG, sourceModule, sourcePort, wire);
    wire.parentElement(null);
  };

  ModuleContainer.prototype.dragPortSocketStarter = function(module, port, context) {
    var relation = port.relations().filter(function(relation) {
      return (relation.type() === ModuleWireRelation.TYPE_TARGET);
    })[0];

    var wire = relation.wire();
    this.draggingWires().push(wire);

    context.x = wire.targetX();
    context.y = wire.targetY();
    context.wire = wire;
    context.type = port.type();

    var binding = this.bindingList().toArray().filter(function(binding) {
      return (binding.targetModule === module && binding.targetPort === port);
    })[0];

    context.sourceModule = binding.sourceModule;
    context.sourcePort = binding.sourcePort;
    context.targetModule = module;
    context.targetPort = port;
  };

  ModuleContainer.prototype.dragPortSocketMover = function(targetModule, targetPort, dx, dy, context) {
    this.dragPortPlugMover(context.sourceModule, context.sourcePort, dx, dy, context);
  };

  ModuleContainer.prototype.dragPortSocketEnder = function(targetModule, targetPort, context) {
    this.dragPortPlugEnder(context.sourceModule, context.sourcePort, context);
  };

  ModuleContainer.LOCK_TYPE_PLUG = ModuleWireRelation.TYPE_SOURCE;
  ModuleContainer.LOCK_TYPE_SOCKET = ModuleWireRelation.TYPE_TARGET;

  if (typeof module !== 'undefined' && module.exports)
    module.exports = ModuleContainer;
  else
    app.ModuleContainer = ModuleContainer;
})(this.app || (this.app = {}));
<|endoftext|>


<commit_before>module.exports = remove

function remove (arr, i) {
  if (i >= arr.length) return
  var last = arr.pop()
  if (i < arr.length) arr[i] = last
  return last
}
<commit_msg>fix wrong element being returned<commit_after>module.exports = remove

function remove (arr, i) {
  if (i >= arr.length) return
  var last = arr.pop()
  if (i < arr.length) {
    var tmp = arr[i]
    arr[i] = last
    return tmp
  }
  return last
}
<|endoftext|>