text:
#include "../prConfig.h"

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include "prFile.h"
#include "prFileShared.h"
#include "prFileManager.h"
#include "../debug/prAssert.h"
#include "../debug/prTrace.h"
#include "../debug/prDebug.h"
#include "../core/prCore.h"
#include "../core/prMacros.h"
#include "../core/prStringUtil.h"

#if defined(PLATFORM_ANDROID)
#include <android/log.h>
#include <libzip/zip.h>
#include <libzip/zipint.h>
#endif

//#define FILE_LOG_CREATE

//using namespace Proteus::Core;

/// ---------------------------------------------------------------------------
/// prFile operation mode.
/// ---------------------------------------------------------------------------
enum prFileMode
{
    FileMode_None,                                      // No file operation has been performed yet!
    FileMode_Normal,                                    // The user opens, reads, closes the file. User also can optionally use their read buffer.
    FileMode_Simple,                                    // The simply calls load. Data is held within file until the file is deleted.
};

/// ---------------------------------------------------------------------------
/// Implementation data
/// ---------------------------------------------------------------------------
typedef struct FileImplementation
{
    // Ctor
    FileImplementation() : filemode     (FileMode_None)
                         , filesize     (0xFFFFFFFF)
                         , filePointer  (0)
    {
        filedata    = nullptr;
        pFile       = nullptr;
        //filemode    = FileMode_None; //cppcheck only triggred these 3?
//        filesize    = 0xFFFFFFFF;
  //      filePointer = 0;
        opened      = false;
        loaded      = false;
        locked      = false;
        inArchive   = false;

        memset(filenameArch, 0, sizeof(filenameArch));
        memset(filenameDisk, 0, sizeof(filenameDisk));
        memset(filenameOrig, 0, sizeof(filenameOrig));

        #if defined(PLATFORM_ANDROID)
        pZipFile    = nullptr;
        bytesRead   = 0;
        #endif
    }

    // Dtor
    ~FileImplementation()
    {
        PRSAFE_DELETE(filedata);
    }

    // Checks for file errors.
    bool WasThereAFileError()
    {
        bool result = false;

        if (pFile)
        {
            if (ferror(pFile))
            {
                const char *message = strerror(errno);

                clearerr(pFile);

                if (message && *message)
                {
                    PRWARN(message);
                }

                result = true;
            }
        }

        return result;
    }

    // Data
    u8         *filedata;                               // Pointer to the files data.
    FILE       *pFile;                                  // Internal file use.
    prFileMode  filemode;                               // Mode of operation.
    char        filenameArch[FILE_MAX_FILENAME_SIZE];   // The files name. (Archive)
    char        filenameDisk[FILE_MAX_FILENAME_SIZE];   // The files name. (With system path added)
    char        filenameOrig[FILE_MAX_FILENAME_SIZE];   // The files name. (Original unaltered)
    u32         filesize;                               // Files size.
    s32         filePointer;                            // prFile position pointer
    bool        opened;                                 // Has the file been opened with Open()
    bool        loaded;                                 // Files loaded/unloaded state.
    bool        locked;                                 // Files locked/unlocked state.
    bool        inArchive;                              // Is the file in the archive?

    #if defined(PLATFORM_ANDROID)
    zip_file   *pZipFile;
    u32         bytesRead;
    #endif

} FileImplementation;

/// ---------------------------------------------------------------------------
/// Ctor.
/// ---------------------------------------------------------------------------
prFile::prFile(const char *filename) : pImpl (new FileImplementation())
                                     , imp   (*pImpl)
{
    PRASSERT(pImpl);
    PRASSERT(filename && *filename);
    PRASSERT(strlen(filename) < FILE_MAX_FILENAME_SIZE);

    // Ensures name is long enough to skip past 'data/'
    PRASSERT(strlen(filename) > 5);

    // Ensures we have a filemanager
    prFileManager *pFM = static_cast<prFileManager *>(prCoreGetComponent(PRSYSTEM_FILEMANAGER));
    PRASSERT(pFM)

    if (strlen(filename) < FILE_MAX_FILENAME_SIZE)
    {
        // Creates file names. One for the disk, one for the archive and keeps the original
        prStringCopySafe(imp.filenameArch, filename + 5, FILE_MAX_FILENAME_SIZE);
        prStringCopySafe(imp.filenameDisk, pFM->GetSystemPath(filename), FILE_MAX_FILENAME_SIZE);
        prStringCopySafe(imp.filenameOrig, filename, FILE_MAX_FILENAME_SIZE);

        // Must be lowercase
        prStringToLower(imp.filenameArch);

        // And use forward slashes
        prStringReplaceChar(imp.filenameArch, '\\', '/');
        prStringReplaceChar(imp.filenameDisk, '\\', '/');

        //prTrace(LogError, "ARC: %s\n", imp.filenameArch);
        //prTrace(LogError, "DSK: %s\n", imp.filenameDisk);
        //prTrace(LogError, "DRI: %s\n", imp.filenameOrig);
    }
    else
    {
        PRWARN("Filename was too long: %s", filename);
        imp.filenameArch[0] = 0;
        imp.filenameDisk[0] = 0;
        imp.filenameOrig[0] = 0;
    }

#ifdef FILE_LOG_CREATE
    {
        static int c = 0;
        PRLOGD("Created prFile: %i - '%s'\n", c++, filename);
    }
#endif
}

/// ---------------------------------------------------------------------------
/// Dtor.
/// ---------------------------------------------------------------------------
prFile::~prFile()
{
    Close();
    PRSAFE_DELETE(pImpl);
}

/// ---------------------------------------------------------------------------
/// Gets the size of the file.
/// ---------------------------------------------------------------------------
u32 prFile::Size() const
{
    PRASSERT(pImpl);
    return imp.filesize;
}

/// ---------------------------------------------------------------------------
/// Determines if the file exists
/// ---------------------------------------------------------------------------
bool prFile::Exists()
{
    PRASSERT(pImpl);

    // Get filemanager
    prFileManager *pFM = static_cast<prFileManager *>(prCoreGetComponent(PRSYSTEM_FILEMANAGER));
    PRASSERT(pFM)

    bool result = false;
    if (imp.filenameDisk[0] != 0 &&
        imp.filenameArch[0] != 0 )
    {
        u32 size = 0;

        // Check archive
        if (pFM->Ready()                     &&
            pFM->ArchiveCount() > 0          &&
            pFM->Exists(imp.filenameArch, size)
           )
        {
            result = true;
        }
        else
        {
#if defined(PLATFORM_ANDROID)
            // Open
            zip* pArchive = prGetAPKArchive();
            if (pArchive)
            {
                prFileManager *pFileManager = static_cast<prFileManager*>(prCoreGetComponent(PRSYSTEM_FILEMANAGER));
                PRASSERT(pFileManager);

                imp.pZipFile = zip_fopen(pArchive, pFileManager->GetSystemPath(imp.filenameArch), 0);
                if (imp.pZipFile)
                {
                    result = true;
                    zip_fclose(imp.pZipFile);
                    imp.pZipFile = nullptr;
                }
                else
                {
                    __android_log_print(ANDROID_LOG_ERROR, "Proteus", "Open: Failed to open file: %s\n", pFileManager->GetSystemPath(imp.filenameArch));
                }
            }
            else
            {
                __android_log_print(ANDROID_LOG_ERROR, "Proteus", "Failed to get zip archive");
            }

#else
            // Check disk
            imp.pFile = fopen(imp.filenameDisk, "r");

            if (imp.pFile)
            {
                // Errors?
                result = !imp.WasThereAFileError();
                fclose(imp.pFile);
                imp.pFile = nullptr;
            }
            else
            {
                prTrace(prLogLevel::LogError, "File does not exist %s\n", imp.filenameDisk);
            }
#endif
        }
    }

    return result;
}

/// ---------------------------------------------------------------------------
/// Opens a file for reading.
/// ---------------------------------------------------------------------------
bool prFile::Open()
{
    PRASSERT(pImpl);

    // Calling open again?
    if (imp.opened)
    {
        return true;
    }

#if defined(PLATFORM_ANDROID)
    // Check mode.
    PRASSERT(imp.filemode != FileMode_Simple, "You cannot open file created by the Load() method.");

    // Open
    zip* pArchive = prGetAPKArchive();
    if (pArchive)
    {
        prFileManager *pFileManager = static_cast<prFileManager*>(prCoreGetComponent(PRSYSTEM_FILEMANAGER));
        PRASSERT(pFileManager);

        imp.pZipFile = zip_fopen(pArchive, pFileManager->GetSystemPath(imp.filenameArch), 0);
        if (imp.pZipFile)
        {
            imp.filesize  = imp.pZipFile->bytes_left;
            imp.filemode  = FileMode_Normal;
            imp.opened    = true;
            imp.bytesRead = 0;
        }
        else
        {
            __android_log_print(ANDROID_LOG_ERROR, "Proteus", "Open: Failed to open file: %s\n", pFileManager->GetSystemPath(imp.filenameArch));
        }
    }
    else
    {
        __android_log_print(ANDROID_LOG_ERROR, "Proteus", "Failed to get zip archive");
    }

#else

    // Get filemanager
    prFileManager *pFM = static_cast<prFileManager *>(prCoreGetComponent(PRSYSTEM_FILEMANAGER));
    PRASSERT(pFM)

    // Archives registered?
    if (pFM->Ready() && pFM->ArchiveCount() > 0)
    {
        u32 size = 0;

        if (pFM->Exists(imp.filenameArch, size))
        {
            // Okay files open.
            imp.filemode  = FileMode_Normal;
            imp.opened    = true;
            imp.inArchive = true;
            imp.filesize  = size;
            return true;
        }
    }

    // Check mode.
    PRASSERT(imp.filemode != FileMode_Simple, "You cannot open file created by the Load() method.");

    // Open the file?
    imp.pFile = fopen(imp.filenameDisk, "rb");
    if (imp.pFile == nullptr)
    {
        // Show error
        imp.WasThereAFileError();
        prTrace(prLogLevel::LogError, "STD: Failed to open file: %s\n", imp.filenameDisk);
        prTrace(prLogLevel::LogError, "STD: Trying to open file: %s\n", imp.filenameOrig);

        imp.pFile = fopen(imp.filenameOrig, "rb");
        if (imp.pFile == nullptr)
        {
            // Show error
            prTrace(prLogLevel::LogError, "STD: Failed to open file: %s\n", imp.filenameOrig);
            imp.WasThereAFileError();
            return false;
        }
    }

    // Get the files size.
    if (fseek(imp.pFile, 0, SEEK_END) == 0)
    {
        imp.filesize = (u32)ftell(imp.pFile);
        rewind(imp.pFile);
    }
    else
    {
        // Show error
        imp.WasThereAFileError();
        fclose(imp.pFile);
        imp.pFile = nullptr;
        return false;
    }

#endif

    // Okay files open.
    imp.filemode = FileMode_Normal;
    imp.opened   = true;
    return true;
}

/// ---------------------------------------------------------------------------
/// Closes a file
/// ---------------------------------------------------------------------------
void prFile::Close()
{
    PRASSERT(pImpl);

    // Check mode.
    if (imp.filemode == FileMode_Simple)
    {
        prTrace(prLogLevel::LogError, "You cannot call close on files created by the Load() method\n");
        return;
    }

#if defined(PLATFORM_ANDROID)
    // Close
    if (imp.pZipFile)
    {
        zip_fclose(imp.pZipFile);
        imp.pZipFile  = nullptr;
        imp.bytesRead = 0;
    }

#else
    // Close
    if (imp.pFile)
    {
        fclose(imp.pFile);
        imp.pFile = nullptr;
    }

#endif

    imp.opened   = false;
    imp.filemode = FileMode_None;
}

