text:
/**\file */
#ifndef SLIC_DECLARATIONS_airfoildfe_H
#define SLIC_DECLARATIONS_airfoildfe_H
#include "MaxSLiCInterface.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

#define airfoildfe_flushSchedulePaddingBits (6)
#define airfoildfe_nPipes (2)
#define airfoildfe_qpadtPortPCIeWidthInBytes (160)
#define airfoildfe_floatBits (64)
#define airfoildfe_bufferIDBits (3)
#define airfoildfe_mainSchedulePaddingBits (7)
#define airfoildfe_flushBufferIDBits (1)
#define airfoildfe_totalResReadOnlyBits (528)
#define airfoildfe_nFlushPipes (1)
#define airfoildfe_bufferAddressBits (9)
#define airfoildfe_PCIE_ALIGNMENT (16)
#define airfoildfe_flushBufferAddressBits (7)

/*----------------------------------------------------------------------------*/
/*---------------------------- Interface default -----------------------------*/
/*----------------------------------------------------------------------------*/

/**
 * \brief Basic static function for the interface 'default'.
 *
 * \param [in] ticks_AirfoilDFEAdtKernel The number of ticks for which kernel "AirfoilDFEAdtKernel" will run.
 * \param [in] ticks_AirfoilDFEResKernel The number of ticks for which kernel "AirfoilDFEResKernel" will run.
 * \param [in] ticks_AirfoilDFEUpdateKernel The number of ticks for which kernel "AirfoilDFEUpdateKernel" will run.
 * \param [in] inscalar_AirfoilDFEAdtKernel_cfl Input scalar parameter "AirfoilDFEAdtKernel.cfl".
 * \param [in] inscalar_AirfoilDFEAdtKernel_gam Input scalar parameter "AirfoilDFEAdtKernel.gam".
 * \param [in] inscalar_AirfoilDFEAdtKernel_gm1 Input scalar parameter "AirfoilDFEAdtKernel.gm1".
 * \param [in] inscalar_AirfoilDFEAdtKernel_numTicks Input scalar parameter "AirfoilDFEAdtKernel.numTicks".
 * \param [in] inscalar_AirfoilDFEResKernel_eps Input scalar parameter "AirfoilDFEResKernel.eps".
 * \param [in] inscalar_AirfoilDFEResKernel_gm1 Input scalar parameter "AirfoilDFEResKernel.gm1".
 * \param [in] inscalar_AirfoilDFEResKernel_nTicks Input scalar parameter "AirfoilDFEResKernel.nTicks".
 * \param [in] inscalar_AirfoilDFEUpdateKernel_doSaveQold Input scalar parameter "AirfoilDFEUpdateKernel.doSaveQold".
 * \param [in] inscalar_AirfoilDFEUpdateKernel_numCells Input scalar parameter "AirfoilDFEUpdateKernel.numCells".
 * \param [in] instream_cpu_qpadt_to_res Stream "cpu_qpadt_to_res".
 * \param [in] instream_size_cpu_qpadt_to_res The size of the stream instream_cpu_qpadt_to_res in bytes.
 * \param [in] instream_setupCPU Stream "setupCPU".
 * \param [in] instream_size_setupCPU The size of the stream instream_setupCPU in bytes.
 * \param [out] outstream_cpu_res_from_res Stream "cpu_res_from_res".
 * \param [in] outstream_size_cpu_res_from_res The size of the stream outstream_cpu_res_from_res in bytes.
 * \param [out] outstream_qCPUOut Stream "qCPUOut".
 * \param [in] outstream_size_qCPUOut The size of the stream outstream_qCPUOut in bytes.
 * \param [out] outstream_rmsOut Stream "rmsOut".
 * \param [in] outstream_size_rmsOut The size of the stream outstream_rmsOut in bytes.
 * \param [in] lmem_address_adtDxRead Linear LMem control for "adtDxRead" stream: base address, in bytes.
 * \param [in] lmem_arr_size_adtDxRead Linear LMem control for "adtDxRead" stream: array size, in bytes.
 * \param [in] lmem_address_adtQ Linear LMem control for "adtQ" stream: base address, in bytes.
 * \param [in] lmem_arr_size_adtQ Linear LMem control for "adtQ" stream: array size, in bytes.
 * \param [in] lmem_address_qRead Linear LMem control for "qRead" stream: base address, in bytes.
 * \param [in] lmem_arr_size_qRead Linear LMem control for "qRead" stream: array size, in bytes.
 * \param [in] lmem_address_resReadOnly Linear LMem control for "resReadOnly" stream: base address, in bytes.
 * \param [in] lmem_arr_size_resReadOnly Linear LMem control for "resReadOnly" stream: array size, in bytes.
 * \param [in] lmem_address_setupWrite Linear LMem control for "setupWrite" stream: base address, in bytes.
 * \param [in] lmem_arr_size_setupWrite Linear LMem control for "setupWrite" stream: array size, in bytes.
 * \param [in] lmem_address_updateQ Linear LMem control for "updateQ" stream: base address, in bytes.
 * \param [in] lmem_arr_size_updateQ Linear LMem control for "updateQ" stream: array size, in bytes.
 * \param [in] lmem_address_updateQold Linear LMem control for "updateQold" stream: base address, in bytes.
 * \param [in] lmem_arr_size_updateQold Linear LMem control for "updateQold" stream: array size, in bytes.
 * \param [in] lmem_address_updateSaveQold Linear LMem control for "updateSaveQold" stream: base address, in bytes.
 * \param [in] lmem_arr_size_updateSaveQold Linear LMem control for "updateSaveQold" stream: array size, in bytes.
 */
void airfoildfe(
	uint64_t ticks_AirfoilDFEAdtKernel,
	uint64_t ticks_AirfoilDFEResKernel,
	uint64_t ticks_AirfoilDFEUpdateKernel,
	double inscalar_AirfoilDFEAdtKernel_cfl,
	double inscalar_AirfoilDFEAdtKernel_gam,
	double inscalar_AirfoilDFEAdtKernel_gm1,
	uint64_t inscalar_AirfoilDFEAdtKernel_numTicks,
	double inscalar_AirfoilDFEResKernel_eps,
	double inscalar_AirfoilDFEResKernel_gm1,
	uint64_t inscalar_AirfoilDFEResKernel_nTicks,
	uint64_t inscalar_AirfoilDFEUpdateKernel_doSaveQold,
	uint64_t inscalar_AirfoilDFEUpdateKernel_numCells,
	const void *instream_cpu_qpadt_to_res,
	size_t instream_size_cpu_qpadt_to_res,
	const void *instream_setupCPU,
	size_t instream_size_setupCPU,
	void *outstream_cpu_res_from_res,
	size_t outstream_size_cpu_res_from_res,
	void *outstream_qCPUOut,
	size_t outstream_size_qCPUOut,
	void *outstream_rmsOut,
	size_t outstream_size_rmsOut,
	size_t lmem_address_adtDxRead,
	size_t lmem_arr_size_adtDxRead,
	size_t lmem_address_adtQ,
	size_t lmem_arr_size_adtQ,
	size_t lmem_address_qRead,
	size_t lmem_arr_size_qRead,
	size_t lmem_address_resReadOnly,
	size_t lmem_arr_size_resReadOnly,
	size_t lmem_address_setupWrite,
	size_t lmem_arr_size_setupWrite,
	size_t lmem_address_updateQ,
	size_t lmem_arr_size_updateQ,
	size_t lmem_address_updateQold,
	size_t lmem_arr_size_updateQold,
	size_t lmem_address_updateSaveQold,
	size_t lmem_arr_size_updateSaveQold);

/**
 * \brief Basic static non-blocking function for the interface 'default'.
 *
 * Schedule to run on an engine and return immediately.
 * The status of the run can be checked either by ::max_wait or ::max_nowait;
 * note that one of these *must* be called, so that associated memory can be released.
 *
 *
 * \param [in] ticks_AirfoilDFEAdtKernel The number of ticks for which kernel "AirfoilDFEAdtKernel" will run.
 * \param [in] ticks_AirfoilDFEResKernel The number of ticks for which kernel "AirfoilDFEResKernel" will run.
 * \param [in] ticks_AirfoilDFEUpdateKernel The number of ticks for which kernel "AirfoilDFEUpdateKernel" will run.
 * \param [in] inscalar_AirfoilDFEAdtKernel_cfl Input scalar parameter "AirfoilDFEAdtKernel.cfl".
 * \param [in] inscalar_AirfoilDFEAdtKernel_gam Input scalar parameter "AirfoilDFEAdtKernel.gam".
 * \param [in] inscalar_AirfoilDFEAdtKernel_gm1 Input scalar parameter "AirfoilDFEAdtKernel.gm1".
 * \param [in] inscalar_AirfoilDFEAdtKernel_numTicks Input scalar parameter "AirfoilDFEAdtKernel.numTicks".
 * \param [in] inscalar_AirfoilDFEResKernel_eps Input scalar parameter "AirfoilDFEResKernel.eps".
 * \param [in] inscalar_AirfoilDFEResKernel_gm1 Input scalar parameter "AirfoilDFEResKernel.gm1".
 * \param [in] inscalar_AirfoilDFEResKernel_nTicks Input scalar parameter "AirfoilDFEResKernel.nTicks".
 * \param [in] inscalar_AirfoilDFEUpdateKernel_doSaveQold Input scalar parameter "AirfoilDFEUpdateKernel.doSaveQold".
 * \param [in] inscalar_AirfoilDFEUpdateKernel_numCells Input scalar parameter "AirfoilDFEUpdateKernel.numCells".
 * \param [in] instream_cpu_qpadt_to_res Stream "cpu_qpadt_to_res".
 * \param [in] instream_size_cpu_qpadt_to_res The size of the stream instream_cpu_qpadt_to_res in bytes.
 * \param [in] instream_setupCPU Stream "setupCPU".
 * \param [in] instream_size_setupCPU The size of the stream instream_setupCPU in bytes.
 * \param [out] outstream_cpu_res_from_res Stream "cpu_res_from_res".
 * \param [in] outstream_size_cpu_res_from_res The size of the stream outstream_cpu_res_from_res in bytes.
 * \param [out] outstream_qCPUOut Stream "qCPUOut".
 * \param [in] outstream_size_qCPUOut The size of the stream outstream_qCPUOut in bytes.
 * \param [out] outstream_rmsOut Stream "rmsOut".
 * \param [in] outstream_size_rmsOut The size of the stream outstream_rmsOut in bytes.
 * \param [in] lmem_address_adtDxRead Linear LMem control for "adtDxRead" stream: base address, in bytes.
 * \param [in] lmem_arr_size_adtDxRead Linear LMem control for "adtDxRead" stream: array size, in bytes.
 * \param [in] lmem_address_adtQ Linear LMem control for "adtQ" stream: base address, in bytes.
 * \param [in] lmem_arr_size_adtQ Linear LMem control for "adtQ" stream: array size, in bytes.
 * \param [in] lmem_address_qRead Linear LMem control for "qRead" stream: base address, in bytes.
 * \param [in] lmem_arr_size_qRead Linear LMem control for "qRead" stream: array size, in bytes.
 * \param [in] lmem_address_resReadOnly Linear LMem control for "resReadOnly" stream: base address, in bytes.
 * \param [in] lmem_arr_size_resReadOnly Linear LMem control for "resReadOnly" stream: array size, in bytes.
 * \param [in] lmem_address_setupWrite Linear LMem control for "setupWrite" stream: base address, in bytes.
 * \param [in] lmem_arr_size_setupWrite Linear LMem control for "setupWrite" stream: array size, in bytes.
 * \param [in] lmem_address_updateQ Linear LMem control for "updateQ" stream: base address, in bytes.
 * \param [in] lmem_arr_size_updateQ Linear LMem control for "updateQ" stream: array size, in bytes.
 * \param [in] lmem_address_updateQold Linear LMem control for "updateQold" stream: base address, in bytes.
 * \param [in] lmem_arr_size_updateQold Linear LMem control for "updateQold" stream: array size, in bytes.
 * \param [in] lmem_address_updateSaveQold Linear LMem control for "updateSaveQold" stream: base address, in bytes.
 * \param [in] lmem_arr_size_updateSaveQold Linear LMem control for "updateSaveQold" stream: array size, in bytes.
 * \return A handle on the execution status, or NULL in case of error.
 */
