text:
#include "database.h"
#include "timer.h"

#define RAND_MAX 100000

void answers(char * string, int newline) {
	//opens the file
	FILE * answers = fopen("answers.txt", "a+");
	//prints the input to the file
	if (newline) {
		fprintf(answers, "%s\n", string);
		fprintf(answers, "\n");
	}
	else {
		fprintf(answers, "%s\n", string);
	}
	//closes the file
	fclose(answers);
}

void AddEntry(Database* self, char * keyc, char * valuec)
{
	DBT key, value;
	memset(&key, 0, sizeof(key));
	key.data = keyc;
	key.size = strlen(key.data) + 1;

	memset(&value, 0, sizeof(value));
	value.data = valuec;
	value.size = strlen(value.data) + 1;

	int ret;
	if ((ret = (*self->cursor)->c_put(*self->cursor, &key, &value, DB_KEYFIRST)) != 0)
		self->db->err(self->db, ret, "DB->cursor");
}

char * _create(Database* self, int dbtype) // btree = 1, hash = 2
{
	struct stat exists;
	db_create(&self->db, NULL, 0);
	char filepath[256];
	strcpy(filepath, "./tmp/ioltuszy_db/");
	strcat(filepath, (dbtype == 1) ? "btree" : (dbtype == 2) ? "hash" : "indexfile");
	strcat(filepath, ".db\0");
	self->db->open(self->db, NULL, filepath, NULL, dbtype, DB_CREATE, 0);
	return filepath;
}
void _destroy(Database* self, char * filepath)
{
	struct stat exists;
	int result = stat(filepath, &exists);
	if (!result)
	{
		self->db->close(self->db, 0);
		_unlink(filepath);
	}
	else
	{
		puts("The database does not exist; please create a database first.");
	}
}
void _populate(Database* self, int amount)
{
	int range;
	int seed = 10000000;
	srand(seed);
	char keybuff[128];
	char valuebuff[128];
	int ret;

	memset(&self->keytomatch1, 0, sizeof(self->keytomatch1));
	memset(&self->valuetomatch1, 0, sizeof(self->valuetomatch1));

	int random_exists[8];

	for (int i = 0; i <= 7; i++) {
		random_exists[i] = rand();
	}

	for (int entry = 0; entry < amount; entry++) { // # to populate with
#pragma region Key Generation
		range = 64 + rand() % (64);
		for (int kbi = 0; kbi < range; kbi++) // keybuffer index
		{
			keybuff[kbi] = (char)(97 + rand() % 26);
		}
		keybuff[range] = 0; // null terminate
#pragma endregion Key Generation
#pragma region Value Generation
		range = 64 + rand() % (64);
		for (int vbi = 0; vbi < range; vbi++) // valuebuffer index
		{
			valuebuff[vbi] = (char)(97 + rand() % 26);
		}
		valuebuff[range] = 0; // null terminate
#pragma endregion Value Generation

		//printf("Key: %s\nData: %s\n", keybuff, valuebuff);

		if (entry == random_exists[0]) {
			strcpy(self->keytomatch0, keybuff);
			strcpy(self->valuetomatch0, valuebuff);

			//printf("Key: %s\n", self->keytomatch0);
			//printf("Value: %s\n", self->valuetomatch0);
		}

		if (entry == random_exists[1]) {
			strcpy(self->keytomatch1, keybuff);
			strcpy(self->valuetomatch1, valuebuff);

			//printf("Key: %s\n", self->keytomatch1);
			//printf("Value: %s\n", self->valuetomatch1);
		}

		if (entry == random_exists[2]) {
			strcpy(self->keytomatch2, keybuff);
			strcpy(self->valuetomatch2, valuebuff);

			//printf("Key: %s\n", self->keytomatch2);
			//printf("Value: %s\n", self->valuetomatch2);
		}

		if (entry == random_exists[3]) {
			strcpy(self->keytomatch3, keybuff);
			strcpy(self->valuetomatch3, valuebuff);

			//printf("Key: %s\n", self->keytomatch3);
			//printf("Value: %s\n", self->valuetomatch3);
		}
		AddEntry(self, keybuff, valuebuff);
	}
}
int _menu(Database* self)
{
	int invalid = 1;
	int selection;
	while (invalid)
	{
		printf("Please enter the number of the task you wish to preform.\n");
		printf("1 - Create and Populate a database\n");
		printf("2 - Retrieve records with a given key\n");
		printf("3 - Retrieve records with given data\n");
		printf("4 - Retrieve records with a given range of key values\n");
		printf("5 - Destroy the database\n");
		printf("6 - Quit\n");
		printf("Please enter your task: ");

		fflush(stdout);
		scanf("%d", &selection);
		if ((selection < 1) || (selection > 6)) {
			printf("Your mode is not one of the accepted modes, please try again.\n");
			char c;
			scanf("%c", &c);
		}
		else
		{
			invalid = 0;
		}
	}
	return selection;
}
void _init(Database* self)
{
	self->create = _create;
	self->destroy = _destroy;
	self->populate = _populate;
	self->menu = _menu;
}

void DBCreate(int dbtype)
{
	Database _D;
	_init(&_D);
	char file[256];
	DBT key, value;
	char keybuff[128];
	char valuebuff[128];
	int ret;
	long start[2], end[2];
	char keytomatch[128], valuetomatch[128];
	char mintomatch[128], maxtomatch[128];
	int searchnumber = 0;
	int resultcount = 0;
	long totalTime = 0;
	while (1)
	{
		int task = _D.menu(&_D);
		switch (task)
		{
		default:
			// Nothing
		case 1:
			strcpy(file, _D.create(&_D, dbtype));
			puts("DB: Created");

			_D.cursor = malloc(sizeof(_D.cursor));
			_D.db->cursor(_D.db, NULL, _D.cursor, 0);

			_D.populate(&_D, 100000);
			break;
		case 2:
			if (searchnumber == 4) {
				//this program needs to search over different keys four times. After all keys have been used, they keys will repeat with this message.
				printf("The keys for search will now repeat.");
				searchnumber = 0;
			}

			if (searchnumber == 3) {
				memset(&keytomatch, 0, sizeof(keytomatch));
				strcpy(keytomatch, _D.keytomatch3);
				searchnumber++;
			}

			if (searchnumber == 2) {
				memset(&keytomatch, 0, sizeof(keytomatch));
				strcpy(keytomatch, _D.keytomatch2);
				searchnumber++;
			}

			if (searchnumber == 1) {
				memset(&keytomatch, 0, sizeof(keytomatch));
				strcpy(keytomatch, _D.keytomatch1);
				searchnumber++;
			}

			if (searchnumber == 0) {
				memset(&keytomatch, 0, sizeof(keytomatch));
				strcpy(keytomatch, _D.keytomatch0);
				searchnumber++;
			}

			memset(&key, 0, sizeof(key));
			key.data = keytomatch;
			key.size = strlen(key.data) + 1;
			value.flags = DB_DBT_USERMEM;
			value.data = valuebuff;
			value.ulen = sizeof(valuebuff);

			clock_readtime(&start); // Start query
			(*_D.cursor)->c_get(*_D.cursor, &key, &value, DB_SET);
			// Got an entry with correct data
			clock_readtime(&end); // End query

			answers(key.data, 0);
			answers(value.data, 1);

			(*_D.cursor)->c_get(*_D.cursor, &key, &value, DB_FIRST);
			printf("Elapsed Time (microseconds): %lu\n", diff_time(end, start));
			printf("Total Records Returned: %d\n", 1);

			/*printf("Key: %.*s\nData: %.*s\n",
			(int)key.size, (char *)key.data,
			(int)value.size, (char *)value.data);*/

			break;
		case 3:
			if (searchnumber == 4) {
				//this program needs to search over different values four times. After all values have been used, the values will repeat with this message.
				printf("The values for search will now repeat.");
				searchnumber = 0;
			}

			if (searchnumber == 3) {
				memset(&valuetomatch, 0, sizeof(valuetomatch));
				strcpy(valuetomatch, _D.valuetomatch3);
				searchnumber++;
			}

			if (searchnumber == 2) {
				memset(&valuetomatch, 0, sizeof(valuetomatch));
				strcpy(valuetomatch, _D.valuetomatch2);
				searchnumber++;
			}

			if (searchnumber == 1) {
				memset(&valuetomatch, 0, sizeof(valuetomatch));
				strcpy(valuetomatch, _D.valuetomatch1);
				searchnumber++;
			}

			if (searchnumber == 0) {
				memset(&valuetomatch, 0, sizeof(valuetomatch));
				strcpy(valuetomatch, _D.valuetomatch0);
				searchnumber++;
			}

			key.flags = DB_DBT_USERMEM;
			key.data = keybuff;
			key.ulen = sizeof(keybuff);
			value.flags = DB_DBT_USERMEM;
			value.data = valuebuff;
			value.ulen = sizeof(valuebuff);
			resultcount = 0;

			clock_readtime(&start); // Start query
			(*_D.cursor)->c_get((*_D.cursor), &key, &value, DB_FIRST);
			if (strcmp((char *)value.data, valuetomatch) == 0)
			{
				// Got an entry with correct data

				clock_readtime(&end);
				totalTime += diff_time(end, start);
				answers(key.data, 0);
				answers(value.data, 1);
				clock_readtime(&start);
				resultcount++;
			}
			while ((ret = (*_D.cursor)->c_get((*_D.cursor), &key, &value, DB_NEXT)) == 0)
			{
				if (strcmp((char *)value.data, valuetomatch) == 0)
				{
					// Got an entry with correct data
					clock_readtime(&end);
					totalTime += diff_time(end, start);
					answers(key.data, 0);
					answers(value.data, 1);
					clock_readtime(&start);
					resultcount++;
				}
			}
			clock_readtime(&end); // End query
			totalTime += diff_time(end, start);

			printf("Elapsed Time (microseconds): %lu\n", totalTime);
			printf("Total Records Returned: %d\n", resultcount);
			break;
		case 4:
			printf("Please enter your minimum range: ");
			scanf("%s", &mintomatch);
			printf("Please enter your maximum range: ");
			scanf("%s", &maxtomatch);

			memset(&key, 0, sizeof(key));
			key.data = mintomatch;
			key.size = strlen(key.data) + 1;
			value.flags = DB_DBT_USERMEM;
			value.data = valuebuff;
			value.ulen = sizeof(valuebuff);

			resultcount = 0;

			if (dbtype == 1)
			{
				clock_readtime(&start); // Start query
				while ((ret = (*_D.cursor)->c_get((*_D.cursor), &key, &value, DB_SET_RANGE)) == 0)
				{
					if (strcmp((char *)key.data, maxtomatch) > 0)
					{
						// End of range
						break;
					}
					answers(key.data, 0);
					answers(value.data, 1);
					resultcount++;
					((char*)key.data)[strlen((char *)key.data) - 1]++; // Increment last char before null terminator
				}
				clock_readtime(&end); // End query
			}
			else
			{
				key.flags = DB_DBT_USERMEM;
				key.data = keybuff;
				key.ulen = sizeof(keybuff);
				clock_readtime(&start); // Start query
				(*_D.cursor)->c_get((*_D.cursor), &key, &value, DB_FIRST);
				if (strcmp((char *)key.data, mintomatch) < 0)
				{
					// Bad key
				}
				else if (strcmp((char *)key.data, maxtomatch) > 0)
				{
					// Bad key
				}
				else
				{
					answers(key.data, 0);
					answers(value.data, 1);
					resultcount++;
				}
				while ((ret = (*_D.cursor)->c_get((*_D.cursor), &key, &value, DB_NEXT)) == 0)
				{
					if (strcmp((char *)key.data, mintomatch) < 0)
					{
						// Bad key
					}
					else if (strcmp((char *)key.data, maxtomatch) > 0)
					{
						// Bad key
					}
					else
					{
						answers(key.data, 0);
						answers(value.data, 1);
						resultcount++;
					}
				}
				clock_readtime(&end); // End query
			}
			printf("Elapsed Time (microseconds): %lu\n", diff_time(end, start));
			printf("Total Records Returned: %d\n", resultcount);
			break;
		case 5:
			_D.destroy(&_D, file);
			break;
		case 6:
			_D.destroy(&_D, file);
			break;
		}
		if (task == 6)
		{
			break;
		}
	}
}


