text:
using System;
using System.IO;
using System.Diagnostics;

using ICSharpCode.SharpZipLib;
using ICSharpCode.SharpZipLib.GZip;

namespace MCloud.Deploy
{
	/// <summary>
	/// Push a local database to the node. If the remote node already has
	/// a database with the same name it will be destroyed and all of its
	/// data will be lost.
	/// This will push the schema and all data, it will not push any privilege
	/// information.
	/// The remote server must already have postgresql installed and running.
	/// </summary>
	public class PushPgsqlDB : SSHDeployment
	{
		private string database;
		private string dump_file;

		/// <summary>
		/// Create a PushNpgsqlDB deployment command with the specified database name.
		/// </summary>
		/// <param name="db_name">
		/// A <see cref="System.String"/>
		/// The name of the database to pull from and push to.
		/// </param>
		public PushPgsqlDB (string db_name)
		{
			Database = db_name;
		}

		/// <summary>
		/// The name of the database to pull data from.
		/// </summary>
		public string Database {
			get { return database; }
			set {
				if (database != value)
					SetDumpFile (null);
				database = value;
			}
		}

		protected override void RunImpl (Node node, NodeAuth auth)
		{
			string host = node.PublicIPs [0].ToString ();
			string file = GetDumpFile ();

			PutFile (host, auth, file, "/root/dump.sql.gz");
			RunCommand ("gunzip -d -f /root/dump.sql.gz", host, auth);
			RunCommand ("mv /root/dump.sql ~postgres/.", host, auth);
			RunCommand ("sudo -u postgres psql -f ~postgres/dump.sql", host, auth);
		}

		private string GetDumpFile ()
		{
			if (dump_file != null)
				return dump_file;

			string file = Path.GetTempFileName ();

			Process p = new Process ();
			// how the hell do i find this on windows?
			p.StartInfo.FileName = "pg_dump";
			p.StartInfo.Arguments = String.Format ("-f {0} -x {1}", file, Database);
			p.StartInfo.UseShellExecute = true;

			p.Start ();
			p.WaitForExit ();

			string zip = Path.GetTempFileName () + ".sql.gz";
			FileStream s = File.OpenWrite (zip);
			FileStream dump_stream = File.OpenRead (file);
			GZipOutputStream zstream = new GZipOutputStream (s);

			int size;
			byte [] buffer = new byte [1000];
    		do {
        		size = dump_stream.Read (buffer, 0, buffer.Length);
        		zstream.Write (buffer, 0, size);
    		} while (size > 0);

			zstream.Close();
    		dump_stream.Close();

			dump_file = zip;
			return zip;
		}

		private void SetDumpFile (string file)
		{
			if (file == null && dump_file != null)
				File.Delete (dump_file);

			dump_file = file;
		}
	}
}


text:
window.onload = main;

function main (){
	var pointA = {
	  x: 3,
	  y: 5
	}

	var pointB = {
	  x: 1,
	  y: 1
	}

	var pointC = pointA;

	var tw = new TWUnit();
	tw.addAssert("Points 1", pointA === pointB, "Are Equals!!", "Aren't equals, what a pity :(");
	tw.addAssert("Points 2", pointA === pointC, "Are Equals!!", "Aren't equals, what a pity :(");
	tw.addAssert("Points 3", pointB === pointC, "Are Equals!!", "Aren't equals, what a pity :(");
	tw.addModule("Points Module");

	tw.addAssert("Sum 1", sum(2,3) == 3, "Very Good!", "Do you know how to sum numbers?");
	tw.addAssert("Sum 2", sum(2,3) == 4, "Very Good!", "Do you know how to sum numbers?");
	tw.addAssert("Sum 3", sum(2,3) == 5, "Very Good!", "Do you know how to sum numbers?");
	tw.addModule("Sum Module");

	tw.runModules();

	if (tw.moduleOk("Points Module"))
		console.log("Points Module are true!");
	else
		console.log("Points Module are false... :(")

	if (tw.modulesOk())
		console.log("All modules are true");
	else
		console.log("You fail...");

}

function sum (number1, number2){
	return number1 + number2;
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Etu\Core\UserBundle\Command;

use Doctrine\ORM\EntityManager;
use Etu\Core\UserBundle\Command\Util\ProgressBar;
use Etu\Core\UserBundle\Entity\User;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class ImportAdmisCommand extends ContainerAwareCommand
{
    /**
     * Configure the command
     */
    protected function configure()
    {
        $this
            ->setName('etu:users:import-admis')
            ->setDescription('Import new temp users')
        ;
    }

    /**
     * @param \Symfony\Component\Console\Input\InputInterface $input
     * @param \Symfony\Component\Console\Output\OutputInterface $output
     * @return void
     * @throws \RuntimeException
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln("\nConnecting to database ...");
        $output->writeln('----------------------------------------');

        $dialog = $this->getHelperSet()->get('dialog');

        $host = $dialog->ask($output, 'Host: ');
        $name = $dialog->ask($output, 'Name: ');
        $user = $dialog->ask($output, 'User: ');
        $pass = $dialog->ask($output, 'Pass: ');

        $pdo = new \PDO('mysql:host=' . $host . ';dbname=' . $name, $user, $pass);
        $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

        $output->writeln("\nFinding users differences ...");
        $output->writeln('----------------------------------------');

        /** @var EntityManager $em */
        $em = $this->getContainer()->get('doctrine')->getManager();

        /*
         * Imported
         */
        $imported = $pdo->query('SELECT * FROM admis')->fetchAll(\PDO::FETCH_OBJ);

        $importedLogins = [];
        $importedRegistry = [];

        foreach ($imported as $import) {
            $importedRegistry[$import->login] = $import;
            $importedLogins[] = $import->login;
        }

        /*
         * Database
         */
        $qb = $em->createQueryBuilder();

        $dbUsers = $qb->select('u.login')
            ->from('EtuUserBundle:User', 'u')
            ->where($qb->expr()->in('u.login', $importedLogins))
            ->getQuery()
            ->getArrayResult();

        $dbLogins = [];

        foreach ($dbUsers as $dbUser) {
            $dbLogins[] = $dbUser['login'];
        }

        $toImport = array_diff($importedLogins, $dbLogins);

        $output->writeln(sprintf('%s users to import', count($toImport)));
        $output->writeln("\nImporting users ...");

        if (count($toImport) > 0) {
            $bar = new ProgressBar('%fraction% [%bar%] %percent%', '=>', ' ', 80, count($toImport));
            $bar->update(0);
            $i = 1;

            foreach($toImport as $loginToImport) {
                $import = $importedRegistry[$loginToImport];

                $user = new User();
                $user->setLogin($import->login);
                $user->setPassword($this->getContainer()->get('etu.user.crypting')->encrypt($import->password));
                $user->setFullName($import->prenom . ' ' . $import->nom);
                $user->setSex(($import->sexe == 'M') ? User::SEX_MALE : User::SEX_FEMALE);
                $user->setSexPrivacy(User::PRIVACY_PRIVATE);
                $user->setCity(ucfirst(strtolower($import->ville)));
                $user->setCityPrivacy(User::PRIVACY_PRIVATE);
                $user->setPostalCode($import->codePostal);
                $user->setPostalCodePrivacy(User::PRIVACY_PRIVATE);
                $user->setCountry(ucfirst(strtolower($import->pays)));
                $user->setCountryPrivacy(User::PRIVACY_PRIVATE);
                $user->setPersonnalMail($import->email);
                $user->setPersonnalMailPrivacy(User::PRIVACY_PRIVATE);
                $user->setBranch($import->branche);
                $user->setFiliere($import->specialite);
                $user->setNiveau(intval($import->niveau));
                $user->setFormation('Inconnue');
                $user->setLanguage('fr');
                $user->setKeepActive(false);

                $em->persist($user);
                $em->flush();

                $bar->update($i);
                $i++;
            }
        }

        $output->write("\nDone\n");
	}
}


text:
package fr.ocr.ihm;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

import com.voiture.Marque;
import com.voiture.Vehicule;
import com.voiture.moteur.Moteur;
import com.voiture.option.Option;

import fr.ocr.sql.DAOMarque;
import fr.ocr.sql.DAOMoteur;
import fr.ocr.sql.DAOOption;
import fr.ocr.sql.DAOVehicule;
import fr.ocr.sql.DatabaseTable;
import fr.ocr.sql.HsqldbConnection;

/***
 *
 * @author XXX
 *
 */
public class DialogAddVehiculeNew extends JDialog {

	/**
	 * VersionID
	 */
	private static final long serialVersionUID = 6378094983421420551L;

	private JTextField jtName;
	private JFormattedTextField jtPrice;
	private JLabel jlName, jlMark, jlMotor, jlPrice;
	private JComboBox<Object> jcbMotors, jcbMarks;
	private JCheckBox[] jcbOptions;

	private List<Option> listOptions = new DAOOption(HsqldbConnection.getInstance()).findAll();
	private List<Moteur> listMotors = new DAOMoteur(HsqldbConnection.getInstance()).findAll();
	private List<Marque> listMarks = new DAOMarque(HsqldbConnection.getInstance()).findAll();

	private Vehicule vehicle;
	private JFrame frame;

	/**
	 *
	 * @param jpParent
	 * @param sTitle
	 * @param isModal
	 */
	public DialogAddVehiculeNew(JFrame jpParent, String sTitle, boolean isModal) {
		super(jpParent, sTitle, isModal);
		frame = jpParent;
		this.setSize(550, 350);
		this.setLocationRelativeTo(null);
		this.setResizable(false);
		this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		this.initComponent();
	}

	/**
	 *
	 * @return
	 */
	public boolean showDialog() {
		this.setVisible(true);
		this.setAlwaysOnTop(true);
		return true;
	}