max_run_t *airfoildfe_nonblock(
	uint64_t ticks_AirfoilDFEAdtKernel,
	uint64_t ticks_AirfoilDFEResKernel,
	uint64_t ticks_AirfoilDFEUpdateKernel,
	double inscalar_AirfoilDFEAdtKernel_cfl,
	double inscalar_AirfoilDFEAdtKernel_gam,
	double inscalar_AirfoilDFEAdtKernel_gm1,
	uint64_t inscalar_AirfoilDFEAdtKernel_numTicks,
	double inscalar_AirfoilDFEResKernel_eps,
	double inscalar_AirfoilDFEResKernel_gm1,
	uint64_t inscalar_AirfoilDFEResKernel_nTicks,
	uint64_t inscalar_AirfoilDFEUpdateKernel_doSaveQold,
	uint64_t inscalar_AirfoilDFEUpdateKernel_numCells,
	const void *instream_cpu_qpadt_to_res,
	size_t instream_size_cpu_qpadt_to_res,
	const void *instream_setupCPU,
	size_t instream_size_setupCPU,
	void *outstream_cpu_res_from_res,
	size_t outstream_size_cpu_res_from_res,
	void *outstream_qCPUOut,
	size_t outstream_size_qCPUOut,
	void *outstream_rmsOut,
	size_t outstream_size_rmsOut,
	size_t lmem_address_adtDxRead,
	size_t lmem_arr_size_adtDxRead,
	size_t lmem_address_adtQ,
	size_t lmem_arr_size_adtQ,
	size_t lmem_address_qRead,
	size_t lmem_arr_size_qRead,
	size_t lmem_address_resReadOnly,
	size_t lmem_arr_size_resReadOnly,
	size_t lmem_address_setupWrite,
	size_t lmem_arr_size_setupWrite,
	size_t lmem_address_updateQ,
	size_t lmem_arr_size_updateQ,
	size_t lmem_address_updateQold,
	size_t lmem_arr_size_updateQold,
	size_t lmem_address_updateSaveQold,
	size_t lmem_arr_size_updateSaveQold);

/**
 * \brief Advanced static interface, structure for the engine interface 'default'
 *
 */
typedef struct {
	uint64_t ticks_AirfoilDFEAdtKernel; /**<  [in] The number of ticks for which kernel "AirfoilDFEAdtKernel" will run. */
	uint64_t ticks_AirfoilDFEResKernel; /**<  [in] The number of ticks for which kernel "AirfoilDFEResKernel" will run. */
	uint64_t ticks_AirfoilDFEUpdateKernel; /**<  [in] The number of ticks for which kernel "AirfoilDFEUpdateKernel" will run. */
	double inscalar_AirfoilDFEAdtKernel_cfl; /**<  [in] Input scalar parameter "AirfoilDFEAdtKernel.cfl". */
	double inscalar_AirfoilDFEAdtKernel_gam; /**<  [in] Input scalar parameter "AirfoilDFEAdtKernel.gam". */
	double inscalar_AirfoilDFEAdtKernel_gm1; /**<  [in] Input scalar parameter "AirfoilDFEAdtKernel.gm1". */
	uint64_t inscalar_AirfoilDFEAdtKernel_numTicks; /**<  [in] Input scalar parameter "AirfoilDFEAdtKernel.numTicks". */
	double inscalar_AirfoilDFEResKernel_eps; /**<  [in] Input scalar parameter "AirfoilDFEResKernel.eps". */
	double inscalar_AirfoilDFEResKernel_gm1; /**<  [in] Input scalar parameter "AirfoilDFEResKernel.gm1". */
	uint64_t inscalar_AirfoilDFEResKernel_nTicks; /**<  [in] Input scalar parameter "AirfoilDFEResKernel.nTicks". */
	uint64_t inscalar_AirfoilDFEUpdateKernel_doSaveQold; /**<  [in] Input scalar parameter "AirfoilDFEUpdateKernel.doSaveQold". */
	uint64_t inscalar_AirfoilDFEUpdateKernel_numCells; /**<  [in] Input scalar parameter "AirfoilDFEUpdateKernel.numCells". */
	const void *instream_cpu_qpadt_to_res; /**<  [in] Stream "cpu_qpadt_to_res". */
	size_t instream_size_cpu_qpadt_to_res; /**<  [in] The size of the stream instream_cpu_qpadt_to_res in bytes. */
	const void *instream_setupCPU; /**<  [in] Stream "setupCPU". */
	size_t instream_size_setupCPU; /**<  [in] The size of the stream instream_setupCPU in bytes. */
	void *outstream_cpu_res_from_res; /**<  [out] Stream "cpu_res_from_res". */
	size_t outstream_size_cpu_res_from_res; /**<  [in] The size of the stream outstream_cpu_res_from_res in bytes. */
	void *outstream_qCPUOut; /**<  [out] Stream "qCPUOut". */
	size_t outstream_size_qCPUOut; /**<  [in] The size of the stream outstream_qCPUOut in bytes. */
	void *outstream_rmsOut; /**<  [out] Stream "rmsOut". */
	size_t outstream_size_rmsOut; /**<  [in] The size of the stream outstream_rmsOut in bytes. */
	size_t lmem_address_adtDxRead; /**<  [in] Linear LMem control for "adtDxRead" stream: base address, in bytes. */
	size_t lmem_arr_size_adtDxRead; /**<  [in] Linear LMem control for "adtDxRead" stream: array size, in bytes. */
	size_t lmem_address_adtQ; /**<  [in] Linear LMem control for "adtQ" stream: base address, in bytes. */
	size_t lmem_arr_size_adtQ; /**<  [in] Linear LMem control for "adtQ" stream: array size, in bytes. */
	size_t lmem_address_qRead; /**<  [in] Linear LMem control for "qRead" stream: base address, in bytes. */
	size_t lmem_arr_size_qRead; /**<  [in] Linear LMem control for "qRead" stream: array size, in bytes. */
	size_t lmem_address_resReadOnly; /**<  [in] Linear LMem control for "resReadOnly" stream: base address, in bytes. */
	size_t lmem_arr_size_resReadOnly; /**<  [in] Linear LMem control for "resReadOnly" stream: array size, in bytes. */
	size_t lmem_address_setupWrite; /**<  [in] Linear LMem control for "setupWrite" stream: base address, in bytes. */
	size_t lmem_arr_size_setupWrite; /**<  [in] Linear LMem control for "setupWrite" stream: array size, in bytes. */
	size_t lmem_address_updateQ; /**<  [in] Linear LMem control for "updateQ" stream: base address, in bytes. */
	size_t lmem_arr_size_updateQ; /**<  [in] Linear LMem control for "updateQ" stream: array size, in bytes. */
	size_t lmem_address_updateQold; /**<  [in] Linear LMem control for "updateQold" stream: base address, in bytes. */
	size_t lmem_arr_size_updateQold; /**<  [in] Linear LMem control for "updateQold" stream: array size, in bytes. */
	size_t lmem_address_updateSaveQold; /**<  [in] Linear LMem control for "updateSaveQold" stream: base address, in bytes. */
	size_t lmem_arr_size_updateSaveQold; /**<  [in] Linear LMem control for "updateSaveQold" stream: array size, in bytes. */
} airfoildfe_actions_t;

/**
 * \brief Advanced static function for the interface 'default'.
 *
 * \param [in] engine The engine on which the actions will be executed.
 * \param [in,out] interface_actions Actions to be executed.
 */
void airfoildfe_run(
	max_engine_t *engine,
	airfoildfe_actions_t *interface_actions);

/**
 * \brief Advanced static non-blocking function for the interface 'default'.
 *
 * Schedule the actions to run on the engine and return immediately.
 * The status of the run can be checked either by ::max_wait or ::max_nowait;
 * note that one of these *must* be called, so that associated memory can be released.
 *
 *
 * \param [in] engine The engine on which the actions will be executed.
 * \param [in] interface_actions Actions to be executed.
 * \return A handle on the execution status of the actions, or NULL in case of error.
 */
max_run_t *airfoildfe_run_nonblock(
	max_engine_t *engine,
	airfoildfe_actions_t *interface_actions);

