text:
// LLVM module pass to create the single function (fully inlined)
// and parallelized kernel for an OpenCL workgroup.
//
// Copyright (c) 2011 Universidad Rey Juan Carlos
//               2012-2015 Pekka Jääskeläinen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#include <cstdio>
#include <map>
#include <iostream>

#include "CompilerWarnings.h"
IGNORE_COMPILER_WARNING("-Wunused-parameter")

#include "pocl.h"

#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/TypeBuilder.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Transforms/Utils/Local.h"

#include "CanonicalizeBarriers.h"
#include "BarrierTailReplication.h"
#include "WorkitemReplication.h"
#include "Barrier.h"
#include "Workgroup.h"

#include "LLVMUtils.h"
#include <cstdio>
#include <map>
#include <iostream>

#include "pocl.h"
#include "pocl_cl.h"

#if _MSC_VER
#  include "vccompat.hpp"
#endif

#define STRING_LENGTH 32

POP_COMPILER_DIAGS

extern cl_device_id currentPoclDevice;

using namespace std;
using namespace llvm;
using namespace pocl;

static Function *createLauncher(Module &M, Function *F);
static void privatizeContext(Module &M, Function *F);
static void createWorkgroup(Module &M, Function *F);
static void createWorkgroupFast(Module &M, Function *F);

// extern cl::opt<string> Header;

/* The kernel to process in this kernel compiler launch. */
cl::opt<string>
KernelName("kernel",
       cl::desc("Kernel function name"),
       cl::value_desc("kernel"),
       cl::init(""));

namespace llvm {

  typedef struct _pocl_context PoclContext;

  template<bool xcompile> class TypeBuilder<PoclContext, xcompile> {
  public:
    static StructType *get(LLVMContext &Context) {
      if (size_t_width == 64)
        {
          return StructType::get
            (TypeBuilder<types::i<32>, xcompile>::get(Context),
             TypeBuilder<types::i<64>[3], xcompile>::get(Context),
             TypeBuilder<types::i<64>[3], xcompile>::get(Context),
             TypeBuilder<types::i<64>[3], xcompile>::get(Context),
             TypeBuilder<types::i<64>[3], xcompile>::get(Context),
             NULL);
        }
      else if (size_t_width == 32)
        {
          return StructType::get
            (TypeBuilder<types::i<32>, xcompile>::get(Context),
             TypeBuilder<types::i<32>[3], xcompile>::get(Context),
             TypeBuilder<types::i<32>[3], xcompile>::get(Context),
             TypeBuilder<types::i<32>[3], xcompile>::get(Context),
             TypeBuilder<types::i<32>[3], xcompile>::get(Context),
             NULL);
        }
      else
        {
          assert (false && "Unsupported size_t width.");
          return NULL;
        }
    }

    /**
     * We compile for various targets with various widths for the size_t
     * type that depends on the pointer type.
     *
     * This should be set when the correct type is known. This is a hack
     * until a better way is found. It's not thread safe, e.g. if one
     * compiles multiple Modules for multiple different pointer widths in
     * a same process with multiple threads. */
    static void setSizeTWidth(int width) {
      size_t_width = width;
    }

    enum Fields {
      WORK_DIM,
      NUM_GROUPS,
      GROUP_ID,
      GLOBAL_OFFSET,
      LOCAL_SIZE
    };
  private:
    static int size_t_width;

  };

  template<bool xcompile>
  int TypeBuilder<PoclContext, xcompile>::size_t_width = 0;

}  // namespace llvm

char Workgroup::ID = 0;
static RegisterPass<Workgroup> X("workgroup", "Workgroup creation pass");

bool
Workgroup::runOnModule(Module &M)
{
  switch (currentPoclDevice->address_bits) {
  case 64:
    TypeBuilder<PoclContext, true>::setSizeTWidth(64);
    break;
  case 32:
    TypeBuilder<PoclContext, true>::setSizeTWidth(32);
    break;
  default:
    assert (false && "Target has an unsupported pointer width.");
    break;
  }

  for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
    if (!i->isDeclaration())
      i->setLinkage(Function::InternalLinkage);
  }

  // store the new and old kernel pairs in order to regenerate
  // all the metadata that used to point to the unmodified
  // kernels
  FunctionMapping kernels;

  for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
    if (!isKernelToProcess(*i)) continue;
    Function *L = createLauncher(M, &*i);

    L->addFnAttr(Attribute::NoInline);

    privatizeContext(M, L);

    if (!currentPoclDevice->spmd) {
      createWorkgroup(M, L);
      createWorkgroupFast(M, L);
    }
    else
      kernels[&*i] = L;
  }

  if (currentPoclDevice->spmd) {
    regenerate_kernel_metadata(M, kernels);

    /* Delete the old kernels. */
    for (FunctionMapping::const_iterator i = kernels.begin(),
           e = kernels.end(); i != e; ++i)
      {
        Function *old_kernel = (*i).first;
        Function *new_kernel = (*i).second;
        if (old_kernel == new_kernel) continue;
        old_kernel->eraseFromParent();
      }
  }

  Function *barrier = cast<Function>
    (M.getOrInsertFunction(BARRIER_FUNCTION_NAME,
                           Type::getVoidTy(M.getContext()),
                           NULL));
  BasicBlock *bb = BasicBlock::Create(M.getContext(), "", barrier);
  ReturnInst::Create(M.getContext(), 0, bb);

  return true;
}

static Function *
createLauncher(Module &M, Function *F)
{
  SmallVector<Type *, 8> sv;

  for (Function::const_arg_iterator i = F->arg_begin(), e = F->arg_end();
       i != e; ++i)
    sv.push_back (i->getType());
  if (currentPoclDevice->spmd) {
    PointerType* g_pc_ptr = PointerType::get(TypeBuilder<PoclContext, true>::get(M.getContext()), 1);
    sv.push_back(g_pc_ptr);
  }
  else
    sv.push_back(TypeBuilder<PoclContext*, true>::get(M.getContext()));

  FunctionType *ft = FunctionType::get(Type::getVoidTy(M.getContext()),
				       ArrayRef<Type *> (sv),
				       false);

  std::string funcName = "";
  funcName = F->getName().str();
  Function *L = NULL;
  if (currentPoclDevice->spmd) {
    Function *F = M.getFunction(funcName);
    F->setName(funcName + "_original");
    L = Function::Create(ft,
                         Function::ExternalLinkage,
                         funcName,
                         &M);
  }
  else
    L = Function::Create(ft,
                         Function::ExternalLinkage,
                         "_pocl_launcher_" + funcName,
                         &M);

  SmallVector<Value *, 8> arguments;
  Function::arg_iterator ai = L->arg_begin();
  for (unsigned i = 0, e = F->getArgumentList().size(); i != e; ++i)  {
    arguments.push_back(&*ai);
    ++ai;
  }

  /* Copy the function attributes to transfer noalias etc. from the
     original kernel which will be inlined into the launcher. */
  L->setAttributes(F->getAttributes());

  Value *ptr, *v;
  char s[STRING_LENGTH];
  GlobalVariable *gv;

  IRBuilder<> builder(BasicBlock::Create(M.getContext(), "", L));

  ptr = builder.CreateStructGEP(ai->getType()->getPointerElementType(), &*ai,
                                TypeBuilder<PoclContext, true>::WORK_DIM);
  gv = M.getGlobalVariable("_work_dim");
  if (gv != NULL) {
    v = builder.CreateLoad(builder.CreateConstGEP1_32(ptr, 0));
    builder.CreateStore(v, gv);
  }

  int size_t_width = 32;
  if (currentPoclDevice->address_bits == 64)
    size_t_width = 64;

  ptr = builder.CreateStructGEP(ai->getType()->getPointerElementType(), &*ai,
                                TypeBuilder<PoclContext, true>::GROUP_ID);
  for (int i = 0; i < 3; ++i) {
    snprintf(s, STRING_LENGTH, "_group_id_%c", 'x' + i);
    gv = M.getGlobalVariable(s);
    if (gv != NULL) {
      if (size_t_width == 64) {
          v = builder.CreateLoad(builder.CreateConstGEP2_64(ptr, 0, i));
      } else {
          v = builder.CreateLoad(
                builder.CreateConstGEP2_32(
                                   ptr->getType()->getPointerElementType(),
                                   ptr, 0, i));
      }
      builder.CreateStore(v, gv);
    }
  }

  if (WGDynamicLocalSize) {
    ptr = builder.CreateStructGEP(ai->getType()->getPointerElementType(), &*ai,
                                  TypeBuilder<PoclContext, true>::LOCAL_SIZE);
    for (int i = 0; i < 3; ++i) {
      snprintf(s, STRING_LENGTH, "_local_size_%c", 'x' + i);
      gv = M.getGlobalVariable(s);
      if (gv != NULL) {
        if (size_t_width == 64) {
          v = builder.CreateLoad(builder.CreateConstGEP2_64(ptr, 0, i));
        } else {
          v = builder.CreateLoad(
                 builder.CreateConstGEP2_32(
                                    ptr->getType()->getPointerElementType(),
                                    ptr, 0, i));
        }
        builder.CreateStore(v, gv);
      }
    }
  }

  ptr = builder.CreateStructGEP(ai->getType()->getPointerElementType(), &*ai,
                                TypeBuilder<PoclContext, true>::NUM_GROUPS);
  for (int i = 0; i < 3; ++i) {
    snprintf(s, STRING_LENGTH, "_num_groups_%c", 'x' + i);
    gv = M.getGlobalVariable(s);
    if (gv != NULL) {
      if (size_t_width == 64)
        {
          v = builder.CreateLoad(builder.CreateConstGEP2_64(ptr, 0, i));
        }
      else
        {
          v = builder.CreateLoad(
                builder.CreateConstGEP2_32(
                  ptr->getType()->getPointerElementType(), ptr, 0, i));
        }
      builder.CreateStore(v, gv);
    }
  }

  ptr = builder.CreateStructGEP(ai->getType()->getPointerElementType(), &*ai,
                                TypeBuilder<PoclContext, true>::GLOBAL_OFFSET);
  for (int i = 0; i < 3; ++i) {
    snprintf(s, STRING_LENGTH, "_global_offset_%c", 'x' + i);
    gv = M.getGlobalVariable(s);
    if (gv != NULL) {
      if (size_t_width == 64)
        {
          v = builder.CreateLoad(builder.CreateConstGEP2_64(ptr, 0, i));
        }
      else
        {
          v = builder.CreateLoad(builder.CreateConstGEP2_32(ptr->getType()->getPointerElementType(), ptr, 0, i));
        }
      builder.CreateStore(v, gv);
    }
  }

  CallInst *c = builder.CreateCall(F, ArrayRef<Value*>(arguments));
  builder.CreateRetVoid();

  InlineFunctionInfo IFI;
  InlineFunction(c, IFI);

  return L;
}

