text:
package luzu.test;

import javafx.util.Pair;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.prefs.Preferences;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * Created by zulk on 12.01.16.
 */
public class IntPartitioner {
    public static void main(String[] args) {

        ArrayList<Integer> mod2 = new ArrayList<>();
        ArrayList<Integer> mod3 = new ArrayList<>();
        ArrayList<Integer> noMod = new ArrayList<>();

        Predicate<Integer> pmod2 = i -> i % 2 == 0;
        Predicate<Integer> pmod3 = i -> i % 3 == 0;

        HashMap<Predicate, Collection> predicateConsumerHashMap = new HashMap<>();
        predicateConsumerHashMap.put(pmod2,mod2);
        predicateConsumerHashMap.put(pmod3,mod3);

//        Stream<Predicate<Integer>> conditions = Stream.of(pmod2, pmod3);i -> i % 2 == 0;

        for (int i=1;i<=10;i++) {
            final int finalI = i;
            Optional<Boolean> any = predicateConsumerHashMap.entrySet()
                    .stream()
                    .filter(s -> s.getKey().test(finalI))
                    .map(s -> s.getValue().add(finalI))
                    .findAny();

            if (!any.isPresent()) {
                noMod.add(finalI);
            }
        }

        System.out.println(mod2);
        System.out.println(mod3);
        System.out.println(noMod);
    }

}


text:
require 'spec_helper'
require 'chef-dk/policyfile/undo_record'

describe ChefDK::Policyfile::UndoRecord do

  subject(:undo_record) { described_class.new }

  let(:policy_revision) do
    {
      "name" => "appserver",
      "revision_id" => "1111111111111111111111111111111111111111111111111111111111111111"
    }
  end

  context "when empty" do

    it "has an empty set of policy groups" do
      expect(undo_record.policy_groups).to eq([])
    end

    it "has an empty set of policy revisions" do
      expect(undo_record.policy_revisions).to eq([])
    end

    it "converts to a serializable data structure" do
      expected = {
        "format_version" => 1,
        "backup_data" => {
          "policy_groups" => [],
          "policy_revisions" => []
        }
      }
      expect(undo_record.for_serialization).to eq(expected)
    end
  end

  context "with policy data" do

    before do
      undo_record.add_policy_group("preprod")
      undo_record.add_policy_revision("appserver", "preprod", policy_revision)
    end

    it "has a policy group" do
      expect(undo_record.policy_groups).to eq( [ "preprod" ] )
    end

    it "has a policy revision" do
      expect(undo_record.policy_revisions.size).to eq(1)
      revision_info = undo_record.policy_revisions.first
      expect(revision_info.policy_name).to eq("appserver")
      expect(revision_info.policy_group).to eq("preprod")
      expect(revision_info.data).to eq(policy_revision)
    end

    it "converts to a serializable data structure" do
      expected = {
        "format_version" => 1,
        "backup_data" => {
          "policy_groups" => [ "preprod" ],
          "policy_revisions" => [
            {
              "policy_name" => "appserver",
              "policy_group" => "preprod",
              "data" => policy_revision
            }
          ]
        }
      }
      expect(undo_record.for_serialization).to eq(expected)
    end

  end

  describe "loading from serialized data" do

    context "with invalid data" do

      context "with an invalid object type" do

        let(:serialized_data) { [] }

        it "raises an error" do
          expect { undo_record.load(serialized_data) }.to raise_error(ChefDK::InvalidUndoRecord)
        end

      end

      context "when required top-level keys aren't present" do

        let(:serialized_data) { {} }

        it "raises an error" do
          expect { undo_record.load(serialized_data) }.to raise_error(ChefDK::InvalidUndoRecord)
        end

      end

      context "when backup_data is an invalid type" do

        let(:serialized_data) do
          {
            "format_version" => 1,
            "backup_data" => []
          }
        end

        it "raises an error" do
          expect { undo_record.load(serialized_data) }.to raise_error(ChefDK::InvalidUndoRecord)
        end

      end

      context "when backup_data is missing required fields" do

        let(:serialized_data) do
          {
            "format_version" => 1,
            "backup_data" => {}
          }
        end

        it "raises an error" do
          expect { undo_record.load(serialized_data) }.to raise_error(ChefDK::InvalidUndoRecord)
        end

      end

      context "when backup_data has invalid policy_groups data" do

        let(:serialized_data) do
          {
            "format_version" => 1,
            "backup_data" => {
              "policy_groups" => nil,
              "policy_revisions" => []
            }
          }
        end

        it "raises an error" do
          expect { undo_record.load(serialized_data) }.to raise_error(ChefDK::InvalidUndoRecord)
        end

      end

      context "when backup_data has and invalid type for policy_revisions" do

        let(:serialized_data) do
          {
            "format_version" => 1,
            "backup_data" => {
              "policy_groups" => [],
              "policy_revisions" => nil
            }
          }
        end

        it "raises an error" do
          expect { undo_record.load(serialized_data) }.to raise_error(ChefDK::InvalidUndoRecord)
        end

      end

      context "when the backup_data has an invalid item in policy revisions" do

        let(:serialized_data) do
          {
            "format_version" => 1,
            "backup_data" => {
              "policy_groups" => [],
              "policy_revisions" => [ nil ]
            }
          }
        end

        it "raises an error" do
          expect { undo_record.load(serialized_data) }.to raise_error(ChefDK::InvalidUndoRecord)
        end

      end
    end

    context "with valid data" do
      let(:serialized_data) do
        {
          "format_version" => 1,
          "backup_data" => {
            "policy_groups" => [ "preprod" ],
            "policy_revisions" => [
              {
                "policy_name" => "appserver",
                "policy_group" => "preprod",
                "data" => policy_revision
              }
            ]
          }
        }
      end

      before do
        undo_record.load(serialized_data)
      end

      it "has a policy group" do
        expect(undo_record.policy_groups).to eq( [ "preprod" ] )
      end

      it "has a policy revision" do
        expect(undo_record.policy_revisions.size).to eq(1)
        revision_info = undo_record.policy_revisions.first
        expect(revision_info.policy_name).to eq("appserver")
        expect(revision_info.policy_group).to eq("preprod")
        expect(revision_info.data).to eq(policy_revision)
      end

      it "converts to a serializable data structure" do
        expect(undo_record.for_serialization).to eq(serialized_data)
      end

    end
  end

