text:
import time
import datetime
from   jinja2             import Environment
from   jinja2             import PackageLoader
from   Room               import Room
from   InformationFetcher import InformationFetcher

class TemplateMatcher():

    def __init__(self):
        self._env                = Environment(loader=PackageLoader('Template', 'tts-templates'))
        self._informationFetcher = InformationFetcher()

    def getHourlyTime(self):
        template = self._env.get_template('time-hourly.txt')
        hour = datetime.datetime.now().time().hour
        _,_,temp,_,_,_,_ = self._informationFetcher.getOutdoor()
        return template.render(hour=hour, temp=temp)

    def getCurrentTime(self):
        template = self._env.get_template('time-current.txt')
        hour     = datetime.datetime.now().time().hour
        minute   = datetime.datetime.now().time().minute
        return template.render(hour=hour, minute=minute)

    def getAcknowledgeStartWashingMachine(self):
        template = self._env.get_template('acknowledge-start-washing-machine.txt')
        return template.render()

    def getAcknowledgeEndWashingMachine(self):
        template = self._env.get_template('acknowledge-end-washing-machine.txt')
        return template.render()

    def getAcknowledgeEmtyingWashingMachine(self):
        template = self._env.get_template('acknowledge-empty-washing-machine.txt')
        return template.render()

    def getAcknowledgeStartShower(self, name):
        template = self._env.get_template('acknowledge-start-shower.txt')
        return template.render(name=name)

    def getAcknowledgeEndShower(self, name):
        template = self._env.get_template('acknowledge-end-shower.txt')
        return template.render(name=name)

    def getAcknowledgeStartBath(self, name):
        template = self._env.get_template('acknowledge-start-bath.txt')
        return template.render(name=name)

    def getAcknowledgeEndBath(self, name):
        template = self._env.get_template('acknowledge-end-bath.txt')
        return template.render(name=name)

    def getAcknowledgeDeactivateBath(self, name):
        template = self._env.get_template('acknowledge-deactivate-everything.txt')
        return template.render(name=name)

    def getWateringTheFlower(self, level):
        template = self._env.get_template('watering-the-flower.txt')
        return template.render(level=level)

    def getWashingMachineReady(self, endtime):
        template = self._env.get_template('washingmachine-ready.txt')
        diff = time.time() - endtime
        hours = int(diff / (60.0 * 60.0) )
        minutes = int( (diff - (hours * 60.0 * 60.0)) / 60.0 )
        return template.render(hours=hours, minutes=minutes)

    def getBathShowerUpdate(self):
        name=self._informationFetcher.getWhoIsInBathShower()
        showerbath=self._informationFetcher.getBathOrShower()
        minutes=self._informationFetcher.getTimeInBathShower()
        outtemp,_,_,condition,_,_,_ = self._informationFetcher.getOutdoor()
        temp=self._informationFetcher.getRoomTemp(Room.BATH_ROOM)
        humidity=self._informationFetcher.getRoomHumidity(Room.BATH_ROOM)
        timehour=datetime.datetime.now().time().hour
        timemin=datetime.datetime.now().time().minute
        template = self._env.get_template('bath-shower-update.txt')
        return template.render(name=name, showerbath=showerbath,minutes=minutes,outtemp=outtemp,condition=condition,temp=temp,humidity=humidity,timehour=timehour,timemin=timemin )

    def getTimeToGoToBed(self):
        template = self._env.get_template('time-to-go-to-bed.txt')
        hour = datetime.datetime.now().time().hour + 1
        return template.render(hour=hour)

    def getWakeupText(self, name):
        template   = self._env.get_template('wakeup.txt')
        name       = name
        fraction, degrees, minutes, seconds = self._informationFetcher.getEarthRotationTime()
        messages   = self._informationFetcher.getNumEmailMessages()
        bathtemp   = self._informationFetcher.getRoomTemp(Room.BATH_ROOM)
        bathhum    = self._informationFetcher.getRoomHumidity(Room.BATH_ROOM)
        planettemp, planethum, planetfeels, conditions, winddir, windspeed, gust = self._informationFetcher.getOutdoor()
        prediction = self._informationFetcher.getPrediction()
        astronauts = self._informationFetcher.getAstronauts()
        return template.render(name=name, degrees=degrees, minutes=minutes, seconds=seconds, messages=messages, bathtemp=bathtemp, bathhum=bathhum, planettemp=planettemp, planethum=planethum, planetfeels=planetfeels, conditions=conditions, winddir=winddir, windspeed=windspeed, gust=gust, prediction=prediction, astronauts=astronauts )

    def getBathToMoisty(self):
        template = self._env.get_template('bath-still-to-moisty.txt')
        return template.render()

    def getWorfsTemperature(self, current, delta):
        template = self._env.get_template('worf-temperature.txt')
        return template.render(current=current, delta=delta)

    def getCo2ToHigh(self, room):
        template = self._env.get_template('co2-to-high.txt')
        return template.render(co2=self._informationFetcher.getRoomCo2Level(room))

    def getRadiationToHigh(self, value):
        template = self._env.get_template('radiation-to-high.txt')
        return template.render(value=value)

    def getRadiationHigherThenAverage(self, valuehere, valueavr):
        template = self._env.get_template('radiation-higher-then-average.txt')
        return template.render(valuehere=valuehere, valueavr=valueavr)

    def getParticulateMatterHigherThenAverage(self, p1, p2):
        template = self._env.get_template('particulate-matter-to-high.txt')
        return template.render(p1=p1, p2=p2)

    def getNewDynamicIP(self, name):
        template = self._env.get_template('new-dynamic-ip.txt')
        return template.render(name=name)

    def getWaterlevelLow(self):
        template = self._env.get_template('tank-waterlevel-low.txt')
        return template.render()

    def getWaterlevelNormal(self):
        template = self._env.get_template('tank-waterlevel-normal.txt')
        return template.render()

    def getWaterChangeOn(self):
        template = self._env.get_template('tank-waterchange-on.txt')
        return template.render()

    def getWaterChangeOff(self):
        template = self._env.get_template('tank-waterchange-off.txt')
        return template.render()

    def getWaterChangeTemp(self, temp):
        template = self._env.get_template('tank-waterchange-temp.txt')
        return template.render(temp=temp)

    def getBikeBatteryLevelWarn(self, level):
        template = self._env.get_template('bike-low-bat.txt')
        return template.render(level=level)

    def getBikeStart(self, hours):
        template = self._env.get_template('bike-start.txt')
        return template.render(hours=hours)

    def getBikeEnd(self, minutes, distance):
        template = self._env.get_template('bike-end.txt')
        return template.render(minutes=minutes, distance=distance)

    def getBikeStatus(self, current, distance):
        template = self._env.get_template('bike-status.txt')
        return template.render(current=current, distance=distance)

if __name__ == '__main__':
    print "Test templates"
    t = TemplateMatcher()
    #print t.getHourlyTime()
    #print t.getCurrentTime()
    #print t.getAcknowledgeStartWashingMachine()
    #print t.getWashingMachineReady(234234)
    #print t.getTimeToGoToBed()
    #print t.getWakeupText('Ansi')
    #print t.getAcknowledgeStartShower('Ansi')
    #print t.getAcknowledgeEndShower('Ansi')
    #print t.getBathShowerUpdate()
    #print t.getWorfsTemperature(12.12, 01.21)
    #print t.getWorfsTemperature(12.12, -1.21)
    #print t.getWorfsTemperature(12.12, 0.0)
    #print t.getCo2ToHigh(Room.ANSI_ROOM)
    #print t.getRadiationToHigh(0.232)
    #print t.getRadiationHigherThenAverage(0.1, 0.09)
    #print t.getWaterlevelLow()
    #print t.getWaterlevelNormal()
    #print t.getParticulateMatterHigherThenAverage(2.2, 3.3)
    #print t.getNewDynamicIP("Zubenelgenubi")
    #print t.getBikeBatteryLevelWarn(4.23)
    #print t.getBikeStart(5)
    #print t.getBikeEnd(23, 32.131)
    #print t.getBikeStatus(42.63424223,  12.2323424)
    #print t.getBikeStatus(42.623423423, -12.234512)
    print t.getWaterChangeOn()
    print t.getWaterChangeOff()
    print t.getWaterChangeTemp(21.3)


text:
#region MIT License

#endregion

using System;

namespace SharpFont
{
	///
	/// Opaque handler to a path stroker object.
	///
	public class Stroker : IDisposable
	{
		#region Fields

		private IntPtr reference;
		private bool disposed;

		private Library parentLibrary;

		#endregion

		#region Constructors

		///
		/// Initializes a new instance of the <see cref="Stroker"/> class.
		///
		/// <param name="library">FreeType library handle.</param>
		public Stroker(Library library)
		{
			IntPtr strokerRef;
			Error err = FT.FT_Stroker_New(library.Reference, out strokerRef);

			if (err != Error.Ok)
				throw new FreeTypeException(err);

			Reference = strokerRef;
			library.AddChildStroker(this);
			parentLibrary = library;
		}

		///
		/// Finalizes an instance of the <see cref="Stroker"/> class.
		///
		~Stroker()
		{
			Dispose(false);
		}

		#endregion

		#region Properties

		///
		/// Gets a value indicating whether the <see cref="Stroker"/> has been disposed.
		///
		public bool IsDisposed
		{
			get
			{
				return disposed;
			}
		}

		internal IntPtr Reference
		{
			get
			{
				if (disposed)
					throw new ObjectDisposedException("Stroker", "Cannot access a disposed object.");

				return reference;
			}

			set
			{
				if (disposed)
					throw new ObjectDisposedException("Stroker", "Cannot access a disposed object.");

				reference = value;
			}
		}

		#endregion

		#region Methods

		///
		/// Reset a stroker object's attributes.
		///
		/// <remarks>
		/// The radius is expressed in the same units as the outline coordinates.
		/// </remarks>
		/// <param name="radius">The border radius.</param>
		/// <param name="lineCap">The line cap style.</param>
		/// <param name="lineJoin">The line join style.</param>
		/// <param name="miterLimit">
		/// The miter limit for the <see cref="StrokerLineJoin.MiterFixed"/> and
		/// <see cref="StrokerLineJoin.MiterVariable"/> line join styles, expressed as 16.16 fixed point value.
		/// </param>
		public void Set(int radius, StrokerLineCap lineCap, StrokerLineJoin lineJoin, int miterLimit)
		{
			if (disposed)
				throw new ObjectDisposedException("Stroker", "Cannot access a disposed object.");

			FT.FT_Stroker_Set(Reference, radius, lineCap, lineJoin, miterLimit);
		}

		///
		/// Reset a stroker object without changing its attributes. You should call this function before beginning a
		/// new series of calls to <see cref="BeginSubPath"/> or <see cref="EndSubPath"/>.
		///
		public void Rewind()
		{
			if (disposed)
				throw new ObjectDisposedException("Stroker", "Cannot access a disposed object.");

			FT.FT_Stroker_Rewind(Reference);
		}