static void
privatizeContext(Module &M, Function *F)
{
  char s[STRING_LENGTH];
  GlobalVariable *gv[3];
  AllocaInst *ai[3] = {NULL, NULL, NULL};

  IRBuilder<> builder(F->getEntryBlock().getFirstNonPHI());

  // Privatize _local_id
  for (int i = 0; i < 3; ++i) {
    snprintf(s, STRING_LENGTH, "_local_id_%c", 'x' + i);
    gv[i] = M.getGlobalVariable(s);
    if (gv[i] != NULL) {
      ai[i] = builder.CreateAlloca(gv[i]->getType()->getElementType(),
				   0, s);
      if(gv[i]->hasInitializer()) {
        Constant *c = gv[i]->getInitializer();
        builder.CreateStore(c, ai[i]);
      }
    }
  }
  for (Function::iterator i = F->begin(), e = F->end(); i != e; ++i) {
    for (BasicBlock::iterator ii = i->begin(), ee = i->end();
         ii != ee; ++ii) {
      for (int j = 0; j < 3; ++j)
        ii->replaceUsesOfWith(gv[j], ai[j]);
    }
  }

  // Privatize _local_size
  for (int i = 0; i < 3; ++i) {
    snprintf(s, STRING_LENGTH, "_local_size_%c", 'x' + i);
    gv[i] = M.getGlobalVariable(s);
    if (gv[i] != NULL) {
      ai[i] = builder.CreateAlloca(gv[i]->getType()->getElementType(),
                                   0, s);
      if(gv[i]->hasInitializer()) {
        Constant *c = gv[i]->getInitializer();
        builder.CreateStore(c, ai[i]);
      }
    }
  }
  for (Function::iterator i = F->begin(), e = F->end(); i != e; ++i) {
    for (BasicBlock::iterator ii = i->begin(), ee = i->end();
         ii != ee; ++ii) {
      for (int j = 0; j < 3; ++j)
        ii->replaceUsesOfWith(gv[j], ai[j]);
    }
  }

  // Privatize _work_dim
  gv[0] = M.getGlobalVariable("_work_dim");
  if (gv[0] != NULL) {
    ai[0] = builder.CreateAlloca(gv[0]->getType()->getElementType(),
                                 0, "_work_dim");
    if(gv[0]->hasInitializer()) {
      Constant *c = gv[0]->getInitializer();
      builder.CreateStore(c, ai[0]);
    }
  }
  for (Function::iterator i = F->begin(), e = F->end(); i != e; ++i) {
    for (BasicBlock::iterator ii = i->begin(), ee = i->end();
	 ii != ee; ++ii) {
      ii->replaceUsesOfWith(gv[0], ai[0]);
    }
  }

  // Privatize _num_groups
  for (int i = 0; i < 3; ++i) {
    snprintf(s, STRING_LENGTH, "_num_groups_%c", 'x' + i);
    gv[i] = M.getGlobalVariable(s);
    if (gv[i] != NULL) {
      ai[i] = builder.CreateAlloca(gv[i]->getType()->getElementType(),
                                   0, s);
      if(gv[i]->hasInitializer()) {
        Constant *c = gv[i]->getInitializer();
        builder.CreateStore(c, ai[i]);
      }
    }
  }
  for (Function::iterator i = F->begin(), e = F->end(); i != e; ++i) {
    for (BasicBlock::iterator ii = i->begin(), ee = i->end();
         ii != ee; ++ii) {
      for (int j = 0; j < 3; ++j)
        ii->replaceUsesOfWith(gv[j], ai[j]);
    }
  }

  // Privatize _group_id
  for (int i = 0; i < 3; ++i) {
    snprintf(s, STRING_LENGTH, "_group_id_%c", 'x' + i);
    gv[i] = M.getGlobalVariable(s);
    if (gv[i] != NULL) {
      ai[i] = builder.CreateAlloca(gv[i]->getType()->getElementType(),
                                   0, s);
      if(gv[i]->hasInitializer()) {
        Constant *c = gv[i]->getInitializer();
        builder.CreateStore(c, ai[i]);
      }
    }
  }
  for (Function::iterator i = F->begin(), e = F->end(); i != e; ++i) {
    for (BasicBlock::iterator ii = i->begin(), ee = i->end();
         ii != ee; ++ii) {
      for (int j = 0; j < 3; ++j)
        ii->replaceUsesOfWith(gv[j], ai[j]);
    }
  }

  // Privatize _global_offset
  for (int i = 0; i < 3; ++i) {
    snprintf(s, STRING_LENGTH, "_global_offset_%c", 'x' + i);
    gv[i] = M.getGlobalVariable(s);
    if (gv[i] != NULL) {
      ai[i] = builder.CreateAlloca(gv[i]->getType()->getElementType(),
                                   0, s);
      if(gv[i]->hasInitializer()) {
        Constant *c = gv[i]->getInitializer();
        builder.CreateStore(c, ai[i]);
      }
    }
  }
  for (Function::iterator i = F->begin(), e = F->end(); i != e; ++i) {
    for (BasicBlock::iterator ii = i->begin(), ee = i->end();
         ii != ee; ++ii) {
      for (int j = 0; j < 3; ++j)
        ii->replaceUsesOfWith(gv[j], ai[j]);
    }
  }
}

/**
 * Creates a work group launcher function (called KERNELNAME_workgroup)
 * that assumes kernel pointer arguments are stored as pointers to the
 * actual buffers and that scalar data is loaded from the default memory.
 */
static void
createWorkgroup(Module &M, Function *F)
{
  IRBuilder<> builder(M.getContext());

  FunctionType *ft =
    TypeBuilder<void(types::i<8>*[],
		     PoclContext*), true>::get(M.getContext());

  std::string funcName = "";
  funcName = F->getName().str();

  Function *workgroup =
    dyn_cast<Function>(M.getOrInsertFunction(funcName + "_workgroup", ft));
  assert(workgroup != NULL);

  builder.SetInsertPoint(BasicBlock::Create(M.getContext(), "", workgroup));

  Function::arg_iterator ai = workgroup->arg_begin();

  SmallVector<Value*, 8> arguments;
  int i = 0;
  for (Function::const_arg_iterator ii = F->arg_begin(), ee = F->arg_end();
       ii != ee; ++ii) {
    Type *t = ii->getType();

    Value *gep = builder.CreateGEP(&*ai,
            ConstantInt::get(IntegerType::get(M.getContext(), 32), i));
    Value *pointer = builder.CreateLoad(gep);

    /* If it's a pass by value pointer argument, we just pass the pointer
     * as is to the function, no need to load form it first. */
    Value *value;
    if (ii->hasByValAttr()) {
        value = builder.CreatePointerCast(pointer, t);
    } else {
        value = builder.CreatePointerCast(pointer, t->getPointerTo());
        value = builder.CreateLoad(value);
    }

    arguments.push_back(value);
    ++i;
  }

  arguments.back() = &*(++ai);

  builder.CreateCall(F, ArrayRef<Value*>(arguments));
  builder.CreateRetVoid();
}

/**
 * Creates a work group launcher more suitable for the heterogeneous
 * host-device setup  (called KERNELNAME_workgroup_fast).
 *
 * 1) Pointer arguments are stored directly as pointers to the
 *    buffers in the argument buffer.
 *
 * 2) Scalar values are loaded from the global memory address
 *    space.
 *
 * This should minimize copying of data and memory allocation
 * at the device.
 */
static void
createWorkgroupFast(Module &M, Function *F)
{
  IRBuilder<> builder(M.getContext());

  FunctionType *ft =
    TypeBuilder<void(types::i<8>*[],
		     PoclContext*), true>::get(M.getContext());

  std::string funcName = "";
  funcName = F->getName().str();
  Function *workgroup =
    dyn_cast<Function>(M.getOrInsertFunction(funcName + "_workgroup_fast", ft));
  assert(workgroup != NULL);

  workgroup->addFnAttr(Attribute::NoInline);

  builder.SetInsertPoint(BasicBlock::Create(M.getContext(), "", workgroup));

  Function::arg_iterator ai = workgroup->arg_begin();

  SmallVector<Value*, 8> arguments;
  int i = 0;
  for (Function::const_arg_iterator ii = F->arg_begin(), ee = F->arg_end();
       ii != ee; ++i, ++ii) {
    Type *t = ii->getType();
    Value *gep = builder.CreateGEP(&*ai,
            ConstantInt::get(IntegerType::get(M.getContext(), 32), i));
    Value *pointer = builder.CreateLoad(gep);

    if (t->isPointerTy()) {
      if (!ii->hasByValAttr()) {
        /* Assume the pointer is directly in the arg array. */
        arguments.push_back(builder.CreatePointerCast(pointer, t));
        continue;
      }

      /* It's a pass by value pointer argument, use the underlying
       * element type in subsequent load. */
      t = t->getPointerElementType();
    }

    /* If it's a pass by value pointer argument, we just pass the pointer
     * as is to the function, no need to load from it first. */
    Value *value;

    if (!ii->hasByValAttr() || ((PointerType*)t)->getAddressSpace() == 1)
      value = builder.CreatePointerCast
        (pointer, t->getPointerTo(POCL_ADDRESS_SPACE_GLOBAL));
    else
      value = builder.CreatePointerCast(pointer, t->getPointerTo());

    if (!ii->hasByValAttr()) {
      value = builder.CreateLoad(value);
    }

    arguments.push_back(value);
  }

  arguments.back() = &*(++ai);

  builder.CreateCall(F, ArrayRef<Value*>(arguments));
  builder.CreateRetVoid();
}

/**
 * Returns true in case the given function is a kernel that
 * should be processed by the kernel compiler.
 */
bool
Workgroup::isKernelToProcess(const Function &F)
{
  const Module *m = F.getParent();

  NamedMDNode *kernels = m->getNamedMetadata("opencl.kernels");
  if (kernels == NULL) {
    if (KernelName == "")
      return true;
    if (F.getName() == KernelName)
      return true;

    return false;
  }

  for (unsigned i = 0, e = kernels->getNumOperands(); i != e; ++i) {
    if (kernels->getOperand(i)->getOperand(0) == NULL)
      continue; // globaldce might have removed uncalled kernels
    Function *k =
      cast<Function>(
        dyn_cast<ValueAsMetadata>(kernels->getOperand(i)->getOperand(0))
          ->getValue());
    if (&F == k)
      return true;
  }

  return false;
}

/**
 * Returns true in case the given function is a kernel
 * with work-group barriers inside it.
 */
bool
Workgroup::hasWorkgroupBarriers(const Function &F)
{
  for (llvm::Function::const_iterator i = F.begin(), e = F.end();
       i != e; ++i) {
    const llvm::BasicBlock* bb = &*i;
    if (Barrier::hasBarrier(bb)) {

      // Ignore the implicit entry and exit barriers.
      if (Barrier::hasOnlyBarrier(bb) && bb == &F.getEntryBlock())
        continue;

      if (Barrier::hasOnlyBarrier(bb) &&
          bb->getTerminator()->getNumSuccessors() == 0)
        continue;

      return true;
    }
  }
  return false;
}


text:
"""
Script to get spectrum from OceanOptics Spectroscope

Things to modify before use:
- gid and uid of current user
"""
from __future__ import print_function

from builtins import str
from builtins import range
import sys, os
base_dir = os.path.dirname(os.path.realpath(__file__))
root_dir = os.path.abspath(os.path.join(base_dir, "..", "..", "helpers"))
sys.path.insert(0, root_dir)
from getSpectra import Icecube
from time import sleep
import argparse
import os
import time
import matplotlib.pyplot as plt
import numpy as np
import pwd
import grp