text:
class App < Sinatra::Base

  use Rack::Session::Cookie , :secret => (ENV['SESSION_SECRET'] || "82e042cd6fde2bf1764f777236db799e")

  fields = ["id", "email-address", "first-name", "last-name", "headline", "industry", "picture-url", "public-profile-url", "location", "skills"]

  use OmniAuth::Builder do
    provider :facebook, ENV['FACEBOOK_APP_ID'], ENV['FACEBOOK_SECRET'], :scope => 'user_likes, user_location, friends_likes, friends_location', :client_options => {:ssl => {:ca_file => "./cacert.pem"}}
  end

  Dir.glob(File.dirname(__FILE__) + '/helpers/*', &method(:require))
  helpers App::Helpers

  # Homepage
  get '/' do
    if current_user.nil?
      haml :index, :layout => :layout
    else
      redirect to("/user/#{current_user.uid}")
    end
  end

  # Authentication
  ['get', 'post'].each do |method|
    send(method, "/auth/:provider/callback") do
      user = User.create_with_omniauth(env['omniauth.auth'])
      session[:uid] = user.uid

      redirect to(session[:redirect_url] || "/user/#{session[:uid]}")
      session[:redirect_url] = nil
    end
  end

  get '/auth/failure/?' do
    raise 'auth error'
  end

  get '/logout/?' do
    session.clear
    redirect to('/')
  end

  # Users
  get '/user/:id' do
    @user = user(params[:id])
    @friends_count = @user.friends_count
    @likes_count = @user.likes_count
    haml :'user/show'
  end

  get '/user/:id/friends' do
    @user = user(params[:id])
    @friends = @user.friends
    haml :'user/index'
  end

  get '/user/:id/likes' do
    @user = user(params[:id])
    @things = @user.likes
    haml :'thing/index'
  end

  get '/user/:id/visualization' do
    @user = user(params[:id])
    haml :'user/visualization'
  end

  get '/visualization' do
    @user = current_user
    random_number = 20 + Random.rand(31)
    @user.friend_matrix.sample(random_number).map{|fm| {"name" => fm[0], "follows" => fm[1]} }.to_json

  end

  # Things
  get '/thing/:id' do
    @thing = Thing.get_by_id(params[:id])
    @users = @thing.users
    haml :'thing/show'
  end

end

redpajama_set_name: RedPajamaGithub


text:
package org.springframework.web.reactive.result.view;

import java.util.HashMap;
import java.util.Map;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import org.springframework.context.support.GenericApplicationContext;
import org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest;
import org.springframework.web.testfixture.server.MockServerWebExchange;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Unit tests for {@link RequestContext}.
 * @author Rossen Stoyanchev
 */
public class RequestContextTests {

	private final MockServerWebExchange exchange =
			MockServerWebExchange.from(MockServerHttpRequest.get("/foo/path").contextPath("/foo"));

	private GenericApplicationContext applicationContext;

	private Map<String, Object> model = new HashMap<>();

	@BeforeEach
	public void init() {
		this.applicationContext = new GenericApplicationContext();
		this.applicationContext.refresh();
	}

	@Test
	public void testGetContextUrl() throws Exception {
		RequestContext context = new RequestContext(this.exchange, this.model, this.applicationContext);
		assertThat(context.getContextUrl("bar")).isEqualTo("/foo/bar");
	}

	@Test
	public void testGetContextUrlWithMap() throws Exception {
		RequestContext context = new RequestContext(this.exchange, this.model, this.applicationContext);
		Map<String, Object> map = new HashMap<>();
		map.put("foo", "bar");
		map.put("spam", "bucket");
		assertThat(context.getContextUrl("{foo}?spam={spam}", map)).isEqualTo("/foo/bar?spam=bucket");
	}

	@Test
	public void testGetContextUrlWithMapEscaping() throws Exception {
		RequestContext context = new RequestContext(this.exchange, this.model, this.applicationContext);
		Map<String, Object> map = new HashMap<>();
		map.put("foo", "bar baz");
		map.put("spam", "&bucket=");
		assertThat(context.getContextUrl("{foo}?spam={spam}", map)).isEqualTo("/foo/bar%20baz?spam=%26bucket%3D");
	}

}


text:
namespace BABYLON {
namespace MaterialsLibrary {

CustomShaderStructure::CustomShaderStructure() =  default;

CustomShaderStructure::~CustomShaderStructure() = default;

} // end of namespace MaterialsLibrary
} // end of namespace BABYLON


text:
class SubstitutionsParser {
public:
    SubstitutionsParser ();
    ~SubstitutionsParser ();

    // Парсинг замен с сайта стхп.
    std::vector<std::string> parse_substitutions () const;

private:
    // Обрезает "лишнее" тело ответа от сайта стхп, оставляя только замены.
    void cut_useless_body (std::string& html_text,
        const std::string& begin, const std::string& end) const;

    // Удаляет весь текст который находится в </> и сами скобочки.
    void cut_html_tags (std::string& html_text) const;

    // Удаление мусора.
    void remove_trash (std::string& text) const;

    // Сплит строки.
    std::vector<std::string> split (const std::string& text) const;

private:
    std::unique_ptr<HttpRequests> m_requests;
};


text:
"""
PyCOMPSs Testbench
========================
"""

# Imports
import unittest

from modules.testCOMPSsDecorator import TestCOMPSsDecorator

def main():
    suite = unittest.TestLoader().loadTestsFromTestCase(TestCOMPSsDecorator)
    unittest.TextTestRunner(verbosity=2).run(suite)

if __name__ == "__main__":
    main()


text:
class UsersController < ApplicationController
  before_action :set_user, except: [:create]

  def new
    @user = User.new
  end

  def show
    render json: @user
  end

  def create
    @user = User.new(user_params)

    if @user.save
      create_session(@user)
      render json: @user
    else
      render json: @user.errors, status: :unprocessable_entity
    end
  end

  def destroy
    @user.destroy

    render json: User.all
  end

  def update
    if @user.update(user_params)
      render json: @user
    else
      render json: @user.errors, status: :unprocessable_entity
    end
  end

  private

  def set_user
    @user = User.find(params[:id])
  end

  def user_params
    # REVIEW why does this fix it? (removing require)
    # http://stackoverflow.com/questions/29815610/using-angular-and-rails-bcrypt-throwing-an-error-when-trying-to-create-user
    # params.require(:user).permit(:username, :password, :password_confirmation)
    params.permit(:username, :password, :password_confirmation,
                  :last_page_edit_id, :last_page_play_id,
                  :last_page_edit_story_id, :last_page_play_story_id)
  end
end


text:
<?php

namespace Johnguild\Muffincms;

use Illuminate\Support\ServiceProvider;

class MuffincmsServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->loadRoutesFrom(__DIR__.'/routes.php');

        $this->loadMigrationsFrom(__DIR__.'/migrations');

        $this->loadViewsFrom(__DIR__.'/MVC/views', 'muffincms');

        $this->publishes([
            __DIR__.'/config' => base_path('config'),
        ], 'muffin_config');

        $this->publishes([
           __DIR__.'/overrides/routes' => base_path('routes'),
        ], 'muffin_route');

        $this->publishes([
           __DIR__.'/overrides/migrations' => base_path('database/migrations'),
        ], 'muffin_admin');

        $this->publishes([
            __DIR__.'/overrides/app' => base_path('app'),
            __DIR__.'/overrides/auth' => base_path('app/http/controllers/auth'),
        ], 'muffin_auth');

        $this->publishes([
            __DIR__.'/mvc/views/pages' => base_path('resources/views/vendor/muffincms/pages'),
            __DIR__.'/mvc/views/users' => base_path('resources/views/vendor/muffincms/users'),
        ], 'muffin_views');

        $this->publishes([
            __DIR__.'/public' => public_path('vendor/muffincms'),
        ], 'muffin_public');
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        // include __DIR__.'/Routes/web.php';
        // $this->app->make('Johnguild\Muffincms\TestController');
        require_once __DIR__ . '/Helpers/Contents.php';
        require_once __DIR__ . '/Helpers/Slugger.php';
        require_once __DIR__ . '/Helpers/Setter.php';
        require_once __DIR__ . '/Helpers/Flasher.php';
    }

}


text:
#pragma once

#include <QtDesigner>
#include <qplugin.h>

class Plugin : public QObject, public QDesignerCustomWidgetCollectionInterface
{
    Q_OBJECT
    Q_INTERFACES(QDesignerCustomWidgetCollectionInterface)
#if QT_VERSION >= 0x050000
    Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QDesignerCustomWidgetCollectionInterface")
#endif // QT_VERSION >= 0x050000

public:
    explicit Plugin(QObject *parent = 0);

    virtual QList<QDesignerCustomWidgetInterface*> customWidgets() const;

private:
    QList<QDesignerCustomWidgetInterface*> m_widgets;
};


text:
package org.deeplearning4j.models.sequencevectors.graph.walkers.impl;

import org.deeplearning4j.models.sequencevectors.graph.enums.NoEdgeHandling;
import org.deeplearning4j.models.sequencevectors.graph.enums.WalkDirection;
import org.deeplearning4j.models.sequencevectors.graph.exception.NoEdgesException;
import org.deeplearning4j.models.sequencevectors.graph.primitives.Graph;
import org.deeplearning4j.models.sequencevectors.graph.primitives.IGraph;
import org.deeplearning4j.models.sequencevectors.graph.primitives.Vertex;
import org.deeplearning4j.models.sequencevectors.graph.vertex.AbstractVertexFactory;
import org.deeplearning4j.models.sequencevectors.graph.walkers.GraphWalker;
import org.deeplearning4j.models.sequencevectors.sequence.Sequence;
import org.deeplearning4j.models.word2vec.VocabWord;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.junit.Assert.*;

/**
 * @author raver119@gmail.com
 */
public class RandomWalkerTest {

    private static IGraph<VocabWord, Double> graph;
    private static IGraph<VocabWord, Double> graphBig;
    private static IGraph<VocabWord, Double> graphDirected;

    protected static final Logger logger = LoggerFactory.getLogger(RandomWalkerTest.class);

    @Before
    public void setUp() throws Exception {
        if (graph == null) {
            graph = new Graph<>(10, false, new AbstractVertexFactory<VocabWord>());

            for (int i = 0; i < 10; i++) {
                graph.getVertex(i).setValue(new VocabWord(i, String.valueOf(i)));

                int x = i + 3;
                if (x >= 10) x = 0;
                graph.addEdge(i, x, 1.0, false);
            }

            graphDirected = new Graph<>(10, false, new AbstractVertexFactory<VocabWord>());

            for (int i = 0; i < 10; i++) {
                graphDirected.getVertex(i).setValue(new VocabWord(i, String.valueOf(i)));

                int x = i + 3;
                if (x >= 10) x = 0;
                graphDirected.addEdge(i, x, 1.0, true);
            }

            graphBig = new Graph<>(1000, false, new AbstractVertexFactory<VocabWord>());

            for (int i = 0; i < 1000; i++) {
                graphBig.getVertex(i).setValue(new VocabWord(i, String.valueOf(i)));

                int x = i + 3;
                if (x >= 1000) x = 0;
                graphBig.addEdge(i, x, 1.0, false);
            }
        }
    }

    @Test
    public void testGraphCreation() throws Exception {
        Graph<VocabWord, Double> graph = new Graph<>(10, false, new AbstractVertexFactory<VocabWord>());

        // we have 10 elements
        assertEquals(10,graph.numVertices());

        for (int i = 0; i < 10; i++) {
            Vertex<VocabWord> vertex = graph.getVertex(i);
            assertEquals(null, vertex.getValue());
            assertEquals(i, vertex.vertexID());
        }
        assertEquals(10, graph.numVertices());
    }

    @Test
    public void testGraphTraverseRandom1() throws Exception {
        RandomWalker<VocabWord> walker = (RandomWalker<VocabWord>) new RandomWalker.Builder<>(graph)
                .setNoEdgeHandling(NoEdgeHandling.SELF_LOOP_ON_DISCONNECTED)
                .setWalkLength(3)
                .build();

        int cnt = 0;
        while (walker.hasNext()) {
            Sequence<VocabWord> sequence = walker.next();

            assertEquals(3, sequence.getElements().size());
            assertNotEquals(null, sequence);

            for (VocabWord word: sequence.getElements()) {
                assertNotEquals(null, word);
            }

            cnt++;
        }

        assertEquals(10, cnt);
    }

