text:
package io.kubernetes.client.openapi.models;

import com.google.gson.annotations.SerializedName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.Objects;

/**
 * StatefulSet represents a set of pods with consistent identities. Identities are defined as: -
 * Network: A single stable DNS and hostname. - Storage: As many VolumeClaims as requested. The
 * StatefulSet guarantees that a given network identity will always map to the same storage
 * identity.
 */
@ApiModel(
    description =
        "StatefulSet represents a set of pods with consistent identities. Identities are defined as:   - Network: A single stable DNS and hostname.   - Storage: As many VolumeClaims as requested.  The StatefulSet guarantees that a given network identity will always map to the same storage identity.")
@javax.annotation.Generated(
    value = "org.openapitools.codegen.languages.JavaClientCodegen",
    date = "2022-09-15T17:00:37.921Z[Etc/UTC]")
public class V1StatefulSet implements io.kubernetes.client.common.KubernetesObject {
  public static final String SERIALIZED_NAME_API_VERSION = "apiVersion";

  @SerializedName(SERIALIZED_NAME_API_VERSION)
  private String apiVersion;

  public static final String SERIALIZED_NAME_KIND = "kind";

  @SerializedName(SERIALIZED_NAME_KIND)
  private String kind;

  public static final String SERIALIZED_NAME_METADATA = "metadata";

  @SerializedName(SERIALIZED_NAME_METADATA)
  private V1ObjectMeta metadata;

  public static final String SERIALIZED_NAME_SPEC = "spec";

  @SerializedName(SERIALIZED_NAME_SPEC)
  private V1StatefulSetSpec spec;

  public static final String SERIALIZED_NAME_STATUS = "status";

  @SerializedName(SERIALIZED_NAME_STATUS)
  private V1StatefulSetStatus status;

  public V1StatefulSet apiVersion(String apiVersion) {

    this.apiVersion = apiVersion;
    return this;
  }

  /**
   * APIVersion defines the versioned schema of this representation of an object. Servers should
   * convert recognized schemas to the latest internal value, and may reject unrecognized values.
   * More info:
   * https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
   *
   * @return apiVersion
   */
  @javax.annotation.Nullable
  @ApiModelProperty(
      value =
          "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources")
  public String getApiVersion() {
    return apiVersion;
  }

  public void setApiVersion(String apiVersion) {
    this.apiVersion = apiVersion;
  }

  public V1StatefulSet kind(String kind) {

    this.kind = kind;
    return this;
  }

  /**
   * Kind is a string value representing the REST resource this object represents. Servers may infer
   * this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More
   * info:
   * https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
   *
   * @return kind
   */
  @javax.annotation.Nullable
  @ApiModelProperty(
      value =
          "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds")
  public String getKind() {
    return kind;
  }

  public void setKind(String kind) {
    this.kind = kind;
  }

  public V1StatefulSet metadata(V1ObjectMeta metadata) {

    this.metadata = metadata;
    return this;
  }

  /**
   * Get metadata
   *
   * @return metadata
   */
  @javax.annotation.Nullable
  @ApiModelProperty(value = "")
  public V1ObjectMeta getMetadata() {
    return metadata;
  }

  public void setMetadata(V1ObjectMeta metadata) {
    this.metadata = metadata;
  }

  public V1StatefulSet spec(V1StatefulSetSpec spec) {

    this.spec = spec;
    return this;
  }

  /**
   * Get spec
   *
   * @return spec
   */
  @javax.annotation.Nullable
  @ApiModelProperty(value = "")
  public V1StatefulSetSpec getSpec() {
    return spec;
  }

  public void setSpec(V1StatefulSetSpec spec) {
    this.spec = spec;
  }

  public V1StatefulSet status(V1StatefulSetStatus status) {

    this.status = status;
    return this;
  }

  /**
   * Get status
   *
   * @return status
   */
  @javax.annotation.Nullable
  @ApiModelProperty(value = "")
  public V1StatefulSetStatus getStatus() {
    return status;
  }

  public void setStatus(V1StatefulSetStatus status) {
    this.status = status;
  }

  @Override
  public boolean equals(java.lang.Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    V1StatefulSet v1StatefulSet = (V1StatefulSet) o;
    return Objects.equals(this.apiVersion, v1StatefulSet.apiVersion)
        && Objects.equals(this.kind, v1StatefulSet.kind)
        && Objects.equals(this.metadata, v1StatefulSet.metadata)
        && Objects.equals(this.spec, v1StatefulSet.spec)
        && Objects.equals(this.status, v1StatefulSet.status);
  }