def main(n, description,intTime, noPlot):
    c = 0
    foldername = time.strftime("%Y%m%d_%H%M%S")
    uid = pwd.getpwnam("sunyudong").pw_uid
    gid = grp.getgrnam("sunyudong").gr_gid
    if not n == -1:
        os.mkdir(foldername)
        path = foldername
        os.chown(path, uid, gid)
        if not description == None:
            z = open("spectra_log", "a")
            os.chown("spectra_log", uid, gid)
            z.write("{}\t{}\n".format(foldername, description))
        with open("{}/meta.info".format(foldername), 'w') as f:
            f.write("{}\tintTime = {} ms\t{}\n".format(foldername, intTime, description))
        os.chown("{}/meta.info".format(foldername), uid, gid)

    with Icecube() as cube:
        if not n == -1:
            # Write model information into meta.info
            with open("{}/meta.info".format(foldername), 'a') as f:
                f.write("Serial ({}) = {}\n".format(cube.type, cube.getSingleEEPROM(0)))
                f.write("Autonulling Factor = {}".format(cube.autonulling))

            # Write some metadata about corrections
            with open("{}/linearity.corr".format(foldername), 'a') as f:
                f.write("Linearity Correction -> {}th Order Polynomial\n".format(cube.getSingleEEPROM(14)))
                for i in range(6, 14):
                    f.write("{}\t{}\n".format(i - 6, cube.getSingleEEPROM(i)))
            os.chown("{}/linearity.corr".format(foldername), uid, gid)

            with open("{}/wavelength.corr".format(foldername), 'a') as f:
                f.write("Wavelength Correction\n")
                for i in range(1, 5):
                    f.write("{}\t{}\n".format(i - 1, cube.getSingleEEPROM(i)))
            os.chown("{}/wavelength.corr".format(foldername), uid, gid)

        cube.setIntegrationTime(intTime)
        totalSet = False
        while True:
            try:
                # sys.stdout.write("\r{}".format(n))
                if n == 0:
                    print("\nAcquisition Complete")
                    break
                elif n > 0:
                    # http://www.kahfei.com/2011/03/11/print-without-newline-in-python/
                    if not totalSet:
                        count = 0
                        total = n
                        digits = int(np.floor(np.log10(total)) + 1)
                        printString = "[{:>10} degC] Acquiring [{:>"+ str(digits) +"}/{}] Left: {}\033[K\r"
                        totalSet = True

                    count += 1
                    print(printString.format(str(cube.getTemp()), count, total, n - 1), end=' ')
                else:
                    print("[{:>10} degC] Live Plotting\033[K\r".format(str(cube.getTemp())), end=' ')

                spec = cube.getSpectra()

                if not noPlot:
                    Y = [i[1] for i in spec]
                    if c == 0: #init
                        X = [i[0] for i in spec]
                        plt.ion()
                        with plt.style.context('fivethirtyeight'):
                            graph = plt.plot(X,Y)[0]
                            plt.xlabel("Wavelength/nm")
                            plt.ylabel("Pixel intensity")
                        c = 1
                    else:
                        graph.set_ydata(Y)
                        with plt.style.context('fivethirtyeight'):
                            plt.draw()
                            plt.pause(0.01)

                # sleep(0.05)

                if n > 0:
                    with open("{}/data_{}".format(foldername,n) , 'w') as f:
                        for i in spec:
                            f.write("{}\t{}\n".format(i[0], i[1]))
                    os.chown("{}/data_{}".format(foldername,n), uid, gid)
                    n -= 1
                    # print " now {} readings left".format(n)

            except KeyboardInterrupt:
                cube.releaseInterface(0)
                cube.close()
                print("\n --- EXITING --- ")
                sys.exit()

def init():
    parser = argparse.ArgumentParser()
    parser.add_argument('n', type = int, help = "no. of readings to take. -1 for infinite")
    #parser.add_argument('-p','--plot', action = 'store_true', help = "flag to enable plotting")
    parser.add_argument('-d', '--description', type = str, help = "label each acquisition", default = None)
    parser.add_argument('-t', '--intTime', type = float, help = "milliseconds of integration time", default = 2)
    parser.add_argument('-p', '--noPlot', action='store_true')
    args = parser.parse_args()

    main(args.n, args.description, args.intTime, args.noPlot)
init()

redpajama_set_name: RedPajamaGithub


text:
package org.python.antlr.ast;
import org.antlr.runtime.CommonToken;
import org.antlr.runtime.Token;
import org.python.antlr.AST;
import org.python.antlr.PythonTree;
import org.python.antlr.adapter.AstAdapters;
import org.python.antlr.base.excepthandler;
import org.python.antlr.base.expr;
import org.python.antlr.base.mod;
import org.python.antlr.base.slice;
import org.python.antlr.base.stmt;
import org.python.core.ArgParser;
import org.python.core.AstList;
import org.python.core.Py;
import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.core.PyStringMap;
import org.python.core.PyType;
import org.python.core.Visitproc;
import org.python.expose.ExposedGet;
import org.python.expose.ExposedMethod;
import org.python.expose.ExposedNew;
import org.python.expose.ExposedSet;
import org.python.expose.ExposedType;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;

@ExposedType(name = "_ast.BoolOp", base = expr.class)
public class BoolOp extends expr {
public static final PyType TYPE = PyType.fromClass(BoolOp.class);
    private boolopType op;
    public boolopType getInternalOp() {
        return op;
    }
    @ExposedGet(name = "op")
    public PyObject getOp() {
        return AstAdapters.boolop2py(op);
    }
    @ExposedSet(name = "op")
    public void setOp(PyObject op) {
        this.op = AstAdapters.py2boolop(op);
    }

    private java.util.List<expr> values;
    public java.util.List<expr> getInternalValues() {
        return values;
    }
    @ExposedGet(name = "values")
    public PyObject getValues() {
        return new AstList(values, AstAdapters.exprAdapter);
    }
    @ExposedSet(name = "values")
    public void setValues(PyObject values) {
        this.values = AstAdapters.py2exprList(values);
    }

    private final static PyString[] fields =
    new PyString[] {new PyString("op"), new PyString("values")};
    @ExposedGet(name = "_fields")
    public PyString[] get_fields() { return fields; }

    private final static PyString[] attributes =
    new PyString[] {new PyString("lineno"), new PyString("col_offset")};
    @ExposedGet(name = "_attributes")
    public PyString[] get_attributes() { return attributes; }

    public BoolOp(PyType subType) {
        super(subType);
    }
    public BoolOp() {
        this(TYPE);
    }
    @ExposedNew
    @ExposedMethod
    public void BoolOp___init__(PyObject[] args, String[] keywords) {
        ArgParser ap = new ArgParser("BoolOp", args, keywords, new String[]
            {"op", "values", "lineno", "col_offset"}, 2, true);
        setOp(ap.getPyObject(0, Py.None));
        setValues(ap.getPyObject(1, Py.None));
        int lin = ap.getInt(2, -1);
        if (lin != -1) {
            setLineno(lin);
        }

        int col = ap.getInt(3, -1);
        if (col != -1) {
            setLineno(col);
        }

    }

    public BoolOp(PyObject op, PyObject values) {
        setOp(op);
        setValues(values);
    }

    public BoolOp(Token token, boolopType op, java.util.List<expr> values) {
        super(token);
        this.op = op;
        this.values = values;
        if (values == null) {
            this.values = new ArrayList<expr>();
        }
        for(PythonTree t : this.values) {
            addChild(t);
        }
    }

    public BoolOp(Integer ttype, Token token, boolopType op, java.util.List<expr> values) {
        super(ttype, token);
        this.op = op;
        this.values = values;
        if (values == null) {
            this.values = new ArrayList<expr>();
        }
        for(PythonTree t : this.values) {
            addChild(t);
        }
    }

    public BoolOp(PythonTree tree, boolopType op, java.util.List<expr> values) {
        super(tree);
        this.op = op;
        this.values = values;
        if (values == null) {
            this.values = new ArrayList<expr>();
        }
        for(PythonTree t : this.values) {
            addChild(t);
        }
    }

    @ExposedGet(name = "repr")
    public String toString() {
        return "BoolOp";
    }

    public String toStringTree() {
        StringBuffer sb = new StringBuffer("BoolOp(");
        sb.append("op=");
        sb.append(dumpThis(op));
        sb.append(",");
        sb.append("values=");
        sb.append(dumpThis(values));
        sb.append(",");
        sb.append(")");
        return sb.toString();
    }

    public <R> R accept(VisitorIF<R> visitor) throws Exception {
        return visitor.visitBoolOp(this);
    }

    public void traverse(VisitorIF<?> visitor) throws Exception {
        if (values != null) {
            for (PythonTree t : values) {
                if (t != null)
                    t.accept(visitor);
            }
        }
    }

    public PyObject __dict__;

    @Override
    public PyObject fastGetDict() {
        ensureDict();
        return __dict__;
    }

    @ExposedGet(name = "__dict__")
    public PyObject getDict() {
        return fastGetDict();
    }

    private void ensureDict() {
        if (__dict__ == null) {
            __dict__ = new PyStringMap();
        }
    }

    private int lineno = -1;
    @ExposedGet(name = "lineno")
    public int getLineno() {
        if (lineno != -1) {
            return lineno;
        }
        return getLine();
    }

    @ExposedSet(name = "lineno")
    public void setLineno(int num) {
        lineno = num;
    }

    private int col_offset = -1;
    @ExposedGet(name = "col_offset")
    public int getCol_offset() {
        if (col_offset != -1) {
            return col_offset;
        }
        return getCharPositionInLine();
    }

    @ExposedSet(name = "col_offset")
    public void setCol_offset(int num) {
        col_offset = num;
    }

}


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

<info><title>Zend_Reflection Reference</title></info>

    <para>
        The various classes in <classname>Zend_Reflection</classname> mimic the
        <acronym>API</acronym> of <acronym>PHP</acronym>'s <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://php.net/reflection">Reflection <acronym>API</acronym></link> - with one
        important difference. <acronym>PHP</acronym>'s Reflection <acronym>API</acronym> does not
        provide introspection into docblock annotation tags, nor into parameter variable
        types or return types.
    </para>

    <para>
        <classname>Zend_Reflection</classname> analyzes method docblock annotations to
        determine parameter variable types and the return type. Specifically,
        the @param and @return annotations are used.
        However, you can also check for any other annotation tags, as well as
        the standard "short" and "long" descriptions.
    </para>

    <para>
        Each reflection object in <classname>Zend_Reflection</classname> overrides the
        <methodname>getDocblock()</methodname> method to return an instance of
        <classname>Zend_Reflection_Docblock</classname>. This class provides introspection
        into the docblocks and annotation tags.
    </para>

    <para>
        <classname>Zend_Reflection_File</classname> is a new reflection class that allows
        introspection of <acronym>PHP</acronym> files. With it, you can retrieve the classes,
        functions, and global <acronym>PHP</acronym> code contained in the file.
    </para>

    <para>
        Finally, the various methods that return other reflection objects
        allow a second parameter, the name of the reflection class to use for
        the returned reflection object.
    </para>