    @Test
    public void testGraphTraverseRandom2() throws Exception {
        RandomWalker<VocabWord> walker = (RandomWalker<VocabWord>) new RandomWalker.Builder<>(graph)
                .setNoEdgeHandling(NoEdgeHandling.EXCEPTION_ON_DISCONNECTED)
                .setWalkLength(20)
                .setWalkDirection(WalkDirection.FORWARD_UNIQUE)
                .setNoEdgeHandling(NoEdgeHandling.CUTOFF_ON_DISCONNECTED)
                .build();

        int cnt = 0;
        while (walker.hasNext()) {
            Sequence<VocabWord> sequence = walker.next();

            assertTrue(sequence.getElements().size() <= 10);
            assertNotEquals(null, sequence);

            for (VocabWord word: sequence.getElements()) {
                assertNotEquals(null, word);
            }

            cnt++;
        }

        assertEquals(10, cnt);
    }

    @Test
    public void testGraphTraverseRandom3() throws Exception {
        RandomWalker<VocabWord> walker = (RandomWalker<VocabWord>) new RandomWalker.Builder<>(graph)
                .setNoEdgeHandling(NoEdgeHandling.EXCEPTION_ON_DISCONNECTED)
                .setWalkLength(20)
                .setWalkDirection(WalkDirection.FORWARD_UNIQUE)
                .setNoEdgeHandling(NoEdgeHandling.EXCEPTION_ON_DISCONNECTED)
                .build();

        try {
            while (walker.hasNext()) {
                Sequence<VocabWord> sequence = walker.next();
                logger.info("Sequence: " + sequence);
            }

            // if cycle passed without exception - something went bad
            assertTrue(false);
        } catch (NoEdgesException e) {
            // this cycle should throw exception
        } catch (Exception e) {
            assertTrue(false);
        }
    }

    @Test
    public void testGraphTraverseRandom4() throws Exception {
        RandomWalker<VocabWord> walker = (RandomWalker<VocabWord>) new RandomWalker.Builder<>(graphBig)
                .setNoEdgeHandling(NoEdgeHandling.EXCEPTION_ON_DISCONNECTED)
                .setWalkLength(20)
                .setWalkDirection(WalkDirection.FORWARD_UNIQUE)
                .setNoEdgeHandling(NoEdgeHandling.CUTOFF_ON_DISCONNECTED)
                .build();

        Sequence<VocabWord> sequence1 = walker.next();

        walker.reset(true);

        Sequence<VocabWord> sequence2 = walker.next();

        assertNotEquals(sequence1.getElements().get(0), sequence2.getElements().get(0));
    }

    @Test
    public void testGraphTraverseRandom5() throws Exception {
        RandomWalker<VocabWord> walker = (RandomWalker<VocabWord>) new RandomWalker.Builder<>(graphBig)
                .setWalkLength(20)
                .setWalkDirection(WalkDirection.FORWARD_UNIQUE)
                .setNoEdgeHandling(NoEdgeHandling.CUTOFF_ON_DISCONNECTED)
                .build();

        Sequence<VocabWord> sequence1 = walker.next();

        walker.reset(false);

        Sequence<VocabWord> sequence2 = walker.next();

        assertEquals(sequence1.getElements().get(0), sequence2.getElements().get(0));
    }

    @Test
    public void testGraphTraverseRandom6() throws Exception {
        GraphWalker<VocabWord> walker = new RandomWalker.Builder<>(graphDirected)
                .setWalkLength(20)
                .setWalkDirection(WalkDirection.FORWARD_UNIQUE)
                .setNoEdgeHandling(NoEdgeHandling.CUTOFF_ON_DISCONNECTED)
                .build();

        Sequence<VocabWord> sequence = walker.next();
        assertEquals("0", sequence.getElements().get(0).getLabel());
        assertEquals("3", sequence.getElements().get(1).getLabel());
        assertEquals("6", sequence.getElements().get(2).getLabel());
        assertEquals("9", sequence.getElements().get(3).getLabel());

        assertEquals(4, sequence.getElements().size());
    }
}


text:
Given /^the time is frozen at (.+)(?: in zone "(.*?)")?$/ do |time, zone|
  zone ||= @current_user.try(:time_zone) || 'UTC'
  Timecop.freeze ActiveSupport::TimeZone[zone].parse time
end


text:
package org.xcolab.service.utils.db.jooq.fulltext;

import org.jooq.Record1;
import org.jooq.SQLDialect;
import org.jooq.SelectConditionStep;
import org.jooq.impl.DefaultDSLContext;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.xcolab.service.utils.db.jooq.test.generated.ContestTable.CONTEST;

public class FulltextConditionTest {

    private final DefaultDSLContext dslContext = new DefaultDSLContext(SQLDialect.MYSQL);

    @Test
    public void testSimpleCondition() {
        final FulltextCondition condition = new FulltextCondition("test", CONTEST.DESCRIPTION);
        final SelectConditionStep<Record1<String>> query =
                dslContext.select(CONTEST.DESCRIPTION).from(CONTEST).where(condition);
        assertEquals("condition not rendered correctly",
                "select `contest__contest`.`description`\n"
                        + "from `contest__contest`\n"
                        + "where (MATCH (description) AGAINST ('test'))",
                query.toString());
    }

    @Test
    public void testQueryWithSpecialCharacters__shouldEscapeCorrectly() {
        final FulltextCondition condition = new FulltextCondition("test' or 'a' = 'a", CONTEST.DESCRIPTION);
        final SelectConditionStep<Record1<String>> query =
                dslContext.select(CONTEST.DESCRIPTION).from(CONTEST).where(condition);
        assertEquals("sql injection possible",
                "select `contest__contest`.`description`\n"
                        + "from `contest__contest`\n"
                        + "where (MATCH (description) AGAINST ('test'' or ''a'' = ''a'))",
                query.toString());
    }
}


text:
Rails.application.routes.draw do
  root to: 'walls#index'
  resources :walls
  mount InnerMessage::Engine => "/inner_message"
end


text:
<?php
class Model_SalidasProductos extends Zend_Db_Table_Abstract {
	protected $_name = 'salidas_productos';

	public function new_order($id_salida,$id_producto,$num_serie){
		$data = array('id_salida' => $id_salida, 'id_producto' => $id_producto,'num_serie' => $num_serie);

		return $this->insert($data);
	}

	public function update_order($id_salida, $id_producto, $num_serie){
		$data = array('num_serie' => $num_serie);

		$where = $this->getAdapter()->quoteInto('id_producto = ? AND id_salida = ?', $id_producto, $id_salida);
		return $this->update($data, $where);
	}

	public function delete_order($id_salida,$id_producto,$num_serie){
		$where = $this->getAdapter()->quoteInto('id_salida = ? AND id_producto = ? AND num_serie = ?', $id_salida, $id_producto, $num_serie);
		return $this->delete($where); //the number of rows deleted
	}

	public function getSalidaProductos($id_salida){
		$where = $this->getAdapter()->quoteInto('id_salida = ?',$id_salida);
		return $this->fetchAll($where);
	}

}


text:
namespace Dewey.Build
{
    public interface IBuildActionFactory
    {
        IBuildAction CreateBuildAction(string buildType);
    }
}


text:
package org.apache.lens.cube.parse;

import static org.apache.lens.cube.error.LensCubeErrorCode.CANNOT_USE_TIMERANGE_WRITER;
import static org.apache.lens.cube.metadata.DateFactory.*;
import static org.apache.lens.cube.metadata.UpdatePeriod.CONTINUOUS;
import static org.apache.lens.cube.metadata.UpdatePeriod.DAILY;
import static org.apache.lens.cube.parse.CubeQueryConfUtil.FAIL_QUERY_ON_PARTIAL_DATA;
import static org.apache.lens.cube.parse.CubeTestSetup.*;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.lens.cube.metadata.UpdatePeriod;
import org.apache.lens.server.api.error.LensException;

import org.apache.hadoop.conf.Configuration;

