text:
package org.apache.geode.cache.client.internal;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.logging.log4j.Logger;

import org.apache.geode.CancelCriterion;
import org.apache.geode.CancelException;
import org.apache.geode.ForcedDisconnectException;
import org.apache.geode.cache.client.internal.ExecuteFunctionOp.ExecuteFunctionOpImpl;
import org.apache.geode.cache.client.internal.ExecuteRegionFunctionOp.ExecuteRegionFunctionOpImpl;
import org.apache.geode.cache.client.internal.ExecuteRegionFunctionSingleHopOp.ExecuteRegionFunctionSingleHopOpImpl;
import org.apache.geode.cache.wan.GatewaySender;
import org.apache.geode.distributed.internal.DistributionConfig;
import org.apache.geode.distributed.internal.InternalDistributedSystem;
import org.apache.geode.distributed.internal.ServerLocation;
import org.apache.geode.internal.cache.tier.sockets.HandShake;
import org.apache.geode.internal.cache.tier.sockets.ServerConnection;
import org.apache.geode.internal.cache.tier.sockets.ServerQueueStatus;
import org.apache.geode.internal.i18n.LocalizedStrings;
import org.apache.geode.internal.logging.LogService;
import org.apache.geode.internal.logging.log4j.LocalizedMessage;
import org.apache.geode.internal.net.SocketCreator;

/**
 * A single client to server connection.
 *
 * The execute method of this class is synchronized to prevent two ops from using the client to
 * server connection at the same time.
 *
 * @since GemFire 5.7
 */
public class ConnectionImpl implements Connection {

  // TODO: DEFAULT_CLIENT_FUNCTION_TIMEOUT should be private
  public static final int DEFAULT_CLIENT_FUNCTION_TIMEOUT = 0;
  private static Logger logger = LogService.getLogger();

  /**
   * Test hook to simulate a client crashing. If true, we will not notify the server when we close
   * the connection.
   */
  private static boolean TEST_DURABLE_CLIENT_CRASH = false;

  // TODO: clientFunctionTimeout is not thread-safe and should be non-static
  private static int clientFunctionTimeout;

  private Socket theSocket;
  private ByteBuffer commBuffer;
  private ByteBuffer commBufferForAsyncRead;
  private ServerQueueStatus status;
  private volatile boolean connectFinished;
  private final AtomicBoolean destroyed = new AtomicBoolean();
  private Endpoint endpoint;

  // In Gateway communication version of connected wan site will be stored after successful
  // handshake
  private short wanSiteVersion = -1;

  private final InternalDistributedSystem ds;

  private OutputStream out;
  private InputStream in;

  private long connectionID = Connection.DEFAULT_CONNECTION_ID;

  private HandShake handShake;

  public ConnectionImpl(InternalDistributedSystem ds, CancelCriterion cancelCriterion) {
    this.ds = ds;
    int time = Integer.getInteger(DistributionConfig.GEMFIRE_PREFIX + "CLIENT_FUNCTION_TIMEOUT",
        DEFAULT_CLIENT_FUNCTION_TIMEOUT);
    clientFunctionTimeout = time >= 0 ? time : DEFAULT_CLIENT_FUNCTION_TIMEOUT;
  }

  public static int getClientFunctionTimeout() {
    return clientFunctionTimeout;
  }

  public ServerQueueStatus connect(EndpointManager endpointManager, ServerLocation location,
      HandShake handShake, int socketBufferSize, int handShakeTimeout, int readTimeout,
      byte communicationMode, GatewaySender sender, SocketCreator sc) throws IOException {
    theSocket = sc.connectForClient(location.getHostName(), location.getPort(), handShakeTimeout,
        socketBufferSize);
    theSocket.setTcpNoDelay(true);
    // System.out.println("ConnectionImpl setting buffer sizes: " +
    // socketBufferSize);
    theSocket.setSendBufferSize(socketBufferSize);

    // Verify buffer sizes
    verifySocketBufferSize(socketBufferSize, theSocket.getReceiveBufferSize(), "receive");
    verifySocketBufferSize(socketBufferSize, theSocket.getSendBufferSize(), "send");

    theSocket.setSoTimeout(handShakeTimeout);
    out = theSocket.getOutputStream();
    in = theSocket.getInputStream();
    this.status = handShake.handshakeWithServer(this, location, communicationMode);
    commBuffer = ServerConnection.allocateCommBuffer(socketBufferSize, theSocket);
    if (sender != null) {
      commBufferForAsyncRead = ServerConnection.allocateCommBuffer(socketBufferSize, theSocket);
    }
    theSocket.setSoTimeout(readTimeout);
    endpoint = endpointManager.referenceEndpoint(location, this.status.getMemberId());
    // logger.warning("ESTABLISHING ENDPOINT:"+location+" MEMBERID:"+endpoint.getMemberId(),new
    // Exception());
    this.connectFinished = true;
    this.endpoint.getStats().incConnections(1);
    return status;
  }

  public void close(boolean keepAlive) throws Exception {

    try {
      // if a forced-disconnect has occurred, we can't send messages to anyone
      boolean sendCloseMsg = !TEST_DURABLE_CLIENT_CRASH;
      if (sendCloseMsg) {
        try {
          ((InternalDistributedSystem) ds).getDistributionManager();
        } catch (CancelException e) { // distribution has stopped
          Throwable t = e.getCause();
          if (t instanceof ForcedDisconnectException) {
            // we're crashing - don't attempt to send a message (bug 39317)
            sendCloseMsg = false;
          }
        }
      }

      if (sendCloseMsg) {
        if (logger.isDebugEnabled()) {
          logger.debug("Closing connection {} with keepAlive: {}", this, keepAlive);
        }
        CloseConnectionOp.execute(this, keepAlive);
      }
    } finally {
      destroy();
    }
  }

  public void emergencyClose() {
    commBuffer = null;
    try {
      theSocket.close();
    } catch (IOException | RuntimeException ignore) {
      // ignore
    }
  }

  public boolean isDestroyed() {
    return this.destroyed.get();
  }

  public void destroy() {
    if (!this.destroyed.compareAndSet(false, true)) {
      // was already set to true so someone else did the destroy
      return;
    }

    if (endpoint != null) {
      if (this.connectFinished) {
        endpoint.getStats().incConnections(-1);
      }
      endpoint.removeReference();
    }
    try {
      if (theSocket != null) {
        theSocket.getOutputStream().flush();
        theSocket.shutdownOutput();
        theSocket.close();
      }
    } catch (Exception e) {
      if (logger.isDebugEnabled()) {
        logger.debug(e.getMessage(), e);
      }
    }
    releaseCommBuffers();
  }

  private void releaseCommBuffers() {
    ByteBuffer bb = this.commBuffer;
    if (bb != null) {
      this.commBuffer = null;
      ServerConnection.releaseCommBuffer(bb);
    }
    bb = this.commBufferForAsyncRead;
    if (bb != null) {
      this.commBufferForAsyncRead = null;
      ServerConnection.releaseCommBuffer(bb);
    }
  }

  public ByteBuffer getCommBuffer() throws SocketException {
    if (isDestroyed()) {
      // see bug 52193. Since the code used to see this
      // as an attempt to use a close socket just throw
      // a SocketException.
      throw new SocketException("socket was closed");
    }
    return commBuffer;
  }

  public ServerLocation getServer() {
    return endpoint.getLocation();
  }

  public Socket getSocket() {
    return theSocket;
  }

  public OutputStream getOutputStream() {
    return out;
  }

  public InputStream getInputStream() {
    return in;
  }

  public ConnectionStats getStats() {
    return endpoint.getStats();
  }

  @Override
  public String toString() {
    return "Connection[" + endpoint + "]@" + this.hashCode();
  }

  public Endpoint getEndpoint() {
    return endpoint;
  }

  public ServerQueueStatus getQueueStatus() {
    return status;
  }

  public Object execute(Op op) throws Exception {
    Object result;
    // Do not synchronize when used for GatewaySender
    // as the same connection is being used
    if ((op instanceof AbstractOp) && ((AbstractOp) op).isGatewaySenderOp()) {
      result = op.attempt(this);
      endpoint.updateLastExecute();
      return result;
    }
    synchronized (this) {
      if (op instanceof ExecuteFunctionOpImpl || op instanceof ExecuteRegionFunctionOpImpl
          || op instanceof ExecuteRegionFunctionSingleHopOpImpl) {
        int earliertimeout = this.getSocket().getSoTimeout();
        this.getSocket().setSoTimeout(getClientFunctionTimeout());
        try {
          result = op.attempt(this);
        } finally {
          this.getSocket().setSoTimeout(earliertimeout);
        }
      } else {
        result = op.attempt(this);
      }
    }
    endpoint.updateLastExecute();
    return result;

  }

  public static void loadEmergencyClasses() {
    // do nothing
  }

  public short getWanSiteVersion() {
    return wanSiteVersion;
  }

  public void setWanSiteVersion(short wanSiteVersion) {
    this.wanSiteVersion = wanSiteVersion;
  }

  public int getDistributedSystemId() {
    return ((InternalDistributedSystem) this.ds).getDistributionManager().getDistributedSystemId();
  }

  public void setConnectionID(long id) {
    this.connectionID = id;
  }

  public long getConnectionID() {
    return this.connectionID;
  }

  protected HandShake getHandShake() {
    return handShake;
  }

  protected void setHandShake(HandShake handShake) {
    this.handShake = handShake;
  }

  /**
   * test hook
   */
  public static void setTEST_DURABLE_CLIENT_CRASH(boolean v) {
    TEST_DURABLE_CLIENT_CRASH = v;
  }

  public ByteBuffer getCommBufferForAsyncRead() throws SocketException {
    if (isDestroyed()) {
      // see bug 52193. Since the code used to see this
      // as an attempt to use a close socket just throw
      // a SocketException.
      throw new SocketException("socket was closed");
    }
    return commBufferForAsyncRead;
  }

  private void verifySocketBufferSize(int requestedBufferSize, int actualBufferSize, String type) {
    if (actualBufferSize < requestedBufferSize) {
      logger.info(LocalizedMessage.create(
          LocalizedStrings.Connection_SOCKET_0_IS_1_INSTEAD_OF_THE_REQUESTED_2,
          new Object[] {new StringBuilder(type).append(" buffer size").toString(), actualBufferSize,
              requestedBufferSize}));
    }
  }
}


text:
#ifndef LIT_GLOBALS_H
#define LIT_GLOBALS_H

#include "jrt.h"

