text:
import { ConsistencyCheckComponent } from 'app/shared/consistency-check/consistency-check.component';
import { ConsistencyCheckService } from 'app/shared/consistency-check/consistency-check.service';
import { ProgrammingExercise } from 'app/entities/programming-exercise.model';
import { Course } from 'app/entities/course.model';
import { ConsistencyCheckError, ErrorType } from 'app/entities/consistency-check-result.model';
import { ArtemisTestModule } from '../../test.module';
import { TranslateDirective } from 'app/shared/language/translate.directive';
import { AlertService } from 'app/core/util/alert.service';
import { of } from 'rxjs';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MockDirective, MockPipe, MockProvider } from 'ng-mocks';
import { TranslateService } from '@ngx-translate/core';
import { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe';
import { NgbHighlight } from '@ng-bootstrap/ng-bootstrap';
import { MockRouterLinkDirective } from '../../helpers/mocks/directive/mock-router-link.directive';

describe('ConsistencyCheckComponent', () => {
    let component: ConsistencyCheckComponent;
    let fixture: ComponentFixture<ConsistencyCheckComponent>;
    let service: ConsistencyCheckService;

    const course = { id: 123, exercises: [] } as Course;
    const programmingExercise = new ProgrammingExercise(course, undefined);
    programmingExercise.id = 456;
    const programmingExercise2 = new ProgrammingExercise(course, undefined);
    programmingExercise.id = 567;
    const error1 = new ConsistencyCheckError();
    error1.programmingExercise = programmingExercise;
    error1.type = ErrorType.TEMPLATE_BUILD_PLAN_MISSING;
    const error2 = new ConsistencyCheckError();
    error2.programmingExercise = programmingExercise;
    error2.type = ErrorType.SOLUTION_BUILD_PLAN_MISSING;

    const consistencyErrors = [error1, error2];
    const programmingExercises = [programmingExercise, programmingExercise2];

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [ArtemisTestModule],
            declarations: [ConsistencyCheckComponent, MockDirective(TranslateDirective), MockPipe(ArtemisTranslatePipe), MockDirective(NgbHighlight), MockRouterLinkDirective],
            providers: [MockProvider(TranslateService), MockProvider(AlertService), MockProvider(ConsistencyCheckService)],
        })
            .compileComponents()
            .then(() => {
                fixture = TestBed.createComponent(ConsistencyCheckComponent);
                component = fixture.componentInstance;
                service = TestBed.inject(ConsistencyCheckService);
            });
    });

    afterEach(() => {
        jest.restoreAllMocks();
    });

    it('should call checks for single programming exercise', () => {
        // GIVEN
        const checkConsistencyForProgrammingExerciseStub = jest.spyOn(service, 'checkConsistencyForProgrammingExercise').mockReturnValue(of(consistencyErrors));

        // WHEN
        component.exercisesToCheck = Array.of(programmingExercise);
        fixture.detectChanges();

        // THEN
        expect(checkConsistencyForProgrammingExerciseStub).toHaveBeenCalledTimes(1);
        expect(component.inconsistencies).toEqual(consistencyErrors);
    });

    it('should call checks for multiple programming exercises', () => {
        // GIVEN
        const checkConsistencyForProgrammingExerciseStub = jest.spyOn(service, 'checkConsistencyForProgrammingExercise').mockReturnValue(of(consistencyErrors));

        // WHEN
        component.exercisesToCheck = programmingExercises;
        fixture.detectChanges();

        // THEN
        expect(checkConsistencyForProgrammingExerciseStub).toHaveBeenCalledTimes(2);
        expect(component.inconsistencies).toEqual(consistencyErrors.concat(consistencyErrors));
    });
});


text:
require 'singleton'

