text:
<!--- Copyright (C) Lightbend Inc. <https://www.lightbend.com> -->
# Writing functional tests

Play provides a number of classes and convenience methods that assist with functional testing. Most of these can be found either in the [`play.test`](api/java/play/test/package-summary.html) package or in the [`Helpers`](api/java/play/test/Helpers.html) class.

You can add these methods and classes by importing the following:

@[test-imports](code/javaguide/tests/FakeApplicationTest.java)

## Creating `Application` instances for testing

Play frequently requires a running [`Application`](api/java/play/Application.html) as context. To provide an environment for tests, Play provides helpers that produce new application instances for testing:

```java
import static play.test.Helpers.*;
```

@[test-fakeapp](code/javaguide/tests/FakeApplicationTest.java)

## Injecting tests

If you're using Guice for [[dependency injection|JavaDependencyInjection]] then an `Application` for testing can be [[built directly|JavaTestingWithGuice]]. You can also inject any members of a test class that you might need. It's generally best practice to inject members only in functional tests and to manually create instances in unit tests.

@[test-injection](code/javaguide/tests/InjectionTest.java)

## Testing with an application

To run tests with an `Application`, you can do the following:

@[test-running-fakeapp](code/javaguide/tests/FakeApplicationTest.java)

You can also extend [`WithApplication`](api/java/play/test/WithApplication.html), this will automatically ensure that an application is started and stopped for each test method:

@[test-withapp](code/javaguide/tests/FunctionalTest.java)

## Testing with a Guice application

To run tests with an `Application` [[created by Guice|JavaTestingWithGuice]], you can do the following:

@[test-guiceapp](code/tests/guice/JavaGuiceApplicationBuilderTest.java)

Note that there are different ways to customize the `Application` creation when using Guice to test.

## Testing a Controller Action through Routing

With a running application, you can retrieve an action reference from the path for a route and invoke it. This also allows you to use `RequestBuilder` which creates a fake request:

@[bad-route-import](code/javaguide/tests/FunctionalTest.java)

@[bad-route](code/javaguide/tests/FunctionalTest.java)

It is also possible to create the `RequestBuilder` using the reverse router directly and avoid hard-coding the router path:

@[good-route](code/javaguide/tests/FunctionalTest.java)

> **Note:** the reverse router is not executing the action, but instead only providing a `Call` with information that will be used to create the `RequestBuilder` and later invoke the the action itself using `Helpers.route(Application, RequestBuilder)`. That is why it is not necessary to pass a `Http.Request` when using the reverse router to create the `Http.RequestBuilder` in tests even if the action is receiving a `Http.Request` as a parameter.

## Testing with a server

Sometimes you want to test the real HTTP stack from within your test. You can do this by starting a test server:

@[test-server](code/javaguide/tests/FunctionalTest.java)

Just as there exists a `WithApplication` class, there is also a [`WithServer`](api/java/play/test/WithServer.html) which you can extend to automatically start and stop a [`TestServer`](api/java/play/test/TestServer.html) for your tests:

@[test-withserver](code/javaguide/tests/ServerFunctionalTest.java)

## Testing with a browser

If you want to test your application from with a Web browser, you can use [Selenium WebDriver](https://github.com/seleniumhq/selenium). Play will start the WebDriver for you, and wrap it in the convenient API provided by [FluentLenium](https://github.com/FluentLenium/FluentLenium).

@[test-browser](code/javaguide/tests/FunctionalTest.java)

And, of course there, is the [`WithBrowser`](api/java/play/test/WithBrowser.html) class to automatically open and close a browser for each test:

@[test-withbrowser](code/javaguide/tests/BrowserFunctionalTest.java)


text:
package org.swingeasy.formatters;

import java.text.ParseException;
import java.util.StringTokenizer;

import javax.swing.text.DefaultFormatter;

/**
 * A formatter for 4-byte IP addresses of the form a.b.c.d
 *
 * @see http://www.java2s.com/Code/Java/Swing-JFC/Acollectionofformattedtextfieldsandabuttonthatdisplaysthefieldvalues.htm
 */
public class IPAddressFormatter extends DefaultFormatter {
    private static final long serialVersionUID = -5848169520434688494L;

    protected final int length;

    public IPAddressFormatter() {
        this(4);
    }

    public IPAddressFormatter(boolean expanded) {
        this(6);
    }

    protected IPAddressFormatter(int l) {
        length = l;
    }

    /**
     * @see javax.swing.text.DefaultFormatter#stringToValue(java.lang.String)
     */
    @Override
    public Object stringToValue(String text) throws ParseException {
        StringTokenizer tokenizer = new StringTokenizer(text, ".");
        byte[] a = new byte[length];
        for (int i = 0; i < length; i++) {
            int b = 0;
            if (!tokenizer.hasMoreTokens()) {
                throw new ParseException("Too few bytes", 0);
            }
            try {
                b = Integer.parseInt(tokenizer.nextToken());
            } catch (NumberFormatException e) {
                throw new ParseException("Not an integer", 0);
            }
            if (b < 0 || b >= 256) {
                throw new ParseException("Byte out of range", 0);
            }
            a[i] = (byte) b;
        }
        if (tokenizer.hasMoreTokens()) {
            throw new ParseException("Too many bytes", 0);
        }
        return a;
    }

    /**
     * @see javax.swing.text.DefaultFormatter#valueToString(java.lang.Object)
     */
    @Override
    public String valueToString(Object value) throws ParseException {
        if (!(value instanceof byte[])) {
            throw new ParseException("Not a byte[]", 0);
        }
        byte[] a = (byte[]) value;
        if (a.length != length) {
            throw new ParseException("Length != " + length, 0);
        }
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int b = a[i];
            if (b < 0) {
                b += 256;
            }
            builder.append(String.valueOf(b));
            if (i + 1 < length) {
                builder.append('.');
            }
        }
        return builder.toString();
    }
}

redpajama_set_name: RedPajamaGithub


text:
(function(){

module.exports = function (modulus) {
  var help = new modulus.help('Project', modulus);

  // list commands
  help.add('list', function () {
    this.line('project list (list)'.verbose);
    this.line('View all projects you have.'.input);
  });

  modulus.program
    .command('project list')
    .description('Lists all projects you currently have access to.')
    .on('--help', help.commands.list)
    .action(function () {
      modulus.runCommand(modulus.commands.project.list, true);
    });

  modulus.program
    .command('list')
    .description('Lists all projects you currently have access to.')
    .on('--help', help.commands.list)
    .action(function () {
      modulus.runCommand(modulus.commands.project.list, true);
    });

  // create command
  help.add('create', function () {
    this.line('project create <name>'.verbose);
    this.line('Creates a new project.'.input);
    this.line('A prompt for name will occur if none is specified.'.input);
    this.line('  options:'.input);
    this.line('    -s, --servo-size    Servo size for the new project [192, 396, 512, 1024, 2048].'.input);
    this.line('    -r, --runtime       Runtime for the new project [Node.js, PHP, Java, Static].'.input);
  });

  modulus.program.option(
    '-s, --servo-size [value]',
    'Servo size for the new project [192, 396, 512, 1024, 2048]');

  modulus.program.option(
    '-r, --runtime [value]',
    'Runtime for the new project [Node.js, PHP, Java, Static]');

  modulus.program
    .command('project create')
    .description('Creates a new project.')
    .on('--help', help.commands.create)
    .action(function (name) {
      if (typeof name !== 'string') {
        name = '';
      }
      modulus.runCommand(
        modulus.commands.project.create,
        [name, modulus.program.servoSize, modulus.program.runtime],
        true);
    });

  // delete command
  help.add('delete', function () {
    this.line('project delete'.verbose);
    this.line('Deletes a project.'.input);
    this.line('A prompt for name will occur if none is specified.'.input);
    this.line('  options:'.input);
    this.line('    -p, --project-name    Name of the project to restart. Prompts are skipped when specified.'.input);
  });

  modulus.program
    .command('project delete')
    .description('Deletes a project')
    .on('--help', help.commands.delete)
    .action(function() {
      modulus.runCommand(modulus.commands.project.delete, [modulus.program.projectName], true);
    });

  // restart command
  help.add('restart', function () {
    this.line('project restart'.verbose);
    this.line('Restarts a project.'.input);
    this.line('  options:'.input);
    this.line('    -p, --project-name    Name of the project to restart. Prompts are skipped when specified.'.input);
  });

  modulus.program
    .command('project restart')
    .description('Restarts a running project.')
    .on('--help', help.commands.restart)
    .action(function () {
      modulus.runCommand(modulus.commands.project.restart, [modulus.program.projectName], true);
    });

  // stop command
  help.add('stop', function () {
    this.line('project stop'.verbose);
    this.line('Stops a running project'.input);
    this.line('  options:'.input);
    this.line('    -p, --project-name    Name of the project to stop. Prompts are skipped when specified.'.input);
  });

  modulus.program
    .command('project stop')
    .description('Stops a running project.')
    .on('--help', help.commands.stop)
    .action(function () {
      modulus.runCommand(modulus.commands.project.stop, [modulus.program.projectName], true);
    });

  // start command
  help.add('start', function () {
    this.line('project start'.verbose);
    this.line('Starts a project'.input);
    this.line('  options:'.input);
    this.line('    -p, --project-name    Name of the project to start. Prompts are skipped when specified.'.input);
  });

  modulus.program
    .command('project start')
    .description('Starts a stopped project.')
    .on('--help', help.commands.start)
    .action(function () {
      modulus.runCommand(modulus.commands.project.start, [modulus.program.projectName], true);
    });

  // deploy command
  help.add('deploy', function () {
    this.line('project deploy (deploy) [options] <directory>'.verbose);
    this.line('Deploys a directory\'s contents to the selected project.'.input);
    this.line('The current working directory is used if no directory is specified.'.input);
    this.line('By default a project type will be detected and any additional actions required will be taken.'.input);
    this.line('  options:'.input);
    this.line('    -p, --project-name      Name of the project to deploy. Prompts are skipped when specified.'.input);
    this.line('    -m, --include-modules   Flag that indicates whether or not to include the node_modules folder in the bundle.'.input);
    this.line('    -r, --registry          Specify a registry to install modules from.'.input);
    this.line('    -w, --with-tests        Specifies that tests should be run before deploying this project.'.input);
    this.line('    -D, --meteor-debug      Override debug mode for meteor project.'.input);
  });

  modulus.program
    .option('-p, --project-name [value]', 'Name of the project to retrieve logs from. Prompts are skipped when specified', null)
    .option('-d, --download', 'Flag that signals to download the logs instead of printing them.')
    .option('-o, --output [value]', 'Specifies the file to download to. Must be file type tar.gz')
    .option('-m, --include-modules', 'Flag that indicates whether or not to include the node_modules folder in the bundle.')
    .option('-r, --registry [value]', 'Specify a registry to install modules from', '')
    .option('-w, --with-tests', 'Specifies that tests should be run before deploying this project.')
    .option('-D, --meteor-debug', 'Override debug mode for meteor projects.');

  modulus.program
    .command('project deploy')
    .description('Deploys the current directory to selected project.')
    .on('--help', help.commands.deploy)
    .action(function (dir) {
      modulus.runCommand(
        modulus.commands.project.deploy,
        [
          modulus.program.projectName,
          dir,
          modulus.program.includeModules,
          modulus.program.registry,
          modulus.program.meteorDebug,
          modulus.program.withTests
        ],
        true);
    });

  modulus.program
    .command('deploy')
    .description('Deploys the current directory to selected project.')
    .on('--help', help.commands.deploy)
    .action(function (dir) {
      modulus.runCommand(
        modulus.commands.project.deploy,
        [
          modulus.program.projectName,
          dir,
          modulus.program.includeModules,
          modulus.program.registry,
          modulus.program.meteorDebug,
          modulus.program.withTests
        ],
        true);
    });

  // logs command
  help.add('logs', function () {
    this.line('project logs'.verbose);
    this.line('Gets logs for the selected project.'.input);
    this.line('  options:'.input);
    this.line('    -p, --project-name   Name of the project to retrieve logs from. Prompts are skipped when specified.'.input);
    this.line('    -d, --download       Flag that signals to download the logs instead of printing them.'.input);
    this.line('    -o, --output         Specifies the file to download to. Must be file type tar.gz'.input);
    this.line('');
  });

  // help for logs clear command
  help.add('logClear', function () {
    this.line('project logs clear'.verbose);
    this.line('Cleans logs for the selected project.'.input);
  });

  var logsHandler = function (dir) {
    modulus.runCommand(
      modulus.commands.project.getLogs,
      [
        modulus.program.projectName,
        modulus.program.download,
        modulus.program.output,
        dir
      ],
      true);
  };

  modulus.program
    .command('project logs')
    .description('Gets logs for the selected project.')
    .on('--help', function () {
      help.commands.logs();
      help.commands.logClear();
    })
    .action(logsHandler);

  // project logs -> project log alias
  modulus.program
    .command('project log')
    .description('Gets logs for the selected project.')
    .on('--help', function () {
      help.commands.logs();
      help.commands.logClear();
    })
    .action(logsHandler);

  // project logs -> logs alias
  modulus.program
    .command('logs')
    .description('Gets logs for the selected project.')
    .on('--help', function () {
      help.commands.logs();
      help.commands.logClear();
    })
    .action(logsHandler);

  // log clear command
  modulus.program
    .command('project logs clear')
    .description('Clears logs for the selected project.')
    .on('--help', help.commands.logClear)
    .action(function () {
      modulus.runCommand(modulus.commands.project.clearLogs, [modulus.program.projectName], true);
    });

  // project logs clear -> logs clear alias
  modulus.program
    .command('logs clear')
    .description('Clears logs for the selected project.')
    .on('--help', help.commands.logClear)
    .action(function () {
      modulus.runCommand(modulus.commands.project.clearLogs, [modulus.program.projectName], true);
    });

  // log stream command
  help.add('logStream', function () {
    this.line('project logs tail'.verbose);
    this.line('Streams logs for the selected project.'.input);
    this.line('  options:'.input);
    this.line('    -S, --servo    Index of a specific servo to tail. Prompts are skipped when specified.'.input);
  });

  modulus.program
    .option('-S, --servo [value]', 'Index of a specific servo to tail. Prompts are skipped when specified.');

  modulus.program
    .command('project logs tail')
    .description('Streams logs for the selected project.')
    .on('--help', help.commands.logStream)
    .action(function () {
      modulus.runCommand(modulus.commands.project.streamLogs, [modulus.program.projectName, modulus.program.servo], true);
    });

  // project logs tail -> logs tail alias
  modulus.program
    .command('logs tail')
    .description('Streams logs for the selected project.')
    .on('--help', help.commands.logStream)
    .action(function () {
      modulus.runCommand(modulus.commands.project.streamLogs, [modulus.program.projectName, modulus.program.servo], true);
    });

  // scale command
  help.add('scale', function () {
    this.line('project scale <servos>'.verbose);
    this.line('Scales a project to use the number of servos given.'.input);
    this.line('    -p, --project-name   Name of the project to scale. Prompts are skipped when specified.'.input);
  });

  modulus.program
    .option('-p, --project-name [value]', 'Name of the project to scale. Prompts are skipped when specified');

  modulus.program
    .command('project scale')
    .description('Scales a project to the number of servos specified.')
    .on('--help', help.commands.scale)
    .action(function () {
      var args = Array.prototype.slice.call(arguments);
      args.pop(); // remove last element, it's always internal commander stuff.
      modulus.runCommand(modulus.commands.project.scale, [args, modulus.program.projectName], true);
    });

  // Generic help for project commands
  modulus.program
    .command('project')
    .description('Lists available project commands.')
    .on('--help', help.getPrinter())
    .action(help.getPrinter());

  return {
    base : 'project',
    help : help
  };
};

})();


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Aspilia paranensis Malme