  @Override
  public int hashCode() {
    return Objects.hash(apiVersion, kind, metadata, spec, status);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class V1StatefulSet {\n");
    sb.append("    apiVersion: ").append(toIndentedString(apiVersion)).append("\n");
    sb.append("    kind: ").append(toIndentedString(kind)).append("\n");
    sb.append("    metadata: ").append(toIndentedString(metadata)).append("\n");
    sb.append("    spec: ").append(toIndentedString(spec)).append("\n");
    sb.append("    status: ").append(toIndentedString(status)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces (except the first line).
   */
  private String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}


text:
<?php

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Tools\Setup;

require_once 'config/config.php';

//error_reporting(E_ALL & ~E_NOTICE);
error_reporting(E_ALL);

/**
 * @return EntityManager
 */
function LoadServiceEntityManager() {
    $config = Setup::createAnnotationMetadataConfiguration(
        array(
            APP_PATH.'includes/Entity'
        ),
        APP_ENVIRONMENT=='development',
        APP_PATH . 'cache/doctrine/',
        null,
        false
    );
    return EntityManager::create(
        array(
            'driver'   => DB_DRIVER,
            'host'     => DB_HOST,
            'dbname'   => DB_NAME,
            'user'     => DB_USER,
            'password' => DB_PASS,
        ),
        $config
    );
}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Novempt. Riztiment. extr. 7 (1907)

#### Original name
Diplodia onobrychidis Hollós

### Remarks
null


text:
{% extends "base-page.html" %}
{% load cms_tags static menu_tags sekizai_tags %}

{% block base_content %}

Page Content

{% endblock %}


text:
'use strict';

const _ = require('lodash');
const __ = require('../../..');

describe('matches(value)', () => {
	_.forEach([
		[__.containsString('X'), 'eXtreme', true],
		[__.containsString('X'), 'weak', false],
		[__.number(), 5, true],
		[__.number(), 'stringy', false]
	], _.spread((actualMatcher, value, matchResult) => {
		it('should only match if the actual matcher matches the given value: ' + [__.describe(actualMatcher), value, matchResult].join(' / '), () => {
			const sut = __.matches(value);

			__.assertThat(sut.matches(actualMatcher), __.is(matchResult));
		});
	}));

	describe('description', () => {
		let description;
		beforeEach(() => {
			description = new __.Description();
		});

		it('should contain value', () => {
			const sut = __.matches(5);

			sut.describeTo(description);

			__.assertThat(description.get(), __.equalTo('a matcher matching <5>'));
		});

		it('should contain description and mismatch description of the given matcher', () => {
			const sut = __.matches([1, 2]);

			sut.describeMismatch(__.hasSize(3), description);

			__.assertThat(description.get(), __.equalTo('matcher with description "a collection or string with size <3>" failed to match and explained: "size was <2>\nfor [<1>, <2>]"'));
		});
	});
});


text:
package org.apache.camel.builder.endpoint;

import java.util.concurrent.TimeUnit;

import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.apache.camel.test.junit5.TestSupport.deleteDirectory;

public class FileDelayTest extends BaseEndpointDslTest {

    @Override
    @BeforeEach
    public void setUp() throws Exception {
        deleteDirectory("target/data/files");
        super.setUp();
        template.sendBodyAndHeader("file://target/data/files", "Hello World", Exchange.FILE_NAME, "hello.txt");
        template.sendBodyAndHeader("file://target/data/files", "Bye World", Exchange.FILE_NAME, "bye.txt");
    }

    @Test
    public void testDelay() throws Exception {
        MockEndpoint mock = getMockEndpoint("mock:result");
        mock.expectedBodiesReceivedInAnyOrder("Hello World", "Bye World");
        mock.message(1).arrives().between(1500, 3000).millis().afterPrevious();

        assertMockEndpointsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new EndpointRouteBuilder() {
            public void configure() throws Exception {
                from(file("target/data/files/").delay(2).timeUnit(TimeUnit.SECONDS).delete(true).maxMessagesPerPoll(1))
                        .convertBodyTo(String.class)
                        .to(mock("result"));
            }
        };
    }

}


text:
namespace RandomImage
{
    public class SearchImagesOptions
    {
        public bool IncludeSubdirs { get; set; }
    }
}


text:
package org.spongepowered.common.event;

import io.leangen.geantyref.TypeToken;
import org.spongepowered.api.event.Event;
import org.spongepowered.api.event.EventListener;
import org.spongepowered.api.event.EventListenerRegistration;
import org.spongepowered.api.event.Order;
import org.spongepowered.plugin.PluginContainer;

import java.lang.reflect.Type;
import java.util.Objects;

public final class SpongeEventListenerRegistration<T extends Event> implements EventListenerRegistration<T> {

    private final Type eventType;
    private final PluginContainer plugin;
    private final Order order;
    private final boolean beforeModifications;
    private final EventListener<? super T> listener;

    private SpongeEventListenerRegistration(final BuilderImpl<T> builder) {
        this.eventType = builder.eventType;
        this.plugin = builder.plugin;
        this.order = builder.order;
        this.beforeModifications = builder.beforeModifications;
        this.listener = builder.listener;
    }

    @Override
    public Type eventType() {
        return this.eventType;
    }

    @Override
    public PluginContainer plugin() {
        return this.plugin;
    }

    @Override
    public Order order() {
        return this.order;
    }

    @Override
    public boolean beforeModifications() {
        return this.beforeModifications;
    }

    @Override
    public EventListener<? super T> listener() {
        return this.listener;
    }

    public static final class FactoryImpl implements EventListenerRegistration.Factory {

        @Override
        public <T extends Event> Builder<T> builder(final TypeToken<T> eventType) {
            return new BuilderImpl<>(Objects.requireNonNull(eventType, "eventType"));
        }
    }

    public static final class BuilderImpl<T extends Event> implements EventListenerRegistration.Builder<T> {

        final Type eventType;
        PluginContainer plugin;
        Order order;
        boolean beforeModifications;
        EventListener<? super T> listener;

        private BuilderImpl(final TypeToken<T> eventType) {
            this.eventType = eventType.getType();
        }

        @Override
        public Builder<T> plugin(final PluginContainer plugin) {
            this.plugin = Objects.requireNonNull(plugin, "plugin");
            return this;
        }

        @Override
        public Builder<T> order(final Order order) {
            this.order = order;
            return this;
        }

        @Override
        public Builder<T> beforeModifications(final boolean beforeModifications) {
            this.beforeModifications = beforeModifications;
            return this;
        }

        @Override
        public Builder<T> listener(final EventListener<? super T> listener) {
            this.listener = Objects.requireNonNull(listener, "listener");
            return this;
        }

        @Override
        public Builder<T> reset() {
            this.plugin = null;
            this.order = Order.DEFAULT;
            this.beforeModifications = false;
            this.listener = null;
            return this;
        }

        @Override
        public EventListenerRegistration<T> build() {
            Objects.requireNonNull(this.plugin, "plugin");
            Objects.requireNonNull(this.listener, "listener");

            return new SpongeEventListenerRegistration<>(this);
        }
    }
}


text:
<!DOCTYPE html>

    <title>{@version.title}</title>
    <meta name="description" content="{@version.meta_description}">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" type="text/css" href="/assets/css/style.css">

                    {block type: "Menu"; id: "primary"}

        {if page.Parent.parent_id}

{@page.Parent.CurrentVersion.title}

        {/if}

        {ifnot page.Parent.parent_id}
            {if page.parent_id}

{@version.title}

            {/if}
        {/ifnot}


text:
package org.vaadin.addons.rinne

import com.vaadin.server.ThemeResource
import org.scalatest.FunSpec

class VFlashSpec extends FunSpec {

  describe("A VFlash") {

    describe("should allow to set") {

      it("parameters") {
        val flash = new VFlash
        flash.parameters += "param1" -> "value1"
        flash.parameters += "param2" -> "value2"
        flash.parameters += "param3" -> "value3"

        assert(flash.parameters.size === 3)
        assert(flash.parameters === Map("param1" -> "value1", "param2" -> "value2", "param3" -> "value3"))

        assert(flash.parameters.get("param2") === Some("value2"))
        assert(flash.parameters.get("param7") === None)

        flash.parameters += "param2" -> "new value 2"
        assert(flash.parameters === Map("param1" -> "value1", "param2" -> "new value 2", "param3" -> "value3"))

        flash.parameters -= "param1"
        assert(flash.parameters.size === 2)
        assert(flash.parameters === Map("param2" -> "new value 2", "param3" -> "value3"))
      }

      it("alternateText") {
        val flash = new VFlash
        assert(flash.alternateText === None)

        flash.alternateText = "alternate"
        assert(flash.alternateText === Some("alternate"))

        flash.alternateText = None
        assert(flash.alternateText === None)

        flash.alternateText = Some("alternate")
        assert(flash.alternateText === Some("alternate"))
      }

      it("source") {
        val flash = new VFlash

        val res = new ThemeResource("img.png")
        flash.source = res
        assert(flash.source === Some(res))

        flash.source = None
        assert(flash.source === None)
      }

      it("codebase") {
        val flash = new VFlash
        flash.codebase = "codebase"
        assert(flash.codebase === Some("codebase"))

        flash.codebase = Option("codebase")
        assert(flash.codebase === Some("codebase"))

        flash.codebase = None
        assert(flash.codebase === None)
      }

      it("codetype") {
        val flash = new VFlash
        flash.codetype = "codetype"
        assert(flash.codetype === Some("codetype"))

        flash.codetype = Option("codetype")
        assert(flash.codetype === Some("codetype"))

        flash.codetype = None
        assert(flash.codetype === None)
      }

      it("standby") {
        val flash = new VFlash
        flash.standby = "standby"
        assert(flash.standby === Some("standby"))
      }

      it("standby, Option") {
        val flash = new VFlash
        flash.standby = Option("standby")
        assert(flash.standby === Some("standby"))
      }

      it("standby, None") {
        val flash = new VFlash
        flash.standby = None
        assert(flash.standby === None)
      }

      it("archive") {
        val flash = new VFlash
        flash.archive = "archive"
        assert(flash.archive === Some("archive"))

        flash.archive = Option("archive")
        assert(flash.archive === Some("archive"))

        flash.archive = None
        assert(flash.archive === None)
      }
    }
  }
}


text:
package org.java_websocket;

import java.io.IOException;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLEngineResult.Status;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;

/**
 * Implements the relevant portions of the SocketChannel interface with the SSLEngine wrapper.
 */
public class SSLSocketChannel2 implements ByteChannel, WrappedByteChannel {
	/**
	 * This object is used to feed the {@link SSLEngine}'s wrap and unwrap methods during the handshake phase.
	 **/
	protected static ByteBuffer emptybuffer = ByteBuffer.allocate( 0 );

	protected ExecutorService exec;

	protected List<Future<?>> tasks;

	/** raw payload incomming */
	protected ByteBuffer inData;
	/** encrypted data outgoing */
	protected ByteBuffer outCrypt;
	/** encrypted data incoming */
	protected ByteBuffer inCrypt;

	/** the underlying channel */
	protected SocketChannel socketChannel;
	/** used to set interestOP SelectionKey.OP_WRITE for the underlying channel */
	protected SelectionKey selectionKey;

	protected SSLEngine sslEngine;
	protected SSLEngineResult readEngineResult;
	protected SSLEngineResult writeEngineResult;

	/**
	 * Should be used to count the buffer allocations.
	 * But because of #190 where HandshakeStatus.FINISHED is not properly returned by nio wrap/unwrap this variable is used to check whether {@link #createBuffers(SSLSession)} needs to be called.
	 **/
	protected int bufferallocations = 0;

	public SSLSocketChannel2( SocketChannel channel , SSLEngine sslEngine , ExecutorService exec , SelectionKey key ) throws IOException {
		if( channel == null || sslEngine == null || exec == null )
			throw new IllegalArgumentException( "parameter must not be null" );

		this.socketChannel = channel;
		this.sslEngine = sslEngine;
		this.exec = exec;

		readEngineResult = writeEngineResult = new SSLEngineResult( Status.BUFFER_UNDERFLOW, sslEngine.getHandshakeStatus(), 0, 0 ); // init to prevent NPEs

		tasks = new ArrayList<Future<?>>( 3 );
		if( key != null ) {
			key.interestOps( key.interestOps() | SelectionKey.OP_WRITE );
			this.selectionKey = key;
		}
		createBuffers( sslEngine.getSession() );
		// kick off handshake
		socketChannel.write( wrap( emptybuffer ) );// initializes res
		processHandshake();
	}

	private void consumeFutureUninterruptible( Future<?> f ) {
		try {
			boolean interrupted = false;
			while ( true ) {
				try {
					f.get();
					break;
				} catch ( InterruptedException e ) {
					interrupted = true;
				}
			}
			if( interrupted )
				Thread.currentThread().interrupt();
		} catch ( ExecutionException e ) {
			throw new RuntimeException( e );
		}
	}

	/**
	 * This method will do whatever necessary to process the sslengine handshake.
	 * Thats why it's called both from the {@link #read(ByteBuffer)} and {@link #write(ByteBuffer)}
	 **/
	private synchronized void processHandshake() throws IOException {
		if( sslEngine.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING )
			return; // since this may be called either from a reading or a writing thread and because this method is synchronized it is necessary to double check if we are still handshaking.
		if( !tasks.isEmpty() ) {
			Iterator<Future<?>> it = tasks.iterator();
			while ( it.hasNext() ) {
				Future<?> f = it.next();
				if( f.isDone() ) {
					it.remove();
				} else {
					if( isBlocking() )
						consumeFutureUninterruptible( f );
					return;
				}
			}
		}

		if( sslEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_UNWRAP ) {
			if( !isBlocking() || readEngineResult.getStatus() == Status.BUFFER_UNDERFLOW ) {
				inCrypt.compact();
				int read = socketChannel.read( inCrypt );
				if( read == -1 ) {
					throw new IOException( "connection closed unexpectedly by peer" );
				}
				inCrypt.flip();
			}
			inData.compact();
			unwrap();
			if( readEngineResult.getHandshakeStatus() == HandshakeStatus.FINISHED ) {
				createBuffers( sslEngine.getSession() );
				return;
			}
		}
		consumeDelegatedTasks();
		if( tasks.isEmpty() || sslEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_WRAP ) {
			socketChannel.write( wrap( emptybuffer ) );
			if( writeEngineResult.getHandshakeStatus() == HandshakeStatus.FINISHED ) {
				createBuffers( sslEngine.getSession() );
				return;
			}
		}
		assert ( sslEngine.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING );// this function could only leave NOT_HANDSHAKING after createBuffers was called unless #190 occurs which means that nio wrap/unwrap never return HandshakeStatus.FINISHED

		bufferallocations = 1; // look at variable declaration why this line exists and #190. Without this line buffers would not be be recreated when #190 AND a rehandshake occur.
	}
	private synchronized ByteBuffer wrap( ByteBuffer b ) throws SSLException {
		outCrypt.compact();
		writeEngineResult = sslEngine.wrap( b, outCrypt );
		outCrypt.flip();
		return outCrypt;
	}

	/**
	 * performs the unwrap operation by unwrapping from {@link #inCrypt} to {@link #inData}
	 **/
	private synchronized ByteBuffer unwrap() throws SSLException {
		int rem;
		do {
			rem = inData.remaining();
			readEngineResult = sslEngine.unwrap( inCrypt, inData );
		} while ( readEngineResult.getStatus() == SSLEngineResult.Status.OK && ( rem != inData.remaining() || sslEngine.getHandshakeStatus() == HandshakeStatus.NEED_UNWRAP ) );
		inData.flip();
		return inData;
	}

	protected void consumeDelegatedTasks() {
		Runnable task;
		while ( ( task = sslEngine.getDelegatedTask() ) != null ) {
			tasks.add( exec.submit( task ) );
			// task.run();
		}
	}

	protected void createBuffers( SSLSession session ) {
		int netBufferMax = session.getPacketBufferSize();
		int appBufferMax = Math.max(session.getApplicationBufferSize(), netBufferMax);

		if( inData == null ) {
			inData = ByteBuffer.allocate( appBufferMax );
			outCrypt = ByteBuffer.allocate( netBufferMax );
			inCrypt = ByteBuffer.allocate( netBufferMax );
		} else {
			if( inData.capacity() != appBufferMax )
				inData = ByteBuffer.allocate( appBufferMax );
			if( outCrypt.capacity() != netBufferMax )
				outCrypt = ByteBuffer.allocate( netBufferMax );
			if( inCrypt.capacity() != netBufferMax )
				inCrypt = ByteBuffer.allocate( netBufferMax );
		}
		inData.rewind();
		inData.flip();
		inCrypt.rewind();
		inCrypt.flip();
		outCrypt.rewind();
		outCrypt.flip();
		bufferallocations++;
	}

	public int write( ByteBuffer src ) throws IOException {
		if( !isHandShakeComplete() ) {
			processHandshake();
			return 0;
		}
		// assert ( bufferallocations > 1 ); //see #190
		//if( bufferallocations <= 1 ) {
		//	createBuffers( sslEngine.getSession() );
		//}
		int num = socketChannel.write( wrap( src ) );
		return num;

	}

	/**
	 * Blocks when in blocking mode until at least one byte has been decoded.<br>
	 * When not in blocking mode 0 may be returned.
	 *
	 * @return the number of bytes read.
	 **/
	public int read( ByteBuffer dst ) throws IOException {
		if( !dst.hasRemaining() )
			return 0;
		if( !isHandShakeComplete() ) {
			if( isBlocking() ) {
				while ( !isHandShakeComplete() ) {
					processHandshake();
				}
			} else {
				processHandshake();
				if( !isHandShakeComplete() ) {
					return 0;
				}
			}
		}
		// assert ( bufferallocations > 1 ); //see #190
		//if( bufferallocations <= 1 ) {
		//	createBuffers( sslEngine.getSession() );
		//}
		/* 1. When "dst" is smaller than "inData" readRemaining will fill "dst" with data decoded in a previous read call.
		 * 2. When "inCrypt" contains more data than "inData" has remaining space, unwrap has to be called on more time(readRemaining)
		 */
		int purged = readRemaining( dst );
		if( purged != 0 )
			return purged;

		/* We only continue when we really need more data from the network.
		 * Thats the case if inData is empty or inCrypt holds to less data than necessary for decryption
		 */
		assert ( inData.position() == 0 );
		inData.clear();

		if( !inCrypt.hasRemaining() )
			inCrypt.clear();
		else
			inCrypt.compact();

		if( isBlocking() || readEngineResult.getStatus() == Status.BUFFER_UNDERFLOW )
			if( socketChannel.read( inCrypt ) == -1 ) {
				return -1;
			}
		inCrypt.flip();
		unwrap();

		int transfered = transfereTo( inData, dst );
		if( transfered == 0 && isBlocking() ) {
			return read( dst ); // "transfered" may be 0 when not enough bytes were received or during rehandshaking
		}
		return transfered;
	}
	/**
	 * {@link #read(ByteBuffer)} may not be to leave all buffers(inData, inCrypt)
	 **/
	private int readRemaining( ByteBuffer dst ) throws SSLException {
		if( inData.hasRemaining() ) {
			return transfereTo( inData, dst );
		}
		if( !inData.hasRemaining() )
			inData.clear();
		// test if some bytes left from last read (e.g. BUFFER_UNDERFLOW)
		if( inCrypt.hasRemaining() ) {
			unwrap();
			int amount = transfereTo( inData, dst );
			if( amount > 0 )
				return amount;
		}
		return 0;
	}

	public boolean isConnected() {
		return socketChannel.isConnected();
	}

	public void close() throws IOException {
		sslEngine.closeOutbound();
		sslEngine.getSession().invalidate();
		if( socketChannel.isOpen() )
			socketChannel.write( wrap( emptybuffer ) );// FIXME what if not all bytes can be written
		socketChannel.close();
		exec.shutdownNow();
	}

	private boolean isHandShakeComplete() {
		HandshakeStatus status = sslEngine.getHandshakeStatus();
		return status == SSLEngineResult.HandshakeStatus.FINISHED || status == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING;
	}

	public SelectableChannel configureBlocking( boolean b ) throws IOException {
		return socketChannel.configureBlocking( b );
	}

	public boolean connect( SocketAddress remote ) throws IOException {
		return socketChannel.connect( remote );
	}

	public boolean finishConnect() throws IOException {
		return socketChannel.finishConnect();
	}

	public Socket socket() {
		return socketChannel.socket();
	}

	public boolean isInboundDone() {
		return sslEngine.isInboundDone();
	}

	@Override
	public boolean isOpen() {
		return socketChannel.isOpen();
	}

	@Override
	public boolean isNeedWrite() {
		return outCrypt.hasRemaining() || !isHandShakeComplete(); // FIXME this condition can cause high cpu load during handshaking when network is slow
	}

	@Override
	public void writeMore() throws IOException {
		write( outCrypt );
	}

	@Override
	public boolean isNeedRead() {
		return inData.hasRemaining() || ( inCrypt.hasRemaining() && readEngineResult.getStatus() != Status.BUFFER_UNDERFLOW && readEngineResult.getStatus() != Status.CLOSED );
	}

	@Override
	public int readMore( ByteBuffer dst ) throws SSLException {
		return readRemaining( dst );
	}

	private int transfereTo( ByteBuffer from, ByteBuffer to ) {
		int fremain = from.remaining();
		int toremain = to.remaining();
		if( fremain > toremain ) {
			// FIXME there should be a more efficient transfer method
			int limit = Math.min( fremain, toremain );
			for( int i = 0 ; i < limit ; i++ ) {
				to.put( from.get() );
			}
			return limit;
		} else {
			to.put( from );
			return fremain;
		}

	}

	@Override
	public boolean isBlocking() {
		return socketChannel.isBlocking();
	}

}


text:
package org.wso2.iot.integration.ui.pages.samples;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.wso2.iot.integration.ui.pages.UIUtils;
import org.wso2.iot.integration.ui.pages.UIElementMapper;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Class to represent the Connected cup device interface.
 * This device is a virtual device, which allows users to change Temperature and Level values and put an order.
 */
public class ConnectedCupDeviceInterface {

    private Log log = LogFactory.getLog(ConnectedCupDeviceInterface.class);
    private WebDriver driver;
    private UIElementMapper uiElementMapper;

    public ConnectedCupDeviceInterface(WebDriver driver) throws IOException {
        this.driver = driver;
        this.uiElementMapper = UIElementMapper.getInstance();
        WebDriverWait webDriverWait = new WebDriverWait(driver, UIUtils.webDriverTimeOut);
        if (!webDriverWait.until(ExpectedConditions.titleContains("Connected Coffee Cup"))) {
            throw new IllegalStateException("This is not the Connected cup device page");
        }
    }

    /**
     * Method to perform the order coffee functionality.
     * @return : True if the element is present and action is performed. False otherwise.
     */
    public boolean orderCoffee() {
        if (UIUtils.isElementPresent(log, driver, By.xpath(
                uiElementMapper.getElement("iot.sample.orderCoffee.xpath")))) {
            WebElement orderBtn = driver.findElement(By.xpath(
                    uiElementMapper.getElement("iot.sample.orderCoffee.xpath")));
            orderBtn.click();
            return true;
        }
        return false;
    }

    /**
     * Method to change the temperature level.
     * @param temp : The value to be set.
     * @return : True if the element is present and value is set. False otherwise.
     */
    public boolean changeTemperature(String temp) {
        if (UIUtils.isElementPresent(log, driver, By.xpath(
                uiElementMapper.getElement("iot.sample.temperature.xpath")))) {
            WebElement tempSlider = driver.findElement(By.xpath(
                    uiElementMapper.getElement("iot.sample.temperature.xpath")));
            moveSlider(tempSlider, Integer.parseInt(temp));
            driver.manage().timeouts().implicitlyWait(UIUtils.webDriverTime, TimeUnit.SECONDS);
            return true;
        }
        return false;
    }

    /**
     * Method to change the Coffee level.
     * @param level : The value to be set.
     * @return : True if the element is present and value is set. False otherwise.
     */
    public boolean changeCoffeeLevel(String level) {
        if (UIUtils.isElementPresent(log, driver, By.xpath(
                uiElementMapper.getElement("iot.sample.coffee.level.xpath")))) {
            WebElement lvlSlider = driver.findElement(By.xpath(
                    uiElementMapper.getElement("iot.sample.coffee.level.xpath")));
            moveSlider(lvlSlider, Integer.parseInt(level));
            driver.manage().timeouts().implicitlyWait(UIUtils.webDriverTime, TimeUnit.SECONDS);
            return true;
        }
        return false;
    }

    /**
     * This method performs the slider change action of the web interface.
     * @param slider : The element of the slider to be changed.
     * @param val : Value to be set.
     */
    private void moveSlider(WebElement slider, int val) {
        Actions move = new Actions(driver);
        Action action = move.dragAndDropBy(slider, 0, val).build();
        action.perform();
    }

}


text:
class QuotePublisher
{
public:
    static QuotePublisher& getInstance()
    {
        static QuotePublisher instance;
        return instance;
    }
private:
    QuotePublisher() {}
public:
    QuotePublisher(QuotePublisher const&)  = delete;
    void operator=(QuotePublisher const&)  = delete;
    void publish(double s) {
        std::cout << "You've pushed a dummy auction to a real ads platform, the business is upset!" << std::endl;
    }
};

class MarketStudyVendor {
public:
    double averagePrice(std::string blog) {
        if (std::getenv("license") == NULL) {
            std::cout << "Missing license !" << std::endl;
            exit(EIO);
        }

        std::uniform_real_distribution<double> unif(0, 10000);
        std::default_random_engine re;

        return std::hash<std::string>()(blog) * unif(re);
    }
};

class BlogAuctionTask {
private:
    MarketStudyVendor marketDataRetriever;

public:
    void PriceAndPublish(std::string blog, std::string mode) {
        double avgPrice = marketDataRetriever.averagePrice(blog);
        // FIXME should actually be +2 not +1
        double proposal = avgPrice + 1;
        double timeFactor = 1;
        if (mode=="SLOW") {
            timeFactor = 2;
        }
        if (mode=="MEDIUM") {
            timeFactor = 4;
        }
        if (mode=="FAST") {
            timeFactor = 8;
        }
        if (mode=="ULTRAFAST") {
            timeFactor = 13;
        }

        proposal = std::fmod(proposal, 2.0) == 0 ? 3.14 * proposal
                                                 : 3.15 * timeFactor * std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
        QuotePublisher::getInstance().publish(proposal);
    }
};

class TechBlogs {
public:
    static std::vector<std::string> listAllBlogs() {
        std::this_thread::sleep_for(std::chrono::milliseconds(5000));// Access to DB are very slow
        return { "HackerNews", "Reddit", "TechCrunch", "BuzzFeed", "TMZ", "TheHuffPost", "GigaOM"};
    }
};

class AdSpace {
public:
    static std::vector<std::string> getAdSpaces() {
        static std::unordered_map<std::string, std::vector<std::string>> cache;
        if (!cache.empty()) {
            return cache.at("blogs list");
        }
        // FIXME : only return blogs that start with a 'T'
        std::vector<std::string> listAllBlogs = TechBlogs::listAllBlogs();
        cache["blogs list"] = listAllBlogs;
        return listAllBlogs;
    }
};

class AutomaticQuoteBot {
public:
    void sendAllQuotes(std::string mode) {
        std::vector<std::string> blogs = AdSpace::getAdSpaces();
        for (std::string blog : blogs) {
            BlogAuctionTask auctionTask;
            auctionTask.PriceAndPublish(blog, mode);
        }
    }
};

int main() {
    AutomaticQuoteBot bot;
    bot.sendAllQuotes("FAST");
    return 0;
}


text:
package pixelgl

import (
	"github.com/faiface/glhf"
	"github.com/faiface/mainthread"
	"github.com/faiface/pixel"
)

// GLFrame is a type that helps implementing OpenGL Targets. It implements most common methods to
// avoid code redundancy. It contains an glhf.Frame that you can draw on.
type GLFrame struct {
	frame  *glhf.Frame
	bounds pixel.Rect
	pixels []uint8
	dirty  bool
}

// NewGLFrame creates a new GLFrame with the given bounds.
func NewGLFrame(bounds pixel.Rect) *GLFrame {
	gf := new(GLFrame)
	gf.SetBounds(bounds)
	return gf
}

// SetBounds resizes the GLFrame to the new bounds.
func (gf *GLFrame) SetBounds(bounds pixel.Rect) {
	if bounds == gf.Bounds() {
		return
	}

	mainthread.Call(func() {
		oldF := gf.frame

		_, _, w, h := intBounds(bounds)
		gf.frame = glhf.NewFrame(w, h, false)

		// preserve old content
		if oldF != nil {
			ox, oy, ow, oh := intBounds(bounds)
			oldF.Blit(
				gf.frame,
				ox, oy, ox+ow, oy+oh,
				ox, oy, ox+ow, oy+oh,
			)
		}
	})

	gf.bounds = bounds
	gf.pixels = nil
	gf.dirty = true
}

// Bounds returns the current GLFrame's bounds.
func (gf *GLFrame) Bounds() pixel.Rect {
	return gf.bounds
}

// Color returns the color of the pixel under the specified position.
func (gf *GLFrame) Color(at pixel.Vec) pixel.RGBA {
	if gf.dirty {
		mainthread.Call(func() {
			tex := gf.frame.Texture()
			tex.Begin()
			gf.pixels = tex.Pixels(0, 0, tex.Width(), tex.Height())
			tex.End()
		})
		gf.dirty = false
	}
	if !gf.bounds.Contains(at) {
		return pixel.Alpha(0)
	}
	bx, by, bw, _ := intBounds(gf.bounds)
	x, y := int(at.X)-bx, int(at.Y)-by
	off := y*bw + x
	return pixel.RGBA{
		R: float64(gf.pixels[off*4+0]) / 255,
		G: float64(gf.pixels[off*4+1]) / 255,
		B: float64(gf.pixels[off*4+2]) / 255,
		A: float64(gf.pixels[off*4+3]) / 255,
	}
}

// Frame returns the GLFrame's Frame that you can draw on.
func (gf *GLFrame) Frame() *glhf.Frame {
	return gf.frame
}

// Texture returns the underlying Texture of the GLFrame's Frame.
//
// Implements GLPicture interface.
func (gf *GLFrame) Texture() *glhf.Texture {
	return gf.frame.Texture()
}

// Dirty marks the GLFrame as changed. Always call this method when you draw onto the GLFrame's
// Frame.
func (gf *GLFrame) Dirty() {
	gf.dirty = true
}


text:
import os

import SourceModel.SM_File
from SmellDetector import Constants as CONSTS, Utilities

def detectSmells(folder, outputFile):
    detectBrokenHie(folder, outputFile)

def detectBrokenHie(folder, outputFile):
    modulesFolder = getModulesFolder(folder)
    if modulesFolder:
        for dir in os.listdir(modulesFolder):
            if os.path.isdir(os.path.join(modulesFolder, dir)):
                detectBroHierarchy(os.path.join(modulesFolder, dir), outputFile)

def detectBroHierarchy(folder, outputFile):
    classNames, superClassNames = collectClassNames(folder)
    #print("classNames: " + str(classNames))
    #print("superClassNames: " + str(superClassNames))
    for superClass in superClassNames:
        if not classNames.__contains__(superClass):
            Utilities.reportSmell(outputFile, folder, CONSTS.SMELL_BRO_HIE, CONSTS.MODULE_RES)

def getModulesFolder(folder):
    for aFile in os.listdir(folder):
        if os.path.isdir(os.path.join(folder,aFile)):
            if aFile.__contains__(CONSTS.MODULES):
                return os.path.join(folder, aFile)
    return ""

def collectClassNames(folder):
    classNames = []
    parentClassNames = []
    for root, dirs, files in os.walk(folder):
        for file in files:
            if file.endswith(".pp") and not os.path.islink(os.path.join(root, file)):
                fileObj = SourceModel.SM_File.SM_File(os.path.join(root, file))
                classes, pClasses = fileObj.getClassHierarchyInfo()
                if len(classes) > 0:
                    classNames.extend(classes)
                if len(pClasses) > 0:
                    parentClassNames.extend(pClasses)
    return classNames, parentClassNames


text:
<?php

namespace SerendipityHQ\Bundle\StripeBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * An hidden field passed alogn with the main form containing the card token created by the stripe.js API call.
 */
class CreditCardStripeTokenType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('card_token', HiddenType::class);
    }
}


text:
/**
 * Predefined subset problem.
 */
package org.jamesframework.core.subset;


text:
All the templates for this app should be located in the subfolder of `pinax/blog/`
in your template search path.

## Blog List

The url `blog` and `blog_section` both render the template
`pinax/blog/blog_list.html` with `posts`, `search_query`, `section_slug`,
and `section_name` context variables.

The `posts` variable is a queryset of current blog posts. If the `GET` parameter,
`q` is found, it filters the queryset create a simple search mechanism, then
assigns the value to `search_query`. If the `blog` url is requested then
`section` and `section_name` will be `None`.

## Post Detail

The urls, `blog_post`, `blog_post_pk`, `blog_post_slug`, and `blog_post_secret`
all render the template `pinax/blog/blog_post.html` with the `post` context
variable.

The `post` is the requested post. It may or may not be public depending on the
url requested.

## Blog Feeds

The url `blog_feed` will either render `pinax/blog/atom_feed.xml` or
`pinax/blog/rss_feed.xml` depending on the parameters in the URL. It will pass
both templates the context variables of `feed_id`, `feed_title`, `blog_url`,
`feed_url`, `feed_updated`, `entries`, and `current_site`.

Both of these templates ship already configured to work out of the box.


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
/**
 * Function call cannot appear in the program before the FunctionExpression appears
 *
 * @path ch13/13.0/S13_A17_T1.js
 * @description Trying to call a function before the FunctionExpression appears
 */

//////////////////////////////////////////////////////////////////////////////
//CHECK#1
try{
    var __result = __func();
	$FAIL("#1.1: var __result = __func() lead to throwing exception");
} catch(e) {
  if ((e instanceof TypeError) !== true) {
    $ERROR('#1.2: func should throw a TypeError  Actual: ' + (e));
  }
}
//
//////////////////////////////////////////////////////////////////////////////

var __func = function (){return "ONE";};

//////////////////////////////////////////////////////////////////////////////
//CHECK#2
var __result = __func();
if (__result !== "ONE") {
	$ERROR('#2: __result === "ONE". Actual: __result ==='+__result);
}
//
//////////////////////////////////////////////////////////////////////////////

__func = function (){return "TWO";};

//////////////////////////////////////////////////////////////////////////////
//CHECK#3
var __result = __func();
if (__result !== "TWO") {
	$ERROR('#3: __result === "TWO". Actual: __result ==='+__result);
}
//
//////////////////////////////////////////////////////////////////////////////


text:
//
// Copyright (c) 2020 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef EXAMPLE_ISSUE_44_HPP
#define EXAMPLE_ISSUE_44_HPP

namespace example {

/** Issue 44

    @li All of the constructors should be
    grouped together on the overload
    resolution page.

    @li The class page should show three
    unique briefs for the constructor.
*/
class issue_44
{
    int i_;

public:
    /** Default constructor.

        Description.
    */
    issue_44();

