text:
using System;
using NUnit.Framework;
using WizardFX;
using WizardFXTests.MockFactories;
using Moq;

namespace WizardFXTests
{
    [TestFixture]
    public class WizardViewTests
    {
        [Test]
        public void GiveAnUnstartedWizard_OnStarting_TheFirstStepIsSentToTheView()
        {
            var view = new MockViewFactory().AView.Mock();
            var controller = new WizardController(view.Object);

            var step = new WizardStep();
            var wizard = new Wizard()
                    .AddStep(step);

            controller.Start(wizard);
            view.Verify(m => m.ShowStep(step));
        }

        [Test]
        public void GivenAStartedWizard_OnMoveNext_TheSecondStepIsSentToTheView()
        {
            var view = new MockViewFactory().AView.Mock();
            var controller = new WizardController(view.Object);

            var step1 = new WizardStep();
            var step2 = new WizardStep();
            var wizard = new Wizard()
                    .AddStep(step1)
                    .AddStep(step2);

            controller.Start(wizard);
            view.Raise(v => v.MovedNext += null, EventArgs.Empty);
            view.Verify(m => m.ShowStep(step2));
        }

        [Test]
        public void GivenAStartedWizard_OnFinish_NoStepIsSentToTheView()
        {
            var view = new MockViewFactory().AView.Mock();
            var controller = new WizardController(view.Object);

            var step = new WizardStep();
            var wizard = new Wizard()
                    .AddStep(step);

            controller.Start(wizard);
            view.Raise(v => v.MovedNext += null, EventArgs.Empty);
            view.Verify(m => m.ShowStep(step), Times.AtMostOnce());
        }

        //[Test]
        //public void GivenAStartedWizard_OnFinish_ViewIsUnloaded()
        //{
        //    var view = new MockViewFactory().AView.Mock();
        //    var controller = new WizardController(view.Object);

        //    var step = new WizardStep();
        //    var wizard = new Wizard()
        //            .AddStep(step);

        //    controller.Start(wizard);
        //    view.Raise(v => v.MovedNext += null, EventArgs.Empty);
        //    view.Verify(m => m.Unload());
        //}

    }
}


text:
<link rel="import" href="../../bower_components/polymer/polymer.htm">
<script type="text/javascript">
MenuBehavior = {
  properties: {
    botaoVoltar: {
      type: Boolean,
      value: false,
      observer: '_botaoVoltarChanged'
    },
    titulo: {
      type: String,
      observer: '_tituloChanged'
    }
  },
  _tituloChanged: function(titulo) {
    this._onTituloAlterado(titulo);
  },
  _onTituloAlterado: function(titulo) {
    // abstract
  },
  ready: function() {
    this.classList.add('pastor-item-menu');
  },
  _botaoVoltarChanged: function(valor) {
    if (valor) {
      this._onMostraBotaoVoltar();
    } else {
      this._onEscondeBotaoVoltar();
    }
  },
  mostraBotaoVoltar: function() {
    this.botaoVoltar = true;
  },
  escondeBotaoVoltar: function() {
    this.botaoVoltar = false;
  },
  _onMostraBotaoVoltar: function() {
    // abstract
  },
  _onEscondeBotaoVoltar: function() {
    // abstract
  },
  _voltar: function() {
    //abstract
  }
}
</script>

redpajama_set_name: RedPajamaGithub


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends CI_Controller {

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     * 		http://example.com/index.php/welcome
     * 	- or -
     * 		http://example.com/index.php/welcome/index
     * 	- or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see https://codeigniter.com/user_guide/general/urls.html
     */
     public function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form','url'));
        $this->load->library(array('session', 'form_validation', 'email'));
        $this->load->database();
        $this->load->model('Init_models');
        $sessname = $this->session->userdata('susername');
        $sessid= $this->session->userdata('suserid');
    }

    public function index() {
         $banners = $this->Init_models->getadvertisebanners();

        $view_params = array(
            'm_title' => 'WelCome To EthioEdu',
            'title' => 'WelCome To EthioEdu',
               'banners' => $banners
        );
        $view_params['homenews'] = $this->Init_models->gethomenews();
        $view_params['homeschool'] = $this->Init_models->gethomeschool();
        $view_params['homeprojects'] = $this->Init_models->gethomeprojects();
        $view_params['homeevents'] = $this->Init_models->gethomeevents();
        $view_params['homevacancy'] = $this->Init_models->gethomevacancy();
        $view_params['homequestions'] = $this->Init_models->gethomequestion();
        $view_params['news'] = $this->Init_models->selectnews();
        $view_params['previous_vacancy'] = $this->Init_models->get_previous_vacancy();
        $this->load->view('home',$view_params);
    }

}


text:
  clazz(const clazz&) = delete; \
  clazz& operator =(const clazz&) = delete

namespace ulti {

typedef uint_fast32_t uint32;

}
#endif // ULTI_LIBULTI_COMMON_H


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
    <size
        android:height="4dp"
        android:width="4dp" />
    <solid android:color="#aaffffff"/>

</shape>


text:
/**
 * \file dict.h
 * \brief Gestion du dictionnaire
 * \author BESNIER Benjamin, DE ARAUJO Bastien, MOLION Enzo, VALETTE Léo
 *
 * Fichier contenant definitions et les fonctions utiles a la gestion du dictionnaire
 *
 */

#ifndef DICT_H
#define DICT_H
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef int bool ;
#define true 1
#define false 0

typedef short int dict_index_t;  	// le type index
typedef long dict_char_t;          // le type valeur/caractere

typedef struct _dict *dict_t;
typedef struct _node *noeud_t;

/**
*\enum dict_error_t
*\brief Type enumere gerrant les codes d'erreurs
*/
typedef enum {
  DICT_NOERROR=0,    // uniquement pour info et node_content
  DICT_NODICT=1,    // dictionnaire invalide
  DICT_INVALID=2,   // index ou prefixe invalide
  DICT_NOTFOUND=3,  // noeud cherche absent
  DICT_FOUND=4, 	// noeud (deja) present
	DICT_ADDED=5, 	// noeud ajoute
  DICT_FULL=6,      // erreur en insertion : plus de place
  DICT_FUNCERROR=7, // uniquement pour apply
  DICT_MALLOCERROR=8  // pour getstring
}dict_error_t;

// constantes dict_index_t
#define DICT_ROOT_INDEX	-1		// index de la racine
#define DICT_NONODE -2			// Index de noeud illegal

// constantes dict_char_t
#define DICT_CHAR_EOS	-1		// End of string (valeur de racine)
#define DICT_CHAR_NOCHAR -2		// Valeur indefinie

// TAILLE_MAX = 2^15
#define TAILLE_MAX 32768

/**
 * \struct hashmap
 * \brief Donne un pointeur de noeud et la longueur du mot associe
 */
typedef struct {
  noeud_t noeud;
  int taille ;
}hashmap;

/**
 * \struct _dict
 * \brief Dictionnaire défini par son nombre d'elements, le noeud racine et une map index -> noeud
 */
struct _dict{
  dict_index_t nb_elt ;
  noeud_t racine ;
  hashmap map[TAILLE_MAX] ;
};

/**
 * \struct _node
 * \brief Noeud defini par un symbole, un index, un pointeur vers son noeud pere, un pointeur vers son noeud frere et un pointeur vers son noeud fils
 */
struct _node {
  uint8_t sym ; // Le char suffixe
  dict_index_t code ; // Le code associe au symbole
  struct _node* frere ; // Le noeud suivant dans la liste de meme niveau
  struct _node* fils ; // Le noeud de profondeur superieure
  struct _node* pere ; // Le noeud de profondeur inferieure
};

#define EOM 256
#define AD 257
#define RD 258

/**
 * @brief      Affiche le dictionnaire (pour toute : entree index et symbole)
 *
 * @param[in]  dico  Le dictionnaire a afficher
 */
void dict_print (const dict_t dico);

/**
 * @brief   Alloue et renvoie un dictionnaire compose des prefixes de taille 1
 */
dict_t dict_new();

/**
 * @brief      Supprime dans le dictionnaire les entrees autres que des prefixes de taille 1
 *
 * @param[in,out]  dico  Le dictionnaire a reinitialiser
 */
dict_error_t dict_reinit(dict_t dico);

/**
 * @brief      Ajoute la chaine de caractere mot au dictionnaire dico
 *
 * @param[in,out]  dico        Le dictionnaire auquel on ajoute un mot
 * @param[in]      mot         Le mot a ajouter
 * @param[in]  taille_mot  le taille du mot
 *
 * @return     Le code d'erreur correspondant suivant l'execution de la fonction
 */

dict_error_t dict_insert(dict_t dico, const uint8_t* mot, const int taille_mot) ;

/**
 * @brief      Renvoie dans resultat le codage correspondant a mot
 *
 * @param[in]   dico        Le dictionnaire ou on recherche le codage
 * @param[in]   mot         Le mot a rechercher correspondant au codage
 * @param[in]   taille_mot  La taille du mot
 * @param[out]  resultat    Le resultat ou l'on stock le codage de mot
 * @param[out]  taille      La taille du codate en nombre de bits
 *
 */
dict_error_t dict_rechercher_mot(const dict_t dico, const uint8_t* mot, const int taille_mot, dict_index_t* resultat, int* taille);

/**
 * @brief      Renvoie dans resultat le mot correspondant au codage index
 *
 * @param[in]  dico      Le dictionnaire ou on recherche le mot
 * @param[in]  index     Le codage du mot a rechercher
 * @param[out]      resultat  L'index trouve
 * @param[out]  taille_resultat La taille du de l'index trouve (en nombre de bits)
 */
dict_error_t dict_rechercher_index(const dict_t dico, const dict_index_t index, uint8_t* resultat, int* taille_resultat);

/**
 * @brief      Permet de liberer la mémoire allouer pour le dictionnaire
 *
 * @param[in,out]  dico  Le dictionnaire a liberer
 */
void free_dico(dict_t dico);

#endif // DICT_H


text:
window.onload = function(){var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");

var startX = 85;
var startY = 70;
var zigzagSpacing = 20;

context.lineWidth = 3;
context.strokeStyle = "#FFFF";
context.beginPath();
context.moveTo(startX, startY);

// draw ten lines
for (var n = 0; n < 10; n++) {
var x = startY + ((n + 1) * zigzagSpacing);
var y;

if (n % 2 == 0) { // if n is even...
y = startY + 120;
}
else { // if n is odd...
y = startY;
}
context.lineTo(x, y);
}

context.stroke();
};


text:
"""
The Celery app for multiprocess, distributed evolution
"""

##########################################################################
## Imports
##########################################################################

from __future__ import absolute_import
from celery import Celery

##########################################################################
## Imports
##########################################################################

app = Celery('evolve', include=['evolve.tasks'])
app.config_from_object('evolve.celeryconfig')

if __name__ == '__main__':
    app.start()


text:
import tkinter as tk
import PyGraph

""" Demo app using PyGraph.

The real meat of the program is in the PyGraph Module """

# init a tkinter window
root = tk.Tk()

# frame to hold a simple text display of data
block_frame = tk.Frame(root, bg='orange')

# pack frame how ever you like
block_frame.pack(side="left", fill=tk.BOTH, expand=True)

# PyBlock object to display text data, common uses to show current values
box = PyGraph.PyBlock(block_frame,55,bg='#202020',fg='white',font_size=30,padx=5,pady=5)

# frame to hold line graph
line_frame = tk.Frame(root)

# pack how ever you want
line_frame.pack(side='left')

# init a PyLine object giving the frame to place it in and width, height params
graph = PyGraph.PyLine(line_frame,600,500)

# some x,y values in a 2D list for the line graph
data = [ [50,100], [100, 130], [150, 300], [200, 90], [300, 400]]

# Pyline method that will either set the data for a line graph or return the
# current data.
graph.graph_data(data)

# tkinter loop to keep the window open
root.mainloop()


text:
Concurrent-Pandas
=================

Concurrent Pandas
-------------

**Concurrent Pandas** is a Python Library that allows you to use Pandas and / or Quandl to concurrently download bulk data using threads or processes. What does concurrency do for you? Download your data simultaneously instead of one key at a time, Concurrent Pandas automatically spawns an optimal number of processes or threads based on the number of processes available on your machine.

Note: Concurrent Pandas is not associated with Quandl or Python Pandas, it just allows you to access them faster.

---
####Features

