text:
QUnit.test('Object.iterateKeys', assert => {
  const { iterateKeys } = Object;
  assert.isFunction(iterateKeys);
  assert.name(iterateKeys, 'iterateKeys');
  assert.arity(iterateKeys, 1);
  assert.looksNative(iterateKeys);
  assert.nonEnumerable(Object, 'iterateKeys');

  const object = {
    q: 1,
    w: 2,
    e: 3,
  };
  const iterator = iterateKeys(object);
  assert.isIterator(iterator);
  assert.isIterable(iterator);
  assert.same(iterator[Symbol.toStringTag], 'Object Iterator');
  assert.deepEqual(iterator.next(), {
    value: 'q',
    done: false,
  });
  delete object.w;
  assert.deepEqual(iterator.next(), {
    value: 'e',
    done: false,
  });
  assert.deepEqual(iterator.next(), {
    value: undefined,
    done: true,
  });
});


text:
export const Identifier = {
  ROOT: 'mdl-radio',
  NATIVE_INPUT: 'mdl-radio__input'
};

export default function MDLRadioMixin(renderer) {
  Object.assign(this, {
    initMdlRadio_() {
      this.renderer_ = bindAll(renderer, this);
    }
  });

  Object.defineProperty(this, 'checked', {
    get: function() {
      return Boolean(this.renderer_.getProperty(Identifier.NATIVE_INPUT, 'checked'));
    },

    set: function(value) {
      this.renderer_.setProperty(Identifier.NATIVE_INPUT, 'checked', value);
    }
  });

  Object.defineProperty(this, 'disabled', {
    get: function() {
      return Boolean(this.renderer_.getProperty(Identifier.NATIVE_INPUT, 'disabled'));
    },

    set: function(value) {
      this.renderer_.setProperty(Identifier.NATIVE_INPUT, 'disabled', value);
    }
  });
}

/**
 * Create a cloned object with functions bound to the given this parameter.
 */
// TODO(mtlin): Make a shared mixin package or utils equivalent.
function bindAll(obj, self) {
  const boundObj = {};
  Object.keys(obj).forEach(key => {
    boundObj[key] = obj[key].bind(self);
  });
  return boundObj;
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.karaf.admin.command;

import org.apache.felix.gogo.commands.Option;
import org.apache.felix.gogo.commands.Command;
import org.apache.karaf.admin.Instance;

/**
 * List available instances
 */
@Command(scope = "admin", name = "list", description = "Lists all existing container instances.")
public class ListCommand extends AdminCommandSupport {

    @Option(name = "-l", aliases = { "--location" }, description = "Displays the location of the container instances", required = false, multiValued = false)
    boolean location;

    @Option(name = "-o", aliases = { "--java-opts" }, description = "Displays the java options used to launch the JVM", required = false, multiValued = false)
    boolean javaOpts;

    protected Object doExecute() throws Exception {
        Instance[] instances = getAdminService().getInstances();
        if (javaOpts) {
            System.out.println("  SSH Port   RMI Ports          State       Pid  JavaOpts");
        } else if (location) {
            System.out.println("  SSH Port   RMI Ports          State       Pid  Location");
        } else {
            System.out.println("  SSH Port   RMI Ports          State       Pid  Name");
        }
        for (Instance instance : instances) {
            StringBuilder sb = new StringBuilder();
            sb.append('[');
            String s = Integer.toString(instance.getSshPort());
            for (int i = s.length(); i < 8; i++) {
                sb.append(' ');
            }
            sb.append(s);
            sb.append("] [");
            String rmiRegistry = Integer.toString(instance.getRmiRegistryPort());
            String rmiServer = Integer.toString(instance.getRmiServerPort());
            sb.append(rmiRegistry).append("/").append(rmiServer);
            for (int i = (rmiRegistry.length() + rmiServer.length() + 1); i < 15; i++) {
                sb.append(' ');
            }
            sb.append("] [");
            String state = instance.getState();
            while (state.length() < "starting".length()) {
                state += " ";
            }
            sb.append(state);
            sb.append("] [");
            s = Integer.toString(instance.getPid());
            for (int i = s.length(); i < 5; i++) {
                sb.append(' ');
            }
            sb.append(s);
            sb.append("] ");
            if (javaOpts) {
                sb.append(instance.getJavaOpts());
            } else if (location) {
                sb.append(instance.getLocation());
            } else {
                sb.append(instance.getName());
            }
            System.out.println(sb.toString());
        }
        return null;
    }

}


text:
<?php

namespace BsbFlysystem\Service\Factory;

use BsbFlysystem\Filesystem\Factory\FilesystemFactory;
use BsbFlysystem\Service\FilesystemManager;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class FilesystemManagerFactory implements FactoryInterface
{
    /**
     * Create service
     *
     * @param ServiceLocatorInterface $serviceLocator
     *
     * @return mixed
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        return $this($serviceLocator, null);
    }

    /**
     * @inheritdoc
     */
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        $config        = $container->get('config');
        $config        = $config['bsb_flysystem']['filesystems'];
        $serviceConfig = [];
        foreach ($config as $key => $filesystems) {
            $serviceConfig['factories'][$key] = FilesystemFactory::class;
            $serviceConfig['shared'][$key]    = isset($filesystems['shared']) ? (bool) $filesystems['shared'] : true;
        }

        return new FilesystemManager($container, $serviceConfig);
    }
}


text:
module Relish
  module ErrorMessages
    module_function

    def project_blank
      'Please specify a project.' + help
    end

    def handle_blank
      'Please specify a new handle.' + help
    end

    def version_blank
      'Please specify a version name.' + help
    end

    def unknown_command
      'Unknown command.' + help
    end

    def help(pad = true)
      (pad ? ' ' : '') + "Run 'relish help' for usage information."
    end
  end
end