import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TestTimeRangeWriterWithQuery extends TestQueryRewrite {

  private Configuration conf;
  private final String cubeName = TEST_CUBE_NAME;

  @BeforeTest
  public void setupDriver() throws Exception {
    conf = new Configuration();
    conf.set(CubeQueryConfUtil.DRIVER_SUPPORTED_STORAGES, "C1,C2");
    conf.setBoolean(CubeQueryConfUtil.DISABLE_AUTO_JOINS, false);
    conf.setBoolean(CubeQueryConfUtil.ENABLE_SELECT_TO_GROUPBY, true);
    conf.setBoolean(CubeQueryConfUtil.ENABLE_GROUP_BY_TO_SELECT, true);
    conf.setBoolean(CubeQueryConfUtil.DISABLE_AGGREGATE_RESOLVER, false);
    conf.setClass(CubeQueryConfUtil.TIME_RANGE_WRITER_CLASS,
      BetweenTimeRangeWriter.class.asSubclass(TimeRangeWriter.class), TimeRangeWriter.class);
  }

  private Date getOneLess(Date in, int calField) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(in);
    cal.add(calField, -1);
    return cal.getTime();
  }

  private Date getUptoHour(Date in) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(in);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    return cal.getTime();
  }

  @Test
  public void testCubeQueryContinuousUpdatePeriod() throws Exception {
    LensException th = null;
    try {
      rewrite("select" + " SUM(msr2) from testCube where " + TWO_DAYS_RANGE, conf);
    } catch (LensException e) {
      th = e;
      log.error("Semantic exception while testing cube query.", e);
    }
    if (!isZerothHour()) {
      Assert.assertNotNull(th);
      Assert
      .assertEquals(th.getErrorCode(), CANNOT_USE_TIMERANGE_WRITER.getLensErrorInfo().getErrorCode());
    }
    // hourly partitions for two days
    conf.setBoolean(FAIL_QUERY_ON_PARTIAL_DATA, true);
    DateFormat qFmt = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
    String twoDaysInRangeClause = getTimeRangeString(DAILY, -2, 0, qFmt);

    String hqlQuery = rewrite("select SUM(msr2) from testCube" + " where " + twoDaysInRangeClause, conf);
    Map<String, String> whereClauses = new HashMap<String, String>();
    whereClauses.put(
      getDbName() + "c1_testfact",
      TestBetweenTimeRangeWriter.getBetweenClause(cubeName, "dt",
        getDateWithOffset(DAILY, -2), getDateWithOffset(DAILY, 0), CONTINUOUS.format()));
    String expected = getExpectedQuery(cubeName, "select sum(testcube.msr2) FROM ", null, null, whereClauses);
    System.out.println("HQL:" + hqlQuery);
    TestCubeRewriter.compareQueries(hqlQuery, expected);

    // multiple range query
    //from date 6 days back
    String fourDaysInRangeClause = getTimeRangeString(DAILY, -6, 0, qFmt);

    hqlQuery =
      rewrite("select SUM(msr2) from testCube" + " where " + twoDaysInRangeClause + " OR "
        + fourDaysInRangeClause, conf);

    whereClauses = new HashMap<String, String>();
    whereClauses.put(
      getDbName() + "c1_testfact",
      TestBetweenTimeRangeWriter.getBetweenClause(cubeName, "dt", getDateWithOffset(DAILY, -2),
        getDateWithOffset(DAILY, 0), CONTINUOUS.format())
        + " OR"
        + TestBetweenTimeRangeWriter.getBetweenClause(cubeName, "dt", getDateWithOffset(DAILY, -6),
        getDateWithOffset(DAILY, 0), CONTINUOUS.format()));
    expected = getExpectedQuery(cubeName, "select sum(testcube.msr2) FROM ", null, null, whereClauses);
    System.out.println("HQL:" + hqlQuery);
    TestCubeRewriter.compareQueries(hqlQuery, expected);

    // format option in the query
    conf.set(CubeQueryConfUtil.PART_WHERE_CLAUSE_DATE_FORMAT, "yyyy-MM-dd HH:mm:ss");
    hqlQuery = rewrite("select SUM(msr2) from testCube" + " where " + TWO_DAYS_RANGE, conf);
    whereClauses = new HashMap<String, String>();
    whereClauses.put(getDbName() + "c1_testfact", TestBetweenTimeRangeWriter.getBetweenClause(cubeName,
      "dt", getUptoHour(TWODAYS_BACK),
      getUptoHour(NOW), TestTimeRangeWriter.DB_FORMAT));
    expected = getExpectedQuery(cubeName, "select sum(testcube.msr2) FROM ", null, null, whereClauses);
    System.out.println("HQL:" + hqlQuery);
    TestCubeRewriter.compareQueries(hqlQuery, expected);
  }

  @Test
  public void testCubeQueryWithTimeDim() throws Exception {
    Configuration tconf = new Configuration(conf);
    // hourly partitions for two days
    tconf.setBoolean(FAIL_QUERY_ON_PARTIAL_DATA, true);
    tconf.set(CubeQueryConfUtil.DRIVER_SUPPORTED_STORAGES, "C4");
    tconf.setBoolean(CubeQueryConfUtil.REPLACE_TIMEDIM_WITH_PART_COL, false);
    tconf.set(CubeQueryConfUtil.PART_WHERE_CLAUSE_DATE_FORMAT, "yyyy-MM-dd HH:mm:ss");
    tconf.set(CubeQueryConfUtil.getValidUpdatePeriodsKey("testfact", "C4"), "MONTHLY,DAILY,HOURLY");

    String query =
      "SELECT test_time_dim, msr2 FROM testCube where " + TWO_DAYS_RANGE_TTD;
    String hqlQuery = rewrite(query, tconf);
    Map<String, String> whereClauses = new HashMap<String, String>();
    whereClauses.put(getDbName() + "c4_testfact2", TestBetweenTimeRangeWriter.getBetweenClause("timehourchain1",
      "full_hour", getUptoHour(TWODAYS_BACK),
      getUptoHour(getOneLess(NOW, UpdatePeriod.HOURLY.calendarField())), TestTimeRangeWriter.DB_FORMAT));
    System.out.println("HQL:" + hqlQuery);
    String expected =
      getExpectedQuery(cubeName, "select timehourchain1.full_hour, sum(testcube.msr2) FROM ", " join " + getDbName()
          + "c4_hourDimTbl timehourchain1 on testcube.test_time_dim_hour_id  = timehourchain1.id", null,
        " GROUP BY timehourchain1.full_hour", null, whereClauses);
    TestCubeRewriter.compareQueries(hqlQuery, expected);

    query =
      "SELECT msr2 FROM testCube where " + TWO_DAYS_RANGE_TTD;
    hqlQuery = rewrite(query, tconf);
    System.out.println("HQL:" + hqlQuery);
    expected =
      getExpectedQuery(cubeName, "select sum(testcube.msr2) FROM ", " join " + getDbName()
        + "c4_hourDimTbl timehourchain1 on testcube.test_time_dim_hour_id  = timehourchain1.id", null, null, null,
        whereClauses);
    TestCubeRewriter.compareQueries(hqlQuery, expected);

    query =
      "SELECT msr2 FROM testCube where testcube.cityid > 2 and " + TWO_DAYS_RANGE_TTD + " and testcube.cityid != 5";
    hqlQuery = rewrite(query, tconf);
    System.out.println("HQL:" + hqlQuery);
    expected =
      getExpectedQuery(cubeName, "select sum(testcube.msr2) FROM ", " join " + getDbName()
          + "c4_hourDimTbl timehourchain1 on testcube.test_time_dim_hour_id  = timehourchain1.id",
        " testcube.cityid > 2 ",
        " and testcube.cityid != 5", null, whereClauses);
    TestCubeRewriter.compareQueries(hqlQuery, expected);

    // multiple range query
    hqlQuery =
      rewrite(
        "select SUM(msr2) from testCube" + " where " + TWO_DAYS_RANGE_TTD
          + " OR " + TWO_DAYS_RANGE_TTD_BEFORE_4_DAYS, tconf);

    whereClauses = new HashMap<>();
    whereClauses.put(
      getDbName() + "c4_testfact2",
      TestBetweenTimeRangeWriter.getBetweenClause("timehourchain1", "full_hour", getUptoHour(TWODAYS_BACK),
        getUptoHour(getOneLess(NOW, UpdatePeriod.HOURLY.calendarField())),
        TestTimeRangeWriter.DB_FORMAT)
        + " OR "
        + TestBetweenTimeRangeWriter.getBetweenClause("timehourchain1", "full_hour", getUptoHour(BEFORE_6_DAYS),
        getUptoHour(getOneLess(BEFORE_4_DAYS, UpdatePeriod.HOURLY.calendarField())),
        TestTimeRangeWriter.DB_FORMAT));
    expected =
      getExpectedQuery(cubeName, "select sum(testcube.msr2) FROM ", " join " + getDbName()
        + "c4_hourDimTbl timehourchain1 on testcube.test_time_dim_hour_id  = timehourchain1.id", null, null, null,
        whereClauses);
    System.out.println("HQL:" + hqlQuery);
    TestCubeRewriter.compareQueries(hqlQuery, expected);

    hqlQuery =
      rewrite(
        "select to_date(test_time_dim), SUM(msr2) from testCube" + " where " + TWO_DAYS_RANGE_TTD
          + " OR " + TWO_DAYS_RANGE_TTD_BEFORE_4_DAYS, tconf);

    expected =
      getExpectedQuery(cubeName, "select to_date(timehourchain1.full_hour), sum(testcube.msr2) FROM ", " join "
          + getDbName() + "c4_hourDimTbl timehourchain1 on testcube.test_time_dim_hour_id  = timehourchain1.id", null,
        " group by to_date(timehourchain1.full_hour)", null, whereClauses);
    System.out.println("HQL:" + hqlQuery);
    TestCubeRewriter.compareQueries(hqlQuery, expected);
  }

  @Test
  public void testCubeQueryWithTimeDimThruChain() throws Exception {
    // hourly partitions for two days
    Configuration tconf = new Configuration(conf);
    tconf.setBoolean(FAIL_QUERY_ON_PARTIAL_DATA, true);
    tconf.set(CubeQueryConfUtil.DRIVER_SUPPORTED_STORAGES, "C4");
    tconf.setBoolean(CubeQueryConfUtil.REPLACE_TIMEDIM_WITH_PART_COL, false);
    tconf.set(CubeQueryConfUtil.PART_WHERE_CLAUSE_DATE_FORMAT, "yyyy-MM-dd HH:mm:ss");
    tconf.set(CubeQueryConfUtil.getValidUpdatePeriodsKey("testfact", "C4"), "MONTHLY,DAILY,HOURLY");

    String query =
      "SELECT test_time_dim2, msr2 FROM testCube where " + TWO_DAYS_RANGE_TTD2;
    String hqlQuery = rewrite(query, tconf);
    Map<String, String> whereClauses = new HashMap<String, String>();
    whereClauses.put(getDbName() + "c4_testfact2", TestBetweenTimeRangeWriter.getBetweenClause(
      "timehourchain2", "full_hour", getUptoHour(TWODAYS_BACK),
      getUptoHour(getOneLess(NOW, UpdatePeriod.HOURLY.calendarField())), TestTimeRangeWriter.DB_FORMAT));
    System.out.println("HQL:" + hqlQuery);
    String expected =
      getExpectedQuery(cubeName, "select timehourchain2.full_hour, sum(testcube.msr2) FROM ", " join " + getDbName()
          + "c4_hourDimTbl timehourchain2 on testcube.test_time_dim_hour_id2  = timehourchain2.id", null,
        " GROUP BY timehourchain2.full_hour", null, whereClauses);
    TestCubeRewriter.compareQueries(hqlQuery, expected);

    query =
      "SELECT msr2 FROM testCube where " + TWO_DAYS_RANGE_TTD2;
    hqlQuery = rewrite(query, tconf);
    System.out.println("HQL:" + hqlQuery);
    expected =
      getExpectedQuery(cubeName, "select sum(testcube.msr2) FROM ", " join " + getDbName()
        + "c4_hourDimTbl timehourchain2 on testcube.test_time_dim_hour_id2  = timehourchain2.id", null, null, null,
        whereClauses);
    TestCubeRewriter.compareQueries(hqlQuery, expected);

    query =
      "SELECT msr2 FROM testCube where testcube.cityid > 2 and " + TWO_DAYS_RANGE_TTD2 + " and testcube.cityid != 5";
    hqlQuery = rewrite(query, tconf);
    System.out.println("HQL:" + hqlQuery);
    expected =
      getExpectedQuery(cubeName, "select sum(testcube.msr2) FROM ", " join " + getDbName()
          + "c4_hourDimTbl timehourchain2 on testcube.test_time_dim_hour_id2  = timehourchain2.id",
          " testcube.cityid > 2 ", " and testcube.cityid != 5", null, whereClauses);
    TestCubeRewriter.compareQueries(hqlQuery, expected);

    // multiple range query
    hqlQuery =
      rewrite(
        "select SUM(msr2) from testCube" + " where " + TWO_DAYS_RANGE_TTD2
          + " OR " + TWO_DAYS_RANGE_TTD2_BEFORE_4_DAYS, tconf);

    whereClauses = new HashMap<>();
    whereClauses.put(
      getDbName() + "c4_testfact2",
      TestBetweenTimeRangeWriter.getBetweenClause("timehourchain2", "full_hour", getUptoHour(TWODAYS_BACK),
        getUptoHour(getOneLess(NOW, UpdatePeriod.HOURLY.calendarField())),
        TestTimeRangeWriter.DB_FORMAT)
        + " OR "
        + TestBetweenTimeRangeWriter.getBetweenClause("timehourchain2", "full_hour", getUptoHour(BEFORE_6_DAYS),
        getUptoHour(getOneLess(BEFORE_4_DAYS, UpdatePeriod.HOURLY.calendarField())),
        TestTimeRangeWriter.DB_FORMAT));
    expected =
      getExpectedQuery(cubeName, "select sum(testcube.msr2) FROM ", " join " + getDbName()
        + "c4_hourDimTbl timehourchain2 on testcube.test_time_dim_hour_id2  = timehourchain2.id", null, null, null,
        whereClauses);
    System.out.println("HQL:" + hqlQuery);
    TestCubeRewriter.compareQueries(hqlQuery, expected);

    hqlQuery =
      rewrite(
        "select to_date(test_time_dim2), SUM(msr2) from testCube" + " where " + TWO_DAYS_RANGE_TTD2
          + " OR " +TWO_DAYS_RANGE_TTD2_BEFORE_4_DAYS, tconf);

    expected =
      getExpectedQuery(cubeName, "select to_date(timehourchain2.full_hour), sum(testcube.msr2) FROM ", " join "
          + getDbName() + "c4_hourDimTbl timehourchain2 on testcube.test_time_dim_hour_id2  = timehourchain2.id", null,
        " group by to_date(timehourchain2.full_hour)", null, whereClauses);
    System.out.println("HQL:" + hqlQuery);
    TestCubeRewriter.compareQueries(hqlQuery, expected);
  }

}


text:
package backend;

public class RegStates {
	private static RegStates instance;
	ReserStation[] sourceStations;
	float regValues[];
	static final int REG_NUM = 11;
	@Override
	public String toString() {
		String ret = "";
		for(int i = 0; i < regValues.length; ++i) {
			ret += i + "\t";
			ret += regValues[i] + "\t";
			ret += (sourceStations[i] == null ? " " :sourceStations[i].getName()) + "\n";
		}
//		ret += 1 + "\t" + regValues[1] + "\t" + sourceStations[1].getName() + "\n";
//		ret += 2 + "\t" + regValues[2] + "\t" + sourceStations[2].getName() + "\n";
//		ret += 3 + "\t" + regValues[3] + "\t" + sourceStations[3].getName() + "\n";
//		ret += 4 + "\t" + regValues[4] + "\t" + sourceStations[4].getName() + "\n";
//		ret += 5 + "\t" + regValues[5] + "\t" + sourceStations[5].getName() + "\n";
		return ret;
	}
	private RegStates(int num) {
		sourceStations = new ReserStation[num];
		regValues = new float[num];
	}

	public static RegStates getInstance() {
		if(instance == null) {
			instance = new RegStates(REG_NUM);
		}
		return instance;
	}

	public boolean isRegToWrite(int ind) {
		return sourceStations[ind] != null;
	}

	public float getRegValue(int ind) {
		return regValues[ind];
	}

	public ReserStation getSourceStation(int ind) {
		return sourceStations[ind];
	}

	public void setSourceStation(int ind, ReserStation src) {
		sourceStations[ind] = src;
	}

	public void setReg(int ind, float result) {
		regValues[ind] = result;
	}

