text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.redhat.samples.rest</groupId>
        <artifactId>samples-rest</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>samples-rest-basic</artifactId>
    <packaging>war</packaging>

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.redhat.samples.rest.client.GreetingClient</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
STATISTIC(numAssignRewritten, "Number of assigns rewritten");

using namespace swift;

/// Emit the sequence that an assign instruction lowers to once we know
/// if it is an initialization or an assignment.  If it is an assignment,
/// a live-in value can be provided to optimize out the reload.
static void lowerAssignInstruction(SILBuilderWithScope &b, AssignInst *inst) {
  LLVM_DEBUG(llvm::dbgs() << "  *** Lowering [isInit="
                          << unsigned(inst->getOwnershipQualifier())
                          << "]: " << *inst << "\n");

  ++numAssignRewritten;

  SILValue src = inst->getSrc();
  SILValue dest = inst->getDest();
  SILLocation loc = inst->getLoc();
  AssignOwnershipQualifier qualifier = inst->getOwnershipQualifier();

  // Unknown qualifier is considered unprocessed. Just lower it as [reassign],
  // but if the destination type is trivial, treat it as [init].
  //
  // Unknown should not be lowered because definite initialization should
  // always set an initialization kind for assign instructions, but there exists
  // some situations where SILGen doesn't generate a mark_uninitialized
  // instruction for a full mark_uninitialized. Thus definite initialization
  // doesn't set an initialization kind for some assign instructions.
  //
  // TODO: Fix SILGen so that this is an assert preventing the lowering of
  //       Unknown init kind.
  if (qualifier == AssignOwnershipQualifier::Unknown)
    qualifier = AssignOwnershipQualifier::Reassign;

  if (qualifier == AssignOwnershipQualifier::Init ||
      inst->getDest()->getType().isTrivial(*inst->getFunction())) {

    // If this is an initialization, or the storage type is trivial, we
    // can just replace the assignment with a store.
    assert(qualifier != AssignOwnershipQualifier::Reinit);
    b.createTrivialStoreOr(loc, src, dest, StoreOwnershipQualifier::Init);
    inst->eraseFromParent();
    return;
  }

  if (qualifier == AssignOwnershipQualifier::Reinit) {
    // We have a case where a convenience initializer on a class
    // delegates to a factory initializer from a protocol extension.
    // Factory initializers give us a whole new instance, so the existing
    // instance, which has not been initialized and never will be, must be
    // freed using dealloc_partial_ref.
    SILValue pointer = b.createLoad(loc, dest, LoadOwnershipQualifier::Take);
    b.createStore(loc, src, dest, StoreOwnershipQualifier::Init);

    auto metatypeTy = CanMetatypeType::get(
        dest->getType().getASTType(), MetatypeRepresentation::Thick);
    auto silMetatypeTy = SILType::getPrimitiveObjectType(metatypeTy);
    SILValue metatype = b.createValueMetatype(loc, silMetatypeTy, pointer);

    b.createDeallocPartialRef(loc, pointer, metatype);
    inst->eraseFromParent();
    return;
  }

  assert(qualifier == AssignOwnershipQualifier::Reassign);
  // Otherwise, we need to replace the assignment with a store [assign] which
  // lowers to the load/store/release dance. Note that the new value is already
  // considered to be retained (by the semantics of the storage type),
  // and we're transferring that ownership count into the destination.

  b.createStore(loc, src, dest, StoreOwnershipQualifier::Assign);
  inst->eraseFromParent();
}

/// Construct the argument list for the assign_by_wrapper initializer or setter.
///
/// Usually this is only a single value and a single argument, but in case of
/// a tuple, the initializer/setter expect the tuple elements as separate
/// arguments. The purpose of this function is to recursively visit tuple
/// elements and add them to the argument list \p arg.
static void getAssignByWrapperArgsRecursively(SmallVectorImpl<SILValue> &args,
    SILValue src, unsigned &argIdx, const SILFunctionConventions &convention,
    SILBuilder &forProjections, SILBuilder &forCleanup) {

  SILLocation loc = (*forProjections.getInsertionPoint()).getLoc();
  SILType srcTy = src->getType();
  if (auto tupleTy = srcTy.getAs<TupleType>()) {
    // In case the source is a tuple, we have to destructure the tuple and pass
    // the tuple elements separately.
    if (srcTy.isAddress()) {
      for (unsigned idx = 0, n = tupleTy->getNumElements(); idx < n; ++idx) {
        auto *TEA = forProjections.createTupleElementAddr(loc, src, idx);
        getAssignByWrapperArgsRecursively(args, TEA, argIdx, convention,
          forProjections, forCleanup);
      }
    } else {
      auto *DTI = forProjections.createDestructureTuple(loc, src);
      for (SILValue elmt : DTI->getAllResults()) {
        getAssignByWrapperArgsRecursively(args, elmt, argIdx, convention,
          forProjections, forCleanup);
      }
    }
    return;
  }
  assert(argIdx < convention.getNumSILArguments() &&
         "initializer or setter has too few arguments");

  SILArgumentConvention argConv = convention.getSILArgumentConvention(argIdx);
  if (srcTy.isAddress() && !argConv.isIndirectConvention()) {
    // In case of a tuple where one element is loadable, but the other is
    // address only, we get the whole tuple as address.
    // For the loadable element, the argument is passed directly, but the
    // tuple element is in memory. For this case we have to insert a load.
    src = forProjections.createTrivialLoadOr(loc, src,
                                             LoadOwnershipQualifier::Take);
  }
  switch (argConv) {
    case SILArgumentConvention::Indirect_In_Guaranteed:
      forCleanup.createDestroyAddr(loc, src);
      break;
    case SILArgumentConvention::Direct_Guaranteed:
      forCleanup.createDestroyValue(loc, src);
      break;
    case SILArgumentConvention::Direct_Unowned:
    case SILArgumentConvention::Indirect_In:
    case SILArgumentConvention::Indirect_In_Constant:
    case SILArgumentConvention::Direct_Owned:
      break;
    case SILArgumentConvention::Indirect_Inout:
    case SILArgumentConvention::Indirect_InoutAliasable:
    case SILArgumentConvention::Indirect_Out:
      llvm_unreachable("wrong convention for setter/initializer src argument");
  }
  args.push_back(src);
  ++argIdx;
}

static void getAssignByWrapperArgs(SmallVectorImpl<SILValue> &args,
            SILValue src, const SILFunctionConventions &convention,
            SILBuilder &forProjections, SILBuilder &forCleanup) {
  unsigned argIdx = convention.getSILArgIndexOfFirstParam();
  getAssignByWrapperArgsRecursively(args, src, argIdx, convention,
                              forProjections, forCleanup);
  assert(argIdx == convention.getNumSILArguments() &&
         "initializer or setter has too many arguments");
}

static void
lowerAssignByWrapperInstruction(SILBuilderWithScope &b,
                                AssignByWrapperInst *inst,
                                SmallSetVector<SILValue, 8> &toDelete) {
  LLVM_DEBUG(llvm::dbgs() << "  *** Lowering " << *inst << "\n");

  ++numAssignRewritten;

  SILValue src = inst->getSrc();
  SILValue dest = inst->getDest();
  SILLocation loc = inst->getLoc();
  SILBuilderWithScope forCleanup(std::next(inst->getIterator()));

  switch (inst->getMode()) {
    case AssignByWrapperInst::Unknown:
      assert(b.getModule().getASTContext().hadError() &&
             "assign_by_wrapper must have a valid mode");
      // In case DefiniteInitialization already gave up with an error, just
      // treat the assign_by_wrapper as an "init".
      LLVM_FALLTHROUGH;
    case AssignByWrapperInst::Initialization:
    case AssignByWrapperInst::Assign: {
      switch (inst->getOriginator()) {
      case AssignByWrapperInst::Originator::TypeWrapper: {
        bool initialization =
            inst->getMode() == AssignByWrapperInst::Initialization;

        if (inst->getDest()->getType().isAddressOnly(*inst->getFunction())) {
          b.createCopyAddr(loc, src, dest, IsTake,
                           initialization ? IsInitialization
                                          : IsNotInitialization);
        } else {
          b.createTrivialStoreOr(loc, src, dest,
                                 initialization
                                     ? StoreOwnershipQualifier::Init
                                     : StoreOwnershipQualifier::Assign);
        }
        break;
      }

      case AssignByWrapperInst::Originator::PropertyWrapper: {
        SILValue initFn = inst->getInitializer();
        CanSILFunctionType fTy = initFn->getType().castTo<SILFunctionType>();
        SILFunctionConventions convention(fTy, inst->getModule());
        SmallVector<SILValue, 4> args;
        if (convention.hasIndirectSILResults()) {
          if (inst->getMode() == AssignByWrapperInst::Assign)
            b.createDestroyAddr(loc, dest);

          args.push_back(dest);
          getAssignByWrapperArgs(args, src, convention, b, forCleanup);
          b.createApply(loc, initFn, SubstitutionMap(), args);
        } else {
          getAssignByWrapperArgs(args, src, convention, b, forCleanup);
          SILValue wrappedSrc =
              b.createApply(loc, initFn, SubstitutionMap(), args);
          if (inst->getMode() == AssignByWrapperInst::Initialization ||
              inst->getDest()->getType().isTrivial(*inst->getFunction())) {
            b.createTrivialStoreOr(loc, wrappedSrc, dest,
                                   StoreOwnershipQualifier::Init);
          } else {
            b.createStore(loc, wrappedSrc, dest,
                          StoreOwnershipQualifier::Assign);
          }
        }
        break;
      }
      }

      // The unused partial_apply violates memory lifetime rules in case "self"
      // is an inout. Therefore we cannot keep it as a dead closure to be
      // cleaned up later. We have to delete it in this pass.
      toDelete.insert(inst->getSetter());

      // Also the argument of the closure (which usually is a "load") has to be
      // deleted to avoid memory lifetime violations.
      auto *setterPA = dyn_cast<PartialApplyInst>(inst->getSetter());
      if (setterPA && setterPA->getNumArguments() == 1)
        toDelete.insert(setterPA->getArgument(0));
      break;
    }
    case AssignByWrapperInst::AssignWrappedValue: {
      SILValue setterFn = inst->getSetter();
      CanSILFunctionType fTy = setterFn->getType().castTo<SILFunctionType>();
      SILFunctionConventions convention(fTy, inst->getModule());
      assert(!convention.hasIndirectSILResults());
      SmallVector<SILValue, 4> args;
      getAssignByWrapperArgs(args, src, convention, b, forCleanup);
      b.createApply(loc, setterFn, SubstitutionMap(), args);

      // The destination address is not used. Remove it if it is a dead access
      // marker. This is important, because also the setter function contains
      // access marker. In case those markers are dynamic it would cause a
      // nested access violation.
      if (isa<BeginAccessInst>(dest))
        toDelete.insert(dest);

      // Again, we have to delete the unused dead closure.
      toDelete.insert(inst->getInitializer());
      break;
    }
  }
  inst->eraseFromParent();
}

static void deleteDeadAccessMarker(BeginAccessInst *BA) {
  SmallVector<SILInstruction *, 4> Users;
  for (Operand *Op : BA->getUses()) {
    SILInstruction *User = Op->getUser();
    if (!isa<EndAccessInst>(User))
      return;

    Users.push_back(User);
  }
  for (SILInstruction *User: Users) {
    User->eraseFromParent();
  }
  BA->eraseFromParent();
}

/// Delete a dead load for a dead setter-closure.
static void deleteDeadClosureArg(LoadInst *load) {
  if (load->getOwnershipQualifier() != LoadOwnershipQualifier::Trivial &&
      load->getOwnershipQualifier() != LoadOwnershipQualifier::Copy)
    return;

  for (Operand *use : load->getUses()) {
    if (!isa<DestroyValueInst>(use->getUser()))
      return;
  }
  while (!load->use_empty()) {
    load->use_begin()->getUser()->eraseFromParent();
  }
  load->eraseFromParent();
}