<info><title>Zend_Reflection_Docblock</title></info>

        <para>
            <classname>Zend_Reflection_Docblock</classname> is the heart of
            <classname>Zend_Reflection</classname>'s value-add over <acronym>PHP</acronym>'s
            Reflection <acronym>API</acronym>. It provides the following methods:
        </para>

        <itemizedlist>
            <listitem>
                <para>
                    <methodname>getContents()</methodname>: returns the full contents of the
                    docblock.
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>getStartLine()</methodname>: returns the starting position of
                    the docblock within the defining file.
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>getEndLine()</methodname>: get last line of docblock within the
                    defining file.
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>getShortDescription()</methodname>: get the short, one-line
                    description (usually the first line of the docblock).
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>getLongDescription()</methodname>: get the long description from
                    the docblock.
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>hasTag($name)</methodname>: determine if the docblock has the
                    given annotation tag.
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>getTag($name)</methodname>: Retrieve the given annotation tag
                    reflection object, or a boolean <constant>FALSE</constant> if it's not
                    present.
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>getTags($filter)</methodname>: Retrieve all tags, or all tags
                    matching the given <varname>$filter</varname> string. The tags
                    returned will be an array of
                    <classname>Zend_Reflection_Docblock_Tag</classname> objects.
                </para>
            </listitem>
        </itemizedlist>

<info><title>Zend_Reflection_Docblock_Tag</title></info>

        <para>
            <classname>Zend_Reflection_Docblock_Tag</classname> provides reflection for
            individual annotation tags. Most tags consist of only a name and a
            description. In the case of some special tags, the class provides a
            factory method for retrieving an instance of the appropriate class.
        </para>

        <para>
            The following methods are defined for
            <classname>Zend_Reflection_Docblock_Tag</classname>:
        </para>

        <itemizedlist>
            <listitem>
                <para>
                    <methodname>factory($tagDocblockLine)</methodname>: instantiate the
                    appropriate tag reflection class and return it.
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>getName()</methodname>: return the annotation tag name.
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>getDescription()</methodname>: return the annotation
                    description.
                </para>
            </listitem>
        </itemizedlist>

<info><title>Zend_Reflection_Docblock_Tag_Param</title></info>

        <para>
            <classname>Zend_Reflection_Docblock_Tag_Param</classname> is a specialized
            version of <classname>Zend_Reflection_Docblock_Tag</classname>. The
            @param annotation tag description consists of the
            parameter type, variable name, and variable description. It adds the
            following methods to <classname>Zend_Reflection_Docblock_Tag</classname>:
        </para>

        <itemizedlist>
            <listitem>
                <para>
                    <methodname>getType()</methodname>: return the parameter variable type.
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>getVariableName()</methodname>: return the parameter variable
                    name.
                </para>
            </listitem>
        </itemizedlist>

<info><title>Zend_Reflection_Docblock_Tag_Return</title></info>

        <para>
            Like <classname>Zend_Reflection_Docblock_Tag_Param</classname>,
            <classname>Zend_Reflection_Docblock_Tag_Return</classname> is a specialized
            version of <classname>Zend_Reflection_Docblock_Tag</classname>. The
            @return annotation tag description consists of the
            return type and variable description. It adds the following method
            to <classname>Zend_Reflection_Docblock_Tag</classname>:
        </para>

        <itemizedlist>
            <listitem>
                <para>
                    <methodname>getType()</methodname>: return the return type.
                </para>
            </listitem>
        </itemizedlist>

<info><title>Zend_Reflection_File</title></info>

        <para>
            <classname>Zend_Reflection_File</classname> provides introspection into
            <acronym>PHP</acronym> files. With it, you can introspect the classes, functions, and
            bare <acronym>PHP</acronym> code defined in a file. It defines the following methods:
        </para>

        <itemizedlist>
            <listitem>
                <para>
                    <methodname>getFileName()</methodname>: retrieve the filename of the file
                    being reflected.
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>getStartLine()</methodname>: retrieve the starting line of the
                    file (always "1").
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>getEndLine()</methodname> retrieve the last line / number of
                    lines in the file.
                </para>
            </listitem>

            <listitem>
                <para>
                    getDocComment($reflectionClass =
                        'Zend_Reflection_Docblock'): retrive the file-level
                    docblock reflection object.
                </para>
            </listitem>

            <listitem>
                <para>
                    getClasses($reflectionClass =
                        'Zend_Reflection_Class'): retrieve an array of
                    reflection objects, one for each class defined in the file.
                </para>
            </listitem>

            <listitem>
                <para>
                    getFunctions($reflectionClass =
                        'Zend_Reflection_Function'): retrieve an array of
                    reflection objects, one for each function defined in the file.
                </para>
            </listitem>

            <listitem>
                <para>
                    getClass($name = null, $reflectionClass =
                        'Zend_Reflection_Class'): retrieve the reflection
                    object for a single class.
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>getContents()</methodname>: retrieve the full contents of the
                    file.
                </para>
            </listitem>
        </itemizedlist>

<info><title>Zend_Reflection_Class</title></info>

        <para>
            <classname>Zend_Reflection_Class</classname> extends
            ReflectionClass, and follows its <acronym>API</acronym>. It adds one
            additional method, <methodname>getDeclaringFile()</methodname>, which may be
            used to retrieve the <classname>Zend_Reflection_File</classname> reflection
            object for the defining file.
        </para>

        <para>
            Additionally, the following methods add an additional argument for
            specifying the reflection class to use when fetching a reflection
            object:
        </para>

        <itemizedlist>
            <listitem>
                <para>
                    <methodname>getDeclaringFile($reflectionClass =
                        'Zend_Reflection_File')</methodname>
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>getDocblock($reflectionClass =
                        'Zend_Reflection_Docblock')</methodname>
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>getInterfaces($reflectionClass =
                        'Zend_Reflection_Class')</methodname>
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>getMethod($reflectionClass = 'Zend_Reflection_Method')</methodname>
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>getMethods($filter = -1, $reflectionClass =
                        'Zend_Reflection_Method')</methodname>
                </para>
            </listitem>

            <listitem><para>
                <methodname>getParentClass($reflectionClass = 'Zend_Reflection_Class')</methodname>
            </para></listitem>

            <listitem>
                <para>
                    getProperty($name, $reflectionClass = 'Zend_Reflection_Property')
                </para>
            </listitem>

            <listitem>
                <para>
                    getProperties($filter = -1, $reflectionClass =
                        'Zend_Reflection_Property')
                </para>
            </listitem>
        </itemizedlist>

<info><title>Zend_Reflection_Extension</title></info>

        <para>
            <classname>Zend_Reflection_Extension</classname> extends
            ReflectionExtension, and follows its <acronym>API</acronym>. It overrides
            the following methods to add an additional argument for specifying
            the reflection class to use when fetching a reflection object:
        </para>

        <itemizedlist>
            <listitem>
                <para>
                    getFunctions($reflectionClass =
                        'Zend_Reflection_Function'): retrieve an array of
                    reflection objects representing the functions defined by the extension.
                </para>
            </listitem>

            <listitem>
                <para>
                    getClasses($reflectionClass =
                        'Zend_Reflection_Class'): retrieve an array of
                    reflection objects representing the classes defined by the extension.
                </para>
            </listitem>
        </itemizedlist>

<info><title>Zend_Reflection_Function</title></info>

        <para>
            <classname>Zend_Reflection_Function</classname> adds a method for retrieving
            the function return type, as well as overrides several methods to
            allow specifying the reflection class to use for returned reflection
            objects.
        </para>

        <itemizedlist>
            <listitem>
                <para>
                    getDocblock($reflectionClass =
                        'Zend_Reflection_Docblock'): retrieve the function
                    docblock reflection object.
                </para>
            </listitem>

            <listitem>
                <para>
                    getParameters($reflectionClass =
                        'Zend_Reflection_Parameter'): retrieve an array of
                    all function parameter reflection objects.
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>getReturn()</methodname>: retrieve the return type reflection
                    object.
                </para>
            </listitem>
        </itemizedlist>

<info><title>Zend_Reflection_Method</title></info>

        <para>
            <classname>Zend_Reflection_Method</classname> mirrors
            <classname>Zend_Reflection_Function</classname>, and only overrides one
            additional method:
        </para>

        <itemizedlist>
            <listitem>
                <para>
                    getParentClass($reflectionClass =
                        'Zend_Reflection_Class'): retrieve the parent class
                    reflection object.
                </para>
            </listitem>
        </itemizedlist>

<info><title>Zend_Reflection_Parameter</title></info>

        <para>
            <classname>Zend_Reflection_Parameter</classname> adds a method for retrieving
            the parameter type, as well as overrides methods to allow specifying
            the reflection class to use on returned reflection objects.
        </para>

        <itemizedlist>
            <listitem>
                <para>
                    getDeclaringClass($reflectionClass =
                        'Zend_Reflection_Class'): get the declaring class of
                    the parameter as a reflection object (if available).
                </para>
            </listitem>

            <listitem>
                <para>
                    getClass($reflectionClass =
                        'Zend_Reflection_Class'): get the class of
                    the parameter as a reflection object (if available).
                </para>
            </listitem>

            <listitem>
                <para>
                    getDeclaringFunction($reflectionClass =
                        'Zend_Reflection_Function'): get the function of
                    the parameter as a reflection object (if available).
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>getType()</methodname>: get the parameter type.
                </para>
            </listitem>
        </itemizedlist>

<info><title>Zend_Reflection_Property</title></info>

        <para>
            <classname>Zend_Reflection_Property</classname> overrides a single method in
            order to allow specifying the returned reflection object class:
        </para>

        <itemizedlist>
            <listitem>
                <para>
                    getDeclaringClass($reflectionClass =
                        'Zend_Reflection_Class'): retrieve the declaring
                    class of the property as a reflection object.
                </para>
            </listitem>
        </itemizedlist>


text:
package com.jw.cool.xuanmusicplayer;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jw.cool.xuanmusicplayer.constant.PatternLockStatus;

import java.util.List;

import me.zhanghai.patternlock.PatternUtils;
import me.zhanghai.patternlock.PatternView;

public class LockActivity extends AppCompatActivity
    implements PatternView.OnPatternListener, View.OnClickListener{
    private static final String TAG = "LockActivity";
    private final int MINIMUM_CELL_COUNT = 6;
    private static final int CLEAR_PATTERN_DELAY_MILLI = 2000;
    private TextView mSetupPatterLockTextView;
    private PatternView mViewPatternView;
    private Button mRedrawPatternViewButton;
    private Button mConfirmPatternViewButton;
//    private LinearLayout mClearAndConfirmLinearLayout;
    List<PatternView.Cell> patternViewCells;
    int lockStatus;
    int resultCode = -1;
    String savedPatternLockString;
    String firstPatternLockString;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lock);
        mSetupPatterLockTextView = (TextView) findViewById(R.id.setup_patter_lock);
        mViewPatternView = (PatternView) findViewById(R.id.patter_view);
        mRedrawPatternViewButton = (Button) findViewById(R.id.redraw_pattern_view);
        mConfirmPatternViewButton = (Button) findViewById(R.id.confirm_pattern_view);
