text:
RmPerm is a command line tool, written in Java, for remove unwanted permissions and/or ADs from an Android APK file.
This is done replacing (using [dexlib2](https://github.com/JesusFreke/smali/tree/master/dexlib2)) the API methods that use certain permissions with custom ones.

You can create your custom methods [in this way](https://github.com/simoneaonzo/ApkWithCustomMethods/blob/master/app/src/main/java/com/example/apkwithcustommethods/CustomMethods.java)
otherwise you can use my custom one: I created [another project](https://github.com/simoneaonzo/ApkWithCustomMethods) for this purpose.

You can download the JAR from [here](https://github.com/simoneaonzo/RmPerm/blob/master/build/libs/rmperm-all.jar?raw=true).

I also released an [Android app](https://github.com/simoneaonzo/AndRmPerm) that uses it, it's GUI is disgusting, any help will be appreciated!

## Usage

```
usage: rmperm [-a] [-c <APK/DEX-filename>] [-d] [-h] [-i <APK-filename>]
-l | -r | -ra | -s <Folder-path> [-o <APK-filename>] [-p <CSVpermission names>] [-v]
 -a,--ads                                  Enable ADs removal
 -c,--custom-methods <APK/DEX-filename>    APK/Dex file with custom
                                           classes
 -d,--debug                                Debug output (implies -v)
 -h,--help                                 Print this help
 -i,--input <APK-filename>                 Input APK file
 -l,--list                                 List permissions
 -o,--output <APK-filename>                Output APK filename
 -p,--permissions <CSV permission names>   Permissions to remove
 -r,--remove                               Remove
 -ra,--removeads                           Remove only ads
 -s,--statistics <Folder-path>             Statistics of contained APKs
 -v,--verbose                              Verbose output
```

N.b.: the square brackets indicate that it is an optional argument.

There are four kinds of scenario:

1. You want to see what permissions  are required by the APK:
  * --list
  * --input *file.apk*
2. You want to remove certain permissions [and ADs] from the APK:
  * --remove
  * --input *file.apk*
  * --output *output.apk*
  * --permissions *PERM1,PERM2,...,PERMN*
  * --custom-methods *custom.apk | classes.dex*
  * [--ads]
3. You want to remove only the ADs from the APK:
  * --removeads
  * --input *file.apk*
  * --output *output.apk*
4. You want to obtain statistics from a set of APKs stored in the same folder:
  * --statistics *folder/*

## How works the permission removal?

Consider a method *m* invoked on a *c* instance of type *C* that returns an object *Or* of type *Tr*, invoked with *n* arguments *a1, ..., an* respectively of type *T1, ..., Tn*

**Tr Or = c.m(T1 a1, ... , Tn an)**

If *Tr = void* the call can be easily removed, otherwise you have to define a static method (so you don't need an instance for invoke it) with the same name (*m* in our case) in a class *H* that returns the same object (*Or* of type *Tr*), invoked with *n+1* arguments *a1, ..., an, an+1* the first of them of type *C*.

**Tr Or = H.m(C c, T1 a1, ... , Tn an)**

In this way for remove a permissionis is sufficient to create a class *H* with all methods of permissions you want to remove.

### Example

Probably you have read anything of what I've written, ok I give to you an example with the method *isWifiEnabled* that use the permission ACCESS_WIFI_STATE:
```
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI SERVICE);
boolean b = wifi.isWifiEnabled();
if (b) {...}
```

You define this method (you can find more of them [here](https://github.com/simoneaonzo/CustomApp/blob/master/app/src/main/java/com/custom/customapp/CustomMethods.java)):
```
@CustomMethodClass
public class CustomMethods {
    @MethodPermission(permission = "android.permission.ACCESS_WIFI_STATE", defClass ="android.net.wifi.WifiManager")
    public static boolean isWifiEnabled(WifiManager wm) {
        return false;
    }
}
```
Here I do something simple but you can instrument, log, hack, crack, trick, track... do what you want!

Finally RmPerm transform it into:
```
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI SERVICE);
boolean b = CustomMethods.isWifiEnabled(wifi);
```

## How works the ADs removal?

All classes like [AdView](https://developers.google.com/android/reference/com/google/android/gms/ads/AdView) and [PublisherAdView](https://developers.google.com/android/reference/com/google/android/gms/ads/doubleclick/PublisherAdView) implement the *loadAd(...)* method.

If this method isn't called the View doesn't load the AD, so, very simply:

  * every time that I found a method called *loadAd*

  * that is defined in a class belonging to *com.google.android.gms.ads.*

  * and its return type is *void*

I remove it :)


text:
package client

// Peer2PeerDiscovery is a peer-to-peer service discovery.
// It always returns the static server.
type Peer2PeerDiscovery struct {
	server   string
	metadata string
}

// NewPeer2PeerDiscovery returns a new Peer2PeerDiscovery.
func NewPeer2PeerDiscovery(server, metadata string) ServiceDiscovery {
	return &Peer2PeerDiscovery{server: server, metadata: metadata}
}

// Clone clones this ServiceDiscovery with new servicePath.
func (d Peer2PeerDiscovery) Clone(servicePath string) ServiceDiscovery {
	return &d
}

// GetServices returns the static server
func (d Peer2PeerDiscovery) GetServices() []*KVPair {
	return []*KVPair{&KVPair{Key: d.server, Value: d.metadata}}
}

// WatchService returns a nil chan.
func (d Peer2PeerDiscovery) WatchService() chan []*KVPair {
	return nil
}

func (d *Peer2PeerDiscovery) RemoveWatcher(ch chan []*KVPair) {}

func (d *Peer2PeerDiscovery) Close() {

}

redpajama_set_name: RedPajamaGithub


text:
package com.jamerlan.utils;

import org.junit.Test;

import static org.junit.Assert.*;

public class CommandParserTest {
    @Test
    public void testParser() throws Exception {
        String line = "BATTLEOPENED 20535 0 0 EvoRTSDedicated4 54.183.228.213 8254 8 0 0 540337253 Archers Battlefield - v05\tEvolution RTS Dedicated Host 4\tEvolution RTS - v10.17";
        CommandParser parser = new CommandParser(line);
        String first = parser.getString(" ");
        System.out.println(first);

        System.out.println(parser.getInt(" "));
        System.out.println(parser.getInt(" "));
        System.out.println(parser.getInt(" "));
        System.out.println(parser.getString(" "));
        System.out.println(parser.getString(" "));//ip
        System.out.println(parser.getInt(" "));//port
        System.out.println(parser.getInt(" "));
        System.out.println(parser.getInt(" "));
        System.out.println(parser.getInt(" "));
        System.out.println(parser.getInt(" "));
        System.out.println(parser.getString("\t"));
        System.out.println(parser.getString("\t"));
        String gameName = parser.getString();
        System.out.println(gameName);

    }

    @Test
    public void testEndOfTheLine() {
        String line = "";
        CommandParser commandParser = new CommandParser(line);
        assertTrue(!commandParser.hasNext(" "));

        String line2 = " ";
        CommandParser commandParser2 = new CommandParser(line2);
        assertTrue(commandParser2.hasNext(" "));
    }
}


text:
module BlackAndWhite
  module Mongoid
    extend ActiveSupport::Concern

    included do
      has_and_belongs_to_many :ab_tests, class_name: 'BlackAndWhite::Mongoid::Test'

      attr_reader :ab_test, :options

      def ab_participate!(test_name, **options, &block)
        @options = options
        if (@ab_test = fetch_ab_test(test_name)).present?
          conditions = true
          conditions = yield(self) if block_given?
          update_participant if conditions
        else
          missing_ab_test(test_name)
        end
      end

      def ab_participates?(test_name)
        ab_tests.detect { |ab_test| ab_test.name == test_name }.present?
      end

      private

      def update_participant
        ab_tests << ab_test
      end

      def missing_ab_test(test_name)
        if options[:raise_on_missing]
          raise AbTestError, "no A/B Test with name #{test_name} exists or it is not active"
        end
        false
      end

      def fetch_ab_test(name)
        query = { name: name }
        if options[:join_inactive] == false
          query.merge!(active: true)
        end

        BlackAndWhite::Mongoid::Test.find_by(query)
      end
    end
  end
end


text:
using namespace primitiv;
using namespace std;
namespace F = primitiv::functions;
namespace I = primitiv::initializers;
namespace O = primitiv::optimizers;

const unsigned NUM_TRAIN_SAMPLES = 60000;
const unsigned NUM_TEST_SAMPLES = 10000;
const unsigned BATCH_SIZE = 200;
const unsigned NUM_TRAIN_BATCHES = NUM_TRAIN_SAMPLES / BATCH_SIZE;
const unsigned NUM_TEST_BATCHES = NUM_TEST_SAMPLES / BATCH_SIZE;
const unsigned MAX_EPOCH = 100;

const unsigned IMAGE_HEIGHT = 28;
const unsigned IMAGE_WIDTH = 28;

const unsigned KERNEL_SIZE1 = 5;  // should be an odd number
const unsigned KERNEL_SIZE2 = 5;  // ditto
const unsigned NUM_CHANNELS1 = 8;
const unsigned NUM_CHANNELS2 = 16;
const unsigned PADDING1 = KERNEL_SIZE1 / 2;
const unsigned PADDING2 = KERNEL_SIZE2 / 2;

const unsigned NUM_INPUT_UNITS
  = (IMAGE_HEIGHT / 4) * (IMAGE_WIDTH / 4) * NUM_CHANNELS2;
const unsigned NUM_HIDDEN_UNITS = 256;
const unsigned NUM_OUTPUT_UNITS = 10;

int main() {
  // Loads data
  vector<float> train_inputs = utils::load_mnist_images(
      "data/train-images-idx3-ubyte", NUM_TRAIN_SAMPLES);
  vector<char> train_labels = utils::load_mnist_labels(
      "data/train-labels-idx1-ubyte", NUM_TRAIN_SAMPLES);
  vector<float> test_inputs = utils::load_mnist_images(
      "data/t10k-images-idx3-ubyte", NUM_TEST_SAMPLES);
  vector<char> test_labels = utils::load_mnist_labels(
      "data/t10k-labels-idx1-ubyte", NUM_TEST_SAMPLES);

  devices::CUDA dev(0);
  Device::set_default(dev);
  Graph g;
  Graph::set_default(g);

  // Parameters of CNNs
  // Shape: {kernel_height, kernel_width, in_channels, out_channels}
  Parameter pw_cnn1(
      {KERNEL_SIZE1, KERNEL_SIZE1, 1, NUM_CHANNELS1},
      I::XavierUniformConv2D());
  Parameter pw_cnn2(
      {KERNEL_SIZE2, KERNEL_SIZE2, NUM_CHANNELS1, NUM_CHANNELS2},
      I::XavierUniformConv2D());

  // Parameters of FC layers
  Parameter pw_fc1({NUM_HIDDEN_UNITS, NUM_INPUT_UNITS},  I::XavierUniform());
  Parameter pw_fc2({NUM_OUTPUT_UNITS, NUM_HIDDEN_UNITS}, I::XavierUniform());
  Parameter pb_fc1({NUM_HIDDEN_UNITS}, I::Constant(0));
  Parameter pb_fc2({NUM_OUTPUT_UNITS}, I::Constant(0));

  // Optimizer
  O::SGD optimizer(.1);
  optimizer.add(pw_cnn1, pw_cnn2, pw_fc1, pw_fc2, pb_fc1, pb_fc2);

  // Helper lambda to construct the predictor network.
  auto make_graph = [&](const vector<float> &inputs, bool train) {
    // Input and parameters.
    const Node x = F::input<Node>(
        Shape({IMAGE_HEIGHT, IMAGE_WIDTH}, BATCH_SIZE), inputs);
    const Node w_cnn1 = F::parameter<Node>(pw_cnn1);
    const Node w_cnn2 = F::parameter<Node>(pw_cnn2);
    const Node w_fc1 = F::parameter<Node>(pw_fc1);
    const Node w_fc2 = F::parameter<Node>(pw_fc2);
    const Node b_fc1 = F::parameter<Node>(pb_fc1);
    const Node b_fc2 = F::parameter<Node>(pb_fc2);
    // CNNs
    const Node h_cnn1 = F::relu(
        F::conv2d(x, w_cnn1, PADDING1, PADDING1, 1, 1, 1, 1));
    const Node h_pool1 = F::max_pool2d(h_cnn1, 2, 2, 0, 0, 2, 2);
    const Node h_cnn2 = F::relu(
        F::conv2d(h_pool1, w_cnn2, PADDING2, PADDING2, 1, 1, 1, 1));
    const Node h_pool2 = F::max_pool2d(h_cnn2, 2, 2, 0, 0, 2, 2);
    // FC layers
    const Node x_fc = F::dropout(F::flatten(h_pool2), .5, train);
    const Node h_fc = F::dropout(
        F::relu(F::matmul(w_fc1, x_fc) + b_fc1), .5, train);
    return F::matmul(w_fc2, h_fc) + b_fc2;
  };

  // Batch randomizer
  mt19937 rng;
  vector<unsigned> ids(NUM_TRAIN_SAMPLES);
  iota(begin(ids), end(ids), 0);

  for (unsigned epoch = 0; epoch < MAX_EPOCH; ++epoch) {
    // Shuffles sample IDs.
    shuffle(begin(ids), end(ids), rng);

    // Training loop
    for (unsigned batch = 0; batch < NUM_TRAIN_BATCHES; ++batch) {
      // Makes a minibatch for training.
      vector<float> inputs(BATCH_SIZE * IMAGE_HEIGHT * IMAGE_WIDTH);
      vector<unsigned> labels(BATCH_SIZE);
      for (unsigned i = 0; i < BATCH_SIZE; ++i) {
        const unsigned id = ids[i + batch * BATCH_SIZE];
        copy(&train_inputs[id * IMAGE_HEIGHT * IMAGE_WIDTH],
             &train_inputs[(id + 1) * IMAGE_HEIGHT * IMAGE_WIDTH],
             &inputs[i * IMAGE_HEIGHT * IMAGE_WIDTH]);
        labels[i] = train_labels[id];
      }

      // Constructs the graph.
      g.clear();
      Node y = make_graph(inputs, true);
      Node loss = F::softmax_cross_entropy(y, labels, 0);
      Node avg_loss = F::batch::mean(loss);

      // Dump computation graph at the first time.
      //if (epoch == 0 && batch == 0) cout << g.dump("dot");

      // Implicit forward, backward, and updates parameters.
      optimizer.reset_gradients();
      avg_loss.backward();
      optimizer.update();
    }

    unsigned match = 0;

    // Test loop
    for (unsigned batch = 0; batch < NUM_TEST_BATCHES; ++batch) {
      // Makes a test minibatch.
      vector<float> inputs(BATCH_SIZE * IMAGE_HEIGHT * IMAGE_WIDTH);
      copy(&test_inputs[batch * BATCH_SIZE * IMAGE_HEIGHT * IMAGE_WIDTH],
           &test_inputs[(batch + 1) * BATCH_SIZE * IMAGE_HEIGHT * IMAGE_WIDTH],
           &inputs[0]);

      // Constructs the graph.
      g.clear();
      Node y = make_graph(inputs, false);

      // Gets outputs, argmax, and compares them with the label.
      vector<float> y_val = y.to_vector();
      for (unsigned i = 0; i < BATCH_SIZE; ++i) {
        float maxval = -1e10;
        int argmax = -1;
        for (unsigned j = 0; j < NUM_OUTPUT_UNITS; ++j) {
          float v = y_val[j + i * NUM_OUTPUT_UNITS];
          if (v > maxval) maxval = v, argmax = static_cast<int>(j);
        }
        if (argmax == test_labels[i + batch * BATCH_SIZE]) ++match;
      }
    }

    const float accuracy = 100.0 * match / NUM_TEST_SAMPLES;
    printf("epoch %d: accuracy: %.2f%%\n", epoch, accuracy);
  }

  return 0;
}


text:
var fs = require('fs');
var path = require('canonical-path');
var util = require('./utils.js');
var semver = require('semver');
var shell = require('shelljs');

var ngdoc = require('../../node_modules/grunt-ngdocs/src/ngdoc.js');
var reader = require('../../node_modules/grunt-ngdocs/src/reader.js');

var projectPath = path.resolve(__dirname, '../..');
var pkg = require(path.resolve(projectPath, 'package.json'));

module.exports = function(grunt) {

  /*
   *
   * Create tasks
   *
   */

  grunt.registerMultiTask('tests', '**Use `grunt test` instead**', function(){
    util.startKarma.call(util, this.data, true, this.async());
  });

  // Run tests on multiple versions of angular
  grunt.registerTask('karmangular', 'Run tests against multiple versions of angular', function() {
    // Start karma servers
    var karmaOpts = grunt.config('karma');

    if (grunt.option('browsers')) {
      grunt.config('karma.options.browsers', grunt.option('browsers').split(/,/).map(function(b) { return b.trim(); }));
    }

    var angularTasks = [];
    for (var o in karmaOpts) {
      if (/^angular-/.test(o)) {
        angularTasks.push(o);
      }
    }

    // If there's a start/run argument, run that argument on each angular task
    if (this.args.length > 0) {
      // Run a test on the most recent angular
      if (this.args[0] === 'latest') {
        var latest = 'angular-' + util.latestAngular();
        var configNamespace = 'karma.' + grunt.config.escape(latest);
        grunt.config(configNamespace + '.background', false);
        grunt.config(configNamespace + '.singleRun', true);
        grunt.task.run('karma:' + latest);
      }

      if (this.args[0] === 'start') {
        angularTasks.forEach(function(t) {
          // Set this karma config to background running
          var configNamespace = 'karma.' + grunt.config.escape(t);
          grunt.config(configNamespace + '.background', true);
          grunt.config(configNamespace + '.singleRun', false);
          grunt.task.run('karma:' + t + ':start');
        });
      }
      else if (this.args[0] === 'run') {
        angularTasks.forEach(function(t) {
          // Set this karma config to background running
          var configNamespace = 'karma.' + grunt.config.escape(t);
          grunt.config(configNamespace + '.background', true);
          grunt.config(configNamespace + '.singleRun', false);
          grunt.task.run('karma:' + t + ':run');
        });
      }
    }
    else {
      angularTasks.forEach(function(t) {
        // Set this task to single running
        var configNamespace = 'karma.' + grunt.config.escape(t);
        grunt.config(configNamespace + '.background', false);
        grunt.config(configNamespace + '.singleRun', true);

        grunt.task.run('karma:' + t);
      });
    }
  });

  // Run multiple tests serially, but continue if one of them fails.
  // Adapted from http://stackoverflow.com/questions/16487681/gruntfile-getting-error-codes-from-programs-serially
  grunt.registerTask('serialsauce', function(){
    // util.travisFoldStart('serialsauce');

    var options = grunt.config('serialsauce');

    var done = this.async();

    var tasks = {}; options.map(function(t) { tasks[t] = 0 });

    var success = true;
    grunt.util.async.forEachSeries(Object.keys(tasks),
      function(task, next) {
        grunt.util.spawn({
          grunt: true,  // use grunt to spawn
          args: [task], // spawn this task
          opts: { stdio: 'inherit' } // print to the same stdout
        }, function(err, result, code) {
          tasks[task] = code;
          if (code !== 0) {
            success = false;
          }
          next();
        });
      },
      function() {
        // util.travisFoldEnd('serialsauce');
        done(success);
    });
  });

  grunt.registerTask('coverage', function () {
    var latest = 'angular-' + util.latestAngular();
    var configNamespace = 'karma.' + grunt.config.escape(latest);
    grunt.config(configNamespace + '.background', false);
    grunt.config(configNamespace + '.singleRun', true);
    grunt.config(configNamespace + '.reporters', ['coverage']);
    grunt.config(configNamespace + '.preprocessors', {
      'src/**/!(*.spec)+(.js)': ['coverage']
    });
    grunt.config(configNamespace + '.coverageReporter', {
      type: 'lcov',
      dir:  'coverage',
      subdir: '.'
    });

    grunt.task.run('karma:' + latest);
  });

  grunt.registerTask('angulars', 'List available angular versions', function() {
    grunt.log.subhead("AngularJS versions available");
    grunt.log.writeln();
    util.angulars().forEach(function (a) {
      grunt.log.writeln(a);
    });
  });

  grunt.registerTask('saucebrowsers', 'List available saucelabs browsers', function() {
    grunt.log.subhead('SauceLabs Browsers Configured');
    grunt.log.writeln();

    var browsers = util.customLaunchers();
    for (var name in browsers) {
      var b = browsers[name];

      var outs = [];
      ['browserName', 'version', 'platform'].map(function (o) {
        if (b[o]) { outs.push(b[o]); }
      });

      grunt.log.write(grunt.log.wordlist([name], { color: 'yellow' }));

      grunt.log.writeln(grunt.log.wordlist([
        ' [',
        outs.join(' | '),
        ']'
      ], { color: 'green', separator: '' }));
    };
  });

  // Utility functions for showing the version
  grunt.registerTask('current-version', function () {
    grunt.log.writeln(util.getVersion());
  });
  grunt.registerTask('stable-version', function () {
    grunt.log.writeln(util.getStableVersion());
  });

  grunt.registerMultiTask('cut-release', 'Release the built code', function() {
    // Require the build and ngdocs tassk to be run first
    grunt.task.requires(['build']);

    var options = this.options({
      stableSuffix: '-stable',
      unstableSuffix: '-unstable',
      cleanup: false
    });

    var done = this.async(),
        self = this;

    var tag = util.getVersion();

    var currentTag = util.getCurrentTag();

    grunt.log.writeln("Version: " + tag);

    if (!tag) {
      grunt.fatal("Couldn't get git version");
    }

    // Figure out if the tag is stable or not (if it has a hyphen in it it's unstable)
    var stable = !/-.+$/.test(tag);
    grunt.log.writeln('stable', stable);

    // Log release type
    grunt.log.writeln(
     'Preparing '
     + grunt.log.wordlist([stable ? 'stable' : 'unstable'], { color: stable ? 'green' : 'yellow'})
     + ' release version '
     + tag
    );

    // If this is a stable release, create a directory for it in the releases dir
    var extension = stable ? options.stableSuffix : options.unstableSuffix;

    self.files.forEach(function (file) {
      var releaseDir;

      // If we're on a stable release or we want to keep unstable releases, create a directory for this release and copy the built files there
      if (currentTag || options.keepUnstable) {
        grunt.log.writeln("DEST: " + file.dest);
        grunt.log.writeln("TAG: " + tag);
        releaseDir = path.join(file.dest, tag);
      }

      file.src.forEach(function (f) {
        var oldFileName = path.basename(f);
        var ext = path.extname(f);
        var basename = path.basename(f, ext);

        if (basename.match(/.min/)) {
          ext = '.min' + ext;
          basename = path.basename(f, ext);
        }

        // Skip file if it was already released
        var re = new RegExp('(' + options.stableSuffix + '|' + options.unstableSuffix + ')');
        if (basename.match(re)) {
          grunt.log.writeln("Skipping file: " + f);
          return;
        }

        // Insert -unstable or -stable into the filename for .css and .js files
        var newFileName;
        if (/(css|js)/.test(ext)) {
          newFileName = basename + extension + ext;
        }
        else {
          newFileName = basename + ext;
        }

        // If this is a stable release
        if (releaseDir) {
          // Create the stable directory if it doesn't exist
          if (!fs.existsSync(releaseDir)) {
            fs.mkdirSync(releaseDir);
          }

          var releasePath = path.join(releaseDir, oldFileName);

          if (path.normalize(f) !== path.normalize(releasePath)) {
            grunt.log.writeln('Copying ' + f + ' to ' + releasePath);
            // fs.createReadStream(f).pipe(fs.createWriteStream(stablePath));
            shell.cp('-f', f, releasePath);
          }
        }

        var newPath = path.join(file.dest, newFileName);

        if (path.normalize(f) !== path.normalize(newPath)) {
          grunt.log.writeln('Copying ' + f + ' to ' + newPath);
          // fs.createReadStream(f).pipe(fs.createWriteStream(newPath));
          shell.cp('-f', f, newPath);
        }

        if (options.cleanup && path.normalize(f) !== path.normalize(newPath)) {
          grunt.log.writeln('Unlinking ' + f, newPath);
          shell.rm(f);
        }
      });
    });

    done();
  });

  // Create the bower.json file
  grunt.registerTask('update-bower-json', function () {
    var currentTag = semver.clean( util.getCurrentTag() );

    var taggedReleaseDir = path.join(path.resolve(process.cwd()), 'dist', 'release', currentTag);

    // Get the list of files from the release directory
    var releaseFiles = fs.readdirSync(taggedReleaseDir)
                         // Filter out minified files and the bower.json file, if it's there already
                         .filter(function (f) {
                            return !/\.min\./.test(f)
                              && !/^bower\.json$/.test(f)
                              && !/^package\.json$/.test(f);
                         })
                         // Preprend "./" to each file path
                         .map(function (f) { return './' + f; });

    // Copy a README file
    var readme = path.resolve(projectPath, 'misc/publish/README.md');
    shell.cp('-f', readme, taggedReleaseDir);

    var bowerJsonFile = path.join(taggedReleaseDir, 'bower.json');
    var pkgJsonFile = path.join(taggedReleaseDir, 'package.json');

    var json = {
      'name': 'angular-ui-grid',
      'description': pkg.description,
      'main': releaseFiles,
      'ignore': [],
      'dependencies': {
        'angular': '>=1.2.16 <=1.3.16' // Note: bower will install 1.2.28 when <=1.3.x is specified...
      },
      'repository': pkg.repository,
      'homepage': 'http://ui-grid.info',
      'keywords': pkg.keywords,
      'license': 'MIT'
    };

    fs.writeFileSync(bowerJsonFile, JSON.stringify(json, null, 2));

    // Add version for package.json
    json.version = currentTag;

    fs.writeFileSync(pkgJsonFile, JSON.stringify(json, null, 2));
  });

  // Publish release to NPM
  grunt.registerTask('npm-publish', function (done) {
    var done = this.async();

    var currentTag = semver.clean( util.getCurrentTag() );

    var taggedReleaseDir = path.join(path.resolve(process.cwd()), 'dist', 'release', currentTag);

    process.chdir(taggedReleaseDir);

    shell.exec('npm publish', function (code, output) {
      done();
    });
  });

  grunt.registerTask('blah', function () {
    reader.docs = []
    grunt.file.recurse(path.resolve(process.cwd(), 'src'), function (abspath, rootdir, subdir, filename) {
      if (!/style\.js$/.test(filename)) { return; }

      var contents = fs.readFileSync(abspath, 'utf8');

      // var d = new ngdoc.Doc(contents);
      // d.parse();
      // console.log(d);

      reader.process(contents, abspath);
    });

    console.log(reader.docs[0].convertUrlToAbsolute());
  });
};


text:
/*!
 * VIZABI Axis Model (hook)
 */

(function () {

  "use strict";

  var root = this;
  var Vizabi = root.Vizabi;
  var utils = Vizabi.utils;

  //warn client if d3 is not defined
  if (!Vizabi._require('d3')) {
    return;
  }

  //constant time formats
  var time_formats = {
    "year": d3.time.format("%Y"),
    "month": d3.time.format("%Y-%m"),
    "week": d3.time.format("%Y-W%W"),
    "day": d3.time.format("%Y-%m-%d"),
    "hour": d3.time.format("%Y-%m-%d %H"),
    "minute": d3.time.format("%Y-%m-%d %H:%M"),
    "second": d3.time.format("%Y-%m-%d %H:%M:%S")
  };

  Vizabi.Model.extend('axis', {
    /**
     * Initializes the color hook
     * @param {Object} values The initial values of this model
     * @param parent A reference to the parent model
     * @param {Object} bind Initial events to bind
     */
    init: function (values, parent, bind) {

      this._type = "axis";
      values = utils.extend({
        use: "value",
        which: undefined,
        min: null,
        max: null
      }, values);
      this._super(values, parent, bind);
    },

    /**
     * Validates a color hook
     */
    validate: function () {

      var possibleScales = ["log", "genericLog", "linear", "time", "pow"];
      if (!this.scaleType || (this.use === "indicator" && possibleScales.indexOf(this.scaleType) === -1)) {
        this.scaleType = 'linear';
      }

      if (this.use !== "indicator" && this.scaleType !== "ordinal") {
        this.scaleType = "ordinal";
      }

      //TODO a hack that kills the scale, it will be rebuild upon getScale request in model.js
      if (this.which_1 != this.which || this.scaleType_1 != this.scaleType) this.scale = null;
      this.which_1 = this.which;
      this.scaleType_1 = this.scaleType;

      if(this.scale && this._readyOnce && this.use=="indicator"){
          if(this.min==null) this.min = this.scale.domain()[0];
          if(this.max==null) this.max = this.scale.domain()[1];

          if(this.min<=0 && this.scaleType=="log") this.min = 0.01;
          if(this.max<=0 && this.scaleType=="log") this.max = 10;

          // Max may be less than min
          // if(this.min>=this.max) this.min = this.max/2;

          if(this.min!=this.scale.domain()[0] || this.max!=this.scale.domain()[1])
              this.scale.domain([this.min, this.max]);
      }
    },

    /**
     * Gets the domain for this hook
     * @returns {Array} domain
     */
    buildScale: function (margins) {
      var domain;
      var scaleType = this.scaleType || "linear";
      if (margins === undefined)
        margins = true;

      if (typeof margins === 'boolean') {
        var res = margins;
        margins = {};
        margins.min = res;
        margins.max = res;
      }

      if (this.scaleType == "time") {
        var limits = this.getLimits(this.which);
        this.scale = d3.time.scale().domain([limits.min, limits.max]);
        return;
      }

      switch (this.use) {
        case "indicator":
          var limits = this.getLimits(this.which),
            margin = (limits.max - limits.min) / 20;

          domain = [(limits.min - (margins.min && margin ? margin : 0)), (limits.max + (margins.max && margin ? margin : 0))];
          if (scaleType == "log") {
            domain = [(limits.min - limits.min / 4), (limits.max + limits.max / 4)];
          }

          break;
        case "property":
          domain = this.getUnique(this.which);
          break;
        case "value":
        default:
          domain = [this.which];
          break;
      }

      if (this.min!=null && this.max!=null && scaleType !== 'ordinal') {
        domain = [this.min, this.max];
        this.min = domain[0];
        this.max = domain[1];
      }

      this.scale = d3.scale[scaleType]().domain(domain);
    }
  });
}).call(this);


text:
(function () {
    var controllerId = 'app.views.layout.sidebarFooter';
    angular.module('app').controller(controllerId, [
        '$rootScope', '$state', 'appSession',
        function ($rootScope, $state, appSession) {
            var ctrl = this;

        }
    ]);
})();


text:
package com.bgstation0.android.sample.accountmanager_;

import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // button1'̎擾.
        Button button1 = (Button)findViewById(R.id.button1);	// button1'ðŽæ"¾.
        button1.setOnClickListener(this);	// ƒŠƒXƒi['Éthis'ðƒZƒbƒg.

    }

    // ƒNƒŠƒbƒN'³'ꂽŽž.
 	@Override
 	public void onClick(View v) {	// onClick'Ì'è‹`(ƒI[ƒo[ƒ‰ƒCƒh)
 		// TODO Auto-generated method stub
 		AccountManager accountManager = AccountManager.get(this);	// accountManagerŽæ"¾.
 		Intent intent = accountManager.newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null, null, null, null);	// ƒAƒJƒEƒ"ƒg'I'ðƒ_ƒCƒAƒƒO'̃Cƒ"ƒeƒ"ƒgŽæ"¾.
 		startActivityForResult(intent, 101);	// intent'ð‹N"®.
 	}

 	// ƒAƒNƒeƒBƒrƒeƒB'ÌŒ‹‰Ê'ª•Ô'Á'Ä'«'½'Æ'«.
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){

    	// Œ‹‰Ê'ɑ΂·'鏈—.
    	super.onActivityResult(requestCode, resultCode, data);	// 'Ü'¸eƒNƒ‰ƒXonActivityResult

    	// 101'ÅOK'̏ꍇ.
    	if (requestCode == 101 && resultCode == Activity.RESULT_OK){
    		String name = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);	// name'ðŽæ"¾.
    		Toast.makeText(this, "name = " + name, Toast.LENGTH_LONG).show();	// name'ð•\Ž¦.
    	}

    }

}