/**
 * ECMAScript standard defines terms "code unit" and "character" as 16-bit unsigned value
 * used to represent 16-bit unit of text, this is the same as code unit in UTF-16 (See ECMA-262 5.1 Chapter 6).
 *
 * The term "code point" or "Unicode character" is used to refer a single Unicode scalar value (may be longer
 * than 16 bits: 0x0 - 0x10FFFFF). One code point could be represented with one ore two 16-bit code units.
 *
 * According to the standard all strings and source text are assumed to be a sequence of code units.
 * Length of a string equals to number of code units in the string, which is not the same as number of Unicode
 * characters in a string.
 *
 * Internally JerryScript engine uses UTF-8 representation of strings to reduce memory overhead. Unicode character
 * occupies from one to four bytes in UTF-8 representation.
 *
 * Unicode scalar value   | Bytes in UTF-8             | Bytes in UTF-16
 *                        | (internal representation)  |
 * ----------------------------------------------------------------------
 *  0x0     - 0x7F        |  1 byte                    |  2 bytes
 *  0x80    - 0x7FF       |  2 bytes                   |  2 bytes
 *  0x800   - 0xFFFF      |  3 bytes                   |  2 bytes
 *  0x10000 - 0x10FFFF    |  4 bytes                   |  4 bytes
 *
 * Scalar values from 0xD800 to 0xDFFF are permanently reserved by Unicode standard to encode high and low
 * surrogates in UTF-16 (Code points 0x10000 - 0x10FFFF are encoded via pair of surrogates in UTF-16).
 * Despite that the official Unicode standard says that no UTF forms can encode these code points, we allow
 * them to be encoded inside strings. The reason for that is compatibility with ECMA standard.
 *
 * For example, assume a string which consists one Unicode character: 0x1D700 (Mathematical Italic Small Epsilon).
 * It has the following representation in UTF-16: 0xD835 0xDF00.
 *
 * ECMA standard allows extracting a substring from this string:
 * > var str = String.fromCharCode (0xD835, 0xDF00); // Create a string containing one character: 0x1D700
 * > str.length; // 2
 * > var str1 = str.substring (0, 1);
 * > str1.length; // 1
 * > str1.charCodeAt (0); // 55349 (this equals to 0xD835)
 *
 * Internally original string would be represented in UTF-8 as the following byte sequence: 0xF0 0x9D 0x9C 0x80.
 * After substring extraction high surrogate 0xD835 should be encoded via UTF-8: 0xED 0xA0 0xB5.
 *
 * Pair of low and high surrogates encoded separately should never occur in internal string representation,
 * it should be encoded as any code point and occupy 4 bytes. So, when constructing a string from two surrogates,
 * it should be processed gracefully;
 * > var str1 = String.fromCharCode (0xD835); // 0xED 0xA0 0xB5 - internal representation
 * > var str2 = String.fromCharCode (0xDF00); // 0xED 0xBC 0x80 - internal representation
 * > var str = str1 + str2; // 0xF0 0x9D 0x9C 0x80 - internal representation,
 *                          // !!! not 0xED 0xA0 0xB5 0xED 0xBC 0x80
 */

/**
 * Description of an ecma-character, which represents 16-bit code unit,
 * which is equal to UTF-16 character (see Chapter 6 from ECMA-262 5.1)
 */
typedef uint16_t ecma_char_t;

/**
 * Description of a collection's/string's length
 */
typedef uint32_t ecma_length_t;

/**
 * Description of an ecma-character pointer
 */
typedef ecma_char_t *ecma_char_ptr_t;

/**
 * Max bytes needed to represent a code unit (utf-16 char) via utf-8 encoding
 */
#define LIT_UTF8_MAX_BYTES_IN_CODE_UNIT (3)

/**
 * Max bytes needed to represent a code point (Unicode character) via utf-8 encoding
 */
#define LIT_UTF8_MAX_BYTES_IN_CODE_POINT (4)

/**
 * Max bytes needed to represent a code unit (utf-16 char) via cesu-8 encoding
 */
#define LIT_CESU8_MAX_BYTES_IN_CODE_UNIT (3)

/**
 * Max bytes needed to represent a code point (Unicode character) via cesu-8 encoding
 */
#define LIT_CESU8_MAX_BYTES_IN_CODE_POINT (6)

/**
 * A byte of utf-8 string
 */
typedef uint8_t lit_utf8_byte_t;

/**
 * Size of a utf-8 string in bytes
 */
typedef uint32_t lit_utf8_size_t;

/**
 * Size of a magic string in bytes
 */
typedef uint8_t lit_magic_size_t;

/**
 * Unicode code point
 */
typedef uint32_t lit_code_point_t;

/**
 * ECMA string hash
 */
typedef uint16_t lit_string_hash_t;

/**
 * Maximum value of ECMA string hash + 1
 *
 * Note:
 *   On ARM, this constant can be encoded as an immediate value
 *   while 0xffffu cannot be. Hence using this constant reduces
 *   binary size and improves performance.
 */
#define LIT_STRING_HASH_LIMIT 0x10000u

#endif /* !LIT_GLOBALS_H */

redpajama_set_name: RedPajamaGithub


text:
//
// Copyright (c) Microsoft.  All rights reserved.
//
// 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.
//

namespace Microsoft.WindowsAzure.Management.Monitoring.Utilities
{
    public static class Constants
    {
        /// <summary>
        /// Service bus resource types
        /// </summary>
        public static class ServiceBusResourceType
        {
            /// <summary>
            /// Topics resource type
            /// </summary>
            public const string Topics = "topics";

            /// <summary>
            /// Queues resource type
            /// </summary>
            public const string Queues = "queues";

            /// <summary>
            /// Notification Hub resource type
            /// </summary>
            public const string NotificationHubs = "notificationhubs";
        }

        /// <summary>
        /// Storage service types
        /// </summary>
        public static class StorageServiceType
        {
            /// <summary>
            /// Blob service type
            /// </summary>
            public const string Blob = "blob";

            /// <summary>
            /// Table service type
            /// </summary>
            public const string Table = "table";

            /// <summary>
            /// Queue service type
            /// </summary>
            public const string Queue = "queue";
        }
    }
}


text:
def typeordercmp(a, b):
    return ordercmp(a, b, same_type=True)

def ordercmp(a, b, same_type=False):
    if same_type and a["type"] != b["type"]:
        return cmp(a["type"].lower(), b["type"].lower())
    a = a["location"]
    b = b["location"]
    # Reverse strand comes second
    if a["type"] != b["type"] and a["type"] == "complement":
        return 1
    apos, bpos = getpos(a, min), getpos(b, min)
    if apos == bpos:
        return getpos(a, max) - getpos(b, max)
    return apos - bpos

def coordoverlap(x1, y1, x2, y2):
    # TODO: Rewrite this with actual math and not
    # a crappy integer intersection.
    assert x1 <= y1 and x2 <= y2, "Invalid coordinates."
    s1 = set(range(x1, y1+1))
    s2 = set(range(x2, y2+1))
    i = s1.intersection(s2)
    return float(len(i)) / (float(len(s1) + len(s2)) - len(i))

def overlapcmp(a, b, jifactor=0.6, same_type=False):
    if same_type and a["type"] != b["type"]:
        return cmp(a["type"].lower(), b["type"].lower())
    a = a["location"]
    b = b["location"]
    amin, amax = getpos(a, min), getpos(a, max)
    bmin, bmax = getpos(b, min), getpos(b, max)
    res = coordoverlap(amin, amax, bmin, bmax)
    if res < jifactor:
        return amin - bmin
    else:
        return 0

def getpos(loc, op):
    if loc["type"] == "index":
        return loc["position"]
    elif loc["type"] in ["bond", "one-of"]:
        return op(loc["positions"])
    elif loc["type"] == "span":
        return op(loc["from"], loc["to"])
    elif loc["type"] in ["site", "choice"]:
        return op(loc["between"])
    elif loc["type"] == "gap":
        return None
    elif loc["type"] in ["complement", "reference"]:
        return getpos(loc["segment"], op)
    elif loc["type"] in ["join", "order"]:
        pos = map(lambda p: getpos(p, op), loc["segments"])
        pos = filter(lambda p: p is not None, pos)
        return op(pos)
    else:
        raise KeyError("Location %r has no 'type'." % loc)

def update_coords(loc, table):
    if loc["type"] == "index":
        loc["position"] = new_coord(loc["position"], table)
    elif loc["type"] in ["bond", "one-of"]:
        loc["positions"] = map(lambda p: new_coord(p, table), loc["positions"])
    elif loc["type"] == "span":
        loc["from"] = new_coord(loc["from"], table)
        loc["to"] = new_coord(loc["to"], table)
    elif loc["type"] in ["site", "choice"]:
        loc["between"] = map(lambda p: new_coord(p, table), loc["between"])
    elif loc["type"] == "gap":
        pass # Gaps aren't coordinates
    elif loc["type"] in ["complement", "reference"]:
        update_coords(loc["segment"], table)
    elif loc["type"] in ["join", "order"]:
        for seg in loc["segments"]:
            update_coords(seg, table)
    else:
        raise KeyError("Location %r has no 'type'." % loc)

def new_coord(pos, table):
    result = None
    for pair in table:
        if pos < pair[0] or pos > pair[1]:
            continue
        if result != None:
            raise ValueError("Coordinate maps to multiple positions.")
        result = pos - pair[0] + table[pair][0]
    if result == None:
        raise ValueError("Unable to map coordinate: %d" % pos)
    return result


text:
package models;

import javax.persistence.*;

@Entity
@Table(name = "results_prediction")
public class ResultPrediction {

    private Long id;
    private String prediction;

    public ResultPrediction() {
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Long getId() {
        return id;
    }

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

    @Basic
    public String getPrediction() {
        return prediction;
    }

    public void setPrediction(String prediction) {
        this.prediction = prediction;
    }
}


text:
module Enumerable
  def pluck(key)
    map { |element| element[key] }
  end
end unless Enumerable.method_defined? :pluck


text:
		<meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>blowdrycss - example site</title>
        <link rel="icon" type="image/x-icon" href="images/favicon.ico">
        <link rel="stylesheet" type="text/css" href="css/blowdry.min.css" />

Blow Dry CSS

Should have margin of 25px all the way around. Javascript class selector assignment.

            Testing
1 2 3


text:
<?php

namespace app\models\base;

use Yii;
use mootensai\behaviors\UUIDBehavior;

/**
 * This is the base model class for table "migration".
 *
 * @property string $version
 * @property integer $apply_time
 */
class Migration extends \yii\db\ActiveRecord
{
    use \mootensai\relation\RelationTrait;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['version'], 'required'],
            [['apply_time'], 'integer'],
            [['version'], 'string', 'max' => 180]
        ];
    }

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'migration';
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'version' => Yii::t('app', 'Version'),
            'apply_time' => Yii::t('app', 'Apply Time'),
        ];
    }

/**
     * @inheritdoc
     * @return array mixed
     */
    public function behaviors()
    {
        return [
            'uuid' => [
                'class' => UUIDBehavior::className(),
                'column' => 'id',
            ],
        ];
    }

    /**
     * @inheritdoc
     * @return \app\models\MigrationQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \app\models\MigrationQuery(get_called_class());
    }
}


text:
package org.wildfly.security.sasl.entity;

import static org.wildfly.security.asn1.ASN1.*;
import static org.wildfly.security.sasl.entity.Entity.*;
import static org.wildfly.security.x500.GeneralName.*;
import static org.wildfly.security.x500.TrustedAuthority.*;
import static org.wildfly.security._private.ElytronMessages.log;

import java.io.ByteArrayInputStream;
import java.io.Closeable;
import java.io.InputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.CertificateParsingException;
import java.security.cert.CertPath;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

import javax.security.auth.x500.X500Principal;

import org.wildfly.common.Assert;
import org.wildfly.security.asn1.ASN1Exception;
import org.wildfly.security.asn1.DERDecoder;
import org.wildfly.security.asn1.DEREncoder;
import org.wildfly.security.x500.GeneralName;
import org.wildfly.security.x500.TrustedAuthority;
import org.wildfly.security.x500.X500;
import org.wildfly.security.x500.X500PrincipalUtil;

/**
 * @author Farah Juma
 */
class EntityUtil {

    private static final byte[] randomCharDictionary;