//        mClearAndConfirmLinearLayout = (LinearLayout) findViewById(R.id.clear_and_confirm);

        mViewPatternView.setOnPatternListener(this);
        mRedrawPatternViewButton.setOnClickListener(this);
        mConfirmPatternViewButton.setOnClickListener(this);

        Intent intent = getIntent();
        lockStatus = intent.getIntExtra(PatternLockStatus.KEY, -1);
        resultCode = -1;
        SharedPreferences sharedPreferences
                = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        savedPatternLockString = sharedPreferences.getString(PatternLockStatus.KEY, "");
        Log.d(TAG, "onCreate savedPatternLockString " + savedPatternLockString
                + " lockStatus " + lockStatus);
        switchLockStatus();
    }

    void setButtonsVisibility(int visibility){
        mRedrawPatternViewButton.setVisibility(visibility);
        mConfirmPatternViewButton.setVisibility(visibility);
    }

    int switchLockStatus(){
        int returnValue = -1;
        Log.d(TAG, "switchLockStatus lockStatus " + lockStatus);
        switch (lockStatus){
            case PatternLockStatus.SET_LOCK:
            case PatternLockStatus.MODIFY_LOCK_CONFIRM_LOCK_FINISH:
                mSetupPatterLockTextView.setText(R.string.setup_pattern_lock_4_cell_at_least);
                setButtonsVisibility(View.INVISIBLE);
                mViewPatternView.clearPattern();
                mViewPatternView.setEnabled(true);
                break;
            case PatternLockStatus.SET_LOCK_FIRST_DRAW_FINISH:
            case PatternLockStatus.MODIFY_LOCK_FIRST_DRAW_FINISH:
                mSetupPatterLockTextView.setText(R.string.has_record_pattern_lock);
                mViewPatternView.setEnabled(false);
                mSetupPatterLockTextView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mViewPatternView.setEnabled(true);
                        setButtonsVisibility(View.VISIBLE);
                        mViewPatternView.clearPattern();
                        mConfirmPatternViewButton.setEnabled(false);
                        mSetupPatterLockTextView.setText(R.string.confirm_pattern_lock);
                    }
                }, 1500);

                break;
            case PatternLockStatus.UNLOCK:
            case PatternLockStatus.MODIFY_LOCK:
            case PatternLockStatus.CLEAR_LOCK:
                mSetupPatterLockTextView.setText(R.string.please_input_pattern_lock);
                setButtonsVisibility(View.INVISIBLE);
                mViewPatternView.setEnabled(true);
                break;
            case PatternLockStatus.MODIFY_LOCK_SECOND_DRAW_FINISH:
            case PatternLockStatus.SET_LOCK_SECOND_DRAW_FINISH:
                mSetupPatterLockTextView.setText(R.string.your_new_patter_lock);
                mViewPatternView.setEnabled(false);
                mConfirmPatternViewButton.setEnabled(true);
                break;
            case PatternLockStatus.CLEAR_LOCK_CONFIRM_LOCK_FINISH:
                SharedPreferences sharedPreferences
                        = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString(PatternLockStatus.KEY, "");
                editor.commit();
                resultCode = 0;
                finish();
                break;
            case PatternLockStatus.UNLOCK__CONFIRM_LOCK_FINISH:
                resultCode = 0;
                finish();
                break;
            default:
                Log.d(TAG, "switchLockStatus lockStatus " + lockStatus);
                finish();
                break;
        }

        return returnValue;
    }

    @Override
    public void finish() {
        setResult(resultCode);
        super.finish();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_lock, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onPatternStart() {
        Log.d(TAG, "onPatternStart ");
        mSetupPatterLockTextView.setText(R.string.finger_up_after_finish_input);
    }

    @Override
    public void onPatternCleared() {
        Log.d(TAG, "onPatternCleared ");

    }

    @Override
    public void onPatternCellAdded(List<PatternView.Cell> list) {
//        Log.d(TAG, "onPatternCellAdded ");
    }

    @Override
    public void onPatternDetected(List<PatternView.Cell> list) {
        Log.d(TAG, "onPatternDetected ");

        if(list.size() < MINIMUM_CELL_COUNT){
            //输入图案元素小于最小值,需继续输入
            handleWrongStatus();

            return;
        }
        String string = PatternUtils.patternToSha1String(list);
        boolean isConfirmed = false;
        Log.d(TAG, "onPatternDetected string " + string);
        //已设置过解锁图案,则先需确认解锁图案
        if(!TextUtils.isEmpty(savedPatternLockString)){
            if(string.equals(savedPatternLockString)){
                //验证通过
                lockStatus += 1;
                savedPatternLockString = null;
                isConfirmed = true;
            }else{
                //绘制图案与已保存的不一致,需重新绘制
                handleWrongStatus();
                return;
            }
        }

        Log.d(TAG, "onPatternDetected isConfirmed " + isConfirmed);
        if(!isConfirmed){
            //若是第二次绘制解锁图案,则比较是否相同(firstPatternLockString不为空表示已绘制过一次)
            if(TextUtils.isEmpty(firstPatternLockString)){
                lockStatus += 1;
                firstPatternLockString = string;
            }else{
                if(string.equals(firstPatternLockString)){
                    lockStatus += 1;
                }else{
                    //两次绘制的图案不一致,需重新绘制
                    handleWrongStatus();
                    return;
                }
            }
        }

        switchLockStatus();
        Log.d(TAG, "onPatternDetected exit");
    }

    void handleWrongStatus(){
        mViewPatternView.setDisplayMode(PatternView.DisplayMode.Wrong);
        mSetupPatterLockTextView.setText(R.string.please_input_again);
        postClearPatternRunnable();
    }

    void postClearPatternRunnable() {
        mViewPatternView.postDelayed(clearPatternRunnable, CLEAR_PATTERN_DELAY_MILLI);
    }

    private final Runnable clearPatternRunnable = new Runnable() {
        public void run() {
            // clearPattern() resets display mode to DisplayMode.Correct.
            mViewPatternView.clearPattern();
        }
    };

    @Override
    public void onClick(View v) {
        Log.d(TAG, "onClick ");
        switch (v.getId()){
            case R.id.redraw_pattern_view:
                onRedrawButtonClick();
                break;
            case R.id.confirm_pattern_view:
                onConfirmButtonClick();
                break;
            default:
                break;
        }
    }

    void onRedrawButtonClick(){
        switch (lockStatus & 0xff000000){
            case PatternLockStatus.MODIFY_LOCK:
                mViewPatternView.clearPattern();
                firstPatternLockString = null;
                lockStatus = PatternLockStatus.MODIFY_LOCK_CONFIRM_LOCK_FINISH;
                switchLockStatus();
                break;
            case PatternLockStatus.SET_LOCK:
                mViewPatternView.clearPattern();
                firstPatternLockString = null;
                lockStatus = PatternLockStatus.SET_LOCK;
                switchLockStatus();
                break;
        }
    }

    void onConfirmButtonClick() {
        SharedPreferences sharedPreferences
                = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(PatternLockStatus.KEY, firstPatternLockString);
        editor.commit();
        resultCode = 0;
        finish();
    }
}


text:
FROM wnameless/oracle-xe-11g

# Replace shell with bash so we can source files
RUN rm /bin/sh && ln -s /bin/bash /bin/sh

# Set debconf to run non-interactively
RUN echo 'debconf debconf/frontend select Noninteractive' | debconf-set-selections

RUN apt-get update && apt-get install -y -q --no-install-recommends \
  apt-transport-https \
  build-essential \
  ca-certificates \
  curl \
  git \
  libssl-dev \
  python \
  rsync \
  software-properties-common \
  wget \
  gpg-agent \
  apt-utils \
  && rm -rf /var/lib/apt/lists/*

# Install node 6,8,10 from nvm
RUN curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash

# make sure that there is enough disk...
RUN . $HOME/.nvm/nvm.sh && nvm install 6
RUN . $HOME/.nvm/nvm.sh && nvm install 8
RUN . $HOME/.nvm/nvm.sh && nvm install 10
RUN . $HOME/.nvm/nvm.sh && nvm install 11

RUN echo 'module.exports = {\
  oracledb: {\
    user          : "system",\
    password      : "oracle",\
    connectString : "localhost/XE",\
    stmtCacheSize : 0\
  }\
}' > /oracle-config.js

ENV ORACLE_HOME /u01/app/oracle/product/11.2.0/xe
ENV ORACLE_SID XE
ENV OCI_LIB_DIR /u01/app/oracle/product/11.2.0/xe/lib
ENV LD_LIBRARY_PATH /u01/app/oracle/product/11.2.0/xe/lib
ENV KNEX_TEST /oracle-config.js
ENV DB "oracledb"
ENV KNEX_TIMEOUT 60000

ADD . knex

CMD /usr/sbin/startup.sh && \
  . $HOME/.nvm/nvm.sh && \
  nvm use ${NODE_VER:-10} && \
  cd knex && \
  npm install && \
  npm install oracledb && \
  npm run build && \
  npm run plaintest


text:
//
//  WKTravelNoteModel.h
//  Walking
//
//  Created by lanou on 16/4/25.
//  Copyright © 2016年 xqy. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "WKTravelNoteUserModel.h"
#import "WKTravelDetailModel.h"
#import "WKTravleNotesModel.h"

@interface WKTravelNoteModel : NSObject

/** ID */
@property (copy, nonatomic)NSString *ID;
/** 标题 */
@property (copy, nonatomic)NSString *name;
/** 起始日期 */
@property (copy, nonatomic)NSString *start_date;
/** 结束时间 */
@property (copy, nonatomic)NSString *end_date;
/** 天数 */
@property (copy, nonatomic)NSString *days;
/** 图片数量 */
@property (copy, nonatomic)NSString *photos_count;
/** 封面图片 */
@property (copy, nonatomic)NSString *front_cover_photo_url;

@property (strong, nonatomic)WKTravleNotesModel *notesModel;

/** 用户信息 */
@property (strong, nonatomic)WKTravelNoteUserModel *userModel;

@end


text:
module.exports = function(stream, log) {
    var previousData = "";
    stream.on("data", function(data) {
        previousData += data.toString();
        var lines = previousData.split("\n");
        previousData = lines.pop();
        lines.forEach(log);
    });
};


text:
package ru.stqa.rep.addressbook.tests;

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.stqa.rep.addressbook.model.GroupData;
import ru.stqa.rep.addressbook.model.Groups;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.testng.Assert.assertEquals;

public class GroupDeletionTests extends TestBase {

  @BeforeMethod
  public void ensurePrecondition() {

    if (app.db().groups().size() == 0) {
      app.goTo().groupPage();
      app.group().create(new GroupData().withName("Друзья").withHeader("Друзья").withFooter("Домашняя группа"));
    }
  }

  @Test
  public void testGroupDeletion() {
    Groups before = app.db().groups();
    GroupData deletedGroup = before.iterator().next();

    app.goTo().groupPage();
    app.group().delete(deletedGroup);

    Groups after = app.db().groups();
    assertEquals(after.size(), before.size() - 1);
    System.out.println("БЫЛО: "+ before.size()+ " СТАЛО: " +after.size());

    assertThat(after, equalTo(before.without(deletedGroup)));
    System.out.println("СТАРАЯ ПРОВЕРКА ДО: "+ after+ " СТАЛО: " +before.without(deletedGroup));

    verifyGroupListInUI(); //новая проверка

  }
}


