<commit_before>var electronPackager = Meteor.wrapAsync(Npm.require("electron-packager"));
var fs = Npm.require('fs');
var mkdirp = Meteor.wrapAsync(Npm.require('mkdirp'));
var path = Npm.require('path');
var proc = Npm.require('child_process');
var dirsum = Meteor.wrapAsync(Npm.require('lucy-dirsum'));
var readFile = Meteor.wrapAsync(fs.readFile);
var writeFile = Meteor.wrapAsync(fs.writeFile);
var rmFile = Meteor.wrapAsync(fs.unlink);
var stat = Meteor.wrapAsync(fs.stat);
var util = Npm.require('util');
var rimraf = Meteor.wrapAsync(Npm.require('rimraf'));
var ncp = Meteor.wrapAsync(Npm.require('ncp'));

var exec = Meteor.wrapAsync(function(command, options, callback){
  proc.exec(command, options, function(err, stdout, stderr){
    callback(err, {stdout: stdout, stderr: stderr});
  });
});

var exists = function(path) {
  try {
    stat(path);
    return true;
  } catch(e) {
    return false;
  }
};

var projectRoot = function(){
  if (process.platform === "win32"){
    return process.env.METEOR_SHELL_DIR.split(".meteor")[0];
  } else {
    return process.env.PWD;
  }
}

var electronSettings = Meteor.settings.electron || {};

var IS_MAC = (process.platform === 'darwin');

/* Entry Point */
createBinaries = function() {
  var results = {};
  var builds;
  if (electronSettings.builds){
    builds = electronSettings.builds;
  } else {
    //just build for the current platform/architecture
    builds = [{platform: process.platform, arch: process.arch}];
  }

  builds.forEach(function(buildInfo){
    var buildRequired = false;

    var buildDirs = createBuildDirectories(buildInfo);

    /* Write out Electron application files */
    var appVersion = electronSettings.version;
    var appName = electronSettings.name || "electron";

    var resolvedAppSrcDir;
    if (electronSettings.appSrcDir) {
      resolvedAppSrcDir = path.join(projectRoot(), 'private', electronSettings.appSrcDir);
    } else {
      // See http://stackoverflow.com/a/29745318/495611 for how the package asset directory is derived.
      // We can't read this from the project directory like the user-specified app directory since
      // we may be loaded from Atmosphere rather than locally.
      resolvedAppSrcDir = path.join(process.cwd(), 'assets', 'packages', 'quark_electron', 'app');
    }

    if (appHasChanged(resolvedAppSrcDir, buildDirs.working)) {
      buildRequired = true;

      var packagePath = packageJSONPath(resolvedAppSrcDir);
      var packageJSON = Npm.require(packagePath);

      // If we're using the default package.json, replace its parameters (note: before the comparison).
      var didReplacePackageParameters = false;
      if (!electronSettings.appSrcDir) {
        if (appVersion) packageJSON.version = appVersion;
        if (appName) {
          packageJSON.name = appName.toLowerCase().replace(/\s/g, '-');
          packageJSON.productName = appName;
        }
        didReplacePackageParameters = true;
      }

      // Record whether `package.json` has changed before overwriting it.
      var packageHasChanged = packageJSONHasChanged(packageJSON, buildDirs.app);

      // Copy the app directory over while also pruning old files.
       if (IS_MAC) {
        // Ensure that the app source directory ends in a slash so we copy its contents.
        // Except node_modules from pruning since we prune that below.
        // TODO(wearhere): `rsync` also uses checksums to only copy what's necessary so theoretically we
        // could always `rsync` rather than checking if the directory's changed first.
         exec(util.format('rsync -a --delete --force --filter="P node_modules" "%s" "%s"',
          path.join(resolvedAppSrcDir, '/'), buildDirs.app));
      } else {
        // TODO(wearhere): More efficient sync on Windows (where `rsync` isn't available.)
        rimraf(buildDirs.app);
        mkdirp(buildDirs.app);
        ncp(resolvedAppSrcDir, buildDirs.app);
      }

      // If we replaced the package parameters, update it in the app dir since we just overwrote it.
      if (didReplacePackageParameters) {
        //for some reason when this file isn't manually removed it
        //fails to be overwritten with an EACCES error
        rmFile(packageJSONPath(buildDirs.app));
        writeFile(packageJSONPath(buildDirs.app), JSON.stringify(packageJSON));
      }
      if (packageHasChanged || !IS_MAC) {
        exec("npm install && npm prune", {cwd: buildDirs.app});
      }
    }

    /* Write out Electron Settings */
    var settings = _.defaults({}, electronSettings, {
      rootUrl: process.env.ROOT_URL
    });

    var signingIdentity = electronSettings.sign;
    var signingIdentityRequiredAndMissing = false;
    if (canServeUpdates()) {
      // Enable the auto-updater if possible.
      if ((buildInfo.platform === 'darwin') && !signingIdentity) {
        // If the app isn't signed and we try to use the auto-updater, it will
        // throw an exception. Log an error if the settings have changed, below.
        signingIdentityRequiredAndMissing = true;
      } else {
        settings.updateFeedUrl = settings.rootUrl + UPDATE_FEED_PATH;
      }
    }

    if (settingsHaveChanged(settings, buildDirs.app)) {
      if (signingIdentityRequiredAndMissing) {
        console.error('Developer ID signing identity is missing: remote updates will not work.');
      }
      buildRequired = true;
      writeFile(settingsPath(buildDirs.app), JSON.stringify(settings));
    }

    var packagerSettings = getPackagerSettings(buildInfo, buildDirs);
    if (packagerSettings.icon && iconHasChanged(packagerSettings.icon, buildDirs.working)) {
      buildRequired = true;
    }

    // TODO(wearhere): If/when the signing identity expires, does its name change? If not, we'll need
    // to force the app to be rebuilt somehow.

    if (packagerSettingsHaveChanged(packagerSettings, buildDirs.working)) {
      buildRequired = true;
    }

    var app = appPath(appName, buildInfo.platform, buildInfo.arch, buildDirs.build);
    if (!exists(app)) {
      buildRequired = true;
    }

    /* Create Build */
    if (buildRequired) {
      var build = electronPackager(packagerSettings)[0];
      console.log("Build created for ", buildInfo.platform, buildInfo.arch, "at", build);
    }

    /* Package the build for download. */
    // TODO(rissem): make this platform independent

    if (buildInfo.platform === 'darwin') {
      // The auto-updater framework only supports installing ZIP releases:
      // https://github.com/Squirrel/Squirrel.Mac#update-json-format
      var downloadName = (appName || "app") + ".zip";
      var compressedDownload = path.join(buildDirs.final, downloadName);

      if (buildRequired || !exists(compressedDownload)) {
        // Use `ditto` to ZIP the app because I couldn't find a good npm module to do it and also that's
        // what a couple of other related projects do:
        // - https://github.com/Squirrel/Squirrel.Mac/blob/8caa2fa2007b29a253f7f5be8fc9f36ace6aa30e/Squirrel/SQRLZipArchiver.h#L24
        // - https://github.com/jenslind/electron-release/blob/4a2a701c18664ec668c3570c3907c0fee72f5e2a/index.js#L109
        exec('ditto -ck --sequesterRsrc --keepParent "' + app + '" "' + compressedDownload + '"');
        console.log("Downloadable created at", compressedDownload);
      }
    }

    results[buildInfo.platform + "-" + buildInfo.arch] = {
      app: app,
      buildRequired: buildRequired
    };
  });

  return results;
};

function createBuildDirectories(build){
  // Use a predictable directory so that other scripts can locate the builds, also so that the builds
  // may be cached:

  var workingDir = path.join(projectRoot(), '.meteor-electron', build.platform + "-" + build.arch);
  mkdirp(workingDir);

  //TODO consider seeding the binaryDir from package assets so package
  //could work without an internet connection

  // *binaryDir* holds the vanilla electron apps
  var binaryDir = path.join(workingDir, "releases");
  mkdirp(binaryDir);

  // *appDir* holds the electron application that points to a meteor app
  var appDir = path.join(workingDir, "apps");
  mkdirp(appDir);

  // *buildDir* contains the uncompressed apps
  var buildDir = path.join(workingDir, "builds");
  mkdirp(buildDir);

  // *finalDir* contains zipped apps ready to be downloaded
  var finalDir = path.join(workingDir, "final");
  mkdirp(finalDir);

  return {
    working: workingDir,
    binary: binaryDir,
    app: appDir,
    build: buildDir,
    final: finalDir
  };
}

