text:
"""
Simple Parallel Model Selection
===============================

In this example, we'll demonstrate how to quickly write a hyperparameter
tuning script that evaluates a set of hyperparameters in parallel.

This script will demonstrate how to use two important parts of the Ray API:
using ``ray.remote`` to define remote functions and ``ray.wait`` to wait for
their results to be ready.

.. image:: ../images/hyperparameter.png
    :align: center

.. important:: For a production-grade implementation of distributed
    hyperparameter tuning, use `Tune`_, a scalable hyperparameter
    tuning library built using Ray's Actor API.

.. _`Tune`: https://ray.readthedocs.io/en/latest/tune.html

Setup: Dependencies
-------------------
First, import some dependencies and define functions to generate
random hyperparameters and retrieve data.
"""
import os
import numpy as np
from filelock import FileLock

import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms

import ray

ray.init()

# The number of sets of random hyperparameters to try.
num_evaluations = 10

# A function for generating random hyperparameters.
def generate_hyperparameters():
    return {
        "learning_rate": 10**np.random.uniform(-5, 1),
        "batch_size": np.random.randint(1, 100),
        "momentum": np.random.uniform(0, 1)
    }

def get_data_loaders(batch_size):
    mnist_transforms = transforms.Compose(
        [transforms.ToTensor(),
         transforms.Normalize((0.1307, ), (0.3081, ))])

    # We add FileLock here because multiple workers will want to
    # download data, and this may cause overwrites since
    # DataLoader is not threadsafe.
    with FileLock(os.path.expanduser("~/data.lock")):
        train_loader = torch.utils.data.DataLoader(
            datasets.MNIST(
                "~/data",
                train=True,
                download=True,
                transform=mnist_transforms),
            batch_size=batch_size,
            shuffle=True)
    test_loader = torch.utils.data.DataLoader(
        datasets.MNIST("~/data", train=False, transform=mnist_transforms),
        batch_size=batch_size,
        shuffle=True)
    return train_loader, test_loader

#######################################################################
# Setup: Defining the Neural Network
# ----------------------------------
#
# We define a small neural network to use in training. In addition,
# we created methods to train and test this neural network.

class ConvNet(nn.Module):
    """Simple two layer Convolutional Neural Network."""

    def __init__(self):
        super(ConvNet, self).__init__()
        self.conv1 = nn.Conv2d(1, 3, kernel_size=3)
        self.fc = nn.Linear(192, 10)

    def forward(self, x):
        x = F.relu(F.max_pool2d(self.conv1(x), 3))
        x = x.view(-1, 192)
        x = self.fc(x)
        return F.log_softmax(x, dim=1)

def train(model, optimizer, train_loader, device=torch.device("cpu")):
    """Optimize the model with one pass over the data.

    Cuts off at 1024 samples to simplify training.
    """
    model.train()
    for batch_idx, (data, target) in enumerate(train_loader):
        if batch_idx * len(data) > 1024:
            return
        data, target = data.to(device), target.to(device)
        optimizer.zero_grad()
        output = model(data)
        loss = F.nll_loss(output, target)
        loss.backward()
        optimizer.step()

def test(model, test_loader, device=torch.device("cpu")):
    """Checks the validation accuracy of the model.

    Cuts off at 512 samples for simplicity.
    """
    model.eval()
    correct = 0
    total = 0
    with torch.no_grad():
        for batch_idx, (data, target) in enumerate(test_loader):
            if batch_idx * len(data) > 512:
                break
            data, target = data.to(device), target.to(device)
            outputs = model(data)
            _, predicted = torch.max(outputs.data, 1)
            total += target.size(0)
            correct += (predicted == target).sum().item()

    return correct / total

#######################################################################
# Evaluating the Hyperparameters
# -------------------------------
#
# For a given configuration, the neural network created previously
# will be trained and return the accuracy of the model. These trained
# networks will then be tested for accuracy to find the best set of
# hyperparameters.
#
# The ``@ray.remote`` decorator defines a remote process.

@ray.remote
def evaluate_hyperparameters(config):
    model = ConvNet()
    train_loader, test_loader = get_data_loaders(config["batch_size"])
    optimizer = optim.SGD(
        model.parameters(),
        lr=config["learning_rate"],
        momentum=config["momentum"])
    train(model, optimizer, train_loader)
    return test(model, test_loader)

#######################################################################
# Synchronous Evaluation of Randomly Generated Hyperparameters
# ------------------------------------------------------------
#
# We will create multiple sets of random hyperparameters for our neural
# network that will be evaluated in parallel.

# Keep track of the best hyperparameters and the best accuracy.
best_hyperparameters = None
best_accuracy = 0
# A list holding the object IDs for all of the experiments that we have
# launched but have not yet been processed.
remaining_ids = []
# A dictionary mapping an experiment's object ID to its hyperparameters.
# hyerparameters used for that experiment.
hyperparameters_mapping = {}

###########################################################################
# Launch asynchronous parallel tasks for evaluating different
# hyperparameters. ``accuracy_id`` is an ObjectID that acts as a handle to
# the remote task. It is used later to fetch the result of the task
# when the task finishes.

# Randomly generate sets of hyperparameters and launch a task to evaluate it.
for i in range(num_evaluations):
    hyperparameters = generate_hyperparameters()
    accuracy_id = evaluate_hyperparameters.remote(hyperparameters)
    remaining_ids.append(accuracy_id)
    hyperparameters_mapping[accuracy_id] = hyperparameters

###########################################################################
# Process each hyperparameter and corresponding accuracy in the order that
# they finish to store the hyperparameters with the best accuracy.

# Fetch and print the results of the tasks in the order that they complete.
while remaining_ids:
    # Use ray.wait to get the object ID of the first task that completes.
    done_ids, remaining_ids = ray.wait(remaining_ids)
    # There is only one return result by default.
    result_id = done_ids[0]

    hyperparameters = hyperparameters_mapping[result_id]
    accuracy = ray.get(result_id)
    print("""We achieve accuracy {:.3}% with
        learning_rate: {:.2}
        batch_size: {}
        momentum: {:.2}
      """.format(100 * accuracy, hyperparameters["learning_rate"],
                 hyperparameters["batch_size"], hyperparameters["momentum"]))
    if accuracy > best_accuracy:
        best_hyperparameters = hyperparameters
        best_accuracy = accuracy

# Record the best performing set of hyperparameters.
print("""Best accuracy over {} trials was {:.3} with
      learning_rate: {:.2}
      batch_size: {}
      momentum: {:.2}
      """.format(num_evaluations, 100 * best_accuracy,
                 best_hyperparameters["learning_rate"],
                 best_hyperparameters["batch_size"],
                 best_hyperparameters["momentum"]))


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Agaric. mod. Tax. (Weinheim), Edn 2 678 (1962)

#### Original name
Rhodocybe parilis var. parilis

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
package com.intellij.xdebugger.impl.ui.tree.actions;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.xdebugger.frame.XValue;
import com.intellij.xdebugger.impl.ui.tree.XDebuggerTree;
import com.intellij.xdebugger.impl.ui.tree.nodes.XValueNodeImpl;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.tree.TreePath;

/**
 * @author nik
 */
public abstract class XDebuggerTreeActionBase extends AnAction {
  public void actionPerformed(final AnActionEvent e) {
    XValueNodeImpl node = getSelectedNode(e.getDataContext());
    if (node == null) return;

    String nodeName = node.getName();
    if (nodeName == null) return;

    perform(node, nodeName, e);
  }

  protected abstract void perform(final XValueNodeImpl node, @NotNull String nodeName, final AnActionEvent e);

  public void update(final AnActionEvent e) {
    XValueNodeImpl node = getSelectedNode(e.getDataContext());
    e.getPresentation().setEnabled(node != null && isEnabled(node));
  }

  protected boolean isEnabled(final XValueNodeImpl node) {
    return node.getName() != null;
  }

  @Nullable
  protected static XValueNodeImpl getSelectedNode(final DataContext dataContext) {
    XDebuggerTree tree = XDebuggerTree.getTree(dataContext);
    if (tree == null) return null;

    TreePath path = tree.getSelectionPath();
    if (path == null) return null;

    Object node = path.getLastPathComponent();
    if (node instanceof XValueNodeImpl) {
      return (XValueNodeImpl)node;
    }
    return null;
  }

  @Nullable
  public static XValue getSelectedValue(@NotNull DataContext dataContext) {
    XValueNodeImpl node = getSelectedNode(dataContext);
    return node != null ? node.getValueContainer() : null;
  }
}


text:
<?php
// src/KK/BlogBundle/Tests/Entity/Repository/BlogRepositoryTest.php

namespace KK\BlogBundle\Tests\Entity\Repository;

use KK\BlogBundle\Entity\Repository\BlogRepository;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class BlogRepositoryTest extends WebTestCase
{
    /**
     * @var \KK\BlogBundle\Entity\Repository\BlogRepository
     */
    private $blogRepository;

    public function setUp()
    {
        $kernel = static::createKernel();
        $kernel->boot();
        $this->blogRepository = $kernel->getContainer()
                ->get('doctrine.orm.entity_manager')
                ->getRepository('KKBlogBundle:Blog');

    }

    public function testGetTags()
    {
        $tags = $this->blogRepository->getTags();

        $this->assertTrue(count($tags) > 1);
        $this->assertContains('symfony2', $tags);
    }

    public function testGetTagWeights()
    {
        $tagsWeight = $this->blogRepository->getTagWeights(
            array('php', 'code', 'code', 'symblog', 'blog')
        );

        $this->assertTrue(count($tagsWeight) > 1);

        // Test case where count is over max weight of 5
        $tagsWeight = $this->blogRepository->getTagWeights(
            array_fill(0, 10, 'php')
        );

        $this->assertTrue(count($tagsWeight) >= 1);

        // Test case with multiple counts over max weight of 5
        $tagsWeight = $this->blogRepository->getTagWeights(
            array_merge(array_fill(0, 5, 'php'), array_fill(0, 1, 'html'), array_fill(0, 3, 'js'))
        );

        $this->assertEquals(5, $tagsWeight['php']);
        $this->assertEquals(3, $tagsWeight['js']);
        $this->assertEquals(1, $tagsWeight['html']);

        // Test empty case
        $tagsWeight = $this->blogRepository->getTagWeights(array());

        $this->assertEmpty($tagsWeight);
    }
}