end

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<locale>
	<backend>
		<whitepapers>
			<item type="label" name="DownloadedOn">
				<translation language="nl"><![CDATA[gedownload op]]></translation>
				<translation language="en"><![CDATA[downloaded on]]></translation>
			</item>
			<item type="label" name="DownloadFile">
				<translation language="nl"><![CDATA[bestand downloaden]]></translation>
				<translation language="en"><![CDATA[download file]]></translation>
			</item>
			<item type="label" name="Downloads">
				<translation language="nl"><![CDATA[downloads]]></translation>
				<translation language="en"><![CDATA[downloads]]></translation>
			</item>
			<item type="label" name="Information">
				<translation language="nl"><![CDATA[informatie over de download]]></translation>
				<translation language="en"><![CDATA[download information]]></translation>
			</item>
			<item type="label" name="NumDownloads">
				<translation language="nl"><![CDATA[aantal keer gedownload]]></translation>
				<translation language="en"><![CDATA[number of times downloaded]]></translation>
			</item>
			<item type="label" name="Phonenumber">
				<translation language="nl"><![CDATA[telefoonnummer]]></translation>
				<translation language="en"><![CDATA[phonenumber]]></translation>
			</item>
			<item type="message" name="NumItemsInRecentWhitepapers">
				<translation language="nl"><![CDATA[Aantal items in recente whitepapers widget]]></translation>
				<translation language="en"><![CDATA[Number of items in recent whitepapers widget]]></translation>
			</item>
			<item type="message" name="NumItemsInRelatedWhitepapers">
				<translation language="nl"><![CDATA[Aantal items in gerelateerde whitepapers widget]]></translation>
				<translation language="en"><![CDATA[Number of items in related whitepapers widget]]></translation>
			</item>
			<item type="message" name="SendInMail">
				<translation language="nl"><![CDATA[Verzend de whitepapers als email]]></translation>
				<translation language="en"><![CDATA[Send the whitepapers as email]]></translation>
			</item>
			<item type="message" name="WhitepaperNotDownloaded">
				<translation language="nl"><![CDATA[Deze whitepaper werd nog niet gedownload.]]></translation>
				<translation language="en"><![CDATA[This whitepaper hasn't been downloaded yet.]]></translation>
			</item>
			<item type="message" name="SubmitAfterDownload">
				<translation language="nl"><![CDATA[Whitepaper downloaden zonder gegevens op te vragen.]]></translation>
				<translation language="en"><![CDATA[Download the whitepaper without requesting information.]]></translation>
			</item>
		</whitepapers>
		<core>
			<item type="label" name="Whitepapers">
				<translation language="nl"><![CDATA[whitepapers]]></translation>
				<translation language="en"><![CDATA[whitepapers]]></translation>
			</item>
		</core>
		<pages>
			<item type="label" name="Detail">
				<translation language="nl"><![CDATA[detail pagina]]></translation>
				<translation language="en"><![CDATA[detail page]]></translation>
			</item>
			<item type="label" name="RecentWhitepapers">
				<translation language="nl"><![CDATA[recente whitepapers]]></translation>
				<translation language="en"><![CDATA[recent whitepapers]]></translation>
			</item>
			<item type="label" name="RelatedWhitepapers">
				<translation language="nl"><![CDATA[gerelateerde whitepapers]]></translation>
				<translation language="en"><![CDATA[related whitepapers]]></translation>
			</item>
		</pages>
	</backend>
	<frontend>
		<core>
			<item type="action" name="Download">
				<translation language="nl"><![CDATA[download]]></translation>
				<translation language="en"><![CDATA[download]]></translation>
			</item>
			<item type="error" name="FileDownloadFailed">
				<translation language="nl"><![CDATA[Er ging iets mis bij het downloaden van het bestand. Gelieve contact op te nemen zodat we dit probleem kunnen oplossen.]]></translation>
				<translation language="en"><![CDATA[Something went wrong while downloading the file. Please contact us so we can resolve this issue.]]></translation>
			</item>
			<item type="label" name="AllWhitepapers">
				<translation language="nl"><![CDATA[alle whitepapers]]></translation>
				<translation language="en"><![CDATA[all whitepapers]]></translation>
			</item>
			<item type="label" name="Download">
				<translation language="nl"><![CDATA[download]]></translation>
				<translation language="en"><![CDATA[download]]></translation>
			</item>
			<item type="label" name="DownloadWhitepaper">
				<translation language="nl"><![CDATA[download deze whitepaper]]></translation>
				<translation language="en"><![CDATA[download this whitepaper]]></translation>
			</item>
			<item type="label" name="Phonenumber">
				<translation language="nl"><![CDATA[telefoonnummer]]></translation>
				<translation language="en"><![CDATA[phonenumber]]></translation>
			</item>
			<item type="label" name="ReadMoreAndDownload">
				<translation language="nl"><![CDATA[lees meer en download whitepaper]]></translation>
				<translation language="en"><![CDATA[read more and download whitepaper]]></translation>
			</item>
			<item type="label" name="RecentWhitepapers">
				<translation language="nl"><![CDATA[recente whitepapers]]></translation>
				<translation language="en"><![CDATA[recent whitepapers]]></translation>
			</item>
			<item type="label" name="RelatedWhitepapers">
				<translation language="nl"><![CDATA[gerelateerde whitepapers]]></translation>
				<translation language="en"><![CDATA[related whitepapers]]></translation>
			</item>
			<item type="message" name="DownloadWhitepaperInfo">
				<translation language="nl"><![CDATA[Voor je deze whitepaper kan downloaden dien je je gegevens in te vullen.]]></translation>
				<translation language="en"><![CDATA[Before you can download this whitepaper, please leave your info.]]></translation>
			</item>
			<item type="message" name="InformationSubmitted">
				<translation language="nl"><![CDATA[We hebben uw gegevens goed ontvangen.]]></translation>
				<translation language="en"><![CDATA[We've received your information well.]]></translation>
			</item>
			<item type="message" name="KeepInformed">
				<translation language="nl"><![CDATA[Ik wil op de hoogte blijven voor dit onderwerp.]]></translation>
				<translation language="en"><![CDATA[I want to stay up to date about this subject.]]></translation>
			</item>
			<item type="message" name="NoWhitepapers">
				<translation language="nl"><![CDATA[Er zijn nog geen whitepapers op dit moment.]]></translation>
				<translation language="en"><![CDATA[There are no whitepapers yet.]]></translation>
			</item>
			<item type="message" name="WhitepaperDownloaded">
				<translation language="nl"><![CDATA[We hebben uw informatie goed ontvangen. Uw download zal zo meteen starten. Indien dit niet gebeurt kunt u hier klikken.]]></translation>
				<translation language="en"><![CDATA[We've received you're info well. The whitepaper will start downloading soon. If this doesn't happen, you can download it here.]]></translation>
			</item>
			<item type="message" name="WhitepaperStartDownloaded">
				<translation language="nl"><![CDATA[Uw download zal zo meteen starten. Indien dit niet gebeurt kunt u hier klikken.]]></translation>
				<translation language="en"><![CDATA[The whitepaper will start downloading soon. If this doesn't happen, you can download it here.]]></translation>
			</item>
			<item type="message" name="WhitepaperEmailAttachment">
				<translation language="nl"><![CDATA[
In bijlage kunt u de whitepaper van "%1$s" vinden.

Meer informatie over deze whitepaper kunt u hier bekijken.
]]></translation>
				<translation language="en"><![CDATA[
You can find the whitepaper for "%1$s" as attachment for this email.

More information about this whitepaper is available here.
]]></translation>
			</item>
		</core>
	</frontend>
</locale>


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"
    />
    <meta name="description" content="Draw rectangles with different colors." />
    <meta name="cesium-sandcastle-labels" content="Development" />
    <title>Cesium Demo</title>

Loading...


text:
package org.javarosa.model.xform;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Vector;

import org.javarosa.core.data.IDataPointer;
import org.javarosa.core.model.FormDef;
import org.javarosa.core.model.IAnswerDataSerializer;
import org.javarosa.core.model.IDataReference;
import org.javarosa.core.model.instance.FormInstance;
import org.javarosa.core.model.instance.TreeElement;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.model.utils.IInstanceSerializingVisitor;
import org.javarosa.core.services.transport.payload.ByteArrayPayload;
import org.javarosa.core.services.transport.payload.DataPointerPayload;
import org.javarosa.core.services.transport.payload.IDataPayload;
import org.javarosa.core.services.transport.payload.MultiMessagePayload;
import org.javarosa.xform.util.XFormAnswerDataSerializer;
import org.kxml2.kdom.Element;
import org.kxml2.kdom.Node;

/**
 * A modified version of Clayton's XFormSerializingVisitor that constructs
 * SMS's.
 *
 * @author Munaf Sheikh, Cell-Life
 *
 */
public class SMSSerializingVisitor implements IInstanceSerializingVisitor {

	private String theSmsStr = null; // sms string to be returned
	private String nodeSet = null; // which nodeset the sms contents are in
	private String xmlns = null;
	private String delimeter = null;
	private String prefix = null;
	private String method = null;
	private TreeReference rootRef;

	/** The serializer to be used in constructing XML for AnswerData elements */
	IAnswerDataSerializer serializer;

	/** The schema to be used to serialize answer data */
	FormDef schema; // not used

	Vector dataPointers;

	private void init() {
		theSmsStr = null;
		schema = null;
		dataPointers = new Vector();
		theSmsStr = "";
	}

	public byte[] serializeInstance(FormInstance model, FormDef formDef) throws IOException {
		init();
		this.schema = formDef;
		return serializeInstance(model);
	}

	/*
	 * (non-Javadoc)
	 * @see org.javarosa.core.model.utils.IInstanceSerializingVisitor#serializeInstance(org.javarosa.core.model.instance.FormInstance)
	 */
	public byte[] serializeInstance(FormInstance model) throws IOException {
		return this.serializeInstance(model, new XPathReference("/"));
	}

	/*
	 * (non-Javadoc)
	 * @see org.javarosa.core.model.utils.IInstanceSerializingVisitor#serializeInstance(org.javarosa.core.model.instance.FormInstance, org.javarosa.core.model.IDataReference)
	 */
	public byte[] serializeInstance(FormInstance model, IDataReference ref) throws IOException {
		init();
		rootRef = model.unpackReference(ref);
		if (this.serializer == null) {
			this.setAnswerDataSerializer(new XFormAnswerDataSerializer());
		}
		model.accept(this);
		if (theSmsStr != null) {
			//Encode in UTF-16 by default, since it's the default for complex messages
			return theSmsStr.getBytes("UTF-16BE");
		} else {
			return null;
		}
	}

	/*
	 * (non-Javadoc)
	 * @see org.javarosa.core.model.utils.IInstanceSerializingVisitor#createSerializedPayload(org.javarosa.core.model.instance.FormInstance)
	 */
	public IDataPayload createSerializedPayload(FormInstance model) throws IOException {
		return createSerializedPayload(model, new XPathReference("/"));
	}

	public IDataPayload createSerializedPayload(FormInstance model, IDataReference ref)
			throws IOException {
		init();
		rootRef = model.unpackReference(ref);
		if (this.serializer == null) {
			this.setAnswerDataSerializer(new XFormAnswerDataSerializer());
		}
		model.accept(this);
		if (theSmsStr != null) {
			byte[] form = theSmsStr.getBytes("UTF-16");
			return new ByteArrayPayload(form, null, IDataPayload.PAYLOAD_TYPE_SMS);
		} else {
			return null;
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.javarosa.core.model.utils.ITreeVisitor#visit(org.javarosa.core.model
	 * .DataModelTree)
	 */
	public void visit(FormInstance tree) {
		nodeSet = new String();

		//TreeElement root = tree.getRoot();
		TreeElement root = tree.resolveReference(rootRef);

		xmlns = root.getAttributeValue("", "xmlns");
		delimeter = root.getAttributeValue("", "delimeter");
		prefix = root.getAttributeValue("", "prefix");

		xmlns = (xmlns != null)? xmlns : " ";
		delimeter = (delimeter != null ) ? delimeter : " ";
		prefix = (prefix != null) ? prefix : " ";

		//Don't bother adding any delimiters, yet. Delimiters are
		//added before tags/data
		theSmsStr = prefix;

		// serialize each node to get it's answers
		for (int j = 0; j < root.getNumChildren(); j++) {
			TreeElement tee = root.getChildAt(j);
			String e = serializeNode(tee);
			if(e != null) {
				theSmsStr += e;
			}
		}
		theSmsStr = theSmsStr.trim();
	}

	public String serializeNode(TreeElement instanceNode) {
		String ae = "";
		// don't serialize template nodes or non-relevant nodes
		if (!instanceNode.isRelevant()
				|| instanceNode.getMult() == TreeReference.INDEX_TEMPLATE)
			return null;

		if (instanceNode.getValue() != null) {
			Object serializedAnswer = serializer.serializeAnswerData(
					instanceNode.getValue(), instanceNode.getDataType());

			if (serializedAnswer instanceof Element) {
				// DON"T handle this.
				throw new RuntimeException("Can't handle serialized output for"
						+ instanceNode.getValue().toString() + ", "
						+ serializedAnswer);
			} else if (serializedAnswer instanceof String) {
				Element e = new Element();
				e.addChild(Node.TEXT, (String) serializedAnswer);

				String tag = instanceNode.getAttributeValue("", "tag");
				ae += ((tag != null) ? tag + delimeter : delimeter); // tag
																		// might
																		// be
																		// null

				for (int k = 0; k < e.getChildCount(); k++) {
					ae += e.getChild(k).toString() + delimeter;
				}

			} else {
				throw new RuntimeException("Can't handle serialized output for"
						+ instanceNode.getValue().toString() + ", "
						+ serializedAnswer);
			}

			if (serializer.containsExternalData(instanceNode.getValue())
					.booleanValue()) {
				IDataPointer[] pointer = serializer
						.retrieveExternalDataPointer(instanceNode.getValue());
				for (int i = 0; i < pointer.length; ++i) {
					dataPointers.addElement(pointer[i]);
				}
			}
		}
		return ae;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @seeorg.javarosa.core.model.utils.IInstanceSerializingVisitor#
	 * setAnswerDataSerializer(org.javarosa.core.model.IAnswerDataSerializer)
	 */
	public void setAnswerDataSerializer(IAnswerDataSerializer ads) {
		this.serializer = ads;
	}

	public IInstanceSerializingVisitor newInstance() {
		XFormSerializingVisitor modelSerializer = new XFormSerializingVisitor();
		modelSerializer.setAnswerDataSerializer(this.serializer);
		return modelSerializer;
	}
}


text:
package monopoly.evenements;

import java.util.Random;

import monopoly.jeu.Joueur;

/**
 * Lace un dé 6 face au hasard
 */
public class TirerDes extends EvenementAbstrait
{
    private static Random generator = new Random();   // Generateur de jet de dés
    private int tir1;
    private int tirDouble;

    /**
     * Construit l'évènement TirerDes
     */
    public TirerDes(Joueur j)
    {
        super("Tirer dés");
        cibler(j);

        tir1        = 0;
        tirDouble   = 0;
    }

    /**
     * Génère deux lancers de dés. Si le joueur est en prison et que les deux jets
     * sont égaux, libère le joueur. Sinon, ajoute un mouvement de valeur de la
     * somme des deux jets à la liste d'actions du joueur, et en ajoute un second si
     * les deux premiers jets étaient égaux
     */
    public void executer()
    {
        int tir1 = (int) (generator.nextDouble() * 6) + 1;
        int tir2 = (int) (generator.nextDouble() * 6) + 1;

        if( cible().enPrison() &&  tir1 == tir2 ) {
            cible().liberer();
        } else if( !cible().enPrison() ) {
            DeplacementRelatif d = new DeplacementRelatif(tir1 + tir2);
            d.cibler(cible());
            this.tir1 = tir1 + tir2;

            if(tir1 == tir2){
                this.tirDouble = (int) (generator.nextFloat() * 6) + 1;
                DeplacementRelatif d2 = new DeplacementRelatif(tirDouble);
                cible().chosesAFaire().add( d2 );
            }
            cible().chosesAFaire().add( d );
            cible().setDernierTir(tir1 + tirDouble);
        }
    }

    public int tir1()
    {
        return tir1;
    }

    public int tirDouble()
    {
        return tirDouble;
    }
}


text:
package org.fastnate.generator.test.schema;

import java.io.IOException;

import javax.persistence.Table;

import org.assertj.core.api.Assertions;
import org.fastnate.generator.test.AbstractEntitySqlGeneratorTest;
import org.junit.Test;

/**
 * Tests that {@link Table#schema() schema} and {@link Table#catalog() catalog} annotations are respected correctly.
 *
 * @author Tobias Liefke
 */
public class SchemaTest extends AbstractEntitySqlGeneratorTest {

	/**
	 * Ensures that {@link Table#schema() schema} and {@link Table#catalog() catalog} annotations are respected
	 * correctly.
	 *
	 * @throws IOException
	 *             if Hibernate or the generator throws one
	 */
	@Test
	public void testSchema() throws IOException {
		final SchemaTestEntity entity = new SchemaTestEntity("Parent");
		entity.getEntities().add(new SchemaTestEntity("Child"));
		entity.getStrings().add("Singlestring");
		write(entity);

		final SchemaTestEntity result = findSingleResult("SELECT e FROM SchemaTestEntity e WHERE e.name = :name",
				SchemaTestEntity.class, "name", entity.getName());
		Assertions.assertThat(result.getName()).isEqualTo(entity.getName());
		Assertions.assertThat(result.getEntities()).hasSameSizeAs(entity.getEntities());
		Assertions.assertThat(result.getEntities().iterator().next().getName())
				.isEqualTo(entity.getEntities().iterator().next().getName());
		Assertions.assertThat(result.getStrings()).containsExactlyElementsOf(entity.getStrings());
	}

}


text:
// Generated by CoffeeScript 1.7.1

(function() {
  var encrypt, fs, http, inet, net, path, spdy, url, utils;

  fs = require('fs');

  spdy = require('spdy');

  http = require('http');

  net = require('net');

  url = require('url');

  path = require("path");

  encrypt = require('./encrypt');

  utils = require("./utils");

  inet = require("./inet");

  exports.main = function() {
    var config, connections, inetNtoa, key, portPassword, timeout, _port, _results;
    console.log(utils.version);
    inetNtoa = function(buf) {
      return buf[0] + "." + buf[1] + "." + buf[2] + "." + buf[3];
    };
    config = utils.parseArgs(true);
    timeout = Math.floor(config.timeout * 1000) || 300000;
    portPassword = config.port_password;
    if (!(config.server && (config.server_port || portPassword) && config.password)) {
      utils.warn('config.json not found, you have to specify all config in commandline');
      process.exit(1);
    }
    connections = 0;
    if (portPassword) {
      if (config.server_port || config.password) {
        utils.warn('warning: port_password should not be used with server_port and password. server_port and password will be ignored');
      }
    } else {
      portPassword = {};
      portPassword[config.server_port.toString()] = config.password;
    }
    _results = [];
    for (_port in portPassword) {
      key = portPassword[_port];
      _results.push((function() {
        var port, server, server_ip, servers, _i, _len;
        port = _port;
        utils.info("calculating ciphers for port " + port);
        server = net.createServer(function(socket) {
          var conn;
          socket = new encrypt.ShadowStream(socket, config.method, key);
          conn = new spdy.Connection(socket, {
            isServer: true,
            client: false
          }, server);
          conn._setVersion(3.1);
          conn.on('error', function(err) {
            return utils.error(err);
          });
          return conn.on('stream', function(stream) {
            var addrLen, cachedPieces, clean, headerLength, remote, remoteAddr, remotePort, stage;
            connections += 1;
            stage = 0;
            headerLength = 0;
            remote = null;
            cachedPieces = [];
            addrLen = 0;
            remoteAddr = null;
            remotePort = null;
            utils.debug("connections: " + connections);
            clean = function() {
              utils.debug("clean");
              connections -= 1;
              remote = null;
              stream = null;
              return utils.debug("connections: " + connections);
            };
            stream.on("data", function(data) {
              var addrtype, buf, e;
              utils.log(utils.EVERYTHING, "connection on data");
              if (stage === 5) {
                return;
              }
              if (stage === 0) {
                try {
                  addrtype = data[0];
                  if (addrtype === void 0) {
                    return;
                  }
                  if (addrtype === 3) {
                    addrLen = data[1];
                  } else if (addrtype !== 1 && addrtype !== 4) {
                    utils.error("unsupported addrtype: " + addrtype + " maybe wrong password");
                    stream.destroy();
                    return;
                  }
                  if (addrtype === 1) {
                    remoteAddr = inetNtoa(data.slice(1, 5));
                    remotePort = data.readUInt16BE(5);
                    headerLength = 7;
                  } else if (addrtype === 4) {
                    remoteAddr = inet.inet_ntop(data.slice(1, 17));
                    remotePort = data.readUInt16BE(17);
                    headerLength = 19;
                  } else {
                    remoteAddr = data.slice(2, 2 + addrLen).toString("binary");
                    remotePort = data.readUInt16BE(2 + addrLen);
                    headerLength = 2 + addrLen + 2;
                  }
                  remote = net.connect(remotePort, remoteAddr, function() {
                    var i, piece;
                    utils.info("connecting " + remoteAddr + ":" + remotePort);
                    if ((remote == null) || (stream == null)) {
                      return;
                    }
                    i = 0;
                    while (i < cachedPieces.length) {
                      piece = cachedPieces[i];
                      remote.write(piece);
                      i++;
                    }
                    cachedPieces = null;
                    remote.pipe(stream);
                    stream.pipe(remote);
                    stage = 5;
                    return utils.debug("stage = 5");
                  });
                  remote.on("error", function(e) {
                    utils.debug("remote on error");
                    return utils.error("remote " + remoteAddr + ":" + remotePort + " error: " + e);
                  });
                  remote.on("close", function(had_error) {
                    utils.debug("remote on close:" + had_error);
                    if (had_error) {
                      if (stream) {
                        return stream.destroy();
                      }
                    } else {
                      if (stream) {
                        return stream.end();
                      }
                    }
                  });
                  remote.setTimeout(timeout, function() {
                    utils.debug("remote on timeout");
                    if (remote) {
                      remote.destroy();
                    }
                    if (stream) {
                      return stream.destroy();
                    }
                  });
                  if (data.length > headerLength) {
                    buf = new Buffer(data.length - headerLength);
                    data.copy(buf, 0, headerLength);
                    cachedPieces.push(buf);
                    buf = null;
                  }
                  stage = 4;
                  return utils.debug("stage = 4");
                } catch (_error) {
                  e = _error;
                  utils.error(e);
                  stream.destroy();
                  if (remote) {
                    return remote.destroy();
                  }
                }
              } else {
                if (stage === 4) {
                  return cachedPieces.push(data);
                }
              }
            });
            stream.on("error", function(e) {
              utils.debug("connection on error");
              return utils.error("local error: " + e);
            });
            stream.on("close", function(had_error) {
              utils.debug("connection on close:" + had_error);
              if (had_error) {
                if (remote) {
                  remote.destroy();
                }
              } else {
                if (remote) {
                  remote.end();
                }
              }
              return clean();
            });
            return stream.setTimeout(timeout, function() {
              utils.debug("connection on timeout");
              if (remote) {
                remote.destroy();
              }
              if (stream) {
                return stream.destroy();
              }
            });
          });
        });
        servers = config.server;
        if (!(servers instanceof Array)) {
          servers = [servers];
        }
        for (_i = 0, _len = servers.length; _i < _len; _i++) {
          server_ip = servers[_i];
          server.listen(port, server_ip, function() {
            return utils.info("server listening at " + server_ip + ":" + port + " ");
          });
        }
        return server.on("error", function(e) {
          if (e.code === "EADDRINUSE") {
            utils.error("Address in use, aborting");
          } else {
            utils.error(e);
          }
          return process.stdout.on('drain', function() {
            return process.exit(1);
          });
        });
      })());
    }
    return _results;
  };

  if (require.main === module) {
    exports.main();
  }

}).call(this);


text:
package cmri.snapshot.api.domain;

/**
 * To model the greeting representation, you create a resource representation class. Provide a plain old java object with fields, constructors, and accessors for the id and content data:
 */
public class Greeting {
    private final long id;
    private final String content;

    public Greeting(long id, String content) {
        this.id = id;
        this.content = content;
    }

    public long getId() {
        return id;
    }

    public String getContent() {
        return content;
    }
}


text:
package graph

// A Node is defined by an ID, a list of edges
// and the distances to any other node.
type Node struct {
	ID       string
	Edges    []Edge
	Distance map[string]float32 // Distance (sum of weights) to a given node (by ID)
}

func NewNode(id string) *Node {
	return &Node{
		ID:       id,
		Edges:    make([]Edge, 0, 10),
		Distance: make(map[string]float32, 10),
	}
}

// Follow an edge from a starting node.
func NextNode(start *Node, edge Edge) *Node {
	if edge.A == start {
		return edge.B
	} else {
		return edge.A
	}
}

// An Edge link two nodes together with a weight.
type Edge struct {
	A      *Node
	B      *Node
	Weight float32
}

// Dijkstra updates the distances from the start node
// to *any* other node in the graph.
func Dijkstra(start *Node) {
	visited := make(map[*Node]struct{}, 10)
	(*start).Distance[(*start).ID] = float32(0)
	currentNode := start

	// Traverse all the graph and find the shortest paths.
	// End when all nodes have been marked as visited.
	for {
		// Check all the unvisited neighbours.
		for _, edge := range (*currentNode).Edges {
			nodePtr := NextNode(currentNode, edge)

			if _, ok := visited[nodePtr]; ok {
				continue // Node has been visited already.
			}

			// Update tentative.
			tentative := (*currentNode).Distance[(*start).ID] + edge.Weight
			d, ok := (*nodePtr).Distance[(*start).ID]
			if !ok || tentative < d {
				(*nodePtr).Distance[(*start).ID] = tentative
			}
		}

		// Mark the current node as visited.
		var foo struct{} // Placeholder.
		visited[currentNode] = foo

		// Select the neighbour with the smallest
		// distance as the next node.
		nextIndex := -1
		min := float32(-1)
		for idx, edge := range (*currentNode).Edges {
			nodePtr := NextNode(currentNode, edge)

			if _, ok := visited[nodePtr]; ok {
				continue // Node has been visited already.
			}
			if min == float32(-1) {
				nextIndex = idx
			} else if (*nodePtr).Distance[(*start).ID] < min {
				nextIndex = idx
			}
		}

		if nextIndex == -1 {
			// No more nodes to visit.
			break
		}

		// Select next node to consider.
		e := (*currentNode).Edges[nextIndex]
		currentNode = NextNode(currentNode, e)
	}
}

// Returns the number of shortest paths between the start node and the end node
// and the number of shortest paths passing through the middleman.
func ShortestPaths(start, end, middleman *Node) (int, int) {
	a, b := make(chan int), make(chan int)
	go followShortestPaths(start, end, middleman, false, 0, 0, a, b)
	return <-a, <-b
}

func followShortestPaths(
	start, end, middleman *Node,
	gtm bool, distance float32, depth int, a, b chan int) {

	if start == end {
		nbsp := 0
		gtmv := 0 // Go Through Middleman Value.
		if depth == 0 || distance == 0 {
			nbsp = 1
			if gtm {
				gtmv = 1
			}
		}
		a <- nbsp
		b <- gtmv
		return // Stop recursion.
	}

	nsp := 0   // Number of Shortest Paths
	nsptm := 0 // Number of Shorest Paths going Through the Middleman

	isMiddleman := gtm
	if end == middleman {
		isMiddleman = true
	}

	if depth == 0 {
		distance = (*end).Distance[(*start).ID]
	}

	// Continue exploration.
	buffer := len((*end).Edges)
	aa, bb := make(chan int, buffer), make(chan int, buffer)
	routines := 0 // Number of routines launched.
	for _, edge := range (*end).Edges {
		next := NextNode(end, edge)

		dist := distance - edge.Weight

		if dist < 0 {
			continue
		}

		// Follow next shortest paths.
		go followShortestPaths(start, next, middleman,
			isMiddleman, dist, depth+1, aa, bb)

		routines++
	}

	// Increment shortest paths.
	for i := 0; i < routines; i++ {
		nsp += <-aa
		nsptm += <-bb
	}

	// Send values to channels
	a <- nsp
	b <- nsptm
}

// Betweenness centrality quantifies the number of times a candidate node acts as
// a bridge along the shortest path between two other nodes.
//
// https://en.wikipedia.org/wiki/Centrality#Betweenness_centrality
//
// The parameter nbOfNodes is the total number of nodes in the graph.
// The candidate node will be ignored if it is in the list of nodes.
func BetweennessCentrality(candidate *Node, nodes []*Node, nbOfNodes int) float32 {
	res := float32(0)
	visited := make(map[*Node]struct{}, 10)
	for _, start := range nodes {
		// Ignore node if we've seen it already,
		// or if it is the candidate node.
		if _, ok := visited[start]; start == candidate || ok {
			continue
		}
		for _, end := range nodes {
			// Ignore node if it is the candidate,
			// or the starting node,
			// or a node we've seen already.
			if _, seen := visited[end]; end == candidate ||
				end == start || seen {
				continue
			}

			// Calculate the number of shortest paths between start and end,
			// and the number of these paths going through the candidate.
			sp, sptm := ShortestPaths(start, end, candidate)

			if sptm > 0 && sp > 0 {
				// Update the result.
				res += float32(sptm) / float32(sp)
			}
		}
		// Mark the start node as visited.
		var placeholder struct{}
		visited[start] = placeholder
	}
	// Normalize the result by the total number of pair of nodes
	// that exist in the graph excluding the candidate node.
	res /= float32(nbOfNodes) * (float32(nbOfNodes-1) / 2)
	return res
}


text:
 Login

    <form id='loginform'>

            Username
            <input type="text" class="form-control" name="username">

            Password
            <input type="password" class="form-control" name="password">

        <button type="submit" class="btn btn-warning btn-lg" id="loginsubmit">Login</button>
    </form>

Or go home.


text:
'use strict';

var assert = require( 'chai' ).assert;

it( 'should have value', function() {
    assert( global.before_set == true );
    assert( global.lifecycle_before_set == true );
} );


text:
'use strict';

module.exports = {
  generateId: require('./generate-id'),
  generateSvg: require('./generate-svg'),
  generateSvgIcon: require('./generate-svg-icon'),
  generateSvgSprite: require('./generate-svg-sprite'),
  svg2symbol: require('./svg2symbol')
};


text:
@interface SKDynamicAttribute : NSObject

@property(nonatomic, readonly) SKObjectMapping *objectMapping;
@property(nonatomic, readonly) NSString *typeName;
@property(nonatomic, readonly) Class classe;
@property(nonatomic, readonly, getter = isPrimitive) BOOL primitive;
@property(nonatomic, readonly, getter = isIdType) BOOL idType;
@property(nonatomic, readonly, getter = isValidObject) BOOL validObject;

- (id)initWithClass: (Class) classs;
- (id)initWithAttributeDescription: (NSString *) description
                            forKey: (NSString *) key
                           onClass: (Class) classe;

- (id)initWithAttributeDescription: (NSString *) description
                            forKey: (NSString *) key
                           onClass: (Class) classe
                     attributeName: (NSString *) attibuteName;

- (id)initWithAttributeDescription: (NSString *) description
                            forKey: (NSString *) key
                           onClass: (Class) classe
                     attributeName: (NSString *) attibuteName
                         converter:(id<SKValueConverter>) converter;
@end


text:
import logging
import re
import icat
import icat.config
from icat.query import Query

logging.basicConfig(level=logging.INFO)

applicableTypes = ["Investigation", "DataCollection",
                   "Sample", "Dataset", "Datafile"]
valueTypes = ["NUMERIC", "STRING", "DATE_AND_TIME"]

def getUnits(s):
    if '(' in s:
        m = re.fullmatch(r'\s*([^()]+)\(([^()]+)\)\s*', s)
        if not m:
            raise ValueError("Invalid unit string '%s'" % s)
        return (m.group(1).strip(), m.group(2).strip())
    else:
        return (s.strip(), None)

def getMinMax(s):
    minmax_re = re.compile(r'''
        \s*
        ([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)
        \s*/\s*
        ([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)
        \s*
    ''', re.X)
    m = minmax_re.fullmatch(s)
    if not m:
        raise ValueError("Invalid min/max value string '%s'" % s)
    return (m.group(1), m.group(2))

config = icat.config.Config(ids=False)
subcmd = config.add_subcommands()

def add_paramtype(client, conf):
    pt = client.new("ParameterType")
    pt.facility = client.assertedSearch("Facility")[0]
    pt.name = conf.name
    units, units_fullname = getUnits(conf.units)
    pt.units = units
    if units_fullname:
        pt.unitsFullName = units_fullname
    if conf.description:
        pt.description = conf.description
    pt.valueType = conf.valueType
    if conf.applicable == "Investigation":
        pt.applicableToInvestigation = True
    elif conf.applicable == "DataCollection":
        pt.applicableToDataCollection = True
    elif conf.applicable == "Sample":
        pt.applicableToSample = True
    elif conf.applicable == "Dataset":
        pt.applicableToDataset = True
    elif conf.applicable == "Datafile":
        pt.applicableToDatafile = True
    if conf.minmax:
        if conf.valueType != "NUMERIC":
            raise ValueError("min/max value does not make sense "
                             "for %s value type" % conf.valueType)
        pt.minimumNumericValue, pt.maximumNumericValue = getMinMax(conf.minmax)
    if conf.permstrings:
        if conf.valueType != "STRING":
            raise ValueError("permissible strings do not make sense "
                             "for %s value type" % conf.valueType)
        for s in conf.permstrings.split(','):
            psv = client.new("PermissibleStringValue", value=s)
            pt.permissibleStringValues.append(psv)
    pt.create()
    return pt

add_config = subcmd.add_subconfig("add",
                                  dict(help="add a new ParameterType"),
                                  func=add_paramtype)
add_config.add_variable('name', ("--name",),
                        dict(help="name"))
add_config.add_variable('units', ("--units",),
                        dict(help="units (unit full name)"))
add_config.add_variable('description', ("--description",),
                        dict(help="description"), optional=True)
add_config.add_variable('valueType', ("--valueType",),
                        dict(help="value type", choices=valueTypes))
add_config.add_variable('applicable', ("--applicable",),
                        dict(help="entity this ParameterTypes is applicable to",
                             choices=applicableTypes), default="Dataset")
add_config.add_variable('minmax', ("--minmax",),
                        dict(help="min/max value"), optional=True)
add_config.add_variable('permstrings', ("--permissible-strings",),
                        dict(help="comma separated list of permissible "
                             "strings"),
                        optional=True)

def ls_paramtypes(client, conf):
    query = Query(client, "ParameterType", includes=["permissibleStringValues"])
    if conf.name:
        query.addConditions({"name": "LIKE '%s%%'" % conf.name})
    if conf.applicable == "Investigation":
        query.addConditions({"applicableToInvestigation": "= 'True'"})
    elif conf.applicable == "DataCollection":
        query.addConditions({"applicableToDataCollection": "= 'True'"})
    elif conf.applicable == "Sample":
        query.addConditions({"applicableToSample": "= 'True'"})
    elif conf.applicable == "Dataset":
        query.addConditions({"applicableToDataset": "= 'True'"})
    elif conf.applicable == "Datafile":
        query.addConditions({"applicableToDatafile": "= 'True'"})
    for pt in client.search(query):
        if pt.unitsFullName:
            units = "%s (%s)" % (pt.units, pt.unitsFullName)
        else:
            units = pt.units
        applicable = []
        if pt.applicableToInvestigation:
            applicable.append("Investigation")
        if pt.applicableToDataCollection:
            applicable.append("DataCollection")
        if pt.applicableToSample:
            applicable.append("Sample")
        if pt.applicableToDataset:
            applicable.append("Dataset")
        if pt.applicableToDatafile:
            applicable.append("Datafile")
        print("----------------------------------------")
        print("name: %s" % pt.name)
        if pt.pid:
            print("pid: %s" % pt.pid)
        print("units: %s" % units)
        if pt.description:
            print("description: %s" % pt.description)
        print("valueType: %s" % pt.valueType)
        if pt.valueType == "STRING" and pt.permissibleStringValues:
            values = [psv.value for psv in pt.permissibleStringValues]
            print("permissibleStringValues: %s" % ", ".join(values))
        if pt.valueType == "NUMERIC" and (pt.minimumNumericValue is not None or
                                          pt.maximumNumericValue is not None):
            print("min - max: %s - %s" % (pt.minimumNumericValue,
                                          pt.maximumNumericValue))
        if pt.verified is not None:
            print("verified: %s" % pt.verified)
        if pt.enforced is not None:
            print("enforced: %s" % pt.enforced)
        print("applicable to: %s" % ", ".join(applicable))
        print("----------------------------------------")
        print()

ls_config = subcmd.add_subconfig("ls",
                                 dict(help="list existing ParameterTypes"),
                                 func=ls_paramtypes)
ls_config.add_variable('name', ("-n", "--name",),
                       dict(help="search by name (prefix)"), optional=True)
ls_config.add_variable('applicable', ("--applicable",),
                       dict(help="limit search to ParameterTypes applicable to "
                            "some entity", choices=applicableTypes),
                       optional=True)

client, conf = config.getconfig()
client.login(conf.auth, conf.credentials)
conf.subcmd.func(client, conf)


text:
import express from 'express';
import logger from '../logger';
import connection from '../database';

import { index } from './index';
import { gamesById, createGame, updateGame } from './games';

const router = express.Router();

router.get('/', index);

router.use((req, res, next) => {
  if (connection.databaseError) {
    res.status(500).send('Something went horribly wrong.');
    logger.error(`API requires MongoDB connection but is in error: ${connection.databaseError}`);
    return;
  }

  next();
});

router.get('/games/:id', gamesById);
router.put('/games/:id', updateGame);
router.post('/games', createGame);

module.exports = router;


text:
package org.zaproxy.zap.extension.pscanrules;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import net.htmlparser.jericho.Source;
import org.apache.commons.collections.iterators.IteratorChain;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.core.scanner.Alert;
import org.parosproxy.paros.model.Model;
import org.parosproxy.paros.network.HttpHeader;
import org.parosproxy.paros.network.HttpMessage;
import org.zaproxy.addon.commonlib.CookieUtils;
import org.zaproxy.zap.extension.pscan.PassiveScanThread;
import org.zaproxy.zap.extension.pscan.PluginPassiveScanner;

public class CookieSecureFlagScanRule extends PluginPassiveScanner {

    /** Prefix for internationalised messages used by this rule */
    private static final String MESSAGE_PREFIX = "pscanrules.cookiesecureflag.";

    private static final int PLUGIN_ID = 10011;

    private static final String SECURE_COOKIE_ATTRIBUTE = "Secure";

    private Model model = null;

    @Override
    public void setParent(PassiveScanThread parent) {
        // Nothing to do.
    }

    @Override
    public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) {
        if (!msg.getRequestHeader().isSecure()) {
            // If SSL isn't used then the Secure flag has not to be checked
            return;
        }

        IteratorChain iterator = new IteratorChain();
        List<String> cookies1 = msg.getResponseHeader().getHeaderValues(HttpHeader.SET_COOKIE);

        if (!cookies1.isEmpty()) {
            iterator.addIterator(cookies1.iterator());
        }

        List<String> cookies2 = msg.getResponseHeader().getHeaderValues(HttpHeader.SET_COOKIE2);

        if (!cookies2.isEmpty()) {
            iterator.addIterator(cookies2.iterator());
        }

        Set<String> ignoreList = CookieUtils.getCookieIgnoreList(getModel());

        while (iterator.hasNext()) {
            String headerValue = (String) iterator.next();
            if (!CookieUtils.hasAttribute(headerValue, SECURE_COOKIE_ATTRIBUTE)) {
                if (CookieUtils.isExpired(headerValue)) {
                    continue;
                }
                if (!ignoreList.contains(CookieUtils.getCookieName(headerValue))) {
                    this.buildAlert(msg, headerValue).raise();
                }
            }
        }
    }

    private AlertBuilder buildAlert(HttpMessage msg, String headerValue) {
        return newAlert()
                .setRisk(Alert.RISK_LOW)
                .setConfidence(Alert.CONFIDENCE_MEDIUM)
                .setDescription(getDescription())
                .setParam(CookieUtils.getCookieName(headerValue))
                .setSolution(getSolution())
                .setReference(getReference())
                .setEvidence(
                        CookieUtils.getSetCookiePlusName(
                                msg.getResponseHeader().toString(), headerValue))
                .setCweId(614) // CWE-614: Sensitive Cookie in HTTPS Session Without 'Secure'
                // Attribute
                .setWascId(13); // WASC-13: Info leakage
    }

    @Override
    public int getPluginId() {
        return PLUGIN_ID;
    }

    @Override
    public String getName() {
        return Constant.messages.getString(MESSAGE_PREFIX + "name");
    }

    private String getDescription() {
        return Constant.messages.getString(MESSAGE_PREFIX + "desc");
    }

    private String getSolution() {
        return Constant.messages.getString(MESSAGE_PREFIX + "soln");
    }

    private String getReference() {
        return Constant.messages.getString(MESSAGE_PREFIX + "refs");
    }

    private Model getModel() {
        if (this.model == null) {
            this.model = Model.getSingleton();
        }
        return this.model;
    }

    /*
     * Just for use in the unit tests
     */
    protected void setModel(Model model) {
        this.model = model;
    }

    @Override
    public List<Alert> getExampleAlerts() {
        List<Alert> alerts = new ArrayList<>();
        alerts.add(buildAlert(new HttpMessage(), "").build());
        return alerts;
    }
}


text:
import numpy as np
import matplotlib.pyplot as plt
import scipy.io as sio
from scipy import optimize

## Machine Learning Online Class - Exercise 5: Regularized Linear Regression and Bias-Variance

#  Instructions
#  ------------
#
#  This file contains code that helps you get started on the
#  linear exercise. You will need to complete the following functions
#  in this exericse:
#
#     linearRegCostFunction
#     learningCurve
#     validationCurve
#     polyFeatures
#

# ==================== All function declaration ====================

def linearRegCostFunction(X, y, theta, lambda_val):
    m = y.shape[0]
    J = 0
    # ============= YOUR CODE HERE =============
    # Instructions: Compute the cost and gradient of regularized linear
    #               regression for a particular choice of theta.
    h_val = np.dot(X, theta).reshape(-1, 1)
    J = np.sum( np.power(h_val-y, 2) )
    J += lambda_val * np.sum ( np.power(theta[2:], 2) )
    J = J / (2 * m)
    # ===========================================
    return J

def linearRegGradFunction(X, y, theta, lambda_val):
    m = y.shape[0]
    grad = np.zeros(theta.shape)
    # ============= YOUR CODE HERE =============
    # Instructions: Compute the cost and gradient of regularized linear
    #               regression for a particular choice of theta.
    h_val = np.dot(X, theta).reshape(-1, 1)
    grad = np.dot( np.transpose(X), (h_val-y) ) / m
    grad[1:] = grad[1:] + lambda_val * np.power(theta[1:], 2).reshape(-1, 1) / m
    # ===========================================
    grad = grad.ravel()
    return grad

def trainLinearReg(X, y, lambda_val):
    initial_theta = np.zeros((X.shape[1], 1))

    costFunc = lambda t : linearRegCostFunction(X, y, t, lambda_val)
    gradFunc = lambda t : linearRegGradFunction(X, y, t, lambda_val)

    fmin_ret = optimize.fmin_cg(costFunc, initial_theta, gradFunc, maxiter=500, full_output=True)

    theta = fmin_ret[0]

    return theta

def learningCurve(X, y, Xval, yval, lambda_val):
    m = X.shape[0]
    error_train = np.zeros(m)
    error_val = np.zeros(m)
    # ============= YOUR CODE HERE =============
    # Instructions: Fill in this function to return training errors in
    #               error_train and the cross validation errors in error_val.
    for i in xrange(m):
        train_X = X[0:i+1, :]
        train_y = y[0:i+1]
        theta = trainLinearReg(train_X, train_y, lambda_val)
        error_train[i] = linearRegCostFunction(train_X, train_y, theta, 0)
        error_val[i] = linearRegCostFunction(Xval, yval, theta, 0)
    # ===========================================
    return error_train, error_val

def polyFeatures(X, p):
    X_poly = np.zeros((X.size, p))
    # ============= YOUR CODE HERE =============
    # Instructions: Given a vector X, return a matrix X_poly where the p-th
    #               column of X contains the values of X to the p-th
    #               power.
    for i in xrange(p):
        X_poly[:, i] = np.power(X, i+1).ravel()
    # ===========================================
    return X_poly

def featureNormalize(X):
    mu = np.mean(X, axis=0)
    X_norm = X - mu
    sigma = np.std(X, axis=0)
    X_norm = X_norm / sigma
    return X_norm, mu, sigma

def plotFit(min_x, max_x, mu, sigma, theta, p):
    x = np.arange(min_x - 15, max_x + 25, 0.05).reshape(-1, 1)
    X_poly = polyFeatures(x, p)
    X_poly = (X_poly - mu) / sigma

    X_poly = np.column_stack((np.ones((x.shape[0],1)), X_poly))

    plt.plot(x, np.dot(X_poly, theta), 'b-')

def validationCurve(X, y, Xval, yval):
    lambda_vec = np.array([0, 0.001, 0.003, 0.01, 0.03, 0.1, 0.3, 1, 3, 10])
    error_train = np.zeros(lambda_vec.size)
    error_val = np.zeros(lambda_vec.size)
    # ============= YOUR CODE HERE =============
    # Instructions: Fill in this function to return training errors in
    #               error_train and the validation errors in error_val. The
    #               vector lambda_vec contains the different lambda parameters
    #               to use for each calculation of the errors, i.e,
    #               error_train(i), and error_val(i) should give
    #               you the errors obtained after training with
    #               lambda = lambda_vec(i)
    for i in xrange(lambda_vec.size):
        theta = trainLinearReg(X, y, lambda_vec[i])
        error_train[i] = linearRegCostFunction(X, y, theta, 0)
        error_val[i] = linearRegCostFunction(Xval, yval, theta, 0)
    # ===========================================
    return lambda_vec, error_train, error_val

if __name__ == "__main__":
    plt.close('all')
    plt.ion() # interactive mode

    # ==================== Part 1: Loading and Visualizing Data ====================

    print('Loading and Visualizing Data ...')

    data_file = '../../data/ex5/ex5data1.mat'
    mat_content = sio.loadmat(data_file)

    X = mat_content['X']
    y = mat_content['y']
    Xval = mat_content['Xval']
    yval = mat_content['yval']
    Xtest = mat_content['Xtest']
    ytest = mat_content['ytest']

    m, n = X.shape

    plt.plot(X, y, 'rx', markersize=10, label='Training Data')
    plt.xlabel('Change in water level (x)')
    plt.ylabel('Water flowing out of the dam (y)')

    raw_input('Program paused. Press enter to continue')

    # =================== Part 2: Regularized Linear Regression Cost ===================

    theta = np.ones((2,1))
    X2 = np.column_stack((np.ones((m,1)), X))
    J = linearRegCostFunction(X2, y, theta, 1)

    print('Cost at theta = [1 ; 1]: %f \n (this value should be about 303.993192)' %  J)

    raw_input('Program paused. Press enter to continue')

    # =================== Part 3: Regularized Linear Regression Gradient ===================

    theta = np.ones((2,1))
    grad = linearRegGradFunction(X2, y, theta, 1)

    print('Gradient at theta = [1 ; 1]: [%f; %f] \n (this value should be about [-15.303016; 598.250744])' %  (grad[0], grad[1]))

    raw_input('Program paused. Press enter to continue')

    # =================== Part 4: Train Linear Regression ===================

    lambda_val = 0;
    theta = trainLinearReg(X2, y, lambda_val);

    plt.plot(X, np.dot(X2, theta), 'b-', label='Linear Regression')
    plt.legend()

    raw_input('Program paused. Press enter to continue')

    # =================== Part 5: Learning Curve for Linear Regression ===================

    lambda_val = 0
    Xval2 = np.column_stack((np.ones((Xval.shape[0], 1)), Xval))
    error_train, error_val = learningCurve(X2, y, Xval2, yval, lambda_val)

    plt.figure()
    plt.title('Learning curve for linear regression')
    plt.legend('Train', 'Cross Validation')
    plt.xlabel('Number of training examples')
    plt.ylabel('Error')
    plt.plot(np.arange(1, m+1), error_train, label='Train error')
    plt.plot(np.arange(1, m+1), error_val, label='Validation error')
    plt.legend()

    print('# Training Examples\tTrain Error\tCross Validation Error')
    for i in xrange(m):
        print('  \t%d\t\t%f\t%f' % (i+1, error_train[i], error_val[i]))

    raw_input('Program paused. Press enter to continue')

    # =================== Part 6: Feature Mapping for Polynomial Regression ===================

    p = 8

    X_poly = polyFeatures(X, p)
    X_poly, mu, sigma = featureNormalize(X_poly)
    X_poly = np.column_stack((np.ones((m, 1)), X_poly))

    X_poly_test = polyFeatures(Xtest, p)
    X_poly_test = (X_poly_test - mu) / sigma
    X_poly_test = np.column_stack((np.ones((X_poly_test.shape[0], 1)), X_poly_test))

    X_poly_val = polyFeatures(Xval, p)
    X_poly_val = (X_poly_val - mu) / sigma
    X_poly_val = np.column_stack((np.ones((X_poly_val.shape[0], 1)), X_poly_val))

    print('Normalized Training Example 1:')
    print(X_poly[0, :])

    raw_input('Program paused. Press enter to continue')

    # =================== Part 7: Learning Curve for Polynomial Regression ===================

    lambda_val = 0
    theta = trainLinearReg(X_poly, y, lambda_val)

    plt.figure()
    plt.title('Polynomial Regression Fit (lambda = %f)' % lambda_val)
    plt.plot(X, y, 'rx', markersize=10, label='Training Data')
    plotFit(np.min(X), np.max(X), mu, sigma, theta, p)
    plt.xlabel('Change in water level (x)')
    plt.ylabel('Water flowing out of the dam (y)')

    error_train, error_val = learningCurve(X_poly, y, X_poly_val, yval, lambda_val)

    plt.figure()
    plt.title('Polynomial Regression Fit (lambda = %f)' % lambda_val)
    plt.xlabel('Number of training examples')
    plt.ylabel('Error')
    plt.plot(np.arange(1, m+1), error_train, label='Train error')
    plt.plot(np.arange(1, m+1), error_val, label='Validation error')
    plt.legend()

    print('# Training Examples\tTrain Error\tCross Validation Error')
    for i in xrange(m):
        print('  \t%d\t\t%f\t%f' % (i+1, error_train[i], error_val[i]))

    raw_input('Program paused. Press enter to continue')

    # =================== Part 8: Validation for Selecting Lambda ===================

    lambda_vec, error_train, error_val = validationCurve(X_poly, y, X_poly_val, yval)

    plt.close('all')
    plt.figure()
    plt.xlabel('lambda')
    plt.ylabel('Error')
    plt.plot(lambda_vec, error_train, label='Train')
    plt.plot(lambda_vec, error_val, label='Cross Validation')
    plt.legend()

    print('# lambda\tTrain Error\tCross Validation Error')
    for i in xrange(lambda_vec.shape[0]):
        print('  \t%d\t\t%f\t%f' % (i+1, error_train[i], error_val[i]))

    raw_input('Program paused. Press enter to continue')

    plt.close('all')


text:
namespace WebApiExam.Api.Infrastructure.ObjectFactory
{
    using System;
    using System.Linq;
    using Ninject;

    public class ObjectFactory
    {
        private static IKernel savedKernel;

        public static void Initialize(IKernel kernel)
        {
            savedKernel = kernel;
        }

        public static T Get<T>()
        {
            return savedKernel.Get<T>();
        }
    }
}


text:
package v3action

// SortOrder is used for sorting.
type SortOrder string

const (
	Ascending  SortOrder = "Ascending"
	Descending SortOrder = "Descending"
)

// Warnings is a list of warnings returned back from the cloud controller
type Warnings []string

// Actor represents a V3 actor.
type Actor struct {
	CloudControllerClient CloudControllerClient
	Config                Config
	SharedActor           SharedActor
	UAAClient             UAAClient
}

// NewActor returns a new V3 actor.
func NewActor(client CloudControllerClient, config Config, sharedActor SharedActor, uaaClient UAAClient) *Actor {
	return &Actor{
		CloudControllerClient: client,
		Config:                config,
		SharedActor:           sharedActor,
		UAAClient:             uaaClient,
	}
}


text:
package ch.usi.inf.l3.piuma.plugin.transformers

import ch.usi.inf.l3.piuma.plugin.TransformerPluginComponent
import scala.reflect.internal.Flags
import ch.usi.inf.l3.piuma.util.SymbolsUtil

trait TreeDuplicatorCake {

  duplicator: TransformerPluginComponent =>

  import duplicator.plgn._
  trait TreeDuplicator {
    self: duplicator.TransformerComponent =>

    import duplicator.plgn.global._

    def duplicate(x: Tree): Tree = {
      require(hasSymbol(x))
      val owner = x.symbol.owner match {
        case s: Symbol if goodSymbol(s) && s.isModule =>
          s.moduleClass
        case s => s
      }
      duplicate(x, owner)
    }

    def duplicate(x: Tree, newOwner: Symbol): Tree = {
      duplicate(x, x.symbol.name, newOwner)
    }

    def duplicate(x: Tree, newName: Name): Tree = {
      require(hasSymbol(x))
      val owner = x.symbol.owner match {
        case s: Symbol if goodSymbol(s) && s.isModule =>
          s.moduleClass
        case s => s
      }
      duplicate(x, newName, owner)
    }
    def duplicate(x: Tree, newName: Name, newOwner: Symbol): Tree = {
      val newSym = x.symbol.cloneSymbol(newOwner).setName(newName)
      x match {
        case ValDef(mods, name, tpt, rhs) =>
          val newTpt = tpt.duplicate
          val newRhs = rhs.duplicate

          fixOwner(newRhs, x.symbol, newSym, Nil)
          fixOwner(newTpt, x.symbol, newSym, Nil)

          // try {
          //   newSym.setInfoAndEnter(.tpe)
          // } catch {
          //   case ex: Exception => newSym.setInfo(x.symbol.tpe)
          // }
          localTyper.typed {
            ValDef(mods, newName.toTermName, newTpt, newRhs).setSymbol(newSym)
          }
        case DefDef(mods, name, tparams, vparamss, tpt, rhs) =>
          val newVparamss = vparamss.map((vparams) => {
            vparams.map((vparam) => {
              val sym =
                newSym.newSyntheticValueParam(vparam.tpe, vparam.name.toTermName)
              sym.setInfo(vparam.symbol.tpe)
              ValDef(sym, vparam.tpt)
            })
          })
          val newParamSyms = newVparamss.flatten.map(_.symbol)

          val newTpt = tpt.duplicate
          val newRhs = rhs.duplicate

          val mtpe = MethodType(newParamSyms, newTpt.tpe)
          val newTpe = tparams match {
            case Nil =>
              mtpe
            case _ =>
              PolyType(tparams.map(_.symbol), mtpe)
          }

          if(newOwner.info.decls.lookup(newSym.name) == NoSymbol) {
            newSym.setInfoAndEnter(newTpe)
          } else {
            newSym.setInfo(newTpe)
          }

          fixOwner(newRhs, x.symbol, newSym, newParamSyms)

          val typedRhs = typed { newRhs }
          localTyper.typed {
            val methdef = DefDef(newSym, newVparamss, typedRhs)
            methdef.tpt setType localTyper.packedType(typedRhs, newSym)
            methdef
          }

        case ModuleDef(mods, name, impl) =>
          val newImpl = duplicate(impl, newSym).asInstanceOf[Template]
          // TODO: Set info for newSym
          localTyper.typed {
            ModuleDef(mods, newName.toTermName, newImpl).setSymbol(newSym)
          }
        case clazz @ ClassDef(mods, name, tparams, impl) =>
          // val newTparams = tparams.foldLeft(Nil: List[TypeDef])((z, y) => {
          //   (duplicate(y, y.name, newSym).asInstanceOf[TypeDef]) :: z
          // }).reverse

          val dbody = impl.duplicate.body
          val nparents = impl.parents.map(_.symbol.tpe)
          val ntpe = ClassInfoType(nparents, newScope, newSym)

          if(newOwner.info.decls.lookup(newSym.name) == NoSymbol) {
            newSym.setInfoAndEnter(ntpe)
          } else {
            newSym.setInfo(ntpe)
          }

          val ths = This(newSym)
          ths.setType(ntpe)

          val newBody = dbody.map(_.substituteThis(clazz.symbol, ths))

          newBody.foreach(fixOwner(_, clazz.symbol, newSym))
          localTyper.typed {
            ClassDef(newSym, Template(impl.parents, impl.self, newBody))
          }
        case _ => x
      }
    }

    def fixOwner(tree: Tree, oldOwner: Symbol, newOwner: Symbol): Unit = {
      fixOwner(tree, oldOwner, newOwner, Nil)
    }

    def fixOwner(tree: Tree, oldOwner: Symbol,
              newOwner: Symbol, paramSyms: List[Symbol]): Unit = {
      paramSyms match {
        case x :: xs =>
          changeParamSymbols(tree, oldOwner, paramSyms)
        case _ =>
      }
      changeOwner(tree, oldOwner, newOwner)
    }

    // This method is stolen from Mina
    private def findSymbol(name: Name, tpe: Type,
      paramSyms: List[Symbol]): Option[Symbol] = {
      val r = for (
        // FIXME:
        // I commented out this statement, because for generics types might change
        // One way to fix this is by passing a List of a pair of old and new symbols.
        // p <- paramSyms if (p.name == name && p.tpe =:= tpe)
        // What about knowing if they have the same owner or not? -- Amanj?
        p <- paramSyms if (p.name == name)
      ) yield {
        p
      }
      r match {
        case head :: Nil => Some(head)
        case _ => None
      }
    }

    // This method is stolen from Mina
    private def changeOwner(tree: Tree, oldOwner: Symbol, newOwner: Symbol): Unit = {
      var list: Map[Symbol, Symbol] = Map.empty
      tree.foreach {
        (x: Tree) =>
          {
            if (goodSymbol(x.symbol)
              && x.symbol.owner == oldOwner) {
              x match {
                case ident: Ident =>
                  assert(list.contains(ident.symbol),
                        s"${ident.symbol} could not be found. ${ident.pos}")
                  ident.symbol = list(ident.symbol)
                case _ =>
                  val ts = x.symbol
                  val ns = x.symbol.cloneSymbol(newOwner)
                  try {
                    x.symbol = ns
                    list = list + (ts -> ns)
                    changeOwner(x, ts, ns)
                  } catch {
                    case x: UnsupportedOperationException =>
                      x.toString
                  }

              }
            }
          }
      }
    }

    // This method is stolen from Mina
    private def changeParamSymbols(tree: Tree, oldOwner: Symbol,
            paramSyms: List[Symbol]): Unit = {
      tree.foreach {
        (x: Tree) =>
          {
            if (goodSymbol(x.symbol)
              && x.symbol.owner == oldOwner) {
              val ns = findSymbol(x.symbol.name, x.symbol.tpe, paramSyms)
              ns match {
                case Some(s) =>
                  try {
                    x.symbol = s
                  } catch {
                    case x: UnsupportedOperationException =>
                      x.toString
                  }
                case None => ()
              }
            }
          }
      }
    }
  }
}


text:
#ifndef SRC_COMPONENTS_INCLUDE_TRANSPORT_MANAGER_TRANSPORT_MANAGER_H_
#define SRC_COMPONENTS_INCLUDE_TRANSPORT_MANAGER_TRANSPORT_MANAGER_H_

#include "transport_manager/common.h"
#include "transport_manager/transport_manager_listener.h"
#include "transport_manager/transport_adapter/transport_adapter_event.h"
#include "protocol/common.h"

namespace resumption {
class LastState;
}

namespace transport_manager {

class TransportAdapterEvent;

/**
 * @brief Interface of transport manager.
 **/
class TransportManager {
 public:
  /**
   * @brief Destructor.
   **/
  virtual ~TransportManager() {}

  /**
   * @brief Initialize transport manager.
   * @return Error code.
   */
  virtual int Init(resumption::LastState& last_state) = 0;

  /**
   * @brief Reinitializes transport manager
   * @return Error code
   */
  virtual int Reinit() = 0;

  /**
    * @brief Start scanning for new devices.
    *
    * @return Code error.
    **/
  virtual int SearchDevices() = 0;

  /**
   * @brief Connect to all applications discovered on device.
   *
   * @param device_id Handle of device to connect to.
   *
   * @return Code error.
   **/
  virtual int ConnectDevice(const DeviceHandle device_id) = 0;

  /**
   * @brief Disconnect from all applications connected on device.
   *
   * @param device_id Handle of device to Disconnect from.
   *
   * @return Code error.
   **/
  virtual int DisconnectDevice(const DeviceHandle device_id) = 0;

  /**
   * @brief Disconnect from applications connected on device by connection
   *unique identifier.
   *
   * @param connection Connection unique identifier.
   *
   * @return Code error.
   **/
  virtual int Disconnect(const ConnectionUID connection_id) = 0;

  /**
   * @brief Disconnect and clear all unprocessed data.
   *
   * @param connection Connection unique identifier.
   */
  virtual int DisconnectForce(const ConnectionUID connection_id) = 0;

  /**
   * @brief Post new message in queue for massages destined to device.
   *
   * @param message Smart pointer to the raw massage.
   *
   * @return Code error.
   **/
  virtual int SendMessageToDevice(
      const protocol_handler::RawMessagePtr message) = 0;

  /**
   * @brief RunAppOnDevice allows run specific application on the certain
   *device.
   *
   * @param device_handle device identifier to run application on.
   *
   * @param bundle_id application id alsow known as bundle id on some devices to
   *run.
   */
  virtual void RunAppOnDevice(const DeviceHandle device_handle,
                              const std::string& bundle_id) = 0;

  /**
   * @brief Post event in the event queue.
   *
   * @param event Current event information.
   *
   * @return Code error.
   **/
  virtual int ReceiveEventFromDevice(const TransportAdapterEvent& event) = 0;

  /**
   * @brief Add transport adapter.
   *
   * @param transport_adapter Transport adapter
   *
   * @return Error code.
   **/
  virtual int AddTransportAdapter(
      transport_adapter::TransportAdapter* transport_adapter) = 0;

  /**
   * @brief Post listener to the container of transport manager listeners.
   *
   * @param listener Pointer to the transport manager listener.
   *
   * @return Code error.
   **/
  virtual int AddEventListener(TransportManagerListener* listener) = 0;

  /**
   * @brief Stop work finally. No new events guaranteed after method finish.
   *
   * @return Error code.
   **/
  virtual int Stop() = 0;

  /**
   * @brief Remove device from the container that hold devices.
   *
   * @param device Handle of device.
   *
   * @return Code error.
   **/
  virtual int RemoveDevice(const DeviceHandle device_handle) = 0;

  /**
   * @brief Turns on or off visibility of SDL to mobile devices
   * when visibility is ON (on_off = true) mobile devices are able to connect
   * otherwise ((on_off = false)) SDL is not visible from outside
   *
   * @return Code error.
   */
  virtual int Visibility(const bool& on_off) const = 0;
};
}  // namespace transport_manager
#endif  // SRC_COMPONENTS_INCLUDE_TRANSPORT_MANAGER_TRANSPORT_MANAGER_H_


text:
'use strict';

var Payment = require('../src/Payments');
var expect = require('chai').expect;

var validCardNumber = '4012888888881881';
var invalidCardNumber = 'visa';
var fakeCardNumber = '4111111111111112';
var cardObject = {
  'card_number': '4242424242424242',
  'exp_month': '12',
  'exp_year': '2017',
  'cvv': '123',
  'currency': 'Rs',
  'name': 'Ziyad Parekh',
  'address_country': 'Pakistan',
  'address_city': 'optional',
  'address_line_1': 'optional',
  'address_line_2': 'optional',
  'address_state': 'optional',
  'address_postal_code': 'optional',
};

describe('Payment', () => {
  it('should return a constructor', () => {
    var payment = new Payment({ card: cardObject });
    expect(payment).to.be.ok;
    expect(payment).to.be.an.instanceof(Payment);
  });

  it('should tokenize a card', () => {
    var payment = new Payment({ card: cardObject });
    console.log(payment.tokenizeCard());
  });

  it('should present a card', () => {
    var payment = new Payment({ card: cardObject });
    payment.presentCard().then((card) => {
      console.log(card);
    })
    //console.log(payment.presentCard());
  });

  it('should validate a card number', () => {
    var payment = new Payment({ card: cardObject });
    expect(payment.validateNumber()).to.equal(true);
  });

  it('should return false for invalid card numbers', () => {
    var fakeCard = Object.assign({}, cardObject, {
      card_number: invalidCardNumber
    });
    var payment = new Payment({ card: fakeCard });
    expect(payment.validateNumber()).to.equal(false);
  });

  it('should validate incorrect months', () => {
    var fakeCard = Object.assign({}, cardObject, {
      exp_month: '123'
    });
    var payment = new Payment({ card: fakeCard });
    expect(payment.validateMonth()).to.equal(false);
  });

  it('should validate a complete card in one go', () => {
    var payment = new Payment({ card: cardObject });
    expect(payment.isCardValid()).to.equal(true);
  });

});


text:
Data Master

                    <?php echo form_open('language/do_add', array('class'=>'form-horizontal', 'id'=> 'form')); ?>

                            Name *

                                <input type="text" class="form-control" name="name" placeholder="Name"/>

                            Value *

                                <textarea class="form-control" name="value" rows="4"></textarea>

                            Language *

                                <select class="form-control" name="language">
                                <?php
                                foreach($languages as $language):
                                ?>
                                <option value="<?php echo $language['value'];?>"><?php echo $language['text'];?></option>
                                <?php
                                endforeach;
                                ?>
                                </select>

                            <button type="submit" class="btn btn-info btn-fill pull-right">Submit</button>
                            <a href="<?php echo site_url('language');?>" class="btn btn-warning btn-fill pull-right">Back

                    <?php echo form_close(); ?>


text:
package level_09;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * --- Part Two ---
 *

 * Apparently, the file actually uses version two of the format.
 *

 * In version two, the only difference is that markers within decompressed data are decompressed. This, the documentation explains, provides much more substantial compression capabilities, allowing many-gigabyte files to be stored in only a few kilobytes.
 *

 * For example:
 *

 * (3x3)XYZ still becomes XYZXYZXYZ, as the decompressed section contains no markers.
 * X(8x2)(3x3)ABCY becomes XABCABCABCABCABCABCY, because the decompressed data from the (8x2) marker is then further decompressed, thus triggering the (3x3) marker twice for a total of six ABC sequences.
 * (27x12)(20x12)(13x14)(7x10)(1x12)A decompresses into a string of A repeated 241920 times.
 * (25x3)(3x3)ABC(2x3)XY(5x2)PQRSTX(18x9)(3x2)TWO(5x7)SEVEN becomes 445 characters long.
 *

 * Unfortunately, the computer you brought probably doesn't have enough memory to actually decompress the file; you'll have to come up with another way to get its decompressed length.
 *

 * What is the decompressed length of the file using this improved format?
 */
public class Level09b {

	// I was to lazy to optimize, so the simple bruteforce will do...

	public static void main(String[] args) throws IOException {
		List<String> content = Files.readAllLines(Paths.get("level_09/in1.txt"));
		Pattern compressionPattern = Pattern.compile("([0-9]+)x([0-9]+)");
		String line = content.get(0);
		line = line.replaceAll("[A-Z]", "A");

/*
		// Test cases
		line = "ADVENT";
		line = "(3x3)XYZ"; // 9
		line = "X(8x2)(3x3)ABCY"; // 20
		line = "(27x12)(20x12)(13x14)(7x10)(1x12)A"; // 241920
*/

		long result = 0L; // We don't need to remember the actual content, total length is enough

		while (true) {
			final int nextIdx = line.indexOf("(");
			if (nextIdx == -1) {
				//System.out.println("Remaining line: " + line);
				result += line.length();
				break;
			}

			//System.out.println("Appending up to next expansion tag: " + line.substring(0, nextIdx));
			result += (line.substring(0, nextIdx)).length();
			line = line.substring(nextIdx);
			//System.out.println("Trimmed line: " + line);

			final Matcher compressionMatcher = compressionPattern.matcher(line);
			if (!compressionMatcher.find()) {
				System.err.println("Shouldn't happen");
				break;
			}
			final int lenToRepeat = Integer.parseInt(compressionMatcher.group(1));
			final int timesRepeat = Integer.parseInt(compressionMatcher.group(2));
			final int matchLen = compressionMatcher.group(0).length() + 2;
			final String repeatMe = line.substring(matchLen, matchLen + lenToRepeat);

			//System.out.println("Going to repeat " + timesRepeat + " times: " + repeatMe);

			final StringBuilder tempResult = new StringBuilder();
			for (int i = 0; i < timesRepeat; i++)
				tempResult.append(repeatMe);

			line = line.substring(matchLen + lenToRepeat);
			tempResult.append(line);
			line = tempResult.toString();

			//System.out.println("Trimmed and semi-expanded line (" + (line.length()) + "/" + result + "): " + line);
			System.out.println(line.length() + "/" + result);
		}

		//System.out.println(result.toString());
		System.out.println("result 2: " + result);
	}
}


text:
#include <aws/elasticloadbalancingv2/model/CreateTargetGroupRequest.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

using namespace Aws::ElasticLoadBalancingv2::Model;
using namespace Aws::Utils;

CreateTargetGroupRequest::CreateTargetGroupRequest() :
    m_nameHasBeenSet(false),
    m_protocol(ProtocolEnum::NOT_SET),
    m_protocolHasBeenSet(false),
    m_protocolVersionHasBeenSet(false),
    m_port(0),
    m_portHasBeenSet(false),
    m_vpcIdHasBeenSet(false),
    m_healthCheckProtocol(ProtocolEnum::NOT_SET),
    m_healthCheckProtocolHasBeenSet(false),
    m_healthCheckPortHasBeenSet(false),
    m_healthCheckEnabled(false),
    m_healthCheckEnabledHasBeenSet(false),
    m_healthCheckPathHasBeenSet(false),
    m_healthCheckIntervalSeconds(0),
    m_healthCheckIntervalSecondsHasBeenSet(false),
    m_healthCheckTimeoutSeconds(0),
    m_healthCheckTimeoutSecondsHasBeenSet(false),
    m_healthyThresholdCount(0),
    m_healthyThresholdCountHasBeenSet(false),
    m_unhealthyThresholdCount(0),
    m_unhealthyThresholdCountHasBeenSet(false),
    m_matcherHasBeenSet(false),
    m_targetType(TargetTypeEnum::NOT_SET),
    m_targetTypeHasBeenSet(false),
    m_tagsHasBeenSet(false)
{
}

Aws::String CreateTargetGroupRequest::SerializePayload() const
{
  Aws::StringStream ss;
  ss << "Action=CreateTargetGroup&";
  if(m_nameHasBeenSet)
  {
    ss << "Name=" << StringUtils::URLEncode(m_name.c_str()) << "&";
  }

  if(m_protocolHasBeenSet)
  {
    ss << "Protocol=" << ProtocolEnumMapper::GetNameForProtocolEnum(m_protocol) << "&";
  }

  if(m_protocolVersionHasBeenSet)
  {
    ss << "ProtocolVersion=" << StringUtils::URLEncode(m_protocolVersion.c_str()) << "&";
  }

  if(m_portHasBeenSet)
  {
    ss << "Port=" << m_port << "&";
  }

  if(m_vpcIdHasBeenSet)
  {
    ss << "VpcId=" << StringUtils::URLEncode(m_vpcId.c_str()) << "&";
  }

  if(m_healthCheckProtocolHasBeenSet)
  {
    ss << "HealthCheckProtocol=" << ProtocolEnumMapper::GetNameForProtocolEnum(m_healthCheckProtocol) << "&";
  }

  if(m_healthCheckPortHasBeenSet)
  {
    ss << "HealthCheckPort=" << StringUtils::URLEncode(m_healthCheckPort.c_str()) << "&";
  }

  if(m_healthCheckEnabledHasBeenSet)
  {
    ss << "HealthCheckEnabled=" << std::boolalpha << m_healthCheckEnabled << "&";
  }

  if(m_healthCheckPathHasBeenSet)
  {
    ss << "HealthCheckPath=" << StringUtils::URLEncode(m_healthCheckPath.c_str()) << "&";
  }

  if(m_healthCheckIntervalSecondsHasBeenSet)
  {
    ss << "HealthCheckIntervalSeconds=" << m_healthCheckIntervalSeconds << "&";
  }

  if(m_healthCheckTimeoutSecondsHasBeenSet)
  {
    ss << "HealthCheckTimeoutSeconds=" << m_healthCheckTimeoutSeconds << "&";
  }

  if(m_healthyThresholdCountHasBeenSet)
  {
    ss << "HealthyThresholdCount=" << m_healthyThresholdCount << "&";
  }

  if(m_unhealthyThresholdCountHasBeenSet)
  {
    ss << "UnhealthyThresholdCount=" << m_unhealthyThresholdCount << "&";
  }

  if(m_matcherHasBeenSet)
  {
    m_matcher.OutputToStream(ss, "Matcher");
  }

  if(m_targetTypeHasBeenSet)
  {
    ss << "TargetType=" << TargetTypeEnumMapper::GetNameForTargetTypeEnum(m_targetType) << "&";
  }

  if(m_tagsHasBeenSet)
  {
    unsigned tagsCount = 1;
    for(auto& item : m_tags)
    {
      item.OutputToStream(ss, "Tags.member.", tagsCount, "");
      tagsCount++;
    }
  }

  ss << "Version=2015-12-01";
  return ss.str();
}

void  CreateTargetGroupRequest::DumpBodyToUrl(Aws::Http::URI& uri ) const
{
  uri.SetQueryString(SerializePayload());
}


text:
[Redis](http://redis.io/) is an advanced key-value cache and store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets, sorted sets, bitmaps and hyperloglogs.

## TL;DR;

```bash
$ helm install stable/redis-ha
```

By default this chart install one master pod containing redis master container and sentinel container, 2 sentinels and 1 redis slave.

## Introduction

This chart bootstraps a [Redis](https://github.com/bitnami/bitnami-docker-redis) deployment on a [Kubernetes](http://kubernetes.io) cluster using the [Helm](https://helm.sh) package manager.

## Prerequisites

- Kubernetes 1.5+ with Beta APIs enabled
- PV provisioner support in the underlying infrastructure

## Installing the Chart

To install the chart

```bash
$ helm install stable/redis-ha
```

The command deploys Redis on the Kubernetes cluster in the default configuration. By default this chart install one master pod containing redis master container and sentinel container, 2 sentinels and 1 redis slave. The [configuration](#configuration) section lists the parameters that can be configured during installation.

> **Tip**: List all releases using `helm list`

## Uninstalling the Chart

To uninstall/delete the deployment:

```bash
$ helm delete <chart-name>
```

The command removes all the Kubernetes components associated with the chart and deletes the release.

## Configuration

The following tables lists the configurable parameters of the Redis chart and their default values.

| Parameter                        | Description                                           | Default                                                   |
| -------------------------------- | ----------------------------------------------------- | --------------------------------------------------------- |
| `redis_image`                    | Redis image                                           | `gcr.io/google_containers/redis:v1`                       |
| `persistentVolume.enabled`       | Use a PVC to persist data                             | `false`                                                   |
| `persistentVolume.storageClass`  | Storage class of backing PVC                          | `generic`                                                 |
| `persistentVolume.accessMode`    | Use volume as ReadOnly or ReadWrite                   | `ReadWriteOnce`                                           |
| `persistentVolume.size`          | Size of data volume                                   | `8Gi`                                                     |
| `persistentVolume.annotations`   | Redis data Persistent Volume Claim annotations        | `{}`                                                      |
| `persistentVolume.existingClaim` | Redis data Persistent Volume existing claim name      | ``                                                        |
| `persistentVolume.mountPath`     | Redis data Persistent Volume mount root path          | `/data`                                                   |
| `persistentVolume.subPath`       | Subdirectory of redis data Persistent Volume to mount | ``                                                        |
| `resources.master`               | CPU/Memory for master nodes resource requests/limits  | Memory: `200Mi`, CPU: `100m`                              |
| `resources.slave`                | CPU/Memory for slave nodes  resource requests/limits  | Memory: `200Mi`, CPU: `100m`                              |
| `resources.sentinel`             | CPU/Memory for sentinel node resource requests/limits | Memory: `200Mi`, CPU: `100m`                              |
| `replicas.master`                | Number of master pods                                 | 1                                                         |
| `replicas.slave`                 | Number of slave pods                                  | 1                                                         |
| `replicas.sentinel`              | Number of sentinel pods                               | 3                                                         |

Specify each parameter using the `--set key=value[,key=value]` argument to `helm install`. For example,

```bash
$ helm install \
  --set redis_image=gcr.io/google_containers/redis:v1 \
    stable/redis-ha
```

The above command sets the Redis server within  `default` namespace.

Alternatively, a YAML file that specifies the values for the parameters can be provided while installing the chart. For example,

```bash
$ helm install -f values.yaml stable/redis-ha
```

> **Tip**: You can use the default [values.yaml](values.yaml)

## Persistence

The chart mounts a [Persistent Volume](kubernetes.io/docs/user-guide/persistent-volumes/) volume at this location. The volume is created using dynamic volume provisioning.


text:
Gathering some data on just how often [Auckland Transport](http://www.maxx.co.nz) buses are running early or late.

### Goals

* Buses near me seem to often run 10+ minutes early, or drivers slope off and skip runs altogether. I want some numbers to prove there's a systemic problem, since my ad-hoc complaints go nowhere.
* Help other people who regularly encounter early/late/no-show buses.

### Inspiration

The name is inspired from a [TransportBlog post](http://transportblog.co.nz/2012/06/19/our-tin-pot-dictator-bus-reliability-stats/) and [Brian Rudman's column in the Herald](http://www.nzherald.co.nz/nz/news/article.cfm?c_id=1&objectid=10794616):

> Auckland Transport's latest "good news" bus-service statistics read like the electoral results of some tin-pot dictator.
>
> Indeed, they're so fantastical any self-respecting dictator would have had them scaled down.
>
> The transport overlords claim last month, Auckland's public bus fleet scored 99.88 per cent for "reliability" and 99.24 per cent for punctuality.

And a follow-up [comment by deserthead](http://transportblog.co.nz/2012/09/17/more-tin-pot-dictator-bus-punctuality-stats/#comment-52564):

> Birkenhead bus 99.98%
> Saddam Hussein (1995) 99.96%
> NZ Bus 99.94%
> Bashar al Assad (2007) 97.60%
> Urban Express 95.96%

But maybe we're just all *really* unlucky or making a big deal out of nothing?

### Okay...?

But wait, we have this fancy realtime bus tracking system, right? Even though apparently, it [needs replacing](http://www.aucklandtransport.govt.nz/about-us/board-members/Board-Meetings-Minutes/Documents/Board%20reports%20December%202013/11i%20Real%20Time%20System.pdf). In the meantime, how about we just look at when buses go past bus stops and see how often they're early or late? Of *course* the times are an estimation and of *course* they don't apply everywhere, but lets have a go and see what we learn. Anyway, passengers are worried about 5+ minutes early or late, not 30 seconds.

Uses the same requests that the Maxx [Real Time Board](http://www.maxx.co.nz/) does. Acts like a browser as much as possible.

### Install & Configure

1. Clone the code
2. Create and activate a python virtualenv (`virtualenv venv; source venv/bin/activate`)
3. `pip install -r requirements.txt`
4. Create `tinpotbus/tinpotbus/settings_site.py` and override any Django settings you need to.
5. `python tinpotbus/manage.py syncdb --migrate`
6. `python tinpotbus/manage.py runserver` to start the debug server
7. Head to `http://localhost:8000/admin/` and create a Watch or two. Use the Stop and Route numbers from the Maxx [Real Time Board](http://www.maxx.co.nz/).
8. Run `python tinpotbus/manage.py watch_refresh` and see the options for how to update regularly (the website does it every 45 seconds fwiw). **Don't abuse the system.**


text:
using System;
using System.IO;

public class Logger
{

    private static Logger instance;
    public static Logger Instance { get { return instance; } }

    private String filePath;

    static Logger()
    {
        instance = new Logger();
    }

    private Logger()
    {
      //  filePath = "./PlayTestSession_"+ DateTime.Now.ToString()+".txt";
      //  this.writeToLog("--- STARTED NEW PLAYTEST SESSION ---");
    }

	public void initializeLogger(string id)
	{
#if UNITY_EDITOR
		return;
#endif
		Directory.CreateDirectory("./PlayTestLogs/"+DateTime.Now.Day);
		filePath = "./PlayTestLogs/"+ DateTime.Now.Day +"/PlayTestSession_"+ id +".txt";
        this.writeToLog("--- STARTED NEW PLAYTEST SESSION ---" + DateTime.Now.Day);//DateTime.Now.ToString());
	}

    public void writeToLog(string textToLog)
    {
#if UNITY_EDITOR
		return;
#endif
        using (System.IO.StreamWriter file = new System.IO.StreamWriter(filePath, true))
        {
            file.WriteLine(textToLog);
        }
    }

}


text:
package acmi.l2.clientmod.unreal.bytecode.token;

import acmi.l2.clientmod.unreal.bytecode.BytecodeInput;
import acmi.l2.clientmod.unreal.bytecode.BytecodeOutput;

import java.io.IOException;

public class LocalVariable extends Token {
    public static final int OPCODE = 0x00;

    private int objRef;

    public LocalVariable(int objRef) {
        this.objRef = objRef;
    }

    public static LocalVariable readFrom(BytecodeInput input) throws IOException {
        return new LocalVariable(input.readCompactInt());
    }

    @Override
    protected int getOpcode() {
        return OPCODE;
    }

    public int getObjRef() {
        return objRef;
    }

    @Override
    public void writeTo(BytecodeOutput output) throws IOException {
        super.writeTo(output);
        output.writeCompactInt(objRef);
    }

    @Override
    public String toString() {
        return "LocalVariable("
                + objRef
                + ')';
    }
}


text:
This is a sample REST api microservice written in C# using the .NET Core Framework. It tries its
best to adhere to the principles of the 12 factor app.

# Related

* [.NET Core](https://www.microsoft.com/net/core)
* [ASP.NET Core](https://docs.microsoft.com/en-us/aspnet/core/)
* [EntityFramework Core](https://docs.microsoft.com/en-us/ef/)
* [ASP.NET Configuration](https://github.com/aspnet/Configuration)
* [12 Factor App](https://12factor.net/)

# TODO

* Use EF Repository
* Use MSSQL on Linux Container
* Access and Audit Logging
* Docker Compose v2 networks
* Docker files for local dev
* Document how 12 factors are satisfied.
* Add port binding without Docker rebuild.
* Add vscode tasks and run mappings.
* Simplify and cleanup Docker build.
* Add NUnit Test Cases
* Utilize MSBuild. See [.NET Core MSBUILD](https://docs.microsoft.com/en-us/dotnet/articles/core/tutorials/target-dotnetcore-with-msbuild)

# Files

## project.json
Project configuration and dependency management.

## project.lock.json
Dependencies as they were resolved during last `dotnet restore` execution.

## appsettings.json
Configuration defaults used by our application. Can be amended or replaced with configuration passed via environment variables.

## Dockerfile
Docker build file. Line by line instructions to building a docker image for this application.

## docker-compose.yml
Docker Compose orchestration. Runs this application's docker image with configuration
and a database.

## Program.cs
Main entry point. Starts up web server with Startup.cs callbacks.

## Startup.cs
Application lifecycle callbacks. Reads configuration files and performs database migration.

## Migrations/
Classes generated by `dotnet ef migrations add`. At least one is provided to create the
database schema. More may be added with time to update the schema of a live system.

## Controllers/WidgetsController.cs
Web MVC controller for our REST api. Maps REST API urls to .NET class methods.

## Data/WidgetsContext.cs
Provides accessor methods to assign Entity classes to a database.

## Entity/Widget.cs
Our 'Widget' identity. Maps to a single relational database table. Simple fields are mapped
to database columns.

## obj/
Intermediate compiled objects.

## bin/
Compiled, published, and packaged output from `dotnet build`, `dotnet publish`, or `dotnet pack`.

## .vscode/
If using Visual Studio Code, these files customize the IDE experience for this project.

# Useful Commands

## Build Script
Compiles and packages with runtime in a Docker image
`./build.sh`

## Download dependencies
`dotnet restore`

## Compile the application
`dotnet build`

## Run app only
`dotnet run`

## Package
`dotnet publish`

## Run app and database
`docker-compose up --build --force-recreate`

## Build docker image
`docker build .`

## Remove database migration files
`dotnet ef migrations remove -f`

## Create new migration
`dotnet ef migrations add name_of_migration`


text:
package calculator;

import org.springframework.boot.Banner.Mode;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

  public static void main(String[] args) {
    SpringApplication app = new SpringApplication(Application.class);
    app.setBannerMode(Mode.LOG);
    app.run(args);
  }

}


text:
package azblob

// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// UserAgent returns the UserAgent string to use when sending http.Requests.
func UserAgent() string {
	return "Azure-SDK-For-Go/0.0.0 azblob/2019-12-12"
}

// Version returns the semantic version (see http://semver.org) of the client.
func Version() string {
	return "0.0.0"
}


text:
//
//    Copyright 2017 KeyleXiao.
//    Contact to Me : Keyle_xiao@hotmail.com
//
//      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
//
//          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.
//

namespace SmartDataViewer.Editor.ModelDesign
{
    public class NodeEditorStyle
    {

    }
}