	public void reset() {
		for(int i = 0;i < REG_NUM;i++) {
			regValues[i] = 0;
			sourceStations[i] = null;
		}
	}

}


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<meta http-equiv="X-UA-COMPATIBLE" content="IE=edge, chrome=1">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>Vector Table</title>
		<link rel="stylesheet" href="resources/css/TWB.css" />

 Home

 About TWB

 Help

Device Data

Pin Maps

Patterns

Project Reports

					<form class="form-group-up">

							<button class="btn btn-default navbar-btn">First</button>
							Cycle:
							<input type="number" name="cycle" data-ng-model="cycleVal"=min="0" max="100">
							<button class="btn btn-default navbar-btn">Go to</button>
							<button class="btn btn-default navbar-btn">Last</button>
							(Test Pattern: {{cycleVal}})

							<button class="btn btn-default navbar-btn">[ ←</button>
							<button class="btn btn-default navbar-btn">] ←</button>
							<button class="btn btn-default navbar-btn">→ [</button>
							<button class="btn btn-default navbar-btn">→ ]</button>

					</form>

								<input data-ng-model ="name" type = "text" size="10">
								[{{$index}}]

								{{data.name}}
								{{data.data[$index]}}

2007 - 2015 © Teseda Corporation - info@teseda.com


text:
id: 587d781a367417b2b2512ab9
title: Use the em Tag to Italicize Text
challengeType: 0
videoUrl: ''
localeTitle: Используйте тег em для текста курсива
---

## Description

 Чтобы подчеркнуть текст, вы можете использовать тег em . Это отображает текст как курсив, так как браузер применяет CSS стиля font-style: italic; к элементу.

## Instructions

 Оберните тег em вокруг содержимого тега абзаца, чтобы подчеркнуть его.

## Tests

```yml
tests:
  - text: Ваш код должен добавить тег <code>em</code> в разметку.
    testString: 'assert($("em").length == 1, "Your code should add an <code>em</code> tag to the markup.");'
  - text: Тег <code>em</code> должен обертывать содержимое тега <code>p</code> но не сам тег <code>p</code> .
    testString: 'assert($("p").children().length == 1 && $("em").children().length == 2, "The <code>em</code> tag should wrap around the contents of the <code>p</code> tag but not the <code>p</code> tag itself.");'

```

## Challenge Seed

```html
<style>
  h4 {
    text-align: center;
    height: 25px;
  }
  p {
    text-align: justify;
  }
  .links {
    text-align: left;
    color: black;
  }
  .fullCard {
    width: 245px;
    border: 1px solid #ccc;
    border-radius: 5px;
    margin: 10px 5px;
    padding: 4px;
  }
  .cardContent {
    padding: 10px;
  }
  .cardText {
    margin-bottom: 30px;
  }
</style>
<div class="fullCard">
  <div class="cardContent">
    <div class="cardText">
      <h4>Google</h4>
      <p>Google was founded by Larry Page and Sergey Brin while they were <u>Ph.D. students</u> at <strong>Stanford University</strong>.</p>
    </div>
    <div class="cardLinks">
      <a href="https://en.wikipedia.org/wiki/Larry_Page" target="_blank" class="links">Larry Page</a><br><br>
      <a href="https://en.wikipedia.org/wiki/Sergey_Brin" target="_blank" class="links">Sergey Brin</a>
    </div>
  </div>
</div>

```

## Solution

```js
// solution required
```


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>org.locationtech.geomesa</groupId>
        <artifactId>geomesa-hbase_2.11</artifactId>
        <version>3.0.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>geomesa-hbase-jobs_2.11</artifactId>
    <name>GeoMesa HBase Jobs</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.locationtech.geomesa</groupId>
            <artifactId>geomesa-hbase-datastore_${scala.binary.version}</artifactId>
        </dependency>
        <dependency>
            <groupId>org.locationtech.geomesa</groupId>
            <artifactId>geomesa-jobs_${scala.binary.version}</artifactId>
        </dependency>

        <!-- provided dependencies -->
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-mapreduce</artifactId>
        </dependency>

        <!-- test dependencies -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
        </dependency>
        <dependency>
            <groupId>org.specs2</groupId>
            <artifactId>specs2-core_${scala.binary.version}</artifactId>
        </dependency>
        <dependency>
            <groupId>org.specs2</groupId>
            <artifactId>specs2-junit_${scala.binary.version}</artifactId>
        </dependency>
    </dependencies>

</project>


text:
本Rails Engine是为了方便公众号运维人员统一管理公众号的开发接口,不同公众号由同一个Rails管理和驱动,对不同的公众号,可实现如下功能:

1. 修改自定义菜单
2. 实现网页授权登录,获取用户信息并保存在数据库
3. 接收微信服务器推送信息,实现自动回复和其他高级功能

## 如何使用

Gemfile:

```
gem 'weixin_pem'
```

config/routes:

```
mount WeixinPam::Engine => '/'
```

启动Rails server

```
bundle exec rails s
```

访问:http://localhost:3000/public_accounts 即可添加/删除公众号配置

## 修改自定义菜单

点击已添加的公众号名字,点击"微信菜单"按钮,该页面可实现如下功能

1. 下载公众号菜单
2. 上传公众号菜单
3. 添加菜单到数据库
4. 移动菜单到"未启用的列表"
5. 对菜单排序

## 如何使用多公众号网页授权

本例子使用Devise作为用户登录模块,用到gem omniauth-wechat-oauth2

Gemfile中:

```
gem 'devise'
gem "omniauth-wechat-oauth2"
```
config/initializers/devise.rb

```
require 'omniauth_setup'
# 此处 setup: OmniauthSetup是关键,他实现不同公众号的api身份切换
config.omniauth :wechat, nil, nil, setup: OmniauthSetup
```

lib/omniauth_setup.rb

```
class OmniauthSetup
  # OmniAuth expects the class passed to setup to respond to the #call method.
  # env - Rack environment
  def self.call(env)
    new(env).setup
  end

  # Assign variables and create a request object for use later.
  # env - Rack environment
  def initialize(env)
    @env = env
    @request = ActionDispatch::Request.new(env)
  end

  # The main purpose of this method is to set the consumer key and secret.
  def setup
    @env['omniauth.strategy'].options.merge!(custom_credentials)
    puts
    puts @env['omniauth.strategy'].options.inspect
    puts
  end

  private

  # Use the subdomain in the request to find the account with credentials
  def custom_credentials
    h = {}
    scope = @request.params.delete(:scope).presence
    h[:scope] = scope if scope
    if account = WeixinPam::PublicAccount.find_by(host: @request.host)
      h.update client_id: account.app_id, client_secret: account.app_secret
    end
    h
  end

end
```

config/routes.rb

```
devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }
```

app/controllers/users/omniauth_callbacks_controller.rb

```
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def wechat
    public_account = WeixinPam::PublicAccount.find_by!(host: request.host)
    ua = WeixinPam::UserAccount.from_omniauth(public_account, request.env["omniauth.auth"])
    if ua.user.persisted?
      update_stored_location_url ua.user
      sign_in_and_redirect ua.user, :event => :authentication
      set_flash_message(:notice, :success, :kind => '微信') if is_navigational_format?
    else
      session["devise.wechat_data"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end

  private

  def update_stored_location_url(user)
    if url = request.env['omniauth.params']['redirect'] || request.env['omniauth.origin']
      store_location_for user, url
    end
  end
end

```
## 如何多公众号响应微信服务器事件推送

创建的公众号如果不填写"微信服务器事件推送的响应Class",WeixinPam会使用开发模式下的默认值PublicAccountReply(lib/public_account_reply.rb)

针对不同公众号,我们可以编写不同的Reply Class去继承PublicAccountReply,实现不同公众号有不同的回复内容。

## 用Devise保护资源

