text:
echo ""
echo "Extract Query 1: What source files were YW annotations extracted from?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/eq01.rq

echo ""
echo "Extract Query 2: What are the names of all program blocks?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/eq02.rq

echo ""
echo "Extract Query 3: What out ports are qualified with URIs?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/eq03.rq

echo ""
echo "Extract Query 4: What ports are qualified with URIs?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/eq04.rq

echo ""
echo "Query 1: Where is the definition of block simulate_data_collection.collect_data_set?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq01.rq

echo ""
echo "Query 2: What is the name and description of the top-level workflow?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq02.rq

echo ""
echo "Query 3: What are the names of any top-level functions?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq03.rq

echo ""
echo "Query 4: What are the names of the programs comprising the top-level workflow?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq04.rq

echo ""
echo "Query 5: What are the names and descriptions of the inputs to the top-level workflow?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq05.rq

echo ""
echo "Query 6: What data is output by program block simulate_data_collection.collect_data_set?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq06.rq

echo ""
echo "Query 7: What program blocks provide input directly to simulate_data_collection.collect_data_set?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq07.rq

echo ""
echo "Query 8: What programs have input ports that receive data simulate_data_collection[cassette_id]"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq08.rq

echo ""
echo "Query 9: How many ports read data simulate_data_collection[frame_number]?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq09.rq

echo ""
echo "Query 10: How many data are read by more than port in workflow simulate_data_collection?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq10.rq

echo ""
echo "Query 11: What program blocks are immediately downstream of calculate_strategy?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq11.rq

echo ""
echo "Query 12: What program blocks are immediately upstream of transform_images?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq12.rq
echo ""
echo "Query 13: (UpstreamProgramName) - What program blocks are upstream of transform_images?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq13.rq

echo ""
echo "Query 14: What program blocks are anywhere downstream of calculate_strategy?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq14.rq

echo ""
echo "Query 15 (DownstreamDataName): What data is immediately downstream of raw_image?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq15.rq

echo ""
echo "Query 16 (UpstreamDataName): What data is immediately upstream of raw_image?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq16.rq

echo ""
echo "Query 17 (DownstreamDataName): What data is downstream of accepted_sample?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq17.rq

echo ""
echo "Query 18 (UpstreamDataName): What data is upstream of raw_image?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq18.rq

echo ""
echo "Query 19: What URI variables are associated with writes of data simulate_data_collection[corrected_image]"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq19.rq

echo ""
echo "Query 20: What URI variables do data written to raw_image and corrected_image have in common?"
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq20.rq

echo ""
echo "Query 21: What data is downstream 2 levels from data energies?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq21.rq

echo ""
echo "Query 22: What data is upstream 2 levels from data corrected_image?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq22.rq

echo ""
echo "Query 23: What program blocks are upstream 3 levels from block transform_images?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq23.rq

echo ""
echo "Query 24: What program blocks are downstream 3 levels from block load_screening_results?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq24.rq

echo ""
echo "Query 25: What program blocks are common upstream blocks of block collect_data_set and log_rejected_sample?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq25.rq

echo ""
echo "Query 26: What program block is the closet upstream block (LCA) of block collect_data_set and log_rejected_sample in common?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq26.rq

echo ""
echo "Query 27: Print all program blocks and their descendant programs with downstream levels in the workflow."
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq27.rq

echo ""
echo "Query 28: Print the names of all ports used as parameters."
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq28.rq

echo ""
echo "Query 29: Print the names of all input ports (including both input data and input parameters)."
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq29.rq

echo ""
echo "Query 30: Print all data only connected by param ports."
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq30.rq

echo ""
echo "Query 31: Print all data only connected by output ports and param ports."
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq31.rq

echo ""
echo "Query 32: Print all data only connected by output ports and input data ports without param ports."
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq32.rq

echo ""
echo "Query 33: What program blocks are in between of program load_screening_results and transform_images?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq33.rq

echo ""
echo "Query 34: What program blocks are in between of data sample_name and total_intensity?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq34.rq

echo ""
echo "Query 35:What data is in between of data sample_name and total_intensity?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/mq35.rq

echo ""
echo "pq01: Is there a channel between output port collect_data_set[frame_number] and input port transform_images[frame_number]?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/pq01.rq

echo ""
echo "Is there a channel between program collect_data_set and log_average_image_intensity?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/pq02.rq

echo ""
echo "What are the channels between program collect_data_set and log_average_image_intensity?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/pq03.rq

echo ""
echo "How many channels does output port collect_data_set[frame_number] connect to? What are they?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/pq04.rq

echo ""
echo "How many channels are there between program collect_data_set and transform_images?"
echo ""
arq --data simulate_data_collection_wf_model_v8.ttl                                                     \
    --query ~/DataONE-Prov-Summer-2017/examples/simulate_data_collection/SPARQL-queries/Jena-ARQ/queries/pq05.rq


text:
package openperipheral.addons.ticketmachine;

import com.google.common.base.Preconditions;
import cpw.mods.fml.common.registry.GameRegistry;
import java.util.Set;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.IIcon;
import net.minecraftforge.common.util.ForgeDirection;
import openmods.api.IHasGui;
import openmods.api.IIconProvider;
import openmods.api.IInventoryCallback;
import openmods.api.IPlaceAwareTile;
import openmods.include.IncludeInterface;
import openmods.inventory.GenericInventory;
import openmods.inventory.IInventoryProvider;
import openmods.sync.SyncableBoolean;
import openmods.sync.SyncableString;
import openmods.tileentity.SyncedTileEntity;
import openmods.utils.ColorUtils;
import openmods.utils.ColorUtils.ColorMeta;
import openmods.utils.ItemUtils;
import openperipheral.api.adapter.Asynchronous;
import openperipheral.api.adapter.method.Arg;
import openperipheral.api.adapter.method.Optionals;
import openperipheral.api.adapter.method.ReturnType;
import openperipheral.api.adapter.method.ScriptCallable;
import openperipheral.api.architecture.FeatureGroup;
import openperipheral.api.peripheral.PeripheralTypeId;

@PeripheralTypeId("openperipheral_ticketmachine")
@FeatureGroup("openperipheral-ticketmachine")
public class TileEntityTicketMachine extends SyncedTileEntity implements IPlaceAwareTile, IHasGui, IIconProvider, IInventoryProvider, IInventoryCallback {

	private static final int SLOT_PAPER = 0;
	private static final int SLOT_INK = 1;
	private static final int SLOT_OUTPUT = 2;

	private final Item ticketItem;

	private static class CustomInventory extends GenericInventory implements ISidedInventory {
		private CustomInventory() {
			super("ticketmachine", false, 3);
		}

		@Override
		public boolean isItemValidForSlot(int i, ItemStack itemstack) {
			if (itemstack == null) return false;

			switch (i) {
				case SLOT_PAPER:
					return itemstack.getItem() == Items.paper;
				case SLOT_INK: {
					Set<ColorMeta> color = ColorUtils.stackToColor(itemstack);
					return color != null && color.contains(ColorMeta.BLACK);
				}
				default:
					return false;
			}
		}

		@Override
		public int[] getAccessibleSlotsFromSide(int side) {
			return new int[] { SLOT_INK, SLOT_PAPER, SLOT_OUTPUT };
		}

		@Override
		public boolean canInsertItem(int slot, ItemStack stack, int side) {
			return isItemValidForSlot(slot, stack);
		}

		@Override
		public boolean canExtractItem(int slot, ItemStack stack, int side) {
			return slot == SLOT_OUTPUT;
		}
	}

	@IncludeInterface(ISidedInventory.class)
	protected GenericInventory inventory = new CustomInventory().addCallback(this);

	@Override
	public IInventory getInventory() {
		return inventory;
	}

	protected SyncableBoolean hasTicket;
	protected SyncableString owner;

	@Override
	protected void createSyncedFields() {
		hasTicket = new SyncableBoolean();
		owner = new SyncableString();
	}

	public TileEntityTicketMachine() {
		ItemStack ticketStack = GameRegistry.findItemStack("Railcraft", "routing.ticket", 1);
		ticketItem = ticketStack != null? ticketStack.getItem() : null;
		syncMap.addUpdateListener(createRenderUpdateListener());
	}

	@ScriptCallable(returnTypes = ReturnType.BOOLEAN, description = "Create a new ticket to the specified destination")
	public boolean createTicket(@Arg(name = "destination", description = "The destination for the ticket") String destination,
			@Arg(name = "amount") @Optionals Integer amount) {
		if (amount == null) amount = 1;
		else Preconditions.checkArgument(amount > 0 && amount <= 64, "Amount must be between 1 and 64");

		ItemStack paperStack = inventory.getStackInSlot(SLOT_PAPER);
		Preconditions.checkArgument(inventory.isItemValidForSlot(SLOT_PAPER, paperStack) && paperStack.stackSize >= amount, "Not enough paper");

		ItemStack inkStack = inventory.getStackInSlot(SLOT_INK);
		Preconditions.checkArgument(inventory.isItemValidForSlot(SLOT_INK, inkStack) && inkStack.stackSize >= amount, "Not enough ink");

		ItemStack output = inventory.getStackInSlot(SLOT_OUTPUT);

		ItemStack newTicket = new ItemStack(ticketItem);
		NBTTagCompound tag = ItemUtils.getItemTag(newTicket);
		tag.setString("owner", owner.getValue());
		tag.setString("dest", destination);

		if (output == null) {
			inventory.setInventorySlotContents(SLOT_OUTPUT, newTicket);
		} else if (ItemStack.areItemStackTagsEqual(output, newTicket) && output.isItemEqual(newTicket) && output.stackSize + amount <= output.getMaxStackSize()) {
			output.stackSize += amount;
		} else throw new IllegalArgumentException("No place in output slot");

		inventory.decrStackSize(SLOT_PAPER, amount);
		inventory.decrStackSize(SLOT_INK, amount);

		worldObj.playSoundEffect(xCoord + 0.5D, yCoord + 0.5D, zCoord + 0.5D, "openperipheraladdons:ticketmachine", 0.3F, 0.6F);
		sync();

		return true;
	}