text:
START_ATF_NAMESPACE
    CNationSettingFactoryRU::CNationSettingFactoryRU()
        : CNationSettingFactory(643)
    {
        using org_ptr = void (WINAPIV*)(struct CNationSettingFactoryRU*);
        (org_ptr(0x1402196a0L))(this);
    };
    void CNationSettingFactoryRU::ctor_CNationSettingFactoryRU()
    {
        using org_ptr = void (WINAPIV*)(struct CNationSettingFactoryRU*);
        (org_ptr(0x1402196a0L))(this);
    };
    struct CNationSettingData* CNationSettingFactoryRU::Create(int iNationCode, char* szNationCodeStr, bool bServiceMode)
    {
        using org_ptr = struct CNationSettingData* (WINAPIV*)(struct CNationSettingFactoryRU*, int, char*, bool);
        return (org_ptr(0x14022e390L))(this, iNationCode, szNationCodeStr, bServiceMode);
    };
END_ATF_NAMESPACE


text:
modified_count=`git status --porcelain | wc -l`
if [[ "${modified_count}" -ne "0" ]]; then
   echo "Your working directoy contains uncommitted changes."
   exit 1
fi

# Make sure no pull can be made before release
LOCAL_ORIGIN=$(git rev-parse @)
REMOTE_ORIGIN=$(git rev-parse @{u})
if [[ "${LOCAL_ORIGIN}" != "${REMOTE_ORIGIN}" ]]; then
   echo "Your local branch is not synchronized with its remote branch."
   exit 1
fi

# How to use the script
function usage {
   echo "Release using Apache Maven"
   echo ""
   echo "Usage:"
   echo "   release.sh REL_VERSION DEV_VERSION GPG_KEYNAME GPG_PASS [PROFILE_ID]"
   echo ""
   echo "      REL_VERSION    The version to use for the release"
   echo "      DEV_VERSION    The version to use for the development"
   echo "      GPG_KEYNAME    The GPG key name"
   echo "      GPG_PASS       The GPG passphrase"
   echo "      PROFILE_ID     The Sonatype Staging Profile ID"
   echo ""
}