function getPackagerSettings(buildInfo, dirs){
  var packagerSettings = {
    dir: dirs.app,
    name: electronSettings.name || "Electron",
    platform: buildInfo.platform,
    arch: buildInfo.arch,
    version: "0.36.0",
    out: dirs.build,
    cache: dirs.binary,
    overwrite: true
  };

  if (electronSettings.version) {
    packagerSettings['app-version'] = electronSettings.version;
  }
  if (electronSettings.icon) {
    var icon = platformSpecificSetting(electronSettings.icon, buildInfo.platform);
    if (icon) {
      var iconPath = path.join(projectRoot(), 'private', icon);
      packagerSettings.icon = iconPath;
    }
  }
  if (electronSettings.sign) {
    packagerSettings.sign = electronSettings.sign;
  }
  if (electronSettings.protocols) {
    packagerSettings.protocols = electronSettings.protocols;
  }
  return packagerSettings;
}

function settingsPath(appDir) {
  return path.join(appDir, 'electronSettings.json');
}

function settingsHaveChanged(settings, appDir) {
  var electronSettingsPath = settingsPath(appDir);
  var existingElectronSettings;
  try {
    existingElectronSettings = Npm.require(electronSettingsPath);
  } catch(e) {
    // No existing settings.
  }
  return !existingElectronSettings || !_.isEqual(settings, existingElectronSettings);
}

function appHasChanged(appSrcDir, workingDir) {
  var appChecksumPath = path.join(workingDir, 'appChecksum.txt');
  var existingAppChecksum;
  try {
    existingAppChecksum = readFile(appChecksumPath, 'utf8');
  } catch(e) {
    // No existing checksum.
  }

  var appChecksum = dirsum(appSrcDir);
  if (appChecksum !== existingAppChecksum) {
    writeFile(appChecksumPath, appChecksum);
    return true;
  } else {
    return false;
  }
}

function packageJSONPath(appDir) {
  return path.join(appDir, 'package.json');
}

function packageJSONHasChanged(packageJSON, appDir) {
  var packagePath = packageJSONPath(appDir);
  var existingPackageJSON;
  try {
    existingPackageJSON = Npm.require(packagePath);
  } catch(e) {
    // No existing package.
  }

  return !existingPackageJSON || !_.isEqual(packageJSON, existingPackageJSON);
}

function packagerSettingsHaveChanged(settings, workingDir) {
  var settingsPath = path.join(workingDir, 'lastUsedPackagerSettings.json');
  var existingPackagerSettings;
  try {
    existingPackagerSettings = Npm.require(settingsPath);
  } catch(e) {
    // No existing settings.
  }

  if (!existingPackagerSettings || !_.isEqual(settings, existingPackagerSettings)) {
    writeFile(settingsPath, JSON.stringify(settings));
    return true;
  } else {
    return false;
  }
}

function iconHasChanged(iconPath, workingDir) {
  var iconChecksumPath = path.join(workingDir, 'iconChecksum.txt');
  var existingIconChecksum;
  try {
    existingIconChecksum = readFile(iconChecksumPath, 'utf8');
  } catch(e) {
    // No existing checksum.
  }

  // `dirsum` works for files too.
  var iconChecksum = dirsum(iconPath);
  if (iconChecksum !== existingIconChecksum) {
    writeFile(iconChecksumPath, iconChecksum);
    return true;
  } else {
    return false;
  }
}

function appPath(appName, platform, arch, buildDir) {
  return path.join(buildDir, [appName, platform, arch].join('-'), appName + '.app');
}
<commit_msg>write out description<commit_after>var electronPackager = Meteor.wrapAsync(Npm.require("electron-packager"));
var fs = Npm.require('fs');
var mkdirp = Meteor.wrapAsync(Npm.require('mkdirp'));
var path = Npm.require('path');
var proc = Npm.require('child_process');
var dirsum = Meteor.wrapAsync(Npm.require('lucy-dirsum'));
var readFile = Meteor.wrapAsync(fs.readFile);
var writeFile = Meteor.wrapAsync(fs.writeFile);
var rmFile = Meteor.wrapAsync(fs.unlink);
var stat = Meteor.wrapAsync(fs.stat);
var util = Npm.require('util');
var rimraf = Meteor.wrapAsync(Npm.require('rimraf'));
var ncp = Meteor.wrapAsync(Npm.require('ncp'));

var exec = Meteor.wrapAsync(function(command, options, callback){
  proc.exec(command, options, function(err, stdout, stderr){
    callback(err, {stdout: stdout, stderr: stderr});
  });
});

var exists = function(path) {
  try {
    stat(path);
    return true;
  } catch(e) {
    return false;
  }
};

var projectRoot = function(){
  if (process.platform === "win32"){
    return process.env.METEOR_SHELL_DIR.split(".meteor")[0];
  } else {
    return process.env.PWD;
  }
}

var electronSettings = Meteor.settings.electron || {};

var IS_MAC = (process.platform === 'darwin');