/// lowerRawSILOperations - There are a variety of raw-sil instructions like
/// 'assign' that are only used by this pass.  Now that definite initialization
/// checking is done, remove them.
static bool lowerRawSILOperations(SILFunction &fn) {
  bool changed = false;

  for (auto &bb : fn) {
    SmallSetVector<SILValue, 8> toDelete;

    auto i = bb.begin(), e = bb.end();
    while (i != e) {
      SILInstruction *inst = &*i;
      ++i;

      // Lower 'assign' depending on initialization kind defined by definite
      // initialization.
      //
      // * Unknown is considered unprocessed and is treated as [reassign] or
      //   [init] if the destination type is trivial.
      // * Init becomes a store [init] or a store [trivial] if the destination's
      //   type is trivial.
      // * Reinit becomes a load [take], store [init], and a
      //   dealloc_partial_ref.
      // * Reassign becomes a store [assign].
      if (auto *ai = dyn_cast<AssignInst>(inst)) {
        SILBuilderWithScope b(ai);
        lowerAssignInstruction(b, ai);
        // Assign lowering may split the block. If it did,
        // reset our iteration range to the block after the insertion.
        if (b.getInsertionBB() != &bb)
          i = e;
        changed = true;
        continue;
      }

      if (auto *ai = dyn_cast<AssignByWrapperInst>(inst)) {
        SILBuilderWithScope b(ai);
        lowerAssignByWrapperInstruction(b, ai, toDelete);
        changed = true;
        continue;
      }

      // mark_uninitialized just becomes a noop, resolving to its operand.
      if (auto *mui = dyn_cast<MarkUninitializedInst>(inst)) {
        mui->replaceAllUsesWith(mui->getOperand());
        mui->eraseFromParent();
        changed = true;
        continue;
      }

      // mark_function_escape just gets zapped.
      if (isa<MarkFunctionEscapeInst>(inst)) {
        inst->eraseFromParent();
        changed = true;
        continue;
      }
    }
    for (SILValue deadVal : toDelete) {
      if (auto *beginAccess = dyn_cast<BeginAccessInst>(deadVal)) {
        deleteDeadAccessMarker(beginAccess);
      } else if (auto *load = dyn_cast<LoadInst>(deadVal)) {
        deleteDeadClosureArg(load);
      } else if (auto *svi = dyn_cast<SingleValueInstruction>(deadVal)) {
        tryDeleteDeadClosure(svi);
      }
    }
  }
  return changed;
}

//===----------------------------------------------------------------------===//
//                            Top Level Entrypoint
//===----------------------------------------------------------------------===//

namespace {

class RawSILInstLowering : public SILFunctionTransform {
  void run() override {
    // Do not try to relower raw instructions in canonical SIL. There won't be
    // any there.
    if (getFunction()->wasDeserializedCanonical()) {
      return;
    }

    // Lower raw-sil only instructions used by this pass, like "assign".
    if (lowerRawSILOperations(*getFunction()))
      invalidateAnalysis(SILAnalysis::InvalidationKind::FunctionBody);
  }
};

} // end anonymous namespace

SILTransform *swift::createRawSILInstLowering() {
  return new RawSILInstLowering();
}

redpajama_set_name: RedPajamaGithub


text:
import sys
import os.path

path_to_script = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(path_to_script, "../src/"))
sys.path.append(os.path.join(path_to_script, "../extern/pyseg_base/src"))
sys.path.append(os.path.join(path_to_script,
                             "../extern/sed3/"))
#sys.path.append(os.path.join(path_to_script, "../extern/"))
#import featurevector
import unittest

from loguru import logger
# logger = logging.getLogger()

#import apdb
#  apdb.set_trace();
#import scipy.io
import numpy as np
import scipy
#from scipy import sparse
import traceback

# ----------------- my scripts --------
import sed3
# import dcmreaddata1 as dcmr
# try:
#    import dcmreaddata as dcmr
# except:
#    from imcut import dcmreaddata as dcmr

import argparse
#import sed3

from .. import misc
from .. import organ_segmentation
from .. import experiments

def main():

    ## logger = logging.getLogger()
    # logger = logging.getLogger()

    logger.setLevel(logging.WARNING)
    ch = logging.StreamHandler()
    logger.addHandler(ch)

    #logger.debug('input params')

    # input parser
    params = {'datadir':None, 'working_voxelsize_mm':3}

    dirpath = os.path.join(path_to_script, "../../../data/medical/data_orig/volumetrie")

    experiment_results = {'params':params,'dirpath':dirpath, 'volume_l':{}}

    output_dirpath = os.path.join(path_to_script, '../../../data/medical')
    dirlist = experiments.get_subdirs(dirpath)

    for key in dirlist:
        print(key)

#        import pdb; pdb.set_trace()
        try:
            dirname = dirlist[key]['abspath']
            params['datadir'] = dirname

            oseg = organ_segmentation.OrganSegmentation(**params)

            oseg.interactivity()
            print("Volume " +
                    str(oseg.get_segmented_volume_size_mm3() / 1000000.0)
                    + ' [l]')

            volume_l = (oseg.get_segmented_volume_size_mm3() / 1000000.0)

            experiment_results['volume_l'][key] = volume_l

            head, teil = os.path.split(dirname)
            filename_organ = os.path.join(output_dirpath, teil)

            data = oseg.export()
            misc.obj_to_file(data, filename_organ + "-organ.pkl", filetype='pickle')
            #misc.obj_to_file(data, "organ.pkl", filetype='pickle')
            misc.obj_to_file(oseg.get_iparams(), filename_organ + '-iparams.pkl', filetype='pickle')
            misc.obj_to_file(experiment_results, filename_organ + "-info.yaml", filetype='yaml')

        except:
            print('Selhani, pokracujeme dal')
            print(traceback.format_exc())
            import pdb; pdb.set_trace()

    misc.obj_to_file(experiment_results, "results.yaml", filetype='yaml')
    #igc = pycat.ImageGraphCut(data3d, zoom = 0.5)
    #igc.interactivity()

    #igc.make_gc()
    #igc.show_segmentation()

    # volume
    #volume_mm3 = np.sum(oseg.segmentation > 0) * np.prod(oseg.voxelsize_mm)

    #pyed = sed3.sed3(oseg.data3d, contour =
    # oseg.segmentation)
    #pyed.show()

#    if args.show_output:
#        oseg.show_output()
#
#    savestring = raw_input('Save output data? (y/n): ')
#    #sn = int(snstring)
#    if savestring in ['Y', 'y']:
#
#        data = oseg.export()
#
#        misc.obj_to_file(data, "organ.pkl", filetype='pickle')
#        misc.obj_to_file(oseg.get_ipars(), 'ipars.pkl', filetype='pickle')
#    #output = segmentation.vesselSegmentation(oseg.data3d,
    # oseg.orig_segmentation)

if __name__ == "__main__":
    main()


text:
<?php
if(!defined('IN_INDEX')) exit;

$dbr = Database::$content->prepare("SELECT id, page, headline, content, content_formatting, teaser_headline, teaser, teaser_formatting, teaser_img, link_name FROM ".Database::$db_settings['pages_table']." WHERE include_page=:include_page ORDER BY include_order ASC");
$dbr->bindParam(':include_page', $data['id'], PDO::PARAM_INT);
$dbr->execute();
$i=0;
while($included_pages_data = $dbr->fetch())
 {
  if($included_pages_data['teaser_headline']=='')
   {
    $included_pages[$i]['teaser_headline'] = stripslashes($included_pages_data['headline']);
   }
  else
   {
    $included_pages[$i]['teaser_headline'] = stripslashes($included_pages_data['teaser_headline']);
   }
  if($included_pages_data['teaser']=='')
   {
    if($included_pages_data['content_formatting']==1)
     {
      $included_pages[$i]['teaser'] = nl2br(stripslashes($included_pages_data['content']));
     }
    else
     {
      $included_pages[$i]['teaser'] = stripslashes($included_pages_data['content']);
     }
   }
  else
   {
    if($included_pages_data['teaser_formatting']==1)
     {
      $included_pages[$i]['teaser'] = nl2br(stripslashes($included_pages_data['teaser']));
     }
    else
     {
      $included_pages[$i]['teaser'] = stripslashes($included_pages_data['teaser']);
     }
   }
  $included_pages[$i]['page'] = $included_pages_data['page'];
  $included_pages[$i]['teaser_img'] = $included_pages_data['teaser_img'];
  if(trim($included_pages_data['teaser_img']!=''))
   {
    $teaser_img_info = getimagesize(BASE_PATH.MEDIA_DIR.$included_pages_data['teaser_img']);
    $included_pages[$i]['teaser_img_width'] = $teaser_img_info[0];
    $included_pages[$i]['teaser_img_height'] = $teaser_img_info[1];
   }
  $included_pages[$i]['link_name'] = stripslashes($included_pages_data['link_name']);
  $i++;
 }
if(isset($included_pages))
 {
  $template->assign('included_pages_number', count($included_pages));
  $template->assign('included_pages', $included_pages);
 }
$template->assign('subtemplate', 'overview.inc.tpl');

if(isset($cache))
 {
  $cache->cacheId = PAGE;
 }
?>


text:
        The City & the City

                        author

                        China Miéville

                        original language
English

                        published
2009

Back cover

When the body of a murdered woman is found in the extraordinary, decaying city of Beszel, somewhere at the edge of Europe, it looks like a routine case for Inspector Tyador Borlú of the Extreme Crime Squad. But as he probes, the evidence begins to point to conspiracies far stranger, and more deadly, than anything he could have imagined. Soon his work puts him and those he cares for in danger. Borlú must travel to the only metropolis on Earth as strange as his own, across a border like no other.

Opening

I could not see the street or much of the estate. We were enclosed by dirt-coloured blocks, from windows out of which leaned vested men and women with morning hair and mugs of drink, eating breakfast and watching us. This open ground between the buildings had once been scuplted. It pitched like a golf course - a child's mimicking of geography. Maybe they had been going to wood it and put in a pond. There was a copse but the saplings were dead.


text:
import UpMap       from './Map';
import {mapObject} from './Out';
import UpSort      from './Srt';
//import keepSliced from './Slc';

var {defineProperty, defineProperties} = Object;
var {prototype} = Array;

// Place the methods on the Array and Upwardable prototype.
var methodMap = {
  as:   UpMap,
  by:   UpSort//,
//  if:   keepFiltered,
//  of:   keepSliced,
//  up:   keepReversed,
//  uniq: keepUnique
};

var arrayProtoMunged = "__UPWARD_METHODS";

var methodDescriptors = mapObject(methodMap, v => ({
  value(...args) { return v(this, ...args); }})
);

if (!prototype[arrayProtoMunged]) {
  defineProperties(prototype, methodDescriptors);
  defineProperty(prototype, arrayProtoMunged, {value: true});
}


text:
struct resource {
  static int count;
  resource() { ++count; }
  resource(resource const&) { ++count; }
  ~resource() { --count; }
};
int resource::count = 0;

typedef std::vector<resource> resources_t;

typedef boost::shared_container_iterator< resources_t > iterator;

void set_range(iterator& i, iterator& end)  {

  boost::shared_ptr< resources_t > objs(new resources_t());

  for (int j = 0; j != 6; ++j)
    objs->push_back(resource());

  i = iterator(objs->begin(),objs);
  end = iterator(objs->end(),objs);
  assert(resource::count == 6);
}

int main() {

  assert(resource::count == 0);

  {
    iterator i;
    {
      iterator end;
      set_range(i,end);
      assert(resource::count == 6);
    }
    assert(resource::count == 6);
  }
  assert(resource::count == 0);

  return 0;
}


text:
class Engine{
	public:
		Engine();
		void init();
		void gameLoop();
		void addLogic(Logic* logicptr);
		void makeSystemMap();
	private:
		AssetManager _assetManager;
		RenderSystem _renderSystem;
		LogicSystem _logicSystem;
		SDLManager _SDLManager;
		SceneManager _sceneManager;
};
#endif