添加config/initializers/weixin_pam.rb,加入如下代码
```

WeixinPam::ApplicationController.class_eval do
  before_action :authenticate_user!
  before_action :ensure_admin_user

  private

  def ensure_admin_user
    fail "没有访问权限" unless current_user.admin?
  end
end


text:
from __future__ import absolute_import

from collections import namedtuple
from datetime import datetime as DateTime

try:
    import django
    from django.conf.urls import url
    from django.conf import empty
    from django.test import Client
except (ImportError, SyntaxError):
    # Django 1.8 does not support Python 2.6 anymore, importing the module
    # triggers a SyntaxError which causes builds to fail.
    django = None
from nose import SkipTest
from pythonic_testcase import *

from soapfish.django_ import django_dispatcher
from soapfish.testutil import echo_service
from soapfish.lib.attribute_dict import AttrDict

Urlconf = namedtuple('Urlconf', 'urlpatterns')

class DjangoDispatchTest(PythonicTestCase):
    def setUp(self):
        if django is None:
            raise SkipTest('django not installed')
        super(DjangoDispatchTest, self).setUp()
        self.service = echo_service()
        if django.conf.settings.__dict__['_wrapped'] is empty:
            django.conf.settings.configure(self.django_settings())

            django.conf.settings.update(AttrDict(
                ROOT_URLCONF=Urlconf(
                    urlpatterns=(
                        url(r"^ws/$", django_dispatcher(self.service)),
                    )
                ),
            ))
        django.setup()
        self.client = Client()

    def test_can_retrieve_wsdl_via_django(self):
        response = self.client.get('/ws/', {'wsdl': None})
        assert_equals(200, response.status_code)
        assert_equals('text/xml', response.get('Content-Type'))
        assert_contains('<wsdl:definitions', response.content.decode('utf8'))

    def test_can_dispatch_simple_request_through_django(self):
        input_value = str(DateTime.now())
        headers, body = self._soap_request(input_value)
        response = self.client.post('/ws/', body, **headers)
        assert_equals(200, response.status_code)
        body = self._parse_soap_response(response.content)
        assert_equals(input_value, body.value)

    # --- internal helpers ----------------------------------------------------
    def _soap_request(self, input_value):
        SOAP = self.service.version
        method = self.service.get_method('echoOperation')

        headers = SOAP.build_http_request_headers(method.soapAction)
        request_headers = self.as_django_client_headers(headers)
        tagname = method.input
        EchoType = self.service.schema.get_element_by_name('echoRequest')._type
        echo = EchoType.create(input_value)
        request_body = SOAP.Envelope.response(tagname, echo)
        return request_headers, request_body

    def _parse_soap_response(self, response_body):
        SOAP = self.service.version
        method = self.service.get_method('echoOperation')

        envelope = SOAP.Envelope.parsexml(response_body)
        assert_none(envelope.Body.Fault)
        output_element = self.service.schema.get_element_by_name(method.output)
        output_ = output_element._type.__class__
        return envelope.Body.parse_as(output_)

    def as_django_client_headers(self, headers):
        request_headers = {}
        for header_name, value in headers.items():
            key = 'HTTP_'+header_name.upper() if (header_name != 'content-type') else 'content_type'
            request_headers[key] = value
        return request_headers

    def django_settings(self):
        return AttrDict(
            DEFAULT_CHARSET='utf8',
            DEBUG=False,
            INSTALLED_APPS=[
                'django.contrib.auth',
                'django.contrib.contenttypes',
            ],
            MIDDLEWARE_CLASSES = (
                'django.contrib.sessions.middleware.SessionMiddleware',
                'django.middleware.common.CommonMiddleware',
                'django.middleware.csrf.CsrfViewMiddleware',
                'django.contrib.auth.middleware.AuthenticationMiddleware',
                'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
                'django.contrib.messages.middleware.MessageMiddleware',
                'django.middleware.clickjacking.XFrameOptionsMiddleware',
            ),
            CACHES={'default': {'BACKEND': 'django.core.cache.backends.dummy.DummyCache'}},
            SESSION_ENGINE='django.contrib.sessions.backends.cache',
            DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3'}},
            DEFAULT_TABLESPACE='',
            DEFAULT_INDEX_TABLESPACE='',
            ABSOLUTE_URL_OVERRIDES={},
            TRANSACTIONS_MANAGED=False,
            USE_TZ=True,
            FORCE_SCRIPT_NAME=None,
            DEBUG_PROPAGATE_EXCEPTIONS=True,
            SESSION_COOKIE_NAME='soapfish',
            SESSION_CACHE_ALIAS='default',
            SESSION_SERIALIZER='django.contrib.sessions.serializers.PickleSerializer',
            USE_X_FORWARDED_HOST=False,
            USE_X_FORWARDED_PORT=False,
            SECURE_PROXY_SSL_HEADER=None,
            ALLOWED_HOSTS=['testserver'],
            CSRF_COOKIE_NAME='csrftoken',
            PREPEND_WWW=False,
            APPEND_SLASH=False,
            MESSAGE_STORAGE='django.contrib.messages.storage.fallback.FallbackStorage',
            USE_I18N=False,
            LANGUAGE_CODE='en',
            ROOT_URLCONF=None,
            DEFAULT_CONTENT_TYPE='text/html',
            SEND_BROKEN_LINK_EMAILS=False,
            USE_ETAGS=False,
            SESSION_SAVE_EVERY_REQUEST=False,
            LOGGING_CONFIG=None,
            LOGGING=None,
        )


text:
var _holder = new DataView(new ArrayBuffer(24));
var _offset = 1.5;
var _value = 1.5;
var _is_little_endian = true;
%DataViewSetFloat32(_holder, _offset, _value, _is_little_endian);


text:
<?xml version="1.0" encoding="UTF-8"?>
<AuraDefinitionBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>40.0</apiVersion>
    <description>SharingComponent</description>
</AuraDefinitionBundle>


text:
pub mod flags;
pub mod load_cargo;
mod parse;
mod symbols;
mod highlight;
mod analysis_stats;
mod diagnostics;
mod ssr;
mod lsif;
mod scip;

mod progress_report;

use std::io::Read;

use anyhow::Result;
use ide::AnalysisHost;
use vfs::Vfs;

#[derive(Clone, Copy)]
pub enum Verbosity {
    Spammy,
    Verbose,
    Normal,
    Quiet,
}

impl Verbosity {
    pub fn is_verbose(self) -> bool {
        matches!(self, Verbosity::Verbose | Verbosity::Spammy)
    }
    pub fn is_spammy(self) -> bool {
        matches!(self, Verbosity::Spammy)
    }
}

fn read_stdin() -> Result<String> {
    let mut buff = String::new();
    std::io::stdin().read_to_string(&mut buff)?;
    Ok(buff)
}

fn report_metric(metric: &str, value: u64, unit: &str) {
    if std::env::var("RA_METRICS").is_err() {
        return;
    }
    println!("METRIC:{}:{}:{}", metric, value, unit)
}

fn print_memory_usage(mut host: AnalysisHost, vfs: Vfs) {
    let mut mem = host.per_query_memory_usage();

    let before = profile::memory_usage();
    drop(vfs);
    let vfs = before.allocated - profile::memory_usage().allocated;
    mem.push(("VFS".into(), vfs));

    let before = profile::memory_usage();
    drop(host);
    mem.push(("Unaccounted".into(), before.allocated - profile::memory_usage().allocated));

    mem.push(("Remaining".into(), profile::memory_usage().allocated));

    for (name, bytes) in mem {
        // NOTE: Not a debug print, so avoid going through the `eprintln` defined above.
        eprintln!("{:>8} {}", bytes, name);
    }
}


text:
module PgAssets
  class PgConstraint < ActiveRecord::Base
    include LoadableAsset

    self.table_name = 'pg_catalog.pg_constraint'

    after_find do
      self.cached_defn = get_constraint_defn
    end

    scope :ours, -> {
      joins('JOIN pg_catalog.pg_namespace ON (pg_constraint.connamespace = pg_namespace.oid)').
      where('pg_namespace.nspname NOT IN (?)', ['pg_catalog', 'information_schema']).
      where('conrelid != 0')  #exclude non-table constraints.  Not sure what to do with domain constraints yet
    }

    def identity
      "#{conname} on #{get_table_name}"
    end

    def sql_for_remove
      "ALTER TABLE #{get_table_name} DROP CONSTRAINT IF EXISTS #{conname}"
    end

    def sql_for_reinstall
      "#{sql_for_remove}; ALTER TABLE #{get_table_name} ADD CONSTRAINT #{conname} #{cached_defn};"
    end

    private

    def get_oid
      sql = "SELECT oid FROM pg_catalog.pg_constraint WHERE conname = '#{conname}' AND connamespace = '#{connamespace}'"
      get_attribute_from_sql sql, :oid
    end

    def get_table_name
      sql = "SELECT relname FROM pg_catalog.pg_class WHERE oid = #{conrelid}"
      get_attribute_from_sql sql, :relname
    end

    def get_constraint_defn
      sql = "SELECT pg_get_constraintdef(#{get_oid}, true) AS constraintdef"
      get_attribute_from_sql sql, :constraintdef
    end
  end
end


text:
Highlights trailing whitespace.

## Installation ##

Use the Atom package manager, which can be found in the Settings view or run `apm install trailing-spaces`  from the command line.

## Configuration ##

Configuration options are available for:
- Enable/disable highlight on lines with a cursor
- Enable/disable highlight on lines which contain only indentation

## Screenshot ##

![](http://snag.gy/OpJpI.jpg)


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.07.02 at 03:35:23 PM MSK
//

package ru.gov.zakupki.oos.types._1;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 * Перечень бизнес-контролей для загрузки
 *
 *
Java class for zfcs_nsiBusinessControlsType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="zfcs_nsiBusinessControlsType">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="nsiBusinessControl" type="{http://zakupki.gov.ru/oos/types/1}zfcs_nsiBusinessControlType" maxOccurs="unbounded"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "zfcs_nsiBusinessControlsType", propOrder = {
    "nsiBusinessControl"
})
public class ZfcsNsiBusinessControlsType {

    @XmlElement(required = true)
    protected List<ZfcsNsiBusinessControlType> nsiBusinessControl;

    /**
     * Gets the value of the nsiBusinessControl property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the nsiBusinessControl property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getNsiBusinessControl().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link ZfcsNsiBusinessControlType }
     *
     *
     */
    public List<ZfcsNsiBusinessControlType> getNsiBusinessControl() {
        if (nsiBusinessControl == null) {
            nsiBusinessControl = new ArrayList<ZfcsNsiBusinessControlType>();
        }
        return this.nsiBusinessControl;
    }

}


text:
package io.cattle.platform.api.schema;

import io.cattle.platform.object.meta.ObjectMetaDataManager;
import io.cattle.platform.object.meta.Relationship;
import io.cattle.platform.util.type.Named;
import io.github.ibuildthecloud.gdapi.factory.impl.SubSchemaFactory;
import io.github.ibuildthecloud.gdapi.model.impl.SchemaImpl;

import java.util.Map;

import javax.inject.Inject;

public class ObjectBasedSubSchemaFactory extends SubSchemaFactory implements Named {

    ObjectMetaDataManager metaDataManager;

    @Override
    protected void prune(SchemaImpl schema) {
        super.prune(schema);

        schema.getIncludeableLinks().clear();

        Map<String,Relationship> rels = metaDataManager.getLinkRelationships(this, schema.getId());
        if ( rels == null || rels.size() == 0 ) {
            return;
        } else {
            schema.getIncludeableLinks().addAll(rels.keySet());
        }
    }

    public ObjectMetaDataManager getMetaDataManager() {
        return metaDataManager;
    }

    @Inject
    public void setMetaDataManager(ObjectMetaDataManager metaDataManager) {
        this.metaDataManager = metaDataManager;
    }

    @Override
    public String getName() {
        return "schema:" + getId();
    }

}


text:
package com.lujiahao.mapping.pojo;

import java.util.Date;

public class TbContent {
    private Long id;

    private Long categoryId;

    private String title;

    private String subTitle;

    private String titleDesc;

    private String url;

    private String pic;

    private String pic2;

    private Date created;

    private Date updated;

    private String content;

    public TbContent(Long id, Long categoryId, String title, String subTitle, String titleDesc, String url, String pic, String pic2, Date created, Date updated, String content) {
        this.id = id;
        this.categoryId = categoryId;
        this.title = title;
        this.subTitle = subTitle;
        this.titleDesc = titleDesc;
        this.url = url;
        this.pic = pic;
        this.pic2 = pic2;
        this.created = created;
        this.updated = updated;
        this.content = content;
    }

    public Long getId() {
        return id;
    }

    public Long getCategoryId() {
        return categoryId;
    }

    public String getTitle() {
        return title;
    }

    public String getSubTitle() {
        return subTitle;
    }

    public String getTitleDesc() {
        return titleDesc;
    }

    public String getUrl() {
        return url;
    }

    public String getPic() {
        return pic;
    }

    public String getPic2() {
        return pic2;
    }

    public Date getCreated() {
        return created;
    }

    public Date getUpdated() {
        return updated;
    }

    public String getContent() {
        return content;
    }
}


text:
package com.caiyi.dailywork.ui;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

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

/**
 * Created by RZQ on 2017/4/1.
 */

public class FlowView extends ViewGroup {
    private static final int LEFT = -1;
    private static final int CENTER = -1;
    private static final int RIGHT = -1;

    protected List<List<View>> mAllViews = new ArrayList<>();
    protected List<Integer> mLineHeight = new ArrayList<>();
    protected List<Integer> mLineWidth = new ArrayList<>();

    private int mGravity;
    private List<View> lineViews = new ArrayList<>();

    public FlowView(Context context) {
        this(context, null);
    }

    public FlowView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FlowView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mGravity = LEFT;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
        int modeHeight = MeasureSpec.getMode(heightMeasureSpec);

        //wrap_content
        int width = 0;
        int height = 0;

        int lineWidth = 0;
        int lineHeight = 0;

        int cCount = getChildCount();

        for (int i = 0; i < cCount; i++) {
            View child = getChildAt(i);
            if (child.getVisibility() == View.GONE) {
                if (i == cCount - 1) {
                    width = Math.max(lineWidth, width);
                }
                continue;
            }
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
            int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
            int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;

            if (lineWidth + childWidth > sizeWidth - getPaddingLeft() - getPaddingRight()) {
                width = Math.max(width, lineWidth);
                lineWidth = childWidth;
                height += lineHeight;
                lineHeight = childHeight;
            } else {
                lineWidth += childWidth;
                lineHeight = Math.max(lineHeight, childHeight);
            }
            if (i == cCount - 1) {
                width = Math.max(lineWidth, width);
                height += lineHeight;
            }
        }
        setMeasuredDimension(
                modeWidth == MeasureSpec.EXACTLY ? sizeWidth : width + getPaddingLeft() + getPaddingRight(),
                modeHeight == MeasureSpec.EXACTLY ? sizeHeight : height + getPaddingTop() + getPaddingBottom()
        );
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        mAllViews.clear();
        mLineHeight.clear();
        mLineWidth.clear();
        lineViews.clear();

        int width = getWidth();

        int lineWidth = 0;
        int lineHeight = 0;

        int cCount = getChildCount();

        for (int i = 0; i < cCount; i++) {
            View child = getChildAt(i);
            if (child.getVisibility() == View.GONE) continue;
            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
            int childWidth = child.getMeasuredWidth();
            int childHeight = child.getMeasuredHeight();

            if (childWidth + lineWidth + lp.leftMargin + lp.rightMargin > width - getPaddingLeft() - getPaddingRight()) {
                mLineHeight.add(lineHeight);
                mAllViews.add(lineViews);
                mLineWidth.add(lineWidth);

                lineWidth = 0;
                lineHeight = childHeight + lp.topMargin + lp.bottomMargin;
                lineViews = new ArrayList<View>();
            }
            mLineHeight.add(lineHeight);
            mLineWidth.add(lineWidth);
            mAllViews.add(lineViews);

            int left = getPaddingLeft();
            int top = getPaddingTop();

            int lineNum = mAllViews.size();

        }
    }
}


text:
import logging
import re
from django.http import HttpResponse
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_exempt
from hiicart.gateway.veritrans_air.ipn import VeritransAirIPN
from hiicart.utils import format_exceptions, cart_by_id, format_data

logger = logging.getLogger("hiicart.gateway.veritrans_air")

def _find_cart(data):
    # invoice may have a suffix due to retries
    order = data.get('orderId')
    if not order:
        logger.warn("No orderId # in data, aborting IPN")
        return None
    return cart_by_id(order)

@csrf_exempt
@format_exceptions
@never_cache
def ipn(request):
    """
    Veritrans Air IPN

    Confirms that payment has been completed and marks invoice as paid.
    """
    if request.method != "POST":
        logger.error("IPN Request not POSTed")
        return HttpResponse("ERR")

    data = request.POST.copy()

    # invoice may have a suffix due to retries
    retry = False
    for key in data.keys():
        # orderId is in both CSV and CC IPNs
        if key.startswith('orderId'):
            # has suffix / is a retry - fix keys
            if re.match('\d', key[-1]):
                data = {re.sub('\d', '', k): v for k, v in data.iteritems()}
                retry = True
            continue
    cart = _find_cart(data)
    if retry:
        logger.info(
            "Retry %s with IPN: \n%s" % (re.sub('[^\d]', '', key), format_data(data))
        )
    else:
        logger.info("IPN Received:\n%s" % format_data(data))
    if not cart:
        logger.error("veritrans air gateway: Unknown transaction: %s" % data)
        return HttpResponse("ERR")

    handler = VeritransAirIPN(cart)
    if data.get('cvsType'):
        if not handler.confirm_cvs_ipn_data(data):
            logger.error("Veritrans Air CVS IPN Confirmation Failed.")
        handler.accept_payment(data)
    else:
        # Verify the data with Veritrans
        if not handler.confirm_ipn_data(data):
            logger.error("Veritrans Air IPN Confirmation Failed.")
            return HttpResponse("ERR")

        status = data["mStatus"]

        if status == 'success':
            handler.accept_payment(data)
        elif status == 'pending':
            handler.payment_pending(data)

    return HttpResponse("OK")


text:
package com.fuhj.itower.service;

import java.io.Serializable;

public interface AbstractService extends Serializable {

}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright 2019 Google LLC
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     https://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<transitionSet
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:interpolator/fast_out_slow_in">

    <transition class="com.google.samples.apps.iosched.widget.transition.RotateX">
        <targets>
            <target android:targetId="@id/expand_icon" />
        </targets>
    </transition>

    <autoTransition android:duration="200" />

</transitionSet>


text:
package com.azure.resourcemanager.netapp.implementation;

import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.SimpleResponse;
import com.azure.core.util.Context;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.netapp.fluent.NetAppResourceQuotaLimitsClient;
import com.azure.resourcemanager.netapp.fluent.models.SubscriptionQuotaItemInner;
import com.azure.resourcemanager.netapp.models.NetAppResourceQuotaLimits;
import com.azure.resourcemanager.netapp.models.SubscriptionQuotaItem;

public final class NetAppResourceQuotaLimitsImpl implements NetAppResourceQuotaLimits {
    private static final ClientLogger LOGGER = new ClientLogger(NetAppResourceQuotaLimitsImpl.class);

    private final NetAppResourceQuotaLimitsClient innerClient;

    private final com.azure.resourcemanager.netapp.NetAppFilesManager serviceManager;

    public NetAppResourceQuotaLimitsImpl(
        NetAppResourceQuotaLimitsClient innerClient,
        com.azure.resourcemanager.netapp.NetAppFilesManager serviceManager) {
        this.innerClient = innerClient;
        this.serviceManager = serviceManager;
    }

    public PagedIterable<SubscriptionQuotaItem> list(String location) {
        PagedIterable<SubscriptionQuotaItemInner> inner = this.serviceClient().list(location);
        return Utils.mapPage(inner, inner1 -> new SubscriptionQuotaItemImpl(inner1, this.manager()));
    }

    public PagedIterable<SubscriptionQuotaItem> list(String location, Context context) {
        PagedIterable<SubscriptionQuotaItemInner> inner = this.serviceClient().list(location, context);
        return Utils.mapPage(inner, inner1 -> new SubscriptionQuotaItemImpl(inner1, this.manager()));
    }

    public SubscriptionQuotaItem get(String location, String quotaLimitName) {
        SubscriptionQuotaItemInner inner = this.serviceClient().get(location, quotaLimitName);
        if (inner != null) {
            return new SubscriptionQuotaItemImpl(inner, this.manager());
        } else {
            return null;
        }
    }

    public Response<SubscriptionQuotaItem> getWithResponse(String location, String quotaLimitName, Context context) {
        Response<SubscriptionQuotaItemInner> inner =
            this.serviceClient().getWithResponse(location, quotaLimitName, context);
        if (inner != null) {
            return new SimpleResponse<>(
                inner.getRequest(),
                inner.getStatusCode(),
                inner.getHeaders(),
                new SubscriptionQuotaItemImpl(inner.getValue(), this.manager()));
        } else {
            return null;
        }
    }

    private NetAppResourceQuotaLimitsClient serviceClient() {
        return this.innerClient;
    }

    private com.azure.resourcemanager.netapp.NetAppFilesManager manager() {
        return this.serviceManager;
    }
}


text:
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'rails'
require 'mongoid'
require 'dm-core'
require 'kaminari'
require 'database_cleaner'
# Ensure we use 'syck' instead of 'psych' in 1.9.2
# RubyGems >= 1.5.0 uses 'psych' on 1.9.2, but
# Psych does not yet support YAML 1.1 merge keys.
# Merge keys is often used in mongoid.yml
# See: http://redmine.ruby-lang.org/issues/show/4300
if RUBY_VERSION >= '1.9.2'
  YAML::ENGINE.yamler = 'syck'
end
require File.join(File.dirname(__FILE__), 'fake_gem')
require File.join(File.dirname(__FILE__), 'fake_app')

require 'rspec/rails'
# Requires supporting files with custom matchers and macros, etc,
# in ./support/ and its subdirectories.
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}

RSpec.configure do |config|
  config.mock_with :rr
  config.before :all do
#     ActiveRecord::Base.connection.execute 'CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255))' unless ActiveRecord::Base.connection.table_exists? 'users'
    CreateAllTables.up unless ActiveRecord::Base.connection.table_exists? 'users'
  end
end


text:
import { PUSH_MEDIA_TO_FAVORITES } from './const';

export default function action(index: Number) {
  return { type: PUSH_MEDIA_TO_FAVORITES, index };
}


text:
import { NativeModules } from 'react-native';
import { Buffer } from 'buffer';
import RSASign from 'jsrsasign';

const { Alipay } = NativeModules;

Alipay.sign = (object, privateKey) => {

  // Add default sign_type
  if (!object.sign_type || object.sign_type.length === 0) {
    object.sign_type = 'RSA';
  }

  // Remove sign field
  delete object.sign;

  // Remove empty field
  Object.keys(object).forEach((key) => {
    if (String(object[key]).length === 0) {
      delete object[key];
    }
  })

  // Sort query string
  var sortedQuery = '';
  let sortedKeys = Object.keys(object).sort((a, b) => a > b);
  for (var i = 0; i < sortedKeys.length; i++) {
    let key = sortedKeys[i];
    let value = object[key];
    sortedQuery += `${(i === 0) ? '' : '&'}${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
  }

  // Create signature
  let alg = {RSA: 'SHA1withRSA', RSA2: 'SHA256withRSA'}[object.sign_type];
  let sig = new RSASign.KJUR.crypto.Signature({alg});
  sig.init(RSASign.KEYUTIL.getKey(privateKey));
  sig.updateString(sortedQuery);
  let sign = Buffer.from(sig.sign(), 'hex').toString('base64');

  sortedQuery += `&sign=${encodeURIComponent(sign)}`;
  return sortedQuery;
}