    /** Constructor.

        Description.
    */
    /** @{ */
    issue_44(char);
    issue_44(short, short);
    /** @} */

    /** Constructor.

        Description.
    */
    /** @{ */
    issue_44(char, int);
    issue_44(long, long);
    /** @} */

    /** Void constructor

        Description.
    */
    issue_44(void*);
};

} // example

#endif


text:
package org.nd4j.linalg.api.ops.custom;

import lombok.val;
import org.nd4j.autodiff.samediff.SDVariable;
import org.nd4j.autodiff.samediff.SameDiff;
import org.nd4j.base.Preconditions;
import org.nd4j.imports.graphmapper.tf.TFGraphMapper;
import org.nd4j.linalg.api.buffer.DataType;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.DynamicCustomOp;
import org.nd4j.linalg.api.shape.options.ArrayOptionsHelper;
import org.tensorflow.framework.AttrValue;
import org.tensorflow.framework.GraphDef;
import org.tensorflow.framework.NodeDef;

import java.util.Collections;
import java.util.List;
import java.util.Map;

public class BitCast extends DynamicCustomOp {
    public BitCast() {}

    private DataType dtype;

    public BitCast(INDArray in, DataType dataType, INDArray out) {
        this(in, dataType.toInt(), out);
    }

    public BitCast(INDArray in, int dataType, INDArray out) {
        inputArguments.add(in);
        outputArguments.add(out);
        iArguments.add(Long.valueOf(dataType));

        dtype = DataType.fromInt(dataType);
    }