/**
 * \brief Group run advanced static function for the interface 'default'.
 *
 * \param [in] group Group to use.
 * \param [in,out] interface_actions Actions to run.
 *
 * Run the actions on the first device available in the group.
 */
void airfoildfe_run_group(max_group_t *group, airfoildfe_actions_t *interface_actions);

/**
 * \brief Group run advanced static non-blocking function for the interface 'default'.
 *
 *
 * Schedule the actions to run on the first device available in the group and return immediately.
 * The status of the run must be checked with ::max_wait.
 * Note that use of ::max_nowait is prohibited with non-blocking running on groups:
 * see the ::max_run_group_nonblock documentation for more explanation.
 *
 * \param [in] group Group to use.
 * \param [in] interface_actions Actions to run.
 * \return A handle on the execution status of the actions, or NULL in case of error.
 */
max_run_t *airfoildfe_run_group_nonblock(max_group_t *group, airfoildfe_actions_t *interface_actions);

/**
 * \brief Array run advanced static function for the interface 'default'.
 *
 * \param [in] engarray The array of devices to use.
 * \param [in,out] interface_actions The array of actions to run.
 *
 * Run the array of actions on the array of engines.  The length of interface_actions
 * must match the size of engarray.
 */
void airfoildfe_run_array(max_engarray_t *engarray, airfoildfe_actions_t *interface_actions[]);

/**
 * \brief Array run advanced static non-blocking function for the interface 'default'.
 *
 *
 * Schedule to run the array of actions on the array of engines, and return immediately.
 * The length of interface_actions must match the size of engarray.
 * The status of the run can be checked either by ::max_wait or ::max_nowait;
 * note that one of these *must* be called, so that associated memory can be released.
 *
 * \param [in] engarray The array of devices to use.
 * \param [in] interface_actions The array of actions to run.
 * \return A handle on the execution status of the actions, or NULL in case of error.
 */
max_run_t *airfoildfe_run_array_nonblock(max_engarray_t *engarray, airfoildfe_actions_t *interface_actions[]);

/**
 * \brief Converts a static-interface action struct into a dynamic-interface max_actions_t struct.
 *
 * Note that this is an internal utility function used by other functions in the static interface.
 *
 * \param [in] maxfile The maxfile to use.
 * \param [in] interface_actions The interface-specific actions to run.
 * \return The dynamic-interface actions to run, or NULL in case of error.
 */
max_actions_t* airfoildfe_convert(max_file_t *maxfile, airfoildfe_actions_t *interface_actions);

/**
 * \brief Initialise a maxfile.
 */
max_file_t* airfoildfe_init(void);

/* Error handling functions */
int airfoildfe_has_errors(void);
const char* airfoildfe_get_errors(void);
void airfoildfe_clear_errors(void);
/* Free statically allocated maxfile data */
void airfoildfe_free(void);
/* returns: -1 = error running command; 0 = no error reported */
int airfoildfe_simulator_start(void);
/* returns: -1 = error running command; 0 = no error reported */
int airfoildfe_simulator_stop(void);

#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* SLIC_DECLARATIONS_airfoildfe_H */


text:
package org.neo4j.cypher.internal.compiler.v2_3.mutation

import org.neo4j.cypher.internal.compiler.v2_3.commands.expressions.Expression

trait SetAction extends UpdateAction with GraphElementPropertyFunctions {
  def rewrite(f: (Expression) => Expression): SetAction
}

redpajama_set_name: RedPajamaGithub


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

namespace Pirate.Textile
{
  public class List : Element
  {
    private List<string> _lines;

    public IEnumerable<string> Lines { get { return _lines; } }

    public bool Numbered { get; private set; }

    public List(bool numbered, string text)
    {
      Numbered = numbered;
      _lines = new List<string>();
      _lines.Add(text);
    }

    public void Add(string text)
    {
      _lines.Add(text);
    }

    public override string ToText()
    {
      if (Numbered)
      {
        var numberedLines = new List<string>();
        var number = 1;

        foreach (var line in Lines)
        {
          numberedLines.Add(number + ". " + Span.RenderText(line));
          number++;
        }

        return string.Join(Environment.NewLine, numberedLines.ToArray()) + Environment.NewLine + Environment.NewLine;
      }
      else
      {
        return string.Join(Environment.NewLine, Lines.Select(line => "* " + Span.RenderText(line)).ToArray()) + Environment.NewLine + Environment.NewLine;
      }
    }

    public override string ToHtml()
    {
      return string.Format(
        CultureInfo.InvariantCulture,
        Numbered ? "
{0}
" : "
{0}
",
        string.Join(Environment.NewLine, Lines.Select(line => "
" + Span.RenderHtml(line) + "
").ToArray()));
    }
  }
}


text:
Running PX4 in SITL Mode
==========================

Introduction
--------------------------
This assumes that you have PX4 (posix configuration) and jMAVSim installed and compiled.  These can be on the same physical machine or on different machines as long as there is a network between the two.  The system has many possible configurations - this README will focus just on one to keep things simple.  Namely:

- The controller inputs are coming from a PIXHAWK that has an active connection to an RC controller and is generating the [Mavlink](https://pixhawk.ethz.ch/mavlink/) message RC_CHANNELS(#65) on its serial (USB) port.  This Pixhawk's USB is connected to a USB port on the machine running PX4.
- PX4 and jMAVSim communicate over UDP
- qGroundControl is connecting to PX4 over UDP

A diagram of the setup described is shown here.  Note that UDP port numbers are only displayed on the socket server and are left blank on the socket client.

![SITL Diagram](SITL_Diagram.png "SITL Diagram")

Steps
---------------------------

1. Connect the RC Controller (PIXHAWK) to the PX4 machine using USB.  Verify the `/dev/ttyACM0` device appears.  Make sure that the persmissions of this device allow the PX4 app to open the device for read/write (`sudo chmod 777 /dev/ttyACM0`).

1. Run the quadrotor simulation:
```
> make sitlrun
```

Detailed Background on System startup
---------------------------

NOTE: This is only necessary if you are not using the instructions above.

1. Connect the RC Controller (PIXHAWK) to the PX4 machine using USB.  Verify the `/dev/ttyACM0` device appears.  Make sure that the persmissions of this device allow the PX4 app to open the device for read/write (`sudo chmod 777 /dev/ttyACM0`).

1. Create the following diretories in "`./Firmware/Build/posix_sitl.build/`":
```
> cd ./Firmware/Build/posix_sitl.build
> mkdir -p rootfs/fs/microsd
> mkdir -p rootfs/eeprom
```

1. Launch PX4 from the SITL build directory "`./Firmware/Build/posix_sitl.build/`" using the command below.  The optional `<startup_file>` can be used to cause a set of commands to be entered into the PX4 shell at startup.
```
> ./px4 <startup_file>
```

There is a sample startup script at `posix_configs/SITL/init/rcS`.
```
> ./px4 ../../posix-configs/SITL/init/rcS
```

Without the `<startup_file>`, the commands can be entered at the shell prompt one at a time.  An example startup file is given below.  This example shows that the "mavlink" module has selected port 14556 for its socket server (as shown in the SITL diagram) and will listen for connections on this port.

1. qGroundControl (QGC) can be connected to this instance of PX4 any time after it is started.  The instructions for configuring (QGC) are not given here in detail, but you just need to configure a UDP connection with ip_address:`<address of PX4 machine>` and port:14556.  (QGC also has a "Listening Port" setting that must be set to another unused port).

1. jMAVSim can now be launched to complete the setup.  At the root directory of the jMAVSim code, type the following command, replacing the IP address of the machine that is running PX4.  The port 14550 is the default port of the simulator module in PX4.
```
> java -cp lib/*:out/production/jmavsim.jar me.drton.jmavsim.Simulator -udp <IP_of_PX4_machine>:14550
```

At this point, you should see the jMAVSim world visualization, and when you increase the throttle on your RC controller, the vehicle will take off.  Note that the RC params in the example startup file may not be correct for your controller.

Example "startup" file
---------------------

```
uorb start
mavlink start -x -u 14556
simulator start -s
param set CAL_GYRO0_ID 2293760
param set CAL_ACC0_ID 1310720
param set CAL_ACC1_ID 1376256
param set CAL_MAG0_ID 196608
rgbled start
tone_alarm start
gyrosim start
accelsim start
barosim start
adcsim start
commander start
sensors start
ekf_att_pos_estimator start
mc_pos_control start
mc_att_control start
hil mode_pwm
param set MAV_TYPE 2
param set RC1_MAX 2015
param set RC1_MIN 996
param set RC1_TRIM 1502
param set RC1_REV -1
param set RC2_MAX 2016
param set RC2_MIN 995
param set RC2_TRIM 1500
param set RC3_MAX 2003
param set RC3_MIN 992
param set RC3_TRIM 992
param set RC4_MAX 2011
param set RC4_MIN 997
param set RC4_TRIM 1504
param set RC4_REV -1
param set RC6_MAX 2016
param set RC6_MIN 992
param set RC6_TRIM 1504
param set RC_CHAN_CNT 8
param set RC_MAP_MODE_SW 5
param set RC_MAP_POSCTL_SW 7
param set RC_MAP_RETURN_SW 8
param set MC_PITCHRATE_P 0.05
param set MC_ROLLRATE_P 0.05
mixer load /dev/pwm_output0 ROMFS/px4fmu_common/mixers/quad_x.main.mix
```


text:
#ifndef __UTIL_GEOM_ELLIPSE_HPP
#define __UTIL_GEOM_ELLIPSE_HPP

#include <cstdlib>

#include "../point.hpp"
#include "../vector.hpp"

namespace util::geom {
    ///////////////////////////////////////////////////////////////////////////
    template <size_t S, typename T>
    struct ellipse {
        util::point<S,T> origin;
        util::vector<S,T> radius;
    };
}

#include "ellipse.ipp"

#endif


text:
%SerialLink.fdyn Integrate forward dynamics
%
% [T,Q,QD] = R.fdyn(T1, TORQFUN) integrates the dynamics of the robot over
% the time  interval 0 to T and returns vectors of time TI, joint position Q
% and joint velocity QD.  The initial joint position and velocity are zero.
% The torque applied to the joints is computed by the user function TORQFUN:
%
% [TI,Q,QD] = R.fdyn(T, TORQFUN, Q0, QD0) as above but allows the initial
% joint position and velocity to be specified.
%
% The control torque is computed by a user defined function
%
% 	TAU = TORQFUN(T, Q, QD, ARG1, ARG2, ...)
%
% where Q and QD are the manipulator joint coordinate and velocity state
% respectively], and T is the current time.
%
% [T,Q,QD] = R.fdyn(T1, TORQFUN, Q0, QD0, ARG1, ARG2, ...) allows optional
% arguments to be passed through to the user function.
%
% Note::
% - This function performs poorly with non-linear joint friction, such as
%   Coulomb friction.  The R.nofriction() method can be used to set this
%   friction to zero.
% - If TORQFUN is not specified, or is given as 0 or [],  then zero torque
%   is applied to the manipulator joints.
% - The builtin integration function ode45() is used.
%
% See also SerialLink.accel, SerialLink.nofriction, SerialLink.RNE, ode45.

% Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9)
%
% Copyright (C) 1993-2011, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB.  If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com

function [t, q, qd] = fdyn(robot, t1, torqfun, q0, qd0, varargin)
    global __fdyn_robot;
    global __fdyn_torqfun;