### Remarks
null


text:
package iso20022

type CancellationStatus4Code string


text:
hook pg_pconnect
--SKIPIF--
<?php
include(__DIR__.'/../skipif.inc');
if (!extension_loaded("pgsql")) die("Skipped: pgsql extension required.");
?>
--INI--
openrasp.root_dir=/tmp/openrasp
openrasp.enforce_policy=On
--FILE--
<?php
pg_pconnect('host=127.0.0.1 port=5432 dbname=test user=postgres');
?>
--EXPECTREGEX--
<\/script><script>location.href="http[s]?:\/\/.*?request_id=[0-9a-f]{32}"<\/script>


text:
module ActiveRecord
  # = Active Record Schema Dumper
  #
  # This class is used to dump the database schema for some connection to some
  # output format (i.e., ActiveRecord::Schema).
  class SchemaDumper #:nodoc:
    private_class_method :new

    # :singleton-method:
    # A list of tables which should not be dumped to the schema.
    # Acceptable values are strings as well as regexp.
    # This setting is only used if ActiveRecord::Base.schema_format == :ruby
    cattr_accessor :ignore_tables
    @@ignore_tables = []

    def self.dump(connection=ActiveRecord::Base.connection, stream=STDOUT, options = {})
      begin
        if options[:schema_search_path]
          current_search_path = ActiveRecord::Base.connection.schema_search_path
          ActiveRecord::Base.connection.schema_search_path = options[:schema_search_path]
        end

        new(connection).dump(stream, options)
      ensure
        ActiveRecord::Base.connection.schema_search_path = current_search_path if current_search_path.present?
      end
      stream
    end

    def dump(stream, options)
      header(stream)
      schemas(stream, options)
      extensions(stream)
      enums(stream)
      domains(stream)
      composite_types(stream)
      functions(stream)
      tables(stream)
      trailer(stream)
      stream
    end

    private

    def initialize(connection)
      @connection = connection
      @types = @connection.native_database_types
      @version = Migrator::current_version rescue nil
      @dumped_tables = []
    end

    def header(stream)
      define_params = @version ? "version: #{@version}" : ""

      if stream.respond_to?(:external_encoding) && stream.external_encoding
        stream.puts "# encoding: #{stream.external_encoding.name}"
      end

      stream.puts <<-HEADER
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.