    static {
        byte[] dict = new byte[93];
        int i = 0;
        for (byte c = '!'; c < ','; c ++) {
            dict[i ++] = c;
        }
        for (byte c = ',' + 1; c < 127; c ++) {
            dict[i ++] = c;
        }
        assert i == dict.length;
        randomCharDictionary = dict;
    }

    /* -- Methods used to encode ASN.1 data structures required for entity authentication -- */

    /**
     * Encode an ASN.1 set of certificates using the given DER encoder and the
     * given {@code X509Certificate} chain.
     *
     * @param encoder the DER encoder
     * @param certChain the X.509 certificate chain to encode
     * @throws ASN1Exception if an error occurs while encoding the given certificate chain
     */
    public static void encodeX509CertificateChain(final DEREncoder encoder, X509Certificate[] certChain) throws ASN1Exception {
        try {
            int chainSize = certChain.length;
            encoder.startSetOf();
            for (int i = 0; i < chainSize; i++) {
                encoder.writeEncoded(certChain[i].getEncoded());
            }
            encoder.endSetOf();
        } catch (CertificateEncodingException e) {
            throw new ASN1Exception(e);
        }
    }

    /**
     *

     * Encode an {@code AlgorithmIdentifier} without any parameters using the given
     * DER encoder and object identifier, where {@code AlgorithmIdentifier} is defined as:
     *
     *

     *      AlgorithmIdentifier  ::=  SEQUENCE  {
     *          algorithm      OBJECT IDENTIFIER,
     *          parameters     ANY DEFINED BY algorithm OPTIONAL
     *      }
     *

     *

     *
     * @param encoder the DER encoder
     * @param objectIdentifier the object identifier for the algorithm
     * @param omitParametersField {@code true} if the parameters field should be ommitted in
     * the encoding and {@code false} otherwise
     * @throws ASN1Exception if the given object identifier is invalid
     */
    public static void encodeAlgorithmIdentifier(final DEREncoder encoder, String objectIdentifier,
            boolean omitParametersField) throws ASN1Exception {
        encoder.startSequence();
        encoder.encodeObjectIdentifier(objectIdentifier);
        if (!omitParametersField) {
            encoder.encodeNull();
        }
        encoder.endSequence();
    }

    /**
     *

     * Encode an {@code AlgorithmIdentifier} using the given DER encoder, where
     * {@code AlgorithmIdentifier} is defined as:
     *
     *

     *      AlgorithmIdentifier  ::=  SEQUENCE  {
     *          algorithm      OBJECT IDENTIFIER,
     *          parameters     ANY DEFINED BY algorithm OPTIONAL
     *      }
     *

     *

     *
     * @param encoder the DER encoder
     * @param algorithm the algorithm name
     * @throws ASN1Exception if the given algorithm name is unrecognised
     */
    public static void encodeAlgorithmIdentifier(final DEREncoder encoder, String algorithm) throws ASN1Exception {
        // Determine whether or not the parameters field should be omitted in the encoding,
        // as specified in RFC 3279 (http://www.ietf.org/rfc/rfc3279)
        boolean omitParametersField;
        switch (algorithm) {
            case SHA1_WITH_RSA: {
                omitParametersField = false;
                break;
            }
            case SHA1_WITH_DSA:
            case SHA1_WITH_ECDSA: {
                omitParametersField = true;
                break;
            }
            default: throw log.asnUnrecognisedAlgorithm(algorithm);
        }
        encodeAlgorithmIdentifier(encoder, algorithmOid(algorithm), omitParametersField);
    }

    /**
     *

     * Encode a {@code GeneralNames} element using the given DER encoder, where
     * {@code GeneralNames} is defined as:
     *
     *

     *      GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
     *

     *

     *
     * @param encoder the DER encoder
     * @param generalNames the general names, as a {@code List} where each entry is a {@link GeneralName}
     * @throws ASN1Exception if any of the general names are invalid
     */
    public static void encodeGeneralNames(final DEREncoder encoder, List<GeneralName> generalNames) throws ASN1Exception {
        encoder.startSequence();
        for (GeneralName generalName : generalNames) {
            generalName.encodeTo(encoder);
        }
        encoder.endSequence();
    }

    /**
     * Encode a {@code GeneralNames} element consisting of one general name using
     * the given DER encoder.
     *
     * @param encoder the DER encoder
     * @param generalName the general name
     * @throws ASN1Exception if the general name is invalid
     */
    public static void encodeGeneralNames(final DEREncoder encoder, GeneralName generalName) throws ASN1Exception {
        List<GeneralName> generalNames = new ArrayList<GeneralName>(1);
        generalNames.add(generalName);
        encodeGeneralNames(encoder, generalNames);
    }

    public static void encodeGeneralNames(final DEREncoder encoder, String subjectName,
            Collection<List<?>> subjectAltNames) throws ASN1Exception {
        encoder.startSequence();
        if (! subjectName.isEmpty()) {
            new DirectoryName(subjectName).encodeTo(encoder);
        }
        if (subjectAltNames != null) {
            for (List<?> altName : subjectAltNames) {
                convertToGeneralName(altName).encodeTo(encoder);
            }
        }
        encoder.endSequence();
    }

    /**
     *

     * Encode a {@code RandomNumber} element using the given DER encoder, where
     * {@code RandomNumber} is defined as:
     *
     *

     *      RandomNumber ::= OCTET STRING (SIZE(8..MAX))
     *

     *

     *
     * @param encoder the DER encoder
     * @param secureRandom the secure random to use (may be null)
     */
    public static byte[] encodeRandomNumber(final DEREncoder encoder, SecureRandom secureRandom) {
        Random random = secureRandom != null ? secureRandom : ThreadLocalRandom.current();
        byte[] randomA = generateRandomString(48, random);
        encoder.encodeOctetString(randomA);
        return randomA;
    }

    public static byte[] generateRandomString(int length, Random random) {
        final byte[] chars = new byte[length];
        for (int i = 0; i < length; i ++) {
            chars[i] = randomCharDictionary[random.nextInt(93)];
        }
        return chars;
    }

    /**
     * Encode an ASN.1 sequence of trusted authorities using the given DER encoder.
     *
     * @param encoder the DER encoder
     * @param trustedAuthorities the trusted authorities as a {@code List} where each entry must
     * be a {@link NameTrustedAuthority}, a {@link CertificateTrustedAuthority}, or a {@link HashTrustedAuthority}
     * @throws ASN1Exception if any of the trusted authorities are invalid
     */
    public static void encodeTrustedAuthorities(final DEREncoder encoder,
            List<TrustedAuthority> trustedAuthorities) throws ASN1Exception {
        encoder.startSequence();
        for (TrustedAuthority trustedAuthority : trustedAuthorities) {
            trustedAuthority.encodeTo(encoder);
        }
        encoder.endSequence();
    }

    /* -- Methods used to decode ASN.1 data structures required for entity authentication -- */

    /**
     * Decode the next element from the given DER decoder as a {@code GeneralNames} element.
     *
     * @param decoder the DER decoder
     * @return the general names
     * @throws ASN1Exception if the next element from the given decoder is not a general names element
     */
    public static List<GeneralName> decodeGeneralNames(final DERDecoder decoder) throws ASN1Exception {
        List<GeneralName> generalNames = new ArrayList<GeneralName>();
        GeneralName generalName = null;
        decoder.startSequence();
        while (decoder.hasNextElement()) {
            out: {
                for (int generalNameType = 0; generalNameType <= 8; generalNameType++) {
                    switch (generalNameType) {
                        case OTHER_NAME:
                            if (decoder.isNextType(CONTEXT_SPECIFIC_MASK, generalNameType, true)) {
                                decoder.decodeImplicit(generalNameType);
                                decoder.startSequence();
                                String typeId = decoder.decodeObjectIdentifier();
                                byte[] encodedValue = decoder.drainElement();
                                decoder.endSequence();
                                generalName = new OtherName(typeId, encodedValue);
                                break out;
                            }
                            break;
                        case RFC_822_NAME:
                            if (decoder.isNextType(CONTEXT_SPECIFIC_MASK, generalNameType, false)) {
                                decoder.decodeImplicit(generalNameType);
                                generalName = new RFC822Name(decoder.decodeIA5String());
                                break out;
                            }
                            break;
                        case DNS_NAME:
                            if (decoder.isNextType(CONTEXT_SPECIFIC_MASK, generalNameType, false)) {
                                decoder.decodeImplicit(generalNameType);
                                generalName = new DNSName(decoder.decodeIA5String());
                                break out;
                            }
                            break;
                        case X400_ADDRESS:
                            if (decoder.isNextType(CONTEXT_SPECIFIC_MASK, generalNameType, true)) {
                                decoder.decodeImplicit(generalNameType);
                                generalName = new X400Address(decoder.drainElementValue(), true);
                                break out;
                            }
                            break;
                        case DIRECTORY_NAME:
                            if (decoder.isNextType(CONTEXT_SPECIFIC_MASK, generalNameType, true)) {
                                byte[] encodedName = decoder.drainElementValue();
                                generalName = new DirectoryName((new X500Principal(encodedName)).getName(X500Principal.CANONICAL));
                                break out;
                            }
                            break;
                        case EDI_PARTY_NAME:
                            if (decoder.isNextType(CONTEXT_SPECIFIC_MASK, generalNameType, true)) {
                                decoder.decodeImplicit(generalNameType);
                                generalName = new EDIPartyName(decoder.drainElementValue(), true);
                                break out;
                            }
                            break;
                        case URI_NAME:
                            if (decoder.isNextType(CONTEXT_SPECIFIC_MASK, generalNameType, false)) {
                                decoder.decodeImplicit(generalNameType);
                                generalName = new URIName(decoder.decodeIA5String());
                                break out;
                            }
                            break;
                        case IP_ADDRESS:
                            if (decoder.isNextType(CONTEXT_SPECIFIC_MASK, generalNameType, false)) {
                                decoder.decodeImplicit(generalNameType);
                                generalName = new IPAddress(decoder.decodeOctetString());
                                break out;
                            }
                            break;
                        case REGISTERED_ID:
                            if (decoder.isNextType(CONTEXT_SPECIFIC_MASK, generalNameType, false)) {
                                decoder.decodeImplicit(generalNameType);
                                generalName = new RegisteredID(decoder.decodeObjectIdentifier());
                                break out;
                            }
                            break;
                        default: throw log.asnInvalidGeneralNameType();
                    }
                }
            }
            generalNames.add(generalName);
        }
        decoder.endSequence();
        return generalNames;
    }

    /**
     * Decode the next element from the given DER decoder as an X.509 certificate chain.
     *
     * @param decoder the DER decoder
     * @return the X.509 certificate chain
     * @throws ASN1Exception if the next element from the given decoder is not an X.509
     * certificate chain or if an error occurs while decoding the X.509 certificate chain
     */
    public static X509Certificate[] decodeX509CertificateChain(final DERDecoder decoder) throws ASN1Exception {
        if (decoder.peekType() != SET_TYPE) {
            throw log.asnUnexpectedTag();
        }
        byte[] certChain = decoder.drainElement();
        try {
            CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
            certChain[0] = SEQUENCE_TYPE; // CertificateFactory#generateCertPath requires a DER SEQUE
            CertPath certPath = certFactory.generateCertPath(new ByteArrayInputStream(certChain));
            List<? extends Certificate> certs = certPath.getCertificates();
            return certs.toArray(new X509Certificate[certs.size()]);
        } catch (CertificateException e) {
            throw new ASN1Exception(e);
        }
    }