module Batchit
  module Context

    mattr_reader :model_infile_map,:model_shadow_map,:model_updates_map
    @@model_infile_map,@@model_shadow_map,@@model_updates_map = {},{},{}

    def self.add_model(model)
      add_infile(model) if add_shadow(model)
    end

    # INFILE methods

    def self.infile_root
      Rails.root
    end

    def self.add_infile(model)
      raise "infile already exists for #{model}" if @@model_infile_map[model]
      @@model_infile_map[model] = Infile.new(model)
    end

    def self.start_batching_all_models
      @@model_infile_map.keys.collect(&:start_batching)
    end

    def self.stop_batching_all_models
      @@model_infile_map.keys.collect(&:stop_batching)
    end

    # SHADOW methods

    def self.sync_all_models
      #:nocov: this cannot be tested since the setup for the other tests means NOT insisting on a fully-synced environment
      ensure_shadow_for_all_models
      cleanup_unused_shadows
      #:nocov:
    end

    def self.ensure_shadow_for_all_models
      #:nocov: this cannot be tested since the setup for the other tests means NOT insisting on a fully-synced environment
      ActiveRecord::Base.connection.tables.each do |table_name|
        model_class_name = table_name.singularize.classify
        next unless model_class = eval(model_class_name) rescue nil

        model_class.ensure_shadow if model_class.respond_to?(:ensure_shadow)
      end
      #:nocov:
    end

    def self.cleanup_unused_shadows
      ActiveRecord::Base.connection.tables.each do |shadow_table_name|
        next unless shadow_table_name =~ /^(.*)_shadows$/

        model_name_part = $1
        model_table_name = model_name_part.pluralize
        model_class_name = model_name_part.classify
        shadow_class_name = shadow_table_name.singularize.classify
        if not (model_class = eval(model_class_name) rescue nil)
          puts "WARNING: Shadow table #{shadow_table_name} exists but no model class #{model_class_name} exists; drop this table yourself, just in case!"
        elsif not @@model_shadow_map.keys.include?(model_class)
          puts "NOTE: Dropping shadow table #{shadow_table_name} and resetting auto-increment for #{model_table_name}"
          puts "WARNING: Could not reset auto-increment for #{model_table_name}; please investigate!" unless ensure_auto_increment(model_class,true)
          ActiveRecord::Base.connection.drop_table(shadow_table_name) rescue puts "WARNING: could not drop #{shadow_table_name}; please investigate!"
        elsif not @@model_shadow_map[model_class]
          puts "WARNING: Shadow class #{shadow_class_name} should exist for #{model_class}, but is missing; please investigate!"
        end
      end
    end

    def self.sync_model(model)
      if not @@model_shadow_map[model] and ensure_shadow_table_exists(model,true) and ensure_no_auto_increment(model,true)
        add_model(model)

        if model.shadow.nil?
          #:nocov: remove when we can figure out how to test; see TODO
          puts "WARNING: Unable to ensure shadow class for #{model}; please investigate!"
          #:nocov:
        elsif (max_id = model.maximum(model.primary_key)) and max_id >= (shadow_id = model.shadow.next_id)
          #:nocov: remove when we can figure out how to test; see TODO
          puts "NOTE: For #{model}, the shadow class had next_id of #{shadow_id} but the model has max_id of #{max_id}, updating..."
          set_auto_increment_for_table(model,model.shadow.table_name)
          #:nocov:
        end

        puts "NOTE: Batching now enabled for #{model}"
      end
    end

    def self.add_shadow(model)
      raise "shadow already exists for #{model}" if @@model_shadow_map[model]
      if not ensure_shadow_table_exists(model)
        puts "WARNING: Batchit model #{model} has no shadow class; batching is disabled"
      elsif not ensure_no_auto_increment(model)
        puts "WARNING: Batchit model #{model} is still auto-increment; batching is disabled"
      else
        shadow_class = instantiate_shadow_class(model)
      end
      @@model_shadow_map[model] = shadow_class
    end

    def self.ensure_shadow_table_exists(model,force = false)
      return true if shadow_table_exists?(model)
      return false unless force

      shadow_table_name = shadow_table_name_for_model(model)
      ActiveRecord::Schema.define{create_table(shadow_table_name)}
      set_auto_increment_for_table(model,shadow_table_name)
      true
    end

    def self.ensure_no_auto_increment(model,force = false)
      return true unless row = detect_primary_key(model,true)
      return false unless force

      model.connection.execute "alter table #{model.table_name} change #{row[0]} #{row[0]} #{row[1]} not null"
      true
    end

    def self.ensure_auto_increment(model,force = false)
      return true unless row = detect_primary_key(model,false)
      return false unless force

      model.connection.execute "alter table #{model.table_name} change #{row[0]} #{row[0]} #{row[1]} not null auto_increment"
      set_auto_increment_for_table(model,model.table_name)
      true
    end

    def self.instantiate_shadow_class(model)
      eval %(class ::#{model}Shadow < ActiveRecord::Base; def self.next_id; result = unscoped.insert({}); where(id: result).delete_all; result; end; end)
      eval %(::#{model}Shadow)
    end

    def self.shadow_table_exists?(model)
      model.connection.table_exists?(shadow_table_name_for_model(model))
    end

    def self.detect_primary_key(model,equal)
      model.connection.select_rows("show columns from #{model.table_name} where extra #{equal ? '=' : '!='} 'auto_increment'").detect{|row| row[0] == model.primary_key}
    end

    def self.shadow_table_name_for_model(model)
      "#{model.table_name.singularize}_shadows"
    end

    def self.set_auto_increment_for_table(model,table_name)
      model.connection.execute "alter table #{table_name} auto_increment = #{(model.maximum(model.primary_key) || 0) + 1}"
    end

  end
end

redpajama_set_name: RedPajamaGithub


text:
<?php defined('SYSPATH') OR die('No direct script access.');

/**
 * This class provides a way to access the scheme for a MySQL database.
 *
 * @package Leap
 * @category MySQL
 * @version 2013-02-01
 *
 * @abstract
 */
abstract class Base_DB_MySQL_Schema extends DB_Schema {

	/**
	 * This function returns an associated array of default properties for the specified
	 * SQL data type.
	 *
	 * @access public
	 * @override
	 * @param string $type                   the SQL data type
	 * @return array                         an associated array of default properties
	 *                                       for the specified data type
	 *
	 * @license http://kohanaframework.org/license
	 *
	 * @see http://dev.mysql.com/doc/refman/5.0/en/data-types.html
	 */
	public function data_type($type) {
		static $types = array(
			'BLOB'                            => array('type' => 'Blob', 'max_length' => 65535),
			'BOOL'                            => array('type' => 'Boolean'),
			'BIGINT UNSIGNED'                 => array('type' => 'Integer', 'range' => array(0, '18446744073709551615')),
			'DEC UNSIGNED'                    => array('type' => 'Decimal', 'range' => array(0, NULL)),
			'DECIMAL UNSIGNED'                => array('type' => 'Decimal', 'range' => array(0, NULL)),
			'DOUBLE PRECISION UNSIGNED'       => array('type' => 'Double', 'range' => array(0, NULL)),
			'DOUBLE UNSIGNED'                 => array('type' => 'Double', 'range' => array(0, NULL)),
			'ENUM'                            => array('type' => 'String'),
			'FIXED'                           => array('type' => 'Double'),
			'FIXED UNSIGNED'                  => array('type' => 'Double', 'range' => array(0, NULL)),
			'FLOAT UNSIGNED'                  => array('type' => 'Double', 'range' => array(0, NULL)),
			'INT UNSIGNED'                    => array('type' => 'Integer', 'range' => array(0, '4294967295')),
			'INTEGER UNSIGNED'                => array('type' => 'Integer', 'range' => array(0, '4294967295')),
			'LONGBLOB'                        => array('type' => 'Blob', 'max_length' => '4294967295'),
			'LONGTEXT'                        => array('type' => 'Text', 'max_length' => '4294967295'),
			'MEDIUMBLOB'                      => array('type' => 'Blob', 'max_length' => 16777215),
			'MEDIUMINT'                       => array('type' => 'Integer', 'range' => array(-8388608, 8388607)),
			'MEDIUMINT UNSIGNED'              => array('type' => 'Integer', 'range' => array(0, 16777215)),
			'MEDIUMTEXT'                      => array('type' => 'Text', 'max_length' => 16777215),
			'NUMERIC UNSIGNED'                => array('type' => 'Decimal', 'range' => array(0, NULL)),
			'POINT'                           => array('type' => 'Binary'),
			'REAL UNSIGNED'                   => array('type' => 'Double', 'range' => array(0, NULL)),
			'SERIAL'                          => array('type' => 'Integer', 'range' => array(0, '18446744073709551615')),
			'SET'                             => array('type' => 'String'),
			'SMALLINT UNSIGNED'               => array('type' => 'Integer', 'range' => array(0, 65535)),
			'TEXT'                            => array('type' => 'Text', 'max_length' => 65535),
			'TINYBLOB'                        => array('type' => 'Blob', 'max_length' => 255),
			'TINYINT UNSIGNED'                => array('type' => 'Integer', 'range' => array(0, 255)),
			'TINYTEXT'                        => array('type' => 'String', 'max_length' => 255),
			'YEAR'                            => array('type' => 'String'),
		);

		$type = strtoupper($type);
		$type = trim(preg_replace('/ ZEROFILL/i', '', $type));

		if (isset($types[$type])) {
			return $types[$type];
		}

		return parent::data_type($type);
	}

	/**
	 * This function returns a result set of fields for the specified table.
	 *
	 * +---------------+---------------+------------------------------------------------------------+
	 * | field         | data type     | description                                                |
	 * +---------------+---------------+------------------------------------------------------------+
	 * | schema        | string        | The name of the schema that contains the table.            |
	 * | table         | string        | The name of the table.                                     |
	 * | column        | string        | The name of the column.                                    |
	 * | type          | string        | The data type of the column.                               |
	 * | max_length    | integer       | The max length, max digits, or precision of the column.    |
	 * | max_decimals  | integer       | The max decimals or scale of the column.                   |
	 * | attributes    | string        | Any additional attributes associated with the column.      |
	 * | seq_index     | integer       | The sequence index of the column.                          |
	 * | nullable      | boolean       | Indicates whether the column can contain a NULL value.     |
	 * | default       | mixed         | The default value of the column.                           |
	 * +---------------+---------------+------------------------------------------------------------+
	 *
	 * @access public
	 * @override
	 * @param string $table                 the table to evaluated
	 * @param string $like                  a like constraint on the query
	 * @return DB_ResultSet                 an array of fields within the specified
	 *                                      table
	 *
	 * @see http://dev.mysql.com/doc/refman/5.5/en/show-columns.html
	 */
	public function fields($table, $like = '') {
		$connection = DB_Connection_Pool::instance()->get_connection($this->data_source);

		$schema = $this->precompiler->prepare_identifier($this->data_source->database);
		$table = $this->precompiler->prepare_identifier($table);

		$sql = "SHOW FULL COLUMNS FROM {$table} FROM {$schema}";

		if ( ! empty($like)) {
			$sql .= ' WHERE `Field` LIKE ' . $this->precompiler->prepare_value($like);
		}

		$sql .= ';';

		$reader = $connection->reader($sql);

		$records = array();
		$position = 0;

		while ($reader->read()) {
			$buffer = $reader->row('array');
			$type = $this->parse_type($buffer['Type']);
			$position++;
			$default = $buffer['Default'];
			if ($default == 'NULL') {
				$default = NULL;
			}
			$record = array(
				'schema' => $this->data_source->database,
				'table' => $table,
				'column' => $buffer['Field'],
				'type' => $type[0],
				'max_length' => $type[1], // max_digits, precision
				'max_decimals' => $type[2], // scale
				'attributes' => $buffer['Extra'],
				'seq_index' => $position,
				'nullable' => ($buffer['Null'] == 'YES'),
				'default' => $default,
			);
			$records[] = $record;
		}

		$reader->free();

		$results = new DB_ResultSet($records);

		return $results;
	}

	/**
	 * This function returns a result set of indexes for the specified table.
	 *
	 * +---------------+---------------+------------------------------------------------------------+
	 * | field         | data type     | description                                                |
	 * +---------------+---------------+------------------------------------------------------------+
	 * | schema        | string        | The name of the schema that contains the table.            |
	 * | table         | string        | The name of the table.                                     |
	 * | index         | string        | The name of the index.                                     |
	 * | column        | string        | The name of the column.                                    |
	 * | seq_index     | integer       | The sequence index of the index.                           |
	 * | ordering      | string        | The ordering of the index.                                 |
	 * | unique        | boolean       | Indicates whether index on column is unique.               |
	 * | primary       | boolean       | Indicates whether index on column is a primary key.        |
	 * +---------------+---------------+------------------------------------------------------------+
	 *
	 * @access public
	 * @override
	 * @param string $table                 the table to evaluated
	 * @param string $like                  a like constraint on the query
	 * @return DB_ResultSet                 a result set of indexes for the specified
	 *                                      table
	 *
	 * @see http://dev.mysql.com/doc/refman/5.6/en/show-index.html
	 */
	public function indexes($table, $like = '') {
		$connection = DB_Connection_Pool::instance()->get_connection($this->data_source);

		$schema = $this->precompiler->prepare_identifier($this->data_source->database);
		$table = $this->precompiler->prepare_identifier($table);

		$sql = "SHOW INDEXES FROM {$table} FROM {$schema}";

		if ( ! empty($like)) {
			$sql .= ' WHERE `Key_name` LIKE ' . $this->precompiler->prepare_value($like);
		}

		$sql .= ';';

		$reader = $connection->reader($sql);

		$records = array();

		while ($reader->read()) {
			$buffer = $reader->row('array');
			$record = array(
				'schema' => $this->data_source->database,
				'table' => $buffer['Table'],
				'index' => $buffer['Key_name'],
				'column' => $buffer['Column_name'],
				'seq_index' => $buffer['Seq_in_index'],
				'ordering' => ($buffer['Collation'] == 'A') ? 'ASC' : NULL,
				'unique' => ($buffer['Non_unique'] == '0'),
				'primary' => ($buffer['Key_name'] == 'PRIMARY'),
			);
			$records[] = $record;
		}

		$reader->free();

		$results = new DB_ResultSet($records);

		return $results;
	}

	/**
	 * This function returns a result set of database tables.
	 *
	 * +---------------+---------------+------------------------------------------------------------+
	 * | field         | data type     | description                                                |
	 * +---------------+---------------+------------------------------------------------------------+
	 * | schema        | string        | The name of the schema that contains the table.            |
	 * | table         | string        | The name of the table.                                     |
	 * | type          | string        | The type of table.                                         |
	 * +---------------+---------------+------------------------------------------------------------+
	 *
	 * @access public
	 * @override
	 * @param string $like                  a like constraint on the query
	 * @return DB_ResultSet                 a result set of database tables
	 *
	 * @see http://www.geeksww.com/tutorials/database_management_systems/mysql/tips_and_tricks/mysql_query_to_find_all_views_in_a_database.php
	 */
	public function tables($like = '') {
		$builder = DB_SQL::select($this->data_source)
			->column('TABLE_SCHEMA', 'schema')
			->column('TABLE_NAME', 'table')
			->column(DB_SQL::expr("'BASE'"), 'type')
			->from('INFORMATION_SCHEMA.TABLES')
			//->where('TABLE_SCHEMA', DB_SQL_Operator::_EQUAL_TO_, $this->data_source->database)
			->where(DB_SQL::expr('UPPER(`TABLE_TYPE`)'), DB_SQL_Operator::_EQUAL_TO_, 'BASE_TABLE')
			->order_by(DB_SQL::expr('UPPER(`TABLE_SCHEMA`)'))
			->order_by(DB_SQL::expr('UPPER(`TABLE_NAME`)'));

		if ( ! empty($like)) {
			$builder->where('TABLE_NAME', DB_SQL_Operator::_LIKE_, $like);
		}

		return $builder->query();
	}

	/**
	 * This function returns a result set of triggers for the specified table.
	 *
	 * +---------------+---------------+------------------------------------------------------------+
	 * | field         | data type     | description                                                |
	 * +---------------+---------------+------------------------------------------------------------+
	 * | schema        | string        | The name of the schema that contains the table.            |
	 * | table         | string        | The name of the table to which the trigger is defined on.  |
	 * | trigger       | string        | The name of the trigger.                                   |
	 * | event         | string        | 'INSERT', 'DELETE', or 'UPDATE'                            |
	 * | timing        | string        | 'BEFORE', 'AFTER', or 'INSTEAD OF'                         |
	 * | per           | string        | 'ROW', 'STATEMENT', or 'EVENT'                             |
	 * | action        | string        | The action that will be triggered.                         |
	 * | seq_index     | integer       | The sequence index of the trigger.                         |
	 * | created       | date/time     | The date/time of when the trigger was created.             |
	 * +---------------+---------------+------------------------------------------------------------+
	 *
	 * @access public
	 * @override
	 * @param string $table                 the table to evaluated
	 * @param string $like                  a like constraint on the query
	 * @return DB_ResultSet                 a result set of triggers for the specified
	 *                                      table
	 *
	 * @see http://dev.mysql.com/doc/refman/5.6/en/triggers-table.html
	 * @see http://dev.mysql.com/doc/refman/5.6/en/show-triggers.html
	 */
	public function triggers($table, $like = '') {
		$builder = DB_SQL::select($this->data_source)
			->column('EVENT_OBJECT_SCHEMA', 'schema')
			->column('EVENT_OBJECT_TABLE', 'table')
			->column('TRIGGER_NAME', 'trigger')
			->column('EVENT_MANIPULATION', 'event')
			->column('ACTION_TIMING', 'timing')
			->column('ACTION_ORIENTATION', 'per')
			->column('ACTION_STATEMENT', 'action')
			->column('ACTION_ORDER', 'seq_index')
			->column('CREATED', 'created')
			->from('INFORMATION_SCHEMA.TRIGGERS')
			//->where('EVENT_OBJECT_SCHEMA', DB_SQL_Operator::_EQUAL_TO_, $this->data_source->database)
			->where(DB_SQL::expr('UPPER(`EVENT_OBJECT_TABLE`)'), DB_SQL_Operator::_EQUAL_TO_, $table)
			->order_by(DB_SQL::expr('UPPER(`EVENT_OBJECT_SCHEMA`)'))
			->order_by(DB_SQL::expr('UPPER(`EVENT_OBJECT_TABLE`)'))
			->order_by(DB_SQL::expr('UPPER(`TRIGGER_NAME`)'))
			->order_by('ACTION_ORDER');

		if ( ! empty($like)) {
			$builder->where('TRIGGER_NAME', DB_SQL_Operator::_LIKE_, $like);
		}

		return $builder->query();
	}

	/**
	 * This function returns a result set of database views.
	 *
	 * +---------------+---------------+------------------------------------------------------------+
	 * | field         | data type     | description                                                |
	 * +---------------+---------------+------------------------------------------------------------+
	 * | schema        | string        | The name of the schema that contains the table.            |
	 * | table         | string        | The name of the table.                                     |
	 * | type          | string        | The type of table.                                         |
	 * +---------------+---------------+------------------------------------------------------------+
	 *
	 * @access public
	 * @override
	 * @param string $like                  a like constraint on the query
	 * @return DB_ResultSet                 a result set of database views
	 *
	 * @see http://www.geeksww.com/tutorials/database_management_systems/mysql/tips_and_tricks/mysql_query_to_find_all_views_in_a_database.php
	 */
	public function views($like = '') {
		$builder = DB_SQL::select($this->data_source)
			->column('TABLE_SCHEMA', 'schema')
			->column('TABLE_NAME', 'table')
			->column(DB_SQL::expr("'VIEW'"), 'type')
			->from('INFORMATION_SCHEMA.TABLES')
			//->where('TABLE_SCHEMA', DB_SQL_Operator::_EQUAL_TO_, $this->data_source->database)
			->where(DB_SQL::expr('UPPER(`TABLE_TYPE`)'), DB_SQL_Operator::_EQUAL_TO_, 'VIEW')
			->order_by(DB_SQL::expr('UPPER(`TABLE_SCHEMA`)'))
			->order_by(DB_SQL::expr('UPPER(`TABLE_NAME`)'));

		if ( ! empty($like)) {
			$builder->where('TABLE_NAME', DB_SQL_Operator::_LIKE_, $like);
		}

		return $builder->query();
	}

}


text:
from __future__ import absolute_import, division, print_function
__metaclass__ = type

ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'community'}

DOCUMENTATION = '''
---
module: profitbricks_volume
short_description: Create or destroy a volume.
description:
     - Allows you to create or remove a volume from a ProfitBricks datacenter. This module has a dependency on profitbricks >= 1.0.0
version_added: "2.0"
options:
  datacenter:
    description:
      - The datacenter in which to create the volumes.
    required: true
  name:
    description:
      - The name of the volumes. You can enumerate the names using auto_increment.
    required: true
  size:
    description:
      - The size of the volume.
    required: false
    default: 10
  bus:
    description:
      - The bus type.
    required: false
    default: VIRTIO
    choices: [ "IDE", "VIRTIO"]
  image:
    description:
      - The system image ID for the volume, e.g. a3eae284-a2fe-11e4-b187-5f1f641608c8. This can also be a snapshot image ID.
    required: true
  image_password:
    description:
      - Password set for the administrative user.
    required: false
    version_added: '2.2'
  ssh_keys:
    description:
      - Public SSH keys allowing access to the virtual machine.
    required: false
    version_added: '2.2'
  disk_type:
    description:
      - The disk type of the volume.
    required: false
    default: HDD
    choices: [ "HDD", "SSD" ]
  licence_type:
    description:
      - The licence type for the volume. This is used when the image is non-standard.
    required: false
    default: UNKNOWN
    choices: ["LINUX", "WINDOWS", "UNKNOWN" , "OTHER"]
  count:
    description:
      - The number of volumes you wish to create.
    required: false
    default: 1
  auto_increment:
    description:
      - Whether or not to increment a single number in the name for created virtual machines.
    default: yes
    choices: ["yes", "no"]
  instance_ids:
    description:
      - list of instance ids, currently only used when state='absent' to remove instances.
    required: false
  subscription_user:
    description:
      - The ProfitBricks username. Overrides the PB_SUBSCRIPTION_ID environment variable.
    required: false
  subscription_password:
    description:
      - THe ProfitBricks password. Overrides the PB_PASSWORD environment variable.
    required: false
  wait:
    description:
      - wait for the datacenter to be created before returning
    required: false
    default: "yes"
    choices: [ "yes", "no" ]
  wait_timeout:
    description:
      - how long before wait gives up, in seconds
    default: 600
  state:
    description:
      - create or terminate datacenters
    required: false
    default: 'present'
    choices: ["present", "absent"]

requirements: [ "profitbricks" ]
author: Matt Baldwin (baldwin@stackpointcloud.com)
'''

EXAMPLES = '''

# Create Multiple Volumes

- profitbricks_volume:
    datacenter: Tardis One
    name: vol%02d
    count: 5
    auto_increment: yes
    wait_timeout: 500
    state: present

# Remove Volumes

- profitbricks_volume:
    datacenter: Tardis One
    instance_ids:
      - 'vol01'
      - 'vol02'
    wait_timeout: 500
    state: absent

'''

import re
import time
import traceback

HAS_PB_SDK = True
try:
    from profitbricks.client import ProfitBricksService, Volume
except ImportError:
    HAS_PB_SDK = False

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.six.moves import xrange
from ansible.module_utils._text import to_native

uuid_match = re.compile(
    '[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12}', re.I)

def _wait_for_completion(profitbricks, promise, wait_timeout, msg):
    if not promise:
        return
    wait_timeout = time.time() + wait_timeout
    while wait_timeout > time.time():
        time.sleep(5)
        operation_result = profitbricks.get_request(
            request_id=promise['requestId'],
            status=True)

        if operation_result['metadata']['status'] == "DONE":
            return
        elif operation_result['metadata']['status'] == "FAILED":
            raise Exception(
                'Request failed to complete ' + msg + ' "' + str(
                    promise['requestId']) + '" to complete.')

    raise Exception(
        'Timed out waiting for async operation ' + msg + ' "' + str(
            promise['requestId']
            ) + '" to complete.')

def _create_volume(module, profitbricks, datacenter, name):
    size = module.params.get('size')
    bus = module.params.get('bus')
    image = module.params.get('image')
    image_password = module.params.get('image_password')
    ssh_keys = module.params.get('ssh_keys')
    disk_type = module.params.get('disk_type')
    licence_type = module.params.get('licence_type')
    wait_timeout = module.params.get('wait_timeout')
    wait = module.params.get('wait')

    try:
        v = Volume(
            name=name,
            size=size,
            bus=bus,
            image=image,
            image_password=image_password,
            ssh_keys=ssh_keys,
            disk_type=disk_type,
            licence_type=licence_type
            )

        volume_response = profitbricks.create_volume(datacenter, v)

        if wait:
            _wait_for_completion(profitbricks, volume_response,
                                 wait_timeout, "_create_volume")

    except Exception as e:
        module.fail_json(msg="failed to create the volume: %s" % str(e))

    return volume_response

def _delete_volume(module, profitbricks, datacenter, volume):
    try:
        profitbricks.delete_volume(datacenter, volume)
    except Exception as e:
        module.fail_json(msg="failed to remove the volume: %s" % str(e))

def create_volume(module, profitbricks):
    """
    Creates a volume.

    This will create a volume in a datacenter.

    module : AnsibleModule object
    profitbricks: authenticated profitbricks object.

    Returns:
        True if the volume was created, false otherwise
    """
    datacenter = module.params.get('datacenter')
    name = module.params.get('name')
    auto_increment = module.params.get('auto_increment')
    count = module.params.get('count')

    datacenter_found = False
    failed = True
    volumes = []

    # Locate UUID for Datacenter
    if not (uuid_match.match(datacenter)):
        datacenter_list = profitbricks.list_datacenters()
        for d in datacenter_list['items']:
            dc = profitbricks.get_datacenter(d['id'])
            if datacenter == dc['properties']['name']:
                datacenter = d['id']
                datacenter_found = True
                break

    if not datacenter_found:
        module.fail_json(msg='datacenter could not be found.')

    if auto_increment:
        numbers = set()
        count_offset = 1

        try:
            name % 0
        except TypeError as e:
            if e.message.startswith('not all'):
                name = '%s%%d' % name
            else:
                module.fail_json(msg=e.message, exception=traceback.format_exc())

        number_range = xrange(count_offset, count_offset + count + len(numbers))
        available_numbers = list(set(number_range).difference(numbers))
        names = []
        numbers_to_use = available_numbers[:count]
        for number in numbers_to_use:
            names.append(name % number)
    else:
        names = [name] * count

    for name in names:
        create_response = _create_volume(module, profitbricks, str(datacenter), name)
        volumes.append(create_response)
        _attach_volume(module, profitbricks, datacenter, create_response['id'])
        failed = False

    results = {
        'failed': failed,
        'volumes': volumes,
        'action': 'create',
        'instance_ids': {
            'instances': [i['id'] for i in volumes],
        }
    }

    return results

def delete_volume(module, profitbricks):
    """
    Removes a volume.

    This will create a volume in a datacenter.

    module : AnsibleModule object
    profitbricks: authenticated profitbricks object.

    Returns:
        True if the volume was removed, false otherwise
    """
    if not isinstance(module.params.get('instance_ids'), list) or len(module.params.get('instance_ids')) < 1:
        module.fail_json(msg='instance_ids should be a list of virtual machine ids or names, aborting')

    datacenter = module.params.get('datacenter')
    changed = False
    instance_ids = module.params.get('instance_ids')

    # Locate UUID for Datacenter
    if not (uuid_match.match(datacenter)):
        datacenter_list = profitbricks.list_datacenters()
        for d in datacenter_list['items']:
            dc = profitbricks.get_datacenter(d['id'])
            if datacenter == dc['properties']['name']:
                datacenter = d['id']
                break

    for n in instance_ids:
        if(uuid_match.match(n)):
            _delete_volume(module, profitbricks, datacenter, n)
            changed = True
        else:
            volumes = profitbricks.list_volumes(datacenter)
            for v in volumes['items']:
                if n == v['properties']['name']:
                    volume_id = v['id']
                    _delete_volume(module, profitbricks, datacenter, volume_id)
                    changed = True

    return changed

def _attach_volume(module, profitbricks, datacenter, volume):
    """
    Attaches a volume.

    This will attach a volume to the server.

    module : AnsibleModule object
    profitbricks: authenticated profitbricks object.

    Returns:
        True if the volume was attached, false otherwise
    """
    server = module.params.get('server')

    # Locate UUID for Server
    if server:
        if not (uuid_match.match(server)):
            server_list = profitbricks.list_servers(datacenter)
            for s in server_list['items']:
                if server == s['properties']['name']:
                    server = s['id']
                    break

        try:
            return profitbricks.attach_volume(datacenter, server, volume)
        except Exception as e:
            module.fail_json(msg='failed to attach volume: %s' % to_native(e), exception=traceback.format_exc())

def main():
    module = AnsibleModule(
        argument_spec=dict(
            datacenter=dict(),
            server=dict(),
            name=dict(),
            size=dict(type='int', default=10),
            bus=dict(choices=['VIRTIO', 'IDE'], default='VIRTIO'),
            image=dict(),
            image_password=dict(default=None, no_log=True),
            ssh_keys=dict(type='list', default=[]),
            disk_type=dict(choices=['HDD', 'SSD'], default='HDD'),
            licence_type=dict(default='UNKNOWN'),
            count=dict(type='int', default=1),
            auto_increment=dict(type='bool', default=True),
            instance_ids=dict(type='list', default=[]),
            subscription_user=dict(),
            subscription_password=dict(no_log=True),
            wait=dict(type='bool', default=True),
            wait_timeout=dict(type='int', default=600),
            state=dict(default='present'),
        )
    )

    if not module.params.get('subscription_user'):
        module.fail_json(msg='subscription_user parameter is required')
    if not module.params.get('subscription_password'):
        module.fail_json(msg='subscription_password parameter is required')

    subscription_user = module.params.get('subscription_user')
    subscription_password = module.params.get('subscription_password')

    profitbricks = ProfitBricksService(
        username=subscription_user,
        password=subscription_password)

    state = module.params.get('state')

    if state == 'absent':
        if not module.params.get('datacenter'):
            module.fail_json(msg='datacenter parameter is required for running or stopping machines.')

        try:
            (changed) = delete_volume(module, profitbricks)
            module.exit_json(changed=changed)
        except Exception as e:
            module.fail_json(msg='failed to set volume state: %s' % to_native(e), exception=traceback.format_exc())

    elif state == 'present':
        if not module.params.get('datacenter'):
            module.fail_json(msg='datacenter parameter is required for new instance')
        if not module.params.get('name'):
            module.fail_json(msg='name parameter is required for new instance')

        try:
            (volume_dict_array) = create_volume(module, profitbricks)
            module.exit_json(**volume_dict_array)
        except Exception as e:
            module.fail_json(msg='failed to set volume state: %s' % to_native(e), exception=traceback.format_exc())

if __name__ == '__main__':
    main()


text:
"""
================
Neuropop Example
================

A demonstration of Neuropop using simulated data

"""

########################################################

import numpy as np
import matplotlib.pyplot as plt

from spykes.ml.neuropop import NeuroPop
from spykes.utils import train_test_split

########################################################
# Create a NeuroPop object
# -----------------------------

n_neurons = 10
pop = NeuroPop(n_neurons=n_neurons, tunemodel='glm')

########################################################
# Simulate a population of neurons
# -----------------------------

n_samples = 1000
x, Y, mu, k0, k, g, b = pop.simulate(pop.tunemodel, n_samples=n_samples,
                                     winsize=400.0)

########################################################
# Split into training and testing sets
# -----------------------------

np.random.seed(42)
(Y_train, Y_test), (x_train, x_test) = train_test_split(Y, x, percent=0.5)

########################################################
# Fit the tuning curves with gradient descent
# -----------------------------

pop.fit(x_train, Y_train)

########################################################
# Predict the population activity with the fit tuning curves
# -----------------------------

Yhat_test = pop.predict(x_test)

########################################################
# Score the prediction
# -----------------------------

Ynull = np.mean(Y_train, axis=0)
pseudo_R2 = pop.score(Y_test, Yhat_test, Ynull, method='pseudo_R2')
print(pseudo_R2)

########################################################
# Plot the simulated and fit tuning curves
# -----------------------------

plt.figure(figsize=[15, 15])

for neuron in range(pop.n_neurons):
    plt.subplot(4, 3, neuron + 1)
    pop.display(x_test, Y_test[:, neuron], neuron=neuron,
                ylim=[0.8 * np.min(Y_test[:, neuron]), 1.2 *
                np.max(Y_test[:, neuron])])

plt.show()

########################################################
# Decode feature from the population activity
# -----------------------------

xhat_test = pop.decode(Y_test)

########################################################
# Visualize ground truth vs. decoded estimates
# -----------------------------

plt.figure(figsize=[6, 5])

plt.plot(x_test, xhat_test, 'k.', alpha=0.5)
plt.xlim([-1.2 * np.pi, 1.2 * np.pi])
plt.ylim([-1.2 * np.pi, 1.2 * np.pi])
plt.xlabel('Ground truth [radians]')
plt.ylabel('Decoded [radians]')
plt.tick_params(axis='y', right='off')
plt.tick_params(axis='x', top='off')
ax = plt.gca()
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

plt.figure(figsize=[15, 5])
jitter = 0.2 * np.random.rand(x_test.shape[0])
plt.subplot(132, polar=True)
plt.plot(x_test, np.ones(x_test.shape[0]) + jitter, 'ko', alpha=0.5)
plt.title('Ground truth')

plt.subplot(133, polar=True)
plt.plot(xhat_test, np.ones(xhat_test.shape[0]) + jitter, 'co', alpha=0.5)
plt.title('Decoded')
plt.show()

########################################################
# Score decoding performance
# -----------------------------

# Circular correlation
circ_corr = pop.score(x_test, xhat_test, method='circ_corr')
print('Circular correlation: %f' % (circ_corr))

########################################################

# Cosine distance
cosine_dist = pop.score(x_test, xhat_test, method='cosine_dist')
print('Cosine distance: %f' % (cosine_dist))


text:
<?php

/**
 * @author     Mike Naberezny <mike@maintainable.com>
 * @author     Derek DeVries <derek@maintainable.com>
 * @author     Chuck Hagenbuch <chuck@horde.org>
 * @license    http://opensource.org/licenses/bsd-license.php
 * @category   Horde
 * @package    Horde_Db
 * @subpackage Adapter
 */
class Horde_Db_Adapter_Postgresql_Column extends Horde_Db_Adapter_Abstract_Column
{
    /*##########################################################################
    # Constants
    ##########################################################################*/

    /**
     * The internal PostgreSQL identifier of the money data type.
     * @const integer
     */
    const MONEY_COLUMN_TYPE_OID = 790;

    /**
     * @var integer
     */
    public static $moneyPrecision = 19;

    /**
     * @var array
     */
    protected static $_hasEmptyStringDefault = array('binary', 'string', 'text');

    /**
     * Construct
     * @param   string  $name
     * @param   string  $default
     * @param   string  $sqlType
     * @param   boolean $null
     */
    public function __construct($name, $default, $sqlType=null, $null=true)
    {
        parent::__construct($name, $this->_extractValueFromDefault($default), $sqlType, $null);
    }

    /**
     * @param   string  $fieldType
     * @return  string
     */
    protected function _simplifiedType($fieldType)
    {
        switch (true) {
            // Numeric and monetary types
            case preg_match('/^(?:real|double precision)$/', $fieldType):
                return 'float';
            // Monetary types
            case preg_match('/^money$/', $fieldType):
                return 'decimal';
            // Character types
            case preg_match('/^(?:character varying|bpchar)(?:\(\d+\))?$/', $fieldType):
                return 'string';
            // Binary data types
            case preg_match('/^bytea$/', $fieldType):
                return 'binary';
            // Date/time types
            case preg_match('/^timestamp with(?:out)? time zone$/', $fieldType):
                return 'datetime';
            case preg_match('/^interval$/', $fieldType):
                return 'string';
            // Geometric types
            case preg_match('/^(?:point|line|lseg|box|"?path"?|polygon|circle)$/', $fieldType):
                return 'string';
            // Network address types
            case preg_match('/^(?:cidr|inet|macaddr)$/', $fieldType):
                return 'string';
            // Bit strings
            case preg_match('/^bit(?: varying)?(?:\(\d+\))?$/', $fieldType):
                return 'string';
            // XML type
            case preg_match('/^xml$/', $fieldType):
                return 'string';
            // Arrays
            case preg_match('/^\D+\[\]$/', $fieldType):
                return 'string';
            // Object identifier types
            case preg_match('/^oid$/', $fieldType):
                return 'integer';
        }

        // Pass through all types that are not specific to PostgreSQL.
        return parent::_simplifiedType($fieldType);
    }

    /**
     * Extracts the value from a PostgreSQL column default definition.
     */
    protected function _extractValueFromDefault($default)
    {
        switch (true) {
            // Numeric types
            case preg_match('/\A-?\d+(\.\d*)?\z/', $default):
                return $default;
            // Character types
            case preg_match('/\A\'(.*)\'::(?:character varying|bpchar|text)\z/m', $default, $matches):
                return $matches[1];
            // Character types (8.1 formatting)
            case preg_match('/\AE\'(.*)\'::(?:character varying|bpchar|text)\z/m', $default, $matches):
                /*@TODO fix preg callback*/
                return preg_replace('/\\(\d\d\d)/', '$1.oct.chr', $matches[1]);
            // Binary data types
            case preg_match('/\A\'(.*)\'::bytea\z/m', $default, $matches):
                return $matches[1];
            // Date/time types
            case preg_match('/\A\'(.+)\'::(?:time(?:stamp)? with(?:out)? time zone|date)\z/', $default, $matches):
                return $matches[1];
            case preg_match('/\A\'(.*)\'::interval\z/', $default, $matches):
                return $matches[1];
            // Boolean type
            case $default == 'true':
                return true;
            case $default == 'false':
                return false;
            // Geometric types
            case preg_match('/\A\'(.*)\'::(?:point|line|lseg|box|"?path"?|polygon|circle)\z/', $default, $matches):
                return $matches[1];
            // Network address types
            case preg_match('/\A\'(.*)\'::(?:cidr|inet|macaddr)\z/', $default, $matches):
                return $matches[1];
            // Bit string types
            case preg_match('/\AB\'(.*)\'::"?bit(?: varying)?"?\z/', $default, $matches):
                return $matches[1];
            // XML type
            case preg_match('/\A\'(.*)\'::xml\z/m', $default, $matches):
                return $matches[1];
            // Arrays
            case preg_match('/\A\'(.*)\'::"?\D+"?\[\]\z/', $default, $matches):
                return $matches[1];
            // Object identifier types
            case preg_match('/\A-?\d+\z/', $default, $matches):
                return $matches[1];
            default:
                // Anything else is blank, some user type, or some function
                // and we can't know the value of that, so return nil.
                return null;
        }
    }

    /**
     * @TODO
     * http://us3.php.net/manual/en/pdo.lobs.php
     * http://us2.php.net/manual/en/function.pdo-pgsqllobopen.php
     * etc.
     */
    /*@TODO bollux
        // Escapes binary strings for bytea input to the database.
        def self.string_to_binary(value)
          if PGconn.respond_to?(:escape_bytea)
            self.class.module_eval do
              define_method(:string_to_binary) do |value|
                PGconn.escape_bytea(value) if value
              end
            end
          else
            self.class.module_eval do
              define_method(:string_to_binary) do |value|
                if value
                  result = ''
                  value.each_byte { |c| result << sprintf('\\\\%03o', c) }
                  result
                end
              end
            end
          end
          self.class.string_to_binary(value)
        end

        // Unescapes bytea output from a database to the binary string it represents.
        def self.binary_to_string(value)
          // In each case, check if the value actually is escaped PostgreSQL bytea output
          // or an unescaped Active Record attribute that was just written.
          if PGconn.respond_to?(:unescape_bytea)
            self.class.module_eval do
              define_method(:binary_to_string) do |value|
                if value =~ /\\\d{3}/
                  PGconn.unescape_bytea(value)
                else
                  value
                end
              end
            end
          else
            self.class.module_eval do
              define_method(:binary_to_string) do |value|
                if value =~ /\\\d{3}/
                  result = ''
                  i, max = 0, value.size
                  while i < max
                    char = value[i]
                    if char == ?\\
                      if value[i+1] == ?\\
                        char = ?\\
                        i += 1
                      else
                        char = value[i+1..i+3].oct
                        i += 3
                      end
                    end
                    result << char
                    i += 1
                  end
                  result
                else
                  value
                end
              end
            end
          end
          self.class.binary_to_string(value)
        end
    */

    /*##########################################################################
    # Protected
    ##########################################################################*/

    /**
     * @param   string  $sqlType
     * @return  int
     */
    protected function _extractLimit($sqlType)
    {
        if (preg_match('/^bigint/i', $sqlType)) {
            return 8;
        }
        if (preg_match('/^smallint/i', $sqlType)) {
            return 2;
        }
        return parent::_extractLimit($sqlType);
    }

    /**
     * @param   string  $sqlType
     * @return  int
     */
    protected function _extractPrecision($sqlType)
    {
        if (preg_match('/^money/', $sqlType)) {
            return self::$moneyPrecision;
        }
        return parent::_extractPrecision($sqlType);
    }

    /**
     * @param   string  $sqlType
     * @return  int
     */
    protected function _extractScale($sqlType)
    {
        if (preg_match('/^money/', $sqlType)) {
            return 2;
        }
        return parent::_extractScale($sqlType);
    }

}


text:
package edu.java.cosc111.samples.net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 *
 * @author Russel
 */
public class BroadcastListener {

    /**
     * @param args the command line arguments
     * @throws java.net.SocketException
     * @throws java.io.IOException
     */
    public static void main(String[] args) throws SocketException, IOException {
        try(DatagramSocket socket = new DatagramSocket(1025)){
            DatagramPacket datagram = new DatagramPacket(new byte[1024], 1024);
            socket.setSoTimeout(10000);
            socket.setBroadcast(true);
            System.out.println("-Listener's Information-");
            System.out.println("  Address:" + InetAddress.getLocalHost());
            System.out.println("  Port:" + socket.getLocalPort());
            socket.receive(datagram);
            byte[] msg = "Hello".getBytes();
            System.out.println("-Broadcaster's Information-");
            //Print sender's address from the received datagram
            System.out.println("  Host: " + datagram.getAddress());
            //Print sender's port from the received datagram
            System.out.println("  Port: " + datagram.getPort());
            //Print sender's message
            System.out.println("  Message: " +  new String(datagram.getData()).trim());
            //Send a reply to the sender directly (not broadcast)
            socket.send(new DatagramPacket(msg,msg.length,datagram.getAddress(),datagram.getPort()));
        }
    }
}


text:
package org.apache.flink.streaming.runtime.operators;

import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.MetricOptions;
import org.apache.flink.runtime.execution.Environment;
import org.apache.flink.runtime.jobgraph.OperatorID;
import org.apache.flink.runtime.operators.testutils.MockEnvironment;
import org.apache.flink.runtime.state.memory.MemoryStateBackend;
import org.apache.flink.runtime.util.TestingTaskManagerRuntimeInfo;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.api.graph.StreamConfig;
import org.apache.flink.streaming.api.operators.Output;
import org.apache.flink.streaming.api.operators.StreamSource;
import org.apache.flink.streaming.runtime.streamrecord.StreamElement;
import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
import org.apache.flink.streaming.runtime.streamstatus.StreamStatusMaintainer;
import org.apache.flink.streaming.runtime.tasks.ProcessingTimeService;
import org.apache.flink.streaming.runtime.tasks.TestProcessingTimeService;
import org.apache.flink.streaming.util.CollectorOutput;
import org.apache.flink.streaming.util.MockStreamTask;
import org.apache.flink.streaming.util.MockStreamTaskBuilder;
import org.apache.flink.util.TestLogger;

import org.junit.Assert;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;

/**
 * Tests for the emission of latency markers by {@link StreamSource} operators.
 */
public class StreamSourceOperatorLatencyMetricsTest extends TestLogger {

	private static final long maxProcessingTime = 100L;
	private static final long latencyMarkInterval = 10L;

	/**
	 * Verifies that by default no latency metrics are emitted.
	 */
	@Test
	public void testLatencyMarkEmissionDisabled() throws Exception {
		testLatencyMarkEmission(0, (operator, timeProvider) -> {
			setupSourceOperator(operator, new ExecutionConfig(), MockEnvironment.builder().build(), timeProvider);
		});
	}

	/**
	 * Verifies that latency metrics can be enabled via the {@link ExecutionConfig}.
	 */
	@Test
	public void testLatencyMarkEmissionEnabledViaExecutionConfig() throws Exception {
		testLatencyMarkEmission((int) (maxProcessingTime / latencyMarkInterval) + 1, (operator, timeProvider) -> {
			ExecutionConfig executionConfig = new ExecutionConfig();
			executionConfig.setLatencyTrackingInterval(latencyMarkInterval);

			setupSourceOperator(operator, executionConfig, MockEnvironment.builder().build(), timeProvider);
		});
	}

	/**
	 * Verifies that latency metrics can be enabled via the configuration.
	 */
	@Test
	public void testLatencyMarkEmissionEnabledViaFlinkConfig() throws Exception {
		testLatencyMarkEmission((int) (maxProcessingTime / latencyMarkInterval) + 1, (operator, timeProvider) -> {
			Configuration tmConfig = new Configuration();
			tmConfig.setLong(MetricOptions.LATENCY_INTERVAL, latencyMarkInterval);

			Environment env = MockEnvironment.builder()
				.setTaskManagerRuntimeInfo(new TestingTaskManagerRuntimeInfo(tmConfig))
				.build();

			setupSourceOperator(operator, new ExecutionConfig(), env, timeProvider);
		});
	}

	/**
	 * Verifies that latency metrics can be enabled via the {@link ExecutionConfig} even if they are disabled via
	 * the configuration.
	 */
	@Test
	public void testLatencyMarkEmissionEnabledOverrideViaExecutionConfig() throws Exception {
		testLatencyMarkEmission((int) (maxProcessingTime / latencyMarkInterval) + 1, (operator, timeProvider) -> {
			ExecutionConfig executionConfig = new ExecutionConfig();
			executionConfig.setLatencyTrackingInterval(latencyMarkInterval);

			Configuration tmConfig = new Configuration();
			tmConfig.setLong(MetricOptions.LATENCY_INTERVAL, 0L);

			Environment env = MockEnvironment.builder()
				.setTaskManagerRuntimeInfo(new TestingTaskManagerRuntimeInfo(tmConfig))
				.build();

			setupSourceOperator(operator, executionConfig, env, timeProvider);
		});
	}

	/**
	 * Verifies that latency metrics can be disabled via the {@link ExecutionConfig} even if they are enabled via
	 * the configuration.
	 */
	@Test
	public void testLatencyMarkEmissionDisabledOverrideViaExecutionConfig() throws Exception {
		testLatencyMarkEmission(0, (operator, timeProvider) -> {
			Configuration tmConfig = new Configuration();
			tmConfig.setLong(MetricOptions.LATENCY_INTERVAL, latencyMarkInterval);

			Environment env = MockEnvironment.builder()
				.setTaskManagerRuntimeInfo(new TestingTaskManagerRuntimeInfo(tmConfig))
				.build();

			ExecutionConfig executionConfig = new ExecutionConfig();
			executionConfig.setLatencyTrackingInterval(0);

			setupSourceOperator(operator, executionConfig, env, timeProvider);
		});
	}

	private interface OperatorSetupOperation {
		void setupSourceOperator(
			StreamSource<Long, ?> operator,
			TestProcessingTimeService testProcessingTimeService
		);
	}

	private void testLatencyMarkEmission(int numberLatencyMarkers, OperatorSetupOperation operatorSetup) throws Exception {
		final List<StreamElement> output = new ArrayList<>();

		final TestProcessingTimeService testProcessingTimeService = new TestProcessingTimeService();
		testProcessingTimeService.setCurrentTime(0L);
		final List<Long> processingTimes = Arrays.asList(1L, 10L, 11L, 21L, maxProcessingTime);

		// regular stream source operator
		final StreamSource<Long, ProcessingTimeServiceSource> operator =
			new StreamSource<>(new ProcessingTimeServiceSource(testProcessingTimeService, processingTimes));

		operatorSetup.setupSourceOperator(operator, testProcessingTimeService);

		// run and wait to be stopped
		operator.run(new Object(), mock(StreamStatusMaintainer.class), new CollectorOutput<Long>(output));

		assertEquals(
			numberLatencyMarkers + 1, // + 1 is the final watermark element
			output.size());

		long timestamp = 0L;

		int i = 0;
		// verify that its only latency markers + a final watermark
		for (; i < numberLatencyMarkers; i++) {
			StreamElement se = output.get(i);
			Assert.assertTrue(se.isLatencyMarker());
			Assert.assertEquals(operator.getOperatorID(), se.asLatencyMarker().getOperatorId());
			Assert.assertEquals(0, se.asLatencyMarker().getSubtaskIndex());
			Assert.assertTrue(se.asLatencyMarker().getMarkedTime() == timestamp);

			timestamp += latencyMarkInterval;
		}

		Assert.assertTrue(output.get(i).isWatermark());
	}

	// ------------------------------------------------------------------------

	private static <T> void setupSourceOperator(
			StreamSource<T, ?> operator,
			ExecutionConfig executionConfig,
			Environment env,
			ProcessingTimeService timeProvider) {

		StreamConfig cfg = new StreamConfig(new Configuration());
		cfg.setStateBackend(new MemoryStateBackend());

		cfg.setTimeCharacteristic(TimeCharacteristic.EventTime);
		cfg.setOperatorID(new OperatorID());

		try {
			MockStreamTask mockTask = new MockStreamTaskBuilder(env)
				.setConfig(cfg)
				.setExecutionConfig(executionConfig)
				.setProcessingTimeService(timeProvider)
				.build();

			operator.setup(mockTask, cfg, (Output<StreamRecord<T>>) mock(Output.class));
		} catch (Exception e) {
			e.printStackTrace();
			fail(e.getMessage());
		}
	}

	// ------------------------------------------------------------------------

	private static final class ProcessingTimeServiceSource implements SourceFunction<Long> {

		private final TestProcessingTimeService processingTimeService;
		private final List<Long> processingTimes;

		private boolean cancelled = false;

		private ProcessingTimeServiceSource(TestProcessingTimeService processingTimeService, List<Long> processingTimes) {
			this.processingTimeService = processingTimeService;
			this.processingTimes = processingTimes;
		}

		@Override
		public void run(SourceContext<Long> ctx) throws Exception {
			for (Long processingTime : processingTimes) {
				if (cancelled) {
					break;
				}

				processingTimeService.setCurrentTime(processingTime);
			}
		}

		@Override
		public void cancel() {
			cancelled = true;
		}
	}
}


text:
#region

using System;
using System.Collections;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using Orchard;
using Orchard.Data;
using Orchard.Logging;
using Orchard.Mvc;
using Orchard.Mvc.Filters;
using Orchard.Themes;
using Orchard.UI.Admin;
using Rijkshuisstijl.UrlProtector.Models;
using Rijkshuisstijl.UrlProtector.Services;

#endregion

namespace Rijkshuisstijl.UrlProtector.Filters
{
    public class UrlFilter : FilterProvider, IActionFilter
    {
        private const int MaxFilteredRecordsInDatabase = 10;
        private readonly ICachedUrlProtectorRules _cachedUrlProtectorRules;
        private readonly IRepository<FilteredRequestRecord> _filteredRequestRecords;
        private readonly IOrchardServices _orchardServices;
        private readonly IWorkContextAccessor _wca;

        public UrlFilter(IWorkContextAccessor wca,
            IRepository<FilteredRequestRecord> filteredRequestRecords,
            ICachedUrlProtectorRules cachedUrlProtectorRules,
            IOrchardServices orchardServices)
        {
            _wca = wca;
            _filteredRequestRecords = filteredRequestRecords;
            _cachedUrlProtectorRules = cachedUrlProtectorRules;
            _orchardServices = orchardServices;
            Logger = NullLogger.Instance;
            UserAgent = _wca.GetContext().HttpContext.Request.UserAgent;
            UserHostAddress = _wca.GetContext().HttpContext.Request.UserHostAddress;
            RequestUrl = _wca.GetContext().HttpContext.Request.Url;
        }

        public String UserAgent { get; set; }
        public string UserHostAddress { get; set; }
        public Uri RequestUrl { get; set; }
        public ILogger Logger { get; set; }

        //Executed for every user request
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //Skip check if there is no url request found
            if (RequestUrl == null)
            {
                return;
            }

            #region Dashboard

            //Check dashboard pages or authorisation pages
            foreach (DashboardFilterRecord dashboardFilterRecord in _cachedUrlProtectorRules.DashboardFilterRecords)
            {
                if (AdminFilter.IsApplied(filterContext.RequestContext) || IsAuthenticationUrl(filterContext.ActionDescriptor.ActionName, filterContext.ActionDescriptor.ControllerDescriptor.ControllerName))
                {
                    //Check if url must be redirected to SSL
                    bool mustBeDirectedToSsl = dashboardFilterRecord.ForceSsl && filterContext.HttpContext.Request.Url != null && !filterContext.HttpContext.Request.IsSecureConnection;

                    //Check if userhostaddress and useragent match the needed pattern
                    Regex userHostAddressPattern = new Regex(dashboardFilterRecord.UserHostAddressPattern, RegexOptions.IgnoreCase);
                    Regex userAgentPattern = new Regex(dashboardFilterRecord.UserAgentPattern);

                    if (userHostAddressPattern.IsMatch(UserHostAddress) && userAgentPattern.IsMatch(UserAgent))
                    {
                        //Userhostaddress and useragent matches the pattern. Access is allowed. Redirect if it must be a SSL session.
                        if (mustBeDirectedToSsl)
                        {
                            filterContext.Result = RedirectToSecure(filterContext.HttpContext.Request.Url);
                        }
                        return;
                    }

                    //No access is granted for this admin request.
                    LogFilteredRequest();

                    //ek:rewrite

                    if (dashboardFilterRecord.ReturnStatusNotFound)
                    {
                        NotFoundResult(filterContext);
                    }
                    else
                    {
                        filterContext.Result = new HttpUnauthorizedResult();
                    }
                    return;
                }
                break;
            }

            #endregion

            #region UrlFilter

            //Check if the url matches a protected url pattern
            foreach (UrlFilterRecord urlFilterRecord in _cachedUrlProtectorRules.UrlFilterRecords.OrderBy(r => r.UrlPriority))
            {
                Regex urlPattern = new Regex(urlFilterRecord.UrlPattern, RegexOptions.IgnoreCase);

                //Do not prevent dashboard with urlfilter settings, it must be done with the dashboard item to prevent patterns that exclude the dashboard by accident
                if (!urlPattern.IsMatch(RequestUrl.AbsolutePath) | AdminFilter.IsApplied(filterContext.RequestContext))
                {
                    continue;
                }

                //Url matches the pattern

                //check if url must be forced to SSL
                bool mustBeDirectedToSsl = urlFilterRecord.ForceSsl && filterContext.HttpContext.Request.Url != null && !filterContext.HttpContext.Request.IsSecureConnection;

                //Check if userhostaddress and useragent match the needed pattern
                Regex userHostAddressPattern = new Regex(urlFilterRecord.UserHostAddressPattern, RegexOptions.IgnoreCase);
                Regex userAgentPattern = new Regex(urlFilterRecord.UserAgentPattern);

                if (userHostAddressPattern.IsMatch(UserHostAddress) && userAgentPattern.IsMatch(UserAgent))
                {
                    //Userhostaddress and useragent matches the pattern. Access is allowed. Redirect if it must be a SSL session.

                    if (mustBeDirectedToSsl)
                    {
                        filterContext.Result = RedirectToSecure(filterContext.HttpContext.Request.Url);
                    }
                    return;
                }

                #endregion

                switch ((UrlFilterReturnActionsEnum) urlFilterRecord.FailureAction)
                {
                    case UrlFilterReturnActionsEnum.AccessDenied:
                        //No access is granted for this request.
                        LogFilteredRequest();
                        filterContext.Result = new HttpUnauthorizedResult();
                        break;
                    case UrlFilterReturnActionsEnum.NotFound:
                        //No access is granted for this request.
                        LogFilteredRequest();
                        NotFoundResult(filterContext);
                        break;
                    case UrlFilterReturnActionsEnum.InMaintenance:
                        //Action is not logged because it could be normal behavior
                        InMaintenanceResult(filterContext);
                        break;
                    case UrlFilterReturnActionsEnum.Redirect:
                        //Action is not logged because it could be normal behavior
                        filterContext.Result = new RedirectResult(urlFilterRecord.RedirectTo);
                        break;
                   case UrlFilterReturnActionsEnum.NoAction:
                        //Do nothing
                        ;
                        break;
                    default:
                        //it should not happen.
                        Logger.Error(null, "An invalid option is choosen for the urlFilterRecord.FailureAction. Value {0} is unknown.", urlFilterRecord.FailureAction);
                        //Take no action for the user
                        ;
                        break;
                }
                return;
            }
        }

        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
        }

        private void NotFoundResult(ActionExecutingContext filterContext)
        {
            dynamic model = _orchardServices.New.NotFound();
            HttpRequestBase request = filterContext.RequestContext.HttpContext.Request;
            string url = request.RawUrl;

            // If the url is relative then replace with Requested path
            model.RequestedUrl = request.Url != null && request.Url.OriginalString.Contains(url) & request.Url.OriginalString != url ?
                request.Url.OriginalString : url;

            // Dont get the user stuck in a 'retry loop' by
            // allowing the Referrer to be the same as the Request
            model.ReferrerUrl = request.UrlReferrer != null &&
                                request.UrlReferrer.OriginalString != model.RequestedUrl ? request.UrlReferrer.OriginalString : null;

            //Add the default theme
            filterContext.HttpContext.Items[typeof (ThemeFilter)] = null;

            //Remove Admin theme if enabled
            DictionaryEntry adminUiFilter = new DictionaryEntry();
            foreach (DictionaryEntry item in filterContext.HttpContext.Items.Cast<DictionaryEntry>().Where(item => item.Key.ToString() == "Orchard.UI.Admin.AdminFilter"))
            {
                adminUiFilter = item;
            }

            if (adminUiFilter.Key != null && !String.IsNullOrEmpty(adminUiFilter.Key.ToString()))
            {
                filterContext.HttpContext.Items.Remove(adminUiFilter.Key);
            }

            filterContext.Result = new ShapeResult(filterContext.Controller, model);
            filterContext.RequestContext.HttpContext.Response.StatusCode = (int) HttpStatusCode.NotFound;

            // prevent IIS 7.0 classic mode from handling the 404/500 itself
            filterContext.RequestContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        }

        private void InMaintenanceResult(ActionExecutingContext filterContext)
        {
            filterContext.HttpContext.Items[typeof (ThemeFilter)] = null;
            dynamic model = _orchardServices.New.Maintenance();
            filterContext.RequestContext.HttpContext.Response.StatusCode = (int) HttpStatusCode.ServiceUnavailable;
            filterContext.Result = new ShapeResult(filterContext.Controller, model);
        }

        private void LogFilteredRequest()
        {
            int newId;

            //Log in the logfile as a warning
            Logger.Warning("UrlProtector prevented access to url {1} from address {0} with useragent {2}", UserHostAddress, RequestUrl, UserAgent);

            //Log in the database for the list with most recent filtered requests
            //Get the last record id to add a new record and recycle if maximum of records is reached
            FilteredRequestRecord mostRecentRecord = (from filteredRecord in _filteredRequestRecords.Table
                orderby filteredRecord.RequestTime descending
                select filteredRecord).FirstOrDefault();

            if (mostRecentRecord == null || mostRecentRecord.Id > MaxFilteredRecordsInDatabase)
            {
                newId = 1;
            }
            else
            {
                newId = mostRecentRecord.Id + 1;
            }

            FilteredRequestRecord newFilteredRequestRecord = new FilteredRequestRecord
            {
                Id = newId,
                RequestTime = DateTime.Now,
                Url = RequestUrl.AbsolutePath,
                UserAgent = UserAgent,
                UserHostAddress = UserHostAddress
            };

            _filteredRequestRecords.Update(newFilteredRequestRecord);
        }

        private static Boolean IsAuthenticationUrl(String actionName, String controllerName)
        {
            return controllerName == "Account" &&
                   (actionName == "LogOn"
                    || actionName == "ChangePassword"
                    || actionName == "AccessDenied"
                    || actionName == "Register"
                    || actionName.StartsWith("ChallengeEmail", StringComparison.OrdinalIgnoreCase));
        }

        private static RedirectResult RedirectToSecure(Uri requestUrl)
        {
            UriBuilder builder = new UriBuilder(requestUrl)
            {
                Scheme = Uri.UriSchemeHttps,
                Port = 443
            };

            return new RedirectResult(builder.Uri.ToString());
        }
    }
}