	@Asynchronous
	@ScriptCallable(returnTypes = ReturnType.STRING, description = "Returns owner of this machine")
	public String getOwner() {
		return owner.getValue();
	}

	@Override
	public void onInventoryChanged(IInventory inventory, int slotNumber) {
		if (worldObj.isRemote) return;
		boolean nowHasTicket = inventory.getStackInSlot(SLOT_OUTPUT) != null;
		if (nowHasTicket != hasTicket.getValue()) hasTicket.set(nowHasTicket);
		markUpdated();
	}

	@Override
	public void onBlockPlacedBy(EntityPlayer player, ForgeDirection side, ItemStack stack, float hitX, float hitY, float hitZ) {
		owner.setValue(player.getCommandSenderName());
	}

	@Override
	public IIcon getIcon(ForgeDirection rotatedDir) {
		if (rotatedDir == ForgeDirection.SOUTH) return hasTicket.getValue()? BlockTicketMachine.iconFrontTicket : BlockTicketMachine.iconFrontEmpty;
		return null;
	}

	@Override
	public Object getServerGui(EntityPlayer player) {
		return new ContainerTicketMachine(player.inventory, this);
	}

	@Override
	public Object getClientGui(EntityPlayer player) {
		return new GuiTicketMachine(new ContainerTicketMachine(player.inventory, this));
	}

	@Override
	public boolean canOpenGui(EntityPlayer player) {
		return true;
	}

	@Override
	public void writeToNBT(NBTTagCompound tag) {
		super.writeToNBT(tag);
		inventory.writeToNBT(tag);
	}

	@Override
	public void readFromNBT(NBTTagCompound tag) {
		super.readFromNBT(tag);
		inventory.readFromNBT(tag);
	}
}

redpajama_set_name: RedPajamaGithub


text:
if you put files in this directory they will be uploaded to couchdb on adapter install/upgrade.
they can then be accessed via http://<couch>:5984/<adapter-name>/...


text: {% include 'supporttools/default_sidelinks.html' %}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:background="@color/lavender" >

	<com.llb.nature.util.PullToRefreshListView
		android:id="@+id/lv_news3"
		android:layout_width="fill_parent"
		android:layout_height="match_parent"
		android:layout_marginLeft="4dp"
		android:layout_marginRight="4dp"
		android:layout_marginTop="3dp"
		android:divider="@color/lavender"
		android:dividerHeight="5sp"
		android:fadingEdge="none"
		android:fastScrollEnabled="true" />

</RelativeLayout>


text:
namespace Poco {
namespace XML {

NamedNodeMap::~NamedNodeMap()
{
}

} } // namespace Poco::XML


text:
package org.apache.felix.ipojo.runtime.core.test.components;

import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Property;
import org.apache.felix.ipojo.annotations.Provides;
import org.apache.felix.ipojo.runtime.core.test.services.HelloService;

/**
 * User: guillaume
 * Date: 20/02/2014
 * Time: 13:29
 */
@Component(name = "hello-service")
@Provides
public class EnglishHelloService2 implements HelloService {

    @Property("Hello")
    private String message;

    @Override
    public String hello(final String name) {
        return message + " " + name;
    }
}


text:
<?php

namespace Renatomefi\ApiBundle\Tests;

use Renatomefi\ApiBundle\Tests\Auth\AssertClientCredentials;
use Renatomefi\ApiBundle\Tests\Auth\AssertClientCredentialsInterface;
use Renatomefi\ApiBundle\Tests\Auth\AssertOAuth;
use Renatomefi\ApiBundle\Tests\Auth\AssertOAuthInterface;
use Renatomefi\ApiBundle\Tests\Auth\AssertUserInfo;
use Renatomefi\ApiBundle\Tests\Auth\OAuthClient;
use Renatomefi\ApiBundle\Tests\Auth\OAuthClientInterface;
use Renatomefi\TestBundle\Rest\AssertRestUtils;
use Renatomefi\TestBundle\Rest\AssertRestUtilsInterface;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\HttpFoundation\Response;

/**
 * Class LogoutTest
 * @package Renatomefi\ApiBundle\Tests
 */
class LogoutTest extends WebTestCase implements AssertClientCredentialsInterface, OAuthClientInterface, AssertRestUtilsInterface, AssertOAuthInterface
{
    use AssertClientCredentials, OAuthClient, AssertRestUtils, AssertOAuth, AssertUserInfo;

    /**
     * @param array $params
     * @param array $headers
     * @return null|Response
     */
    protected function getLogout($params = [], $headers = [])
    {
        $client = static::createClient();

        $client->request('GET', '/logout', $params, [], $headers);

        return $client->getResponse();
    }

    /**
     * @param $accessToken
     * @return null|Response
     */
    protected function getUserInfo($accessToken)
    {
        $client = static::createClient();

        $client->request('GET', '/api/user/info',
            ['access_token' => $accessToken]
        );

        return $client->getResponse();
    }

    /**
     * Test logout action
     */
    public function testLogout()
    {
        $response = $this->getLogout();

        $this->assertEquals(Response::HTTP_OK, $response->getStatusCode());
    }

    /**
     * @depends testLogout
     */
    public function testLogoutClearCredentialsFromCookies()
    {
        $clientCredentials = $this->getAdminCredentials();

        $client = static::createClient();

        $client->getCookieJar()->set(
            new Cookie('access_token', $clientCredentials->access_token)
        );

        $client->getCookieJar()->set(
            new Cookie('refresh_token', $clientCredentials->refresh_token)
        );

        $client->request('GET', '/logout');

        $logoutResponse = $client->getResponse();

        $this->assertEquals(Response::HTTP_OK, $logoutResponse->getStatusCode());

        $response = $this->getUserInfo($clientCredentials->access_token);

        $this->assertOAuthInvalidToken($response);
    }

    /**
     * @depends testLogout
     */
    public function testLogoutClearCredentialsFromHeader()
    {
        $clientCredentials = $this->getAdminCredentials();

        $logoutResponse = $this->getLogout([], [
            'HTTP_AUTHORIZATION' => 'Bearer ' . $clientCredentials->access_token
        ]);

        $this->assertEquals(Response::HTTP_OK, $logoutResponse->getStatusCode());

        $response = $this->getUserInfo($clientCredentials->access_token);

        $this->assertOAuthInvalidToken($response);
    }

    /**
     * @depends testLogout
     */
    public function testLogoutClearCredentialsFromParam()
    {
        $clientCredentials = $this->getAdminCredentials();

        $adminResponse = $this->getUserInfo($clientCredentials->access_token);

        $adminData = json_decode($adminResponse->getContent());

        $this->assertUserInfoObjStructure($adminData);
        $this->assertUserInfoObjAdminAuth($adminData);

        $logoutResponse = $this->getLogout([
            'access_token' => $clientCredentials->access_token
        ]);

        $this->assertEquals(Response::HTTP_OK, $logoutResponse->getStatusCode());

        $response = $this->getUserInfo($clientCredentials->access_token);

        $this->assertOAuthInvalidToken($response);
    }
}


text:
package geeksforgeeks;

import geeksforgeeks._01DataStructures_BinaryTree_00.Node;
import ctci._05queue;