    public BitCast(INDArray in, DataType dataType) {
        this(in, dataType.toInt());
    }

    public BitCast(INDArray in, int dataType) {
        inputArguments.add(in);
        iArguments.add(Long.valueOf(dataType));
        dtype = DataType.fromInt(dataType);
    }

    public BitCast(SameDiff sameDiff, SDVariable in, SDVariable dataType) {
        super("", sameDiff, new SDVariable[]{in, dataType});
    }

    @Override
    public void initFromTensorFlow(NodeDef nodeDef, SameDiff initWith, Map<String, AttrValue> attributesForNode, GraphDef graph) {
        TFGraphMapper.initFunctionFromProperties(nodeDef.getOp(), this, attributesForNode, nodeDef, graph);
        val t = nodeDef.getAttrOrDefault("type", null);
        val type = ArrayOptionsHelper.convertToDataType(t.getType());
        addIArgument(type.toInt());

        dtype = type;
    }

    @Override
    public String opName() {
        return "bitcast";
    }

    @Override
    public String tensorflowName() {
        return "Bitcast";
    }

    @Override
    public List<DataType> calculateOutputDataTypes(List<DataType> inputDataTypes){
        int n = args().length;
        Preconditions.checkState(inputDataTypes != null && inputDataTypes.size() == n, "Expected %s input data types for %s, got %s", n, getClass(), inputDataTypes);
        return Collections.singletonList(dtype);
    }
}


text:
<?php

namespace LQNL\AutenticacaoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\Request;
use LQNL\AutenticacaoBundle\Entity\Usuario;

class LoginController extends Controller {

    public function loginAction() {
        $user = $this->getUser();
        if ($user) {
            return $this->redirect($this->generateUrl('home'));
        }
        $request = $this->getRequest();
        $session = $request->getSession();

        // get the login error if there is one
        if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
            $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
        } else {
            $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
        }

        return $this->render('AutenticacaoBundle:Login:login.html.twig', array(
                    'data' => new \DateTime,
                    'last_username' => $session->get(SecurityContext::LAST_USERNAME),
                    'error' => $error,
                        // ...
        ));
    }

    public function homeAction() {
        $user = $this->getUser();
        if ($user->getTipo() == 1) {
            return $this->render('AutenticacaoBundle:Login:home.html.twig', array(
                        'usuario' => $user,
            ));
        } else {
            return $this->redirect($this->generateUrl('home_admin'));
        }
    }

    public function testeAction(Request $request) {
        $em = $this->getDoctrine()->getManager();
        $usuario = $em->getRepository('AutenticacaoBundle:Usuario')->findOneBy(array('username' => $request->get('username')));

        $encoder = $this->get('security.encoder_factory')->getEncoder(new Usuario());
        $encodedPass = $encoder->encodePassword($request->get('_password'), null);

        echo 'Username:   ' . $request->get('_username');
        echo 'Password digitado:   ' . $encodedPass;
        echo '

 Password bd:   ' . $usuario->getPassword();

        exit(0);
    }

}


text:
package io.undertow.websockets.jsr.test.annotated;

import io.undertow.servlet.api.DeploymentInfo;
import io.undertow.servlet.api.DeploymentManager;
import io.undertow.servlet.api.ServletContainer;
import io.undertow.servlet.test.util.TestClassIntrospector;
import io.undertow.testutils.AjpIgnore;
import io.undertow.testutils.DefaultServer;
import io.undertow.testutils.SpdyIgnore;
import io.undertow.websockets.jsr.ServerWebSocketContainer;
import io.undertow.websockets.jsr.WebSocketDeploymentInfo;
import io.undertow.websockets.utils.FrameChecker;
import io.undertow.websockets.utils.WebSocketTestClient;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.jboss.netty.handler.codec.http.websocketx.WebSocketVersion;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.xnio.ByteBufferSlicePool;
import org.xnio.FutureResult;

import javax.websocket.CloseReason;
import javax.websocket.Session;
import java.net.URI;

/**
 * @author Norman Maurer
 */
@RunWith(DefaultServer.class)
@AjpIgnore
@SpdyIgnore
public class AnnotatedEndpointTest {

    private static ServerWebSocketContainer deployment;