if [[ $# -lt "5" ]]; then
   usage
   exit 1
fi

REL_VERSION="$1"
DEV_VERSION="$2"
GPG_KEYNAME="$3"
GPG_PASS="${4}"
PROFILE_ID="${5}"
REL_TAG="v${REL_VERSION}"

mvn clean
mvn -Prelease release:prepare -DreleaseVersion="${REL_VERSION}" -DdevelopmentVersion="${DEV_VERSION}" -Dtag=${REL_TAG} -Darguments="-Dgpg.passphrase=${GPG_PASS} -Dgpg.keyname=${GPG_KEYNAME}"
mvn -Prelease release:perform -DreleaseVersion="${REL_VERSION}" -DdevelopmentVersion="${DEV_VERSION}" -Dtag=${REL_TAG} -Darguments="-Dgpg.passphrase=${GPG_PASS} -Dgpg.keyname=${GPG_KEYNAME}"
mvn -Prelease deploy -Dgpg.passphrase=${GPG_PASS} -Dgpg.keyname=${GPG_KEYNAME}

echo "Released version:       ${REL_VERSION}"
echo "Release tag:            ${REL_TAG}"
echo "Development version:    ${DEV_VERSION}"


text:
'use strict';

import * as dom from 'vs/base/browser/dom';
import * as editorCommon from 'vs/editor/common/editorCommon';
import {IViewContext} from 'vs/editor/browser/editorBrowser';
import {ViewPart} from 'vs/editor/browser/view/viewPart';

export interface IVisibleLineData {
	getDomNode(): HTMLElement;
	setDomNode(domNode: HTMLElement): void;

	onContentChanged(): void;
	onLinesInsertedAbove(): void;
	onLinesDeletedAbove(): void;
	onLineChangedAbove(): void;
	onTokensChanged(): void;
	onConfigurationChanged(e:editorCommon.IConfigurationChangedEvent): void;

	getLineOuterHTML(out:string[], lineNumber: number, deltaTop: number): void;
	getLineInnerHTML(lineNumber: number): string;

	shouldUpdateHTML(lineNumber:number, inlineDecorations:editorCommon.IModelDecoration[]): boolean;
	layoutLine(lineNumber: number, deltaTop:number): void;
}

interface IRendererContext {
	domNode: HTMLElement;
	rendLineNumberStart: number;
	lines: IVisibleLineData[];
	linesLength: number;
	getInlineDecorationsForLineInViewport(lineNumber:number): editorCommon.IModelDecoration[];
	viewportTop: number;
	viewportHeight: number;
	scrollDomNode: HTMLElement;
	scrollDomNodeIsAbove: boolean;
}

export class ViewLayer extends ViewPart {

	public domNode: HTMLElement;

	_lines:IVisibleLineData[];
	_rendLineNumberStart:number;

	private _renderer: ViewLayerRenderer;

	constructor(context:IViewContext) {
		super(context);

		this.domNode = this._createDomNode();

		this._lines = [];
		this._rendLineNumberStart = 1;

		this._renderer = new ViewLayerRenderer(
			() => this._createLine(),
			() => this._extraDomNodeHTML()
		);
	}

	public dispose(): void {
		super.dispose();
		this._lines = null;
	}

	protected _extraDomNodeHTML(): string {
		return '';
	}

	// ---- begin view event handlers

	public onConfigurationChanged(e:editorCommon.IConfigurationChangedEvent): boolean {
		for (var i = 0; i < this._lines.length; i++) {
			this._lines[i].onConfigurationChanged(e);
		}
		return true;
	}

	public onLayoutChanged(layoutInfo:editorCommon.IEditorLayoutInfo): boolean {
		return true;
	}

	public onScrollChanged(e:editorCommon.IScrollEvent): boolean {
		return e.vertical;
	}

	public onZonesChanged(): boolean {
		return true;
	}

	public onModelFlushed(): boolean {
		this._lines = [];
		this._rendLineNumberStart = 1;
		dom.clearNode(this.domNode);
		return true;
	}

	public onModelLinesDeleted(e:editorCommon.IViewLinesDeletedEvent): boolean {
		var from = Math.max(e.fromLineNumber - this._rendLineNumberStart, 0);
		var to = Math.min(e.toLineNumber - this._rendLineNumberStart, this._lines.length - 1);
		var i:number;

		// Adjust this._rendLineNumberStart
		if (e.fromLineNumber < this._rendLineNumberStart) {
			// Deleting lines starting above the viewport

			if (e.toLineNumber < this._rendLineNumberStart) {
				// All deleted lines are above the viewport
				this._rendLineNumberStart -= (e.toLineNumber - e.fromLineNumber + 1);
			} else {
				// Some deleted lines are inside the viewport
				this._rendLineNumberStart = e.fromLineNumber;
			}
		}

		// Remove lines if they fall in the viewport
		if (from <= to) {
			// Remove from DOM
			for (i = from; i <= to; i++) {
				var lineDomNode = this._lines[i].getDomNode();
				if (lineDomNode) {
					this.domNode.removeChild(lineDomNode);
				}
			}
			// Remove from array
			this._lines.splice(from, to - from + 1);
		}

		// Mark the rest of the visible lines as possibly invalid
		for (i = from; i < this._lines.length; i++) {
			this._lines[i].onLinesDeletedAbove();
		}

		return true;
	}

	public onModelLineChanged(e:editorCommon.IViewLineChangedEvent): boolean {
		var lineIndex = e.lineNumber - this._rendLineNumberStart,
			shouldRender = false;

		if (lineIndex >= 0 && lineIndex < this._lines.length) {
			this._lines[lineIndex].onContentChanged();
			shouldRender = true;
		}

		// Mark the rest of the visible lines as possibly invalid
		for (var i = Math.max(lineIndex, 0); i < this._lines.length; i++) {
			this._lines[i].onLineChangedAbove();
			shouldRender = true;
		}

		return shouldRender;
	}

	public onModelLinesInserted(e:editorCommon.IViewLinesInsertedEvent): boolean {
		var i:number;

		if (e.fromLineNumber <= this._rendLineNumberStart) {
			// a. We are inserting lines above the viewport
			this._rendLineNumberStart += (e.toLineNumber - e.fromLineNumber + 1);

			// Mark the visible lines as possibly invalid
			for (i = 0; i < this._lines.length; i++) {
				this._lines[i].onLinesInsertedAbove();
			}

			return true;
		}

		if (e.fromLineNumber >= this._rendLineNumberStart + this._lines.length) {
			// b. We are inserting lines below the viewport
			return false;
		}

		// c. We are inserting lines in the viewport

		var insertFrom = Math.min(e.fromLineNumber - this._rendLineNumberStart, this._lines.length - 1);
		var insertTo = Math.min(e.toLineNumber - this._rendLineNumberStart, this._lines.length - 1);
		if (insertFrom <= insertTo) {
			// Insert lines that fall inside the viewport
			for (i = insertFrom; i <= insertTo; i++) {
				var line:IVisibleLineData = this._createLine();
				this._lines.splice(i, 0, line);
			}

			// We need to remove lines that are pushed outside the viewport by this insertion,
			// due to the Math.min above on `insertTo`. Otherwise, it is possible for the next line
			// after the insertion to be marked `maybeInvalid` when it should be definitely `invalid`.
			var insertCount = insertTo - insertFrom + 1;
			for (i = 0; i < insertCount; i++) {
				// Remove from array
				var lastLine = this._lines.pop();
				// Remove from DOM
				var lineDomNode = lastLine.getDomNode();
				if (lineDomNode) {
					this.domNode.removeChild(lineDomNode);
				}
			}
		}

		// Mark the rest of the lines as possibly invalid
		for (i = insertTo; i < this._lines.length; i++) {
			this._lines[i].onLinesInsertedAbove();
		}

		return true;
	}

	public onModelTokensChanged(e:editorCommon.IViewTokensChangedEvent): boolean {
		var changedFromIndex = e.fromLineNumber - this._rendLineNumberStart;
		var changedToIndex = e.toLineNumber - this._rendLineNumberStart;

		if (changedToIndex < 0 || changedFromIndex >= this._lines.length) {
			return false;
		}

		var fromIndex = Math.min(Math.max(changedFromIndex, 0), this._lines.length - 1);
		var toIndex = Math.min(Math.max(changedToIndex, 0), this._lines.length - 1);

		var somethingMayHaveChanged = false;

		for (var i = fromIndex; i <= toIndex; i++) {
			somethingMayHaveChanged = true;
			this._lines[i].onTokensChanged();
		}

		return somethingMayHaveChanged;
	}

	// ---- end view event handlers
	private _scrollDomNode: HTMLElement = null;
	private _scrollDomNodeIsAbove: boolean = false;
	public _renderLines(linesViewportData:editorCommon.IViewLinesViewportData): void {

		var ctx: IRendererContext = {
			domNode: this.domNode,
			rendLineNumberStart: this._rendLineNumberStart,
			lines: this._lines,
			linesLength: this._lines.length,
			getInlineDecorationsForLineInViewport: (lineNumber:number) => linesViewportData.getInlineDecorationsForLineInViewport(lineNumber),
			viewportTop: linesViewportData.viewportTop,
			viewportHeight: linesViewportData.viewportHeight,
			scrollDomNode: this._scrollDomNode,
			scrollDomNodeIsAbove: this._scrollDomNodeIsAbove
		};

		// Decide if this render will do a single update (single large .innerHTML) or many updates (inserting/removing dom nodes)
		var resCtx = this._renderer.renderWithManyUpdates(ctx, linesViewportData.startLineNumber, linesViewportData.endLineNumber, linesViewportData.relativeVerticalOffset);

		this._rendLineNumberStart = resCtx.rendLineNumberStart;
		this._lines = resCtx.lines;
		this._scrollDomNode = resCtx.scrollDomNode;
		this._scrollDomNodeIsAbove = resCtx.scrollDomNodeIsAbove;
	}

	public _createDomNode(): HTMLElement {
		var domNode = document.createElement('div');
		domNode.className = 'view-layer';
		domNode.style.position = 'absolute';
		domNode.setAttribute('role', 'presentation');
		domNode.setAttribute('aria-hidden', 'true');
		return domNode;
	}

	public _createLine(): IVisibleLineData {
		throw new Error('Implement me!');
	}
}

class ViewLayerRenderer {

	private _createLine: () => IVisibleLineData;
	private _extraDomNodeHTML: () => string;

	constructor(createLine: () => IVisibleLineData, extraDomNodeHTML: () => string) {
		this._createLine = createLine;
		this._extraDomNodeHTML = extraDomNodeHTML;
	}

	public renderWithManyUpdates(ctx: IRendererContext, startLineNumber: number, stopLineNumber: number, deltaTop:number[]): IRendererContext {
		return this._render(ctx, startLineNumber, stopLineNumber, deltaTop);
	}

	private _render(inContext: IRendererContext, startLineNumber: number, stopLineNumber: number, deltaTop:number[]): IRendererContext {

		var ctx: IRendererContext = {
			domNode: inContext.domNode,
			rendLineNumberStart: inContext.rendLineNumberStart,
			lines: inContext.lines.slice(0),
			linesLength: inContext.linesLength,
			getInlineDecorationsForLineInViewport: inContext.getInlineDecorationsForLineInViewport,
			viewportTop: inContext.viewportTop,
			viewportHeight: inContext.viewportHeight,
			scrollDomNode: inContext.scrollDomNode,
			scrollDomNodeIsAbove: inContext.scrollDomNodeIsAbove
		};

		var canRemoveScrollDomNode = true;
		if (ctx.scrollDomNode) {
			var time = this._getScrollDomNodeTime(ctx.scrollDomNode);
			if ((new Date()).getTime() - time < 1000) {
				canRemoveScrollDomNode = false;
			}
		}

		if (canRemoveScrollDomNode && ((ctx.rendLineNumberStart + ctx.linesLength - 1 < startLineNumber) || (stopLineNumber < ctx.rendLineNumberStart))) {
			// There is no overlap whatsoever
			ctx.rendLineNumberStart = startLineNumber;
			ctx.linesLength = stopLineNumber - startLineNumber + 1;
			ctx.lines = [];
			for (var x = startLineNumber; x <= stopLineNumber; x++) {
				ctx.lines[x - startLineNumber] = this._createLine();
			}
			this._finishRendering(ctx, true, deltaTop);
			ctx.scrollDomNode = null;
			return ctx;
		}

		// Update lines which will remain untouched
		this._renderUntouchedLines(
			ctx,
			Math.max(startLineNumber - ctx.rendLineNumberStart, 0),
			Math.min(stopLineNumber - ctx.rendLineNumberStart, ctx.linesLength - 1),
			deltaTop,
			startLineNumber
		);

		var fromLineNumber: number,
			toLineNumber: number,
			removeCnt: number;

		if (ctx.rendLineNumberStart > startLineNumber) {
			// Insert lines before
			fromLineNumber = startLineNumber;
			toLineNumber = Math.min(stopLineNumber, ctx.rendLineNumberStart - 1);
			if (fromLineNumber <= toLineNumber) {
				this._insertLinesBefore(ctx, fromLineNumber, toLineNumber, deltaTop, startLineNumber);
				ctx.linesLength += toLineNumber - fromLineNumber + 1;

				// Clean garbage above
				if (ctx.scrollDomNode && ctx.scrollDomNodeIsAbove) {
					if (ctx.scrollDomNode.parentNode) {
						ctx.scrollDomNode.parentNode.removeChild(ctx.scrollDomNode);
					}
					ctx.scrollDomNode = null;
				}
			}
		} else if (ctx.rendLineNumberStart < startLineNumber) {
			// Remove lines before
			removeCnt = Math.min(ctx.linesLength, startLineNumber - ctx.rendLineNumberStart);
			if (removeCnt > 0) {
				this._removeLinesBefore(ctx, removeCnt);
				ctx.linesLength -= removeCnt;
			}
		}

		ctx.rendLineNumberStart = startLineNumber;

		if (ctx.rendLineNumberStart + ctx.linesLength - 1 < stopLineNumber) {
			// Insert lines after
			fromLineNumber = ctx.rendLineNumberStart + ctx.linesLength;
			toLineNumber = stopLineNumber;

			if (fromLineNumber <= toLineNumber) {
				this._insertLinesAfter(ctx, fromLineNumber, toLineNumber, deltaTop, startLineNumber);
				ctx.linesLength += toLineNumber - fromLineNumber + 1;

				// Clean garbage below
				if (ctx.scrollDomNode && !ctx.scrollDomNodeIsAbove) {
					if (ctx.scrollDomNode.parentNode) {
						ctx.scrollDomNode.parentNode.removeChild(ctx.scrollDomNode);
					}
					ctx.scrollDomNode = null;
				}
			}

		} else if (ctx.rendLineNumberStart + ctx.linesLength - 1 > stopLineNumber) {
			// Remove lines after
			fromLineNumber = Math.max(0, stopLineNumber - ctx.rendLineNumberStart + 1);
			toLineNumber = ctx.linesLength - 1;
			removeCnt = toLineNumber - fromLineNumber + 1;

			if (removeCnt > 0) {
				this._removeLinesAfter(ctx, removeCnt);
				ctx.linesLength -= removeCnt;
			}
		}

		this._finishRendering(ctx, false, deltaTop);

		return ctx;
	}

	private _renderUntouchedLines(ctx: IRendererContext, startIndex: number, endIndex: number, deltaTop:number[], deltaLN:number): void {
		var i: number,
			lineNumber: number;

		for (i = startIndex; i <= endIndex; i++) {
			lineNumber = ctx.rendLineNumberStart + i;
			var lineDomNode = ctx.lines[i].getDomNode();
			if (lineDomNode) {
				ctx.lines[i].layoutLine(lineNumber, deltaTop[lineNumber - deltaLN]);
			}
		}
	}

	private _insertLinesBefore(ctx: IRendererContext, fromLineNumber: number, toLineNumber: number, deltaTop:number[], deltaLN:number): void {
		var newLines:IVisibleLineData[] = [],
			line:IVisibleLineData,
			lineNumber: number;

		for (lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {
			line = this._createLine();
			newLines.push(line);
		}
		ctx.lines = newLines.concat(ctx.lines);
	}

	private _getScrollDomNodeTime(domNode: HTMLElement): number {
		var lastScrollTime = domNode.getAttribute('last-scroll-time');
		if (lastScrollTime) {
			return parseInt(lastScrollTime, 10);
		}
		return 0;
	}

	private _removeIfNotScrollDomNode(ctx: IRendererContext, domNode: HTMLElement, isAbove: boolean) {
		var time = this._getScrollDomNodeTime(domNode);
		if (!time) {
			ctx.domNode.removeChild(domNode);
			return;
		}

		if (ctx.scrollDomNode) {
			var otherTime = this._getScrollDomNodeTime(ctx.scrollDomNode);
			if (otherTime > time) {
				// The other is the real scroll dom node
				ctx.domNode.removeChild(domNode);
				return;
			}

			if (ctx.scrollDomNode.parentNode) {
				ctx.scrollDomNode.parentNode.removeChild(ctx.scrollDomNode);
			}

			ctx.scrollDomNode = null;
		}

		ctx.scrollDomNode = domNode;
		ctx.scrollDomNodeIsAbove = isAbove;
	}

	private _removeLinesBefore(ctx: IRendererContext, removeCount: number): void {
		var i: number;

		for (i = 0; i < removeCount; i++) {
			var lineDomNode = ctx.lines[i].getDomNode();
			if (lineDomNode) {
				this._removeIfNotScrollDomNode(ctx, lineDomNode, true);
			}
		}
		ctx.lines.splice(0, removeCount);
	}

	private _insertLinesAfter(ctx: IRendererContext, fromLineNumber: number, toLineNumber: number, deltaTop:number[], deltaLN:number): void {
		var newLines:IVisibleLineData[] = [],
			line:IVisibleLineData,
			lineNumber: number;

		for (lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {
			line = this._createLine();
			newLines.push(line);
		}
		ctx.lines = ctx.lines.concat(newLines);
	}

	private _removeLinesAfter(ctx: IRendererContext, removeCount: number): void {
		var i: number,
			removeIndex = ctx.linesLength - removeCount;

		for (i = 0; i < removeCount; i++) {
			var lineDomNode = ctx.lines[removeIndex + i].getDomNode();
			if (lineDomNode) {
				this._removeIfNotScrollDomNode(ctx, lineDomNode, false);
			}
		}
		ctx.lines.splice(removeIndex, removeCount);
	}

	private _finishRendering(ctx: IRendererContext, domNodeIsEmpty:boolean, deltaTop:number[]): void {

		var i: number,
			len: number,
			line: IVisibleLineData,
			lineNumber: number,
			hadNewLine = false,
			wasNew: boolean[] = [],
			newLinesHTML: string[] = [],
			hadInvalidLine = false,
			wasInvalid: boolean[] = [],
			invalidLinesHTML: string[] = [];

		for (i = 0, len = ctx.linesLength; i < len; i++) {
			line = ctx.lines[i];
			lineNumber = i + ctx.rendLineNumberStart;

			if (line.shouldUpdateHTML(lineNumber, ctx.getInlineDecorationsForLineInViewport(lineNumber))) {
				var lineDomNode = line.getDomNode();
				if (!lineDomNode) {
					// Line is new
					line.getLineOuterHTML(newLinesHTML, lineNumber, deltaTop[i]);
					wasNew[i] = true;
					hadNewLine = true;
				} else {
					// Line is invalid
					line.getLineOuterHTML(invalidLinesHTML, lineNumber, deltaTop[i]);
					wasInvalid[i] = true;
					hadInvalidLine = true;
//					lineDomNode.innerHTML = line.getLineInnerHTML(lineNumber);
				}
			}
		}

		if (hadNewLine) {
			var lastChild = <HTMLElement>ctx.domNode.lastChild;
			if (domNodeIsEmpty || !lastChild) {
				ctx.domNode.innerHTML = this._extraDomNodeHTML() + newLinesHTML.join('');
			} else {
				lastChild.insertAdjacentHTML('afterend', newLinesHTML.join(''));
			}

			var currChild = <HTMLElement>ctx.domNode.lastChild;
			for (i = ctx.linesLength - 1; i >= 0; i--) {
				line = ctx.lines[i];
				if (wasNew[i]) {
					line.setDomNode(currChild);
					currChild = <HTMLElement>currChild.previousSibling;
				}
			}
		}

		if (hadInvalidLine) {

			var hugeDomNode = document.createElement('div');

			hugeDomNode.innerHTML = invalidLinesHTML.join('');

			var lineDomNode:HTMLElement,
				source:HTMLElement;
			for (i = 0; i < ctx.linesLength; i++) {
				line = ctx.lines[i];
				if (wasInvalid[i]) {
					source = <HTMLElement>hugeDomNode.firstChild;
					lineDomNode = line.getDomNode();
					lineDomNode.parentNode.replaceChild(source, lineDomNode);
					line.setDomNode(source);
				}
			}
		}
	}
}


text:
"""
    proxy.py
    ~~~~~~~~
    ⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on
    Network monitoring, controls & Application development, testing, debugging.

    :copyright: (c) 2013-present by Abhinav Singh and contributors.
    :license: BSD, see LICENSE for more details.
"""
import selectors

import pytest
import unittest
from unittest import mock

from pytest_mock import MockerFixture

from proxy.core.connection import UpstreamConnectionPool

class TestConnectionPool(unittest.TestCase):

    @mock.patch('proxy.core.connection.pool.TcpServerConnection')
    def test_acquire_and_retain_and_reacquire(self, mock_tcp_server_connection: mock.Mock) -> None:
        pool = UpstreamConnectionPool()
        # Mock
        mock_conn = mock_tcp_server_connection.return_value
        addr = mock_conn.addr
        mock_conn.is_reusable.side_effect = [
            True,
        ]
        mock_conn.closed = False
        # Acquire
        created, conn = pool.acquire(addr)
        mock_tcp_server_connection.assert_called_once_with(addr[0], addr[1])
        mock_conn.mark_inuse.assert_called_once()
        mock_conn.reset.assert_not_called()
        self.assertTrue(created)
        self.assertEqual(conn, mock_conn)
        self.assertEqual(len(pool.pools[addr]), 1)
        self.assertTrue(conn in pool.pools[addr])
        self.assertEqual(len(pool.connections), 1)
        self.assertEqual(pool.connections[conn.connection.fileno()], mock_conn)
        # Retail
        pool.retain(conn)
        self.assertEqual(len(pool.pools[addr]), 1)
        self.assertTrue(conn in pool.pools[addr])
        mock_conn.reset.assert_called_once()
        # Reacquire
        created, conn = pool.acquire(addr)
        self.assertFalse(created)
        self.assertEqual(conn, mock_conn)
        self.assertEqual(len(pool.pools[addr]), 1)
        self.assertTrue(conn in pool.pools[addr])

    @mock.patch('proxy.core.connection.pool.TcpServerConnection')
    def test_closed_connections_are_removed_on_release(
            self, mock_tcp_server_connection: mock.Mock,
    ) -> None:
        pool = UpstreamConnectionPool()
        # Mock
        mock_conn = mock_tcp_server_connection.return_value
        mock_conn.closed = True
        addr = mock_conn.addr
        # Acquire
        created, conn = pool.acquire(addr)
        self.assertTrue(created)
        mock_tcp_server_connection.assert_called_once_with(addr[0], addr[1])
        self.assertEqual(conn, mock_conn)
        self.assertEqual(len(pool.pools[addr]), 1)
        self.assertTrue(conn in pool.pools[addr])
        # Release
        mock_conn.is_reusable.return_value = False
        pool.release(conn)
        self.assertEqual(len(pool.pools[addr]), 0)
        # Acquire
        created, conn = pool.acquire(addr)
        self.assertTrue(created)
        self.assertEqual(mock_tcp_server_connection.call_count, 2)

class TestConnectionPoolAsync:

    @pytest.mark.asyncio    # type: ignore[misc]
    async def test_get_events(self, mocker: MockerFixture) -> None:
        mock_tcp_server_connection = mocker.patch(
            'proxy.core.connection.pool.TcpServerConnection',
        )
        pool = UpstreamConnectionPool()
        mock_conn = mock_tcp_server_connection.return_value
        addr = mock_conn.addr
        pool.add(addr)
        mock_tcp_server_connection.assert_called_once_with(addr[0], addr[1])
        mock_conn.connect.assert_called_once()
        events = await pool.get_events()
        print(events)
        assert events == {
            mock_conn.connection.fileno.return_value: selectors.EVENT_READ,
        }
        assert pool.pools[addr].pop() == mock_conn
        assert len(pool.pools[addr]) == 0
        assert pool.connections[mock_conn.connection.fileno.return_value] == mock_conn

    @pytest.mark.asyncio    # type: ignore[misc]
    async def test_handle_events(self, mocker: MockerFixture) -> None:
        mock_tcp_server_connection = mocker.patch(
            'proxy.core.connection.pool.TcpServerConnection',
        )
        pool = UpstreamConnectionPool()
        mock_conn = mock_tcp_server_connection.return_value
        addr = mock_conn.addr
        pool.add(addr)
        assert len(pool.pools[addr]) == 1
        assert len(pool.connections) == 1
        await pool.handle_events([mock_conn.connection.fileno.return_value], [])
        assert len(pool.pools[addr]) == 0
        assert len(pool.connections) == 0


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Desktop.Framework.Controls;
using ArcGIS.Desktop.Mapping;
using System.Xml.Linq;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Core.Data;

namespace SeqNum
{
  internal class SeqNumControlViewModel : EmbeddableControl
  {
    public SeqNumControlViewModel(XElement options, bool canChangeOptions) : base(options, canChangeOptions)
    {
    }

    public List<String> layerList
    {
      get { return Module1._layerList; }
      set { SetProperty(ref Module1._layerList, value); }
    }

    public List<String> fieldList
    {
      get { return Module1._fieldList; }
      set { SetProperty(ref Module1._fieldList, value); }
    }

    public String targetLayer
    {
      get { return Module1._targetLayer; }
      set
      {
        if (value == Module1._targetLayer) return;

        SetProperty(ref Module1._targetLayer, value);

        //if targetlayer is null for some reason then also null field dropdown
        if (value == null)
        {
          fieldList = null;
          return;
        }

        //get field list for the selected target layer
        QueuedTask.Run(() =>
        {
          var featLayer = MapView.Active.Map.FindLayers(Module1._targetLayer).First() as BasicFeatureLayer;
          var flf = featLayer.GetTable().GetDefinition().GetFields();

          fieldList = flf.Where(f => f.FieldType == FieldType.Integer | f.FieldType == FieldType.SmallInteger |
            f.FieldType == FieldType.String).Select(f => f.Name).ToList();
        });
      }
    }

    public String targetField
    {
      get { return Module1._targetField; }
      set
      {
        if (value == null) return;
        SetProperty(ref Module1._targetField, value);
        //is the targetfield a string (cache this value?)
        QueuedTask.Run(() =>
        {
          var featLayer = MapView.Active.Map.FindLayers(Module1._targetLayer).First() as BasicFeatureLayer;
          var flf = featLayer.GetTable().GetDefinition().GetFields();
          SetProperty(ref Module1._isTargetFieldString, flf.First(f => f.Name == value).FieldType == FieldType.String);
          NotifyPropertyChanged("isStringFormatEnabled");
        });
      }
    }

    public string stringFormat
    {
      get { return Module1._stringFormat; }
      set { SetProperty(ref Module1._stringFormat, value); }
    }

    public string formatToolTip =>
      "The format represents how the sequential number is written to the textfield" + "\n" +
      "Use a # to denote the incrementing sequential number" + "\n" +
      "Multiple # will add leading 0's" + "\n" +
      //"e.g." + "\n" +
      "Format      Text" + "\n" +
      "ABC-#       ABC-1" + "\n" +
      "ABC-###  ABC-001";

    public bool isStringFormatEnabled
    {
      get { return Module1._isTargetFieldString; }
    }

    public String startValue
    {
      get {return Module1._startValue;}
      set { SetProperty(ref Module1._startValue, value); }
    }

    public  String incValue
    {
      get { return Module1._incValue; }
      set { SetProperty(ref Module1._incValue, value); }
    }
  }
}


text:
#include "setup.h"

#include <stdio.h>
#include <string.h>

#include <curl/curl.h>
#include "urldata.h"
#include "sendf.h"
#include "multiif.h"
#include "speedcheck.h"

void Curl_speedinit(struct SessionHandle *data)
{
  memset(&data->state.keeps_speed, 0, sizeof(struct timeval));
}

CURLcode Curl_speedcheck(struct SessionHandle *data,
                         struct timeval now)
{
  if((data->progress.current_speed >= 0) &&
     data->set.low_speed_time &&
     (Curl_tvlong(data->state.keeps_speed) != 0) &&
     (data->progress.current_speed < data->set.low_speed_limit)) {
    long howlong = Curl_tvdiff(now, data->state.keeps_speed);

    /* We are now below the "low speed limit". If we are below it
       for "low speed time" seconds we consider that enough reason
       to abort the download. */

    if( (howlong/1000) > data->set.low_speed_time) {
      /* we have been this slow for long enough, now die */
      failf(data,
            "Operation too slow. "
            "Less than %d bytes/sec transfered the last %d seconds",
            data->set.low_speed_limit,
            data->set.low_speed_time);
      return CURLE_OPERATION_TIMEOUTED;
    }
    Curl_expire(data, howlong);
  }
  else {
    /* we keep up the required speed all right */
    data->state.keeps_speed = now;

    if(data->set.low_speed_limit)
      /* if there is a low speed limit enabled, we set the expire timer to
         make this connection's speed get checked again no later than when
         this time is up */
      Curl_expire(data, data->set.low_speed_time*1000);
  }
  return CURLE_OK;
}


text:
About the Founder

Mike Pan is an established member of the Blender community with 12 years of 3D graphics experience and a keen interest in visualization and educational media.

 In the past, he has worked at University of British Columbia in Canada, Institute of Clinical Physiology in Italy, and Harvard Medical School.

                {% for member in site.people %}

{{ member.name }}

{{ member.position }}

                            {% for network in member.social %}

                            {% endfor %}

                {% endfor %}

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aut eaque, laboriosam veritatis, quos non quis ad perspiciatis, totam corporis ea, alias ut unde.


text:
Copyright © 2017 | Glenn Dayton

{% include google-analytics.html %}


text:
import {combineReducers} from 'redux';
import {routerReducer as routing} from 'react-router-redux';
import {reducer as formReducer} from 'redux-form';

import store from './store';

// Combine reducers with routeReducer which keeps track of
// router state
const rootReducer = combineReducers({
  form: formReducer,
  routing,
  store
});

export default rootReducer;


text:
<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;

class SiteController extends Controller
{
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

}