text:
import sys
import os

try:
    sys.path.append (os.path.abspath ('../'))
    from number_ninja import *
except:
    print ('flow ninja requires package number_ninja, please add the path to number_ninja')

from flow_ninja import *
from particle_ninja import *
from particle import *
from weight_engine import *


text:
<?php

namespace Persona\Hris\Attendance\Model;

use Persona\Hris\Employee\Model\EmployeeInterface;

/**
 * @author Muhamad Surya Iksanudin <surya.iksanudin@personahris.com>
 */
interface EmployeeAttendanceInterface
{
    /**
     * @return string
     */
    public function getId(): string;

    /**
     * @return null|EmployeeInterface
     */
    public function getEmployee(): ? EmployeeInterface;

    /**
     * @param EmployeeInterface $employee
     */
    public function setEmployee(EmployeeInterface $employee = null): void;

    /**
     * @return null|ShiftmentInterface
     */
    public function getShiftment(): ? ShiftmentInterface;

    /**
     * @param ShiftmentInterface $shiftment
     */
    public function setShiftment(ShiftmentInterface $shiftment = null): void;

    /**
     * @return \DateTime
     */
    public function getAttendanceDate(): \DateTime;

    /**
     * @param \DateTime $attendanceDate
     */
    public function setAttendanceDate(\DateTime $attendanceDate): void;

    /**
     * @return string
     */
    public function getSnapShot(): string;

    /**
     * @return string
     */
    public function getGeoLocation(): string;

    /**
     * @return string
     */
    public function getTimeIn(): string;

    /**
     * @return string
     */
    public function getTimeOut(): string;

    /**
     * @return string
     */
    public function getEarlyIn(): string;

    /**
     * @param string $earlyIn
     */
    public function setEarlyIn(string $earlyIn): void;

    /**
     * @return string
     */
    public function getEarlyOut(): string;

    /**
     * @param string $earlyOut
     */
    public function setEarlyOut(string $earlyOut): void;

    /**
     * @return string
     */
    public function getLateIn(): string;

    /**
     * @param string $lateIn
     */
    public function setLateIn(string $lateIn): void;

    /**
     * @return string
     */
    public function getLateOut(): string;

    /**
     * @param string $lateOut
     */
    public function setLateOut(string $lateOut): void;

    /**
     * @return bool
     */
    public function isAbsent(): bool;

    /**
     * @param bool $isAbsent
     */
    public function setAbsent(bool $isAbsent): void;

    /**
     * @return null|AbsentReasonInterface
     */
    public function getAbsentReason(): ? AbsentReasonInterface;

    /**
     * @param AbsentReasonInterface $absentReason
     */
    public function setAbsentReason(AbsentReasonInterface $absentReason = null): void;

    /**
     * @return string
     */
    public function getRemark(): ? string;

    /**
     * @param string $remark
     */
    public function setRemark(string $remark = null): void;
}


text:
Namespace Core

    Public MustInherit Class AbstractExcelSubObject : Inherits AbstractExcelObject : Implements IExcelObject

        Protected ReadOnly Parent As IExcelObject

        Public Sub New(ByVal parent As IExcelObject, ByVal comObject As Object)
            MyBase.New(comObject)
            Me.Parent = parent
            parent.AddToManager(comObject)
        End Sub

        Public Overridable Sub AddToManager(ByVal comObject As Object) Implements IExcelObject.AddToManager
            Parent.AddToManager(comObject)
        End Sub

    End Class
End Namespace


text:
package kafka.api

import java.util.concurrent.{ExecutionException, TimeUnit, TimeoutException}
import java.util.{Properties, Random}

import kafka.common.Topic
import kafka.consumer.SimpleConsumer
import kafka.integration.KafkaServerTestHarness
import kafka.server.KafkaConfig
import kafka.utils.{ShutdownableThread, TestUtils}
import org.apache.kafka.clients.producer._
import org.apache.kafka.clients.producer.internals.ErrorLoggingCallback
import org.apache.kafka.common.KafkaException
import org.apache.kafka.common.errors.{InvalidTopicException, NotEnoughReplicasAfterAppendException, NotEnoughReplicasException}
import org.junit.Assert._
import org.junit.{After, Before, Test}

class ProducerFailureHandlingTest extends KafkaServerTestHarness {
  private val producerBufferSize = 30000
  private val serverMessageMaxBytes =  producerBufferSize/2

  val numServers = 2

  val overridingProps = new Properties()
  overridingProps.put(KafkaConfig.AutoCreateTopicsEnableProp, false.toString)
  overridingProps.put(KafkaConfig.MessageMaxBytesProp, serverMessageMaxBytes.toString)
  // Set a smaller value for the number of partitions for the offset commit topic (__consumer_offset topic)
  // so that the creation of that topic/partition(s) and subsequent leader assignment doesn't take relatively long
  overridingProps.put(KafkaConfig.OffsetsTopicPartitionsProp, 1.toString)

  def generateConfigs() =
    TestUtils.createBrokerConfigs(numServers, zkConnect, false).map(KafkaConfig.fromProps(_, overridingProps))

  private var consumer1: SimpleConsumer = null
  private var consumer2: SimpleConsumer = null

  private var producer1: KafkaProducer[Array[Byte],Array[Byte]] = null
  private var producer2: KafkaProducer[Array[Byte],Array[Byte]] = null
  private var producer3: KafkaProducer[Array[Byte],Array[Byte]] = null
  private var producer4: KafkaProducer[Array[Byte],Array[Byte]] = null

  private val topic1 = "topic-1"
  private val topic2 = "topic-2"

  @Before
  override def setUp() {
    super.setUp()

    producer1 = TestUtils.createNewProducer(brokerList, acks = 0, maxBlockMs = 3000L, bufferSize = producerBufferSize)
    producer2 = TestUtils.createNewProducer(brokerList, acks = 1, maxBlockMs = 3000L, bufferSize = producerBufferSize)
    producer3 = TestUtils.createNewProducer(brokerList, acks = -1, maxBlockMs = 3000L, bufferSize = producerBufferSize)
  }

  @After
  override def tearDown() {
    if (producer1 != null) producer1.close
    if (producer2 != null) producer2.close
    if (producer3 != null) producer3.close
    if (producer4 != null) producer4.close

    super.tearDown()
  }

  /**
   * With ack == 0 the future metadata will have no exceptions with offset -1
   */
  @Test
  def testTooLargeRecordWithAckZero() {
    // create topic
    TestUtils.createTopic(zkUtils, topic1, 1, numServers, servers)

    // send a too-large record
    val record = new ProducerRecord[Array[Byte],Array[Byte]](topic1, null, "key".getBytes, new Array[Byte](serverMessageMaxBytes + 1))
    assertEquals("Returned metadata should have offset -1", producer1.send(record).get.offset, -1L)
  }

  /**
   * With ack == 1 the future metadata will throw ExecutionException caused by RecordTooLargeException
   */
  @Test
  def testTooLargeRecordWithAckOne() {
    // create topic
    TestUtils.createTopic(zkUtils, topic1, 1, numServers, servers)

    // send a too-large record
    val record = new ProducerRecord[Array[Byte],Array[Byte]](topic1, null, "key".getBytes, new Array[Byte](serverMessageMaxBytes + 1))
    intercept[ExecutionException] {
      producer2.send(record).get
    }
  }

  /**
   * With non-exist-topic the future metadata should return ExecutionException caused by TimeoutException
   */
  @Test
  def testNonExistentTopic() {
    // send a record with non-exist topic
    val record = new ProducerRecord[Array[Byte],Array[Byte]](topic2, null, "key".getBytes, "value".getBytes)
    intercept[ExecutionException] {
      producer1.send(record).get
    }
  }

  /**
   * With incorrect broker-list the future metadata should return ExecutionException caused by TimeoutException
   *
   * TODO: other exceptions that can be thrown in ExecutionException:
   *    UnknownTopicOrPartitionException
   *    NotLeaderForPartitionException
   *    LeaderNotAvailableException
   *    CorruptRecordException
   *    TimeoutException
   */
  @Test
  def testWrongBrokerList() {
    // create topic
    TestUtils.createTopic(zkUtils, topic1, 1, numServers, servers)

    // producer with incorrect broker list
    producer4 = TestUtils.createNewProducer("localhost:8686,localhost:4242", acks = 1, maxBlockMs = 3000L, bufferSize = producerBufferSize)

    // send a record with incorrect broker list
    val record = new ProducerRecord[Array[Byte],Array[Byte]](topic1, null, "key".getBytes, "value".getBytes)
    intercept[ExecutionException] {
      producer4.send(record).get
    }
  }

  /**
   *  The send call with invalid partition id should throw KafkaException caused by IllegalArgumentException
   */
  @Test
  def testInvalidPartition() {
    // create topic
    TestUtils.createTopic(zkUtils, topic1, 1, numServers, servers)

    // create a record with incorrect partition id, send should fail
    val record = new ProducerRecord[Array[Byte],Array[Byte]](topic1, new Integer(1), "key".getBytes, "value".getBytes)
    intercept[IllegalArgumentException] {
      producer1.send(record)
    }
    intercept[IllegalArgumentException] {
      producer2.send(record)
    }
    intercept[IllegalArgumentException] {
      producer3.send(record)
    }
  }

  /**
   * The send call after producer closed should throw KafkaException cased by IllegalStateException
   */
  @Test
  def testSendAfterClosed() {
    // create topic
    TestUtils.createTopic(zkUtils, topic1, 1, numServers, servers)

    val record = new ProducerRecord[Array[Byte],Array[Byte]](topic1, null, "key".getBytes, "value".getBytes)

    // first send a message to make sure the metadata is refreshed
    producer1.send(record).get
    producer2.send(record).get
    producer3.send(record).get

    intercept[IllegalStateException] {
      producer1.close
      producer1.send(record)
    }
    intercept[IllegalStateException] {
      producer2.close
      producer2.send(record)
    }
    intercept[IllegalStateException] {
      producer3.close
      producer3.send(record)
    }

    // re-close producer is fine
  }

  @Test
  def testCannotSendToInternalTopic() {
    val thrown = intercept[ExecutionException] {
      producer2.send(new ProducerRecord[Array[Byte],Array[Byte]](Topic.InternalTopics.head, "test".getBytes, "test".getBytes)).get
    }
    assertTrue("Unexpected exception while sending to an invalid topic " + thrown.getCause, thrown.getCause.isInstanceOf[InvalidTopicException])
  }

  @Test
  def testNotEnoughReplicas() {
    val topicName = "minisrtest"
    val topicProps = new Properties()
    topicProps.put("min.insync.replicas",(numServers+1).toString)

    TestUtils.createTopic(zkUtils, topicName, 1, numServers, servers, topicProps)

    val record = new ProducerRecord[Array[Byte],Array[Byte]](topicName, null, "key".getBytes, "value".getBytes)
    try {
      producer3.send(record).get
      fail("Expected exception when producing to topic with fewer brokers than min.insync.replicas")
    } catch {
      case e: ExecutionException =>
        if (!e.getCause.isInstanceOf[NotEnoughReplicasException]) {
          fail("Expected NotEnoughReplicasException when producing to topic with fewer brokers than min.insync.replicas")
        }
    }
  }

  @Test
  def testNotEnoughReplicasAfterBrokerShutdown() {
    val topicName = "minisrtest2"
    val topicProps = new Properties()
    topicProps.put("min.insync.replicas",numServers.toString)

    TestUtils.createTopic(zkUtils, topicName, 1, numServers, servers,topicProps)

    val record = new ProducerRecord[Array[Byte],Array[Byte]](topicName, null, "key".getBytes, "value".getBytes)
    // this should work with all brokers up and running
    producer3.send(record).get

    // shut down one broker
    servers.head.shutdown()
    servers.head.awaitShutdown()
    try {
      producer3.send(record).get
      fail("Expected exception when producing to topic with fewer brokers than min.insync.replicas")
    } catch {
      case e: ExecutionException =>
        if (!e.getCause.isInstanceOf[NotEnoughReplicasException]  &&
            !e.getCause.isInstanceOf[NotEnoughReplicasAfterAppendException] &&
            !e.getCause.isInstanceOf[TimeoutException]) {
          fail("Expected NotEnoughReplicasException or NotEnoughReplicasAfterAppendException when producing to topic " +
            "with fewer brokers than min.insync.replicas, but saw " + e.getCause)
        }
    }

    // restart the server
    servers.head.startup()
  }