text:
package org.tweetwallfx.devoxx.api.cfp.client;

import java.util.Collections;
import java.util.List;
import static org.tweetwallfx.util.ToString.createToString;
import static org.tweetwallfx.util.ToString.map;

/**
 * A listing of tracks handled by the REST API.
 */
public class Tracks {

    /**
     * Description of content.
     */
    private String content;

    /**
     * All tracks.
     */
    private List<Track> tracks;

    public String getContent() {
        return content;
    }

    public void setContent(final String content) {
        this.content = content;
    }

    public List<Track> getTracks() {
        return null == tracks
                ? Collections.emptyList()
                : Collections.unmodifiableList(tracks);
    }

    public void setRooms(final List<Track> tracks) {
        setTracks(tracks);
    }

    public void setTracks(final List<Track> tracks) {
        this.tracks = tracks;
    }

    @Override
    public String toString() {
        return createToString(this, map(
                "content", getContent(),
                "tracks", getTracks()
        )) + " extends " + super.toString();
    }
}


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/login/login_utils.h"

#include <algorithm>
#include <set>
#include <vector>

#include "base/base_paths.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/location.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/singleton.h"
#include "base/memory/weak_ptr.h"
#include "base/prefs/pref_member.h"
#include "base/prefs/pref_service.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/synchronization/lock.h"
#include "base/sys_info.h"
#include "base/task_runner_util.h"
#include "base/threading/worker_pool.h"
#include "base/time/time.h"
#include "chrome/browser/about_flags.h"
#include "chrome/browser/app_mode/app_mode_utils.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_shutdown.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/chromeos/boot_times_loader.h"
#include "chrome/browser/chromeos/login/auth/chrome_cryptohome_authenticator.h"
#include "chrome/browser/chromeos/login/chrome_restart_request.h"
#include "chrome/browser/chromeos/login/demo_mode/demo_app_launcher.h"
#include "chrome/browser/chromeos/login/existing_user_controller.h"
#include "chrome/browser/chromeos/login/lock/screen_locker.h"
#include "chrome/browser/chromeos/login/profile_auth_data.h"
#include "chrome/browser/chromeos/login/saml/saml_offline_signin_limiter.h"
#include "chrome/browser/chromeos/login/saml/saml_offline_signin_limiter_factory.h"
#include "chrome/browser/chromeos/login/session/user_session_manager.h"
#include "chrome/browser/chromeos/login/signin/oauth2_login_manager.h"
#include "chrome/browser/chromeos/login/signin/oauth2_login_manager_factory.h"
#include "chrome/browser/chromeos/login/startup_utils.h"
#include "chrome/browser/chromeos/login/ui/input_events_blocker.h"
#include "chrome/browser/chromeos/login/ui/login_display_host.h"
#include "chrome/browser/chromeos/login/user_flow.h"
#include "chrome/browser/chromeos/login/users/chrome_user_manager.h"
#include "chrome/browser/chromeos/login/users/supervised_user_manager.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/first_run/first_run.h"
#include "chrome/browser/google/google_brand_chromeos.h"
#include "chrome/browser/lifetime/application_lifetime.h"
#include "chrome/browser/pref_service_flags_storage.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/rlz/rlz.h"
#include "chrome/browser/signin/signin_manager_factory.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/profile_sync_service_factory.h"
#include "chrome/browser/ui/app_list/start_page_service.h"
#include "chrome/browser/ui/startup/startup_browser_creator.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/logging_chrome.h"
#include "chrome/common/pref_names.h"
#include "chromeos/chromeos_switches.h"
#include "chromeos/cryptohome/cryptohome_util.h"
#include "chromeos/dbus/cryptohome_client.h"
#include "chromeos/dbus/dbus_method_call_status.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/session_manager_client.h"
#include "chromeos/login/auth/user_context.h"
#include "chromeos/login/user_names.h"
#include "chromeos/settings/cros_settings_names.h"
#include "components/signin/core/browser/signin_manager.h"
#include "components/user_manager/user.h"
#include "components/user_manager/user_manager.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_service.h"
#include "google_apis/gaia/gaia_auth_consumer.h"
#include "net/base/network_change_notifier.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
#include "url/gurl.h"