	/**
	 * Init des composants
	 */
	private void initComponent() {

		// ===================================================================================
		// Bloc Nom du véhicule
		// ===================================================================================
		JPanel jpName = new JPanel();
		jpName.setBackground(Color.white);
		jpName.setPreferredSize(new Dimension(220, 60));
		jtName = new JTextField();
		jtName.setPreferredSize(new Dimension(100, 25));
		jpName.setBorder(BorderFactory.createTitledBorder("Nom du véhicule"));
		jlName = new JLabel("Nom : ");
		jpName.add(jlName);
		jpName.add(jtName);

		// ===================================================================================
		// Bloc Marque du véhicule
		// ===================================================================================
		JPanel jpMark = new JPanel();
		jpMark.setBackground(Color.white);
		jpMark.setPreferredSize(new Dimension(220, 60));
		jpMark.setBorder(BorderFactory.createTitledBorder("Marque du véhicule"));
		jcbMarks = new JComboBox<Object>();

		for (Marque m : listMarks)
			jcbMarks.addItem(m);

		jlMark = new JLabel("Marque : ");
		jpMark.add(jlMark);
		jpMark.add(jcbMarks);

		// ===================================================================================
		// Bloc Moteur du véhicule
		// ===================================================================================
		JPanel jpMotor = new JPanel();
		jpMotor.setBackground(Color.white);
		jpMotor.setBorder(BorderFactory.createTitledBorder("Type de moteur du véhicule"));
		jpMotor.setPreferredSize(new Dimension(440, 60));

		jcbMotors = new JComboBox<Object>();

		for (Moteur m : listMotors) {
			jcbMotors.addItem(m);
		}
		jlMotor = new JLabel("Moteur : ");
		jpMotor.add(jlMotor);
		jpMotor.add(jcbMotors);

		// ===================================================================================
		// Bloc Prix du véhicule
		// ===================================================================================
		JPanel jpPrice = new JPanel();

		jpPrice.setBackground(Color.white);
		jpPrice.setPreferredSize(new Dimension(440, 60));
		jpPrice.setBorder(BorderFactory.createTitledBorder("Prix du véhicule"));

		jtPrice = new JFormattedTextField(NumberFormat.getNumberInstance());
		jtPrice.setPreferredSize(new Dimension(100, 25));
		jlPrice = new JLabel("Prix :");

		jpPrice.add(jlPrice);
		jpPrice.add(jtPrice);

		// ===================================================================================
		// Bloc Options du véhicule
		// ===================================================================================
		JPanel jpOptions = new JPanel();
		jpOptions.setBackground(Color.white);
		jpOptions.setPreferredSize(new Dimension(530, 80));
		jpOptions.setBorder(BorderFactory.createTitledBorder("Options Disponibles"));

		jcbOptions = new JCheckBox[listOptions.size()];

		for (int i = 0; i < listOptions.size(); i++) {
			Option opt = listOptions.get(i);
			jcbOptions[i] = new JCheckBox(opt.toString());
			jpOptions.add(jcbOptions[i]);
		}

		JPanel jpContent = new JPanel();
		jpContent.setBackground(Color.white);
		jpContent.add(jpName);
		jpContent.add(jpMark);
		jpContent.add(jpMotor);
		jpContent.add(jpPrice);
		jpContent.add(jpOptions);

		JPanel jpControl = new JPanel();
		JButton jBtnOK = new JButton("OK");

		// Quand on valide l'ajout du nouveau véhicule par clique sur le bouton
		// OK
		jBtnOK.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {

				String nameVehicle = jtName.getText();
				try {

					// Message de contrôle si le Nom est vide
					if (nameVehicle.trim().equals("")) {
						throw new EmptyFieldException("Le champ 'nom' est obligatoire ! ");
					}

					// Message de contrôle si le prixe est vide
					if (jtPrice.getText().trim().equals("")) {
						throw new EmptyFieldException("Le champ 'prix' est obligatoire ! ");
					}
					// Récupérer les données de la Marque
					Marque mark = (Marque) jcbMarks.getSelectedItem();

					// Récupérer les donénes du Moteur
					Moteur motor = (Moteur) jcbMotors.getSelectedItem();

					// Récupérer les données des Options
					List<Option> listOpt = new ArrayList<>();
					for (int i = 0; i < jcbOptions.length; i++) {
						if (jcbOptions[i].isSelected()) {
							listOpt.add(listOptions.get(i));
						}
					}

					// Récupérer les données Prix
					Double price = ((Number) jtPrice.getValue()).doubleValue();

					// Créer le nouveau véhicule
					vehicle = new Vehicule(0, nameVehicle, mark, motor, listOpt, price);

					// Sauvegarder en base et update JTable
					Thread t = new Thread(new Runnable() {
						public void run() {
							DAOVehicule vehicleDao = new DAOVehicule(HsqldbConnection.getInstance());
							boolean result = vehicleDao.create(vehicle);
							if (result) {
								SwingUtilities.invokeLater(new Runnable() {
									public void run() {
										frame.getContentPane().removeAll();
										frame.getContentPane().add(new JScrollPane(SortTable.getTableSorted(DatabaseTable.VEHICULE)), BorderLayout.CENTER);
										frame.getContentPane().revalidate();
									}
								});
							}
						}
					});
					t.start();
					setVisible(false);
				} catch (EmptyFieldException e) {
				} catch (NumberFormatException e) {
					new EmptyFieldException(e.getMessage());
				}
			}
		});

		// Clique sur le bouton Annuler
		JButton jBtnCancel = new JButton("Annuler");
		jBtnCancel.setForeground(Color.red);
		jBtnCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				setVisible(false);
			}
		});

		jpControl.add(jBtnOK);
		jpControl.add(jBtnCancel);

		this.getContentPane().add(jpContent, BorderLayout.CENTER);
		this.getContentPane().add(jpControl, BorderLayout.SOUTH);
	}
}


text:
title: Mathematics
icon: widgets

resources:

layout: page
---

    {% for resource in page.resources %}

      {{ resource.icon }}
      {{ resource.title }}

{{ resource.description }}

    {% endfor %}
    {% for page in site.pages %}
    {% if page.category == "Mathematics" %}

      {{ page.icon }}
      {{ page.title }}

{{ page.description }}

    {% endif %}
    {% endfor %}


text:
Passerelle
===

Passerelle is a Flask-based Python app that **takes one git URL, clones
it locally and pushes it to a second URL**.

I'm building this in the context of pushing a specific git repo to
Heroku from a Chrome extension. Since I can't push directly from a
browser (unless I rebuilt a git client in Native Client, I guess?),
here is Passerelle.

How to use Passerelle
---

I'm just starting so I'm not entirely sure how it will work, but most
likely you'll have your Passerelle instance and will call it with
something that look like that:

    http://passerelle.example.com/?from=git@github.com%3ATimothee/Passerelle.git&to=git@heroku.com%3Apasserelle-heroku.git

and with some way to insure you're you and not anybody. Still TBD, but
I'd probably have a secret key set as environment variable that the
JavaScript client would also know and bim bam boom, we have something to
compare.

License
---

This code is provided under the MIT License.

(c) 2013 Timothée Boucher - timotheeboucher.com


text:
'use strict';

// Load requirements
const path = require('path'),
      fs = require('fs'),
      assign = require('deep-assign');

module.exports = function() {

  // Build base class
  let config = {

    setup: false,

    osSetup: false,

    directories: {
      config: path.resolve(path.join(__base, '../config')),
      settings: path.resolve(path.join(__base, '../config'))
    },

    file: null,

    get: function() {
      return ( this.exists() ? JSON.parse(fs.readFileSync(this.file, 'utf8')) : {} );
    },

    set: function(config) {
      fs.writeFileSync(this.file, JSON.stringify(assign(this.get(), config), null, 4));
    },

    exists: function() {
      return fs.existsSync(this.file);
    }
  };

  // Set file path
  config.file = path.join(config.directories.config, 'config.json');

  // Try to create the config directory
  if ( ! fs.existsSync(config.directories.config) ) {
    fs.mkdirSync(config.directories.config);

    if ( ! fs.existsSync(config.directories.config) ) {
      throw new Error('Failed to create config directory');
    }
  }

  // Create config file
  if ( ! config.exists() ) {
    config.set({setup: config.setup, directories: config.directories});

  // Merge existing config into object
  } else {
    config = assign(config, config.get());
  }

  return config;
};


text:
from __future__ import division
# use cPickle when using python2 for better performance
try:
    import cPickle as pickle
except ImportError:
    import pickle
import logging
import os
import random
import re
from collections import defaultdict

class StringContinuationImpossibleError(Exception):
    pass

# {words: {word: prob}}
# We have to define these as separate functions so they can be pickled.
def _db_factory():
    return defaultdict(_one_dict)

def _one():
    return 1.0

def _one_dict():
    return defaultdict(_one)

def _wordIter(text, separator='.'):
    """
    An iterator over the 'words' in the given text, as defined by
    the regular expression given as separator.
    """
    exp = re.compile(separator)
    pos = 0
    for occ in exp.finditer(text):
        sub = text[pos:occ.start()].strip()
        if sub:
            yield sub
        pos = occ.start() + 1
    if pos < len(text):
        # take case of the last part
        sub = text[pos:].strip()
        if sub:
            yield sub

class MarkovChain(object):
    def __init__(self, dbFilePath=None):
        self.dbFilePath = dbFilePath
        if not dbFilePath:
            self.dbFilePath = os.path.join(os.path.dirname(__file__), "markovdb")
        try:
            with open(self.dbFilePath, 'rb') as dbfile:
                self.db = pickle.load(dbfile)
        except (IOError, ValueError):
            logging.warn('Database file corrupt or not found, using empty database')
            self.db = _db_factory()

    def generateDatabase(self, textSample, sentenceSep='[.\n]', n=2):
        """ Generate word probability database from raw content string """
        # I'm using the database to temporarily store word counts
        textSample = _wordIter(textSample, sentenceSep)  # get an iterator for the 'sentences'
        # We're using '' as special symbol for the beginning
        # of a sentence
        self.db[('',)][''] = 0.0
        for line in textSample:
            words = line.strip().split()  # split words in line
            if len(words) == 0:
                continue
            # first word follows a sentence end
            self.db[("",)][words[0]] += 1

            for order in range(1, n + 1):
                for i in range(len(words) - 1):
                    if i + order >= len(words):
                        continue
                    word = tuple(words[i:i + order])
                    self.db[word][words[i + order]] += 1

                # last word precedes a sentence end
                self.db[tuple(words[len(words) - order:len(words)])][""] += 1

        # We've now got the db filled with parametrized word counts
        # We still need to normalize this to represent probabilities
        for word in self.db:
            wordsum = 0
            for nextword in self.db[word]:
                wordsum += self.db[word][nextword]
            if wordsum != 0:
                for nextword in self.db[word]:
                    self.db[word][nextword] /= wordsum
        return self.dumpdb()

    def dumpdb(self):
        try:
            with open(self.dbFilePath, 'wb') as dbfile:
                pickle.dump(self.db, dbfile)
            # It looks like db was written successfully
            return True
        except IOError:
            logging.warn('Database file could not be written')
            return False

    def generateString(self):
        """ Generate a "sentence" with the database of known text """
        return self._accumulateWithSeed(('',))

    def generateStringWithSeed(self, seed):
        """ Generate a "sentence" with the database and a given word """
        # using str.split here means we're constructing the list in memory
        # but as the generated sentence only depends on the last word of the seed
        # I'm assuming seeds tend to be rather short.
        words = seed.split()
        if (words[-1],) not in self.db:
            # The only possible way it won't work is if the last word is not known
            raise StringContinuationImpossibleError('Could not continue string: '
                                                    + seed)
        return self._accumulateWithSeed(words)

    def _accumulateWithSeed(self, seed):
        """ Accumulate the generated sentence with a given single word as a
        seed """
        nextWord = self._nextWord(seed)
        sentence = list(seed) if seed else []
        while nextWord:
            sentence.append(nextWord)
            nextWord = self._nextWord(sentence)
        return ' '.join(sentence).strip()

    def _nextWord(self, lastwords):
        lastwords = tuple(lastwords)
        if lastwords != ('',):
            while lastwords not in self.db:
                lastwords = lastwords[1:]
                if not lastwords:
                    return ''
        probmap = self.db[lastwords]
        sample = random.random()
        # since rounding errors might make us miss out on some words
        maxprob = 0.0
        maxprobword = ""
        for candidate in probmap:
            # remember which word had the highest probability
            # this is the word we'll default to if we can't find anythin else
            if probmap[candidate] > maxprob:
                maxprob = probmap[candidate]
                maxprobword = candidate
            if sample > probmap[candidate]:
                sample -= probmap[candidate]
            else:
                return candidate
        # getting here means we haven't found a matching word. :(
        return maxprobword


text:
![Thor](http://adronhall.smugmug.com/Software/Software-Development/Pyrocumulus/i-NqSGc4m/0/S/Marvel-vs-Capcom-3-MVC3-S.jpg "Thor")
Project Thor Overview:
===
The Thor.NET Project is setup to deliver a high quality, solid user experience, and resilient user interface for Cloud Foundry (w/ Iron Foundry Extension Support) PaaS enabled systems to the Apple OS-X System. This project, to ensure a solid user experience utilizes the Cocoa Framework.

_**Please fork and contribute back.**_
If you'd like to contact the team working on Thor so we can discuss our current road map tweet us at [@ironfoundryorg](https://twitter.com/#!/ironfoundryorg) or message us via the [Iron Foundry Organization Site](http://help.ironfoundry.org/tickets/new), please feel free to contact me [Adron Hall](https://github.com/Adron/) via Twitter [@Adron](https://twitter.com/#!/adron) or e-mail me <adron.hall@tier3.com>. You can also of course message me directly via Github.

The goal behind this project is to provide a native Windows 7 user interface for administration of Cloud Foundry enabled targets, the applications and services deployed and the resources allocated to these environments.
License:
===
Copyright 2012 Iron Foundry Organization

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)

   Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Technology:
===
The technology used includes several different pieces of the .NET Framework, 3rd Party Open Source Software Libraries and custom code.

Key Libraries in the Application:

	*	.NET Framework 4.0
	*	Caliburn.Micro for MVVM Framework

Key Libraries in the Testing of the Application:

	*	NUnit
	*	NSubstitute
	*	NBuilder
	*	FluentAssertions

Patterns:
===


text:
var _ = require('lodash'),
    hbs = require('express-hbs'),
    config = require('../../config'),
    common = require('../../lib/common'),
    templates = require('../../controllers/frontend/templates'),
    escapeExpression = hbs.Utils.escapeExpression,
    _private = {},
    errorHandler = {};

/**
 * This is a bare minimum setup, which allows us to render the error page
 * It uses the {{asset}} helper, and nothing more
 */
_private.createHbsEngine = function createHbsEngine() {
    var engine = hbs.create();
    engine.registerHelper('asset', require('../../helpers/asset'));

    return engine.express4();
};

/**
 * Get an error ready to be shown the the user
 *
 * @TODO: support multiple errors within one single error, see https://github.com/TryGhost/Ghost/issues/7116#issuecomment-252231809
 */
_private.prepareError = function prepareError(err, req, res, next) {
    if (_.isArray(err)) {
        err = err[0];
    }

    if (!common.errors.utils.isIgnitionError(err)) {
        // We need a special case for 404 errors
        // @TODO look at adding this to the GhostError class
        if (err.statusCode && err.statusCode === 404) {
            err = new common.errors.NotFoundError({
                err: err
            });
        } else {
            err = new common.errors.GhostError({
                err: err,
                message: err.message,
                statusCode: err.statusCode
            });
        }
    }

    // used for express logging middleware see core/server/app.js
    req.err = err;

    // alternative for res.status();
    res.statusCode = err.statusCode;

    // never cache errors
    res.set({
        'Cache-Control': 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0'
    });

    next(err);
};

_private.JSONErrorRenderer = function JSONErrorRenderer(err, req, res, next) { // eslint-disable-line no-unused-vars
    // @TODO: jsonapi errors format (http://jsonapi.org/format/#error-objects)
    res.json({
        errors: [{
            message: err.message,
            context: err.context,
            errorType: err.errorType,
            errorDetails: err.errorDetails
        }]
    });
};

_private.ErrorFallbackMessage = function ErrorFallbackMessage(err) {
    return '
' + common.i18n.t('errors.errors.oopsErrorTemplateHasError') + '
' +
    '
' + common.i18n.t('errors.errors.encounteredError') + '
' +
    '
' + escapeExpression(err.message || err) + '
' +
    '

' + common.i18n.t('errors.errors.whilstTryingToRender') + '
' +
    err.statusCode + ' ' + '
' + escapeExpression(err.message || err) + '
';
};

_private.ThemeErrorRenderer = function ThemeErrorRenderer(err, req, res, next) {
    // If the error code is explicitly set to STATIC_FILE_NOT_FOUND,
    // Skip trying to render an HTML error, and move on to the basic error renderer
    // We do this because customised 404 templates could reference the image that's missing
    // A better long term solution might be to do this based on extension
    if (err.code === 'STATIC_FILE_NOT_FOUND') {
        return next(err);
    }

    // Renderer begin
    // Format Data
    var data = {
        message: err.message,
        // @deprecated
        code: err.statusCode,
        statusCode: err.statusCode,
        errorDetails: err.errorDetails || []
    };

    // Template
    templates.setTemplate(req, res);

    // It can be that something went wrong with the theme or otherwise loading handlebars
    // This ensures that no matter what res.render will work here
    // @TODO: split the error handler for assets, admin & theme to refactor this away
    if (_.isEmpty(req.app.engines)) {
        res._template = 'error';
        req.app.engine('hbs', _private.createHbsEngine());
        req.app.set('view engine', 'hbs');
        req.app.set('views', config.get('paths').defaultViews);
    }

    // @TODO use renderer here?!
    // Render Call - featuring an error handler for what happens if rendering fails
    res.render(res._template, data, function renderResponse(err, html) {
        if (!err) {
            return res.send(html);
        }

        // re-attach new error e.g. error template has syntax error or misusage
        req.err = err;

        // And then try to explain things to the user...
        // Cheat and output the error using handlebars escapeExpression
        return res.status(500).send(_private.ErrorFallbackMessage(err));
    });
};

_private.HTMLErrorRenderer = function HTMLErrorRender(err, req, res, next) {  // eslint-disable-line no-unused-vars
    var data = {
        message: err.message,
        statusCode: err.statusCode,
        errorDetails: err.errorDetails || []
    };

    res.render('error', data, function renderResponse(err, html) {
        if (!err) {
            return res.send(html);
        }

        // re-attach new error e.g. error template has syntax error or misusage
        req.err = err;

        // And then try to explain things to the user...
        // Cheat and output the error using handlebars escapeExpression
        return res.status(500).send(_private.ErrorFallbackMessage(err));
    });
};

_private.BasicErrorRenderer = function BasicErrorRenderer(err, req, res, next) { // eslint-disable-line no-unused-vars
    return res.send(res.statusCode + ' ' + err.message);
};

errorHandler.resourceNotFound = function resourceNotFound(req, res, next) {
    // TODO, handle unknown resources & methods differently, so that we can also produce
    // 405 Method Not Allowed
    next(new common.errors.NotFoundError({message: common.i18n.t('errors.errors.resourceNotFound')}));
};

errorHandler.pageNotFound = function pageNotFound(req, res, next) {
    next(new common.errors.NotFoundError({message: common.i18n.t('errors.errors.pageNotFound')}));
};

errorHandler.handleJSONResponse = [
    // Make sure the error can be served
    _private.prepareError,
    // Render the error using JSON format
    _private.JSONErrorRenderer
];

errorHandler.handleHTMLResponse = [
    // Make sure the error can be served
    _private.prepareError,
    // Render the error using HTML format
    _private.HTMLErrorRenderer,
    // Fall back to basic if HTML is not explicitly accepted
    _private.BasicErrorRenderer
];

errorHandler.handleThemeResponse = [
    // Make sure the error can be served
    _private.prepareError,
    // Render the error using theme template
    _private.ThemeErrorRenderer,
    // Fall back to basic if HTML is not explicitly accepted
    _private.BasicErrorRenderer
];

module.exports = errorHandler;


text:
import { Util } from './../libs/util';
import { AbstractAPIService } from "./abstract-api-service";
import { sprintf } from "../libs/sprintf";

export abstract class AbstractQueue<T> {
  protected api: AbstractAPIService;
  protected items: T[] = [];
  protected T_Class: any;
  private storageKey: string;
  private timer: any;

  protected INTERVAL = 5000;

  constructor(T_Class?: any, storageKey?: string) {
    this.storageKey = storageKey ? storageKey : this.constructor.name;
    if(T_Class) this.T_Class = T_Class;
    this.log('Instantiated');
  }

  protected abstract process(): void;

  protected filter(items: T[]): T[] { // Override
    return items;
  }

  start() {
    this.log('Started');

    this.timer = window.setInterval(() => {
      if(this.items.length != 0){
        this.log('Processing...');
        this.process();
      } else {
        this.log('Empty queue, waiting.');
      }
    }, this.INTERVAL);
  }

  stop() {
    this.log('Stopped');
    clearInterval(this.timer);
  }

  init() {
    if(window['cordova'] || window.location.href.indexOf('localhost') != -1){
      if(window['cordova']) console.log('[AbstractQueue.init] Cordova ready!');
      this.load();
      this.start();
    } else {
      setTimeout(() => {
        console.warn('[AbstractQueue.init] Cordova not ready, retrying shortly...');
        this.init();
      }, 1000);
    }
  }

  log(...params) {
      if(typeof params[0] == 'string'){
          params[0] = `[${this.constructor.name}] ` + params[0];
      }

      console.log.apply(this, params);
  }

  async load() {
    this.log('Loading');

    try{
      let queueJson = await this.api.getCacheItem(this.storageKey);

      if(queueJson){
          let queue: T[] = Util.parseJSON(queueJson);

          if(queue instanceof Array){
              if(this.T_Class){
                  let T_Class = this.T_Class;
                  this.items = queue.map(item => new T_Class(item));
              } else {
                  this.items = queue;
              }

              this.items = this.filter(this.items);

              this.log('Loaded: ', this.items);
          } else {
            this.log('Retrieved queue data is invalid: ', queueJson);
          }
      } else {
        this.log('Retrieved queue is empty.');
      }
    } catch(error){
      console.error(sprintf('%s load error: ', this.constructor.name, error));
    }
  }

  async save() {
    let queueJson = JSON.stringify(this.items);
    await this.api.setCacheItem(this.storageKey, queueJson);
  }

  find(key, value): T {
    for(let item of this.items){
      if(item[key] === value){
        return item;
      }
    }

    return null;
  }

  findAll(key, value): T[] {
    let matches: T[] = [];

    for(let item of this.items){
      if(item[key] === value){
        matches.push(item);
      }
    }

    return matches;
  }

  getItems(byRef: boolean = false): T[] {
      return byRef ? this.items : this.items.slice();
  }

  getCount(): number {
    return this.items.length;
  }

  push(item: T) {
    this.items.push(item);
    this.log('Pushed item: ', item);
    this.save();
  }

  peek(): T {
      return this.items.length != 0 ? this.items[0] : null;
  }

  pop(): T {
      if(this.items.length == 0) return null;
      let item = this.items.shift();
      this.log('Popped item: ', item);
      this.save();
      return item;
  }

  popToBack(): T {
    if(this.items.length == 0) return null;
    let item = this.items.shift();
    this.items.push(item);
    this.log('Popped item to back: ', item);
    this.save();
    return item;
  }
}


text:
package com.mvp4g.example.client.main;

import com.mvp4g.client.event.EventFilter;

public class MainEventFilter implements EventFilter<MainEventBus> {

	public boolean filterEvent( String eventType, Object[] params, MainEventBus eventBus )	{
		eventBus.setFilteringEnabledForNextOne( false );
		eventBus.displayMessage( "Main Event " + eventType + " has been filtered." );
		return false;
	}
}


text:
import { ERROR, Toast } from '@/modules/toast/handler/handlerToast';
import { toHex } from 'web3-utils';
import wallets from '@/modules/access-wallet/common/walletTypes';

/**
 * Attempts to switch metamask network to current mew network.
 * Informs user of pending or unknown networks.
 */

/**
 * @param {Number} chainID - Chain Id for network
 * @param {String} walletType - Wallet type
 * @param {Boolean} options.toast - Show toast
 * @return {Boolean} returns false if networks do not match, true if they do, or if its not a web3 wallet
 */
export default async (chainID, walletType, options = { toast: true }) => {
  const { ethereum } = window;
  if (
    walletType === wallets.WEB3_WALLET &&
    ethereum.isMetaMask &&
    !ethereum.hasOwnProperty('isMewWallet') &&
    !ethereum.hasOwnProperty('isTrust')
  ) {
    try {
      if (chainID) {
        const data = { chainId: toHex(chainID) };
        await ethereum.request({
          method: 'wallet_switchEthereumChain',
          params: [data]
        });
        return true;
      }
      return false;
    } catch (er) {
      const { message } = er;
      let toastMsg = ' ';
      let toastLink = {};
      if (message && options.toast) {
        if (message.includes('pending')) {
          toastMsg =
            'There is a pending request to MetaMask, make your selection before continuing';
        } else if (message.includes('adding')) {
          toastLink = {
            title:
              "It seems like you don't have this network set up in MetaMask. Please go here to add the network.",
            url: 'https://chainlist.org/'
          };
        } else if (message.includes('rejected')) return false;
        else if (message.includes("hasn't been added")) {
          toastLink = {
            title:
              "It seems like you don't have this network set up in your wallet. Please go here to add the network.",
            url: 'https://chainlist.org/'
          };
        } else {
          toastMsg = 'There was a problem processing your request to MetaMask';
        }
        setTimeout(() => {
          Toast(toastMsg, toastLink, ERROR, 5000);
        }, 100);
      }
      return false;
    }
  }
  return true;
};