/*
 * http://www.geeksforgeeks.org/connect-nodes-at-same-level/
 * Connect nodes at same level
 */;
 public class _01DataStructures_BinaryTree_28 {
	 public static void main(String[] args) {
		 _01DataStructures_BinaryTree_00 binaryTree1=new _01DataStructures_BinaryTree_00();
		 binaryTree1.insert(null,null,1);
		 binaryTree1.insert(1,"left",2);
		 binaryTree1.insert(1,"right",3);
		 binaryTree1.insert(2,"left",4);
		 binaryTree1.insert(2,"right",5);
		 binaryTree1.insert(3,"right",6);
		 binaryTree1.preOrder();
		 connectNodes(binaryTree1);
		 printConnections(binaryTree1);
	 }

	 private static void printConnections(
			 _01DataStructures_BinaryTree_00 binaryTree1) {
		 printConnections(binaryTree1.rootNode);
	 }

	 private static void printConnections(
			 geeksforgeeks._01DataStructures_BinaryTree_00.Node node) {
		 if(node!=null)
		 {
			 System.out.print(node.data+",");
			 Node mainNode=node;
			 while(mainNode.nextRight!=null){
				 System.out.print(mainNode.nextRight.data+",");
				 mainNode=mainNode.nextRight;
			 }
			 if(node.left!=null)
				 printConnections(node.left);
			 else if(node.right!=null)
				 printConnections(node.right);
		 }

	 }

	 private static void connectNodes(_01DataStructures_BinaryTree_00 binaryTree1) {
		 leveOrderTraversal(binaryTree1.rootNode);
		 System.out.println();
	 }

	 private static void leveOrderTraversal(Node node) {
		 if(node!=null){
			 tempQueue1 queue=new tempQueue1();
			 _05queue levelsQueue=new _05queue();
			 Node n=node;
			 int mainlevel=1,level=1;
			 while(n!=null){
				 System.out.print(n.data+"/"+level+",");
				 if(n.left!=null){
					 queue.add(n.left);
					 levelsQueue.add(getLevel(node,n.left));
				 }
				 if(n.right!=null){
					 queue.add(n.right);
					 levelsQueue.add(getLevel(node,n.right));
				 }

				 level=levelsQueue.poll();
				 Node temp=n;
				 n=queue.poll();
				 if(level==mainlevel)
					 temp.nextRight=n;
				 else
					 mainlevel=level;
			 }
		 }

	 }

	 private static int getLevel(
			 geeksforgeeks._01DataStructures_BinaryTree_00.Node node,
			 geeksforgeeks._01DataStructures_BinaryTree_00.Node left) {

		 return getLevel(node,left.data,1);
	 }

	 private static int getLevel(
			 geeksforgeeks._01DataStructures_BinaryTree_00.Node node,
			 Integer data, int level) {
		 if(node==null)
			 return 0;
		 if(node.data==data)
			 return level;
		 int downLevel=getLevel(node.left,data,level+1);
		 if(downLevel!=0)
			 return downLevel;
		 downLevel=getLevel(node.right,data,level+1);
		 return downLevel;

	 }

 }
 class tempQueue1 {
	 Node headNode;
	 Node exitNode;
	 int noOfElements=0;
	 public _01DataStructures_BinaryTree_00.Node poll(){//Retrieves and removes the head of this queue, or returns null if this queue is empty.
		 _01DataStructures_BinaryTree_00.Node returnData=null;
		 if(headNode!=null)
		 {
			 returnData=headNode.data;
			 headNode=headNode.next;
			 noOfElements--;
		 }
		 return returnData;
	 }
	 public _01DataStructures_BinaryTree_00.Node peek(){//Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
		 if(headNode!=null)
			 return headNode.data;
		 return null;
	 }
	 public Boolean isEmpty(){
		 return noOfElements==0?true:false;
	 }
	 public void clear(){
		 noOfElements=0;
		 headNode=exitNode=null;
	 }
	 public void add(_01DataStructures_BinaryTree_00.Node value){
		 if(headNode==null){
			 headNode=new Node();
			 headNode.data=value;
			 exitNode=headNode;
		 }
		 else{
			 Node newNode=new Node();
			 newNode.data=value;
			 exitNode.next=newNode;
			 exitNode=newNode;
		 }
		 noOfElements++;
	 }
	 public _01DataStructures_BinaryTree_00.Node remove(){//Retrieves and removes the head of this queue. This method differs from poll only in that it throws an exception if this queue is empty.
		 _01DataStructures_BinaryTree_00.Node returnData=null;
		 if(headNode!=null)
		 {
			 returnData=headNode.data;
			 headNode=headNode.next;
			 noOfElements--;
		 }
		 return returnData;
	 }
	 public Boolean contains(_01DataStructures_BinaryTree_00.Node value){
		 Node pointerNode=new Node();
		 pointerNode=headNode;
		 while(pointerNode!=null){
			 if(pointerNode.data==value)
				 return true;
			 pointerNode=pointerNode.next;
		 }
		 return false;
	 }
	 public int size(){
		 return noOfElements;
	 }
	 public String toString(){
		 StringBuilder outputStringBuilder=new StringBuilder();
		 Node pointerNode=new Node();
		 pointerNode=headNode;
		 while(pointerNode!=null){
			 outputStringBuilder.append(pointerNode.data+"\n");
			 pointerNode=pointerNode.next;
		 }
		 return outputStringBuilder.toString();
	 }

	 class Node{
		 _01DataStructures_BinaryTree_00.Node data;
		 Node next;
		 Integer level=0;
		 public _01DataStructures_BinaryTree_00.Node getData() {
			 return data;
		 }
		 public void setData(_01DataStructures_BinaryTree_00.Node data) {
			 this.data = data;
		 }
		 public Node getNext() {
			 return next;
		 }
		 public void setNext(Node next) {
			 this.next = next;
		 }

	 }
 }


text:
package net.runelite.client.externalplugins;

import java.lang.invoke.MethodHandles;
import java.net.URL;
import java.net.URLClassLoader;
import lombok.Getter;
import lombok.Setter;
import net.runelite.client.util.ReflectUtil;

class ExternalPluginClassLoader extends URLClassLoader implements ReflectUtil.PrivateLookupableClassLoader
{
	@Getter
	private final ExternalPluginManifest manifest;

	@Getter
	@Setter
	private MethodHandles.Lookup lookup;

	ExternalPluginClassLoader(ExternalPluginManifest manifest, URL[] urls)
	{
		super(urls, ExternalPluginClassLoader.class.getClassLoader());
		this.manifest = manifest;
		ReflectUtil.installLookupHelper(this);
	}

	@Override
	public Class<?> defineClass0(String name, byte[] b, int off, int len) throws ClassFormatError
	{
		return super.defineClass(name, b, off, len);
	}
}


text:
package jena;

public class sparql
{
    // Call-through to arq command line application
    public static void main(String[] args)
    {
        query.invokeCmd("arq.sparql",args) ;
    }
}


text:
layout: post
title: How do you check if an array contains duplicate values in typescript or javascript?
---

One of the famous interview question is:

> How do you check if an array contains duplicate values?

This is a data structures related interview question. So language is not a bar for this. There are so many solutions provided in many different languages. Here is my suggestion using `ES6`:

```
function CheckIfAnArrayContainsDuplicateValues(myArray) {
  return myArray.length === new Set(myArray).size;
}
```

This is how you can test it:

```
let uniqueArray = [1, 2, 3, 4, 5];
console.log(`Does ${uniqueArray} contains duplicates? : ${CheckIfAnArrayContainsDuplicateValues(uniqueArray)}`);

let nonUniqueArray = [1, 1, 2, 3, 4, 5];
console.log(`Does ${nonUniqueArray} contains duplicates? : ${CheckIfAnArrayContainsDuplicateValues(nonUniqueArray)}`);
```

Hope this helps!


text:
function HeaderCtrl($scope, $timeout, $mdSidenav) {
	'use strict';
	$scope.toggleMenu = function () {
		$mdSidenav('sidenav').toggle();
	};

}

HeaderCtrl.$inject = ['$scope', '$timeout', '$mdSidenav'];

module.exports = HeaderCtrl;


text:
require 'kwalify/util/hashlike'

module Babel

  ##
  class Team
    include Kwalify::Util::HashLike
    attr_accessor :name             # str
    attr_accessor :desc             # str
    attr_accessor :chief            # map
    attr_accessor :members          # seq
  end

  ##
  class Member
    include Kwalify::Util::HashLike
    attr_accessor :name             # str
    attr_accessor :desc             # str
    attr_accessor :team             # map
  end

end


text:
const webpack = require(`webpack`);

/* common config options */

let webpackConfig = {
  entry: `./src/index.js`,

  module: {
    loaders: [{
      loader: `babel-loader`,
      test: /\.js$/
    }]
  },

  resolve: {
    extensions: [ ``, `.js` ]
  }
};

/* env-specific config options */

switch (process.env.NODE_ENV) {

  case `development`:

    webpackConfig = Object.assign({}, webpackConfig, {
      output: {
        filename: `eleanor.js`,
        library: true,
        libraryTarget: `commonjs2`,
        path: `${__dirname}/dev`
      }
    });

    break;

  case `production`:

    webpackConfig = Object.assign({}, webpackConfig, {
      output: {
        filename: `eleanor.js`,
        library: true,
        libraryTarget: `commonjs2`,
        path: `${__dirname}/dist`
      },
      plugins: [
        new webpack.optimize.UglifyJsPlugin({
          minimize: true
        })
      ]
    });

    break;
  default:
}

module.exports = webpackConfig;


text:
package frogcraftrebirth.common.item;

import frogcraftrebirth.common.block.BlockMPS;
import frogcraftrebirth.common.lib.item.ItemFrogBlock;
import ic2.api.item.ElectricItem;
import ic2.api.item.IElectricItem;
import net.minecraft.client.resources.I18n;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.NonNullList;
import net.minecraft.world.World;

import java.util.List;

public class ItemMPS extends ItemFrogBlock implements IElectricItem {

	public ItemMPS(BlockMPS block) {
		super(block, aStack -> "normal");
		setHasSubtypes(false);
		setMaxStackSize(1);
	}

	@Override
	public boolean canProvideEnergy(ItemStack itemStack) {
		return true;
	}

	@Override
	public double getMaxCharge(ItemStack itemStack) {
		normalize(itemStack);
		return itemStack.getTagCompound().getInteger("maxCharge");
	}

	@Override
	public int getTier(ItemStack itemStack) {
		normalize(itemStack);
		return itemStack.getTagCompound().getInteger("tier");
	}

	@Override
	public double getTransferLimit(ItemStack itemStack) {
		normalize(itemStack);
		return itemStack.getTagCompound().getInteger("tier") * 32;
	}

	@Override
	public void getSubItems(CreativeTabs tab, NonNullList<ItemStack> list) {
		if (this.isInCreativeTab(tab)) {
			// Add necessary NBT data so that we won't get NPE.
			ItemStack discharged = normalize(new ItemStack(this, 1, 0));
			list.add(discharged.copy());
			ElectricItem.manager.charge(discharged, 60000, 1, true, false);
			list.add(discharged);
		}
	}

	@Override
	public void addInformation(ItemStack stack, World worldIn, List<String> aList, ITooltipFlag flag) {
		aList.add(I18n.format("tile.mobilePowerStation.info"));
	}

	public static ItemStack normalize(ItemStack stack) {
		if (stack.getItem() instanceof ItemMPS && !stack.hasTagCompound()) {
			NBTTagCompound newTag = new NBTTagCompound();
			newTag.setInteger("charge", 0);
			newTag.setInteger("maxCharge", 60000);
			newTag.setInteger("tier", 1);
			stack.setTagCompound(newTag);
			return stack;
		} else
			return stack; // Prevent attaching unnecessary data to other item
	}

}


text:
@**
* Yobi, Project Hosting SW
*
* Copyright 2013 NAVER Corp.
* http://yobi.io
*
* @Author Jihan Kim
*
* 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.
**@
@(project:Project, totalIssues:Double)