		///
		/// A convenience function used to parse a whole outline with the stroker. The resulting outline(s) can be
		/// retrieved later by functions like <see cref="GetCounts"/> and <see cref="Export"/>.
		///
		/// <remarks><para>
		/// If 'opened' is 0 (the default), the outline is treated as a closed path, and the stroker generates two
		/// distinct 'border' outlines.
		/// </para><para>
		/// If 'opened' is 1, the outline is processed as an open path, and the stroker generates a single 'stroke'
		/// outline.
		/// </para><para>
		/// This function calls <see cref="Rewind"/> automatically.
		/// </para></remarks>
		/// <param name="outline">The source outline.</param>
		/// <param name="opened">
		/// A boolean. If 1, the outline is treated as an open path instead of a closed one.
		/// </param>
		public void ParseOutline(Outline outline, bool opened)
		{
			if (disposed)
				throw new ObjectDisposedException("Stroker", "Cannot access a disposed object.");

			if (outline == null)
				throw new ArgumentNullException("outline");

			Error err = FT.FT_Stroker_ParseOutline(Reference, outline.Reference, opened);

			if (err != Error.Ok)
				throw new FreeTypeException(err);
		}

		///
		/// Start a new sub-path in the stroker.
		///
		/// <remarks>
		/// This function is useful when you need to stroke a path that is not stored as an <see cref="Outline"/>
		/// object.
		/// </remarks>
		/// <param name="to">A pointer to the start vector.</param>
		/// <param name="open">A boolean. If 1, the sub-path is treated as an open one.</param>
		public void BeginSubPath(FTVector to, bool open)
		{
			if (disposed)
				throw new ObjectDisposedException("Stroker", "Cannot access a disposed object.");

			Error err = FT.FT_Stroker_BeginSubPath(Reference, ref to, open);

			if (err != Error.Ok)
				throw new FreeTypeException(err);
		}

		///
		/// Close the current sub-path in the stroker.
		///
		/// <remarks>
		/// You should call this function after <see cref="BeginSubPath"/>. If the subpath was not 'opened', this
		/// function 'draws' a single line segment to the start position when needed.
		/// </remarks>
		public void EndSubPath()
		{
			if (disposed)
				throw new ObjectDisposedException("Stroker", "Cannot access a disposed object.");

			Error err = FT.FT_Stroker_EndSubPath(Reference);

			if (err != Error.Ok)
				throw new FreeTypeException(err);
		}

		///
		/// 'Draw' a single line segment in the stroker's current sub-path, from the last position.
		///
		/// <remarks>
		/// You should call this function between <see cref="BeginSubPath"/> and <see cref="EndSubPath"/>.
		/// </remarks>
		/// <param name="to">A pointer to the destination point.</param>
		public void LineTo(FTVector to)
		{
			if (disposed)
				throw new ObjectDisposedException("Stroker", "Cannot access a disposed object.");

			Error err = FT.FT_Stroker_LineTo(Reference, ref to);

			if (err != Error.Ok)
				throw new FreeTypeException(err);
		}

		///
		/// 'Draw' a single quadratic Bézier in the stroker's current sub-path, from the last position.
		///
		/// <remarks>
		/// You should call this function between <see cref="BeginSubPath"/> and <see cref="EndSubPath"/>.
		/// </remarks>
		/// <param name="control">A pointer to a Bézier control point.</param>
		/// <param name="to">A pointer to the destination point.</param>
		public void ConicTo(FTVector control, FTVector to)
		{
			if (disposed)
				throw new ObjectDisposedException("Stroker", "Cannot access a disposed object.");

			Error err = FT.FT_Stroker_ConicTo(Reference, ref control, ref to);

			if (err != Error.Ok)
				throw new FreeTypeException(err);
		}

		///
		/// 'Draw' a single cubic Bézier in the stroker's current sub-path, from the last position.
		///
		/// <remarks>
		/// You should call this function between <see cref="BeginSubPath"/> and <see cref="EndSubPath"/>.
		/// </remarks>
		/// <param name="control1">A pointer to the first Bézier control point.</param>
		/// <param name="control2">A pointer to second Bézier control point.</param>
		/// <param name="to">A pointer to the destination point.</param>
		public void CubicTo(FTVector control1, FTVector control2, FTVector to)
		{
			if (disposed)
				throw new ObjectDisposedException("Stroker", "Cannot access a disposed object.");

			Error err = FT.FT_Stroker_CubicTo(Reference, ref control1, ref control2, ref to);

			if (err != Error.Ok)
				throw new FreeTypeException(err);
		}

		///
		/// Call this function once you have finished parsing your paths with the stroker. It returns the number of
		/// points and contours necessary to export one of the 'border' or 'stroke' outlines generated by the stroker.
		///
		/// <remarks><para>
		/// When an outline, or a sub-path, is 'closed', the stroker generates two independent 'border' outlines, named
		/// 'left' and 'right'.
		/// </para><para>
		/// When the outline, or a sub-path, is 'opened', the stroker merges the 'border' outlines with caps. The
		/// 'left' border receives all points, while the 'right' border becomes empty.
		/// </para><para>
		/// Use the function <see cref="GetCounts"/> instead if you want to retrieve the counts associated to both
		/// borders.
		/// </para></remarks>
		/// <param name="border">The border index.</param>
		/// <param name="pointsCount">The number of points.</param>
		/// <param name="contoursCount">The number of contours.</param>
		[CLSCompliant(false)]
		public void GetBorderCounts(StrokerBorder border, out uint pointsCount, out uint contoursCount)
		{
			if (disposed)
				throw new ObjectDisposedException("Stroker", "Cannot access a disposed object.");

			Error err = FT.FT_Stroker_GetBorderCounts(Reference, border, out pointsCount, out contoursCount);

			if (err != Error.Ok)
				throw new FreeTypeException(err);
		}

		/// <para>
		/// Call this function after <see cref="GetBorderCounts"/> to export the corresponding border to your own
		/// <see cref="Outline"/> structure.
		/// </para><para>
		/// Note that this function appends the border points and contours to your outline, but does not try to resize
		/// its arrays.
		/// </para>
		/// <remarks><para>
		/// Always call this function after <see cref="GetBorderCounts"/> to get sure that there is enough room in your
		/// <see cref="Outline"/> object to receive all new data.
		/// </para><para>
		/// When an outline, or a sub-path, is 'closed', the stroker generates two independent 'border' outlines, named
		/// 'left' and 'right'.
		/// </para><para>
		/// When the outline, or a sub-path, is 'opened', the stroker merges the 'border' outlines with caps. The
		/// 'left' border receives all points, while the 'right' border becomes empty.
		/// </para><para>
		/// Use the function <see cref="Export"/> instead if you want to retrieve all borders at once.
		/// </para></remarks>
		/// <param name="border">The border index.</param>
		/// <param name="outline">The target outline handle.</param>
		public void ExportBorder(StrokerBorder border, Outline outline)
		{
			if (disposed)
				throw new ObjectDisposedException("Stroker", "Cannot access a disposed object.");

			if (outline == null)
				throw new ArgumentNullException("outline");

			FT.FT_Stroker_ExportBorder(Reference, border, outline.Reference);
		}

		///
		/// Call this function once you have finished parsing your paths with the stroker. It returns the number of
		/// points and contours necessary to export all points/borders from the stroked outline/path.
		///
		/// <param name="pointsCount">The number of points.</param>
		/// <param name="contoursCount">The number of contours.</param>
		[CLSCompliant(false)]
		public void GetCounts(out uint pointsCount, out uint contoursCount)
		{
			if (disposed)
				throw new ObjectDisposedException("Stroker", "Cannot access a disposed object.");

			Error err = FT.FT_Stroker_GetCounts(Reference, out pointsCount, out contoursCount);

			if (err != Error.Ok)
				throw new FreeTypeException(err);
		}

		/// <para>
		/// Call this function after <see cref="GetBorderCounts"/> to export all borders to your own
		/// <see cref="Outline"/> structure.
		/// </para><para>
		/// Note that this function appends the border points and contours to your outline, but does not try to resize
		/// its arrays.
		/// </para>
		/// <param name="outline">The target outline handle.</param>
		public void Export(Outline outline)
		{
			if (disposed)
				throw new ObjectDisposedException("Stroker", "Cannot access a disposed object.");

			if (outline == null)
				throw new ArgumentNullException("outline");

			FT.FT_Stroker_Export(Reference, outline.Reference);
		}

		///
		/// Disposes an instance of the <see cref="Stroker"/> class.
		///
		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
		}

		private void Dispose(bool disposing)
		{
			if (!disposed)
			{
				disposed = true;

				FT.FT_Stroker_Done(reference);

				// removes itself from the parent Library, with a check to prevent this from happening when Library is
				// being disposed (Library disposes all it's children with a foreach loop, this causes an
				// InvalidOperationException for modifying a collection during enumeration)
				if (!parentLibrary.IsDisposed)
					parentLibrary.RemoveChildStroker(this);
			}
		}

		#endregion
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.codeborne.selenide.commands;

import com.codeborne.selenide.Condition;
import com.codeborne.selenide.SelenideElement;
import com.codeborne.selenide.impl.WebElementSource;
import org.assertj.core.api.WithAssertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebElement;

import java.lang.reflect.Field;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

final class ShouldCommandTest implements WithAssertions {
  private final SelenideElement proxy = mock(SelenideElement.class);
  private final WebElementSource locator = mock(WebElementSource.class);
  private final Should shouldCommand = new Should();
  private final WebElement mockedFoundElement = mock(WebElement.class);

  @BeforeEach
  void setup() {
    when(locator.getWebElement()).thenReturn(mockedFoundElement);
  }

  @Test
  void testDefaultConstructor() throws NoSuchFieldException, IllegalAccessException {
    Should should = new Should();
    Field prefixField = should.getClass().getDeclaredField("prefix");
    prefixField.setAccessible(true);
    String prefix = (String) prefixField.get(should);
    assertThat(prefix.isEmpty())
      .isTrue();
  }

  @Test
  void testExecuteMethodWithNonStringArgs() {
    SelenideElement returnedElement = shouldCommand.execute(proxy, locator, new Object[]{Condition.disabled});
    assertThat(returnedElement)
      .isEqualTo(proxy);
  }

  @Test
  void testExecuteMethodWithStringArgs() {
    SelenideElement returnedElement = shouldCommand.execute(proxy, locator, new Object[]{"hello"});
    assertThat(returnedElement)
      .isEqualTo(proxy);
  }
}


text:
package me.alb_i986.hbs.domain;

public class Piazzamento {

    private TipoLink_Piazzamento piazzamento;

    public Piazzamento(TipoLink_Piazzamento piazzamento) {
        this.piazzamento = piazzamento;
    }