text:
<!doctype html>

    <meta charset=utf-8>
    <title>Test cookie name parsing</title>
    <meta name=help href="https://tools.ietf.org/html/rfc6265#section-5.2">
    <meta name="timeout" content="long">


text:
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')

describe "ActiverecordRecursiveTreeScopes" do
  describe 'has_ancestors' do
    context 'given a scope name that conflicts' do
      it do
        lambda{ Employee.has_ancestors :ancestors }.should raise_error(ArgumentError, "Employee already responds to ancestors. Please pick another name for has_ancestors scope.")
      end
    end
  end

  describe 'has_descendants' do
    context 'given a scope name that conflicts' do
      it do
        lambda{ Employee.has_descendants :descendants }.should raise_error(ArgumentError, "Employee already responds to descendants. Please pick another name for has_descendants scope.")
      end
    end
  end

  describe 'simple tree' do
    let!(:alonso)  { Employee.create! name: 'Alonso'                    }
    let!(:alfred)  { Employee.create! name: 'Alfred'                    }
    let!(:barry)   { Employee.create! name: 'Barry',   manager: alfred  }
    let!(:bob)     { Employee.create! name: 'Bob',     manager: alfred  }
    let!(:charles) { Employee.create! name: 'Charles', manager: barry   }
    let!(:cameron) { Employee.create! name: 'Cameron', manager: barry   }
    let!(:carl)    { Employee.create! name: 'Carl',    manager: barry   }
    let!(:dave)    { Employee.create! name: 'Dave',    manager: carl    }
    let!(:daryl)   { Employee.create! name: 'Daryl',   manager: charles }
    let!(:dick)    { Employee.create! name: 'Dick',    manager: charles }
    let!(:edward)  { Employee.create! name: 'Edward',  manager: dick    }
    let!(:frank)   { Employee.create! name: 'Frank',   manager: edward  }

    describe 'chaining' do
      describe 'ancestors' do
        it do
          frank.managers.where(name: 'Barry').should == [ barry ]
        end
      end

      describe 'descendants' do
        it do
          barry.managed.where("name LIKE ?", 'D%').should == [ dave, daryl, dick ]
        end
      end
    end

    describe 'Alonso' do
      subject { alonso }
      its(:manager) { should be_nil }
      its(:directly_managed) { should == [] }
      its(:managers) { should == [] }
      its(:managed) { should == [] }
    end

    describe 'Alfred' do
      subject { alfred }
      its(:manager) { should be_nil }
      its(:directly_managed) { should == [ barry, bob ] }
      its(:managers) { should == [] }
      its(:managed) { should == [ barry, bob, charles, cameron, carl, dave, daryl, dick, edward, frank ] }
    end

    describe 'Barry' do
      subject { barry }
      its(:manager) { should == alfred }
      its(:directly_managed) { should == [ charles, cameron, carl ] }
      its(:managers) { should == [ alfred ] }
      its(:managed) { should == [ charles, cameron, carl, dave, daryl, dick, edward, frank ] }
    end

    describe 'Bob' do
      subject { bob }
      its(:manager) { should == alfred }
      its(:directly_managed) { should == [] }
      its(:managers) { should == [ alfred ] }
      its(:managed) { should == [] }
    end

    describe 'Charles' do
      subject { charles }
      its(:manager) { should == barry }
      its(:directly_managed) { should == [ daryl, dick ] }
      its(:managers) { should == [ alfred, barry ] }
      its(:managed) { should == [ daryl, dick, edward, frank ] }
    end

    describe 'Cameron' do
      subject { cameron }
      its(:manager) { should == barry }
      its(:directly_managed) { should == [] }
      its(:managers) { should == [ alfred, barry ] }
      its(:managed) { should == [] }
    end

    describe 'Carl' do
      subject { carl }
      its(:manager) { should == barry }
      its(:directly_managed) { should == [ dave ] }
      its(:managers) { should == [ alfred, barry ] }
      its(:managed) { should == [ dave ] }
    end

    describe 'Dave' do
      subject { dave }
      its(:manager) { should == carl }
      its(:directly_managed) { should == [] }
      its(:managers) { should == [ alfred, barry, carl ] }
      its(:managed) { should == [] }
    end

    describe 'Daryl' do
      subject { daryl }
      its(:manager) { should == charles }
      its(:directly_managed) { should == [] }
      its(:managers) { should == [ alfred, barry, charles ] }
      its(:managed) { should == [] }
    end

    describe 'Dick' do
      subject { dick }
      its(:manager) { should == charles }
      its(:directly_managed) { should == [ edward ] }
      its(:managers) { should == [ alfred, barry, charles ] }
      its(:managed) { should == [ edward, frank ] }
    end

    describe 'Edward' do
      subject { edward }
      its(:manager) { should == dick }
      its(:directly_managed) { should == [ frank ] }
      its(:managers) { should == [ alfred, barry, charles, dick ] }
      its(:managed) { should == [ frank ] }
    end

    describe 'Frank' do
      subject { frank }
      its(:manager) { should == edward }
      its(:directly_managed) { should == [] }
      its(:managers) { should == [ alfred, barry, charles, dick, edward ] }
      its(:managed) { should == [] }
    end
  end

  describe 'multiple key tree' do
    let!(:george)  { Person.create! name: 'George' }
    let!(:hazel)   { Person.create! name: 'Hazel' }
    let!(:bill)    { Person.create! name: 'Bill', father: george, mother: hazel }
    let!(:william) { Person.create! name: 'William' }
    let!(:sharlyn) { Person.create! name: 'Sharlyn' }
    let!(:tamara)  { Person.create! name: 'Tamara', father: william, mother: sharlyn }
    let!(:john)    { Person.create! name: 'John', father: bill, mother: tamara }
    let!(:mark)    { Person.create! name: 'Mark', father: bill, mother: tamara }
    let!(:buster)  { Person.create! name: 'Buster', father: john }

    describe 'George' do
      subject { george }
      its(:mother) { should be_nil }
      its(:father) { should be_nil }
      its(:progenitors) { should == [] }
      its(:progeny) { should == [ bill, john, mark, buster ] }
    end

    describe 'Hazel' do
      subject { hazel }
      its(:mother) { should be_nil }
      its(:father) { should be_nil }
      its(:progenitors) { should == [] }
      its(:progeny) { should == [ bill, john, mark, buster ] }
    end

    describe 'William' do
      subject { william }
      its(:mother) { should be_nil }
      its(:father) { should be_nil }
      its(:progenitors) { should == [] }
      its(:progeny) { should == [ tamara, john, mark, buster ] }
    end

    describe 'Sharlyn' do
      subject { sharlyn }
      its(:mother) { should be_nil }
      its(:father) { should be_nil }
      its(:progenitors) { should == [] }
      its(:progeny) { should == [ tamara, john, mark, buster ] }
    end

    describe 'Bill' do
      subject { bill }
      its(:mother) { should == hazel }
      its(:father) { should == george }
      its(:progenitors) { should == [ george, hazel ] }
      its(:progeny) { should == [ john, mark, buster ] }
    end

    describe 'Tamara' do
      subject { tamara }
      its(:mother) { should == sharlyn }
      its(:father) { should == william }
      its(:progenitors) { should == [ william, sharlyn ] }
      its(:progeny) { should == [ john, mark, buster ] }
    end

    describe 'John' do
      subject { john }
      its(:mother) { should == tamara }
      its(:father) { should == bill }
      its(:progenitors) { should == [ george, hazel, bill, william, sharlyn, tamara ] }
      its(:progeny) { should == [ buster ] }
    end

    describe 'Mark' do
      subject { mark }
      its(:mother) { should == tamara }
      its(:father) { should == bill }
      its(:progenitors) { should == [ george, hazel, bill, william, sharlyn, tamara ] }
      its(:progeny) { should == [] }
    end

    describe 'Buster' do
      subject { buster }
      its(:mother) { should be_nil }
      its(:father) { should == john }
      its(:progenitors) { should == [ george, hazel, bill, william, sharlyn, tamara, john ] }
      its(:progeny) { should == [] }
    end
  end
end


text:
require "rspec/roles/version"
require "rspec/roles/implements_role"
require "rspec/roles/role_set"

module RSpec
  module Roles
    def self.define(&block)
      role_set.apply(&block)
    end

    def self.roles
      role_set.to_hash
    end

    private

    def self.role_set
      RoleSet.instance
    end
  end
end


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

namespace CompareCloudware.Domain.Models
{
    #region FreeTrialPeriod
    public class FreeTrialPeriod
    {
        public virtual int FreeTrialPeriodID { get; set; }
        public virtual string FreeTrialPeriodName { get; set; }
        public virtual Status FreeTrialPeriodStatus { get; set; }
        public virtual byte[] RowVersion { get; set; }
        public virtual List<CloudApplication> CloudApplications { get; set; }
    }
    #endregion
}


text:
package ch.ethz.topobench.graph.print;

import ch.ethz.topobench.graph.utility.BoundsCalculator;
import ch.ethz.topobench.graph.Graph;

import java.io.BufferedWriter;
import java.io.FileWriter;

public class PrinterPathLengths {

    private final int numNodes;
    private final Graph graph;
    private final int shortestPathLen[][];

    public PrinterPathLengths(Graph graph) {
        this.graph = graph;
        this.numNodes = graph.getNumNodes();
        this.shortestPathLen = graph.getShortestPathLen();
    }