/* Entry Point */
createBinaries = function() {
  var results = {};
  var builds;
  if (electronSettings.builds){
    builds = electronSettings.builds;
  } else {
    //just build for the current platform/architecture
    builds = [{platform: process.platform, arch: process.arch}];
  }

  builds.forEach(function(buildInfo){
    var buildRequired = false;

    var buildDirs = createBuildDirectories(buildInfo);

    /* Write out Electron application files */
    var appVersion = electronSettings.version;
    var appName = electronSettings.name || "electron";
    var appDescription = electronSettings.description;

    var resolvedAppSrcDir;
    if (electronSettings.appSrcDir) {
      resolvedAppSrcDir = path.join(projectRoot(), 'private', electronSettings.appSrcDir);
    } else {
      // See http://stackoverflow.com/a/29745318/495611 for how the package asset directory is derived.
      // We can't read this from the project directory like the user-specified app directory since
      // we may be loaded from Atmosphere rather than locally.
      resolvedAppSrcDir = path.join(process.cwd(), 'assets', 'packages', 'quark_electron', 'app');
    }

    if (appHasChanged(resolvedAppSrcDir, buildDirs.working)) {
      buildRequired = true;

      var packagePath = packageJSONPath(resolvedAppSrcDir);
      var packageJSON = Npm.require(packagePath);

      // If we're using the default package.json, replace its parameters (note: before the comparison).
      var didReplacePackageParameters = false;
      if (!electronSettings.appSrcDir) {
        if (appVersion) packageJSON.version = appVersion;
        if (appName) {
          packageJSON.name = appName.toLowerCase().replace(/\s/g, '-');
          packageJSON.productName = appName;
        }
        if (appDescription){
          packageJSON.description = appDescription;
        }
        didReplacePackageParameters = true;
      }

      // Record whether `package.json` has changed before overwriting it.
      var packageHasChanged = packageJSONHasChanged(packageJSON, buildDirs.app);

      // Copy the app directory over while also pruning old files.
       if (IS_MAC) {
        // Ensure that the app source directory ends in a slash so we copy its contents.
        // Except node_modules from pruning since we prune that below.
        // TODO(wearhere): `rsync` also uses checksums to only copy what's necessary so theoretically we
        // could always `rsync` rather than checking if the directory's changed first.
         exec(util.format('rsync -a --delete --force --filter="P node_modules" "%s" "%s"',
          path.join(resolvedAppSrcDir, '/'), buildDirs.app));
      } else {
        // TODO(wearhere): More efficient sync on Windows (where `rsync` isn't available.)
        rimraf(buildDirs.app);
        mkdirp(buildDirs.app);
        ncp(resolvedAppSrcDir, buildDirs.app);
      }

      // If we replaced the package parameters, update it in the app dir since we just overwrote it.
      if (didReplacePackageParameters) {
        //for some reason when this file isn't manually removed it
        //fails to be overwritten with an EACCES error
        rimraf(packageJSONPath(buildDirs.app));
        writeFile(packageJSONPath(buildDirs.app), JSON.stringify(packageJSON));
      }
      if (packageHasChanged || !IS_MAC) {
        exec("npm install && npm prune", {cwd: buildDirs.app});
      }
    }

    /* Write out Electron Settings */
    var settings = _.defaults({}, electronSettings, {
      rootUrl: process.env.ROOT_URL
    });

    var signingIdentity = electronSettings.sign;
    var signingIdentityRequiredAndMissing = false;
    if (canServeUpdates()) {
      // Enable the auto-updater if possible.
      if ((buildInfo.platform === 'darwin') && !signingIdentity) {
        // If the app isn't signed and we try to use the auto-updater, it will
        // throw an exception. Log an error if the settings have changed, below.
        signingIdentityRequiredAndMissing = true;
      } else {
        settings.updateFeedUrl = settings.rootUrl + UPDATE_FEED_PATH;
      }
    }

    if (settingsHaveChanged(settings, buildDirs.app)) {
      if (signingIdentityRequiredAndMissing) {
        console.error('Developer ID signing identity is missing: remote updates will not work.');
      }
      buildRequired = true;
      writeFile(settingsPath(buildDirs.app), JSON.stringify(settings));
    }

    var packagerSettings = getPackagerSettings(buildInfo, buildDirs);
    if (packagerSettings.icon && iconHasChanged(packagerSettings.icon, buildDirs.working)) {
      buildRequired = true;
    }

    // TODO(wearhere): If/when the signing identity expires, does its name change? If not, we'll need
    // to force the app to be rebuilt somehow.

    if (packagerSettingsHaveChanged(packagerSettings, buildDirs.working)) {
      buildRequired = true;
    }

    var app = appPath(appName, buildInfo.platform, buildInfo.arch, buildDirs.build);
    if (!exists(app)) {
      buildRequired = true;
    }

    /* Create Build */
    if (buildRequired) {
      var build = electronPackager(packagerSettings)[0];
      console.log("Build created for ", buildInfo.platform, buildInfo.arch, "at", build);
    }

    /* Package the build for download. */
    // TODO(rissem): make this platform independent

    if (buildInfo.platform === 'darwin') {
      // The auto-updater framework only supports installing ZIP releases:
      // https://github.com/Squirrel/Squirrel.Mac#update-json-format
      var downloadName = (appName || "app") + ".zip";
      var compressedDownload = path.join(buildDirs.final, downloadName);

      if (buildRequired || !exists(compressedDownload)) {
        // Use `ditto` to ZIP the app because I couldn't find a good npm module to do it and also that's
        // what a couple of other related projects do:
        // - https://github.com/Squirrel/Squirrel.Mac/blob/8caa2fa2007b29a253f7f5be8fc9f36ace6aa30e/Squirrel/SQRLZipArchiver.h#L24
        // - https://github.com/jenslind/electron-release/blob/4a2a701c18664ec668c3570c3907c0fee72f5e2a/index.js#L109
        exec('ditto -ck --sequesterRsrc --keepParent "' + app + '" "' + compressedDownload + '"');
        console.log("Downloadable created at", compressedDownload);
      }
    }

    results[buildInfo.platform + "-" + buildInfo.arch] = {
      app: app,
      buildRequired: buildRequired
    };
  });

  return results;
};

function createBuildDirectories(build){
  // Use a predictable directory so that other scripts can locate the builds, also so that the builds
  // may be cached:

  var workingDir = path.join(projectRoot(), '.meteor-electron', build.platform + "-" + build.arch);
  mkdirp(workingDir);

  //TODO consider seeding the binaryDir from package assets so package
  //could work without an internet connection

  // *binaryDir* holds the vanilla electron apps
  var binaryDir = path.join(workingDir, "releases");
  mkdirp(binaryDir);

  // *appDir* holds the electron application that points to a meteor app
  var appDir = path.join(workingDir, "apps");
  mkdirp(appDir);

  // *buildDir* contains the uncompressed apps
  var buildDir = path.join(workingDir, "builds");
  mkdirp(buildDir);

  // *finalDir* contains zipped apps ready to be downloaded
  var finalDir = path.join(workingDir, "final");
  mkdirp(finalDir);

  return {
    working: workingDir,
    binary: binaryDir,
    app: appDir,
    build: buildDir,
    final: finalDir
  };
}

function getPackagerSettings(buildInfo, dirs){
  var packagerSettings = {
    dir: dirs.app,
    name: electronSettings.name || "Electron",
    platform: buildInfo.platform,
    arch: buildInfo.arch,
    version: "0.36.0",
    out: dirs.build,
    cache: dirs.binary,
    overwrite: true
  };

  if (electronSettings.version) {
    packagerSettings['app-version'] = electronSettings.version;
  }
  if (electronSettings.icon) {
    var icon = platformSpecificSetting(electronSettings.icon, buildInfo.platform);
    if (icon) {
      var iconPath = path.join(projectRoot(), 'private', icon);
      packagerSettings.icon = iconPath;
    }
  }
  if (electronSettings.sign) {
    packagerSettings.sign = electronSettings.sign;
  }
  if (electronSettings.protocols) {
    packagerSettings.protocols = electronSettings.protocols;
  }
  return packagerSettings;
}

function settingsPath(appDir) {
  return path.join(appDir, 'electronSettings.json');
}

function settingsHaveChanged(settings, appDir) {
  var electronSettingsPath = settingsPath(appDir);
  var existingElectronSettings;
  try {
    existingElectronSettings = Npm.require(electronSettingsPath);
  } catch(e) {
    // No existing settings.
  }
  return !existingElectronSettings || !_.isEqual(settings, existingElectronSettings);
}

function appHasChanged(appSrcDir, workingDir) {
  var appChecksumPath = path.join(workingDir, 'appChecksum.txt');
  var existingAppChecksum;
  try {
    existingAppChecksum = readFile(appChecksumPath, 'utf8');
  } catch(e) {
    // No existing checksum.
  }

  var appChecksum = dirsum(appSrcDir);
  if (appChecksum !== existingAppChecksum) {
    writeFile(appChecksumPath, appChecksum);
    return true;
  } else {
    return false;
  }
}

function packageJSONPath(appDir) {
  return path.join(appDir, 'package.json');
}

function packageJSONHasChanged(packageJSON, appDir) {
  var packagePath = packageJSONPath(appDir);
  var existingPackageJSON;
  try {
    existingPackageJSON = Npm.require(packagePath);
  } catch(e) {
    // No existing package.
  }

  return !existingPackageJSON || !_.isEqual(packageJSON, existingPackageJSON);
}

function packagerSettingsHaveChanged(settings, workingDir) {
  var settingsPath = path.join(workingDir, 'lastUsedPackagerSettings.json');
  var existingPackagerSettings;
  try {
    existingPackagerSettings = Npm.require(settingsPath);
  } catch(e) {
    // No existing settings.
  }

  if (!existingPackagerSettings || !_.isEqual(settings, existingPackagerSettings)) {
    writeFile(settingsPath, JSON.stringify(settings));
    return true;
  } else {
    return false;
  }
}

function iconHasChanged(iconPath, workingDir) {
  var iconChecksumPath = path.join(workingDir, 'iconChecksum.txt');
  var existingIconChecksum;
  try {
    existingIconChecksum = readFile(iconChecksumPath, 'utf8');
  } catch(e) {
    // No existing checksum.
  }

  // `dirsum` works for files too.
  var iconChecksum = dirsum(iconPath);
  if (iconChecksum !== existingIconChecksum) {
    writeFile(iconChecksumPath, iconChecksum);
    return true;
  } else {
    return false;
  }
}