text:
<?php
namespace Nkey\Caribu\Mvc\View\Bootstrap\Controls\Form;

/**
 * Bootstrap field abstraction
 *
 * @author Maik Greubel <greubel@nkey.de>
 *
 *         This file is part of Caribu MVC Bootstrap addon package
 */
abstract class Field extends FormElement
{
}


text:
package elasta.criteria.json.mapping;

import elasta.criteria.ParamsBuilder;import elasta.criteria.ParamsBuilder;
import io.vertx.core.json.JsonObject;

/**
 * Created by Jango on 2017-01-07.
 */
public interface JsonQueryParser {
    String toSql(JsonObject query, ParamsBuilder paramsBuilder);
}


text:
<?xml version="1.0" encoding="utf-8"?>

<!--
  ~ The MIT License (MIT)
  ~
  ~ Copyright (c) 2012 Curt Binder
  ~
  ~ Permission is hereby granted, free of charge, to any person obtaining a copy
  ~ of this software and associated documentation files (the "Software"), to deal
  ~ in the Software without restriction, including without limitation the rights
  ~ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  ~ copies of the Software, and to permit persons to whom the Software is
  ~ furnished to do so, subject to the following conditions:
  ~
  ~ The above copyright notice and this permission notice shall be included in all
  ~ copies or substantial portions of the Software.
  ~
  ~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  ~ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  ~ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  ~ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  ~ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  ~ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  ~ SOFTWARE.
  -->

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TableLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:stretchColumns="1" >

        <include
            android:id="@+id/t1_row"
            layout="@layout/genericlabelrow" />

        <include
            android:id="@+id/t2_row"
            layout="@layout/genericlabelrow" />

        <include
            android:id="@+id/t3_row"
            layout="@layout/genericlabelrow" />

        <include
            android:id="@+id/ph_row"
            layout="@layout/genericlabelrow" />

        <include
            android:id="@+id/dp_row"
            layout="@layout/genericlabelrow" />

        <include
            android:id="@+id/ap_row"
            layout="@layout/genericlabelrow" />

        <include
            android:id="@+id/dp2_row"
            layout="@layout/genericlabelrow" />

        <include
            android:id="@+id/ap2_row"
            layout="@layout/genericlabelrow" />

        <include
            android:id="@+id/atolow_row"
            layout="@layout/genericlabelrow" />

        <include
            android:id="@+id/atohi_row"
            layout="@layout/genericlabelrow" />

        <include
            android:id="@+id/salinity_row"
            layout="@layout/genericlabelrow" />

        <include
            android:id="@+id/orp_row"
            layout="@layout/genericlabelrow" />

        <include
            android:id="@+id/phe_row"
            layout="@layout/genericlabelrow" />

        <include
            android:id="@+id/water_row"
            layout="@layout/genericlabelrow" />

        <include
            android:id="@+id/water1_row"
            layout="@layout/genericlabelrow" />

        <include
            android:id="@+id/water2_row"
            layout="@layout/genericlabelrow" />

        <include
            android:id="@+id/water3_row"
            layout="@layout/genericlabelrow" />

        <include
            android:id="@+id/water4_row"
            layout="@layout/genericlabelrow" />

        <include
            android:id="@+id/humidity_row"
            layout="@layout/genericlabelrow" />

        <include
            android:id="@+id/par_row"
            layout="@layout/genericlabelrow" />
    </TableLayout>