/// ---------------------------------------------------------------------------
/// Reads data from an open file
/// ---------------------------------------------------------------------------
u32 prFile::Read(void *pDataBuffer, u32 size)
{
    // Sanity checks
    PRASSERT(pImpl        != nullptr);
    PRASSERT(imp.opened   == true);
    PRASSERT(imp.filemode == FileMode_Normal);
    PRASSERT(pDataBuffer  != nullptr);
    PRASSERT(size > 0);

    // Get filemanager
    prFileManager *pFM = static_cast<prFileManager *>(prCoreGetComponent(PRSYSTEM_FILEMANAGER));
    PRASSERT(pFM)

    size_t bytes = 0xFFFFFFFF;
    if (imp.inArchive)
    {
        bytes = pFM->Read((u8*)pDataBuffer, size, prStringHash(imp.filenameArch));

        #if defined(PLATFORM_ANDROID)
        __android_log_print(ANDROID_LOG_ERROR, "Proteus", "Error: File found in archive");
        #endif
    }
    else
    {
#if defined(PLATFORM_ANDROID)
        // Read from disk.
        PRASSERT(imp.pZipFile != nullptr);
        bytes = zip_fread(imp.pZipFile, pDataBuffer, size);
        imp.bytesRead += bytes;
        //__android_log_print(ANDROID_LOG_ERROR, "Proteus", "Loaded: %s", imp.filenameArch);

#else
        // Read from disk.
        PRASSERT(imp.pFile != nullptr);

        bytes = fread(pDataBuffer, 1, size, imp.pFile);

        //if (bytes != size)
        //{
        //    Trace("Bytes read did not equal sized passed.\n");
        //    Trace("This may not be an error.\n");
        //}

        if (ferror(imp.pFile))
        {
            imp.WasThereAFileError();
        }
#endif
    }

    return (u32)bytes;
}

/// ---------------------------------------------------------------------------
/// Seek within an open file.
/// ---------------------------------------------------------------------------
void prFile::Seek(s32 offset, s32 origin)
{
    // Sanity checks
    PRASSERT(pImpl);

    if (imp.inArchive)
    {
        PRPANIC("Not implemented");
    }
    else
    {
        Internal_Seek(offset, origin);
    }
}

/// ---------------------------------------------------------------------------
/// Returns the file pointers position.
/// ---------------------------------------------------------------------------
s32 prFile::Tell() const
{
    // Sanity checks
    PRASSERT(pImpl);

    if (imp.inArchive)
    {
        PRPANIC("Not implemented");
    }
    else
    {
        return Internal_Tell();
    }

    return -1;
}

/// ---------------------------------------------------------------------------
/// Sets the file pointer back to the start of the file.
/// ---------------------------------------------------------------------------
void prFile::Rewind()
{
    // Sanity checks
    PRASSERT(pImpl);

    if (imp.inArchive)
    {
        PRPANIC("Not implemented");
    }
    else
    {
        return Internal_Rewind();
    }
}

/// ---------------------------------------------------------------------------
/// Rewind to the start of the file
/// ---------------------------------------------------------------------------
void prFile::Internal_Rewind()
{
    PRASSERT(pImpl);
    PRASSERT(imp.pFile);

    rewind(imp.pFile);
}

/// ---------------------------------------------------------------------------
/// Seeks to a position within a file
/// ---------------------------------------------------------------------------
void prFile::Internal_Seek(s32 offset, s32 origin)
{
    PRASSERT(pImpl);
    PRASSERT(PRBETWEEN(origin, PRFILE_SEEK_SET, PRFILE_SEEK_END));

#if defined(PLATFORM_ANDROID)
    PRASSERT(imp.pZipFile != nullptr);

    // Read to simulate seek
    if (origin == PRFILE_SEEK_CUR)
    {
        u8 *pData = new u8[offset];
        imp.bytesRead += zip_fread(imp.pZipFile, pData, offset);
        PRSAFE_DELETE_ARRAY(pData);
    }
    // Reads from start to simulate seek set.
    else if (origin == PRFILE_SEEK_SET)
    {
        zip* pArchive = prGetAPKArchive();
        if (pArchive)
        {
            // Close the old file.
            zip_fclose(imp.pZipFile);
            imp.pZipFile  = nullptr;
            imp.bytesRead = 0;

            prFileManager *pFileManager = static_cast<prFileManager*>(prCoreGetComponent(PRSYSTEM_FILEMANAGER));
            PRASSERT(pFileManager);

            // Reopen file to get back to start!
            imp.pZipFile = zip_fopen(pArchive, pFileManager->GetSystemPath(imp.filenameArch), 0);
            if (imp.pZipFile)
            {
                // Seek to the point asked.
                u8 *pData = new u8[offset];
                imp.bytesRead += zip_fread(imp.pZipFile, pData, offset);
                PRSAFE_DELETE_ARRAY(pData);
            }
        }
    }
    else if (origin == PRFILE_SEEK_END)
    {
    }
    else
    {
        PRPANIC("Unknown origin");
    }

#else
    PRASSERT(imp.pFile);
    fseek(imp.pFile, offset, origin);

#endif
}

/// ---------------------------------------------------------------------------
/// Returns the current file pointer position
/// ---------------------------------------------------------------------------
s32 prFile::Internal_Tell() const
{
    PRASSERT(pImpl);

#if defined(PLATFORM_ANDROID)
    return imp.bytesRead;

#else
    PRASSERT(imp.pFile);
    return (s32)ftell(imp.pFile);

#endif
}

// ----------------------------------------------------------------------------
//
// ----------------------------------------------------------------------------
/*bool prFile::Internal_FileDataLoaded()
{
    PRASSERT(pImpl);
    return (imp.filedata != nullptr);
}

// ----------------------------------------------------------------------------
//
// ----------------------------------------------------------------------------
void prFile::Internal_SetFileData(u8 *pData)
{
    PRASSERT(pImpl);
    PRASSERT(pData);

    if (pData)
    {
    }
}*/


text:
import unittest

class VersionTestCase(unittest.TestCase):
    """
    Test case for the version module.
    """

    def test_attributes(self):
        """
        Tests the version module attributes.
        """
        from flx import version

        self.assertFalse(version.__dict__ is None)
        self.assertTrue('__version__' in version.__dict__)

redpajama_set_name: RedPajamaGithub


text:
layout: "aws"
page_title: "AWS: aws_route_table"
sidebar_current: "docs-aws-resource-route-table|"
description: |-
  Provides a resource to create a VPC routing table.
---

# aws\_route\_table

Provides a resource to create a VPC routing table.

~> **NOTE on Route Tables and Routes:** Terraform currently
provides both a standalone [Route resource](route.html) and a Route Table resource with routes
defined in-line. At this time you cannot use a Route Table with in-line routes
in conjunction with any Route resources. Doing so will cause
a conflict of rule settings and will overwrite rules.

## Example usage with tags:

```
resource "aws_route_table" "r" {
    vpc_id = "${aws_vpc.default.id}"
    route {
        cidr_block = "10.0.1.0/24"
        gateway_id = "${aws_internet_gateway.main.id}"
    }

	tags {
		Name = "main"
	}
}
```

## Argument Reference

The following arguments are supported:

* `vpc_id` - (Required) The ID of the routing table.
* `route` - (Optional) A list of route objects. Their keys are documented below.
* `tags` - (Optional) A mapping of tags to assign to the resource.
* `propagating_vgws` - (Optional) A list of virtual gateways for propagation.

Each route supports the following:

* `cidr_block` - (Required) The CIDR block of the route.
* `gateway_id` - (Optional) The Internet Gateway ID.
* `nat_gateway_id` - (Optional) The NAT Gateway ID.
* `instance_id` - (Optional) The EC2 instance ID.
* `vpc_peering_connection_id` - (Optional) The VPC Peering ID.
* `network_interface_id` - (Optional) The ID of the elastic network interface (eni) to use.

Each route must contain either a `gateway_id`, an `instance_id`, a `nat_gateway_id`, a
`vpc_peering_connection_id` or a `network_interface_id`. Note that the default route, mapping
the VPC's CIDR block to "local", is created implicitly and cannot be specified.

## Attributes Reference

The following attributes are exported:
~> **NOTE:** Only the target that is entered is exported as a readable
attribute once the route resource is created.

* `id` - The ID of the routing table


text:
  margin: auto !important;
  margin-top: 50px !important;
}
.jiathis_style_32x32 {
  height: 32px;
  -webkit-filter: grayscale(60%);
  -moz-filter: grayscale(60%);
  -ms-filter: grayscale(60%);
  -o-filter: grayscale(60%);
  filter: grayscale(60%);
  transition-duration: 0.5s;
  transition-property: filter, -webkit-filter, -moz-filter, -ms-filter, -o-filter;
}
.jiathis_style_32x32:hover {
  -webkit-filter: grayscale(0%);
  -moz-filter: grayscale(0%);
  -ms-filter: grayscale(0%);
  -o-filter: grayscale(0%);
  filter: grayscale(0%);
}
.jiathis_style > div {
  border: none !important;
}
.main-content .jiathis_style_32x32 .jtico {
  display: inline-block !important;
}
.jiathis_style .ckepopBottom {
  padding: 5px;
}


text:
cmd=run.pl
num_epochs=15      # Number of epochs of training;
                   # the number of iterations is worked out from this.
initial_effective_lrate=0.01
final_effective_lrate=0.001
rand_prune=4.0 # Relates to a speedup we do for LDA.
minibatch_size=512  # This default is suitable for GPU-based training.
                    # Set it to 128 for multi-threaded CPU-based training.
max_param_change=2.0  # max param change per minibatch
samples_per_iter=400000 # each iteration of training, see this many samples
                        # per job.  This option is passed to get_egs.sh
num_jobs_initial=1  # Number of neural net jobs to run in parallel at the start of training
num_jobs_final=8   # Number of neural net jobs to run in parallel at the end of training
prior_subset_size=20000 # 20k samples per job, for computing priors.
num_jobs_compute_prior=10 # these are single-threaded, run on CPU.
get_egs_stage=0    # can be used for rerunning after partial
online_ivector_dir=
remove_egs=true  # set to false to disable removing egs after training is done.

max_models_combine=20 # The "max_models_combine" is the maximum number of models we give
  # to the final 'combine' stage, but these models will themselves be averages of
  # iteration-number ranges.

shuffle_buffer_size=5000 # This "buffer_size" variable controls randomization of the samples
                # on each iter.  You could set it to 0 or to a large value for complete
                # randomization, but this would both consume memory and cause spikes in
                # disk I/O.  Smaller is easier on disk and memory but less random.  It's
                # not a huge deal though, as samples are anyway randomized right at the start.
                # (the point of this is to get data in different minibatches on different iterations,
                # since in the preconditioning method, 2 samples in the same minibatch can
                # affect each others' gradients.

add_layers_period=2 # by default, add new layers every 2 iterations.
stage=-6
exit_stage=-100 # you can set this to terminate the training early.  Exits before running this stage

chunk_training=false  # if true training is done with chunk randomization, rather than frame randomization

randprune=4.0 # speeds up LDA.
use_gpu=true    # if true, we run on GPU.
cleanup=true
egs_dir=
configs_dir=
max_lda_jobs=10  # use no more than 10 jobs for the LDA accumulation.
lda_opts=
egs_opts=
transform_dir=     # If supplied, this dir used instead of alidir to find transforms.
cmvn_opts=  # will be passed to get_lda.sh and get_egs.sh, if supplied.
frames_per_eg=8 # to be passed on to get_egs.sh

# Raw nnet training options i.e. without transition model
nj=4
dense_targets=true        # Use dense targets instead of sparse targets

# End configuration section.

trap 'for pid in $(jobs -pr); do kill -KILL $pid; done' INT QUIT TERM

echo "$0 $@"  # Print the command line for logging

if [ -f path.sh ]; then . ./path.sh; fi
. parse_options.sh || exit 1;