#if defined(USE_ATHENA)
#include "athena/extensions/public/extensions_delegate.h"
#include "athena/main/public/athena_launcher.h"
#endif

using content::BrowserThread;

namespace {

void LogCustomSwitches(const std::set<std::string>& switches) {
  if (!VLOG_IS_ON(1))
    return;
  for (std::set<std::string>::const_iterator it = switches.begin();
       it != switches.end();
       ++it) {
    VLOG(1) << "Switch leading to restart: '" << *it << "'";
  }
}

}  // anonymous namespace

namespace chromeos {

namespace {

// Returns new CommandLine with per-user flags.
CommandLine CreatePerSessionCommandLine(Profile* profile) {
  CommandLine user_flags(CommandLine::NO_PROGRAM);
  about_flags::PrefServiceFlagsStorage flags_storage_(profile->GetPrefs());
  about_flags::ConvertFlagsToSwitches(
      &flags_storage_, &user_flags, about_flags::kAddSentinels);
  return user_flags;
}

// Returns true if restart is needed to apply per-session flags.
bool NeedRestartToApplyPerSessionFlags(
    const CommandLine& user_flags,
    std::set<CommandLine::StringType>* out_command_line_difference) {
  // Don't restart browser if it is not first profile in session.
  if (user_manager::UserManager::Get()->GetLoggedInUsers().size() != 1)
    return false;

  // Only restart if needed and if not going into managed mode.
  if (user_manager::UserManager::Get()->IsLoggedInAsSupervisedUser())
    return false;

  if (about_flags::AreSwitchesIdenticalToCurrentCommandLine(
          user_flags,
          *CommandLine::ForCurrentProcess(),
          out_command_line_difference)) {
    return false;
  }

  return true;
}

bool CanPerformEarlyRestart() {
  // Desktop build is used for development only. Early restart is not supported.
  if (!base::SysInfo::IsRunningOnChromeOS())
    return false;

  if (!ChromeUserManager::Get()->GetCurrentUserFlow()->
          SupportsEarlyRestartToApplyFlags()) {
    return false;
  }

  const ExistingUserController* controller =
      ExistingUserController::current_controller();
  if (!controller)
    return true;

  // Early restart is possible only if OAuth token is up to date.

  if (controller->password_changed())
    return false;

  if (controller->auth_mode() != LoginPerformer::AUTH_MODE_INTERNAL)
    return false;

  // No early restart if Easy unlock key needs to be updated.
  if (UserSessionManager::GetInstance()->NeedsToUpdateEasyUnlockKeys())
    return false;

  return true;
}

}  // namespace

class LoginUtilsImpl : public LoginUtils,
                       public base::SupportsWeakPtr<LoginUtilsImpl>,
                       public UserSessionManagerDelegate {
 public:
  LoginUtilsImpl()
      : delegate_(NULL) {
  }

  virtual ~LoginUtilsImpl() {
  }

  // LoginUtils implementation:
  virtual void RespectLocalePreference(Profile* profile,
                                       const base::Closure& callback) OVERRIDE;
  virtual void DoBrowserLaunch(Profile* profile,
                               LoginDisplayHost* login_host) OVERRIDE;
  virtual void PrepareProfile(
      const UserContext& user_context,
      bool has_auth_cookies,
      bool has_active_session,
      LoginUtils::Delegate* delegate) OVERRIDE;
  virtual void DelegateDeleted(LoginUtils::Delegate* delegate) OVERRIDE;
  virtual void CompleteOffTheRecordLogin(const GURL& start_url) OVERRIDE;
  virtual scoped_refptr<Authenticator> CreateAuthenticator(
      AuthStatusConsumer* consumer) OVERRIDE;
  virtual bool RestartToApplyPerSessionFlagsIfNeed(Profile* profile,
                                                   bool early_restart) OVERRIDE;

  // UserSessionManager::Delegate implementation:
   virtual void OnProfilePrepared(Profile* profile) OVERRIDE;
 #if defined(ENABLE_RLZ)
   virtual void OnRlzInitialized() OVERRIDE;
 #endif

 private:
  void DoBrowserLaunchInternal(Profile* profile,
                               LoginDisplayHost* login_host,
                               bool locale_pref_checked);

  static void RunCallbackOnLocaleLoaded(
      const base::Closure& callback,
      InputEventsBlocker* input_events_blocker,
      const std::string& locale,
      const std::string& loaded_locale,
      const bool success);

  // Attempts restarting the browser process and esures that this does
  // not happen while we are still fetching new OAuth refresh tokens.
  void AttemptRestart(Profile* profile);

  // Has to be scoped_refptr, see comment for CreateAuthenticator(...).
  scoped_refptr<Authenticator> authenticator_;

  // Delegate to be fired when the profile will be prepared.
  LoginUtils::Delegate* delegate_;

  DISALLOW_COPY_AND_ASSIGN(LoginUtilsImpl);
};

class LoginUtilsWrapper {
 public:
  static LoginUtilsWrapper* GetInstance() {
    return Singleton<LoginUtilsWrapper>::get();
  }