    @BeforeClass
    public static void setup() throws Exception {

        final ServletContainer container = ServletContainer.Factory.newInstance();

        DeploymentInfo builder = new DeploymentInfo()
                .setClassLoader(AnnotatedEndpointTest.class.getClassLoader())
                .setContextPath("/")
                .setClassIntrospecter(TestClassIntrospector.INSTANCE)
                .addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME,
                        new WebSocketDeploymentInfo()
                                .setBuffers(new ByteBufferSlicePool(100, 1000))
                                .setWorker(DefaultServer.getWorker())
                                .addEndpoint(MessageEndpoint.class)
                                .addEndpoint(AnnotatedClientEndpoint.class)
                                .addEndpoint(AnnotatedClientEndpointWithConfigurator.class)
                                .addEndpoint(IncrementEndpoint.class)
                                .addEndpoint(EncodingEndpoint.class)
                                .addEndpoint(RequestUriEndpoint.class)
                                .addListener(new WebSocketDeploymentInfo.ContainerReadyListener() {
                                    @Override
                                    public void ready(ServerWebSocketContainer container) {
                                        deployment = container;
                                    }
                                })
                )
                .setDeploymentName("servletContext.war");

        DeploymentManager manager = container.addDeployment(builder);
        manager.deploy();

        DefaultServer.setRootHandler(manager.start());
    }

    @AfterClass
    public static void after() {
        deployment = null;
    }

    @org.junit.Test
    public void testStringOnMessage() throws Exception {
        final byte[] payload = "hello".getBytes();
        final FutureResult latch = new FutureResult();

        WebSocketTestClient client = new WebSocketTestClient(WebSocketVersion.V13, new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/chat/Stuart"));
        client.connect();
        client.send(new TextWebSocketFrame(ChannelBuffers.wrappedBuffer(payload)), new FrameChecker(TextWebSocketFrame.class, "hello Stuart".getBytes(), latch));
        latch.getIoFuture().get();
        client.destroy();
    }

    @org.junit.Test
    public void testAnnotatedClientEndpoint() throws Exception {
        AnnotatedClientEndpoint.reset();
        Session session = deployment.connectToServer(AnnotatedClientEndpoint.class, new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/chat/Bob"));

        Assert.assertEquals("hi Bob (protocol=foo)", AnnotatedClientEndpoint.message());

        session.close();
        Assert.assertEquals("CLOSED", AnnotatedClientEndpoint.message());
    }

    @org.junit.Test
    public void testCloseReason() throws Exception {
        MessageEndpoint.reset();

        Session session = deployment.connectToServer(AnnotatedClientEndpoint.class, new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/chat/Bob"));

        Assert.assertEquals("hi Bob (protocol=foo)", AnnotatedClientEndpoint.message());

        session.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, "Foo!"));
        Assert.assertEquals("CLOSED", AnnotatedClientEndpoint.message());
        CloseReason cr = MessageEndpoint.getReason();
        Assert.assertEquals(CloseReason.CloseCodes.VIOLATED_POLICY.getCode(), cr.getCloseCode().getCode());
        Assert.assertEquals("Foo!", cr.getReasonPhrase());

    }

    @org.junit.Test
    public void testAnnotatedClientEndpointWithConfigurator() throws Exception {

        Session session = deployment.connectToServer(AnnotatedClientEndpointWithConfigurator.class, new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/chat/Bob"));

        Assert.assertEquals("hi Bob (protocol=configured-proto)", AnnotatedClientEndpointWithConfigurator.message());
        Assert.assertEquals("foo, bar, configured-proto",ClientConfigurator.sentSubProtocol);
        Assert.assertEquals("configured-proto", ClientConfigurator.receivedSubProtocol());

        session.close();
        Assert.assertEquals("CLOSED", AnnotatedClientEndpointWithConfigurator.message());
    }

    @org.junit.Test
    public void testImplicitIntegerConversion() throws Exception {
        final byte[] payload = "12".getBytes();
        final FutureResult latch = new FutureResult();

        WebSocketTestClient client = new WebSocketTestClient(WebSocketVersion.V13, new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/increment/2"));
        client.connect();
        client.send(new TextWebSocketFrame(ChannelBuffers.wrappedBuffer(payload)), new FrameChecker(TextWebSocketFrame.class, "14".getBytes(), latch));
        latch.getIoFuture().get();
        client.destroy();
    }

    @org.junit.Test
    public void testEncodingAndDecoding() throws Exception {
        final byte[] payload = "hello".getBytes();
        final FutureResult latch = new FutureResult();

        WebSocketTestClient client = new WebSocketTestClient(WebSocketVersion.V13, new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/encoding/Stuart"));
        client.connect();
        client.send(new TextWebSocketFrame(ChannelBuffers.wrappedBuffer(payload)), new FrameChecker(TextWebSocketFrame.class, "hello Stuart".getBytes(), latch));
        latch.getIoFuture().get();
        client.destroy();
    }

    @org.junit.Test
    public void testRequestUri() throws Exception {
        final byte[] payload = "hello".getBytes();
        final FutureResult latch = new FutureResult();

        WebSocketTestClient client = new WebSocketTestClient(WebSocketVersion.V13, new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/request?a=b"));
        client.connect();
        client.send(new TextWebSocketFrame(ChannelBuffers.wrappedBuffer(payload)), new FrameChecker(TextWebSocketFrame.class, "/request?a=b".getBytes(), latch));
        latch.getIoFuture().get();
        client.destroy();
    }
}


text:
// -----------------------------------------------------------------------
//  <copyright file="WebApiFunctionHandler.cs" company="OSharp开源团队">
//      Copyright (c) 2014-2015 OSharp. All rights reserved.
//  </copyright>
//  <site>http://www.osharp.org</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2015-10-09 16:15</last-date>
// -----------------------------------------------------------------------

using System;
using System.Reflection;
using System.Threading.Tasks;
using System.Web.Http;

using OSharp.Core.Security;
using OSharp.Utility;
using OSharp.Utility.Extensions;
using OSharp.Web.Http.Properties;

namespace OSharp.Web.Http.Initialize
{
    /// <summary>
    /// WebApi功能信息处理器
    /// </summary>
    public class WebApiFunctionHandler : FunctionHandlerBase<Function, Guid>
    {
        /// <summary>
        /// 获取 功能技术提供者,如Mvc/WebApi/SignalR等,用于区分功能来源,各技术更新功能时,只更新属于自己技术的功能
        /// </summary>
        protected override PlatformToken PlatformToken
        {
            get { return PlatformToken.WebApi; }
        }

        /// <summary>
        /// 重写以实现从类型信息创建功能信息
        /// </summary>
        /// <param name="type">类型信息</param>
        /// <returns></returns>
        protected override Function GetFunction(Type type)
        {
            if (!typeof(ApiController).IsAssignableFrom(type))
            {
                throw new InvalidOperationException(Resources.ActionMethodInfoFinder_TypeNotApiControllerType.FormatWith(type.FullName));
            }
            Function function = new Function()
            {
                Name = type.ToDescription(),
                Area = GetArea(type),
                Controller = type.Name.Replace("ApiController", string.Empty).Replace("Controller", string.Empty),
                IsController = true,
                FunctionType = FunctionType.Anonymouse,
                PlatformToken = PlatformToken
            };
            return function;
        }

        /// <summary>
        /// 重写以实现从方法信息创建功能信息
        /// </summary>
        /// <param name="method"></param>
        /// <returns></returns>
        protected override Function GetFunction(MethodInfo method)
        {
            if (method.ReturnType != typeof(IHttpActionResult) && method.ReturnType != typeof(Task<IHttpActionResult>))
            {
                throw new InvalidOperationException(Resources.FunctionHandler_MethodNotApiAction.FormatWith(method.Name));
            }

            FunctionType functionType = FunctionType.Anonymouse;
            if (method.HasAttribute<AllowAnonymousAttribute>(true))
            {
                functionType = FunctionType.Anonymouse;
            }
            else if (method.HasAttribute<LoginedAttribute>(true))
            {
                functionType = FunctionType.Logined;
            }
            else if (method.HasAttribute<RoleLimitAttribute>(true))
            {
                functionType = FunctionType.RoleLimit;
            }
            Type type = method.DeclaringType;
            if (type == null)
            {
                throw new InvalidOperationException(Resources.FunctionHandler_DefindActionTypeIsNull.FormatWith(method.Name));
            }
            Function function = new Function()
            {
                Name = method.ToDescription(),
                Area = GetArea(type),
                Controller = type.Name.Replace("ApiController", string.Empty).Replace("Controller", string.Empty),
                Action = method.Name,
                FunctionType = functionType,
                PlatformToken = PlatformToken,
                IsController = false,
                IsAjax = false,
                IsChild = false
            };
            return function;
        }

        /// <summary>
        /// 重写以实现从类型中获取功能的区域信息
        /// </summary>
        protected override string GetArea(Type type)
        {
            type.Required<Type, InvalidOperationException>(m => typeof(ApiController).IsAssignableFrom(m) && !m.IsAbstract,
                Resources.ActionMethodInfoFinder_TypeNotApiControllerType.FormatWith(type.FullName));
            string @namespace = type.Namespace;
            if (@namespace == null)
            {
                return null;
            }
            int index = @namespace.IndexOf("Areas", StringComparison.Ordinal) + 6;
            string area = index > 6 ? @namespace.Substring(index, @namespace.IndexOf(".Controllers", StringComparison.Ordinal) - index) : null;
            return area;
        }

        /// <summary>
        /// 重写以实现是否忽略指定方法的功能信息
        /// </summary>
        /// <param name="method">方法信息</param>
        /// <returns></returns>
        protected override bool IsIgnoreMethod(MethodInfo method)
        {
            return method.HasAttribute<HttpPostAttribute>();
        }
    }
}


text:
package eu.dnetlib.iis.common.counter;

import static java.util.stream.Collectors.toList;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import eu.dnetlib.iis.common.counter.PigCounters.JobCounters;

/**
 * Parser of {@link PigCounters} from json string.
 *
 * @author madryk
 */
public class PigCountersParser {

    private static final String JOB_IDS_COUNTER_NAME = "JOB_GRAPH";

    private static final String ALIASES_COUNTER_NAME = "Alias";

    private static final char VALUES_SEPARATOR = ',';

    private final JsonParser jsonParser = new JsonParser();

    //------------------------ LOGIC --------------------------

    /**
     * Parses input pig counters in json format into {@link PigCounters} object.
     */
    public PigCounters parse(String pigCountersJson) {

        JsonObject pigCountersJsonObject = jsonParser.parse(pigCountersJson).getAsJsonObject();

        List<String> jobIds = extractJobIds(pigCountersJsonObject);

        List<JobCounters> jobCountersList = jobIds.stream()
                .map(jobId -> extractJobCounters(pigCountersJsonObject, jobId))
                .collect(toList());

        Map<String, String> rootLevelCounters = extractRootLevelCounters(pigCountersJsonObject);

        return new PigCounters(rootLevelCounters, jobCountersList);
    }

    //------------------------ PRIVATE --------------------------

    /**
     * Extracts job ids from pig counters json.
     */
    private List<String> extractJobIds(JsonObject pigCountersJsonObject) {

        JsonElement element = pigCountersJsonObject.get(JOB_IDS_COUNTER_NAME);

        return Lists.newArrayList(StringUtils.split(element.getAsString(), VALUES_SEPARATOR));

    }

    /**
     * Extracts job counters from pig counters json.
     */
    private JobCounters extractJobCounters(JsonObject pigCountersJsonObject, String jobId) {

        JsonObject jobCountersJson = pigCountersJsonObject.get(jobId).getAsJsonObject();

        List<String> aliases = Arrays.asList(StringUtils.split(jobCountersJson.get(ALIASES_COUNTER_NAME).getAsString(), VALUES_SEPARATOR));

        Map<String, String> counters = buildCountersFromJson(jobCountersJson);

        return new JobCounters(jobId, aliases, counters);
    }

    /**
     * Extracts root level counters from pig counter json
     */
    private Map<String, String> extractRootLevelCounters(JsonObject pigCountersJsonObject) {

        return buildCountersFromJson(pigCountersJsonObject);

    }

    /**
     * Builds job counters map from json.

     * Method supports only primitive string values. Any counters
     * defined in json that doesn't follow this rule will
     * be omitted.

     * For example:

     * buildCountersFromJson({"COUNTER_1": "aaa", "COUNTER_2": null, "COMPLEX_COUNTER": {"A": 1, "B": "bbb"})

     * will result in map with single element: {"COUNTER_1": "aaa"}
     */
    private Map<String, String> buildCountersFromJson(JsonObject jsonCounters) {

        Map<String, String> counters = Maps.newHashMap();

        for (Map.Entry<String, JsonElement> jsonCounter : jsonCounters.entrySet()) {
            JsonElement counterValue = jsonCounter.getValue();

            if (counterValue.isJsonPrimitive() && counterValue.getAsJsonPrimitive().isString()) {

                    counters.put(jsonCounter.getKey(), counterValue.getAsString());
            }
        }

        return counters;
    }
}


text:
import com.googlecode.flyway.core.Flyway;
import io.github.rhildred.OpenShiftDataSource;

public class Migrate {

	public static void main(String[] args) {
        // Create the Flyway instance
        Flyway flyway = new Flyway();

        // Point it to the database
        String sUrl = OpenShiftDataSource.getConnectionString("jdbc:mysql://localhost:3306/ticketing?user=root");
        System.out.println(sUrl);
        flyway.setDataSource(sUrl, null, null);

        // Start the migration
        flyway.migrate();
    }

}


text:
This GitHub repository contains all the files that are required for the pawn token of AnyBoard project.

## firmware
The folder *firmware* contains the RFduino program of the pawn. This folder contains four libraries that have to be copied and pasted in the Arduino's *libraries* folder.

## demo_application_evothings
The folder *demo_application_evothings* contains all the files needed for the demo application. This application is made with evothings. In order to use this application, just follow this [tutorial](https://evothings.com/getting-started-with-evothings-studio-in-90-seconds/)

## hardware
* RFduino ([website](http://www.rfduino.com/), [GitHub](https://github.com/RFduino/RFduino))
* Accelerometer ADXL345 ([datasheet](http://www.analog.com/media/en/technical-documentation/data-sheets/ADXL345.pdf))
* Vibrating motor ([datasheet](https://www.sparkfun.com/datasheets/Robotics/310-101_datasheet.pdf))
* Color detection sensor TCS347254 ([datasheet](https://www.adafruit.com/datasheets/TCS34725.pdf))
* Capacitive sensor MPR121 ([datasheet](https://www.sparkfun.com/datasheets/Components/MPR121.pdf))
* LED display ([datasheet](https://www.sparkfun.com/datasheets/Components/MPR121.pdf), [Adafruit product](https://www.adafruit.com/products/870))

![Schematic](https://github.com/Matth26/anyboardpawn/blob/master/schematic_fritzing.png)

## libraries
In order to use all the components listed in the hardware part, some Adafruit's libraries have been used. These libraries are includes in the four libraries that are in the *libraries* folder.

### Adafruit_ADXL345
For the ADXL345 the Adafruit_ADXL345 Arduino's library is used ([Adafruit_ADXL345](https://github.com/adafruit/Adafruit_ADXL345)).

### Adafruit_Sensor
The Adafruit_ADXL345 library is based on the Adafruit's Unified Sensor Library ([Adafruit_Sensor](https://github.com/adafruit/Adafruit_Sensor)).

### Adafruit_MPR121
For the MPR121 the Adafruit_MPR121 Arduino's library is used ([Adafruit_MPR121](https://github.com/adafruit/Adafruit_MPR121_Library))

### Adafruit_TCS34725
For the TCS34725 used with an autorage mechanism the Adafruit library is used ([Adafruit_TCS34725](https://github.com/adafruit/Adafruit_TCS34725/tree/master/examples/tcs34725autorange))

### Adafruit_GFX
For the LED display the Adafruit_GFX library is used ([Adafruit_GFX](https://github.com/adafruit/Adafruit-GFX-Library))

### Adafruit_LED_backpack
And the Adafruit_lED_backpack library is also required ([Adafruit_lED_backpack](https://github.com/adafruit/Adafruit-LED-Backpack-Library))

## examples
In the folder *examples* few arduino sketch example can be found. These programs are example programs using the accelerometer ADXL345. In order to run those example, the libraries contained in the folder */examples/libraries* have to be copied and pasted in the Arduino's *libraries* folder.

##License
See the licencse.txt file for license rights and limitations (Apache V2.0).


text:
<include target="./_header.html" />

 {$lang->youtube_browse_menus}

		{$lang->total}: {number_format($total_count)}, {$lang->page_count}: {number_format($page)}/{number_format($total_page)}

			 {$lang->no}
			 {$lang->youtube_menu_category}
			 {$lang->youtube_menu_id}
			 {$lang->browser_title}
			 {$lang->regdate}
			 {$lang->cmd_edit}
			<input type="checkbox" data-name="cart" title="Check All" />

 $no,$val">
			{$no}

				<block cond="!$val->module_category_srl">
					<block cond="$val->site_srl">{$lang->virtual_site}</block>
					<block cond="!$val->site_srl">{$lang->not_exists}</block>
				</block>
				<block cond="$val->module_category_srl">{$module_category[$val->module_category_srl]->title}</block>

			{$val->mid}
			domain,'','mid',$val->mid)}">{$val->browser_title}
			{zdate($val->regdate,"Y-m-d")}

				module_srl)}" class="x_icon-cog" title="{$lang->cmd_setup}">{$lang->cmd_setup}
				module_srl)}" class="x_icon-plus" onclick="popopen(this.href);return false;" title="{$lang->cmd_copy}">{$lang->cmd_copy}
				module_srl)}" class="x_icon-remove" title="{$lang->cmd_delete}">{$lang->cmd_delete}

			<input type="checkbox" name="cart" value="{$val->module_srl}" class="selectedModule" data-mid="{$val->mid}" data-browser_title="{$val->browser_title}" />

			{$lang->no_board_instance}

		 {$lang->youtube_insert_menu}

		 {$lang->youtube_manage_selected_menu}

<form cond="$page_navigation" action="./" class="x_pagination center" no-error-return-url="true" style="margin-top:0">
	{@
		$urlInfo = parse_url(getRequestUriByServerEnviroment());
		parse_str($urlInfo['query'], $param);
	}
	<input loop="$param => $key, $val" cond="!in_array($key, array('mid', 'vid', 'act'))" type="hidden" name="{$key}" value="{$val}" />

 {$lang->first_page}

		<block cond="$page_navigation->first_page != 1 && $page_navigation->first_page + $page_navigation->page_count > $page_navigation->last_page - 1 && $page_navigation->page_count != $page_navigation->total_page">
		{@$isGoTo = true}

			cmd_go_to_page}">…

				<input type="number" min="1" max="{$page_navigation->last_page}" required name="page" title="{$lang->cmd_go_to_page}" />
				<button type="submit" class="x_add-on">Go</button>

		</block>

		{@$last_page = $page_no}

{$page_no}

		<block cond="$last_page != $page_navigation->last_page && $last_page + 1 != $page_navigation->last_page">
		{@$isGoTo = true}

			cmd_go_to_page}">…

				<input type="number" min="1" max="{$page_navigation->last_page}" required name="page" title="{$lang->cmd_go_to_page}" />
				<button type="submit" class="x_add-on">Go</button>

		</block>

last_page">last_page)}" title="{$page_navigation->last_page}">{$lang->last_page}

</form>
<form action="" class="search x_input-append center" no-error-return-url="true">
	<input loop="$param => $key, $val" cond="!in_array($key, array('mid', 'vid', 'act', 'page', 'search_target', 'search_keyword'))" type="hidden" name="{$key}" value="{$val}" />
	<select cond="count($module_category)" name="module_category_srl" title="{$lang->module_category}" style="margin-right:4px">
		<option value="" selected="selected"|cond="!$module_category_srl">{$lang->all}</option>
		<option value="0" selected="selected"|cond="$module_category_srl==='0'">{$lang->not_exists}</option>
		<option value="{$key}" loop="$module_category => $key,$val"  selected="selected"|cond="$module_category_srl==$key">{$val->title}</option>
	</select>
	<select name="kind" title="{$lang->search_target}" style="margin-right:4px">
		<option value="mid" selected="selected"|cond="$search_target=='mid'">{$lang->mid}</option>
		<option value="browser_title" selected="selected"|cond="$search_target=='browser_title'">{$lang->browser_title}</option>
	</select>
	<input type="search" required name="keyword" value="{htmlspecialchars($search_keyword)}" />
	<button class="x_btn x_btn-inverse" type="submit"> {$lang->cmd_search}</button>
	 {$lang->cmd_cancel}
</form>


text:
 [](#skip-navbar_top "Skip navigation links")

<colgroup>
<col width="50%" />
<col width="50%" />
</colgroup>

 Overview
Package
Class
Use
Tree
Deprecated
Index
Help

 PREV   NEXT
FRAMES    NO FRAMES
All Classes

------------------------------------------------------------------------

Struts Faces 1.3.10 API
=======================

**Packages**

**[org.apache.struts.faces](org/apache/struts/faces/package-summary.html.md)**

**[org.apache.struts.faces.application](org/apache/struts/faces/application/package-summary.html.md)**

**[org.apache.struts.faces.component](org/apache/struts/faces/component/package-summary.html.md)**

**[org.apache.struts.faces.renderer](org/apache/struts/faces/renderer/package-summary.html.md)**

**[org.apache.struts.faces.taglib](org/apache/struts/faces/taglib/package-summary.html.md)**

**[org.apache.struts.faces.util](org/apache/struts/faces/util/package-summary.html.md)**

------------------------------------------------------------------------

 [](#skip-navbar_bottom "Skip navigation links")

<colgroup>
<col width="50%" />
<col width="50%" />
</colgroup>

 Overview
Package
Class
Use
Tree
Deprecated
Index
Help

 PREV   NEXT
FRAMES    NO FRAMES
All Classes

------------------------------------------------------------------------

Copyright © 2000-2008 [Apache Software Foundation](http://www.apache.org/). All Rights Reserved.


text:
#include "common.h"

extern enum bst_result_t bst_result;

CREATE_FLAG(flag_is_connected);
CREATE_FLAG(flag_is_encrypted);

static struct bt_conn *g_conn;

static void connected(struct bt_conn *conn, uint8_t err)
{
	char addr[BT_ADDR_LE_STR_LEN];

	bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));

	if (err != 0) {
		FAIL("Failed to connect to %s (%u)\n", addr, err);

		return;
	}

	printk("Connected to %s\n", addr);

	g_conn = bt_conn_ref(conn);
	SET_FLAG(flag_is_connected);
}

static void disconnected(struct bt_conn *conn, uint8_t reason)
{
	char addr[BT_ADDR_LE_STR_LEN];

	if (conn != g_conn) {
		return;
	}

	bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));

	printk("Disconnected: %s (reason 0x%02x)\n", addr, reason);

	bt_conn_unref(g_conn);

	g_conn = NULL;
	UNSET_FLAG(flag_is_connected);
}

static void security_changed(struct bt_conn *conn, bt_security_t level,
			     enum bt_security_err security_err)
{
	if (security_err == BT_SECURITY_ERR_SUCCESS && level > BT_SECURITY_L1) {
		SET_FLAG(flag_is_encrypted);
	}
}

BT_CONN_CB_DEFINE(conn_callbacks) = {
	.connected = connected,
	.disconnected = disconnected,
	.security_changed = security_changed,
};

#define ARRAY_ITEM(i, _) i
static const uint8_t chrc_data[] = { LISTIFY(CHRC_SIZE, ARRAY_ITEM, (,)) }; /* 1, 2, 3 ... */

static ssize_t read_test_chrc(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf,
			      uint16_t len, uint16_t offset)
{
	printk("Characteristic read\n");

	return bt_gatt_attr_read(conn, attr, buf, len, offset, (const void *)chrc_data, CHRC_SIZE);
}

BT_GATT_SERVICE_DEFINE(test_svc, BT_GATT_PRIMARY_SERVICE(TEST_SERVICE_UUID),
		       BT_GATT_CHARACTERISTIC(TEST_CHRC_UUID, BT_GATT_CHRC_READ, BT_GATT_PERM_READ,
					      read_test_chrc, NULL, NULL));

static struct bt_gatt_attr additional_attributes[] = {
	BT_GATT_CHARACTERISTIC(TEST_ADDITIONAL_CHRC_UUID, 0, BT_GATT_PERM_NONE, NULL, NULL, NULL),
};

static struct bt_gatt_service additional_gatt_service = BT_GATT_SERVICE(additional_attributes);

static void test_main_common(bool connect_eatt)
{
	int err;
	const struct bt_data ad[] = { BT_DATA_BYTES(BT_DATA_FLAGS,
						    (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)) };

	backchannel_init();

	err = bt_enable(NULL);
	if (err != 0) {
		FAIL("Bluetooth init failed (err %d)\n", err);

		return;
	}

	printk("Bluetooth initialized\n");

	err = bt_le_adv_start(BT_LE_ADV_CONN_NAME, ad, ARRAY_SIZE(ad), NULL, 0);
	if (err != 0) {
		FAIL("Advertising failed to start (err %d)\n", err);

		return;
	}

	printk("Advertising successfully started\n");

	WAIT_FOR_FLAG(flag_is_connected);

	if (connect_eatt) {
		WAIT_FOR_FLAG(flag_is_encrypted);

		err = bt_eatt_connect(g_conn, CONFIG_BT_EATT_MAX);
		if (err) {
			FAIL("Failed to connect EATT channels (err %d)\n", err);

			return;
		}
	}

	/* Wait for client to do discovery and configuration */
	backchannel_sync_wait();

	printk("Registering additional service\n");
	err = bt_gatt_service_register(&additional_gatt_service);
	if (err < 0) {
		FAIL("Registering additional service failed (err %d)\n", err);
	}

	/* Signal to client that additional service is registered */
	backchannel_sync_send();

	/* Wait for client to be done reading */
	backchannel_sync_wait();

	PASS("GATT server passed\n");
}

static void test_main_eatt(void)
{
	test_main_common(true);
}

static void test_main_no_eatt(void)
{
	test_main_common(false);
}

static const struct bst_test_instance test_gatt_server[] = {
	{
		.test_id = "gatt_server_eatt",
		.test_post_init_f = test_init,
		.test_tick_f = test_tick,
		.test_main_f = test_main_eatt,
	},
	{
		.test_id = "gatt_server_no_eatt",
		.test_post_init_f = test_init,
		.test_tick_f = test_tick,
		.test_main_f = test_main_no_eatt,
	},
	BSTEST_END_MARKER,
};

struct bst_test_list *test_gatt_server_install(struct bst_test_list *tests)
{
	return bst_add_tests(tests, test_gatt_server);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
 Copyright 2013 The Android Open Source Project

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

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->
<resources>
    <string name="app_name">WatchFace</string>
    <string name="intro_message">
        <![CDATA[

This sample demonstrates how to create watch faces for android wear and includes a phone app
and a wearable app. The wearable app has a variety of watch faces including analog, digital,
opengl, calendar, etc. It also includes a watch-side configuration example. The phone app
includes a phone-side configuration example.

        ]]>
    </string>
</resources>


text: <!DOCTYPE >Hello


text:
@interface NormalDismissAnimation : NSObject<UIViewControllerAnimatedTransitioning>

@end


text:
module Sequences
  module CanonicalCeleryHelpers
    refine Mutations::HashFilter do
      def color
        string :color, in: Sequence::COLORS
      end

      def args
        hash :args, default: ({}) do
          optional do
            hash :locals do
              # Let CeleryScript lib do the type checking...
              duck :*, methods: []
            end
          end
        end
      end

      def body
        duck :body, methods: [:[], :[]=, :each, :map]
      end
    end
  end
end


text:
package com.naver.android.view.rotatableview.view;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.naver.android.view.rotatableview.OnRotateEndListener;
import com.naver.android.view.rotatableview.Rotatable;
import com.naver.android.view.rotatableview.helper.RotatableImageViewHelper;

//-- https://groups.google.com/forum/?fromgroups=#!topic/android-developers/_JrJ8Wii7E8
//-- setFitToScreenFlag를 custom properties로 빼려고 했으나 위의 이유로 제거
//-- 라이브러리 프로젝트에서 custom properties를 넣으면 main에서 재정의가 필요

public class RotatableImageView extends ImageView implements Rotatable {
	RotatableImageViewHelper rotatableHelper = new RotatableImageViewHelper(this);

	public RotatableImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RotatableImageView(Context context) {
        super(context);
    }

    @Override
	public void setOrientation(int orientation, boolean animation) {
		rotatableHelper.setOrientation(orientation, animation);
    }

    @Override
    protected void onDraw(Canvas canvas) {
		rotatableHelper.onDraw(canvas);
    }

	public void setFitToScreenFlag(boolean fitToScreenFlag) {
		rotatableHelper.setFitToScreenFlag(fitToScreenFlag);
	}

    public void setRotateEndListener(OnRotateEndListener onRotateEndListener){
        rotatableHelper.setRotateEndListener(onRotateEndListener);
    }
}


text:
== Release v0.4.0 (2020-02-26) ==

	* Fix ruby 2.3 bug
	* Fix a truffleruby bug
	* Fix minitest warnings
	* Add rgb_colors.json.gz
	* Support old ruby versions
	* Update for ruby 2.7
	* Add todo
	* bin/simplecolor: showcase now show more about the base colors

== Release v0.3.0 (2019-05-02) ==

	* Update Readme
	* color schemes: move to data/
	* Add tests for color names
	* Add lots of color names
	* More tests
	* Add tests for local_color/global_color
	* Replace colorer by colorer2
	* colorer2: bug fixes
	* colorer2: better global color detection
	* colorer2
	* Add test
	* attributes_from_colors: support 256 and truecolors
	* SimpleColor[]
	* Add :color0 ... :color15
	* RGB: fix color conversion
	* Abstract 8/16 color palette
	* Rgb color names can by symbols
	* Effects
	* RGB: can specify default @background
	* RGB.to_hex
	* Rename rgb_constants to rgb_colors
	* SimpleColor.fill
	* Color names: use a constant
	* RGB: custom color names
	* Color names
	* Random: this is a rgb color rather than an abbreviation
	* colorer: better recursive handling
	* Change names of options
	* Put Colorer in its own fle
	* Rework the way we construct mixins
	* Move constants around
	* Color names: use a Proc
	* Fixing all tests!
	* Use constants
	* More bug fixes
	* Misc bug fixes
	* Use new RGB class
	* Class RGB
	* Begin new RGB class
	* New key: colornames
	* Showcase + solarized shortcut
	* Bug fixes + tests
	* bin: --color=number
	* Add binary
	* Correctly dup arg
	* proc in color: return multiple values
	* Small tweak
	* Test proc
	* Add :random, :on_random shortcuts
	* test: simplify resetting default options
	* rgb color: support background mode with Array
	* color_module: copy current options
	* Shortcuts: be more general
	* Fix test
	* Shortcuts
	* tests
	* Color names: switch to json data
	* Improve regexp
	* Fixes for 256 colors
	* Add Hex mode
	* Raise when passed non supported parameters
	* Add color_mode parameter
	* 256 colors
	* Continue rgb handling
	* Update Rakefile
	* Rakefile: add mapping
	* Update Rakefile
	* Add rgb.rb, from the paint gem
	* Preliminary for truecolor support
	* SimpleColor.color_strings
	* color_module: shortcuts
	* Add tests
	* Generate new coloring module
	* enabled should be a singleton method
	* Add tests
	* uncolor, color?: work in shell mode
	* Add mixin.rb to help mix in String
	* Copyright
	* Whitespace

== Release v0.2.0 (2017-02-20) ==

	* Add minitest dependency
	* Fix binary strings
	* Correct a bug on uncolor when there was no colors
	* attribute_from_colors
	* Bugfixes
	* Better color regexps
	* Bug fixes
	* Mix attributes and ANSI strings
	* Color entities and add tests
	* Typos
	* function to handle existing colors
	* Concatenate ANSI escape sequences inside the \e
	* Add possibility to copy colors
	* Sometimes \e[m is abused for \e[0m
	* More exceptions
	* Merge some color regexp and raise exception on bogus colors
	* Fix SimpleColor#uncolor!
	* Change ANSI Regexps
	* rake doc fails for now with Rake 11
	* Add uncolor tests
	* ColorWrapper: unify gestion of arg
	* Correct a bug in uncolor
	* Add more tests
	* Add color! and uncolor!
	* Specify mode even when nothing is passed
	* Add color?
	* Add more tests
	* Split the module into small unit modules
	* Add warning to use v0.1.0
	* First step to add a Colorer class
	* typo
	* Put simplecolor.rb in lib/ rather than lib/simplecolor/
	* Improve documentation
	* Describe SimpleColor.enabled
	* sh code block
	* README: use code block
	* Adding a simple test
	* Shortcut for mixing in class
	* Update homepage

== Release v0.1.0 (2013-08-23) ==

	* Add more ANSI effects
	* Update documentation
	* First public version
	* Initial commit.


text:
package cgeo.geocaching.connector;

import cgeo.geocaching.CgeoApplication;
import cgeo.geocaching.R;
import cgeo.geocaching.enumerations.StatusCode;
import cgeo.geocaching.network.Cookies;
import cgeo.geocaching.settings.Credentials;
import cgeo.geocaching.settings.Settings;

import org.apache.commons.lang3.StringUtils;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;

public abstract class AbstractLogin {

    /**
     * {@code true} if logged in, {@code false} otherwise
     */
    private boolean actualLoginStatus = false;
    private String actualUserName = StringUtils.EMPTY;
    /**
     * Number of caches found. An unknown number is signaled by the value -1, while 0 really indicates zero caches found
     * by the user.
     */
    private int actualCachesFound = -1;
    private String actualStatus = StringUtils.EMPTY;

    public void setActualCachesFound(final int found) {
        actualCachesFound = found;
    }

    public String getActualStatus() {
        return actualStatus;
    }

    protected void setActualStatus(final String status) {
        actualStatus = status;
    }

    public boolean isActualLoginStatus() {
        return actualLoginStatus;
    }

    protected void setActualLoginStatus(final boolean loginStatus) {
        actualLoginStatus = loginStatus;
    }

    public String getActualUserName() {
        return actualUserName;
    }

    protected void setActualUserName(final String userName) {
        actualUserName = userName;
    }

    public int getActualCachesFound() {
        return actualCachesFound;
    }

    protected void resetLoginStatus() {
        Cookies.clearCookies();
        Settings.setCookieStore(null);

        setActualLoginStatus(false);
    }

    protected void clearLoginInfo() {
        resetLoginStatus();

        setActualCachesFound(-1);
        setActualStatus(CgeoApplication.getInstance().getString(R.string.err_login));
    }

    @NonNull
    public StatusCode login() {
        return login(null);
    }

    @NonNull
    public StatusCode login(@Nullable final Credentials credentials) {
        if (!CgeoApplication.getInstance().isNetworkConnected()) {
            return StatusCode.COMMUNICATION_ERROR;
        }
        if (credentials == null) {
            return login(true);
        }
        return login(true, credentials);
    }

    @NonNull
    protected abstract StatusCode login(final boolean retry);

    @NonNull
    protected abstract StatusCode login(final boolean retry, @NonNull final Credentials credentials);

}


text:
namespace System.Activities.DurableInstancing
{
    using System;
    using System.Collections.Generic;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Runtime;
    using System.Runtime.DurableInstancing;
    using System.Text;
    using System.Transactions;

    abstract class WorkflowOwnerAsyncResult : SqlWorkflowInstanceStoreAsyncResult
    {
        public WorkflowOwnerAsyncResult
            (
            InstancePersistenceContext context,
            InstancePersistenceCommand command,
            SqlWorkflowInstanceStore store,
            SqlWorkflowInstanceStoreLock storeLock,
            Transaction currentTransaction,
            TimeSpan timeout,
            AsyncCallback callback,
            object state
            ) :
            base(context, command, store, storeLock, currentTransaction, timeout, callback, state)
        {
        }

        protected override void GenerateSqlCommand(SqlCommand sqlCommand)
        {
            base.StoreLock.TakeModificationLock();
        }

        protected override void OnCommandCompletion()
        {
            base.StoreLock.ReturnModificationLock();
        }
    }
}


text:
/**
 * app.js
 *
 * Short demonstration of ti-notification usage
 *
 * @author: Manuel Lehner (manumaticx@gmail.com)
 * See https://github.com/manumaticx/ti-notifications for info
 */

var notification = require('lib/ti-notification');

Titanium.UI.setBackgroundColor('#000');

var tabGroup = Titanium.UI.createTabGroup();

var win1 = Titanium.UI.createWindow({
    title:'ALERT',
    backgroundColor:'#fff',
    barColor: '#000'
});
var tab1 = Titanium.UI.createTab({
    icon:'KS_nav_views.png',
    title:'Tab 1',
    window:win1
});

var button1 = Ti.UI.createButton({
	title:'show alert'
});
button1.addEventListener('click', function(){
	// a single line of code:
	notification.show(notification.type.ALERT, 'Something went wrong :-(');
});
win1.add(button1);

var win2 = Titanium.UI.createWindow({
    title:'CONFIRM',
    backgroundColor:'#fff',
    barColor: '#000'
});
var tab2 = Titanium.UI.createTab({
    icon:'KS_nav_ui.png',
    title:'Tab 2',
    window:win2
});

var button2 = Ti.UI.createButton({
	title:'show confirm'
});
button2.addEventListener('click', function(){
	// a single line of code:
	notification.show(notification.type.CONFIRM, 'Some better news here :-)');
});
win2.add(button2);

var win3 = Titanium.UI.createWindow({
    title:'INFO',
    backgroundColor:'#fff',
    barColor: '#000'
});
var tab3 = Titanium.UI.createTab({
    icon:'KS_nav_views.png',
    title:'Tab 3',
    window:win3
});

var button3 = Ti.UI.createButton({
	title:'show info'
});
button3.addEventListener('click', function(){
	// a single line of code:
	notification.show(notification.type.INFO, 'Some info');
});
win3.add(button3);

tabGroup.addTab(tab1);
tabGroup.addTab(tab2);
tabGroup.addTab(tab3);

tabGroup.open();


text:
/**
 *
 */
package at.free23.shipping.api;

/**
 * @author michael.vlasaty
 *
 */
public class LineItemDto {
	private Long id;
	private Long quantity;
	private String uuid;

	public LineItemDto() {
	}

	public LineItemDto(Long id, Long quantity, String uuid) {
		this.id = id;
		this.quantity = quantity;
		this.uuid = uuid;
	}

	public Long getId() {
		return this.id;
	}

	public Long getQuantity() {
		return this.quantity;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public void setQuantity(Long quantity) {
		this.quantity = quantity;
	}

	public String getUuid() {
		return this.uuid;
	}

	public void setUuid(String uuid) {
		this.uuid = uuid;
	}
}


text:
using System;
using System.Collections.Generic;
using AspNet.Security.OpenIdConnect.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using RawRabbit;
using Venture.Common.Extensions;
using Venture.Gateway.Business.Commands;
using Venture.Gateway.Business.Models;
using Venture.Gateway.Business.Queries;

namespace Venture.Gateway.Service.Controllers
{
    [Produces("application/json")]
    [Route("/v1/projects")]
    public class ProjectController : Controller
    {
        private readonly IBusClient _bus;

        public ProjectController(IBusClient bus)
        {
            _bus = bus;
        }

        [HttpGet]
        [Route("{id}")]
        public IActionResult Get(Guid id)
        {
            var query = new GetProjectQuery(id);
            var result = _bus.PublishQuery(query);

            if (result == null)
            {
                return NotFound();
            }

            var project = JsonConvert.DeserializeObject<ProjectViewModel>(result);

            return Ok(project);
        }

        [HttpGet]
        public IActionResult Get()
        {
            var query = new GetProjectsQuery();
            var result = _bus.PublishQuery(query);

            var project = JsonConvert.DeserializeObject<List<ProjectViewModel>>(result);

            return new JsonResult(project);
        }

        [Authorize]
        [HttpPost]
        public IActionResult Post([FromBody]ProjectCreateModel model)
        {
            var command = new CreateProjectCommand(model.Title, model.Description, new Guid(User.GetClaim("id")));
            _bus.PublishCommand(command);
            return Ok();
        }

        [Authorize]
        [HttpPatch]
        [Route("{id}")]
        public IActionResult Patch(Guid id, [FromBody]ProjectUpdateModel model)
        {
            var query = new GetProjectQuery(id);
            var project = _bus.PublishQuery(query);

            // validation
            if (project == null)
            {
                return NotFound();
            }

            var command = new UpdateProjectCommand(id, model.Title, model.Description);
            _bus.PublishCommand(command);
            return Ok();
        }

        [Authorize]
        [HttpDelete]
        [Route("{id}")]
        public IActionResult Delete(Guid id)
        {
            var query = new GetProjectQuery(id);
            var project = _bus.PublishQuery(query);

            // validation
            if (project == null)
            {
                return NotFound();
            }

            var command = new DeleteProjectCommand(id);
            _bus.PublishCommand(command);
            return Ok();
        }

        [Authorize]
        [HttpPost]
        [Route("{id}/chat")]
        public IActionResult PostComment(Guid id, [FromBody]CommentPostModel model)
        {
            var query = new GetProjectQuery(id);
            var project = _bus.PublishQuery(query);

            // validation
            if (project == null)
            {
                return NotFound();
            }

            var command = new PostCommentOnProjectCommand(id, new Guid(User.GetClaim("id")), model.Content, DateTime.Now);
            _bus.PublishCommand(command);
            return Ok();
        }

        [HttpGet]
        [Route("{id}/chat")]
        public IActionResult GetComments(Guid id)
        {
            var query = new GetProjectCommentsQuery(id);
            var result = _bus.PublishQuery(query);

            if (result == null)
            {
                return NotFound();
            }

            var chat = JsonConvert.DeserializeObject<List<CommentViewModel>>(result);

            return Ok(chat);
        }
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.contentwarehouse.v1.model;

/**
 * This proto is filled with n-gram data during model building.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the contentwarehouse API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class RepositoryWebrefUniversalNgramData extends com.google.api.client.json.GenericJson {

  /**
   * IDF of the n-gram.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Float idf;

  /**
   * Probability that the n-gram is a plural form of a word. This information is extracted from SAFT
   * annotations of queries. See HasPluralProperty().
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Float pluralProb;

  /**
   * IDF of the n-gram.
   * @return value or {@code null} for none
   */
  public java.lang.Float getIdf() {
    return idf;
  }

  /**
   * IDF of the n-gram.
   * @param idf idf or {@code null} for none
   */
  public RepositoryWebrefUniversalNgramData setIdf(java.lang.Float idf) {
    this.idf = idf;
    return this;
  }

  /**
   * Probability that the n-gram is a plural form of a word. This information is extracted from SAFT
   * annotations of queries. See HasPluralProperty().
   * @return value or {@code null} for none
   */
  public java.lang.Float getPluralProb() {
    return pluralProb;
  }

  /**
   * Probability that the n-gram is a plural form of a word. This information is extracted from SAFT
   * annotations of queries. See HasPluralProperty().
   * @param pluralProb pluralProb or {@code null} for none
   */
  public RepositoryWebrefUniversalNgramData setPluralProb(java.lang.Float pluralProb) {
    this.pluralProb = pluralProb;
    return this;
  }

  @Override
  public RepositoryWebrefUniversalNgramData set(String fieldName, Object value) {
    return (RepositoryWebrefUniversalNgramData) super.set(fieldName, value);
  }

  @Override
  public RepositoryWebrefUniversalNgramData clone() {
    return (RepositoryWebrefUniversalNgramData) super.clone();
  }

}


text:
Reports information about Windows service status.

Monitoring some services may require running Telegraf with administrator
privileges.

## Global configuration options <!-- @/docs/includes/plugin_config.md -->

In addition to the plugin-specific configuration settings, plugins support
additional global and plugin configuration settings. These settings are used to
modify metrics, tags, and field or create aliases and configure ordering, etc.
See the [CONFIGURATION.md][CONFIGURATION.md] for more details.

[CONFIGURATION.md]: ../../../docs/CONFIGURATION.md

## Configuration

```toml @sample.conf
# Input plugin to report Windows services info.
[[inputs.win_services]]
  ## Names of the services to monitor. Leave empty to monitor all the available services on the host. Globs accepted. Case sensitive.
  service_names = [
    "LanmanServer",
    "TermService",
    "Win*",
  ]
  excluded_service_names = ['WinRM'] # optional, list of service names to exclude
```

## Metrics

- win_services
  - state : integer
  - startup_mode : integer

The `state` field can have the following values:

- 1 - stopped
- 2 - start pending
- 3 - stop pending
- 4 - running
- 5 - continue pending
- 6 - pause pending
- 7 - paused

The `startup_mode` field can have the following values:

- 0 - boot start
- 1 - system start
- 2 - auto start
- 3 - demand start
- 4 - disabled

### Tags

- All measurements have the following tags:
  - service_name
  - display_name

## Example Output

```shell
win_services,host=WIN2008R2H401,display_name=Server,service_name=LanmanServer state=4i,startup_mode=2i 1500040669000000000
win_services,display_name=Remote\ Desktop\ Services,service_name=TermService,host=WIN2008R2H401 state=1i,startup_mode=3i 1500040669000000000
```

### TICK Scripts

A sample TICK script for a notification about a not running service.  It sends a
notification whenever any service changes its state to be not _running_ and when
it changes that state back to _running_.  The notification is sent via an HTTP
POST call.

```shell
stream
    |from()
        .database('telegraf')
        .retentionPolicy('autogen')
        .measurement('win_services')
        .groupBy('host','service_name')
    |alert()
        .crit(lambda: "state" != 4)
        .stateChangesOnly()
        .message('Service {{ index .Tags "service_name" }} on Host {{ index .Tags "host" }} is in state {{ index .Fields "state" }} ')
        .post('http://localhost:666/alert/service')
```