	n = robot.n;
	if nargin == 2
		torqfun = 0;
		q0 = zeros(1,n);
		qd0 = zeros(1,n);
	elseif nargin == 3
		q0 = zeros(1,n);
		qd0 = zeros(1,n);
	elseif nargin == 4
		qd0 = zeros(1,n);
	end

    % concatenate q and qd into the initial state vector
	x0= [q0(:); qd0(:)];

    __fdyn_robot = robot;
    __fdyn_torqfun = torqfun;

	dt = t1/100;
	t = 0:dt:t1;

	y = lsode(@fdyn2, x0, t);
	t = t'
	q = y(:,1:n);
	qd = y(:,n+1:2*n);

%FDYN2  private function called by FDYN
%
%	XDD = FDYN2(T, X, FLAG, ROBOT, TORQUEFUN)
%
% Called by FDYN to evaluate the robot velocity and acceleration for
% forward dynamics.  T is the current time, X = [Q QD] is the state vector,
% ROBOT is the object being integrated, and TORQUEFUN is the string name of
% the function to compute joint torques and called as
%
%       TAU = TORQUEFUN(T, X)
%
% if not given zero joint torques are assumed.
%
% The result is XDD = [QD QDD].

function xd = fdyn2(x, t)
    global __fdyn_robot;
	global __fdyn_torqfun;
    robot = __fdyn_robot;
    torqfun = __fdyn_torqfun;
	n = robot.n;
	q = x(1:n);
	qd = x(n+1:2*n);
	if isstr(torqfun)
		tau = feval(torqfun, t, q, qd);
	else
		tau = zeros(n,1)';
	end

	qdd = accel(robot, x(1:n,1)', x(n+1:2*n,1)', tau);
	xd = [x(n+1:2*n,1); qdd];


text:
package com.imagero.uio.imageio.spi;

import com.imagero.uio.imageio.UioImageInputStream;
import com.imagero.uio.RandomAccessInput;
import com.imagero.uio.UIOStreamBuilder;
import com.imagero.uio.impl.RandomAccessFileX;

import javax.imageio.spi.ImageInputStreamSpi;
import javax.imageio.stream.ImageInputStream;
import java.io.File;
import java.util.Locale;

/**
 * @author Andrey Kuznetsov
 */
public class UioRAFImageInputStreamSpi extends ImageInputStreamSpi {

    public UioRAFImageInputStreamSpi() {
        super("imagero.com (Andrey Kuznetsov)", "0.9", com.imagero.uio.impl.RandomAccessFileX.class);
    }

    public String getDescription(Locale locale) {
        return "Service provider that instantiates a UioImageInputStream from a com.imagero.uio.impl.RandomAccessFileX";
    }

    public ImageInputStream createInputStreamInstance(Object input, boolean useCache, File cacheDir) {
        if (input instanceof RandomAccessFileX) {
            try {
                RandomAccessFileX raf = (RandomAccessFileX) input;
                RandomAccessInput ro = new UIOStreamBuilder(raf).setBuffered(true).create();
                return new UioImageInputStream(ro);
            }
            catch (Exception ex) {
                return null;
            }
        }
	throw new IllegalArgumentException();
    }
}


text:
This test setup was adapted from: https://github.com/Azure/iotedgedev/tree/v2.1.4/docker/runtime

## Building from RCs

RCs for the Azure IoT Edge runtime are not available on standard package managers, so the build is done against GitHub release assets directly.

See: https://docs.microsoft.com/en-us/azure/iot-edge/how-to-install-iot-edge-linux#install-runtime-using-release-assets

## Use IoT Edge CLI

Once the container is running, you can interact with the IoT Edge daemon like so:

```bash
docker exec iot-edge-device iotedge -H http://<CONTAINER_IP>:15580 <command>
```

For example, to list the active IoT Edge modules:

```bash
docker exec iot-edge-device iotedge -H "http://$(docker inspect iot-edge-device -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}'):15580" list
```

## Simulated temperature sensor

The `SimulatedTemperatureSensor` is enabled in the environment.

To view simulated data, run:

```bash
docker logs -f SimulatedTemperatureSensor
```

## Logs collection

To send integration logs to Staging US, edit your `ddev` configuration with:

```toml
[orgs.staging-us]
api_key = "<STAGING_API_KEY>"
logs_url = "<STAGING_AGENT_INTAKE_HOSTNAME>"
```

Then start the environment using `-o staging-us`.

Validate that logs are being sent by inspecting the logs section of `docker exec -it <agent_container_name> agent status`.

## Generate mock server metrics

The data in [`metrics/`](./compose/device/mock_server/metrics) was generated as follows:

* Start an E2E environment.
* Let it run for a few minutes.
* Generate metrics files:

```bash
curl localhost:9601/metrics > azure_iot_edge/tests/compose/mock_server/metrics/edge_hub.txt
curl localhost:9602/metrics > azure_iot_edge/tests/compose/mock_server/metrics/edge_agent.txt
```

* Manually edit `edge_agent.txt` (replace `<INSTANCE_NUMBER>` with the instance number from the output):
  * Add a value line for `edgeAgent_unsuccessful_iothub_syncs_total` (no way to trigger unsuccessful syncs were found):

    ```
    edgeAgent_unsuccessful_iothub_syncs_total{iothub="iot-edge-dev-hub.azure-devices.net",edge_device="testEdgeDevice",instance_number="c2c90030-2df4-4c92-98cb-deaa9ef05cac",ms_telemetry="True"} 0
    ```

  * Add value lines for `edgeAgent_module_stop_total`:

    ```
    edgeAgent_module_stop_total{iothub="iot-edge-dev-hub.azure-devices.net",edge_device="testEdgeDevice",instance_number="c2c90030-2df4-4c92-98cb-deaa9ef05cac",module_name="SimulatedTemperatureSensor",module_version="1.0",ms_telemetry="True"} 0
    edgeAgent_module_stop_total{iothub="iot-edge-dev-hub.azure-devices.net",edge_device="testEdgeDevice",instance_number="c2c90030-2df4-4c92-98cb-deaa9ef05cac",module_name="edgeHub",module_version="",ms_telemetry="True"} 0
    ```