function appPath(appName, platform, arch, buildDir) {
  return path.join(buildDir, [appName, platform, arch].join('-'), appName + '.app');
}
<|endoftext|>


<commit_before>/**
 * Created by egacl on 08-06-15.
 */

angular.module('versu.login', [])

.controller('LoginCtrl', function($scope, $state, TwitterService, UserTwitterService, $ionicHistory){
    //se limpia el historial
    $ionicHistory.clearHistory();
    $scope.showLoginButton = true;

    $scope.userLoginData = {};

    var doLogin = function () {
        UserTwitterService.initialization(function (loginData, userData) {
            //console.log('login: se recupera info de usuario: ' + loginData + ' / ' + userData);
            $ionicHistory.nextViewOptions({
                disableBack: true
            });
            $state.go('login');
        });
    };

    if(TwitterService.getStoredToken()!==null) {
        $scope.showLoginButton = false;
        doLogin();
    }
    else {
        console.log('Usuario debe autenticarse antes de entrar a la app');
    };

    $scope.login = function() {
        doLogin();
    };

    $scope.otherLogin = function() {
        console.log($scope.userLoginData.username + ' usuario chanta entrando!');
        TwitterService.setOtherUser($scope.userLoginData.username);
        $state.go('app.home');
    };
})<commit_msg>fix login twitter<commit_after>/**
 * Created by egacl on 08-06-15.
 */

angular.module('versu.login', [])

.controller('LoginCtrl', function($scope, $state, TwitterService, UserTwitterService, $ionicHistory){
    //se limpia el historial
    $ionicHistory.clearHistory();
    $scope.showLoginButton = true;

    $scope.userLoginData = {};

    var doLogin = function () {
        UserTwitterService.initialization(function (loginData, userData) {
            //console.log('login: se recupera info de usuario: ' + loginData + ' / ' + userData);
            $ionicHistory.nextViewOptions({
                disableBack: true
            });
            $state.go('app.home');
        });
    };

    if(TwitterService.getStoredToken()!==null) {
        $scope.showLoginButton = false;
        doLogin();
    }
    else {
        console.log('Usuario debe autenticarse antes de entrar a la app');
    };

    $scope.login = function() {
        doLogin();
    };

    $scope.otherLogin = function() {
        console.log($scope.userLoginData.username + ' usuario chanta entrando!');
        TwitterService.setOtherUser($scope.userLoginData.username);
        $state.go('app.home');
    };
})<|endoftext|>


<commit_before>'use strict';
import noUseExtendNativeRule from '../rules/no-use-extend-native';
import {RuleTester} from 'eslint';

let ruleTester = new RuleTester();