    /**
     *

     * Decode the next element from the given DER decoder as a {@code CertData} element,
     * which is defined as follows:
     *
     *

     *      CertData ::= CHOICE {
     *          certificateSet     SET SIZE (1..MAX) OF Certificate,
     *          certURL            IA5String
     *      }
     *

     *

     *
     * @param decoder the DER decoder
     * @return the X.509 certificate or certificate chain
     * @throws ASN1Exception if the next element from the given decoder is not a {@code CertData}
     * element or if an error occurs while decoding the certificate data
     */
    public static X509Certificate[] decodeCertificateData(final DERDecoder decoder) throws ASN1Exception {
        X509Certificate[] peerCertChain;
        if (decoder.peekType() == SET_TYPE) {
            peerCertChain = decodeX509CertificateChain(decoder);
        } else if (decoder.peekType() == IA5_STRING_TYPE) {
            try {
                X509Certificate peerCert = getCertificateFromUrl(decoder.decodeIA5String());
                peerCertChain = new X509Certificate[] {peerCert};
            } catch (IOException e) {
                throw log.asnUnableToReadCertificateData(e);
            }
        } else {
            throw log.asnUnexpectedTag();
        }
        return peerCertChain;
    }

    /**
     * Obtain an X509Certificate using the given URL.
     *
     * @param certUrl the URL to the X.509 certificate to use, as a string, must be a non-relative URL
     * @return the X.509 certificate
     * @throws IOException if the X.509 certificate cannot be obtained
     */
    public static X509Certificate getCertificateFromUrl(String certUrl) throws IOException {
        try {
            return getCertificateFromUrl(new URL(certUrl));
        } catch (MalformedURLException e) {
            throw log.asnUnableToReadCertificateFromUrl(certUrl, e);
        }
    }

    /**
     * Obtain an X509Certificate using the given URL.
     *
     * @param certUrl the URL to the X.509 certificate to use
     * @return the X.509 certificate
     * @throws IOException if the X.509 certificate cannot be obtained
     */
    public static X509Certificate getCertificateFromUrl(URL certUrl) throws IOException {
        Assert.checkNotNullParam("certUrl", certUrl);
        X509Certificate cert;
        InputStream in = null;
        try {
            in = certUrl.openStream();
            CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
            cert = (X509Certificate) certFactory.generateCertificate(in);
        } catch (CertificateException e) {
            throw log.asnUnableToReadCertificateFromUrl(certUrl.toString(), e);
        } finally {
            safeClose(in);
        }
        return cert;
    }

    /**
     * Decode the next element from the given DER decoder as a trusted authorities element.
     *
     * @param decoder the DER decoder
     * @return the trusted authorities
     * @throws ASN1Exception if the next element from the given decoder is not a trusted authorities
     * element or if an error occurs while decoding the trusted authorities element
     */
    public static List<TrustedAuthority> decodeTrustedAuthorities(final DERDecoder decoder) throws ASN1Exception {
        List<TrustedAuthority> trustedAuthorities = new ArrayList<TrustedAuthority>();
        TrustedAuthority trustedAuthority = null;
        decoder.startSequence();
        while (decoder.hasNextElement()) {
            out: {
                for (int trustedAuthorityType = 0; trustedAuthorityType <= 4; trustedAuthorityType++) {
                    switch (trustedAuthorityType) {
                        case AUTHORITY_NAME:
                            if (decoder.isNextType(CONTEXT_SPECIFIC_MASK, trustedAuthorityType, true)) {
                                byte[] encodedName = decoder.drainElementValue();
                                trustedAuthority = new NameTrustedAuthority((new X500Principal(encodedName)).getName(X500Principal.CANONICAL));
                                break out;
                            }
                            break;
                        case AUTHORITY_CERTIFICATE:
                            if (decoder.isNextType(CONTEXT_SPECIFIC_MASK, trustedAuthorityType, true)) {
                                decoder.decodeImplicit(trustedAuthorityType);
                                byte[] cert = decoder.drainElement();
                                cert[0] = SEQUENCE_TYPE; // Replace the trusted authority type tag with a DER SEQUENCE tag, as required by CertificateFactory#generateCertificate
                                try {
                                    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
                                    trustedAuthority = new CertificateTrustedAuthority((X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(cert)));
                                } catch (CertificateException e) {
                                    throw new ASN1Exception(e);
                                }
                                break out;
                            }
                            break;
                        case ISSUER_NAME_HASH:
                            if (decoder.isNextType(CONTEXT_SPECIFIC_MASK, trustedAuthorityType, false)) {
                                decoder.decodeImplicit(trustedAuthorityType);
                                trustedAuthority = new IssuerNameHashTrustedAuthority(decoder.decodeOctetString());
                                break out;
                            }
                            break;
                        case ISSUER_KEY_HASH:
                            if (decoder.isNextType(CONTEXT_SPECIFIC_MASK, trustedAuthorityType, false)) {
                                decoder.decodeImplicit(trustedAuthorityType);
                                trustedAuthority = new IssuerKeyHashTrustedAuthority(decoder.decodeOctetString());
                                break out;
                            }
                            break;
                        case PKCS_15_KEY_HASH:
                            if (decoder.isNextType(CONTEXT_SPECIFIC_MASK, trustedAuthorityType, false)) {
                                decoder.decodeImplicit(trustedAuthorityType);
                                trustedAuthority = new PKCS15KeyHashTrustedAuthority(decoder.decodeOctetString());
                                break out;
                            }
                            break;
                        default: throw log.asnInvalidGeneralNameType();
                    }
                }
            }
            trustedAuthorities.add(trustedAuthority);
        }
        decoder.endSequence();
        return trustedAuthorities;
    }

    public static boolean matchGeneralNames(List<GeneralName> generalNames,
            List<GeneralName> actualGeneralNames) {
        if ((generalNames == null) || (actualGeneralNames == null)) {
            return false;
        }
        for (GeneralName generalName : generalNames) {
            for (GeneralName actualGeneralName : actualGeneralNames) {
                if (matchGeneralName(generalName, actualGeneralName)) {
                    return true;
                }
            }
        }
        return false;
    }

    public static boolean matchGeneralName(GeneralName generalName, GeneralName actualGeneralName) {
        if ((generalName instanceof DNSName) && (actualGeneralName instanceof DirectoryName)) {
            // Check if the DNSName matches the DirectoryName's (most specific) Common Name field.
            // Although specifying a DNS name using the Common Name field has been deprecated, it is
            // still used in practice (e.g., see http://tools.ietf.org/html/rfc2818).
            String[] cnValues = X500PrincipalUtil.getAttributeValues(new X500Principal(((DirectoryName) actualGeneralName).getName()), X500.OID_AT_COMMON_NAME);
            String dnsName = ((DNSName) generalName).getName();
            return dnsName.equalsIgnoreCase(cnValues[0]);
        } else {
            return generalName.equals(actualGeneralName);
        }
    }

    public static boolean matchGeneralNames(List<GeneralName> generalNames, X509Certificate cert) {
        X500Principal certSubjectName = cert.getSubjectX500Principal();
        try {
            if (matchGeneralNames(generalNames, convertToGeneralNames(cert.getSubjectAlternativeNames()))) {
                return true;
            }
        } catch (CertificateParsingException e) {
            // Ignore unless the subject name is empty
            if (certSubjectName == null) {
                throw log.unableToDetermineSubjectName(e);
            }
        }
        List<GeneralName> certNames;
        if (certSubjectName != null) {
            certNames = new ArrayList<GeneralName>(1);
            certNames.add(new DirectoryName(certSubjectName.getName(X500Principal.CANONICAL)));
            if (matchGeneralNames(generalNames, certNames)) {
                return true;
            }
        }
        return false;
    }

    public static String getDistinguishedNameFromGeneralNames(List<GeneralName> generalNames) {
        for (GeneralName generalName : generalNames) {
            if (generalName instanceof DirectoryName) {
                return ((DirectoryName) generalName).getName();
            }
        }
        return null;
    }

    private static GeneralName convertToGeneralName(List<?> generalName) throws ASN1Exception {
        int type = ((Integer) generalName.get(0)).intValue();
        Object name = generalName.get(1);
        switch (type) {
            case OTHER_NAME:
                return new OtherName((byte[]) name);
            case RFC_822_NAME:
                return new RFC822Name((String) name);
            case DNS_NAME:
                return new DNSName((String) name);
            case X400_ADDRESS:
                return new X400Address((byte[]) name);
            case DIRECTORY_NAME:
                return new DirectoryName((String) name);
            case EDI_PARTY_NAME:
                return new EDIPartyName((byte[]) name);
            case URI_NAME:
                return new URIName((String) name);
            case IP_ADDRESS:
                return new IPAddress((String) name);
            case REGISTERED_ID:
                return new RegisteredID((String) name);
            default: throw log.asnInvalidGeneralNameType();
        }
    }

    private static List<GeneralName> convertToGeneralNames(Collection<List<?>> generalNames) throws ASN1Exception {
        if (generalNames == null) {
            return null;
        }
        List<GeneralName> convertedGeneralNames = new ArrayList<GeneralName>();
        for (List<?> generalName : generalNames) {
            convertedGeneralNames.add(convertToGeneralName(generalName));
        }
        return convertedGeneralNames;
    }

    private static void safeClose(Closeable c) {
        if (c != null) {
            try {
                c.close();
            } catch (Throwable ignored) {}
        }
    }
}


text:
package net.jadecy.utils;

import java.util.ArrayList;
import java.util.Collection;

import junit.framework.TestCase;

public class ComparableArrayListTest extends TestCase {

    //--------------------------------------------------------------------------
    // PUBLIC METHODS
    //--------------------------------------------------------------------------

    public void test_ComparableArrayList() {
        final ComparableArrayList<Integer> list1 = new ComparableArrayList<Integer>();
        list1.add(1);

        final ComparableArrayList<Integer> list2 = new ComparableArrayList<Integer>();
        list2.add(2);

        // Default comparator.
        assertEquals(-1, list1.compareTo(list2));
    }

    public void test_ComparableArrayList_Collection() {
        final Collection<Integer> coll = new ArrayList<Integer>();
        coll.add(1);
        coll.add(3);
        coll.add(2);

        final ComparableArrayList<Integer> list = new ComparableArrayList<Integer>(coll);
        assertEquals(3, list.size());
        assertEquals((Integer) 1, list.get(0));
        assertEquals((Integer) 3, list.get(1));
        assertEquals((Integer) 2, list.get(2));
    }

    public void test_compareTo_L1ShorterSoInferior() {
        final ComparableArrayList<Integer> list1 = new ComparableArrayList<Integer>();
        list1.add(17);

        final ComparableArrayList<Integer> list2 = new ComparableArrayList<Integer>();
        list2.add(1);
        list2.add(2);

        assertEquals(-1, list1.compareTo(list2));
    }

    public void test_compareTo_L1LongerSoSuperior() {
        final ComparableArrayList<Integer> list1 = new ComparableArrayList<Integer>();
        list1.add(1);
        list1.add(2);

        final ComparableArrayList<Integer> list2 = new ComparableArrayList<Integer>();
        list2.add(17);

        assertEquals(1, list1.compareTo(list2));
    }

    public void test_compareTo_L1Equal() {
        final ComparableArrayList<Integer> list1 = new ComparableArrayList<Integer>();
        list1.add(1);
        list1.add(2);

        final ComparableArrayList<Integer> list2 = new ComparableArrayList<Integer>();
        list2.add(1);
        list2.add(2);

        assertEquals(0, list1.compareTo(list2));
    }