export default Alipay;


text:
package org.apache.twill.internal.utils;

/**
 * Utility class to help adjusting container resource requirement.
 */
public final class Resources {

  /**
   * Computes the max heap size for a JVM process.
   *
   * @param containerMemory memory in MB of the container memory.
   *                        It is the maximum memory size allowed for the process.
   * @param nonHeapMemory memory in MB that needs to be reserved for non JVM heap memory for the process.
   * @param minHeapRatio minimum ratio for heap to non-heap memory.
   * @return memory in MB representing the max heap size for a JVM process.
   */
  public static int computeMaxHeapSize(int containerMemory, int nonHeapMemory, double minHeapRatio) {
    if (((double) (containerMemory - nonHeapMemory) / containerMemory) >= minHeapRatio) {
      // Reduce -Xmx by the reserved memory size.
      return containerMemory - nonHeapMemory;
    } else {
      // If it is a small VM, just discount it by the min ratio.
      return (int) Math.ceil(containerMemory * minHeapRatio);
    }
  }

  private Resources() {
  }
}


text:
ActiveRecord::Schema.define(version: 20170712200530) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "daily_menus", force: :cascade do |t|
    t.datetime "date", null: false
    t.string "content", null: false
    t.bigint "restaurant_id", null: false
    t.index ["restaurant_id"], name: "index_daily_menus_on_restaurant_id"
  end

  create_table "restaurants", force: :cascade do |t|
    t.string "type", null: false
    t.index ["type"], name: "index_restaurants_on_type", unique: true
  end

  add_foreign_key "daily_menus", "restaurants", on_delete: :cascade
end


text:
// SchematicFileSerializer.h

// Declares the cSchematicFileSerializer class representing the interface to load and save cBlockArea to a .schematic file

#pragma once

#include "../BlockArea.h"
#include "../StringCompression.h"

// fwd: FastNBT.h
class cParsedNBT;

class cSchematicFileSerializer
{
public:

	/** Loads an area from a .schematic file. */
	static void LoadFromSchematicFile(cBlockArea & a_BlockArea, const std::string & a_FileName);

	/** Loads an area from a string containing the .schematic file data. */
	static void LoadFromSchematicString(cBlockArea & a_BlockArea, ContiguousByteBufferView a_SchematicData);

	/** Saves the area into a .schematic file. */
	static void SaveToSchematicFile(const cBlockArea & a_BlockArea, const std::string & a_FileName);

	/** Saves the area into a string containing the .schematic file data. */
	static Compression::Result SaveToSchematicString(const cBlockArea & a_BlockArea);

private:

	/** Loads the area from a schematic file uncompressed and parsed into a NBT tree. */
	static void LoadFromSchematicNBT(cBlockArea & a_BlockArea, const cParsedNBT & a_NBT);

	/** Saves the area into a NBT representation and returns the NBT data as a string. */
	static ContiguousByteBuffer SaveToSchematicNBT(const cBlockArea & a_BlockArea);
};


text:
First, we recover all entries from https://bio.tools using `get_all_biotools.py` script which generates `all_biotools.json` file.

### Mapping between Galaxy wrappers and https://bio.tools entries