ruleTester.run('no-use-native-extend', noUseExtendNativeRule, {
  valid: [
    {code: 'gulp.task();'},
    {code: 'Custom.prototype.custom'},
    {code: 'Array.prototype.map'},
    {code: 'Array.prototype.map.call([1,2,3], function (x) { console.log(x); });'},
    {code: '[].push(1);'},
    {code: '({}).toString();'},
    {code: '/match_this/.test();'},
    {code: '\'string\'.toString();'},
    {code: '(1).toFixed();'},
    {code: '1..toFixed();'},
    {code: '1.0.toFixed();'},
    {code: '(\'str\' + \'ing\').toString();'},
    {code: '(\'str\' + \'i\' + \'ng\').toString();'},
    {code: '(1 + 1).valueOf();'},
    {code: '(1 + 1 + 1).valueOf();'},
    {code: '(1 + \'string\').toString();'},
    {code: '(/regex/ + /regex/).toString();'},
    {code: '(/regex/ + 1).toString();'},
    {code: '([1] + [2]).toString();'},
    {code: '(function testFunction() {}).toString();'},
    {code: 'new Array().toString();'},
    {code: 'new ArrayBuffer().constructor();'},
    {code: 'new Boolean().toString();'},
    {code: 'new DataView().buffer();'},
    {code: 'new Date().getDate();'},
    {code: 'new Error().message();'},
    {code: 'new Error().stack;'},
    {code: 'new Float32Array().values();'},
    {code: 'new Float64Array().values();'},
    {code: 'new Function().toString();'},
    {code: 'new Int16Array().values();'},
    {code: 'new Int32Array().values();'},
    {code: 'new Int8Array().values();'},
    {code: 'new Map().clear();'},
    {code: 'new Number().toString();'},
    {code: 'new Object().toString();'},
    {code: 'new Object().toString;'},
    {code: 'new Promise().then();'},
    {code: 'new RegExp().test();'},
    {code: 'new Set().values();'},
    {code: 'new String().toString();'},
    {code: 'new Symbol().toString();'},
    {code: 'new Uint16Array().values();'},
    {code: 'new Uint32Array().values();'},
    {code: 'new Uint8ClampedArray().values();'},
    {code: 'new WeakMap().get();'},
    {code: 'new WeakSet().has();'},
    {code: 'new Array()[\'length\']'},
    {code: 'new Array()[\'toString\']()'}
  ],
  invalid: [
    {
      code: 'Array.prototype.custom;',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: '[].length();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: '\'unicorn\'.green;',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: '[].custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: '({}).custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: '/match_this/.custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: '\'string\'.custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: '(\'str\' + \'ing\').custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: '(\'str\' + \'i\' + \'ng\').custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: '(1 + \'ing\').custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: '(/regex/ + \'ing\').custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: '(1 + 1).toLowerCase();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: '(1 + 1 + 1).toLowerCase();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: '(function testFunction() {}).custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Array().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new ArrayBuffer().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Boolean().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new DataView().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Date().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Error().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Float32Array().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Float64Array().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Function().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Int16Array().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Int32Array().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Int8Array().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Map().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Number().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Object().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Promise().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new RegExp().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Set().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new String().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Symbol().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Uint16Array().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Uint32Array().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Uint8Array().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Uint8ClampedArray().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new WeakMap().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new WeakSet().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Array()[\'custom\']',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Array()[\'custom\']()',
      errors: [{message: 'Avoid using extended native objects'}]
    }
  ]
});
<commit_msg>refactor(test): remove duplicate structure for valid<commit_after>'use strict';
import noUseExtendNativeRule from '../rules/no-use-extend-native';
import {RuleTester} from 'eslint';

let ruleTester = new RuleTester();

ruleTester.run('no-use-native-extend', noUseExtendNativeRule, {
  valid: [
    'gulp.task();',
    'Custom.prototype.custom',
    'Array.prototype.map',
    'Array.prototype.map.call([1,2,3], function (x) { console.log(x); });',
    '[].push(1);',
    '({}).toString();',
    '/match_this/.test();',
    '\'string\'.toString();',
    '(1).toFixed();',
    '1..toFixed();',
    '1.0.toFixed();',
    '(\'str\' + \'ing\').toString();',
    '(\'str\' + \'i\' + \'ng\').toString();',
    '(1 + 1).valueOf();',
    '(1 + 1 + 1).valueOf();',
    '(1 + \'string\').toString();',
    '(/regex/ + /regex/).toString();',
    '(/regex/ + 1).toString();',
    '([1] + [2]).toString();',
    '(function testFunction() {}).toString();',
    'new Array().toString();',
    'new ArrayBuffer().constructor();',
    'new Boolean().toString();',
    'new DataView().buffer();',
    'new Date().getDate();',
    'new Error().message();',
    'new Error().stack;',
    'new Float32Array().values();',
    'new Float64Array().values();',
    'new Function().toString();',
    'new Int16Array().values();',
    'new Int32Array().values();',
    'new Int8Array().values();',
    'new Map().clear();',
    'new Number().toString();',
    'new Object().toString();',
    'new Object().toString;',
    'new Promise().then();',
    'new RegExp().test();',
    'new Set().values();',
    'new String().toString();',
    'new Symbol().toString();',
    'new Uint16Array().values();',
    'new Uint32Array().values();',
    'new Uint8ClampedArray().values();',
    'new WeakMap().get();',
    'new WeakSet().has();',
    'new Array()[\'length\']',
    'new Array()[\'toString\']()'
  ].map(code => ({code})),
  invalid: [
    {
      code: 'Array.prototype.custom;',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: '[].length();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: '\'unicorn\'.green;',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: '[].custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: '({}).custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: '/match_this/.custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: '\'string\'.custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: '(\'str\' + \'ing\').custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: '(\'str\' + \'i\' + \'ng\').custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: '(1 + \'ing\').custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: '(/regex/ + \'ing\').custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: '(1 + 1).toLowerCase();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: '(1 + 1 + 1).toLowerCase();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: '(function testFunction() {}).custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Array().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new ArrayBuffer().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Boolean().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new DataView().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Date().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Error().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Float32Array().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Float64Array().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Function().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Int16Array().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Int32Array().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Int8Array().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Map().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Number().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Object().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Promise().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new RegExp().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Set().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new String().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Symbol().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Uint16Array().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Uint32Array().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Uint8Array().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Uint8ClampedArray().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new WeakMap().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new WeakSet().custom();',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Array()[\'custom\']',
      errors: [{message: 'Avoid using extended native objects'}]
    },
    {
      code: 'new Array()[\'custom\']()',
      errors: [{message: 'Avoid using extended native objects'}]
    }
  ]
});
<|endoftext|>


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

    angular.module('yuyanApp').controller('manageQuestionCtrl', ['$scope', '$rootScope', '$stateParams', '$state', '$uibModal', 'yuyanAPISvc',
        function ($scope, $rootScope, $stateParams, $state, $uibModal, yuyanAPISvc) {

            $scope.survey = $stateParams.survey;
            $scope.APIMini = 1;
            $scope.APIResolved = 1;
            var survey = $scope.survey;

            // functions
            $scope.goHome = goHome;
            $scope.goSurvey = goSurvey;
            $scope.deleteQuestion = deleteQuestion;
            $scope.addEditQuestion = addEditQuestion;

            function goHome() {
                $state.go('survey');
            }

            function goSurvey() {
                $state.go('manage');
            }

            function deleteQuestion(question) {
                //$scope.deleteQuestion = null;
                var modalInstance = $uibModal.open({
                    animation: true,
                    templateUrl: 'components/manage/modal/deleteQuestion.html',
                    controller: 'deleteQuestionCtrl',
                    size: 'md',
                    resolve: {
                        question: question
                    }
                });

                modalInstance.result.then(function (question) {
                    $scope.deleteQuestion = question;
                    yuyanAPISvc.questionCrudSvc().remove({ surveyId: question.SurveyId, questionId: question.QuestionId },
                        function (data) {
                            var index = $scope.survey.dtoQuestions.indexOf($scope.deleteQuestion);
                            $scope.survey.dtoQuestions.splice(index, 1);

                            toastr.success("Survey Deleted!");
                        }, function (data) {

                        });
                }, function () {
                    // dismissed log
                });
            }

            function addEditQuestion(question) {
                if (!question)
                {
                    question = {
                        SurveyId: $scope.survey.SurveyId,
                        QuestionType: 1,
                        Question: '',
                        dtoItems: []
                    };
                }

                var modalInstance = $uibModal.open({
                    animation: true,
                    templateUrl: 'components/manage/modal/addEditQuestion.html',
                    controller: 'addEditQuestionCtrl',
                    size: 'md',
                    resolve: {
                        question: angular.copy(question)
                    }
                });

                modalInstance.result.then(function (data) {
                    // renew UI dom

                    var isNew = true;
                    // refresh the survey dtoQuestions
                    angular.forEach($scope.survey.dtoQuestions, function (q) {
                        if (q.QuestionId == data.QuestionId) {
                            q.Question = data.Question;
                            q.IsActive = data.IsActive;
                            q.IsDeleted = data.IsDeleted;
                            q.QuestionId = data.QuestionId;
                            q.QuestionOrder = data.QuestionOrder;
                            q.QuestionType = data.QuestionType;
                            q.dtoItems = data.dtoItems;
                            q.SurveyId = data.SurveyId;

                            isNew = false;
                        }
                    });

                    if (isNew) {
                        $scope.survey.dtoQuestions.push(data);
                    }

                }, function () {
                    // dismissed log
                });
            }

        }]);
})();<commit_msg>fix the delete function (question)<commit_after>(function () {
    'use strict';

    angular.module('yuyanApp').controller('manageQuestionCtrl', ['$scope', '$rootScope', '$stateParams', '$state', '$uibModal', 'yuyanAPISvc',
        function ($scope, $rootScope, $stateParams, $state, $uibModal, yuyanAPISvc) {

            $scope.survey = $stateParams.survey;
            $scope.APIMini = 1;
            $scope.APIResolved = 1;
            var survey = $scope.survey;

            // functions
            $scope.goHome = goHome;
            $scope.goSurvey = goSurvey;
            $scope.deleteQuestion = deleteQuestion;
            $scope.addEditQuestion = addEditQuestion;

            function goHome() {
                $state.go('survey');
            }

            function goSurvey() {
                $state.go('manage');
            }

            function deleteQuestion(question) {
                //$scope.deleteQuestion = null;
                var modalInstance = $uibModal.open({
                    animation: true,
                    templateUrl: 'components/manage/modal/deleteQuestion.html',
                    controller: 'deleteQuestionCtrl',
                    size: 'md',
                    resolve: {
                        question: question
                    }
                });

                modalInstance.result.then(function (question) {

                    yuyanAPISvc.questionCrudSvc().remove({ surveyId: question.SurveyId, questionId: question.QuestionId },
                        function (data) {

                            var index = 0;
                            angular.forEach($scope.survey.dtoQuestions, function (q, key) {
                                if (q.QuestionId == question.QuestionId)
                                    index = key;
                            });

                            $scope.survey.dtoQuestions.splice(index, 1);

                            toastr.success("Survey Deleted!");
                        }, function (data) {

                        });
                }, function () {
                    // dismissed log
                });
            }

            function addEditQuestion(question) {
                if (!question)
                {
                    question = {
                        SurveyId: $scope.survey.SurveyId,
                        QuestionType: 1,
                        Question: '',
                        dtoItems: []
                    };
                }

                var modalInstance = $uibModal.open({
                    animation: true,
                    templateUrl: 'components/manage/modal/addEditQuestion.html',
                    controller: 'addEditQuestionCtrl',
                    size: 'md',
                    resolve: {
                        question: angular.copy(question)
                    }
                });

                modalInstance.result.then(function (data) {
                    // renew UI dom

                    var isNew = true;
                    // refresh the survey dtoQuestions
                    angular.forEach($scope.survey.dtoQuestions, function (q) {
                        if (q.QuestionId == data.QuestionId) {
                            q.Question = data.Question;
                            q.IsActive = data.IsActive;
                            q.IsDeleted = data.IsDeleted;
                            q.QuestionId = data.QuestionId;
                            q.QuestionOrder = data.QuestionOrder;
                            q.QuestionType = data.QuestionType;
                            q.dtoItems = data.dtoItems;
                            q.SurveyId = data.SurveyId;

                            isNew = false;
                        }
                    });

                    if (isNew) {
                        $scope.survey.dtoQuestions.push(data);
                    }

                }, function () {
                    // dismissed log
                });
            }

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


<commit_before>'use strict';

/**
 * @ngdoc directive
 * @name waxeApp.directive:editor
 * @description
 * # editor
 */
angular.module('waxeApp')
    .directive('editor', ['$interval', '$anchorScroll', '$location',  'Session', 'FileUtils', function ($interval, $anchorScroll, $location, Session, FileUtils) {
        return {
            template: '

',
            restrict: 'E',
            scope: {
                'html': '='
            },
            link: function postLink(scope, element) {
                element.append(scope.html);
                var listener = scope.$watch(function(){
                    if(element.text()) {
                        $anchorScroll($location.hash());
                        // Remove the watch since the form is fully loaded
                        listener();
                        waxe.form = new waxe.Form(scope.$parent.treeData);
                        Session.form = waxe.form;
                        angular.element(document).on('click', '.btn-external-editor', function() {
                            eval('scope.$parent.' + angular.element(this).attr('ng-click'));
                        });
                    }
                });

                Session.autosave_interval = $interval(function() {
                    if (Session.form && Session.form.filename && Session.form.status === 'updated'){
                        FileUtils.save();
                    }
                }, 1000 * 10);
            }
        };
    }])
    .directive('xmlfilters', [function () {
        return {
            template: '
<button class="btn btn-default btn-xs" ng-class="{\'active\': filter.active}" ng-click="toggle(filter)" ng-repeat="filter in filters">{{filter.name}}</button>
',
            restrict: 'E',
            scope: {
                'filters': '='
            },
            link: function postLink(scope, element) {
                var $container;
                var cntActive = 0;
                var activeFilter = function(name, active) {
                    if (active) {
                        $container.addClass('xml-filter-' + name);
                        cntActive += 1;
                    }
                    else {
                        $container.removeClass('xml-filter-' + name);
                        cntActive -= 1;
                    }
                    if (cntActive > 0) {
                        $container.addClass('xml-filters');
                    }
                    else {
                        $container.removeClass('xml-filters');
                    }
                };
                if (scope.filters !== null) {
                    var w = scope.$watch(function() {
                        $container = angular.element('.layout-container');
                        if($container.length && angular.isDefined(scope.filters)) {
                            w();
                            element.addClass('has-xml-filters');
                            angular.forEach(scope.filters, function(filter) {
                                if (filter.active) {
                                    activeFilter(filter.name, true);
                                }
                            });
                        }
                    });
                }

                scope.toggle = function(filter) {
                    filter.active = !filter.active;
                    activeFilter(filter.name, filter.active);
                };
            }
        };
    }]);
<commit_msg>Support title on filter<commit_after>'use strict';

/**
 * @ngdoc directive
 * @name waxeApp.directive:editor
 * @description
 * # editor
 */
angular.module('waxeApp')
    .directive('editor', ['$interval', '$anchorScroll', '$location',  'Session', 'FileUtils', function ($interval, $anchorScroll, $location, Session, FileUtils) {
        return {
            template: '

',
            restrict: 'E',
            scope: {
                'html': '='
            },
            link: function postLink(scope, element) {
                element.append(scope.html);
                var listener = scope.$watch(function(){
                    if(element.text()) {
                        $anchorScroll($location.hash());
                        // Remove the watch since the form is fully loaded
                        listener();
                        waxe.form = new waxe.Form(scope.$parent.treeData);
                        Session.form = waxe.form;
                        angular.element(document).on('click', '.btn-external-editor', function() {
                            eval('scope.$parent.' + angular.element(this).attr('ng-click'));
                        });
                    }
                });

                Session.autosave_interval = $interval(function() {
                    if (Session.form && Session.form.filename && Session.form.status === 'updated'){
                        FileUtils.save();
                    }
                }, 1000 * 10);
            }
        };
    }])
    .directive('xmlfilters', [function () {
        return {
            template: '
<button class="btn btn-default btn-xs" ng-class="{\'active\': filter.active}" title="{{filter.title}}" ng-click="toggle(filter)" ng-repeat="filter in filters">{{filter.name}}</button>
',
            restrict: 'E',
            scope: {
                'filters': '='
            },
            link: function postLink(scope, element) {
                var $container;
                var cntActive = 0;
                var activeFilter = function(name, active) {
                    if (active) {
                        $container.addClass('xml-filter-' + name);
                        cntActive += 1;
                    }
                    else {
                        $container.removeClass('xml-filter-' + name);
                        cntActive -= 1;
                    }
                    if (cntActive > 0) {
                        $container.addClass('xml-filters');
                    }
                    else {
                        $container.removeClass('xml-filters');
                    }
                };
                if (scope.filters !== null) {
                    var w = scope.$watch(function() {
                        $container = angular.element('.layout-container');
                        if($container.length && angular.isDefined(scope.filters)) {
                            w();
                            element.addClass('has-xml-filters');
                            angular.forEach(scope.filters, function(filter) {
                                if (filter.active) {
                                    activeFilter(filter.name, true);
                                }
                            });
                        }
                    });
                }

                scope.toggle = function(filter) {
                    filter.active = !filter.active;
                    activeFilter(filter.name, filter.active);
                };
            }
        };
    }]);
<|endoftext|>


<commit_before>import { inject as service } from '@ember/service';
import Component from '@ember/component';
import { isSafari } from 'ui/utils/platform';
import layout from './template';
import { get, set } from '@ember/object';
import { Promise as EmberPromise, all } from 'rsvp';

export default Component.extend({
  layout,
  settings: service(),

  label:           null,
  namePlaceholder: '',
  name:            null,
  value:           null,
  placeholder:     "",
  accept:          "text/*",
  multiple:        false,
  minHeight:       0,
  maxHeight:       200,
  inputName:       false,
  canChangeName:   true,
  canUpload:       true,
  showUploadLabel: true,

  tagName: ['div'],
  classNames: ['box','mb-10','p-10','pt-0'],

  _boundChange: null,
  shouldChangeName: true,

  actions: {
    click() {
      this.$('INPUT[type=file]')[0].click();
    },

    wantsChange() {
      set(this, 'shouldChangeName', true);
    }
  },

  didInsertElement() {
    set(this, '_boundChange', (event) => { this.change(event); });
    this.$('INPUT[type=file]').on('change', get(this, '_boundChange'));
  },

  willDestroyElement() {
    this.$('INPUT[type=file]').off('change', get(this, '_boundChange'));
  },

  change(event) {
    var input = event.target;

    if ( input.files && input.files.length ) {
      if ( get(this, 'canChangeName') ) {
        const firstName = input.files[0].name;
        if ( get(this, 'multiple') ) {
          const ext = firstName.replace(/.*\./,'');
          set(this, 'name', 'multiple.'+ext);
        } else {
          set(this, 'name', firstName);
        }

        set(this, 'shouldChangeName', false);
      }
    }

    const promises = [];
    let file;
    for ( let i = 0 ; i < input.files.length ; i++ ) {
      file = input.files[i];
      promises.push(new EmberPromise((resolve, reject) => {
        var reader = new FileReader();

        reader.onload = (res) => {
          var out = res.target.result;
          resolve(out);
        };

        reader.onerror = (err) => {
          reject(err);
        };

        reader.readAsText(file);
      }));
    }

    all(promises).then((res) => {
      let value = res.join('\n');
      set(this, 'value', value);
    }).finally(() => {
      input.value = '';
    });
  },

  actualAccept: function() {
    if ( isSafari ) {
      return '';
    } else {
      return get(this, 'accept');
    }
  }.property('accept'),
});
<commit_msg>Fix manual input for input-text-file<commit_after>import { inject as service } from '@ember/service';
import Component from '@ember/component';
import { isSafari } from 'ui/utils/platform';
import layout from './template';
import { get, set } from '@ember/object';
import { Promise as EmberPromise, all } from 'rsvp';

export default Component.extend({
  layout,
  settings: service(),

  label:           null,
  namePlaceholder: '',
  name:            null,
  value:           null,
  placeholder:     "",
  accept:          "text/*",
  multiple:        false,
  minHeight:       0,
  maxHeight:       200,
  inputName:       false,
  canChangeName:   true,
  canUpload:       true,
  showUploadLabel: true,

  tagName: ['div'],
  classNames: ['box','mb-10','p-10','pt-0'],

  _boundChange: null,
  shouldChangeName: true,

  actions: {
    click() {
      this.$('INPUT[type=file]')[0].click();
    },

    wantsChange() {
      set(this, 'shouldChangeName', true);
    }
  },

  didInsertElement() {
    set(this, '_boundChange', (event) => { this.change(event); });
    this.$('INPUT[type=file]').on('change', get(this, '_boundChange'));
  },

  willDestroyElement() {
    this.$('INPUT[type=file]').off('change', get(this, '_boundChange'));
  },

  change(event) {
    var input = event.target;

    if ( !input.files || !input.files.length ) {
      return;
    }

    if ( get(this, 'canChangeName') ) {
      const firstName = input.files[0].name;
      if ( get(this, 'multiple') ) {
        const ext = firstName.replace(/.*\./,'');
        set(this, 'name', 'multiple.'+ext);
      } else {
        set(this, 'name', firstName);
      }

      set(this, 'shouldChangeName', false);
    }

    const promises = [];
    let file;
    for ( let i = 0 ; i < input.files.length ; i++ ) {
      file = input.files[i];
      promises.push(new EmberPromise((resolve, reject) => {
        var reader = new FileReader();

        reader.onload = (res) => {
          var out = res.target.result;
          resolve(out);
        };

        reader.onerror = (err) => {
          reject(err);
        };

        reader.readAsText(file);
      }));
    }

    all(promises).then((res) => {
      let value = res.join('\n');
      set(this, 'value', value);
    }).finally(() => {
      input.value = '';
    });
  },

  actualAccept: function() {
    if ( isSafari ) {
      return '';
    } else {
      return get(this, 'accept');
    }
  }.property('accept'),
});
<|endoftext|>


<commit_before>define(['app', 'underscore', './local-storage-service', './app-config-service',
'components/scbd-angularjs-services/services/locale'], function(app, _) {

    app.factory('articlesService', ['$http', '$q', 'localStorageService', 'appConfigService', 'locale',
        function($http, $q, realm, localStorageService, appConfigService, locale) {
            return new function() {

                //================================================================================================================
                this.getArticles = function(qs, openInNew) {

                        return $http.get('https://api.cbd.int/api/v2017/articles', {params: qs})
                          .then(function(results){
                                if((results||{}).data && results.data.length > 0)
                                {
                                    var value = JSON.stringify(results.data);

                                    if(openInNew){
                                        value = openInNewWindow(value);
                                    }
                                    value = replaceOembed(value);

                                    return JSON.parse(value);
                                }
                        })
                }
                //================================================================================================================
                function openInNewWindow(str) {
                    return str.replace(/href=/g," target=\\\"_new_window_\\\" href=" );
                }

                //================================================================================================================
                 function replaceOembed(value) {

                        if(value.indexOf("<oembed") > 0){

                            value = value.replace(/www\.youtube\.com\/watch\?v\=/g, "www.youtube.com/embed/" );
                            value = value.replace(/vimeo\.com\//g, "player.vimeo.com/video/" );
                            value = value.replace(/\<oembed url=/g, "\<\/oembed\>/g ," style=\\\"width: 100%; height: 450px;\\\" frameborder=\\\"0\\\" allow=\\\"autoplay; encrypted-media\\\" allowfullscreen=\\\"\\\">" );

                        }

                        return value;

                }

            }
        }
    ]);
});
<commit_msg>remove unused local-storage reference<commit_after>define(['app', 'underscore', './app-config-service',
'components/scbd-angularjs-services/services/locale'], function(app, _) {

    app.factory('articlesService', ['$http',
        function($http) {
            return new function() {

                //================================================================================================================
                this.getArticles = function(qs, openInNew) {

                        return $http.get('https://api.cbd.int/api/v2017/articles', {params: qs})
                          .then(function(results){
                                if((results||{}).data && results.data.length > 0)
                                {
                                    var value = JSON.stringify(results.data);

                                    if(openInNew){
                                        value = openInNewWindow(value);
                                    }
                                    value = replaceOembed(value);

                                    return JSON.parse(value);
                                }
                        })
                }
                //================================================================================================================
                function openInNewWindow(str) {
                    return str.replace(/href=/g," target=\\\"_new_window_\\\" href=" );
                }

                //================================================================================================================
                 function replaceOembed(value) {

                        if(value.indexOf("<oembed") > 0){

                            value = value.replace(/www\.youtube\.com\/watch\?v\=/g, "www.youtube.com/embed/" );
                            value = value.replace(/vimeo\.com\//g, "player.vimeo.com/video/" );
                            value = value.replace(/\<oembed url=/g, "\<\/oembed\>/g ," style=\\\"width: 100%; height: 450px;\\\" frameborder=\\\"0\\\" allow=\\\"autoplay; encrypted-media\\\" allowfullscreen=\\\"\\\">" );

                        }

                        return value;

                }

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


<commit_before>Ext.define('Mba.ux.Searchbar.Searchbar', {
    extend: 'Ext.Container',
    xtype: 'searchbar',

    requires: [
        'Mba.ux.Searchbar.Search',
        'Ext.field.Search'
    ],

    config: {
        cls: 'searchbar',
        layout: 'hbox',
        placeholder: 'Pesquise aqui...',
        items:[{
            xtype: 'button',
            hidden: true,
            ui: 'plain',
            iconCls: 'ion-md-arrow-back',
            cls: 'cancel-search-android',
            itemId: Ext.os.is.Android ? 'cancelSearch' : 'cancelSearchAndroid',
            handler: function() {
                this.parent.down('#searchBarField').setValue(null);
                this.parent.down('#searchBarField').blur();
            }
        }, {
            xtype: 'searchfield',
            itemId: 'searchBarField',
            flex: 2,
            listeners: {
                focus: function() {
                    this.parent.down('#cancelSearch').show();
                    this.toggleCls('search-focused');
                },
                blur: function() {
                    this.parent.down('#cancelSearch').hide();
                    this.toggleCls('search-focused');
                }
            }
        }, {
            xtype: 'button',
            hidden: true,
            ui: 'plain',
            flex: 1,
            text: 'Cancelar',
            cls: 'cancel-search',
            itemId: Ext.os.is.iOS ? 'cancelSearch' : 'cancelSearchAndroid',
            handler: function() {
                this.parent.down('#searchBarField').setValue(null);
                this.parent.down('#searchBarField').blur();
            }
        }]
    },

    /**
     * Atualizando placeholder do campo de busca da searchBar
     * @param value
     */
    updatePlaceholder: function(value) {
        this.down('#searchBarField').setPlaceHolder(value);
    }

});
<commit_msg>correção de blur para cancel (eventos)<commit_after>Ext.define('Mba.ux.Searchbar.Searchbar', {
    extend: 'Ext.Container',
    xtype: 'searchbar',

    requires: [
        'Mba.ux.Searchbar.Search',
        'Ext.field.Search'
    ],

    config: {
        cls: 'searchbar',
        layout: 'hbox',
        placeholder: 'Pesquise aqui...',
        items:[{
            xtype: 'button',
            hidden: true,
            ui: 'plain',
            iconCls: 'ion-md-arrow-back',
            cls: 'cancel-search-android',
            itemId: Ext.os.is.Android ? 'cancelSearch' : 'cancelSearchAndroid',
            handler: function() {
                this.parent.down('#searchBarField').setValue(null);
                this.parent.down('#searchBarField').blur();
                this.hide();
                this.parent.down('#searchBarField').fireEvent('cancel');
            }
        }, {
            xtype: 'searchfield',
            itemId: 'searchBarField',
            flex: 2,
            listeners: {
                focus: function() {
                    this.parent.down('#cancelSearch').show();
                    this.toggleCls('search-focused');
                }
            }
        }, {
            xtype: 'button',
            hidden: true,
            ui: 'plain',
            flex: 1,
            text: 'Cancelar',
            cls: 'cancel-search',
            itemId: Ext.os.is.iOS ? 'cancelSearch' : 'cancelSearchAndroid',
            handler: function() {
                this.parent.down('#searchBarField').setValue(null);
                this.parent.down('#searchBarField').blur();
                this.hide();
                this.parent.down('#searchBarField').fireEvent('cancel');
            }
        }]
    },

    /**
     * Atualizando placeholder do campo de busca da searchBar
     * @param value
     */
    updatePlaceholder: function(value) {
        this.down('#searchBarField').setPlaceHolder(value);
    }

});
<|endoftext|>


<commit_before>
  /**
   *  Pane to set longitude and latitude columns
   *  in the geocoding dialog.
   *
   *  - It needs a table model, if not it won't be able
   *    to know table columns to complete longitude and
   *    latitude options.
   *
   */

  cdb.admin.GeocodingDialog.Pane.LonLat = cdb.admin.GeocodingDialog.Pane.extend({

    className: 'geocoding-pane-lonlat',

    _TEXTS: {
      placeholder:  _t('Select the column(s)'),
      error:        _t('You have to select longitude and latitude')
    },

    initialize: function() {
      this.table = this.options.table;
      this.model = new cdb.admin.GeocodingDialog.Pane.Model({
        valid:      false,
        longitude:  '',
        latitude:   ''
      });
      this.template = cdb.templates.getTemplate(this.options.template || 'table/views/geocoding_dialog/geocoding_dialog_pane_lonlat');
      this._initBinds();
    },

    _initBinds: function() {
      _.bindAll(this, '_onOkClick');
      this.model.bind('change:latitude change:longitude', this._onModelChange, this);
      this.model.bind('change:valid',                     this._onValidChange, this);
    },

    _initViews: function() {
      // Latitude
      var latitude = new cdb.forms.Combo({
        model:        this.model,
        property:     'latitude',
        width:        '220px',
        placeholder:  this._TEXTS.placeholder,
        extra:        this._getTableColumns()
      });

      this.addView(latitude);
      this.$(".table-column.latitude").append(latitude.render().el);

      // Longitude
      var longitude = new cdb.forms.Combo({
        model:        this.model,
        property:     'longitude',
        width:        '220px',
        placeholder:  this._TEXTS.placeholder,
        extra:        this._getTableColumns()
      });

      this.addView(longitude);
      this.$(".table-column.longitude").append(longitude.render().el);

      // Error tab
      this.pane_info = new cdb.admin.ImportInfo({
        el:    this.$('div.infobox'),
        model: this.model
      });
      this.addView(this.pane_info);
    },

    _onValidChange: function() {
      this.$('a.ok')[ this.model.get('valid') ? 'removeClass' : 'addClass' ]('disabled');
    },

    _onModelChange: function() {
      var isValid = this.model.get('latitude') && this.model.get('longitude') ? true : false;
      this.model.set('valid', isValid);

      if (isValid) {
        this.pane_info.hideTab();
      }
    },

    _onOkClick: function(e) {
      if (e) this.killEvent(e);

      if (this.model.get('valid')) {
        this.trigger('geocodingChosen', this.model.attributes, this);
        this.pane_info.hideTab();
      } else {
        this.pane_info.activeTab('error', this._TEXTS.error );
      }
    }

  });<commit_msg>checking latitude/longitude columns for lonlat pane<commit_after>
  /**
   *  Pane to set longitude and latitude columns
   *  in the geocoding dialog.
   *
   *  - It needs a table model, if not it won't be able
   *    to know table columns to complete longitude and
   *    latitude options.
   *
   */

  cdb.admin.GeocodingDialog.Pane.LonLat = cdb.admin.GeocodingDialog.Pane.extend({

    className: 'geocoding-pane-lonlat',

    _TEXTS: {
      placeholder:  _t('Select the column(s)'),
      error:        _t('You have to select longitude and latitude')
    },

    initialize: function() {
      this.table = this.options.table;
      this.model = new cdb.admin.GeocodingDialog.Pane.Model({
        valid:      false,
        longitude:  '',
        latitude:   ''
      });
      this.template = cdb.templates.getTemplate(this.options.template || 'table/views/geocoding_dialog/geocoding_dialog_pane_lonlat');
      this._initBinds();
    },

    _initBinds: function() {
      _.bindAll(this, '_onOkClick');
      this.model.bind('change:latitude change:longitude', this._onModelChange, this);
      this.model.bind('change:valid',                     this._onValidChange, this);
    },

    _initViews: function() {
      // Latitude
      var latitude = new cdb.forms.Combo({
        model:        this.model,
        property:     'latitude',
        width:        '220px',
        placeholder:  this._TEXTS.placeholder,
        extra:        this._getTableColumns()
      });

      this.addView(latitude);
      this.$(".table-column.latitude").append(latitude.render().el);

      // Longitude
      var longitude = new cdb.forms.Combo({
        model:        this.model,
        property:     'longitude',
        width:        '220px',
        placeholder:  this._TEXTS.placeholder,
        extra:        this._getTableColumns()
      });

      this.addView(longitude);
      this.$(".table-column.longitude").append(longitude.render().el);

      // Error tab
      this.pane_info = new cdb.admin.ImportInfo({
        el:    this.$('div.infobox'),
        model: this.model
      });
      this.addView(this.pane_info);

      // Check if LONGITUDE and/or LATITUDE columns are present
      this._checkSelectedColumns()
    },

    // Check if table has longitude or latitude column
    // because select2 auto select those columns if they
    // are present
    _checkSelectedColumns: function() {
      this.model.set({
        longitude: this.$(".table-column.longitude select").val(),
        latitude: this.$(".table-column.latitude select").val()
      })
    },

    _onValidChange: function() {
      this.$('a.ok')[ this.model.get('valid') ? 'removeClass' : 'addClass' ]('disabled');
    },

    _onModelChange: function() {
      var isValid = this.model.get('latitude') && this.model.get('longitude') ? true : false;
      this.model.set('valid', isValid);

      if (isValid) {
        this.pane_info.hideTab();
      }
    },

    _onOkClick: function(e) {
      if (e) this.killEvent(e);

      if (this.model.get('valid')) {
        this.trigger('geocodingChosen', this.model.attributes, this);
        this.pane_info.hideTab();
      } else {
        this.pane_info.activeTab('error', this._TEXTS.error );
      }
    }

  });<|endoftext|>


<commit_before>urb.waspElem = function(ele){
  url = ele.src || ele.href
  if(!url || (new URL(url)).host != document.location.host)
    return;
  urb.waspUrl(url)
}
urb.waspUrl = function(url){
  var xhr = new XMLHttpRequest()
  xhr.open("HEAD", url)
  xhr.send()
  xhr.onload = urb.waspLoadedXHR
}
urb.waspLoadedXHR = function(){urb.wasp(urb.getXHRWasp(this))}
urb.getXHRWasp = function(xhr){
  var dep = xhr.getResponseHeader("etag")
  if(dep) return JSON.parse(dep.substr(2))
}

urb.datadeps = {}
urb.waspData = function(dep){
  urb.datadeps[dep] = true
  urb.wasp(dep)
}
urb.ondataupdate = urb.onupdate  // overridable

var _onupdate = urb.onupdate
urb.onupdate = function(dep){
  if(urb.datadeps[dep]) urb.ondataupdate(dep)
  else _onupdate(dep)
}
<commit_msg>wasp-data debug mode urb.verb<commit_after>// debugging
urb.verb = false
urb.sources = {}
urb.deps.map(function(a){urb.sources[a] = "dep"})

urb.waspElem = function(ele){
  url = ele.src || ele.href
  if(!url || (new URL(url)).host != document.location.host)
    return;
  urb.waspUrl(url)
}
urb.waspUrl = function(url){
  var xhr = new XMLHttpRequest()
  xhr.open("HEAD", url)
  xhr.send()
  xhr.onload = urb.waspLoadedXHR
  xhr.channel = url
}
urb.waspLoadedXHR = function(){
  urb.sources[urb.getXHRWasp(this)] = this.channel
  urb.wasp(urb.getXHRWasp(this))
}
urb.getXHRWasp = function(xhr){
  var dep = xhr.getResponseHeader("etag")
  if(dep) return JSON.parse(dep.substr(2))
}

urb.datadeps = {}
urb.waspData = function(dep){
  urb.datadeps[dep] = true
  urb.wasp(dep)
}
urb.ondataupdate = urb.onupdate  // overridable

var _onupdate = urb.onupdate
urb.onupdate = function(dep){
  if(urb.verb)
    console.log("update", urb.datadeps[dep] ? "data" : "full", dep, urb.sources[dep])
  if(urb.datadeps[dep]) urb.ondataupdate(dep)
  else _onupdate(dep)
}
<|endoftext|>