@import utils.TemplateHelper._
@import scala.collection.mutable._

@if(Issue.countIssues(project.id, State.OPEN) == 0){

@Messages("issue.is.empty")

        @Messages("issue.menu.new")

} else {
    @for(member <- project.members) {
        @defining(countOpenIssuesBy(project, Map("assigneeId"->member.user.id.toString))) { assignedIssues =>
            @defining(getPercent(assignedIssues, totalIssues)){ assignedPerc =>
                @if(assignedIssues > 0){

                            member.user.id.toString))"
                            class="usf-group" title="@member.user.name (@{"@"}@member.user.loginId)">

                                @member.user.name
                                 @{"@"}@member.user.loginId

                            @assignedIssues
                            (@assignedPerc%)

                }
            }
        }
    }

    @defining(countOpenIssuesBy(project, Map("assigneeId"->User.anonymous.id.toString))) { notAssignedIssues =>
        @defining(getPercent(notAssignedIssues, totalIssues)) { notAssignedPerc =>

                    User.anonymous.id.toString))">
                    @Messages("issue.noAssignee")

                    @notAssignedIssues
                    (@notAssignedPerc%)

        }
    }
}


text:
* Review course [outline](./README.md) especially prerequisites
* Fill-out course questionnaire


text:
package com.battlelancer.seriesguide.billing.amazon;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import com.amazon.device.iap.PurchasingService;
import com.amazon.device.iap.model.FulfillmentResult;
import com.amazon.device.iap.model.Product;
import com.amazon.device.iap.model.Receipt;
import com.amazon.device.iap.model.UserData;
import com.battlelancer.seriesguide.R;
import com.battlelancer.seriesguide.settings.AdvancedSettings;
import de.greenrobot.event.EventBus;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import timber.log.Timber;

public class AmazonIapManager {

    public static class AmazonIapMessageEvent {
        public final int messageResId;

        public AmazonIapMessageEvent(int messageResId) {
            this.messageResId = messageResId;
        }
    }

    public static class AmazonIapPriceEvent {
        public final Product product;

        public AmazonIapPriceEvent(Product product) {
            this.product = product;
        }
    }

    public static class AmazonIapAvailabilityEvent {
        public final boolean productAvailable;
        public final boolean userCanSubscribe;

        public AmazonIapAvailabilityEvent(boolean productAvailable, boolean userCanSubscribe) {
            this.productAvailable = productAvailable;
            this.userCanSubscribe = userCanSubscribe;
        }
    }

    private static AmazonIapManager amazonIapManager;

    /**
     * Sets up Amazon IAP.
     *
     * <p> Ensure to call this in {@code onCreate} of any activity before making calls to the
     * instance retrieved by {@link #get()}.
     */
    public static synchronized void setup(Context context) {
        if (amazonIapManager != null) {
            return;
        }
        AmazonIapManager iapManager = new AmazonIapManager(context);
        PurchasingService.registerListener(context.getApplicationContext(),
                new AmazonPurchasingListener(iapManager));
        Timber.i("IAP sandbox mode is: " + PurchasingService.IS_SANDBOX_MODE);
        amazonIapManager = iapManager;
    }

    /**
     * Ensure you have called {@link #setup} once in the main activity of the app or this will
     * return {@code null}.
     */
    public static AmazonIapManager get() {
        return amazonIapManager;
    }

    private final Context context;
    private final SubscriptionDataSource dataSource;

    private boolean userDataAvailable;
    private boolean subAvailable;
    private UserIapData userIapData;

    public AmazonIapManager(Context context) {
        this.context = context.getApplicationContext();
        this.dataSource = new SubscriptionDataSource(context);
        this.userDataAvailable = false;
        this.subAvailable = false;
        this.userIapData = null;
    }

    /**
     * Call this in e.g. {@code onStart} to request data about all available products.
     *
     * <p> If successful, a {@link com.battlelancer.seriesguide.billing.amazon.AmazonIapManager.AmazonIapPriceEvent}
     * will be posted.
     */
    public void requestProductData() {
        // get product availability
        Timber.d("getProductData");
        final Set<String> productSkus = new HashSet<>();
        for (final AmazonSku mySku : AmazonSku.values()) {
            productSkus.add(mySku.getSku());
        }
        PurchasingService.getProductData(productSkus);
    }

    /**
     * Call this in {@code onResume} to update the current user's data and to request the latest
     * purchase updates from Amazon.
     *
     * <p> If successful, one or more {@link com.battlelancer.seriesguide.billing.amazon.AmazonIapManager.AmazonIapAvailabilityEvent}
     * will be posted.
     *
     * <p> In addition on failure, a {@link com.battlelancer.seriesguide.billing.amazon.AmazonIapManager.AmazonIapMessageEvent}
     * with an error message will be posted.
     */
    public void requestUserDataAndPurchaseUpdates() {
        Timber.d("getUserData");
        PurchasingService.getUserData();
        Timber.d("getPurchaseUpdates");
        PurchasingService.getPurchaseUpdates(false);
    }

    /**
     * Connect to the database when main activity's {@code onResume} before calling {@link
     * #requestUserDataAndPurchaseUpdates()}.
     */
    public void activate() {
        dataSource.open();
    }

    /**
     * Gracefully close the database in the activity's {@code onPause}.
     */
    public void deactivate() {
        dataSource.close();
    }

    /**
     * Checks if the current user has an active subscription. If the user was subscribed, but now is
     * not {@link com.battlelancer.seriesguide.billing.amazon.AmazonBillingActivity} is launched.
     *
     * <p> If user or sub data could not be fetched, keeps the last subscription state.
     */
    public void validateSubscription(Activity activity) {
        Timber.d("validateSubscription");
        boolean isSubscribed;
        if (userIapData != null) {
            loadSubscriptionRecords();

            isSubscribed = userIapData.isSubsActiveCurrently();
        } else if (userDataAvailable) {
            // user is not logged in
            isSubscribed = false;
        } else {
            // data could not be fetched, keep last sub state
            return;
        }

        // update state
        boolean isSubscribedOld = AdvancedSettings.getLastSubscriptionState(activity);
        AdvancedSettings.setSubscriptionState(activity, isSubscribed);

        // notify if subscription has expired
        if (isSubscribedOld && !isSubscribed) {
            activity.startActivity(new Intent(activity, AmazonBillingActivity.class));
            activity.finish();
        }
    }

    /**
     * Method to set the app's amazon user id and marketplace from IAP SDK responses.
     */
    protected void setAmazonUserId(final String newAmazonUserId,
            final String newAmazonMarketplace) {
        userDataAvailable = true;

        // Reload everything if the Amazon user has changed.
        if (newAmazonUserId == null) {
            // A null user id typically means there is no registered Amazon account.
            if (userIapData != null) {
                userIapData = null;
                refreshSubsAvailability();
            }
        } else if (userIapData == null || !newAmazonUserId.equals(userIapData.getAmazonUserId())) {
            // If there was no existing Amazon user then either no customer was
            // previously registered or the application has just started.

            // If the user id does not match then another Amazon user has registered.
            userIapData = new UserIapData(newAmazonUserId, newAmazonMarketplace);
            refreshSubsAvailability();
        }
    }

    protected void enablePurchaseForSkus(final Map<String, Product> productData) {
        // currently only one sku (try-then-buy subscription)
        Product product = productData.get(AmazonSku.SERIESGUIDE_SUB.getSku());
        if (product != null) {
            subAvailable = true;
            EventBus.getDefault().post(new AmazonIapPriceEvent(product));
        }
    }

    protected void disablePurchaseForSkus(final Set<String> unavailableSkus) {
        if (unavailableSkus.contains(AmazonSku.SERIESGUIDE_SUB.toString())) {
            subAvailable = false;
            // reasons for product not available can be:
            // * Item not available for this country
            // * Item pulled off from Appstore by developer
            // * Item pulled off from Appstore by Amazon
            EventBus.getDefault()
                    .post(new AmazonIapMessageEvent(R.string.subscription_unavailable));
        }
    }

    protected void disableAllPurchases() {
        this.subAvailable = false;
        refreshSubsAvailability();
    }

    /**
     * This method contains the business logic to fulfill the customer's purchase based on the
     * receipt received from InAppPurchase SDK's {@link com.amazon.device.iap.PurchasingListener#onPurchaseResponse}
     * or {@link com.amazon.device.iap.PurchasingListener#onPurchaseUpdatesResponse}.
     */
    protected void handleSubscriptionPurchase(final Receipt receipt, final UserData userData) {
        try {
            if (receipt.isCanceled()) {
                // Check whether this receipt is for an expired or canceled subscription
                revokeSubscription(receipt);
            } else {
                // We strongly recommend that you verify the receipt on server-side.

                // don't care for now
                //if (!verifyReceiptFromYourService(receipt.getReceiptId(), userData)) {
                //    // if the purchase cannot be verified,
                //    // show relevant error message to the customer.
                //    return;
                //}

                grantSubscriptionPurchase(receipt, userData);
            }
        } catch (Throwable e) {
            EventBus.getDefault().post(new AmazonIapMessageEvent(R.string.subscription_failed));
        }
    }

    private void grantSubscriptionPurchase(final Receipt receipt, final UserData userData) {
        final AmazonSku amazonSku = AmazonSku.fromSku(receipt.getSku());
        // Verify that the SKU is still applicable.
        if (amazonSku != AmazonSku.SERIESGUIDE_SUB) {
            Timber.w("The SKU [" + receipt.getSku() + "] in the receipt is not valid anymore ");
            // if the sku is not applicable anymore, call
            // PurchasingService.notifyFulfillment with status "UNAVAILABLE"
            PurchasingService.notifyFulfillment(receipt.getReceiptId(),
                    FulfillmentResult.UNAVAILABLE);
            return;
        }
        try {
            // Set the purchase status to fulfilled for your application
            saveSubscriptionRecord(receipt, userData.getUserId());
            AdvancedSettings.setSubscriptionState(context, true);
            PurchasingService.notifyFulfillment(receipt.getReceiptId(),
                    FulfillmentResult.FULFILLED);
        } catch (final Throwable e) {
            // If for any reason the app is not able to fulfill the purchase,
            // add your own error handling code here.
            Timber.e("Failed to grant entitlement purchase, with error " + e.getMessage());
        }
    }