The second step is to perform mapping between Galaxy wrappers and entries on https://bio.tools.
You need to have downloaded all wrappers from the instance first (using: [get\_xmls\_from\_galaxy.py](https://github.com/khillion/galaxyxml-analysis/tree/master/galaxyxml_analysis)).
To do that, we used `xml_biotools_mapping.py` script.

```bash
python xml_biotools_mapping.py -d USEGALAXY -r USEGALAXY/download_report.json -b all_biotools.json -o
```

This generates a `mapping.tsv` file that needs to be manually curated prior to use.

### Manual curation of raw `mapping.tsv` file

Prior to run ToolDog to annotate every wrappers, we need to curate the `mapping.tsv` file.

#### Remove wrappers with no corresponding https://bio.tools entry

```bash
awk 'index($3, "[")' mapping.tsv
```

#### Maps wrapper to a unique entry

This step is done manually, to check which entry corresponds best to the wrapper.
For bedtools tools:
```bash
awk '{if($3~"bedtools") $3="bedtools";print}' FS="\t" OFS="\t" mapping.tsv
```
For emboss entries:
```bash
awk '{if($3~"emboss") $3="emboss";print}' FS="\t" OFS="\t" mapping.tsv
```

You end up with the `filtered\_mapping.tsv` file

### Running ToolDog on selected tools

All concerned wrappers were copied into `old_xmls` folder.
```bash
mkdir old_xmls
for i in `cut -f1 final_mapping.tsv`;do cp $i old_xmls;done
```
And paths are updated in the `filtered_mapping.tsv` to build `final_mapping.tsv`:
```bash
awk '{split($1,a,"/"); $1="old_xmls/"a[3]; print}' FS="\t" OFS="\t" filtered_mapping.tsv > final_mapping.tsv
```

Tools were annotated using [ToolDog](https://github.com/bio-tools/ToolDog). Results of annotation can be found in `new_xmls` folder.

#### Tools that could not be annotated (7 out of 224)

| Galaxy wrapper | Biotool entry | Reason |
| -------------- | ------------- | ------ |
| kraken.xml | kraken | Unable to load XML into `galaxyxml` because there is a param without `name` |
| rg_rnaStar.xml | star | Unable to load XML into `galaxyxml` because there is a param without `name` |
| kraken-filter.xml | kraken | Unable to load XML into `galaxyxml` because there is a param without `name` |
| fastq_combiner.xml | fastq_groomer_parallel-ip | TODO |
| closestBed.xml | bedtools | Unable to load XML into `galaxyxml` because there is a param without `name` |
| hisat2.xml | HISAT2 | Unable to load XML into `galaxyxml` because there is a param without `name` |
| diamond.xml | Diamond | Unable to load XML into `galaxyxml` because there is a param without `name` |

## 01 September 2017

Re-run analysis and counts number of tools based on different criteria (can be found in logs file):

| Title | Counts |
| ----- | ------ |
| Total number of tools cloned from toolshed | 665 |
| Tool description with `<citations>` | 455 |
| `<citations>` with DOI | 399 |
| Entry found corresponding to DOI on bio.tools | 224 |
| Edam terms retrieved from bio.tools | 217 |

Only 106 wrappers have been annotated with ToolDog (can be found in `new_xmls` folder)
because wrappers that cannot be loaded into the `galaxyxml` model or EDAM with no uri in bio.tools.


text:
using System;
using Xamarin.Forms;

namespace Xamarin.Forms.Controls
{
	public class AlertGallery : ContentPage
	{
		public AlertGallery ()
		{
			var lblResult = new Label { Text = "Result: ", AutomationId = "testResult" };

			var btn1 = new Button { Text = "Alert Override1", AutomationId = "test1" };
			btn1.Clicked += async (sender, e) => {
				await DisplayAlert ("TheAlertTitle", "TheAlertMessage", "TheCancelButton");;
			};

			var btn2 = new Button { Text = "Alert Override2", AutomationId = "test2" };
			btn2.Clicked += async (sender, e) => {
				var result = await DisplayAlert ("TheAlertTitle", "TheAlertMessage", "TheAcceptButton", "TheCancelButton");
				lblResult.Text = string.Format("Result: {0}", result);
			};

			Content =  new StackLayout {  Children = { lblResult, btn1, btn2 }};
		}
	}
}


text:
<?php

use \Cviebrock\EloquentSluggable\SluggableInterface;
use \Cviebrock\EloquentSluggable\SluggableTrait;
use \Lanz\Commentable\Commentable;
use Mmanos\Metable\Metable;

/**
 * Class Post
 *
 * @package Plugins\posts\models
 * @property integer $id
 * @property string $slug
 * @property string $title
 * @property string $content
 * @property boolean $status
 * @property \Carbon\Carbon $created_at
 * @property \Carbon\Carbon $updated_at
 * @property-read \Illuminate\Database\Eloquent\Collection|\Venturecraft\Revisionable\Revision[] $revisionHistory
 * @property-read \Illuminate\Database\Eloquent\Collection|\Lanz\Commentable\Comment[] $comments
 * @method static \Illuminate\Database\Query\Builder|\Page whereId($value)
 * @method static \Illuminate\Database\Query\Builder|\Page whereSlug($value)
 * @method static \Illuminate\Database\Query\Builder|\Page whereTitle($value)
 * @method static \Illuminate\Database\Query\Builder|\Page whereContent($value)
 * @method static \Illuminate\Database\Query\Builder|\Page whereStatus($value)
 * @method static \Illuminate\Database\Query\Builder|\Page whereCreatedAt($value)
 * @method static \Illuminate\Database\Query\Builder|\Page whereUpdatedAt($value)
 * @property string $layout
 * @method static \Illuminate\Database\Query\Builder|\Page whereLayout($value)
 * @property-read mixed $default_metas
 * @property-read \Illuminate\Database\Eloquent\Collection|\$this->metaModel()[] $metas
 */
class Page extends \Eloquent implements SluggableInterface
{
    use SluggableTrait;
    use \Venturecraft\Revisionable\RevisionableTrait;
    use Commentable,Metable,Feedable,Translatable;

    protected $table = 'pages';
    protected $appends = array('default_metas');

    protected $sluggable = array(
        'build_from' => 'title',
        'save_to'    => 'slug',
    );

    protected $meta_model = 'Meta';
    protected $metable_table = 'page_metas';

    protected $translatable = array('title','content');

    public function getDefaultMetasAttribute(){
        $metas = array();
        $desc = $this->meta('meta_description');
        $keyw = $this->meta('meta_keywords');
        if(is_null($desc)){
            $metas[] = array('name'=>'meta_description','value'=>'');
        }
        if(is_null($keyw)){
            $metas[] = array('name'=>'meta_keywords','value'=>'');
        }
        return $metas;
    }

    public function delete(){
        $this->comments()->delete();
        return parent::delete();
    }

    public function renderContent(){
        $content = $this->content;
        $oembed = new \AutoEmbed;
        $content = $oembed->parse($content);
        return $content;
    }

    public function save(array $options = array()){

        $this->title = ($this->title)?$this->title:'';
        $this->content = ($this->content)?$this->content:'';

        try{
            return parent::save($options);
        }catch(Exception $e){
            App::abort(500,'ERROR!');
        }
    }
}


text:
<!DOCTYPE html>

    <title>jsTester</title>
    <link rel="stylesheet" type="text/css" href="../public/stylesheets/style.css" />

jsTester


text:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>

<script>
function iframeLoad(iframe){
	var src = (iframe.src)?iframe.src:iframe.contentWindow.location.href;
	document.body.appendChild(document.createElement("br"));
	document.body.appendChild(document.createTextNode("IFAME 标记 src 值为 "+ src + " 的 onload 事件触发"));
}
function addEvent(eventName,element,fn){
	if (element.attachEvent) element.attachEvent("on"+eventName,fn);
	else element.addEventListener(eventName,fn,false);
}
window.onload = function (){
	var iframe = document.createElement('iframe');
	addEvent("load",iframe,function (){iframeLoad(iframe)});
	iframe.src= "about:blank";
	document.body.appendChild(iframe);
	setTimeout(function (){iframe.src="iframe.html";},300)
}
</script>
</body>
</html>


text:
<?xml version="1.0"?>
<sparql xmlns="http://www.w3.org/2005/sparql-results#"
        xml:base="http://example.org/boolean-result/">
  <head>
    <link href="metadata.rdf"/>
    <link href="http://bar.com/baz.ttl"/>
  </head>
  <boolean>true</boolean>
</sparql>


text:
package anubis.runtime.traits.func;

import anubis.AnubisObject;
import anubis.runtime.ABuiltinFunction;
import anubis.runtime.ANumber;
import anubis.runtime.AObjects;
import anubis.runtime.Utils;

public abstract class AbstractNumberFunction1 extends ABuiltinFunction._0 implements ANumber.UnaryOperator<Number> {
	public AbstractNumberFunction1() {
		super();
	}

	public AbstractNumberFunction1(AnubisObject owner, String name) {
		super(owner, name);
	}

	@Override
	protected AnubisObject exec(AnubisObject this1) {
		ANumber num = Utils.cast(ANumber.class, this1);
		return AObjects.getNumber(num.operate(this));
	}
}


text:
"""Module to read diverse format of structured files

Module based on the csv module (with tweaks)

Container can be used to put results in objects, list or tuples, with or without constraints

See tests (in __main__) for more detailed examples

"""

__all__ = ['TsvReader', 'CsvReader', 'StructuredReader']

from csv import DictReader
import csv

from definitions import ObjectContainer, TupleContainer, ListContainer

class StructuredReader(object):
    def __init__(self, filename, container = None, dialect = 'simplecsv'):
        self._container = None
        if isinstance(container, ObjectContainer):
            self._container = container
            self._reader = DictReader(filename, fieldnames = None, restkey = "restkey", restval = "restval", dialect = dialect)
        elif isinstance(container, TupleContainer) or isinstance(container, ListContainer):
            self._container = container
            self._reader = csv.reader(filename, dialect = dialect)
        else:
            raise Exception("Given container is not valid")

    def next(self):
        # do not treat the header row
        if self._reader.line_num == 0:
            self._reader.next()

        row = self._reader.next()
        return self._container.fetch(row)

    def __iter__(self):
        return self

class CsvReader(StructuredReader):
    def __init__(self, fileObj, container = None):
        StructuredReader.__init__(self, fileObj, container, dialect = 'simplecsv')

class TsvReader(StructuredReader):
    def __init__(self, fileObj, container = None):
        StructuredReader.__init__(self, fileObj, container, dialect = 'simpletsv')

# class Reader(object):
# def __init__(self, filename, resultContainer = None):
#         '''Create a new file reader
#
#         filename - path to the file to read
#         ncolumns - number of columns to read
#         columnMapping'''
#         self.__filename = filename
#         self.results = resultContainer
#
#     def readFile(self):
#         if os.path.isfile(self.__filename):
#             with open(self.__filename, 'r') as readFile:
#                 for singleLine in readFile:
#                     self.processLine(singleLine)
#
#     def processLine(self, line):
#         self.results.append(line)
# class StructuredReader(Reader):
#     LINE_SEPARATOR = r"\n"
#     COLUMN_SEPARATOR = r"\t"
#     COMMENT_CHARACTER = None
#
# #     FETCH_TUPLE = 1
# #     FETCH_OBJECT = 2
# #
# #     FETCH_LIST = 10
# #     FETCH_DICT = 20
#
#     def __init__(self, filename, ncolumns, fetchContainer, resultContainer):
#         '''Create a new file reader
#
#         filename - path to the file to read
#         ncolumns - number of columns to read
#         columnMapping'''
#         Reader.__init__(self, filename, resultContainer)
#         self.__ncolumns = ncolumns
#         self.__matcher = self.getMatcher()
#
#     def processLine(self, line):
#         match = self.__matcher.match(line)
#         if match is not None:
#             for colNum in range(1, self.getColumnNumber()):
#                 val = match.group(colNum)
#
#     def getLineSeparator(self):
#         return self.LINE_SEPARATOR
#
#     def getColumnSeparator(self):
#         return self.COLUMN_SEPARATOR
#
#     def getColumnNumber(self):
#         return self.__ncolumns
#
#     def getCommentCharacter(self):
#         return self.COMMENT_CHARACTER
#
#     def getMatcher(self):
#         # match a single column
#         match = r"(.*?)%s" % self.getColumnSeparator()
#         # multiply by the number of columns
#         match = match * self.getColumnNumber()
#         # match the rest of the line
#         match += r".*%s" % self.getLineSeparator()
#
#         if self.COMMENT_CHARACTER is not None:
#             match = r"[^%s]" % self.getCommentCharacter() + match
#
#         return re.compile(match)


text:
layout: default
title: CAS - Amazon Cloud Directory Authentication
category: Authentication
---
{% include variables.html %}

# Amazon Cloud Directory Authentication

Amazon Cloud Directory is a highly available multi-tenant directory-based store
in AWS. These directories scale automatically to hundreds of millions of
objects as needed for applications. This lets operation's staff
focus on developing and deploying applications that drive the business, not managing directory infrastructure.

To learn more, please [see this guide](http://docs.aws.amazon.com/directoryservice/latest/admin-guide/directory_amazon_cd.html).

## Configuration

Support is enabled by including the following dependency in the WAR overlay:

{% include casmodule.html group="org.apereo.cas" module="cas-server-support-cloud-directory-authentication" %}

{% include casproperties.html properties="cas.authn.cloud-directory"  %}

AWS credentials are fetched from the following sources automatically, where relevant
and made possible via CAS configuration:

1. EC2 instance metadata linked to the IAM role.
2. External properties file that contains `accessKey` and `secretKey` as property keys.
3. AWS profile path and profile name.
4. System properties that include `aws.accessKeyId`, `aws.secretKey` and `aws.sessionToken`
5. Environment variables that include `AWS_ACCESS_KEY_ID`, `AWS_SECRET_KEY` and `AWS_SESSION_TOKEN`.
6. Properties file on the classpath as `awscredentials.properties` that contains `accessKey` and `secretKey` as property keys.
7. Static credentials for access key and secret provided directly by the configuration at hand (logging, etc).

## Troubleshooting

To enable additional logging, configure the log4j configuration file to add the following levels:

```xml
...
<Logger name="com.amazonaws" level="debug" additivity="false">
    <AppenderRef ref="console"/>
    <AppenderRef ref="file"/>
</Logger>
...