- **Sequential Downloading of Keys**
- **Concurrent downloading of keys using thread or process pools**
- **All Concurrent Downloading will automatically pick an optimal number of threads or processes to use for your system**
- **Recursive data structure unpacking for key insertion**
  - Pass one or many:
    - Lists
    - Sets
    - Deques
    - Any other data structures that inherit from abstract base class *Container* provided it is not also inheriting from Python *basestring* and it allows for iteration.
- **Automatic re-attempts if the download fails or times out**
  - Retries increase the time to try again with each successive failure
- **Variety of data sources supported**
  - Quandl
  - Federal Reserve Economic Data
  - Google Finance
  - Yahoo Finance
  - More coming soon!
- **Data is returned in a hashmap for fast lookups** ( *O(1) average case* )
  - Hash Map Keys are the strings entered for lookup, buckets contain your Panda data frame

---
####Easy to use
```
# Define your keys
yahoo_keys = ["aapl", "xom", "msft", "goog", "brk-b", "TSLA", "IRBT"]
# Instantiate Concurrent Pandas
fast_panda = concurrentpandas.ConcurrentPandas()
# Set your data source
fast_panda.set_source_yahoo_finance()
# Insert your keys
fast_panda.insert_keys(yahoo_keys)
# Choose either asynchronous threads, processes, or a single sequential download
fast_panda.consume_keys_asynchronous_threads()
# The Concurrent Pandas object contains a dict of your results now
mymap = fast_panda.return_map()
# Easily pull the data out of the map for your research
print(mymap["aapl"].head)
```

---
#####Installation Instructions

Note : only tested on Linux

To install execute:

```
pip install ConcurrentPandas
```

---
#####Updates

New in 0.1.2
Ability to interact with stock options

Now requires BeautifulSoup4, and Pandas 0.16 or newer.

---
#####Misc

Tested on Python 2.7.6 and Python 3.4.0

To see what else I'm building or follow / contact me check out my [github][1], [twitter][3], and my [personal site][2].

[1]: https://github.com/briwilcox
[2]: http://brianmwilcox.com/
[3]: https://twitter.com/brian_m_wilcox


text:
package org.eclipse.jdt.internal.ui.actions;

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

import org.eclipse.jface.viewers.CheckboxTreeViewer;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.Viewer;

import org.eclipse.jdt.core.dom.IVariableBinding;

public class GenerateConstructorUsingFieldsContentProvider implements ITreeContentProvider {

	private static final Object[] EMPTY= new Object[0];

	private List<IVariableBinding> fFields;
	private List<IVariableBinding> fSelected;

	public GenerateConstructorUsingFieldsContentProvider(List<IVariableBinding> fields, List<IVariableBinding> selected) {
		fFields= fields;
		fSelected= selected;
	}

	public boolean canMoveDown(List<?> selectedElements) {
		int nSelected= selectedElements.size();
		for (int index= fFields.size() - 1; index >= 0 && nSelected > 0; index--) {
			if (!selectedElements.contains(fFields.get(index))) {
				return true;
			}
			nSelected--;
		}
		return false;
	}

	public boolean canMoveUp(List<?> selected) {
		int nSelected= selected.size();
		for (int index= 0; index < fFields.size() && nSelected > 0; index++) {
			if (!selected.contains(fFields.get(index))) {
				return true;
			}
			nSelected--;
		}
		return false;
	}

	/*
	 * @see IContentProvider#dispose()
	 */
	public void dispose() {
	}

	public void down(List<?> checked, CheckboxTreeViewer tree) {
		if (checked.size() > 0) {
			setElements(reverse(moveUp(reverse(fFields), checked)), tree);
			tree.reveal(checked.get(checked.size() - 1));
		}
		tree.setSelection(new StructuredSelection(checked));
	}

	/*
	 * @see ITreeContentProvider#getChildren(Object)
	 */
	public Object[] getChildren(Object parentElement) {
		return EMPTY;
	}

	/*
	 * @see IStructuredContentProvider#getElements(Object)
	 */
	public Object[] getElements(Object inputElement) {
		return fFields.toArray();
	}

	public List<IVariableBinding> getFieldsList() {
		return fFields;
	}

	public Object[] getInitiallySelectedElements() {
		if (fSelected.isEmpty())
			return getElements(null);
		return fSelected.toArray();
	}

	/*
	 * @see ITreeContentProvider#getParent(Object)
	 */
	public Object getParent(Object element) {
		return null;
	}

	/*
	 * @see ITreeContentProvider#hasChildren(Object)
	 */
	public boolean hasChildren(Object element) {
		return getChildren(element).length > 0;
	}

	/*
	 * @see IContentProvider#inputChanged(Viewer, Object, Object)
	 */
	public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
	}

	private List<IVariableBinding> moveUp(List<IVariableBinding> elements, List<?> move) {
		List<IVariableBinding> result= new ArrayList<IVariableBinding>(elements.size());
		IVariableBinding floating= null;
		for (int index= 0; index < elements.size(); index++) {
			IVariableBinding current= elements.get(index);
			if (move.contains(current)) {
				result.add(current);
			} else {
				if (floating != null) {
					result.add(floating);
				}
				floating= current;
			}
		}
		if (floating != null) {
			result.add(floating);
		}
		return result;
	}

	private List<IVariableBinding> reverse(List<IVariableBinding> list) {
		List<IVariableBinding> reverse= new ArrayList<IVariableBinding>(list.size());
		for (int index= list.size() - 1; index >= 0; index--) {
			reverse.add(list.get(index));
		}
		return reverse;
	}

	public void setElements(List<IVariableBinding> elements, CheckboxTreeViewer tree) {
		fFields= new ArrayList<IVariableBinding>(elements);
		if (tree != null)
			tree.refresh();
	}

	public void up(List<?> checked, CheckboxTreeViewer tree) {
		if (checked.size() > 0) {
			setElements(moveUp(fFields, checked), tree);
			tree.reveal(checked.get(0));
		}
		tree.setSelection(new StructuredSelection(checked));
	}
}


text:
\begin{titlepage}
{\centering
\includegraphics[width=0.5\textwidth]{pics/tu-logo}\\
}
{\huge\centering
Wie findet man einen guten Parkplatz?\\
\noindent\large
Eine Untersuchung von verschiedenen Heuristiken in unterschiedlichen Situationen\\[1cm]
}
\begin{tabular}{ll}
Dozent&Dr. Martin Bracke\\
Veranstaltung&Moderne Mathematik: Mathematisches Modellieren\\
Semester& SS16\\
Angefertigt von&Steffen Holzer (379484) \& Ellen Wagner (387149)
\end{tabular}
\hrule
\tableofcontents
\pagestyle{empty}
\end{titlepage}


text:
use tokio_proto::pipeline::ClientService;
use tokio_core::net::TcpStream;

use super::proto::MessagingClientProto;

pub struct Client;

pub struct ClientHandle {
    inner: ClientService<TcpStream, MessagingClientProto>,
}


text:
package build

import "runtime"

// getToolDir returns the default value of ToolDir.
func getToolDir() string {
	return envOr("GCCGOTOOLDIR", runtime.GCCGOTOOLDIR)
}


text:
from keystone.manage2 import base
from keystone.manage2 import mixins

class Command(base.BaseBackendCommand, mixins.ListMixin,
        mixins.DateTimeMixin):
    """Lists all tokens in the system."""

    # pylint: disable=E1101
    def get_tokens(self):
        return self.token_manager.get_all()

    def run(self, args):
        """Process argparse args, and print results to stdout"""
        table = self.build_table(["ID", "User ID", "Tenant ID",
            "Expiration"])

        for obj in self.get_tokens():
            row = [obj.id, obj.user_id, obj.tenant_id,
                    self.datetime_to_str(obj.expires)]
            table.add_row(row)

        self.print_table(table)


text:
UploadEngine::Engine.routes.draw do
  resources :uploads
end


text:
/*	____________________________________________________________________________

	                 Scanner Component for the Macc n Cheese Compiler

	                                mscan.h

                              Version 2007 - 2016

	                           James L. Richards
	                     Last Update: August 28, 2007
	                      	   Nelson A Castillo
	                     Last Update: January 31, 2016

	The routines in this unit are based on those provided in the book
	"Crafting A Compiler" by Charles N. Fischer and Richard J. LeBlanc, Jr.,
	Benjamin Cummings Publishing Co. (1991).

	See Section 2.2, pp. 25-29.
	____________________________________________________________________________
*/

#ifndef SCANNER
#define SCANNER
#include <string>

const int ID_STRING_LEN = 1024;

enum Token { EOF_SYM, BOOL_SYM, BREAK_SYM, CASE_SYM, CHEESE_SYM, DECS_SYM,
    DO_SYM, ELSE_SYM, END_SYM, FALSE_SYM, FLOAT_SYM, FOR_SYM, HIPHIP_SYM,
    IF_SYM, INT_SYM, LISTEN_SYM, OTHERWISE_SYM, UNTIL_SYM, SELECT_SYM,
    SHOUT_SYM, THEN_SYM, TRUE_SYM, WHILE_SYM, LSTAPLE, RSTAPLE, LBANANA,
    RBANANA, LMUSTACHE, RMUSTACHE, COLON, SEMICOLON, COMMA, ASSIGN_OP, PLUS_OP,
    MINUS_OP, MULT_OP, DIV_OP, LT_OP, LE_OP, GT_OP, GE_OP, EQ_OP1, EQ_OP2,
    NE_OP, ID, BOOL_LIT, INT_LIT, FLOAT_LIT, CHEESE_LIT
};

class Scanner {
public:

	string tokenBuffer; // current token
	string lineBuffer; // current line
	int lineNumber; // line counter
	int cheese_size;

    /**
     * Initializes the scanner object.
     */
	Scanner();

    /**
     * Retrieves the next token available in the input stream.
     */
	Token GetNextToken();

private:

    /**
     * Appends character c to the end of the token buffer provided that the
     * buffer is not full.
     */
    void BufferChar(char c);

    /**
     * Checks the identifier in the token buffer to see if it is a reserved
     * word or a user-defined identifier and returns the appropriate token.
     */
    Token CheckReserved();

    /**
     * Erases the contents of the tokenBuffer.
     */
    void ClearBuffer();

    /**
     * Processes a lexical error at character c by ignoring that character and
     * getting the next character.
     */
    void LexicalError(char& c);
    void LexicalError(char& c, const string& errorExp);

    /**
     * Gets next available character from the source file.
     */
    char NextChar();

};
#endif


text:
var http = require("http"),
    url = require("url"),
    path = require("path"),
    fs = require("fs")
    port = process.argv[2] || 8001;
var sys = require('sys');
var Connect = require('connect');

var root = __dirname + '';

http.createServer(function(request, response) {

  var uri = url.parse(request.url).pathname
    , filename = path.join(process.cwd(), uri);

  var contentTypesByExtension = {
    '.html': "text/html",
    '.css':  "text/css",
    '.js':   "text/javascript"
  };

  var Server = module.exports = Connect.createServer();
  Server.use('/',
      Connect.responseTime()
      , Connect.logger()
  );

  path.exists(filename, function(exists) {
    if(!exists) {
      response.writeHead(404, {"Content-Type": "text/plain"});
      response.write("404 Not Found\n");
      response.end();
      return;
    }

    if (fs.statSync(filename).isDirectory()) filename += '/index.html';

    fs.readFile(filename, "binary", function(err, file) {
      if(err) {
        response.writeHead(500, {"Content-Type": "text/plain"});
        response.write(err + "\n");
        response.end();
        return;
      }

      var headers = {};
      var contentType = contentTypesByExtension[path.extname(filename)];
      if (contentType) headers["Content-Type"] = contentType;
      response.writeHead(200, headers);
      response.write(file, "binary");
      response.end();
    });
  });
}).listen(parseInt(port, 10));

console.log("Static file server running at\n  => http://localhost:" + port + "/\nCTRL + C to shutdown");


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

public class QuadTree<T> where T : IBoundable
{
    public const int DefaultMaxDepth = 3;

    public readonly int MaxDepth;

    private Node<T> root;

    public QuadTree(int width, int height, int maxDepth = DefaultMaxDepth)
    {
        this.root = new Node<T>(0, 0, width, height);
        this.Bounds = this.root.Bounds;
        this.MaxDepth = maxDepth;
    }

    public int Count { get; private set; }

    public Rectangle Bounds { get; private set; }

    public void ForEachDfs(Action<List<T>, int, int> action)
    {
        this.ForEachDfs(this.root, action);
    }