  * Add value lines for `edgeAgent_total_disk_space_bytes` (containers don't have individual disks):

    ```
    edgeAgent_total_disk_space_bytes{iothub="iot-edge-dev-hub.azure-devices.net",edge_device="testEdgeDevice",instance_number="c2c90030-2df4-4c92-98cb-deaa9ef05cac",module_name="edgeAgent",ms_telemetry="True"} 1073741824
    edgeAgent_total_disk_space_bytes{iothub="iot-edge-dev-hub.azure-devices.net",edge_device="testEdgeDevice",instance_number="c2c90030-2df4-4c92-98cb-deaa9ef05cac",module_name="edgeHub",ms_telemetry="True"} 1073741824
    edgeAgent_total_disk_space_bytes{iothub="iot-edge-dev-hub.azure-devices.net",edge_device="testEdgeDevice",instance_number="c2c90030-2df4-4c92-98cb-deaa9ef05cac",module_name="SimulatedTemperatureSensor",ms_telemetry="False"} 1073741824
    ```

* Manually edit `edge_hub.txt` (replace `<INSTANCE_NUMBER>` with the instance number from the output):
  * Edit any `NaN` values so that all metrics report correctly.
  * Add a value line for `edgehub_dropped_total`:

    ```
    edgehub_messages_dropped_total{iothub="iot-edge-dev-hub.azure-devices.net",edge_device="testEdgeDevice",instance_number="<INSTANCE_NUMBER>",from="testEdgeDevice/SimulatedTemperatureSensor",from_route_output="temperatureOutput",reason="ttl_expiry",ms_telemetry="True"} 1
    ```

  * Add a value line for `edgehub_offline_count_total`:

    ```
    edgehub_offline_count_total{iothub="iot-edge-dev-hub.azure-devices.net",edge_device="testEdgeDevice",instance_number="<INSTANCE_NUMBER>",id="testEdgeDevice/$edgeHub",ms_telemetry="True"} 1
    ```

  * Add a definition and value for the `edgehub_messages_unack_total` metric (no way to trigger storage failures locally was found):

    ```
    # HELP edgehub_messages_unack_total Total number of messages unack because storage failure
    # TYPE edgehub_messages_unack_total counter
    edgehub_messages_unack_total{iothub="iot-edge-dev-hub.azure-devices.net",edge_device="testEdgeDevice",instance_number="<INSTANCE_NUMBER>",from="testEdgeDevice/SimulatedTemperatureSensor",from_route_output="temperatureOutput",reason="storage_failure",ms_telemetry="True"} 1
    ```

  * Add a definition and value for the `edgehub_operation_retry_total` metric (no way to trigger them locally was found):

    ```
    # HELP edgehub_operation_retry_total Total number of times edgeHub operations were retried
    # TYPE edgehub_operation_retry_total counter
    edgehub_operation_retry_total{iothub="iot-edge-dev-hub.azure-devices.net",edge_device="testEdgeDevice",instance_number="<INSTANCE_NUMBER>",id="testEdgeDevice/$edgeHub",operation="test",ms_telemetry="True"} 1
    ```

  * Add a definition and value for the `edgehub_client_connect_failed_total` metric (we do not have auth set up yet):

    ```
    # HELP edgehub_client_connect_failed_total Total number of times clients failed to connect to edgeHub
    # TYPE edgehub_client_connect_failed_total counter
    edgehub_client_connect_failed_total{iothub="iot-edge-dev-hub.azure-devices.net",edge_device="testEdgeDevice",instance_number="0dab21d7-d0de-4527-99df-27c8e5861eac",id="testEdgeDevice/SimulatedTemperatureSensor",reason="not_authenticated",ms_telemetry="True"} 1
    ```

## Troubleshooting

Guides:

* https://docs.microsoft.com/en-us/azure/iot-edge/troubleshoot-common-errors
* https://docs.microsoft.com/en-us/azure/iot-edge/troubleshoot

In particular, you can run a `check` command in the `iot-edge-device` container to check for any configuration or connectivity issues:

```bash
$ docker exec -it iot-edge-device iotedge -H "http://$(docker inspect iot-edge-device -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}'):15580" check
Configuration checks
--------------------
√ config.yaml is well-formed - OK
√ config.yaml has well-formed connection string - OK
√ container engine is installed and functional - OK
× config.yaml has correct hostname - Error
    config.yaml has hostname edgehub but device reports hostname 0504777ae8c2.
    Hostname in config.yaml must either be identical to the device hostname or be a fully-qualified domain name that has the device hostname as the first component.
× config.yaml has correct URIs for daemon mgmt endpoint - Error
    Error: could not execute list-modules request: an error occurred trying to connect: Connection refused (os error 111)
...
```


text:
package org.topbraid.shacl.arq.functions;

import org.apache.jena.graph.Node;
import org.apache.jena.sparql.expr.NodeValue;
import org.apache.jena.sparql.function.FunctionEnv;
import org.topbraid.jenax.functions.AbstractFunction1;
import org.topbraid.jenax.util.JenaDatatypes;
import org.topbraid.shacl.vocabulary.SH;

/**
 * Native implementation of dash:isDeactivated.
 * Not that it's a complex function, but it's called very often.
 *
 * @author Holger Knublauch
 */
public class IsDeactivatedFunction extends AbstractFunction1 {

	@Override
	protected NodeValue exec(Node arg1, FunctionEnv env) {
		return NodeValue.makeBoolean(env.getActiveGraph().contains(arg1, SH.deactivated.asNode(), JenaDatatypes.TRUE.asNode()));
	}
}


text:
#ifndef ZENDERER__GUI__FONT_CORE_HPP
#define ZENDERER__GUI__FONT_CORE_HPP

// Include FreeType2 API.
#include "ft2build.h"
#include "freetype/freetype.h"
#include "freetype/ftglyph.h"

#include "Zenderer/Core/Subsystem.hpp"
#include "Zenderer/CoreGraphics/Texture.hpp"
#include "Zenderer/Math/Shapes.hpp"

namespace zen
{
/// A collection of TrueType font rendering wrapper utilities.
namespace gui
{
    /// Initializes the core FreeType2 library.
    class ZEN_API zFontLibrary : public zSubsystem
    {
    public:
        ~zFontLibrary()
        {
            this->Destroy();
        }

        /**
         * Initializes the FreeType library.
         *  This should be called prior to ANY other font operations,
         *  preferably by the @a Zenderer initialization function.
         *
         * @return  `true` on success, `false` on failure.
         *
         * @see     zen::Init()
         *
         * @note    Initialization is guaranteed to only occur one
         *          time despite multiple potential calls to this
         *          method.
         **/
        bool Init()
        {
            if(m_init) return true;
            return (m_init = (FT_Init_FreeType(&m_Library) == 0));
        }

        bool Destroy()
        {
            if(!m_init) return true;
            FT_Done_FreeType(m_Library);
            return !(m_init = false);
        }

        static zFontLibrary& InitFreetype()
        {
            static zFontLibrary s_TTF;
            s_TTF.Init();
            return s_TTF;
        }

        const FT_Library GetLibrary() const
        {
            return m_Library;
        }

    private:
        FT_Library m_Library;
    };

    /// A glyph structure used internally by the font API.
    struct glyph_t
    {
        gfxcore::zTexture*  texture;    ///< Raw bitmap
        math::vectoru16_t   size;       ///< Raw bitmap size
        math::vectoru16_t   position;   ///< Position on baseline to render
        uint16_t            advance;    ///< Pixels until next character
    };
}   // namespace gfx
}   // namespace zen

#endif // ZENDERER__GUI__FONT_CORE_HPP

/**
 * @class zen::gui::zFontLibrary
 * @details
 *  This is a wrapper class around the FreeType API that is at the core
 *  of rendering text in @a Zenderer. It will initialize the library a
 *  single time and track its state, cleaning up when necessary.
 *
 * @see zen::Init()
 **/

/** @} **/


text:
var getNumInRow;
var getNumInCol;
var getBoard;
var initBoard;
var boardMouseDown;
var boardMouseUp;
var boardMouseMove;
var getTimeLeft;
var getOrbSelected;

(function() {
// TODO break up long functions here

var gameRules = {
  skyfall:  true,
  moveTime: 4,
  minOrbs:  3,
  numInRow: 6,
  numInCol: 5,
};
var board = [];
var timeLeft = 0;
var timeMoveStarted = new Date();
var moved = false;
var orbSelected = null;

function rollOrb() {
  // TODO: adjusted skyfall rate
  // Reserch skyfall rates, if 15% dark is 15/100 says dark orb spawns, or 1.15 weight on dark
  // Also account for tricolor, no-RCV and similar skyfalls
  // TODO cloud blind
  return {
    color:    Math.floor(Math.random() * 6),
    enhanced: false,
    locked:   false,
    blind1:   false, // Regular blind, slide orbs to reveal
    blind2:   0, // Duration blind, cannot see orbs until timer is over
    matched:  false,
    trueX:    null,
    trueY:    null,
    offset:   0
  };
};

function refreshBoard() {
  gameRules = getGameRules();
  board = [];
  for(var i = 0; i < gameRules.numInCol; i++) {
  board[i] = [];
    for(var j = 0; j < gameRules.numInRow; j++) {
      // TODO: actual skyfall stuff, no available combos
      board[i][j] = rollOrb();
    }
  }
};

function cascade(skyfall) {
  for(var n = 0; n < gameRules.numInCol; n++) {
    var hasCascade = false;
    for(var j = 0; j < gameRules.numInRow; j++) {
      // must loop from bottom to top
      for(var i = gameRules.numInCol-1; i > 0; i--) {
        if(board[i][j].color == -1 && board[i-1][j].color != -1) {
          board[i][j].color = board[i-1][j].color;
          board[i][j].enhanced = board[i-1][j].enhanced;
          board[i][j].locked = board[i-1][j].locked;
          board[i][j].blind1 = board[i-1][j].blind1;
          board[i][j].blind2 = board[i-1][j].blind2;
          board[i-1][j].color = -1;
          board[i][j].offset = 1;
          hasCascade = true;
        }
      }
      if(board[0][j].color == -1 && skyfall) {
        board[0][j] = rollOrb();
        board[0][j].offset = 1;
        hasCascade = true;
      }
    }
    if (!hasCascade) {
      break;
    }
    pushAnimation({timeLeft: 0.25, type: "pause"});
    for (var x = 0; x < 0.25 / deltaT; x++) {
      for(var i = 0; i < gameRules.numInCol; i++) {
        for(var j = 0; j < gameRules.numInRow; j++) {
          board[i][j].offset = Math.max(board[i][j].offset - 4 * deltaT, 0);
        }
      }
      pushBoard(board);
      pushDamage(getDamage());
      pushRcv(getRcv());
      pushHp(getHp());
    }
  }
  if (gameRules.skyfall || !skyfall) {
    getMatches();
  }
};

function getMatches() {
  timeLeft = 0;
  // keep track of what combo an orb is part of
  var boardMask = [];
  for (var i = 0; i < gameRules.numInCol; i++) {
    boardMask[i] = [];
    for (var j = 0; j < gameRules.numInRow; j++) {
      boardMask[i][j] = { matched: false, comboId: 0 };
    }
  }

  var combos = 0; // Not yet how many combos, but how many groups of three
  // TODO: support unable to match attribute effect
  // Animation goes left to right, then bottom to top
  for (var i = gameRules.numInCol - 1; i >= 0; i--) {
    for (var j = 0; j < gameRules.numInRow; j++) {
      // color is -1 after cascade when skyfall is disabled
      if (board[i][j].color == -1) {
        continue;
      }
      // check vertical combos, but not in bottom 2 rows
      if (i < gameRules.numInCol - 2) {
        if (board[i][j].color == board[i+1][j].color && board[i][j].color == board[i+2][j].color) {
          boardMask[i][j].matched = true;
          boardMask[i][j].comboId = combos;
          boardMask[i+1][j].matched = true;
          boardMask[i+1][j].comboId = combos;
          boardMask[i+2][j].matched = true;
          boardMask[i+2][j].comboId = combos;
          combos += 1;
        }
      }
      // check horizontal combos, but not in right 2 cols
      if (j < gameRules.numInRow - 2) {
        if (board[i][j].color == board[i][j+1].color && board[i][j].color == board[i][j+2].color) {
          boardMask[i][j].matched = true;
          boardMask[i][j].comboId = combos;
          boardMask[i][j+1].matched = true;
          boardMask[i][j+1].comboId = combos;
          boardMask[i][j+2].matched = true;
          boardMask[i][j+2].comboId = combos;
          combos += 1;
        }
      }
    }
  }
  // Method to merge two overlapping combos
  function combine(id1, id2) {
    if (id1 != id2) {
      for (var i = 0; i < gameRules.numInCol; i++) {
        for (var j = 0; j < gameRules.numInRow; j++) {
          if (boardMask[i][j].comboId == id2) boardMask[i][j].comboId = id1;
        }
      }
    }
  }
  for (var i = gameRules.numInCol - 1; i >= 0; i--) {
    for (var j = 0; j < gameRules.numInRow; j++) {
      if (boardMask[i][j].matched) {
        // Check each adjacent orb to see if it is matched and of the same color
        if (i > 0 && board[i][j].color == board[i-1][j].color && boardMask[i-1][j].matched) {
          combine(boardMask[i][j].comboId, boardMask[i-1][j].comboId);
        }
        if (j > 0 && board[i][j].color == board[i][j-1].color && boardMask[i][j-1].matched) {
          combine(boardMask[i][j].comboId, boardMask[i][j-1].comboId);
        }
        if (i < gameRules.numInCol - 1 && board[i][j].color == board[i+1][j].color && boardMask[i+1][j].matched) {
          combine(boardMask[i][j].comboId, boardMask[i+1][j].comboId);
        }
        if (j < gameRules.numInRow - 1 && board[i][j].color == board[i][j+1].color && boardMask[i][j+1].matched) {
          combine(boardMask[i][j].comboId, boardMask[i][j+1].comboId);
        }
      }
    }
  }
  // Add each remaining combo id to this list
  var comboIds = new Set([]);
  for (var i = 0; i < gameRules.numInCol; i++) {
    for (var j = 0; j < gameRules.numInRow; j++) {
      if (boardMask[i][j].matched) {
        comboIds.add(boardMask[i][j].comboId);
      }
    }
  }
  comboList = [];
  // TODO: animate iff used on team
  // TODO: Support bombs
  // Remove matched orbs, check combo stats
  var idsInOrder = Array.from(comboIds).sort(function(a, b){return a-b});
  for (let comboId of idsInOrder) {
    var comboStats = {
      att:     -1,
      orbs:    0,
      enhance: 0,
      cross:   false,
      tpa:     false,
      row:     false,
      col:     false,
      o51e:    false,
      box:     false, // TODO
    };
    for (var i = 0; i < gameRules.numInCol; i++) {
      // check whether this row is solid
      var isRow = true;
      for (var j = 0; j < gameRules.numInRow; j++) {
        if (boardMask[i][j].matched && boardMask[i][j].comboId == comboId) {
          comboStats.att = board[i][j].color;
          // get whether it is part of a cross. Still need to check that size == 5 later
          if (i > 0 && i < gameRules.numInCol - 1 && j > 0 && j < gameRules.numInRow - 1) {
            if (board[i+1][j].color == board[i][j].color &&
                board[i-1][j].color == board[i][j].color &&
                board[i][j+1].color == board[i][j].color &&
                board[i][j-1].color == board[i][j].color) {
                comboStats.cross = true;
            }
          }
          if (board[i][j].enhanced) {
            comboStats.enhance += 1;
          }
          comboStats.orbs += 1;
        } else {
          isRow = false;
        }
      }
      if (isRow) {
        comboStats.row = true;
      }
    }
    for (var j = 0; j < gameRules.numInRow; j++) {
      // check whether this row is solid
      var isCol = true;
      for (var i = 0; i < gameRules.numInCol; i++) {
        if (!boardMask[i][j].matched || boardMask[i][j].comboId != comboId) {
          isCol = false;
        }
      }
      if (isCol) {
        comboStats.col = true;
      }
    }
    if (comboStats.orbs == 4) {
      comboStats.tpa = true;
    }
    if (comboStats.orbs != 5) {
      comboStats.cross = false;
    }
    if (comboStats.orbs == 5 && comboStats.enhance > 0){
      comboStats.o51e = true;
    }
    if (comboStats.orbs >= gameRules.minMatch) {
      for (var i = 0; i < gameRules.numInCol; i++) {
        for (var j = 0; j < gameRules.numInRow; j++) {
          if (boardMask[i][j].matched && boardMask[i][j].comboId == comboId) {
            pushAnimation({timeLeft: 0.5,
                           type:     "erase",
                           color:    board[i][j].color, // TODO: Add support for blinds, locks and enhance here
                           i:        i,
                           j:        j});
            board[i][j].color = -1;
          }
        }
      }
      comboList[comboList.length] = comboStats;
      useCombo(comboStats);
      pushAnimation({timeLeft: 0.5, type: "pause"});
      for (var i = 0; i < 0.5 / deltaT; i++) {
        pushBoard(board);
        pushDamage(getDamage());
        pushRcv(getRcv());
        pushHp(getHp());
      }
    }
  }
  if(comboList.length == 0) {
    endCombos();
    if (!gameRules.skyfall) {
      cascade(true);
    }
  } else {
    cascade(gameRules.skyfall);
  }
};

boardMouseDown = function(row, col) {
  orbSelected = { row: Math.round(row), col: Math.round(col) };
  board[orbSelected.row][orbSelected.col].trueX = col;
  board[orbSelected.row][orbSelected.col].trueY = row;
  moved = false;
  gameRules = getGameRules();
};

boardMouseUp = function() {
  if (orbSelected != null) {
    board[orbSelected.row][orbSelected.col].trueX = null;
    board[orbSelected.row][orbSelected.col].trueY = null;
    orbSelected = null;
    if (moved == true) {
      moved = false;
      getMatches();
    }
  }
};

boardMouseMove = function(row, col) {
  if (orbSelected != null) {
    if (Math.round(col) != orbSelected.col || Math.round(row) != orbSelected.row) {
      if (Math.sqrt(Math.pow(Math.round(col) - col, 2) + Math.pow(Math.round(row) - row, 2)) < .5) {
        var temp = board[Math.round(row)][Math.round(col)];
        board[Math.round(row)][Math.round(col)] = board[orbSelected.row][orbSelected.col];
        board[orbSelected.row][orbSelected.col] = temp;
        board[Math.round(row)][Math.round(col)].blind1 = false;
        board[orbSelected.row][orbSelected.col].blind1 = false;
        orbSelected = { row: Math.round(row), col: Math.round(col) };
        if (!moved) {
          moved = true;
          timeMoveStarted = new Date();
        }
      }
    }
    board[orbSelected.row][orbSelected.col].trueX = col;
    board[orbSelected.row][orbSelected.col].trueY = row;
  }
};

setInterval(function() {
  // TODO Valten orbs
  if (moved) {
    timeLeft = (gameRules.moveTime - (new Date() - timeMoveStarted) / 1000.) / gameRules.moveTime;
    if (timeLeft <= 0) {
      board[orbSelected.row][orbSelected.col].trueX = null;
      board[orbSelected.row][orbSelected.col].trueY = null;
      orbSelected = null;
      moved = false;
      getMatches();
    }
  }
}, deltaT * 1000);

getNumInRow = function() { return gameRules.numInRow; };
getNumInCol = function() { return gameRules.numInCol; };

getBoard = function() {
  return JSON.parse(JSON.stringify(board));
};

initBoard = function() {
  refreshBoard();
};

getTimeLeft = function() {
  return timeLeft;
};

getOrbSelected = function() {
  return orbSelected;
};

})();


text:
package dynamics;

import java.io.File;

import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.config.Configuration;
import dynamics.config.properties.ConfigProcessing;
import dynamics.proxy.IDynamicProxy;

import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;

@Mod(modid = DynamicLib.MODID, name = DynamicLib.NAME, version = "$LIB-VERSION$")
public class DynamicLib {

    public static final String MODID = "dynamiclib";
    public static final String NAME = "DynamicLib";

    @Instance(MODID)
    public static DynamicLib instance;

    @SidedProxy(clientSide = "dynamics.proxy.DynamicClientProxy", serverSide = "dynamics.proxy.DynamicServerProxy")
    public static IDynamicProxy proxy;

    @EventHandler
    public void preInit(FMLPreInitializationEvent event) {
        MinecraftForge.EVENT_BUS.register(GameRuleManager.instance);

        final File configFile = event.getSuggestedConfigurationFile();
        Configuration config = new Configuration(configFile);
        ConfigProcessing.processAnnotations(MODID, config, LibConfig.class);
        if (config.hasChanged()) config.save();

        proxy.preInit();
    }

    @EventHandler
    public void init(FMLInitializationEvent event) {
        proxy.init();
    }

    @EventHandler
    public void postInit(FMLPostInitializationEvent event) {
        proxy.postInit();
    }
}


text:
package cephfs

import (
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestGetFsCid(t *testing.T) {
	t.Run("unmounted", func(t *testing.T) {
		mount, err := CreateMount()
		defer func() { assert.NoError(t, mount.Release()) }()
		require.NoError(t, err)
		require.NotNil(t, mount)

		err = mount.ReadDefaultConfigFile()
		require.NoError(t, err)

		cid, err := mount.GetFsCid()
		assert.Error(t, err)
		assert.Equal(t, cid, int64(0))
	})
	t.Run("mounted", func(t *testing.T) {
		mount := fsConnect(t)
		defer fsDisconnect(t, mount)

		cid, err := mount.GetFsCid()
		assert.NoError(t, err)
		assert.GreaterOrEqual(t, cid, int64(0))
	})
}


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

<!DOCTYPE document PUBLIC "-//APACHE//DTD Documentation V2.0//EN" "http://forrest.apache.org/dtd/document-v20.dtd">
<document>

    <title>Welcome to the org.apache.forrest.plugin.input.dtdx Plugin</title>

      <title>Apache Forrest dtdx-input Plugin</title>

        This plugin org.apache.forrest.plugin.input.dtdx uses the
        NekoDTD tool packaged as a Cocoon Generator
        to automatically generate some hyperlinked DTD reference documentation.

        See the Samples.

</document>


text:
defaults write com.apple.Safari AlwaysRestoreSessionAtLaunch -bool true

# Start with a new private window
# defaults write com.apple.Safari OpenPrivateWindowWhenNotRestoringSessionAtLaunch -bool true

# Setup new window and tab behvior
# 0: Homepage
# 1: Empty Page
# 2: Same Page
# 3: Bookmarks
# 4: Top Sites
defaults write com.apple.Safari NewTabBehavior -int 1
defaults write com.apple.Safari NewWindowBehavior -int 1

# Set home page to `about:blank` for faster loading
defaults write com.apple.Safari HomePage -string 'about:blank'

# Remove history items (in days)
defaults write com.apple.Safari HistoryAgeInDaysLimit -int 31

# Save downloded files to
defaults write com.apple.Safari DownloadsPath -string '~/Downloads'

# Save format
# 0: Page Source
# 1: Web Archive
defaults write com.apple.Safari SavePanelFileFormat -int 0

# Remove downloads list items
# 0: Manually
# 1: When Safari Quits
# 2: Upon Successful Download
defaults write com.apple.Safari DownloadsClearingPolicy -int 2

# Prevent Safari from opening "safe" files automatically after downloading
defaults write com.apple.Safari AutoOpenSafeDownloads -bool false

# Tabs
###############################################################################

# Open pages in tabs instead of windows:
# 0: Never
# 1: Automatically
# 2: Always
defaults write com.apple.Safari TabCreationPolicy -int 2

# AutoFill
###############################################################################

# AutoFill using info from my Contacts card
defaults write com.apple.Safari AutoFillFromAddressBook -bool true

# AutoFill user names and passwords
defaults write com.apple.Safari AutoFillPasswords -bool true

# AutoFill credit cards
defaults write com.apple.Safari AutoFillCreditCardData -bool true

# AutoFill other forms
defaults write com.apple.Safari AutoFillMiscellaneousForms -bool true

# Search
###############################################################################

# Include search engine suggestions
defaults write com.apple.Safari SuppressSearchSuggestions -bool false

# Include Spotlight Suggestions
defaults write com.apple.Safari UniversalSearchEnabled -bool true

# Show Favorites under Smart Search field
defaults write com.apple.Safari ShowFavoritesUnderSmartSearchField -bool false

# Enable Quick Website Search
defaults write com.apple.Safari WebsiteSpecificSearchEnabled -bool true

# Preload Top Hit in the background
defaults write com.apple.Safari PreloadTopHit -bool true

# Backspace key to go to the previous page in history
defaults write com.apple.Safari com.apple.Safari.ContentPageGroupIdentifier.WebKit2BackspaceKeyNavigationEnabled -bool false

# Security
###############################################################################

# Warn when visiting a fraudulent website
# defaults write com.apple.Safari WarnAboutFraudulentWebsites -bool true

# Enable JavaScript
# defaults write com.apple.Safari WebKitJavaScriptEnabled -bool true
# defaults write com.apple.Safari com.apple.Safari.ContentPageGroupIdentifier.WebKit2JavaScriptEnabled -bool true

# Block pop-up windows
# defaults write com.apple.Safari WebKitJavaScriptCanOpenWindowsAutomatically -bool false
# defaults write com.apple.Safari com.apple.Safari.ContentPageGroupIdentifier.WebKit2JavaScriptCanOpenWindowsAutomatically -bool false

# Allow WebGL
# defaults write com.apple.Safari com.apple.Safari.ContentPageGroupIdentifier.WebKit2WebGLEnabled -bool true

# Internet plug-ins
defaults write com.apple.Safari WebKitPluginsEnabled -bool true
defaults write com.apple.Safari com.apple.Safari.ContentPageGroupIdentifier.WebKit2PluginsEnabled -bool true
defaults write com.apple.Safari WebKitJavaEnabled -bool false
defaults write com.apple.Safari com.apple.Safari.ContentPageGroupIdentifier.WebKit2JavaEnabled -bool false

# Privacy
###############################################################################

# Cookies and website data:
# 0,2: Always block
# 3,1: Allow from current website only
# 2,1: Allow from websites I visit
# 1,0: Always allow
defaults write com.apple.Safari BlockStoragePolicy -int 2
defaults write com.apple.Safari WebKitStorageBlockingPolicy -int 1
defaults write com.apple.Safari com.apple.Safari.ContentPageGroupIdentifier.WebKit2StorageBlockingPolicy -int 1

# Website use of location services:
# 0: Deny without prompting
# 1: Prompt for each website once each day
# 2: Prompt for each website one time only
defaults write com.apple.Safari SafariGeolocationPermissionPolicy -int 2

# Ask websites not to track me
defaults write com.apple.Safari SendDoNotTrackHTTPHeader -bool true

# Allow websites to check if Apple Pay is set up
defaults write com.apple.Safari com.apple.Safari.ContentPageGroupIdentifier.WebKit2ApplePayCapabilityDisclosureAllowed -bool true

# Extensions
###############################################################################

# Enable extensions
defaults write com.apple.Safari ExtensionsEnabled -bool true

# Add Safari extensions
# "/Applications/Safari Technology Preview.app"
# "/Applications/WebKit.app"
safari_browsers="/Applications/Safari.app"
safari_extensions=(
  "http://download.livereload.com/2.1.0/LiveReload-2.1.0.safariextz"
  "http://sobolev.us/download/stylish/stylish.safariextz"
  "https://cache.agilebits.com/dist/1P/ext/1Password-4.6.6.safariextz"
)

# Download Extensions
for safari in "${safari_browsers[@]}"; do
  for extension in "${safari_extensions[@]}"; do
    wget -qcP ~/Downloads "$extension"
  done
done

# Install Extensions
osascript <<EOD
tell application "Finder"
  set safariextzs to $(IFS=,; sed 's/,/","/g' <<< "{\"${safari_extensions[*]##*/}\"}")
  repeat with safariextz in safariextzs
    set safariextz to file ((home as Unicode text) & "Downloads:" & safariextz)
    if exists safariextz then
      ignoring application responses
        tell application "Safari" to open safariextz
      end ignoring
      tell application "System Events"
        tell process "Safari"
          set frontmost to true
          -- window "Extensions"
          repeat until (exists window 1) and subrole of window 1 is in {"AXStandardWindow", "AXDialog"}
            delay 1
          end repeat
          if exists (sheet 1 of window 1) then
            click button 1 of sheet 1 of window 1 -- "Install from Gallery" or "Trust"
          else
            click button 1 of window 1 -- Error "OK"
          end if
        end tell
      end tell
    end if
  end repeat
end tell
EOD

# Cleanup
for extension in "${safari_extensions[@]}"; do
  rm ~/Downloads/${extension[@]##*/} 2>/dev/null
done

# Advanced
###############################################################################

# Show full URL
defaults write com.apple.Safari ShowFullURLInSmartSearchField -bool true

# Stop internet plug-ins to save power
# defaults write com.apple.Safari com.apple.Safari.ContentPageGroupIdentifier.WebKit2PlugInSnapshottingEnabled -bool true

# Press Tab to highlight each item on a webpage
defaults write com.apple.Safari WebKitTabToLinksPreferenceKey -bool false

# Set default encoding
defaults write com.apple.Safari WebKitDefaultTextEncodingName -string 'utf-8'
defaults write com.apple.Safari com.apple.Safari.ContentPageGroupIdentifier.WebKit2DefaultTextEncodingName -string 'utf-8'

# Enable the Develop menu and the Web Inspector
defaults write com.apple.Safari IncludeDevelopMenu -bool true
defaults write com.apple.Safari WebKitDeveloperExtrasEnabledPreferenceKey -bool true
defaults write com.apple.Safari com.apple.Safari.ContentPageGroupIdentifier.WebKit2DeveloperExtrasEnabled -bool true

# Miscellaneous
###############################################################################

# Show bookmarks bar
defaults write com.apple.Safari ShowFavoritesBar-v2 -bool false

# Thumbnail cache for History and Top Sites
#defaults write com.apple.Safari DebugSnapshotsUpdatePolicy -int 2

# Debug menu
#defaults write com.apple.Safari IncludeInternalDebugMenu -bool true

# Search with Contains instead of Starts With
defaults write com.apple.Safari FindOnPageMatchesWordStartsOnly -bool false

# Remove useless icons from Safari's bookmarks bar
defaults write com.apple.Safari ProxiesInBookmarksBar '()'

# Add a context menu item for showing the Web Inspector in web views
defaults write NSGlobalDomain WebKitDeveloperExtras -bool true

# Set tab bar visibility
# defaults write com.apple.Safari AlwaysShowTabBar -bool false

# Show status bar
defaults write com.apple.Safari ShowStatusBar -bool true

# Disable Webkit Nightly start page
defaults write org.webkit.nightly.WebKit StartPageDisabled -bool true

# Toggle the toolbar with `⌘⌥T`
# defaults write com.apple.Safari NSUserKeyEquivalents -dict-add 'Hide Toolbar' '@~t'
# defaults write com.apple.Safari NSUserKeyEquivalents -dict-add 'Show Toolbar' '@~t'

# Open Bookmarks Group in tabs
# defaults write com.apple.Safari NSUserKeyEquivalents -dict-add '\033Bookmarks\033Work\033Open in New Tabs' '@$g'

# Print
################################################################################

# Print headers and footers
defaults write com.apple.Safari PrintHeadersAndFooters -bool false

# Print backgrounds
defaults write com.apple.Safari WebKitShouldPrintBackgroundsPreferenceKey -bool false
defaults write com.apple.Safari "com.apple.Safari.ContentPageGroupIdentifier.WebKit2ShouldPrintBackgrounds" -bool false


text:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';
import { Observable } from 'rxjs/Observable';
import { Product } from './../../core/models/product';
import { ProductService } from './../../core/services/product.service';

@Component({
  selector: 'app-product-detail-page',
  templateUrl: './product-detail-page.component.html',
  styleUrls: ['./product-detail-page.component.scss']
})

export class ProductDetailPageComponent implements OnInit {
  actionsSubscription: Subscription;
  product$: Product = null;
  routeSubs: Subscription;
  productId: any;

  constructor(
    private route: ActivatedRoute,
    private productService: ProductService
  ) {

  }
  ngOnInit() {
    this.actionsSubscription = this.route.params.subscribe(
      (params: any) => {
        this.productId = params['id'];
        this.productService
            .getProduct(this.productId)
            .subscribe((res) => {
              this.product$ = res;
              console.log(this.product$);
            });
      }
    )
  }
}


text:
package factory.method;

public class Cat implements Animal{

	@Override
	public void voice() {
		System.out.println("Meow");
	}

}


text:
var should = require("should");
var request = require('supertest');
var express = require('express');
var sinon = require('sinon');

var locales = require("../../../../red/api/editor/locales");

describe("api/editor/locales", function() {
    beforeEach(function() {
    })
    afterEach(function() {
    })
    describe('get named resource catalog',function() {
        var app;
        before(function() {
            // bit of a mess of internal workings
            locales.init({
                i18n: {
                    i: {
                        lng: function() { return 'en-US'},
                        setLng: function(lang,callback) {
                            if (callback) {
                                callback();
                            }
                        }
                    },
                    catalog: function(namespace, lang) {
                        return {namespace:namespace, lang:lang};
                    }
                }
            });
            app = express();
            app.get(/locales\/(.+)\/?$/,locales.get);
        });
        it('returns with default language', function(done) {
            request(app)
                .get("/locales/message-catalog")
                .expect(200)
                .end(function(err,res) {
                    if (err) {
                        return done(err);
                    }
                    res.body.should.have.property('namespace','message-catalog');
                    done();
                });
        });
        it('returns with selected language', function(done) {
            request(app)
                .get("/locales/message-catalog?lng=fr-FR")
                .expect(200)
                .end(function(err,res) {
                    if (err) {
                        return done(err);
                    }
                    res.body.should.have.property('namespace','message-catalog');
                    res.body.should.have.property('lang','fr-FR');
                    done();
                });
        });
    });

    describe('get all node resource catalogs',function() {
        var app;
        before(function() {
            // bit of a mess of internal workings
            locales.init({
                i18n: {
                    catalog: function(namespace, lang) {
                        return {
                            "node-red": "should not return",
                            "test-module-a-id": "test-module-a-catalog",
                            "test-module-b-id": "test-module-b-catalog",
                            "test-module-c-id": "test-module-c-catalog"
                        }[namespace]
                    }
                },
                nodes: {
                    getNodeList: function() {
                        return [
                            {module:"node-red",id:"node-red-id"},
                            {module:"test-module-a",id:"test-module-a-id"},
                            {module:"test-module-b",id:"test-module-b-id"}
                        ];
                    }
                }
            });
            app = express();
            app.get("/locales/nodes",locales.getAllNodes);
        });
        it('returns with the node catalogs', function(done) {
            request(app)
                .get("/locales/nodes")
                .expect(200)
                .end(function(err,res) {
                    if (err) {
                        return done(err);
                    }
                    res.body.should.eql({
                        'test-module-a-id': 'test-module-a-catalog',
                        'test-module-b-id': 'test-module-b-catalog'
                    });
                    done();
                });
        });
    });
});


text:
package io.druid.segment;

import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.Runnables;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

import javax.annotation.Nullable;
import java.io.Closeable;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

public class CloserRuleTest
{
  @Rule
  public final CloserRule closer = new CloserRule(true);
  @Test
  public void testCloses() throws Throwable
  {
    final CloserRule closer = new CloserRule(false);
    final AtomicBoolean closed = new AtomicBoolean(false);
    closer.closeLater(
        new Closeable()
        {
          @Override
          public void close() throws IOException
          {
            closed.set(true);
          }
        }
    );
    run(closer, Runnables.doNothing());
    Assert.assertTrue(closed.get());
  }

  @Test
  public void testAutoCloses() throws Throwable
  {
    final CloserRule closer = new CloserRule(false);
    final AtomicBoolean closed = new AtomicBoolean(false);
    closer.closeLater(
        new AutoCloseable()
        {
          @Override
          public void close() throws Exception
          {
            closed.set(true);
          }
        }
    );
    run(closer, Runnables.doNothing());
    Assert.assertTrue(closed.get());
  }

  @Test
  public void testPreservesException() throws Throwable
  {
    final CloserRule closer = new CloserRule(false);
    final AtomicBoolean closed = new AtomicBoolean(false);
    closer.closeLater(
        new Closeable()
        {
          @Override
          public void close() throws IOException
          {
            closed.set(true);
          }
        }
    );

    final String msg = "You can't divide by zero, you can only take the limit of such!";
    Exception ex = null;
    try {
      run(
          closer, new Runnable()
          {
            @Override
            public void run()
            {
              throw new ArithmeticException(msg);
            }
          }
      );
    }
    catch (Exception e) {
      ex = e;
    }
    Assert.assertTrue(closed.get());
    Assert.assertNotNull(ex);
    Assert.assertTrue(ex instanceof ArithmeticException);
    Assert.assertEquals(msg, ex.getMessage());
  }

  @Test
  public void testAddsSuppressed() throws Throwable
  {
    final CloserRule closer = new CloserRule(false);
    final AtomicBoolean closed = new AtomicBoolean(false);
    final String ioExceptionMsg = "You can't triple stamp a double stamp!";
    closer.closeLater(
        new Closeable()
        {
          @Override
          public void close() throws IOException
          {
            throw new IOException(ioExceptionMsg);
          }
        }
    );
    closer.closeLater(
        new Closeable()
        {
          @Override
          public void close() throws IOException
          {
            closed.set(true);
          }
        }
    );

    final String msg = "You can't divide by zero, you can only take the limit of such!";
    Throwable ex = null;
    try {
      run(
          closer, new Runnable()
          {
            @Override
            public void run()
            {
              throw new ArithmeticException(msg);
            }
          }
      );
    }
    catch (Throwable e) {
      ex = e;
    }
    Assert.assertTrue(closed.get());
    Assert.assertNotNull(ex);
    Assert.assertTrue(ex instanceof ArithmeticException);
    Assert.assertEquals(msg, ex.getMessage());
    Assert.assertEquals(
        ImmutableList.of(ioExceptionMsg),
        Lists.transform(
            Arrays.asList(ex.getSuppressed()),
            new Function<Throwable, String>()
            {
              @Nullable
              @Override
              public String apply(@Nullable Throwable input)
              {
                if (input == null) {
                  return null;
                }
                return input.getSuppressed()[0].getMessage();
              }
            }
        )
    );
  }

  @Test
  public void testThrowsCloseException()
  {
    final CloserRule closer = new CloserRule(true);
    final String ioExceptionMsg = "You can't triple stamp a double stamp!";
    closer.closeLater(
        new Closeable()
        {
          @Override
          public void close() throws IOException
          {
            throw new IOException(ioExceptionMsg);
          }
        }
    );
    Throwable ex = null;
    try {
      run(closer, Runnables.doNothing());
    }
    catch (Throwable throwable) {
      ex = throwable;
    }
    Assert.assertNotNull(ex);
    ex = ex.getSuppressed()[0];
    Assert.assertNotNull(ex);
    Assert.assertTrue(ex instanceof IOException);
    Assert.assertEquals(ioExceptionMsg, ex.getMessage());
  }

  @Test
  public void testJustLogs() throws Throwable
  {
    final CloserRule closer = new CloserRule(false);
    final String ioExceptionMsg = "You can't triple stamp a double stamp!";
    closer.closeLater(
        new Closeable()
        {
          @Override
          public void close() throws IOException
          {
            throw new IOException(ioExceptionMsg);
          }
        }
    );
    run(closer, Runnables.doNothing());
  }

  @Test
  public void testJustLogsAnything() throws Throwable
  {
    final CloserRule closer = new CloserRule(false);
    final String ioExceptionMsg = "You can't triple stamp a double stamp!";
    closer.closeLater(
        new Closeable()
        {
          @Override
          public void close() throws IOException
          {
            throw new IOException(ioExceptionMsg);
          }
        }
    );
    closer.closeLater(
        new Closeable()
        {
          @Override
          public void close() throws IOException
          {
            throw new IOException(ioExceptionMsg);
          }
        }
    );
    closer.closeLater(
        new AutoCloseable()
        {
          @Override
          public void close() throws Exception
          {
            throw new IOException(ioExceptionMsg);
          }
        }
    );
    run(closer, Runnables.doNothing());
  }

  @Test
  public void testClosesEverything()
  {
    final AtomicLong counter = new AtomicLong(0L);
    final CloserRule closer = new CloserRule(true);
    final String ioExceptionMsg = "You can't triple stamp a double stamp!";
    final List<IOException> ioExceptions = Arrays.<IOException>asList(
        new IOException(ioExceptionMsg),
        null,
        new IOException(ioExceptionMsg),
        null,
        new IOException(ioExceptionMsg),
        null
    );
    for(final IOException throwable : ioExceptions){
      closer.closeLater(
          new Closeable()
          {
            @Override
            public void close() throws IOException
            {
              counter.incrementAndGet();
              if(throwable != null){
                throw throwable;
              }
            }
          }
      );
    }
    for(final IOException throwable : ioExceptions){
      closer.closeLater(
          new AutoCloseable()
          {
            @Override
            public void close() throws Exception
            {
              counter.incrementAndGet();
              if(throwable != null){
                throw throwable;
              }
            }
          }
      );
    }
    Throwable ex = null;
    try {
      run(closer, Runnables.doNothing());
    }catch (Throwable throwable) {
      ex = throwable;
    }
    Assert.assertNotNull(ex);
    Assert.assertEquals(ioExceptions.size() * 2, counter.get());
    Assert.assertEquals(ioExceptions.size(), ex.getSuppressed().length);
  }

  @Ignore // This one doesn't quite work right, it will throw the IOException, but JUnit doesn't detect it properly and treats it as suppressed instead
  @Test(expected = IOException.class)
  public void testCloserException()
  {
    closer.closeLater(
        new Closeable()
        {
          @Override
          public void close() throws IOException
          {
            throw new IOException("This is a test");
          }
        }
    );
  }

  private void run(CloserRule closer, final Runnable runnable) throws Throwable
  {
    closer.apply(
        new Statement()
        {
          @Override
          public void evaluate() throws Throwable
          {
            runnable.run();
          }
        }, Description.createTestDescription(
            CloserRuleTest.class.getCanonicalName(), "baseRunner", UUID.randomUUID()
        )
    ).evaluate();
  }
}


text:
from os import path
from setuptools import setup, find_packages

here = path.abspath(path.dirname(__file__))

with open('requirements.txt') as f:
    install_requires = f.read().splitlines()

with open("README.md", "r") as fh:
    long_description = fh.read()

setup(
    name='appknox',
    version='4.2.1',
    description='Command-line interface & Python wrapper for the Appknox API',
    long_description=long_description,
    url='https://github.com/appknox/appknox-python',
    long_description_content_type="text/markdown",
    author='Appknox',
    author_email='engineering@appknox.com',
    license='MIT',
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'Topic :: Software Development :: Build Tools',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.5',
    ],

    keywords='appknox xysec rest api wrapper cli mobile security',
    packages=find_packages(),
    py_modules=['appknox'],
    entry_points='''
        [console_scripts]
        appknox=appknox.cli:main
    ''',
    install_requires=install_requires,
    extras_require={
        'dev': [''],
        'test': [''],
    },
)