</ScrollView>


text:
<!DOCTYPE html>

    <title>Three Sixty</title>
    <link rel="stylesheet" href="styles.css">

    <input type="text" id="img" placeholder="Image Path" />
    <input type="button" id="submit" value="Submit" />


text:
using System;
using System.Threading;
using Serilog.Core;
using Serilog.Events;
using Umbraco.Cms.Core.Cache;

namespace Umbraco.Cms.Core.Logging.Serilog.Enrichers
{
    /// <summary>
    /// Enrich log events with a HttpRequestNumber unique within the current
    /// logging session.
    /// Original source - https://github.com/serilog-web/classic/blob/master/src/SerilogWeb.Classic/Classic/Enrichers/HttpRequestNumberEnricher.cs
    /// Nupkg: 'Serilog.Web.Classic' contains handlers and extra bits we do not want
    /// </summary>
    public class HttpRequestNumberEnricher : ILogEventEnricher
    {
        private readonly IRequestCache _requestCache;
        private static int _lastRequestNumber;
        private static readonly string _requestNumberItemName = typeof(HttpRequestNumberEnricher).Name + "+RequestNumber";

        /// <summary>
        /// The property name added to enriched log events.
        /// </summary>
        private const string _httpRequestNumberPropertyName = "HttpRequestNumber";