if [ $# != 3 ]; then
  echo "Usage: $0 [opts] <data> <targets-scp> <exp-dir>"
  echo " e.g.: $0 data/train scp:snr_targets/targets.scp exp/nnet3_snr_predictor"
  echo ""
  echo "Main options (for others, see top of script file)"
  echo "  --config <config-file>                           # config file containing options"
  echo "  --cmd (utils/run.pl|utils/queue.pl <queue opts>) # how to run jobs."
  echo "  --num-epochs <#epochs|15>                        # Number of epochs of training"
  echo "  --initial-effective-lrate <lrate|0.02> # effective learning rate at start of training."
  echo "  --final-effective-lrate <lrate|0.004>   # effective learning rate at end of training."
  echo "                                                   # data, 0.00025 for large data"
  echo "  --num-hidden-layers <#hidden-layers|2>           # Number of hidden layers, e.g. 2 for 3 hours of data, 4 for 100hrs"
  echo "  --add-layers-period <#iters|2>                   # Number of iterations between adding hidden layers"
  echo "  --num-jobs-initial <num-jobs|1>                  # Number of parallel jobs to use for neural net training, at the start."
  echo "  --num-jobs-final <num-jobs|8>                    # Number of parallel jobs to use for neural net training, at the end"
  echo "  --num-threads <num-threads|16>                   # Number of parallel threads per job, for CPU-based training (will affect"
  echo "                                                   # results as well as speed; may interact with batch size; if you increase"
  echo "                                                   # this, you may want to decrease the batch size."
  echo "  --parallel-opts <opts|\"-pe smp 16 -l ram_free=1G,mem_free=1G\">      # extra options to pass to e.g. queue.pl for processes that"
  echo "                                                   # use multiple threads... note, you might have to reduce mem_free,ram_free"
  echo "                                                   # versus your defaults, because it gets multiplied by the -pe smp argument."
  echo "  --minibatch-size <minibatch-size|128>            # Size of minibatch to process (note: product with --num-threads"
  echo "                                                   # should not get too large, e.g. >2k)."
  echo "  --samples-per-iter <#samples|400000>             # Number of samples of data to process per iteration, per"
  echo "                                                   # process."
  echo "  --splice-indexes <string|layer0/-4:-3:-2:-1:0:1:2:3:4> "
  echo "                                                   # Frame indices used for each splice layer."
  echo "                                                   # Format : layer<hidden_layer_index>/<frame_indices>....layer<hidden_layer>/<frame_indices> "
  echo "                                                   # (note: we splice processed, typically 40-dimensional frames"
  echo "  --lda-dim <dim|''>                               # Dimension to reduce spliced features to with LDA"
  echo "  --stage <stage|-4>                               # Used to run a partially-completed training process from somewhere in"
  echo "                                                   # the middle."

  exit 1;
fi

data=$1
targets_scp=$2
dir=$3

# Check some files.
for f in $data/feats.scp $targets_scp; do
  [ ! -f $f ] && echo "$0: no such file $f" && exit 1;
done

# in this dir we'll have just one job.
sdata=$data/split$nj
utils/split_data.sh $data $nj

mkdir -p $dir/log
echo $nj > $dir/num_jobs

# First work out the feature and iVector dimension, needed for tdnn config creation.
feat_dim=$(feat-to-dim --print-args=false scp:$data/feats.scp -) || \
      { echo "$0: Error getting feature dim"; exit 1; }

if [ -z "$online_ivector_dir" ]; then
  ivector_dim=0
else
  ivector_dim=$(feat-to-dim scp:$online_ivector_dir/ivector_online.scp -) || exit 1;
fi

if [ ! -z "$configs_dir" ]; then
  cp -rT $configs_dir $dir/configs || exit 1
fi

if [ $stage -le -5 ]; then
  # Initialize as "raw" nnet, prior to training the LDA-like preconditioning
  # matrix.  This first config just does any initial splicing that we do;
  # we do this as it's a convenient way to get the stats for the 'lda-like'
  # transform.
  $cmd $dir/log/nnet_init.log \
    nnet3-init --srand=-2 $dir/configs/init.config $dir/init.raw || exit 1;
fi

# sourcing the "vars" below sets
# model_left_context=(something)
# model_right_context=(something)
# num_hidden_layers=(something)
# num_targets=(something)
# add_lda=(true|false)
# include_log_softmax=(true|false)
# objective_type=(something)
. $dir/configs/vars || exit 1;
left_context=$model_left_context
right_context=$model_right_context

[ -z "$num_targets" ] && echo "\$num_targets is not defined. Needs to be defined in $dir/configs/vars." && exit 1
[ -z "$add_lda" ] && echo "\$add_lda is not defined. Needs to be defined in $dir/configs/vars." && exit 1
[ -z "$include_log_softmax" ] && echo "\$include_log_softmax is not defined. Needs to be defined in $dir/configs/vars." && exit 1
[ -z "$objective_type" ] && echo "\$objective_type is not defined. Needs to be defined in $dir/configs/vars." && exit 1

context_opts="--left-context=$left_context --right-context=$right_context"

! [ "$num_hidden_layers" -gt 0 ] && echo \
 "$0: Expected num_hidden_layers to be defined" && exit 1;

if $dense_targets; then
  tmp_num_targets=`feat-to-dim scp:$targets_scp - 2>/dev/null` || exit 1

  if [ $tmp_num_targets -ne $num_targets ]; then
    echo "Mismatch between num-targets provided to script vs configs"
    exit 1
  fi
fi

if [ $stage -le -4 ] && [ -z "$egs_dir" ]; then
  extra_opts=()
  [ ! -z "$cmvn_opts" ] && extra_opts+=(--cmvn-opts "$cmvn_opts")
  [ ! -z "$feat_type" ] && extra_opts+=(--feat-type $feat_type)
  [ ! -z "$online_ivector_dir" ] && extra_opts+=(--online-ivector-dir $online_ivector_dir)
  extra_opts+=(--transform-dir "$transform_dir")
  extra_opts+=(--left-context $left_context)
  extra_opts+=(--right-context $right_context)
  echo "$0: calling get_egs.sh"

  if $dense_targets; then
    target_type=dense
  else
    target_type=sparse
  fi

  steps/nnet3/get_egs_targets.sh $egs_opts "${extra_opts[@]}" \
    --samples-per-iter $samples_per_iter --stage $get_egs_stage \
    --cmd "$cmd" --nj $nj \
    --frames-per-eg $frames_per_eg \
    --target-type $target_type --num-targets $num_targets \
    $data $targets_scp $dir/egs || exit 1;
fi

[ -z $egs_dir ] && egs_dir=$dir/egs

if [ "$feat_dim" != "$(cat $egs_dir/info/feat_dim)" ]; then
  echo "$0: feature dimension mismatch with egs, $feat_dim vs $(cat $egs_dir/info/feat_dim)";
  exit 1;
fi
if [ "$ivector_dim" != "$(cat $egs_dir/info/ivector_dim)" ]; then
  echo "$0: ivector dimension mismatch with egs, $ivector_dim vs $(cat $egs_dir/info/ivector_dim)";
  exit 1;
fi

# copy any of the following that exist, to $dir.
cp $egs_dir/{cmvn_opts,splice_opts,final.mat} $dir 2>/dev/null

# confirm that the egs_dir has the necessary context (especially important if
# the --egs-dir option was used on the command line).
egs_left_context=$(cat $egs_dir/info/left_context) || exit -1
egs_right_context=$(cat $egs_dir/info/right_context) || exit -1
 ( [ $egs_left_context -lt $left_context ] || \
   [ $egs_right_context -lt $right_context ] ) && \
   echo "$0: egs in $egs_dir have too little context" && exit -1;

frames_per_eg=$(cat $egs_dir/info/frames_per_eg) || { echo "error: no such file $egs_dir/info/frames_per_eg"; exit 1; }
num_archives=$(cat $egs_dir/info/num_archives) || { echo "error: no such file $egs_dir/info/frames_per_eg"; exit 1; }

# num_archives_expanded considers each separate label-position from
# 0..frames_per_eg-1 to be a separate archive.
if [ "$chunk_training" == "true" ]; then
  num_archives_expanded=$num_archives
else
  num_archives_expanded=$[$num_archives*$frames_per_eg]
fi

[ $num_jobs_initial -gt $num_jobs_final ] && \
  echo "$0: --initial-num-jobs cannot exceed --final-num-jobs" && exit 1;

[ $num_jobs_final -gt $num_archives_expanded ] && \
  echo "$0: --final-num-jobs cannot exceed #archives $num_archives_expanded." && exit 1;

if $add_lda && [ $stage -le -3 ]; then
  echo "$0: getting preconditioning matrix for input features."
  num_lda_jobs=$num_archives
  [ $num_lda_jobs -gt $max_lda_jobs ] && num_lda_jobs=$max_lda_jobs

  # Write stats with the same format as stats for LDA.
  $cmd JOB=1:$num_lda_jobs $dir/log/get_lda_stats.JOB.log \
      nnet3-acc-lda-stats --rand-prune=$rand_prune \
        $dir/init.raw "ark:$egs_dir/egs.JOB.ark" $dir/JOB.lda_stats || exit 1;

  all_lda_accs=$(for n in $(seq $num_lda_jobs); do echo $dir/$n.lda_stats; done)
  $cmd $dir/log/sum_transform_stats.log \
    sum-lda-accs $dir/lda_stats $all_lda_accs || exit 1;

  rm $all_lda_accs || exit 1;

  # this computes a fixed affine transform computed in the way we described in
  # Appendix C.6 of http://arxiv.org/pdf/1410.7455v6.pdf; it's a scaled variant
  # of an LDA transform but without dimensionality reduction.
  $cmd $dir/log/get_transform.log \
     nnet-get-feature-transform $lda_opts $dir/lda.mat $dir/lda_stats || exit 1;

  ln -sf ../lda.mat $dir/configs/lda.mat
fi

if [ $stage -le -1 ]; then
  # Add the first layer; this will add in the lda.mat
  $cmd $dir/log/add_first_layer.log \
       nnet3-init --srand=-3 $dir/init.raw $dir/configs/layer1.config $dir/0.raw || exit 1;

fi

# set num_iters so that as close as possible, we process the data $num_epochs
# times, i.e. $num_iters*$avg_num_jobs) == $num_epochs*$num_archives_expanded,
# where avg_num_jobs=(num_jobs_initial+num_jobs_final)/2.

num_archives_to_process=$[$num_epochs*$num_archives_expanded]
num_archives_processed=0
num_iters=$[($num_archives_to_process*2)/($num_jobs_initial+$num_jobs_final)]

finish_add_layers_iter=$[$num_hidden_layers * $add_layers_period]

! [ $num_iters -gt $[$finish_add_layers_iter+2] ] \
  && echo "$0: Insufficient epochs" && exit 1

echo "$0: Will train for $num_epochs epochs = $num_iters iterations"

if $use_gpu; then
  parallel_suffix=""
  train_queue_opt="--gpu 1"
  combine_queue_opt="--gpu 1"
  prior_gpu_opt="--use-gpu=yes"
  prior_queue_opt="--gpu 1"
  parallel_train_opts=
  if ! cuda-compiled; then
    echo "$0: WARNING: you are running with one thread but you have not compiled"
    echo "   for CUDA.  You may be running a setup optimized for GPUs.  If you have"
    echo "   GPUs and have nvcc installed, go to src/ and do ./configure; make"
    exit 1
  fi
else
  echo "$0: without using a GPU this will be very slow.  nnet3 does not yet support multiple threads."
  parallel_train_opts="--use-gpu=no"
  combine_queue_opt=""  # the combine stage will be quite slow if not using
                        # GPU, as we didn't enable that program to use
                        # multiple threads.
  prior_gpu_opt="--use-gpu=no"
  prior_queue_opt=""
fi

approx_iters_per_epoch_final=$[$num_archives_expanded/$num_jobs_final]
# First work out how many iterations we want to combine over in the final
# nnet3-combine-fast invocation.  (We may end up subsampling from these if the
# number exceeds max_model_combine).  The number we use is:
# min(max(max_models_combine, approx_iters_per_epoch_final),
#     1/2 * iters_after_last_layer_added)
num_iters_combine=$max_models_combine
if [ $num_iters_combine -lt $approx_iters_per_epoch_final ]; then
   num_iters_combine=$approx_iters_per_epoch_final
fi
half_iters_after_add_layers=$[($num_iters-$finish_add_layers_iter)/2]
if [ $num_iters_combine -gt $half_iters_after_add_layers ]; then
  num_iters_combine=$half_iters_after_add_layers
fi
first_model_combine=$[$num_iters-$num_iters_combine+1]

x=0

compute_accuracy=false
if [ "$objective_type" == "linear" ]; then
  compute_accuracy=true
fi

while [ $x -lt $num_iters ]; do
  [ $x -eq $exit_stage ] && echo "$0: Exiting early due to --exit-stage $exit_stage" && exit 0;

  this_num_jobs=$(perl -e "print int(0.5+$num_jobs_initial+($num_jobs_final-$num_jobs_initial)*$x/$num_iters);")

  ilr=$initial_effective_lrate; flr=$final_effective_lrate; np=$num_archives_processed; nt=$num_archives_to_process;
  this_learning_rate=$(perl -e "print (($x + 1 >= $num_iters ? $flr : $ilr*exp($np*log($flr/$ilr)/$nt))*$this_num_jobs);");

  echo "On iteration $x, learning rate is $this_learning_rate."

  if [ $x -ge 0 ] && [ $stage -le $x ]; then

    # Set off jobs doing some diagnostics, in the background.
    # Use the egs dir from the previous iteration for the diagnostics
    $cmd $dir/log/compute_prob_valid.$x.log \
      nnet3-compute-prob --compute-accuracy=$compute_accuracy $dir/$x.raw \
      "ark,bg:nnet3-merge-egs ark:$egs_dir/valid_diagnostic.egs ark:- |" &
    $cmd $dir/log/compute_prob_train.$x.log \
      nnet3-compute-prob --compute-accuracy=$compute_accuracy $dir/$x.raw \
      "ark,bg:nnet3-merge-egs ark:$egs_dir/train_diagnostic.egs ark:- |" &

    if [ $x -gt 0 ]; then
      $cmd $dir/log/progress.$x.log \
        nnet3-show-progress --use-gpu=no $dir/$[x-1].raw $dir/$x.raw \
        "ark,bg:nnet3-merge-egs ark:$egs_dir/train_diagnostic.egs ark:-|" '&&' \
        nnet3-info $dir/$x.raw &
    fi

    echo "Training neural net (pass $x)"

    if [ $x -gt 0 ] && \
      [ $x -le $[($num_hidden_layers-1)*$add_layers_period] ] && \
      [ $[$x%$add_layers_period] -eq 0 ]; then
      do_average=false # if we've just mixed up, don't do averaging but take the
                       # best.
      cur_num_hidden_layers=$[1+$x/$add_layers_period]
      config=$dir/configs/layer$cur_num_hidden_layers.config
      raw="nnet3-copy --learning-rate=$this_learning_rate $dir/$x.raw - | nnet3-init --srand=$x - $config - |"
    else
      do_average=true
      if [ $x -eq 0 ]; then do_average=false; fi # on iteration 0, pick the best, don't average.
      raw="nnet3-copy --learning-rate=$this_learning_rate $dir/$x.raw -|"
    fi
    if $do_average; then
      this_minibatch_size=$minibatch_size
    else
      # on iteration zero or when we just added a layer, use a smaller minibatch
      # size (and we will later choose the output of just one of the jobs): the
      # model-averaging isn't always helpful when the model is changing too fast
      # (i.e. it can worsen the objective function), and the smaller minibatch
      # size will help to keep the update stable.
      this_minibatch_size=$[$minibatch_size/2];
    fi

    rm $dir/.error 2>/dev/null

    ( # this sub-shell is so that when we "wait" below,
      # we only wait for the training jobs that we just spawned,
      # not the diagnostic jobs that we spawned above.

      # We can't easily use a single parallel SGE job to do the main training,
      # because the computation of which archive and which --frame option
      # to use for each job is a little complex, so we spawn each one separately.
      for n in $(seq $this_num_jobs); do
        k=$[$num_archives_processed + $n - 1]; # k is a zero-based index that we'll derive
                                               # the other indexes from.
        archive=$[($k%$num_archives)+1]; # work out the 1-based archive index.
        frame=$[(($k/$num_archives)%$frames_per_eg)]; # work out the 0-based frame
        # index; this increases more slowly than the archive index because the
        # same archive with different frame indexes will give similar gradients,
        # so we want to separate them in time.

        $cmd $train_queue_opt $dir/log/train.$x.$n.log \
          nnet3-train $parallel_train_opts \
          --max-param-change=$max_param_change "$raw" \
          "ark,bg:nnet3-copy-egs --frame=$frame $context_opts ark:$egs_dir/egs.$archive.ark ark:- | nnet3-shuffle-egs --buffer-size=$shuffle_buffer_size --srand=$x ark:- ark:-| nnet3-merge-egs --minibatch-size=$this_minibatch_size --discard-partial-minibatches=true ark:- ark:- |" \
          $dir/$[$x+1].$n.raw || touch $dir/.error &
      done
      wait
    )
    # the error message below is not that informative, but $cmd will
    # have printed a more specific one.
    [ -f $dir/.error ] && echo "$0: error on iteration $x of training" && exit 1;

    nnets_list=
    for n in `seq 1 $this_num_jobs`; do
      nnets_list="$nnets_list $dir/$[$x+1].$n.raw"
    done

    if $do_average; then
      # average the output of the different jobs.
      $cmd $dir/log/average.$x.log \
        nnet3-average $nnets_list $dir/$[x+1].raw || exit 1;
    else
      # choose the best from the different jobs.
      n=$(perl -e '($nj,$pat)=@ARGV; $best_n=1; $best_logprob=-1.0e+10; for ($n=1;$n<=$nj;$n++) {
          $fn = sprintf($pat,$n); open(F, "<$fn") || die "Error opening log file $fn";
          undef $logprob; while (<F>) { if (m/log-prob-per-frame=(\S+)/) { $logprob=$1; } }
          close(F); if (defined $logprob && $logprob > $best_logprob) { $best_logprob=$logprob;
          $best_n=$n; } } print "$best_n\n"; ' $this_num_jobs $dir/log/train.$x.%d.log) || exit 1;
      [ -z "$n" ] && echo "Error getting best model" && exit 1;
      $cmd $dir/log/select.$x.log \
        nnet3-copy $dir/$[$x+1].$n.raw $dir/$[$x+1].raw || exit 1;
    fi

    rm $nnets_list
    [ ! -f $dir/$[$x+1].raw ] && exit 1;
    if [ -f $dir/$[$x-1].raw ] && $cleanup && \
       [ $[($x-1)%100] -ne 0  ] && [ $[$x-1] -lt $first_model_combine ]; then
      rm $dir/$[$x-1].raw
    fi
  fi
  x=$[$x+1]
  num_archives_processed=$[$num_archives_processed+$this_num_jobs]
done

if [ $stage -le $num_iters ]; then
  echo "Doing final combination to produce final.raw"

  # Now do combination.  In the nnet3 setup, the logic
  # for doing averaging of subsets of the models in the case where
  # there are too many models to reliably esetimate interpolation
  # factors (max_models_combine) is moved into the nnet3-combine
  nnets_list=()
  for n in $(seq 0 $[num_iters_combine-1]); do
    iter=$[$first_model_combine+$n]
    nnet=$dir/$iter.raw
    [ ! -f $nnet ] && echo "Expected $nnet to exist" && exit 1;
    nnets_list[$n]=$nnet
  done

  # Below, we use --use-gpu=no to disable nnet3-combine-fast from using a GPU,
  # as if there are many models it can give out-of-memory error; and we set
  # num-threads to 8 to speed it up (this isn't ideal...)

  $cmd $combine_queue_opt $dir/log/combine.log \
    nnet3-combine --num-iters=40 \
    --enforce-sum-to-one=true --enforce-positive-weights=true \
    --verbose=3 "${nnets_list[@]}" "ark,bg:nnet3-merge-egs --minibatch-size=1024 ark:$egs_dir/combine.egs ark:-|" \
    $dir/final.raw || exit 1;

  # Compute the probability of the final, combined model with
  # the same subset we used for the previous compute_probs, as the
  # different subsets will lead to different probs.
  $cmd $dir/log/compute_prob_valid.final.log \
    nnet3-compute-prob --compute-accuracy=$compute_accuracy $dir/final.raw \
    "ark,bg:nnet3-merge-egs ark:$egs_dir/valid_diagnostic.egs ark:- |" &
  $cmd $dir/log/compute_prob_train.final.log \
    nnet3-compute-prob --compute-accuracy=$compute_accuracy $dir/final.raw \
    "ark,bg:nnet3-merge-egs ark:$egs_dir/train_diagnostic.egs ark:- |" &
fi

if $include_log_softmax && [ $stage -le $[$num_iters+1] ]; then
  echo "Getting average posterior for purpose of using as prior to convert posteriors to likelihoods."
  # Note: this just uses CPUs, using a smallish subset of data.
  if [ $num_jobs_compute_prior -gt $num_archives ]; then egs_part=1;
  else egs_part=JOB; fi
  rm $dir/post.$x.*.vec 2>/dev/null
  $cmd JOB=1:$num_jobs_compute_prior $prior_queue_opt $dir/log/get_post.$x.JOB.log \
    nnet3-copy-egs --frame=random $context_opts --srand=JOB ark:$egs_dir/egs.$egs_part.ark ark:- \| \
    nnet3-subset-egs --srand=JOB --n=$prior_subset_size ark:- ark:- \| \
    nnet3-merge-egs ark:- ark:- \| \
    nnet3-compute-from-egs $prior_gpu_opt --apply-exp=true \
    $dir/final.raw ark:- ark:- \| \
    matrix-sum-rows ark:- ark:- \| vector-sum ark:- $dir/post.$x.JOB.vec || exit 1;

  sleep 3;  # make sure there is time for $dir/post.$x.*.vec to appear.

  $cmd $dir/log/vector_sum.$x.log \
   vector-sum $dir/post.$x.*.vec $dir/post.$x.vec || exit 1;

  rm -f $dir/post.$x.*.vec;

fi

if [ ! -f $dir/final.raw ]; then
  echo "$0: $dir/final.raw does not exist."
  # we don't want to clean up if the training didn't succeed.
  exit 1;
fi

sleep 2

echo Done

if $cleanup; then
  echo Cleaning up data
  if $remove_egs && [[ $egs_dir =~ $dir/egs* ]]; then
    steps/nnet2/remove_egs.sh $egs_dir
  fi

  echo Removing most of the models
  for x in `seq 0 $num_iters`; do
    if [ $[$x%100] -ne 0 ] && [ $x -ne $num_iters ] && [ -f $dir/$x.mdl ]; then
       # delete all but every 100th model; don't delete the ones which combine to form the final model.
      rm $dir/$x.raw
    fi
  done
fi


text:
## Schema

- Protocol: HTTPS only
- Domain: TBD
- Content type: JSON only
- Date format: ISO 8601 (YYYY-MM-DDTHH:MM:SSZ)

All valid GET requests return a json object as the response. GET requests return either a collection or an item in the data property.

A collection is returned as an array of objects:

```
{
    "data": [
        ...
    ],
    ...
}
```

An item is returned as an object:

```
{
    "data": {
        ...
    },
    ...
}
```

Other members can be used for metadata (e.g. links) and are described in the appropriate sections.

## Authentication

TBD - Key-based authentication managed by KIS. Likely to be a request to KIS-help to generate a new key.

## Pagination

All GET requests that return a collection are paginated with a default page length of 20. A specific page can be accessed by appending a `page` parameter to the query string. The number of items returned per page can be changed by appending a `per_page` parameter to the query string, up to a maximum of X.

The links field in the response contains navigable links (next, last, first, prev) for following. Somewhere in the response, it includes the total number of pages and current page.


text:
/*
 ________  ___       __   ___  ________
|\   ____\|\  \     |\  \|\  \|\   ____\
\ \  \___|\ \  \    \ \  \ \  \ \  \___|
 \ \_____  \ \  \  __\ \  \ \  \ \  \  ___
  \|____|\  \ \  \|\__\_\  \ \  \ \  \|\  \
    ____\_\  \ \____________\ \__\ \_______\
   |\_________\|____________|\|__|\|_______|
   \|_________|

   It's delicious.
   Brought to you by the fine folks at Gilt (http://github.com/gilt)
*/

  // c) Given the list of all extracted package.json's and the file picked above:
  // i) Extract the uiDependencies or dependencies hash from each file
  // ii) Merge with that, the lazyDependencies hash from the same file
  // NOTE) we build up an intermediate data structure, for error reporting purposes.
  // d) Iterate over each set of dependencies, merging them together intelligently, and look for
  // conflicts
  // i) Example of "intelligently" merging: given 2 versions of foo.bar, 1.2.3 and 1.2.x, merge
  // that as 1.2.3, since 1.2.x is a mask that 1.2.3 satisfies.
  // e) Generate a merged package.json file in a temp folder

// handles merging module packages
module.exports = function (gulp, swig) {
  return function packageMerge() {
    const _ = require('underscore');
    const fs = require('fs');
    const path = require('path');
    const gutil = require('gulp-util');
    const util = require('./merge-util')(gulp, swig);
    const merge = require('./merge')(gulp, swig, util);

    // figure out which type we're dealing with
    if (fs.existsSync(path.join(swig.cwd, 'app.js')) || fs.existsSync(path.join(swig.cwd, 'build.sbt'))) { // node or scala apps
      merge();
    } else if (swig.argv.module) {
      swig.log.task('Merging UI-* Module Package Dependencies');

      // enforce that this is a copy of swig.pkg.dependencies, and not a
      // reference. prevents other tasks from using a tainted object.
      const deps = _.extend({}, swig.pkg.dependencies || {});

      util.generate(deps);
    } else {
      throw new gutil.PluginError('package-merge',
      "Couldn't determine what type of thing we're working on.\n" +
      "If it's a Node app, it should have an 'app.js' file in the root.\n" +
      "If it's a Play/Scala app, it should have JARs in /lib.\n" +
      'Swig only supports Node and JVM apps, and ui-* module repos.');
    }
  };
};


text:
package com.intellij.psi.impl.source.tree.java;

import com.intellij.lang.ASTNode;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiImplUtil;
import com.intellij.psi.impl.source.Constants;
import com.intellij.psi.impl.source.tree.ChildRole;
import com.intellij.psi.impl.source.tree.CompositePsiElement;
import com.intellij.psi.scope.PsiScopeProcessor;
import com.intellij.psi.tree.ChildRoleBase;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NotNull;

/**
 * @author dsl
 */
public class PsiForeachStatementImpl extends CompositePsiElement implements PsiForeachStatement, Constants {
  private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.tree.java.PsiForeachStatementImpl");
  public PsiForeachStatementImpl() {
    super(FOREACH_STATEMENT);
  }

  @Override
  @NotNull
  public PsiParameter getIterationParameter() {
    return (PsiParameter) findChildByRoleAsPsiElement(ChildRole.FOR_ITERATION_PARAMETER);
  }

  @Override
  public PsiExpression getIteratedValue() {
    return (PsiExpression) findChildByRoleAsPsiElement(ChildRole.FOR_ITERATED_VALUE);
  }

  @Override
  public PsiStatement getBody() {
    return (PsiStatement) findChildByRoleAsPsiElement(ChildRole.LOOP_BODY);
  }

  @Override
  @NotNull
  public PsiJavaToken getLParenth() {
    return (PsiJavaToken) findChildByRoleAsPsiElement(ChildRole.LPARENTH);
  }

  @Override
  public PsiJavaToken getRParenth() {
    return (PsiJavaToken) findChildByRoleAsPsiElement(ChildRole.RPARENTH);
  }

  @Override
  public ASTNode findChildByRole(int role) {
    LOG.assertTrue(ChildRole.isUnique(role));

    switch(role) {
      case ChildRole.LOOP_BODY:
        return PsiImplUtil.findStatementChild(this);

      case ChildRole.FOR_ITERATED_VALUE:
        return findChildByType(EXPRESSION_BIT_SET);

      case ChildRole.FOR_KEYWORD:
        return getFirstChildNode();

      case ChildRole.LPARENTH:
        return findChildByType(LPARENTH);

      case ChildRole.RPARENTH:
        return findChildByType(RPARENTH);

      case ChildRole.FOR_ITERATION_PARAMETER:
        return findChildByType(PARAMETER);

      case ChildRole.COLON:
        return findChildByType(COLON);

      default:
        return null;
    }
  }

  @Override
  public int getChildRole(@NotNull ASTNode child) {
    LOG.assertTrue(child.getTreeParent() == this);

    IElementType i = child.getElementType();
    if (i == FOR_KEYWORD) {
      return ChildRole.FOR_KEYWORD;
    }
    else if (i == LPARENTH) {
      return ChildRole.LPARENTH;
    }
    else if (i == RPARENTH) {
      return ChildRole.RPARENTH;
    }
    else if (i == PARAMETER) {
      return ChildRole.FOR_ITERATION_PARAMETER;
    }
    else if (i == COLON) {
      return ChildRole.COLON;
    }
    else {
      if (EXPRESSION_BIT_SET.contains(child.getElementType())) {
        return ChildRole.FOR_ITERATED_VALUE;
      }
      else if (child.getPsi() instanceof PsiStatement) {
        return ChildRole.LOOP_BODY;
      }
      else {
        return ChildRoleBase.NONE;
      }
    }
  }

  public String toString() {
    return "PsiForeachStatement";
  }

  @Override
  public boolean processDeclarations(@NotNull PsiScopeProcessor processor, @NotNull ResolveState state, PsiElement lastParent, @NotNull PsiElement place) {
    processor.handleEvent(PsiScopeProcessor.Event.SET_DECLARATION_HOLDER, this);
    if (lastParent == null || lastParent.getParent() != this || lastParent == getIteratedValue())
      // Parent element should not see our vars
      return true;

    return processor.execute(getIterationParameter(), state);
  }

  @Override
  public void accept(@NotNull PsiElementVisitor visitor) {
    if (visitor instanceof JavaElementVisitor) {
      ((JavaElementVisitor)visitor).visitForeachStatement(this);
    }
    else {
      visitor.visitElement(this);
    }
  }
}


text:
<?php
class Inputtype_model extends CI_Model {
    private $table = 'inputtype';
    public function __construct()
    {
        $this->load->database('default');
    }

    public function post_new_inputtype()
    {
    	$data = array(
		    'nameinputtype' => $this->input->post('name',TRUE)
		);

		return $this->db->insert($this->table, $data);
    }

    public function get_inputtype_name($id)
    {
        $this->db->select('nameinputtype');
        return $this->db->get_where($this->table, array('idinputtype' => $id))->row();
    }

    public function get_inputtype($id)
    {
        return $this->db->get_where($this->table, array('idinputtype' => $id))->row();
    }

    public function list_all_inputtype()
    {
        return $this->db->get($this->table)->result();
    }

    public function update_inputtype($id)
    {
        $data = array(
          'nameinputtype' => $this->input->post('name',TRUE)
        );
        $this->db->where('idinputtype',$id);
        return $this->db->update($this->table,$data);
    }

    public function delete_inputtype($id)
		{
				$this->db->where('idinputtype',$id);
				return $this->db->delete($this->table);
		}

}


text:
class User < ActiveRecord::Base
  has_many :items, :dependent => :destroy
  has_many :cards#, :dependent => :destroy
  has_many :game_scores, :dependent => :destroy
  before_create :defaults
  after_create :receive_cards
  named_scope :ordered_by_score, :order => "score DESC"
  named_scope :researchers, :conditions => {:admin => false, :researcher => true}

  #Receive the starting cards
  def receive_cards
    card_dealer = CardDealer.new
    Configuration[:starting_cards].times do
      card_dealer.deal_for(self)
    end
  end

  #Defines the default values for attribute as given by Configuration
  def defaults
    self.hand_limit = Configuration[:starting_hand_limit] unless self.hand_limit
    self.cards_per_hour = Configuration[:starting_cards_per_hour] unless self.cards_per_hour
    self.money = Configuration[:starting_money] unless self.money
  end

  #Return a user with this facebook_id (creating one if could not find)
  def self.for(facebook_id)
    User.find_or_create_by_facebook_id(facebook_id)
  end

  #Calculates how much money gifts the user can send
  def max_money_gifts
    self.money < 0 ? 0 : self.money / Configuration[:money_gift_value]
  end

  #Calculates the user hand size
  def hand_size
    items = self.items.select {|item| !item.used?}
    cards = self.cards.select {|card| !card.played?}
    items.size + cards.size
  end
end


text:
import React from 'react'
import { observer } from "mobx-react"
import configObject from '../../config/app.js'

@observer
class FilterRow extends React.Component {
	constructor(){
		super()
		this.state = {

		}
	}
	componentWillMount(){

	}
	setDataType(e){
		let types = configObject.filterTypes.filter((x)=>{
			return x.type.indexOf(e.target.options[e.target.options.selectedIndex].getAttribute('type')) != -1
		})
		this.props.changeHandler('filterTypes',types[0].options,this.props.filterData.id)
		if(e.target.options[e.target.options.selectedIndex].getAttribute('data-relatedTo')){
			this.props.changeHandler('relatedTo',e.target.options[e.target.options.selectedIndex].getAttribute('data-relatedTo'),this.props.filterData.id)
			if(types[0].notContains.indexOf(e.target.options[e.target.options.selectedIndex].getAttribute('data-relatedTo')) != -1){
				this.props.changeHandler('filterTypes',types[0].optionsNotContains,this.props.filterData.id)
			}
		}
		this.props.changeHandler('columnType',e.target.options[e.target.options.selectedIndex].getAttribute('type'),this.props.filterData.id)
		this.props.changeHandler('filterType','',this.props.filterData.id)
		this.props.changeHandler('dataType',e.target.value,this.props.filterData.id)
	}
	setType(e){
		this.props.changeHandler('selectedType',e.target.value,this.props.filterData.id)
	}
	setFilterType(e){
		this.props.changeHandler('filterType',e.target.value,this.props.filterData.id)
	}
	setDataValue(ischeckbox,e){
		let value = e.target.value
		if(ischeckbox) value = e.target.checked
		if(this.props.filterData.columnType === 'Number'){
			value = parseInt(value)
		}
		this.props.changeHandler('dataValue',value,this.props.filterData.id)
	}
	setListDataValue(e){
		let value = e.target.nextSibling.value
		if(value){
			this.props.changeHandler('listDataValue',value,this.props.filterData.id)
		}
		e.target.nextSibling.value = null
	}
	removeListDataValue(index){
		this.props.removeListDataValue(index,this.props.filterData.id)
	}
	getInputType(props){
		let inputType
		// if filtertype selected is exists or doesnotexists then return disabled input
		if(['exists','doesNotExists'].indexOf(props.filterData.filterType) !== -1){
			return <input type="text" className="inputfilter" disabled="true" style={{visibility:'hidden'}}/>
		}
		// if no filtertype selected then return disabled input
		if(!props.filterData.filterType){
			return <input type="text" className="inputfilter" disabled="true"/>
		}
		if(props.filterData.columnType){
			if(['Text','Email','URL','EncryptedText'].indexOf(props.filterData.columnType) != -1){
				inputType = <input type="text" className="inputfilter" value={ props.filterData.dataValue } onChange={ this.setDataValue.bind(this,false) }/>
			}
			else if(['Number'].indexOf(props.filterData.columnType) != -1){
				inputType = <input type="number" className="inputfilter" value={ props.filterData.dataValue } onChange={ this.setDataValue.bind(this,false) }/>
			}
			else if(['DateTime'].indexOf(props.filterData.columnType) != -1){
				inputType = <input type="date" className="inputfilter" value={ props.filterData.dataValue } onChange={ this.setDataValue.bind(this,false) }/>
			}
			else if(['Boolean'].indexOf(props.filterData.columnType) != -1){
				inputType = <input type="checkbox" className="inputfilter boolfilter" checked={ props.filterData.dataValue } onChange={ this.setDataValue.bind(this,true) }/>
			}
			else if(['List'].indexOf(props.filterData.columnType) != -1){
				inputType = this.getListInput(props)
			}
			else {
				inputType = <input type="text" className="inputfilter" disabled="true"/>
			}
		} else {
			inputType = <input type="text" className="inputfilter" disabled="true"/>
		}
		return inputType
	}
	getListInput(props){
		let inputType
		if(props.filterData.relatedTo){
			if(['Text','Email','URL','EncryptedText','Number'].indexOf(props.filterData.relatedTo) != -1){

				inputType =

								<input type="text" className="inputfilterlist"/>
								{
									this.props.filterData.listDataValue.map((x,i)=>{
										return

													<input type="text" className="inputfilterlistValues" value={ x } disabled="true" />

									})
								}

			}
			else if(['DateTime'].indexOf(props.filterData.relatedTo) != -1){
				inputType =

								<input type="date" className="inputfilterlist"/>
								{
									this.props.filterData.listDataValue.map((x,i)=>{
										return

													<input type="date" className="inputfilterlistValues" value={ x } disabled="true" />

									})
								}

			}
			else {
				inputType = <input type="text" className="inputfilter" disabled="true" value={ props.filterData.dataValue } onChange={ this.setDataValue.bind(this,false) }/>
			}
		} else {
			inputType = <input type="text" className="inputfilter" disabled="true" value={ props.filterData.dataValue } onChange={ this.setDataValue.bind(this,false) }/>
		}
		return inputType
	}
	render() {

		let dataTypes = this.props.tableStore.getColumns
						.filter((x)=>{
							return !(x.dataType == 'Id' || x.dataType == 'ACL')
						})
						.map((data,i)=>{
							if(data.dataType == 'List'){
								return <option key={ i } value={ data.name } type={ data.dataType } data-relatedTo={ data.relatedTo }>{ data.name }</option>
							} else {
								return <option key={ i } value={ data.name } type={ data.dataType }>{ data.name }</option>
							}
						})
		let type = this.props.filterData.type.map((x,i)=>{
			return <option key={ i } value={ x }>{ x }</option>
		})
		let filterTypes = this.props.filterData.filterTypes.map((data,i)=>{
			return <option key={ i } value={ data }>{ data }</option>
		})
		let inputType = this.getInputType(this.props)

		return (

	          	<select className="form-control selectfilter" value={ this.props.filterData.selectedType } onChange={ this.setType.bind(this) }>
	          		{ type }
	          	</select>
	          	<select className="form-control selectfilter" value={ this.props.filterData.dataType } onChange={ this.setDataType.bind(this) }>
	          		<option value=''>-select-</option>
	          		{ dataTypes }
	          	</select>
	          	<select className="form-control selectfilter" value={ this.props.filterData.filterType } onChange={ this.setFilterType.bind(this) }>
	          		{ filterTypes }
	          	</select>
	          	{ inputType }

		);
	}
}

export default FilterRow


text:
package com.dolphinmum.web.db;

import com.dolphinmum.web.db.model.*;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by meajhlp on 15/7/2.
 * 评价详情相关数据操作
 */
@Repository
public class EvaluationDao extends BasicDao {

    /**
     * 查询类目配置概况
     * @param category
     */
    public void insertCategory(T_evaluation_category category){
        String sql = "insert into t_evaluation_category(category_id,config_id,purpose,desc_detail,enable) " +
                "values(?,?,?,?,?)";

        insertOrUpdateData(sql, new Object[]{
                category.getCategory_id(), category.getConfig_id(),"","",false
        });
    }

    /**
     * 删除类目概况
     * @param categoryId
     */
    public void deleteCategory(int categoryId){
        insertOrUpdateData("delete from t_evaluation_category where category_id=?", new Object[]{categoryId});

        List<T_evaluation_category_config> configs = queryCategoryConfigs(categoryId);
        for (T_evaluation_category_config config : configs){
            deleteCategoryConfig(config.getId());
        }

        List<T_evaluation_good> goodList = queryAllCategoryGood(categoryId);
        for (T_evaluation_good good : goodList){
            deleteGood(good.getGood_id());
        }

        deleteGroup(queryGroup(0,categoryId,-1));
    }

    /**
     * 更新类目概况
     * @param category
     */
    public void updateCategory(T_evaluation_category category){
        String sql = "update t_evaluation_category set " +
                "config_id=?,purpose=?,desc_detail=?,enable=? where " +
                "category_id=?";
        insertOrUpdateData(sql, new Object[]{
                category.getConfig_id(),category.getPurpose(),category.getDesc_detail(),
                category.isEnable(),category.getCategory_id()
        });
    }

    /**
     * 查询类目概况
     * @param categoryId 类目ID
     * @param start
     * @param limit
     * @return
     */
    public List<T_evaluation_category> queryCategories(int categoryId, int start, int limit){
        String sql = "select * from t_evaluation_category";
        if (categoryId > 0){
            sql += " where category_id=?";
        }
        sql += " limit ?,?";

        if (categoryId > 0){
            return query(sql, BeanPropertyRowMapper.newInstance(T_evaluation_category.class),categoryId, start, limit);
        }
        return query(sql, BeanPropertyRowMapper.newInstance(T_evaluation_category.class), start, limit);
    }

    /**
     * 查询类目首页配置基本信息
     * @param categoryId
     * @return
     */
    public T_evaluation_category queryCategory(int categoryId){
        return queryForObject("select * from t_evaluation_category where category_id=?",
                BeanPropertyRowMapper.newInstance(T_evaluation_category.class), categoryId);
    }

    /**
     * 查询满足条件的类目总数
     * @param categoryId
     * @return
     */
    public int queryCategoriesTotal(int categoryId){
        String sql = "select count(1) from t_evaluation_category";
        if (categoryId > 0){
            sql += " where category_id=?";
            return queryForObject(sql, Integer.class, categoryId);
        }
        return queryForObject(sql, Integer.class);
    }

    /**
     * 插入类目配置记录
     * @param config
     * @return
     */
    public int insertCategoryConfig(T_evaluation_category_config config){
        String sql = "insert into t_evaluation_category_config(category_id,operator_name,diff_text_1," +
                "diff_text_2,diff_text_3,diff_text_4,enable) values(?,?,?,?,?,?,?)";
        int configId = insertData(sql, new Object[]{
                config.getCategory_id(),config.getOperator_name(),config.getDiff_text_1(),
                config.getDiff_text_2(),config.getDiff_text_3(),config.getDiff_text_4(),config.isEnable()
        });

        if (queryCategoryConfigs(config.getCategory_id()).size() == 0){
            T_evaluation_category category = new T_evaluation_category();
            category.setCategory_id(config.getCategory_id());
            category.setConfig_id(configId);
            category.setPurpose("");
            category.setDesc_detail("");
            category.setEnable(false);
            insertCategory(category);
        }
        return configId;
    }

    /**
     * 删除类目配置
     * @param id
     */
    public void deleteCategoryConfig(int id){
        String sql = "delete from t_evaluation_category_config where id=?";
        insertOrUpdateData(sql, new Object[]{id});

        deleteCategoryConfigDetail(id);
    }

    /**
     * 更新类目配置
     * @param config
     */
    public void updateCategoryConfig(T_evaluation_category_config config){
        String sql = "update t_evaluation_category_config set category_id=?,operator_name=?," +
                "diff_text_1=?,diff_text_2=?,diff_text_3=?,diff_text_4=?,enable=? where id=?";

        insertOrUpdateData(sql, new Object[]{
                config.getCategory_id(), config.getOperator_name(), config.getDiff_text_1(),
                config.getDiff_text_2(), config.getDiff_text_3(), config.getDiff_text_4(),
                config.isEnable(), config.getId()
        });
    }

    /**
     * 查询类目配置
     * @param categoryId 类目ID
     * @return
     */
    public List<T_evaluation_category_config> queryCategoryConfigs(int categoryId){
        String sql = "select * from t_evaluation_category_config where category_id=? order by logdate desc";
        return query(sql, BeanPropertyRowMapper.newInstance(T_evaluation_category_config.class), categoryId);
    }

    /**
     * 查询类目配置
     * @param configId
     * @return
     */
    public T_evaluation_category_config queryCategoryConfig(int configId){
        return queryForObject("select * from t_evaluation_category_config where id=?",
                BeanPropertyRowMapper.newInstance(T_evaluation_category_config.class), configId);
    }

    /**
     * 保存配置详情
     * @param details
     */
    public void insertCategoryDetails(List<T_evaluation_category_detail> details){
        if (details == null || details.size() == 0){
            return;
        }
        String sql = "insert into t_evaluation_category_detail" +
                "(config_id,type,img_id,brand_id,good_id,order_num) " +
                "values(?,?,?,?,?,?)";

        List<Object[]> params = new ArrayList<Object[]>();
        for(T_evaluation_category_detail detail : details){
            params.add(new Object[]{
                    detail.getConfig_id(),detail.getType(),detail.getImg_id(),
                    detail.getBrand_id(),detail.getGood_id(),detail.getOrder_num()
            });
        }

        batchInsertOrUpdateData(sql, params);
    }

    /**
     * 删除类目配置的所有明细
     * @param configId
     */
    public void deleteCategoryConfigDetail(int configId) {
        String sql = "delete from t_evaluation_category_detail where config_id=?";
        insertOrUpdateData(sql, new Object[]{configId});
    }

    /**
     * 查询配置详情
     * @param configId
     * @return
     */
    public List<T_evaluation_category_detail> queryCategoryDetails(int configId){
        String sql = "select * from t_evaluation_category_detail where config_id=? order by type,order_num";
        return query(sql, BeanPropertyRowMapper.newInstance(T_evaluation_category_detail.class), configId);
    }

    /**
     * 新增评测配置组
     * @param group
     * @return
     */
    public int insertGroup(T_evaluation_group group){
        String sql = "insert into t_evaluation_group(category_id,name,order_num,parent_id,meaning,method) values(?,?,?,?,?,?)";
        return insertData(sql, new Object[]{
                group.getCategory_id(), group.getName(), group.getOrder_num(), group.getParent_id(),
                group.getMeaning(),group.getMethod()
        });
    }

    /**
     * 批量增加评测配置组
     * @param groups
     */
    public void insertGroup(List<T_evaluation_group> groups){
        if (groups == null || groups.size() == 0){
            return;
        }
        String sql = "insert into t_evaluation_group(category_id,name,order_num,parent_id,meaning,method) values(?,?,?,?,?,?)";
        List<Object[]> params = new ArrayList<Object[]>();
        for (T_evaluation_group group : groups){
            params.add(new Object[]{
                    group.getCategory_id(),group.getName(),group.getOrder_num(),group.getParent_id(),
                    group.getMeaning(),group.getMethod()
            });
        }
        batchInsertOrUpdateData(sql, params);
    }

    /**
     * 删除评测配置组
     * @param groups
     */
    public void deleteGroup(List<T_evaluation_group> groups){
        if (groups == null || groups.size() == 0){
            return;
        }
        String sql = "delete from t_evaluation_group where id=?";
        List<Object[]> params = new ArrayList<Object[]>();
        for (T_evaluation_group group : groups){
            params.add(new Object[]{group.getId()});
        }
        batchInsertOrUpdateData(sql, params);
    }

    /**
     * 删除评论组
     * @param group
     */
    public void deleteGroup(T_evaluation_group group){
        String sql = "delete from t_evaluation_group where id=?";
        insertOrUpdateData(sql, new Object[]{group.getId()});
    }

    /**
     * 更新评测配置组
     * @param group
     */
    public void updateGroup(T_evaluation_group group){

        String sql = "update t_evaluation_group set name=?,order_num=?,meaning=?,method=? where id=?";
        insertOrUpdateData(sql, new Object[]{
                group.getName(), group.getOrder_num(), group.getMeaning(),group.getMethod(),group.getId()
        });

    }

    /**
     * 更新评测配置组
     * @param groups
     */
    public void updateGroup(List<T_evaluation_group> groups){
        if (groups == null || groups.size() == 0){
            return;
        }
        String sql = "update t_evaluation_group set name=?,order_num=?,meaning=?,method=? where id=?";
        List<Object[]> params = new ArrayList<Object[]>();
        for (T_evaluation_group group : groups){
            params.add(new Object[]{
                    group.getName(), group.getOrder_num(),group.getMeaning(),group.getMethod(), group.getId()
            });
        }
        batchInsertOrUpdateData(sql, params);
    }

    /**
     * 查询评测项目组
     * @param groupId
     * @param categoryId
     * @return
     */
    public List<T_evaluation_group> queryGroup(int groupId, int categoryId, int parentId){
        if (groupId > 0){
            return query("select * from t_evaluation_group where id=?",
                    BeanPropertyRowMapper.newInstance(T_evaluation_group.class), groupId);
        }
        //
        String sql = "select * from t_evaluation_group";
        if (categoryId > 0){
            if (parentId < 0){
                sql += " where category_id=? order by order_num";
                return query(sql, BeanPropertyRowMapper.newInstance(T_evaluation_group.class), categoryId);
            }else{
                sql += " where category_id=? and parent_id=? order by order_num";
                return query(sql, BeanPropertyRowMapper.newInstance(T_evaluation_group.class), categoryId, parentId);
            }
        }
        sql += " order by order_num";
        return query(sql, BeanPropertyRowMapper.newInstance(T_evaluation_group.class));
    }

    /**
     * 添加评测商品基本信息
     * @param good
     * @return
     */
    public void insertGood(T_evaluation_good good){
        String sql = "insert into t_evaluation_good(good_id,category_id,try_price,try_url,enable) " +
                "VALUES(?,?,?,?,?)";
        insertOrUpdateData(sql, new Object[]{
                good.getGood_id(),good.getCategory_id(),good.getTry_price(),good.getTry_url(),good.isEnable()
        });
    }

    /**
     * 删除评测商品信息
     * @param goodId
     */
    public void deleteGood(int goodId){
        String sql = "delete from t_evaluation_good where good_id=?";
        insertOrUpdateData(sql, new Object[]{goodId});

        deleteGoodDetail(goodId, 0);
        deleteGoodImg(goodId, 0);
    }

    /**
     * 查询类目所有评测商品
     * @param categoryId
     * @return
     */
    public List<T_evaluation_good> queryAllCategoryGood(int categoryId){
        return query("select * from t_evaluation_good where category_id=?",
                BeanPropertyRowMapper.newInstance(T_evaluation_good.class), categoryId);
    }

    /**
     * 根据商品ID查询评测基本信息
     * @param goodId
     * @return
     */
    public T_evaluation_good queryGood(int goodId){
        try {
            return queryForObject("select * from t_evaluation_good where good_id=?",
                    BeanPropertyRowMapper.newInstance(T_evaluation_good.class), goodId);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    /**
     * 查询评测商品
     * @param brandId 品牌ID
     * @param status 是否已完成
     * @return
     */
    public List<T_evaluation_good> queryGood(int categoryId, int brandId, Boolean status, int start, int limit){
        QuerySqlAndParams sqlAndParams = generateQueryGoodSql(categoryId, brandId, status);

        Object[] params = new Object[sqlAndParams.params.length + 2];
        for (int i=0;i<sqlAndParams.params.length;i++){
            params[i] = sqlAndParams.params[i];
        }
        params[sqlAndParams.params.length] = start;
        params[sqlAndParams.params.length+1] = limit;

        return query(sqlAndParams.sql + " limit ?,?",
                BeanPropertyRowMapper.newInstance(T_evaluation_good.class), params);
    }

    /**
     * 查询满足条件的评测商品总数
     * @param brandId
     * @param status
     * @return
     */
    public int queryGoodTotal(int categoryId, int brandId, Boolean status){
        QuerySqlAndParams sqlAndParams = generateQueryGoodSql(categoryId, brandId, status);
        return queryForObject("select count(1) from (" + sqlAndParams.sql + ") tt", Integer.class, sqlAndParams.params);
    }

    /**
     * 生成查询评测商品基本SQL
     * @param brandId 品牌ID
     * @param status 是否已完成
     * @return
     */
    private QuerySqlAndParams generateQueryGoodSql(int categoryId, int brandId, Boolean status){
        List<String> queryConditions = new ArrayList<String>();
        List<Object> params = new ArrayList<Object>();
        boolean hasBrandIdParam = false;
        if (brandId > 0){
            queryConditions.add("t2.brand_id=?");
            params.add(brandId);
            hasBrandIdParam = true;
        }
        if (status != null){
            queryConditions.add("t1.enable=?");
            params.add(status);
        }
        queryConditions.add("t1.category_id=?");
        params.add(categoryId);

        StringBuffer sqlBuffer = new StringBuffer();
        sqlBuffer.append("select t1.* from t_evaluation_good t1 ");
        if (hasBrandIdParam){
            sqlBuffer.append(", t_goods t2 ");
        }
        if (queryConditions.size() > 0){
            sqlBuffer.append("where ");
            if (hasBrandIdParam){
                sqlBuffer.append("t1.good_id=t2.id and ");
            }
            for (int i=0;i< queryConditions.size();i++){
                if (i > 0){
                    sqlBuffer.append(" and ");
                }
                sqlBuffer.append(queryConditions.get(i));
            }
        }
        QuerySqlAndParams sqlAndParams = new QuerySqlAndParams();
        sqlAndParams.sql = sqlBuffer.toString();
        sqlAndParams.params = params.toArray();
        return sqlAndParams;
    }

    /**
     * 生成的sql 及 查询条件
     */
    private class QuerySqlAndParams {
        String sql;
        Object[] params;
    }

    /**
     * 增加评测商品评测图片信息
     * @param goodImgs
     */
    public void insertGoodImg(List<T_evaluation_good_img> goodImgs){
        if (goodImgs == null || goodImgs.size() == 0){
            return;
        }
        String sql = "insert into t_evaluation_good_img(good_id,evaluation_group_id,img_id,order_num) " +
                "values(?,?,?,?)";
        List<Object[]> params = new ArrayList<Object[]>();
        for (T_evaluation_good_img goodImg : goodImgs){
            params.add(new Object[]{
                    goodImg.getGood_id(),goodImg.getEvaluation_group_id(),
                    goodImg.getImg_id(),goodImg.getOrder_num()
            });
        }
        batchInsertOrUpdateData(sql, params);
    }

    /**
     * 删除商品评测图片信息
     * @param goodId 商品ID
     * @param groupId 评测组ID
     */
    public void deleteGoodImg(int goodId, int groupId) {
        if (goodId > 0){
            String sql = "delete from t_evaluation_good_img where good_id=?";
            insertOrUpdateData(sql, new Object[]{goodId});
            return;
        }

        if (groupId > 0){
            String sql = "delete from t_evaluation_good_img where evaluation_group_id=?";
            insertOrUpdateData(sql, new Object[]{groupId});
            return;
        }

    }

    /**
     * 查询评测商品图片信息
     * @param goodId 商品ID
     * @param groupId 评测组ID
     * @return
     */
    public List<T_images> queryGoodImg(int goodId, int groupId){
        String sql = "select t1.* from t_images t1,t_evaluation_good_img t2 " +
                "where t1.id=t2.img_id and t2.good_id=? and t2.evaluation_group_id=? order by order_num";
        return query(sql, BeanPropertyRowMapper.newInstance(T_images.class), goodId, groupId);
    }

    /**
     * 保存评测商品结果明细信息
     * @param goodDetails
     */
    public void insertGoodDetail(List<T_evaluation_good_detail> goodDetails){
        String sql = "insert into t_evaluation_good_detail(good_id,evaluation_group_id," +
                "result,score) values(?,?,?,?)";
        List<Object[]> params = new ArrayList<Object[]>();
        for (T_evaluation_good_detail goodDetail : goodDetails){
            params.add(new Object[]{
                    goodDetail.getGood_id(),goodDetail.getEvaluation_group_id(),
                    goodDetail.getResult(),
                    goodDetail.getScore()
            });
        }
        batchInsertOrUpdateData(sql, params);
    }

    /**
     * 删除商品评测结果明细
     * @param goodId
     */
    public void deleteGoodDetail(int goodId, int groupId) {
        if (goodId > 0){
            String sql = "delete from t_evaluation_good_detail where good_id=?";
            insertOrUpdateData(sql, new Object[]{goodId});
            return;
        }

        if (groupId > 0){
            String sql = "delete from t_evaluation_good_detail where evaluation_group_id=?";
            insertOrUpdateData(sql, new Object[]{groupId});
            return;
        }
    }

    /**
     * 查询评测详情
     * @param goodId 商品ID
     * @param groupId 评测组ID
     * @return
     */
    public T_evaluation_good_detail queryGoodDetail(int goodId, int groupId){
        String sql = "select * from t_evaluation_good_detail where good_id=? and evaluation_group_id=?";
        return queryForObject(sql, BeanPropertyRowMapper.newInstance(T_evaluation_good_detail.class), goodId, groupId);
    }

    /**
     * 查询商品评测详情列表
     * @param goodId
     * @return
     */
    public List<T_evaluation_good_detail> queryGoodDetailList(int goodId){
        String sql = "select * from t_evaluation_good_detail where good_id=?";
        return query(sql, BeanPropertyRowMapper.newInstance(T_evaluation_good_detail.class), goodId);
    }

    /**
     * 判断评测项目是否已被使用
     * @param groupId
     * @return
     */
    public boolean isChildGroupInUse(int groupId){

        String sql = "select count(1) from t_evaluation_good_detail where evaluation_group_id=?";
        int count = queryForObject(sql, Integer.class, groupId);
        return count > 0;
    }

    /**
     * 判断评测组中得子项目是否已被使用
     * @param groupId
     * @return
     */
    public boolean isParentGroupInUse(int groupId){
        String sql = "select count(1) from t_evaluation_good_detail t1, t_evaluation_group t2 " +
                "where t1.evaluation_group_id=t2.id and t2.parent_id=?";
        int count = queryForObject(sql, Integer.class, groupId);
        return count > 0;
    }
}


text:
import FLOAT32_SIGN_MASK = require( './index' );

// TESTS //

// The export is a number...
{
	// tslint:disable-next-line:no-unused-expression
	FLOAT32_SIGN_MASK; // $ExpectType number
}


text:
> Feel free to try to break this, submit issues and pull requests, and/or request features!

Automatically adds a decorator to React components.  Accepts a single argument, a path to some module for error reporting, and if there's an error, it will catch it and pass it to the reporter.  The reporter can be either of the following:

  * ReactComponent that may use the props below to render a message
  * function that accepts the arguments below; it may also return a ReactComponent or ReactElement to be rendered

Props/Arguments:

  - error
  - instance
  - filename
  - displayName

## Installation

```
jspm install babel-plugin-react-error-catcher=github:loggur/babel-plugin-react-error-catcher
```
or
```
jspm install npm:babel-plugin-react-error-catcher
```
or
```
npm install babel-plugin-react-error-catcher
```

## Brief API Overview

There's not much to it, really.  All you do is provide the plugin to Babel with the path to a reporter module.  Use whatever reporter you want, or try out one of the three included:

1. [Function that logs errors to console](https://github.com/loggur/babel-plugin-react-error-catcher/blob/master/reporters/console.js)

2. [Component that displays the error string with white text on a red background](https://github.com/loggur/babel-plugin-react-error-catcher/blob/master/reporters/basic-reporter.js)

3. [Function that uses the component from #2 but ensures it's the same size as the originating component](https://github.com/loggur/babel-plugin-react-error-catcher/blob/master/reporters/same-size-reporter.js)

**Note:**  The reporter may also export a `rendered` function that you can use to obtain information about components as soon as they've successfully rendered.  See [`same-size-reporter`](https://github.com/loggur/babel-plugin-react-error-catcher/blob/master/reporters/same-size-reporter.js#L41-L72) for an example.

## JSPM Example ([Quick Link](https://github.com/loggur/babel-plugin-react-error-catcher/blob/master/examples/jspm))

From [`examples/jspm/client/minimal-editor.js`](https://github.com/loggur/babel-plugin-react-error-catcher/blob/master/examples/jspm/client/minimal-editor.js):
```js
import hotPlugin    from 'babel-plugin-react-hot';
import errorCatcher from 'babel-plugin-react-error-catcher';

const reportersDir = 'babel-plugin-react-error-catcher/reporters/';
const reporterPath = reportersDir+'same-size-reporter';

System.config({
  "trace": true,
  "babelOptions": {
    "stage": 0,
    "optional": [
      "runtime"
    ],
    "plugins": [
      hotPlugin,
      errorCatcher(reporterPath)
    ]
  }
});
```

That's it!  Try it yourself:

> **Note:**  NPM likes to timeout sometimes when downloading packages, so if this happens, just keep trying `npm install` and `npm run jspm-install` before `npm start`.

```
git clone git@github.com:loggur/babel-plugin-react-error-catcher.git
cd babel-plugin-react-error-catcher/examples/jspm
npm install
npm run jspm-install
npm start
open http://localhost:8080
```

## WebPack Example ([Quick Link](https://github.com/loggur/babel-plugin-react-error-catcher/blob/master/examples/webpack))

[`examples/webpack/.babelrc`](https://github.com/loggur/babel-plugin-react-error-catcher/blob/master/examples/webpack/.babelrc):
```json
{
  "stage": 0,
  "optional": [
    "runtime"
  ],
  "plugins": [
    "react-hot",
    "./error-catcher"
  ]
}
```

[`examples/webpack/error-catcher.js`](https://github.com/loggur/babel-plugin-react-error-catcher/blob/master/examples/webpack/error-catcher.js):
```js
var catcherPath = 'babel-plugin-react-error-catcher';
var reporterPath = catcherPath+'/reporters/same-size-reporter';

module.exports = require(catcherPath)(reporterPath);
```

That's it!  Try it yourself:

> **Note:**  NPM likes to timeout sometimes when downloading packages, so if this happens, just keep trying `npm install` before `npm start`.

```
git clone git@github.com:loggur/babel-plugin-react-error-catcher.git
cd babel-plugin-react-error-catcher/examples/webpack
npm install
npm start
open http://localhost:8080
```

## Real World Example

This is currently used within [`web-tedit`](https://github.com/loggur/web-tedit) (extensive work-in-progress) and it is designed to work with React hot reloading.  See [`babel-plugin-react-hot`](https://github.com/loggur/babel-plugin-react-hot) for said Babel plugin.

## License

MIT


text:
package com.navercorp.pinpoint.collector.cluster.connection;

import com.navercorp.pinpoint.collector.util.Address;
import com.navercorp.pinpoint.common.util.Assert;
import com.navercorp.pinpoint.rpc.PinpointSocket;
import com.navercorp.pinpoint.rpc.client.DefaultPinpointClientFactory;
import com.navercorp.pinpoint.rpc.client.PinpointClientFactory;
import com.navercorp.pinpoint.rpc.cluster.ClusterOption;
import com.navercorp.pinpoint.rpc.cluster.Role;
import com.navercorp.pinpoint.rpc.util.ClassUtils;
import com.navercorp.pinpoint.rpc.util.ClientFactoryUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Taejin Koo
 */
public class CollectorClusterConnector implements CollectorClusterConnectionProvider {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final CollectorClusterConnectionOption option;

    private PinpointClientFactory clientFactory;
    public CollectorClusterConnector(CollectorClusterConnectionOption option) {
        this.option = Assert.requireNonNull(option, "option must not be null");
    }

    @Override
    public void start() {
        logger.info("{} initialization started.", ClassUtils.simpleClassName(this));

        ClusterOption clusterOption = new ClusterOption(true, option.getClusterId(), Role.ROUTER);

        this.clientFactory = new DefaultPinpointClientFactory();

        this.clientFactory.setTimeoutMillis(1000 * 5);
        this.clientFactory.setMessageListener(option.getRouteMessageHandler());
        this.clientFactory.setServerStreamChannelMessageListener(option.getRouteStreamMessageHandler());
        this.clientFactory.setClusterOption(clusterOption);

        Map<String, Object> properties = new HashMap<>();
        properties.put("id", option.getClusterId());
        clientFactory.setProperties(properties);

        logger.info("{} initialization completed.", ClassUtils.simpleClassName(this));
    }

    @Override
    public void stop() {
        logger.info("{} destroying started.", ClassUtils.simpleClassName(this));

        if (clientFactory != null) {
            clientFactory.release();
        }

        logger.info("{} destroying completed.", ClassUtils.simpleClassName(this));
    }

    PinpointSocket connect(Address address) {
        if (clientFactory == null) {
            throw new IllegalStateException("not started.");
        }

        PinpointSocket socket = ClientFactoryUtils.createPinpointClient(address.getHost(), address.getPort(), clientFactory);
        return socket;
    }

}


text:
if (this.message === 'notvalid') {
    error('message', "Message must not be notvalid");
}

if (this.title === 'notvalid') {
    error('title', "Title must not be notvalid");
}

if (this.title === '$VALIDATE_TEST') {
  this.message += "x";
}

errorIf(this.title === "$ERROR_IF_TEST", 'errorIf', "Yep");
errorUnless(this.title !== "$ERROR_UNLESS_TEST", 'errorUnless', "Yep");


text:
This program holds a library of books.

Using an Object constructor makes sure you can easily add books to it, as you please.

When you call the program with a specific book, it 'reads' (aka prints) the book title, and it's pages.

By using a loop for printing out the pages, it doesn't matter if you only have 1 page in the array or a gazillion. It prints outs the existing pages in the book with the proper page number in front of it.


text:
class AddRestrictedVisibilityLevelsToApplicationSettings < ActiveRecord::Migration
  def change
    add_column :application_settings, :restricted_visibility_levels, :text
  end
end


text:
package org.ehcache.clustered;

import org.ehcache.Cache;
import org.ehcache.PersistentCacheManager;
import org.ehcache.clustered.client.config.ClusteringServiceConfiguration;
import org.ehcache.clustered.client.config.builders.ClusteredResourcePoolBuilder;
import org.ehcache.clustered.client.config.builders.ClusteringServiceConfigurationBuilder;
import org.ehcache.clustered.client.internal.ClusterTierManagerClientEntity;
import org.ehcache.clustered.client.internal.lock.VoltronReadWriteLock;
import org.ehcache.clustered.client.service.EntityBusyException;
import org.ehcache.clustered.common.internal.ClusterTierManagerConfiguration;
import org.ehcache.clustered.reconnect.ThrowingResiliencyStrategy;
import org.ehcache.clustered.util.TCPProxyUtil;
import org.ehcache.config.CacheConfiguration;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.config.units.MemoryUnit;
import org.ehcache.testing.TestRetryer;
import org.ehcache.testing.TestRetryer.OutputIs;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.terracotta.connection.Connection;
import org.terracotta.connection.entity.EntityRef;
import org.terracotta.exception.EntityNotFoundException;
import org.terracotta.lease.connection.LeasedConnectionFactory;
import org.terracotta.testing.rules.Cluster;

import com.tc.net.proxy.TCPProxy;

import java.net.URI;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.stream.Stream;

import static java.time.Duration.ofSeconds;
import static java.util.EnumSet.of;
import static org.ehcache.clustered.common.EhcacheEntityVersion.ENTITY_VERSION;
import static org.ehcache.clustered.util.TCPProxyUtil.setDelay;
import static org.ehcache.testing.StandardTimeouts.eventually;
import static org.ehcache.testing.TestRetryer.tryValues;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.terracotta.testing.rules.BasicExternalClusterBuilder.newCluster;

/**
 * ReconnectDuringDestroyTest
 */
public class ReconnectDuringDestroyTest extends ClusteredTests {

  private static URI connectionURI;
  private static List<TCPProxy> proxies;
  PersistentCacheManager cacheManager;

  @ClassRule @Rule
  public static final TestRetryer<Duration, Cluster> CLUSTER = tryValues(
    Stream.of(ofSeconds(1), ofSeconds(10), ofSeconds(3)),
    leaseLength -> newCluster().in(clusterPath()).withServiceFragment(
      offheapResource("primary-server-resource", 64) + leaseLength(leaseLength)).build(),
    of(OutputIs.CLASS_RULE));

  @BeforeClass
  public static void initializeProxy() throws Exception {
    proxies = new ArrayList<>();
    connectionURI = TCPProxyUtil.getProxyURI(CLUSTER.get().getConnectionURI(), proxies);
  }

  @Before
  public void initializeCacheManager() {
    ClusteringServiceConfiguration clusteringConfiguration =
      ClusteringServiceConfigurationBuilder.cluster(connectionURI.resolve("/crud-cm"))
        .autoCreate(server -> server.defaultServerResource("primary-server-resource")).build();

    CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder
      = CacheManagerBuilder.newCacheManagerBuilder().with(clusteringConfiguration);
    cacheManager = clusteredCacheManagerBuilder.build(false);
    cacheManager.init();
  }

  /*
  This is to test the scenario in which reconnect happens while cache manager
  destruction is in progress. This test checks whether the cache manager
  gets destructed properly in the reconnect path once the connection is closed
  after the prepareForDestroy() call.
  */
  @Test
  public void reconnectDuringDestroyTest() throws Exception {
    cacheManager.close();
    Connection client = null;
    try {
      client = LeasedConnectionFactory.connect(connectionURI, new Properties());
      VoltronReadWriteLock voltronReadWriteLock = new VoltronReadWriteLock(client, "crud-cm");
      try (VoltronReadWriteLock.Hold localMaintenance = voltronReadWriteLock.tryWriteLock()) {
        if (localMaintenance == null) {
          throw new EntityBusyException("Unable to obtain maintenance lease for " + "crud-cm");
        }
        EntityRef<ClusterTierManagerClientEntity, ClusterTierManagerConfiguration, Void> ref = getEntityRef(client);
        try {
          ClusterTierManagerClientEntity entity = ref.fetchEntity(null);
          entity.prepareForDestroy();
          entity.close();
        } catch (EntityNotFoundException e) {
          Assert.fail();
        }
      }
      // For reconnection.
      long delay = CLUSTER.input().plusSeconds(1).toMillis();
      setDelay(delay, proxies);
      try {
        Thread.sleep(delay);
      } finally {
        setDelay(0L, proxies);
      }
      client = LeasedConnectionFactory.connect(connectionURI, new Properties());

      // For mimicking the cacheManager.destroy() in the reconnect path.
      voltronReadWriteLock = new VoltronReadWriteLock(client, "crud-cm");
      try (VoltronReadWriteLock.Hold localMaintenance = voltronReadWriteLock.tryWriteLock()) {
        if (localMaintenance == null) {
          throw new EntityBusyException("Unable to obtain maintenance lease for " + "crud-cm");
        }
        EntityRef<ClusterTierManagerClientEntity, ClusterTierManagerConfiguration, Void> ref = getEntityRef(client);
        try {
          ClusterTierManagerClientEntity entity = ref.fetchEntity(null);
          entity.prepareForDestroy();
          entity.close();
        } catch (EntityNotFoundException e) {
          Assert.fail("Unexpected exception " + e.getMessage());
        }
        if (!ref.destroy()) {
          Assert.fail("Unexpected exception while trying to destroy cache manager");
        }
      }
    } finally {
      client.close();
    }
  }

  @Test
  public void reconnectAfterDestroyOneOfTheCache() throws Exception {
    try {
      CacheConfiguration<Long, String> config = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
        ResourcePoolsBuilder.newResourcePoolsBuilder()
          .with(ClusteredResourcePoolBuilder.
            clusteredDedicated("primary-server-resource", 1, MemoryUnit.MB)))
        .withResilienceStrategy(new ThrowingResiliencyStrategy<>())
        .build();
      Cache<Long, String> cache1 = cacheManager.createCache("clustered-cache-1", config);
      Cache<Long, String> cache2 = cacheManager.createCache("clustered-cache-2", config);
      cache1.put(1L, "The one");
      cache1.put(2L, "The two");
      cache2.put(1L, "The one");
      cache2.put(2L, "The two");
      cacheManager.destroyCache("clustered-cache-1");

      // For reconnection.
      long delay = CLUSTER.input().plusSeconds(1L).toMillis();
      setDelay(delay, proxies);
      try {
        Thread.sleep(delay);
      } finally {
        setDelay(0L, proxies);
      }

      Cache<Long, String> cache2Again = cacheManager.getCache("clustered-cache-2", Long.class, String.class);
      eventually().runsCleanly(() -> {
        assertThat(cache2Again.get(1L), equalTo("The one"));
        assertThat(cache2Again.get(2L), equalTo("The two"));
      });
      cache2Again.put(3L, "The three");
      assertThat(cache2Again.get(3L), equalTo("The three"));
    } finally {
      cacheManager.close();
    }
  }

  private EntityRef<ClusterTierManagerClientEntity, ClusterTierManagerConfiguration, Void> getEntityRef(Connection client) throws org.terracotta.exception.EntityNotProvidedException {
    return client.getEntityRef(ClusterTierManagerClientEntity.class, ENTITY_VERSION, "crud-cm");
  }
}


text:
import fs from "fs";
import path from "path";
import yaml from "js-yaml";
import { generator } from "../src/index";

jest.mock("commander", () => ({
  checkRequired: true,
  arguments: jest.fn().mockReturnThis(),
  option: jest.fn().mockReturnThis(),
  action: jest.fn().mockReturnThis(),
  parse: jest.fn().mockReturnThis()
}));

describe("generate flow types", () => {
  describe("parse additional properties", () => {
    it("should generate expected flow types", () => {
      const file = path.join(__dirname, "__mocks__/additionalProperties.swagger.yaml");
      const content = yaml.safeLoad(fs.readFileSync(file, "utf8"));
      const expected = path.join(__dirname, "__mocks__/additionalProperties.flow.js");
      const expectedString = fs.readFileSync(expected, "utf8");
      expect(generator(content)).toEqual(expectedString);
    });
  });
});


text:
<!doctype html>
<!-- This file is generated by build.py. -->
<title>video wide.jpg; overflow:hidden; -o-object-fit:none; -o-object-position:30px center</title>
<link rel="stylesheet" href="../../support/reftests.css">
<link rel='match' href='hidden_none_30px_center-ref.html'>
<style>
 #test > * { overflow:hidden; -o-object-fit:none; -o-object-position:30px center }
</style>
<div id="test">
 <video poster="../../support/wide.jpg"></video>
</div>


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
    <meta name="format-detection" content="telephone=no">
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/style.css">

Rules

Of an Impromptu

 While this was designed to be used for Academic Deecathlon, it can also be used to learn how to think on the fly. The rules of an impromptu are:

1. You have one minute to chose between the three topics and start preparing.

2. Give a 1 minute 30 second to 2 minute speech on the subject.

3. In general, you should try to avoid being controversial.

Main  |  About


text:
namespace tyr { namespace basic {

namespace CurrentThread {
  bool is_main_thread(void) {
    return tid() == kern_getpid();
  }
}

}}