    public bool Insert(T item)
    {
        Rectangle itemBound = item.Bounds;
        Node<T> current = this.root;
        if (!itemBound.IsInside(current.Bounds))
        {
            return false;
        }
        int depth = 1;
        while (true)
        {
            int quadrant = this.GetQuadrant(current, itemBound);
            if (quadrant == -1)
            {
                break;
            }
            current = current.Children[quadrant];
            depth++;
        }

        current.Items.Add(item);

        TrySplitNode(current, depth);
        this.Count++;
        return true;
    }

    private void TrySplitNode(Node<T> node, int depth)
    {
        if (!node.ShouldSplit || depth >= MaxDepth)
        {
            return;
        }
        int x1 = node.Bounds.X1;
        int y1 = node.Bounds.Y1;
        int leftWidth = node.Bounds.MidX - x1;
        int rightWidth = node.Bounds.Width - leftWidth;
        int upperHight = node.Bounds.MidY - y1;
        int lowerHight = node.Bounds.Height - upperHight;

        if(node.Children == null)
        {
            node.Children = new Node<T>[4];
            Node<T> upperLeft = new Node<T>(x1, y1, leftWidth, upperHight);
            Node<T> upperRight = new Node<T>(node.Bounds.MidX, y1, rightWidth, upperHight);
            Node<T> lowerLeft = new Node<T>(x1, node.Bounds.MidY, leftWidth, lowerHight);
            Node<T> lowerRight = new Node<T>(node.Bounds.MidX, node.Bounds.MidY, rightWidth, lowerHight);

            node.Children[0] = upperRight;
            node.Children[1] = upperLeft;
            node.Children[2] = lowerLeft;
            node.Children[3] = lowerRight;
        }

        List<T> itemsToRemove = new List<T>();

        for(int i = node.Items.Count - 1; i >= 0; i--)
        {
            T item = node.Items[i];
            int quadrant = this.GetQuadrant(node, item.Bounds);
            if(quadrant != -1)
            {
                node.Children[quadrant].Items.Add(item);
                if(node.Items[i].Bounds.Y1 == new TestBox(0,0).Bounds.Y1)
                {

                }
                node.Items.RemoveAt(i);
            }
        }

        foreach(var sector in node.Children)
        {
            TrySplitNode(sector, depth + 1);
        }
    }

    private int GetQuadrant(Node<T> node, Rectangle itemBounds)
    {
        if(node.Children == null)
        {
            return -1;
        }

        for(int i = 0; i < 4; i++)
        {
            Rectangle nodeBounds = node.Children[i].Bounds;
            if (itemBounds.IsInside(nodeBounds))
            {
                return i;
            }
        }

        return -1;
    }

    public List<T> Report(Rectangle bounds)
    {
        List<T> result = new List<T>();
        this.ReportCollisions(this.root, result, bounds);
        return result;
    }

    private void ReportCollisions(Node<T> node, List<T> result, Rectangle bounds)
    {

        int quadrant = this.GetQuadrant(node, bounds);

        if(quadrant == -1)
        {
            this.ForEachDfs(node, (items, depth, q) =>
            {
                foreach(var item in items)
                {
                    if (item.Bounds.Intersects(bounds))
                    {
                        result.Add(item);
                    }
                }
            });
        }
        else
        {
            this.ReportCollisions(node.Children[quadrant], result, bounds);
            result.AddRange(node.Items);
        }
    }

    private void ForEachDfs(Node<T> node, Action<List<T>, int, int> action, int depth = 1, int quadrant = 0)
    {
        if (node == null)
        {
            return;
        }

        if (node.Items.Any())
        {
            action(node.Items, depth, quadrant);
        }

        if (node.Children != null)
        {
            for (int i = 0; i < node.Children.Length; i++)
            {
                ForEachDfs(node.Children[i], action, depth + 1, i);
            }
        }
    }
}


text:
package com.glaf.core.web.servlet;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.zip.GZIPOutputStream;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.glaf.core.config.BaseConfiguration;
import com.glaf.core.config.Configuration;
import com.glaf.core.config.SystemProperties;
import com.glaf.core.util.FileUtils;
import com.glaf.core.util.IOUtils;
import com.glaf.core.web.resource.WebResource;
import com.glaf.core.xml.MimeMappingReader;