ActiveRecord::Schema.define(#{define_params}) do

HEADER
    end

    def trailer(stream)
      stream.puts "end"
    end

    def schemas(stream, options)
      search_paths = @connection.schema_search_paths - ['public']
      search_paths -= @connection.schema_search_paths if options[:schema_search_path]
      if search_paths.any?
        stream.puts "  # Create schemas (except public schema) configured in search_path option in database.yml"
        search_paths.each do |schema|
          stream.puts "  create_schema #{schema.inspect}"
        end
        stream.puts
      end
    end

    def extensions(stream)
      return unless @connection.supports_extensions?
      extensions = @connection.extensions_with_namespace
      extensions.select! {|e| @connection.schema_search_paths.include?(e.second) }
      if extensions.any?
        stream.puts "  # These are extensions that must be enabled in order to support this database"
        extensions.each do |extension|
          stream.puts "  enable_extension #{extension.first.inspect}, schema: #{extension.second.inspect}"
        end
        stream.puts
      end
    end

    # Export enums types
    def enums(stream)
      enum_query = <<-SQL
        SELECT pg_type.typname AS enumtype,
            pg_enum.enumlabel AS enumlabel
        FROM pg_type
        JOIN pg_enum
            ON pg_enum.enumtypid = pg_type.oid;
      SQL
      enums = @connection.execute(enum_query, "SCHEMA").group_by{|e| e['enumtype']}.each_with_object({}) do |(k, v), h|
         h[k] = v.map{|g| g['enumlabel']}
      end
      enums.select! {|e| @connection.schema_search_paths.include?(@connection.schema_for_enum(e)) }
      if enums.any?
        stream.puts "  # Create user defined Enum types"
        enums.each do |enum, values|
          schema = @connection.schema_for_enum(enum)
          if @connection.shared_schemas.include?(schema)
            stream.puts "  create_enum :#{enum}, #{values.map(&:to_sym).inspect}, schema: :#{schema}"
          else
            stream.puts "  create_enum :#{enum}, #{values.map(&:to_sym).inspect}"
          end
        end
        stream.puts
      end
    end

    # Domains
    def domains(stream)
      domains = @connection.domains_with_type_and_namespace
      domains.select! {|d| @connection.schema_search_paths.include?(d.first) }
      if domains.any?
        stream.puts "  # These are user defined domains for this application"
        domains.each do |domain|
          stream.puts "  create_domain #{domain.second.inspect}, as: #{domain.third.inspect}, schema: #{domain.first.inspect}"
        end
        stream.puts
      end
    end

    # User defined composite types
    def composite_types(stream)
      composite_types = @connection.composite_types
      composite_types.select! {|c| @connection.schema_search_paths.include?(@connection.schema_for_composite_type(c)) }
      if composite_types.any?
        stream.puts "  # These are user defined composite data types for this application"
        composite_types.each do |composite_type|
          schema = @connection.schema_for_composite_type(composite_type)
          if @connection.shared_schemas.include?(schema)
            stream.puts "  create_composite_type :#{composite_type}, schema: :#{schema} do |t|"
          else
            stream.puts "  create_composite_type :#{composite_type} do |t|"
          end
          column_specs = @connection.columns(composite_type).map do |column|
            @connection.column_spec(column)
          end.compact

          column_specs.each do |s|
            options = s.reject{|k, v| [:name,:type].include? k}.values
            stream.puts "    t.#{s[:type]}\t#{s[:name]}, #{options.join(', ')}"
          end
          stream.puts "  end"
          stream.puts
        end
      end
    end

    def functions(stream)
      funcs = @connection.functions.select {|f| @connection.schema_search_paths.include?(f.values.first[:schema]) }
      if funcs.any?
        stream.puts "  # These are user defined functions for this application"
        funcs.each do |func|
          func.each do |name, definition|
            stream.print "  create_function :#{name}, "
            stream.print "schema: :#{definition[:schema]}, " if definition[:schema]
            stream.print "returns: :#{definition[:returns]}, "
            stream.print "language: :#{definition[:language].downcase}, "
            stream.puts "as: <<-FUNCTION"
            stream.puts "#{definition[:as]}"
            stream.puts "  FUNCTION"
            stream.puts
          end
        end
      end
    end

    def tables(stream)
      @connection.tables.sort.each do |tbl|
        next if ['schema_migrations', 'active_record_internal_metadatas', ignore_tables].flatten.any? do |ignored|
          case ignored
          when String; remove_prefix_and_suffix(tbl) == ignored
          when Regexp; remove_prefix_and_suffix(tbl) =~ ignored
          else
            raise StandardError, 'ActiveRecord::SchemaDumper.ignore_tables accepts an array of String and / or Regexp values.'
          end
        end
        table(tbl, stream)
      end
    end

    # Output table and columns - but don't output columns that are inherited from
    # a parent table.
    #
    # TODO: Qualify with the schema name IF the table is in a schema other than the first
    # schema in the search path (not including the $user schema)
    def table(table, stream)
      return if already_dumped?(table)
      if parent_table = @connection.parent_table(table)
        table(parent_table, stream)
        parent_column_names = @connection.columns(parent_table).map(&:name)
      end
      columns = @connection.columns(table)
      schema = @connection.schema_for_table(table)
      begin
        tbl = StringIO.new

        # first dump primary key column
        if @connection.respond_to?(:pk_and_sequence_for)
          pk, seq = @connection.pk_and_sequence_for(table)
        elsif @connection.respond_to?(:primary_key)
          pk = @connection.primary_key(table)
        end

        tbl.print "  create_table #{remove_prefix_and_suffix(table).inspect}"
        if parent_table
          tbl.print %Q(, inherits: "#{parent_table}")
        else
          if column = columns.detect { |c| c.name == pk }
            if pk != 'id'
              tbl.print %Q(, primary_key: "#{pk}")
            elsif column.sql_type == 'uuid'
              tbl.print ", id: :uuid"
              tbl.print %Q(, default: "#{column.default_function}") if column.default_function
            end
          else
            tbl.print ", id: false"
          end
        end
        if @connection.shared_schemas.include?(schema)
          tbl.print ", schema: #{schema.inspect}"
        else
          tbl.print ", force: true"
        end
        tbl.puts " do |t|"

        # then dump all non-primary key columns that are not inherited from a parent table
        column_specs = columns.map do |column|
          # raise StandardError, "Unknown type '#{column.sql_type}' for column '#{column.name}' with type #{column.type}" if @types[column.type].nil?
          next if column.name == pk
          next if parent_column_names && parent_column_names.include?(column.name)
          @connection.column_spec(column)
        end.compact

        # find all migration keys used in this table
        keys = @connection.migration_keys

        # figure out the lengths for each column based on above keys
        lengths = keys.map { |key|
          column_specs.map { |spec|
            spec[key] ? spec[key].length + 2 : 0
          }.max
        }

        # the string we're going to sprintf our values against, with standardized column widths
        format_string = lengths.map{ |len| "%-#{len}s" }

        # find the max length for the 'type' column, which is special
        type_length = column_specs.map{ |column| column[:type].length }.max

        # add column type definition to our format string
        format_string.unshift "    t.%-#{type_length}s "

        format_string *= ''

        column_specs.each do |colspec|
          values = keys.zip(lengths).map{ |key, len| colspec.key?(key) ? colspec[key] + ", " : " " * len }
          values.unshift colspec[:type]
          tbl.print((format_string % values).gsub(/,\s*$/, ''))
          tbl.puts
        end

        tbl.puts "  end"
        tbl.puts

        indexes(table, tbl)
        triggers(table, tbl)

        tbl.rewind
        stream.print tbl.read
      # rescue => e
      #   stream.puts "# Could not dump table #{table.inspect} because of following #{e.class}"
      #   stream.puts "#   #{e.message}"
      #   stream.puts
      end

      @dumped_tables << table
      stream
    end

    # Output indexes but don't output indexes that are inherited from parent tables
    # since those will be created by create_table.
    def indexes(table, stream)
      if (indexes = @connection.indexes(table)).any?
        if parent_table = @connection.parent_table(table)
          parent_indexes = @connection.indexes(parent_table)
        end

        indexes.delete_if {|i| is_parent_index?(i, parent_indexes) } if parent_indexes
        return if indexes.empty?

        add_index_statements = indexes.map do |index|
          statement_parts = [
            ('add_index ' + remove_prefix_and_suffix(index.table).inspect),
            index.columns.inspect,
            ('name: ' + index.name.inspect),
          ]
          statement_parts << 'unique: true' if index.unique

          index_lengths = (index.lengths || []).compact
          statement_parts << ('length: ' + Hash[index.columns.zip(index.lengths)].inspect) unless index_lengths.empty?

          index_orders = (index.orders || {})
          statement_parts << ('order: ' + index.orders.inspect) unless index_orders.empty?

          statement_parts << ('where: ' + index.where.inspect) if index.where

          statement_parts << ('using: ' + index.using.inspect) if index.using

          statement_parts << ('type: ' + index.type.inspect) if index.type

          '  ' + statement_parts.join(', ')
        end

        stream.puts add_index_statements.sort.join("\n")
        stream.puts
      end
    end

    def triggers(table, stream)
      parent_triggers = @connection.triggers_for_table(@connection.parent_table(table))
      triggers = @connection.triggers_for_table(table).reject{|name, definition| parent_triggers.keys.include?(name)}
      if triggers.any?
        triggers.each do |trigger|
          name = trigger.first
          definition = trigger.second
          definition[:execute] = definition[:execute].split('.').last  # Remove the schema name
          definition = definition.inject([]) {|a, (k, v)| a << "#{k}: #{v.inspect}"}.join(', ')
          stream.puts "  create_trigger :#{name}, #{definition}"
        end
        stream.puts
      end
    end

    def remove_prefix_and_suffix(table)
      table.gsub(/^(#{ActiveRecord::Base.table_name_prefix})(.+)(#{ActiveRecord::Base.table_name_suffix})$/,  "\\2")
    end

    def already_dumped?(table)
      @dumped_tables.include? table
    end

    def is_parent_index?(index, parent_indexes)
      parent_indexes.each do |pindex|
        return true if pindex.columns == index.columns
      end
      return false
    end

    def custom_primary_key_sequence(table, pk)
      # Get the default value of the pk, save it if its a nextval()
      # Get the sequence, return false if the sequence is owned by the table
      # else return the sequence name in schema.sequence format
    end
  end
end


text:
#include <nuttx/config.h>
#include <stdint.h>

/****************************************************************************
 * Prototypes for interrupt handling
 ****************************************************************************/

inline int calypso_kbd_irq(int irq, uint32_t *regs);

/****************************************************************************
 * Initialize device, add /dev/... nodes
 ****************************************************************************/

void calypso_armio(void);


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.darkkilauea.intotheheavens.ITHScript;

import java.io.*;

/**
 *
 * @author joshua
 */
public final class Variable extends ScriptObject
{
    private boolean _global = false;
    private String _name = null;

    public Variable(String name)
    {
        super();
        setName(name);
    }

    public Variable(String name, int value)
    {
        super(value);
        setName(name);
    }

    public Variable(String name, double value)
    {
        super(value);
        setName(name);
    }

    public Variable(String name, String value)
    {
        super(value);
        setName(name);
    }

    protected Variable(String name, ScriptObject object)
    {
        super(object);
        setName(name);
    }

    public boolean isGlobal()
    {
        return _global;
    }

    public void setGlobal(boolean global)
    {
        _global = global;
    }

    public void setName(String name)
    {
        _name = name;
    }

    public String getName()
    {
        return _name;
    }

    public int getType()
    {
        return _type;
    }

    public void setValue(int value)
    {
        _type = ScriptObject.SOT_INTEGER;
        _intValue = value;
        _floatValue = 0;
        _stringValue = null;
    }

    public void setValue(double value)
    {
        _type = ScriptObject.SOT_FLOAT;
        _floatValue = value;
        _intValue = 0;
        _stringValue = null;
    }

    public void setValue(String value)
    {
        _type = ScriptObject.SOT_STRING;
        _stringValue = value;
        _intValue = 0;
        _floatValue = 0;
    }

    public boolean isNull()
    {
        return _type == ScriptObject.SOT_NULL;
    }

    public void setNull()
    {
        _type = ScriptObject.SOT_NULL;
        _stringValue = null;
        _intValue = 0;
        _floatValue = 0;
    }

    public void copyTo(Variable other)
    {
        other._global = this._global;
        other._name = this._name;
        other._floatValue = this._floatValue;
        other._intValue = this._intValue;
        other._stringValue = this._stringValue;
    }

    @Override
    public void saveToStream(OutputStream stream) throws IOException
    {
        DataOutputStream output = new DataOutputStream(stream);

        output.writeUTF(_name);
        super.saveToStream(stream);
    }

    @Override
    public void loadFromStream(InputStream stream) throws IOException
    {
        DataInputStream input = new DataInputStream(stream);

        _name = input.readUTF();
        super.loadFromStream(stream);
    }
}


text:
namespace ECSE
{

//! A Component which stores circular collision mask data and collision history.
class CircleColliderComponent : public ColliderComponent
{
public:
    //! This is an extension of ColliderComponent.
    using ExtendsComponent = ColliderComponent;

    float radius;   //!< The circle's radius.
};

}


text:
import React from "react";
import { shallow } from "enzyme";
import { shallowToJson } from "enzyme-to-json";
import Showcase from "../Showcase";

describe("Showcase", () => {
  test("Snapshot", () => {
    const component = shallow(<Showcase projects={[]} />);
    const tree = shallowToJson(component);
    expect(tree).toMatchSnapshot();
  });
});


text:
// notice_start

// notice_end

import esp from '../../src';

describe('Router', () => {

    var _router;

    beforeEach(() => {
        _router = new esp.Router();
    });

    describe('.removeModel()', () => {

        var _preProcessorReceivedCount = 0;
        var _eventReceivedCount1 = 0;
        var _eventReceivedCount2 = 0;
        var _postProcessorReceivedCount = 0;
        var _updateReceivedCount1 = 0;
        var _updateReceivedCount2 = 0;
        var _model;

        beforeEach(()=> {
            _model = {
                removeAtPre: false,
                removeAtUpdate: false,
                removeAtPost: false,
                removeAtDispatch: false
            };
            _router.addModel(
                'modelId1',
                _model,
                {
                    preEventProcessor: (model) => {
                        _preProcessorReceivedCount++;
                        if (model.removeAtPre) {
                            _router.removeModel('modelId1');
                        }
                    },
                    postEventProcessor : (model) => {
                        _postProcessorReceivedCount++;
                        if(model.removeAtPost) {
                            _router.removeModel('modelId1');
                        }
                    }
                }
            );
            _router.getEventObservable('modelId1', 'Event1').observe((event, context, model) => {
                _eventReceivedCount1++;
                if(model.removeAtDispatch) {
                    _router.removeModel('modelId1');
                }
            });
            _router.getEventObservable('modelId1', 'Event1').observe(() => {
                _eventReceivedCount2++;
            });
            _router.getModelObservable('modelId1').observe(model => {
                _updateReceivedCount1++;
                if(model.removeAtUpdate) {
                    _router.removeModel('modelId1');
                }
            });
            _router.getModelObservable('modelId1').observe(() => {
                _updateReceivedCount2++;
            });
            // the model gets pumped on initial observe so reset these here
            _preProcessorReceivedCount = 0;
            _eventReceivedCount1 =0;
            _eventReceivedCount2 =0;
            _postProcessorReceivedCount  =0;
            _updateReceivedCount1 = 0;
            _updateReceivedCount2 = 0;
        });

        it('throws if arguments incorrect', () => {
            expect(() => {_router.removeModel(); }).toThrow(new Error("The modelId argument should be a string"));
        });

        it('should onComplete all event streams when the model is removed', () => {
            var didComplete = false;
            _router.getEventObservable('modelId1', 'Event1').observe(
                () => {},
                () => didComplete = true
            );
            _router.removeModel('modelId1');
            expect(didComplete).toEqual(true);
        });

        it('should onComplete all update streams when the model is removed', () => {
            var didComplete = false;
            _router.getModelObservable('modelId1').observe(
                () => {},
                () => didComplete = true
            );
            _router.removeModel('modelId1');
            expect(didComplete).toEqual(true);
        });

        describe('model deletion during the event processing workflow', () => {

            function expectReceived(options) {
                expect(_preProcessorReceivedCount).toEqual(options.atPre);
                expect(_eventReceivedCount1).toEqual(options.atEvent1);
                expect(_eventReceivedCount2).toEqual(options.atEvent2);
                expect(_postProcessorReceivedCount).toEqual(options.atPost);
                expect(_updateReceivedCount1).toEqual(options.atUpdate1);
                expect(_updateReceivedCount2).toEqual(options.atUpdate2);
            }

            it('should allow a preprocessor to removeModel', () => {
                _model.removeAtPre = true;
                _router.publishEvent('modelId1', 'Event1', { });
                expectReceived({
                    atPre: 1,
                    atEvent1: 0,
                    atEvent2: 0,
                    atPost: 0,
                    atUpdate1: 0,
                    atUpdate2: 0
                });
            });

            it('should allow an eventProcessor to removeModel', () => {
                _model.removeAtDispatch = true;
                _router.publishEvent('modelId1', 'Event1', { });
                expectReceived({
                    atPre: 1,
                    atEvent1: 1,
                    atEvent2: 0,
                    atPost: 0,
                    atUpdate1: 0,
                    atUpdate2: 0
                });
            });

            it('should allow a postprocessor to removeModel', () => {
                _model.removeAtPost = true;
                _router.publishEvent('modelId1', 'Event1', { });
                expectReceived({
                    atPre: 1,
                    atEvent1: 1,
                    atEvent2: 1,
                    atPost: 1,
                    atUpdate1: 0,
                    atUpdate2: 0
                });
            });

            it('should allow a model update observer to removeModel', () => {
                _model.removeAtUpdate = true;
                _router.publishEvent('modelId1', 'Event1', { });
                expectReceived({
                    atPre: 1,
                    atEvent1: 1,
                    atEvent2: 1,
                    atPost: 1,
                    atUpdate1: 1,
                    atUpdate2: 0
                });
            });
        });
    });
});


text:
export const RECEIVE_INITIAL_CAMPAIGN = 'RECEIVE_INITIAL_CAMPAIGN';
export const RECEIVE_COURSE_CLONE = 'RECEIVE_COURSE_CLONE';
export const UPDATE_COURSE = 'UPDATE_COURSE';
export const CREATED_COURSE = 'CREATED_COURSE';


text:
public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Solution s = new Solution();
		assert s.reverse(1234) == 4321;
		assert s.reverse(-1234) == -4321;
		assert s.reverse(0) == 0;
		assert s.reverse(1000000003) == Integer.MAX_VALUE;
		assert s.reverse(Integer.MAX_VALUE) == Integer.MAX_VALUE;
		assert s.reverse(-1000000003) == Integer.MIN_VALUE;
	}
}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../openssl_sys/constant.X509v3_KU_DECIPHER_ONLY.html">

Redirecting to ../../openssl_sys/constant.X509v3_KU_DECIPHER_ONLY.html...


text:
<?php
/**
 * Source Interface
 *
 * @author Wenzel Pünter <wenzel@phelix.me>
 * @version 1.0.0
 * @package Lingua
*/
namespace Lingua\Data;

use Lingua\Setup;

/**
 * Classes implementing the {@see \Lingua\Data\SourceInterface} represent resources found on the
 * internet or locally, which need to get fetched. Usually, the data is published under some terms
 * of use, which are displayed by the {@see \Lingua\Data\Setup} class objects.
 *
 * Each {@see \Lingua\Data\SourceÌnterface} can have one or multiple Providers, which implement
 * interfaces to provide the data in a standardized way.
 *
 * @since 1.0.0
*/
interface SourceInterface
{
    /**
     * Set Download Directory
     *
     * This method sets the shared download directory of the source and all its providers.
     *
     * @param string $directory
     * @return static
    */
    public function setDownloadDirectory(string $directory);

    /**
     * Get Download Directory
     *
     * This method returns the download directory set using `setDownloadDirectory` or `null`
     * in case no download directory has been set.
     *
     * @return string|null
    */
    public function getDownloadDirectory();

    /**
     * Get License
     *
     * This method returns the license conditions of the source or `null`, if the source
     * is provided as public domain.
     *
     * @return string|null
    */
    public function getLicense();

    /**
     * Fetch
     *
     * This method call triggers the fetching process, which can include downloading
     * data from the internet, extracting this data and then parsing it. The source
     * provider implementation(s) specify the available data.
     *
     * @return static
    */
    public function fetch();

    /**
     * Get Providers
     *
     * This method returns a `SplObjectStorage` with all providers of the source attached.
     *
     * @return SplObjectStorage
    */
    public function getProviders();
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getExpoSdkStatus = exports.EXPO_SDK_NOT_IMPORTED = exports.EXPO_SDK_NOT_INSTALLED = exports.EXPO_SDK_INSTALLED_AND_IMPORTED = exports.validateWithNetworkAsync = exports.validateLowLatencyAsync = exports.validateWithSchemaFileAsync = exports.FATAL = exports.WARNING = exports.NO_ISSUES = undefined;

let _checkNpmVersionAsync = (() => {
  var _ref = _asyncToGenerator(function* (projectRoot) {
    try {
      yield (_Binaries || _load_Binaries()).sourceBashLoginScriptsAsync();
      let npmVersionResponse = yield (0, (_spawnAsync || _load_spawnAsync()).default)('npm', ['--version']);
      let npmVersion = (_lodash || _load_lodash()).default.trim(npmVersionResponse.stdout);
      if ((_semver || _load_semver()).default.lt(npmVersion, MIN_NPM_VERSION) || _isNpmVersionWithinRanges(npmVersion, BAD_NPM_VERSION_RANGES)) {
        (_ProjectUtils || _load_ProjectUtils()).logError(projectRoot, 'expo', `Error: You are using npm version ${npmVersion}. We recommend version ${CORRECT_NPM_VERSION}. To install it, run 'npm i -g npm@${CORRECT_NPM_VERSION}'.`, 'doctor-npm-version');
        return WARNING;
      } else if (_isNpmVersionWithinRanges(npmVersion, WARN_NPM_VERSION_RANGES)) {
        (_ProjectUtils || _load_ProjectUtils()).logWarning(projectRoot, 'expo', `Warning: You are using npm version ${npmVersion}. There may be bugs in this version, use it at your own risk. We recommend version ${CORRECT_NPM_VERSION}.`, 'doctor-npm-version');
      } else {
        (_ProjectUtils || _load_ProjectUtils()).clearNotification(projectRoot, 'doctor-npm-version');
      }
    } catch (e) {
      (_ProjectUtils || _load_ProjectUtils()).logWarning(projectRoot, 'expo', `Warning: Could not determine npm version. Make sure your version is >= ${MIN_NPM_VERSION} - we recommend ${CORRECT_NPM_VERSION}.`, 'doctor-npm-version');
      return WARNING;
    }

    return NO_ISSUES;
  });

  return function _checkNpmVersionAsync(_x) {
    return _ref.apply(this, arguments);
  };
})();

let _checkWatchmanVersionAsync = (() => {
  var _ref2 = _asyncToGenerator(function* (projectRoot) {
    // There's no point in checking any of this stuff if watchman isn't supported on this platform
    if (!(_Watchman || _load_Watchman()).isPlatformSupported()) {
      (_ProjectUtils || _load_ProjectUtils()).clearNotification(projectRoot, 'doctor-watchman-version');
      return;
    }

    let watchmanVersion = yield (_Watchman || _load_Watchman()).unblockAndGetVersionAsync(projectRoot);

    // If we can't get the watchman version, `getVersionAsync` will return `null`
    if (!watchmanVersion) {
      // watchman is probably just not installed
      (_ProjectUtils || _load_ProjectUtils()).clearNotification(projectRoot, 'doctor-watchman-version');
      return;
    }

    if ((_semver || _load_semver()).default.lt(watchmanVersion, MIN_WATCHMAN_VERSION)) {
      let warningMessage = `Warning: You are using an old version of watchman (v${watchmanVersion}). This may cause problems for you.\n\nWe recommend that you either uninstall watchman (and XDE will try to use a copy it is bundled with) or upgrade watchman to a newer version, at least v${MIN_WATCHMAN_VERSION}.`;

      // Add a note about homebrew if the user is on a Mac
      if (process.platform === 'darwin') {
        warningMessage += `\n\nIf you are using homebrew, try:\nbrew uninstall watchman; brew install watchman`;
      }
      (_ProjectUtils || _load_ProjectUtils()).logWarning(projectRoot, 'expo', warningMessage, 'doctor-watchman-version');
    } else {
      (_ProjectUtils || _load_ProjectUtils()).clearNotification(projectRoot, 'doctor-watchman-version');
    }
  });

  return function _checkWatchmanVersionAsync(_x2) {
    return _ref2.apply(this, arguments);
  };
})();

let validateWithSchemaFileAsync = exports.validateWithSchemaFileAsync = (() => {
  var _ref3 = _asyncToGenerator(function* (projectRoot, schemaPath) {
    let { exp, pkg } = yield (_ProjectUtils || _load_ProjectUtils()).readConfigJsonAsync(projectRoot);
    let schema = JSON.parse((yield _fs.default.readFile.promise(schemaPath, 'utf8')));
    return validateWithSchema(exp, schema.schema, 'exp.json', 'UNVERSIONED');
  });

  return function validateWithSchemaFileAsync(_x3, _x4) {
    return _ref3.apply(this, arguments);
  };
})();

let _validateAssetFieldsAsync = (() => {
  var _ref4 = _asyncToGenerator(function* (projectRoot, exp) {
    try {
      const assetSchemas = yield (_ExpSchema || _load_ExpSchema()).getAssetSchemasAsync(exp.sdkVersion);
      yield Promise.all(assetSchemas.map((() => {
        var _ref5 = _asyncToGenerator(function* ({
          fieldPath,
          schema: { meta: { asset, contentTypePattern, contentTypeHuman } }
        }) {
          const value = (_lodash || _load_lodash()).default.get(exp, fieldPath);
          if (asset && value) {
            if (contentTypePattern) {
              // NOTE(nikki): The '4100' below should be enough for most file types, though we
              //              could probably go shorter....
              //              http://www.garykessler.net/library/file_sigs.html
              const filePath = _path.default.resolve(projectRoot, value);
              const contentType = _fs.default.existsSync(filePath) ? (0, (_fileType || _load_fileType()).default)((yield (0, (_readChunk || _load_readChunk()).default)(filePath, 0, 4100))).mime : (yield (_request || _load_request()).default.promise.head({ url: value })).headers['content-type'];
              if (!contentType.match(new RegExp(contentTypePattern))) {
                const configName = yield (_ProjectUtils || _load_ProjectUtils()).configFilenameAsync(projectRoot);
                (_ProjectUtils || _load_ProjectUtils()).logWarning(projectRoot, 'expo', `Warning: Problem in ${configName}. Field '${fieldPath}' should point to a ${contentTypeHuman}, but the file at '${value}' has type '${contentType}'. See ${(_Config || _load_Config()).default.helpUrl}`, `doctor-validate-asset-fields-${fieldPath}`);
              } else {
                (_ProjectUtils || _load_ProjectUtils()).clearNotification(projectRoot, `doctor-validate-asset-fields-${fieldPath}`);
              }
            }
          }
        });

        return function (_x7) {
          return _ref5.apply(this, arguments);
        };
      })()));

      (_ProjectUtils || _load_ProjectUtils()).clearNotification(projectRoot, 'doctor-validate-asset-fields');
    } catch (e) {
      (_ProjectUtils || _load_ProjectUtils()).logWarning(projectRoot, 'expon', `Warning: Problem validating asset fields: ${e.message}.`, 'doctor-validate-asset-fields');
    }
  });

  return function _validateAssetFieldsAsync(_x5, _x6) {
    return _ref4.apply(this, arguments);
  };
})();

let _validatePackageJsonAndExpJsonAsync = (() => {
  var _ref6 = _asyncToGenerator(function* (exp, pkg, projectRoot) {
    if (!exp || !pkg) {
      // readConfigJsonAsync already logged an error
      return FATAL;
    }

    try {
      yield _checkWatchmanVersionAsync(projectRoot);
    } catch (e) {
      (_ProjectUtils || _load_ProjectUtils()).logWarning(projectRoot, 'expo', `Warning: Problem checking watchman version. ${e.message}.`, 'doctor-problem-checking-watchman-version');
    }
    (_ProjectUtils || _load_ProjectUtils()).clearNotification(projectRoot, 'doctor-problem-checking-watchman-version');

    const expJsonExists = yield (_ProjectUtils || _load_ProjectUtils()).fileExistsAsync(_path.default.join(projectRoot, 'exp.json'));
    const appJsonExists = yield (_ProjectUtils || _load_ProjectUtils()).fileExistsAsync(_path.default.join(projectRoot, 'app.json'));

    if (expJsonExists && appJsonExists) {
      (_ProjectUtils || _load_ProjectUtils()).logWarning(projectRoot, 'expo', `Warning: Both app.json and exp.json exist in this directory. Only one should exist for a single project.`, 'doctor-both-app-and-exp-json');
      return WARNING;
    }
    (_ProjectUtils || _load_ProjectUtils()).clearNotification(projectRoot, 'doctor-both-app-and-exp-json');

    let sdkVersion = exp.sdkVersion;
    const configName = yield (_ProjectUtils || _load_ProjectUtils()).configFilenameAsync(projectRoot);
    try {
      // TODO(perry) figure out a way to tell the schema validator whether this is exp.json or app.json
      let schema = yield (_ExpSchema || _load_ExpSchema()).getSchemaAsync(sdkVersion);
      let { errorMessage } = validateWithSchema(exp, schema, configName, sdkVersion);

      if (errorMessage) {
        (_ProjectUtils || _load_ProjectUtils()).logWarning(projectRoot, 'expo', errorMessage, 'doctor-schema-validation');
        return WARNING;
      } else {
        (_ProjectUtils || _load_ProjectUtils()).clearNotification(projectRoot, 'doctor-schema-validation');
      }

      (_ProjectUtils || _load_ProjectUtils()).clearNotification(projectRoot, 'doctor-schema-validation-exception');
    } catch (e) {
      (_ProjectUtils || _load_ProjectUtils()).logWarning(projectRoot, 'expo', `Warning: Problem validating ${configName}: ${e.message}.`, 'doctor-schema-validation-exception');
    }

    // Warn if sdkVersion is UNVERSIONED
    if (sdkVersion === 'UNVERSIONED') {
      (_ProjectUtils || _load_ProjectUtils()).logWarning(projectRoot, 'expo', `Warning: Using unversioned Expo SDK. Do not publish until you set sdkVersion in ${configName}`, 'doctor-unversioned');
      return WARNING;
    }
    (_ProjectUtils || _load_ProjectUtils()).clearNotification(projectRoot, 'doctor-unversioned');

    // react-native is required
    if (!pkg.dependencies || !pkg.dependencies['react-native']) {
      (_ProjectUtils || _load_ProjectUtils()).logWarning(projectRoot, 'expo', `Warning: Can't find react-native in package.json dependencies`, 'doctor-no-react-native-in-package-json');
      return WARNING;
    }
    (_ProjectUtils || _load_ProjectUtils()).clearNotification(projectRoot, 'doctor-no-react-native-in-package-json');

    // TODO(adam) set up caching for this
    let sdkVersions = yield (_Api || _load_Api()).default.sdkVersionsAsync();
    if (!sdkVersions) {
      (_ProjectUtils || _load_ProjectUtils()).logWarning(projectRoot, 'expo', `Warning: Couldn't connect to SDK versions server`, 'doctor-versions-endpoint-failed');
      return WARNING;
    }
    (_ProjectUtils || _load_ProjectUtils()).clearNotification(projectRoot, 'doctor-versions-endpoint-failed');

    if (!sdkVersions[sdkVersion]) {
      (_ProjectUtils || _load_ProjectUtils()).logWarning(projectRoot, 'expo', `Warning: Invalid sdkVersion. Valid options are ${(_lodash || _load_lodash()).default.keys(sdkVersions).join(', ')}`, 'doctor-invalid-sdk-version');
      return WARNING;
    }
    (_ProjectUtils || _load_ProjectUtils()).clearNotification(projectRoot, 'doctor-invalid-sdk-version');

    const reactNativeIssue = yield _validateReactNativeVersionAsync(exp, pkg, projectRoot, sdkVersions, sdkVersion);

    if (reactNativeIssue !== NO_ISSUES) {
      return reactNativeIssue;
    }

    // TODO: Check any native module versions here

    return NO_ISSUES;
  });

  return function _validatePackageJsonAndExpJsonAsync(_x8, _x9, _x10) {
    return _ref6.apply(this, arguments);
  };
})();

let _validateReactNativeVersionAsync = (() => {
  var _ref7 = _asyncToGenerator(function* (exp, pkg, projectRoot, sdkVersions, sdkVersion) {
    if ((_Config || _load_Config()).default.validation.reactNativeVersionWarnings) {
      let reactNative = pkg.dependencies['react-native'];

      // TODO(2016-12-20): Remove the check for our old "exponentjs" org eventually
      if (!reactNative.match(/(exponent(?:js)?|expo)\/react-native/)) {
        return NO_ISSUES;

        // (TODO-2017-07-20): Validate the react-native version if it uses
        // officially published package rather than Expo fork. Expo fork of
        // react-native was required before CRNA. We now only run the react-native
        // validation of the version if we are using the fork. We should probably
        // validate the version here as well such that it matches with the
        // react-native version compatible with the selected SDK.
        //
        // ProjectUtils.logWarning(
        //   projectRoot,
        //   'expo',
        //   `Warning: Not using the Expo fork of react-native. See ${Config.helpUrl}.`,
        //   'doctor-not-using-expo-fork'
        // );
        // return WARNING;
      }
      (_ProjectUtils || _load_ProjectUtils()).clearNotification(projectRoot, 'doctor-not-using-expo-fork');

      try {
        let reactNativeTag = reactNative.match(/sdk-\d+\.\d+\.\d+/)[0];
        let sdkVersionObject = sdkVersions[sdkVersion];

        // TODO: Want to be smarter about this. Maybe warn if there's a newer version.
        if ((_semver || _load_semver()).default.major((_Versions || _load_Versions()).parseSdkVersionFromTag(reactNativeTag)) !== (_semver || _load_semver()).default.major((_Versions || _load_Versions()).parseSdkVersionFromTag(sdkVersionObject['expoReactNativeTag']))) {
          (_ProjectUtils || _load_ProjectUtils()).logWarning(projectRoot, 'expo', `Warning: Invalid version of react-native for sdkVersion ${sdkVersion}. Use github:expo/react-native#${sdkVersionObject['expoReactNativeTag']}`, 'doctor-invalid-version-of-react-native');
          return WARNING;
        }
        (_ProjectUtils || _load_ProjectUtils()).clearNotification(projectRoot, 'doctor-invalid-version-of-react-native');

        (_ProjectUtils || _load_ProjectUtils()).clearNotification(projectRoot, 'doctor-malformed-version-of-react-native');
      } catch (e) {
        (_ProjectUtils || _load_ProjectUtils()).logWarning(projectRoot, 'expo', `Warning: ${reactNative} is not a valid version. Version must be in the form of sdk-x.y.z. Please update your package.json file.`, 'doctor-malformed-version-of-react-native');
        return WARNING;
      }
    }

    return NO_ISSUES;
  });

  return function _validateReactNativeVersionAsync(_x11, _x12, _x13, _x14, _x15) {
    return _ref7.apply(this, arguments);
  };
})();

// TODO: use `yarn check`

let _validateNodeModulesAsync = (() => {
  var _ref8 = _asyncToGenerator(function* (projectRoot) {
    let { exp, pkg } = yield (_ProjectUtils || _load_ProjectUtils()).readConfigJsonAsync(projectRoot);
    let nodeModulesPath = projectRoot;
    if (exp.nodeModulesPath) {
      nodeModulesPath = _path.default.join(projectRoot, exp.nodeModulesPath);
    }

    // Check to make sure node_modules exists at all
    try {
      let result = _fs.default.statSync(_path.default.join(nodeModulesPath, 'node_modules'));
      if (!result.isDirectory()) {
        (_ProjectUtils || _load_ProjectUtils()).logError(projectRoot, 'expo', `Error: node_modules directory is missing. Please run \`npm install\` in your project directory.`, 'doctor-node-modules-missing');
        return FATAL;
      }

      (_ProjectUtils || _load_ProjectUtils()).clearNotification(projectRoot, 'doctor-node-modules-missing');
    } catch (e) {
      (_ProjectUtils || _load_ProjectUtils()).logError(projectRoot, 'expo', `Error: node_modules directory is missing. Please run \`npm install\` in your project directory.`, 'doctor-node-modules-missing');
      return FATAL;
    }

    // Check to make sure react native is installed
    try {
      let result = _fs.default.statSync(_path.default.join(nodeModulesPath, 'node_modules', 'react-native', 'local-cli', 'cli.js'));
      if (!result.isFile()) {
        (_ProjectUtils || _load_ProjectUtils()).logError(projectRoot, 'expo', `Error: React native is not installed. Please run \`npm install\` in your project directory.`, 'doctor-react-native-not-installed');
        return FATAL;
      }

      (_ProjectUtils || _load_ProjectUtils()).clearNotification(projectRoot, 'doctor-react-native-not-installed');
    } catch (e) {
      (_ProjectUtils || _load_ProjectUtils()).logError(projectRoot, 'expo', `Error: React native is not installed. Please run \`npm install\` in your project directory.`, 'doctor-react-native-not-installed');
      return FATAL;
    }

    // Validate all package.json dependencies are installed and up to date
    if (pkg.dependencies) {
      yield (_Binaries || _load_Binaries()).sourceBashLoginScriptsAsync();

      try {
        yield (0, (_spawnAsync || _load_spawnAsync()).default)('npm', ['--version']);
      } catch (e) {
        (_ProjectUtils || _load_ProjectUtils()).logWarning(projectRoot, 'expo', `\`npm\` command not found. If you have npm installed please run \`npm install -g exp && exp path\`.`, 'doctor-npm-not-found');
        return WARNING;
      }
      (_ProjectUtils || _load_ProjectUtils()).clearNotification(projectRoot, 'doctor-npm-not-found');

      let npmls;
      try {
        let npmlsCommand = yield (0, (_spawnAsync || _load_spawnAsync()).default)('npm', ['ls', '--json', '--depth', '1'], {
          cwd: nodeModulesPath
        });
        npmls = npmlsCommand.stdout;
      } catch (e) {
        npmls = e.stdout; // `npm ls` sometimes returns an error code
      }

      if (!npmls) {
        (_ProjectUtils || _load_ProjectUtils()).logWarning(projectRoot, 'expo', `Problem checking node_modules dependencies. Could not run \`npm ls\` in ${projectRoot}.`, 'doctor-could-not-run-npm-ls');
        return WARNING;
      }
      (_ProjectUtils || _load_ProjectUtils()).clearNotification(projectRoot, 'doctor-could-not-run-npm-ls');

      let npmlsDependencies;
      try {
        npmlsDependencies = JSON.parse(npmls).dependencies;
      } catch (e) {
        (_ProjectUtils || _load_ProjectUtils()).logWarning(projectRoot, 'expo', `Problem checking node_modules dependencies: ${e.message}`, 'doctor-problem-checking-node-modules');
        return WARNING;
      }
      (_ProjectUtils || _load_ProjectUtils()).clearNotification(projectRoot, 'doctor-problem-checking-node-modules');

      if (npmlsDependencies) {
        let errorStrings = [];
        (_lodash || _load_lodash()).default.forEach(pkg.dependencies, function (versionRequired, dependency) {
          let installedDependency = npmlsDependencies[dependency];
          if (dependency === 'react' && versionRequired.match(/alpha/)) {
            // ignore alpha dependencies on react
          } else if (!installedDependency || !installedDependency.version) {
            if (installedDependency && installedDependency.peerMissing) {
              errorStrings.push(`Warning: '${dependency}' peer depencency missing. Run \`npm ls\` in ${nodeModulesPath} to see full warning.`);
            } else {
              errorStrings.push(`Warning: '${dependency}' dependency is not installed.`);
            }
          } else if (dependency !== 'react-native' && !(_semver || _load_semver()).default.satisfies(installedDependency.version, versionRequired) && !versionRequired.includes(installedDependency.from)) {
            // TODO: also check react-native
            // For react native, `from` field looks like "exponent/react-native#sdk-8.0.1" and
            // versionRequired looks like "github:exponent/react-native#sdk-8.0.0"
            errorStrings.push(`Warning: Installed version ${installedDependency.version} of '${dependency}' does not satisfy required version ${versionRequired}`);
          }
        });

        if (errorStrings.length > 0) {
          errorStrings.push(`\nIf there is an issue running your project, please run \`npm install\` in ${nodeModulesPath} and restart.`);
          (_ProjectUtils || _load_ProjectUtils()).logWarning(projectRoot, 'expo', errorStrings.join('\n'), 'doctor-node-modules-issues');
          return WARNING;
        } else {
          (_ProjectUtils || _load_ProjectUtils()).clearNotification(projectRoot, 'doctor-node-modules-issues');
        }
      }
    }

    return NO_ISSUES;
  });

  return function _validateNodeModulesAsync(_x16) {
    return _ref8.apply(this, arguments);
  };
})();

let validateLowLatencyAsync = exports.validateLowLatencyAsync = (() => {
  var _ref9 = _asyncToGenerator(function* (projectRoot) {
    return validateAsync(projectRoot, false);
  });

  return function validateLowLatencyAsync(_x17) {
    return _ref9.apply(this, arguments);
  };
})();

let validateWithNetworkAsync = exports.validateWithNetworkAsync = (() => {
  var _ref10 = _asyncToGenerator(function* (projectRoot) {
    return validateAsync(projectRoot, true);
  });

  return function validateWithNetworkAsync(_x18) {
    return _ref10.apply(this, arguments);
  };
})();

let validateAsync = (() => {
  var _ref11 = _asyncToGenerator(function* (projectRoot, allowNetwork) {
    let { exp, pkg } = yield (_ProjectUtils || _load_ProjectUtils()).readConfigJsonAsync(projectRoot);

    let status = yield _checkNpmVersionAsync(projectRoot);
    if (status === FATAL) {
      return status;
    }

    let newStatus = yield _validatePackageJsonAndExpJsonAsync(exp, pkg, projectRoot);
    if (newStatus > status) {
      status = newStatus;
    }

    // Don't block this! It has to make network requests so it's slow.
    if (allowNetwork) {
      _validateAssetFieldsAsync(projectRoot, exp);
    }

    // TODO: this broke once we started using yarn because `npm ls` doesn't
    // work on a yarn install. Use `yarn check` in the future.
    if (status !== FATAL && exp && !exp.ignoreNodeModulesValidation) {
      let nodeModulesStatus = yield _validateNodeModulesAsync(projectRoot);
      if (nodeModulesStatus > status) {
        return nodeModulesStatus;
      }
    }

    return status;
  });

  return function validateAsync(_x19, _x20) {
    return _ref11.apply(this, arguments);
  };
})();

let getExpoSdkStatus = exports.getExpoSdkStatus = (() => {
  var _ref12 = _asyncToGenerator(function* (projectRoot) {
    let { pkg } = yield (_ProjectUtils || _load_ProjectUtils()).readConfigJsonAsync(projectRoot);

    try {
      let sdkPkg;
      if (pkg.dependencies['exponent']) {
        sdkPkg = 'exponent';
      } else if (pkg.dependencies['expo']) {
        sdkPkg = 'expo';
      } else {
        return EXPO_SDK_NOT_INSTALLED;
      }

      let mainFilePath = _path.default.join(projectRoot, pkg.main);
      let mainFile = yield _fs.default.readFile.promise(mainFilePath, 'utf8');

      // TODO: support separate .ios.js and .android.js files
      if (mainFile.includes(`from '${sdkPkg}'`) || mainFile.includes(`require('${sdkPkg}')`)) {
        return EXPO_SDK_INSTALLED_AND_IMPORTED;
      } else {
        return EXPO_SDK_NOT_IMPORTED;
      }
    } catch (e) {
      return EXPO_SDK_NOT_IMPORTED;
    }
  });

  return function getExpoSdkStatus(_x21) {
    return _ref12.apply(this, arguments);
  };
})();

exports.validateWithSchema = validateWithSchema;

require('instapromise');

var _lodash;

function _load_lodash() {
  return _lodash = _interopRequireDefault(require('lodash'));
}

var _semver;

function _load_semver() {
  return _semver = _interopRequireDefault(require('semver'));
}

var _fs = _interopRequireDefault(require('fs'));

var _jsonschema;

function _load_jsonschema() {
  return _jsonschema = _interopRequireDefault(require('jsonschema'));
}

var _path = _interopRequireDefault(require('path'));

var _request;

function _load_request() {
  return _request = _interopRequireDefault(require('request'));
}

var _spawnAsync;

function _load_spawnAsync() {
  return _spawnAsync = _interopRequireDefault(require('@expo/spawn-async'));
}

var _readChunk;

function _load_readChunk() {
  return _readChunk = _interopRequireDefault(require('read-chunk'));
}

var _fileType;

function _load_fileType() {
  return _fileType = _interopRequireDefault(require('file-type'));
}

var _ExpSchema;

function _load_ExpSchema() {
  return _ExpSchema = _interopRequireWildcard(require('./ExpSchema'));
}

var _ProjectUtils;

function _load_ProjectUtils() {
  return _ProjectUtils = _interopRequireWildcard(require('./ProjectUtils'));
}

var _Api;

function _load_Api() {
  return _Api = _interopRequireDefault(require('../Api'));
}

var _Binaries;

function _load_Binaries() {
  return _Binaries = _interopRequireWildcard(require('../Binaries'));
}

var _Config;

function _load_Config() {
  return _Config = _interopRequireDefault(require('../Config'));
}

var _Versions;

function _load_Versions() {
  return _Versions = _interopRequireWildcard(require('../Versions'));
}

var _Watchman;

function _load_Watchman() {
  return _Watchman = _interopRequireWildcard(require('../Watchman'));
}

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

const NO_ISSUES = exports.NO_ISSUES = 0;
const WARNING = exports.WARNING = 1;
const FATAL = exports.FATAL = 2;

const MIN_WATCHMAN_VERSION = '4.6.0';
const MIN_NPM_VERSION = '3.0.0';
const CORRECT_NPM_VERSION = '4.6.1';
const WARN_NPM_VERSION_RANGES = ['>= 5.0.0'];
const BAD_NPM_VERSION_RANGES = ['>= 5.0.0 <= 5.0.3'];

function _isNpmVersionWithinRanges(npmVersion, ranges) {
  return (_lodash || _load_lodash()).default.some(ranges, range => (_semver || _load_semver()).default.satisfies(npmVersion, range));
}

function validateWithSchema(exp, schema, configName, sdkVersion) {
  let validator = new (_jsonschema || _load_jsonschema()).default.Validator();
  let validationResult = validator.validate(exp, schema);

  let fullMessage;
  if (validationResult.errors && validationResult.errors.length > 0) {
    fullMessage = `Warning: Problem${validationResult.errors.length > 1 ? 's' : ''} in ${configName}. See https://docs.expo.io/versions/v${sdkVersion}/guides/configuration.html.`;
    for (let error of validationResult.errors) {
      // Formate the message nicely
      let message = error.stack.replace(/instance\./g, '').replace(/exists in instance/g, `exists in ${configName}`).replace('instance additionalProperty', 'additional property');
      fullMessage += `\n  - ${message}.`;
    }
  }

  return { errorMessage: fullMessage };
}

const EXPO_SDK_INSTALLED_AND_IMPORTED = exports.EXPO_SDK_INSTALLED_AND_IMPORTED = 0;
const EXPO_SDK_NOT_INSTALLED = exports.EXPO_SDK_NOT_INSTALLED = 1;
const EXPO_SDK_NOT_IMPORTED = exports.EXPO_SDK_NOT_IMPORTED = 2;
//# sourceMappingURL=../__sourcemaps__/project/Doctor.js.map


text:
from moztelemetry import get_pings_properties
from moztelemetry.dataset import Dataset

def map_frame(frame, modules):
    if 'ip' not in frame:
        return None
    if 'module_index' not in frame:
        return None
    offset = int(frame['ip'], 16)
    module_index = frame['module_index']
    if module_index is None:
        return None
    if modules is not None and module_index >= 0 and module_index < len(modules):
        if 'base_addr' in modules[module_index]:
            offset -= int(modules[module_index]['base_addr'], 16)
    return [module_index, hex(offset)]

def get_payload_hangs(ping):
    if ping["payload/stackTraces/threads"] is None:
        return []
    if ping["payload/stackTraces/crash_info/crashing_thread"] is None:
        return []
    crash_thread = ping["payload/stackTraces/threads"][ping["payload/stackTraces/crash_info/crashing_thread"]]
    frames = crash_thread['frames']

    stack = [
        map_frame(f, ping["payload/stackTraces/modules"])
        for f in reversed(frames)
    ]
    return [{
        'stack': [f for f in stack if f is not None],
        'duration': 1,
        'thread': ping['payload/processType'],
        'runnableName': 'dummy_runnable',
        'process': ping['payload/processType'],
        'annotations': {},
    }]

def get_payload_modules(ping):
    crash_modules = ping["payload/stackTraces/modules"]
    if crash_modules is None:
        return []
    return [[m.get('debug_file', None), m.get('debug_id', None)] for m in crash_modules]

def map_to_hang_format(ping):
    return {
        "environment/system/os/name": ping["environment/system/os/name"],
        "environment/system/os/version": ping["environment/system/os/version"],
        "application/architecture": ping["application/architecture"],
        "application/buildId": ping["application/buildId"],
        "payload/stackTraces/crash_info/crashing_thread": ping["payload/stackTraces/crash_info/crashing_thread"],
        "payload/stackTraces/threads": ping["payload/stackTraces/threads"],
        "payload/stackTraces/modules": ping["payload/stackTraces/modules"],
        "payload/hangs": get_payload_hangs(ping),
        "payload/modules": get_payload_modules(ping),
        "payload/timeSinceLastPing": 86400,
    }

def get_data(sc, config, date):
    date_str = date.strftime("%Y%m%d")

    pings = (Dataset.from_source("telemetry")
             .where(docType='crash')
             .where(submissionDate=lambda b: b.startswith(date_str))
             .where(appUpdateChannel=config['channel'])
             .records(sc, sample=config['sample_size']))

    properties = ["environment/system/os/name",
                  "environment/system/os/version",
                  "application/architecture",
                  "application/buildId",
                  "payload/processType",
                  "payload/stackTraces/crash_info/crashing_thread",
                  "payload/stackTraces/threads",
                  "payload/stackTraces/modules",]

    try:
        pings_props = get_pings_properties(pings, properties, with_processes=True)
    except ValueError:
        return None

    return pings_props.map(map_to_hang_format)


text:
package uk.gov.dstl.baleen.schedules;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.io.IOException;

import org.apache.uima.collection.CollectionException;
import org.apache.uima.resource.ResourceInitializationException;
import org.junit.Test;

public class OnceTest extends AbstractSchedulerTest<Once> {

  public OnceTest() {
    super(Once.class);
  }

  @Test
  public void test() throws CollectionException, IOException, ResourceInitializationException {
    Once once = create();

    assertTrue(once.hasNext());

    assertFalse(once.hasNext());
    assertFalse(once.hasNext());
  }
}


text:
__author__ = 'cpaulson'
import pyKriging
from pyKriging.krige import kriging
from pyKriging.samplingplan import samplingplan

# The Kriging model starts by defining a sampling plan, we use an optimal Latin Hypercube here
sp = samplingplan(2)
X = sp.optimallhc(15)

# Next, we define the problem we would like to solve
testfun = pyKriging.testfunctions().branin

# We generate our observed values based on our sampling plan and the test function
y = testfun(X)

print 'Setting up the Kriging Model'

# Now that we have our initial data, we can create an instance of a kriging model
k = kriging(X, y, testfunction=testfun, name='simple', testPoints=250)
k.train(optimizer='ga')
k.snapshot()

for i in range(5):
    newpoints = k.infill(2)
    for point in newpoints:
        print 'Adding point {}'.format(point)
        k.addPoint(point, testfun(point)[0])
    k.train()
    k.snapshot()

# #And plot the model

print 'Now plotting final results...'
k.plot()


text:
package org.frameworkset.spi.remote.netty;

import org.frameworkset.netty.NettyRPCServer;

/**
 *
Title: TestServer.java

 *
Description:

 *
bboss workgroup

 *
Copyright (c) 2007

 * @Date 2010-4-20 11:47:22
 * @author biaoping.yin
 * @version 1.0
 */
public class TestServer
{
    public static void main(String[] args)
    {
//    	AssembleUtil.registAssembleCallback(new WebDocbaseAssembleCallback("D:/workspace/bbossgroup-2.0-RC2/bbossaop/"));
        NettyRPCServer.getNettyRPCServer().start();
    }
}


text:
from language_model import LanguageModel
from smoothed_language_model import SmoothedLanguageModel, LaPlaceLanguageModel, BayesLanguageModel
import unittest
import logging
import sys

class TestSmoothedLanguageModel(unittest.TestCase):

    def setUp(self):

        self.doc = { 'hello': 1,
                'world': 2,
                'help': 1
        }

        self.col = {'hello': 20,
               'world': 5,
               'good': 5,
               'bye': 15,
               'free': 1,
               'code': 1,
               'source': 1,
               'compile': 1,
               'error': 1
        }

        self.colLM = LanguageModel(term_dict=self.col)
        self.docLM = LanguageModel(term_dict=self.doc)

    def test_calculate_likelihood(self):
        model = SmoothedLanguageModel(self.docLM, self.colLM, lam=0.5)
        phello = model.get_term_prob('hello')
        self.assertEquals(phello, (1.0/8.0)+(1.0/5.0))

        phelp = model.get_term_prob('help')
        self.assertEquals(phelp, (1.0/8.0))

        pworld = model.get_term_prob('world')
        self.assertEquals(pworld, (1.0/4.0)+(1.0/20.0))

        perror = model.get_term_prob('error')
        self.assertEquals(perror, 1.0/100.0)

    def test_calculate_laplace_likelihood(self):
        model = LaPlaceLanguageModel(self.docLM, self.colLM, alpha = 1.0)
        phello = model.get_term_prob('hello')
        self.assertEquals(phello,2.0/13.0)

        phelp = model.get_term_prob('help')
        self.assertEquals(phelp,2.0/13.0)

        pworld = model.get_term_prob('world')
        self.assertEquals(pworld,3.0/13.0)

        perror = model.get_term_prob('error')
        self.assertEquals(perror,1.0/13.0)

    def test_calculate_JM_likelihood(self):
        pass

    def test_calculate_bayes_likelihood(self):
        model = BayesLanguageModel(self.docLM, self.colLM, beta = 5.0)

        phello = model.get_term_prob('hello')
        self.assertAlmostEqual(phello, 3.0/9.0)

        phelp = model.get_term_prob('help')
        self.assertAlmostEqual(phelp, 1.0/9.0)

        pworld = model.get_term_prob('world')
        self.assertAlmostEqual(pworld, 2.5/9.0)

        perror = model.get_term_prob('error')
        self.assertAlmostEqual(perror, 1.0/90.0)

if __name__ == '__main__':
    logging.basicConfig(stream=sys.stderr)
    logging.getLogger("TestSmoothedModel").setLevel(logging.DEBUG)
    unittest.main(exit=False)


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Pycnidiostroma eugenicae F. Stevens

### Remarks
null


text:
'use strict'

import React from 'react'
const _ = require('lodash')

var widgets = {}

var getWidget = function (user) {

  //var PersonalAddress = React.createClass(require('../routes/editUser/components/personalAddressFields'))
  //var OfficeAddress = React.createClass(require('../routes/editUser/components/officeAddressFields'))
  //var Rcslider = React.createClass(require('rc-slider'))
  //
  //widgets['user'] = {
  //  PersonalAddress:<PersonalAddress user={user}/>,
  //  OfficeAddress: <OfficeAddress user={user}/>,
  //  Rcslider: <Rcslider user={user}/>
  //}
  //
  //
  //console.log('Choose widgets for', user)
  return []//_.values(widgets.user)
}

module.exports.getWidget = getWidget


text: export { default } from 'ui-base-theme/components/demo--ui-button-group';


text:
/**
 * @interface
 */
export class AuthorizationStore {

  /**
   * the query params the user is currently showing
   * @type {object}
   */
  get query() {};
  /**
   * sets and saves a value against the store
   * @param {string} key - the key to store the value against
   * @param {object} value - the value to store
   * @returns {Promise} - a promise to have saved the value
   */
  set(key, value) {

  }

  /**
   * gets a value saved against the specified key
   *
   * @param {string} key - the key the value is saved against
   * @returns {object} - the value at the specified key or null
   */
  get(key) {

  }

  /**
   * removes any value saved against the specified key permanently
   * @param {string} key - the key the value is saved against
   * @returns {Promise} - a promise to have deleted the value from the store
   */
  delete(key) {

  }

  /**
   * mark the current authorization flow as complete i.e. after having swapped all access tokens and request tokens
   * @returns {undefined}
   */
  done() {

  }

  /**
   * redirect the user to the specified uri
   * the user is no longer present after this call so should only happen at the end of a flow
   * @param {string} uri - the uri to redirect the user to
   * @returns {undefined}
   */
  redirect(uri) {

  }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Test tracing UMD</title>

Test tracing UMD

      This fixture tests that the new tracing API is accessible via UMD build using the UMD shim.
      It does not exhaustively test API functionality, only that the forwarded methods can be called.

      Before running the tests below, check the console to make sure there are no errors.

      Tests
      <button id="run-test-button" onClick="runAllTests()">Run all tests</button>

        Test scheduler API

        Test tracing API

        Test tracing subscriptions API

        Test end-to-end integration


text:
package com.jme3.audio;

import com.jme3.asset.AssetKey;
import com.jme3.export.InputCapsule;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.export.OutputCapsule;
import java.io.IOException;

/**
 * AudioKey is extending AssetKey by holding stream flag.
 *
 * @author Kirill Vainer
 */
public class AudioKey extends AssetKey<AudioData> {

    private boolean stream;
    private boolean streamCache;

    /**
     * Create a new AudioKey.
     *
     * @param name Name of the asset
     * @param stream If true, the audio will be streamed from harddrive,
     * otherwise it will be buffered entirely and then played.
     * @param streamCache If stream is true, then this specifies if
     * the stream cache is used. When enabled, the audio stream will
     * be read entirely but not decoded, allowing features such as
     * seeking, determining duration and looping.
     */
    public AudioKey(String name, boolean stream, boolean streamCache){
        this(name, stream);
        this.streamCache = streamCache;
    }

    /**
     * Create a new AudioKey
     *
     * @param name Name of the asset
     * @param stream If true, the audio will be streamed from harddrive,
     * otherwise it will be buffered entirely and then played.
     */
    public AudioKey(String name, boolean stream){
        super(name);
        this.stream = stream;
    }

    public AudioKey(String name){
        super(name);
        this.stream = false;
    }

    public AudioKey(){
    }

    @Override
    public String toString(){
        return name + (stream ?
                          (streamCache ?
                            " (Stream/Cache)" :
                            " (Stream)") :
                         " (Buffer)");
    }

    /**
     * @return True if the loaded audio should be a {@link AudioStream} or
     * false if it should be a {@link AudioBuffer}.
     */
    public boolean isStream() {
        return stream;
    }

    /**
     * Specifies if the stream cache is used.
     *
     * When enabled, the audio stream will
     * be read entirely but not decoded, allowing features such as
     * seeking, looping and determining duration.
     */
    public boolean useStreamCache(){
        return streamCache;
    }

    @Override
    public boolean shouldCache(){
        return !stream && !streamCache;
    }

    @Override
    public void write(JmeExporter ex) throws IOException{
        super.write(ex);
        OutputCapsule oc = ex.getCapsule(this);
        oc.write(stream, "do_stream", false);
        oc.write(streamCache, "use_stream_cache", false);
    }

    @Override
    public void read(JmeImporter im) throws IOException{
        super.read(im);
        InputCapsule ic = im.getCapsule(this);
        stream = ic.readBoolean("do_stream", false);
        streamCache = ic.readBoolean("use_stream_cache", false);
    }

}


text:
import React from 'react'
import {Link} from 'react-router'
import $ from 'jquery'
import Firebase from 'firebase'

const SignupStudent = require('./signup_student');
const SignupInstructor = require('./signup_instructor');
const Login = require('./login');

const userRef = new Firebase('https://arrowlense2-0.firebaseio.com/');
// const userInfo = new Firebase('https://arrowlense2-0.firebaseio.com/users/');
var users = userRef.child('users');

export default React.createClass({

  contextTypes: {    //get editable value from parent.
    user: React.PropTypes.string,
    setCurrentUserId: React.PropTypes.func,
    router: React.PropTypes.object.isRequired,
  },

  handleLogout: function(event) {
    event.preventDefault();
    userRef.unauth();
    this.context.setCurrentUserId('');
    alert('Successfully logged out.')
    this.context.router.push('/');
  },
  render: function() {
    if (this.context.user !== '') {
      return(

<Link to="/user">{this.context.user}</Link>

 LOGOUT

      )
    } else {
      return(

              SIGNUP

<Link to="/instructor_signup">Instructor Signup</Link>

<Link to="/student_signup">Student Signup</Link>

          {/*
<Link to="/signup"> SIGNUP</Link>
*/}

<Link to="/login"> LOGIN</Link>

      )
    }
  }
});


text:
# About
NokDoc CLI Tool built to interact with Nokia (fALU) [documentation portal](https://support.alcatel-lucent.com) in a CLI fashion.

It exposes to a user a set of commands and options for the following
high-level tasks:
- Build an HTML document with a list of all documentation entries for selected product/release. [Example](https://nokdoc.github.io/docs/nuage/nokdoc__NUAGE__4.0.R6.1.html);
- Download a zipped collection with documents for selected product/release;
- Query the documentation server about available releases for a given product/release.

Check out [NokDoc Lib](https://nokdoc.github.io) site where HTML files grabbed by NokDoc were manually aggregated per product family.

# How to install NokDoc CLI Tool
A proper way to install Python CLI tools would be by using a virtual environment.
One of the main reasons to do so is to keep your system-packages clean and consistent. I urge you to embrace the power of [pipsi](https://github.com/mitsuhiko/pipsi) tool that capable of install any Python CLI tool in a separate virtualenv and take care of all the internal links.

If you do not care much about your system-wide Python packages you can skip pipsi installation and install NokDoc with plain pip: `pip3 install nokdoc` (just make sure to use pip for python3).

## Installing pipsi
### Prerequisites
You have to have `virtualenv` package installed to install pipsi. If have a clean system with no virtualenv or pip installed the easiest way to install necessary things would be:
```
## Debian-based. For example Ubuntu 14.0.5
sudo apt-get update
sudo apt-get install python3-pip
sudo pip3 install virtualenv

## RHEL-based (Centos 7)
sudo yum -y install https://centos7.iuscommunity.org/ius-release.rpm
sudo yum install python35u
sudo yum install python35u-pip
sudo pip3.5 install virtualenv
```
### Installing pipsi
Then use installation script provided via pipsi github package
```shell
curl https://raw.githubusercontent.com/mitsuhiko/pipsi/master/get-pipsi.py | python3
```
Pay attention to the python interpreter version after the pipe. NokDoc has been tested with `python3` that is why `python3` interpreter should be used to install pipsi. On your installation there might not be `python3` but `python3.5` executable. Yes, it works with `python2.7`, but I do not test it.

Also ensure that you have met pipsi requirement to add additional path to your `PATH` env. variable. On Mac OS and Ubuntu systems pipsi might tell you how to do that in the end of its installation process:
```shell
Warning:
  It looks like /home/vagrant/.local/bin is not on your PATH so pipsi will
  not work out of the box.  To fix this problem make sure to
  add this to your .bashrc / .profile file:

  export PATH=/home/vagrant/.local/bin:$PATH

# adding new path to $PATH
echo "export PATH=/home/vagrant/.local/bin:$PATH" >> ~/.profile
# (re-open your session to changes take effect)
# or issue "source ~/.profile"
```

## Installing NokDoc
Once you have pipsi installed you can safely install NokDoc:
```
pipsi install nokdoc
```

# How to use NokDoc
NokDoc has built-in help:
```
rdodin@vbox:~$ nokdoc
Usage: nokdoc [OPTIONS] COMMAND [ARGS]...

  NokDoc CLI Tool is exposing a set of commands to interact with Nokia
  documentation portal. It offers CLI experience for tasks like - getting
  links to the docs aggregated into HTML file - downloading docs collections
  automatically

  It works for authorized users and guests.

Options:
  -l, --login TEXT  Put in your login to get access to thedocumentation
                    requiring authorization
  -p, --proxy TEXT
  --help            Show this message and exit.

Commands:
  batchgetlinks  Invokes getlinks command for a list of...
  getdocs        Downloads documentation collection for a...
  getlinks       Gets a single HTML file with links to the...
  htmlfix        Renames Nuage documentation directories from...
  showrels       Lists all available releases for a given...
```
Let's explore what can be done with NokDoc.
### Guest access and logged users
Nokia documentation falls into two categories: one that can be accessed without registration and other that will ask for a login.
NokDoc allows a user to work as a guest (i.e. non logged in) and in authorized mode.

Unauthorized users will be able to receive only those documents which are open.

If you have a login to the documentation portal then simply pass your login to run NokDoc commands in the authorized mode with optional `-l <username>` parameter:
```
nokdoc -l <username> COMMAND [OPTIONS]
```
NokDoc will prompt you for your password and authorize you with the documentation server.
## Getting HTML file with links to documentation
One feature of NokDoc is to build HTML files with the direct links to the documentation articles. An example of such a page can be found [here](https://nokdoc.github.io/docs/7750sr/nokdoc__7750SR__14.0.html). The idea was to save such files locally to keep the whole documentation at hand.
```
nokdoc -l <username> getlinks -p <product_name> -r <release>
```
Each command has its own help section with optional parameters explained:
```
rdodin@vbox:~$ nokdoc getlinks --help
Usage: nokdoc getlinks [OPTIONS]

  Gets a single HTML file with links to the documetation elements for a
  given product.

Options:
  -p, --product [1350oms|5620sam|7210sas|7450ess|7705sar|7750sr|7850-8vsg|7850vsa|7850vsg|7950xrs|nuage|nuage-vns|nuage-vsp|vsr]
                                  [required]
  -r, --release TEXT              Release version, use "showrels" command to
                                  list them
  -f, --format [pdf|html|zip]     Specify documentation format to fetch.If
                                  unspecified -> all types will be collected.
  -s, --sort [title|issue_date]   Choose sorting key. Defaults to "title"
  --help                          Show this message and exit.
```
As you see there are some filtering options, though in practice you most probably will need just `--product` and `--release` to filter docs for a particular release of a given product:
```
# this will build an HTML file with docs available for everyone
# since no login option was passed
nokdoc getlinks -p 7750sr -r 14.0
```
## Downloading documentation collection
Another feature of NokDoc is being able to generate request to the documentation server for collection generation and automatically download it once it is available.

This makes for those product families who has no zip collections provided as a part of documentation set.
```
# for example this one will try to download a collection
# for nuage-vns release 4.0.R4 (pdf files only)
nokdoc -l rdodin getdocs -p nuage-vns -r 4.0.r4 -f pdf
```
Again, options can be explored via built-in help page:
```
rdodin@vbox:~$ nokdoc getdocs --help
Usage: nokdoc getdocs [OPTIONS]

  Downloads documentation collection for a given product family. Optionally
  specify release version to fetch OPtionally specify format of the docs to
  fetch

  Currently supported products: nuage, nuage-vsp, nuage-vns

Options:
  -p, --product [1350oms|5620sam|7210sas|7450ess|7705sar|7750sr|7850-8vsg|7850vsa|7850vsg|7950xrs|nuage|nuage-vns|nuage-vsp|vsr]
                                  [required]
  -r, --release TEXT              Release version, use "showrels" command to
                                  list them
  -f, --format [pdf|html|zip]     Specify documentation format to fetch.If
                                  unspecified -> all types will be collected.
  --help                          Show this message and exit.
```
## Batch getlinks operation
To be able to (re)generate every doc for [nokdoc.github.io](https://nokdoc.github.io)
a `batchgetlinks` command has been introduced. It opens a configuration file in
YAML format that contains products and releases one need to get documentation links for.
Example of such config file:
```
7850vsg:
  releases:
    -
7950xrs:
  releases:
    - "14.0"
    - "13.0"
    - "12.0"
    - "11.0"
```
This file dictates the following: get documentation links for:
- product 7850vsg which has no releases
- product 7950xrs for the stated releases

Effectively you will end up with total of 5 HTML files (one for each pair of (product, release))
grouped under `docs/[product]`.

Under the hood `batchgetlinks` command Invokes `getlinks` command with
appropriate product and release as inputs.

Refer to this command for example of execution:
```
nokdoc -l <username> batchgetlinks batchgetlinks.yml
```
Here batchgetlinks.yml file exists in the current working directory.
## Exploring available releases
Obviously almost everytime each command refers to some release for a given product. Yet it is not obvious what releases and in what numbering convention are available to pass into `--release` option.

For this purpose another small command was introduced:
```
# listing all available releases for 7750SR family
[vagrant@localhost ~]$ nokdoc showrels -p 7750sr

  ####### SHOW RELEASES #######
  Checking available releases...
  Available releases for 7750sr family: 4.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, Arbor6.0, Arbor7.0, Arbor7.5, ArborCP5.7, ArborCP5.8p3, ArborCP5.8p4, ArborTMS5.6.P5, ArborTMS5.7.P4, ArborTMS5.8, arborTMS5.8P4, ArborTMS5.8P5, MG3.1, MG4.0, MG5.0, MG6.0, MG7.0, MG8.0
```
## Fixing documentation directories names
Once you have downloaded Nuage documentation in html format, you might get lost once you peer into the unarchived directory:
```shell
rdodin@pc /d/System/Downloads/unarchived_docs
$ ls
3HE09895AAAN/  3HE10726AAAI/  3HE10733AAAI/  3HE11477AAAD/  README.txt
3HE10560AAAI/  3HE10727AAAI/  3HE10736AAAI/  3HE11593AAAC/
3HE10723AAAI/  3HE10730AAAI/  3HE10933AAAI/  3HE11966AAAB/
3HE10724AAAI/  3HE10731AAAI/  3HE10974AAAI/  3HE12055AAAB/
3HE10725AAAI/  3HE10732AAAI/  3HE11202AAAG/  3HE12105AAAA/
```
I am still in the process of learning all the `doc-id --> doc-title` so to help myself I incorporated a `htmlfix` command which will decode the directories names to human-readable versions:
```shell
rdodin@pc /d/System/Downloads/unarchived_docs
$ ls
Nuage_7850_VSA-8_Installation_Guide/
Nuage_7850_VSA-VSG_Installation_Guide/
Nuage_Docker_Integration_Guide/
Nuage_Kubernetes_Integration_Guide/
Nuage_Mesos_Integration_Guide/
Nuage_OpenShift_Integration_Guide/
# <omitted for brevity>
```
There are two possible options to do such a rename depending on what format do you keep your docs in:

### **1 You have a zipped archive with docs**
If you just downloaded an archive with HTML dirs inside and want to keep it in archive just with the proper names, navigate nokdoc to the archive like this:
```shell
 $ nokdoc htmlfix -p /d/System/Downloads/nokdoc__NUAGE__4.0.R8__HTML__2017_04_01.zip

  ####### HTML DOC FIX #######

  Processing a zip archive "D:/System/Downloads/nokdoc__NUAGE__4.0.R8__HTML__2017_04_01.zip"...
  Successfully unzipped documentation archive...
  Archiving renamed documents...
.
  Removing temporary files...
  Successfully created archive with renamed documents!
    --> D:/System/Downloads/nokdoc__NUAGE__4.0.R8__HTML__2017_04_01.zip
```
Now your original archive **will be rewritten** and contain meaningful directory names instead of original ones.
### **2 You have an unzipped directory with docs**
If you already unarchived docs and want to just rename the dirs, point nokdoc to the parent directory like in the following example:
```
$ nokdoc htmlfix -p /d/System/Downloads/unarchived_docs/

  ####### HTML DOC FIX #######

  Processing a directory "D:/System/Downloads/unarchived_docs/" with docs inside...
  Renamed doc dirs in the "D:\System\Downloads\unarchived_docs" directory...
```
# Contribution or requests?
If you have some opinions regarding this tool or would like to propose a feature request -- create an **Issue** and we will have a chat about it.
## How can I help?
If you would like to contribute feel free to clone this repo and come up will pull request. Right now I have some features in mind you can possibly help me with:
### New documentation releases tracking.
This task is twofold. On a global scale we need to track if new release branch
has been pushed to documentation portal. For instance `nokdoc showrels -p PRODUCT`
will list all available releases. We need to check what releases were used by
`batchgetlinks` command execution and compare it to the current list of releases.

Sometimes docs get updated. This means that it is good to know if some doc
has been updated inside every release trunk. This can be checked by Issue Date
field.
### Nokdoc server edition
A possible solution to eliminate checking for updated docs is to run `batchgetlinks`
on a daily basis.
### Design enhancements
If you feel like current design can be improved, share your templates/thoughts