  LoginUtils* get() {
    base::AutoLock create(create_lock_);
    if (!ptr_.get())
      reset(new LoginUtilsImpl);
    return ptr_.get();
  }

  void reset(LoginUtils* ptr) {
    ptr_.reset(ptr);
  }

 private:
  friend struct DefaultSingletonTraits<LoginUtilsWrapper>;

  LoginUtilsWrapper() {}

  base::Lock create_lock_;
  scoped_ptr<LoginUtils> ptr_;

  DISALLOW_COPY_AND_ASSIGN(LoginUtilsWrapper);
};

void LoginUtilsImpl::DoBrowserLaunchInternal(Profile* profile,
                                             LoginDisplayHost* login_host,
                                             bool locale_pref_checked) {
  if (browser_shutdown::IsTryingToQuit())
    return;

  if (!locale_pref_checked) {
    RespectLocalePreference(profile,
                            base::Bind(&LoginUtilsImpl::DoBrowserLaunchInternal,
                                       base::Unretained(this),
                                       profile,
                                       login_host,
                                       true /* locale_pref_checked */));
    return;
  }

  if (!ChromeUserManager::Get()->GetCurrentUserFlow()->ShouldLaunchBrowser()) {
    ChromeUserManager::Get()->GetCurrentUserFlow()->LaunchExtraSteps(profile);
    return;
  }

  if (RestartToApplyPerSessionFlagsIfNeed(profile, false))
    return;

  if (login_host) {
    login_host->SetStatusAreaVisible(true);
    login_host->BeforeSessionStart();
  }

  BootTimesLoader::Get()->AddLoginTimeMarker("BrowserLaunched", false);

  VLOG(1) << "Launching browser...";
  TRACE_EVENT0("login", "LaunchBrowser");

#if defined(USE_ATHENA)
  athena::ExtensionsDelegate::CreateExtensionsDelegateForChrome(profile);
  athena::StartAthenaSessionWithContext(profile);
#else
  StartupBrowserCreator browser_creator;
  int return_code;
  chrome::startup::IsFirstRun first_run = first_run::IsChromeFirstRun() ?
      chrome::startup::IS_FIRST_RUN : chrome::startup::IS_NOT_FIRST_RUN;

  browser_creator.LaunchBrowser(*CommandLine::ForCurrentProcess(),
                                profile,
                                base::FilePath(),
                                chrome::startup::IS_PROCESS_STARTUP,
                                first_run,
                                &return_code);

  // Triggers app launcher start page service to load start page web contents.
  app_list::StartPageService::Get(profile);
#endif

  // Mark login host for deletion after browser starts.  This
  // guarantees that the message loop will be referenced by the
  // browser before it is dereferenced by the login host.
  if (login_host)
    login_host->Finalize();
  user_manager::UserManager::Get()->SessionStarted();
  chromeos::BootTimesLoader::Get()->LoginDone(
      user_manager::UserManager::Get()->IsCurrentUserNew());
}

// static
void LoginUtilsImpl::RunCallbackOnLocaleLoaded(
    const base::Closure& callback,
    InputEventsBlocker* /* input_events_blocker */,
    const std::string& /* locale */,
    const std::string& /* loaded_locale */,
    const bool /* success */) {
  callback.Run();
}

void LoginUtilsImpl::RespectLocalePreference(Profile* profile,
                                             const base::Closure& callback) {
  if (browser_shutdown::IsTryingToQuit())
    return;

  user_manager::User* const user =
      ProfileHelper::Get()->GetUserByProfile(profile);
  scoped_ptr<locale_util::SwitchLanguageCallback> locale_switched_callback(
      new locale_util::SwitchLanguageCallback(base::Bind(
              &LoginUtilsImpl::RunCallbackOnLocaleLoaded,
              callback,
              base::Owned(new InputEventsBlocker))));  // Block UI events until
                                                       // the ResourceBundle is
                                                       // reloaded.
  if (!UserSessionManager::GetInstance()->RespectLocalePreference(
          profile,
          user,
          locale_switched_callback.Pass())) {
    callback.Run();
  }
}

void LoginUtilsImpl::DoBrowserLaunch(Profile* profile,
                                     LoginDisplayHost* login_host) {
  DoBrowserLaunchInternal(profile, login_host, false /* locale_pref_checked */);
}

void LoginUtilsImpl::PrepareProfile(
    const UserContext& user_context,
    bool has_auth_cookies,
    bool has_active_session,
    LoginUtils::Delegate* delegate) {
  // TODO(nkostylev): We have to initialize LoginUtils delegate as long
  // as it coexist with SessionManager.
  delegate_ = delegate;

  // For the transition part LoginUtils will just delegate profile
  // creation and initialization to SessionManager. Later LoginUtils will be
  // removed and all LoginUtils clients will just work with SessionManager
  // directly.
  UserSessionManager::GetInstance()->StartSession(
      user_context, authenticator_, has_auth_cookies, has_active_session, this);
}

void LoginUtilsImpl::DelegateDeleted(LoginUtils::Delegate* delegate) {
  if (delegate_ == delegate)
    delegate_ = NULL;
}

bool LoginUtilsImpl::RestartToApplyPerSessionFlagsIfNeed(Profile* profile,
                                                         bool early_restart) {
  if (ProfileHelper::IsSigninProfile(profile))
    return false;

  if (early_restart && !CanPerformEarlyRestart())
    return false;

  const CommandLine user_flags(CreatePerSessionCommandLine(profile));
  std::set<CommandLine::StringType> command_line_difference;
  if (!NeedRestartToApplyPerSessionFlags(user_flags, &command_line_difference))
    return false;

  LogCustomSwitches(command_line_difference);

  about_flags::ReportCustomFlags("Login.CustomFlags", command_line_difference);

  CommandLine::StringVector flags;
  // argv[0] is the program name |CommandLine::NO_PROGRAM|.
  flags.assign(user_flags.argv().begin() + 1, user_flags.argv().end());
  LOG(WARNING) << "Restarting to apply per-session flags...";
  DBusThreadManager::Get()->GetSessionManagerClient()->SetFlagsForUser(
      user_manager::UserManager::Get()->GetActiveUser()->email(), flags);
  AttemptRestart(profile);
  return true;
}

void LoginUtilsImpl::CompleteOffTheRecordLogin(const GURL& start_url) {
  VLOG(1) << "Completing incognito login";

  // For guest session we ask session manager to restart Chrome with --bwsi
  // flag. We keep only some of the arguments of this process.
  const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
  CommandLine command_line(browser_command_line.GetProgram());
  std::string cmd_line_str =
      GetOffTheRecordCommandLine(start_url,
                                 StartupUtils::IsOobeCompleted(),
                                 browser_command_line,
                                 &command_line);

  // This makes sure that Chrome restarts with no per-session flags. The guest
  // profile will always have empty set of per-session flags. If this is not
  // done and device owner has some per-session flags, when Chrome is relaunched
  // the guest profile session flags will not match the current command line and
  // another restart will be attempted in order to reset the user flags for the
  // guest user.
  const CommandLine user_flags(CommandLine::NO_PROGRAM);
  if (!about_flags::AreSwitchesIdenticalToCurrentCommandLine(
           user_flags,
           *CommandLine::ForCurrentProcess(),
           NULL)) {
    DBusThreadManager::Get()->GetSessionManagerClient()->SetFlagsForUser(
        chromeos::login::kGuestUserName,
        CommandLine::StringVector());
  }

  RestartChrome(cmd_line_str);
}

scoped_refptr<Authenticator> LoginUtilsImpl::CreateAuthenticator(
    AuthStatusConsumer* consumer) {
  // Screen locker needs new Authenticator instance each time.
  if (ScreenLocker::default_screen_locker()) {
    if (authenticator_.get())
      authenticator_->SetConsumer(NULL);
    authenticator_ = NULL;
  }

  if (authenticator_.get() == NULL) {
    authenticator_ = new ChromeCryptohomeAuthenticator(consumer);
  } else {
    // TODO(nkostylev): Fix this hack by improving Authenticator dependencies.
    authenticator_->SetConsumer(consumer);
  }
  return authenticator_;
}

void LoginUtilsImpl::OnProfilePrepared(Profile* profile) {
  if (delegate_)
    delegate_->OnProfilePrepared(profile);
}

#if defined(ENABLE_RLZ)
void LoginUtilsImpl::OnRlzInitialized() {
  if (delegate_)
    delegate_->OnRlzInitialized();
}
#endif

void LoginUtilsImpl::AttemptRestart(Profile* profile) {
  if (UserSessionManager::GetInstance()
          ->CheckEasyUnlockKeyOps(
              base::Bind(&LoginUtilsImpl::AttemptRestart,
                         base::Unretained(this),
                         profile))) {
    return;
  }

  if (UserSessionManager::GetInstance()->GetSigninSessionRestoreStrategy() !=
      OAuth2LoginManager::RESTORE_FROM_COOKIE_JAR) {
    chrome::AttemptRestart();
    return;
  }

  // We can't really quit if the session restore process that mints new
  // refresh token is still in progress.
  OAuth2LoginManager* login_manager =
      OAuth2LoginManagerFactory::GetInstance()->GetForProfile(profile);
  if (login_manager->state() !=
          OAuth2LoginManager::SESSION_RESTORE_PREPARING &&
      login_manager->state() !=
          OAuth2LoginManager::SESSION_RESTORE_IN_PROGRESS) {
    chrome::AttemptRestart();
    return;
  }

  LOG(WARNING) << "Attempting browser restart during session restore.";
  UserSessionManager::GetInstance()->set_exit_after_session_restore(true);
}

// static
LoginUtils* LoginUtils::Get() {
  return LoginUtilsWrapper::GetInstance()->get();
}

// static
void LoginUtils::Set(LoginUtils* mock) {
  LoginUtilsWrapper::GetInstance()->reset(mock);
}

// static
bool LoginUtils::IsWhitelisted(const std::string& username,
                               bool* wildcard_match) {
  // Skip whitelist check for tests.
  if (CommandLine::ForCurrentProcess()->HasSwitch(
      chromeos::switches::kOobeSkipPostLogin)) {
    return true;
  }

  CrosSettings* cros_settings = CrosSettings::Get();
  bool allow_new_user = false;
  cros_settings->GetBoolean(kAccountsPrefAllowNewUser, &allow_new_user);
  if (allow_new_user)
    return true;
  return cros_settings->FindEmailInList(
      kAccountsPrefUsers, username, wildcard_match);
}

}  // namespace chromeos