    public void test_compareTo_L1Inferior() {
        final ComparableArrayList<Integer> list1 = new ComparableArrayList<Integer>();
        list1.add(1);
        list1.add(2);

        final ComparableArrayList<Integer> list2 = new ComparableArrayList<Integer>();
        list2.add(1);
        list2.add(3);

        assertEquals(-1, list1.compareTo(list2));
    }

    public void test_compareTo_L1Superior() {
        final ComparableArrayList<Integer> list1 = new ComparableArrayList<Integer>();
        list1.add(1);
        list1.add(3);

        final ComparableArrayList<Integer> list2 = new ComparableArrayList<Integer>();
        list2.add(1);
        list2.add(2);

        assertEquals(1, list1.compareTo(list2));
    }
}


text:
namespace callbacks
{
// Callbacks must be non-blocking (avoid 'delay')
//
// modular_device.getParameterValue must be cast to either:
// const char *
// long
// double
// bool
// ArduinoJson::JsonArray &
// ArduinoJson::JsonObject &
//
// For more info read about ArduinoJson parsing https://github.com/janelia-arduino/ArduinoJson
//
// modular_device.getSavedVariableValue type must match the saved variable default type
// modular_device.setSavedVariableValue type must match the saved variable default type

void getLedsPoweredCallback()
{
  bool leds_powered = controller.getLedsPowered();
  modular_device.addToResponse("leds_powered",leds_powered);
}

void setMfcFlowCallback()
{
  long mfc = modular_device.getParameterValue(constants::mfc_parameter_name);
  long percent = modular_device.getParameterValue(constants::percent_parameter_name);
  controller.setMfcFlow(mfc,percent);
}

void setMfcFlowsCallback()
{
  ArduinoJson::JsonArray & percents_array = modular_device.getParameterValue(constants::percents_parameter_name);
  int mfc = 0;
  for (ArduinoJson::JsonArray::iterator it=percents_array.begin();
       it != percents_array.end();
       ++it)
  {
    long percent = *it;
    controller.setMfcFlow(mfc,percent);
    mfc++;
  }
}

void getMfcFlowSettingCallback()
{
  long mfc = modular_device.getParameterValue(constants::mfc_parameter_name);
  uint8_t percent = controller.getMfcFlowSetting(mfc);
  modular_device.addToResponse("percent",percent);
}

void getMfcFlowSettingsCallback()
{
  modular_device.addKeyToResponse("percents");
  modular_device.startResponseArray();
  for (int mfc=0; mfc<constants::MFC_COUNT; mfc++)
  {
    uint8_t percent = controller.getMfcFlowSetting(mfc);
    modular_device.addToResponse(percent);
  }
  modular_device.stopResponseArray();
}

void getMfcFlowMeasureCallback()
{
  long mfc = modular_device.getParameterValue(constants::mfc_parameter_name);
  uint8_t percent = controller.getMfcFlowMeasure(mfc);
  modular_device.addToResponse("percent",percent);
}

void getMfcFlowMeasuresCallback()
{
  modular_device.addKeyToResponse("percents");
  modular_device.startResponseArray();
  for (int mfc=0; mfc<constants::MFC_COUNT; mfc++)
  {
    uint8_t percent = controller.getMfcFlowMeasure(mfc);
    modular_device.addToResponse(percent);
  }
  modular_device.stopResponseArray();
}

void getAnalogInputCallback()
{
  long ain = modular_device.getParameterValue(constants::ain_parameter_name);
  uint8_t percent = controller.getAnalogInput(ain);
  modular_device.addToResponse("percent",percent);
}

void getAnalogInputsCallback()
{
  modular_device.addKeyToResponse("percents");
  modular_device.startResponseArray();
  for (int ain=0; ain<constants::AIN_COUNT; ain++)
  {
    uint8_t percent = controller.getAnalogInput(ain);
    modular_device.addToResponse(percent);
  }
  modular_device.stopResponseArray();
}

void saveStateCallback()
{
  long state = modular_device.getParameterValue(constants::state_parameter_name);
  controller.saveState(state);
}

void recallStateCallback()
{
  long state = modular_device.getParameterValue(constants::state_parameter_name);
  controller.recallState(state);
}

void getSavedStatesCallback()
{
  uint8_t states_array[constants::STATE_COUNT][constants::MFC_COUNT];
  controller.getStatesArray(states_array);
  modular_device.addKeyToResponse("saved_states");
  modular_device.startResponseArray();
  for (int state=0; state<constants::STATE_COUNT; state++)
  {
    modular_device.startResponseArray();
    for (int mfc=0; mfc<constants::MFC_COUNT; mfc++)
    {
      modular_device.addToResponse(states_array[state][mfc]);
    }
    modular_device.stopResponseArray();
  }
  modular_device.stopResponseArray();
}

void pulseBncBCallback()
{
  long duration = modular_device.getParameterValue(constants::duration_parameter_name);
  EventController::event_controller.addPwmUsingDelayPeriodOnDuration(setBncBHighCallback,
                                                                     setBncBLowCallback,
                                                                     5,
                                                                     1,
                                                                     duration,
                                                                     1,
                                                                     0,
                                                                     NULL,
                                                                     NULL);
}

// Standalone Callbacks
void executeStandaloneCallbackCallback()
{
  controller.executeStandaloneCallback();
}

void saveStateStandaloneCallback()
{
  uint8_t state = controller.getStateIntVar();
  controller.saveState(state);
}

void recallStateStandaloneCallback()
{
  uint8_t state = controller.getStateIntVar();
  controller.recallState(state);
}

void pulseBncBStandaloneCallback()
{
  uint16_t duration = controller.getDurationIntVar();
  EventController::event_controller.addPwmUsingDelayPeriodOnDuration(setBncBHighCallback,
                                                                     setBncBLowCallback,
                                                                     5,
                                                                     1,
                                                                     duration,
                                                                     1,
                                                                     0,
                                                                     NULL,
                                                                     NULL);
}

// EventController Callbacks

void setBncBHighCallback(int index)
{
  digitalWrite(constants::bnc_b_pin,HIGH);
}

void setBncBLowCallback(int index)
{
  digitalWrite(constants::bnc_b_pin,LOW);
}
}


text:
window.Helper = {
    loop: (func, time, total) => {
        let interval = setInterval(func, time);
        setTimeout(() => {
            clearInterval(interval);
        }, total);
    }
};


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>libsudoku: /Users/tristan/Coding/sudoku-solver/include/tcb Directory Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

libsudoku

Simple Sudoku Solver library

include

tcb

tcb Directory Reference

Files

file  	sudoku.h [code]

file  	sudoku.hpp [code]

<address class="footer">
Generated by

 1.8.13
</address>


text:
namespace views {
class Label;
class Textarea;
class View;
}  // namespace views

namespace views {
class Label;
class Textarea;
class View;
class MenuRunner;
}

namespace ui {
class MenuModel;
}

// View of a user note in the side panel in multiple states. The view in the
// default state draws a label with a date, a menu button, and a label with a
// text. The view in creating state draws a textarea, and two buttons (cancel
// and add). The view in the edit state is similar to the creating state but
// sets a text in the textarea. Lastly, the view in the orphaned state is
// similar to the default state but draws an additional label.
class UserNoteView : public views::View {
 public:
  enum class State {
    // State that will display an existing user note.
    kDefault,
    // State that will display a new user note.
    kCreating,
    // State that will display an existing user note to be edited.
    kEditing,
    // State that will display a detached user note (note without a highlight
    // on the page).
    kDetached
  };

  explicit UserNoteView(
      UserNoteUICoordinator* coordinator,
      user_notes::UserNoteInstance* user_note_instance,
      UserNoteView::State state = UserNoteView::State::kDefault);
  UserNoteView(const UserNoteView&) = delete;
  UserNoteView& operator=(const UserNoteView&) = delete;
  ~UserNoteView() override;

  const base::UnguessableToken& user_note_id() { return id_; }

  const gfx::Rect& user_note_rect() const { return rect_; }

  // views::View:
  // TODO(crbug.com/1313967): Keyboard navigation and touchscreens are currently
  // not handled.
  bool OnMousePressed(const ui::MouseEvent& event) override;

 private:
  void CreateOrUpdateNoteView(UserNoteView::State state,
                              base::Time date,
                              const std::u16string content,
                              const std::u16string quote);
  void OnCancelUserNote(UserNoteView::State state);
  void OnAddUserNote();
  void OnSaveUserNote();
  void OnOpenMenu();
  void OnMenuClosed();
  void OnEditUserNote(int event_flags);
  void OnDeleteUserNote(int event_flags);
  void OnLearnUserNote(int event_flags);
  void SetCreatingOrEditState(const std::u16string content,
                              UserNoteView::State state);
  void SetDefaultOrDetachedState(base::Time date,
                                 const std::u16string content,
                                 const std::u16string quote);

  raw_ptr<user_notes::UserNoteInstance> user_note_instance_;
  raw_ptr<views::Textarea> text_area_ = nullptr;
  raw_ptr<views::View> button_container_ = nullptr;
  raw_ptr<views::Label> user_note_body_ = nullptr;
  raw_ptr<views::View> user_note_header_ = nullptr;
  raw_ptr<views::View> user_note_quote_ = nullptr;
  raw_ptr<UserNoteUICoordinator> coordinator_ = nullptr;
  std::unique_ptr<views::MenuRunner> menu_runner_;
  std::unique_ptr<ui::MenuModel> dialog_model_;
  base::UnguessableToken id_;
  gfx::Rect rect_;
};

#endif  // CHROME_BROWSER_UI_VIEWS_SIDE_PANEL_USER_NOTE_USER_NOTE_VIEW_H_


text:
@implementation UINavigationBar (CMKit)

- (void)setTransparent:(BOOL)transparent {
    [self setTransparent:transparent translucent:YES];
}