  private class ProducerScheduler extends ShutdownableThread("daemon-producer", false)
  {
    val numRecords = 1000
    var sent = 0
    var failed = false

    val producer = TestUtils.createNewProducer(brokerList, bufferSize = producerBufferSize, retries = 10)

    override def doWork(): Unit = {
      val responses =
        for (i <- sent+1 to sent+numRecords)
        yield producer.send(new ProducerRecord[Array[Byte],Array[Byte]](topic1, null, null, i.toString.getBytes),
                            new ErrorLoggingCallback(topic1, null, null, true))
      val futures = responses.toList

      try {
        futures.map(_.get)
        sent += numRecords
      } catch {
        case e : Exception => failed = true
      }
    }

    override def shutdown(){
      super.shutdown()
      producer.close
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <view
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.aviary.android.feather.widget.ImageViewTouchBrush"
        android:clickable="true"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:hapticFeedbackEnabled="true" />

</RelativeLayout>


text:
package com.granule.calcdeps;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import com.granule.FragmentDescriptor;

public class DependencyInfo {
    FragmentDescriptor script;
    private List<String> provides = new ArrayList<String>();
    private List<String> requires = new ArrayList<String>();

    public DependencyInfo(FragmentDescriptor script) {
        this.script = script;
    }

    public String toString() {
        StringBuilder prov = new StringBuilder();
        for (int i = 0; i < provides.size(); i++)
            prov.append(i != 0 ? "," : "").append(provides.get(i));
        StringBuilder req = new StringBuilder();
        for (int i = 0; i < requires.size(); i++)
            req.append(i != 0 ? "," : "").append(requires.get(i));
        return MessageFormat.format("{0} Provides: {1} Requires: {2}", script==null?"":script.toString(), prov.toString(), req.toString());
    }

    public List<String> getProvides() {
        return provides;
    }

    public List<String> getRequires() {
        return requires;
    }
}


text:
/* CSS Document */
html, body, div, span, object, iframe,h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, code,del, dfn, em, img, q, dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,table, caption, tbody, tfoot, thead, tr, th, td,img{ margin:0px; padding:0px;}
ul,li,dl,dt,dd,ol{ list-style:none;}
.clear{ clear:both; font-size:0; line-height:0; height:0;}
a,a:link,a:visited{ color:#4e4e4e; text-decoration:none;}
a:hover{ color:#FF0000; text-decoration:underline;}
img{ border:0px;}
body{ font-family:"宋体"; font-size:12px; margin:0px; line-height:160%; color:#4e4e4e;background:#fff url(../img/bobybg2.jpg) no-repeat 50% 0px;}
.nobg{ background:none !important;}
.padding1{ padding:1px;}.padding2{ padding:2px;}.padding3{ padding:3px;}.padding4{ padding:4px;}.padding5{ padding:5px;}.padding6{ padding:6px;}.padding7{ padding:7px;}.padding8{ padding:8px;}.padding9{ padding:9px;}.padding10{ padding:10px;}
.red,.red:link,.red:visited{ color:#ff0000;}
.green,.green:link,.green:visited{ color:#0b861f;}
.blue,.blue:link,.blue:visited{ color:#0076cd;}
.btn_search{ border:0px; background:#0076cd; color:#ffffff; height:22px; line-height:22px; cursor:pointer; padding:0px 15px; *padding:0px 7px; vertical-align:middle; display:inline-block; _display:inline; _zoom:1;}
.fontV{font-family:Verdana, Arial, Helvetica, sans-serif}
.font14{font-size:14px;}
.font11{font-size:11px;}
.textheight24{line-height:24px;}

/*新站点头部*/
.top{width:1004px; margin:0px auto;color:#000;}
.top_toplink{height:24px;line-height:24px;padding-top:9px;color:#000;}
.top_toplink span{float:right;color:#000;}
.top_toplink span a:link,.top_toplink span a:visited{color:#000;text-decoration:none;}
.top_toplink span a:hover{color:#000;text-decoration:underline;}
.top_banner{height:137px;}
.top_logo{float:left;width:307px; height:64px;padding-top:38px;padding-left:2px;}
.top_logo h1{ background:url(../img/site_name.gif) no-repeat left top; display:block; height:100%;}
.top_logo h1 a{ display:block; height:100%; text-indent:-300px; width:307px; overflow:hidden;}
.top_right{float:right;padding-top:34px;}
.top_tq{font-size:12px;text-align:right;}
.top_tq span{font-size:14px;color:#0076c9;font-family:'microsoft yahei',"黑体";margin:0 10px;}
.top_tq img{vertical-align:text-bottom;}
.top_search{ width:240px; height:22px; padding:1px; background:#cacaca;text-align:right;margin-top:10px;}
.top_search input{ height:20px; line-height:20px; border:none; background:#ffffff; padding:1px; margin:0px; display:block; float:left; width:178px;}
.top_search button{ width:60px; height:22px; line-height:22px;  float:left; display:block; border:none; background:#0076c9; color:#ffffff; font-size:14px; cursor:pointer;}

/**/
.site_body{ width:1004px; margin:0px auto;}
.site_body1{ width:1004px; margin:0px auto;}
.site_nr{padding:0 0px;}
.partborder{ border:1px solid #e5e5e5;}
.partinborder{ border:1px solid #dcdcdc;}
.partM{ margin-top:13px;}
.timespan{ float:right; font-size:11px; font-family:Verdana,Geneva; line-height:24px; width:80px; text-align:right;}
/*当前位置*/
.site_postion{ background:url(../img/site_postionbg.gif) repeat-x; height:33px; padding-left:15px; padding-top:15px;}
.postion_icon{ background:url(../img/icon_1.gif) no-repeat; padding-left:30px; color:#686868; height:20px; line-height:20px; font-size:14px;}

/*分页代码*/
.pageation{ padding:15px 0px; text-align:center; font-size:14px; font-family:"宋体";}
.pageation span{ display:inline-block; _display:inline; _zoom:1;}
.pageation .pagetotle{ margin-right:15px;}
.pageation .home{}
.pageation .end{}
.pageation .pagenum{ margin:0px 5px;}
.pageation .pagenum a:link,.pageation .pagenum a:visited{ display:inline-block; _display:inline; _zoom:1; margin-left:3px; border:1px solid #CBCBCB; padding:1px 8px; background:#f0f0f0; font-size:14px;}
.pageation .pagenum a:hover{ border:1px solid #0274BD; background:#f5f5f5; text-decoration:none;}
.pageation .pagenum .this:link,.pageation .pagenum .this:visited{ border:1px solid #04326E; background:#0274BD; color:#ffffff; font-weight:600;}
.pageation .gopage{ margin-left:15px;}
.pageation .gopage select{/* margin:0px 2px;*/}

/*站点底部*/
.site_footer{ margin-top:13px;}
.wrapper_footer{ width:1004px; margin:0px auto;}
.footer_link{ height:80px; background:url(../img/footer_linkbg.gif);/* border:1px solid #cacaca; border-left:none; border-right:none; background:#f3f3f3;*/}
.footer_link .wrapper_footer{ height:24px; padding-top:28px;}
.footer_link .footer_link_left{ border-left:1px solid #cacaca; background:#f3f3f3; float:left; font-size:18px; font-weight:600; font-family:'microsoft yahei',"黑体" ; color:#0076c9; line-height:24px; width:125px; height:24px; text-align:center;}
.footer_link .footer_link_right{ border-right:1px solid #cacaca; background:#f3f3f3; float:right; width:877px; height:24px;}
.footer_link .footer_link_right .input2{ width:136px; height:24px; line-height:24px; vertical-align:middle;}
.footer_link .footer_link_right .input2 option{ line-height:24px;}
.footer_menu{ height:38px; background:#0076c9; text-align:center;}
.footer_menu .footerlink_text{ text-align:center; color:#ffffff; line-height:38px; font-size:14px;}
.footer_menu .footerlink_text a:link,.footer_menu .footerlink_text a:visited{ color:#FFFFFF;}
.footer_copyright{ padding:15px 0px; text-align:center; line-height:24px;}
/*站点底部 end*/

/*新站点底部*/
.foot{width:100%; margin:0px auto;height:135px;border-top:3px solid #0076c9;background:#e5e5e5;}
.foot1{width:100%; margin:0px auto;height:135px;border-top:3px solid #0076c9;background:#e5e5e5;}
.foot_text{border-bottom:3px solid #0076c9;padding-top:12px;}
.foot_left{padding-top:10px;color:#0076c9;text-align:center;}
.foot_left a:link,.foot_left a:visited{color:#0076c9;text-decoration:none;}
.foot_left a:hover{color:#0076c9;text-decoration:underline;}
.foot_right{text-align:center;line-height:24px;padding-top:6px;}
.index_linktable{width:100%; margin:0px auto;background:#f4f4f4;border-top:1px solid #e5e5e5;margin-top:12px;height:40px;padding-top:8px;}
.index_link{width:1004px;margin:0px auto;}
.index_link .input2{ width:132px; height:24px; line-height:24px; vertical-align:middle;}
.index_link .input2 option{ line-height:24px;}

/*浮动、到顶*/
*html{background-image:url(about:blank);background-attachment:fixed;}/*解决IE6下滚动抖动的问题*/
.sitekf{ background:url(../img/kf_bg.gif) repeat-x 0px -2px #eeeeee; padding-top:3px; width:72px; text-align:center; float:right;
 position:fixed; top:188px; right:5px; cursor:pointer; _position:absolute; _bottom:auto; _top:expression(eval(document.documentElement.scrollTop+188)) /*_top:expression(eval(document.documentElement.scrollTop+document.documentElement.clientHeight-this.offsetHeight-(parseInt(this.currentStyle.marginTop,10)||0)-(parseInt(this.currentStyle.marginBottom,10)||0)));*/}
.sitekf ul{ display:block; border-right:1px solid #dddddd; border-left:1px solid #dddddd;}
.sitekf ul li{ border-top:1px solid #ffffff; border-bottom:1px solid #dddddd; display:block;}
.sitekf ul li a{ font-size:13px; font-family:'microsoft yahei',"黑体" ; display:block; color:#000000;}
.sitekf ul li a:hover{ color:#4f4f51; text-decoration:none;/* background-color:#FFFFFF;*/}
.sitekf ul li a span{ height:20px; line-height:20px;}
.kf_weibo:link,.kf_weibo:visited{ background:url(../img/icon_weibo.gif) center 10px no-repeat; padding-top:60px; padding-bottom:10px;}
.kf_weixin:link,.kf_weixin:visited{ background:url(../img/icon_weixin.gif) center 10px no-repeat; padding-top:60px; padding-bottom:10px;}
.kf_jishi:link,.kf_jishi:visited{ background:url(../img/icon_jsjl.gif) center 10px no-repeat; padding-top:60px; padding-bottom:10px;}
.kf_gotop:link,.kf_gotop:visited{ background:url(../img/icon_gotop.gif) center 7px no-repeat #FFFFFF; padding-top:20px; padding-bottom:3px;}
/*浮动、到顶 end*/

/*新导航*/
.site_Nmenu{ width:1004px; height:46px; border-bottom:2px solid #9f1610;  margin:0px auto; position:relative;z-index:101;}
.site_Nmenu ul{ padding-top:6px; padding-left:8px; z-index:12; position:absolute; left:0px; top:0px;}
.site_Nmenu ul li{ width:140px; height:40px; float:left; margin-left:1px; text-align:center;}
.site_Nmenu ul li .Nmlink:link,.site_Nmenu ul li .Nmlink:visited{outline:none; color:#0072c8; font-size:16px; font-family:'microsoft yahei',"微软雅黑"; line-height:40px; height:40px; text-decoration:none; display:inline-block; *display:inline; *zoom:1; cursor:pointer;}
.site_Nmenu ul li .Nmlink:hover{ color:#f00;}
.iconimg{ display:inline-block; *display:inline; *zoom:1; vertical-align:middle;}
.site_Nmenu ul li .iconimg{ margin-right:3px; margin-bottom:7px; _margin-bottom:0px; cursor:pointer;}
.icon_mico1{ background:url(../img/micon_1.png) top center no-repeat; width:26px; height:26px; _background:url(../img/micon_1.gif) top center no-repeat;}
.icon_mico2{ background:url(../img/micon_2.png) top center no-repeat; width:26px; height:26px; _background:url(../img/micon_2.gif) top center no-repeat;}
.icon_mico3{ background:url(../img/micon_3.png) top center no-repeat; width:26px; height:26px; _background:url(../img/micon_3.gif) top center no-repeat;}
.icon_mico4{ background:url(../img/micon_4.png) top center no-repeat; width:26px; height:26px; _background:url(../img/micon_4.gif) top center no-repeat;}
.icon_mico5{ background:url(../img/micon_5.png) top center no-repeat; width:26px; height:26px; _background:url(../img/micon_5.gif) top center no-repeat;}
.icon_mico6{ background:url(../img/micon_6.png) top center no-repeat; width:26px; height:26px; _background:url(../img/micon_6.gif) top center no-repeat;}
.icon_mico7{ background:url(../img/micon_7.png) top center no-repeat; width:26px; height:26px; _background:url(../img/micon_7.gif) top center no-repeat;}
.site_Nmenu ul li .Nmenu_XMC{ position:absolute; left:0px; top:48px; display:none; z-index:99999;background:#fff;height:260px;padding:20px 30px 30px 30px;text-align:left;border-left:2px solid #9f1610;border-right:2px solid #9f1610;border-bottom:2px solid #9f1610;}
.site_Nmenu ul li.hover .Nmenu_XMC{ display:block;}/*鼠标经过时显示下拉*/
.site_Nmenu ul li.hover .iconimg{ background-position:bottom center;}/*鼠标经过时切换图标*/
.site_Nmenu ul li.hover .Nmlink:link,.site_Nmenu ul li.hover .Nmlink:visited{ color:#FFF;}
.Nmenu_tabg{ background:url(../img/menu_overbg.png) left top no-repeat; width:140px; height:40px; position:absolute; top:6px; left:8px; z-index:11; display:none; _background:url(../img/menu_overbg.gif) left top no-repeat;}
.site_Nmenu ul li.hover{ background:url(../img/menu_overbg.png) left top no-repeat; _background:url(../img/menu_overbg.gif) left top no-repeat;}


text:
"""
Domain exceptions for Reactor cloud account operations
"""

class RegistrationFailure(Exception):
    """
    Thrown if we couldn't register the reactor
    """
    pass

class InvalidSystemSettings(Exception):
    """
    Thrown if we received bad system settings
    """
    pass

class ProbeExceptionNoReactorAccess(Exception):
    """
    Thrown if we tried to probe the connected account, but ran into a permissions error in AWS.
    This should not happen upon initial connection (we check this), however if manual
    changes are made by the account owner, it may adversely affect our ability to get information.
    """
    pass

class ProbeExceptionReactorThrottled(Exception):
    """
    Thrown if we tried to probe the connected account, but we're getting throttled by AWS.
    This should not happen under normal circumstances - we try very hard to avoid chatty connections.
    """
    pass

class GenericProbeException(Exception):
    """
    Thrown if we tried to probe the connected account, but got an unspecified error.
    """
    pass

class CloudAccountMetadataLookupException(Exception):
    """
    Thrown on a cloud account cache miss or general cache failure.
    """
    pass


text:
using System;
using System.Collections.Generic;
using System.Timers;
using OpenMetaverse.Packets;
using OpenSim.Framework;
using OpenSim.Framework.Monitoring;
using OpenSim.Region.Framework.Interfaces;

namespace OpenSim.Region.Framework.Scenes
{
    /// <summary>
    /// Collect statistics from the scene to send to the client and for access by other monitoring tools.
    /// </summary>
    /// <remarks>
    /// FIXME: This should be a monitoring region module
    /// </remarks>
    public class SimStatsReporter
    {
        private static readonly log4net.ILog m_log
            = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public const string LastReportedObjectUpdateStatName = "LastReportedObjectUpdates";
        public const string SlowFramesStatName = "SlowFrames";

        public delegate void SendStatResult(SimStats stats);

        public delegate void YourStatsAreWrong();

        public event SendStatResult OnSendStatsResult;

        public event YourStatsAreWrong OnStatsIncorrect;

        private SendStatResult handlerSendStatResult;

        private YourStatsAreWrong handlerStatsIncorrect;

        // Determines the size of the array that is used to collect StatBlocks
        // for sending to the SimStats and SimExtraStatsCollector
        private const int m_statisticArraySize = 28;

        /// <summary>
        /// These are the IDs of stats sent in the StatsPacket to the viewer.
        /// </summary>
        /// <remarks>
        /// Some of these are not relevant to OpenSimulator since it is architected differently to other simulators
        /// (e.g. script instructions aren't executed as part of the frame loop so 'script time' is tricky).
        /// </remarks>
        public enum Stats : uint
        {
            TimeDilation = 0,
            SimFPS = 1,
            PhysicsFPS = 2,
            AgentUpdates = 3,
            FrameMS = 4,
            NetMS = 5,
            OtherMS = 6,
            PhysicsMS = 7,
            AgentMS = 8,
            ImageMS = 9,
            ScriptMS = 10,
            TotalPrim = 11,
            ActivePrim = 12,
            Agents = 13,
            ChildAgents = 14,
            ActiveScripts = 15,
            ScriptLinesPerSecond = 16,
            InPacketsPerSecond = 17,
            OutPacketsPerSecond = 18,
            PendingDownloads = 19,
            PendingUploads = 20,
            VirtualSizeKb = 21,
            ResidentSizeKb = 22,
            PendingLocalUploads = 23,
            UnAckedBytes = 24,
            PhysicsPinnedTasks = 25,
            PhysicsLodTasks = 26,
            SimPhysicsStepMs = 27,
            SimPhysicsShapeMs = 28,
            SimPhysicsOtherMs = 29,
            SimPhysicsMemory = 30,
            ScriptEps = 31,
            SimSpareMs = 32,
            SimSleepMs = 33,
            SimIoPumpTime = 34,
            FrameDilation = 35,
            UsersLoggingIn = 36,
            TotalGeoPrim = 37,
            TotalMesh = 38,
            ThreadCount = 39
        }

        /// <summary>
        /// This is for llGetRegionFPS
        /// </summary>
        public float LastReportedSimFPS
        {
            get { return lastReportedSimFPS; }
        }

        /// <summary>
        /// Number of object updates performed in the last stats cycle
        /// </summary>
        /// <remarks>
        /// This isn't sent out to the client but it is very useful data to detect whether viewers are being sent a
        /// large number of object updates.
        /// </remarks>
        public float LastReportedObjectUpdates { get; private set; }

        public float[] LastReportedSimStats
        {
            get { return lastReportedSimStats; }
        }

        /// <summary>
        /// Number of frames that have taken longer to process than Scene.MIN_FRAME_TIME
        /// </summary>
        public Stat SlowFramesStat { get; private set; }

        /// <summary>
        /// The threshold at which we log a slow frame.
        /// </summary>
        public int SlowFramesStatReportThreshold { get; private set; }

        /// <summary>
        /// Extra sim statistics that are used by monitors but not sent to the client.
        /// </summary>
        /// <value>
        /// The keys are the stat names.
        /// </value>
        private Dictionary<string, float> m_lastReportedExtraSimStats = new Dictionary<string, float>();

        // Sending a stats update every 3 seconds-
        private int m_statsUpdatesEveryMS = 3000;
        private float m_statsUpdateFactor;
        private float m_timeDilation;
        private int m_fps;

        /// <summary>
        /// Number of the last frame on which we processed a stats udpate.
        /// </summary>
        private uint m_lastUpdateFrame;

        /// <summary>
        /// Our nominal fps target, as expected in fps stats when a sim is running normally.
        /// </summary>
        private float m_nominalReportedFps = 55;

        /// <summary>
        /// Parameter to adjust reported scene fps
        /// </summary>
        /// <remarks>
        /// Our scene loop runs slower than other server implementations, apparantly because we work somewhat differently.
        /// However, we will still report an FPS that's closer to what people are used to seeing.  A lower FPS might
        /// affect clients and monitoring scripts/software.
        /// </remarks>
        private float m_reportedFpsCorrectionFactor = 5;

        // saved last reported value so there is something available for llGetRegionFPS
        private float lastReportedSimFPS;
        private float[] lastReportedSimStats = new float[m_statisticArraySize];
        private float m_pfps;

        /// <summary>
        /// Number of agent updates requested in this stats cycle
        /// </summary>
        private int m_agentUpdates;

        /// <summary>
        /// Number of object updates requested in this stats cycle
        /// </summary>
        private int m_objectUpdates;

        private int m_frameMS;
        private int m_spareMS;
        private int m_netMS;
        private int m_agentMS;
        private int m_physicsMS;
        private int m_imageMS;
        private int m_otherMS;
        private int m_scriptMS;

        private int m_rootAgents;
        private int m_childAgents;
        private int m_numPrim;
        private int m_numGeoPrim;
        private int m_numMesh;
        private int m_inPacketsPerSecond;
        private int m_outPacketsPerSecond;
        private int m_activePrim;
        private int m_unAckedBytes;
        private int m_pendingDownloads;
        private int m_pendingUploads = 0;  // FIXME: Not currently filled in
        private int m_activeScripts;
        private int m_scriptLinesPerSecond;

        private int m_objectCapacity = 45000;

        // This is the number of frames that will be stored and then averaged for
        // the Total, Simulation, Physics, and Network Frame Time; It is set to
        // 10 by default but can be changed by the OpenSim.ini configuration file
        // NumberOfFrames parameter
        private int m_numberFramesStored;

        // The arrays that will hold the time it took to run the past N frames,
        // where N is the num_frames_to_average given by the configuration file
        private double[] m_totalFrameTimeMilliseconds;
        private double[] m_simulationFrameTimeMilliseconds;
        private double[] m_physicsFrameTimeMilliseconds;
        private double[] m_networkFrameTimeMilliseconds;

        // The location of the next time in milliseconds that will be
        // (over)written when the next frame completes
        private int m_nextLocation = 0;

        // The correct number of frames that have completed since the last stats
        // update for physics
        private int m_numberPhysicsFrames;

        // The current number of users attempting to login to the region
        private int m_usersLoggingIn;

        // The last reported value of threads from the SmartThreadPool inside of
        // XEngine
        private int m_inUseThreads;

        private Scene m_scene;

        private RegionInfo ReportingRegion;

        private Timer m_report = new Timer();

        private IEstateModule estateModule;

        public SimStatsReporter(Scene scene)
            : this(scene, Scene.m_defaultNumberFramesStored)
        {
        }

        public SimStatsReporter(Scene scene, int numberOfFrames)
        {
            // Store the number of frames from the OpenSim.ini configuration file
            m_numberFramesStored = numberOfFrames;

            // Initialize the different frame time arrays to the correct sizes
            m_totalFrameTimeMilliseconds = new double[m_numberFramesStored];
            m_simulationFrameTimeMilliseconds = new double[m_numberFramesStored];
            m_physicsFrameTimeMilliseconds = new double[m_numberFramesStored];
            m_networkFrameTimeMilliseconds = new double[m_numberFramesStored];

            // Initialize the current number of users logging into the region
            m_usersLoggingIn = 0;

            m_scene = scene;
            m_reportedFpsCorrectionFactor = scene.MinFrameSeconds * m_nominalReportedFps;
            m_statsUpdateFactor = (float)(m_statsUpdatesEveryMS / 1000);
            ReportingRegion = scene.RegionInfo;

            m_objectCapacity = scene.RegionInfo.ObjectCapacity;
            m_report.AutoReset = true;
            m_report.Interval = m_statsUpdatesEveryMS;
            m_report.Elapsed += TriggerStatsHeartbeat;
            m_report.Enabled = true;

            if (StatsManager.SimExtraStats != null)
                OnSendStatsResult += StatsManager.SimExtraStats.ReceiveClassicSimStatsPacket;

            /// At the moment, we'll only report if a frame is over 120% of target, since commonly frames are a bit
            /// longer than ideal (which in itself is a concern).
            SlowFramesStatReportThreshold = (int)Math.Ceiling(scene.MinFrameTicks * 1.2);

            SlowFramesStat
                = new Stat(
                    "SlowFrames",
                    "Slow Frames",
                    "Number of frames where frame time has been significantly longer than the desired frame time.",
                    " frames",
                    "scene",
                    m_scene.Name,
                    StatType.Push,
                    null,
                    StatVerbosity.Info);

            StatsManager.RegisterStat(SlowFramesStat);

        }

        public void Close()
        {
            m_report.Elapsed -= TriggerStatsHeartbeat;
            m_report.Close();
        }

        /// <summary>
        /// Sets the number of milliseconds between stat updates.
        /// </summary>
        /// <param name='ms'></param>
        public void SetUpdateMS(int ms)
        {
            m_statsUpdatesEveryMS = ms;
            m_statsUpdateFactor = (float)(m_statsUpdatesEveryMS / 1000);
            m_report.Interval = m_statsUpdatesEveryMS;
        }

        private void TriggerStatsHeartbeat(object sender, EventArgs args)
        {
            try
            {
                statsHeartBeat(sender, args);
            }
            catch (Exception e)
            {
                m_log.Warn(string.Format(
                    "[SIM STATS REPORTER] Update for {0} failed with exception ",
                    m_scene.RegionInfo.RegionName), e);
            }
        }

        private void statsHeartBeat(object sender, EventArgs e)
        {
            double totalSumFrameTime;
            double simulationSumFrameTime;
            double physicsSumFrameTime;
            double networkSumFrameTime;
            float frameDilation;
            int currentFrame;

            if (!m_scene.Active)
                return;

            // Create arrays to hold the statistics for this current scene,
            // these will be passed to the SimExtraStatsCollector, they are also
            // sent to the SimStats class
            SimStatsPacket.StatBlock[] sb = new
                SimStatsPacket.StatBlock[m_statisticArraySize];
            SimStatsPacket.RegionBlock rb = new SimStatsPacket.RegionBlock();

            // Know what's not thread safe in Mono... modifying timers.
            // m_log.Debug("Firing Stats Heart Beat");
            lock (m_report)
            {
                uint regionFlags = 0;

                try
                {
                    if (estateModule == null)
                        estateModule = m_scene.RequestModuleInterface<IEstateModule>();
                    regionFlags = estateModule != null ? estateModule.GetRegionFlags() : (uint) 0;
                }
                catch (Exception)
                {
                    // leave region flags at 0
                }

#region various statistic googly moogly

               // ORIGINAL code commented out until we have time to add our own
               // statistics to the statistics window, this will be done as a
               // new section given the title of our current project
                // We're going to lie about the FPS because we've been lying since 2008.  The actual FPS is currently
                // locked at a maximum of 11.  Maybe at some point this can change so that we're not lying.
                //int reportedFPS = (int)(m_fps * m_reportedFpsCorrectionFactor);
               int reportedFPS = m_fps;

                // save the reported value so there is something available for llGetRegionFPS
                lastReportedSimFPS = reportedFPS / m_statsUpdateFactor;

               // ORIGINAL code commented out until we have time to add our own
               // statistics to the statistics window
                //float physfps = ((m_pfps / 1000));
               float physfps = m_numberPhysicsFrames;

                //if (physfps > 600)
                //physfps = physfps - (physfps - 600);

                if (physfps < 0)
                    physfps = 0;

#endregion

                m_rootAgents = m_scene.SceneGraph.GetRootAgentCount();
                m_childAgents = m_scene.SceneGraph.GetChildAgentCount();
                m_numPrim = m_scene.SceneGraph.GetTotalObjectsCount();
                m_numGeoPrim = m_scene.SceneGraph.GetTotalPrimObjectsCount();
                m_numMesh = m_scene.SceneGraph.GetTotalMeshObjectsCount();
                m_activePrim = m_scene.SceneGraph.GetActiveObjectsCount();
                m_activeScripts = m_scene.SceneGraph.GetActiveScriptsCount();

                // FIXME: Checking for stat sanity is a complex approach.  What we really need to do is fix the code
                // so that stat numbers are always consistent.
                CheckStatSanity();

                //Our time dilation is 0.91 when we're running a full speed,
                // therefore to make sure we get an appropriate range,
                // we have to factor in our error.   (0.10f * statsUpdateFactor)
                // multiplies the fix for the error times the amount of times it'll occur a second
                // / 10 divides the value by the number of times the sim heartbeat runs (10fps)
                // Then we divide the whole amount by the amount of seconds pass in between stats updates.

                // 'statsUpdateFactor' is how often stats packets are sent in seconds. Used below to change
                // values to X-per-second values.

                uint thisFrame = m_scene.Frame;
                uint numFrames = thisFrame - m_lastUpdateFrame;
                float framesUpdated = (float)numFrames * m_reportedFpsCorrectionFactor;
                m_lastUpdateFrame = thisFrame;

                // Avoid div-by-zero if somehow we've not updated any frames.
                if (framesUpdated == 0)
                    framesUpdated = 1;

                for (int i = 0; i < m_statisticArraySize; i++)
                {
                    sb[i] = new SimStatsPacket.StatBlock();
                }

                // Resetting the sums of the frame times to prevent any errors
                // in calculating the moving average for frame time
                totalSumFrameTime = 0;
                simulationSumFrameTime = 0;
                physicsSumFrameTime = 0;
                networkSumFrameTime = 0;

                // Loop through all the frames that were stored for the current
                // heartbeat to process the moving average of frame times
                for (int i = 0; i < m_numberFramesStored; i++)
                {
                    // Sum up each frame time in order to calculate the moving
                    // average of frame time
                    totalSumFrameTime += m_totalFrameTimeMilliseconds[i];
                    simulationSumFrameTime +=
                        m_simulationFrameTimeMilliseconds[i];
                    physicsSumFrameTime += m_physicsFrameTimeMilliseconds[i];
                    networkSumFrameTime += m_networkFrameTimeMilliseconds[i];
                }

                // Get the index that represents the current frame based on the next one known; go back
                // to the last index if next one is stated to restart at 0
                if (m_nextLocation == 0)
                    currentFrame = m_numberFramesStored - 1;
                else
                    currentFrame = m_nextLocation - 1;

                // Calculate the frame dilation; which is currently based on the ratio between the sum of the
                // physics and simulation rate, and the set minimum time to run a scene's frame
                frameDilation = (float)(m_simulationFrameTimeMilliseconds[currentFrame] +
                   m_physicsFrameTimeMilliseconds[currentFrame]) / m_scene.MinFrameTicks;

                // ORIGINAL code commented out until we have time to add our own
                sb[0].StatID = (uint) Stats.TimeDilation;
                sb[0].StatValue = (Single.IsNaN(m_timeDilation)) ? 0.1f : m_timeDilation ; //((((m_timeDilation + (0.10f * statsUpdateFactor)) /10)  / statsUpdateFactor));

                sb[1].StatID = (uint) Stats.SimFPS;
                sb[1].StatValue = reportedFPS / m_statsUpdateFactor;

                sb[2].StatID = (uint) Stats.PhysicsFPS;
                sb[2].StatValue = physfps / m_statsUpdateFactor;

                sb[3].StatID = (uint) Stats.AgentUpdates;
                sb[3].StatValue = (m_agentUpdates / m_statsUpdateFactor);

                sb[4].StatID = (uint) Stats.Agents;
                sb[4].StatValue = m_rootAgents;

                sb[5].StatID = (uint) Stats.ChildAgents;
                sb[5].StatValue = m_childAgents;

                sb[6].StatID = (uint) Stats.TotalPrim;
                sb[6].StatValue = m_numPrim;

                sb[7].StatID = (uint) Stats.ActivePrim;
                sb[7].StatValue = m_activePrim;

               // ORIGINAL code commented out until we have time to add our own
               // statistics to the statistics window
                sb[8].StatID = (uint)Stats.FrameMS;
                //sb[8].StatValue = m_frameMS / framesUpdated;
                sb[8].StatValue = (float) totalSumFrameTime / m_numberFramesStored;

                sb[9].StatID = (uint)Stats.NetMS;
                //sb[9].StatValue = m_netMS / framesUpdated;
                sb[9].StatValue = (float) networkSumFrameTime / m_numberFramesStored;

                sb[10].StatID = (uint)Stats.PhysicsMS;
                //sb[10].StatValue = m_physicsMS / framesUpdated;
                sb[10].StatValue = (float) physicsSumFrameTime / m_numberFramesStored;

                sb[11].StatID = (uint)Stats.ImageMS ;
                sb[11].StatValue = m_imageMS / framesUpdated;

                sb[12].StatID = (uint)Stats.OtherMS;
                //sb[12].StatValue = m_otherMS / framesUpdated;
                sb[12].StatValue = (float) simulationSumFrameTime / m_numberFramesStored;

                sb[13].StatID = (uint)Stats.InPacketsPerSecond;
                sb[13].StatValue = (m_inPacketsPerSecond / m_statsUpdateFactor);

                sb[14].StatID = (uint)Stats.OutPacketsPerSecond;
                sb[14].StatValue = (m_outPacketsPerSecond / m_statsUpdateFactor);

                sb[15].StatID = (uint)Stats.UnAckedBytes;
                sb[15].StatValue = m_unAckedBytes;

                sb[16].StatID = (uint)Stats.AgentMS;
                sb[16].StatValue = m_agentMS / framesUpdated;

                sb[17].StatID = (uint)Stats.PendingDownloads;
                sb[17].StatValue = m_pendingDownloads;

                sb[18].StatID = (uint)Stats.PendingUploads;
                sb[18].StatValue = m_pendingUploads;

                sb[19].StatID = (uint)Stats.ActiveScripts;
                sb[19].StatValue = m_activeScripts;

                sb[20].StatID = (uint)Stats.ScriptLinesPerSecond;
                sb[20].StatValue = m_scriptLinesPerSecond / m_statsUpdateFactor;

                sb[21].StatID = (uint)Stats.SimSpareMs;
                sb[21].StatValue = m_spareMS / framesUpdated;

                // Current ratio between the sum of physics and sim rate, and the
                // minimum time to run a scene's frame
                sb[22].StatID = (uint)Stats.FrameDilation;
                sb[22].StatValue = frameDilation;

                // Current number of users currently attemptint to login to region
                sb[23].StatID = (uint)Stats.UsersLoggingIn;
                sb[23].StatValue = m_usersLoggingIn;

                // Total number of geometric primitives in the scene
                sb[24].StatID = (uint)Stats.TotalGeoPrim;
                sb[24].StatValue = m_numGeoPrim;

                // Total number of mesh objects in the scene
                sb[25].StatID = (uint)Stats.TotalMesh;
                sb[25].StatValue = m_numMesh;

                // Current number of threads that XEngine is using
                sb[26].StatID = (uint)Stats.ThreadCount;
                sb[26].StatValue = m_inUseThreads;

                sb[27].StatID = (uint)Stats.ScriptMS;
                sb[27].StatValue = (numFrames <= 0) ? 0 : ((float)m_scriptMS / numFrames);

                for (int i = 0; i < m_statisticArraySize; i++)
                {
                    lastReportedSimStats[i] = sb[i].StatValue;
                }

                SimStats simStats
                    = new SimStats(
                        ReportingRegion.RegionLocX, ReportingRegion.RegionLocY, regionFlags, (uint)m_objectCapacity,
                        rb, sb, m_scene.RegionInfo.originRegionID);

                handlerSendStatResult = OnSendStatsResult;
                if (handlerSendStatResult != null)
                {
                    handlerSendStatResult(simStats);
                }

                // Extra statistics that aren't currently sent to clients
                lock (m_lastReportedExtraSimStats)
                {
                    m_lastReportedExtraSimStats[LastReportedObjectUpdateStatName] = m_objectUpdates / m_statsUpdateFactor;
                    m_lastReportedExtraSimStats[SlowFramesStat.ShortName] = (float)SlowFramesStat.Value;

                    Dictionary<string, float> physicsStats = m_scene.PhysicsScene.GetStats();

                    if (physicsStats != null)
                    {
                        foreach (KeyValuePair<string, float> tuple in physicsStats)
                        {
                            // FIXME: An extremely dirty hack to divide MS stats per frame rather than per second
                            // Need to change things so that stats source can indicate whether they are per second or
                            // per frame.
                            if (tuple.Key.EndsWith("MS"))
                                m_lastReportedExtraSimStats[tuple.Key] = tuple.Value / framesUpdated;
                            else
                                m_lastReportedExtraSimStats[tuple.Key] = tuple.Value / m_statsUpdateFactor;
                        }
                    }
                }

                ResetValues();
            }
        }

        private void ResetValues()
        {
            // Reset the number of frames that the physics library has
            // processed since the last stats report
            m_numberPhysicsFrames = 0;

            m_timeDilation = 0;
            m_fps = 0;
            m_pfps = 0;
            m_agentUpdates = 0;
            m_objectUpdates = 0;
            //m_inPacketsPerSecond = 0;
            //m_outPacketsPerSecond = 0;
            m_unAckedBytes = 0;
            m_scriptLinesPerSecond = 0;

            m_frameMS = 0;
            m_agentMS = 0;
            m_netMS = 0;
            m_physicsMS = 0;
            m_imageMS = 0;
            m_otherMS = 0;
            m_scriptMS = 0;
            m_spareMS = 0;
        }

        # region methods called from Scene
        // The majority of these functions are additive
        // so that you can easily change the amount of
        // seconds in between sim stats updates

        public void AddTimeDilation(float td)
        {
            //float tdsetting = td;
            //if (tdsetting > 1.0f)
                //tdsetting = (tdsetting - (tdsetting - 0.91f));

            //if (tdsetting < 0)
                //tdsetting = 0.0f;
            m_timeDilation = td;
        }

        internal void CheckStatSanity()
        {
            if (m_rootAgents < 0 || m_childAgents < 0)
            {
                handlerStatsIncorrect = OnStatsIncorrect;
                if (handlerStatsIncorrect != null)
                {
                    handlerStatsIncorrect();
                }
            }
            if (m_rootAgents == 0 && m_childAgents == 0)
            {
                m_unAckedBytes = 0;
            }
        }

        public void AddFPS(int frames)
        {
            m_fps += frames;
        }

        public void AddPhysicsFPS(float frames)
        {
            m_pfps += frames;
        }

        public void AddObjectUpdates(int numUpdates)
        {
            m_objectUpdates += numUpdates;
        }

        public void AddAgentUpdates(int numUpdates)
        {
            m_agentUpdates += numUpdates;
        }

        public void AddInPackets(int numPackets)
        {
            m_inPacketsPerSecond = numPackets;
        }

        public void AddOutPackets(int numPackets)
        {
            m_outPacketsPerSecond = numPackets;
        }

        public void AddunAckedBytes(int numBytes)
        {
            m_unAckedBytes += numBytes;
            if (m_unAckedBytes < 0) m_unAckedBytes = 0;
        }

        public void addFrameMS(int ms)
        {
            m_frameMS += ms;

            // At the moment, we'll only report if a frame is over 120% of target, since commonly frames are a bit
            // longer than ideal due to the inaccuracy of the Sleep in Scene.Update() (which in itself is a concern).
            if (ms > SlowFramesStatReportThreshold)
                SlowFramesStat.Value++;
        }

        public void AddSpareMS(int ms)
        {
            m_spareMS += ms;
        }

        public void addNetMS(int ms)
        {
            m_netMS += ms;
        }

        public void addAgentMS(int ms)
        {
            m_agentMS += ms;
        }

        public void addPhysicsMS(int ms)
        {
            m_physicsMS += ms;
        }

        public void addImageMS(int ms)
        {
            m_imageMS += ms;
        }

        public void addOtherMS(int ms)
        {
            m_otherMS += ms;
        }

        public void AddScriptMS(int ms)
        {
            m_scriptMS += ms;
        }

        public void addPhysicsFrame(int frames)
        {
            // Add the number of physics frames to the correct total physics
            // frames
            m_numberPhysicsFrames += frames;
        }

        public void addFrameTimeMilliseconds(double total, double simulation,
            double physics, double network)
        {
            // Save the frame times from the current frame into the appropriate
            // arrays
            m_totalFrameTimeMilliseconds[m_nextLocation] = total;
            m_simulationFrameTimeMilliseconds[m_nextLocation] = simulation;
            m_physicsFrameTimeMilliseconds[m_nextLocation] = physics;
            m_networkFrameTimeMilliseconds[m_nextLocation] = network;

            // Update to the next location in the list
            m_nextLocation++;

            // Since the list will begin to overwrite the oldest frame values
            // first, the next location needs to loop back to the beginning of the
            // list whenever it reaches the end
            m_nextLocation = m_nextLocation % m_numberFramesStored;
        }

        public void AddPendingDownloads(int count)
        {
            m_pendingDownloads += count;

            if (m_pendingDownloads < 0)
                m_pendingDownloads = 0;

            //m_log.InfoFormat("[stats]: Adding {0} to pending downloads to make {1}", count, m_pendingDownloads);
        }

        public void addScriptLines(int count)
        {
            m_scriptLinesPerSecond += count;
        }

        public void AddPacketsStats(int inPackets, int outPackets, int unAckedBytes)
        {
            AddInPackets(inPackets);
            AddOutPackets(outPackets);
            AddunAckedBytes(unAckedBytes);
        }

        public void UpdateUsersLoggingIn(bool isLoggingIn)
        {
            // Determine whether the user has started logging in or has completed
            // logging into the region
            if (isLoggingIn)
            {
                // The user is starting to login to the region so increment the
                // number of users attempting to login to the region
                m_usersLoggingIn++;
            }
            else
            {
                // The user has finished logging into the region so decrement the
                // number of users logging into the region
                m_usersLoggingIn--;
            }
        }

        public void SetThreadCount(int inUseThreads)
        {
            // Save the new number of threads to our member variable to send to
            // the extra stats collector
            m_inUseThreads = inUseThreads;
        }

        #endregion

        public Dictionary<string, float> GetExtraSimStats()
        {
            lock (m_lastReportedExtraSimStats)
                return new Dictionary<string, float>(m_lastReportedExtraSimStats);
        }
    }
}


text:
package com.jasonlam604.stocktechnicals.util;

import java.math.BigDecimal;

public class NumberFormatter {

	private NumberFormatter() {
	}

	public static double round(double value) {
		return NumberFormatter.round(value, 2);
	}

	public static double round(double value, int numberOfDigitsAfterDecimalPoint) {
		BigDecimal bigDecimal = new BigDecimal(value);
		bigDecimal = bigDecimal.setScale(numberOfDigitsAfterDecimalPoint, BigDecimal.ROUND_HALF_UP);
		return bigDecimal.doubleValue();
	}

}


text:
import React from 'react';
import {
  Text,
  View,
  LayoutAnimation,
  Alert,
  ScrollView
} from 'react-native';

import {
  DragContainer,
  Draggable,
  DropZone
} from './index'

class MyDropZoneContent extends React.Component {
  componentWillReceiveProps({dragOver}) {
    if (dragOver !== this.props.dragOver) LayoutAnimation.easeInEaseOut();
  }
  render() {
    return <View style={{width: this.props.dragOver ? 110 : 100, height:  this.props.dragOver ? 110 : 100, backgroundColor: '#ddd', alignItems: 'center', justifyContent: 'center'}}>
      <View>
        <Text>{"LET GO"}</Text>
      </View>
    </View>
  }
}

class DeleteZone extends React.Component {
  componentWillReceiveProps({dragOver}) {
    if (dragOver !== this.props.dragOver) LayoutAnimation.easeInEaseOut();
  }
  render() {
    return <View style={{top: this.props.dragOver ? 0: -100, height: 100, backgroundColor: 'red', alignItems: 'center', justifyContent: 'center'}}>
      <View>
        <Text>{'DELETE'}</Text>
      </View>
    </View>
  }
}

class DraggyInner extends React.Component {
  render() {
    if (this.props.dragOver && !this.props.ghost && !this.props.dragging) {
      return <View style={{height: 100, width: 100, backgroundColor: 'green'}} />
    }
    let shadows = {shadowColor: 'black', shadowOffset: {width: 0, height: 20}, shadowOpacity: .5, shadowRadius: 20, opacity: .5};
    return <View style={[{height: 100, width: 100, backgroundColor: this.props.ghost ? '#777' : '#777'}, this.props.dragging ? shadows : null]} />
  }
}

class Draggy extends React.Component {
  render() {
    return <Draggable data="Whatevs" style={{margin: 7.5}}>
        <DropZone>
          <DraggyInner />
        </DropZone>
    </Draggable>
  }
}

class DragDropTest extends React.Component {
    constructor(props) {
        super(props);
        this.displayName = 'DragDropTest';
    }
    render() {
        return <DragContainer>
        <DropZone style={{position: 'absolute', top: 0, left: 0, right: 0, height: 100}} onDrop={() => Alert.alert('DELETE!!!')}>
          <DeleteZone />
        </DropZone>
        <View style={{flex: 1, padding: 20, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-around'}}>
             <DropZone onDrop={e => Alert.alert("Dropped it on area 1")}>
              <MyDropZoneContent />
            </DropZone>
            <DropZone onDrop={e => Alert.alert("Dropped it on area 2")}>
              <MyDropZoneContent />
            </DropZone>
          </View>
            <View style={{height: 115}}>
              <ScrollView horizontal={true}>
              <View style={{justifyContent: 'center', alignItems: 'flex-end', flexDirection: 'row'}}>
                <Draggy />
                <Draggy />
                <Draggy />
                <Draggy />
                <Draggy />
                <Draggy />
                <Draggy />
              </View>
              </ScrollView>
            </View>
        </DragContainer>
    }
}

export default DragDropTest;


text:
#include <aws/pinpoint/model/SimpleCondition.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace Pinpoint
{
namespace Model
{

SimpleCondition::SimpleCondition() :
    m_eventConditionHasBeenSet(false),
    m_segmentConditionHasBeenSet(false),
    m_segmentDimensionsHasBeenSet(false)
{
}

SimpleCondition::SimpleCondition(JsonView jsonValue) :
    m_eventConditionHasBeenSet(false),
    m_segmentConditionHasBeenSet(false),
    m_segmentDimensionsHasBeenSet(false)
{
  *this = jsonValue;
}

SimpleCondition& SimpleCondition::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("EventCondition"))
  {
    m_eventCondition = jsonValue.GetObject("EventCondition");

    m_eventConditionHasBeenSet = true;
  }

  if(jsonValue.ValueExists("SegmentCondition"))
  {
    m_segmentCondition = jsonValue.GetObject("SegmentCondition");

    m_segmentConditionHasBeenSet = true;
  }

  if(jsonValue.ValueExists("segmentDimensions"))
  {
    m_segmentDimensions = jsonValue.GetObject("segmentDimensions");

    m_segmentDimensionsHasBeenSet = true;
  }

  return *this;
}

JsonValue SimpleCondition::Jsonize() const
{
  JsonValue payload;

  if(m_eventConditionHasBeenSet)
  {
   payload.WithObject("EventCondition", m_eventCondition.Jsonize());

  }

  if(m_segmentConditionHasBeenSet)
  {
   payload.WithObject("SegmentCondition", m_segmentCondition.Jsonize());

  }

  if(m_segmentDimensionsHasBeenSet)
  {
   payload.WithObject("segmentDimensions", m_segmentDimensions.Jsonize());

  }

  return payload;
}

} // namespace Model
} // namespace Pinpoint
} // namespace Aws


text:
import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';

export default class Component extends React.Component {
  classNames(...args) {
    return classnames(args);
  }

  className(...args) {
    const { className } = this.props;
    return this.classNames.apply(this, args.concat([className]));
  }

  style(args) {
    const { style } = this.props;
    return Object.assign({}, args, style)
  }
}

Component.propTypes = {
  className: PropTypes.string,
  style: PropTypes.object
};


text:
<?php

namespace Monospice\SpicyRepositories\Laravel\Traits;

use Illuminate\Database\Eloquent\Builder as QueryBuilder;

/**
 * Defines methods for adding basic criteria to Repository classes
 *
 * @category Package
 * @package  Monospice\SpicyRepositories
 * @author   Cy Rossignol <cy@rossignols.me>
 * @license  See LICENSE file
 * @link     http://github.com/monospice/spicy-repositories
 */
trait BasicCriteria
{
    /**
     * The relationships of the model used for the withRelated() criterion
     *
     * @var array
     */
    protected $related;

    // Inherit Doc from Interfaces\BasicCriteria
    public function onlyCriterion(QueryBuilder $query, $columns)
    {
        $columns = static::getArgumentsArray($columns, func_get_args());

        return $query->select($columns);
    }

    // Inherit Doc from Interfaces\BasicCriteria
    public function excludeCriterion(QueryBuilder $query, $columns)
    {
        $columns = static::getArgumentsArray($columns, func_get_args());

        // Get the attributes of the model and filter out all but specified
        $schema = $query->getQuery()->getConnection()->getSchemaBuilder();
        $allColumns = $schema->getColumnListing($query->getModel()->getTable());
        $difference = array_diff($allColumns, $columns);

        return $query->select($difference);
    }

    // Inherit Doc from Interfaces\BasicCriteria
    public function limitCriterion(QueryBuilder $query, $limit)
    {
        return $query->limit($limit);
    }

    // Inherit Doc from Interfaces\BasicCriteria
    public function orderByCriterion(
        QueryBuilder $query,
        $column,
        $direction = 'asc'
    ) {
        return $query->orderBy($column, $direction);
    }

    // Inherit Doc from Interfaces\BasicCriteria
    public function withCriterion(QueryBuilder $query, $related)
    {
        $related = static::getArgumentsArray($related, func_get_args());

        return $query->with($related);
    }

    // Inherit Doc from Interfaces\BasicCriteria
    public function withRelatedCriterion(QueryBuilder $query)
    {
        if ($this->related === null) {
            throw new \RuntimeException(
                'No relationships defined in the repository. Eloquent does ' .
                'not support reading relationships from the Model. Related ' .
                'models must be defined in the $related property of the ' .
                'repository.'
            );
        }

        return $query->with($this->related);
    }

    /**
     * Get the array of dynamic arguments without the QueryBuilder argument
     *
     * @param mixed $array     Might be an array or the first passed argument
     * @param array $arguments The arguments passed to the method
     *
     * @return array The sanitized array of arguments
     */
    protected function getArgumentsArray($array, array $arguments)
    {
        if (is_array($array)) {
            return $array;
        }

        array_shift($arguments);

        return $arguments;
    }
}


text:
using namespace invlib;

template
<
    typename BackendType
>
void backend_test()
{
    using RealType   = typename BackendType::RealType;
    using MatrixType = Matrix<BackendType>;
    using VectorType = Vector<typename MatrixType::VectorType>;
    using MatrixReferenceType = Matrix<MatrixArchetype<RealType>>;
    using VectorReferenceType = Vector<VectorArchetype<RealType>>;

    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis_m(1, 10);
    std::uniform_int_distribution<> dis_n(1, 10);

    size_t m = dis_m(gen);
    size_t n = dis_n(gen);

    VectorType a = VectorData<RealType>::random(n);
    VectorType b = VectorData<RealType>::random(n);

    VectorReferenceType a_ref(static_cast<VectorData<RealType>>(a));
    VectorReferenceType b_ref(static_cast<VectorData<RealType>>(b));

    // Vector addition.

    a.accumulate(b);
    a_ref.accumulate(b_ref);

    VectorData<RealType> a_base(a);
    VectorData<RealType> a_ref_base(a_ref);

    auto error = maximum_error(a_base, a_ref_base);
    BOOST_TEST((error < 1e-8), "Error: accumulate, maximum difference = "
               << error);

    // Vector difference.

    a.subtract(b);
    a_ref.subtract(b_ref);

    a_base     = a;
    a_ref_base = a_ref;

    error = maximum_error<VectorData<RealType>>(a_base, a_ref_base);
    BOOST_TEST((error < 1e-8), "Error: subtract, maximum difference = "
               << error);

    // Addition of a scalar.

    a.accumulate(1.0);
    a_ref.accumulate(1.0);

    a_base     = a;
    a_ref_base = a_ref;

    error = maximum_error<VectorData<RealType>>(a_base, a_ref_base);
    BOOST_TEST((error < 1e-8), "Error: accumulate scalar, maximum difference = "
               << error);

    // Scaling of a vector.

    a.scale(3.142);
    a_ref.scale(3.142);

    a_base     = a;
    a_ref_base = a_ref;

    error = maximum_error<VectorData<RealType>>(a_base, a_ref_base);
    BOOST_TEST((error < 1e-8), "Error: scale, maximum difference = "
               << error);

    // Dot product.

    RealType d = dot(a,b);
    RealType d_ref = dot(a_ref, b_ref);

    error = std::abs(d - d_ref) / std::max(std::abs(d), std::abs(d_ref));
    BOOST_TEST((error < 1e-8), "Error: dot product, maximum difference = "
               << error);

    // Norm.

    RealType norm = b.norm();
    RealType norm_ref = b_ref.norm();

    error = std::abs(norm - norm_ref) / std::max(std::abs(d), std::abs(d_ref));
    BOOST_TEST((error < 1e-8), "Error: norm, maximum difference = "
               << error);

    // Matrix Vector Product.

    MatrixReferenceType A_ref   = SparseData<RealType>::random(m, n);
    SparseData<RealType> A_base(A_ref);
    MatrixType A(A_base);

    VectorType c = A * a;
    VectorReferenceType c_ref = A_ref * a_ref;

    VectorData<RealType> c_base(c);
    VectorData<RealType> c_ref_base(c_ref);
    error = maximum_error(c_base, c_ref_base);

    BOOST_TEST((error < 1e-8), "Error: matrix vector product, maximum difference = "
               << error);

    // Transposed Matrix Vector Product.

    a     = transp(A) * c;
    a_ref = transp(A_ref) * c_ref;

    c_base     = a;
    c_ref_base = a_ref;

    error = maximum_error(c_base, c_ref_base);
    BOOST_TEST((error < 1e-8), "Error: transposed matrix vector product,"
                               " maximum difference = " << error);
}

#ifdef CUDA
using CudaSparseCR = CudaSparse<double, Representation::CompressedRows>;
using CudaSparseCC = CudaSparse<double, Representation::CompressedColumns>;
using CudaSparseHY = CudaSparse<double, Representation::Hybrid>;
using cuda_types   = boost::mpl::list<CudaSparseCR, CudaSparseCC, CudaSparseHY>;
#else
using cuda_types   = boost::mpl::list<>;
#endif

#ifdef MKL
using MklSparseCO  = MklSparse<double, Representation::Coordinates>;
using MklSparseCR  = MklSparse<double, Representation::CompressedRows>;
using MklSparseCC  = MklSparse<double, Representation::CompressedColumns>;
using MklSparseHY  = MklSparse<double, Representation::Hybrid>;
using mkl_types    = boost::mpl::list<MklSparseCO, MklSparseCR, MklSparseCC, MklSparseHY>;
#else
using mkl_types   = boost::mpl::list<>;
#endif

using matrix_types = typename boost::mpl::insert_range<
    cuda_types,
    typename boost::mpl::end<cuda_types>::type,
    mkl_types>::type;

BOOST_AUTO_TEST_CASE_TEMPLATE(backend, T, matrix_types)
{
    size_t ntests = 1000;
    for (unsigned int i = 0; i < ntests; i++)
    {
        backend_test<T>();
    }
}


text:
package org.sagebionetworks.bridge.android.di;

import java.util.concurrent.TimeUnit;

import javax.inject.Named;
import javax.net.SocketFactory;

import dagger.Module;
import dagger.Provides;
import okhttp3.OkHttpClient;

/**
 * Created by liujoshua on 2/22/2018.
 */
@Module
public class S3Module {
    @Provides
    @Named("s3OkHttp3Client")
    @BridgeStudyScope
    OkHttpClient getS3OkHttp3Client(SocketFactory socketFactory) {
        return new OkHttpClient.Builder()
                .socketFactory(socketFactory)
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true).build();
    }
}


text:
package es.um.nosql.streaminginference.json2dbschema.util.abstractjson;

public interface IAJBoolean	extends IAJElement {

}


text:
Simple little gem that adds mediumable functionality to your models

## Installation

Add this line to your application's Gemfile:

    gem 'mediumable'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install mediumable

## Usage

Just install and use acts_as_mediumable in any model you wish to add media to.

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
Copyright (C) 2006, 2008 Mark Joshi

This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/

QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license.  You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

#ifndef quantlib_market_model_pathwise_multi_product_hpp
#define quantlib_market_model_pathwise_multi_product_hpp

#include <ql/types.hpp>
#include <vector>
#include <memory>

namespace QuantLib {

    class EvolutionDescription;
    class CurveState;

    //! market-model pathwise product
    /*! This is the abstract base class that encapsulates the notion of a
    product: it contains the information that would be in the termsheet
    of the product.

    It's useful to have it be able to do several products simultaneously.
    The products would have to have the same underlying rate times of
    course. The class is therefore really encapsulating the notion of a
    multi-product.

    For each time evolved to, it generates the cash flows associated to
    that time for the state of the yield curve. If one was doing a
    callable product then this would encompass the product and its
    exercise strategy.

    This class differs from market-model multi-product in that it also returns the
    derivative of the pay-off with respect to each forward rate

    */

    class MarketModelPathwiseMultiProduct
    {
    public:
        struct CashFlow {
            Size timeIndex;
            std::vector<Real > amount;
        };
        virtual ~MarketModelPathwiseMultiProduct() {}

        virtual std::vector<Size> suggestedNumeraires() const = 0;
        virtual const EvolutionDescription& evolution() const = 0;
        virtual std::vector<Time> possibleCashFlowTimes() const = 0;
        virtual Size numberOfProducts() const = 0;
        virtual Size maxNumberOfCashFlowsPerProductPerStep() const = 0;

        virtual bool alreadyDeflated() const =0;

        //! during simulation put product at start of path
        virtual void reset() = 0;
        //! return value indicates whether path is finished, TRUE means done
        virtual bool nextTimeStep(
            const CurveState& currentState,
            std::vector<Size>& numberCashFlowsThisStep,
            std::vector<std::vector<MarketModelPathwiseMultiProduct::CashFlow> >& cashFlowsGenerated) = 0;
        //! returns a newly-allocated copy of itself
        virtual std::auto_ptr<MarketModelPathwiseMultiProduct> clone() const = 0;
    };

}

#endif