text:
package com.greenpepper.confluence;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ConfluencePlugin {
    public static final String VERSION = "${pom.version}";

    private static Date versionDate;

    public static final Date versionDate() {
        String date = "${timestamp}";
        try {
            versionDate = new SimpleDateFormat("dd/MM/yyyy HH:mm").parse(date);
        } catch (ParseException e) {
            throw new RuntimeException("Unable to get version date", e);
        }
        return versionDate;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<screens xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://ofbiz.apache.org/Widget-Screen" xsi:schemaLocation="http://ofbiz.apache.org/Widget-Screen http://ofbiz.apache.org/dtds/widget-screen.xsd">

    <screen name="ListReports">

            <actions>
                <set field="titleProperty" value="AccountingArPageTitleListReports"/>
                <set field="tabButtonItem" value="viewReports"/>
                <set field="invoiceTypeId" value="PURCHASE_INVOICE"/>
                <set field="organizationPartyId" from-field="userPreferences.ORGANIZATION_PARTY" default-value="${defaultOrganizationPartyId}"/>


text:
package com.navercorp.pinpoint.bootstrap.util.spring;

import com.navercorp.pinpoint.common.util.logger.CommonLogger;
import com.navercorp.pinpoint.common.util.logger.StdoutCommonLoggerFactory;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;

/**
 * Utility class for working with Strings that have placeholder values in them. A placeholder takes the form
 * {@code ${name}}. Using {@code PropertyPlaceholderHelper} these placeholders can be substituted for
 * user-supplied values. <p> Values for substitution can be supplied using a {@link Properties} instance or
 * using a {@link PlaceholderResolver}.
 *
 * pinpoint copy : https://github.com/spring-projects/spring-framework/blob/master/spring-core/src/main/java/org/springframework/util/PropertyPlaceholderHelper.java
 *
 * @author Juergen Hoeller
 * @author Rob Harrop
 * @since 3.0
 */
public class PropertyPlaceholderHelper {

    private static final CommonLogger logger = StdoutCommonLoggerFactory.INSTANCE.getLogger(PropertyPlaceholderHelper.class.getName());

    private static final Map<String, String> wellKnownSimplePrefixes = new HashMap<>(4);

    static {
        wellKnownSimplePrefixes.put("}", "{");
        wellKnownSimplePrefixes.put("]", "[");
        wellKnownSimplePrefixes.put(")", "(");
    }

    private final String placeholderPrefix;

    private final String placeholderSuffix;

    private final String simplePrefix;

    private final String valueSeparator;

    private final boolean ignoreUnresolvablePlaceholders;

    /**
     * Creates a new {@code PropertyPlaceholderHelper} that uses the supplied prefix and suffix.
     * Unresolvable placeholders are ignored.
     * @param placeholderPrefix the prefix that denotes the start of a placeholder.
     * @param placeholderSuffix the suffix that denotes the end of a placeholder.
     */
    public PropertyPlaceholderHelper(String placeholderPrefix, String placeholderSuffix) {
        this(placeholderPrefix, placeholderSuffix, null, true);
    }

    /**
     * Creates a new {@code PropertyPlaceholderHelper} that uses the supplied prefix and suffix.
     * @param placeholderPrefix the prefix that denotes the start of a placeholder
     * @param placeholderSuffix the suffix that denotes the end of a placeholder
     * @param valueSeparator the separating character between the placeholder variable
     * and the associated default value, if any
     * @param ignoreUnresolvablePlaceholders indicates whether unresolvable placeholders should be ignored
     * ({@code true}) or cause an exception ({@code false}).
     */
    public PropertyPlaceholderHelper(String placeholderPrefix, String placeholderSuffix,
                                     String valueSeparator, boolean ignoreUnresolvablePlaceholders) {
        Objects.requireNonNull(placeholderPrefix, "placeholderPrefix");
        Objects.requireNonNull(placeholderSuffix, "placeholderSuffix");

        this.placeholderPrefix = placeholderPrefix;
        this.placeholderSuffix = placeholderSuffix;
        String simplePrefixForSuffix = wellKnownSimplePrefixes.get(this.placeholderSuffix);
        if (simplePrefixForSuffix != null && this.placeholderPrefix.endsWith(simplePrefixForSuffix)) {
            this.simplePrefix = simplePrefixForSuffix;
        }
        else {
            this.simplePrefix = this.placeholderPrefix;
        }
        this.valueSeparator = valueSeparator;
        this.ignoreUnresolvablePlaceholders = ignoreUnresolvablePlaceholders;
    }

    /**
     * Replaces all placeholders of format {@code ${name}} with the corresponding property
     * from the supplied {@link Properties}.
     * @param value the value containing the placeholders to be replaced.
     * @param properties the {@code Properties} to use for replacement.
     * @return the supplied value with placeholders replaced inline.
     */
    public String replacePlaceholders(String value, final Properties properties) {
        Objects.requireNonNull(value, "value");

        return replacePlaceholders(value, new PlaceholderResolver() {
            public String resolvePlaceholder(String placeholderName) {
                return properties.getProperty(placeholderName);
            }
        });
    }

    /**
     * Replaces all placeholders of format {@code ${name}} with the value returned from the supplied
     * {@link PlaceholderResolver}.
     * @param value the value containing the placeholders to be replaced.
     * @param placeholderResolver the {@code PlaceholderResolver} to use for replacement.
     * @return the supplied value with placeholders replaced inline.
     */
    public String replacePlaceholders(String value, PlaceholderResolver placeholderResolver) {
        Objects.requireNonNull(value, "value");

        return parseStringValue(value, placeholderResolver, new HashSet<String>());
    }

    protected String parseStringValue(
            String strVal, PlaceholderResolver placeholderResolver, Set<String> visitedPlaceholders) {

        StringBuilder buf = new StringBuilder(strVal);

        int startIndex = strVal.indexOf(this.placeholderPrefix);
        while (startIndex != -1) {
            int endIndex = findPlaceholderEndIndex(buf, startIndex);
            if (endIndex != -1) {
                String placeholder = buf.substring(startIndex + this.placeholderPrefix.length(), endIndex);
                String originalPlaceholder = placeholder;
                if (!visitedPlaceholders.add(originalPlaceholder)) {
                    throw new IllegalArgumentException(
                            "Circular placeholder reference '" + originalPlaceholder + "' in property definitions");
                }
                // Recursive invocation, parsing placeholders contained in the placeholder key.
                placeholder = parseStringValue(placeholder, placeholderResolver, visitedPlaceholders);
                // Now obtain the value for the fully resolved key...
                String propVal = placeholderResolver.resolvePlaceholder(placeholder);
                if (propVal == null && this.valueSeparator != null) {
                    int separatorIndex = placeholder.indexOf(this.valueSeparator);
                    if (separatorIndex != -1) {
                        String actualPlaceholder = placeholder.substring(0, separatorIndex);
                        String defaultValue = placeholder.substring(separatorIndex + this.valueSeparator.length());
                        propVal = placeholderResolver.resolvePlaceholder(actualPlaceholder);
                        if (propVal == null) {
                            propVal = defaultValue;
                        }
                    }
                }
                if (propVal != null) {
                    // Recursive invocation, parsing placeholders contained in the
                    // previously resolved placeholder value.
                    propVal = parseStringValue(propVal, placeholderResolver, visitedPlaceholders);
                    buf.replace(startIndex, endIndex + this.placeholderSuffix.length(), propVal);
                    if (logger.isTraceEnabled()) {
                        logger.trace("Resolved placeholder '" + placeholder + "'");
                    }
                    startIndex = buf.indexOf(this.placeholderPrefix, startIndex + propVal.length());
                }
                else if (this.ignoreUnresolvablePlaceholders) {
                    // Proceed with unprocessed value.
                    startIndex = buf.indexOf(this.placeholderPrefix, endIndex + this.placeholderSuffix.length());
                }
                else {
                    throw new IllegalArgumentException("Could not resolve placeholder '" +
                            placeholder + "'" + " in string value \"" + strVal + "\"");
                }
                visitedPlaceholders.remove(originalPlaceholder);
            }
            else {
                startIndex = -1;
            }
        }

        return buf.toString();
    }

    private int findPlaceholderEndIndex(CharSequence buf, int startIndex) {
        int index = startIndex + this.placeholderPrefix.length();
        int withinNestedPlaceholder = 0;
        while (index < buf.length()) {
//            if (StringUtils.substringMatch(buf, index, this.placeholderSuffix)) {
            // copy spring StringUtils
            if (substringMatch(buf, index, this.placeholderSuffix)) {
                if (withinNestedPlaceholder > 0) {
                    withinNestedPlaceholder--;
                    index = index + this.placeholderSuffix.length();
                }
                else {
                    return index;
                }
            }
            // copy spring StringUtils
//            else if (StringUtils.substringMatch(buf, index, this.simplePrefix)) {
            else if (substringMatch(buf, index, this.simplePrefix)) {
                withinNestedPlaceholder++;
                index = index + this.simplePrefix.length();
            }
            else {
                index++;
            }
        }
        return -1;
    }

    /**
     * Copy org.springframework.util.StringUtils
     * Test whether the given string matches the given substring
     * at the given index.
     * @param str the original string (or StringBuilder)
     * @param index the index in the original string to start matching against
     * @param substring the substring to match at the given index
     */
    public static boolean substringMatch(CharSequence str, int index, CharSequence substring) {
        for (int j = 0; j < substring.length(); j++) {
            int i = index + j;
            if (i >= str.length() || str.charAt(i) != substring.charAt(j)) {
                return false;
            }
        }
        return true;
    }

    /**
     * Strategy interface used to resolve replacement values for placeholders contained in Strings.
     * @see PropertyPlaceholderHelper
     */
    public interface PlaceholderResolver {

        /**
         * Resolves the supplied placeholder name into the replacement value.
         * @param placeholderName the name of the placeholder to resolve.
         * @return the replacement value or {@code null} if no replacement is to be made.
         */
        String resolvePlaceholder(String placeholderName);
    }

}


text:
package node

import (
	"context"
	"io"
	"log"

	pb "github.com/daniel-almeida/BerkeleyAlgorithm/pkg/proto"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

func NewFollower(leaderAddr string, id string, c *Clock) *Follower {
	return &Follower{
		leaderAddress: leaderAddr,
		id:            id,
		c:             c,
	}
}

type Follower struct {
	id            string
	leaderAddress string
	c             *Clock
}

func (f *Follower) Start() {
	conn, err := grpc.Dial(f.leaderAddress, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("fail to dial: %v", err)
	}
	defer conn.Close()

	client := pb.NewClockClient(conn)

	ctx, cancel := context.WithCancel(context.Background())

	stream, err := client.Sync(ctx)
	if err != nil {
		log.Fatalf("failed Sync: %v", err)
	}

	done := make(chan struct{})
	go func() {
		for {
			in, err := stream.Recv()
			if err == io.EOF {
				close(done)
				return
			}

			if err != nil {
				log.Fatalf("failed Recv: %v", err)
			}

			log.Printf("Received Message: %v\n", in)

			switch in.TheOneof.(type) {
			case *pb.SyncMessage_Request:
				err = stream.Send(&pb.SyncMessage{
					SyncRound: in.SyncRound,
					TheOneof: &pb.SyncMessage_Response{
						Response: &pb.ClockResponse{
							LeaderClock:   in.GetRequest().GetLeaderClock(),
							FollowerClock: int32(f.c.current),
						},
					},
				})
			case *pb.SyncMessage_Update:
				if in.SyncRound < int32(f.c.round) {
					log.Printf("sync round out of sync (current %v, last known %v", in.SyncRound, f.c.round)
					continue
				}

				offset := in.GetUpdate().Offset

				// Update local clock with offset received from leader
				log.Printf("applying offset %v to local clock %v", offset, f.c.current)
				f.c.current += int(offset)
			default:
				log.Printf("invalid message type: %v", in)
			}

			if err != nil {
				log.Printf("failed to send message: %s", err)
			}
		}
	}()

	err = stream.Send(&pb.SyncMessage{
		SenderId: "sender",
		TheOneof: &pb.SyncMessage_Register{},
	})
	if err != nil {
		log.Fatalf("failed to Register: %v", err)
	}

	<-done
	cancel()
}


text:
/**
 * @flow
 */
import DiodeRootQuery from "../query/DiodeRootQuery";
import { createContainer } from "./DiodeContainer";
import type { DiodeContainer, DiodeContainerSpec } from "./DiodeContainer";

export type DiodeRootContainer = DiodeContainer & {
  query: DiodeRootQuery
};

export function createRootContainer(
  Component: any,
  spec: DiodeContainerSpec
): DiodeRootContainer {
  const Container: DiodeContainer = createContainer(Component, spec);
  Container.query = new DiodeRootQuery(Container.query);
  return Container;
}


text:
'use strict';

export type ReactPropTypeLocations = 'prop' | 'context' | 'childContext';


text:
int realmain(int argc, char * const argv[]);
int main(int argc, char * const argv[])
{
  return realmain(argc, argv);
}


text:
package org.apereo.cas.support.saml.services;

import org.apereo.cas.util.junit.EnabledIfContinuousIntegration;
import org.apereo.cas.util.junit.EnabledIfPortOpen;

import org.junit.jupiter.api.Tag;
import org.springframework.test.context.TestPropertySource;

/**
 * The {@link SamlRegisteredServiceJpaPostgresTests} handles test cases for {@link SamlRegisteredService}.
 *
 * @author Misagh Moayyed
 * @since 6.0.0
 */
@TestPropertySource(locations = "classpath:samlpostgres.properties")
@EnabledIfPortOpen(port = 5432)
@EnabledIfContinuousIntegration
@Tag("Postgres")
public class SamlRegisteredServiceJpaPostgresTests extends SamlRegisteredServiceJpaTests {
}


text:
<?php

namespace Ise\Bread\ServiceManager;

use Zend\ServiceManager\AbstractPluginManager as ZendAbstractPluginManager;
use Zend\ServiceManager\Exception\InvalidServiceException;

abstract class AbstractPluginManager extends ZendAbstractPluginManager
{

    /**
     * @var string
     */
    protected $instanceOf;

    /**
     * {@inheritDoc}
     */
    public function validatePlugin($instance)
    {
        if ($instance instanceof $this->instanceOf) {
            return;
        }

        throw new InvalidServiceException(sprintf(
            '%s expects an instance of %s, %s given.',
            __CLASS__,
            $this->instanceOf,
            is_object($instance) ? get_class($instance) : gettype($instance)
        ));
    }
}


text:
#pragma once
#include <aws/elastictranscoder/ElasticTranscoder_EXPORTS.h>
#include <aws/elastictranscoder/model/TimeSpan.h>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace ElasticTranscoder
{
namespace Model
{
  /*

Settings for one clip in a composition. All jobs in a playlist must have the same clip settings.

  */
  class AWS_ELASTICTRANSCODER_API Clip
  {
  public:
    Clip();
    Clip(const Aws::Utils::Json::JsonValue& jsonValue);
    Clip& operator=(const Aws::Utils::Json::JsonValue& jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /*

Settings that determine when a clip begins and how long it lasts.

    */
    inline const TimeSpan& GetTimeSpan() const{ return m_timeSpan; }

    /*

Settings that determine when a clip begins and how long it lasts.

    */
    inline void SetTimeSpan(const TimeSpan& value) { m_timeSpanHasBeenSet = true; m_timeSpan = value; }

    /*

Settings that determine when a clip begins and how long it lasts.

    */
    inline void SetTimeSpan(TimeSpan&& value) { m_timeSpanHasBeenSet = true; m_timeSpan = value; }

    /*

Settings that determine when a clip begins and how long it lasts.

    */
    inline Clip& WithTimeSpan(const TimeSpan& value) { SetTimeSpan(value); return *this;}

    /*

Settings that determine when a clip begins and how long it lasts.

    */
    inline Clip& WithTimeSpan(TimeSpan&& value) { SetTimeSpan(value); return *this;}

  private:
    TimeSpan m_timeSpan;
    bool m_timeSpanHasBeenSet;
  };

} // namespace Model
} // namespace ElasticTranscoder
} // namespace Aws


text:
package org.aikodi.chameleon.plugin;

import org.aikodi.chameleon.workspace.View;

public abstract class ViewProcessorImpl extends ProcessorImpl<View,ViewProcessor> implements ViewProcessor {

	@Override
   public View view() {
		return container();
	}

	@Override
	public <T extends ViewProcessor> void setView(View view, Class<T> keyInterface) {
		setContainer(view, keyInterface);
	}

	@Override
	public abstract ViewProcessorImpl clone();

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Nova Hedwigia 25(1-2): 64 (1974)

#### Original name
Rhizophlyctis reynoldsii Dogma

### Remarks
null


text:
<!DOCTYPE html>

		<title>three.js webgl - collada - skinning</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

			three.js collada loader - skinning
			| Dancing Stormtrooper StrykerDoesAnimation is licensed under CC Attribution


text:
static struct ISO14443AAnticolState g_sAnticolState;

//*****************************************************************************
//
// ISO14443-A Anti-collision implementation, iterative depth-first tree search
// with optional backtracking.
//
// Usage:
// In ISO 14443 A there are two types of resting states for cards: IDLE and
// HALT.  A card enters IDLE state after powering up and performing all the
// necessary internal initialization.  The specification states that the card
// must be in IDLE state and ready to accept commands 5ms after being put into
// an unmodulated (e.g. no commands sent) field of the necessary strength.
//
// This pause is guaranteed by ISO14443APowerOn().
//
// During the selection and anti-collision phase cards will be in intermediary
// states (READY and READY*) but then always return to the original state
// (IDLE and HALT).
//
// After a card has been selected by any of the ISO14443ASelect* functions
// of this module it can be sent to the HALT state with ISO14443AHalt(),
// and must be sent to HALT (or deactivated in another way) before calling
// another ISO14443ASelect* function.
//
// Cards in the IDLE state react to both WUPA and REQA commands, cards in
// HALT state react only to WUPA commands.  Cards in HALT state can not
// return to IDLE state except through completely powering off the card
// and powering it up again, but the specification makes no claims as to how
// long the field must be off in order for the card to power off and this time
// will vary between card types.
//
// The ISO14443ASelectFirst/Next functions take one parameter (\e ucCmd) that
// must be \b ISO14443A_REQA or \b ISO14443A_WUPA to specify which wake up
// method to use.  ISO14443ASelect will always use WUPA.
//
// This leads to two main usage protocols:
//
A: Detect only new cards

//
 Keep field enabled at all times
//
 Use ISO14443ASelectFirst() with ISO14443A_REQA to find new cards that
//     entered the field.  Note: Ensure a pause of 5ms before each call to
//     ISO14443ASelectFirst(), e.g. with ISO14443APowerOn().
//
 If a card was found by SelectFirst, operate on that card and
//     deactivate it with ISO14443AHalt().  Note: all successful calls to any
//     ISO14443ASelect* function should always be paired with a call to
//     ISO14443AHalt() before the next call to any ISO14443ASelect* function.
//
 Repeatedly call ISO14443ASelectFirst() with \b ISO14443A_REQA in a
//      loop.  It will only find new cards and not relist the cards that were
//      already handled and halted
//

//  Pseudo C:

//  while(1) {
//      ISO14443APowerOn();
//      if(ISO14443ASelectFirst(ISO14443A_REQA, ...)) {
//
//          Do something with the card
//
//          ISO14443AHalt();
//      }
//
//      Do NOT power off the field
//  }
//

//
//
B: List all cards in the field

//
 Optionally disable the field or do other things, but enable the
//      field at least for 5ms (e.g. with ISO14443APowerOn())
//
 Call ISO14443ASelectFirst() with \b ISO14443A_WUPA to find the first
//      card, handle it, call ISO14443AHalt().  If at least one card was
//      found, use ISO14443ASelectNext() with \b ISO14443A_WUPA in a loop to
//      find more cards, handle them and call ISO14443AHalt() on them.
//
 You may disable the field and restart the procedure at any time with
//      ISO14443APowerOn() and ISO14443ASelectFirst().  It will always list
//      all cards in the field, not only new cards.
//

//  Pseudo C:

//  while(1) {
//      ISO14443APowerOn();
//      if(ISO14443ASelectFirst(ISO14443A_WUPA, ...)) {
//          do {
//
//              Do something with the card
//
//              ISO14443AHalt();
//          } while(ISO14443ASelectNext(ISO14443A_WUPA, ...));
//      }
//
//      You may power off the field here
//  }
//

//
// In both cases ISO14443ASelect() can be used at any time (after halting a
// previously selected card) to select a card by known UID.
//
//*****************************************************************************

//*****************************************************************************
//
// This structure stores the UID that we're currently working on.
//
//*****************************************************************************
struct ISO14443AAnticolState
{
    //
    // This field stores the raw responses that the anti-collision is actually
    // performed over, e.g. 3 times 5 bytes.  Same goes for \e ucCollisions.
    // Before returning the UID to the calling code this must be cleaned,
    // that is remove cascade tag and BCC.
    //
    unsigned char ucUID[15];
    //
    // Stores the collision positions discovered so far.  It is a bit field
    // with the same indices as \e ucUID.
    //
    unsigned char ucCollisions[15];
    //
    // Stores the number of bits that we've successfully received or
    // disambiguated.  Note: Real count for the \e ucUID field of this
    // structure, not NVB format.  For example 8 means 1 byte and 0 bits, 40
    // means full cascade level 1, 41 means full cascade level 1 plus 1 bit in
    // cascade level 2.
    //
    unsigned int iBitPos;
};

//*****************************************************************************
//
// Set up registers for ISO 14443 A 106Kbit/s operation.  This function must
// be called after initializing the TRF79x0 (for example with TRF79x0Init()
// or TRF79x0DirectCommand() with argument \b TRF79X0_SOFT_INIT_CMD) and before
// calling any of the other ISO14443A functions.
//
//*****************************************************************************
void
ISO14443ASetupRegisters(void)
{
    //
    // Set the ISO format to ISO1443A 106Kbps.
    //
    TRF79x0WriteRegister(TRF79X0_ISO_CONTROL_REG,
                         TRF79X0_ISO_CONTROL_14443A_106K);

    //
    // Set the TX pulse to 106ns (0x20 * 73.7ns).
    //
    TRF79x0WriteRegister(TRF79X0_TX_PULSE_LENGTH_CTRL_REG, 0x20);

    //
    // Set the RX No response wait time to 529us (0xe * 37.76us).
    //
    TRF79x0WriteRegister(TRF79X0_RX_NO_RESPONSE_WAIT_REG, 0x0e);

    //
    // Set the RX wait time to 66us (7 * 9.44us).
    //
    TRF79x0WriteRegister(TRF79X0_RX_WAIT_TIME_REG, 0x07);

    //
    // Set the SYSCLK to 6.78MHz and the Modulation Depth to OOK.
    //
    TRF79x0WriteRegister(TRF79X0_MODULATOR_CONTROL_REG,
                         (TRF79X0_MOD_CTRL_SYS_CLK_6_78MHZ |
                          TRF79X0_MOD_CTRL_MOD_OOK_100));

    //
    // Configure the Special Settings Register.
    //
    TRF79x0WriteRegister(TRF79X0_RX_SPECIAL_SETTINGS_REG,
       (TRF79x0ReadRegister(TRF79X0_RX_SPECIAL_SETTINGS_REG) & 0x0f) |
        TRF79X0_RX_SP_SET_M848);

    //
    // Configure the Test Settings Register.
    //
    TRF79x0WriteRegister(TRF79X0_TEST_SETTING1_REG, 0x20);

    //
    // Set the regulator voltage to be automatic.
    //
    TRF79x0WriteRegister(TRF79X0_REGULATOR_CONTROL_REG,
                         TRF79X0_REGULATOR_CTRL_AUTO_REG);
}

//*****************************************************************************
//
// Power on the field and wait for a time that is long enough to guarantee
// that all cards in the field will be initialized.
//
//*****************************************************************************
void
ISO14443APowerOn(void)
{
    unsigned char ucReg;

    //
    // Enable RF field and receiver.
    //
    ucReg = TRF79x0ReadRegister(TRF79X0_CHIP_STATUS_CTRL_REG);
    TRF79x0WriteRegister(TRF79X0_CHIP_STATUS_CTRL_REG,
                         ucReg | TRF79X0_STATUS_CTRL_RF_ON);

    //
    // Wait 5ms (as per ISO 14443-3 clause 5).
    //
    SysCtlDelay(((SysCtlClockGet() / 3) * 5) / 1000);
}

//*****************************************************************************
//
// Power off the field and wait for some time.
//
//*****************************************************************************
void
ISO14443APowerOff(void)
{
    unsigned char ucReg;

    //
    // Disable RF field and receiver.
    //
    ucReg = TRF79x0ReadRegister(TRF79X0_CHIP_STATUS_CTRL_REG);

    TRF79x0WriteRegister(TRF79X0_CHIP_STATUS_CTRL_REG,
                         ucReg & ~TRF79X0_STATUS_CTRL_RF_ON);

    //
    // Wait 5ms.
    //
    SysCtlDelay(((SysCtlClockGet() / 3) * 5) / 1000);
}

//*****************************************************************************
//
// Transmit a HLTA command that should HALT the currently selected card.  You
// should always call this function after a successful call to either
// ISO14443ASelect(), ISO14443ASelectFirst() or ISO14443ASelectNext() and
// before any other call to any of those functions.
//
//*****************************************************************************
void
ISO14443AHalt(void)
{
    //
    // HLTA command.
    //
    const unsigned char pucHLTA[2] = {0x50, 0x00};

    TRF79x0Transceive(pucHLTA, sizeof(pucHLTA), 0, NULL, NULL, NULL,
                      TRF79X0_TRANSCEIVE_CRC);
}

//*****************************************************************************
//
// Transceive ISO 14443-A REQA type command.
//
// \param ucCmd is the command, either \b ISO14443A_REQA or \b ISO14443A_WUPA
// \param piATQA is a pointer to an integer to store the received ATQA and
//  will be set to -1 if a collision occurred.
//
// \return true if at least one card responded that is capable of bit-frame
//  anti-collision (e.g. no collision and one of the lower 5 bits of response
//  set, or collision within the first 5 bits, or collision not in the first
//  5 bits but at least one of the first 5 bits is a 1-bit) and false
// otherwise.
//
// \note User code usually does not need to call this function since it is
// implicitly called in ISO14443ASelect(), ISO14443ASelectFirst() or
// ISO14443ASelectNext().
//
//*****************************************************************************
int
ISO14443AREQA(unsigned char ucCmd, int *piATQA)
{
    unsigned char pucResponse[2];
    unsigned int uiRxSize;
    int iColPos;

    uiRxSize = sizeof(pucResponse);

    //
    // Transmit WUPA/REQA, receive ATQA.
    //
    TRF79x0Transceive(&ucCmd, 0, 7, pucResponse, &uiRxSize, 0,
                      TRF79X0_TRANSCEIVE_NO_CRC);

    if(uiRxSize == 2)
    {
        //
        // Valid ATQA received, return it as an integer.  Was transmitted
        // LSByte first.
        //
        if(piATQA != NULL)
        {
            *piATQA = pucResponse[0] | (pucResponse[1] << 8);
        }

        //
        // Return true if one of the lower 5 bits was set.
        //
        return((pucResponse[0] & 0x1F) != 0);
    }
    else
    {
        //
        // No valid ATQA received.
        //
        if(piATQA != NULL)
        {
            *piATQA = -1;
        }

        if(uiRxSize == 0)
        {
            //
            // No response at all -> no card with bit-frame anti-collision.
            //
            return(0);
        }
        else
        {
            //
            // Probably some collision.
            //
            iColPos = TRF79x0GetCollisionPosition();

            if(iColPos > 5)
            {
                //
                // Collision not within the first 5 bits, return true if one of
                // the lower 5 bits was set.
                //
                return((pucResponse[0] & 0x1F) != 0);
            }
            else if(iColPos > 0 && iColPos <= 5)
            {
                //
                // Collision within the first 5 bits, so at least one of them
                // was 1.
                //
                return(1);
            }
            else
            {
                //
                // No collision, but only 1 byte sent?  That card's not right.
                //
                return(0);
            }
        }
    }
}

//*****************************************************************************
//
// Find one card through the anti-collision procedure with given \e psState.
//
// \param psState is the anti-collision state to start from.  If this state
// already specifies a full UID then it will be selected, otherwise
// anti-collision will be tried to complete that starting state, with no
// backtracking.
// \param pucUID is an output buffer to write the selected UID and may be
// \b NULL in which case the UID will not be returned.
// \param puiUIDSize inputs the available space in bytes in \e pucUID and
// returns with the actual length that has been stored there.
// \param pucSAK is an output parameter that stores the received SAK value.
// May be \b NULL in which case the SAK will not be returned
//
// This is a depth first search in a binary tree over the UID space.  On each
// attempt we can learn up to 4 bytes of the UID of the card(s) currently in
// the field.  If the UIDs of two cards differ we will learn that too and get
// the collision position: the position of the bit where the UID of at least
// two cards differs.  We will mark this position in the appropriate field in
// the structure ISO14443AnticolState and then branch first in the direction of
// 0 and increase iBitPos to include this bit.
//
// \return This function returns 1 if a card was selected and 0 otherwise.
//
//*****************************************************************************
static int
ISO14443ADoAnticol(struct ISO14443AAnticolState *psState, unsigned char *pucUID,
                   unsigned int *puiUIDSize, unsigned char *pucSAK)
{
    int iCascadeLevel, iPos;
    unsigned char pucCmd[7], pucResponse[5];
    unsigned int uiRxSize;
    int iIdx, iMaskPosition, iCollPosition, iValidBits, iMaxLength, iNVB;

    iCascadeLevel = 1;

    while(iCascadeLevel < 4)
    {
        //
        // Already known bits for this cascade level, e.g. not including
        // the possible 5 bytes * 8 bits/byte for the lower levels.
        //
        iValidBits = psState->iBitPos - (iCascadeLevel - 1) * 5 * 8;

        //
        // Clamp to a full cascade level.
        //
        if(iValidBits > 40)
        {
            iValidBits = 40;
        }

        //
        // NVB format: bytes.
        //
        iNVB = (iValidBits / 8) << 4;

        //
        // NVB format: bits.
        //
        iNVB |= (iValidBits % 8);

        //
        // Also count the command byte and the NVB byte itself.
        //
        iNVB += 0x20;

        //
        // Prepare command for this level: ANTICOLLISION if less than a full 5
        // bytes for the current cascade level, SELECT otherwise.
        //
        switch (iCascadeLevel)
        {
            case 1:
            {
                pucCmd[0] = 0x93;
                break;
            }
            case 2:
            {
                pucCmd[0] = 0x95;
                break;
            }
            case 3:
            {
                pucCmd[0] = 0x97;
                break;
            }
            default:
            {
                break;
            }
        }

        pucCmd[1] = iNVB;

        //
        // Copy over known bytes (number of bits for this level divided by 8,
        // rounded up).
        //
        memcpy(pucCmd + 2, psState->ucUID + (iCascadeLevel - 1) * 5,
               (iValidBits + 7) / 8);

        //
        // Enforce a small delay of ~600us before each anti-collision frame.
        //
        SysCtlDelay(((SysCtlClockGet() / 3) * 6) / 10000);

        //
        // Maximal expected response length.
        //
        uiRxSize = 5;

        if(iNVB != 0x70)
        {
            //
            // Anti-collision command.
            //
            TRF79x0Transceive(pucCmd, pucCmd[1] >> 4, pucCmd[1] & 0xf,
                              pucResponse, &uiRxSize, NULL,
                              TRF79X0_TRANSCEIVE_NO_CRC);

            if(uiRxSize == 0)
            {
                return(0);
            }

            iCollPosition = TRF79x0GetCollisionPosition();

            if(iCollPosition < 0)
            {
                //
                // No collision occurred, add full response data to known bits.
                //
                iCollPosition = 40;
            }
            else
            {
                //
                // Collision occurred, only add the part that was received
                // correctly.
                //
                // TF7960 Collision position register is in NVB format,
                // convert to straight bit position.  This will be the number
                // of bits that were the same in all responding cards.
                //
                iCollPosition -= 0x20;
                iCollPosition = ((iCollPosition >> 4) * 8) + (iCollPosition & 0xf);
            }

            //
            // Bounds check the results and return 0 if it was invalid.
            //
            if(iCollPosition < 0 || iCollPosition > 40)
            {
                return(0);
            }

            //
            // Mask out the invalid bits in the last byte of the response, if
            // any.
            //
            // Graphic:
            // UID bytes:  | first  || second || third  || fourth || fifth  |
            //             | iValidBits |
            //             |       iCollPosition       |
            // In this graphic the first byte is fully valid.  The second byte
            // was sent partially invalid, but should have been masked on a
            // previous run.  The third byte is received partially invalid and
            // needs to be masked.  Response will only contain the second and
            // third byte (although both are received properly byte-aligned).
            //
            //
            // This many bits in response are valid or at least compatible
            // with the UID.
            //
            iMaskPosition = iCollPosition - (iValidBits / 8) * 8;

            if(iMaskPosition % 8)
            {
                //
                // Need to construct a mask for iMaskPosition%8 bits and
                // apply it at iMaskPosition/8.
                //
                pucResponse[iMaskPosition / 8] &= ~((~0) << (iMaskPosition % 8));
            }

            //
            // Merge in up to iMaskPosition/8 (rounded up) byte into response
            // at index iBitPos/8 (rounded down).
            //
            for(iIdx = 0; iIdx < (iMaskPosition + 7) / 8; iIdx++)
            {
                psState->ucUID[(psState->iBitPos / 8) + iIdx] |=
                    pucResponse[iIdx];
            }

            psState->iBitPos += iCollPosition - iValidBits;

            //
            // Only within this cascade level:
            //
            if(psState->iBitPos % 40 != 0)
            {
                //
                // Mark backtracking point.
                //
                psState->ucCollisions[psState->iBitPos / 8] |=
                    1 << (psState->iBitPos % 8);

                //
                // Walk into the 0 direction.
                //
                psState->iBitPos += 1;
            }
        }
        else
        {
            //
            // Select command.
            //
            TRF79x0Transceive(pucCmd, pucCmd[1] >> 4, pucCmd[1] & 0xf,
                              pucResponse, &uiRxSize, NULL,
                              TRF79X0_TRANSCEIVE_CRC);

            if(uiRxSize == 1)
            {
                //
                // SAK received.
                //
                if(pucResponse[0] & 0x04)
                {
                    //
                    // UID not complete, increase cascade level.
                    //
                    iCascadeLevel++;

                    if(iCascadeLevel > 3)
                    {
                        break;
                    }
                }
                else
                {
                    //
                    // UID complete, return.
                    //
                    break;
                }
            }
            else
            {
                //
                // Some error, card not selected.
                //
                memset(psState->ucUID, 0, sizeof(psState->ucUID));
                psState->iBitPos = 0;
                break;
            }
        }
    }

    //
    // Some error, not fully selected.
    //
    if(((psState->iBitPos % 40) != 0) || (psState->iBitPos == 0))
    {
        return(0);
    }

    //
    // Fully selected a card.  pucResponse[0] should be from the last
    // transaction, of a SELECT command, and therefore contain the SAK
    //
    if(pucSAK != NULL)
    {
        *pucSAK = pucResponse[0];
    }

    //
    // If requested, return the UID, without cascade tag and BCC.
    //
    if(pucUID != NULL && puiUIDSize != NULL)
    {
        iMaxLength = *puiUIDSize;
        iPos = 0;
        *puiUIDSize = 0;

        //
        // From the 5 bytes in each cascade level the 3 middle bytes need to be
        // copied for each level except for the last, where the first 4 bytes
        // need to be copied.
        //
        for(iPos = 0; iPos < psState->iBitPos / 8; iPos += 5)
        {
            if(iPos + 5 < psState->iBitPos / 8)
            {
                //
                // Not the last cascade level.
                //
                if(*puiUIDSize + 3 > iMaxLength)
                {
                    //
                    // Not enough space
                    //
                    *puiUIDSize = 0;
                    break;
                }

                //
                // Copy 3 bytes (e.g. don't copy cascade tag and BCC).
                //
                memcpy(pucUID + *puiUIDSize, psState->ucUID + iPos + 1, 3);

                *puiUIDSize += 3;
            }
            else
            {
                //
                // Last cascade level.
                //
                if(*puiUIDSize + 4 > iMaxLength)
                {
                    //
                    // Not enough space.
                    //
                    *puiUIDSize = 0;

                    break;
                }

                //
                // Copy 4 bytes (e.g. don't copy BCC).
                //
                memcpy(pucUID + *puiUIDSize, psState->ucUID + iPos, 4);

                *puiUIDSize += 4;
            }
        }
    }
    return(1);
}

//*****************************************************************************
//
// Selects the first (or only) card and returns its UID, UID length and
// SAK bytes.
//
// \param ucCmd must be ISO14443A_REQA or ISO14443A_WUPA.
// \param pucUID will store UID of the card that was selected.  May be NULL
// in which case the UID will not be returned.
// \param puiUIDSize must be initialized with the length of the buffer in
// \e pucUID and will return the number of bytes actually stored.
// \param pucSAK will store the SAK byte of the card that was selected and may
// be NULL in which case the SAK byte will not be returned.
//
// The function call initializes and updates a static internal state that
// marks the position in the anti-collision procedure.  ISO14443ASelectNext()
// can be used to continue with the anti-collision from that starting point.
//
// \note You should call ISO14443AHalt() if this function returned true and
// you are done operating on the card.
//
// \return Function returns 1 if a card was selected, 0 otherwise.
//
//*****************************************************************************
int
ISO14443ASelectFirst(unsigned char ucCmd, unsigned char *pucUID,
                     unsigned int *puiUIDSize, unsigned char *pucSAK)
{
    //
    // Initialize/clear static state.
    //
    memset(&g_sAnticolState, 0, sizeof(g_sAnticolState));

    //
    // Wake up all or only new tags.
    //
    if(ISO14443AREQA(ucCmd, NULL) == 0)
    {
        //
        // No tag with support for bit frame anti-collision found.
        //
        return(0);
    }

    return(ISO14443ADoAnticol(&g_sAnticolState, pucUID, puiUIDSize, pucSAK));
}

//*****************************************************************************
//
// Selects the next card and returns its UID, UID length and SAK bytes.
//
// \param ucCmd must be ISO14443A_REQA or ISO14443A_WUPA.
// \param UID will store UID of the card that was selected and may be NULL
// in which case the UID will not be returned.
// \param puiUIDSize must be initialized with the length of the buffer in
// \e UID and will return the number of bytes actually stored.
// \param pucSAK will store the SAK byte of the card that was selected and may
// be NULL in which case the SAK byte will not be returned.
//
// Uses the state that was initialized by ISO14443SelectFirst() and tries
// to find more cards in the field.
//
// \note You should call ISO14443AHalt() if this function returned true and
// you are done operating on the card.
//
// \return This function returns 1 if a card was selected and 0 otherwise.
//
//*****************************************************************************
int
ISO14443ASelectNext(unsigned char ucCmd, unsigned char *pucUID,
                    unsigned int *puiUIDSize, unsigned char *pucSAK)
{
    //
    // Backtrack through static state: starting at iBitPos and going reverse,
    // find the first bit that's set in collisions, walk into the 1 direction,
    // clear the collision indicator and set iBitPos to that position.
    //
    while(--g_sAnticolState.iBitPos > 0)
    {
        //
        // Clear UID bit at this position to clean the state.
        //
        g_sAnticolState.ucUID[g_sAnticolState.iBitPos / 8] &=
            ~(1 << (g_sAnticolState.iBitPos % 8));

        if(g_sAnticolState.ucCollisions[g_sAnticolState.iBitPos / 8] &
           (1 << (g_sAnticolState.iBitPos % 8)))
        {
            //
            // This is our new starting point, set UID bit to walk into the
            // 1 direction.
            //
            g_sAnticolState.ucUID[g_sAnticolState.iBitPos / 8] |=
                1 << (g_sAnticolState.iBitPos % 8);

            //
            // Remove backtracking marker.
            //
            g_sAnticolState.ucCollisions[g_sAnticolState.iBitPos / 8] &=
                ~(1 << (g_sAnticolState.iBitPos % 8));

            //
            // Increment bit position to account for the bit that we just
            // added, then break loop to perform anti-collision with the new
            // partial UID.
            //
            g_sAnticolState.iBitPos++;

            break;
        }

        //
        // Not a backtracking point, go further back.
        //
    }

    //
    // No further backtracking points -> no other cards.
    //
    if(g_sAnticolState.iBitPos <= 0)
    {
        return(0);
    }

    //
    // Wake up all or only new tags.
    //
    if(!ISO14443AREQA(ucCmd, NULL))
    {
        //
        // No tag with support for bit frame anti-collision found.
        //
        return(0);
    }

    return(ISO14443ADoAnticol(&g_sAnticolState, pucUID, puiUIDSize, pucSAK));
}

//*****************************************************************************
//
// Selects a card with given UID and return its SAK byte.
//
// \param pucUID must point to the UID of the card that should be selected and
// may not be NULL.
// \param uiUIDSize must be the length in bytes of the UID stored in \e pucUID.
// \param pucSAK will store the SAK byte of the card that was selected.  May be
// \b NULL in which case the SAK byte will not be returned.
//
// \note You should call ISO14443AHalt() if this function returned true and
// you are done operating on the card.
//
// \return This function will return 1 if a card was selected and 0 otherwise.
//
//*****************************************************************************
int
ISO14443ASelect(unsigned char const *pucUID, unsigned int uiUIDSize,
                unsigned char *pucSAK)
{
    int iIdx, iPos;
    struct ISO14443AAnticolState sState;

    //
    // Check if the given UID size is supported.
    //
    if((uiUIDSize != 4) && (uiUIDSize != 7) && (uiUIDSize != 10))
    {
        return(0);
    }

    //
    // Prepare a state for the given UID.
    //
    sState.iBitPos = 0;

    for(iPos = 0; iPos < uiUIDSize;)
    {
        //
        // Check if this is the final cascade level.
        //
        if(iPos + 4 < uiUIDSize)
        {
            //
            // If this was not the final cascade level then add a cascade tag.
            //
            sState.ucUID[sState.iBitPos / 8] = 0x88;

            //
            // Copy three bytes of UID.
            //
            memcpy(sState.ucUID + (sState.iBitPos / 8) + 1, pucUID + iPos, 3);

            //
            // Increment position in UID.
            //
            iPos += 3;
        }
        else
        {
            //
            // For the final cascade level just copy four bytes of UID.
            //
            memcpy(sState.ucUID + (sState.iBitPos / 8), pucUID + iPos, 4);

            //
            // Increment position in UID.
            //
            iPos += 4;
        }

        //
        // Calculate BCC.
        //
        sState.ucUID[sState.iBitPos / 8 + 4] = 0;

        for(iIdx = 0; iIdx < 4; iIdx++)
        {
            sState.ucUID[sState.iBitPos / 8 + 4] ^=
                sState.ucUID[sState.iBitPos / 8 + iIdx];
        }

        //
        // Increment position in state.
        //
        sState.iBitPos += 40;
    }

    //
    // Always wake up all cards.
    //
    if(!ISO14443AREQA(ISO14443A_WUPA, NULL))
    {
        //
        // No tag with support for bit frame anti-collision found.
        //
        return(0);
    }

    return(ISO14443ADoAnticol(&sState, NULL, NULL, pucSAK));
}

//*****************************************************************************
//
// Helper functions for ISO 14443-A frames to be sent or received in Direct
// Mode.
//
//*****************************************************************************

//*****************************************************************************
//
// Calculates odd parity for one byte.
//
//*****************************************************************************
static unsigned char
ParityByte(unsigned char ucByte)
{
    ucByte ^= ucByte >> 1;
    ucByte ^= ucByte >> 1;
    ucByte ^= ucByte >> 1;
    ucByte ^= ucByte >> 1;
    ucByte ^= ucByte >> 1;
    ucByte ^= ucByte >> 1;
    ucByte ^= ucByte >> 1;
    return((ucByte & 1) ^ 1);
}

//*****************************************************************************
//
// Checks that data has correct (odd) parity
//
// \param pusData is the data buffer to check and must store 16 bits per one
// logical byte: the lower 8 bits are the data byte, the LSBit in the upper
// byte is the parity.
// \param lSize is the number of logical bytes/16 bit words in \e pusData.
//
// \return This function returns 1 if the parity was correct and 0 otherwise.
//
//*****************************************************************************
int
ISO14443ACheckParity(const unsigned short * const pusData, const long lSize)
{
    int iFailed, iIdx;

    iFailed = 0;

    for(iIdx = 0; iIdx < lSize; iIdx++)
    {
        iFailed |= (pusData[iIdx] >> 8) ^ ParityByte(pusData[iIdx] & 0xff);
    }

    return(!iFailed);
}

//*****************************************************************************
//
// Sets data to correct (odd) parity
//
// \param pusData is the data buffer to update and must store 16 bits per one
// logical byte: the lower 8 bits are the data byte, the LSBit in the upper
// byte is the parity.
// \param lSize is the number of logical bytes/16 bit words in \e data
//
//*****************************************************************************
void
ISO14443ACalculateParity(unsigned short * const pusData, const long lSize)
{
    int iIdx;

    for(iIdx = 0; iIdx < lSize; iIdx++)
    {
        pusData[iIdx] = (pusData[iIdx] & 0xff) |
                        (ParityByte(pusData[iIdx] & 0xff) << 8);
    }
}

//*****************************************************************************
//
// Calculate CRC-A and return it.
//
//*****************************************************************************
static unsigned short
CalculateCRC(const unsigned short * const pusData, const long lSize)
{
    unsigned short usCrc;
    int iIdx, iBit;
    unsigned char ucByte, ucBit;

    usCrc = 0x6363;

    for(iIdx = 0; iIdx < lSize; iIdx++)
    {
        ucByte = pusData[iIdx] & 0xff;

        for(iBit = 0; iBit < 8; iBit++)
        {
            ucBit = (usCrc ^ ucByte) & 1;

            ucByte >>= 1;
            usCrc >>= 1;

            if(ucBit)
            {
                usCrc ^= 0x8408;
            }
        }
    }
    return(usCrc);
}

//*****************************************************************************
//
// Check that data has correct CRC in last two bytes.
//
// \param pusData is the data buffer to check and must store 16 bits per one
// logical byte: the lower 8 bits are the data byte, the LSBit in the upper
// byte is the parity.
// \param lSize is the number of logical bytes/16 bit words in \e pusData.
// Must be at least 2, since the CRC consists of two bytes.
//
// \return This function returns 1 if the CRC was correct and 0 otherwise.
//
//*****************************************************************************
int
ISO14443ACheckCRC(const unsigned short * const pusData, const long lSize)
{
    unsigned short usCrc;

    if(lSize < 2)
    {
        return(0);
    }

    usCrc = CalculateCRC(pusData, lSize - 2);

    if(((usCrc & 0xff) == (pusData[lSize - 2] & 0xff)) &&
       (((usCrc >> 8) & 0xff) == (pusData[lSize - 1] & 0xff)))
    {
        return(1);
    }
    return(0);
}

//*****************************************************************************
//
// Appends correct CRC to the data
//
// \param pusData is the data buffer to update and must store 16 bits per one
// logical byte: the lower 8 bits are the data byte, the LSBit in the upper
// byte is the parity.
// \param lSize is the number of logical bytes/16 bit words in \e pusData.  The
// buffer in \e pusData must have room for an additional two logical bytes.
//
// \return This function returns the new length to correctly append the CRC.
//
//*****************************************************************************
long
ISO14443ACalculateCRC(unsigned short * const pusData, const long lSize)
{
    unsigned short usCrc;

    usCrc = CalculateCRC(pusData, lSize);

    pusData[lSize] = usCrc & 0xff;
    pusData[lSize + 1] = (usCrc >> 8) & 0xff;

    ISO14443ACalculateParity(pusData + lSize, 2);

    return(lSize + 2);
}


text:
var config = require('./config-dev');
var winston = require('winston');
var mongoose = require('mongoose');
var server = require('./server');
var schedule = require('./etc/schedule');

console.log("Starting logger...");
winston.add(winston.transports.File, {
	filename: config.logger.api,
	level: config.logger.level,
	maxsize: config.logger.maxsize,
	maxFiles: config.logger.maxFiles,
	json: false
});
winston.handleExceptions(new winston.transports.File({
	filename: config.logger.exception,
	maxsize: config.logger.maxsize,
	maxFiles: config.logger.maxFiles,
	json: false
}));
console.log("logger started.");

console.log("Connecting to MongoDB...");
mongoose.connect(config.db.mongodb, function(err) {
	if (err) {
		console.log("Cannot connect to DB: " + config.db.mongodb);
		throw err;
	}
});
console.log("successfully connected to DB.");

console.log("Starting web server...");
server.start();
winston.info("Server started.");

console.log("Successfully started web server. Waiting for incoming connections...");


text:
Copyright 2016 Mentor Graphics Corporation
All Rights Reserved Worldwide

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.

# Procedural Specification Interface

The procedural specification interface (PSI) enables a Portable Stimulus Model to be
declared using a procedural programming language. There are two core elements to the
procedural specification interface:
* A C++ class library with constructs that enable creation of a PSS model
* A C++ API, targeted at tool vendors, that allows specification and introspection

This collection of source files provides the following:
* Header files for the class library and C++ API. The constructs in these header
  files are intended to be part of the standard.
* A reference implementation of the class library and C++ API. The constructs
  in these files are not intended to be part of the standard.
* Examples and tests of the class library and API.
* Utilities built on top of the APIs. These utilities are not intended to
  be part of the standard.

# Directory Structure

* contrib - The contrib directory contains an implementation of the class library,
            C++ API, and utilities used by the tests
* doc     - The doc directory contains scripts used for generating documentation
* include - The include directory contains header files with the public interface
            to the class library and C++ API.
* schema  - The schema directory contains an XML schema used by the tests to
            validate the procedurally-constructed Portable Stimulus Specification.
* tests   - The tests directory contains test code, scripts, and reference files
            for testing the public header files and contributed implementation.

# Tests
Please see the README.md file, in the tests subdirectory, for more information
on how to run the tests.

# Tools
The following tools are used:
* A C++11-compliant GCC. GCC 5.4.0 was used during development of this code, though other compiler versions may work as well.
* GNU Make. GNU Make 4.2.1 was used during development of this code, though other versions may also work.
* Apache ANT. Apache ANT is used during the (optional) generation of API documentation.
* Doxygen. Doxygen is used during the (optional) generation of API documentation.


text:
CT_BEGIN_DECLS

float ct_parse_float(char *src, float err);
int ct_parse_int(char *src, int err);
uint32_t ct_parse_hex32(char *src, uint32_t err);

CT_END_DECLS


text:
<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Password Reminder Language Lines
    |--------------------------------------------------------------------------
    |
    | The following language lines are the default lines which match reasons
    | that are given by the password broker for a password update attempt
    | has failed, such as for an invalid token or invalid new password.
    |
    */

    'password' => 'Les mots de passe doivent avoir au moins six caractères et doivent être identiques.',
    'reset'    => 'Votre mot de passe a été réinitialisé !',
    'sent'     => 'Nous vous avons envoyé par courriel le lien de réinitialisation du mot de passe !',
    'token'    => "Ce jeton de réinitialisation du mot de passe n'est pas valide.",
    'user'     => "Aucun utilisateur n'a été trouvé avec cette adresse e-mail.",

];


text:
<?php
/**
 * Smarty plugin
 * @package Smarty
 * @subpackage plugins
 */

/**
 * Smarty {html_image} function plugin
 *
 * Type:     function

 * Name:     html_image

 * Date:     Feb 24, 2003

 * Purpose:  format HTML tags for the image

 * Input:

 *         - file = file (and path) of image (required)
 *         - height = image height (optional, default actual height)
 *         - width = image width (optional, default actual width)
 *         - basedir = base directory for absolute paths, default
 *                     is environment variable DOCUMENT_ROOT
 *         - path_prefix = prefix for path output (optional, default empty)
 *
 * Examples: {html_image file="/images/masthead.gif"}
 * Output:
 * @link http://smarty.php.net/manual/en/language.function.html.image.php {html_image}
 *      (Smarty online manual)
 * @author   Monte Ohrt <monte at ohrt dot com>
 * @author credits to Duda <duda@big.hu> - wrote first image function
 *           in repository, helped with lots of functionality
 * @version  1.0
 * @param array
 * @param Smarty
 * @return string
 * @uses smarty_function_escape_special_chars()
 */
function smarty_function_html_image($params, &$smarty)
{
	require_once $smarty->_get_plugin_filepath('shared','escape_special_chars');

	$alt = '';
	$file = '';
	$height = '';
	$width = '';
	$extra = '';
	$prefix = '';
	$suffix = '';
	$path_prefix = '';
	$server_vars = ($smarty->request_use_auto_globals) ? $_SERVER : $GLOBALS['HTTP_SERVER_VARS'];
	$basedir = isset($server_vars['DOCUMENT_ROOT']) ? $server_vars['DOCUMENT_ROOT'] : '';
	foreach($params as $_key => $_val) {
		switch($_key) {
			case 'file':
			case 'height':
			case 'width':
			case 'dpi':
			case 'path_prefix':
			case 'basedir':
				$$_key = $_val;
				break;

			case 'alt':
				if(!is_array($_val)) {
					$$_key = smarty_function_escape_special_chars($_val);
				} else {
					$smarty->trigger_error("html_image: extra attribute '$_key' cannot be an array", E_USER_NOTICE);
				}
				break;

			case 'link':
			case 'href':
				$prefix = '';
				$suffix = '';
				break;

			default:
				if(!is_array($_val)) {
					$extra .= ' '.$_key.'="'.smarty_function_escape_special_chars($_val).'"';
				} else {
					$smarty->trigger_error("html_image: extra attribute '$_key' cannot be an array", E_USER_NOTICE);
				}
				break;
		}
	}

	if (empty($file)) {
		$smarty->trigger_error("html_image: missing 'file' parameter", E_USER_NOTICE);
		return;
	}

	if (substr($file,0,1) == '/') {
		$_image_path = $basedir . $file;
	} else {
		$_image_path = $file;
	}

	if(!isset($params['width']) || !isset($params['height'])) {
		if(!$_image_data = @getimagesize($_image_path)) {
			if(!file_exists($_image_path)) {
				$smarty->trigger_error("html_image: unable to find '$_image_path'", E_USER_NOTICE);
				return;
			} else if(!is_readable($_image_path)) {
				$smarty->trigger_error("html_image: unable to read '$_image_path'", E_USER_NOTICE);
				return;
			} else {
				$smarty->trigger_error("html_image: '$_image_path' is not a valid image file", E_USER_NOTICE);
				return;
			}
		}
		if ($smarty->security &&
		($_params = array('resource_type' => 'file', 'resource_name' => $_image_path)) &&
		(require_once(SMARTY_CORE_DIR . 'core.is_secure.php')) &&
		(!smarty_core_is_secure($_params, $smarty)) ) {
			$smarty->trigger_error("html_image: (secure) '$_image_path' not in secure directory", E_USER_NOTICE);
		}

		if(!isset($params['width'])) {
			$width = $_image_data[0];
		}
		if(!isset($params['height'])) {
			$height = $_image_data[1];
		}

	}

	if(isset($params['dpi'])) {
		if(strstr($server_vars['HTTP_USER_AGENT'], 'Mac')) {
			$dpi_default = 72;
		} else {
			$dpi_default = 96;
		}
		$_resize = $dpi_default/$params['dpi'];
		$width = round($width * $_resize);
		$height = round($height * $_resize);
	}

	return $prefix . '' . $suffix;
}

/* vim: set expandtab: */

?>


text:
package com.datastax.oss.driver.internal.core.channel;

import static com.datastax.oss.driver.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import com.datastax.oss.driver.api.core.CqlIdentifier;
import com.datastax.oss.driver.api.core.DefaultProtocolVersion;
import com.datastax.oss.driver.api.core.connection.BusyConnectionException;
import com.datastax.oss.driver.api.core.connection.ClosedConnectionException;
import com.datastax.oss.driver.internal.core.protocol.FrameDecodingException;
import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableList;
import com.datastax.oss.protocol.internal.Frame;
import com.datastax.oss.protocol.internal.ProtocolConstants;
import com.datastax.oss.protocol.internal.request.Query;
import com.datastax.oss.protocol.internal.response.Error;
import com.datastax.oss.protocol.internal.response.event.StatusChangeEvent;
import com.datastax.oss.protocol.internal.response.result.SetKeyspace;
import com.datastax.oss.protocol.internal.response.result.Void;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelPromise;
import java.net.InetSocketAddress;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

public class InFlightHandlerTest extends ChannelHandlerTestBase {
  private static final Query QUERY = new Query("select * from foo");
  private static final int SET_KEYSPACE_TIMEOUT_MILLIS = 100;
  private static final int MAX_ORPHAN_IDS = 10;

  @Mock private StreamIdGenerator streamIds;

  @Before
  @Override
  public void setup() {
    super.setup();
    MockitoAnnotations.initMocks(this);
    when(streamIds.preAcquire()).thenReturn(true);
  }

  @Test
  public void should_fail_if_connection_busy() throws Throwable {
    // Given
    addToPipeline();
    when(streamIds.acquire()).thenReturn(-1);

    // When
    ChannelFuture writeFuture =
        channel.writeAndFlush(
            new DriverChannel.RequestMessage(
                QUERY, false, Frame.NO_PAYLOAD, new MockResponseCallback()));

    // Then
    assertThat(writeFuture)
        .isFailed(e -> assertThat(e).isInstanceOf(BusyConnectionException.class));
  }

  @Test
  public void should_assign_streamid_and_send_frame() {
    // Given
    addToPipeline();
    when(streamIds.acquire()).thenReturn(42);
    MockResponseCallback responseCallback = new MockResponseCallback();

    // When
    ChannelFuture writeFuture =
        channel.writeAndFlush(
            new DriverChannel.RequestMessage(QUERY, false, Frame.NO_PAYLOAD, responseCallback));

    // Then
    assertThat(writeFuture).isSuccess();
    verify(streamIds).acquire();

    Frame frame = readOutboundFrame();
    assertThat(frame.streamId).isEqualTo(42);
    assertThat(frame.message).isEqualTo(QUERY);
  }

  @Test
  public void should_notify_callback_of_response() {
    // Given
    addToPipeline();
    when(streamIds.acquire()).thenReturn(42);
    MockResponseCallback responseCallback = new MockResponseCallback();
    channel.writeAndFlush(
        new DriverChannel.RequestMessage(QUERY, false, Frame.NO_PAYLOAD, responseCallback));
    Frame requestFrame = readOutboundFrame();

    // When
    Frame responseFrame = buildInboundFrame(requestFrame, Void.INSTANCE);
    writeInboundFrame(responseFrame);

    // Then
    assertThat(responseCallback.getLastResponse()).isSameAs(responseFrame);
    verify(streamIds).release(42);
  }

  @Test
  public void should_notify_response_promise_when_decoding_fails() throws Throwable {
    // Given
    addToPipeline();
    when(streamIds.acquire()).thenReturn(42);
    MockResponseCallback responseCallback = new MockResponseCallback();
    channel
        .writeAndFlush(
            new DriverChannel.RequestMessage(QUERY, false, Frame.NO_PAYLOAD, responseCallback))
        .awaitUninterruptibly();

    // When
    RuntimeException mockCause = new RuntimeException("test");
    channel.pipeline().fireExceptionCaught(new FrameDecodingException(42, mockCause));

    // Then
    assertThat(responseCallback.getFailure()).isSameAs(mockCause);
    verify(streamIds).release(42);
  }

  @Test
  public void should_release_stream_id_when_orphaned_callback_receives_response() {
    // Given
    addToPipeline();
    when(streamIds.acquire()).thenReturn(42);
    MockResponseCallback responseCallback = new MockResponseCallback();
    channel.writeAndFlush(
        new DriverChannel.RequestMessage(QUERY, false, Frame.NO_PAYLOAD, responseCallback));
    Frame requestFrame = readOutboundFrame();

    // When
    channel.writeAndFlush(responseCallback); // means cancellation (see DriverChannel#cancel)
    Frame responseFrame = buildInboundFrame(requestFrame, Void.INSTANCE);
    writeInboundFrame(responseFrame);

    // Then
    verify(streamIds).release(42);
    // The response is not propagated, because we assume a callback that cancelled managed its own
    // termination
    assertThat(responseCallback.getLastResponse()).isNull();
  }

  @Test
  public void should_delay_graceful_close_and_complete_when_last_pending_completes() {
    // Given
    addToPipeline();
    when(streamIds.acquire()).thenReturn(42);
    MockResponseCallback responseCallback = new MockResponseCallback();
    channel
        .writeAndFlush(
            new DriverChannel.RequestMessage(QUERY, false, Frame.NO_PAYLOAD, responseCallback))
        .awaitUninterruptibly();

    // When
    channel.write(DriverChannel.GRACEFUL_CLOSE_MESSAGE);

    // Then
    // not closed yet because there is one pending request
    assertThat(channel.closeFuture()).isNotDone();

    // When
    // completing pending request
    Frame requestFrame = readOutboundFrame();
    writeInboundFrame(requestFrame, Void.INSTANCE);

    // Then
    assertThat(channel.closeFuture()).isSuccess();
  }

  @Test
  public void should_delay_graceful_close_and_complete_when_last_pending_cancelled() {
    // Given
    addToPipeline();
    when(streamIds.acquire()).thenReturn(42);
    MockResponseCallback responseCallback = new MockResponseCallback();
    channel
        .writeAndFlush(
            new DriverChannel.RequestMessage(QUERY, false, Frame.NO_PAYLOAD, responseCallback))
        .awaitUninterruptibly();

    // When
    channel.write(DriverChannel.GRACEFUL_CLOSE_MESSAGE);

    // Then
    // not closed yet because there is one pending request
    assertThat(channel.closeFuture()).isNotDone();

    // When
    // cancelling pending request
    channel.write(responseCallback);

    // Then
    assertThat(channel.closeFuture()).isSuccess();
  }

  @Test
  public void should_graceful_close_immediately_if_no_pending() {
    // Given
    addToPipeline();

    // When
    channel.write(DriverChannel.GRACEFUL_CLOSE_MESSAGE);

    // Then
    assertThat(channel.closeFuture()).isSuccess();
  }

  @Test
  public void should_refuse_new_writes_during_graceful_close() {
    // Given
    addToPipeline();
    when(streamIds.acquire()).thenReturn(42);
    MockResponseCallback responseCallback = new MockResponseCallback();
    channel
        .writeAndFlush(
            new DriverChannel.RequestMessage(QUERY, false, Frame.NO_PAYLOAD, responseCallback))
        .awaitUninterruptibly();

    // When
    channel.write(DriverChannel.GRACEFUL_CLOSE_MESSAGE);

    // Then
    // not closed yet because there is one pending request
    assertThat(channel.closeFuture()).isNotDone();
    // should not allow other write
    ChannelFuture otherWriteFuture =
        channel.writeAndFlush(
            new DriverChannel.RequestMessage(QUERY, false, Frame.NO_PAYLOAD, responseCallback));
    assertThat(otherWriteFuture)
        .isFailed(
            e ->
                assertThat(e)
                    .isInstanceOf(IllegalStateException.class)
                    .hasMessage("Channel is closing"));
  }

  @Test
  public void should_close_gracefully_if_orphan_ids_above_max_and_pending_requests() {
    // Given
    addToPipeline();
    // Generate n orphan ids by writing and cancelling the requests:
    for (int i = 0; i < MAX_ORPHAN_IDS; i++) {
      when(streamIds.acquire()).thenReturn(i);
      MockResponseCallback responseCallback = new MockResponseCallback();
      channel
          .writeAndFlush(
              new DriverChannel.RequestMessage(QUERY, false, Frame.NO_PAYLOAD, responseCallback))
          .awaitUninterruptibly();
      channel.writeAndFlush(responseCallback).awaitUninterruptibly();
    }
    // Generate another request that is pending and not cancelled:
    when(streamIds.acquire()).thenReturn(MAX_ORPHAN_IDS);
    MockResponseCallback pendingResponseCallback = new MockResponseCallback();
    channel
        .writeAndFlush(
            new DriverChannel.RequestMessage(
                QUERY, false, Frame.NO_PAYLOAD, pendingResponseCallback))
        .awaitUninterruptibly();

    // When
    // Generate the n+1th orphan id that makes us go above the threshold
    when(streamIds.acquire()).thenReturn(MAX_ORPHAN_IDS + 1);
    MockResponseCallback responseCallback = new MockResponseCallback();
    channel
        .writeAndFlush(
            new DriverChannel.RequestMessage(QUERY, false, Frame.NO_PAYLOAD, responseCallback))
        .awaitUninterruptibly();
    channel.writeAndFlush(responseCallback).awaitUninterruptibly();

    // Then
    // Channel should be closing gracefully. There's no way to observe that from the outside, so
    // write another request and check that it's rejected:
    assertThat(channel.closeFuture()).isNotDone();
    ChannelFuture otherWriteFuture =
        channel.writeAndFlush(
            new DriverChannel.RequestMessage(QUERY, false, Frame.NO_PAYLOAD, responseCallback));
    assertThat(otherWriteFuture)
        .isFailed(
            e ->
                assertThat(e)
                    .isInstanceOf(IllegalStateException.class)
                    .hasMessage("Channel is closing"));

    // When
    // Cancel the last pending request
    channel.writeAndFlush(pendingResponseCallback).awaitUninterruptibly();

    // Then
    // The graceful shutdown completes
    assertThat(channel.closeFuture()).isSuccess();
  }

  @Test
  public void should_close_immediately_if_orphan_ids_above_max_and_no_pending_requests() {
    // Given
    addToPipeline();
    // Generate n orphan ids by writing and cancelling the requests:
    for (int i = 0; i < MAX_ORPHAN_IDS; i++) {
      when(streamIds.acquire()).thenReturn(i);
      MockResponseCallback responseCallback = new MockResponseCallback();
      channel
          .writeAndFlush(
              new DriverChannel.RequestMessage(QUERY, false, Frame.NO_PAYLOAD, responseCallback))
          .awaitUninterruptibly();
      channel.writeAndFlush(responseCallback).awaitUninterruptibly();
    }

    // When
    // Generate the n+1th orphan id that makes us go above the threshold
    when(streamIds.acquire()).thenReturn(MAX_ORPHAN_IDS);
    MockResponseCallback responseCallback = new MockResponseCallback();
    channel
        .writeAndFlush(
            new DriverChannel.RequestMessage(QUERY, false, Frame.NO_PAYLOAD, responseCallback))
        .awaitUninterruptibly();
    channel.writeAndFlush(responseCallback).awaitUninterruptibly();

    // Then
    // Channel should close immediately since no active pending requests.
    assertThat(channel.closeFuture()).isSuccess();
  }

  @Test
  public void should_fail_all_pending_when_force_closed() throws Throwable {
    // Given
    addToPipeline();
    when(streamIds.acquire()).thenReturn(42, 43);
    MockResponseCallback responseCallback1 = new MockResponseCallback();
    MockResponseCallback responseCallback2 = new MockResponseCallback();
    channel
        .writeAndFlush(
            new DriverChannel.RequestMessage(QUERY, false, Frame.NO_PAYLOAD, responseCallback1))
        .awaitUninterruptibly();
    channel
        .writeAndFlush(
            new DriverChannel.RequestMessage(QUERY, false, Frame.NO_PAYLOAD, responseCallback2))
        .awaitUninterruptibly();

    // When
    channel.write(DriverChannel.FORCEFUL_CLOSE_MESSAGE);

    // Then
    assertThat(channel.closeFuture()).isSuccess();
    for (MockResponseCallback callback : ImmutableList.of(responseCallback1, responseCallback2)) {
      assertThat(callback.getFailure())
          .isInstanceOf(ClosedConnectionException.class)
          .hasMessageContaining("Channel was force-closed");
    }
  }

  @Test
  public void should_fail_all_pending_and_close_on_unexpected_inbound_exception() throws Throwable {
    // Given
    addToPipeline();
    when(streamIds.acquire()).thenReturn(42, 43);
    MockResponseCallback responseCallback1 = new MockResponseCallback();
    MockResponseCallback responseCallback2 = new MockResponseCallback();
    channel
        .writeAndFlush(
            new DriverChannel.RequestMessage(QUERY, false, Frame.NO_PAYLOAD, responseCallback1))
        .awaitUninterruptibly();
    channel
        .writeAndFlush(
            new DriverChannel.RequestMessage(QUERY, false, Frame.NO_PAYLOAD, responseCallback2))
        .awaitUninterruptibly();

    // When
    RuntimeException mockException = new RuntimeException("test");
    channel.pipeline().fireExceptionCaught(mockException);

    // Then
    assertThat(channel.closeFuture()).isSuccess();
    for (MockResponseCallback callback : ImmutableList.of(responseCallback1, responseCallback2)) {
      Throwable failure = callback.getFailure();
      assertThat(failure).isInstanceOf(ClosedConnectionException.class);
      assertThat(failure.getCause()).isSameAs(mockException);
    }
  }

  @Test
  public void should_fail_all_pending_if_connection_lost() {
    // Given
    addToPipeline();
    when(streamIds.acquire()).thenReturn(42, 43);
    MockResponseCallback responseCallback1 = new MockResponseCallback();
    MockResponseCallback responseCallback2 = new MockResponseCallback();
    channel
        .writeAndFlush(
            new DriverChannel.RequestMessage(QUERY, false, Frame.NO_PAYLOAD, responseCallback1))
        .awaitUninterruptibly();
    channel
        .writeAndFlush(
            new DriverChannel.RequestMessage(QUERY, false, Frame.NO_PAYLOAD, responseCallback2))
        .awaitUninterruptibly();

    // When
    channel.pipeline().fireChannelInactive();

    // Then
    for (MockResponseCallback callback : ImmutableList.of(responseCallback1, responseCallback2)) {
      assertThat(callback.getFailure())
          .isInstanceOf(ClosedConnectionException.class)
          .hasMessageContaining("Lost connection to remote peer");
    }
  }

  @Test
  public void should_hold_stream_id_for_multi_response_callback() {
    // Given
    addToPipeline();
    when(streamIds.acquire()).thenReturn(42);
    MockResponseCallback responseCallback =
        new MockResponseCallback(frame -> frame.message instanceof Error);

    // When
    channel
        .writeAndFlush(
            new DriverChannel.RequestMessage(QUERY, false, Frame.NO_PAYLOAD, responseCallback))
        .awaitUninterruptibly();

    // Then
    // notify callback of stream id
    assertThat(responseCallback.streamId).isEqualTo(42);

    Frame requestFrame = readOutboundFrame();
    for (int i = 0; i < 5; i++) {
      // When
      // completing pending request
      Frame responseFrame = buildInboundFrame(requestFrame, Void.INSTANCE);
      writeInboundFrame(responseFrame);

      // Then
      assertThat(responseCallback.getLastResponse()).isSameAs(responseFrame);
      // Stream id not released, callback can receive more responses
      verify(streamIds, never()).release(42);
    }

    // When
    // a terminal response comes in
    Frame responseFrame = buildInboundFrame(requestFrame, new Error(0, "test"));
    writeInboundFrame(responseFrame);

    // Then
    verify(streamIds).release(42);
    assertThat(responseCallback.getLastResponse()).isSameAs(responseFrame);

    // When
    // more responses come in
    writeInboundFrame(requestFrame, Void.INSTANCE);

    // Then
    // the callback does not get them anymore (this could only be responses to a new request that
    // reused the id)
    assertThat(responseCallback.getLastResponse()).isNull();
  }

  @Test
  public void
      should_release_stream_id_when_orphaned_multi_response_callback_receives_last_response() {
    // Given
    addToPipeline();
    when(streamIds.acquire()).thenReturn(42);
    MockResponseCallback responseCallback =
        new MockResponseCallback(frame -> frame.message instanceof Error);

    channel
        .writeAndFlush(
            new DriverChannel.RequestMessage(QUERY, false, Frame.NO_PAYLOAD, responseCallback))
        .awaitUninterruptibly();

    Frame requestFrame = readOutboundFrame();
    for (int i = 0; i < 5; i++) {
      Frame responseFrame = buildInboundFrame(requestFrame, Void.INSTANCE);
      writeInboundFrame(responseFrame);
      assertThat(responseCallback.getLastResponse()).isSameAs(responseFrame);
      verify(streamIds, never()).release(42);
    }

    // When
    // cancelled mid-flight
    channel.writeAndFlush(responseCallback);

    // Then
    // subsequent non-final responses are not propagated (we assume the callback completed itself
    // already), but do not release the stream id
    writeInboundFrame(requestFrame, Void.INSTANCE);
    assertThat(responseCallback.getLastResponse()).isNull();
    verify(streamIds, never()).release(42);

    // When
    // the terminal response arrives
    writeInboundFrame(requestFrame, new Error(0, "test"));

    // Then
    // still not propagated but the id is released
    assertThat(responseCallback.getLastResponse()).isNull();
    verify(streamIds).release(42);
  }

  @Test
  public void should_set_keyspace() {
    // Given
    addToPipeline();
    ChannelPromise setKeyspacePromise = channel.newPromise();
    DriverChannel.SetKeyspaceEvent setKeyspaceEvent =
        new DriverChannel.SetKeyspaceEvent(CqlIdentifier.fromCql("ks"), setKeyspacePromise);

    // When
    channel.pipeline().fireUserEventTriggered(setKeyspaceEvent);
    Frame requestFrame = readOutboundFrame();

    // Then
    assertThat(requestFrame.message).isInstanceOf(Query.class);
    writeInboundFrame(requestFrame, new SetKeyspace("ks"));
    assertThat(setKeyspacePromise).isSuccess();
  }

  @Test
  public void should_fail_to_set_keyspace_if_query_times_out() throws InterruptedException {
    // Given
    addToPipeline();
    ChannelPromise setKeyspacePromise = channel.newPromise();
    DriverChannel.SetKeyspaceEvent setKeyspaceEvent =
        new DriverChannel.SetKeyspaceEvent(CqlIdentifier.fromCql("ks"), setKeyspacePromise);

    // When
    channel.pipeline().fireUserEventTriggered(setKeyspaceEvent);
    TimeUnit.MILLISECONDS.sleep(SET_KEYSPACE_TIMEOUT_MILLIS * 2);
    channel.runPendingTasks();

    // Then
    assertThat(setKeyspacePromise).isFailed();
  }

  @Test
  public void should_notify_callback_of_events() {
    // Given
    EventCallback eventCallback = mock(EventCallback.class);
    addToPipelineWithEventCallback(eventCallback);

    // When
    StatusChangeEvent event =
        new StatusChangeEvent(
            ProtocolConstants.StatusChangeType.UP, new InetSocketAddress("127.0.0.1", 9042));
    Frame eventFrame =
        Frame.forResponse(
            DefaultProtocolVersion.V3.getCode(),
            -1,
            null,
            Collections.emptyMap(),
            Collections.emptyList(),
            event);
    writeInboundFrame(eventFrame);

    // Then
    ArgumentCaptor<StatusChangeEvent> captor = ArgumentCaptor.forClass(StatusChangeEvent.class);
    verify(eventCallback).onEvent(captor.capture());
    assertThat(captor.getValue()).isSameAs(event);
  }

  private void addToPipeline() {
    addToPipelineWithEventCallback(null);
  }

  private void addToPipelineWithEventCallback(EventCallback eventCallback) {
    channel
        .pipeline()
        .addLast(
            new InFlightHandler(
                DefaultProtocolVersion.V3,
                streamIds,
                MAX_ORPHAN_IDS,
                SET_KEYSPACE_TIMEOUT_MILLIS,
                channel.newPromise(),
                eventCallback,
                "test"));
  }
}


text:
<?php
/**
 * class Recurly_CreditPayment
 * @property string $uuid The uuid of the credit payment.
 * @property string $currency The currency of the amount_in_cents.
 * @property int $amount_in_cents The amount of the credit payment.
 * @property DateTime $created_at
 * @property DateTime $updated_at
 * @property DateTime $voided_at
 */
class Recurly_CreditPayment extends Recurly_Resource
{
  protected function getNodeName() {
    return 'credit_payment';
  }

  protected function getWriteableAttributes() {
   return array();
  }
}


text:
package org.spongycastle.util;

public interface StringList
    extends Iterable<String>
{
    boolean add(String s);

    String get(int index);

    int size();

    String[] toStringArray();

    /**
     * Return a section of the contents of the list. If the list is too short the array is filled with nulls.
     *
     * @param from the initial index of the range to be copied, inclusive
     * @param to the final index of the range to be copied, exclusive.
     * @return an array of length to - from
     */
    String[] toStringArray(int from, int to);
}


text:
// .NAME vtkInterpolatingSubdivisionFilter - generate a subdivision surface using an Interpolating Scheme
// .SECTION Description
// vtkInterpolatingSubdivisionFilter is an abstract class that defines
// the protocol for interpolating subdivision surface filters.

// .SECTION Thanks
// This work was supported by PHS Research Grant No. 1 P41 RR13218-01
// from the National Center for Research Resources.

// .SECTION See Also
// vtkLinearSubdivisionFilter vtkButterflySubdivisionFilter

#ifndef vtkInterpolatingSubdivisionFilter_h
#define vtkInterpolatingSubdivisionFilter_h

#include "vtkFiltersGeneralModule.h" // For export macro
#include "vtkPolyDataAlgorithm.h"

class vtkCellArray;
class vtkCellData;
class vtkIdList;
class vtkIntArray;
class vtkPointData;
class vtkPoints;
class vtkPolyData;

class VTKFILTERSGENERAL_EXPORT vtkInterpolatingSubdivisionFilter : public vtkPolyDataAlgorithm
{
public:
  vtkTypeMacro(vtkInterpolatingSubdivisionFilter,vtkPolyDataAlgorithm);
  void PrintSelf(ostream& os, vtkIndent indent);

  // Description:
  // Set/get the number of subdivisions.
  vtkSetMacro(NumberOfSubdivisions,int);
  vtkGetMacro(NumberOfSubdivisions,int);

protected:
  vtkInterpolatingSubdivisionFilter();
  ~vtkInterpolatingSubdivisionFilter() {}

  int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
  virtual int GenerateSubdivisionPoints (vtkPolyData *inputDS, vtkIntArray *edgeData, vtkPoints *outputPts, vtkPointData *outputPD) = 0;
  void GenerateSubdivisionCells (vtkPolyData *inputDS, vtkIntArray *edgeData, vtkCellArray *outputPolys, vtkCellData *outputCD);
  int FindEdge (vtkPolyData *mesh, vtkIdType cellId, vtkIdType p1,
                vtkIdType p2, vtkIntArray *edgeData, vtkIdList *cellIds);
  vtkIdType InterpolatePosition (vtkPoints *inputPts, vtkPoints *outputPts,
                                 vtkIdList *stencil, double *weights);
  int NumberOfSubdivisions;

private:
  vtkInterpolatingSubdivisionFilter(const vtkInterpolatingSubdivisionFilter&);  // Not implemented.
  void operator=(const vtkInterpolatingSubdivisionFilter&);  // Not implemented.
};

#endif


text:
package leap.web.download;

import leap.lang.logging.Log;
import leap.lang.logging.LogFactory;
import leap.lang.resource.Resource;
import leap.web.Request;
import leap.web.Response;
import leap.web.Utils;

/**
 * A file content in webapp.
 */
public class ServletResourceDownload extends AbstractDownload {

	private static final Log log = LogFactory.get(ServletResourceDownload.class);

	protected String path;

	/**
	 * Pass the servlet path.
	 */
	public ServletResourceDownload(String path) {
		this.path = path;
	}

	@Override
    protected Resource getResource(Request request, Response response) throws Throwable {
		log.debug("Returning war file content of path : {}",path);
		return Utils.getResource(request.getServletContext(), path);
    }

}


text:
package org.openntf.xsp.extlib.application;

import java.io.IOException;

import javax.faces.FacesException;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;

import org.openntf.xsp.extlib.Activator;

import com.ibm.xsp.application.StateManagerImpl;
import com.ibm.xsp.util.Delegation;

public class StateManager extends StateManagerImpl {
	private final javax.faces.application.StateManager _delegate;
	private final static boolean _debug = Activator._debug;

	public StateManager(javax.faces.application.StateManager paramStateManager) {
		super(paramStateManager);
		_delegate = paramStateManager;
		if (_debug) {
			System.out.println(getClass().getName() + " created using "
					+ (_delegate != null ? _delegate.getClass().getName() : "null"));
		}
	}

	public StateManager() throws FacesException, ClassNotFoundException, InstantiationException, IllegalAccessException {
		javax.faces.application.StateManager priorStateManager = ((javax.faces.application.StateManager) Delegation
				.getImplementation("state-manager"));
		this._delegate = priorStateManager;
		if (_debug) {
			System.out.println(getClass().getName() + " created empty using "
					+ (_delegate != null ? _delegate.getClass().getName() : "null"));
		}
	}

	@Override
	public void writeState(FacesContext paramFacesContext, StateManager.SerializedView paramSerializedView)
			throws IOException {
		// your code goes here
		super.writeState(paramFacesContext, paramSerializedView);
	}

	@Override
	public UIViewRoot restoreView(FacesContext paramFacesContext, String paramString1, String paramString2) {
		// your code goes here
		return super.restoreView(paramFacesContext, paramString1, paramString2);
	}
}


text:
#ifndef itkRegionGrowImageFilter_h
#define itkRegionGrowImageFilter_h

#include "itkObject.h"
#include "itkImageToImageFilter.h"

namespace itk
{
/**
 *\class RegionGrowImageFilter
 * \brief Base class for RegionGrowImageFilter object
 *
 * itkRegionGrowImageFilter is the base class for the
 * RegionGrowImageFilter objects. It provides
 * the basic function definitions that are inherent to a
 * RegionGrowImageFilter objects.
 * It is templated over the type of input and output image.
 *
 * This object defines the interface for those algorithm that perform
 * feature/object segmentation by merging regions (parts of the image) that
 * are similar in nature based on some metric. As a result parts of the image
 * which belong to the same object gets merged and the region grows.
 *
 * As an example regarding using this class to implementation of advanced
 * region growing algorithm, itkRegionGrowImageFilterKLM class has been
 * derived from this class. The virtual function ApplyRegionGrowImageFilter()
 * provides the interface to the outside world to extend/enhance the scope of
 * the current algorithm or write other region growing algorithms. The
 * function MergeRegions is interface for the operation that merges two
 * regions.
 *
 * The local variable GridSize is used to define
 * the initial small regions that the image is fragmented (atomic
 * regions) into. For an 12 x 12 input image, GridSize set equal
 * to [3, 3] will result in 16 initial regions. The default values are
 * set equal to 2.
 * The user can sets the number of desired regions via the m_MaxNumRegions
 * parameter and the algorithm tries to perform region merging until there
 * are only m_MaxNumRegions. If m_MaxNumRegions is more than the number of
 * initial blocks, no region merging occurs.
 *
 * These blocks are important as the labels associated with these blocks keep
 * changing during the region growing process and at the end, while generating
 * the results, each of these atomic blocks are revisited and the blocks
 * with same labels are considered to belong to the same region.
 *
 * This object supports data handling of multiband images. The object
 * accepts images in vector format, where each pixel is a vector and each
 * element of the vector corresponds to an entry from 1 particular band of
 * a multiband dataset. The input to this object is assumed to be a multiband
 * vector image, and the output is defined by specific algorithm
 * implementation. The second template parameter is used to generate the
 * the output image and can be modified according the algorithm
 * specific output type.
 *
 * We expect the user to provide the input to the routine in vector format.
 * A single band image is treated as a vector image with a single element
 * for every vector.
 *
 * \ingroup RegionGrowingSegmentation
 * \ingroup ITKKLMRegionGrowing
 *
 * \sphinx
 * \sphinxexample{Segmentation/KLMRegionGrowing/BasicRegionGrowing,Basic Region Growing}
 * \endsphinx
 */
template <typename TInputImage, typename TOutputImage>
class ITK_TEMPLATE_EXPORT RegionGrowImageFilter : public ImageToImageFilter<TInputImage, TOutputImage>
{
public:
  ITK_DISALLOW_COPY_AND_ASSIGN(RegionGrowImageFilter);

  /** Standard class type aliases. */
  using Self = RegionGrowImageFilter;
  using Superclass = ImageToImageFilter<TInputImage, TOutputImage>;
  using Pointer = SmartPointer<Self>;
  using ConstPointer = SmartPointer<const Self>;

  /** Run-time type information (and related methods). */
  itkTypeMacro(RegionGrowImageFilter, ImageToImageFilter);

  /** Type definition for the input image. */
  using InputImageType = TInputImage;
  using InputImagePointer = typename TInputImage::Pointer;
  using InputImageConstPointer = typename TInputImage::ConstPointer;

  /** Type definition for the input image pixel type. */
  using InputImagePixelType = typename TInputImage::PixelType;

  /** Type definition for the output image. */
  using OutputImageType = TOutputImage;
  using OutputImagePointer = typename TOutputImage::Pointer;

  /** Type definition for the input image pixel type. */
  using OutputImagePixelType = typename TOutputImage::PixelType;

  /** Type definition for the initial grid. */
  using GridSizeType = typename TInputImage::SizeType;

  /** Set/Get the initial grid. */
  itkSetMacro(GridSize, GridSizeType);
  itkGetConstReferenceMacro(GridSize, GridSizeType);

  /** Set/Get the number of regions desired. */
  itkSetMacro(MaximumNumberOfRegions, unsigned int);
  itkGetConstReferenceMacro(MaximumNumberOfRegions, unsigned int);

  /** Define a virtual RegionGrowImageFilter function. */
  virtual void
  ApplyRegionGrowImageFilter() = 0;

  /** Merge two regions. */
  virtual void
  MergeRegions() = 0;

protected:
  RegionGrowImageFilter();
  ~RegionGrowImageFilter() override = default;
  void
  PrintSelf(std::ostream & os, Indent indent) const override;

private:
  unsigned int m_MaximumNumberOfRegions;

  GridSizeType m_GridSize;
}; // class RegionGrowImageFilter
} // namespace itk

#ifndef ITK_MANUAL_INSTANTIATION
#  include "itkRegionGrowImageFilter.hxx"
#endif

#endif


text:
import React from 'react'
import { Segment } from 'shengnian-ui-react'

const SegmentExamplePiled = () => (
  <Segment piled>
    Pellentesque habitant morbi tristique senectus.
  </Segment>
)

export default SegmentExamplePiled


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Cercospora densissima Speg.

### Remarks
null