    public void print(String filePath) {

        try {

            // Calculate paths
            graph.calculateShortestPaths();

            // Open stream
            FileWriter fileStream = new FileWriter(filePath);
            BufferedWriter out = new BufferedWriter(fileStream);

            // Calculate
            double sum = 0.0;
            for (int i = 0; i < numNodes; i++) {
                for (int j = 0; j < numNodes; j++) {
                    sum += shortestPathLen[i][j];
                }
            }

            // Show all graph statistics
            out.write("GENERAL STATISTICS:");
            out.write("\nTotal node pairs: " + (numNodes * numNodes));
            out.write("\nAverage path length for node pairs: " + (sum / (numNodes * numNodes)));

            // For regular graph online with uniform weights
            int d = graph.getAdjacencyList()[0].size();
            int w = graph.getNodeWeight(0);
            out.write("\n\nUNDER ASSUMPTION OF REGULAR GRAPH with n=" + numNodes + ", d=" + d + ":");
            out.write("\nMinimum bound on average path length for node pairs: " + BoundsCalculator.avgPathLengthMinBound(numNodes, d));
            out.write("\nMaximum A2A total throughput per node: " + BoundsCalculator.maxThroughputPerNode(numNodes, d));
            out.write("\nMaximum A2A total throughput per server: " + BoundsCalculator.maxThroughputPerServer(numNodes, d, w));

            // Print path lengths
            out.write("\n\nPATH LENGTH FOR NODE PAIRS:\n");
            for (int i = 0; i < numNodes; i++) {
                for (int j = 0; j < numNodes; j++) {
                    out.write(i + " " + j + " " + shortestPathLen[i][j] + "\n");
                }
            }

            // Close stream
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}


text:
'use strict';

exports.start = function () {

};


text:
	<form class="toggle-component-form" name="$ctrl.form" novalidate>
	    {{$ctrl.offLabel}}

			<input
				class="toggle-component-input"
				type="checkbox"
				name="checkbox"
				ng-model="$ctrl.state"
				ng-change="$ctrl.onChange($event)" />

	    {{$ctrl.onLabel}}
	</form>


text:
namespace network {

using net::kSimpleGET_Transaction;
using net::MockHttpRequest;
using net::MockNetworkLayer;
using net::MockTransaction;
using net::TEST_MODE_SYNC_NET_START;

const char kUploadData[] = "upload_data";
int64_t kUploadIdentifier = 17;

class TestCallback {
 public:
  TestCallback() : run_count_(0), value_(0) {}
  void Run(int value) {
    run_count_++;
    value_ = value;
  }
  int run_count() { return run_count_; }
  int value() { return value_; }

 private:
  int run_count_;
  int value_;
};

class ThrottlingControllerTestHelper {
 public:
  explicit ThrottlingControllerTestHelper(
      MockTransaction mock_transaction = kSimpleGET_Transaction)
      : completion_callback_(base::BindRepeating(&TestCallback::Run,
                                                 base::Unretained(&callback_))),
        mock_transaction_(mock_transaction),
        buffer_(base::MakeRefCounted<net::IOBuffer>(64)),
        net_log_with_source_(
            net::NetLogWithSource::Make(net::NetLog::Get(),
                                        net::NetLogSourceType::URL_REQUEST)),
        profile_id_(base::UnguessableToken::Create()) {
    mock_transaction_.test_mode = TEST_MODE_SYNC_NET_START;
    mock_transaction_.url = "http://dot.com";
    AddMockTransaction(&mock_transaction_);

    std::unique_ptr<net::HttpTransaction> network_transaction;
    network_layer_.CreateTransaction(net::DEFAULT_PRIORITY,
                                     &network_transaction);
    transaction_ = std::make_unique<ThrottlingNetworkTransaction>(
        std::move(network_transaction));
  }

  void SetNetworkState(bool offline, double download, double upload) {
    std::unique_ptr<NetworkConditions> conditions(
        new NetworkConditions(offline, 0, download, upload));
    ThrottlingController::SetConditions(profile_id_, std::move(conditions));
  }

  void SetNetworkState(const base::UnguessableToken& id, bool offline) {
    std::unique_ptr<NetworkConditions> conditions(
        new NetworkConditions(offline));
    ThrottlingController::SetConditions(id, std::move(conditions));
  }

  int Start(bool with_upload) {
    request_ = std::make_unique<MockHttpRequest>(mock_transaction_);
    throttling_token_ = ScopedThrottlingToken::MaybeCreate(
        net_log_with_source_.source().id, profile_id_);

    if (with_upload) {
      upload_data_stream_ =
          std::make_unique<net::ChunkedUploadDataStream>(kUploadIdentifier);
      upload_data_stream_->AppendData(kUploadData, std::size(kUploadData),
                                      true);
      request_->upload_data_stream = upload_data_stream_.get();
    }

    int rv = transaction_->Start(request_.get(), completion_callback_,
                                 net_log_with_source_);
    EXPECT_EQ(with_upload, !!transaction_->custom_upload_data_stream_);
    return rv;
  }

  int Read(net::IOBuffer* buffer, int buffer_size) {
    return transaction_->Read(buffer, buffer_size, completion_callback_);
  }

  int Read() { return Read(buffer_.get(), 64); }

  bool ShouldFail() {
    if (transaction_->interceptor_)
      return transaction_->interceptor_->IsOffline();
    ThrottlingNetworkInterceptor* interceptor =
        ThrottlingController::GetInterceptor(net_log_with_source_.source().id);
    EXPECT_TRUE(!!interceptor);
    return interceptor->IsOffline();
  }

  bool HasStarted() { return !!transaction_->request_; }

  bool HasFailed() { return transaction_->failed_; }

  void CancelTransaction() { transaction_.reset(); }

  int ReadUploadData() {
    EXPECT_EQ(net::OK, transaction_->custom_upload_data_stream_->Init(
                           completion_callback_, net::NetLogWithSource()));
    return transaction_->custom_upload_data_stream_->Read(buffer_.get(), 64,
                                                          completion_callback_);
  }

  ~ThrottlingControllerTestHelper() {
    RemoveMockTransaction(&mock_transaction_);
  }

  TestCallback* callback() { return &callback_; }
  ThrottlingNetworkTransaction* transaction() { return transaction_.get(); }

  void FastForwardUntilNoTasksRemain() {
    task_environment_.FastForwardUntilNoTasksRemain();
  }

 private:
  base::test::SingleThreadTaskEnvironment task_environment_{
      base::test::SingleThreadTaskEnvironment::TimeSource::MOCK_TIME};
  MockNetworkLayer network_layer_;
  TestCallback callback_;
  net::CompletionRepeatingCallback completion_callback_;
  MockTransaction mock_transaction_;
  std::unique_ptr<ThrottlingNetworkTransaction> transaction_;
  scoped_refptr<net::IOBuffer> buffer_;
  std::unique_ptr<net::ChunkedUploadDataStream> upload_data_stream_;
  std::unique_ptr<MockHttpRequest> request_;
  std::unique_ptr<network::ScopedThrottlingToken> throttling_token_;
  const net::NetLogWithSource net_log_with_source_;
  const base::UnguessableToken profile_id_;
};

TEST(ThrottlingControllerTest, SingleDisableEnable) {
  ThrottlingControllerTestHelper helper;
  helper.SetNetworkState(false, 0, 0);
  helper.Start(false);

  EXPECT_FALSE(helper.ShouldFail());
  helper.SetNetworkState(true, 0, 0);
  EXPECT_TRUE(helper.ShouldFail());
  helper.SetNetworkState(false, 0, 0);
  EXPECT_FALSE(helper.ShouldFail());

  base::RunLoop().RunUntilIdle();
}

TEST(ThrottlingControllerTest, InterceptorIsolation) {
  const base::UnguessableToken another_profile_id =
      base::UnguessableToken::Create();
  ThrottlingControllerTestHelper helper;
  helper.SetNetworkState(false, 0, 0);
  helper.Start(false);

  EXPECT_FALSE(helper.ShouldFail());
  helper.SetNetworkState(another_profile_id, true);
  EXPECT_FALSE(helper.ShouldFail());
  helper.SetNetworkState(true, 0, 0);
  EXPECT_TRUE(helper.ShouldFail());

  helper.SetNetworkState(another_profile_id, false);
  helper.SetNetworkState(false, 0, 0);
  base::RunLoop().RunUntilIdle();
}

TEST(ThrottlingControllerTest, FailOnStart) {
  ThrottlingControllerTestHelper helper;
  helper.SetNetworkState(true, 0, 0);

  int rv = helper.Start(false);
  EXPECT_EQ(rv, net::ERR_INTERNET_DISCONNECTED);

  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(helper.callback()->run_count(), 0);
}

TEST(ThrottlingControllerTest, FailRunningTransaction) {
  ThrottlingControllerTestHelper helper;
  helper.SetNetworkState(false, 0, 0);
  TestCallback* callback = helper.callback();

  int rv = helper.Start(false);
  EXPECT_EQ(rv, net::OK);

  rv = helper.Read();
  EXPECT_EQ(rv, net::ERR_IO_PENDING);
  EXPECT_EQ(callback->run_count(), 0);

  helper.SetNetworkState(true, 0, 0);
  EXPECT_EQ(callback->run_count(), 0);

  // Wait until HttpTrancation completes reading and invokes callback.
  // ThrottlingNetworkTransaction should report error instead.
  helper.FastForwardUntilNoTasksRemain();
  EXPECT_EQ(callback->run_count(), 1);
  EXPECT_EQ(callback->value(), net::ERR_INTERNET_DISCONNECTED);

  // Check that transaction is not failed second time.
  helper.SetNetworkState(false, 0, 0);
  helper.SetNetworkState(true, 0, 0);
  EXPECT_EQ(callback->run_count(), 1);
}

TEST(ThrottlingControllerTest, ReadAfterFail) {
  ThrottlingControllerTestHelper helper;
  helper.SetNetworkState(false, 0, 0);

  int rv = helper.Start(false);
  EXPECT_EQ(rv, net::OK);
  EXPECT_TRUE(helper.HasStarted());

  helper.SetNetworkState(true, 0, 0);
  // Not failed yet, as no IO was initiated.
  EXPECT_FALSE(helper.HasFailed());

  rv = helper.Read();
  // Fails on first IO.
  EXPECT_EQ(rv, net::ERR_INTERNET_DISCONNECTED);

  // Check that callback is never invoked.
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(helper.callback()->run_count(), 0);
}

TEST(ThrottlingControllerTest, CancelTransaction) {
  ThrottlingControllerTestHelper helper;
  helper.SetNetworkState(false, 0, 0);

  int rv = helper.Start(false);
  EXPECT_EQ(rv, net::OK);
  EXPECT_TRUE(helper.HasStarted());
  helper.CancelTransaction();

  // Should not crash.
  helper.SetNetworkState(true, 0, 0);
  helper.SetNetworkState(false, 0, 0);
  base::RunLoop().RunUntilIdle();
}

TEST(ThrottlingControllerTest, CancelFailedTransaction) {
  ThrottlingControllerTestHelper helper;
  helper.SetNetworkState(true, 0, 0);

  int rv = helper.Start(false);
  EXPECT_EQ(rv, net::ERR_INTERNET_DISCONNECTED);
  EXPECT_TRUE(helper.HasStarted());
  helper.CancelTransaction();

  // Should not crash.
  helper.SetNetworkState(true, 0, 0);
  helper.SetNetworkState(false, 0, 0);
  base::RunLoop().RunUntilIdle();
}

TEST(ThrottlingControllerTest, UploadDoesNotFail) {
  ThrottlingControllerTestHelper helper;
  helper.SetNetworkState(true, 0, 0);
  int rv = helper.Start(true);
  EXPECT_EQ(rv, net::ERR_INTERNET_DISCONNECTED);
  rv = helper.ReadUploadData();
  EXPECT_EQ(rv, static_cast<int>(std::size(kUploadData)));
}

TEST(ThrottlingControllerTest, DownloadOnly) {
  ThrottlingControllerTestHelper helper;
  TestCallback* callback = helper.callback();

  helper.SetNetworkState(false, 10000000, 0);
  int rv = helper.Start(false);
  EXPECT_EQ(rv, net::ERR_IO_PENDING);
  helper.FastForwardUntilNoTasksRemain();
  EXPECT_EQ(callback->run_count(), 1);
  EXPECT_GE(callback->value(), net::OK);

  rv = helper.Read();
  EXPECT_EQ(rv, net::ERR_IO_PENDING);
  EXPECT_EQ(callback->run_count(), 1);
  helper.FastForwardUntilNoTasksRemain();
  EXPECT_EQ(callback->run_count(), 2);
  EXPECT_GE(callback->value(), net::OK);
}

TEST(ThrottlingControllerTest, UploadOnly) {
  ThrottlingControllerTestHelper helper;
  TestCallback* callback = helper.callback();

  helper.SetNetworkState(false, 0, 1000000);
  int rv = helper.Start(true);
  EXPECT_EQ(rv, net::OK);
  helper.FastForwardUntilNoTasksRemain();
  EXPECT_EQ(callback->run_count(), 0);

  rv = helper.Read();
  EXPECT_EQ(rv, net::ERR_IO_PENDING);
  EXPECT_EQ(callback->run_count(), 0);
  helper.FastForwardUntilNoTasksRemain();
  EXPECT_EQ(callback->run_count(), 1);
  EXPECT_GE(callback->value(), net::OK);

  rv = helper.ReadUploadData();
  EXPECT_EQ(rv, net::ERR_IO_PENDING);
  EXPECT_EQ(callback->run_count(), 1);
  helper.FastForwardUntilNoTasksRemain();
  EXPECT_EQ(callback->run_count(), 2);
  EXPECT_EQ(callback->value(), static_cast<int>(std::size(kUploadData)));
}

TEST(ThrottlingControllerTest, DownloadBufferSizeIsNotModifiedIfNotThrottled) {
  MockTransaction mock_transaction = kSimpleGET_Transaction;
  const int kLargeDataSize = 1024 * 1024;
  std::string large_data(kLargeDataSize, 'x');
  mock_transaction.data = large_data.c_str();
  ThrottlingControllerTestHelper helper(mock_transaction);
  TestCallback* callback = helper.callback();

  helper.SetNetworkState(false, 0, 0);
  int rv = helper.Start(false);
  EXPECT_EQ(rv, net::OK);

  auto large_data_buffer = base::MakeRefCounted<net::IOBuffer>(kLargeDataSize);
  rv = helper.Read(large_data_buffer.get(), kLargeDataSize);
  EXPECT_EQ(rv, net::ERR_IO_PENDING);
  helper.FastForwardUntilNoTasksRemain();
  EXPECT_EQ(callback->run_count(), 1);
  EXPECT_EQ(callback->value(), kLargeDataSize);
}

TEST(ThrottlingControllerTest, DownloadIsStreamed) {
  MockTransaction mock_transaction = kSimpleGET_Transaction;
  const int kLargeDataSize = 1024 * 1024;
  std::string large_data(kLargeDataSize, 'x');
  mock_transaction.data = large_data.c_str();
  ThrottlingControllerTestHelper helper(mock_transaction);
  TestCallback* callback = helper.callback();

  helper.SetNetworkState(false, 1, 0);
  int rv = helper.Start(false);
  EXPECT_EQ(rv, net::ERR_IO_PENDING);
  helper.FastForwardUntilNoTasksRemain();
  EXPECT_EQ(callback->run_count(), 1);
  EXPECT_GE(callback->value(), net::OK);

  auto large_data_buffer = base::MakeRefCounted<net::IOBuffer>(kLargeDataSize);
  helper.Read(large_data_buffer.get(), kLargeDataSize);
  EXPECT_EQ(rv, net::ERR_IO_PENDING);
  EXPECT_EQ(callback->run_count(), 1);
  helper.FastForwardUntilNoTasksRemain();
  EXPECT_EQ(callback->run_count(), 2);
  EXPECT_GT(callback->value(), net::OK);
  EXPECT_LT(callback->value(), kLargeDataSize);
}

}  // namespace network


text:
package org.more.webui.render.select;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.Map;
import org.more.util.BeanUtils;
import org.more.webui.components.UISelectInput;
import org.more.webui.context.ViewContext;
import org.more.webui.tag.TemplateBody;
import freemarker.template.TemplateException;
/**
 * 将选择输入组建渲染成一组radio框。
 *
客户端模型:UIRadioSelectOnlyInput(UIRadioSelectOnlyInput.js)
 * @version : 2012-5-18
 * @author 赵永春 (zyc@byshell.org)
 */
public class RadioOnlySelectInputRender<T extends UISelectInput> extends AbstractSelectInputRender<T> {
    @Override
    public String getClientType() {
        return "UIRadioOnlySelectInput";
    }
    @Override
    public String tagName(ViewContext viewContext, T component) {
        return "ul";
    }
    @Override
    public Map<String, Object> tagAttributes(ViewContext viewContext, T component) {
        Map<String, Object> attr = super.tagAttributes(viewContext, component);
        attr.put("renderType", this.getRenderType(component).name());
        return attr;
    }
    @Override
    public void render(ViewContext viewContext, T component, TemplateBody arg3, Writer writer) throws IOException, TemplateException {
        List<?> listData = component.getValueList();
        String keyField = component.getKeyField();
        String varField = component.getVarField();
        Object[] selectVar = component.getSelectValues();
        int index = 0;
        if (listData != null)
            for (Object obj : listData) {
                if (obj == null)
                    continue;
                Object keyValue = null;
                Object varValue = null;
                if (obj instanceof Map) {
                    Map mapData = (Map) obj;
                    keyValue = mapData.get(keyField);
                    varValue = mapData.get(varField);
                } else {
                    keyValue = BeanUtils.readPropertyOrField(obj, keyField);
                    varValue = BeanUtils.readPropertyOrField(obj, varField);
                }
                //输出
                String checkedStr = "no";
                String checkedMark = "";
                String titleMark = (this.getRenderType(component) == RenderType.onlyTitle) ? " style='display:none;'" : "";
                for (Object selItem : selectVar)
                    if (keyValue != null && keyValue.equals(selItem) == true) {
                        checkedStr = "";
                        checkedMark = "checked='checked'";
                    } else {
                        checkedStr = "no";
                        checkedMark = "";
                    }
                writer.write("
");
                writer.write("  ");
                writer.write("    ");
                writer.write("      ");
                writer.write("      <input type='radio' forComID='" + component.getComponentID() + "' name='" + component.getName() + "' value='" + keyValue + "' oriData='' " + checkedMark + " " + titleMark + "/>");
                writer.write("      " + varValue + "");
                writer.write("    ");
                writer.write("  ");
                writer.write("
 ");
                index++;
            }
    }
    /*----------------------------------------------------------------*/
    public static enum RenderType {
        /**选择框前面输出选项文本(有选择框)。*/
        normal,
        /**选择框只包含文本(不带有选择框)。*/
        onlyTitle,
    }
    protected RenderType getRenderType(T component) {
        return RenderType.normal;
    }
}


text:
/*
 * 作者:钟勋 (e-mail:zhongxunking@163.com)
 */

/*
 * 修订记录:
 * @author 钟勋 2019-09-01 20:03 创建
 */
package org.antframework.configcenter.biz.service;

import lombok.AllArgsConstructor;
import org.antframework.common.util.facade.BizException;
import org.antframework.common.util.facade.CommonResultCode;
import org.antframework.common.util.facade.FacadeUtils;
import org.antframework.common.util.facade.Status;
import org.antframework.configcenter.biz.util.Apps;
import org.antframework.configcenter.biz.util.Profiles;
import org.antframework.configcenter.dal.dao.BranchRuleDao;
import org.antframework.configcenter.dal.entity.BranchRule;
import org.antframework.configcenter.facade.info.AppInfo;
import org.antframework.configcenter.facade.info.BranchRuleInfo;
import org.antframework.configcenter.facade.info.ProfileInfo;
import org.antframework.configcenter.facade.order.FindBranchRulesOrder;
import org.antframework.configcenter.facade.result.FindBranchRulesResult;
import org.bekit.service.annotation.service.Service;
import org.bekit.service.annotation.service.ServiceBefore;
import org.bekit.service.annotation.service.ServiceExecute;
import org.bekit.service.engine.ServiceContext;
import org.springframework.core.convert.converter.Converter;

import java.util.List;

/**
 * 查找分支规则
 */
@Service
@AllArgsConstructor
public class FindBranchRulesService {
    // 转换器
    private static final Converter<BranchRule, BranchRuleInfo> CONVERTER = new FacadeUtils.DefaultConverter<>(BranchRuleInfo.class);

    // 分支规则dao
    private final BranchRuleDao branchRuleDao;

    @ServiceBefore
    public void before(ServiceContext<FindBranchRulesOrder, FindBranchRulesResult> context) {
        FindBranchRulesOrder order = context.getOrder();
        // 校验
        AppInfo app = Apps.findApp(order.getAppId());
        if (app == null) {
            throw new BizException(Status.FAIL, CommonResultCode.INVALID_PARAMETER.getCode(), String.format("应用[%s]不存在", order.getAppId()));
        }
        ProfileInfo profile = Profiles.findProfile(order.getProfileId());
        if (profile == null) {
            throw new BizException(Status.FAIL, CommonResultCode.INVALID_PARAMETER.getCode(), String.format("环境[%s]不存在", order.getProfileId()));
        }
    }

    @ServiceExecute
    public void execute(ServiceContext<FindBranchRulesOrder, FindBranchRulesResult> context) {
        FindBranchRulesOrder order = context.getOrder();
        FindBranchRulesResult result = context.getResult();
        // 查找分支规则
        List<BranchRule> branchRules = branchRuleDao.findByAppIdAndProfileIdOrderByPriorityAsc(order.getAppId(), order.getProfileId());
        branchRules.stream()
                .map(CONVERTER::convert)
                .forEach(result::addBranchRule);
    }
}


text:
package org.orekit.propagation;

import org.hipparchus.geometry.euclidean.threed.Vector3D;
import org.hipparchus.ode.nonstiff.AdaptiveStepsizeIntegrator;
import org.hipparchus.ode.nonstiff.DormandPrince853Integrator;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.orekit.Utils;
import org.orekit.forces.gravity.potential.GravityFieldFactory;
import org.orekit.forces.gravity.potential.SHMFormatReader;
import org.orekit.frames.FramesFactory;
import org.orekit.orbits.EquinoctialOrbit;
import org.orekit.orbits.Orbit;
import org.orekit.orbits.OrbitType;
import org.orekit.propagation.analytical.BrouwerLyddanePropagator;
import org.orekit.propagation.numerical.NumericalPropagator;
import org.orekit.propagation.semianalytical.dsst.DSSTPropagator;
import org.orekit.time.AbsoluteDate;
import org.orekit.utils.PVCoordinates;

public class AdditionalStateProviderTest {

    private double                     mu;
    private AbsoluteDate               initDate;
    private SpacecraftState            initialState;
    private AdaptiveStepsizeIntegrator integrator;

    @BeforeEach
    public void setUp() {
        Utils.setDataRoot("regular-data:potential/shm-format");
        GravityFieldFactory.addPotentialCoefficientsReader(new SHMFormatReader("^eigen_cg03c_coef$", false));
        mu  = GravityFieldFactory.getUnnormalizedProvider(0, 0).getMu();
        final Vector3D position = new Vector3D(7.0e6, 1.0e6, 4.0e6);
        final Vector3D velocity = new Vector3D(-500.0, 8000.0, 1000.0);
        initDate = AbsoluteDate.J2000_EPOCH;
        final Orbit orbit = new EquinoctialOrbit(new PVCoordinates(position,  velocity),
                                                 FramesFactory.getEME2000(), initDate, mu);
        initialState = new SpacecraftState(orbit);
        double[][] tolerance = NumericalPropagator.tolerances(0.001, orbit, OrbitType.EQUINOCTIAL);
        integrator = new DormandPrince853Integrator(0.001, 200, tolerance[0], tolerance[1]);
        integrator.setInitialStepSize(60);
    }

    @Test
    public void testIssue900Numerical() {

        // Create propagator
        final NumericalPropagator propagator = new NumericalPropagator(integrator);
        propagator.setInitialState(initialState);

        // Create additional state provider
        final String name          = "init";
        final TimeDifferenceProvider provider = new TimeDifferenceProvider(name);
        Assertions.assertFalse(provider.wasCalled());

        // Add the provider to the propagator
        propagator.addAdditionalStateProvider(provider);

        // Propagate
        final double dt = 600.0;
        final SpacecraftState propagated = propagator.propagate(initDate.shiftedBy(dt));

        // Verify
        Assertions.assertTrue(provider.wasCalled());
        Assertions.assertEquals(dt, propagated.getAdditionalState(name)[0], 0.01);

    }

    @Test
    public void testIssue900Dsst() {

        // Initialize propagator
        final DSSTPropagator propagator = new DSSTPropagator(integrator);
        propagator.setInitialState(initialState, PropagationType.MEAN);

        // Create additional state provider
        final String name          = "init";
        final TimeDifferenceProvider provider = new TimeDifferenceProvider(name);
        Assertions.assertFalse(provider.wasCalled());

        // Add the provider to the propagator
        propagator.addAdditionalStateProvider(provider);

        // Propagate
        final double dt = 600.0;
        final SpacecraftState propagated = propagator.propagate(initialState.getDate().shiftedBy(dt));

        // Verify
        Assertions.assertTrue(provider.wasCalled());
        Assertions.assertEquals(dt, propagated.getAdditionalState(name)[0], 0.01);

    }

    @Test
    public void testIssue900BrouwerLyddane() {

        // Initialize propagator
        BrouwerLyddanePropagator propagator = new BrouwerLyddanePropagator(initialState.getOrbit(), Utils.defaultLaw(),
                                                                           GravityFieldFactory.getUnnormalizedProvider(5, 0), BrouwerLyddanePropagator.M2);

        // Create additional state provider
        final String name          = "init";
        final TimeDifferenceProvider provider = new TimeDifferenceProvider(name);
        Assertions.assertFalse(provider.wasCalled());

        // Add the provider to the propagator
        propagator.addAdditionalStateProvider(provider);

        // Propagate
        final double dt = 600.0;
        final SpacecraftState propagated = propagator.propagate(initialState.getDate().shiftedBy(dt));

        // Verify
        Assertions.assertTrue(provider.wasCalled());
        Assertions.assertEquals(dt, propagated.getAdditionalState(name)[0], 0.01);

    }

    private static class TimeDifferenceProvider implements AdditionalStateProvider {

        private String  name;
        private boolean called;
        private double  dt;

        public TimeDifferenceProvider(final String name) {
            this.name   = name;
            this.called = false;
            this.dt     = 0.0;
        }

        @Override
        public void init(SpacecraftState initialState, AbsoluteDate target) {
            this.called = true;
            this.dt     = target.durationFrom(initialState.getDate());
        }

        @Override
        public String getName() {
            return name;
        }

        @Override
        public double[] getAdditionalState(SpacecraftState state) {
            return new double[] {
                dt
            };
        }

        public boolean wasCalled() {
            return called;
        }

    }

}


text:
package labels

import (
	"bytes"
	"fmt"
	"sort"
	"strings"

	"k8s.io/kubernetes/pkg/util/fielderrors"
	"k8s.io/kubernetes/pkg/util/sets"
	"k8s.io/kubernetes/pkg/util/validation"
)

// Selector represents a label selector.
type Selector interface {
	// Matches returns true if this selector matches the given set of labels.
	Matches(Labels) bool

	// Empty returns true if this selector does not restrict the selection space.
	Empty() bool

	// String returns a human readable string that represents this selector.
	String() string

	// Add add a specific requirement for the selector
	Add(key string, operator Operator, values []string) Selector
}

// Everything returns a selector that matches all labels.
func Everything() Selector {
	return LabelSelector{}
}

// Operator represents a key's relationship
// to a set of values in a Requirement.
type Operator string

const (
	DoesNotExistOperator Operator = "!"
	EqualsOperator       Operator = "="
	DoubleEqualsOperator Operator = "=="
	InOperator           Operator = "in"
	NotEqualsOperator    Operator = "!="
	NotInOperator        Operator = "notin"
	ExistsOperator       Operator = "exists"
)

//LabelSelector is a list of Requirements.
type LabelSelector []Requirement

// Sort by  obtain determisitic parser
type ByKey []Requirement

func (a ByKey) Len() int { return len(a) }

func (a ByKey) Swap(i, j int) { a[i], a[j] = a[j], a[i] }

func (a ByKey) Less(i, j int) bool { return a[i].key < a[j].key }

// Requirement is a selector that contains values, a key
// and an operator that relates the key and values. The zero
// value of Requirement is invalid.
// Requirement implements both set based match and exact match
// Requirement is initialized via NewRequirement constructor for creating a valid Requirement.
type Requirement struct {
	key       string
	operator  Operator
	strValues sets.String
}

// NewRequirement is the constructor for a Requirement.
// If any of these rules is violated, an error is returned:
// (1) The operator can only be In, NotIn, Equals, DoubleEquals, NotEquals, Exists, or DoesNotExist.
// (2) If the operator is In or NotIn, the values set must be non-empty.
// (3) If the operator is Equals, DoubleEquals, or NotEquals, the values set must contain one value.
// (4) If the operator is Exists or DoesNotExist, the value set must be empty.
// (5) The key is invalid due to its length, or sequence
//     of characters. See validateLabelKey for more details.
//
// The empty string is a valid value in the input values set.
func NewRequirement(key string, op Operator, vals sets.String) (*Requirement, error) {
	if err := validateLabelKey(key); err != nil {
		return nil, err
	}
	switch op {
	case InOperator, NotInOperator:
		if len(vals) == 0 {
			return nil, fmt.Errorf("for 'in', 'notin' operators, values set can't be empty")
		}
	case EqualsOperator, DoubleEqualsOperator, NotEqualsOperator:
		if len(vals) != 1 {
			return nil, fmt.Errorf("exact-match compatibility requires one single value")
		}
	case ExistsOperator, DoesNotExistOperator:
		if len(vals) != 0 {
			return nil, fmt.Errorf("values set must be empty for exists and does not exist")
		}
	default:
		return nil, fmt.Errorf("operator '%v' is not recognized", op)
	}

	for v := range vals {
		if err := validateLabelValue(v); err != nil {
			return nil, err
		}
	}
	return &Requirement{key: key, operator: op, strValues: vals}, nil
}

// Matches returns true if the Requirement matches the input Labels.
// There is a match in the following cases:
// (1) The operator is Exists and Labels has the Requirement's key.
// (2) The operator is In, Labels has the Requirement's key and Labels'
//     value for that key is in Requirement's value set.
// (3) The operator is NotIn, Labels has the Requirement's key and
//     Labels' value for that key is not in Requirement's value set.
// (4) The operator is DoesNotExist or NotIn and Labels does not have the
//     Requirement's key.
func (r *Requirement) Matches(ls Labels) bool {
	switch r.operator {
	case InOperator, EqualsOperator, DoubleEqualsOperator:
		if !ls.Has(r.key) {
			return false
		}
		return r.strValues.Has(ls.Get(r.key))
	case NotInOperator, NotEqualsOperator:
		if !ls.Has(r.key) {
			return true
		}
		return !r.strValues.Has(ls.Get(r.key))
	case ExistsOperator:
		return ls.Has(r.key)
	case DoesNotExistOperator:
		return !ls.Has(r.key)
	default:
		return false
	}
}

func (r *Requirement) Key() string {
	return r.key
}
func (r *Requirement) Operator() Operator {
	return r.operator
}
func (r *Requirement) Values() sets.String {
	ret := sets.String{}
	for k := range r.strValues {
		ret.Insert(k)
	}
	return ret
}

// Return true if the LabelSelector doesn't restrict selection space
func (lsel LabelSelector) Empty() bool {
	if lsel == nil {
		return true
	}
	return len(lsel) == 0
}

// String returns a human-readable string that represents this
// Requirement. If called on an invalid Requirement, an error is
// returned. See NewRequirement for creating a valid Requirement.
func (r *Requirement) String() string {
	var buffer bytes.Buffer
	if r.operator == DoesNotExistOperator {
		buffer.WriteString("!")
	}
	buffer.WriteString(r.key)

	switch r.operator {
	case EqualsOperator:
		buffer.WriteString("=")
	case DoubleEqualsOperator:
		buffer.WriteString("==")
	case NotEqualsOperator:
		buffer.WriteString("!=")
	case InOperator:
		buffer.WriteString(" in ")
	case NotInOperator:
		buffer.WriteString(" notin ")
	case ExistsOperator, DoesNotExistOperator:
		return buffer.String()
	}

	switch r.operator {
	case InOperator, NotInOperator:
		buffer.WriteString("(")
	}
	if len(r.strValues) == 1 {
		buffer.WriteString(r.strValues.List()[0])
	} else { // only > 1 since == 0 prohibited by NewRequirement
		buffer.WriteString(strings.Join(r.strValues.List(), ","))
	}

	switch r.operator {
	case InOperator, NotInOperator:
		buffer.WriteString(")")
	}
	return buffer.String()
}

// Add adds a requirement to the selector. It copies the current selector returning a new one
func (lsel LabelSelector) Add(key string, operator Operator, values []string) Selector {
	var reqs []Requirement
	for _, item := range lsel {
		reqs = append(reqs, item)
	}
	if r, err := NewRequirement(key, operator, sets.NewString(values...)); err == nil {
		reqs = append(reqs, *r)
	}
	return LabelSelector(reqs)
}

// Matches for a LabelSelector returns true if all
// its Requirements match the input Labels. If any
// Requirement does not match, false is returned.
func (lsel LabelSelector) Matches(l Labels) bool {
	for _, req := range lsel {
		if matches := req.Matches(l); !matches {
			return false
		}
	}
	return true
}

// String returns a comma-separated string of all
// the LabelSelector Requirements' human-readable strings.
func (lsel LabelSelector) String() string {
	var reqs []string
	for _, req := range lsel {
		reqs = append(reqs, req.String())
	}
	return strings.Join(reqs, ",")
}

// constants definition for lexer token
type Token int

const (
	ErrorToken Token = iota
	EndOfStringToken
	ClosedParToken
	CommaToken
	DoesNotExistToken
	DoubleEqualsToken
	EqualsToken
	IdentifierToken // to represent keys and values
	InToken
	NotEqualsToken
	NotInToken
	OpenParToken
)

// string2token contains the mapping between lexer Token and token literal
// (except IdentifierToken, EndOfStringToken and ErrorToken since it makes no sense)
var string2token = map[string]Token{
	")":     ClosedParToken,
	",":     CommaToken,
	"!":     DoesNotExistToken,
	"==":    DoubleEqualsToken,
	"=":     EqualsToken,
	"in":    InToken,
	"!=":    NotEqualsToken,
	"notin": NotInToken,
	"(":     OpenParToken,
}

// The item produced by the lexer. It contains the Token and the literal.
type ScannedItem struct {
	tok     Token
	literal string
}

// isWhitespace returns true if the rune is a space, tab, or newline.
func isWhitespace(ch byte) bool {
	return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n'
}

// isSpecialSymbol detect if the character ch can be an operator
func isSpecialSymbol(ch byte) bool {
	switch ch {
	case '=', '!', '(', ')', ',':
		return true
	}
	return false
}

// Lexer represents the Lexer struct for label selector.
// It contains necessary informationt to tokenize the input string
type Lexer struct {
	// s stores the string to be tokenized
	s string
	// pos is the position currently tokenized
	pos int
}

// read return the character currently lexed
// increment the position and check the buffer overflow
func (l *Lexer) read() (b byte) {
	b = 0
	if l.pos < len(l.s) {
		b = l.s[l.pos]
		l.pos++
	}
	return b
}

// unread 'undoes' the last read character
func (l *Lexer) unread() {
	l.pos--
}

// scanIdOrKeyword scans string to recognize literal token (for example 'in') or an identifier.
func (l *Lexer) scanIdOrKeyword() (tok Token, lit string) {
	var buffer []byte
IdentifierLoop:
	for {
		switch ch := l.read(); {
		case ch == 0:
			break IdentifierLoop
		case isSpecialSymbol(ch) || isWhitespace(ch):
			l.unread()
			break IdentifierLoop
		default:
			buffer = append(buffer, ch)
		}
	}
	s := string(buffer)
	if val, ok := string2token[s]; ok { // is a literal token?
		return val, s
	}
	return IdentifierToken, s // otherwise is an identifier
}

// scanSpecialSymbol scans string starting with special symbol.
// special symbol identify non literal operators. "!=", "==", "="
func (l *Lexer) scanSpecialSymbol() (Token, string) {
	lastScannedItem := ScannedItem{}
	var buffer []byte
SpecialSymbolLoop:
	for {
		switch ch := l.read(); {
		case ch == 0:
			break SpecialSymbolLoop
		case isSpecialSymbol(ch):
			buffer = append(buffer, ch)
			if token, ok := string2token[string(buffer)]; ok {
				lastScannedItem = ScannedItem{tok: token, literal: string(buffer)}
			} else if lastScannedItem.tok != 0 {
				l.unread()
				break SpecialSymbolLoop
			}
		default:
			l.unread()
			break SpecialSymbolLoop
		}
	}
	if lastScannedItem.tok == 0 {
		return ErrorToken, fmt.Sprintf("error expected: keyword found '%s'", buffer)
	}
	return lastScannedItem.tok, lastScannedItem.literal
}

// skipWhiteSpaces consumes all blank characters
// returning the first non blank character
func (l *Lexer) skipWhiteSpaces(ch byte) byte {
	for {
		if !isWhitespace(ch) {
			return ch
		}
		ch = l.read()
	}
}

// Lex returns a pair of Token and the literal
// literal is meaningfull only for IdentifierToken token
func (l *Lexer) Lex() (tok Token, lit string) {
	switch ch := l.skipWhiteSpaces(l.read()); {
	case ch == 0:
		return EndOfStringToken, ""
	case isSpecialSymbol(ch):
		l.unread()
		return l.scanSpecialSymbol()
	default:
		l.unread()
		return l.scanIdOrKeyword()
	}
}

// Parser data structure contains the label selector parser data strucutre
type Parser struct {
	l            *Lexer
	scannedItems []ScannedItem
	position     int
}

// Parser context represents context during parsing:
// some literal for example 'in' and 'notin' can be
// recognized as operator for example 'x in (a)' but
// it can be recognized as value for example 'value in (in)'
type ParserContext int

const (
	KeyAndOperator ParserContext = iota
	Values
)

// lookahead func returns the current token and string. No increment of current position
func (p *Parser) lookahead(context ParserContext) (Token, string) {
	tok, lit := p.scannedItems[p.position].tok, p.scannedItems[p.position].literal
	if context == Values {
		switch tok {
		case InToken, NotInToken:
			tok = IdentifierToken
		}
	}
	return tok, lit
}

// consume returns current token and string. Increments the the position
func (p *Parser) consume(context ParserContext) (Token, string) {
	p.position++
	tok, lit := p.scannedItems[p.position-1].tok, p.scannedItems[p.position-1].literal
	if context == Values {
		switch tok {
		case InToken, NotInToken:
			tok = IdentifierToken
		}
	}
	return tok, lit
}

// scan runs through the input string and stores the ScannedItem in an array
// Parser can now lookahead and consume the tokens
func (p *Parser) scan() {
	for {
		token, literal := p.l.Lex()
		p.scannedItems = append(p.scannedItems, ScannedItem{token, literal})
		if token == EndOfStringToken {
			break
		}
	}
}

// parse runs the left recursive descending algorithm
// on input string. It returns a list of Requirement objects.
func (p *Parser) parse() ([]Requirement, error) {
	p.scan() // init scannedItems

	var requirements []Requirement
	for {
		tok, lit := p.lookahead(Values)
		switch tok {
		case IdentifierToken, DoesNotExistToken:
			r, err := p.parseRequirement()
			if err != nil {
				return nil, fmt.Errorf("unable to parse requirement: %v", err)
			}
			requirements = append(requirements, *r)
			t, l := p.consume(Values)
			switch t {
			case EndOfStringToken:
				return requirements, nil
			case CommaToken:
				t2, l2 := p.lookahead(Values)
				if t2 != IdentifierToken && t2 != DoesNotExistToken {
					return nil, fmt.Errorf("found '%s', expected: identifier after ','", l2)
				}
			default:
				return nil, fmt.Errorf("found '%s', expected: ',' or 'end of string'", l)
			}
		case EndOfStringToken:
			return requirements, nil
		default:
			return nil, fmt.Errorf("found '%s', expected: !, identifier, or 'end of string'", lit)
		}
	}
}

func (p *Parser) parseRequirement() (*Requirement, error) {
	key, operator, err := p.parseKeyAndInferOperator()
	if err != nil {
		return nil, err
	}
	if operator == ExistsOperator || operator == DoesNotExistOperator { // operator found lookahead set checked
		return NewRequirement(key, operator, nil)
	}
	operator, err = p.parseOperator()
	if err != nil {
		return nil, err
	}
	var values sets.String
	switch operator {
	case InOperator, NotInOperator:
		values, err = p.parseValues()
	case EqualsOperator, DoubleEqualsOperator, NotEqualsOperator:
		values, err = p.parseExactValue()
	}
	if err != nil {
		return nil, err
	}
	return NewRequirement(key, operator, values)

}

// parseKeyAndInferOperator parse literals.
// in case of no operator '!, in, notin, ==, =, !=' are found
// the 'exists' operator is inferred
func (p *Parser) parseKeyAndInferOperator() (string, Operator, error) {
	var operator Operator
	tok, literal := p.consume(Values)
	if tok == DoesNotExistToken {
		operator = DoesNotExistOperator
		tok, literal = p.consume(Values)
	}
	if tok != IdentifierToken {
		err := fmt.Errorf("found '%s', expected: identifier", literal)
		return "", "", err
	}
	if err := validateLabelKey(literal); err != nil {
		return "", "", err
	}
	if t, _ := p.lookahead(Values); t == EndOfStringToken || t == CommaToken {
		if operator != DoesNotExistOperator {
			operator = ExistsOperator
		}
	}
	return literal, operator, nil
}

// parseOperator return operator and eventually matchType
// matchType can be exact
func (p *Parser) parseOperator() (op Operator, err error) {
	tok, lit := p.consume(KeyAndOperator)
	switch tok {
	// DoesNotExistToken shouldn't be here because it's a unary operator, not a binary operator
	case InToken:
		op = InOperator
	case EqualsToken:
		op = EqualsOperator
	case DoubleEqualsToken:
		op = DoubleEqualsOperator
	case NotInToken:
		op = NotInOperator
	case NotEqualsToken:
		op = NotEqualsOperator
	default:
		return "", fmt.Errorf("found '%s', expected: '=', '!=', '==', 'in', notin'", lit)
	}
	return op, nil
}

// parseValues parses the values for set based matching (x,y,z)
func (p *Parser) parseValues() (sets.String, error) {
	tok, lit := p.consume(Values)
	if tok != OpenParToken {
		return nil, fmt.Errorf("found '%s' expected: '('", lit)
	}
	tok, lit = p.lookahead(Values)
	switch tok {
	case IdentifierToken, CommaToken:
		s, err := p.parseIdentifiersList() // handles general cases
		if err != nil {
			return s, err
		}
		if tok, _ = p.consume(Values); tok != ClosedParToken {
			return nil, fmt.Errorf("found '%s', expected: ')'", lit)
		}
		return s, nil
	case ClosedParToken: // handles "()"
		p.consume(Values)
		return sets.NewString(""), nil
	default:
		return nil, fmt.Errorf("found '%s', expected: ',', ')' or identifier", lit)
	}
}

// parseIdentifiersList parses a (possibly empty) list of
// of comma separated (possibly empty) identifiers
func (p *Parser) parseIdentifiersList() (sets.String, error) {
	s := sets.NewString()
	for {
		tok, lit := p.consume(Values)
		switch tok {
		case IdentifierToken:
			s.Insert(lit)
			tok2, lit2 := p.lookahead(Values)
			switch tok2 {
			case CommaToken:
				continue
			case ClosedParToken:
				return s, nil
			default:
				return nil, fmt.Errorf("found '%s', expected: ',' or ')'", lit2)
			}
		case CommaToken: // handled here since we can have "(,"
			if s.Len() == 0 {
				s.Insert("") // to handle (,
			}
			tok2, _ := p.lookahead(Values)
			if tok2 == ClosedParToken {
				s.Insert("") // to handle ,)  Double "" removed by StringSet
				return s, nil
			}
			if tok2 == CommaToken {
				p.consume(Values)
				s.Insert("") // to handle ,, Double "" removed by StringSet
			}
		default: // it can be operator
			return s, fmt.Errorf("found '%s', expected: ',', or identifier", lit)
		}
	}
}

// parseExactValue parses the only value for exact match style
func (p *Parser) parseExactValue() (sets.String, error) {
	s := sets.NewString()
	tok, lit := p.lookahead(Values)
	if tok == EndOfStringToken || tok == CommaToken {
		s.Insert("")
		return s, nil
	}
	tok, lit = p.consume(Values)
	if tok == IdentifierToken {
		s.Insert(lit)
		return s, nil
	}
	return nil, fmt.Errorf("found '%s', expected: identifier", lit)
}

// Parse takes a string representing a selector and returns a selector
// object, or an error. This parsing function differs from ParseSelector
// as they parse different selectors with different syntaxes.
// The input will cause an error if it does not follow this form:
//
// <selector-syntax> ::= <requirement> | <requirement> "," <selector-syntax> ]
// <requirement> ::= [!] KEY [ <set-based-restriction> | <exact-match-restriction> ]
// <set-based-restriction> ::= "" | <inclusion-exclusion> <value-set>
// <inclusion-exclusion> ::= <inclusion> | <exclusion>
//           <exclusion> ::= "notin"
//           <inclusion> ::= "in"
//           <value-set> ::= "(" <values> ")"
//              <values> ::= VALUE | VALUE "," <values>
// <exact-match-restriction> ::= ["="|"=="|"!="] VALUE
// KEY is a sequence of one or more characters following [ DNS_SUBDOMAIN "/" ] DNS_LABEL
// VALUE is a sequence of zero or more characters "([A-Za-z0-9_-\.])". Max length is 64 character.
// Delimiter is white space: (' ', '\t')
// Example of valid syntax:
//  "x in (foo,,baz),y,z notin ()"
//
// Note:
//  (1) Inclusion - " in " - denotes that the KEY exists and is equal to any of the
//      VALUEs in its requirement
//  (2) Exclusion - " notin " - denotes that the KEY is not equal to any
//      of the VALUEs in its requirement or does not exist
//  (3) The empty string is a valid VALUE
//  (4) A requirement with just a KEY - as in "y" above - denotes that
//      the KEY exists and can be any VALUE.
//  (5) A requirement with just !KEY requires that the KEY not exist.
//
func Parse(selector string) (Selector, error) {
	p := &Parser{l: &Lexer{s: selector, pos: 0}}
	items, error := p.parse()
	if error == nil {
		sort.Sort(ByKey(items)) // sort to grant determistic parsing
		return LabelSelector(items), error
	}
	return nil, error
}

const qualifiedNameErrorMsg string = "must match regex [" + validation.DNS1123SubdomainFmt + " / ] " + validation.DNS1123LabelFmt

func validateLabelKey(k string) error {
	if !validation.IsQualifiedName(k) {
		return fielderrors.NewFieldInvalid("label key", k, qualifiedNameErrorMsg)
	}
	return nil
}

func validateLabelValue(v string) error {
	if !validation.IsValidLabelValue(v) {
		return fielderrors.NewFieldInvalid("label value", v, qualifiedNameErrorMsg)
	}
	return nil
}

// SelectorFromSet returns a Selector which will match exactly the given Set. A
// nil and empty Sets are considered equivalent to Everything().
func SelectorFromSet(ls Set) Selector {
	if ls == nil {
		return LabelSelector{}
	}
	var requirements []Requirement
	for label, value := range ls {
		if r, err := NewRequirement(label, EqualsOperator, sets.NewString(value)); err != nil {
			//TODO: double check errors when input comes from serialization?
			return LabelSelector{}
		} else {
			requirements = append(requirements, *r)
		}
	}
	return LabelSelector(requirements)
}