        public HttpRequestNumberEnricher(IRequestCache requestCache)
        {
            _requestCache = requestCache ?? throw new ArgumentNullException(nameof(requestCache));
        }

        /// <summary>
        /// Enrich the log event with the number assigned to the currently-executing HTTP request, if any.
        /// </summary>
        /// <param name="logEvent">The log event to enrich.</param>
        /// <param name="propertyFactory">Factory for creating new properties to add to the event.</param>
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            if (logEvent == null) throw new ArgumentNullException(nameof(logEvent));

            var requestNumber = _requestCache.Get(_requestNumberItemName,
                    () => Interlocked.Increment(ref _lastRequestNumber));

            var requestNumberProperty = new LogEventProperty(_httpRequestNumberPropertyName, new ScalarValue(requestNumber));
            logEvent.AddPropertyIfAbsent(requestNumberProperty);
        }
    }
}


text:
package org.apache.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;

public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

  private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();

  private static java.util.List<String> _jspx_dependants;

  private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector;

  public java.util.List<String> getDependants() {
    return _jspx_dependants;
  }

  public void _jspService(HttpServletRequest request, HttpServletResponse response)
        throws java.io.IOException, ServletException {

    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
      response.setContentType("text/html;charset=UTF-8");
      pageContext = _jspxFactory.getPageContext(this, request, response,
      			null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;
      _jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");

      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("<!DOCTYPE html>\n");
      out.write("\n");
      out.write("    \n");
      out.write("        <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n");
      out.write("        <title>JSP Page</title>\n");
      out.write("    \n");
      out.write("    \n");
      out.write("
Hello World!
\n");
      out.write("        <form action=\"TestSelvlet\" method=\"get\">\n");
      out.write("            <input type=\"submit\" value=\"submit\"/>\n");
      out.write("        </form>\n");
      out.write("    \n");
      out.write("\n");
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          out.clearBuffer();
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else throw new ServletException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}


text:
> The require hook will bind itself to node's require and automatically compile files on the fly.

One of the ways you can use Babel is through the require hook. The require hook
will bind itself to node's `require` and automatically compile files on the
fly. This is equivalent to CoffeeScript's
[coffee-script/register](http://coffeescript.org/v2/annotated-source/register.html).

## Install

```sh
npm install babel-register --save-dev
```

## Usage

```js
require("babel-register");
```

All subsequent files required by node with the extensions `.es6`, `.es`, `.jsx`
and `.js` will be transformed by Babel.

Polyfill not included

    You must include the polyfill separately
    when using features that require it, like generators.

### Ignores `node_modules` by default

**NOTE:** By default all requires to `node_modules` will be ignored. You can
override this by passing an ignore regex via:

```js
require("babel-register")({
  // This will override `node_modules` ignoring - you can alternatively pass
  // an array of strings to be explicitly matched or a regex / glob
  ignore: false
});
```

## Specifying options

```javascript
require("babel-register")({
  // Optional ignore regex - if any filenames **do** match this regex then they
  // aren't compiled.
  ignore: /regex/,

  // Ignore can also be specified as a function.
  ignore: function(filename) {
    if (filename === "/path/to/es6-file.js") {
      return false;
    } else {
      return true;
    }
  },

  // Optional only regex - if any filenames **don't** match this regex then they
  // aren't compiled
  only: /my_es6_folder/,

  // Setting this will remove the currently hooked extensions of .es6, `.es`, `.jsx`
  // and .js so you'll have to add them back if you want them to be used again.
  extensions: [".es6", ".es", ".jsx", ".js"],

  // Setting this to false will disable the cache.
  cache: true
});
```

You can pass in all other [options](https://babeljs.io/docs/usage/api/#options) as well,
including `plugins` and `presets`. But note that the closest [`.babelrc`](https://babeljs.io/docs/usage/babelrc/)
to each file still applies, and takes precedence over any options you pass in here.

## Environment variables

By default `babel-node` and `babel-register` will save to a json cache in your
temporary directory.

This will heavily improve with the startup and compilation of your files. There
are however scenarios where you want to change this behaviour and there are
environment variables exposed to allow you to do this.

### BABEL_CACHE_PATH

Specify a different cache location.

```sh
BABEL_CACHE_PATH=/foo/my-cache.json babel-node script.js
```

### BABEL_DISABLE_CACHE

Disable the cache.

```sh
BABEL_DISABLE_CACHE=1 babel-node script.js
```


text:
                <ows:DataType ows:reference="http://www.w3.org/TR/xmlschema-2/#{{ put.data_type }}">{{ put.data_type }}</ows:DataType>
                {% if put.uom %}
                <UOMs>
                    <Default>
                        <ows:UOM {%if put.uom %}ows:reference="{{ put.uom.reference }}"{% endif %}>{{ put.uom.uom }}</ows:UOM>
                    </Default>
                    <Supported>
                        {% for uom in put.uoms %}
                        <ows:UOM ows:reference="{{ put.uom.reference }}">{{ put.uom.uom }}</ows:UOM>
                        {% endfor %}
                    </Supported>
                </UOMs>
                {% endif %}
                {% if put.any_value %}
                <ows:AnyValue/>
                {% elif put.values_reference %}
                <ows:ValuesReference ows:reference="{{ put.values_reference.reference }}"/>
                {% elif put.allowed_values %}
                <ows:AllowedValues>
                    {% for value in put.allowed_values %}
                    {% if value.allowed_type == "value" %}
                    <ows:Value>{{ value.value }}</ows:Value>
                    {% else %}
                    <ows:Range ows:rangeClosure="{{ value.range_closure }}">
                        <ows:MinimumValue>{{ value.minval }}</ows:MinimumValue>
                        <ows:MaximumValue>{{ value.maxval }}</ows:MaximumValue>
                        {% if value.spacing %}
                        <ows:Spacing>{{ value.spacing }}</ows:Spacing>
                        {% endif %}
                    </ows:Range>
                    {% endif %}
                    {% endfor %}
                </ows:AllowedValues>
                {% endif %}
                {% if put.data is defined and put.data is not none %}
                <DefaultValue>{{ put.data }}</DefaultValue>
                {% endif %}


text:
namespace orbit_windows_utils {

struct Module {
  std::string name;
  std::string full_path;
  uint64_t file_size = 0;
  uint64_t address_start = 0;
  uint64_t address_end = 0;
  uint64_t load_bias = 0;
  std::string build_id;
  std::vector<orbit_grpc_protos::ModuleInfo::ObjectSegment> sections;
};

// List all modules of the process identified by "pid".
[[nodiscard]] std::vector<Module> ListModules(uint32_t pid);

}  // namespace orbit_windows_utils

#endif  // WINDOWS_UTILS_LIST_MODULES_H_


text:
<?php

//dont cache
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?>

<!DOCTYPE html>

		<title>Ontdek jouw Radio 2 Top 30 geboorteplaat</title>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="description" content="Welk nummer stond op 1 in de Radio 2 Top 30 op de dag dat jij geboren bent?">
    <meta name="og:image" content="/img/FB-share-img-general.jpg">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
		<link href="https://fonts.googleapis.com/css?family=Anton" rel="stylesheet">
    <link rel="stylesheet" href="css/top30.css">

                    <form id="mainform" role="form" action="save.php" METHOD="POST">
                        <fieldset class="form-group">
                            Hallo! Wat is je naam?
                            <input type="text" class="form-control" id="name" name="name" />
                        </fieldset>
                        <fieldset class="form-group">
                            Dag , in welk jaar ben je geboren?
                            <input type="text" class="form-control" id="year" name="year"/>
                        </fieldset>
                        <fieldset class="form-group">
                            En in welke maand?
                            <select class="form-control"  id="maand" name="maand" >
                              <option value="1">Januari</option>
                              <option value="2">Februari</option>
                              <option value="3">Maart</option>
                              <option value="4">April</option>
                              <option value="5">Mei</option>
                              <option value="6">Juni</option>
                              <option value="7">Juli</option>
                              <option value="8">Augustus</option>
                              <option value="9">September</option>
                              <option value="10">Oktober</option>
                              <option value="11">November</option>
                              <option value="12">December</option>
                            </select>
                        </fieldset>
                        <fieldset class="form-group">
                            Welke dag?
                            <select class="form-control" id="dag" name="dag">
                              <option value="1">1</option>
                              <option value="2">2</option>
                              <option value="3">3</option>
                              <option value="4">4</option>
                              <option value="5">5</option>
                              <option value="6">6</option>
                              <option value="7">7</option>
                              <option value="8">8</option>
                              <option value="9">9</option>
                              <option value="10">10</option>
                              <option value="11">11</option>
                              <option value="12">12</option>
                              <option value="13">13</option>
                              <option value="14">14</option>
                              <option value="15">15</option>
                              <option value="16">16</option>
                              <option value="17">17</option>
                              <option value="18">18</option>
                              <option value="19">19</option>
                              <option value="20">20</option>
                              <option value="21">21</option>
                              <option value="22">22</option>
                              <option value="23">23</option>
                              <option value="24">24</option>
                              <option value="25">25</option>
                              <option value="26">26</option>
                              <option value="27">27</option>
                              <option value="28">28</option>
                              <option value="29">29</option>
                              <option value="30">30</option>
                              <option value="31">31</option>
                            </select>
                        </fieldset>
                        <button id="submitbutton" type="submit" class="btn btn-default">Indienen</button>
                    </form>


text:
package worldweather

import (
	"fmt"
	"strconv"
)

// ErrorDescription represents an error that returned by World Weather API.
// `{ "data": { "error": [ {"msg": "Unable to find any matching weather location to the query submitted!" } ] }}`
type ErrorDescription struct {
	Message string `json:"msg"`
}

// CommonData represents a common response fields returned as part of API response.
type CommonData struct {
	Error []*ErrorDescription `json:"error"`
}

// HasError tells if the response contains any error.
func (data *CommonData) HasError() bool {
	return len(data.Error) > 0
}

// LocalWeatherResponse represents local weather information.
// https://developer.worldweatheronline.com/api/docs/local-city-town-weather-api.aspx#data_element
type LocalWeatherResponse struct {
	Data *WeatherData `json:"data"`
}

// WeatherData represents a set of weather information.
type WeatherData struct {
	CommonData
	Request          []*Request          `json:"request"`
	CurrentCondition []*CurrentCondition `json:"current_condition"`
	Weather          []*Weather          `json:"weather"`
}

// Request represents a client's request.
type Request struct {
	Type  string `json:"type"`
	Query string `json:"query"`
}

// CurrentCondition represents the current weather condition returned by API.
type CurrentCondition struct {
	ObservationTime       string                `json:"observation_time"`
	Temperature           int                   `json:"temp_C,string"`
	FeelingTemperature    int                   `json:"FeelsLikeC,string"`
	WindSpeed             int                   `json:"windspeedKmph,string"`
	WindDirection         int                   `json:"winddirDegree,string"`
	WindDirectionCardinal string                `json:"winddir16Point"`
	WeatherCode           string                `json:"weatherCode"`
	WeatherIcon           []*WeatherIcon        `json:"weatherIconUrl"`
	Description           []*WeatherDescription `json:"weatherDesc"`
	Precipitation         float32               `json:"precpMM,string"`     // Precipitation in mm
	Humidity              int                   `json:"humidity,string"`    // Humidity in percentage
	Visibility            int                   `json:"visibility,string"`  // Visibility in kilometres
	Pressure              int                   `json:"pressure,string"`    // Atmospheric pressure in millibars
	CloudCover            int                   `json:"cloudcocver,string"` // Cloud cover amount in percentage (%)
}

// WeatherIcon is an icon url that represents corresponding weather.
type WeatherIcon struct {
	URL string `json:"value"`
}

// WeatherDescription represents a weather description.
type WeatherDescription struct {
	Content string `json:"value"`
}

// Weather represents a set of weather information.
type Weather struct {
	Astronomy []*Astronomy     `json:"astronomy"`
	Date      string           `json:"date"` // 2016-09-04
	MaxTempC  int              `json:"maxTempC,string"`
	MaxTempF  int              `json:"maxTempF,string"`
	MinTempC  int              `json:"minTempC,string"`
	MinTempF  int              `json:"minTempF,string"`
	UV        int              `json:"uvindex,string"`
	Hourly    []*HourlyWeather `json:"hourly"`
}

// HourlyWeather represents hourly weather information.
type HourlyWeather struct {
	Time                  HourlyForecastTime    `json:"time"`         // hhmm format
	Temperature           int                   `json:"tempC,string"` // not temp_C
	FeelingTemperature    int                   `json:"FeelsLikeC,string"`
	WindSpeed             int                   `json:"windspeedKmph,string"`
	WindDirection         int                   `json:"winddirDegree,string"`
	WindDirectionCardinal string                `json:"winddir16Point"`
	WeatherCode           string                `json:"weatherCode"`
	WeatherIcon           []*WeatherIcon        `json:"weatherIconUrl"`
	Description           []*WeatherDescription `json:"weatherDesc"`
	Precipitation         float32               `json:"precpMM,string"`     // Precipitation in mm
	Humidity              int                   `json:"humidity,string"`    // Humidity in percentage
	Visibility            int                   `json:"visibility,string"`  // Visibility in kilometres
	Pressure              int                   `json:"pressure,string"`    // Atmospheric pressure in millibars
	CloudCover            int                   `json:"cloudcocver,string"` // Cloud cover amount in percentage (%)
}

// HourlyForecastTime is a time representation for hourly forecast.
type HourlyForecastTime struct {
	OriginalValue string
	DisplayTime   string
	Hour          int
}

// UnmarshalText converts a time value returned by the API to a more convenient form.
func (t *HourlyForecastTime) UnmarshalText(b []byte) error {
	str := string(b)
	t.OriginalValue = str

	hhmm, err := strconv.Atoi(str)
	if err != nil {
		return err
	}
	hhmmStr := fmt.Sprintf("%04d", hhmm)
	t.DisplayTime = hhmmStr[:2] + ":" + hhmmStr[2:]
	t.Hour, _ = strconv.Atoi(hhmmStr[:2])

	return nil
}

// Astronomy represents astronomical information.
type Astronomy struct {
	Sunrise  string `json:"sunrise"`
	Sunset   string `json:"sunset"`
	MoonRise string `json:"moonrise"`
	MoonSet  string `json:"moonset"`
}


text:
*This question is the same as "Max Chunks to Make Sorted" except the integers of the given array are not necessarily distinct, the input array could be up to length `2000`, and the elements could be up to `10**8`.*

------

Given an array `arr` of integers (**not necessarily distinct**), we split the array into some number of "chunks" (partitions), and individually sort each chunk. After concatenating them, the result equals the sorted array.

What is the most number of chunks we could have made?

**Example 1:**

```
Input: arr = [5,4,3,2,1]
Output: 1
Explanation:
Splitting into two or more chunks will not return the required result.
For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted.
```

**Example 2:**

```
Input: arr = [2,1,3,4,4]
Output: 4
Explanation:
We can split into two chunks, such as [2, 1], [3, 4, 4].
However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.
```

**Note:**

- `arr` will have length in range `[1, 2000]`.
- `arr[i]` will be an integer in range `[0, 10**8]`.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MYVote.Models
{
    public partial class Question
    {
        public List<AnswerOption> AnswerOptions = new List<AnswerOption>();

        public void fillValues()
        {
            using (var db = new EF_DB_Context())
            {
                var answerOptionsFinder = from a in db.QuestionAnswerOption
                                          where a.QuestionId == Id
                                          select a.AnswerOptionId;

                AnswerOptions = db.AnswerOption.Where(a => answerOptionsFinder.Any(a2 => a2 == a.Id)).ToList();
            }
        }
    }
}


text:
        <title>Peta</title>
	<link rel="stylesheet" type="text/css" href="<?=base_url()?>assets/js/ext-3.4.1/resources/css/ext-all.css" />


text:
<meta charset="UTF-8">
<title>NormalizerModelBuilder.main - biomedicus-core</title>
<link rel="stylesheet" href="../../../style.css">

biomedicus-core / edu.umn.biomedicus.normalization / NormalizerModelBuilder / main

main

static fun main(args: Array<String>): Unit