- (void)setTransparent:(BOOL)transparent translucent:(BOOL)translucent {
    if (transparent) {
        [self setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
        self.shadowImage = [UIImage new];
        self.translucent = translucent;
    } else {
        [self setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
        self.shadowImage = nil;
        self.translucent = translucent;
    }
}

@end


text:
// src/polyfills.js must be the first import.
import '../polyfills';

import {draw3p, init} from '../integration-lib';
import {register} from '../3p';

import {mathml} from '../mathml';

init(window);
register('mathml', mathml);

window.draw3p = draw3p;


text:
import Measure from './measure.js';

/**
 * Parse a song from an Object.
 * @param {Object} songData The song to load.
 * @param {String} [songData.title] Title of the song.
 * @param {String} [songData.composer] Composer of the song.
 * @param {Number[]} [songData.timeSignature] Time Signature of the song, an
 * Array of 2 integers.
 * @param {String} [songData.key] Original key of the song.
 * @param {Number|String} [songData.transpose] Key to transpose to, or integer
 * of semitones to transpose by.
 * @param {Array.<null, Array>} [songData.chords] The chords array to parse.
 * @class
 * @public
 */
export default function Song(songData) {

  /**
   * A list of measures and nulls, in order. Null represents a newline.
   * @type {?Measure[]}
   * @public
   */
  this.measures = [];

  /**
   * Append a measure to the piece
   * @param {Object} measureToParse Pseudo-measure object to parse.
   * @param {?Number} index Optional: Index for the new measure.
   * @return {Measure} The generated measure.
   * @public
   */
  this.addMeasure = function(measureToParse, index) {
    return new Measure(this, index, measureToParse);
  };

  /**
   * Change the transposition.
   * @param {Number|String} transpose Key to transpose to, or integer of
   * semitones to transpose by.
   * @public
   */
  this.setTranspose = function(transpose) {
    if(Number.isInteger(transpose)) {
      this.transpose = transpose % 12;
    } else {
      let orig_chord = Tonal.Chord.tokenize(this.key);
      let new_chord = Tonal.Chord.tokenize(transpose);
      this.transpose = Tonal.Distance.semitones(
        orig_chord[0],
        new_chord[0]
      );
      this.transposeInt = Tonal.Interval.fromSemitones(this.transpose);
      /*if(orig_chord.quality != new_chord.quality) {
        // for example, if the song is in CM and user transposes to Am
        // if you try to transpose to not Major/Minor I'll cry.
        if(new_chord.quality == 'Minor') {
          this.transpose = (this.transpose + 3) % 12;
        } else {
          this.transpose = (this.transpose - 3) % 12;
        }
      }*/
    }
  };

  /**
   * Get the transposed key of the song.
   * @returns {String} the transposed key.
   * @public
   */
  this.getTransposedKey = function() {
    return Tonal.Note.pc(
      Tonal.transpose(this.key, Tonal.Interval.fromSemitones(this.transpose))
    );
  };

  /**
   * Parse a song from an Array of pseudo-measure objects.
   * @param {Array.<Object>} array The array to parse into a song.
   * @public
   */
  this.parseMeasureArray = function(array) {
    for(let measure of array) {
      if(measure) {
        this.addMeasure(measure, null);
      }
    }
  };

  /**
   * Title of the song.
   * @type {String}
   */
  this.title = songData.title || '';
  /**
   * Composer of the song.
   * @type {String}
   */
  this.composer = songData.composer || '';
  /**
   * Time signature of the song.
   * @type {Number[]}
   */
  this.timeSignature = songData.timeSignature || [4,4];
  /**
   * Key of the song. A chord name.
   * @type {String}
   */
  this.key = songData.key || 'C'; // stop judging me ok
  /**
   * Number of semitones to transpose by -- an integer mod 12.
   * @type {Number}
   */
  this.transpose = 0;

  if(songData.transpose !== undefined) this.setTranspose(songData.transpose);

  if(songData.measures) {
    this.parseMeasureArray(songData.measures);
  } else {
    const emptyMeasure = {beats: (new Array(this.timeSignature[0])).fill(null)};
    const emptyData = (new Array(8)).fill(emptyMeasure);
    this.parseMeasureArray(emptyData);
  }

  this.serialize = function() {
    const out = {
      title: this.title,
      composer: this.composer,
      timeSignature: this.timeSignature,
      key: this.key,
      transpose: this.transpose,
      measures: this.measures.map(measure => {
        const mout = {
          beats: measure._beats
        };
        Object.keys(measure.attributes).forEach(attrName => {
          if(measure.attributes.hasOwnProperty(attrName)) {
            mout[attrName] = measure.attributes[attrName];
          }
        });
        return mout;
      })
    };

    return out;
  };
}


text:
#ifndef MARKOVEDITORWIDGET_H
#define MARKOVEDITORWIDGET_H

#include <QPlainTextEdit>
#include <QSyntaxHighlighter>

#include "Logic/CompilerError.h"
#include "Logic/MarkovAlgorithm.h"

class LineNumberArea;

class MarkovEditorWidget : public QPlainTextEdit
{
    Q_OBJECT

public:
    explicit MarkovEditorWidget(QWidget *parent = 0);
    ~MarkovEditorWidget();

    void lineNumberAreaPaintEvent(QPaintEvent *event);
    int lineNumberAreaWidth();
    void breakPointPress(QMouseEvent* event);

public slots:

    /**
     * @brief when source code from file is loaded this slot will be called.
     * Source code should be put to QTextEditor.
     * @param source_code
     * @param user_change if true then change in source will be treated
     * like user has changet id
     */
    void newSourceCode(QString source_code, bool system_change=true);

    /**
     * @brief the text which is selected should be deleted.
     */
    void deleteSelection();

    /**
     * @brief highlights line with light blue color.
     * Only one line can be highlighted in given time.
     * @param line_number
     */
    void showLineHighlight(int line_number);

    /**
     * @brief removes highlight from the line.
     */
    void removeLineHighlight();

protected:
    void resizeEvent(QResizeEvent *event);
    void keyPressEvent ( QKeyEvent * e );
signals:
    /**
     * @brief if any changes where done to source code
     * @param source_code
     */
    void sourceCodeChanged(QString source_code);

    /**
     * @brief if algorithm was updated
     */
    void markovAlgorithmChanged(MarkovAlgorithm algorithm);

    /**
     * @brief  when _can_run changes.
     */
    void canRun(bool);

    void breakPointAdded(int line_number);
    void breakPointRemoved(int line_number);

    /**
     * @brief when user sets cursor to the line with error
     * @param line_number
     * @param error
     */
    void lineFocusWithError(int line_number, CompilerError error);// -

    /**
     * @brief when user sets cursor to the line without error
     * @param line_number
     */
    void lineFocusWithoutError(int line_number);
private:
    void toggleBreakPoint(int line_number);
    void notifyAboutCurrentLineErrors();
    void setCanRun(bool new_value);

    /**
     * @brief list of errors which are in source code
     */
    QVector<CompilerError> _errors;
    /**
     * @brief last successfully parsed algorithm
     */
    MarkovAlgorithm _algorithm;

    /**
     * @brief list of active break points
     */
    QSet<int> _breakpoints;

    /**
     * @brief if the are no errors it should be true and false otherwise.
     * When changed canRun should be emitted.
     * MUST BE CHANGED ONLY BY setCanRun(bool)
     */
    bool _can_run;

    QString _last_source_code;

    QSet<int> _lines_with_errors;
    QMap<int, CompilerError> _errors_map;

    QWidget *lineNumberArea;
    QPair<int, int> m_countCache;
    QFont _line_number_font;
    QFontMetrics _line_number_metrics;
    int _current_line;
    int _highlighted_number;

    class MarkovHighliter : public QSyntaxHighlighter
    {
    public:
        MarkovHighliter(MarkovEditorWidget *editor);
        void highlightBlock(const QString & text);
    private:
        MarkovEditorWidget* _editor;
    };

    MarkovHighliter _highlighter;
    int getSelectedLines(QTextCursor cursor);
private slots:
    void userChangedSourceCode();
    void updateErrors();

    void updateLineNumberAreaWidth();
    void highlightCurrentLine();
    void updateLineNumberArea(const QRect &, int);
};

class LineNumberArea : public QWidget
{
public:
    LineNumberArea(MarkovEditorWidget *editor) : QWidget(editor) {
        codeEditor = editor;
    }

    QSize sizeHint() const {
        return QSize(codeEditor->lineNumberAreaWidth(), 0);
    }

protected:
    void paintEvent(QPaintEvent *event) {
        codeEditor->lineNumberAreaPaintEvent(event);
    }

    void mousePressEvent(QMouseEvent * event)
    {
        codeEditor->breakPointPress(event);
    }

private:
    MarkovEditorWidget *codeEditor;
};

#endif // MARKOVEDITORWIDGET_H


text:
<?php

/**
 * Provides save function to edit screen.
 */

$this->require_acl ('admin', 'translator');
$this->restful (new Translator ());


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace CJia.Parking.Views
{
    public interface IPaymentView : CJia.Parking.Tools.IView
    {
        /// <summary>
        /// 初始化事件
        /// </summary>
        event EventHandler<Views.PaymentArgs> OnInit;

        /// <summary>
        /// 保存事件
        /// </summary>
        event EventHandler<Views.PaymentArgs> OnReCharge;

        /// <summary>
        /// 会员点击聚焦
        /// </summary>
        event EventHandler<Views.PaymentArgs> OnPaylogFocusedRowChanged;

        ///// <summary>
        ///// 重新加载会员信息
        ///// </summary>
        //event EventHandler<Views.PaymentArgs> OnRefreshMem;

        /// <summary>
        /// 绑定界面会员Grid
        /// </summary>
        /// <param name="dtMemType"></param>
        void ExeGridMember(DataTable dtMember);

        /// <summary>
        /// 绑定下拉会员类型
        /// </summary>
        /// <param name="dtMemType"></param>
        void ExeDropMemType(DataTable dtMemType);

        /// <summary>
        /// 绑定会员日志记录
        /// </summary>
        /// <param name="dtMemPaylog"></param>
        void ExeGridMemPaylog(DataTable dtMemPaylog);
    }

    public class PaymentArgs : EventArgs
    {
        /// <summary>
        /// 缴费流水号
        /// </summary>
        public long PayLogId;

        /// <summary>
        /// 会员ID
        /// </summary>
        public long MemId;

        /// <summary>
        /// 会员姓名
        /// </summary>
        public string MemName;

        /// <summary>
        /// 会员类型ID
        /// </summary>
        public long MemTypeId;

        /// <summary>
        /// 免费停车时长
        /// </summary>
        public string FreeTime;

        /// <summary>
        /// 缴费金额
        /// </summary>
        public double PayAmount;

        ///// <summary>
        ///// 缴费日期
        ///// </summary>
        //public DateTime PayDate;

        /// <summary>
        /// 开始计费日期
        /// </summary>
        public DateTime StartDate;

        /// <summary>
        /// 有效日期
        /// </summary>
        public DateTime EffectiveDate;

    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <gradient
        android:angle="270"
        android:centerColor="#d3d7d4"
        android:endColor="#d3d7d4"
        android:startColor="#d9d6c3" />
    <stroke android:width="1dip"
        android:color="#d1c7b7"></stroke>
</shape>


text:
* [accessibility](ts.symbolvisibilityresult.md#accessibility)
* [aliasesToMakeVisible](ts.symbolvisibilityresult.md#aliasestomakevisible)
* [errorNode](ts.symbolvisibilityresult.md#errornode)
* [errorSymbolName](ts.symbolvisibilityresult.md#errorsymbolname)

## Properties

### accessibility: [SymbolAccessibility](../enums/ts.symbolaccessibility.md)

* Defined in [lib/typescript/tsc.d.ts:1115](https://github.com/kimamula/typedoc/blob/HEAD/src/lib/typescript/tsc.d.ts#L1115)

### Optional aliasesToMakeVisible: [AnyImportSyntax](../modules/ts.md#anyimportsyntax)[]

* Defined in [lib/typescript/tsc.d.ts:1116](https://github.com/kimamula/typedoc/blob/HEAD/src/lib/typescript/tsc.d.ts#L1116)

### Optional errorNode: [Node](ts.node.md)

* Defined in [lib/typescript/tsc.d.ts:1118](https://github.com/kimamula/typedoc/blob/HEAD/src/lib/typescript/tsc.d.ts#L1118)

### Optional errorSymbolName: string

* Defined in [lib/typescript/tsc.d.ts:1117](https://github.com/kimamula/typedoc/blob/HEAD/src/lib/typescript/tsc.d.ts#L1117)

Generated using [TypeDoc](http://typedoc.io)


text:
#if defined(_WIN32)

#define UNICODE

#include <windows.h>
#include <Windowsx.h>
#include <Uxtheme.h>
#include <Switch/Undef.hpp>
#include "WindowProcedureApiWin32.hpp"
#include "../../include/Switch/System/Windows/Forms/Form.hpp"
#include "../../include/Switch/System/Windows/Forms/Screen.hpp"

using namespace System;
using namespace System::Windows::Forms;

void Native::FormApi::Close(System::Windows::Forms::Form& form) {
  CloseWindow((HWND)form.Handle());
}

intptr Native::FormApi::Create(System::Windows::Forms::Form& form, bool withClientsize) {
  System::Drawing::Rectangle bounds = form.Bounds;
  bounds.X = bounds.X + Screen::AllScreens()[0].WorkingArea().X;
  bounds.Y = bounds.Y + Screen::AllScreens()[0].WorkingArea().Y;

  switch (form.StartPosition) {
  case FormStartPosition::CenterScreen: bounds = System::Drawing::Rectangle((Screen::AllScreens()[0].WorkingArea().Width + Screen::AllScreens()[0].WorkingArea().X - form.Width) / 2, (Screen::AllScreens()[0].WorkingArea().Height + Screen::AllScreens()[0].WorkingArea().Y - form.Height) / 2, form.Width, form.Height); break;
  case FormStartPosition::Manual: bounds = form.Bounds; break;
  case FormStartPosition::WindowsDefaultBounds: bounds = Drawing::Rectangle(CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT); break;
  case FormStartPosition::CenterParent:
  case FormStartPosition::WindowsDefaultLocation: bounds = Drawing::Rectangle(CW_USEDEFAULT, CW_USEDEFAULT, withClientsize ? form.ClientSize().Width() : form.Width(), withClientsize ? form.ClientSize().Height() : form.Height()); break;
  }

  HWND handle = CreateWindowEx(0, WC_DIALOG, form.Text().w_str().c_str(), WS_OVERLAPPED | WS_CAPTION | WS_CLIPSIBLINGS | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_GROUP, bounds.Left, bounds.Top, bounds.Width, bounds.Height, NULL, (HMENU)0, GetModuleHandle(NULL), (LPVOID)NULL);
  WindowProcedure::DefWindowProcs[(intptr)handle] = (WNDPROC)SetWindowLongPtr(handle, GWLP_WNDPROC, (LONG_PTR)WindowProcedure::WndProc);

  if (withClientsize) {
    RECT rect = { 0, 0, form.ClientSize().Width, form.ClientSize().Height };
    AdjustWindowRectEx(&rect, GetWindowLong(handle, GWL_STYLE), false /*menu == null*/, GetWindowLong(handle, GWL_EXSTYLE));
    form.Size = System::Drawing::Size(rect.right - rect.left, rect.bottom - rect.top);
    if (form.StartPosition == FormStartPosition::CenterScreen)
      bounds = System::Drawing::Rectangle((Screen::AllScreens()[0].WorkingArea().Width + Screen::AllScreens()[0].WorkingArea().X - form.Width) / 2, (Screen::AllScreens()[0].WorkingArea().Height + Screen::AllScreens()[0].WorkingArea().Y - form.Height) / 2, form.Width, form.Height);
    else {
      RECT actualRect = { 0, 0, 0, 0 };
      GetWindowRect(handle, &actualRect);
      bounds = System::Drawing::Rectangle(actualRect.left, actualRect.top, form.Width, form.Height);
    }
    form.Location = System::Drawing::Point(bounds.Left, bounds.Top);
    form.Size = System::Drawing::Size(bounds.Width, bounds.Height);
  } else {
    RECT actualRect = { 0, 0, 0, 0 };
    GetWindowRect(handle, &actualRect);
    form.Location = System::Drawing::Point(actualRect.left, actualRect.top);
    form.Size = System::Drawing::Size(actualRect.right - actualRect.left, actualRect.bottom - actualRect.top);
  }

  return (intptr)handle;
}

System::Drawing::Size Native::FormApi::GetDefaultSize() {
  return System::Drawing::Size(300, 300);
}

#endif


text:
/* tslint:disable:max-classes-per-file */
import {expect} from 'chai';
import {addAssociation, addForeignKey, getAssociations, getForeignKeys} from "../../../lib/services/association";
import {Model} from "../../../lib/models/Model";

describe('service.association', () => {

  describe('addAssociation', () => {

    it('should add association to target metadata', () => {
      const target = {};
      const RELATION = 'hasMany';
      const AS_NAME = 'test';
      const RELATED_CLASS_GETTER = () => class T extends Model<T> {};
      addAssociation(target, RELATION, RELATED_CLASS_GETTER, AS_NAME);
      const associations = getAssociations(target);

      expect(associations).to.have.property('length', 1);
      expect(associations[0]).to.eql({
        relation: RELATION,
        options: {},
        through: undefined,
        throughClassGetter: undefined,
        as: AS_NAME,
        relatedClassGetter: RELATED_CLASS_GETTER,
      });
    });

    it('should add association to target metadata, but not parent', () => {
      const parent = {};
      const target = Object.create(parent);
      const RELATION = 'hasMany';
      const PARENT_RELATION = 'belongsToMany';
      const AS_NAME = 'test';
      const RELATED_CLASS_GETTER = () => class T extends Model<T> {};
      addAssociation(parent, PARENT_RELATION, RELATED_CLASS_GETTER, AS_NAME);
      addAssociation(target, RELATION, RELATED_CLASS_GETTER, AS_NAME);

      const associations = getAssociations(target);
      expect(associations).to.have.property('length', 2);
      expect(associations[0]).to.eql({
        relation: PARENT_RELATION,
        options: {},
        through: undefined,
        throughClassGetter: undefined,
        as: AS_NAME,
        relatedClassGetter: RELATED_CLASS_GETTER,
      });
      expect(associations[1]).to.eql({
        relation: RELATION,
        options: {},
        through: undefined,
        throughClassGetter: undefined,
        as: AS_NAME,
        relatedClassGetter: RELATED_CLASS_GETTER,
      });

      const parentAssociations = getAssociations(parent);
      expect(parentAssociations).to.have.property('length', 1);
      expect(parentAssociations[0]).to.eql({
        relation: PARENT_RELATION,
        options: {},
        through: undefined,
        throughClassGetter: undefined,
        as: AS_NAME,
        relatedClassGetter: RELATED_CLASS_GETTER,
      });
    });

  });

  describe('addForeignKey', () => {

    it('should add foreign key to target metadata', () => {
      const target = {};
      const FOREIGN_KEY = 'testId';
      const RELATED_CLASS_GETTER = () => class T extends Model<T> {};
      addForeignKey(target, RELATED_CLASS_GETTER, FOREIGN_KEY);
      const foreignKeys = getForeignKeys(target);

      expect(foreignKeys).to.have.property('length', 1);
      expect(foreignKeys[0]).to.eql({
        foreignKey: FOREIGN_KEY,
        relatedClassGetter: RELATED_CLASS_GETTER,
      });
    });

    it('should add foreign key to target metadata, but not parent', () => {
      const parent = {};
      const target = Object.create(parent);
      const FOREIGN_KEY = 'testId';
      const PARENT_FOREIGN_KEY = 'parentTestId';
      const RELATED_CLASS_GETTER = () => class T extends Model<T> {};
      addForeignKey(parent, RELATED_CLASS_GETTER, PARENT_FOREIGN_KEY);
      addForeignKey(target, RELATED_CLASS_GETTER, FOREIGN_KEY);

      const foreignKeys = getForeignKeys(target);
      expect(foreignKeys).to.have.property('length', 2);
      expect(foreignKeys[0]).to.eql({
        foreignKey: PARENT_FOREIGN_KEY,
        relatedClassGetter: RELATED_CLASS_GETTER,
      });
      expect(foreignKeys[1]).to.eql({
        foreignKey: FOREIGN_KEY,
        relatedClassGetter: RELATED_CLASS_GETTER,
      });

      const parentForeignKeys = getForeignKeys(parent);
      expect(parentForeignKeys).to.have.property('length', 1);
      expect(parentForeignKeys[0]).to.eql({
        foreignKey: PARENT_FOREIGN_KEY,
        relatedClassGetter: RELATED_CLASS_GETTER,
      });
    });

  });

});


text:
import { TestBed } from '@angular/core/testing';
import { Actions } from '@ngrx/effects';
import { provideMockActions } from '@ngrx/effects/testing';
import { Observable } from 'rxjs';
import { MapApiService } from '../services';
import { MapApiEffects } from './map-api.effects';

describe('MapApiEffects', () => {
  let actions$: Observable<any>;
  let effects: MapApiEffects;
  let mapApiService: jasmine.SpyObj<MapApiService>;

  beforeEach(() => {
    mapApiService = jasmine.createSpyObj('mapApiService', ['loadScript']);

    TestBed.configureTestingModule({
      providers: [
        MapApiEffects,
        { provide: MapApiService, useValue: mapApiService },
        provideMockActions(() => actions$),
      ],
    });

    actions$ = TestBed.inject(Actions);
    effects = TestBed.inject<MapApiEffects>(MapApiEffects);
  });

  it('should be created', () => {
    expect(effects).toBeTruthy();
  });
});


text:
__author__ = 'xertrov'

# run like:
# $ python -m nvbtally.updater -h

from queue import Queue
from time import sleep, time
import argparse

from sqlalchemy.orm import sessionmaker

from blockchain.blockexplorer import get_latest_block

from .coinsecrets import get_block_range, get_blocks

from .models import engine, Nulldata, ScannedBlock

CONFIRMATIONS_NEEDED = 2  # keep this at 2, if reorgs are required we can use strip_after

class Updater:

    def __init__(self):
        self.Session = sessionmaker(bind=engine)
        self.session = self.Session()
        self.session.add(ScannedBlock(height=0))

    def strip_after(self, height):
        self.session.query(Nulldata).filter(Nulldata.height >= height).delete()
        self.session.query(ScannedBlock).filter(ScannedBlock.height >= height).delete()
        self.session.commit()

    def run(self, starting_block=351816, run_forever=False, sleep_for=30):
        q = Queue()

        # 1 confirmation should mean top_block = latest_block.height, offset of 1 needed
        top_block = get_latest_block().height - CONFIRMATIONS_NEEDED + 1
        min_block = starting_block

        cached_blocks = set()

        def update_queue():
            nonlocal cached_blocks
            _chunk = 750  # 1000 throws exception
            for i in range(min_block, top_block + 1, _chunk):
                comp_range = list(filter(lambda j: j not in cached_blocks, range(i, i + _chunk)))
                cached_blocks = cached_blocks | {i.height for i in self.session.query(ScannedBlock).filter(ScannedBlock.height.in_(comp_range)).all()}
            for i in range(min_block, top_block + 1):
                if i not in cached_blocks:
                    q.put(i)
                    cached_blocks.add(i)

        update_queue()

        while True:
            n = min(q.qsize(), 50)

            if n == 0:
                if run_forever:
                    print(int(time()), 'No blocks with >= %d confirmations, sleeping for %d seconds then updating...' % (CONFIRMATIONS_NEEDED, sleep_for))
                    sleep(sleep_for)
                    top_block = get_latest_block().height - CONFIRMATIONS_NEEDED
                    update_queue()
                    continue
                else:
                    break

            to_fetch = [q.get() for _ in range(n)]
            print('Fetching %d, min: %d, max: %d' % (n, min(to_fetch), max(to_fetch)))
            blocks = get_blocks(*to_fetch)

            for block in blocks:
                h = block['height']
                t = block['timestamp']
                nds = block['op_returns']
                self.session.add_all([Nulldata(height=h, timestamp=t, txid=nulldata['txid'], script=nulldata['script']) for nulldata in nds])
                self.session.add(ScannedBlock(height=h))
                self.session.commit()
                print('Processed', block['height'])

parser = argparse.ArgumentParser(description="Update DB with new OP_RETURN txs.")
parser.add_argument('--watch', help='Remain open and wait for new blocks.', action='store_true')
parser.add_argument('--sleepfor', help='Seconds to sleep after update routine', type=int, default=30)
parser.add_argument('--strip-after', help='Remove all nulldatas from height H or up', type=int)
parser.add_argument('--start-from', help='Scan all nulldatas occuring in or after this block', type=int, default=351816)
args = parser.parse_args()

if __name__ == "__main__":
    u = Updater()
    if args.strip_after is not None:
        print('Stripped from %d onwards' % args.strip_after)
        u.strip_after(args.strip_after)
    else:
        u.run(args.start_from, args.watch, args.sleepfor)  # 351817 is the first NVB tx, so don't bother before this


text:
package com.amazonaws.services.simpleemailv2.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.simpleemailv2.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * PlacementStatistics JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class PlacementStatisticsJsonUnmarshaller implements Unmarshaller<PlacementStatistics, JsonUnmarshallerContext> {

    public PlacementStatistics unmarshall(JsonUnmarshallerContext context) throws Exception {
        PlacementStatistics placementStatistics = new PlacementStatistics();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("InboxPercentage", targetDepth)) {
                    context.nextToken();
                    placementStatistics.setInboxPercentage(context.getUnmarshaller(Double.class).unmarshall(context));
                }
                if (context.testExpression("SpamPercentage", targetDepth)) {
                    context.nextToken();
                    placementStatistics.setSpamPercentage(context.getUnmarshaller(Double.class).unmarshall(context));
                }
                if (context.testExpression("MissingPercentage", targetDepth)) {
                    context.nextToken();
                    placementStatistics.setMissingPercentage(context.getUnmarshaller(Double.class).unmarshall(context));
                }
                if (context.testExpression("SpfPercentage", targetDepth)) {
                    context.nextToken();
                    placementStatistics.setSpfPercentage(context.getUnmarshaller(Double.class).unmarshall(context));
                }
                if (context.testExpression("DkimPercentage", targetDepth)) {
                    context.nextToken();
                    placementStatistics.setDkimPercentage(context.getUnmarshaller(Double.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return placementStatistics;
    }

    private static PlacementStatisticsJsonUnmarshaller instance;

    public static PlacementStatisticsJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new PlacementStatisticsJsonUnmarshaller();
        return instance;
    }
}


text:
void initUI(){
  if(DEBUG) Serial.println("Ui: initialized");
}

void handleMenuButton(){
  nextFrame();
}

void handleMenuHold(){
    switch(getFrameNr()){
    case 0: //status screen
      if(setting.useClip()) setting.resetClip();
      else setting.resetShots();
      break;
    case 1: //Mode Setting screen
      break;
    case 2: //Clip Setting screen
      setting.resetClip();
      break;
    case 3: //Battery status screen
      break;
    case 4: //Fire status screen
      break;
    default:
      break;
  }
}

void handlePlusButton(){
  switch(getFrameNr()){
    case 0: //status screen
      setting.increaseSpeed();
      break;
    case 1: //Mode Setting screen
      setting.setNextFireMode();
      break;
    case 2: //Clip Setting screen
      setting.increaseClipSize();
      break;
    case 3: //Battery status screen
      break;
    case 4: //Fire status screen
      break;
    default:
      break;
  }
}

void handleMinusButton(){
    switch(getFrameNr()){
    case 0: //status screen
      setting.decreaseSpeed();
      break;
    case 1: //Mode Setting screen
      setting.setPrevFireMode();
      break;
    case 2: //Clip Setting screen

      setting.decreaseClipSize();
      break;
    case 3: //Battery status screen
      break;
    case 4: //Fire status screen
      break;
    default:
      break;
  }
}


text:
package edu.duke.cabig.c3pr.dao;

import java.util.List;

import org.springframework.transaction.annotation.Transactional;

import edu.duke.cabig.c3pr.domain.BaseResearchStaffDataContainer;

@Transactional(readOnly = true)
public class BaseResearchStaffDataContainerDao extends GridIdentifiableDao<BaseResearchStaffDataContainer>{

	@Override
	public Class<BaseResearchStaffDataContainer> domainClass() {
		return BaseResearchStaffDataContainer.class;
	}

    @Transactional(readOnly = false)
	public void save(BaseResearchStaffDataContainer baseResearchStaffDataContainer){
		getHibernateTemplate().saveOrUpdate(baseResearchStaffDataContainer);
	}

    @SuppressWarnings("unchecked")
	public BaseResearchStaffDataContainer getByEmailAddress(String email) {
        List<BaseResearchStaffDataContainer> results = getHibernateTemplate().find("from BaseResearchStaffDataContainer rs where rs.contactMechanisms.value = '" +email+ "'");
        return results.size() > 0 ? results.get(0) : null;
    }

    	/**
	 * Initialize.
	 *
	 * @param baseResearchStaffDataContainer the research staff
	 */
	public void initialize(BaseResearchStaffDataContainer baseResearchStaffDataContainer){
		getHibernateTemplate().initialize(baseResearchStaffDataContainer.getContactMechanisms());
	}

	@Override
	public BaseResearchStaffDataContainer getById(int id) {
		BaseResearchStaffDataContainer baseResearchStaffDataContainer =  super.getById(id);
		baseResearchStaffDataContainer.getBaseOrganizationDataContainers().size();
		baseResearchStaffDataContainer.getContactMechanisms().size();
		return baseResearchStaffDataContainer;
	}
}


text:
class AssignmentLog < ActiveRecord::Base
end


text:
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""This script is used to synthesize generated parts of this library."""

import pathlib

import synthtool as s
from synthtool import gcp
from synthtool.languages import python

REPO_ROOT = pathlib.Path(__file__).parent.absolute()

common = gcp.CommonTemplates()

# ----------------------------------------------------------------------------
# Add templated files
# ----------------------------------------------------------------------------
templated_files = common.py_library(
    system_test_python_versions=["3.8"],
    cov_level=100,
    intersphinx_dependencies={
        "pandas": "https://pandas.pydata.org/pandas-docs/stable/"
    },
)
s.move(templated_files, excludes=["docs/multiprocessing.rst", "README.rst"])

# ----------------------------------------------------------------------------
# Fixup files
# ----------------------------------------------------------------------------

s.replace(
    [".coveragerc"], "google/cloud/__init__.py", "db_dtypes/requirements.py",
)

s.replace(
    ["noxfile.py"], r"[\"']google[\"']", '"db_dtypes"',
)

s.replace(
    ["noxfile.py"], r"import shutil", "import re\nimport shutil",
)

s.replace(
    ["noxfile.py"], "--cov=google", "--cov=db_dtypes",
)

# There are no system tests for this package.
old_sessions = """
    "unit",
    "system",
    "cover",
    "lint",
"""

new_sessions = """
    "lint",
    "unit",
    "unit_prerelease",
    "compliance",
    "compliance_prerelease",
    "cover",
"""

s.replace(["noxfile.py"], old_sessions, new_sessions)

# Add compliance tests.
s.replace(
    ["noxfile.py"], r"def default\(session\):", "def default(session, tests_path):"
)
s.replace(["noxfile.py"], r'os.path.join\("tests", "unit"\),', "tests_path,")
s.replace(
    ["noxfile.py"],
    r'f"--junitxml=unit_{session.python}_sponge_log.xml",',
    r'f"--junitxml={os.path.split(tests_path)[-1]}_{session.python}_sponge_log.xml",',
)
s.replace(
    ["noxfile.py"],
    r'''
@nox.session\(python=UNIT_TEST_PYTHON_VERSIONS\)
def unit\(session\):
    """Run the unit test suite."""
    default\(session\)
''',
    r'''
def prerelease(session, tests_path):
    constraints_path = str(
        CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt"
    )

    # PyArrow prerelease packages are published to an alternative PyPI host.
    # https://arrow.apache.org/docs/python/install.html#installing-nightly-packages
    session.install(
        "--extra-index-url",
        "https://pypi.fury.io/arrow-nightlies/",
        "--prefer-binary",
        "--pre",
        "--upgrade",
        "pyarrow",
    )
    session.install(
        "--extra-index-url",
        "https://pypi.anaconda.org/scipy-wheels-nightly/simple",
        "--prefer-binary",
        "--pre",
        "--upgrade",
        "pandas",
    )
    session.install(
        "mock",
        "asyncmock",
        "pytest",
        "pytest-cov",
        "pytest-asyncio",
        "-c",
        constraints_path,
    )

    # Because we test minimum dependency versions on the minimum Python
    # version, the first version we test with in the unit tests sessions has a
    # constraints file containing all dependencies and extras.
    with open(
        CURRENT_DIRECTORY
        / "testing"
        / f"constraints-{UNIT_TEST_PYTHON_VERSIONS[0]}.txt",
        encoding="utf-8",
    ) as constraints_file:
        constraints_text = constraints_file.read()

    # Ignore leading whitespace and comment lines.
    deps = [
        match.group(1)
        for match in re.finditer(
            r"^\\s*(\\S+)(?===\\S+)", constraints_text, flags=re.MULTILINE
        )
    ]

    # We use --no-deps to ensure that pre-release versions aren't overwritten
    # by the version ranges in setup.py.
    session.install(*deps)
    session.install("--no-deps", "-e", ".")

    # Print out prerelease package versions.
    session.run("python", "-m", "pip", "freeze")

    # Run py.test against the unit tests.
    session.run(
        "py.test",
        "--quiet",
        f"--junitxml={os.path.split(tests_path)[-1]}_prerelease_{session.python}_sponge_log.xml",
        "--cov=db_dtypes",
        "--cov=tests/unit",
        "--cov-append",
        "--cov-config=.coveragerc",
        "--cov-report=",
        "--cov-fail-under=0",
        tests_path,
        *session.posargs,
    )

@nox.session(python=UNIT_TEST_PYTHON_VERSIONS[-1])
def compliance(session):
    """Run the compliance test suite."""
    default(session, os.path.join("tests", "compliance"))

@nox.session(python=UNIT_TEST_PYTHON_VERSIONS[-1])
def compliance_prerelease(session):
    """Run the compliance test suite with prerelease dependencies."""
    prerelease(session, os.path.join("tests", "compliance"))

@nox.session(python=UNIT_TEST_PYTHON_VERSIONS)
def unit(session):
    """Run the unit test suite."""
    default(session, os.path.join("tests", "unit"))

@nox.session(python=UNIT_TEST_PYTHON_VERSIONS[-1])
def unit_prerelease(session):
    """Run the unit test suite with prerelease dependencies."""
    prerelease(session, os.path.join("tests", "unit"))
''',
)

# ----------------------------------------------------------------------------
# Samples templates
# ----------------------------------------------------------------------------

python.py_samples(skip_readmes=True)

# ----------------------------------------------------------------------------
# Final cleanup
# ----------------------------------------------------------------------------

s.shell.run(["nox", "-s", "blacken"], hide_output=False)
for noxfile in REPO_ROOT.glob("samples/**/noxfile.py"):
    s.shell.run(["nox", "-s", "blacken"], cwd=noxfile.parent, hide_output=False)