text:
/**
 * @file
 * A class for comminicating with a drupal site with a services endpoint.
 *
 * For documentation, see project page.
 */

/**
 * Constructor.
 */
var drupalService = function() {
  this.url;
  this.data;
  this.method;
  this.callback = function(data) {
    console.log(data);
  }
  this.error = function(data) {
    console.log(data);
  }
}

/**
 * Function to send post requests.
 */
drupalService.prototype.post = function() {
  var xhr = this.xhr('post');
  xhr.send(JSON.stringify(this.data));
}

/**
 * Function to send GET requests.
 */
drupalService.prototype.get = function() {
  var xhr = this.xhr('get');
  xhr.send();
}

/**
 * Internal function to set up ajax request.
 */
drupalService.prototype.xhr = function(op, fn) {
  var url = this.url + '/' + this.method;
  var xhr = new XMLHttpRequest();
  var service = this;
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        service.callback(JSON.parse(xhr.responseText));
      }
      else {
        service.error(xhr);
      }
    }
  }
  switch (op) {
    case 'get':
      xhr.open('GET', url, true);
      break;

    case 'post':
      xhr.open('POST', url, true);
      xhr.setRequestHeader("Content-type", "application/json");
      break;

    // @todo: other requests that GET and POST.
  }
  return xhr;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
	PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
	"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="scut.legend.cg.dao.ProductProduceDao">
	<resultMap type="scut.legend.cg.po.ProductProduce" id="productProduceResultMap">
		<id property="id" column="id"/>
		<result property="produceNum" column="produce_num"/>
		<result property="produceDate" column="produce_date"/>
		<result property="produceQuantity" column="produce_quantity"/>

		<result property="staffId" column="staff_id"/>
		<result property="staffName" column="staff_name"/>

		<association property="product" column="product_id"
		javaType="scut.legend.cg.po.Product"
		select="selectProductByProductId"></association>
	</resultMap>

	<resultMap type="scut.legend.cg.po.Product" id="productMap">
			<id property="productId" column="product_id"></id>
			<result property="productShape" column="product_shape"></result>
			<result property="productSize" column="product_size" />

			<association property="productModelInfo" column="product_model_info_id"
				javaType="scut.legend.cg.po.ProductModelInfo"
				select="selectProductModelById">
					<id property="id" column="id"/>
					<result property="productModel" column="product_model"/>
			</association>
	</resultMap>

	<select id="selectProductModelById" resultType="scut.legend.cg.po.ProductModelInfo">
		select product_model from product_model_info where id=#{id}
	</select>

	<select id="selectProductByProductId" resultMap="productMap">
		select * from product where product_id=#{product.productId}
	</select>

	<sql id="columnList">
		produce_num,produce_date,produce_quantity,staff_id,staff_name
	</sql>

	<!-- 计数 -->
	<select id="getDeliveryNumSuffix" resultType="java.lang.Integer">
		select count(id) from product_produce
		where produce_date = #{0}
	</select>

	<!--需要先查询product数据库表得到productId(如果不存在则向product数据库表插入一条新记录),然后 新增一条产品产出登记记录 -->
	<insert id="createOneProductProduce" parameterType="scut.legend.cg.po.ProductProduce" useGeneratedKeys="true" keyProperty="id">
		insert into product_produce
		(<include refid="columnList"/>,product_id)
		values(#{produceNum},#{produceDate},#{produceQuantity},#{staffId},#{staffName},
				(select product_id from product where
											product_model_info_id=(select id from product_model_info where
																	product_model=#{product.productModelInfo.productModel})
											and product_size=#{product.productSize}
											and product_shape=#{product.productShape})
		)
	</insert>

	<!-- 修改一条产品产出记录,但produceNum、staffId、staffName不可更改 -->
	<!-- 需要先查询product数据库表得到productId(如果不存在则向product数据库表插入一条新记录),然后进行修改操作 -->
	<update id="updateOneProductProduce" parameterType="scut.legend.cg.po.ProductProduce">
		update product_produce
		set
		produce_quantity=#{produceQuantity},
		product_id=(select product_id from product where
											product_model_info_id=(select id from product_model_info where
																	product_model=#{product.productModelInfo.productModel})
											and product_size=#{product.productSize}
											and product_shape=#{product.productShape})
		where id=#{id}
	</update>

	<!-- 获取所有产品产出记录
	<select id="getAllProductProduce" resultMap="productProduceResultMap">
		select * from product_produce
	</select>
	-->
	<!--  根据条件获取产品产出记录,起始时间和结束时间进行筛选 -->
	<select id="getProductProduceByDate" resultMap="productProduceResultMap">
		select * from product_produce where produce_date between #{0} and #{1}
		order by produce_num DESC
		limit #{2},#{3}
	</select>
	<!-- 根据起始时间和结束时间获取记录数目 -->
	<select id="getCountByTime" resultType="java.lang.Integer">
		select count(*) from product_produce
		where produce_date between #{0} and #{1}
	</select>

	<!-- 根据id获取一条产品产出记录 -->
	<select id="getProductProduceById" resultMap="productProduceResultMap">
		select * from product_produce where id=#{0}
	</select>

</mapper>


text:
import React, {FC} from 'react'
import {capitalize} from 'lodash'

// Components
import {
  Dropdown,
  ComponentStatus,
  DropdownMenuTheme,
} from '@influxdata/clockface'

// Types
import {ColorLabel} from 'src/types/colors'

interface PassedProps {
  selected: ColorLabel
  colors: ColorLabel[]
  onChoose: (colors: ColorLabel) => void
}

interface DefaultProps {
  disabled?: boolean
  stretchToFit?: boolean
  widthPixels?: number
}

type Props = PassedProps & DefaultProps

const ColorDropdown: FC<Props> = props => {
  const {
    selected,
    colors,
    onChoose,
    disabled,
    stretchToFit,
    widthPixels,
  } = props

  const status = disabled ? ComponentStatus.Disabled : ComponentStatus.Default
  const width = stretchToFit ? null : widthPixels

  return (
    <Dropdown
      widthPixels={width}
      button={(active, onClick) => (
        <Dropdown.Button active={active} onClick={onClick} status={status}>

              {capitalize(selected.name)}

        </Dropdown.Button>
      )}
      menu={onCollapse => (
        <Dropdown.Menu onCollapse={onCollapse} theme={DropdownMenuTheme.Onyx}>
          {colors.map(color => (
            <Dropdown.Item
              id={color.name}
              key={color.name}
              value={color}
              selected={color.name === selected.name}
              onClick={onChoose}
            >

                  {capitalize(color.name)}

            </Dropdown.Item>
          ))}
        </Dropdown.Menu>
      )}
    />
  )
}

ColorDropdown.defaultProps = {
  stretchToFit: false,
  disabled: false,
  widthPixels: 100,
}

export default ColorDropdown


text:
class AzCommonsRequirementsReliability < AzCommon

  belongs_to :matrix, :class_name=>'AzCommonsRequirementsReliability', :foreign_key=>'copy_of'

  def self.get_label
    return "Требования к надежности"
  end

  def self.get_default
    return find(:first)
  end

end


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>remove example 03</title>

Text
Text

Text
Text
Goodbye! Goodbye!
Goodbye!

Text
Text


text:
package test.gov.nih.nci.security.threadsafe;

import gov.nih.nci.security.AuthorizationManager;
import gov.nih.nci.security.SecurityServiceProvider;

/**
 *
 * CSMAPI MySQL Deadlock Issue Test.
 * - Use PrimeCSMData.java to prime the database for this Test.
 *
 * @author Vijay
 *
 */
public class CSMAPIMySQLDeadLockTest {

	String sessionName;

	int innerLoopCount = 5;
	int outerLoopCount = 10;
	boolean showAllLogs = false;

	AuthorizationManager am = null;
	RandomIntGenerator randomUser = new RandomIntGenerator(2, 11);
	RandomIntGenerator randomUser2 = new RandomIntGenerator(2, 11);
	RandomIntGenerator randomGroup = new RandomIntGenerator(2, 10);
	RandomIntGenerator randomProtectionElement = new RandomIntGenerator(2, 10);
	RandomIntGenerator randomProtectionGroup= new RandomIntGenerator(2, 10);
	RandomIntGenerator randomPrivilege = new RandomIntGenerator(2, 12);
	RandomIntGenerator randomRole= new RandomIntGenerator(2, 5);

	public CSMAPIMySQLDeadLockTest(String sessionName) {
		this.sessionName = sessionName;
	}

	public static void main(String[] args) {
		CSMAPIMySQLDeadLockTest sc = new CSMAPIMySQLDeadLockTest(
				"TestSession");
		sc.doWork();
	}

	public void startSession() {
		try {

			System.out.println(this.sessionName +": StartSession: Sesion is starting");
			am = SecurityServiceProvider.getAuthorizationManager("security");
			if (am == null) {
				throw new Exception();
			}
			am = (AuthorizationManager) am;
			System.out.println(this.sessionName	+ ": StartSession: Got Managers");
		} catch (Exception ex) {
			System.out.println(this.sessionName	+ " StartSession: Could not initialize the managers");
			ex.printStackTrace();
			System.exit(0);
		}
	}

	public void doWork() {
		startSession();

		/*
		 * The Goal of this test is to do manipulations that include a assigning
		 * or associating User/PE/PGs etc to verify if there are any Deadlock
		 * issues with MySQL.
		 *
		 * Below are some associations and manipulations. They should be in any order or
		 * fashion.
		 *
		 */

		System.out.println(" assignGroupRoleToProtectionGroup");
//		assignGroupRoleToProtectionGroup();
		System.out.println(" addGroupRoleToProtectionGroup");
		addGroupRoleToProtectionGroup();

		System.out.println(" assignGroupsToUser");
//		assignGroupsToUser();
		System.out.println(" addGroupsToUser");
		addGroupsToUser();

		System.out.println(" assignOwners");
//		assignOwners();
		System.out.println(" addOwners");
		addOwners();

		System.out.println(" assignParentProtectionGroup");
//		assignParentProtectionGroup() ;

		System.out.println(" assignPrivilegesToRole");
//		assignPrivilegesToRole();
		System.out.println(" addPrivilegesToRole");
		addPrivilegesToRole();

		System.out.println(" assignProtectionElement");
		assignProtectionElement();

		System.out.println(" assignProtectionElements");
//		assignProtectionElements();
		System.out.println(" assignProtectionElements");
		addProtectionElements();

		System.out.println(" assignToProtectionGroups");
//		assignToProtectionGroups();
		System.out.println(" addToProtectionGroups");
		addToProtectionGroups();

		System.out.println(" assignUserRoleToProtectionGroup");
//		assignUserRoleToProtectionGroup();
		System.out.println(" addUserRoleToProtectionGroup");
		addUserRoleToProtectionGroup();

		System.out.println(" assignUsersToGroup");
//		assignUsersToGroup();
		System.out.println(" addUsersToGroup");
		addUsersToGroup();

		System.out.println(" assignUserToGroup");
		assignUserToGroup();

	}

	private void assignGroupRoleToProtectionGroup() {
		String pgId = String.valueOf(randomProtectionGroup.draw());
		String groupId = String.valueOf(randomGroup.draw());
		String roleId = String.valueOf(randomRole.draw());
		try {
			for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
				String[] roleIds = new String[1];
				for (int count = 0; count < outerLoopCount; count++) {
					pgId = String.valueOf(randomProtectionGroup.draw() - 1);
					groupId = String.valueOf(randomGroup.draw() - 1);
					roleId =  String.valueOf(randomRole.draw() - 1);
					roleIds[0]=roleId;
					am.assignGroupRoleToProtectionGroup(pgId, groupId, roleIds);

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

	}

	private void addGroupRoleToProtectionGroup() {
		String pgId = String.valueOf(randomProtectionGroup.draw());
		String groupId = String.valueOf(randomGroup.draw());
		String roleId = String.valueOf(randomRole.draw());
		try {
			for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
				String[] roleIds = new String[1];
				for (int count = 0; count < outerLoopCount; count++) {
					pgId = String.valueOf(randomProtectionGroup.draw() - 1);
					groupId = String.valueOf(randomGroup.draw() - 1);
					roleId =  String.valueOf(randomRole.draw() - 1);
					roleIds[0]=roleId;
					am.addGroupRoleToProtectionGroup(pgId, groupId, roleIds);

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

	}

	private void assignGroupsToUser() {
		String userId = String.valueOf(randomUser.draw());
		String groupId = String.valueOf(randomGroup.draw());
		try {
			for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
					String[] groupIds = new String[1];
					for (int count = 0; count < outerLoopCount; count++) {
						userId = String.valueOf(randomUser.draw() - 1);
						groupId = String.valueOf(randomGroup.draw() - 1);
						groupIds[0] = groupId;
						am.assignGroupsToUser(userId, groupIds);
					}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void addGroupsToUser() {
		String userId = String.valueOf(randomUser.draw());
		String groupId = String.valueOf(randomGroup.draw());
		try {
			for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
					String[] groupIds = new String[1];
					for (int count = 0; count < outerLoopCount; count++) {
						userId = String.valueOf(randomUser.draw() - 1);
						groupId = String.valueOf(randomGroup.draw() - 1);
						groupIds[0] = groupId;
						am.addGroupsToUser(userId, groupIds);
					}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void assignUserToGroup() {
		String userId = String.valueOf(randomProtectionElement.draw() );
		String gId = String.valueOf(randomProtectionElement.draw() );
		try {
			for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
				String[] pgIds = new String[1];
				for (int count = 0; count < outerLoopCount; count++) {
					userId = String.valueOf(randomUser.draw()-2 );
					gId = String.valueOf(randomGroup.draw()-1 );
					am.assignUserToGroup("TestUserLoginName"+userId, "TestGroupName"+gId);
				}
			}
		} catch (Exception e) {
			e.printStackTrace(); }
	}

	private void assignUserRoleToProtectionGroup() {
		String userId = String.valueOf(randomUser.draw() );
		String pgId = String.valueOf(randomProtectionGroup.draw() );
		String roleId = String.valueOf(randomRole.draw() );
		try {
			for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
				String[] roleIds = new String[1];
				for (int count = 0; count < outerLoopCount; count++) {
					userId = String.valueOf(randomUser.draw() - 1);
					pgId = String.valueOf(randomProtectionGroup.draw() - 1);
					roleId = String.valueOf(randomRole.draw() - 1);
					roleIds[0]=roleId;
					am.assignUserRoleToProtectionGroup(userId,roleIds, pgId);
				}
			}
		} catch (Exception e) {
			e.printStackTrace(); }
	}
	private void addUserRoleToProtectionGroup() {
		String userId = String.valueOf(randomUser.draw() );
		String pgId = String.valueOf(randomProtectionGroup.draw() );
		String roleId = String.valueOf(randomRole.draw() );
		try {
			for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
				String[] roleIds = new String[1];
				for (int count = 0; count < outerLoopCount; count++) {
					userId = String.valueOf(randomUser.draw() - 1);
					pgId = String.valueOf(randomProtectionGroup.draw() - 1);
					roleId = String.valueOf(randomRole.draw() - 1);
					roleIds[0]=roleId;
					am.addUserRoleToProtectionGroup(userId,roleIds, pgId);
				}
			}
		} catch (Exception e) {
			e.printStackTrace(); }
	}

	private void assignToProtectionGroups() {
		String pgId = String.valueOf(randomProtectionElement.draw() );
		String peId = String.valueOf(randomProtectionGroup.draw() );
		try {
			for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
				String[] pgIds = new String[1];
				for (int count = 0; count < outerLoopCount; count++) {
					pgId = String.valueOf(randomProtectionGroup.draw() - 1);
					peId = String.valueOf(randomProtectionElement.draw() - 1);
					pgIds[0]=pgId;
					am.assignToProtectionGroups(peId, pgIds);
				}
			}
		} catch (Exception e) {
			e.printStackTrace(); }
	}
	private void addToProtectionGroups() {
		String pgId = String.valueOf(randomProtectionElement.draw() );
		String peId = String.valueOf(randomProtectionGroup.draw() );
		try {
			for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
				String[] pgIds = new String[1];
				for (int count = 0; count < outerLoopCount; count++) {
					pgId = String.valueOf(randomProtectionGroup.draw() - 1);
					peId = String.valueOf(randomProtectionElement.draw() - 1);
					pgIds[0]=pgId;
					am.addToProtectionGroups(peId, pgIds);
				}
			}
		} catch (Exception e) {
			e.printStackTrace(); }
	}

	private void assignProtectionElements() {
		String pgId = String.valueOf(randomProtectionGroup.draw());
		String peId = String.valueOf(randomProtectionElement.draw());
		try {
			for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
				String[] peIds = new String[1];
				for (int count = 0; count < outerLoopCount; count++) {
					pgId = String.valueOf(randomProtectionGroup.draw() - 2);
					peId = String.valueOf(randomProtectionElement.draw() - 1);
					peIds[0]=peId;
					am.assignProtectionElements(pgId, peIds);
				}
			}
		} catch (Exception e) {
			e.printStackTrace(); }

	}

	private void addProtectionElements() {
		String pgId = String.valueOf(randomProtectionGroup.draw());
		String peId = String.valueOf(randomProtectionElement.draw());
		try {
			for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
				String[] peIds = new String[1];
				for (int count = 0; count < outerLoopCount; count++) {
					pgId = String.valueOf(randomProtectionGroup.draw() - 1);
					peId = String.valueOf(randomProtectionElement.draw() - 1);
					peIds[0]=peId;
					am.addProtectionElements(pgId, peIds);
				}
			}
		} catch (Exception e) {
		//	e.printStackTrace();
		}

	}

	private void assignProtectionElement() {
		String pgId = String.valueOf(randomProtectionGroup.draw());
		String peId = String.valueOf(randomProtectionElement.draw());

			for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {

				for (int count = 0; count < outerLoopCount; count++) {
					pgId = String.valueOf(randomProtectionGroup.draw() - 2);
					peId = String.valueOf(randomProtectionElement.draw() - 1);
					try {
						am.assignProtectionElement("TestProtectionGroupName"+pgId, "TestProtectionElementObjectID"+peId);
					} catch (Exception e) {
						 //e.printStackTrace();

					}

				}
			}

	}

	private void assignParentProtectionGroup() {
		String pgId = String.valueOf(randomRole.draw());
		String parentPgId = String.valueOf(randomProtectionElement.draw());
		try {
			for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {

				for (int count = 0; count < outerLoopCount; count++) {
					pgId = String.valueOf(randomProtectionGroup.draw() );
					parentPgId = String.valueOf(randomProtectionGroup.draw());
					am.assignParentProtectionGroup(pgId, parentPgId);
				}
			}
		} catch (Exception e) {
			e.printStackTrace(); }
	}

	private void assignPrivilegesToRole() {

		String roleId = String.valueOf(randomRole.draw());
		String privId = String.valueOf(randomProtectionElement.draw());
		try {
			for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
				String[] privIds = new String[1];
				for (int count = 0; count < outerLoopCount; count++) {
					roleId = String.valueOf(randomRole.draw() - 1);
					privId = String.valueOf(randomPrivilege.draw() - 1);
					privIds[0] = privId;
					am.assignPrivilegesToRole(roleId, privIds);
				}
			}
		} catch (Exception e) {
			e.printStackTrace(); }
	}
	private void addPrivilegesToRole() {

		String roleId = String.valueOf(randomRole.draw());
		String privId = String.valueOf(randomProtectionElement.draw());
		try {
			for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
				String[] privIds = new String[1];
				for (int count = 0; count < outerLoopCount; count++) {
					roleId = String.valueOf(randomRole.draw() - 1);
					privId = String.valueOf(randomPrivilege.draw() - 1);
					privIds[0] = privId;
					am.addPrivilegesToRole(roleId, privIds);
				}
			}
		} catch (Exception e) {
			e.printStackTrace(); }
	}

	private void assignOwners() {
		String userId = String.valueOf(randomUser.draw());
		String peId = String.valueOf(randomProtectionElement.draw());
		try {
			for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {

				String[] userIds = new String[1];
				for (int count = 0; count < outerLoopCount; count++) {
					userId = String.valueOf(randomUser.draw() - 1);
					userIds[0] = userId;
					peId = String.valueOf(randomProtectionElement.draw() - 1);
					am.assignOwners(peId, userIds);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void addOwners() {
		String userId = String.valueOf(randomUser.draw());
		String peId = String.valueOf(randomProtectionElement.draw());
		try {
			for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {

				String[] userIds = new String[1];
				for (int count = 0; count < outerLoopCount; count++) {
					userId = String.valueOf(randomUser.draw() - 1);
					userIds[0] = userId;
					peId = String.valueOf(randomProtectionElement.draw() - 1);
					am.addOwners(peId, userIds);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void assignUsersToGroup() {
		String userId = String.valueOf(randomUser.draw());
		String groupId = String.valueOf(randomGroup.draw());
		try {
			for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
				String[] userIds = new String[1];
				for (int count = 0; count < outerLoopCount; count++) {
					userId = String.valueOf(randomUser.draw() - 1);
					groupId = String.valueOf(randomGroup.draw() - 1);
					userIds[0] = userId;
					am.assignUsersToGroup(groupId, userIds);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private void addUsersToGroup() {
		String userId = String.valueOf(randomUser.draw());
		String groupId = String.valueOf(randomGroup.draw());
		try {
			for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
				String[] userIds = new String[1];
				for (int count = 0; count < outerLoopCount; count++) {
					userId = String.valueOf(randomUser.draw() - 1);
					groupId = String.valueOf(randomGroup.draw() - 1);
					userIds[0] = userId;
					am.addUsersToGroup(groupId, userIds);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void removeOwnerForProtectionElement() {
		String userId = String.valueOf(randomUser.draw());
		String peId = String.valueOf(randomProtectionElement.draw());
		try {
			for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
				String[] userIds = new String[1];
				for (int count = 0; count < outerLoopCount; count++) {
					userId = String.valueOf(randomUser.draw() - 1);
					userIds[0] = userId;
					peId = String.valueOf(randomProtectionElement.draw() - 1);
					am.removeOwnerForProtectionElement(peId, userIds);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}


text:
<?php

namespace Tga\OpenGraphBundle\Registry;

use Symfony\Component\Routing\Router;
use Tga\OpenGraphBundle\Map\AbstractOpenGraphMap;
use Tga\OpenGraphBundle\Map\OpenGraphMapInterface;
use Tga\OpenGraphBundle\Registry\Exception\FrozenRegistryException;
use Tga\OpenGraphBundle\Routing\RouterAwareInterface;

class Registry
{
    /**
     * @var Router
     */
    protected $router;

    /**
     * @var OpenGraphMapInterface[]
     */
    protected $maps;

    /**
     * @var bool
     */
    protected $frozen = false;

    /**
     * @param Router $router
     */
    public function __construct(Router $router)
    {
        $this->router = $router;
        $this->maps = array();
    }

    /**
     * @param OpenGraphMapInterface $map
     * @return $this
     * @throws Exception\FrozenRegistryException
     */
    public function register(OpenGraphMapInterface $map)
    {
        if ($this->frozen) {
            throw new FrozenRegistryException('register', $map);
        }

        $this->maps[] = $map;

        return $this;
    }

    /**
     * @param OpenGraphMapInterface $map
     * @return bool
     * @throws Exception\FrozenRegistryException
     */
    public function unregister(OpenGraphMapInterface $map)
    {
        if ($this->frozen) {
            throw new FrozenRegistryException('unregister', $map);
        }

        if (($key = array_search($map, $this->maps)) !== false) {
            unset($this->maps[$key]);

            return true;
        }

        return false;
    }

    /**
     * @return $this
     */
    public function freeze()
    {
        $this->injectRouter();

        $this->frozen = true;

        return $this;
    }

    /**
     * @return bool
     */
    public function isFrozen()
    {
        return $this->frozen;
    }

    /**
     * @return OpenGraphMapInterface[]
     */
    public function getMaps()
    {
        return $this->maps;
    }

    /**
     * @return Router
     */
    public function getRouter()
    {
        return $this->router;
    }

    /**
     * Inject router in maps extending the abstract one
     *
     * @return \Tga\OpenGraphBundle\Map\OpenGraphMapInterface[]
     */
    protected function injectRouter()
    {
        foreach ($this->maps as $key => $map) {
            if ($map instanceof RouterAwareInterface) {
                $this->maps[$key]->setRouter($this->router);
            }
        }

        return $this->maps;
    }
}


text:
from django.conf import settings

from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider

_FXA_SETTINGS = getattr(settings, "SOCIALACCOUNT_PROVIDERS", {}).get("fxa", {})
FXA_OAUTH_ENDPOINT = _FXA_SETTINGS.get(
    "OAUTH_ENDPOINT", "https://oauth.accounts.firefox.com/v1"
)
FXA_PROFILE_ENDPOINT = _FXA_SETTINGS.get(
    "PROFILE_ENDPOINT", "https://profile.accounts.firefox.com/v1"
)

class FirefoxAccountsAccount(ProviderAccount):
    def to_str(self):
        return self.account.uid

class FirefoxAccountsProvider(OAuth2Provider):
    id = "fxa"
    name = "Firefox Accounts"
    account_class = FirefoxAccountsAccount

    def get_default_scope(self):
        return ["profile"]

    def extract_uid(self, data):
        return str(data["uid"])

    def extract_common_fields(self, data):
        return dict(email=data.get("email"))

provider_classes = [FirefoxAccountsProvider]


text:
var phoneServices = angular.module('deviceServices', ['ngResource']);
phoneServices.factory('Devices', ['$resource',
    function($resource){
        return $resource('api/devices', {}, {
            query: {method:'GET', isArray:true}
        });
    }]);

phoneServices.factory('Runs', ['$resource',
    function($resource){
        return $resource('api/runs/:id/:device', {}, {
            get: {method:'GET'}
        });
    }]);


text:
```lua
local sprite = Sprite(width, height)
local sprite = Sprite(width, height, colorMode)
local sprite = Sprite(spec)
local sprite = Sprite(otherSprite)
local sprite = Sprite{ fromFile=filename }
local sprite = Sprite{ fromFile=filename, oneFrame }
```

Creates a new sprite with the given `width` and `height`. The
[color mode](colormode.md#colormode) is optional, [RGB](colormode.md#colormodergb)
by default.

The `spec` parameter is an [image specification](imagespec.md#imagespec) object.

If `otherSprite` is given (other `Sprite` object), the sprite is duplicated.

If `fromFile` is given, it indicates a file name (a string) and it's
like opening a new document with [`app.open()`](app.md#appopen).

## Sprite.width

```lua
local w = sprite.width
sprite.width = w
```

Returns or changes the sprite width. Use
[Sprite:resize](#spriteresize) if you want to change the sprite size
resizing layers, images, etc.

## Sprite.height

```lua
local h = sprite.height
sprite.height = h
```

Returns or changes the sprite height. Use
[Sprite:resize](#spriteresize) if you want to change the sprite size
resizing layers, images, etc.

## Sprite.bounds

```lua
local rectangle = sprite.bounds
```

Returns the bounds of the sprite as a
[rectangle](rectangle.md#rectangle) in the position `0,0`.
This is like calling `Rectangle{ x=0, y=0, width=sprite.width, height=sprite.height }`.

## Sprite.gridBounds

```lua
local rectangle = sprite.gridBounds
sprite.gridBounds = rectangle
```

Gets or sets the bounds of the sprite grid as a
[rectangle](rectangle.md#rectangle).

## Sprite.pixelRatio

```lua
local size = sprite.pixelRatio
sprite.pixelRatio = size
```

Gets or sets the pixel ratio of the sprite as a
[size](size.md#size).

## Sprite.selection

```lua
local selection = sprite.selection
sprite.selection = newSelection
```

Gets or sets the active sprite selection. This property is an instance
of the [Selection class](selection.md#selection) to manipulate the set of
selected pixels in the canvas.

## Sprite.filename

```lua
local name = sprite.filename
sprite.filename = newName
```

Gets or sets the name of the file from where this sprite was loaded or
saved. Or an empty string if this is a new sprite without an
associated file.

## Sprite.colorMode

Returns the [color mode](colormode.md#colormode) of this sprite.

## Sprite.spec

```lua
local spec = sprite.spec
```

The [specification](imagespec.md#imagespec) for image in this sprite.

## Sprite.frames

```lua
for i,frame in ipairs(s.frames) do
  -- ...
end
for i = 1,#s.frames do
  -- s.frames[i]
end
```

An array of [frames](frame.md#frame).

## Sprite.palettes

An array of [palettes](palette.md#palette). Generally it contains only one
palette (`sprite.palettes[1]`).

In the future we'll support multiple palettes to create
[color cycling animations](https://en.wikipedia.org/wiki/Color_cycling).

## Sprite.layers

```lua
for i,layer in ipairs(s.layers) do
  -- ...
end
for i = 1,#s.layers do
  -- s.layers[i]
end
```

An array of [layers](layer.md#layer).

## Sprite.cels

```lua
for i,cel in ipairs(s.cels) do
  -- ...
end
for i = 1,#s.cels do
  -- s.cels[i]
end
```

An array of [cels](cel.md#cel).

## Sprite.tags

```lua
for i,tag in ipairs(s.tags) do
  -- ...
end
for i = 1,#s.tags do
  -- s.tags[i]
end
```

An array of [tags](tag.md#tag).

## Sprite.slices

```lua
for i,slice in ipairs(s.slices) do
  -- ...
end
for i = 1,#s.slices do
  -- s.slices[i]
end
```

An array of [slices](slice.md#slice).

## Sprite.backgroundLayer

Returns the [background
layer](https://www.aseprite.org/docs/layers/#background-layer) a
[layer](layer.md#layer) object or `nil` if the sprite doesn't contain a
background layer.

## Sprite.transparentColor

```lua
local number = sprite.transparentColor
sprite.transparentColor = number
```

The transparent color is an intenger that specifies what index (`0` by
default) is the transparent color in transparent layers on indexed
sprites.

## Sprite:resize()

```lua
sprite:resize(width, height)
sprite:resize(size)
```

Resize the sprite (and all frames/cels) to the given dimensions. See
[Size class](size.md#size).

## Sprite:crop()

```lua
sprite:crop(x, y, width, height)
sprite:crop(rectangle)
```

Crops the sprite to the given dimensions. See the
[Rectangle class](rectangle.md#rectangle).

## Sprite:saveAs()

```lua
sprite:saveAs(filename)
```

Saves the sprite to the given file and mark the sprite as saved so
closing it doesn't will ask to save changes.

## Sprite:saveCopyAs()

```lua
sprite:saveCopyAs(filename)
```

Saves a copy of the sprite in the given file but doesn't change the
saved state of the sprite, if the sprite is modified and then try to
close it, the user will be asked to save changes.

## Sprite:close()

```lua
sprite:close()
```

Closes the sprite. This doesn't ask the user to save changes. If you
want to do the classic *File > Close* where the user is asking to save
changes, you can use `app.command.CloseFile()`.

## Sprite:loadPalette()

```lua
sprite:loadPalette(filename)
```

Sets the sprite palette loading it from the given file.

The same can be achieved using [`Palette{ fromFile }`](palette.md#palette):

```lua
sprite:setPalette(Palette{ fromFile=filename })
```

## Sprite:setPalette()

```lua
sprite:setPalette(palette)
```

Changes the sprite [palette](palette.md#palette).

## Sprite:assignColorSpace

```lua
local colorSpace = ColorSpace{ sRGB=true }
sprite:assignColorSpace(colorSpace)
```

Assign a new [color space](colorspace.md#colorspace) to the sprite without
modifying the sprite pixels.

## Sprite:convertColorSpace

```lua
local colorSpace = ColorSpace{ sRGB=true }
sprite:convertColorSpace(colorSpace)
```

Converts all the sprite pixels to a new [color space](colorspace.md#colorspace)
so the image looks the same as in the previous color space (all pixels
will be adjusted to the new color space).

## Sprite:newLayer()

```lua
local layer = sprite:newLayer()
```

Creates a new [layer](layer.md#layer) at the top of the layers stack.

## Sprite:newGroup()

```lua
local layerGroup = sprite:newGroup()
```

Creates a new empty [layer group](layer.md#layer) at the top of the layers stack.

## Sprite:deleteLayer()

```lua
sprite:deleteLayer(layer)
sprite:deleteLayer(layerName)
```

Deletes the given [layer](layer.md#layer) or the layer with the given `layerName` (a string).

## Sprite:newFrame()

```lua
local frame = sprite:newFrame(frame)
local frame = sprite:newFrame(frameNumber)
```

Creates a copy of the given [frame](frame.md#frame) object or frame number
and returns a [`Frame`](frame.md#frame) that points to the newly created
frame in `frameNumber` position.

## Sprite:newEmptyFrame()

Creates a new empty frame in the given `frameNumber` (an integer) and
returns the new [frame](frame.md#frame).

## Sprite:deleteFrame()

```lua
sprite:deleteFrame(frame)
```

## Sprite:newCel()

```lua
cel = sprite:newCel(layer, frame)
cel = sprite:newCel(layer, frame, image, position)
```

Creates a new [cel](cel.md#cel) in the given [layer](layer.md#layer) and `frame`
number. If the [image](image.md#image) is not specified, a new image will be
created with the size of the sprite canvas. The [position](point.md#point)
is a point to locate the image.

## Sprite:deleteCel()

```lua
sprite:deleteCel(cel)
sprite:deleteCel(layer, frame)
```

Deletes the given [cel](cel.md#cel). If the cel is from a transparent
layer, the cel is completely deleted, but if the cel is from a
background layer, the cel will be delete with the
[background color](app.md#appbgcolor).

## Sprite:newTag()

```lua
local tag = sprite:newTag(fromFrameNumber, toFrameNumber)
```

Creates a new [tag](tag.md#tag) in the given frame range and with the given name.

## Sprite:deleteTag()

```lua
sprite:deleteTag(tag)
sprite:deleteTag(tagName)
```

Deletes the given [tag](tag.md#tag).

## Sprite:newSlice()

```lua
local slice = sprite:newSlice()
local slice = sprite:newSlice(Rectangle)
```

Returns a new [slice](slice.md#slice).

## Sprite:deleteSlice()

```lua
sprite:deleteSlice(slice)
sprite:deleteSlice(sliceName)
```

Deletes the given [slice](slice.md#slice).

## Sprite:flatten()

```lua
sprite:flatten()
```

Flatten all layers of the sprite into one layer.
It's like calling `app.commands.FlattenLayers()`.


text:
package org.locationtech.geowave.core.store.api;

import org.locationtech.geowave.core.store.statistics.StatisticType;

/**
 * Base interface for statistic queries.
 *
 * @param <V> the statistic value type
 * @param <R> the return type of the statistic value
 */
public interface StatisticQuery<V extends StatisticValue<R>, R> {
  /**
   * @return the statistic type for the query
   */
  public StatisticType<V> statisticType();

  /**
   * @return the tag filter
   */
  public String tag();

  /**
   * @return the bin filter
   */
  public BinConstraints binConstraints();

  /**
   * @return the authorizations for the query
   */
  public String[] authorizations();
}


text:
#ifdef AWS_MULTI_FRAMEWORK
#import <AWSRuntime/AmazonServiceRequest.h>
#else
#import "AmazonServiceRequest.h"
#endif

#import "SESRequest.h"
#import "SESVerifyEmailIdentityRequest.h"

/**
 * Verify Email Identity Request Marshaller
 */
@interface SESVerifyEmailIdentityRequestMarshaller:NSObject {
}

+(AmazonServiceRequest *)createRequest:(SESVerifyEmailIdentityRequest *)verifyEmailIdentityRequest;

@end


text:
import io
import unittest
from unittest.mock import patch
from kattis import k_loorolls

###############################################################################

class SampleInput(unittest.TestCase):
    '''Problem statement sample inputs and outputs'''

    def test_sample_input_1(self):
        '''Run and assert problem statement sample 1 input and output.'''
        inputs = '31 6\n'
        outputs = '4\n'

        with patch('sys.stdin', io.StringIO(inputs)) as stdin,\
             patch('sys.stdout', new_callable=io.StringIO) as stdout:
            k_loorolls.main()
            self.assertEqual(stdout.getvalue(), outputs)
            self.assertEqual(stdin.read(), '')

    def test_sample_input_2(self):
        '''Run and assert problem statement sample 2 input and output.'''
        inputs = '10000000000 17\n'
        outputs = '3\n'

        with patch('sys.stdin', io.StringIO(inputs)) as stdin,\
             patch('sys.stdout', new_callable=io.StringIO) as stdout:
            k_loorolls.main()
            self.assertEqual(stdout.getvalue(), outputs)
            self.assertEqual(stdin.read(), '')

###############################################################################

if __name__ == '__main__':
    unittest.main()


text:
import apache_beam as beam
import logging

from apache_beam import metrics
from apache_beam.io.gcp.datastore.v1new import datastoreio
from apache_beam.io.gcp.datastore.v1new.types import Query
from apache_beam.options.pipeline_options import GoogleCloudOptions
from apache_beam.options.pipeline_options import PipelineOptions

DATETIME_FORMAT = '%Y-%m-%d:%H:%M:%S%z'

class TokenSelectionOptions(PipelineOptions):

  @classmethod
  def _add_argparse_args(cls, parser):
    parser.add_value_provider_argument(
        '--max_lifetime',
        help=('The duration of time an UploadToken should be kept in '
              'the Datstore, expressed as a string in hours or '
              'minutes or combinations (e.g. 1h30m)'),
        default='6h',
    )
    parser.add_value_provider_argument(
        '--reference_time',
        help=(f'A datetime-parseable reference time, in this '
              f'format: {DATETIME_FORMAT} -- if empty means '
              f'"now".'),
        default='',
    )

  def get_selection_provider(self):
    return _SelectionProvider(self.max_lifetime, self.reference_time)

# TODO(https://crbug.com/1262292): Update after Python2 trybots retire.
# pylint: disable=useless-object-inheritance
class _SelectionProvider(object):

  def __init__(self, max_lifetime, reference_time):
    self._max_lifetime = max_lifetime
    self._reference_time = reference_time
    self._cached_max_lifetime = None
    self._cached_reference_time = None

  @property
  def max_lifetime(self):
    import datetime
    import re
    if self._cached_max_lifetime is None:
      # Support hours and minutes and combinations of each.
      result = re.match(r'((?P<hours>\d+)[Hh])?((?P<minutes>\d+)[Mm])?',
                        self._max_lifetime.get())
      hours = result.group('hours') or '0'
      minutes = result.group('minutes') or '0'
      self._cached_max_lifetime = datetime.timedelta(
          minutes=int(minutes), hours=int(hours))
    return self._cached_max_lifetime

  @property
  def reference_time(self):
    import datetime
    if self._cached_reference_time is None:
      ref_time = self._reference_time.get()
      if not ref_time:
        self._cached_reference_time = datetime.datetime.now(
            tz=datetime.timezone.utc)
      else:
        self._cached_reference_time = datetime.datetime.strptime(
            ref_time, DATETIME_FORMAT)
    return self._cached_reference_time

  def __str__(self):
    return (f'_SelectionProvider(max_lifetime={self._max_lifetime},'
            f'ref={self._reference_time})')

def select_expired_tokens(
    raw_tokens: beam.Pipeline,
    raw_measurements: beam.Pipeline,
    selection_provider: _SelectionProvider,
):
  missing_token_measurements_count = metrics.Metrics.counter(
      'select', 'missing_token_measurements_count')
  deleted_tokens = metrics.Metrics.counter('select', 'deleted_tokens')
  deleted_measurements = metrics.Metrics.counter('select',
                                                 'deleted_measurements')

  def extract_update_timestamp(token):
    return (token.key.to_client_key().id, token)

  tokens = (
      raw_tokens
      | 'ExtractTokenKey' >> beam.Map(extract_update_timestamp))

  def extract_associated_token(measurement_entity, missing_counter):
    measurement = measurement_entity.to_client_entity()
    token_key = measurement.get('token')
    if not token_key:
      missing_counter.inc()
      token_key = '(unspecified)'
    else:
      token_key = token_key.id
    return (token_key, measurement_entity.key)

  measurements = (
      raw_measurements
      | 'ExtractAssociatedToken' >> beam.Map(extract_associated_token,
                                             missing_token_measurements_count))

  # We'll collect all `Measurement` keys by the 'Token' key.
  measurements_by_token = (({
      'token': tokens,
      'measurements': measurements,
  })
                           | 'Merge' >> beam.CoGroupByKey())

  expired_tokens_counter = metrics.Metrics.counter('select', 'expired_tokens')

  def expired_token_selector(keyed_token_and_measurements, selection_provider):
    _, token_and_measurements = keyed_token_and_measurements
    tokens = token_and_measurements['token']

    # This means we have already deleted the token for these
    # measurements, so we'll always delete these measurements.
    if not tokens:
      expired_tokens_counter.inc()
      return True
    token = token_and_measurements['token'][0].to_client_entity()
    lifetime = (selection_provider.reference_time - token['update_time'])
    if lifetime >= selection_provider.max_lifetime:
      expired_tokens_counter.inc()
      return True
    return False

  # We return two PCollection instances, one with just the expired tokens and
  # the other the expired measurements.
  expired_tokens = (
      measurements_by_token
      | 'SelectExpiredTokens' >> beam.Filter(expired_token_selector,
                                             selection_provider))

  def extract_token_key(keyed_token_and_measurements, counter):
    _, token_and_measurements = keyed_token_and_measurements
    tokens = token_and_measurements['token']
    res = [t.key for t in tokens]
    counter.inc(len(res))
    return res

  def pick_nonempty_tokens(keyed_token_and_measurements):
    token_key, _ = keyed_token_and_measurements
    return token_key != '(unspecified)' or len(token_key) > 0

  tokens_to_delete = (
      expired_tokens
      | 'PickNonEmptyTokens' >> beam.Filter(pick_nonempty_tokens)
      | 'ExtractTokenKeys' >> beam.FlatMap(extract_token_key, deleted_tokens))

  def extract_measurement(keyed_token_and_measurements, counter):
    _, token_and_measurements = keyed_token_and_measurements
    res = token_and_measurements['measurements']
    counter.inc(len(res))
    return res

  measurements_to_delete = (
      expired_tokens
      | 'ExtractMeasurementKeys' >> beam.FlatMap(extract_measurement,
                                                 deleted_measurements))

  return tokens_to_delete, measurements_to_delete

class CountInput(beam.DoFn):

  def __init__(self, counter):
    self._counter = counter

  def process(self, input):
    self._counter.inc()
    yield input

def main():
  project = 'chromeperf'
  options = PipelineOptions()
  options.view_as(GoogleCloudOptions).project = project
  selection_options = options.view_as(TokenSelectionOptions)

  p = beam.Pipeline(options=options)
  token_count = metrics.Metrics.counter('main', 'tokens_read')
  measurement_count = metrics.Metrics.counter('main', 'measurements_read')

  raw_tokens = (
      p | 'ReadUploadTokens' >>
      datastoreio.ReadFromDatastore(query=Query(kind='Token', project=project)))

  # Count the tokens.
  _ = (raw_tokens | 'CountTokens' >> beam.ParDo(CountInput(token_count)))

  raw_measurements = (
      p
      | 'ReadMeasurements' >> datastoreio.ReadFromDatastore(
          query=Query(kind='Measurement', project=project)))

  # Count the measurements.
  _ = (
      raw_measurements
      | 'CountMeasurements' >> beam.ParDo(CountInput(measurement_count)))

  tokens_to_delete, measurements_to_delete = select_expired_tokens(
      raw_tokens, raw_measurements, selection_options.get_selection_provider())

  _ = (
      tokens_to_delete
      | 'DeleteTokens' >> datastoreio.DeleteFromDatastore(project))

  _ = (
      measurements_to_delete
      | 'ReshuffleMeasurements' >> beam.Reshuffle()
      | 'DeleteMeasurements' >> datastoreio.DeleteFromDatastore(project))

  # Run the pipeline!
  result = p.run()
  result.wait_until_finish()

if __name__ == '__main__':
  logging.getLogger().setLevel(logging.INFO)
  main()


text:
#include "DemoServer.h"
#include "EventManager.h"
#include <iostream>

using namespace std;

DemoServer::DemoServer()
: topic("http://example.com/simple/ev3")
{
  addRemoteProcedure("http://example.com/simple/calc#add",&DemoServer::adding);
  addRemoteProcedure("http://example.com/simple/ev1",&DemoServer::handleEvent1);

  running = true;
  eventThread = thread(&DemoServer::eventLoop,this);
}

DemoServer::~DemoServer()
{
  running = false;
  std::cout << "DemoServer shutting down" << std::endl;
  eventThread.join();
  std::cout << "DemoServer shut down" << std::endl;
}

int DemoServer::adding(int a, int b)
{
  return a+b;
}

void DemoServer::handleEvent1(int a)
{
  std::cout << "Event 1 received " << a << std::endl;
}

void DemoServer::eventLoop()
{
	while(running)
	{
		this_thread::sleep_for(chrono::seconds(5));

		/* Use EventManager directly */
		EventManager::getInstance().publish("http://example.com/simple/ev2", 55);

		/* Publish to predefined topic */
		topic.update(12);
	}
}


text:
package org.apache.flink.runtime.rest.handler.cluster;

import org.apache.flink.api.common.time.Time;
import org.apache.flink.runtime.rest.handler.AbstractRestHandler;
import org.apache.flink.runtime.rest.handler.HandlerRequest;
import org.apache.flink.runtime.rest.messages.DashboardConfiguration;
import org.apache.flink.runtime.rest.messages.EmptyMessageParameters;
import org.apache.flink.runtime.rest.messages.EmptyRequestBody;
import org.apache.flink.runtime.rest.messages.MessageHeaders;
import org.apache.flink.runtime.webmonitor.RestfulGateway;
import org.apache.flink.runtime.webmonitor.retriever.GatewayRetriever;

import javax.annotation.Nonnull;

import java.time.ZonedDateTime;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * Handler which returns the dashboard configuration.
 */
public class DashboardConfigHandler extends AbstractRestHandler<RestfulGateway, EmptyRequestBody, DashboardConfiguration, EmptyMessageParameters> {

	private final DashboardConfiguration dashboardConfiguration;

	public DashboardConfigHandler(
			GatewayRetriever<? extends RestfulGateway> leaderRetriever,
			Time timeout,
			Map<String, String> responseHeaders,
			MessageHeaders<EmptyRequestBody, DashboardConfiguration, EmptyMessageParameters> messageHeaders,
			long refreshInterval,
			boolean webSubmitEnabled) {
		super(leaderRetriever, timeout, responseHeaders, messageHeaders);

		dashboardConfiguration = DashboardConfiguration.from(refreshInterval, ZonedDateTime.now(), webSubmitEnabled);
	}

	@Override
	public CompletableFuture<DashboardConfiguration> handleRequest(@Nonnull HandlerRequest<EmptyRequestBody, EmptyMessageParameters> request, @Nonnull RestfulGateway gateway) {
		return CompletableFuture.completedFuture(dashboardConfiguration);
	}
}


text:
%% Règles sur les listes
% Titre : Définition de la règle sommeList
% Règle : sommeList/2
% Param 1 : Liste dont on cherche à sommer les éléments
% Param 2 : Résultat
% Usage : Calcul de la somme des éléments de la liste.
sommeList([],0):- !.
sommeList([L|T], Somme) :- sommeList(T,S), Somme is S + L.

% Titre : Définition de la règle sommeImpaire
% Règle : sommeList/2
% Param 1 : Liste dont on cherche à sommer les éléments
% Param 2 : Résultat
% Usage : Calcul de la somme des éléments aux positions impairs de la liste (1, 3, ...).
sommeImpaire([],0) :- !.
sommeImpaire([W,_|T],Somme) :- sommeImpaire(T,S), Somme is W + S.
sommeImpaire([W],Somme) :- Somme is W.

% Titre : Définition de la règle moyenne
% Règle  : moyenne/2
% Param 1 : Liste dont on cherche à calculer la moyenne
% Param 2 : Résultat
% Usage : Calcul la moyenne des éléments.
moyenne(L,M):- sommeList(L,S), length(L,Len), M is S / Len.

% Titre : Définition de la règle noccur
% Règle : noccur/3
% Param 1 : Elément
% Param 2 : Liste dans laquelle on recherche le nombre d'occurence du paramètre 1
% Param 3 : Résultat
% Usage : Calcul le nombre d'occurence du paramètre 1.
noccur(_, [], 0).
noccur(E,[E|T],X):- noccur(E, T, X2), X is X2 + 1 .
noccur(E,[Y|T],X):- E \= Y, noccur(E, T, X).

% Titre : Définition de la règle adjacent
% Règle : adjacent/3
% Param 1 : Elément 1
% Param 2 : Elément 2
% Param : Liste dans laquelle on recherche l'adjacence des éléments.
% Usage : Recherche l'adjacence des paramètres 1 et 2 (dans cet ordre) dans le paramètre 3.
adjacent(X,Y,[X,Y|_]).
adjacent(X,Y,[_|T]):- adjacent(X,Y,T).

% Titre : Définition de la règle prefix
% Règle : prefix/2
% Param 1 : Elément 1
% Param 2 : Elément 2
% Usage : Recherche si le paramètre 1 est un prefix du paramètre 2.
prefix([],_).
prefix([H|T],[H|U]):- prefix(T,U).

% Titre : Définition de la règle suffix
% Règle : suffix/2
% Param 1 : Elément 1
% Param 2 : Elément 2
% Usage : Recherche si le paramètre 1 est un suffix du paramètre 2.
suffix(S,S).
suffix(S,[_|T]) :- suffix(S,T).

% Titre : Définition de la règle double
% Règle : double/2
% Param 1 : Elément 1
% Param 2 : Elément 2
% Usage : Recherche si le paramètre 2 est un double du paramètre 1.
double([T],[T,T]).
double([T|L],[T,T|X]):- double(L,X).


text:
require "rails_helper"

describe Eve::UpdateFactionsJob do
  it { should be_an(ApplicationJob) }

  it { expect(described_class.queue_name).to eq("default") }

  describe "#perform" do
    before do
      #
      # LanguageMapper::LANGUAGES.each_key do |locale|
      #   Eve::FactionsImporter.new(locale).import
      # end
      #
      LanguageMapper::LANGUAGES.each_key do |locale|
        expect(Eve::FactionsImporter).to receive(:new).with(locale) do
          double.tap do |a|
            expect(a).to receive(:import)
          end
        end
      end
    end

    specify { expect { subject.perform }.not_to raise_error }
  end
end


text:
<?php
/**
 * log-to-file
 *
 * @file: Decorator.php
 * @author Ashterix <ashterix69@gmail.com>
 *
 * Class - Decorator
 * @description
 *
 * Created by JetBrains PhpStorm.
 * Date: 18.03.2015
 * Time: 13:57
 */

namespace LogToFile;

class Decorator {

    const FORMAT_DATE = "Y-m-d";
    const FORMAT_TIME = "H:s:i";

    /**
     * @var string Message after wrapping
     */
    private $wrappedMsg = '';

    /**
     * @description Add separator to wrapper
     *
     * @param string $separator
     * @param int $countRepetitions
     *
     * @return $this
     */
    public function addSeparator($separator = '*', $countRepetitions = 1)
    {
        $this->wrappedMsg .= str_repeat($separator, $countRepetitions);

        return $this;
    }

    /**
     * @description Add newline
     *
     * @return $this
     */
    public function addNewline()
    {
        $this->wrappedMsg .= PHP_EOL;

        return $this;
    }

    /**
     * @description Add date to wrapper
     *
     * @return $this
     */
    public function addDate()
    {
        $this->wrappedMsg .= date(self::FORMAT_DATE);

        return $this;
    }

    /**
     * @description Add time to wrapper
     *
     * @return $this
     */
    public function addTime()
    {
        $this->wrappedMsg .= date(self::FORMAT_TIME);

        return $this;
    }

    /**
     * @description Add message to wrapper
     *
     * @param $msg
     *
     * @return $this
     */
    public function addMsg($msg)
    {
        $this->wrappedMsg .= $msg;

        return $this;
    }

    /**
     * @description Return wrapped message
     *
     * @return string
     */
    public function getBuildMsg()
    {
        $return = $this->wrappedMsg;
        $this->wrappedMsg = '';

        return $return;
    }

}


text:
package fi.ni.ifc2x3;
import fi.ni.ifc2x3.interfaces.*;
import fi.ni.*;
import java.util.*;

/*
 * IFC Java class
 * @author Jyrki Oraskari
 * @license This work is licensed under a Creative Commons Attribution 3.0 Unported License.
 * http://creativecommons.org/licenses/by/3.0/
 */

public class IfcTimeSeriesValue extends Thing
{
 // The property attributes
 List<String> listValues = new IfcList<String>();

 // Getters and setters of properties

 public List<String> getListValues() {
   return listValues;
 }
 public void setListValues(String value){
   this.listValues.add(value);

 }

}


text:
#pragma once

#include <openssl/dh.h>

#include "stuffer/s2n_stuffer.h"

#include "utils/s2n_blob.h"

struct s2n_dh_params {
    DH *dh;
};

extern int s2n_pkcs3_to_dh_params(struct s2n_dh_params *dh_params, struct s2n_blob *pkcs3);
extern int s2n_dh_p_g_Ys_to_dh_params(struct s2n_dh_params *dh_params, struct s2n_blob *p, struct s2n_blob *g, struct s2n_blob *ys);
extern int s2n_dh_params_to_p_g_Ys(struct s2n_dh_params *server_dh_params, struct s2n_stuffer *out, struct s2n_blob *output);
extern int s2n_dh_compute_shared_secret_as_server(struct s2n_dh_params *server_dh_params, struct s2n_stuffer *Yc_in, struct s2n_blob *shared_key);
extern int s2n_dh_compute_shared_secret_as_client(struct s2n_dh_params *server_dh_params, struct s2n_stuffer *Yc_out, struct s2n_blob *shared_key);
extern int s2n_dh_params_copy(struct s2n_dh_params *from, struct s2n_dh_params *to);
extern int s2n_dh_generate_ephemeral_key(struct s2n_dh_params *dh_params);
extern int s2n_dh_params_free(struct s2n_dh_params *dh_params);


text:
use crate::loom::sync::atomic::AtomicUsize;

use std::fmt;
use std::sync::atomic::Ordering::{AcqRel, Acquire, Release};
use std::usize;

pub(super) struct State {
    val: AtomicUsize,
}

/// Current state value.
#[derive(Copy, Clone)]
pub(super) struct Snapshot(usize);

type UpdateResult = Result<Snapshot, Snapshot>;

/// The task is currently being run.
const RUNNING: usize = 0b0001;

/// The task is complete.
///
/// Once this bit is set, it is never unset.
const COMPLETE: usize = 0b0010;

/// Extracts the task's lifecycle value from the state.
const LIFECYCLE_MASK: usize = 0b11;

/// Flag tracking if the task has been pushed into a run queue.
const NOTIFIED: usize = 0b100;

/// The join handle is still around.
#[allow(clippy::unusual_byte_groupings)] // https://github.com/rust-lang/rust-clippy/issues/6556
const JOIN_INTEREST: usize = 0b1_000;

/// A join handle waker has been set.
#[allow(clippy::unusual_byte_groupings)] // https://github.com/rust-lang/rust-clippy/issues/6556
const JOIN_WAKER: usize = 0b10_000;

/// The task has been forcibly cancelled.
#[allow(clippy::unusual_byte_groupings)] // https://github.com/rust-lang/rust-clippy/issues/6556
const CANCELLED: usize = 0b100_000;

/// All bits.
const STATE_MASK: usize = LIFECYCLE_MASK | NOTIFIED | JOIN_INTEREST | JOIN_WAKER | CANCELLED;

/// Bits used by the ref count portion of the state.
const REF_COUNT_MASK: usize = !STATE_MASK;

/// Number of positions to shift the ref count.
const REF_COUNT_SHIFT: usize = REF_COUNT_MASK.count_zeros() as usize;

/// One ref count.
const REF_ONE: usize = 1 << REF_COUNT_SHIFT;

/// State a task is initialized with.
///
/// A task is initialized with three references:
///
///  * A reference that will be stored in an OwnedTasks or LocalOwnedTasks.
///  * A reference that will be sent to the scheduler as an ordinary notification.
///  * A reference for the JoinHandle.
///
/// As the task starts with a `JoinHandle`, `JOIN_INTEREST` is set.
/// As the task starts with a `Notified`, `NOTIFIED` is set.
const INITIAL_STATE: usize = (REF_ONE * 3) | JOIN_INTEREST | NOTIFIED;

#[must_use]
pub(super) enum TransitionToRunning {
    Success,
    Cancelled,
    Failed,
    Dealloc,
}

#[must_use]
pub(super) enum TransitionToIdle {
    Ok,
    OkNotified,
    OkDealloc,
    Cancelled,
}

#[must_use]
pub(super) enum TransitionToNotifiedByVal {
    DoNothing,
    Submit,
    Dealloc,
}

#[must_use]
pub(super) enum TransitionToNotifiedByRef {
    DoNothing,
    Submit,
}

/// All transitions are performed via RMW operations. This establishes an
/// unambiguous modification order.
impl State {
    /// Returns a task's initial state.
    pub(super) fn new() -> State {
        // The raw task returned by this method has a ref-count of three. See
        // the comment on INITIAL_STATE for more.
        State {
            val: AtomicUsize::new(INITIAL_STATE),
        }
    }

    /// Loads the current state, establishes `Acquire` ordering.
    pub(super) fn load(&self) -> Snapshot {
        Snapshot(self.val.load(Acquire))
    }

    /// Attempts to transition the lifecycle to `Running`. This sets the
    /// notified bit to false so notifications during the poll can be detected.
    pub(super) fn transition_to_running(&self) -> TransitionToRunning {
        self.fetch_update_action(|mut next| {
            let action;
            assert!(next.is_notified());

            if !next.is_idle() {
                // This happens if the task is either currently running or if it
                // has already completed, e.g. if it was cancelled during
                // shutdown. Consume the ref-count and return.
                next.ref_dec();
                if next.ref_count() == 0 {
                    action = TransitionToRunning::Dealloc;
                } else {
                    action = TransitionToRunning::Failed;
                }
            } else {
                // We are able to lock the RUNNING bit.
                next.set_running();
                next.unset_notified();

                if next.is_cancelled() {
                    action = TransitionToRunning::Cancelled;
                } else {
                    action = TransitionToRunning::Success;
                }
            }
            (action, Some(next))
        })
    }

    /// Transitions the task from `Running` -> `Idle`.
    ///
    /// Returns `true` if the transition to `Idle` is successful, `false` otherwise.
    /// The transition to `Idle` fails if the task has been flagged to be
    /// cancelled.
    pub(super) fn transition_to_idle(&self) -> TransitionToIdle {
        self.fetch_update_action(|curr| {
            assert!(curr.is_running());

            if curr.is_cancelled() {
                return (TransitionToIdle::Cancelled, None);
            }

            let mut next = curr;
            let action;
            next.unset_running();

            if !next.is_notified() {
                // Polling the future consumes the ref-count of the Notified.
                next.ref_dec();
                if next.ref_count() == 0 {
                    action = TransitionToIdle::OkDealloc;
                } else {
                    action = TransitionToIdle::Ok;
                }
            } else {
                // The caller will schedule a new notification, so we create a
                // new ref-count for the notification. Our own ref-count is kept
                // for now, and the caller will drop it shortly.
                next.ref_inc();
                action = TransitionToIdle::OkNotified;
            }

            (action, Some(next))
        })
    }

    /// Transitions the task from `Running` -> `Complete`.
    pub(super) fn transition_to_complete(&self) -> Snapshot {
        const DELTA: usize = RUNNING | COMPLETE;

        let prev = Snapshot(self.val.fetch_xor(DELTA, AcqRel));
        assert!(prev.is_running());
        assert!(!prev.is_complete());

        Snapshot(prev.0 ^ DELTA)
    }

    /// Transitions from `Complete` -> `Terminal`, decrementing the reference
    /// count the specified number of times.
    ///
    /// Returns true if the task should be deallocated.
    pub(super) fn transition_to_terminal(&self, count: usize) -> bool {
        let prev = Snapshot(self.val.fetch_sub(count * REF_ONE, AcqRel));
        assert!(
            prev.ref_count() >= count,
            "current: {}, sub: {}",
            prev.ref_count(),
            count
        );
        prev.ref_count() == count
    }

    /// Transitions the state to `NOTIFIED`.
    ///
    /// If no task needs to be submitted, a ref-count is consumed.
    ///
    /// If a task needs to be submitted, the ref-count is incremented for the
    /// new Notified.
    pub(super) fn transition_to_notified_by_val(&self) -> TransitionToNotifiedByVal {
        self.fetch_update_action(|mut snapshot| {
            let action;

            if snapshot.is_running() {
                // If the task is running, we mark it as notified, but we should
                // not submit anything as the thread currently running the
                // future is responsible for that.
                snapshot.set_notified();
                snapshot.ref_dec();

                // The thread that set the running bit also holds a ref-count.
                assert!(snapshot.ref_count() > 0);

                action = TransitionToNotifiedByVal::DoNothing;
            } else if snapshot.is_complete() || snapshot.is_notified() {
                // We do not need to submit any notifications, but we have to
                // decrement the ref-count.
                snapshot.ref_dec();

                if snapshot.ref_count() == 0 {
                    action = TransitionToNotifiedByVal::Dealloc;
                } else {
                    action = TransitionToNotifiedByVal::DoNothing;
                }
            } else {
                // We create a new notified that we can submit. The caller
                // retains ownership of the ref-count they passed in.
                snapshot.set_notified();
                snapshot.ref_inc();
                action = TransitionToNotifiedByVal::Submit;
            }

            (action, Some(snapshot))
        })
    }

    /// Transitions the state to `NOTIFIED`.
    pub(super) fn transition_to_notified_by_ref(&self) -> TransitionToNotifiedByRef {
        self.fetch_update_action(|mut snapshot| {
            if snapshot.is_complete() || snapshot.is_notified() {
                // There is nothing to do in this case.
                (TransitionToNotifiedByRef::DoNothing, None)
            } else if snapshot.is_running() {
                // If the task is running, we mark it as notified, but we should
                // not submit as the thread currently running the future is
                // responsible for that.
                snapshot.set_notified();
                (TransitionToNotifiedByRef::DoNothing, Some(snapshot))
            } else {
                // The task is idle and not notified. We should submit a
                // notification.
                snapshot.set_notified();
                snapshot.ref_inc();
                (TransitionToNotifiedByRef::Submit, Some(snapshot))
            }
        })
    }

    /// Sets the cancelled bit and transitions the state to `NOTIFIED` if idle.
    ///
    /// Returns `true` if the task needs to be submitted to the pool for
    /// execution.
    pub(super) fn transition_to_notified_and_cancel(&self) -> bool {
        self.fetch_update_action(|mut snapshot| {
            if snapshot.is_cancelled() || snapshot.is_complete() {
                // Aborts to completed or cancelled tasks are no-ops.
                (false, None)
            } else if snapshot.is_running() {
                // If the task is running, we mark it as cancelled. The thread
                // running the task will notice the cancelled bit when it
                // stops polling and it will kill the task.
                //
                // The set_notified() call is not strictly necessary but it will
                // in some cases let a wake_by_ref call return without having
                // to perform a compare_exchange.
                snapshot.set_notified();
                snapshot.set_cancelled();
                (false, Some(snapshot))
            } else {
                // The task is idle. We set the cancelled and notified bits and
                // submit a notification if the notified bit was not already
                // set.
                snapshot.set_cancelled();
                if !snapshot.is_notified() {
                    snapshot.set_notified();
                    snapshot.ref_inc();
                    (true, Some(snapshot))
                } else {
                    (false, Some(snapshot))
                }
            }
        })
    }

    /// Sets the `CANCELLED` bit and attempts to transition to `Running`.
    ///
    /// Returns `true` if the transition to `Running` succeeded.
    pub(super) fn transition_to_shutdown(&self) -> bool {
        let mut prev = Snapshot(0);

        let _ = self.fetch_update(|mut snapshot| {
            prev = snapshot;

            if snapshot.is_idle() {
                snapshot.set_running();
            }

            // If the task was not idle, the thread currently running the task
            // will notice the cancelled bit and cancel it once the poll
            // completes.
            snapshot.set_cancelled();
            Some(snapshot)
        });

        prev.is_idle()
    }

    /// Optimistically tries to swap the state assuming the join handle is
    /// __immediately__ dropped on spawn.
    pub(super) fn drop_join_handle_fast(&self) -> Result<(), ()> {
        use std::sync::atomic::Ordering::Relaxed;

        // Relaxed is acceptable as if this function is called and succeeds,
        // then nothing has been done w/ the join handle.
        //
        // The moment the join handle is used (polled), the `JOIN_WAKER` flag is
        // set, at which point the CAS will fail.
        //
        // Given this, there is no risk if this operation is reordered.
        self.val
            .compare_exchange_weak(
                INITIAL_STATE,
                (INITIAL_STATE - REF_ONE) & !JOIN_INTEREST,
                Release,
                Relaxed,
            )
            .map(|_| ())
            .map_err(|_| ())
    }

    /// Tries to unset the JOIN_INTEREST flag.
    ///
    /// Returns `Ok` if the operation happens before the task transitions to a
    /// completed state, `Err` otherwise.
    pub(super) fn unset_join_interested(&self) -> UpdateResult {
        self.fetch_update(|curr| {
            assert!(curr.is_join_interested());

            if curr.is_complete() {
                return None;
            }

            let mut next = curr;
            next.unset_join_interested();

            Some(next)
        })
    }

    /// Sets the `JOIN_WAKER` bit.
    ///
    /// Returns `Ok` if the bit is set, `Err` otherwise. This operation fails if
    /// the task has completed.
    pub(super) fn set_join_waker(&self) -> UpdateResult {
        self.fetch_update(|curr| {
            assert!(curr.is_join_interested());
            assert!(!curr.has_join_waker());

            if curr.is_complete() {
                return None;
            }

            let mut next = curr;
            next.set_join_waker();

            Some(next)
        })
    }

    /// Unsets the `JOIN_WAKER` bit.
    ///
    /// Returns `Ok` has been unset, `Err` otherwise. This operation fails if
    /// the task has completed.
    pub(super) fn unset_waker(&self) -> UpdateResult {
        self.fetch_update(|curr| {
            assert!(curr.is_join_interested());
            assert!(curr.has_join_waker());

            if curr.is_complete() {
                return None;
            }

            let mut next = curr;
            next.unset_join_waker();

            Some(next)
        })
    }

    pub(super) fn ref_inc(&self) {
        use std::process;
        use std::sync::atomic::Ordering::Relaxed;

        // Using a relaxed ordering is alright here, as knowledge of the
        // original reference prevents other threads from erroneously deleting
        // the object.
        //
        // As explained in the [Boost documentation][1], Increasing the
        // reference counter can always be done with memory_order_relaxed: New
        // references to an object can only be formed from an existing
        // reference, and passing an existing reference from one thread to
        // another must already provide any required synchronization.
        //
        // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
        let prev = self.val.fetch_add(REF_ONE, Relaxed);

        // If the reference count overflowed, abort.
        if prev > isize::MAX as usize {
            process::abort();
        }
    }

    /// Returns `true` if the task should be released.
    pub(super) fn ref_dec(&self) -> bool {
        let prev = Snapshot(self.val.fetch_sub(REF_ONE, AcqRel));
        assert!(prev.ref_count() >= 1);
        prev.ref_count() == 1
    }

    /// Returns `true` if the task should be released.
    pub(super) fn ref_dec_twice(&self) -> bool {
        let prev = Snapshot(self.val.fetch_sub(2 * REF_ONE, AcqRel));
        assert!(prev.ref_count() >= 2);
        prev.ref_count() == 2
    }

    fn fetch_update_action<F, T>(&self, mut f: F) -> T
    where
        F: FnMut(Snapshot) -> (T, Option<Snapshot>),
    {
        let mut curr = self.load();

        loop {
            let (output, next) = f(curr);
            let next = match next {
                Some(next) => next,
                None => return output,
            };

            let res = self.val.compare_exchange(curr.0, next.0, AcqRel, Acquire);

            match res {
                Ok(_) => return output,
                Err(actual) => curr = Snapshot(actual),
            }
        }
    }

    fn fetch_update<F>(&self, mut f: F) -> Result<Snapshot, Snapshot>
    where
        F: FnMut(Snapshot) -> Option<Snapshot>,
    {
        let mut curr = self.load();

        loop {
            let next = match f(curr) {
                Some(next) => next,
                None => return Err(curr),
            };

            let res = self.val.compare_exchange(curr.0, next.0, AcqRel, Acquire);

            match res {
                Ok(_) => return Ok(next),
                Err(actual) => curr = Snapshot(actual),
            }
        }
    }
}

// ===== impl Snapshot =====

impl Snapshot {
    /// Returns `true` if the task is in an idle state.
    pub(super) fn is_idle(self) -> bool {
        self.0 & (RUNNING | COMPLETE) == 0
    }

    /// Returns `true` if the task has been flagged as notified.
    pub(super) fn is_notified(self) -> bool {
        self.0 & NOTIFIED == NOTIFIED
    }

    fn unset_notified(&mut self) {
        self.0 &= !NOTIFIED
    }

    fn set_notified(&mut self) {
        self.0 |= NOTIFIED
    }

    pub(super) fn is_running(self) -> bool {
        self.0 & RUNNING == RUNNING
    }

    fn set_running(&mut self) {
        self.0 |= RUNNING;
    }

    fn unset_running(&mut self) {
        self.0 &= !RUNNING;
    }

    pub(super) fn is_cancelled(self) -> bool {
        self.0 & CANCELLED == CANCELLED
    }

    fn set_cancelled(&mut self) {
        self.0 |= CANCELLED;
    }

    /// Returns `true` if the task's future has completed execution.
    pub(super) fn is_complete(self) -> bool {
        self.0 & COMPLETE == COMPLETE
    }

    pub(super) fn is_join_interested(self) -> bool {
        self.0 & JOIN_INTEREST == JOIN_INTEREST
    }

    fn unset_join_interested(&mut self) {
        self.0 &= !JOIN_INTEREST
    }

    pub(super) fn has_join_waker(self) -> bool {
        self.0 & JOIN_WAKER == JOIN_WAKER
    }

    fn set_join_waker(&mut self) {
        self.0 |= JOIN_WAKER;
    }

    fn unset_join_waker(&mut self) {
        self.0 &= !JOIN_WAKER
    }

    pub(super) fn ref_count(self) -> usize {
        (self.0 & REF_COUNT_MASK) >> REF_COUNT_SHIFT
    }

    fn ref_inc(&mut self) {
        assert!(self.0 <= isize::MAX as usize);
        self.0 += REF_ONE;
    }

    pub(super) fn ref_dec(&mut self) {
        assert!(self.ref_count() > 0);
        self.0 -= REF_ONE
    }
}

impl fmt::Debug for State {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        let snapshot = self.load();
        snapshot.fmt(fmt)
    }
}

impl fmt::Debug for Snapshot {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt.debug_struct("Snapshot")
            .field("is_running", &self.is_running())
            .field("is_complete", &self.is_complete())
            .field("is_notified", &self.is_notified())
            .field("is_cancelled", &self.is_cancelled())
            .field("is_join_interested", &self.is_join_interested())
            .field("has_join_waker", &self.has_join_waker())
            .field("ref_count", &self.ref_count())
            .finish()
    }
}


text:
require 'twilio-ruby'

response = Twilio::TwiML::VoiceResponse.new
response.gather

puts response