    protected void handleReceipt(final Receipt receipt, final UserData userData) {
        switch (receipt.getProductType()) {
            case CONSUMABLE:
                // check consumable sample for how to handle consumable purchases
                break;
            case ENTITLED:
                // check entitlement sample for how to handle consumable purchases
                break;
            case SUBSCRIPTION:
                handleSubscriptionPurchase(receipt, userData);
                break;
        }
    }

    protected void purchaseFailed() {
        EventBus.getDefault().post(new AmazonIapMessageEvent(R.string.subscription_failed));
    }

    protected void refreshSubsAvailability() {
        final boolean available = subAvailable && userIapData != null
                && userIapData.getAmazonUserId() != null;
        EventBus.getDefault().post(new AmazonIapAvailabilityEvent(available,
                userIapData != null && !userIapData.isSubsActiveCurrently()));
    }

    /**
     * Reload the subscription history from database
     */
    protected void reloadSubscriptionStatus() {
        loadSubscriptionRecords();
        refreshSubsAvailability();
    }

    private void loadSubscriptionRecords() {
        final List<SubscriptionRecord> subsRecords = dataSource.getSubscriptionRecords(
                userIapData.getAmazonUserId());
        userIapData.setSubscriptionRecords(subsRecords);
    }

    /**
     * Save subscription purchase detail locally.
     */
    private void saveSubscriptionRecord(final Receipt receipt, final String userId) {
        dataSource
                .insertOrUpdateSubscriptionRecord(receipt.getReceiptId(),
                        userId,
                        receipt.getPurchaseDate().getTime(),
                        receipt.getCancelDate() == null ? SubscriptionRecord.TO_DATE_NOT_SET
                                : receipt.getCancelDate().getTime(),
                        receipt.getSku());
    }

    private void revokeSubscription(final Receipt receipt) {
        final String receiptId = receipt.getReceiptId();
        dataSource.cancelSubscription(receiptId, receipt.getCancelDate().getTime());
    }
}


text:
@implementation DKTransitionDelegate