    //serve in un evetuale UC - fineCorsa (assegna piazzamenti ai partecipanti)
    public void inserire_link(Corsa co, SingoloCavallo ca) {
        co.addPiazzamento(piazzamento);
        ca.addPiazzamento(piazzamento);
    }
}


text:
package org.apache.http.entity.mime;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.Arrays;

import org.apache.http.Consts;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;

public class TestMultipartForm {

    private File tmpfile;

    @After
    public void cleanup() {
        if (tmpfile != null) {
            tmpfile.delete();
        }
    }

    @Test
    public void testMultipartFormStringParts() throws Exception {
        final FormBodyPart p1 = FormBodyPartBuilder.create(
                "field1",
                new StringBody("this stuff", ContentType.DEFAULT_TEXT)).build();
        final FormBodyPart p2 = FormBodyPartBuilder.create(
                "field2",
                new StringBody("that stuff", ContentType.create(
                        ContentType.TEXT_PLAIN.getMimeType(), Consts.UTF_8))).build();
        final FormBodyPart p3 = FormBodyPartBuilder.create(
                "field3",
                new StringBody("all kind of stuff", ContentType.DEFAULT_TEXT)).build();
        final HttpStrictMultipart multipart = new HttpStrictMultipart(null, "foo",
                Arrays.asList(p1, p2, p3));

        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        multipart.writeTo(out);
        out.close();

        final String expected =
            "--foo\r\n" +
            "Content-Disposition: form-data; name=\"field1\"\r\n" +
            "Content-Type: text/plain; charset=ISO-8859-1\r\n" +
            "Content-Transfer-Encoding: 8bit\r\n" +
            "\r\n" +
            "this stuff\r\n" +
            "--foo\r\n" +
            "Content-Disposition: form-data; name=\"field2\"\r\n" +
            "Content-Type: text/plain; charset=UTF-8\r\n" +
            "Content-Transfer-Encoding: 8bit\r\n" +
            "\r\n" +
            "that stuff\r\n" +
            "--foo\r\n" +
            "Content-Disposition: form-data; name=\"field3\"\r\n" +
            "Content-Type: text/plain; charset=ISO-8859-1\r\n" +
            "Content-Transfer-Encoding: 8bit\r\n" +
            "\r\n" +
            "all kind of stuff\r\n" +
            "--foo--\r\n";
        final String s = out.toString("US-ASCII");
        Assert.assertEquals(expected, s);
        Assert.assertEquals(s.length(), multipart.getTotalLength());
    }

    @Test
    public void testMultipartFormCustomContentType() throws Exception {
        final FormBodyPart p1 = FormBodyPartBuilder.create(
                "field1",
                new StringBody("this stuff", ContentType.DEFAULT_TEXT)).build();
        final FormBodyPart p2 = FormBodyPartBuilder.create(
                "field2",
                new StringBody("that stuff", ContentType.parse("stuff/plain; param=value"))).build();
        final HttpStrictMultipart multipart = new HttpStrictMultipart(null, "foo",
                Arrays.asList(p1, p2));

        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        multipart.writeTo(out);
        out.close();

        final String expected =
                "--foo\r\n" +
                        "Content-Disposition: form-data; name=\"field1\"\r\n" +
                        "Content-Type: text/plain; charset=ISO-8859-1\r\n" +
                        "Content-Transfer-Encoding: 8bit\r\n" +
                        "\r\n" +
                        "this stuff\r\n" +
                        "--foo\r\n" +
                        "Content-Disposition: form-data; name=\"field2\"\r\n" +
                        "Content-Type: stuff/plain; param=value\r\n" +
                        "Content-Transfer-Encoding: 8bit\r\n" +
                        "\r\n" +
                        "that stuff\r\n" +
                        "--foo--\r\n";
        final String s = out.toString("US-ASCII");
        Assert.assertEquals(expected, s);
        Assert.assertEquals(s.length(), multipart.getTotalLength());
    }

    @Test
    public void testMultipartFormBinaryParts() throws Exception {
        tmpfile = File.createTempFile("tmp", ".bin");
        final Writer writer = new FileWriter(tmpfile);
        try {
            writer.append("some random whatever");
        } finally {
            writer.close();
        }

        final FormBodyPart p1 = FormBodyPartBuilder.create(
                "field1",
                new FileBody(tmpfile)).build();
        @SuppressWarnings("resource")
        final FormBodyPart p2 = FormBodyPartBuilder.create(
                "field2",
                new InputStreamBody(new FileInputStream(tmpfile), "file.tmp")).build();
        final HttpStrictMultipart multipart = new HttpStrictMultipart(null, "foo",
                Arrays.asList(p1, p2));

        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        multipart.writeTo(out);
        out.close();

        final String expected =
            "--foo\r\n" +
            "Content-Disposition: form-data; name=\"field1\"; " +
                "filename=\"" + tmpfile.getName() + "\"\r\n" +
            "Content-Type: application/octet-stream\r\n" +
            "Content-Transfer-Encoding: binary\r\n" +
            "\r\n" +
            "some random whatever\r\n" +
            "--foo\r\n" +
            "Content-Disposition: form-data; name=\"field2\"; " +
                "filename=\"file.tmp\"\r\n" +
            "Content-Type: application/octet-stream\r\n" +
            "Content-Transfer-Encoding: binary\r\n" +
            "\r\n" +
            "some random whatever\r\n" +
            "--foo--\r\n";
        final String s = out.toString("US-ASCII");
        Assert.assertEquals(expected, s);
        Assert.assertEquals(-1, multipart.getTotalLength());
    }

    @Test
    public void testMultipartFormStrict() throws Exception {
        tmpfile = File.createTempFile("tmp", ".bin");
        final Writer writer = new FileWriter(tmpfile);
        try {
            writer.append("some random whatever");
        } finally {
            writer.close();
        }

        final FormBodyPart p1 = FormBodyPartBuilder.create(
                "field1",
                new FileBody(tmpfile)).build();
        final FormBodyPart p2 = FormBodyPartBuilder.create(
                "field2",
                new FileBody(tmpfile, ContentType.create("text/plain", "ANSI_X3.4-1968"), "test-file")).build();
        @SuppressWarnings("resource")
        final FormBodyPart p3 = FormBodyPartBuilder.create(
                "field3",
                new InputStreamBody(new FileInputStream(tmpfile), "file.tmp")).build();
        final HttpStrictMultipart multipart = new HttpStrictMultipart(null, "foo",
                Arrays.asList(p1, p2, p3));

        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        multipart.writeTo(out);
        out.close();

        final String expected =
            "--foo\r\n" +
            "Content-Disposition: form-data; name=\"field1\"; " +
                "filename=\"" + tmpfile.getName() + "\"\r\n" +
            "Content-Type: application/octet-stream\r\n" +
            "Content-Transfer-Encoding: binary\r\n" +
            "\r\n" +
            "some random whatever\r\n" +
            "--foo\r\n" +
            "Content-Disposition: form-data; name=\"field2\"; " +
                "filename=\"test-file\"\r\n" +
            "Content-Type: text/plain; charset=US-ASCII\r\n" +
            "Content-Transfer-Encoding: binary\r\n" +
            "\r\n" +
            "some random whatever\r\n" +
            "--foo\r\n" +
            "Content-Disposition: form-data; name=\"field3\"; " +
                "filename=\"file.tmp\"\r\n" +
            "Content-Type: application/octet-stream\r\n" +
            "Content-Transfer-Encoding: binary\r\n" +
            "\r\n" +
            "some random whatever\r\n" +
            "--foo--\r\n";
        final String s = out.toString("US-ASCII");
        Assert.assertEquals(expected, s);
        Assert.assertEquals(-1, multipart.getTotalLength());
    }

    @Test
    public void testMultipartFormRFC6532() throws Exception {
        tmpfile = File.createTempFile("tmp", ".bin");
        final Writer writer = new FileWriter(tmpfile);
        try {
            writer.append("some random whatever");
        } finally {
            writer.close();
        }

        final FormBodyPart p1 = FormBodyPartBuilder.create(
                "field1\u0414",
                new FileBody(tmpfile)).build();
        final FormBodyPart p2 = FormBodyPartBuilder.create(
                "field2",
                new FileBody(tmpfile, ContentType.create("text/plain", "ANSI_X3.4-1968"), "test-file")).build();
        @SuppressWarnings("resource")
        final FormBodyPart p3 = FormBodyPartBuilder.create(
                "field3",
                new InputStreamBody(new FileInputStream(tmpfile), "file.tmp")).build();
        final HttpRFC6532Multipart multipart = new HttpRFC6532Multipart(null, "foo",
                Arrays.asList(p1, p2, p3));

        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        multipart.writeTo(out);
        out.close();

        final String expected =
            "--foo\r\n" +
            "Content-Disposition: form-data; name=\"field1\u0414\"; " +
                "filename=\"" + tmpfile.getName() + "\"\r\n" +
            "Content-Type: application/octet-stream\r\n" +
            "Content-Transfer-Encoding: binary\r\n" +
            "\r\n" +
            "some random whatever\r\n" +
            "--foo\r\n" +
            "Content-Disposition: form-data; name=\"field2\"; " +
                "filename=\"test-file\"\r\n" +
            "Content-Type: text/plain; charset=US-ASCII\r\n" +
            "Content-Transfer-Encoding: binary\r\n" +
            "\r\n" +
            "some random whatever\r\n" +
            "--foo\r\n" +
            "Content-Disposition: form-data; name=\"field3\"; " +
                "filename=\"file.tmp\"\r\n" +
            "Content-Type: application/octet-stream\r\n" +
            "Content-Transfer-Encoding: binary\r\n" +
            "\r\n" +
            "some random whatever\r\n" +
            "--foo--\r\n";
        final String s = out.toString("UTF-8");
        Assert.assertEquals(expected, s);
        Assert.assertEquals(-1, multipart.getTotalLength());
    }

    private static final int SWISS_GERMAN_HELLO [] = {
        0x47, 0x72, 0xFC, 0x65, 0x7A, 0x69, 0x5F, 0x7A, 0xE4, 0x6D, 0xE4
    };

    private static final int RUSSIAN_HELLO [] = {
        0x412, 0x441, 0x435, 0x43C, 0x5F, 0x43F, 0x440, 0x438,
        0x432, 0x435, 0x442
    };

    private static String constructString(final int [] unicodeChars) {
        final StringBuilder buffer = new StringBuilder();
        if (unicodeChars != null) {
            for (final int unicodeChar : unicodeChars) {
                buffer.append((char)unicodeChar);
            }
        }
        return buffer.toString();
    }