public class WebResourceServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected static final Log logger = LogFactory
			.getLog(WebResourceServlet.class);

	protected static Configuration conf = BaseConfiguration.create();

	protected static ConcurrentMap<String, String> mimeMapping = new ConcurrentHashMap<String, String>();

	protected static boolean debugMode = false;

	protected boolean isGZIPSupported(HttpServletRequest req) {
		String browserEncodings = req.getHeader("accept-encoding");
		boolean supported = ((browserEncodings != null) && (browserEncodings
				.indexOf("gzip") != -1));
		String userAgent = req.getHeader("user-agent");
		if ((userAgent != null) && userAgent.startsWith("httpunit")) {
			logger.debug("httpunit detected, disabling filter...");
			return false;
		} else {
			return supported;
		}
	}

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String contextPath = request.getContextPath();
		String requestURI = request.getRequestURI();
		String resPath = requestURI.substring(contextPath.length(),
				requestURI.length());

		// logger.debug("contextPath:" + contextPath);
		// logger.debug("requestURI:" + requestURI);
		// logger.debug("resPath:" + resPath);

		int slash = request.getRequestURI().lastIndexOf("/");
		String file = request.getRequestURI().substring(slash + 1);
		if (StringUtils.endsWithIgnoreCase(file, ".class")) {
			return;
		}
		if (StringUtils.endsWithIgnoreCase(file, ".jsp")) {
			return;
		}
		if (StringUtils.endsWithIgnoreCase(file, ".conf")) {
			return;
		}
		if (StringUtils.endsWithIgnoreCase(file, "-config.properties")) {
			return;
		}
		if (StringUtils.endsWithIgnoreCase(file, "-spring-context.xml")) {
			return;
		}
		if (StringUtils.endsWithIgnoreCase(file, "Mapper.xml")) {
			return;
		}

		int dot = file.lastIndexOf(".");
		String ext = file.substring(dot + 1);
		String contentType = "";
		boolean requiredZip = false;
		if (StringUtils.equalsIgnoreCase(ext, "jpg")
				|| StringUtils.equalsIgnoreCase(ext, "jpeg")
				|| StringUtils.equalsIgnoreCase(ext, "gif")
				|| StringUtils.equalsIgnoreCase(ext, "png")) {
			contentType = "image/" + ext;
			requiredZip = false;
		} else if (StringUtils.equalsIgnoreCase(ext, "bmp")) {
			contentType = "image/bmp";
			requiredZip = true;
		} else if (StringUtils.equalsIgnoreCase(ext, "svg")) {
			contentType = "image/svg+xml";
			requiredZip = true;
		} else if (StringUtils.equalsIgnoreCase(ext, "css")) {
			contentType = "text/css";
			requiredZip = true;
		} else if (StringUtils.equalsIgnoreCase(ext, "txt")) {
			contentType = "text/plain";
			requiredZip = true;
		} else if (StringUtils.equalsIgnoreCase(ext, "htm")
				|| StringUtils.equalsIgnoreCase(ext, "html")) {
			contentType = "text/html";
			requiredZip = true;
		} else if (StringUtils.equalsIgnoreCase(ext, "js")) {
			contentType = "application/javascript";
			requiredZip = true;
		} else if (StringUtils.equalsIgnoreCase(ext, "ttf")) {
			contentType = "application/x-font-ttf";
			requiredZip = true;
		} else if (StringUtils.equalsIgnoreCase(ext, "eot")) {
			contentType = "application/vnd.ms-fontobject";
		} else if (StringUtils.equalsIgnoreCase(ext, "woff")) {
			contentType = "application/x-font-woff";
		} else if (StringUtils.equalsIgnoreCase(ext, "swf")) {
			contentType = "application/x-shockwave-flash";
		} else {
			contentType = mimeMapping.get(ext.trim().toLowerCase());
		}

		if (requiredZip && isGZIPSupported(request)
				&& conf.getBoolean("gzipEnabled", true)) {
			requiredZip = true;
		} else {
			requiredZip = false;
		}

		InputStream inputStream = null;
		ServletOutputStream output = null;
		boolean zipFlag = false;
		byte[] raw = null;
		try {
			output = response.getOutputStream();
			if (!debugMode) {
				raw = WebResource.getData(resPath);
				if (requiredZip) {
					raw = WebResource.getData(resPath + ".gz");
					if (raw != null) {
						zipFlag = true;
					}
				}
			}
			if (raw == null) {
				zipFlag = false;
				String filename = SystemProperties.getAppPath() + resPath;
				File filex = new File(filename);
				if (filex.exists() && filex.isFile()) {
					inputStream = FileUtils.getInputStream(filename);
				}
				if (inputStream == null) {
					inputStream = WebResourceServlet.class
							.getResourceAsStream(resPath);
				}

				logger.debug("load resource:" + resPath);
				raw = FileUtils.getBytes(inputStream);
				if (!debugMode) {
					WebResource.setBytes(resPath, raw);
				}

				GZIPOutputStream gzipStream = null;
				ByteArrayOutputStream compressedContent = null;
				try {
					// prepare a gzip stream
					compressedContent = new ByteArrayOutputStream();
					gzipStream = new GZIPOutputStream(compressedContent);
					gzipStream.write(raw);
					gzipStream.finish();
					// get the compressed content
					byte[] compressedBytes = compressedContent.toByteArray();
					WebResource.setBytes(resPath + ".gz", compressedBytes);
					logger.debug(resPath + " raw size:[" + raw.length
							+ "] gzip compressed size:["
							+ compressedBytes.length + "]");
					if (requiredZip) {
						raw = compressedBytes;
						zipFlag = true;
					}
				} catch (Exception ex) {
					zipFlag = false;
				} finally {
					IOUtils.closeStream(compressedContent);
					IOUtils.closeStream(gzipStream);
				}
			}

			if (zipFlag) {
				response.addHeader("Content-Encoding", "gzip");
			}

			if (raw != null) {
				response.setStatus(HttpServletResponse.SC_OK);
				response.setContentType(contentType);
				response.setContentLength(raw.length);
				output.write(raw);
				output.flush();
				IOUtils.closeStream(output);
			}
		} catch (IOException ex) {
			// ex.printStackTrace();
		} finally {
			raw = null;
			IOUtils.closeStream(inputStream);
			IOUtils.closeStream(output);
		}

		response.flushBuffer();
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	@Override
	public void init(ServletConfig config) {
		logger.info("--------------WebResourceServlet init----------------");
		try {
			if (System.getProperty("debugMode") != null) {
				debugMode = true;
				logger.info("---------------WebResource开启调试模式---------------");
			}
			MimeMappingReader reader = new MimeMappingReader();
			Map<String, String> mapping = reader.read();
			Set<Entry<String, String>> entrySet = mapping.entrySet();
			for (Entry<String, String> entry : entrySet) {
				String key = entry.getKey();
				String value = entry.getValue();
				mimeMapping.put(key, value);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}


text:
using namespace net::test_spdy3;

namespace net {

class SpdyHttpStreamSpdy3Test : public testing::Test {
 public:
  OrderedSocketData* data() { return data_.get(); }
 protected:
  SpdyHttpStreamSpdy3Test() {}

  virtual void SetUp() {
    SpdySession::set_default_protocol(SSLClientSocket::kProtoSPDY3);
  }

  virtual void TearDown() {
    crypto::ECSignatureCreator::SetFactoryForTesting(NULL);
    MessageLoop::current()->RunAllPending();
  }

  int InitSession(MockRead* reads, size_t reads_count,
                  MockWrite* writes, size_t writes_count,
                  HostPortPair& host_port_pair) {
    HostPortProxyPair pair(host_port_pair, ProxyServer::Direct());
    data_.reset(new OrderedSocketData(reads, reads_count,
                                      writes, writes_count));
    session_deps_.socket_factory->AddSocketDataProvider(data_.get());
    http_session_ = SpdySessionDependencies::SpdyCreateSession(&session_deps_);
    session_ = http_session_->spdy_session_pool()->Get(pair, BoundNetLog());
    transport_params_ = new TransportSocketParams(host_port_pair,
                                      MEDIUM, false, false);
    TestCompletionCallback callback;
    scoped_ptr<ClientSocketHandle> connection(new ClientSocketHandle);
    EXPECT_EQ(ERR_IO_PENDING,
              connection->Init(host_port_pair.ToString(),
                               transport_params_,
                               MEDIUM,
                               callback.callback(),
                               http_session_->GetTransportSocketPool(
                                   HttpNetworkSession::NORMAL_SOCKET_POOL),
                               BoundNetLog()));
    EXPECT_EQ(OK, callback.WaitForResult());
    return session_->InitializeWithSocket(connection.release(), false, OK);
  }

  void TestSendCredentials(
    ServerBoundCertService* server_bound_cert_service,
    const std::string& cert,
    const std::string& proof,
    SSLClientCertType type);

  SpdySessionDependencies session_deps_;
  scoped_ptr<OrderedSocketData> data_;
  scoped_refptr<HttpNetworkSession> http_session_;
  scoped_refptr<SpdySession> session_;
  scoped_refptr<TransportSocketParams> transport_params_;

 private:
  SpdyTestStateHelper spdy_state_;
};

TEST_F(SpdyHttpStreamSpdy3Test, SendRequest) {
  scoped_ptr<SpdyFrame> req(ConstructSpdyGet(NULL, 0, false, 1, LOWEST));
  MockWrite writes[] = {
    CreateMockWrite(*req.get(), 1),
  };
  scoped_ptr<SpdyFrame> resp(ConstructSpdyGetSynReply(NULL, 0, 1));
  MockRead reads[] = {
    CreateMockRead(*resp, 2),
    MockRead(SYNCHRONOUS, 0, 3)  // EOF
  };

  HostPortPair host_port_pair("www.google.com", 80);
  HostPortProxyPair pair(host_port_pair, ProxyServer::Direct());
  EXPECT_EQ(OK, InitSession(reads, arraysize(reads), writes, arraysize(writes),
      host_port_pair));

  HttpRequestInfo request;
  request.method = "GET";
  request.url = GURL("http://www.google.com/");
  TestCompletionCallback callback;
  HttpResponseInfo response;
  HttpRequestHeaders headers;
  BoundNetLog net_log;
  scoped_ptr<SpdyHttpStream> http_stream(
      new SpdyHttpStream(session_.get(), true));
  ASSERT_EQ(
      OK,
      http_stream->InitializeStream(&request, net_log, CompletionCallback()));

  EXPECT_EQ(ERR_IO_PENDING, http_stream->SendRequest(headers, NULL, &response,
                                                     callback.callback()));
  EXPECT_TRUE(http_session_->spdy_session_pool()->HasSession(pair));

  // This triggers the MockWrite and read 2
  callback.WaitForResult();

  // This triggers read 3. The empty read causes the session to shut down.
  data()->CompleteRead();

  // Because we abandoned the stream, we don't expect to find a session in the
  // pool anymore.
  EXPECT_FALSE(http_session_->spdy_session_pool()->HasSession(pair));
  EXPECT_TRUE(data()->at_read_eof());
  EXPECT_TRUE(data()->at_write_eof());
}

TEST_F(SpdyHttpStreamSpdy3Test, SendChunkedPost) {
  UploadDataStream::set_merge_chunks(false);

  scoped_ptr<SpdyFrame> req(ConstructChunkedSpdyPost(NULL, 0));
  scoped_ptr<SpdyFrame> chunk1(ConstructSpdyBodyFrame(1, false));
  scoped_ptr<SpdyFrame> chunk2(ConstructSpdyBodyFrame(1, true));
  MockWrite writes[] = {
    CreateMockWrite(*req.get(), 1),
    CreateMockWrite(*chunk1, 2),  // POST upload frames
    CreateMockWrite(*chunk2, 3),
  };
  scoped_ptr<SpdyFrame> resp(ConstructSpdyPostSynReply(NULL, 0));
  MockRead reads[] = {
    CreateMockRead(*resp, 4),
    CreateMockRead(*chunk1, 5),
    CreateMockRead(*chunk2, 5),
    MockRead(SYNCHRONOUS, 0, 6)  // EOF
  };

  HostPortPair host_port_pair("www.google.com", 80);
  HostPortProxyPair pair(host_port_pair, ProxyServer::Direct());
  EXPECT_EQ(OK, InitSession(reads, arraysize(reads), writes, arraysize(writes),
                            host_port_pair));

  HttpRequestInfo request;
  request.method = "POST";
  request.url = GURL("http://www.google.com/");
  request.upload_data = new UploadData();
  request.upload_data->set_is_chunked(true);
  request.upload_data->AppendChunk(kUploadData, kUploadDataSize, false);
  request.upload_data->AppendChunk(kUploadData, kUploadDataSize, true);
  TestCompletionCallback callback;
  HttpResponseInfo response;
  HttpRequestHeaders headers;
  BoundNetLog net_log;
  SpdyHttpStream http_stream(session_.get(), true);
  ASSERT_EQ(
      OK,
      http_stream.InitializeStream(&request, net_log, CompletionCallback()));

  // http_stream.SendRequest() will take ownership of upload_stream.
  UploadDataStream* upload_stream = new UploadDataStream(request.upload_data);
  ASSERT_EQ(OK, upload_stream->Init());
  EXPECT_EQ(ERR_IO_PENDING, http_stream.SendRequest(
      headers, upload_stream, &response, callback.callback()));
  EXPECT_TRUE(http_session_->spdy_session_pool()->HasSession(pair));

  // This triggers the MockWrite and read 2
  callback.WaitForResult();

  // This triggers read 3. The empty read causes the session to shut down.
  data()->CompleteRead();
  MessageLoop::current()->RunAllPending();

  // Because we abandoned the stream, we don't expect to find a session in the
  // pool anymore.
  EXPECT_FALSE(http_session_->spdy_session_pool()->HasSession(pair));
  EXPECT_TRUE(data()->at_read_eof());
  EXPECT_TRUE(data()->at_write_eof());
}

// Test case for bug: http://code.google.com/p/chromium/issues/detail?id=50058
TEST_F(SpdyHttpStreamSpdy3Test, SpdyURLTest) {
  const char * const full_url = "http://www.google.com/foo?query=what#anchor";
  const char * const base_url = "http://www.google.com/foo?query=what";
  scoped_ptr<SpdyFrame> req(ConstructSpdyGet(base_url, false, 1, LOWEST));
  MockWrite writes[] = {
    CreateMockWrite(*req.get(), 1),
  };
  scoped_ptr<SpdyFrame> resp(ConstructSpdyGetSynReply(NULL, 0, 1));
  MockRead reads[] = {
    CreateMockRead(*resp, 2),
    MockRead(SYNCHRONOUS, 0, 3)  // EOF
  };

  HostPortPair host_port_pair("www.google.com", 80);
  HostPortProxyPair pair(host_port_pair, ProxyServer::Direct());
  EXPECT_EQ(OK, InitSession(reads, arraysize(reads), writes, arraysize(writes),
      host_port_pair));

  HttpRequestInfo request;
  request.method = "GET";
  request.url = GURL(full_url);
  TestCompletionCallback callback;
  HttpResponseInfo response;
  HttpRequestHeaders headers;
  BoundNetLog net_log;
  scoped_ptr<SpdyHttpStream> http_stream(new SpdyHttpStream(session_, true));
  ASSERT_EQ(
      OK,
      http_stream->InitializeStream(&request, net_log, CompletionCallback()));

  EXPECT_EQ(ERR_IO_PENDING, http_stream->SendRequest(headers, NULL, &response,
                                                     callback.callback()));

  SpdyHeaderBlock* spdy_header =
    http_stream->stream()->spdy_headers().get();
  EXPECT_TRUE(spdy_header != NULL);
  if (spdy_header->find(":path") != spdy_header->end())
    EXPECT_EQ("/foo?query=what", spdy_header->find(":path")->second);
  else
    FAIL() << "No url is set in spdy_header!";

  // This triggers the MockWrite and read 2
  callback.WaitForResult();

  // This triggers read 3. The empty read causes the session to shut down.
  data()->CompleteRead();

  // Because we abandoned the stream, we don't expect to find a session in the
  // pool anymore.
  EXPECT_FALSE(http_session_->spdy_session_pool()->HasSession(pair));
  EXPECT_TRUE(data()->at_read_eof());
  EXPECT_TRUE(data()->at_write_eof());
}

namespace {

void GetECServerBoundCertAndProof(
    const std::string& origin,
    ServerBoundCertService* server_bound_cert_service,
    std::string* cert,
    std::string* proof) {
  TestCompletionCallback callback;
  std::vector<uint8> requested_cert_types;
  requested_cert_types.push_back(CLIENT_CERT_ECDSA_SIGN);
  SSLClientCertType cert_type;
  std::string key;
  ServerBoundCertService::RequestHandle request_handle;
  int rv = server_bound_cert_service->GetDomainBoundCert(
      origin, requested_cert_types, &cert_type, &key, cert, callback.callback(),
      &request_handle);
  EXPECT_EQ(ERR_IO_PENDING, rv);
  EXPECT_EQ(OK, callback.WaitForResult());
  EXPECT_EQ(CLIENT_CERT_ECDSA_SIGN, cert_type);

  unsigned char secret[32];
  memset(secret, 'A', arraysize(secret));

  // Convert the key string into a vector<unit8>
  std::vector<uint8> key_data(key.begin(), key.end());

  base::StringPiece spki_piece;
  ASSERT_TRUE(asn1::ExtractSPKIFromDERCert(*cert, &spki_piece));
  std::vector<uint8> spki(spki_piece.data(),
                          spki_piece.data() + spki_piece.size());

  std::vector<uint8> proof_data;
  scoped_ptr<crypto::ECPrivateKey> private_key(
      crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
          ServerBoundCertService::kEPKIPassword, key_data, spki));
  scoped_ptr<crypto::ECSignatureCreator> creator(
      crypto::ECSignatureCreator::Create(private_key.get()));
  creator->Sign(secret, arraysize(secret), &proof_data);
  proof->assign(proof_data.begin(), proof_data.end());
}

}  // namespace

// Constructs a standard SPDY SYN_STREAM frame for a GET request with
// a credential set.
SpdyFrame* ConstructCredentialRequestFrame(int slot, const GURL& url,
                                                 int stream_id) {
  const SpdyHeaderInfo syn_headers = {
    SYN_STREAM,
    stream_id,
    0,
    ConvertRequestPriorityToSpdyPriority(LOWEST),
    slot,
    CONTROL_FLAG_FIN,
    false,
    INVALID,
    NULL,
    0,
    DATA_FLAG_NONE
  };

  // TODO(rch): this is ugly.  Clean up.
  std::string str_path = url.PathForRequest();
  std::string str_scheme = url.scheme();
  std::string str_host = url.host();
  if (url.has_port()) {
    str_host += ":";
    str_host += url.port();
  }
  scoped_array<char> req(new char[str_path.size() + 1]);
  scoped_array<char> scheme(new char[str_scheme.size() + 1]);
  scoped_array<char> host(new char[str_host.size() + 1]);
  memcpy(req.get(), str_path.c_str(), str_path.size());
  memcpy(scheme.get(), str_scheme.c_str(), str_scheme.size());
  memcpy(host.get(), str_host.c_str(), str_host.size());
  req.get()[str_path.size()] = '\0';
  scheme.get()[str_scheme.size()] = '\0';
  host.get()[str_host.size()] = '\0';

  const char* const headers[] = {
    ":method",
    "GET",
    ":path",
    req.get(),
    ":host",
    host.get(),
    ":scheme",
    scheme.get(),
    ":version",
    "HTTP/1.1"
  };
  return ConstructSpdyPacket(
      syn_headers, NULL, 0, headers, arraysize(headers)/2);
}

// TODO(rch): When openssl supports server bound certifictes, this
// guard can be removed
#if !defined(USE_OPENSSL)
// Test that if we request a resource for a new origin on a session that
// used domain bound certificates, that we send a CREDENTIAL frame for
// the new domain before we send the new request.
void SpdyHttpStreamSpdy3Test::TestSendCredentials(
    ServerBoundCertService* server_bound_cert_service,
    const std::string& cert,
    const std::string& proof,
    SSLClientCertType type) {
  const char* kUrl1 = "https://www.google.com/";
  const char* kUrl2 = "https://www.gmail.com/";

  SpdyCredential cred;
  cred.slot = 2;
  cred.proof = proof;
  cred.certs.push_back(cert);

  scoped_ptr<SpdyFrame> req(ConstructCredentialRequestFrame(
      1, GURL(kUrl1), 1));
  scoped_ptr<SpdyFrame> credential(ConstructSpdyCredential(cred));
  scoped_ptr<SpdyFrame> req2(ConstructCredentialRequestFrame(
      2, GURL(kUrl2), 3));
  MockWrite writes[] = {
    CreateMockWrite(*req.get(), 0),
    CreateMockWrite(*credential.get(), 2),
    CreateMockWrite(*req2.get(), 3),
  };

  scoped_ptr<SpdyFrame> resp(ConstructSpdyGetSynReply(NULL, 0, 1));
  scoped_ptr<SpdyFrame> resp2(ConstructSpdyGetSynReply(NULL, 0, 3));
  MockRead reads[] = {
    CreateMockRead(*resp, 1),
    CreateMockRead(*resp2, 4),
    MockRead(SYNCHRONOUS, 0, 5)  // EOF
  };

  HostPortPair host_port_pair(HostPortPair::FromURL(GURL(kUrl1)));
  HostPortProxyPair pair(host_port_pair, ProxyServer::Direct());

  DeterministicMockClientSocketFactory* socket_factory =
      session_deps_.deterministic_socket_factory.get();
  scoped_refptr<DeterministicSocketData> data(
      new DeterministicSocketData(reads, arraysize(reads),
                                  writes, arraysize(writes)));
  socket_factory->AddSocketDataProvider(data.get());
  SSLSocketDataProvider ssl(SYNCHRONOUS, OK);
  ssl.domain_bound_cert_type = type;
  ssl.server_bound_cert_service = server_bound_cert_service;
  ssl.protocol_negotiated = SSLClientSocket::kProtoSPDY3;
  socket_factory->AddSSLSocketDataProvider(&ssl);
  http_session_ = SpdySessionDependencies::SpdyCreateSessionDeterministic(
      &session_deps_);
  session_ = http_session_->spdy_session_pool()->Get(pair, BoundNetLog());
  transport_params_ = new TransportSocketParams(host_port_pair,
                                                MEDIUM, false, false);
  TestCompletionCallback callback;
  scoped_ptr<ClientSocketHandle> connection(new ClientSocketHandle);
  SSLConfig ssl_config;
  scoped_refptr<SOCKSSocketParams> socks_params;
  scoped_refptr<HttpProxySocketParams> http_proxy_params;
  scoped_refptr<SSLSocketParams> ssl_params(
      new SSLSocketParams(transport_params_,
                          socks_params,
                          http_proxy_params,
                          ProxyServer::SCHEME_DIRECT,
                          host_port_pair,
                          ssl_config,
                          0,
                          false,
                          false));
  EXPECT_EQ(ERR_IO_PENDING,
            connection->Init(host_port_pair.ToString(),
                             ssl_params,
                             MEDIUM,
                             callback.callback(),
                             http_session_->GetSSLSocketPool(
                                 HttpNetworkSession::NORMAL_SOCKET_POOL),
                             BoundNetLog()));
  callback.WaitForResult();
  EXPECT_EQ(OK,
            session_->InitializeWithSocket(connection.release(), true, OK));

  HttpRequestInfo request;
  request.method = "GET";
  request.url = GURL(kUrl1);
  HttpResponseInfo response;
  HttpRequestHeaders headers;
  BoundNetLog net_log;
  scoped_ptr<SpdyHttpStream> http_stream(
      new SpdyHttpStream(session_.get(), true));
  ASSERT_EQ(
      OK,
      http_stream->InitializeStream(&request, net_log, CompletionCallback()));

  //  EXPECT_FALSE(session_->NeedsCredentials(request.url));
  //  GURL new_origin(kUrl2);
  //  EXPECT_TRUE(session_->NeedsCredentials(new_origin));

  EXPECT_EQ(ERR_IO_PENDING, http_stream->SendRequest(headers, NULL, &response,
                                                     callback.callback()));
  EXPECT_TRUE(http_session_->spdy_session_pool()->HasSession(pair));

  data->RunFor(2);
  callback.WaitForResult();

  // Start up second request for resource on a new origin.
  scoped_ptr<SpdyHttpStream> http_stream2(
      new SpdyHttpStream(session_.get(), true));
  request.url = GURL(kUrl2);
  ASSERT_EQ(
      OK,
      http_stream2->InitializeStream(&request, net_log, CompletionCallback()));
  EXPECT_EQ(ERR_IO_PENDING, http_stream2->SendRequest(headers, NULL, &response,
                                                     callback.callback()));
  data->RunFor(2);
  callback.WaitForResult();

  EXPECT_EQ(ERR_IO_PENDING, http_stream2->ReadResponseHeaders(
      callback.callback()));
  data->RunFor(1);
  EXPECT_EQ(OK, callback.WaitForResult());
  ASSERT_TRUE(response.headers.get() != NULL);
  ASSERT_EQ(200, response.headers->response_code());
}

class MockECSignatureCreator : public crypto::ECSignatureCreator {
  public:
   explicit MockECSignatureCreator(crypto::ECPrivateKey* key) : key_(key) {}

   virtual bool Sign(const uint8* data,
                     int data_len,
                     std::vector<uint8>* signature) OVERRIDE {
     std::vector<uint8> private_key_value;
     key_->ExportValue(&private_key_value);
     std::string head = "fakesignature";
     std::string tail = "/fakesignature";

     signature->clear();
     signature->insert(signature->end(), head.begin(), head.end());
     signature->insert(signature->end(), private_key_value.begin(),
                       private_key_value.end());
     signature->insert(signature->end(), '-');
     signature->insert(signature->end(), data, data + data_len);
     signature->insert(signature->end(), tail.begin(), tail.end());
     return true;
   }

 private:
   crypto::ECPrivateKey* key_;
   DISALLOW_COPY_AND_ASSIGN(MockECSignatureCreator);
};

class MockECSignatureCreatorFactory : public crypto::ECSignatureCreatorFactory {
 public:
  MockECSignatureCreatorFactory() {}
  virtual ~MockECSignatureCreatorFactory() {}

  virtual crypto::ECSignatureCreator* Create(
      crypto::ECPrivateKey* key) OVERRIDE {
    return new MockECSignatureCreator(key);
  }
 private:
   DISALLOW_COPY_AND_ASSIGN(MockECSignatureCreatorFactory);
};

TEST_F(SpdyHttpStreamSpdy3Test, SendCredentialsEC) {
  scoped_ptr<crypto::ECSignatureCreatorFactory> ec_signature_creator_factory(
      new MockECSignatureCreatorFactory());
  crypto::ECSignatureCreator::SetFactoryForTesting(
      ec_signature_creator_factory.get());

  scoped_ptr<ServerBoundCertService> server_bound_cert_service(
      new ServerBoundCertService(new DefaultServerBoundCertStore(NULL)));
  std::string cert;
  std::string proof;
  GetECServerBoundCertAndProof("http://www.gmail.com/",
                               server_bound_cert_service.get(),
                               &cert, &proof);

  TestSendCredentials(server_bound_cert_service.get(), cert, proof,
                      CLIENT_CERT_ECDSA_SIGN);
}

#endif  // !defined(USE_OPENSSL)

// TODO(willchan): Write a longer test for SpdyStream that exercises all
// methods.

}  // namespace net


text:
module HAProxy
  # Responsible for reading an HAProxy config file and building an HAProxy::Config instance.
  class Parser
    # Raised when an error occurs during parsing.
    Error = Class.new(StandardError)

    # haproxy 1.3
    SERVER_ATTRIBUTE_NAMES_1_3 = %w[
      addr backup check cookie disabled fall id inter fastinter downinter
      maxconn maxqueue minconn port redir rise slowstart source track weight
    ]
    # Added in haproxy 1.4
    SERVER_ATTRIBUTE_NAMES_1_4 = %w[error-limit observe on-error]
    # Added in haproxy 1.5
    SERVER_ATTRIBUTE_NAMES_1_5 = %w[
      agent-check agent-inter agent-port ca-file check-send-proxy check-ssl
      ciphers crl-file crt error-limit force-sslv3 force-tlsv10 force-tlsv11
      force-tlsv12 no-sslv3 no-tls-tickets no-tlsv10 no-tlsv11 no-tlsv12 non-stick observe
      on-error on-marked-down on-marked-up send-proxy send-proxy-v2 send-proxy-v2-ssl
      send-proxy-v2-ssl-cn ssl verify verifyhost
    ]
    # Added in haproxy 1.6
    SERVER_ATTRIBUTE_NAMES_1_6 = %w[
      namespace no-ssl-reuse resolve-prefer resolvers sni tcp-ut
    ]
    # Added in haproxy 1.7
    SERVER_ATTRIBUTE_NAMES_1_7 = %w[
      agent-send init-addr resolve-net
    ]
    SERVER_ATTRIBUTE_NAMES_1_8 = %w[
      agent-addr check-sni enabled force-tlsv13 no-agent-check no-backup no-check no-check-ssl
      no-send-proxy no-send-proxy-v2 no-send-proxy-v2-ssl no-send-proxy-v2-ssl-cn no-ssl no-tlsv13
      no-verifyhost ssl-max-ver ssl-min-ver ssl-reuse stick tls-tickets
    ]
    SERVER_ATTRIBUTE_NAMES_1_9 = %w[
      alpn check-alpn max-reuse npn pool-max-conn pool-purge-delay proto proxy-v2-options
    ].freeze
    SERVER_ATTRIBUTE_NAMES = [
      SERVER_ATTRIBUTE_NAMES_1_3,
      SERVER_ATTRIBUTE_NAMES_1_4,
      SERVER_ATTRIBUTE_NAMES_1_5,
      SERVER_ATTRIBUTE_NAMES_1_6,
      SERVER_ATTRIBUTE_NAMES_1_7,
      SERVER_ATTRIBUTE_NAMES_1_8,
      SERVER_ATTRIBUTE_NAMES_1_9,
    ].flatten.freeze

    attr_accessor :verbose, :options, :parse_result

    def initialize(options = nil)
      options ||= {}
      options = {verbose: false}.merge(options)

      self.options = options
      self.verbose = options[:verbose]
    end

    def parse_file(filename)
      config_text = File.read(filename)
      parse(config_text)
    end

    def parse(config_text)
      result = parse_config_text(config_text)
      self.parse_result = result
      build_config(result)
    end

    protected

    def parse_config_text(config_text)
      parser = HAProxy::Treetop::ConfigParser.new
      result = parser.parse(config_text)
      raise HAProxy::Parser::Error.new(parser.failure_reason) if result.nil?
      result
    end

    def build_config(result)
      HAProxy::Config.new(result).tap do |config|
        config.global = config_hash_from_config_section(result.global) if result.global
        config.frontends  += collect_frontends(result)
        config.backends   += collect_backends(result)
        config.listeners  += collect_listeners(result)
        config.defaults   += collect_defaults(result)
        config.userlists  += collect_userlists(result)
      end
    end

    def build_frontend(fs)
      Frontend.new.tap do |f|
        f.name        = try_send(fs.frontend_header, :proxy_name, :content)
        f.host        = try_send(fs.frontend_header, :service_address, :host, :content)
        f.port        = try_send(fs.frontend_header, :service_address, :port, :content)
        f.options     = options_hash_from_config_section(fs)
        f.config      = config_hash_from_config_section(fs)
      end
    end

    def build_backend(bs)
      Backend.new.tap do |b|
        b.name        = try_send(bs.backend_header, :proxy_name, :content)
        b.options     = options_hash_from_config_section(bs)
        b.config      = config_hash_from_config_section(bs)
        b.servers     = server_hash_from_config_section(bs)
      end
    end

    def build_listener(ls)
      Listener.new.tap do |l|
        l.name        = try_send(ls.listen_header, :proxy_name, :content)
        l.host        = try_send(ls.listen_header, :service_address, :host, :content)
        l.port        = try_send(ls.listen_header, :service_address, :port, :content)
        l.options     = options_hash_from_config_section(ls)
        l.config      = config_hash_from_config_section(ls)
        l.servers     = server_hash_from_config_section(ls)
      end
    end

    def build_userlist(section)
      Userlist.new.tap do |ul|
        ul.name   = try_send(section.userlist_header, :proxy_name, :content)
        ul.users  = users_from_userlist_section(section)
        ul.groups = groups_from_userlist_section(section)
      end
    end

    def users_from_userlist_section(section)
      section.users.map do |user_line|
        UserlistUser.new.tap do |u|
          u.name      = user_line.name.content
          u.password  = user_line.password
          u.groups    = user_line.group_names
        end
      end
    end

    def groups_from_userlist_section(section)
      section.groups.map do |group_line|
        UserlistGroup.new.tap do |g|
          g.name = group_line.name.content
          g.users = group_line.user_names
        end
      end
    end

    def build_default(ds)
      Default.new.tap do |d|
        d.name        = try_send(ds.defaults_header, :proxy_name, :content)
        d.options     = options_hash_from_config_section(ds)
        d.config      = config_hash_from_config_section(ds)
      end
    end

    def collect_frontends(result)
      result.frontends.map { |fs| build_frontend(fs) }
    end

    def collect_backends(result)
      result.backends.map { |bs| build_backend(bs) }
    end

    def collect_listeners(result)
      result.listeners.map { |ls| build_listener(ls) }
    end

    def collect_userlists(result)
      result.userlists.map { |ls| build_userlist(ls) }
    end

    def collect_defaults(result)
      result.defaults.map { |ds| build_default(ds) }
    end

    def try_send(node, *method_names)
      method_name = method_names.shift
      return unless node.respond_to?(method_name)

      next_node = node.send(method_name)
      method_names.empty? ? next_node : try_send(next_node, *method_names)
    end

    def server_hash_from_config_section(cs)
      cs.servers.each_with_object({}) do |s, ch|
        value = try_send(s, :value, :content)
        ch[s.name] = Server.new(s.name, s.host, s.port, parse_server_attributes(value))
      end
    end

    # Parses server attributes from the server value. I couldn't manage to get treetop to do
    # this.
    #
    # Types of server attributes to support:
    # ipv4, boolean, string, integer, time (us, ms, s, m, h, d), url, source attributes
    #
    # BUG: If an attribute value matches an attribute name, the parser will assume that a new
    # attribute value has started. I don't know how haproxy itself handles that situation.
    def parse_server_attributes(value)
      parts = value.to_s.split(/\s/)
      current_name = nil
      pairs = parts.each_with_object({}) { |part, attrs|
        if SERVER_ATTRIBUTE_NAMES.include?(part)
          current_name = part
          attrs[current_name] = []
        elsif current_name.nil?
          raise "Invalid server attribute: #{part}"
        else
          attrs[current_name] << part
        end
      }

      clean_parsed_server_attributes(pairs)
    end

    # Converts attributes with no values to true, and combines everything else into space-
    # separated strings.
    def clean_parsed_server_attributes(pairs)
      pairs.each do |k, v|
        pairs[k] = if v.empty?
          true
        else
          v.join(" ")
        end
      end
    end

    def options_hash_from_config_section(cs)
      cs.option_lines.each_with_object({}) do |l, ch|
        ch[l.keyword.content] = l.value ? l.value.content : nil
      end
    end

    def config_hash_from_config_section(cs)
      cs.config_lines.reject {|l| l.keyword.content == "option"}.each_with_object({}) do |l, ch|
        ch[l.keyword.content] = l.value ? l.value.content : nil
      end
    end
  end
end


text:
namespace llvm {

struct Session {
  orc::ExecutionSession ES;
  std::unique_ptr<jitlink::JITLinkMemoryManager> MemMgr;
  orc::ObjectLinkingLayer ObjLayer;
  std::vector<orc::JITDylib *> JDSearchOrder;
  Triple TT;

  Session(Triple TT);
  void dumpSessionInfo(raw_ostream &OS);
  void modifyPassConfig(const Triple &FTT,
                        jitlink::PassConfiguration &PassConfig);

  using MemoryRegionInfo = RuntimeDyldChecker::MemoryRegionInfo;

  struct FileInfo {
    StringMap<MemoryRegionInfo> SectionInfos;
    StringMap<MemoryRegionInfo> StubInfos;
    StringMap<MemoryRegionInfo> GOTEntryInfos;
  };

  using SymbolInfoMap = StringMap<MemoryRegionInfo>;
  using FileInfoMap = StringMap<FileInfo>;

  Expected<FileInfo &> findFileInfo(StringRef FileName);
  Expected<MemoryRegionInfo &> findSectionInfo(StringRef FileName,
                                               StringRef SectionName);
  Expected<MemoryRegionInfo &> findStubInfo(StringRef FileName,
                                            StringRef TargetName);
  Expected<MemoryRegionInfo &> findGOTEntryInfo(StringRef FileName,
                                                StringRef TargetName);

  bool isSymbolRegistered(StringRef Name);
  Expected<MemoryRegionInfo &> findSymbolInfo(StringRef SymbolName,
                                              Twine ErrorMsgStem);

  SymbolInfoMap SymbolInfos;
  FileInfoMap FileInfos;
  uint64_t SizeBeforePruning = 0;
  uint64_t SizeAfterFixups = 0;
};

Error registerMachOStubsAndGOT(Session &S, jitlink::LinkGraph &G);

} // end namespace llvm

#endif // LLVM_TOOLS_LLVM_JITLINK_LLVM_JITLINK_H


text:
import React, { Component, PropTypes } from 'react';
import Helmet from 'react-helmet';
import queryString from 'query-string';
import { size, extend, map, debounce, pick } from 'lodash';
import numeral from 'numeral';
import { connect } from 'react-redux';
import { search as youTubeSearch } from 'redux/modules/youtube';
import { asyncConnect } from 'redux-async-connect';
import { push as pushState } from 'react-router-redux';

import { VideoDetails } from 'components';

function isEqualQuery(query1, query2) {
  return query1.q === query2.q && query1.page === query2.page && query1.order === query2.order;
}

function isSearchLoaded(youtube, query) {
  return youtube && youtube.result && isEqualQuery(youtube.result, query);
}

@asyncConnect([{
  promise: ({store: {dispatch, getState}}) => {
    const youtube = getState().youtube;
    const query = getState().routing.locationBeforeTransitions.query;
    if (query.q && !isSearchLoaded(youtube, query)) {
      return dispatch(youTubeSearch(query));
    }
  }
}])
@connect(
    state => ({ youtube: state.youtube }),
    { pushState, youTubeSearch }
)
export default class Search extends Component {

  static propTypes = {
    location: PropTypes.object.isRequired,
    youTubeSearch: PropTypes.func.isRequired,
    youtube: PropTypes.object,
    pushState: PropTypes.func.isRequired
  }

  componentWillMount() {
    this.setState({
      query: pick(this.props.youtube.result, ['q', 'order', 'page', 'pageToken']),
      debounceYouTubeSearch: debounce(this.search.bind(this), 600)
    });
  }

  componentDidMount() {
    this._popState = function() {
      this.props.pushState(this.props.location.pathname + document.location.search);
      this.setState({ query: queryString.parse(document.location.search) });
    }.bind(this);
    window.addEventListener('popstate', this._popState);
  }

  componentWillUnmount() {
    window.removeEventListener('popstate', this._popState);
  }

  /* Search without reloading component */
  search() {
    if (!this.props.youtube.searching && !isSearchLoaded(this.props.youtube, this.state.query)) this.props.youTubeSearch(this.state.query);
    this.setState({ isTyping: false });
  }

  /* On form submit with Enter keypress */
  submit(e) {
    e.preventDefault();
    if (!this.props.youtube.searching && !isSearchLoaded(this.props.youtube, this.state.query)) {
      this.changeQueryString(this.state.query);
      this.search();
    }
  }

  /* replace querystring without calling a location change */
  changeQueryString(query) {
    let querystring = '';
    if (size(query)) querystring = '?' + queryString.stringify(query);

    // To have meaningful back and forward points.
    if (this.state.isTyping) {
      history.replaceState({}, '', this.props.location.pathname + querystring);
    } else {
      history.pushState({}, '', this.props.location.pathname + querystring);
    }
  }

  /**
  * When a user starts typing, lets show instant results.
  **/
  keywordChange(e) {
    const keyword = e.target.value;

    // Determine new querystring
    const query = extend({}, this.state.query, {q: keyword});
    if (!query.q) delete query.q;
    delete query.page;
    delete query.pageToken;

    // Replace querystring as we type
    this.changeQueryString(query);

    // Set local state and set up debouncer, but don't reload whole component.
    this.setState({ query: query, isTyping: true });
    this.state.debounceYouTubeSearch(query);
  }

  orderChange(e) {
    const order = e.target.value;

    // Determine new querystring
    const query = extend({}, this.state.query, {order: order});
    if (query.order === 'relevance') delete query.order;
    delete query.page;
    delete query.pageToken;

    this.setState({ query: query });
    this.props.pushState(this.props.location.pathname + '?' + queryString.stringify(query));
  }

  changePage(page, pageToken) {
    return function() {
      const query = extend({}, this.state.query, { page: page, pageToken: pageToken });
      this.setState({ query: query });
      this.props.pushState(this.props.location.pathname + '?' + queryString.stringify(query));
    }.bind(this);
  }

  render() {
    const styles = require('./Search.scss');
    const youtube = this.props.youtube;
    const numPages = youtube.result && youtube.result.pageInfo.totalResults / youtube.result.pageInfo.resultsPerPage;
    const page = (youtube.result && youtube.result.page ? Number(youtube.result.page) : 1);
    const nextButton = youtube && youtube.result && youtube.result.nextPageToken &&
<button className="btn btn-primary" onClick={this.changePage(page + 1, youtube.result.nextPageToken)} style={{ float: 'right' }}>Next Page </button>
;
    const prevButton = youtube && youtube.result && youtube.result.prevPageToken &&
<button className="btn btn-primary" onClick={this.changePage(page - 1, youtube.result.prevPageToken)} style={{ float: 'left' }}> Previous Page</button>
;

    let videoList = null;
    if (youtube.result && !!size(youtube.result.items)) {
      videoList = (

         { map(youtube.result.items, (item) => <VideoDetails video={item} stats={youtube.stats && youtube.stats[item.id.videoId]} videoid={item.id.videoId} key={item.id.videoId} />) }

       );
    }

    let resultsText =

;
    if (!youtube.searching && youtube.result && !!size(youtube.result.items)) {
      resultsText =
{numeral(youtube.result.pageInfo.totalResults).format('0,0')} videos found. Page {page} of {numeral(numPages).format('0,0')}.
;
    }

    let statusText = null;
    if (youtube.searching) {
      statusText =
 Searching...
;
    } else if (!youtube.searching && youtube.result && !size(youtube.result.items)) {
      statusText =
No Videos found
;
    } else if (!youtube.searching && !youtube.result) {
      statusText =
No videos to show yet...
;
    }

    return (

        <Helmet title="Search" />
          <form className="form-inline" onSubmit={this.submit.bind(this)}>

              <input
                type="search"
                name="search"
                autoSave="youtubeSearch"
                results="10"
                placeholder="Enter your search query..."
                className={[styles.searchBox, 'form-control'].join(' ')}
                onChange={this.keywordChange.bind(this)}
                value={this.state.query.q}
                autoFocus
                />

              <select className="form-control" value={this.state.query.order || 'relevance'} onChange={this.orderChange.bind(this)}>
                <option value="relevance">Sort by Relavance</option>
                <option value="date">Sort by Date</option>
                <option value="rating">Sort by Rating</option>
              </select>

          </form>
          { resultsText }

          { statusText }
          { nextButton }
          { prevButton }
          { videoList }
          { nextButton }
          { prevButton }

    );
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Verrucaria viridiatra Grognot

### Remarks
null


text:
package com.hazelcast.internal.config;

import com.hazelcast.config.CacheSimpleConfig;
import com.hazelcast.config.Config;
import com.hazelcast.config.EvictionConfig;
import com.hazelcast.config.InMemoryFormat;
import com.hazelcast.config.InvalidConfigurationException;
import com.hazelcast.config.MapConfig;
import com.hazelcast.config.MaxSizePolicy;
import com.hazelcast.config.NativeMemoryConfig;
import com.hazelcast.config.cp.CPSubsystemConfig;
import com.hazelcast.spi.impl.NodeEngine;
import com.hazelcast.spi.merge.SplitBrainMergePolicyProvider;
import com.hazelcast.spi.properties.HazelcastProperties;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.annotation.ParallelJVMTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.mockito.Mockito;

import static com.hazelcast.config.InMemoryFormat.BINARY;
import static com.hazelcast.config.InMemoryFormat.NATIVE;
import static com.hazelcast.config.InMemoryFormat.OBJECT;
import static com.hazelcast.internal.config.ConfigValidator.checkCPSubsystemConfig;
import static com.hazelcast.internal.config.ConfigValidator.checkCacheConfig;
import static com.hazelcast.internal.config.ConfigValidator.checkMapConfig;
import static com.hazelcast.internal.config.ConfigValidator.checkNearCacheNativeMemoryConfig;
import static org.mockito.Mockito.when;

@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelJVMTest.class})
public class ConfigValidatorTest extends HazelcastTestSupport {

    private HazelcastProperties properties;
    private NativeMemoryConfig nativeMemoryConfig;
    private SplitBrainMergePolicyProvider splitBrainMergePolicyProvider;

    @Before
    public void setUp() {
        Config config = new Config();
        nativeMemoryConfig = config.getNativeMemoryConfig();
        NodeEngine nodeEngine = Mockito.mock(NodeEngine.class);
        when(nodeEngine.getConfigClassLoader()).thenReturn(config.getClassLoader());

        splitBrainMergePolicyProvider = new SplitBrainMergePolicyProvider(nodeEngine);
        when(nodeEngine.getSplitBrainMergePolicyProvider()).thenReturn(splitBrainMergePolicyProvider);

        properties = nodeEngine.getProperties();
    }

    @Test
    public void testConstructor() {
        assertUtilityConstructor(ConfigValidator.class);
    }

    @Test
    public void checkMapConfig_BINARY() {
        checkMapConfig(getMapConfig(BINARY), nativeMemoryConfig, splitBrainMergePolicyProvider, properties);
    }

    @Test
    public void checkMapConfig_OBJECT() {
        checkMapConfig(getMapConfig(OBJECT), nativeMemoryConfig, splitBrainMergePolicyProvider, properties);
    }

    /**
     * Not supported in open source version, so test is expected to throw exception.
     */
    @Test(expected = InvalidConfigurationException.class)
    public void checkMapConfig_NATIVE() {
        checkMapConfig(getMapConfig(NATIVE), nativeMemoryConfig, splitBrainMergePolicyProvider, properties);
    }

    private MapConfig getMapConfig(InMemoryFormat inMemoryFormat) {
        return new MapConfig()
                .setInMemoryFormat(inMemoryFormat);
    }

    @Test
    public void checkCacheConfig_withEntryCountMaxSizePolicy_OBJECT() {
        EvictionConfig evictionConfig = new EvictionConfig()
                .setMaxSizePolicy(MaxSizePolicy.ENTRY_COUNT);
        CacheSimpleConfig cacheSimpleConfig = new CacheSimpleConfig()
                .setInMemoryFormat(OBJECT)
                .setEvictionConfig(evictionConfig);

        checkCacheConfig(cacheSimpleConfig, splitBrainMergePolicyProvider);
    }

    @Test(expected = IllegalArgumentException.class)
    public void checkCacheConfig_withEntryCountMaxSizePolicy_NATIVE() {
        EvictionConfig evictionConfig = new EvictionConfig()
                .setMaxSizePolicy(MaxSizePolicy.ENTRY_COUNT);
        CacheSimpleConfig cacheSimpleConfig = new CacheSimpleConfig()
                .setInMemoryFormat(NATIVE)
                .setEvictionConfig(evictionConfig);

        checkCacheConfig(cacheSimpleConfig, splitBrainMergePolicyProvider);
    }

    @Test
    public void checkNearCacheNativeMemoryConfig_shouldNotNeedNativeMemoryConfig_BINARY_onOS() {
        checkNearCacheNativeMemoryConfig(BINARY, null, false);
    }

    @Test
    public void checkNearCacheNativeMemoryConfig_shouldNotNeedNativeMemoryConfig_BINARY_onEE() {
        checkNearCacheNativeMemoryConfig(BINARY, null, true);
    }

    @Test
    public void checkNearCacheNativeMemoryConfig_shouldNotThrowExceptionWithoutNativeMemoryConfig_NATIVE_onOS() {
        checkNearCacheNativeMemoryConfig(NATIVE, null, false);
    }

    @Test
    public void checkNearCacheNativeMemoryConfig_shouldNotThrowExceptionWithNativeMemoryConfig_NATIVE_onEE() {
        NativeMemoryConfig nativeMemoryConfig = new NativeMemoryConfig()
                .setEnabled(true);

        checkNearCacheNativeMemoryConfig(NATIVE, nativeMemoryConfig, true);
    }

    @Test(expected = InvalidConfigurationException.class)
    public void checkNearCacheNativeMemoryConfig_shouldThrowExceptionWithoutNativeMemoryConfig_NATIVE_onEE() {
        checkNearCacheNativeMemoryConfig(NATIVE, null, true);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testValidationFails_whenGroupSizeSetCPMemberCountNotSet() {
        CPSubsystemConfig config = new CPSubsystemConfig();
        config.setGroupSize(3);

        checkCPSubsystemConfig(config);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testValidationFails_whenGroupSizeGreaterThanCPMemberCount() {
        CPSubsystemConfig config = new CPSubsystemConfig();
        config.setGroupSize(5);
        config.setCPMemberCount(3);

        checkCPSubsystemConfig(config);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testValidationFails_whenSessionHeartbeatIntervalGreaterThanSessionTTL() {
        CPSubsystemConfig config = new CPSubsystemConfig();
        config.setSessionTimeToLiveSeconds(5);
        config.setSessionHeartbeatIntervalSeconds(10);

        checkCPSubsystemConfig(config);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testValidationFails_whenSessionTTLGreaterThanMissingCPMemberAutoRemovalSeconds() {
        CPSubsystemConfig config = new CPSubsystemConfig();
        config.setMissingCPMemberAutoRemovalSeconds(5);
        config.setSessionTimeToLiveSeconds(10);

        checkCPSubsystemConfig(config);
    }
}


text:
package generate

import (
	"context"
	"os"
	"strings"

	"github.com/containers/common/libimage"
	"github.com/containers/podman/v3/libpod"
	"github.com/containers/podman/v3/libpod/define"
	ann "github.com/containers/podman/v3/pkg/annotations"
	envLib "github.com/containers/podman/v3/pkg/env"
	"github.com/containers/podman/v3/pkg/signal"
	"github.com/containers/podman/v3/pkg/specgen"
	spec "github.com/opencontainers/runtime-spec/specs-go"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
	"golang.org/x/sys/unix"
)

// Fill any missing parts of the spec generator (e.g. from the image).
// Returns a set of warnings or any fatal error that occurred.
func CompleteSpec(ctx context.Context, r *libpod.Runtime, s *specgen.SpecGenerator) ([]string, error) {
	// Only add image configuration if we have an image
	var newImage *libimage.Image
	var inspectData *libimage.ImageData
	var err error
	if s.Image != "" {
		newImage, _, err = r.LibimageRuntime().LookupImage(s.Image, nil)
		if err != nil {
			return nil, err
		}

		inspectData, err = newImage.Inspect(ctx, false)
		if err != nil {
			return nil, err
		}

		if s.HealthConfig == nil {
			// NOTE: the health check is only set for Docker images
			// but inspect will take care of it.
			s.HealthConfig = inspectData.HealthCheck
		}

		// Image stop signal
		if s.StopSignal == nil {
			if inspectData.Config.StopSignal != "" {
				sig, err := signal.ParseSignalNameOrNumber(inspectData.Config.StopSignal)
				if err != nil {
					return nil, err
				}
				s.StopSignal = &sig
			}
		}
	}

	rtc, err := r.GetConfig()
	if err != nil {
		return nil, err
	}

	// Get Default Environment from containers.conf
	defaultEnvs, err := envLib.ParseSlice(rtc.GetDefaultEnvEx(s.EnvHost, s.HTTPProxy))
	if err != nil {
		return nil, errors.Wrap(err, "error parsing fields in containers.conf")
	}
	if defaultEnvs["container"] == "" {
		defaultEnvs["container"] = "podman"
	}
	var envs map[string]string

	// Image Environment defaults
	if inspectData != nil {
		// Image envs from the image if they don't exist
		// already, overriding the default environments
		envs, err = envLib.ParseSlice(inspectData.Config.Env)
		if err != nil {
			return nil, errors.Wrap(err, "Env fields from image failed to parse")
		}
		defaultEnvs = envLib.Join(defaultEnvs, envs)
	}

	// First transform the os env into a map. We need it for the labels later in
	// any case.
	osEnv, err := envLib.ParseSlice(os.Environ())
	if err != nil {
		return nil, errors.Wrap(err, "error parsing host environment variables")
	}
	// Caller Specified defaults
	if s.EnvHost {
		defaultEnvs = envLib.Join(defaultEnvs, osEnv)
	} else if s.HTTPProxy {
		for _, envSpec := range []string{
			"http_proxy",
			"HTTP_PROXY",
			"https_proxy",
			"HTTPS_PROXY",
			"ftp_proxy",
			"FTP_PROXY",
			"no_proxy",
			"NO_PROXY",
		} {
			if v, ok := osEnv[envSpec]; ok {
				defaultEnvs[envSpec] = v
			}
		}
	}

	s.Env = envLib.Join(defaultEnvs, s.Env)

	// Labels and Annotations
	annotations := make(map[string]string)
	if newImage != nil {
		labels, err := newImage.Labels(ctx)
		if err != nil {
			return nil, err
		}

		// labels from the image that don't exist already
		if len(labels) > 0 && s.Labels == nil {
			s.Labels = make(map[string]string)
		}
		for k, v := range labels {
			if _, exists := s.Labels[k]; !exists {
				s.Labels[k] = v
			}
		}

		// Add annotations from the image
		for k, v := range inspectData.Annotations {
			annotations[k] = v
		}
	}

	// in the event this container is in a pod, and the pod has an infra container
	// we will want to configure it as a type "container" instead defaulting to
	// the behavior of a "sandbox" container
	// In Kata containers:
	// - "sandbox" is the annotation that denotes the container should use its own
	//   VM, which is the default behavior
	// - "container" denotes the container should join the VM of the SandboxID
	//   (the infra container)

	if len(s.Pod) > 0 {
		annotations[ann.SandboxID] = s.Pod
		annotations[ann.ContainerType] = ann.ContainerTypeContainer
	}

	for _, v := range rtc.Containers.Annotations {
		split := strings.SplitN(v, "=", 2)
		k := split[0]
		v := ""
		if len(split) == 2 {
			v = split[1]
		}
		annotations[k] = v
	}
	// now pass in the values from client
	for k, v := range s.Annotations {
		annotations[k] = v
	}
	s.Annotations = annotations

	if len(s.SeccompProfilePath) < 1 {
		p, err := libpod.DefaultSeccompPath()
		if err != nil {
			return nil, err
		}
		s.SeccompProfilePath = p
	}

	if len(s.User) == 0 && inspectData != nil {
		s.User = inspectData.Config.User
	}
	if err := finishThrottleDevices(s); err != nil {
		return nil, err
	}
	// Unless already set via the CLI, check if we need to disable process
	// labels or set the defaults.
	if len(s.SelinuxOpts) == 0 {
		if err := setLabelOpts(s, r, s.PidNS, s.IpcNS); err != nil {
			return nil, err
		}
	}

	// If caller did not specify Pids Limits load default
	if s.ResourceLimits == nil || s.ResourceLimits.Pids == nil {
		if s.CgroupsMode != "disabled" {
			limit := rtc.PidsLimit()
			if limit != 0 {
				if s.ResourceLimits == nil {
					s.ResourceLimits = &spec.LinuxResources{}
				}
				s.ResourceLimits.Pids = &spec.LinuxPids{
					Limit: limit,
				}
			}
		}
	}

	if s.LogConfiguration == nil {
		s.LogConfiguration = &specgen.LogConfig{}
	}
	// set log-driver from common if not already set
	if len(s.LogConfiguration.Driver) < 1 {
		s.LogConfiguration.Driver = rtc.Containers.LogDriver
	}
	if len(rtc.Containers.LogTag) > 0 {
		if s.LogConfiguration.Driver != define.JSONLogging {
			if s.LogConfiguration.Options == nil {
				s.LogConfiguration.Options = make(map[string]string)
			}

			s.LogConfiguration.Options["tag"] = rtc.Containers.LogTag
		} else {
			logrus.Warnf("log_tag %q is not allowed with %q log_driver", rtc.Containers.LogTag, define.JSONLogging)
		}
	}

	warnings, err := verifyContainerResources(s)
	if err != nil {
		return warnings, err
	}

	// Warn on net=host/container/pod/none and port mappings.
	if (s.NetNS.NSMode == specgen.Host || s.NetNS.NSMode == specgen.FromContainer ||
		s.NetNS.NSMode == specgen.FromPod || s.NetNS.NSMode == specgen.NoNetwork) &&
		len(s.PortMappings) > 0 {
		warnings = append(warnings, "Port mappings have been discarded as one of the Host, Container, Pod, and None network modes are in use")
	}

	return warnings, nil
}

// finishThrottleDevices takes the temporary representation of the throttle
// devices in the specgen and looks up the major and major minors. it then
// sets the throttle devices proper in the specgen
func finishThrottleDevices(s *specgen.SpecGenerator) error {
	if bps := s.ThrottleReadBpsDevice; len(bps) > 0 {
		for k, v := range bps {
			statT := unix.Stat_t{}
			if err := unix.Stat(k, &statT); err != nil {
				return err
			}
			v.Major = (int64(unix.Major(uint64(statT.Rdev))))
			v.Minor = (int64(unix.Minor(uint64(statT.Rdev))))
			s.ResourceLimits.BlockIO.ThrottleReadBpsDevice = append(s.ResourceLimits.BlockIO.ThrottleReadBpsDevice, v)
		}
	}
	if bps := s.ThrottleWriteBpsDevice; len(bps) > 0 {
		for k, v := range bps {
			statT := unix.Stat_t{}
			if err := unix.Stat(k, &statT); err != nil {
				return err
			}
			v.Major = (int64(unix.Major(uint64(statT.Rdev))))
			v.Minor = (int64(unix.Minor(uint64(statT.Rdev))))
			s.ResourceLimits.BlockIO.ThrottleWriteBpsDevice = append(s.ResourceLimits.BlockIO.ThrottleWriteBpsDevice, v)
		}
	}
	if iops := s.ThrottleReadIOPSDevice; len(iops) > 0 {
		for k, v := range iops {
			statT := unix.Stat_t{}
			if err := unix.Stat(k, &statT); err != nil {
				return err
			}
			v.Major = (int64(unix.Major(uint64(statT.Rdev))))
			v.Minor = (int64(unix.Minor(uint64(statT.Rdev))))
			s.ResourceLimits.BlockIO.ThrottleReadIOPSDevice = append(s.ResourceLimits.BlockIO.ThrottleReadIOPSDevice, v)
		}
	}
	if iops := s.ThrottleWriteIOPSDevice; len(iops) > 0 {
		for k, v := range iops {
			statT := unix.Stat_t{}
			if err := unix.Stat(k, &statT); err != nil {
				return err
			}
			v.Major = (int64(unix.Major(uint64(statT.Rdev))))
			v.Minor = (int64(unix.Minor(uint64(statT.Rdev))))
			s.ResourceLimits.BlockIO.ThrottleWriteIOPSDevice = append(s.ResourceLimits.BlockIO.ThrottleWriteIOPSDevice, v)
		}
	}
	return nil
}


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

$lang['email_must_be_array'] = 'Parametrem validace emailu musí bát pole.';
$lang['email_invalid_address'] = 'Nesprávna emailová adresa: %s';
$lang['email_attachment_missing'] = 'Nepodařilo se nalézt přílohu: %s';
$lang['email_attachment_unreadable'] = 'Nepodařilo se otevřít přílohu: %s';
$lang['email_no_from'] = 'Není možné odeslat  email bez "From" v hlavičce.';
$lang['email_no_recipients'] = 'Je nutné specifikovat alespoň jednoho adresáta: To, Cc, or Bcc';
$lang['email_send_failure_phpmail'] = 'Nepodařilo se odeslat email pomocí mail(). Je možné že není serverem podporována.';
$lang['email_send_failure_sendmail'] = 'Nepodařilo se odeslat email pomocí Sendmail. Je možné že není serverem podporována.';
$lang['email_send_failure_smtp'] = 'Nepodařilo se odeslat email pomocí SMTP. Je možné že není serverem podporována.';
$lang['email_sent'] = 'Vaše zpráva byla úspěšně odeslána pmocí protokolu: %s';
$lang['email_no_socket'] = 'Nepodařilo se otevřít socket pro Sendmail. Zkontrolujte prosím nastavení';
$lang['email_no_hostname'] = 'Není specifikováno SMTP hostname.';
$lang['email_smtp_error'] = 'Nastal SMTP error: %s';
$lang['email_no_smtp_unpw'] = 'Error: Je nutné poskytnout SMTP přihlašovací jméno a heslo.';
$lang['email_failed_smtp_login'] = 'Nepodařilo se odeslat příkaz AUTH LOGIN. Error: %s';
$lang['email_smtp_auth_un'] = 'Nepodařilo se autentizovat pomocjí přihlašovacího jména. Error: %s';
$lang['email_smtp_auth_pw'] = 'Nepodařilo se autentizovat pomocjí hesla. Error: %s';
$lang['email_smtp_data_failure'] = 'Nemodařilo se odeslat data: %s';
$lang['email_exit_status'] = 'Exit s kódem: %s';


text:
require 'rails_helper'
include Api::FeedsHelper

describe Api::StagesController do
  render_views

  before :each do
    controller.go_cache.clear
    allow(controller).to receive(:stage_service).and_return(@stage_service = double())
    # allow(controller).to receive(:set_locale)
    allow(controller).to receive(:populate_config_validity)

  end

  it "should load stage data" do
    stage = StageMother.create_passed_stage("pipeline_name", 30, "stage_name", 2, "dev", java.util.Date.new())
    stage.setPipelineId(120)
    expect(@stage_service).to receive(:stageById).with(99).and_return(stage)
    get 'index', params: {:id => "99", :format => "xml", :no_layout => true}

    doc = Nokogiri::XML(response.body)
    stage_element = doc.xpath("stage[@name='stage_name'][@counter='2']")
    expect(stage_element).to_not be_nil_or_empty

    stage_element.tap do |entry|
      expect(entry.xpath("link[@rel='self'][@href='http://test.host/go/api/stages/#{stage.getId()}.xml']")).to_not be_nil_or_empty
      expect(entry.xpath("pipeline[@name='pipeline_name'][@counter='30'][@label='LABEL-30'][@href='http://test.host/go/api/pipelines/pipeline_name/120.xml']")).to_not be_nil_or_empty
      expect(entry.xpath("updated").text).to eq(DateUtils.formatISO8601(stage.latestTransitionDate()))
      expect(entry.xpath("result").text).to eq(StageResult::Passed.to_s)
      expect(entry.xpath("state").text).to eq("Completed")
      expect(entry.xpath("approvedBy").text).to eq(GoConstants::DEFAULT_APPROVED_BY)

      job_element = entry.xpath("jobs")
      expect(job_element).to_not be_nil_or_empty
      job_element.tap do |node|
        expect(node.xpath("job[@href='http://test.host/go/api/jobs/-1.xml']")).to_not be_nil_or_empty
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <filter>
        <filter-name>ObjectifyFilter</filter-name>
        <filter-class>com.googlecode.objectify.ObjectifyFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>ObjectifyFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>plainTextDelta</servlet-name>
        <servlet-class>edu.sjsu.cs218.deltasADT.PlainTextDeltaServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>plainTextDelta</servlet-name>
        <url-pattern>/plainTextDelta</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>searchReplaceDelta</servlet-name>
        <servlet-class>edu.sjsu.cs218.deltasADT.SearchReplaceDeltaServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>searchReplaceDelta</servlet-name>
        <url-pattern>/searchReplaceDelta</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>adtDelta</servlet-name>
        <servlet-class>edu.sjsu.cs218.deltasADT.AdtDeltaServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>adtDelta</servlet-name>
        <url-pattern>/adtDelta</url-pattern>
    </servlet-mapping>

</web-app>


text:
package core.framework.internal.template.source;

/**
 * @author neo
 */
public interface TemplateSource {
    String name();

    String content();

    TemplateSource resolve(String path);
}


text:
require 'rails_helper'

RSpec.describe RecipeDetailsController, type: :controller do
  include RecipeContext
  login_user

  let!(:recipe_detail) { RecipeDetail.create! detail_attributes }
  # TODO: Add ingredients
  let(:detail_attributes) {
    {
      batch_size: 20.0,
      efficiency: 72.0,
      recipe: recipe
    }
  }

  let(:invalid_attributes) {
    skip("Add a hash of attributes invalid for your model")
  }

  let(:valid_session) { {} }

  describe 'GET #show' do
    subject(:get_show) do
      get :show, params: { recipe_id: recipe.id }, session: valid_session
    end

    login_user

    it 'returns a success response' do
      get_show
      expect(response).to be_success
    end

    it 'assigns recipe ingredients' do
      get_show
      expect(assigns(:details)).to eq recipe_detail
      expect(assigns(:hops)).to eq recipe_detail.hops
      expect(assigns(:fermentables)).to eq recipe_detail.fermentables
      expect(assigns(:miscs)).to eq recipe_detail.miscs
      expect(assigns(:yeasts)).to eq recipe_detail.yeasts
    end

    it "creates a RecipeDetail for recipe if it doesn't exist"
  end

end


text:
using System.Web.Routing;

namespace Canonicalize
{
    /// <summary>
    /// Adds an extension method on <see cref="RouteCollection"/> enabling the fluent API.
    /// </summary>
    public static class RouteCollectionExtensions
    {
        /// <summary>
        /// Adds a <see cref="CanonicalizeRoute"/> to the route collection and returns a <see cref="CanonicalizeRouteBuilder"/> for fluent configuration.
        /// </summary>
        /// <param name="routes">The collection to which the <see cref="CanonicalizeRoute"/> is to be added.</param>
        /// <returns>Entry object for fluent URL canonicaliztion configuration.</returns>
        public static CanonicalizeRouteBuilder Canonicalize(this RouteCollection routes)
        {
            var route = new CanonicalizeRoute();
            routes.Add(route);

            return new CanonicalizeRouteBuilder(route);
        }
    }
}


text:
package org.apache.heron.scheduler.kubernetes;

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

import org.apache.heron.spi.common.Config;

import io.kubernetes.client.models.V1AWSElasticBlockStoreVolumeSource;
import io.kubernetes.client.models.V1HostPathVolumeSource;
import io.kubernetes.client.models.V1NFSVolumeSource;
import io.kubernetes.client.models.V1Volume;

final class Volumes {

  static final String AWS_EBS = "awsElasticBlockStore";
  static final String HOST_PATH = "hostPath";
  static final String NFS = "nfs";

  private final Map<String, VolumeFactory> volumes = new HashMap<>();

  private Volumes() {
    volumes.put(HOST_PATH, new HostPathVolumeFactory());
    volumes.put(NFS, new NfsVolumeFactory());
    volumes.put(AWS_EBS, new AwsEbsVolumeFactory());
  }

  static Volumes get() {
    return new Volumes();
  }

  V1Volume create(Config config) {
    final String volumeType = KubernetesContext.getVolumeType(config);
    if (volumes.containsKey(volumeType)) {
      return volumes.get(volumeType).create(config);
    }
    return null;
  }

  interface VolumeFactory {
    V1Volume create(Config config);
  }

  private static V1Volume newVolume(Config config) {
    final String volumeName = KubernetesContext.getVolumeName(config);
    return new V1Volume().name(volumeName);
  }

  static class HostPathVolumeFactory implements VolumeFactory {
    @Override
    public V1Volume create(Config config) {
      final V1Volume volume = newVolume(config);

      final String path = KubernetesContext.getHostPathVolumePath(config);
      final V1HostPathVolumeSource hostPathVolume =
          new V1HostPathVolumeSource()
              .path(path);
      volume.hostPath(hostPathVolume);

      return volume;
    }
  }

  static class NfsVolumeFactory implements VolumeFactory {
    @Override
    public V1Volume create(Config config) {
      final V1Volume volume = newVolume(config);

      final String path = KubernetesContext.getNfsVolumePath(config);
      final String server = KubernetesContext.getNfsServer(config);
      V1NFSVolumeSource nfsVolumeSource =
          new V1NFSVolumeSource()
              .path(path)
              .server(server);
      volume.setNfs(nfsVolumeSource);

      return volume;
    }
  }

  static class AwsEbsVolumeFactory implements VolumeFactory {
    @Override
    public V1Volume create(Config config) {
      final V1Volume volume = newVolume(config);

      final String volumeId = KubernetesContext.getAwsEbsVolumeId(config);
      final String fsType = KubernetesContext.getAwsEbsFsType(config);
      V1AWSElasticBlockStoreVolumeSource awsElasticBlockStoreVolumeSource =
          new V1AWSElasticBlockStoreVolumeSource()
              .volumeID(volumeId)
              .fsType(fsType);
      volume.setAwsElasticBlockStore(awsElasticBlockStoreVolumeSource);

      return volume;
    }
  }
}