- (id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
{
    DKAnimationTransition *transitioning = [DKAnimationTransition new];
    return transitioning;
}

- (id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    DKAnimationTransition *transitioning = [DKAnimationTransition new];
    transitioning.reverse = YES;
    return transitioning;
}
@end


text:
module Pacific
class DeployDatabase
def initialize(yamlObject)
	@applicationName = yamlObject.applicationName
	@filename = yamlObject.filename
	@sshUser = yamlObject.databaseSshUser || yamlObject.webserverSshUser
	@webserverIP = yamlObject.webserverIP
	@databaseIP = yamlObject.databaseIP || @webserverIP
	@databaseName = yamlObject.databaseName #|| "sqlite3"
	@sshPort = yamlObject.databaseSshPort || yamlObject.webserverSshPort
	@identityFile = yamlObject.databaseIdentityFile || yamlObject.webserverIdentityFile
	@IP = @databaseIP || @webserverIP
	@databaseVersion = yamlObject.databaseVersion
	@remote = Remote.new(@IP,@sshUser,@sshPort,@identityFile,@filename,@deploymentUser)
end

def deployDatabase
	@remote.setPwd if !@remote.pwd
	if @applicationName
		@remote.installYaml
		# @remote.installPacificGem #remove it
		$pacificBranch = Pacific.run("git branch | grep \\* | cut -d\" \" -f2", stdout: true)
		$pacificBranch = false if $pacificBranch.match(/detached/)
		$pacificCurrentCommit = Pacific.run("git rev-parse HEAD", stdout: true)
		puts "\e[0;31mWarning:\e[m You are currently off B R A N C H !!!.\nIgnore this warning if you have reference #{$pacificCurrentCommit} upstream. Ctrl + c to stop." if !$pacificBranch
		puts "Deploying branch:\e[1;34m #{$pacificBranch}\e[m" if $pacificBranch
		tasks = []
		tasks << {tasks: "sudo puppet apply /usr/local/pacific/manifests/postgresusers.pp",
			message: "Preapring database for #{@applicationName}."} if @databaseName && @databaseName.include?("postgres")
		tasks << {task: "sudo puppet apply /usr/local/pacific/manifests/sqlite3.pp",
			message: "Checking for sqlite3..."} if @databaseName && @databaseName.include?("sqlite")
		@remote.doTask(tasks) if !tasks.empty?
		@remote.download("/var/lib/postgresql/.#{@applicationName}AppPass","/var/www/#{@applicationName}/#{@applicationName}/config/.#{@applicationName}AppPass") if @databaseIP != @webserverIP
	end
end

def deployBareMetal
	@remote.setPwd if !@remote.pwd
	@remote.installPacificGem @databaseIP if @databaseIP != @webserverIP
	tasks = []
	tasks << {task: "sudo puppet apply /usr/local/pacific/manifests/postgresql.pp",
		message: "Installing postgresql #{@databaseVersion}. Please, wait."} if @databaseName && @databaseName.include?("postgres")
	tasks << {task: "sudo puppet apply /usr/local/pacific/manifests/sqlite3.pp",
		message: "Installing sqlite3."} if @databaseName && @databaseName.include?("sqlite")
	@remote.doTask(tasks) if !tasks.empty?
end
end;end


text:
/*
 * if viewport is MOBILE
 * ----------------------------------------------- */
function isMobile() {
    var breakpoint = 768;
    var isMobile = false;

    isMobile = updateIsMobile(breakpoint);

    window.addEventListener("DOMContentLoaded", function (event) {
        isMobile = updateIsMobile(breakpoint);
    });

    return isMobile;
}

function updateIsMobile(breakpoint) {
    return document.body.clientWidth < breakpoint;
}

/*
 *
 * ----------------------------------------------- */
$('.d-flex-media').each(function(index, value) {
    var all = $(this).find(".flex-grow-1 .title").map(function() {
        return this.innerHTML;
    }).get();

    if (isMobile()) {
        $(this).find(".flex-grow-1 .title").hide();
    }

    if (isMobile()) {
        $(this).find(".title-sp").html(all.join());
    }
});


text:
'use strict';

var express = require('express');
var router = express.Router();
var passport = require('passport');

var User = require('../models/user');
var Room = require('../models/room');

// Главная страница
router.get('/', function(req, res, next) {
    // Если пользователь авторизован, перекидываем на страницу с комнатами
    if (req.isAuthenticated()) {
        res.redirect('/rooms');
    } else {
        res.render('login', {
            success: req.flash('success')[0],
            errors: req.flash('error'),
            showRegisterForm: req.flash('showRegisterForm')[0]
        });
    }
});

// Авторизация
router.post('/login', passport.authenticate('local', {
    successRedirect: '/rooms',
    failureRedirect: '/',
    failureFlash: true
}));

// Регистрация
router.post('/register', function(req, res, next) {

    var credentials = {
        'username': req.body.username,
        'password': req.body.password,
        'email': req.body.email
    };

    if (credentials.username === '' || credentials.password === '' || credentials.email === '') {
        req.flash('error', 'Ошибка регистрации');
        req.flash('showRegisterForm', true);
        res.redirect('/');
    } else {

        // Проверяем уникальность логина
        User.findOne({
            'username': new RegExp('^' + req.body.username + '$', 'i')
        }, function(err, user) {
            if (err) throw err;
            if (user) {
                req.flash('error', 'Такой пользователь уже есть!');
                req.flash('showRegisterForm', true);
                res.redirect('/');
            } else {
                User.create(credentials, function(err, newUser) {
                    if (err) throw err;
                    req.flash('success', 'Вы успешно зарегистрированы!');
                    res.redirect('/');
                });
            }
        });
    }
});

// Комнаты
router.get('/rooms', [User.isAuthenticated, function(req, res, next) {
    Room.find(function(err, rooms) {
        if (err) throw err;
        res.render('rooms', {
            rooms
        });
    });
}]);

// Чат
router.get('/chat/:id', [User.isAuthenticated, function(req, res, next) {
    var roomId = req.params.id;
    Room.findById(roomId, function(err, room) {
        if (err) throw err;
        if (!room) {
            return next();
        }
        res.render('chatroom', {
            user: req.user,
            room: room
        });
    });

}]);

// Выход
router.get('/logout', function(req, res, next) {
    // убираем req.user
    req.logout();

    // удаляем сессию
    req.session = null;

    // перенаправляем на главную страницу
    res.redirect('/');
});

module.exports = router;


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Phlyctidium astrantiae Wallr.

### Remarks
null


text:
@interface PodsDummy_LionheartExtensions : NSObject
@end
@implementation PodsDummy_LionheartExtensions
@end


text:
export default {
  path: 'sample/request',
  getComponent (nextState, cb) {
    let app = this.app
    require.ensure([], require => {
      cb(null, require('./'))
    }, 'request')
  },
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />

    <package name="default" namespace="/" extends="struts-default">

		<!--
			Spring 整合 Struts2 时, 在 Struts2 中配置的 Spring 的 Action 的 class 需要指向 IOC 容器中该 bean 的 id
		-->
		<action name="person-save" class="personAction">
			<result>/success.jsp</result>
		</action>

    </package>

</struts>


text:
/*=========================================================================================
    File Name: line-stacked-area.js
    Description: Chartjs line stacked area chart
    ----------------------------------------------------------------------------------------
    Item Name: Robust - Responsive Admin Theme
    Version: 1.2
    Author: PIXINVENT
    Author URL: http://www.themeforest.net/user/pixinvent
==========================================================================================*/

// Line stacked area chart
// ------------------------------
$(window).on("load", function(){

    //Get the context of the Chart canvas element we want to select
    // var ctx = document.getElementById("line-stacked-area").getContext("2d");
    var ctx = $('#line-stacked-area');

    // Chart Options
    var chartOptions = {
        responsive: true,
        maintainAspectRatio: false,
        legend: {
            position: 'bottom',
        },
        hover: {
            mode: 'label'
        },
        scales: {
            xAxes: [{
                display: true,
                gridLines: {
                    color: "#f3f3f3",
                    drawTicks: false,
                },
                scaleLabel: {
                    display: true,
                    labelString: 'Month'
                }
            }],
            yAxes: [{
                display: true,
                gridLines: {
                    color: "#f3f3f3",
                    drawTicks: false,
                },
                scaleLabel: {
                    display: true,
                    labelString: 'Value'
                }
            }]
        },
        title: {
            display: true,
            text: 'Chart.js Line Chart - Legend'
        }
    };

    // Chart Data
    var chartData = {
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [{
            label: "My First dataset",
            data: [65, 59, 80, 81, 56, 55, 40],
            backgroundColor: "rgba(103, 58, 183,.4)",
            borderColor: "transparent",
            pointBorderColor: "#673AB7",
            pointBackgroundColor: "#FFF",
            pointBorderWidth: 2,
            pointHoverBorderWidth: 2,
            pointRadius: 4,
        }, {
            label: "My Second dataset",
            data: [28, 48, 40, 19, 86, 27, 90],
            backgroundColor: "rgba(0,188,212,.4)",
            borderColor: "transparent",
            pointBorderColor: "#00BCD4",
            pointBackgroundColor: "#FFF",
            pointBorderWidth: 2,
            pointHoverBorderWidth: 2,
            pointRadius: 4,
        }, {
            label: "My Third dataset",
            data: [80, 25, 16, 36, 67, 18, 76],
            backgroundColor: "rgba(255,87,34,.4)",
            borderColor: "transparent",
            pointBorderColor: "#FF5722",
            pointBackgroundColor: "#FFF",
            pointBorderWidth: 2,
            pointHoverBorderWidth: 2,
            pointRadius: 4,
        }]
    };

    var config = {
        type: 'line',

        // Chart Options
        options : chartOptions,

        // Chart Data
        data : chartData
    };

    // Create the chart
    var stackedAreaChart = new Chart(ctx, config);
});


text:
<?php

namespace Chalcedonyt\COSProcessor\Factory\Column;

use Chalcedonyt\COSProcessor\Column\Column;

class LeftPaddedDecimalWithoutDelimiterColumnFactory
{
    /**
     * This column has a fixed length and contains a decimal value without a delimiter.
     * E.g. with a length of 6 and a value of 10, the final value would be "001000"
     * @param String. Any passed value will be cast to a string. E.g. 0 will be cast to "0"
     * @param int. The fixed length of the string
     * @param String An optional label for the column, used in error messages.
     * @return Column
     */
    public static function create($value, $length, $label = ''){
        //need to test this thoroughly.
        $value = (string)(round($value, 2)*100);
        $column = new Column();
        $column -> setFixedLength($length);
        $column -> setLabel($label);
        $column -> setValue($value);
        $column -> setPaddingType(Column::PADDING_ZEROFILL_LEFT);
        return $column;
    }
}


text:
package servicebroker

import (
	"fmt"

	"code.cloudfoundry.org/cli/cf/api"
	"code.cloudfoundry.org/cli/cf/commandregistry"
	"code.cloudfoundry.org/cli/cf/configuration/coreconfig"
	"code.cloudfoundry.org/cli/cf/flags"
	. "code.cloudfoundry.org/cli/cf/i18n"
	"code.cloudfoundry.org/cli/cf/requirements"
	"code.cloudfoundry.org/cli/cf/terminal"
)

type CreateServiceBroker struct {
	ui                terminal.UI
	config            coreconfig.Reader
	serviceBrokerRepo api.ServiceBrokerRepository
}

func init() {
	commandregistry.Register(&CreateServiceBroker{})
}

func (cmd *CreateServiceBroker) MetaData() commandregistry.CommandMetadata {
	fs := make(map[string]flags.FlagSet)
	fs["space-scoped"] = &flags.BoolFlag{Name: "space-scoped", Usage: T("Make the broker's service plans only visible within the targeted space")}

	return commandregistry.CommandMetadata{
		Name:        "create-service-broker",
		ShortName:   "csb",
		Description: T("Create a service broker"),
		Usage: []string{
			T("CF_NAME create-service-broker SERVICE_BROKER USERNAME PASSWORD URL [--space-scoped]"),
		},
		Flags: fs,
	}
}

func (cmd *CreateServiceBroker) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) {
	if len(fc.Args()) != 4 {
		cmd.ui.Failed(T("Incorrect Usage. Requires SERVICE_BROKER, USERNAME, PASSWORD, URL as arguments\n\n") + commandregistry.Commands.CommandUsage("create-service-broker"))
		return nil, fmt.Errorf("Incorrect usage: %d arguments of %d required", len(fc.Args()), 4)
	}

	reqs := []requirements.Requirement{
		requirementsFactory.NewLoginRequirement(),
	}

	if fc.IsSet("space-scoped") {
		reqs = append(
			reqs,
			requirementsFactory.NewTargetedSpaceRequirement(),
		)
	}

	return reqs, nil
}

func (cmd *CreateServiceBroker) SetDependency(deps commandregistry.Dependency, pluginCall bool) commandregistry.Command {
	cmd.ui = deps.UI
	cmd.config = deps.Config
	cmd.serviceBrokerRepo = deps.RepoLocator.GetServiceBrokerRepository()
	return cmd
}

func (cmd *CreateServiceBroker) Execute(c flags.FlagContext) error {
	name := c.Args()[0]
	username := c.Args()[1]
	password := c.Args()[2]
	url := c.Args()[3]

	var err error
	if c.Bool("space-scoped") {
		cmd.ui.Say(T("Creating service broker {{.Name}} in org {{.Org}} / space {{.Space}} as {{.Username}}...",
			map[string]interface{}{
				"Name":     terminal.EntityNameColor(name),
				"Org":      terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
				"Space":    terminal.EntityNameColor(cmd.config.SpaceFields().Name),
				"Username": terminal.EntityNameColor(cmd.config.Username())}))
		err = cmd.serviceBrokerRepo.Create(name, url, username, password, cmd.config.SpaceFields().GUID)
	} else {
		cmd.ui.Say(T("Creating service broker {{.Name}} as {{.Username}}...",
			map[string]interface{}{
				"Name":     terminal.EntityNameColor(name),
				"Username": terminal.EntityNameColor(cmd.config.Username())}))
		err = cmd.serviceBrokerRepo.Create(name, url, username, password, "")
	}

	if err != nil {
		return err
	}

	cmd.ui.Ok()
	return err
}


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/template_main_layout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/background"
    android:foreground="@drawable/shape_window_dim"
    tools:context="de.fau.cs.mad.rpgpack.TemplateStoreMainActivity" >

 <RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    tools:context=".TemplateStoreMainActivity"
     >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:layout_centerHorizontal="true"
        android:layout_marginTop="16dp"
        android:text="@string/template_store_main_heading"
        android:textColor="@color/white"
        android:textSize="@dimen/text_xxl">

    </TextView>

    <View
    android:id="@+id/separator"
    android:layout_marginBottom="20dp"
    android:layout_marginTop="5dp"
    android:layout_width="fill_parent"
    android:layout_height="1dp"
    android:layout_below="@+id/textView1"
    android:background="@android:color/darker_gray"/>

    <ListView
        android:id="@+id/listView1"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignTop="@android:id/list"
        android:layout_marginRight="20dp"
        android:listSelector="@drawable/store_list_selector"
        android:divider="@color/white"
        android:dividerHeight="1sp"
        >

    </ListView>

    <ListView
        android:id="@android:id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/separator"
        android:layout_marginTop="20dp"
        android:divider="@android:color/white"
        android:dividerHeight="1dp"
        android:layout_toRightOf="@+id/listView1" >

    </ListView>

</RelativeLayout>

</FrameLayout>


text:
class AddCodeToSpreeGiftCards < ActiveRecord::Migration
  def change
    add_column :spree_gift_cards, :code, :string
  end
end


text:
require 'rubygems'

$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
vendored_rgtk = File.join(File.dirname(__FILE__), '..', 'vendor', 'rgtk', 'lib')
$LOAD_PATH.unshift(vendored_rgtk) if File.exists?(vendored_rgtk)

require 'rgtk'
require 'webkit'
require 'vte'
require 'activerecord'

Rgtk.root = File.expand_path("#{File.dirname(__FILE__)}/..") unless defined?(RGTK_ROOT)

class SozdatApp < Rgtk::App
end

App = SozdatApp.instance


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="bottom"
    android:background="@color/transparent">

    <View
        android:id="@+id/view_empty"
        android:layout_width="match_parent"
        android:layout_height="160dp"
        android:background="@color/black_half"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="0dp"
        android:orientation="vertical"
        android:background="@color/white">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="42dp"
            android:paddingLeft="15dp"
            android:paddingRight="15dp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="5dp"
                android:gravity="center"
                android:singleLine="true"
                android:text="选择优惠券"
                android:textSize="14sp"
                android:textColor="@color/black_3333"
                android:background="@color/transparent"
                />
            <Button
                android:id="@+id/btn_order_agreement"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_alignParentRight="true"
                android:layout_marginLeft="5dp"
                android:gravity="center"
                android:singleLine="true"
                android:text="不使用优惠券"
                android:textSize="14sp"
                android:textColor="@color/blue_2299"
                android:background="@color/transparent"
                />
        </RelativeLayout>
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@color/black_dcdc"/>

        <ListView
            android:id="@+id/coupon_listview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:divider="@null"
            android:visibility="visible"
            android:scrollbars="none"
            android:listSelector="@color/transparent"
            android:background="@color/white">
        </ListView>
        <TextView
            android:id="@+id/tv_empty_nolist"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginTop="25dp"
            android:layout_marginLeft="5dp"
            android:drawableTop="@drawable/icon_empty"
            android:drawablePadding="25dp"
            android:gravity="center"
            android:singleLine="true"
            android:text="暂无可用优惠券!"
            android:textSize="16sp"
            android:textColor="@color/black_3333"
            android:background="@color/transparent"
            />
    </LinearLayout>

</LinearLayout>


text:
package com.palantir.atlasdb.keyvalue.cassandra;

import com.google.common.collect.Multimap;
import com.google.common.collect.Range;
import com.google.common.collect.RangeMap;
import com.palantir.atlasdb.keyvalue.cassandra.pool.CassandraServer;
import com.palantir.common.annotations.ImmutablesStyles.WeakInterningImmutablesStyle;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import one.util.streamex.EntryStream;
import org.apache.cassandra.thrift.TokenRange;
import org.immutables.value.Value;

public final class CassandraLogHelper {
    private CassandraLogHelper() {
        // Utility class.
    }

    public static <T> Map<String, T> mapOfHosts(Map<CassandraServer, T> hosts) {
        return EntryStream.of(hosts).mapKeys(CassandraServer::cassandraHostName).toMap();
    }

    public static HostAndIpAddress host(InetSocketAddress host) {
        return HostAndIpAddress.fromAddress(host);
    }

    static Collection<String> collectionOfHosts(Collection<CassandraServer> hosts) {
        return hosts.stream().map(CassandraServer::cassandraHostName).collect(Collectors.toSet());
    }

    static List<String> tokenRangesToServer(Multimap<Set<TokenRange>, CassandraServer> tokenRangesToHost) {
        return tokenRangesToHost.entries().stream()
                .map(entry ->
                        "host " + entry.getValue().cassandraHostName() + " with proxy has range " + entry.getKey())
                .collect(Collectors.toList());
    }

    public static List<String> tokenMap(RangeMap<LightweightOppToken, ? extends Collection<CassandraServer>> tokenMap) {
        return tokenMap.asMapOfRanges().entrySet().stream()
                .map(rangeListToHostEntry -> String.format(
                        "range from %s to %s is on host %s",
                        getLowerEndpoint(rangeListToHostEntry.getKey()),
                        getUpperEndpoint(rangeListToHostEntry.getKey()),
                        CassandraLogHelper.collectionOfHosts(rangeListToHostEntry.getValue())))
                .collect(Collectors.toList());
    }

    private static String getLowerEndpoint(Range<LightweightOppToken> range) {
        if (!range.hasLowerBound()) {
            return "(no lower bound)";
        }
        return range.lowerEndpoint().toString();
    }

    private static String getUpperEndpoint(Range<LightweightOppToken> range) {
        if (!range.hasUpperBound()) {
            return "(no upper bound)";
        }
        return range.upperEndpoint().toString();
    }

    public static List<String> tokenRangeHashes(Set<TokenRange> tokenRanges) {
        return tokenRanges.stream()
                .map(range -> "(" + range.getStart_token().hashCode() + ", "
                        + range.getEnd_token().hashCode() + ")")
                .collect(Collectors.toList());
    }

    // Weakly intern instances as there should be a relatively small, generally fixed number of Cassandra servers.
    @Value.Immutable(lazyhash = true, intern = true, builder = false)
    @WeakInterningImmutablesStyle
    interface HostAndIpAddress {
        @Value.Parameter
        String host();

        @Nullable
        @Value.Parameter
        String ipAddress();

        static HostAndIpAddress fromAddress(InetSocketAddress address) {
            InetAddress inetAddress = address.getAddress();
            if (inetAddress != null) {
                return ImmutableHostAndIpAddress.of(address.getHostString(), inetAddress.getHostAddress());
            }
            return ImmutableHostAndIpAddress.of(address.getHostString(), /* unresolved IP */ null);
        }
    }
}


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

namespace Linguistics
{
    /// <summary>
    /// Stores a tagged word.
    /// </summary>
    public class TypeWordCombo
    {
        public TypeWordCombo(string type, string word)
        {
            Type = type;
            Word = word;
        }
        public string Type { get; set; }
        public string Word { get; set; }
    }
}


text:
module ApplicationFormattersHelper
  include ApplicationHTMLFormattersHelper

  # Formats the given user-input string. The string is assumed not to contain HTML markup, and
  # will be processed for simple formatting like newlines using the Rails +simple_format+ helper.
  #
  # This will treat the given text as a block element.
  #
  # @param [String] text The text to display.
  # @return [String]
  def format_block_text(text)
    simple_format(html_escape(text), {}, sanitize: false)
  end

  # Formats the given user-input string. The string is assumed not to contain HTML markup.
  #
  # @param [String] text The text to display.
  # @return [String]
  def format_inline_text(text)
    html_escape(text)
  end

  # Formats the given User as a user-visible string.
  #
  # @param [User] user The User to display.
  # @return [String] The user-visible string to represent the User, suitable for rendering as
  #   output.
  def display_user(user)
    user&.name
  end

  # Displays the given user's image.
  #
  # @param [User] user The user to display
  # @return [String] A HTML fragment containing the image to display for the user.
  def display_user_image(user)
    content_tag(:span, class: ['image']) do
      if user.nil? || user.profile_photo.medium.url.nil?
        image_tag('user_silhouette.svg')
      else
        image_tag(user.profile_photo.medium.url)
      end
    end
  end

  # Return the given user's image url.
  #
  # @param [User] user The user to display
  # @return [String] A url for the image.
  def user_image(user)
    if user.nil? || user.profile_photo.medium.url.nil?
      image_path('user_silhouette.svg')
    else
      image_path(user.profile_photo.medium.url)
    end
  end

  # Links to the given User.
  #
  # @param [User] user The User to display.
  # @param [Hash] options The options to pass to +link_to+
  # @yield The user will be yielded to the provided block, and the block can override the display
  #   of the User.
  # @yieldparam [User] user The user to display.
  # @return [String] The user-visible string, including embedded HTML which will display the
  #   string within a link to bring to the User page.
  def link_to_user(user, options = {})
    link_path = user_path(user)
    link_to(link_path, options) do
      if block_given?
        yield(user)
      else
        display_user(user)
      end
    end
  end

  # Custom datetime formats
  Time::DATE_FORMATS[:date_only_long] = '%B %d, %Y'
  Time::DATE_FORMATS[:date_only_short] = '%d %b'
  Time::DATE_FORMATS[:i18n_default] = I18n.t('time.formats.default')

  # Format the given datetime
  #
  # @param [DateTime] date The datetime to be formatted
  # @param [Symbol] format The output format. Use Ruby's defaults or see above for
  #   some predefined formats.
  #   e.g. :long => "December 04, 2007 00:00"
  #        :short => "04 Dec 00:00"
  #        :date_only_long => "December 04, 2007"
  #        :date_only_short => "04 Dec"
  # @return [String] the formatted datetime string
  def format_datetime(date, format = :long, user: nil)
    user ||= respond_to?(:current_user) ? current_user : nil
    user_zone = user&.time_zone || Application.config.x.default_user_time_zone
    # TODO: Fix the query. This is a workaround to display the time in the correct zone, there are
    # places where datetimes are directly fetched from db and skipped AR, which result in incorrect
    # time zone.
    date = date.in_time_zone(user_zone) if date.zone != user_zone

    date.to_formatted_s(format)
  end

  # @return the duration in the format of "HH:MM:SS", eg 04H05M11S
  def format_duration(total_seconds)
    seconds = total_seconds % 60
    minutes = (total_seconds / 60) % 60
    hours = total_seconds / (60 * 60)
    format('%<hours>02dH%<minutes>02dM%<seconds>02dS', hours: hours, minutes: minutes, seconds: seconds)
  end

  # A helper for generating CSS classes, based on the time-bounded status of the item.
  #
  # @param [ActiveRecord::Base] item An ActiveRecord object which has time-bounded fields.
  # @return [Array<String>] An array of CSS classes applicable for the provided item.
  def time_period_class(item)
    if !item.started?
      ['not-started']
    elsif item.ended?
      ['ended']
    else # Started, but not yet ended.
      ['currently-active']
    end
  end

  # A helper for retrieving the title for a time-bounded item's status.
  #
  # @param [ActiveRecord::Base] item An ActiveRecord object which has time-bounded fields.
  # @return [String] A translated string representing the status of the item.
  # @return [nil] If the item is valid.
  def time_period_message(item)
    if !item.started?
      t('common.not_started')
    elsif item.ended?
      t('common.ended')
    end
  end

  # A helper for retrieving the title of a published item's status.
  #
  # @param [ActiveRecord::Base] item An ActiveRecord object which has a published field.
  # @return [String] A translated string representing the status of the item.
  # @return [nil] If the item is published.
  def draft_message(item)
    t('common.draft') unless item.published?
  end

  # A helper for generating CSS classes, based on the unread status of the item.
  #
  # @param [ActiveRecord::Base] item An ActiveRecord object which acts as readable.
  # @return [Array<String>] An array of CSS classes applicable for the provided item.
  def unread_class(item)
    if item.unread?(current_user)
      ['unread']
    else
      []
    end
  end

  # Changes boolean values (True/False) into readable forms (Yes/No).
  #
  # @param [Boolean|nil] bool
  # @return [String] A readable form of true and false, Yes and No.
  def format_boolean(bool)
    bool ? t('common.truthy') : t('common.falsey')
  end
end


text:
<model>
    <mount>//OPNsense/clamav/general</mount>
    <description>ClamAV configuration</description>
    <version>1.0.0</version>
    <items>
        <enabled type="BooleanField">
            <default>0</default>
            <Required>Y</Required>
        </enabled>
        <fc_enabled type="BooleanField">
            <default>0</default>
            <Required>Y</Required>
        </fc_enabled>
        <enabletcp type="BooleanField">
            <default>1</default>
            <Required>Y</Required>
        </enabletcp>
        <maxthreads type="IntegerField">
            <default>10</default>
            <Required>N</Required>
        </maxthreads>
        <maxqueue type="IntegerField">
            <default>100</default>
            <Required>N</Required>
        </maxqueue>
        <idletimeout type="IntegerField">
            <default>30</default>
            <Required>N</Required>
        </idletimeout>
        <maxdirrecursion type="IntegerField">
            <default>20</default>
            <Required>N</Required>
        </maxdirrecursion>
        <followdirsym type="BooleanField">
            <default>0</default>
            <Required>N</Required>
        </followdirsym>
        <followfilesym type="BooleanField">
            <default>0</default>
	    <Required>N</Required>
	</followfilesym>
        <disablecache type="TextField">
            <default>0</default>
	    <Required>N</Required>
	</disablecache>
        <scanpe type="BooleanField">
            <default>1</default>
	    <Required>N</Required>
	</scanpe>
        <scanelf type="BooleanField">
            <default>1</default>
            <Required>N</Required>
        </scanelf>
        <detectbroken type="BooleanField">
            <default>0</default>
            <Required>N</Required>
        </detectbroken>
        <scanole2 type="BooleanField">
            <default>1</default>
            <Required>N</Required>
        </scanole2>
        <ole2blockmarcros type="BooleanField">
            <default>0</default>
            <Required>N</Required>
        </ole2blockmarcros>
        <scanpdf type="BooleanField">
            <default>1</default>
            <Required>N</Required>
        </scanpdf>
        <scanswf type="BooleanField">
            <default>1</default>
            <Required>N</Required>
        </scanswf>
        <scanxmldocs type="BooleanField">
            <default>1</default>
            <Required>N</Required>
        </scanxmldocs>
        <scanhwp3 type="BooleanField">
            <default>1</default>
            <Required>N</Required>
        </scanhwp3>
        <scanmailfiles type="BooleanField">
            <default>1</default>
            <Required>N</Required>
        </scanmailfiles>
        <scanhtml type="BooleanField">
            <default>1</default>
            <Required>N</Required>
        </scanhtml>
        <scanarchive type="BooleanField">
            <default>1</default>
            <Required>N</Required>
        </scanarchive>
        <arcblockenc type="BooleanField">
            <default>0</default>
            <Required>N</Required>
        </arcblockenc>
        <maxscansize type="TextField">
            <default>100M</default>
            <Required>N</Required>
        </maxscansize>
	<maxfilesize type="TextField">
            <default>25M</default>
            <Required>N</Required>
        </maxfilesize>
	<maxrecursion type="IntegerField">
            <default>16</default>
            <Required>N</Required>
        </maxrecursion>
	<maxfiles type="IntegerField">
            <default>10000</default>
            <Required>N</Required>
	</maxfiles>
        <fc_logverbose type="BooleanField">
            <default>0</default>
            <Required>N</Required>
        </fc_logverbose>
        <fc_databasemirror type="TextField">
            <default>database.clamav.net</default>
            <Required>Y</Required>
        </fc_databasemirror>
        <fc_timeout type="TextField">
            <default>60</default>
            <Required>Y</Required>
        </fc_timeout>
        <fc_malwareexpert type="BooleanField">
            <default>0</default>
            <Required>N</Required>
        </fc_malwareexpert>
        <fc_blurl type="BooleanField">
            <default>0</default>
            <Required>N</Required>
        </fc_blurl>
        <fc_jurlbla type="BooleanField">
            <default>0</default>
            <Required>N</Required>
        </fc_jurlbla>
        <fc_bofhland type="BooleanField">
            <default>0</default>
            <Required>N</Required>
        </fc_bofhland>
    </items>
</model>


text:
#pragma once
#include <aws/iam/IAM_EXPORTS.h>
#include <aws/iam/IAMRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace IAM
{
namespace Model
{

  /*
  */
  class AWS_IAM_API ListServerCertificatesRequest : public IAMRequest
  {
  public:
    ListServerCertificatesRequest();
    Aws::String SerializePayload() const override;

    /*

 The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts.

 This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates.

    */
    inline const Aws::String& GetPathPrefix() const{ return m_pathPrefix; }

    /*

 The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts.

 This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates.

    */
    inline void SetPathPrefix(const Aws::String& value) { m_pathPrefixHasBeenSet = true; m_pathPrefix = value; }

    /*

 The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts.

 This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates.

    */
    inline void SetPathPrefix(Aws::String&& value) { m_pathPrefixHasBeenSet = true; m_pathPrefix = value; }

    /*

 The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts.

 This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates.

    */
    inline void SetPathPrefix(const char* value) { m_pathPrefixHasBeenSet = true; m_pathPrefix.assign(value); }

    /*

 The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts.

 This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates.

    */
    inline ListServerCertificatesRequest& WithPathPrefix(const Aws::String& value) { SetPathPrefix(value); return *this;}

    /*

 The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts.

 This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates.

    */
    inline ListServerCertificatesRequest& WithPathPrefix(Aws::String&& value) { SetPathPrefix(value); return *this;}

    /*

 The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts.

 This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates.

    */
    inline ListServerCertificatesRequest& WithPathPrefix(const char* value) { SetPathPrefix(value); return *this;}

    /*

Use this parameter only when paginating results and only after you have received a response where the results are truncated. Set it to the value of the Marker element in the response you just received.

    */
    inline const Aws::String& GetMarker() const{ return m_marker; }

    /*

Use this parameter only when paginating results and only after you have received a response where the results are truncated. Set it to the value of the Marker element in the response you just received.

    */
    inline void SetMarker(const Aws::String& value) { m_markerHasBeenSet = true; m_marker = value; }

    /*

Use this parameter only when paginating results and only after you have received a response where the results are truncated. Set it to the value of the Marker element in the response you just received.

    */
    inline void SetMarker(Aws::String&& value) { m_markerHasBeenSet = true; m_marker = value; }

    /*

Use this parameter only when paginating results and only after you have received a response where the results are truncated. Set it to the value of the Marker element in the response you just received.

    */
    inline void SetMarker(const char* value) { m_markerHasBeenSet = true; m_marker.assign(value); }

    /*

Use this parameter only when paginating results and only after you have received a response where the results are truncated. Set it to the value of the Marker element in the response you just received.

    */
    inline ListServerCertificatesRequest& WithMarker(const Aws::String& value) { SetMarker(value); return *this;}

    /*

Use this parameter only when paginating results and only after you have received a response where the results are truncated. Set it to the value of the Marker element in the response you just received.

    */
    inline ListServerCertificatesRequest& WithMarker(Aws::String&& value) { SetMarker(value); return *this;}

    /*

Use this parameter only when paginating results and only after you have received a response where the results are truncated. Set it to the value of the Marker element in the response you just received.

    */
    inline ListServerCertificatesRequest& WithMarker(const char* value) { SetMarker(value); return *this;}

    /*

Use this only when paginating results to indicate the maximum number of items you want in the response. If there are additional items beyond the maximum you specify, the IsTruncated response element is true.

This parameter is optional. If you do not include it, it defaults to 100.

    */
    inline long GetMaxItems() const{ return m_maxItems; }

    /*

Use this only when paginating results to indicate the maximum number of items you want in the response. If there are additional items beyond the maximum you specify, the IsTruncated response element is true.

This parameter is optional. If you do not include it, it defaults to 100.

    */
    inline void SetMaxItems(long value) { m_maxItemsHasBeenSet = true; m_maxItems = value; }

    /*

Use this only when paginating results to indicate the maximum number of items you want in the response. If there are additional items beyond the maximum you specify, the IsTruncated response element is true.

This parameter is optional. If you do not include it, it defaults to 100.

    */
    inline ListServerCertificatesRequest& WithMaxItems(long value) { SetMaxItems(value); return *this;}

  private:
    Aws::String m_pathPrefix;
    bool m_pathPrefixHasBeenSet;
    Aws::String m_marker;
    bool m_markerHasBeenSet;
    long m_maxItems;
    bool m_maxItemsHasBeenSet;
  };

} // namespace Model
} // namespace IAM
} // namespace Aws


text:
<title>dot_picture_processing.js sample</title>

dot_picture_processing.js sample

<input type="file" id="selectfile" accept='image/*'>

<input type="range" id="dots_len_bar" min="0" max="0" step="1" value="0" oninput="changeValue(this.value)" onchange="excute_convert_to_dot(this.value)">
0

<canvas id="resultcanvas">
</canvas>


text:
        <title>OpenLayers Vector Behavior Example</title>
        <link rel="stylesheet" href="../theme/default/style.css" type="text/css" />
        <link rel="stylesheet" href="style.css" type="text/css" />

Vector Behavior Example

            Uses a BBOX strategy, WFS protocol, and GML format.

The vector layer shown uses the BBOX strategy, the WFS protocol,
            and the GML format.  The BBOX strategy fetches features within a
            bounding box.  When the map bounds invalidate the data bounds,
            another request is triggered.  The WFS protocol gets features
            through a WFS request.  The GML format is used to serialize
            features.