    @Test
    public void testMultipartFormBrowserCompatibleNonASCIIHeaders() throws Exception {
        final String s1 = constructString(SWISS_GERMAN_HELLO);
        final String s2 = constructString(RUSSIAN_HELLO);

        tmpfile = File.createTempFile("tmp", ".bin");
        final Writer writer = new FileWriter(tmpfile);
        try {
            writer.append("some random whatever");
        } finally {
            writer.close();
        }

        @SuppressWarnings("resource")
        final FormBodyPart p1 = FormBodyPartBuilder.create(
                "field1",
                new InputStreamBody(new FileInputStream(tmpfile), s1 + ".tmp")).build();
        @SuppressWarnings("resource")
        final FormBodyPart p2 = FormBodyPartBuilder.create(
                "field2",
                new InputStreamBody(new FileInputStream(tmpfile), s2 + ".tmp")).build();
        final HttpBrowserCompatibleMultipart multipart = new HttpBrowserCompatibleMultipart(
                Consts.UTF_8, "foo",
                Arrays.asList(p1, p2));

        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        multipart.writeTo(out);
        out.close();

        final String expected =
            "--foo\r\n" +
            "Content-Disposition: form-data; name=\"field1\"; " +
                "filename=\"" + s1 + ".tmp\"\r\n" +
            "Content-Type: application/octet-stream\r\n" +
            "\r\n" +
            "some random whatever\r\n" +
            "--foo\r\n" +
            "Content-Disposition: form-data; name=\"field2\"; " +
                "filename=\"" + s2 + ".tmp\"\r\n" +
            "Content-Type: application/octet-stream\r\n" +
            "\r\n" +
            "some random whatever\r\n" +
            "--foo--\r\n";
        final String s = out.toString("UTF-8");
        Assert.assertEquals(expected, s);
        Assert.assertEquals(-1, multipart.getTotalLength());
    }

    @Test
    public void testMultipartFormStringPartsMultiCharsets() throws Exception {
        final String s1 = constructString(SWISS_GERMAN_HELLO);
        final String s2 = constructString(RUSSIAN_HELLO);

        final FormBodyPart p1 = FormBodyPartBuilder.create(
                "field1",
                new StringBody(s1, ContentType.create("text/plain", Charset.forName("ISO-8859-1")))).build();
        final FormBodyPart p2 = FormBodyPartBuilder.create(
                "field2",
                new StringBody(s2, ContentType.create("text/plain", Charset.forName("KOI8-R")))).build();
        final HttpStrictMultipart multipart = new HttpStrictMultipart(null, "foo",
                Arrays.asList(p1, p2));

        final ByteArrayOutputStream out1 = new ByteArrayOutputStream();
        multipart.writeTo(out1);
        out1.close();

        final ByteArrayOutputStream out2 = new ByteArrayOutputStream();

        out2.write((
            "--foo\r\n" +
            "Content-Disposition: form-data; name=\"field1\"\r\n" +
            "Content-Type: text/plain; charset=ISO-8859-1\r\n" +
            "Content-Transfer-Encoding: 8bit\r\n" +
            "\r\n").getBytes(Consts.ASCII));
        out2.write(s1.getBytes(Consts.ISO_8859_1));
        out2.write(("\r\n" +
            "--foo\r\n" +
            "Content-Disposition: form-data; name=\"field2\"\r\n" +
            "Content-Type: text/plain; charset=KOI8-R\r\n" +
            "Content-Transfer-Encoding: 8bit\r\n" +
            "\r\n").getBytes(Consts.ASCII));
        out2.write(s2.getBytes(Charset.forName("KOI8-R")));
        out2.write(("\r\n" +
            "--foo--\r\n").getBytes(Consts.ASCII));
        out2.close();

        final byte[] actual = out1.toByteArray();
        final byte[] expected = out2.toByteArray();

        Assert.assertEquals(expected.length, actual.length);
        for (int i = 0; i < actual.length; i++) {
            Assert.assertEquals(expected[i], actual[i]);
        }
        Assert.assertEquals(expected.length, multipart.getTotalLength());
    }

}


text:
"""
Access to cpio archive representation via function
Modules for various archive formats can provide a function with a common name.
"""

from stat import S_IFDIR, S_IFREG, S_IFLNK, S_IFIFO, S_IFCHR, S_IFBLK, S_IFSOCK, S_IFMT

from . import CacheAttr
from .data import Bytes, Int, MTime, Pad, Tail, pad, PString
from .named import VarStruct
from .enum import Enum

Number = Int(base=16, length=8)

class FileType(Enum, int):
    """
    File type as obtained from mode bits
    """
    Directory, File, Symlink = S_IFDIR, S_IFREG, S_IFLNK
    FIFO, Cdev, Bdev, Socket = S_IFIFO, S_IFCHR, S_IFBLK, S_IFSOCK

class Cpio(VarStruct):
    """
    Representation of cpio archive
    Iterator yields archive members.
    Each member contains all subsequent members in its tail.
    """
    class magic(Enum, Bytes, length=6):
        """ Magic number for two cpio formats """
        new, crc = b'070701', b'070702'
    inode, mode, uid, gid, nlink = 5*(Number,)
    mtime = MTime(base=16, length=8)
    filesize, major, minor, rmajor, rminor = 5*(Number,)
    name = PString(base=16, length=8)
    check = Number
    pad = Pad(align=4)
    tail = Tail

    @CacheAttr
    def filetype(self):
        """ Extract file type from mode bits """
        return FileType(S_IFMT(self.mode))

    def isreg(self):
        """ Test for regular file type """
        return self.filetype == FileType.File

    @CacheAttr
    def contents(self):
        """ Slice payload to exclude subsequent content """
        return self.tail[:self.filesize]

    def __iter__(self):
        align = type(self).pad.align
        while len(self.tail) > 0:
            yield self
            size = self.filesize
            self = type(self)(self.tail, size + pad(size, align))
        assert str(self.name) == 'TRAILER!!!', "Truncated archive"

def archive(mem):
    """ Instantiate Cpio on specified memoryview """
    return Cpio(mem)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Ann. R. bot. Gdns Peradeniya 7(2): 135 (1920)

#### Original name
Calonectria oodes Petch

### Remarks
null


text:
class UsersController < ApplicationController
  before_filter :authenticate_user!, :except => [:show]

  def index
    redirect_to root_url
  end

  def show
    @user = User.find(params[:id])
    @reviews = @user.reviews
    @rides = @user.rides
    if @reviews.length == 0
      @reviews = nil
    end
    if @rides.length == 0
      @rides = nil
    end
    @review = Review.new
  end

  def profile
    @user = current_user
  end

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