text:
import MapObject from '../map-object/constructor';

export default class Channels extends MapObject {
}


text:
"""empty message

Revision ID: df62be078722
Revises: 30ca04771e1d
Create Date: 2016-08-09 13:10:19.435723

"""

# revision identifiers, used by Alembic.
revision = 'df62be078722'
down_revision = '30ca04771e1d'

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(u'density_product_id_fkey', 'density', type_='foreignkey')
    op.create_foreign_key(None, 'density', 'product', ['product_id'], ['id'], ondelete='CASCADE')
    op.drop_constraint(u'edb_product_id_fkey', 'edb_product', type_='foreignkey')
    op.create_foreign_key(None, 'edb_product', 'product', ['id'], ['id'])
    op.drop_constraint(u'prod_allergene_association_product_id_fkey', 'prod_allergene_association', type_='foreignkey')
    op.drop_constraint(u'prod_allergene_association_allergene_id_fkey', 'prod_allergene_association', type_='foreignkey')
    op.create_foreign_key(None, 'prod_allergene_association', 'allergene', ['allergene_id'], ['id'], ondelete='CASCADE')
    op.create_foreign_key(None, 'prod_allergene_association', 'product', ['product_id'], ['id'], ondelete='CASCADE')
    op.drop_constraint(u'prod_nutrient_association_nutrient_id_fkey', 'prod_nutrient_association', type_='foreignkey')
    op.drop_constraint(u'prod_nutrient_association_product_id_fkey', 'prod_nutrient_association', type_='foreignkey')
    op.create_foreign_key(None, 'prod_nutrient_association', 'product', ['product_id'], ['id'], ondelete='CASCADE')
    op.create_foreign_key(None, 'prod_nutrient_association', 'nutrient', ['nutrient_id'], ['id'], ondelete='CASCADE')
    op.drop_constraint(u'prod_process_association_nutrient_id_fkey', 'prod_process_association', type_='foreignkey')
    op.drop_constraint(u'prod_process_association_process_id_fkey', 'prod_process_association', type_='foreignkey')
    op.create_foreign_key(None, 'prod_process_association', 'process', ['process_id'], ['id'], ondelete='CASCADE')
    op.create_foreign_key(None, 'prod_process_association', 'nutrient', ['nutrient_id'], ['id'], ondelete='CASCADE')
    op.drop_constraint(u'prod_process_co2_association_product_id_fkey', 'prod_process_co2_association', type_='foreignkey')
    op.drop_constraint(u'prod_process_co2_association_process_id_fkey', 'prod_process_co2_association', type_='foreignkey')
    op.create_foreign_key(None, 'prod_process_co2_association', 'process', ['process_id'], ['id'], ondelete='CASCADE')
    op.create_foreign_key(None, 'prod_process_co2_association', 'product', ['product_id'], ['id'], ondelete='CASCADE')
    op.drop_constraint(u'synonym_prod_association_product_id_fkey', 'synonym_prod_association', type_='foreignkey')
    op.drop_constraint(u'synonym_prod_association_synonym_name_fkey', 'synonym_prod_association', type_='foreignkey')
    op.create_foreign_key(None, 'synonym_prod_association', 'synonym', ['synonym_name'], ['name'], ondelete='CASCADE')
    op.create_foreign_key(None, 'synonym_prod_association', 'product', ['product_id'], ['id'], ondelete='CASCADE')
    op.drop_constraint(u'template_id_fkey', 'template', type_='foreignkey')
    op.create_foreign_key(None, 'template', 'product', ['id'], ['id'])
    op.drop_constraint(u'unit_weight_product_id_fkey', 'unit_weight', type_='foreignkey')
    op.create_foreign_key(None, 'unit_weight', 'product', ['product_id'], ['id'], ondelete='CASCADE')
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(None, 'unit_weight', type_='foreignkey')
    op.create_foreign_key(u'unit_weight_product_id_fkey', 'unit_weight', 'product', ['product_id'], ['id'])
    op.drop_constraint(None, 'template', type_='foreignkey')
    op.create_foreign_key(u'template_id_fkey', 'template', 'product', ['id'], ['id'], ondelete=u'CASCADE')
    op.drop_constraint(None, 'synonym_prod_association', type_='foreignkey')
    op.drop_constraint(None, 'synonym_prod_association', type_='foreignkey')
    op.create_foreign_key(u'synonym_prod_association_synonym_name_fkey', 'synonym_prod_association', 'synonym', ['synonym_name'], ['name'])
    op.create_foreign_key(u'synonym_prod_association_product_id_fkey', 'synonym_prod_association', 'product', ['product_id'], ['id'])
    op.drop_constraint(None, 'prod_process_co2_association', type_='foreignkey')
    op.drop_constraint(None, 'prod_process_co2_association', type_='foreignkey')
    op.create_foreign_key(u'prod_process_co2_association_process_id_fkey', 'prod_process_co2_association', 'process', ['process_id'], ['id'])
    op.create_foreign_key(u'prod_process_co2_association_product_id_fkey', 'prod_process_co2_association', 'product', ['product_id'], ['id'])
    op.drop_constraint(None, 'prod_process_association', type_='foreignkey')
    op.drop_constraint(None, 'prod_process_association', type_='foreignkey')
    op.create_foreign_key(u'prod_process_association_process_id_fkey', 'prod_process_association', 'process', ['process_id'], ['id'])
    op.create_foreign_key(u'prod_process_association_nutrient_id_fkey', 'prod_process_association', 'nutrient', ['nutrient_id'], ['id'])
    op.drop_constraint(None, 'prod_nutrient_association', type_='foreignkey')
    op.drop_constraint(None, 'prod_nutrient_association', type_='foreignkey')
    op.create_foreign_key(u'prod_nutrient_association_product_id_fkey', 'prod_nutrient_association', 'product', ['product_id'], ['id'])
    op.create_foreign_key(u'prod_nutrient_association_nutrient_id_fkey', 'prod_nutrient_association', 'nutrient', ['nutrient_id'], ['id'])
    op.drop_constraint(None, 'prod_allergene_association', type_='foreignkey')
    op.drop_constraint(None, 'prod_allergene_association', type_='foreignkey')
    op.create_foreign_key(u'prod_allergene_association_allergene_id_fkey', 'prod_allergene_association', 'allergene', ['allergene_id'], ['id'])
    op.create_foreign_key(u'prod_allergene_association_product_id_fkey', 'prod_allergene_association', 'product', ['product_id'], ['id'])
    op.drop_constraint(None, 'edb_product', type_='foreignkey')
    op.create_foreign_key(u'edb_product_id_fkey', 'edb_product', 'product', ['id'], ['id'], ondelete=u'CASCADE')
    op.drop_constraint(None, 'density', type_='foreignkey')
    op.create_foreign_key(u'density_product_id_fkey', 'density', 'product', ['product_id'], ['id'])
    ### end Alembic commands ###


text:
#include <aws/ssm-contacts/model/ListContactsResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::SSMContacts::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

ListContactsResult::ListContactsResult()
{
}

ListContactsResult::ListContactsResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

ListContactsResult& ListContactsResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  JsonView jsonValue = result.GetPayload().View();
  if(jsonValue.ValueExists("NextToken"))
  {
    m_nextToken = jsonValue.GetString("NextToken");

  }

  if(jsonValue.ValueExists("Contacts"))
  {
    Aws::Utils::Array<JsonView> contactsJsonList = jsonValue.GetArray("Contacts");
    for(unsigned contactsIndex = 0; contactsIndex < contactsJsonList.GetLength(); ++contactsIndex)
    {
      m_contacts.push_back(contactsJsonList[contactsIndex].AsObject());
    }
  }

  return *this;
}


text:
import pkg_resources

__version__ = pkg_resources.resource_string("dglke", "VERSION.txt").decode("utf-8").strip()