    if @user.update_attributes(params[:user])
      redirect_to :action => "show", :id => params[:id]
    else
      redirect_to root_url
    end
  end

end


text:
from setuptools import setup

setup(
    name='ts-pip-plugin',

    packages=['ts_pip_plugin'],

    version='1.0.2',

    description='Scans a Python project for all installed pip modules and posts the scan information to the TrustSource service or writes it to disc',

    author='EACG GmbH',

    license='ASL-2.0',

    url='https://github.com/trustsource/ts-pip-plugin.git',

    download_url='',

    keywords=['scanning', 'dependencies', 'modules', 'compliance', 'TrustSource'],

    classifiers=[],

    install_requires=['ts-python-client', 'importlib-metadata'],

    scripts=['ts-pip-plugin'],

    entry_points={
        'console_scripts': ['ts-pip-plugin=ts_pip_plugin.cli:main'],
    }
)


text:
import csv
import gensim
import logging, bz2
import nltk
from collections import defaultdict
import json

#logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)

def recursive_node_to_dict(node):
    result = {
        'name': node.name,
    }
    children = [recursive_node_to_dict(c) for c in node.get_children()]
    if children:
        result['children'] = children
    return result

word_freq = {}
wordlist = []
tweets = []
with open('twits.csv', 'rb') as csvfile:
    twitsreader = csv.reader(csvfile, delimiter=',', quotechar='|')
    for row in twitsreader:
        stoplist = set('for a of the and to in is rt t.co / \\'.split())
        row = [word for word in str(row).lower().split() if word not in stoplist]
        for n in ('\'','rt','"','[',']','@','!', 'http',':','#','/','t.co',',','&',';',',','\\',')','(','.','?', '-'	): #remove meaningless characters
            row = str(row).replace(n,'')
        row=row.lower()
        tokenize = nltk.word_tokenize(row)
        tweets.append(tokenize)
        words = row.split()
        for word in words: #create wordlist for id2word dictionary mapping
			word = word.strip()
			word = unicode(word, "utf-8")
			word = nltk.word_tokenize(word)
			wordlist.append(word)
'''
for word in wordlist:
	word_freq = {i:words.count(i) for i in set(words)}

print word_freq
'''

id2word = gensim.corpora.Dictionary(wordlist)
corpus = [id2word.doc2bow(tweet) for tweet in tweets]
#print id2word
lda = gensim.models.LdaModel(corpus, num_topics = 10,id2word=id2word)

topics= lda.show_topics(topics=-1)
lda.save('lda.csv')
#print topics

clean_topics = []
probs = []
vals = []
json = '{ "name": "parent", "children": [ '
topicDict = defaultdict(list)
topicDict['names'].append('parent')
counter = 0
for topic in topics:
	counter = counter +1
	tempTopic = []
	tempProbs = []
	topic = topic.split(' + ')
	json = json + '{"name" : "topic' + str(counter) + '", "children": [ '
	topicDict['children'].append('topic' + str(counter))
	for word in topic:
		val = word.split('*')
		tempProbs.append(val[0])
		tempTopic.append(val[1])
		json = json + '{"name" : "' + val[1] + '", "size": ' + val[0] + '}, '
		topicDict['topic' + str(counter)].append((val[1],val[0]))
	json = json[:len(json)-2] + ']},'
	probs.append(tempProbs)
	clean_topics.append(tempTopic)

json = json[:len(json)-1] + ']}'
print json

json_string = json.dumps(topicDict)
f = open('topics.json', 'w')
print >> f,json_string
f.close()

with open('topics.csv', 'wb') as acsv:
    w = csv.writer(acsv)
    #w.writerow(('Tweet'))
    for topic in clean_topics:
        w.writerow(topic)

with open('probs.csv', 'wb') as acsv:
    w = csv.writer(acsv)
    #w.writerow(('Tweet'))
    for row in probs:
        w.writerow(row)


text:
layout: post
title: "Jenius Engineer reading list #79"
author: dedenf
tags:
    - news
    - jenius

categories:
    - readinglist
    - engineer
published: true
---

- [Zammad -- web based open source helpdesk/customer support system](https://github.com/zammad/zammad)
- [Writing GraphQL queries in native Ruby = Love ❤](https://www.contentful.com/blog/2018/11/20/graphql-ruby-love-backend-developer/)
- [🛁 Clean Code concepts adapted for Ruby](https://github.com/uohzxela/clean-code-ruby)
- [The Benefits of Materialized Views (and how to use them in your Ruby on Rails project)](https://medium.com/@rebo_dood/the-benefits-of-materialized-views-and-how-to-use-them-in-your-ruby-on-rails-project-4ac1b5432881)
- [What Is MJIT in Ruby 2.6 & How Does It Work?](https://www.rubyguides.com/2018/11/ruby-mjit/?tl_inbound=1&tl_target_all=1&tl_form_type=1&tl_period_type=1)
- [No more hassle with Rails secret management](https://developer.epages.com/blog/coding/no-more-hassle-with-rails-secret-management/)


text:
<?php

/**
 * CodeFaqs 2013
 *
 * @author Marc Morera
 * @author Miguel Angel Rios
 */

namespace CodeFaqs\SecureBundle\Security\User\Provider;

use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\HttpFoundation\Session\Session;
use \TwitterOAuth;
use FOS\UserBundle\Doctrine\UserManager;

class TwitterProvider implements UserProviderInterface
{
    /**
     * @var \Twitter
     */
    protected $twitterOAuth;

    /**
     * @var UserManager
     */
    protected $userManager;

    /**
     * @var Session
     */
    protected $session;

    /**
     * Construct method
     *
     * @param TwitterOAuth $twitterOAuth
     * @param UserManager  $userManager
     * @param Session      $session
     */
    public function __construct(TwitterOAuth $twitterOAuth, UserManager $userManager, Session $session)
    {
        $this->twitterOAuth = $twitterOAuth;
        $this->userManager = $userManager;
        $this->session = $session;
    }

    public function supportsClass($class)
    {
        return $this->userManager->supportsClass($class);
    }

    /**
     * Find User given a Twitter id
     *
     * @param String $username Username
     *
     * @return User
     */
    public function findUserByUsername($username)
    {
        return $this->userManager->findUserBy(array('username' => $username));
    }

    /**
     * Given a username, load user
     *
     * @param String $username Username
     *
     * @return Mixed
     */
    public function loadUserByUsername($username)
    {
        $user = $this->findUserByUsername($username);

         $this->twitterOAuth->setOAuthToken( $this->session->get('access_token') , $this->session->get('access_token_secret'));

        try {
             $info = $this->twitterOAuth->get('account/verify_credentials');
        } catch (\Exception $e) {
             $info = null;
        }

        if (!empty($info)) {

            /**
             * Non existing user. Creating new document
             */
            if (empty($user)) {
                $user = $this->userManager->createUser();
                $user->createFromTwitter();
                $user->setEnabled(true);
                $user->setPassword('');
            }

            $username = $info->screen_name;
            $user   ->setTwitterID($info->id)
                    ->setTwitterUsername($username)
                    ->setUsername($username)
                    ->setEmail('')
                    ->setTwitterPhoto($info->profile_image_url_https)
                    ->setTwitterLocation($info->location)
                    ->setTwitterName($info->name);

            $this->userManager->updateUser($user);
        }

        if (empty($user)) {
            throw new UsernameNotFoundException('The user is not authenticated on twitter');
        }

        return $user;

    }

    public function refreshUser(UserInterface $user)
    {
        if (!$this->supportsClass(get_class($user)) || !$user->getTwitterID()) {
            throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));
        }

        return $this->loadUserByUsername($user->getTwitterID());
    }
}


text:
#include "kernel/abstract.h"
#include "library/constants.h"
#include "library/tactic/tactic.h"
#include "library/tactic/elaborate.h"
#include "library/tactic/expr_to_tactic.h"

namespace lean {
expr mk_assert_tactic_expr(name const & id, expr const & e) {
    return mk_app(mk_constant(get_tactic_assert_hypothesis_name()),
                  mk_constant(id), e);
}

tactic assert_tactic(elaborate_fn const & elab, name const & id, expr const & e) {
    return tactic01([=](environment const & env, io_state const & ios, proof_state const & s) {
            proof_state new_s = s;
            goals const & gs  = new_s.get_goals();
            if (!gs) {
                throw_no_goal_if_enabled(s);
                return none_proof_state();
            }
            bool report_unassigned = true;
            if (auto new_e = elaborate_with_respect_to(env, ios, elab, new_s, e, none_expr(), report_unassigned)) {
                goals const & gs   = new_s.get_goals();
                goal const & g     = head(gs);
                if (g.find_hyp(id)) {
                    throw_tactic_exception_if_enabled(s, sstream() << "invalid 'assert' tactic, goal already has a "
                                                      "hypothesis named '" << id << "'");
                    // goal already has a hypothesis named id
                    return none_proof_state();
                }
                name_generator ngen = new_s.get_ngen();
                expr new_meta1      = g.mk_meta(ngen.next(), *new_e);
                goal new_goal1(new_meta1, *new_e);
                expr new_local      = mk_local(ngen.next(), id, *new_e, binder_info());
                buffer<expr> hyps;
                g.get_hyps(hyps);
                hyps.push_back(new_local);
                expr new_mvar2      = mk_metavar(ngen.next(), Pi(hyps, g.get_type()));
                hyps.pop_back();
                expr new_meta2_core = mk_app(new_mvar2, hyps);
                expr new_meta2      = mk_app(new_meta2_core, new_local);
                goal new_goal2(new_meta2, g.get_type());
                substitution new_subst = new_s.get_subst();
                assign(new_subst, g, mk_app(new_meta2_core, new_meta1));
                return some_proof_state(proof_state(new_s, cons(new_goal1, cons(new_goal2, tail(gs))), new_subst, ngen));
            }
            return none_proof_state();
        });
}

void initialize_assert_tactic() {
    register_tac(get_tactic_assert_hypothesis_name(),
                 [](type_checker &, elaborate_fn const & fn, expr const & e, pos_info_provider const *) {
                     name id = tactic_expr_to_id(app_arg(app_fn(e)), "invalid 'assert' tactic, argument must be an identifier");
                     check_tactic_expr(app_arg(e), "invalid 'assert' tactic, argument must be an expression");
                     return assert_tactic(fn, id, get_tactic_expr_expr(app_arg(e)));
                 });
}
void finalize_assert_tactic() {
}
}


text:
package net.gotev.sipservice;

public interface SipServiceConstants {

    /*
     * Intent Actions for Sip Service
     */
    String ACTION_RESTART_SIP_STACK = "restartSipStack";
    String ACTION_SET_ACCOUNT = "setAccount";
    String ACTION_REMOVE_ACCOUNT = "removeAccount";
    String ACTION_MAKE_CALL = "makeCall";
    String ACTION_HANG_UP_CALL = "hangUpCall";
    String ACTION_HANG_UP_CALLS = "hangUpCalls";
    String ACTION_HOLD_CALLS = "holdCalls";
    String ACTION_GET_CALL_STATUS = "getCallStatus";
    String ACTION_SEND_DTMF = "sendDtmf";
    String ACTION_ACCEPT_INCOMING_CALL = "acceptIncomingCall";
    String ACTION_DECLINE_INCOMING_CALL = "declineIncomingCall";
    String ACTION_SET_HOLD = "callSetHold";
    String ACTION_SET_MUTE = "callSetMute";
    String ACTION_TOGGLE_HOLD = "callToggleHold";
    String ACTION_TOGGLE_MUTE = "callToggleMute";
    String ACTION_TRANSFER_CALL = "callTransfer";
    String ACTION_ATTENDED_TRANSFER_CALL = "callAttendedTransfer";
    String ACTION_GET_CODEC_PRIORITIES = "codecPriorities";
    String ACTION_SET_CODEC_PRIORITIES = "setCodecPriorities";
    String ACTION_GET_REGISTRATION_STATUS = "getRegistrationStatus";
    String ACTION_REFRESH_REGISTRATION = "refreshRegistration";
    String ACTION_SET_DND = "setDND";
    String ACTION_SET_INCOMING_VIDEO = "setIncomingVideo";
    String ACTION_SET_SELF_VIDEO_ORIENTATION = "setSelfVideoOrientation";
    String ACTION_SET_VIDEO_MUTE = "setVideoMute";
    String ACTION_START_VIDEO_PREVIEW = "startVideoPreview";
    String ACTION_STOP_VIDEO_PREVIEW = "stopVideoPreview";
    String ACTION_SWITCH_VIDEO_CAPTURE_DEVICE = "switchVideoCaptureDevice";
    String ACTION_MAKE_DIRECT_CALL = "makeDirectCall";
    String ACTION_RECONNECT_CALL = "reconnectCall";
    String ACTION_MAKE_SILENT_CALL = "makeSilentCall";

    /*
     * Generic Parameters
     */
    String PARAM_ACCOUNT_DATA = "accountData";
    String PARAM_ACCOUNT_ID = "accountID";
    String PARAM_NUMBER = "number";
    String PARAM_CALL_ID = "callId";
    String PARAM_CALL_ID_DEST = "callIdDest";
    String PARAM_DTMF = "dtmf";
    String PARAM_HOLD = "hold";
    String PARAM_MUTE = "mute";
    String PARAM_CODEC_PRIORITIES = "codecPriorities";
    String PARAM_REG_EXP_TIMEOUT = "regExpTimeout";
    String PARAM_REG_CONTACT_PARAMS = "regContactParams";
    String PARAM_DND = "dnd";
    String PARAM_IS_VIDEO = "isVideo";
    String PARAM_IS_VIDEO_CONF = "isVideoConference";
    String PARAM_SURFACE = "surface";
    String PARAM_ORIENTATION = "orientation";
    String PARAM_GUEST_NAME = "guestName";
    String PARAM_DIRECT_CALL_URI = "sipUri";
    String PARAM_DIRECT_CALL_SIP_SERVER = "sipServer";
    String PARAM_DIRECT_CALL_TRANSPORT = "directTransport";
    String PARAM_IS_TRANSFER = "isTransfer";

    /**
     * Specific Parameters passed in the broadcast intents.
     */
    String PARAM_REGISTRATION_CODE = "registrationCode";
    String PARAM_REMOTE_URI = "remoteUri";
    String PARAM_DISPLAY_NAME = "displayName";
    String PARAM_CALL_STATE = "callState";
    String PARAM_CALL_STATUS = "callStatus";
    String PARAM_CONNECT_TIMESTAMP = "connectTimestamp";
    String PARAM_STACK_STARTED = "stackStarted";
    String PARAM_CODEC_PRIORITIES_LIST = "codecPrioritiesList";
    String PARAM_MEDIA_STATE_KEY = "mediaStateKey";
    String PARAM_MEDIA_STATE_VALUE = "mediaStateValue";
    String PARAM_VIDEO_MUTE = "videoMute";
    String PARAM_SUCCESS = "success";
    String PARAM_INCOMING_VIDEO_WIDTH = "incomingVideoWidth";
    String PARAM_INCOMING_VIDEO_HEIGHT = "incomingVideoHeight";
    String PARAM_CALL_RECONNECTION_STATE = "callReconnectionState";
    String PARAM_SILENT_CALL_STATUS = "silentCallStatus";

    /**
     * Specific Parameters passed in the broadcast intents for call stats.
     */
    String PARAM_CALL_STATS_DURATION = "callStatsDuration";
    String PARAM_CALL_STATS_AUDIO_CODEC = "callStatsAudioCodec";
    String PARAM_CALL_STATS_CALL_STATUS = "callStatsCallStatus";
    String PARAM_CALL_STATS_RX_STREAM = "callStatsRxStream";
    String PARAM_CALL_STATS_TX_STREAM = "callStatsTxStream";

    /**
     * Video Configuration Params
     */

    int FRONT_CAMERA_CAPTURE_DEVICE = 1;    // Front Camera idx
    int BACK_CAMERA_CAPTURE_DEVICE = 2;     // Back Camera idx
    int DEFAULT_RENDER_DEVICE = 0;          // OpenGL Render
    String OPENH264_CODEC_ID = "H264/97";
    int H264_DEF_WIDTH = 640;
    int H264_DEF_HEIGHT = 360;
    String ANDROID_H264_CODEC_ID = "H264/99";
    String ANDROID_VP8_CODEC_ID = "VP8/103";
    String ANDROID_VP9_CODEC_ID = "VP9/106";

    /**
     * Janus Bridge call specific parameters.
     */
    String PROFILE_LEVEL_ID_HEADER = "profile-level-id";
    String PROFILE_LEVEL_ID_LOCAL = "42e01e";
    String PROFILE_LEVEL_ID_JANUS_BRIDGE = "42e01f";

    /**
     * Generic Constants
     */
    int DELAYED_JOB_DEFAULT_DELAY = 5000;

    /**
     * SIP DEFAULT PORTS
     */
    int DEFAULT_SIP_PORT = 5060;

    /**
     * PJSIP TLS VERIFY PEER ERROR
     */
    int PJSIP_TLS_ECERTVERIF = 171173;
}


text:
package net.michael_j.ddd.application.listener;

import com.google.common.eventbus.Subscribe;
import net.michael_j.ddd.core.user.event.UserEvent;
import net.michael_j.ddd.core.user.event.UserEventPublisher;
import net.michael_j.ddd.core.user.event.UserEventType;
import net.michael_j.ddd.infrastructure.email.EmailSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Created by Michael Jiang on 16/1/12.
 */
@Service
public class UserRegisterListener {
    @Resource
    private EmailSender emailSender;

    @Autowired
    public UserRegisterListener(UserEventPublisher userEventPublisher) {
        userEventPublisher.register(this);
    }

    @Subscribe
    public void listenUserRegisterEvent(UserEvent userEvent) {
        if (userEvent.getType().equals(UserEventType.REGISTER)) {
            emailSender.send(userEvent.getName(), "welcome to join us!");
        }
    }
}


text:
package org.apache.bookkeeper.bookie.storage.directentrylogger;

import static org.apache.bookkeeper.bookie.storage.EntryLogTestUtils.assertEntryEquals;
import static org.apache.bookkeeper.bookie.storage.EntryLogTestUtils.logIdFromLocation;
import static org.apache.bookkeeper.bookie.storage.EntryLogTestUtils.makeEntry;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;

import com.google.common.util.concurrent.MoreExecutors;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import lombok.extern.slf4j.Slf4j;
import org.apache.bookkeeper.bookie.EntryLogMetadata;
import org.apache.bookkeeper.bookie.storage.EntryLogger;
import org.apache.bookkeeper.bookie.storage.MockEntryLogIds;
import org.apache.bookkeeper.common.util.nativeio.NativeIOImpl;
import org.apache.bookkeeper.slogger.Slogger;
import org.apache.bookkeeper.stats.NullStatsLogger;
import org.apache.bookkeeper.test.TmpDirs;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;

/**
 * TestDirectEntryLogger.
 */
@Slf4j
public class TestDirectEntryLogger {
    private final Slogger slog = Slogger.CONSOLE;

    private static final long ledgerId1 = 1234;

    private final TmpDirs tmpDirs = new TmpDirs();

    @After
    public void cleanup() throws Exception {
        tmpDirs.cleanup();
    }

    @Test
    public void testLogRolling() throws Exception {
        File ledgerDir = tmpDirs.createNew("logRolling", "ledgers");
        File curDir = new File(ledgerDir, "current");
        curDir.mkdirs();

        ByteBuf e1 = makeEntry(ledgerId1, 1L, 4000);
        ByteBuf e2 = makeEntry(ledgerId1, 2L, 4000);
        ByteBuf e3 = makeEntry(ledgerId1, 3L, 4000);

        try (EntryLogger elog = new DirectEntryLogger(
                     curDir, new MockEntryLogIds(),
                     new NativeIOImpl(),
                     ByteBufAllocator.DEFAULT,
                     MoreExecutors.newDirectExecutorService(),
                     MoreExecutors.newDirectExecutorService(),
                     9000, // max file size (header + size of one entry)
                     10 * 1024 * 1024, // max sane entry size
                     1024 * 1024, // total write buffer size
                     1024 * 1024, // total read buffer size
                     64 * 1024, // read buffer size
                     1, // numReadThreads
                     300, // max fd cache time in seconds
                     slog, NullStatsLogger.INSTANCE)) {
            long loc1 = elog.addEntry(ledgerId1, e1.slice());
            int logId1 = logIdFromLocation(loc1);
            assertThat(logId1, equalTo(1));

            long loc2 = elog.addEntry(ledgerId1, e2.slice());
            int logId2 = logIdFromLocation(loc2);
            assertThat(logId2, equalTo(2));

            long loc3 = elog.addEntry(ledgerId1, e3.slice());
            int logId3 = logIdFromLocation(loc3);
            assertThat(logId3, equalTo(3));
        }
    }

    @Test
    public void testReadLog() throws Exception {
        File ledgerDir = tmpDirs.createNew("logRolling", "ledgers");
        File curDir = new File(ledgerDir, "current");
        curDir.mkdirs();

        ByteBuf e1 = makeEntry(ledgerId1, 1L, 100);
        ByteBuf e2 = makeEntry(ledgerId1, 2L, 100);
        ByteBuf e3 = makeEntry(ledgerId1, 3L, 100);

        try (EntryLogger elog = new DirectEntryLogger(
                     curDir, new MockEntryLogIds(),
                     new NativeIOImpl(),
                     ByteBufAllocator.DEFAULT,
                     MoreExecutors.newDirectExecutorService(),
                     MoreExecutors.newDirectExecutorService(),
                     200000, // max file size (header + size of one entry)
                     10 * 1024 * 1024, // max sane entry size
                     1024 * 1024, // total write buffer size
                     1024 * 1024, // total read buffer size
                     64 * 1024, // read buffer size
                     1, // numReadThreads
                     300, // max fd cache time in seconds
                     slog, NullStatsLogger.INSTANCE)) {
            long loc1 = elog.addEntry(ledgerId1, e1.slice());
            long loc2 = elog.addEntry(ledgerId1, e2.slice());
            elog.flush();

            ByteBuf e1read = elog.readEntry(ledgerId1, 1L, loc1);
            ByteBuf e2read = elog.readEntry(ledgerId1, 2L, loc2);
            assertEntryEquals(e1read, e1);
            assertEntryEquals(e2read, e2);
            e1read.release();
            e2read.release();

            long loc3 = elog.addEntry(ledgerId1, e3.slice());
            elog.flush();

            ByteBuf e3read = elog.readEntry(ledgerId1, 3L, loc3);
            assertEntryEquals(e3read, e3);
            e3read.release();
        }
    }

    @Test
    public void testLogReaderCleanup() throws Exception {
        File ledgerDir = tmpDirs.createNew("logRolling", "ledgers");
        File curDir = new File(ledgerDir, "current");
        curDir.mkdirs();

        final int entrySize = Buffer.ALIGNMENT;
        final int maxFileSize = Header.EMPTY_HEADER.length + entrySize;
        final int maxCachedReaders = 16;

        AtomicInteger outstandingReaders = new AtomicInteger(0);
        EntryLogger elog = new DirectEntryLogger(
                     curDir, new MockEntryLogIds(),
                     new NativeIOImpl(),
                     ByteBufAllocator.DEFAULT,
                     MoreExecutors.newDirectExecutorService(),
                     MoreExecutors.newDirectExecutorService(),
                     maxFileSize,
                     10 * 1024 * 1024, // max sane entry size
                     1024 * 1024, // total write buffer size
                     maxCachedReaders * maxFileSize, // total read buffer size
                     maxFileSize, // read buffer size
                     1, // numReadThreads
                     300, // max fd cache time in seconds
                     slog, NullStatsLogger.INSTANCE) {
                @Override
                LogReader newDirectReader(int logId) throws IOException {
                    outstandingReaders.incrementAndGet();
                    return new DirectReader(logId, logFilename(curDir, logId), ByteBufAllocator.DEFAULT,
                                            new NativeIOImpl(), Buffer.ALIGNMENT, 10 * 1024 * 1024,
                                            NullStatsLogger.INSTANCE.getOpStatsLogger("")) {
                        @Override
                        public void close() throws IOException {
                            super.close();
                            outstandingReaders.decrementAndGet();
                        }
                    };
                }
            };
        try {
            List<Long> locations = new ArrayList<>();
            // `+ 1` is not a typo: create one more log file than the max number of o cached readers
            for (int i = 0; i < maxCachedReaders + 1; i++) {
                ByteBuf e = makeEntry(ledgerId1, i, entrySize);
                long loc = elog.addEntry(ledgerId1, e.slice());
                locations.add(loc);
            }
            elog.flush();
            for (Long loc : locations) {
                elog.readEntry(loc).release();
            }
            assertThat(outstandingReaders.get(), equalTo(maxCachedReaders));
        } finally {
            elog.close();
        }
        assertThat(outstandingReaders.get(), equalTo(0));
    }

    @Test
    public void testReadMetadataAndScan() throws Exception {
        File ledgerDir = tmpDirs.createNew("directCanReadAndScanMeta", "ledgers");
        File curDir = new File(ledgerDir, "current");
        curDir.mkdirs();

        long ledgerId1 = 1L;
        long ledgerId2 = 2L;

        ByteBuf e1 = makeEntry(ledgerId1, 1L, 1000);
        ByteBuf e2 = makeEntry(ledgerId2, 2L, 2000);
        ByteBuf e3 = makeEntry(ledgerId1, 3L, 3000);

        long loc1, loc2, loc3;
        try (DirectEntryLogger elog = new DirectEntryLogger(
                     curDir, new MockEntryLogIds(),
                     new NativeIOImpl(),
                     ByteBufAllocator.DEFAULT,
                     MoreExecutors.newDirectExecutorService(),
                     MoreExecutors.newDirectExecutorService(),
                     2 << 16, // max file size
                     10 * 1024 * 1024, // max sane entry size
                     1024 * 1024, // total write buffer size
                     1024 * 1024, // total read buffer size
                     64 * 1024, // read buffer size
                     1, // numReadThreads
                     300, // max fd cache time in seconds
                     slog, NullStatsLogger.INSTANCE)) {
            loc1 = elog.addEntry(ledgerId1, e1);
            loc2 = elog.addEntry(ledgerId2, e2);
            loc3 = elog.addEntry(ledgerId1, e3);
        }

        try (DirectEntryLogger elog = new DirectEntryLogger(
                     curDir, new MockEntryLogIds(),
                     new NativeIOImpl(),
                     ByteBufAllocator.DEFAULT,
                     MoreExecutors.newDirectExecutorService(),
                     MoreExecutors.newDirectExecutorService(),
                     2 << 16, // max file size
                     10 * 1024 * 1024, // max sane entry size
                     1024 * 1024, // total write buffer size
                     1024 * 1024, // total read buffer size
                     64 * 1024, // read buffer size
                     1, // numReadThreads
                     300, // max fd cache time in seconds
                     slog, NullStatsLogger.INSTANCE)) {
            int logId = logIdFromLocation(loc1);
            assertThat(logId, equalTo(logIdFromLocation(loc2)));
            assertThat(logId, equalTo(logIdFromLocation(loc3)));

            EntryLogMetadata metaRead = elog.readEntryLogIndex(logId);
            assertThat(metaRead.getEntryLogId(), equalTo((long) logId));
            assertThat(metaRead.getTotalSize(), equalTo(1000L + 2000 + 3000 + (Integer.BYTES * 3)));
            assertThat(metaRead.getRemainingSize(), equalTo(metaRead.getTotalSize()));
            assertThat(metaRead.getLedgersMap().get(ledgerId1), equalTo(1000L + 3000L + (Integer.BYTES * 2)));
            assertThat(metaRead.getLedgersMap().get(ledgerId2), equalTo(2000L + Integer.BYTES));

            EntryLogMetadata metaScan = elog.scanEntryLogMetadata(logId, null);
            assertThat(metaScan.getEntryLogId(), equalTo((long) logId));
            assertThat(metaScan.getTotalSize(), equalTo(1000L + 2000 + 3000 + (Integer.BYTES * 3)));
            assertThat(metaScan.getRemainingSize(), equalTo(metaScan.getTotalSize()));
            assertThat(metaScan.getLedgersMap().get(ledgerId1), equalTo(1000L + 3000L + (Integer.BYTES * 2)));
            assertThat(metaScan.getLedgersMap().get(ledgerId2), equalTo(2000L + Integer.BYTES));
        }
    }

    @Test
    public void testMetadataFallback() throws Exception {
        File ledgerDir = tmpDirs.createNew("directMetaFallback", "ledgers");
        File curDir = new File(ledgerDir, "current");
        curDir.mkdirs();

        long ledgerId1 = 1L;
        long ledgerId2 = 2L;

        ByteBuf e1 = makeEntry(ledgerId1, 1L, 1000);
        ByteBuf e2 = makeEntry(ledgerId2, 2L, 2000);
        ByteBuf e3 = makeEntry(ledgerId1, 3L, 3000);

        int maxFileSize = 1000 + 2000 + 3000 + (Integer.BYTES * 3) + 4096;
        long loc1, loc2, loc3;
        try (DirectEntryLogger writer = new DirectEntryLogger(
                     curDir, new MockEntryLogIds(),
                     new NativeIOImpl(),
                     ByteBufAllocator.DEFAULT,
                     MoreExecutors.newDirectExecutorService(),
                     MoreExecutors.newDirectExecutorService(),
                     2 << 16, // max file size
                     10 * 1024 * 1024, // max sane entry size
                     1024 * 1024, // total write buffer size
                     1024 * 1024, // total read buffer size
                     64 * 1024, // read buffer size
                     1, // numReadThreads
                     300, // max fd cache time in seconds
                     slog, NullStatsLogger.INSTANCE)) {
            loc1 = writer.addEntry(ledgerId1, e1);
            loc2 = writer.addEntry(ledgerId2, e2);
            loc3 = writer.addEntry(ledgerId1, e3);
            writer.flush();

            try (DirectEntryLogger reader = new DirectEntryLogger(
                         curDir, new MockEntryLogIds(),
                         new NativeIOImpl(),
                         ByteBufAllocator.DEFAULT,
                         MoreExecutors.newDirectExecutorService(),
                         MoreExecutors.newDirectExecutorService(),
                         2 << 16, // max file size
                         10 * 1024 * 1024, // max sane entry size
                         1024 * 1024, // total write buffer size
                         1024 * 1024, // total read buffer size
                         64 * 1024, // read buffer size
                         1, // numReadThreads
                         300, // max fd cache time in seconds
                         slog, NullStatsLogger.INSTANCE)) {
                int logId = logIdFromLocation(loc1);
                try {
                    reader.readEntryLogIndex(logId);
                    Assert.fail("Shouldn't be there");
                } catch (IOException ioe) {
                    // expected
                }

                EntryLogMetadata metaRead = reader.getEntryLogMetadata(logId); // should fail read, fallback to scan
                assertThat(metaRead.getEntryLogId(), equalTo((long) logId));
                assertThat(metaRead.getTotalSize(), equalTo(1000L + 2000 + 3000 + (Integer.BYTES * 3)));
                assertThat(metaRead.getRemainingSize(), equalTo(metaRead.getTotalSize()));
                assertThat(metaRead.getLedgersMap().get(ledgerId1), equalTo(1000L + 3000L + (Integer.BYTES * 2)));
                assertThat(metaRead.getLedgersMap().get(ledgerId2), equalTo(2000L + Integer.BYTES));
            }
        }
    }

    @Test
    public void testMetadataManyBatch() throws Exception {
        File ledgerDir = tmpDirs.createNew("directMetaManyBatches", "ledgers");
        File curDir = new File(ledgerDir, "current");
        curDir.mkdirs();

        long lastLoc = -1;
        int ledgerCount = 11000;
        try (DirectEntryLogger writer = new DirectEntryLogger(
                     curDir, new MockEntryLogIds(),
                     new NativeIOImpl(),
                     ByteBufAllocator.DEFAULT,
                     MoreExecutors.newDirectExecutorService(),
                     MoreExecutors.newDirectExecutorService(),
                     2 << 24, // max file size
                     10 * 1024 * 1024, // max sane entry size
                     32 * 1024 * 1024, // total write buffer size
                     32 * 1024 * 1024, // total read buffer size
                     16 * 1024 * 1024, // read buffer size
                     1, // numReadThreads
                     300, // max fd cache time in seconds
                     slog, NullStatsLogger.INSTANCE)) {
            for (int i = 0; i < ledgerCount; i++) {
                long loc = writer.addEntry(i, makeEntry(i, 1L, 1000));
                if (lastLoc >= 0) {
                    assertThat(logIdFromLocation(loc), equalTo(logIdFromLocation(lastLoc)));
                }
                lastLoc = loc;
            }
            writer.flush();
        }

        try (DirectEntryLogger reader = new DirectEntryLogger(
                     curDir, new MockEntryLogIds(),
                     new NativeIOImpl(),
                     ByteBufAllocator.DEFAULT,
                     MoreExecutors.newDirectExecutorService(),
                     MoreExecutors.newDirectExecutorService(),
                     2 << 20, // max file size
                     10 * 1024 * 1024, // max sane entry size
                     32 * 1024 * 1024, // total write buffer size
                     32 * 1024 * 1024, // total read buffer size
                     16 * 1024 * 1024, // read buffer size
                     1, // numReadThreads
                     300, // max fd cache time in seconds
                     slog, NullStatsLogger.INSTANCE)) {
            int logId = logIdFromLocation(lastLoc);
            EntryLogMetadata metaRead = reader.readEntryLogIndex(logId);

            assertThat(metaRead.getEntryLogId(), equalTo((long) logId));
            assertThat(metaRead.getTotalSize(), equalTo((1000L + Integer.BYTES) * ledgerCount));
            assertThat(metaRead.getRemainingSize(), equalTo(metaRead.getTotalSize()));
            for (int i = 0; i < ledgerCount; i++) {
                assertThat(metaRead.getLedgersMap().containsKey(i), equalTo(true));
            }
        }
    }

    @Test
    public void testGetFlushedLogs() throws Exception {
        File ledgerDir = tmpDirs.createNew("testFlushedLogs", "ledgers");
        File curDir = new File(ledgerDir, "current");
        curDir.mkdirs();

        ExecutorService executor = Executors.newFixedThreadPool(5);
        CompletableFuture<Void> blockClose = new CompletableFuture<>();
        NativeIOImpl nativeIO = new NativeIOImpl() {
                @Override
                public int close(int fd) {
                    try {
                        blockClose.join();
                        return super.close(fd);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }

            };
        DirectEntryLogger entryLogger = new DirectEntryLogger(
                curDir, new MockEntryLogIds(),
                nativeIO,
                ByteBufAllocator.DEFAULT,
                executor,
                executor,
                23000, // max file size
                10 * 1024 * 1024, // max sane entry size
                1024 * 1024, // total write buffer size
                1024 * 1024, // total read buffer size
                32 * 1024, // read buffer size
                1, // numReadThreads
                300, // max fd cache time in seconds
                slog, NullStatsLogger.INSTANCE);
        try { // not using try-with-resources because close needs to be unblocked in failure
            // Add entries.
            // Ledger 1 is on first entry log
            // Ledger 2 spans first, second and third entry log
            // Ledger 3 is on the third entry log (which is still active when extract meta)
            long loc1 = entryLogger.addEntry(1L, makeEntry(1L, 1L, 5000));
            long loc2 = entryLogger.addEntry(2L, makeEntry(2L, 1L, 5000));
            assertThat(logIdFromLocation(loc2), equalTo(logIdFromLocation(loc1)));
            long loc3 = entryLogger.addEntry(2L, makeEntry(2L, 1L, 15000));
            assertThat(logIdFromLocation(loc3), greaterThan(logIdFromLocation(loc2)));
            long loc4 = entryLogger.addEntry(2L, makeEntry(2L, 1L, 15000));
            assertThat(logIdFromLocation(loc4), greaterThan(logIdFromLocation(loc3)));
            long loc5 = entryLogger.addEntry(3L, makeEntry(3L, 1L, 1000));
            assertThat(logIdFromLocation(loc5), equalTo(logIdFromLocation(loc4)));

            long logId1 = logIdFromLocation(loc2);
            long logId2 = logIdFromLocation(loc3);
            long logId3 = logIdFromLocation(loc5);

            // all three should exist
            assertThat(entryLogger.logExists(logId1), equalTo(true));
            assertThat(entryLogger.logExists(logId2), equalTo(true));
            assertThat(entryLogger.logExists(logId3), equalTo(true));

            assertThat(entryLogger.getFlushedLogIds(), empty());

            blockClose.complete(null);
            entryLogger.flush();

            assertThat(entryLogger.getFlushedLogIds(), containsInAnyOrder(logId1, logId2));

            long loc6 = entryLogger.addEntry(3L, makeEntry(3L, 1L, 25000));
            assertThat(logIdFromLocation(loc6), greaterThan(logIdFromLocation(loc5)));
            entryLogger.flush();

            assertThat(entryLogger.getFlushedLogIds(), containsInAnyOrder(logId1, logId2, logId3));
        } finally {
            blockClose.complete(null);
            entryLogger.close();
            executor.shutdownNow();
        }
    }

    @Test
    public void testBufferSizeNotPageAligned() throws Exception {
        File ledgerDir = tmpDirs.createNew("logRolling", "ledgers");
        File curDir = new File(ledgerDir, "current");
        curDir.mkdirs();

        ByteBuf e1 = makeEntry(ledgerId1, 1L, 4000);
        ByteBuf e2 = makeEntry(ledgerId1, 2L, 4000);
        ByteBuf e3 = makeEntry(ledgerId1, 3L, 4000);

        try (EntryLogger elog = new DirectEntryLogger(
                curDir, new MockEntryLogIds(),
                new NativeIOImpl(),
                ByteBufAllocator.DEFAULT,
                MoreExecutors.newDirectExecutorService(),
                MoreExecutors.newDirectExecutorService(),
                9000, // max file size (header + size of one entry)
                10 * 1024 * 1024, // max sane entry size
                128 * 1024 + 500, // total write buffer size
                128 * 1024 + 300, // total read buffer size
                64 * 1024, // read buffer size
                1, // numReadThreads
                300, // max fd cache time in seconds
                slog, NullStatsLogger.INSTANCE)) {
            long loc1 = elog.addEntry(ledgerId1, e1.slice());
            int logId1 = logIdFromLocation(loc1);
            assertThat(logId1, equalTo(1));

            long loc2 = elog.addEntry(ledgerId1, e2.slice());
            int logId2 = logIdFromLocation(loc2);
            assertThat(logId2, equalTo(2));

            long loc3 = elog.addEntry(ledgerId1, e3.slice());
            int logId3 = logIdFromLocation(loc3);
            assertThat(logId3, equalTo(3));
        }
    }
}


text:
Webservice api exercise

Authorization

Username: <input id="username" type="text" />

Password: <input type="password" id="password" />

<button id="get_auth">Get Auth Token</button>

Auth Token: <input type="text" id="token" placeholder="Enter auth token" />

VC Methods

Platform Name: <input type="text" id="platform_name" />

Discovery Address: <input type="text" id="discovery_address" />

<button id="register">Register Platform</button>

Shortcut buttons

<button id="register1">Register Platform http://127.0.0.2:8080</button>
<button id="register2">Register Platform http://127.0.0.3:8080</button>
<button id="register3">Register Platform http://127.0.0.4:8080</button>

Setting Key: <input type="text" id="setting_key" />

Setting Value: <input type="text" id="setting_value" />
<button id="set_setting">Save Value</button>
<button id="set_null_setting">Save Null Value (remove key)</button>
<button id="get_setting">Get Value</button>
<button id="get_setting_keys">Get Keys</button>

Platform Listings

<button id="list_platforms">List Platforms</button>
<button id="list_deivces">List Devices</button>
<button id="list_performance">List Performance</button>
<button id="get_topic_list">List Topics</button>

VIP Identity: <input type="text" id="vip_identity" value="platform.agent" />

Agent id: <input type="text" id="agent_id" value="platform.agent" />

VIP Address: <input type="text" id="vip_address" placeholder="VIP Address where VIP Identity is located" />

Platform UUID: <input type="text" id="platform_uuid" placeholder="Platform uuid to remove" />

<button id="unregister">Unregister VIP Address</button>

Platform Agent API

Platform UUID: <select id="agent_platform_uuid"></select>

Install Agent: <input type="file" id="agent_file" name="agent_file" />

<button id="list_agents">List Agents</button> <button id="get_devices">Get Devices</button>

Agent UUID: <input id="agent_uuid" placeholder="Agent to act on" />

Arguments: <input id="agent_method" placeholder="Method to call"/> <input id="agent_method_args" placeholder="key:value arguments to pass" />

<button id="inspect_agent">Inspect Agent</button>
<button id="execute_method">Execute Method</button>
<button id="status_agents">Status Agents</button>

Platform Historian

Topic: <input id="historian_topic" placeholder="Historian topic to query" />

<button id="query_historian">Query Historian</button>

Request Sent

<textarea id="request_sent" cols="100" rows="5"></textarea>

Response Data

<textarea id="output_data" cols="100" rows="5"></textarea>


text:
FROM hanscoder/java:v1.0
MAINTAINER Hans Sowa "hanssowa@gmail.com"

RUN add-apt-repository ppa:cwchien/gradle && \
    apt-get update && \
    apt-get install gradle-2.4

ENV GRADLE_HOME /usr/lib/gradle/2.4


text:
var express = require('express')
var router = express.Router();

var mongoose = require('mongoose');
var Todo = mongoose.model('Todo');

router.route('/')
	.get(function(req,res){
		res.send(200,'Yo!');
});

	router.route('/todos')
	.get(function(req,res){
		Todo.find(function(err,todoss){
			console.log('Todo');
		res.send(200,todoss);
		});
})
	.post(function(req,res){
		var todosall = req.body;
		var todolist = todosall.list;
		var todos = todosall.todotasks;

		console.log(todosall);
 	console.log("data : " + todos);
		console.log('list name : ' + todolist);

		Todo.findOne({list:todolist},function(err,todo){
			if(err){
				return res.send(err);
			}

			if(todo){
				return res.send(500, 'Todo List Name Already Exists.....');
			}

			for( i in todos){
				console.log(i);
				console.log(todos[i]);
				var currToDo = todos[i];
				var todo = new Todo();
				todo.list = currToDo.list;
				todo.todo =  currToDo.todo;
				console.log("Posting To Do Task Data............")
				todo.save(function(err,post){
					console.log('sent');
				})
			}

			res.send(200,"Ok");
		})

	});

module.exports = router


text:
<!DOCTYPE html>

    <title>ITTCaptionPlacement Enumeration Reference</title>
    <link rel="stylesheet" type="text/css" href="../../css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="../../css/highlight.css" />
    <meta charset='utf-8'>

 Docs (44% documented)

         Reference

        ITTCaptionPlacement Enumeration Reference

            Enumerations

                FCPXMLElementType

            Extensions

                CMTime

                XMLDocument

                XMLElement

                – TextAlignment

                – TimecodeFormat

                – AudioLayout

                – AudioRate

                – RenderColorSpace

                – MulticamSourceEnable

                – CaptionFormat

                – CaptionLanguage

                – CEA608CaptionDisplayStyle

                – ITTCaptionPlacement

                – CEA608CaptionAlignment

                – CEA608Color

                – StoryElementLocation

            Structures

                FCPXMLUtility

ITTCaptionPlacement

public enum ITTCaptionPlacement : String

Caption placement for ITT captions.

                    top

Undocumented

Declaration

Swift

case top = "top"

                    bottom

Undocumented

Declaration

Swift

case bottom = "bottom"

                    left

Undocumented

Declaration

Swift

case left = "left"

                    right

Undocumented

Declaration

Swift

case right = "right"

© 2018 . All rights reserved. (Last updated: 2018-09-20)

Generated by jazzy ♪♫ v0.9.3, a Realm project.


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-parent</artifactId>
		<version>2.0.0.BUILD-SNAPSHOT</version>
		<relativePath>../spring-boot-parent</relativePath>
	</parent>
	<artifactId>spring-boot-actuator</artifactId>
	<name>Spring Boot Actuator</name>
	<description>Spring Boot Actuator</description>
	<url>http://projects.spring.io/spring-boot/</url>
	<organization>
		<name>Pivotal Software, Inc.</name>
		<url>http://www.spring.io</url>
	</organization>
	<properties>
		<main.basedir>${basedir}/..</main.basedir>
	</properties>
	<dependencies>
		<!-- Compile -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-autoconfigure</artifactId>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
		</dependency>
		<!-- Optional -->
		<dependency>
			<groupId>com.fasterxml.jackson.dataformat</groupId>
			<artifactId>jackson-dataformat-xml</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>com.github.ben-manes.caffeine</groupId>
			<artifactId>caffeine</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>com.hazelcast</groupId>
			<artifactId>hazelcast</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>com.hazelcast</groupId>
			<artifactId>hazelcast-spring</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>com.sun.mail</groupId>
			<artifactId>javax.mail</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>com.timgroup</groupId>
			<artifactId>java-statsd-client</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>com.zaxxer</groupId>
			<artifactId>HikariCP</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>io.dropwizard.metrics</groupId>
			<artifactId>metrics-core</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>io.lettuce</groupId>
			<artifactId>lettuce-core</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>io.searchbox</groupId>
			<artifactId>jest</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>javax.cache</groupId>
			<artifactId>cache-api</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>javax.jms</groupId>
			<artifactId>javax.jms-api</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>net.sf.ehcache</groupId>
			<artifactId>ehcache</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.apache.activemq</groupId>
			<artifactId>activemq-broker</artifactId>
			<optional>true</optional>
			<exclusions>
				<exclusion>
					<artifactId>geronimo-jms_1.1_spec</artifactId>
					<groupId>org.apache.geronimo.specs</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-dbcp2</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-core</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-el</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.apache.tomcat</groupId>
			<artifactId>tomcat-jdbc</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.elasticsearch</groupId>
			<artifactId>elasticsearch</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.flywaydb</groupId>
			<artifactId>flyway-core</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.core</groupId>
			<artifactId>jersey-server</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.containers</groupId>
			<artifactId>jersey-container-servlet-core</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.jolokia</groupId>
			<artifactId>jolokia-core</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.infinispan</groupId>
			<artifactId>infinispan-spring4-embedded</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.liquibase</groupId>
			<artifactId>liquibase-core</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-messaging</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webflux</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.amqp</groupId>
			<artifactId>spring-rabbit</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-cassandra</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-couchbase</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-ldap</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-mongodb</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-neo4j</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-redis</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-solr</artifactId>
			<optional>true</optional>
			<exclusions>
				<!-- the version of solr here is incompatible with jackson-xml because
					of an old woodstox -->
				<exclusion>
					<artifactId>wstx-asl</artifactId>
					<groupId>org.codehaus.woodstox</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.integration</groupId>
			<artifactId>spring-integration-core</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
			<optional>true</optional>
		</dependency>
		<!-- Annotation processing -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-autoconfigure-processor</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>
		<!-- Test -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-test-support</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.jayway.jsonpath</groupId>
			<artifactId>json-path</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>io.projectreactor.ipc</groupId>
			<artifactId>reactor-netty</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>io.undertow</groupId>
			<artifactId>undertow-core</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>io.undertow</groupId>
			<artifactId>undertow-servlet</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.jboss.spec.javax.servlet</groupId>
					<artifactId>jboss-servlet-api_3.1_spec</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.hsqldb</groupId>
			<artifactId>hsqldb</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.media</groupId>
			<artifactId>jersey-media-json-jackson</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.ext</groupId>
			<artifactId>jersey-spring3</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.skyscreamer</groupId>
			<artifactId>jsonassert</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-elasticsearch</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-rest-webmvc</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.integration</groupId>
			<artifactId>spring-integration-jmx</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.yaml</groupId>
			<artifactId>snakeyaml</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>