text:
.DEFAULT_GOAL := sketch

##
## Useful paths, constants, etc.
##

ifeq ($(LIB_MAPLE_HOME),)
SRCROOT := .
else
SRCROOT := $(LIB_MAPLE_HOME)
endif
BUILD_PATH = build
LIBMAPLE_PATH := $(SRCROOT)/libmaple
WIRISH_PATH := $(SRCROOT)/wirish
SUPPORT_PATH := $(SRCROOT)/support
LIBRARIES_PATH := $(SRCROOT)/libraries
# Support files for linker
LDDIR := $(SUPPORT_PATH)/ld
# Support files for this Makefile
MAKEDIR := $(SUPPORT_PATH)/make
BOARD_INCLUDE_DIR := $(MAKEDIR)/board-includes

##
## Target-specific configuration.  This determines some compiler and
## linker options/flags.
##

# Try "make help" for more information on BOARD and MEMORY_TARGET;
# these default to a Maple Flash build.
BOARD ?= maple
MEMORY_TARGET ?= flash

# Chooses the bootloader, available: maple and robotis
BOOTLOADER ?= maple

# This is the serial port used by robotis bootloader
ROBOTIS_PORT ?= /dev/ttyACM0

# $(BOARD)- and $(MEMORY_TARGET)-specific configuration
include $(MAKEDIR)/target-config.mk

##
## Build rules and useful templates
##

include $(MAKEDIR)/build-rules.mk
include $(MAKEDIR)/build-templates.mk

##
## Compilation flags
##

# FIXME: the following allows for deprecated include style, e.g.:
#     #include "libmaple.h"
# or
#     #include "wirish.h"
# It slows compilation noticeably; remove after 1 release.
TARGET_FLAGS    += -I$(LIBMAPLE_PATH)/include/libmaple                       \
                   -I$(WIRISH_PATH)/include/wirish
TARGET_FLAGS += -I$(LIBRARIES_PATH) # for internal lib. includes, e.g. <Wire/WireBase.h>
GLOBAL_CFLAGS   := -Os -g3 -gdwarf-2 -nostdlib \
                   -ffunction-sections -fdata-sections \
		   -Wl,--gc-sections $(TARGET_FLAGS) \
		   -DBOOTLOADER_$(BOOTLOADER)

GLOBAL_CXXFLAGS := -fno-rtti -fno-exceptions -Wall $(TARGET_FLAGS)
GLOBAL_ASFLAGS  := -x assembler-with-cpp $(TARGET_FLAGS)
LDFLAGS  = $(TARGET_LDFLAGS) $(TOOLCHAIN_LDFLAGS) -mcpu=cortex-m3 -mthumb \
           -Xlinker --gc-sections \
           -Xassembler --march=armv7-m -Wall
#          -Xlinker --print-gc-sections \

##
## Set all submodules here
##

LIBMAPLE_MODULES += $(SRCROOT)/libmaple
LIBMAPLE_MODULES += $(SRCROOT)/libmaple/usb   # The USB module is kept separate
LIBMAPLE_MODULES += $(LIBMAPLE_MODULE_SERIES) # STM32 series submodule in libmaple
LIBMAPLE_MODULES += $(SRCROOT)/wirish

# Official libraries:
LIBMAPLE_MODULES += $(SRCROOT)/libraries/Servo
LIBMAPLE_MODULES += $(SRCROOT)/libraries/LiquidCrystal
LIBMAPLE_MODULES += $(SRCROOT)/libraries/Wire
# Experimental libraries:
#LIBMAPLE_MODULES += $(SRCROOT)/libraries/FreeRTOS
LIBMAPLE_MODULES += $(SRCROOT)/libraries/kaa
#LIBMAPLE_MODULES += $(SRCROOT)/libraries/esp8266
#LIBMAPLE_MODULES += $(SRCROOT)/libraries/cc3000

# User modules:
ifneq ($(USER_MODULES),)
LIBMAPLE_MODULES += $(USER_MODULES)
endif

# Call each module's rules.mk:
$(foreach m,$(LIBMAPLE_MODULES),$(eval $(call LIBMAPLE_MODULE_template,$(m))))

##
## Targets
##

# main target
include $(SRCROOT)/build-targets.mk

.PHONY: install sketch clean help cscope tags ctags ram flash jtag doxygen mrproper list-boards

# Target upload commands
# USB ID for DFU upload -- FIXME: do something smarter with this
BOARD_USB_VENDOR_ID  := 1EAF
BOARD_USB_PRODUCT_ID := 0003

ifeq ($(BOOTLOADER),maple)
UPLOAD_ram   := $(SUPPORT_PATH)/scripts/reset.py && \
                sleep 1                  && \
                $(DFU) -a0 -d $(BOARD_USB_VENDOR_ID):$(BOARD_USB_PRODUCT_ID) -D $(BUILD_PATH)/$(BOARD).bin -R
UPLOAD_flash := $(SUPPORT_PATH)/scripts/reset.py && \
                sleep 1                  && \
                $(DFU) -a1 -d $(BOARD_USB_VENDOR_ID):$(BOARD_USB_PRODUCT_ID) -D $(BUILD_PATH)/$(BOARD).bin -R
endif

ifeq ($(BOOTLOADER),robotis)
UPLOAD_flash := $(SUPPORT_PATH)/scripts/robotis-loader.py $(ROBOTIS_PORT) $(BUILD_PATH)/$(BOARD).bin
endif

# Conditionally upload to whatever the last build was
install: INSTALL_TARGET = $(shell cat $(BUILD_PATH)/build-type 2>/dev/null)
install: $(BUILD_PATH)/$(BOARD).bin
	@echo "Install target:" $(INSTALL_TARGET)
	$(UPLOAD_$(INSTALL_TARGET))

# Force a rebuild if the target changed
PREV_BUILD_TYPE = $(shell cat $(BUILD_PATH)/build-type 2>/dev/null)
build-check:
ifneq ($(PREV_BUILD_TYPE), $(MEMORY_TARGET))
	$(shell rm -rf $(BUILD_PATH))
endif

sketch: build-check MSG_INFO $(BUILD_PATH)/$(BOARD).bin $(BUILD_PATH)/$(BOARD).hex

clean:
	rm -rf build

mrproper: clean
	rm -rf doxygen

help:
	@echo ""
	@echo "Basic usage (BOARD defaults to maple):"
	@echo "    $$ cp your-main.cpp main.cpp"
	@echo "    $$ make BOARD=your_board"
	@echo "    $$ make BOARD=your_board install"
	@echo ""
	@echo "(Multiple source files? Link with libmaple.a (\`$$ make library')"
	@echo "or hack build-targets.mk appropriately.)"
	@echo ""
	@echo "Important targets:"
	@echo "    sketch:   Compile for BOARD to MEMORY_TARGET (default)."
	@echo "    install:  Compile and upload over USB using Maple bootloader"
	@echo ""
	@echo "You *must* set BOARD if not compiling for Maple (e.g."
	@echo "use BOARD=maple_mini for mini, etc.), and MEMORY_TARGET"
	@echo "if not compiling to Flash. Run \`$$ make list-boards' for"
	@echo "a list of all boards."
	@echo ""
	@echo "Valid MEMORY_TARGETs (default=flash):"
	@echo "    ram:    Compile to RAM (doesn't touch Flash)"
	@echo "    flash:  Compile to Flash (for Maple bootloader)"
	@echo "    jtag:   Compile for JTAG/SWD upload (overwrites bootloader)"
	@echo ""
	@echo "Other targets:"
	@echo "    clean: Remove all build and object files"
	@echo "    doxygen: Build Doxygen HTML and XML documentation"
	@echo "    help: Show this message"
	@echo "    mrproper: Remove all generated files"
	@echo ""

cscope:
	rm -rf cscope.*
	find . -name '*.[hcS]' -o -name '*.cpp' | xargs cscope -b

tags:
	etags `find . -name "*.c" -o -name "*.cpp" -o -name "*.h"`
	@echo "Made TAGS file for EMACS code browsing"

ctags:
	ctags-exuberant -R .
	@echo "Made tags file for VIM code browsing"

ram:
	@$(MAKE) MEMORY_TARGET=ram --no-print-directory sketch

flash:
	@$(MAKE) MEMORY_TARGET=flash --no-print-directory sketch

jtag:
	@$(MAKE) MEMORY_TARGET=jtag --no-print-directory sketch

doxygen:
	doxygen $(SUPPORT_PATH)/doxygen/Doxyfile

# This output is kind of ugly, but I don't understand make very well.
list-boards:
	@echo " $(addsuffix "\\n",$(basename $(notdir $(wildcard $(BOARD_INCLUDE_DIR)/*.mk))))"


text:
#include "MnHesse.h"
#include "MnUserParameterState.h"
#include "MnUserFcn.h"
#include "FCNBase.h"
#include "MnPosDef.h"
#include "HessianGradientCalculator.h"
#include "Numerical2PGradientCalculator.h"
#include "InitialGradientCalculator.h"
#include "MinimumState.h"
#include "VariableMetricEDMEstimator.h"

MnUserParameterState MnHesse::operator()(const FCNBase& fcn, const std::vector<double>& par, const std::vector<double>& err, unsigned int maxcalls) const {
  return (*this)(fcn, MnUserParameterState(par, err), maxcalls);
}

MnUserParameterState MnHesse::operator()(const FCNBase& fcn, const std::vector<double>& par, const std::vector<double>& cov, unsigned int nrow, unsigned int maxcalls) const {
  return (*this)(fcn, MnUserParameterState(par, cov, nrow), maxcalls);
}

MnUserParameterState MnHesse::operator()(const FCNBase& fcn, const std::vector<double>& par, const MnUserCovariance& cov, unsigned int maxcalls) const {
  return (*this)(fcn, MnUserParameterState(par, cov), maxcalls);
}

MnUserParameterState MnHesse::operator()(const FCNBase& fcn, const MnUserParameters& par, unsigned int maxcalls) const {
  return (*this)(fcn, MnUserParameterState(par), maxcalls);
}

MnUserParameterState MnHesse::operator()(const FCNBase& fcn, const MnUserParameters& par, const MnUserCovariance& cov, unsigned int maxcalls) const {
  return (*this)(fcn, MnUserParameterState(par, cov), maxcalls);
}

MnUserParameterState MnHesse::operator()(const FCNBase& fcn, const MnUserParameterState& state, unsigned int maxcalls) const {

  unsigned int n = state.variableParameters();
  MnUserFcn mfcn(fcn, state.trafo());
  MnAlgebraicVector x(n);
  for(unsigned int i = 0; i < n; i++) x(i) = state.intParameters()[i];
  double amin = mfcn(x);
  Numerical2PGradientCalculator gc(mfcn, state.trafo(), theStrategy);
  MinimumParameters par(x, amin);
  FunctionGradient gra = gc(par);
  MinimumState tmp = (*this)(mfcn, MinimumState(par, MinimumError(MnAlgebraicSymMatrix(n), 1.), gra, state.edm(), state.nfcn()), state.trafo(), maxcalls);

  return MnUserParameterState(tmp, fcn.up(), state.trafo());
}

MinimumState MnHesse::operator()(const MnFcn& mfcn, const MinimumState& st, const MnUserTransformation& trafo, unsigned int maxcalls) const {

  const MnMachinePrecision& prec = trafo.precision();
  // make sure starting at the right place
  double amin = mfcn(st.vec());
  double aimsag = sqrt(prec.eps2())*(fabs(amin)+mfcn.up());

  // diagonal elements first

  unsigned int n = st.parameters().vec().size();
  if(maxcalls == 0) maxcalls = 200 + 100*n + 5*n*n;

  MnAlgebraicSymMatrix vhmat(n);
  MnAlgebraicVector g2 = st.gradient().g2();
  MnAlgebraicVector gst = st.gradient().gstep();
  MnAlgebraicVector grd = st.gradient().grad();
  MnAlgebraicVector dirin = st.gradient().gstep();
  MnAlgebraicVector yy(n);
  if(st.gradient().isAnalytical()) {
    InitialGradientCalculator igc(mfcn, trafo, theStrategy);
    FunctionGradient tmp = igc(st.parameters());
    gst = tmp.gstep();
    dirin = tmp.gstep();
    g2 = tmp.g2();
  }

  MnAlgebraicVector x = st.parameters().vec();

  for(unsigned int i = 0; i < n; i++) {

    double xtf = x(i);
    double dmin = 8.*prec.eps2()*(fabs(xtf) + prec.eps2());
    double d = fabs(gst(i));
    if(d < dmin) d = dmin;

    for(unsigned int icyc = 0; icyc < ncycles(); icyc++) {
      double sag = 0.;
      double fs1 = 0.;
      double fs2 = 0.;
      for(unsigned int multpy = 0; multpy < 5; multpy++) {
	x(i) = xtf + d;
	fs1 = mfcn(x);
	x(i) = xtf - d;
	fs2 = mfcn(x);
	x(i) = xtf;
	sag = 0.5*(fs1+fs2-2.*amin);
	if(sag > prec.eps2()) goto L30; // break;
	if(trafo.parameter(i).hasLimits()) {
	  if(d > 0.5) goto L26;
	  d *= 10.;
	  if(d > 0.5) d = 0.51;
	  continue;
	}
	d *= 10.;
      }

L26:
      std::cout<<"MnHesse: 2nd derivative zero for parameter "<<i<<std::endl;
      std::cout<<"MnHesse fails and will return diagonal matrix "<<std::endl;

      for(unsigned int j = 0; j < n; j++) {
	double tmp = g2(j) < prec.eps2() ? 1. : 1./g2(j);
	vhmat(j,j) = tmp < prec.eps2() ? 1. : tmp;
      }

      return MinimumState(st.parameters(), MinimumError(vhmat, MinimumError::MnHesseFailed()), st.gradient(), st.edm(), st.nfcn()+mfcn.numOfCalls());

L30:
      double g2bfor = g2(i);
      g2(i) = 2.*sag/(d*d);
      grd(i) = (fs1-fs2)/(2.*d);
      gst(i) = d;
      dirin(i) = d;
      yy(i) = fs1;
      double dlast = d;
      d = sqrt(2.*aimsag/fabs(g2(i)));
      if(trafo.parameter(i).hasLimits()) d = std::min(0.5, d);
      if(d < dmin) d = dmin;

      // see if converged
      if(fabs((d-dlast)/d) < tolerstp()) break;
      if(fabs((g2(i)-g2bfor)/g2(i)) < tolerg2()) break;
      d = std::min(d, 10.*dlast);
      d = std::max(d, 0.1*dlast);
    }
    vhmat(i,i) = g2(i);
    if(mfcn.numOfCalls() - st.nfcn() > maxcalls) {
      std::cout<<"MnHesse: maximum number of allowed function calls exhausted."<<std::endl;
      std::cout<<"MnHesse fails and will return diagonal matrix "<<std::endl;
      for(unsigned int j = 0; j < n; j++) {
	double tmp = g2(j) < prec.eps2() ? 1. : 1./g2(j);
	vhmat(j,j) = tmp < prec.eps2() ? 1. : tmp;
      }

      return MinimumState(st.parameters(), MinimumError(vhmat, MinimumError::MnHesseFailed()), st.gradient(), st.edm(), st.nfcn()+mfcn.numOfCalls());
    }

  }

  if(theStrategy.strategy() > 0) {
    // refine first derivative
    HessianGradientCalculator hgc(mfcn, trafo, theStrategy);
    FunctionGradient gr = hgc(st.parameters(), FunctionGradient(grd, g2, gst));
    grd = gr.grad();
  }

  //off-diagonal elements
  for(unsigned int i = 0; i < n; i++) {
    x(i) += dirin(i);
    for(unsigned int j = i+1; j < n; j++) {
      x(j) += dirin(j);
      double fs1 = mfcn(x);
      double elem = (fs1 + amin - yy(i) - yy(j))/(dirin(i)*dirin(j));
      vhmat(i,j) = elem;
      x(j) -= dirin(j);
    }
    x(i) -= dirin(i);
  }

  //verify if matrix pos-def (still 2nd derivative)
  MinimumError tmp = MnPosDef()(MinimumError(vhmat,1.), prec);
  vhmat = tmp.invHessian();
  int ifail = invert(vhmat);
  if(ifail != 0) {
    std::cout<<"MnHesse: matrix inversion fails!"<<std::endl;
    std::cout<<"MnHesse fails and will return diagonal matrix."<<std::endl;

    MnAlgebraicSymMatrix tmpsym(vhmat.nrow());
    for(unsigned int j = 0; j < n; j++) {
      double tmp = g2(j) < prec.eps2() ? 1. : 1./g2(j);
      tmpsym(j,j) = tmp < prec.eps2() ? 1. : tmp;
    }

    return MinimumState(st.parameters(), MinimumError(tmpsym, MinimumError::MnHesseFailed()), st.gradient(), st.edm(), st.nfcn()+mfcn.numOfCalls());
  }

  FunctionGradient gr(grd, g2, gst);

  if(tmp.isMadePosDef()) {
    std::cout<<"MnHesse: matrix is invalid!"<<std::endl;
    std::cout<<"MnHesse: matrix is not pos. def.!"<<std::endl;
    std::cout<<"MnHesse: matrix was forced pos. def."<<std::endl;
    return MinimumState(st.parameters(), MinimumError(vhmat, MinimumError::MnMadePosDef()), gr, st.edm(), mfcn.numOfCalls());
  }

  //calculate edm
  MinimumError err(vhmat, 0.);
  VariableMetricEDMEstimator estim;
  double edm = estim.estimate(gr, err);

  return MinimumState(st.parameters(), err, gr, edm, mfcn.numOfCalls());
}

/*
MinimumError MnHesse::hessian(const MnFcn& mfcn, const MinimumState& st, const MnUserTransformation& trafo) const {

  const MnMachinePrecision& prec = trafo.precision();
  // make sure starting at the right place
  double amin = mfcn(st.vec());
//   if(fabs(amin - st.fval()) > prec.eps2()) std::cout<<"function value differs from amin  by "<<amin - st.fval()<<std::endl;

  double aimsag = sqrt(prec.eps2())*(fabs(amin)+mfcn.up());

  // diagonal elements first

  unsigned int n = st.parameters().vec().size();
  MnAlgebraicSymMatrix vhmat(n);
  MnAlgebraicVector g2 = st.gradient().g2();
  MnAlgebraicVector gst = st.gradient().gstep();
  MnAlgebraicVector grd = st.gradient().grad();
  MnAlgebraicVector dirin = st.gradient().gstep();
  MnAlgebraicVector yy(n);
  MnAlgebraicVector x = st.parameters().vec();

  for(unsigned int i = 0; i < n; i++) {

    double xtf = x(i);
    double dmin = 8.*prec.eps2()*fabs(xtf);
    double d = fabs(gst(i));
    if(d < dmin) d = dmin;
    for(int icyc = 0; icyc < ncycles(); icyc++) {
      double sag = 0.;
      double fs1 = 0.;
      double fs2 = 0.;
      for(int multpy = 0; multpy < 5; multpy++) {
	x(i) = xtf + d;
	fs1 = mfcn(x);
	x(i) = xtf - d;
	fs2 = mfcn(x);
	x(i) = xtf;
	sag = 0.5*(fs1+fs2-2.*amin);
	if(sag > prec.eps2()) break;
	if(trafo.parameter(i).hasLimits()) {
	  if(d > 0.5) {
	    std::cout<<"second derivative zero for parameter "<<i<<std::endl;
	    std::cout<<"return diagonal matrix "<<std::endl;
	    for(unsigned int j = 0; j < n; j++) {
	      vhmat(j,j) = (g2(j) < prec.eps2() ? 1. : 1./g2(j));
 	      return MinimumError(vhmat, 1., false);
	    }
	  }
	  d *= 10.;
	  if(d > 0.5) d = 0.51;
	  continue;
	}
	d *= 10.;
      }
      if(sag < prec.eps2()) {
	std::cout<<"MnHesse: internal loop exhausted, return diagonal matrix."<<std::endl;
	for(unsigned int i = 0; i < n; i++)
	  vhmat(i,i) = (g2(i) < prec.eps2() ? 1. : 1./g2(i));
	return MinimumError(vhmat, 1., false);
      }
      double g2bfor = g2(i);
      g2(i) = 2.*sag/(d*d);
      grd(i) = (fs1-fs2)/(2.*d);
      gst(i) = d;
      dirin(i) = d;
      yy(i) = fs1;
      double dlast = d;
      d = sqrt(2.*aimsag/fabs(g2(i)));
      if(trafo.parameter(i).hasLimits()) d = std::min(0.5, d);
      if(d < dmin) d = dmin;

      // see if converged
      if(fabs((d-dlast)/d) < tolerstp()) break;
      if(fabs((g2(i)-g2bfor)/g2(i)) < tolerg2()) break;
      d = std::min(d, 10.*dlast);
      d = std::max(d, 0.1*dlast);
    }
    vhmat(i,i) = g2(i);
  }

  //off-diagonal elements
  for(unsigned int i = 0; i < n; i++) {
    x(i) += dirin(i);
    for(unsigned int j = i+1; j < n; j++) {
      x(j) += dirin(j);
      double fs1 = mfcn(x);
      double elem = (fs1 + amin - yy(i) - yy(j))/(dirin(i)*dirin(j));
      vhmat(i,j) = elem;
      x(j) -= dirin(j);
    }
    x(i) -= dirin(i);
  }

  return MinimumError(vhmat, 0.);
}
*/

redpajama_set_name: RedPajamaGithub


text:
import actions from './actions'
import countTimer from './countTimer'
const root = Object.assign({}, {...actions, ...countTimer})
export default root


text: joyent production practices http://www.joyent.com/developers/node


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>setAll method - ImmutableListMixin class - polymer_app_layout.behaviors library - Dart API</title>

    <base href="../..">

    <link href='https://fonts.googleapis.com/css?family=Source+Code+Pro|Roboto:500,400italic,300,400' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="static-assets/prettify.css">
    <link rel="stylesheet" href="static-assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="static-assets/styles.css">

    <meta name="description" content="API docs for the setAll method from the ImmutableListMixin class, for the Dart programming language.">
    <link rel="icon" href="static-assets/favicon.png">

            <button id="sidenav-left-toggle" type="button"> </button>

polymer_app_layout_template

polymer_app_layout.behaviors

ImmutableListMixin

setAll

setAll

polymer_app_layout_template

polymer_app_layout.behaviors

ImmutableListMixin

setAll

method
 setAll

Source

polymer_app_layout_template

polymer_app_layout.behaviors

ImmutableListMixin

Properties

first

isEmpty

isNotEmpty

iterator

last

length

reversed

single

Constructors

ImmutableListMixin

Operators

operator []

operator []=

Methods

add

addAll

any

asMap

clear

contains

elementAt

every

expand

fillRange

firstWhere

fold

forEach

getRange

indexOf

insert

insertAll

join

lastIndexOf

lastWhere

map

reduce

remove

removeAt

removeLast

removeRange

removeWhere

replaceRange

retainWhere

setAll

setRange

shuffle

singleWhere

skip

skipWhile

sort

sublist

take

takeWhile

toList

toSet

where

            void
            setAll(

                int index,
Iterable<E> iterable

            )

Overwrites objects of this with the objects of iterable, starting
at position index in this list.

List<String> list = 'a', 'b', 'c';
list.setAll(1, 'bee', 'sea');
list.join(', '); // 'a, bee, sea'

This operation does not increase the length of this.

The index must be non-negative and no greater than length.

The iterable must not have more elements than what can fit from index
to length.

If iterable is based on this list, its values may change /during/ the
setAll operation.

Source

void setAll(int index, Iterable<E> iterable) {
  throw new UnsupportedError("Cannot modify an immutable List.");
}

                  polymer_app_layout_template 0.1.0 api docs

                •

                •

                  cc license


text:
// Graph Engine
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
#include <os/os.h>
#include "Trinity/Collections/List.h"
#include "Trinity/Configuration/TrinityConfig.h"
#include "BackgroundThread/BackgroundThread.h"
#include "LogAutoFlushTask.h"
#include <corelib>
#include <io>
#include <atomic>
#include <thread>
#include <mutex>
#include <deque>

#if defined(TRINITY_PLATFORM_WINDOWS)
#include <DbgHelp.h>
#endif

#include "Log.h"

using namespace Trinity;
using namespace Trinity::IO;

namespace Trinity
{
    namespace Diagnostics
    {
        const size_t MAX_LOG_ENTRY_COUNT = 1 << 20;
        typedef struct
        {
            u16char* logMessage;
            int64_t  logTimestamp;
            LogLevel logLevel;
        } LOG_ENTRY, *PLOG_ENTRY;
        // static data and methods

        static std::mutex           s_LogMutex;
        static std::mutex           s_LogInitMutex;
        static std::deque<LOG_ENTRY>s_LogEntries;
        static LogLevel             s_CurrentLogLevel = LogLevel::Info;
        static String               s_LogLevelName[7]  { "OFF", "Fatal", "Error", "Warning", "Info", "Debug", "Verbose", };
        static String               s_LoggingPrefix[7] { "[ OFF     ] ", "[ FATAL   ] ", "[ ERROR   ] ", "[ WARNING ] ", "[ INFO    ] ", "[ DEBUG   ] ", "[ VERBOSE ] " };
        static String               s_LogFileName;
        static StreamWriter         s_LogStream;
        static bool                 s_EchoOnConsole = true;
        static bool                 s_initialized = false;

        static void lock()
        {
            s_LogMutex.lock();
        }

        static void unlock()
        {
            s_LogMutex.unlock();
        }

        void InitializeLogger()
        {
            s_LogInitMutex.lock();
            if (s_initialized)
            {
                s_LogInitMutex.unlock();
                return;
            }
            String log_path = TrinityConfig::LogDirectory();

            //If two instances are started at the same time, one of them would fail to open log file.
        DetermineLogFileName:
            s_LogFileName = Path::Combine(log_path, "trinity-[" + DateTime::Now().ToStringForFilename() + "].log");
            s_LogStream.Open(s_LogFileName);
            if (!s_LogStream.Good())
            {
                if (File::Exists(s_LogFileName))
                {
                    WriteLine(LogLevel::Warning, "Logger: log file {0} already exists, waiting for one second before generating a new log file name.", s_LogFileName);
                    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
                    goto DetermineLogFileName;
                }
                else
                {
                    WriteLine(LogLevel::Error, "Logger: cannot open log file {0} for write, logging to file is disabled.", s_LogFileName);
                }
            }
            WriteLine(LogLevel::Info, "Trinity Assembly Path: {0}", Path::MyAssemblyPath());
            BackgroundThread::TaskScheduler::AddTask(new LogAutoFlushTask());
            s_initialized = true;
            s_LogInitMutex.unlock();
        }

        static String LogLevelToString(LogLevel level)
        {
            return s_LogLevelName[level];
        }

        static void _flush_if_necessary(LogLevel level)
        {
            if (level <= LogLevel::Info)
                s_LogStream.Flush();
        }

        // Caller holds s_LogMutex
        static inline void _post_log_entry(const LogLevel logLevel, const String& msg, DateTime& time)
        {
            // Drop oldest entries if the capacity limit is reached
            while (s_LogEntries.size() >= MAX_LOG_ENTRY_COUNT)
            {
                //free msg buffer
                free(s_LogEntries.front().logMessage);
                s_LogEntries.pop_front();
            }

            auto wchar_arr = msg.ToWcharArray();
            u16char *buf   = (u16char*)malloc(sizeof(u16char) * wchar_arr.Length());
            std::copy(wchar_arr.begin(), wchar_arr.end(), buf);

            s_LogEntries.emplace_back(LOG_ENTRY
            {
                buf,
                time.Timestamp(),
                logLevel,
            });
        }

        //////////////////////////////

        // Interface implementations

        void PrintCallStack(void)
        {
#if defined(TRINITY_PLATFORM_WINDOWS)
            uint32_t  i;
            void         * stack[100];
            unsigned short frames;
            SYMBOL_INFO  * symbol;
            HANDLE         process;

            process = GetCurrentProcess();
            SymInitialize(process, NULL, TRUE);

            frames = CaptureStackBackTrace(0, 100, stack, NULL);
            symbol = (SYMBOL_INFO *)calloc(sizeof(SYMBOL_INFO) + 256 * sizeof(char), 1);

            if (symbol == NULL)
            {
                Trinity::IO::Console::WriteLine("Cannot calloc symbol buffer");
                return;
            }

            symbol->MaxNameLen = 255;
            symbol->SizeOfStruct = sizeof(SYMBOL_INFO);

            lock();
            for (i = 1 /*skip myself*/; i < frames; i++)
            {
                SymFromAddr(process, (DWORD64)(stack[i]), 0, symbol);
                String func_name = String(symbol->Name);
                Trinity::IO::Console::WriteLine("{0}: {1} - {2}", frames - i - 1, func_name, (LPVOID)symbol->Address);
            }
            unlock();

            free(symbol);

            Trinity::IO::Console::WriteLine("Press any key to continue ...");
#pragma warning(suppress: 6031)
            getchar();
#else
            Trinity::IO::Console::WriteLine("PrintStack: Windows only.");
#endif
        }

        void _writeline_impl(LogLevel logLevel, const String& msg)
        {
            if (logLevel <= s_CurrentLogLevel && logLevel != LogLevel::Off)
            {
                lock();

                DateTime dt     = DateTime::Now();
                String   time   = "[" + dt.ToString() + "]";
                String   header = s_LoggingPrefix[(int)logLevel];

                _post_log_entry(logLevel, msg, dt);

                if (s_EchoOnConsole)
                {
                    Console::Write(header);
                    Console::WriteLine(msg);
                }

                if (s_LogStream.Good())
                {
                    s_LogStream.Write(time);
                    s_LogStream.Write(header);
                    s_LogStream.WriteLine(msg);
                    _flush_if_necessary(logLevel);
                }

                unlock();
            }
        }

        void Flush()
        {
            lock();

            if (s_LogStream.Good())
            {
                s_LogStream.Flush();
            }

            Console::Flush();

            unlock();
        }

        void _writeline_impl(LogLevel logLevel, const char* srcFile, int32_t lineNum, const String& msg)
        {
            if (logLevel <= s_CurrentLogLevel && logLevel != LogLevel::Off)
            {

                String message;

                message.Append(String::Format("::Begin LogEntry (LogLevel:{0})", LogLevelToString(logLevel)));
#if defined(TRINITY_PLATFORM_WINDOWS)
                message.Append(String::Format("    ProcessId: {0}, ThreadId: {1}, Elapsed Seconds: {2}", GetCurrentProcessId(), GetCurrentThreadId(), ((double)clock()) / CLOCKS_PER_SEC));
#else
                message.Append(String::Format("    ProcessId: {0}, ThreadId: {1}, Elapsed Seconds: {2}", getpid(), pthread_self(), ((double)clock()) / CLOCKS_PER_SEC));
#endif
                message.Append(String::Format("    File: {0} \t Line: {1}", srcFile, lineNum));
                message.Append(msg);
                message.Append("::End LogEntry");

                _writeline_impl(logLevel, message);
            }
        }

        void SetLogLevel(LogLevel level)
        {
            s_CurrentLogLevel = level;
            WriteLine(LogLevel::Info, "LogLevel set to {0}", s_LoggingPrefix[level]);
        }

        void SetEchoOnConsole(bool is_set)
        {
            s_EchoOnConsole = is_set;
            WriteLine(LogLevel::Info, "EchoOnConsole set to {0}", is_set ? "ON" : "OFF");
        }

        //////////////////////////////
    }
}

DLL_EXPORT
VOID __stdcall CLogInitializeLogger(const u16char* logDir)
{
    TrinityConfig::SetLogDirectory(String::FromWcharArray(logDir, -1));
    Trinity::Diagnostics::InitializeLogger();
}

DLL_EXPORT
VOID __stdcall CLogWriteLine(Trinity::Diagnostics::LogLevel logLevel, const u16char* str)
{
    String msg_str = String::FromWcharArray(str, -1);
    _writeline_impl(logLevel, msg_str);
}

DLL_EXPORT
VOID __stdcall CLogFlush()
{
    Trinity::Diagnostics::Flush();
}

DLL_EXPORT
VOID __stdcall CLogSetLogLevel(Trinity::Diagnostics::LogLevel level)
{
    Trinity::Diagnostics::SetLogLevel(level);
}

DLL_EXPORT
VOID __stdcall CLogSetEchoOnConsole(bool is_set)
{
    Trinity::Diagnostics::SetEchoOnConsole(is_set);
}

// E_SUCCESS if there are one or more entries collected.
// E_FAILURE if failed to retrieve, or there are no entries committed.
DLL_EXPORT
TrinityErrorCode __stdcall CLogCollectEntries(OUT size_t& arr_size, OUT PLOG_ENTRY& entries)
{
    lock();
    arr_size   = s_LogEntries.size();
    entries    = arr_size == 0 ? nullptr : (PLOG_ENTRY)malloc(sizeof(LOG_ENTRY) * arr_size);
    std::copy(s_LogEntries.begin(), s_LogEntries.end(), entries);
    s_LogEntries.clear();
    unlock();
    return arr_size == 0 ? TrinityErrorCode::E_FAILURE : TrinityErrorCode::E_SUCCESS;
}


text:
import React from 'react';
import './App.css';
import Header from "./Header";
import Main from "./Main";
import LoginScreen from '../containers/LoginScreen';
import Welcome from "./Welcome";
import Clubs from "./Clubs";

class App extends React.Component {
	constructor(props){
		super(props);
		this.state={
			loginPage:[],
			userId:null,
			mainPage:[],
			name:"",
			email:""
		}
	}
  deleteUser(){
  	console.log("tried")
  	this.setState({
  		userId:null
  	})
  }

	render() {
			return (<div>
			<Main/>
				<Header appContext={this} userId ={this.state.userId} deleteUser={this.deleteUser.bind(this)} name={this.state.name} email={this.state.email}/>
				{!this.state.userId && this.state.loginPage.length==0 && <Welcome appContext={this}/>}
				{this.state.userId && this.state.mainPage}
				{this.state.loginPage}
				</div>
				)
		}

}

export default App;


text:
<?php

/**
 * @file
 */

namespace Drupal\superinfo\Content;

use Drupal\Core\Controller\ControllerBase;

/**
 * An example controller.
   $SuperinfoContentGenerator = new SuperinfoContentGenerator();
   $SuperinfoContentGenerator->superinfoTable();
 */
class SuperinfoContentGenerator extends ControllerBase {

  /**
   *
   */
  public function superinfoTable() {
    $output = '';
    $output .= '
';
      $output .= '
';

        $output .= '
';
          $output .= '
';

            $output .= '
';
              $output .= '
';
                $output .= t('Search') . ' <input data-ng-model="inputFilter.$">';
              $output .= '
';
            $output .= '
';

            $output .= '
';
              $output .= '
';
                $output .= '
';
                  $output .= '
';
                    $output .= '';
                      $output .= "{{ tableHeadKey }}";
                    $output .= '	';
                  $output .= '
';
                $output .= '
';

                $output .= '
';
                  $output .= '
';
                    $output .= '';
                      $output .= '{{ tableRowCell }}';
                    $output .= '	';
                  $output .= '
';

                $output .= '
';
              $output .= '
';
            $output .= '
';

          $output .= '
';
        $output .= '
';

      $output .= '
';
    $output .= '
';

    return $output;
  }

}


text:
import re

from django.conf import settings
from django.core import mail
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.client import Client
from django.contrib.sites.models import Site

from account.models import User
from admiral.models import AdmiralSite

class ManageDetailsTest(TestCase):
    urls = "account.tests.account_urls"
    PROTOCOL = 'http://'
    HTTP_HOST='admiralstorage.co.uk'
    fixtures = ['account/tests/users.json']

    def setUp(self):
        # Create the default site
        AdmiralSite.objects.create(domain=self.HTTP_HOST, name="Admiral Storage")

        #Create a default profile

    def test_change_password(self):
        # Login
        """
        Test POST on /account/login/
        """
        data = {
            'username':'test@test.com',
            'password':'demo1234',
        }
        response = self.client.post(reverse("account_login"), data, HTTP_HOST=self.HTTP_HOST)
        self.assertEquals(response.status_code, 302)

        # Change password
        data = {
            'old_password':'demo1234',
            'new_password1':'demo123',
            'new_password2':'demo123',
        }
        response = self.client.post(reverse("account_password_change"), data, HTTP_HOST=self.HTTP_HOST)
        # Should not redirect as not allowed to login
        self.assertEquals(response.status_code, 302)

    def test_update_details(self):

        data = {
            'username':'test@test.com',
            'password':'demo1234',
        }
        response = self.client.post(reverse("account_login"), data, HTTP_HOST=self.HTTP_HOST)
        self.assertEquals(response.status_code, 302)

        data = {
            'title':'mr',
            'first_name':'John',
            'last_name':'Johnson',
            'email':'test@test.com',
            'company_name':'companyabc',
            'phone_number':'08233114343',
            'mobile_number':'0763362743',
            'fax_number':'712037123',
        }
        response = self.client.post(reverse("account_update_details"), data, HTTP_HOST=self.HTTP_HOST)
        # Should not redirect as not allowed to login
        self.assertEquals(response.status_code, 302)
        self.assertEquals(response.url, '%s%s%s' % (self.PROTOCOL, self.HTTP_HOST, reverse("my_account")))


text:
package android.studio.imports.templates;

import java.io.FileNotFoundException;
import java.util.Objects;
import org.nbandroid.netbeans.gradle.core.sdk.ManifestParser;
import org.openide.filesystems.FileObject;
import org.openide.util.Exceptions;

/**
 * Handler which manages instantiating FreeMarker templates, copying resources
 * and merging into existing files
 */
public class Template {

    public static final String TEMPLATE_XML_NAME = "template.xml";
    // Various tags and attributes used in template.xml
    public static final String TAG_EXECUTE = "execute";
    public static final String TAG_GLOBALS = "globals";
    public static final String TAG_GLOBAL = "global";
    public static final String TAG_PARAMETER = "parameter";
    public static final String TAG_THUMB = "thumb";
    public static final String TAG_THUMBS = "thumbs";
    public static final String TAG_DEPENDENCY = "dependency";
    public static final String TAG_ICONS = "icons";
    public static final String ATTR_FORMAT = "format";
    public static final String ATTR_VALUE = "value";
    public static final String ATTR_DEFAULT = "default";
    public static final String ATTR_SUGGEST = "suggest";
    public static final String ATTR_ID = "id";
    public static final String ATTR_NAME = "name";
    public static final String ATTR_DESCRIPTION = "description";
    public static final String ATTR_TYPE = "type";
    public static final String ATTR_HELP = "help";
    public static final String ATTR_FILE = "file";
    public static final String ATTR_CONSTRAINTS = "constraints";
    public static final String ATTR_VISIBILITY = "visibility";
    public static final String ATTR_ENABLED = "enabled";
    public static final String CATEGORY_ACTIVITIES = "activities";
    public static final String CATEGORY_PROJECTS = "gradle-projects";
    public static final String CATEGORY_OTHER = "other";
    public static final String CATEGORY_APPLICATION = "Application";

    /**
     * Highest supported format; templates with a higher number will be skipped
     *

     *

     *
 1: Initial format, supported by ADT 20 and up.
     *
 2: ADT 21 and up. Boolean variables that have a default value and
     * are not edited by the user would end up as strings in ADT 20; now they
     * are always proper Booleans. Templates which rely on this should specify
     * format >= 2.
     *
 3: The wizard infrastructure passes the {@code isNewProject} boolean
     * variable to indicate whether a wizard is created as part of a new blank
     * project
     *
 4: Constraint type app_package ({@link Constraint#APP_PACKAGE}),
     * provides srcDir, resDir and manifestDir variables for locations of files
     *
 5: All files are relative to the template instead of using an
     * implicit "root" folder.
     *

     */
    static final int CURRENT_FORMAT = 5;

    /**
     * Templates from this version and up use relative (from this template) path
     * names. Recipe files from older versions uses an implicit "root" folder.
     */
    static final int RELATIVE_FILES_FORMAT = 5;

    private static final int MAX_WARNINGS = 10;
    private static final String GOOGLE_GLASS_PATH_19 = "/addon-google_gdk-google-19/";
    private final FileObject fileObject;
    private TemplateMetadata metadata;

    public Template(FileObject fileObject) {
        this.fileObject = fileObject;
    }

    public FileObject getFileObject() {
        return fileObject;
    }

    public TemplateMetadata getMetadata() {
        if (metadata == null) {
            try {
                metadata = new TemplateMetadata(ManifestParser.parseStream(fileObject.getInputStream()));
            } catch (FileNotFoundException ex) {
                Exceptions.printStackTrace(ex);
            }
        }

        return metadata;
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 37 * hash + Objects.hashCode(this.fileObject);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Template other = (Template) obj;
        if (!Objects.equals(this.fileObject, other.fileObject)) {
            return false;
        }
        return true;
    }

}


text:
describe(`example-phone`, () => {
  describe(`As an authenticated user not in a call`, () => {
    it(`can preview its video`);
    it(`can move the preview into a call`);
  });
});


text:
case class Rule(name: String)

def foo = List("1", "2").map(Rule.apply)


text:
/* */
var Syntax = require('esprima-fb').Syntax;
var utils = require('../src/utils');
function visitObjectLiteralSpread(traverse, node, path, state) {
  utils.catchup(node.range[0], state);
  utils.append('Object.assign({', state);
  utils.move(node.range[0] + 1, state);
  var previousWasSpread = false;
  for (var i = 0; i < node.properties.length; i++) {
    var property = node.properties[i];
    if (property.type === Syntax.SpreadProperty) {
      if (!previousWasSpread) {
        utils.append('}', state);
      }
      if (i === 0) {
        utils.append(',', state);
      }
      utils.catchup(property.range[0], state);
      utils.move(property.range[0] + 3, state);
      traverse(property.argument, path, state);
      utils.catchup(property.range[1], state);
      previousWasSpread = true;
    } else {
      utils.catchup(property.range[0], state);
      if (previousWasSpread) {
        utils.append('{', state);
      }
      traverse(property, path, state);
      utils.catchup(property.range[1], state);
      previousWasSpread = false;
    }
  }
  utils.catchupWhiteSpace(node.range[1] - 1, state);
  utils.move(node.range[1], state);
  if (!previousWasSpread) {
    utils.append('}', state);
  }
  utils.append(')', state);
  return false;
}
visitObjectLiteralSpread.test = function(node, path, state) {
  if (node.type !== Syntax.ObjectExpression) {
    return false;
  }
  var hasAtLeastOneSpreadProperty = false;
  for (var i = 0; i < node.properties.length; i++) {
    var property = node.properties[i];
    if (property.type === Syntax.SpreadProperty) {
      hasAtLeastOneSpreadProperty = true;
    } else if (property.kind !== 'init') {
      return false;
    }
  }
  return hasAtLeastOneSpreadProperty;
};
exports.visitorList = [visitObjectLiteralSpread];


text:
#if 0

#ifndef FCGLView_h
#define FCGLView_h

#include "Shared/Core/FCCore.h"

class FCGLView : public FCBase
{
public:
	FCGLView( std::string name, std::string parent, const FCVector2i& size );
	virtual ~FCGLView();

	virtual void Update( float dt );
	virtual void SetDepthBuffer( bool enabled );
	virtual void SetRenderTarget( FCVoidVoidFuncPtr func );
	virtual void SetFrameBuffer();
	virtual void Clear();
	virtual void SetProjectionMatrix();
	virtual void PresentFramebuffer();
	virtual FCVector2f ViewSize();
	virtual FCVector3f PosOnPlane( const FCVector2f& point );
	virtual void SetClearColor( const FCColor4f& color );
	virtual void SetFOV( float fov );
	virtual void SetNearClip( float clip );
	virtual void SetFarClip( float clip );
	virtual void SetFrustumTranslation( const FCVector3f& trans );
protected:
	std::string	m_name;
};

typedef FCSharedPtr<FCGLView> FCGLViewRef;
typedef std::map<std::string, FCGLViewRef>	FCGLViewMap;

extern FCGLViewRef plt_FCGLView_Create( std::string name, std::string parent, const FCVector2i& size );

#endif

#endif


text:
layout: default
title: Courtyard By Marriott
description: Meyer Brothers Building Company has been building in Kansas City since 1977. We speacilize in design-build and tilt-up construction for retail, industrial, institutinal, office buildings, and all other commercial needs. Give us a call at 816-246-4800 to find out more information on how we can build your next facility.
keywords: Meyer, Brothers, Meyer Brothers, Construction, Building, tilt-up, Brother, Framing, Build-to-suit, Build to suit, tilt up, contractor, general contractor, kansas city general contractor, contracting, developments, build, new building, new facility, meyer company, courtyard by marriott, design build
---

    rest assured, we're good.

    Meyer Brothers Building Co. was the Design/Build General Contractor of this turnkey project.

    The building is a four story structure utilizing a prefabricated load bearing
            metal stud system combined with a concrete structural floor system utilizing an Epicor deck as the building skeleton.

    The roof system consists of a single-ply rubber membrane coupled with a pre-finished architectural sheet metal roof system.

    Hotel amenities include a restaurant & lounge, indoor pool & spa, meeting areas and access to a city owned conference center and golf course.

    Project details

       Square Footage

       69,000 S.F.

       Location

       1500 NE Coronado Dr. |
                Blue Springs, MO 64014

       End Use

       121 Room Hotel

       Completion Date

       April 2000

       Architectural Features

       Epicor deck skeleton, Restaraunt, Pool & Spa

       Owner/Reference

       RMT of Blue Springs

       To protect our clients privacy, please

        contact

       us for development reference information.

       Architect

       Michael Treanor Architects


text:
package org.olat.presentation.portal.macartney;

import java.text.DecimalFormat;
import java.util.Map;

import org.olat.lms.properties.PropertyManagerEBL;
import org.olat.presentation.framework.core.UserRequest;
import org.olat.presentation.framework.core.components.Component;
import org.olat.presentation.framework.core.components.velocity.VelocityContainer;
import org.olat.presentation.framework.core.control.DefaultController;
import org.olat.presentation.framework.core.control.WindowControl;
import org.olat.presentation.framework.core.translator.PackageTranslator;
import org.olat.presentation.framework.core.translator.PackageUtil;
import org.olat.presentation.framework.core.translator.Translator;
import org.olat.system.commons.Settings;
import org.olat.system.event.Event;
import org.olat.system.spring.CoreSpringFactory;

/**
 * Description:

 * Run view controller of macartney portlet
 *

 * Initial Date: 11.07.2005

 *
 * @author gnaegi
 */
public class MacartneyPortletRunController extends DefaultController {

    private static final String VELOCITY_ROOT = PackageUtil.getPackageVelocityRoot(MacartneyPortlet.class);
    private Translator trans;
    private VelocityContainer macartneyVC;

    private static final int maxEpisodes = 468;
    private static final long updateInterval = 86400000; // one day in milliseconds

    private static long comicStartDate = 0;

    /**
     * Constructor
     *
     * @param ureq
     * @param imageBaseUri
     */
    // o_clusterOK by:se synchronized on MacartneyPortlet class as olatresourceable
    protected MacartneyPortletRunController(final UserRequest ureq, final WindowControl wControl, final Map configuration) {
        super(wControl);
        this.trans = new PackageTranslator(PackageUtil.getPackageName(MacartneyPortlet.class), ureq.getLocale());
        this.macartneyVC = new VelocityContainer("macartneyVC", VELOCITY_ROOT + "/macartneyPortlet.html", trans, this);

        if (comicStartDate == 0) {
            comicStartDate = getPropertyManagerEBL().getComicStartDate(comicStartDate, MacartneyPortletRunController.class.getSimpleName());
        }

        // time between comic start and now
        final long timeDelta = (System.currentTimeMillis() - comicStartDate);
        // number of increments since comic start
        final long incrementNumber = (timeDelta / updateInterval);
        // module with max episodes to start over again when finished
        // + 1 since comic starts at position 1 and not 0
        final long imageNumber = (incrementNumber % maxEpisodes) + 1;

        // calculate current episode url and push to velocity
        final DecimalFormat df = new DecimalFormat("0000");
        final String currentEpisodeImage = "loge_" + df.format(imageNumber) + ".jpg";
        final String configuredImageBaseUri = (String) configuration.get("imageBaseUri");
        if (configuredImageBaseUri.startsWith("http://") || configuredImageBaseUri.startsWith("https://")) {
            // feature: if the configured imageBaseUri contains http: or https: already, don't do
            // magic "trying-to-detect-the-correct-protocol-via-olat.properties" but use it right away
            this.macartneyVC.contextPut("imageBaseUri", configuredImageBaseUri);
        } else {
            // otherwise do the old magic
            this.macartneyVC.contextPut("imageBaseUri", Settings.getURIScheme() + configuredImageBaseUri);
        }
        this.macartneyVC.contextPut("currentEpisodeImage", currentEpisodeImage);

        setInitialComponent(this.macartneyVC);
    }

    @Override
    protected void event(final UserRequest ureq, final Component source, final Event event) {
        // no events to catch
    }

    @Override
    protected void doDispose() {
        // nothing to dispose
    }

    private PropertyManagerEBL getPropertyManagerEBL() {
        return CoreSpringFactory.getBean(PropertyManagerEBL.class);
    }

}


text:
package eu.scasefp7.eclipse.servicecomposition.operation.ipr;

import gr.iti.wsdl.wsdlToolkit.WSOperation;

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

public class SLA {

	//cost, usage duration and discount aspects of the service
	private String SLA_CostCurrency = "";
	private String SLA_CostPaymentChargeType = "";
	private Date SLA_EndDate;
	private Date SLA_StartDate;
	private String hasStatus = "";
	private int durationInUsages;
	private int durationInUsagesSpent;
	private int durationInUsers;
	private int durationInUsersSpent;
	private int vendorWithTotalTimeOfLoyaltyToOwn;
	private float SLA_Cost;
	private float SLA_CostAfterDiscount;
	private String ownerOfAgreement = "";
	private ServiceLicense serviceLicense = new ServiceLicense();
	private String vendorOfAgreement = "";
	private List<String> validForCountries = new ArrayList<String>();
	private List<WSOperation> accompanyingServices = new ArrayList<WSOperation>();
	private List<DiscountSchema> discountSchema = new ArrayList<DiscountSchema>();
	private String ontologyURI = "";

	public String getOntologyURI() {
		return ontologyURI;
	}

	public void setOntologyURI(String ontologyURI) {
		this.ontologyURI = ontologyURI;
	}

	/**
	 * @return the sLA_CostCurrency
	 */
	public String getSLA_CostCurrency() {
		return SLA_CostCurrency;
	}

	/**
	 * @param sLA_CostCurrency
	 *            the sLA_CostCurrency to set
	 */
	public void setSLA_CostCurrency(String sLA_CostCurrency) {
		SLA_CostCurrency = sLA_CostCurrency;
	}

	/**
	 * @return the sLA_CostPaymentChargeType
	 */
	public String getSLA_CostPaymentChargeType() {
		return SLA_CostPaymentChargeType;
	}

	/**
	 * @param sLA_CostPaymentChargeType
	 *            the sLA_CostPaymentChargeType to set
	 */
	public void setSLA_CostPaymentChargeType(String sLA_CostPaymentChargeType) {
		SLA_CostPaymentChargeType = sLA_CostPaymentChargeType;
	}

	/**
	 * @return the sLA_EndDate
	 */
	public Date getSLA_EndDate() {
		return SLA_EndDate;
	}

	/**
	 * @param sLA_EndDate
	 *            the sLA_EndDate to set
	 */
	public void setSLA_EndDate(Date sLA_EndDate) {
		SLA_EndDate = sLA_EndDate;
	}

	/**
	 * @return the sLA_StartDate
	 */
	public Date getSLA_StartDate() {
		return SLA_StartDate;
	}

	/**
	 * @param sLA_StartDate
	 *            the sLA_StartDate to set
	 */
	public void setSLA_StartDate(Date sLA_StartDate) {
		SLA_StartDate = sLA_StartDate;
	}

	/**
	 * @return the hasStatus
	 */
	public String getHasStatus() {
		return hasStatus;
	}

	/**
	 * @param hasStatus
	 *            the hasStatus to set
	 */
	public void setHasStatus(String hasStatus) {
		this.hasStatus = hasStatus;
	}

	/**
	 * @return the durationInUsages
	 */
	public int getDurationInUsages() {
		return durationInUsages;
	}

	/**
	 * @param durationInUsages
	 *            the durationInUsages to set
	 */
	public void setDurationInUsages(int durationInUsages) {
		this.durationInUsages = durationInUsages;
	}

	/**
	 * @return the durationInUsagesSpent
	 */
	public int getDurationInUsagesSpent() {
		return durationInUsagesSpent;
	}

	/**
	 * @param durationInUsagesSpent
	 *            the durationInUsagesSpent to set
	 */
	public void setDurationInUsagesSpent(int durationInUsagesSpent) {
		this.durationInUsagesSpent = durationInUsagesSpent;
	}

	/**
	 * @return the durationInUsers
	 */
	public int getDurationInUsers() {
		return durationInUsers;
	}

	/**
	 * @param durationInUsers
	 *            the durationInUsers to set
	 */
	public void setDurationInUsers(int durationInUsers) {
		this.durationInUsers = durationInUsers;
	}

	/**
	 * @return the durationInUsersSpent
	 */
	public int getDurationInUsersSpent() {
		return durationInUsersSpent;
	}

	/**
	 * @param durationInUsersSpent
	 *            the durationInUsersSpent to set
	 */
	public void setDurationInUsersSpent(int durationInUsersSpent) {
		this.durationInUsersSpent = durationInUsersSpent;
	}

	/**
	 * @return the vendorWithTotalTimeOfLoyaltyToOwn
	 */
	public int getVendorWithTotalTimeOfLoyaltyToOwn() {
		return vendorWithTotalTimeOfLoyaltyToOwn;
	}

	/**
	 * @param vendorWithTotalTimeOfLoyaltyToOwn
	 *            the vendorWithTotalTimeOfLoyaltyToOwn to set
	 */
	public void setVendorWithTotalTimeOfLoyaltyToOwn(
			int vendorWithTotalTimeOfLoyaltyToOwn) {
		this.vendorWithTotalTimeOfLoyaltyToOwn = vendorWithTotalTimeOfLoyaltyToOwn;
	}

	/**
	 * @return the sLA_Cost
	 */
	public float getSLA_Cost() {
		return SLA_Cost;
	}

	/**
	 * @param sLA_Cost
	 *            the sLA_Cost to set
	 */
	public void setSLA_Cost(float sLA_Cost) {
		SLA_Cost = sLA_Cost;
	}

	/**
	 * @return the sLA_CostAfterDiscount
	 */
	public float getSLA_CostAfterDiscount() {
		return SLA_CostAfterDiscount;
	}

	/**
	 * @param sLA_CostAfterDiscount
	 *            the sLA_CostAfterDiscount to set
	 */
	public void setSLA_CostAfterDiscount(float sLA_CostAfterDiscount) {
		SLA_CostAfterDiscount = sLA_CostAfterDiscount;
	}

	/**
	 * @return the validForCountries
	 */
	public List<String> getValidForCountries() {
		return validForCountries;
	}

	/**
	 * @param validForCountries
	 *            the validForCountries to set
	 */
	public void setValidForCountries(List<String> validForCountries) {
		this.validForCountries = validForCountries;
	}

	public ServiceLicense getServiceLicense() {
		return serviceLicense;
	}

	public void setServiceLicense(ServiceLicense serviceLicense) {
		this.serviceLicense = serviceLicense;
	}

	public List<WSOperation> getAccompanyingServices() {
		return accompanyingServices;
	}

	public void setAccompanyingServices(List<WSOperation> accompanyingServices) {
		this.accompanyingServices = accompanyingServices;
	}

	/**
	 * @return the discountSchema
	 */
	public List<DiscountSchema> getDiscountSchema() {
		return discountSchema;
	}

	/**
	 * @param discountSchema
	 *            the discountSchema to set
	 */
	public void setDiscountSchema(List<DiscountSchema> discountSchema) {
		this.discountSchema = discountSchema;
	}

	public String getOwnerOfAgreement() {
		return ownerOfAgreement;
	}

	public void setOwnerOfAgreement(String ownerOfAgreement) {
		this.ownerOfAgreement = ownerOfAgreement;
	}

	public String getVendorOfAgreement() {
		return vendorOfAgreement;
	}

	public void setVendorOfAgreement(String vendorOfAgreement) {
		this.vendorOfAgreement = vendorOfAgreement;
	}

	public SLA clone() {
		SLA sla = new SLA();
		sla.setSLA_CostCurrency(this.getSLA_CostCurrency());
		sla.setSLA_CostPaymentChargeType(this.getSLA_CostPaymentChargeType());
		if (this.getSLA_StartDate() != null)
			sla.setSLA_StartDate((Date) this.getSLA_StartDate().clone());
		if (this.getSLA_EndDate() != null)
			sla.setSLA_EndDate((Date) this.getSLA_EndDate().clone());
		sla.setHasStatus(this.getHasStatus());
		sla.setDurationInUsages(this.getDurationInUsages());
		sla.setDurationInUsagesSpent(this.getDurationInUsagesSpent());
		sla.setDurationInUsers(this.getDurationInUsers());
		sla.setDurationInUsagesSpent(this.getDurationInUsersSpent());
		sla.setVendorWithTotalTimeOfLoyaltyToOwn(this
				.getVendorWithTotalTimeOfLoyaltyToOwn());
		sla.setSLA_Cost(this.getSLA_Cost());
		sla.setSLA_CostAfterDiscount(this.getSLA_CostAfterDiscount());

		sla.setOwnerOfAgreement(this.getOwnerOfAgreement());
		sla.setServiceLicense(this.getServiceLicense().clone());
		sla.setOntologyURI(this.getOntologyURI());
		sla.setVendorOfAgreement(this.getVendorOfAgreement());

		for (int i = 0; i < this.getValidForCountries().size(); i++) {
			sla.getValidForCountries().add(this.getValidForCountries().get(i));
		}

		// TODO accompanyingSolutions are not cloned

		for (int i = 0; i < this.getDiscountSchema().size(); i++) {
			sla.getDiscountSchema()
					.add(this.getDiscountSchema().get(i).clone());
		}

		return sla;
	}

}


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

import java.io.ByteArrayInputStream;

import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.impl.history.HistoryLevel;
import org.flowable.common.engine.impl.identity.Authentication;
import org.flowable.engine.impl.test.HistoryTestHelper;
import org.flowable.engine.impl.test.PluggableFlowableTestCase;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.engine.task.Attachment;
import org.flowable.engine.test.Deployment;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

/**
 * Test case for all {@link FlowableEvent}s related to attachments.
 *
 * @author Frederik Heremans
 */
public class AttachmentEventsTest extends PluggableFlowableTestCase {

    private TestFlowableEntityEventListener listener;

    /**
     * Test create, update and delete events of attachments on a task/process.
     */
    @Test
    @Deployment(resources = { "org/flowable/engine/test/api/runtime/oneTaskProcess.bpmn20.xml" })
    public void testAttachmentEntityEvents() throws Exception {

        if (HistoryTestHelper.isHistoryLevelAtLeast(HistoryLevel.ACTIVITY, processEngineConfiguration)) {
            ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");

            org.flowable.task.api.Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
            assertNotNull(task);

            // Create link-attachment
            Attachment attachment = taskService.createAttachment("test", task.getId(), processInstance.getId(), "attachment name", "description", "http://flowable.org");
            assertNull(attachment.getUserId());
            assertEquals(2, listener.getEventsReceived().size());
            FlowableEngineEntityEvent event = (FlowableEngineEntityEvent) listener.getEventsReceived().get(0);
            assertEquals(FlowableEngineEventType.ENTITY_CREATED, event.getType());
            assertEquals(processInstance.getId(), event.getProcessInstanceId());
            assertEquals(processInstance.getId(), event.getExecutionId());
            assertEquals(processInstance.getProcessDefinitionId(), event.getProcessDefinitionId());
            Attachment attachmentFromEvent = (Attachment) event.getEntity();
            assertEquals(attachment.getId(), attachmentFromEvent.getId());
            event = (FlowableEngineEntityEvent) listener.getEventsReceived().get(1);
            assertEquals(FlowableEngineEventType.ENTITY_INITIALIZED, event.getType());
            assertEquals(processInstance.getId(), event.getProcessInstanceId());
            assertEquals(processInstance.getId(), event.getExecutionId());
            assertEquals(processInstance.getProcessDefinitionId(), event.getProcessDefinitionId());
            attachmentFromEvent = (Attachment) event.getEntity();
            assertEquals(attachment.getId(), attachmentFromEvent.getId());
            listener.clearEventsReceived();

            // Create binary attachment
            Authentication.setAuthenticatedUserId("testuser");
            attachment = taskService.createAttachment("test", task.getId(), processInstance.getId(), "attachment name", "description", new ByteArrayInputStream("test".getBytes()));
            assertNotNull(attachment.getUserId());
            assertEquals("testuser", attachment.getUserId());
            assertEquals(2, listener.getEventsReceived().size());
            event = (FlowableEngineEntityEvent) listener.getEventsReceived().get(0);
            assertEquals(FlowableEngineEventType.ENTITY_CREATED, event.getType());
            assertEquals(processInstance.getId(), event.getProcessInstanceId());
            assertEquals(processInstance.getId(), event.getExecutionId());
            assertEquals(processInstance.getProcessDefinitionId(), event.getProcessDefinitionId());
            attachmentFromEvent = (Attachment) event.getEntity();
            assertEquals(attachment.getId(), attachmentFromEvent.getId());

            event = (FlowableEngineEntityEvent) listener.getEventsReceived().get(1);
            assertEquals(FlowableEngineEventType.ENTITY_INITIALIZED, event.getType());
            listener.clearEventsReceived();

            // Update attachment
            attachment = taskService.getAttachment(attachment.getId());
            attachment.setDescription("Description");
            taskService.saveAttachment(attachment);

            assertEquals(1, listener.getEventsReceived().size());
            event = (FlowableEngineEntityEvent) listener.getEventsReceived().get(0);
            assertEquals(FlowableEngineEventType.ENTITY_UPDATED, event.getType());
            assertEquals(processInstance.getId(), event.getProcessInstanceId());
            assertEquals(processInstance.getId(), event.getExecutionId());
            assertEquals(processInstance.getProcessDefinitionId(), event.getProcessDefinitionId());
            attachmentFromEvent = (Attachment) event.getEntity();
            assertEquals(attachment.getId(), attachmentFromEvent.getId());
            assertEquals("Description", attachmentFromEvent.getDescription());
            listener.clearEventsReceived();

            // Finally, delete attachment
            taskService.deleteAttachment(attachment.getId());
            assertEquals(1, listener.getEventsReceived().size());
            event = (FlowableEngineEntityEvent) listener.getEventsReceived().get(0);
            assertEquals(FlowableEngineEventType.ENTITY_DELETED, event.getType());
            assertEquals(processInstance.getId(), event.getProcessInstanceId());
            assertEquals(processInstance.getId(), event.getExecutionId());
            assertEquals(processInstance.getProcessDefinitionId(), event.getProcessDefinitionId());
            attachmentFromEvent = (Attachment) event.getEntity();
            assertEquals(attachment.getId(), attachmentFromEvent.getId());
        }
    }

    /**
     * Test create, update and delete events of users.
     */
    @Test
    public void testAttachmentEntityEventsStandaloneTask() throws Exception {
        if (HistoryTestHelper.isHistoryLevelAtLeast(HistoryLevel.ACTIVITY, processEngineConfiguration)) {
            org.flowable.task.api.Task task = null;
            try {
                task = taskService.newTask();
                taskService.saveTask(task);
                assertNotNull(task);

                // Create link-attachment
                Attachment attachment = taskService.createAttachment("test", task.getId(), null, "attachment name", "description", "http://flowable.org");
                assertEquals(2, listener.getEventsReceived().size());
                FlowableEngineEntityEvent event = (FlowableEngineEntityEvent) listener.getEventsReceived().get(0);
                assertEquals(FlowableEngineEventType.ENTITY_CREATED, event.getType());
                assertNull(event.getProcessInstanceId());
                assertNull(event.getExecutionId());
                assertNull(event.getProcessDefinitionId());
                Attachment attachmentFromEvent = (Attachment) event.getEntity();
                assertEquals(attachment.getId(), attachmentFromEvent.getId());
                event = (FlowableEngineEntityEvent) listener.getEventsReceived().get(1);
                assertEquals(FlowableEngineEventType.ENTITY_INITIALIZED, event.getType());
                listener.clearEventsReceived();

                // Create binary attachment
                attachment = taskService.createAttachment("test", task.getId(), null, "attachment name", "description", new ByteArrayInputStream("test".getBytes()));
                assertEquals(2, listener.getEventsReceived().size());
                event = (FlowableEngineEntityEvent) listener.getEventsReceived().get(0);
                assertEquals(FlowableEngineEventType.ENTITY_CREATED, event.getType());
                assertNull(event.getProcessInstanceId());
                assertNull(event.getExecutionId());
                assertNull(event.getProcessDefinitionId());
                attachmentFromEvent = (Attachment) event.getEntity();
                assertEquals(attachment.getId(), attachmentFromEvent.getId());

                event = (FlowableEngineEntityEvent) listener.getEventsReceived().get(1);
                assertEquals(FlowableEngineEventType.ENTITY_INITIALIZED, event.getType());
                listener.clearEventsReceived();

                // Update attachment
                attachment = taskService.getAttachment(attachment.getId());
                attachment.setDescription("Description");
                taskService.saveAttachment(attachment);

                assertEquals(1, listener.getEventsReceived().size());
                event = (FlowableEngineEntityEvent) listener.getEventsReceived().get(0);
                assertEquals(FlowableEngineEventType.ENTITY_UPDATED, event.getType());
                assertNull(event.getProcessInstanceId());
                assertNull(event.getExecutionId());
                assertNull(event.getProcessDefinitionId());
                attachmentFromEvent = (Attachment) event.getEntity();
                assertEquals(attachment.getId(), attachmentFromEvent.getId());
                assertEquals("Description", attachmentFromEvent.getDescription());
                listener.clearEventsReceived();

                // Finally, delete attachment
                taskService.deleteAttachment(attachment.getId());
                assertEquals(1, listener.getEventsReceived().size());
                event = (FlowableEngineEntityEvent) listener.getEventsReceived().get(0);
                assertEquals(FlowableEngineEventType.ENTITY_DELETED, event.getType());
                assertNull(event.getProcessInstanceId());
                assertNull(event.getExecutionId());
                assertNull(event.getProcessDefinitionId());
                attachmentFromEvent = (Attachment) event.getEntity();
                assertEquals(attachment.getId(), attachmentFromEvent.getId());

            } finally {
                if (task != null && task.getId() != null) {
                    taskService.deleteTask(task.getId());
                    historyService.deleteHistoricTaskInstance(task.getId());
                }
            }
        }
    }

    @Test
    public void testAttachmentEntityEventsOnHistoricTaskDelete() throws Exception {
        if (HistoryTestHelper.isHistoryLevelAtLeast(HistoryLevel.ACTIVITY, processEngineConfiguration)) {
            org.flowable.task.api.Task task = null;
            try {
                task = taskService.newTask();
                taskService.saveTask(task);
                assertNotNull(task);

                // Create link-attachment
                Attachment attachment = taskService.createAttachment("test", task.getId(), null, "attachment name", "description", "http://flowable.org");
                listener.clearEventsReceived();

                // Delete task and historic task
                taskService.deleteTask(task.getId());
                historyService.deleteHistoricTaskInstance(task.getId());

                assertEquals(1, listener.getEventsReceived().size());
                FlowableEngineEntityEvent event = (FlowableEngineEntityEvent) listener.getEventsReceived().get(0);
                assertEquals(FlowableEngineEventType.ENTITY_DELETED, event.getType());
                assertNull(event.getProcessInstanceId());
                assertNull(event.getExecutionId());
                assertNull(event.getProcessDefinitionId());
                Attachment attachmentFromEvent = (Attachment) event.getEntity();
                assertEquals(attachment.getId(), attachmentFromEvent.getId());

            } finally {
                if (task != null && task.getId() != null) {
                    taskService.deleteTask(task.getId());
                    historyService.deleteHistoricTaskInstance(task.getId());
                }
            }
        }
    }

    @BeforeEach
    protected void setUp() throws Exception {
        listener = new TestFlowableEntityEventListener(Attachment.class);
        processEngineConfiguration.getEventDispatcher().addEventListener(listener);
    }

    @AfterEach
    protected void tearDown() throws Exception {

        if (listener != null) {
            processEngineConfiguration.getEventDispatcher().removeEventListener(listener);
        }
    }
}


text:
SYNONYM

#### According to
IRMNG Homonym List

#### Published in
Rabenh. Krypt. -Fl. (Leipzig), Edn 2 1(3): 289 (1889)

#### Original name
Caldesia Rehm, 1889

### Remarks
null


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                "http://www.w3.org/TR/REC-html40/loose.dtd">

  <title>Description of safeDivide</title>
  <meta name="keywords" content="safeDivide">
  <meta name="description" content="safeDivide - divides two arrays, checking for 0/0.">
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <meta name="generator" content="m2html v1.5 © 2003-2005 Guillaume Flandin">
  <meta name="robots" content="index, follow">
  <link type="text/css" rel="stylesheet" href="../m2html.css">

Home >  SaliencyToolbox > safeDivide.m

safeDivide

PURPOSE

safeDivide - divides two arrays, checking for 0/0.

SYNOPSIS

function result = safeDivide(arg1,arg2)

DESCRIPTION

 safeDivide - divides two arrays, checking for 0/0.

 result = safeDivide(arg1,arg2)
    returns arg1./arg2, where 0/0 is assumed to be 0 instead of NaN.

CROSS-REFERENCE INFORMATION

This function calls:

This function is called by:

hueDistance	hueDistance - computes the distance in a simplified 2d color space.

makeBlueYellowPyramid	makeBlueYellowPyramid - creates a blue-yellow opponency pyramid.

makeRedGreenPyramid	makeRedGreenPyramid - creates a red-green opponency pyramid

SOURCE CODE

0001 % safeDivide - divides two arrays, checking for 0/0.
0002 %
0003 % result = safeDivide(arg1,arg2)
0004 %    returns arg1./arg2, where 0/0 is assumed to be 0 instead of NaN.
0005
0006 % This file is part of the SaliencyToolbox - Copyright (C) 2006-2013
0007 % by Dirk B. Walther and the California Institute of Technology.
0008 % See the enclosed LICENSE.TXT document for the license agreement.
0009 % More information about this project is available at:
0010 % http://www.saliencytoolbox.net
0011
0012 function result = safeDivide(arg1,arg2)
0013
0014 ze = (arg2 == 0);
0015 arg2(ze) = 1;
0016 result = arg1./arg2;
0017 result(ze) = 0;

<address>Generated on Thu 18-Jul-2013 06:10:46 by m2html © 2005</address>


text:
package com.opengamma.financial.analytics.conversion;

import org.threeten.bp.Period;
import org.threeten.bp.ZoneOffset;
import org.threeten.bp.ZonedDateTime;

import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.analytics.financial.instrument.InstrumentDefinition;
import com.opengamma.analytics.financial.instrument.fra.ForwardRateAgreementDefinition;
import com.opengamma.analytics.financial.instrument.index.IborIndex;
import com.opengamma.core.holiday.HolidaySource;
import com.opengamma.core.id.ExternalSchemes;
import com.opengamma.core.region.RegionSource;
import com.opengamma.financial.convention.ConventionBundle;
import com.opengamma.financial.convention.ConventionBundleSource;
import com.opengamma.financial.convention.HolidaySourceCalendarAdapter;
import com.opengamma.financial.convention.calendar.Calendar;
import com.opengamma.financial.convention.frequency.PeriodFrequency;
import com.opengamma.financial.security.FinancialSecurityVisitorAdapter;
import com.opengamma.financial.security.fra.FRASecurity;
import com.opengamma.financial.security.fra.ForwardRateAgreementSecurity;
import com.opengamma.id.ExternalId;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.money.Currency;

/**
 * @deprecated Use {@link FRASecurityConverter}. {@link ConventionBundleSource} should not be used,
 * as the conventions are not typed.
 */
@Deprecated
public class FRASecurityConverterDeprecated extends FinancialSecurityVisitorAdapter<InstrumentDefinition<?>> {
  private final HolidaySource _holidaySource;
  private final RegionSource _regionSource;
  private final ConventionBundleSource _conventionSource;

  public FRASecurityConverterDeprecated(final HolidaySource holidaySource, final RegionSource regionSource, final ConventionBundleSource conventionSource) {
    ArgumentChecker.notNull(holidaySource, "holiday source");
    ArgumentChecker.notNull(regionSource, "region source");
    ArgumentChecker.notNull(conventionSource, "convention source");
    _holidaySource = holidaySource;
    _regionSource = regionSource;
    _conventionSource = conventionSource;
  }

  @Override
  public ForwardRateAgreementDefinition visitFRASecurity(final FRASecurity security) {
    ArgumentChecker.notNull(security, "security");
    final Currency currency = security.getCurrency();
    final ConventionBundle fraConvention = _conventionSource.getConventionBundle(security.getUnderlyingId());
    if (fraConvention == null) {
      throw new OpenGammaRuntimeException("Could not get convention for " + security.getUnderlyingId());
    }
    final ZonedDateTime accrualStartDate = security.getStartDate();
    final ZonedDateTime accrualEndDate = security.getEndDate();
    final double notional = security.getAmount();
    final Calendar calendar = CalendarUtils.getCalendar(_regionSource, _holidaySource, ExternalSchemes.currencyRegionId(currency)); //TODO exchange region?
    final IborIndex iborIndex = new IborIndex(currency, fraConvention.getPeriod(), fraConvention.getSettlementDays(), fraConvention.getDayCount(), fraConvention.getBusinessDayConvention(),
        fraConvention.isEOMConvention());
    return ForwardRateAgreementDefinition.from(accrualStartDate, accrualEndDate, notional, iborIndex, security.getRate(), calendar);
  }

  @Override
  public ForwardRateAgreementDefinition visitForwardRateAgreementSecurity(final ForwardRateAgreementSecurity security) {
    ArgumentChecker.notNull(security, "security");
    final Currency currency = security.getCurrency();
    final Period period = PeriodFrequency.of(security.getIndexFrequency().getName()).getPeriod();
    final ZonedDateTime accrualStartDate = security.getStartDate().atStartOfDay(ZoneOffset.UTC);
    final ZonedDateTime accrualEndDate = security.getEndDate().atStartOfDay(ZoneOffset.UTC);
    final double notional = security.getAmount();
    final Calendar calendar = new HolidaySourceCalendarAdapter(_holidaySource, security.getCalendars().toArray(new ExternalId[security.getCalendars().size()]));
    final IborIndex iborIndex = new IborIndex(currency, period, security.getFixingLag(), security.getDayCount(), security.getFixingBusinessDayConvention(), false);
    return ForwardRateAgreementDefinition.from(accrualStartDate, accrualEndDate, notional, iborIndex, security.getRate(), calendar);
  }

}


text:
namespace boost {
namespace beast {
namespace detail {

class clamp_test : public beast::unit_test::suite
{
public:
    void testClamp()
    {
        BEAST_EXPECT(clamp(
            (std::numeric_limits<std::uint64_t>::max)()) ==
                (std::numeric_limits<std::size_t>::max)());
    }

    void run() override
    {
        testClamp();
    }
};

BEAST_DEFINE_TESTSUITE(beast,core,clamp);

} // detail
} // beast
} // boost


text:
/** @module models/Note */

var Backbone = require('backbone');
var IDB = require('backbone-indexeddb');
var database = require('../database');
var encryptor = require('../encryptor');
var utils = require('../utils');

/**
 * Represents a note.
 * @constructor
 * @augments Backbone.Model
 */
module.exports = Backbone.Model.extend(/** @lends module:models/Note# */ {

    /**
     * IndexedDB database.
     * @type {!Object}
     */
    database: database,

    /**
     * Default note attributes.
     * @type {!Object}
     */
    defaults: {
        body: '',
        url: '',
        created: null,
        modified: null,
        isDeleted: false
    },

    /**
     * IndexedDB database name.
     * @type {!string}
     */
    storeName: 'notes',

    /**
     * Backbone-indexeddb sync function.
     * @type {!function}
     */
    sync: IDB.sync,

    /**
     * Return true if the note is not deleted and is either not encrypted
     * or has been decrypted successfully.
     * @return {!boolean}
     */
    isReadable: function() {
        return !this.get('isDeleted') && !this.isUndecryptable();
    },

    /**
     * Return true if the note cannot be decrypted successfully.
     * @return {!boolean}
     */
    isUndecryptable: function() {
        return encryptor.isEncrypted(this.attributes);
    },

    /**
     * Return true if the note matches the supplied query.
     * @param {!string} query Query to search for, which must be lowercase.
     * @return {!boolean}
     */
    matches: function(query) {
        return this.matches_(this.get('body'), this.get('url'), query)
    },

    /**
     * Return true if the note used to matches the supplied query.
     * @param {!string} query Query to search for, which must be lowercase.
     * @return {!boolean}
     */
    matchedPreviously: function(query) {
        var attrs = this.previousAttributes();

        return this.matches_(attrs.body || '', attrs.url || '', query)
    },

    /**
     * Parse and decrypt the response from IndexedDB.
     * @param {!Object} response Response from IndexedDB.
     * @return {!Object} The note's attributes.
     */
    parse: function(response) {
        encryptor.decrypt(response);
        return response;
    },

    /**
     * Delete the note.
     * @param {Object=} options
     */
    remove: function(options) {
        options = options || {};
        this.save({ isDeleted: true, modified: new Date().getTime() }, options);
    },

    /**
     * Un-delete the note.
     * @param {Object=} options
     */
    undoRemove: function(options) {
        options = options || {};
        this.save({
            isDeleted: false,
            modified: new Date().getTime()
        }, options);
    },

    /**
     * Validate that the note's body and url are not both falsy.
     * @return {?Array} An array if there are 1 or more errors, or null
     * otherwise.
     */
    validate: function(attrs) {
        var errors = [];

        if (!attrs.body && !attrs.url) {
            errors.push({
                location: 'body',
                message: 'Both the "Body" and "Web-addresses and/or tags" fields cannot be blank.'
            });
        }
        return errors.length ? errors : null;
    },

    /**
     * Return true if the note matches the supplied query.
     * @param {!string} body
     * @param {!string} url
     * @param {!string} query Query to search for, which must be lowercase.
     * @return {!boolean}
     * @private
     */
    matches_: function(body, url, query) {
        var words = query.split(/\s+/);
        var word;

        body = body.toLowerCase();
        url = url.toLowerCase();

        for (var i = 0; i < words.length; i++) {
            word = words[i];

            if (body.indexOf(word) == -1 && url.indexOf(word) == -1) {
                return false;
            }
        }
        return true;
    }
});


text:
Pattern: `__init__` is generator

Issue: -

## Description

Used when the special class method `__init__` is turned into a generator by a yield in its body.

## Further Reading

* [Pylint - E0100](http://pylint-messages.wikidot.com/messages:e0100)


text:
#include "config.h"
#include "NinePieceImage.h"
#include <wtf/NeverDestroyed.h>

namespace WebCore {

static DataRef<NinePieceImageData>& defaultData()
{
    static NeverDestroyed<DataRef<NinePieceImageData>> data(NinePieceImageData::create());
    return data.get();
}

NinePieceImage::NinePieceImage()
    : m_data(defaultData())
{
}

NinePieceImage::NinePieceImage(PassRefPtr<StyleImage> image, LengthBox imageSlices, bool fill, LengthBox borderSlices, LengthBox outset, ENinePieceImageRule horizontalRule, ENinePieceImageRule verticalRule)
    : m_data(NinePieceImageData::create())
{
    m_data.access()->image = image;
    m_data.access()->imageSlices = WTF::move(imageSlices);
    m_data.access()->borderSlices = WTF::move(borderSlices);
    m_data.access()->outset = WTF::move(outset);
    m_data.access()->fill = fill;
    m_data.access()->horizontalRule = horizontalRule;
    m_data.access()->verticalRule = verticalRule;
}

NinePieceImageData::NinePieceImageData()
    : fill(false)
    , horizontalRule(StretchImageRule)
    , verticalRule(StretchImageRule)
    , image(0)
    , imageSlices(Length(100, Percent), Length(100, Percent), Length(100, Percent), Length(100, Percent))
    , borderSlices(Length(1, Relative), Length(1, Relative), Length(1, Relative), Length(1, Relative))
    , outset(0)
{
}

inline NinePieceImageData::NinePieceImageData(const NinePieceImageData& other)
    : RefCounted<NinePieceImageData>()
    , fill(other.fill)
    , horizontalRule(other.horizontalRule)
    , verticalRule(other.verticalRule)
    , image(other.image)
    , imageSlices(other.imageSlices)
    , borderSlices(other.borderSlices)
    , outset(other.outset)
{
}

PassRef<NinePieceImageData> NinePieceImageData::copy() const
{
    return adoptRef(*new NinePieceImageData(*this));
}

bool NinePieceImageData::operator==(const NinePieceImageData& other) const
{
    return StyleImage::imagesEquivalent(image.get(), other.image.get())
        && imageSlices == other.imageSlices
        && fill == other.fill
        && borderSlices == other.borderSlices
        && outset == other.outset
        && horizontalRule == other.horizontalRule
        && verticalRule == other.verticalRule;
}

}


text:
package com.google.api.ads.adwords.jaxws.v201406.video;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *             Returns the list of videos that have been used in ads by the current
 *             customer, the match the filters given by the selector.
 *
 *             @param selector Determines which videos to return.
 *             @return A list of videos.
 *             @throws ApiException if problems occurred while fetching videos.
 *
 *
 *
Java class for get element declaration.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <element name="get">
 *   <complexType>
 *     <complexContent>
 *       <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *         <sequence>
 *           <element name="selector" type="{https://adwords.google.com/api/adwords/video/v201406}VideoSelector" minOccurs="0"/>
 *         </sequence>
 *       </restriction>
 *     </complexContent>
 *   </complexType>
 * </element>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "selector"
})
@XmlRootElement(name = "get")
public class VideoServiceInterfaceget {

    protected VideoSelector selector;

    /**
     * Gets the value of the selector property.
     *
     * @return
     *     possible object is
     *     {@link VideoSelector }
     *
     */
    public VideoSelector getSelector() {
        return selector;
    }

    /**
     * Sets the value of the selector property.
     *
     * @param value
     *     allowed object is
     *     {@link VideoSelector }
     *
     */
    public void setSelector(VideoSelector value) {
        this.selector = value;
    }

}


text:
(function() {
    'use strict';

    /**
     * Get the main module (shared for Workout).
     */
    angular.module(appName)
        /**
         * Login Controller.
         */
        .controller('ConfirmBookingController', ConfirmBooking);

    ConfirmBooking.$inject = ['$state', '$filter', '$http', 'config', '$location','CommonService','BookingDataService'];

    function ConfirmBooking($state, $filter, $http, config, $location,  CommonService, BookingDataService) {
        var BookingVm = this;
        BookingVm.finalBalance = 0;
        BookingVm.currentUserDetails = {};
        BookingVm.successMessagePopup = false;
        BookingVm.initialBalance = 0;
        BookingVm.paymentDetails = {};
        // Variable declarations
        // Function declarations
        BookingVm.decreaseOpacity = decreaseOpacity;
        BookingVm.increaseOpacity = increaseOpacity;
        BookingVm.bookingPayment = bookingPayment;
        BookingVm.goToLive = goToLive;

        activate();

        function activate() {
            BookingVm.bookingAmount = (CommonService.getBookingDetails().bookingCount * 157);
            BookingVm.currentUserDetails = CommonService.getUserDetails();
            BookingVm.initialBalance = CommonService.getUserDetails().scutops_money;

            BookingVm.paymentDetails.order_id = CommonService.getBookingDetails().order_id;
            BookingVm.paymentDetails.cust_id = CommonService.getUserDetails().id;
            // To initialize anything before the project starts
        }

        function decreaseOpacity(){
            document.getElementsByClassName("main-content2")[0].style.opacity="0.5";
        }

        function increaseOpacity(){
            document.getElementsByClassName("main-content2")[0].style.opacity="1";
        }

        function bookingPayment(){

            var balance = BookingVm.initialBalance - BookingVm.bookingAmount;

            if(balance >= 0){
                BookingVm.currentUserDetails.scutops_money = balance; //updating the user details

                BookingVm.paymentDetails.newBalance = balance;

                var paymentDetails = JSON.stringify(BookingVm.paymentDetails);// preparing for passing to the php file
                //console.log(paymentDetails);
                BookingDataService.makePayment(paymentDetails).then(function(response){
                    CommonService.setUserDetails(BookingVm.currentUserDetails);//updating user details in common service
                    BookingVm.finalBalance = balance;
                    decreaseOpacity();
                    BookingVm.successMessagePopup = true;
                });
            }
            else
                alert("Insufficient balance");
        }

        function goToLive(){
            $state.go("liveUpdate");
        }

    }

})();


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sshutils.views.components;

import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.*;
/**
 *
 * @author hutchuk
 */
public class ImportFileFilter extends FileFilter {

    public final static String winscp = "ini";
     /*
     * Get the extension of a file.
     */
    public static String getExtension(File f) {
        String ext = null;
        String s = f.getName();
        int i = s.lastIndexOf('.');

        if (i > 0 &&  i < s.length() - 1) {
            ext = s.substring(i+1).toLowerCase();
        }
        return ext;
    }

    //Accept all directories and all gif, jpg, tiff, or png files.
    public boolean accept(File f) {
        if (f.isDirectory()) {
            return true;
        }

        String extension = getExtension(f);
        if (extension != null) {
            if (extension.equals(winscp) ) {
                    return true;
            } else {
                return false;
            }
        }

        return false;
    }

    //The description of this filter
    public String getDescription() {
        return "Winscp Import Files";
    }
}


text:
'use strict';

import styled from 'styled-components';

const ListIndexWrapper = styled.button`
  border-radius: 40%;
  width: 30px;
  height: 20px;
  background: #000080;
  border: 1px solid #000080;
  color: #FFF;
  text-align: center;
`;

export default ListIndexWrapper;


text:
class CreatePeople < ActiveRecord::Migration
  def change
    create_table :people do |t|
      t.string :first_name, null: false
      t.string :last_name, null: false
      t.string :gender
      t.date :date_of_birth
      t.string :place_of_birth

      t.jsonb :address, default: '{}'
      t.jsonb :contact, default: '{}'

      t.timestamps null: false
    end
  end
end


text:
#include "../platform/platform.h"
#include "kaa_log.h"
#include "../kaa_common.h"
#include "../platform/ext_system_logger.h"
#include "kaa_mem.h"

#include "../platform/stdio.h"

#define KAA_LOG_PREFIX_FORMAT   "%04d/%02d/%02d %d:%02d:%02d [%s] [%s:%d] (%d) - "

// minimal size = sizeof(char) + sizeof('\n')
#define KAA_MINIMAL_BUFFER_SIZE 2

/**
 * Printable loglevels
 * @see kaa_log_level_t
 */
static const char* kaa_log_level_name[] =
{
      "NONE"
    , "FATAL"
    , "ERROR"
    , "WARNING"
    , "INFO"
    , "DEBUG"
    , "TRACE"
};

struct kaa_logger_t {
    FILE           *sink;
    kaa_log_level_t max_log_level;
    char           *log_buffer;
    size_t          buffer_size;
};

kaa_error_t kaa_log_create(kaa_logger_t **logger_p, size_t buffer_size, kaa_log_level_t max_log_level, FILE* sink)
{
    if (!logger_p || (buffer_size < KAA_MINIMAL_BUFFER_SIZE) || (max_log_level > KAA_MAX_LOG_LEVEL))
        return KAA_ERR_BADPARAM;

    *logger_p = (kaa_logger_t *) KAA_MALLOC(sizeof(kaa_logger_t));
    if (!*logger_p)
        return KAA_ERR_NOMEM;

    (*logger_p)->log_buffer = (char *) KAA_MALLOC(buffer_size * sizeof(char));
    if (!(*logger_p)->log_buffer) {
        KAA_FREE(*logger_p);
        *logger_p = NULL;
        return KAA_ERR_NOMEM;
    }

    (*logger_p)->buffer_size = buffer_size;

    (*logger_p)->sink = sink ? sink : stdout;
    (*logger_p)->max_log_level = max_log_level;
#ifdef KAA_TRACE_MEMORY_ALLOCATIONS
    kaa_trace_memory_allocs_set_logger(*logger_p);
#endif
    return KAA_ERR_NONE;
}

kaa_error_t kaa_log_destroy(kaa_logger_t *logger)
{
    KAA_RETURN_IF_NIL(logger, KAA_ERR_BADPARAM);
#ifdef KAA_TRACE_MEMORY_ALLOCATIONS
    kaa_trace_memory_allocs_set_logger(NULL);
#endif
    KAA_FREE(logger->log_buffer);
    KAA_FREE(logger);
    return KAA_ERR_NONE;
}

kaa_log_level_t kaa_get_max_log_level(const kaa_logger_t *self)
{
    return self ? self->max_log_level : KAA_LOG_LEVEL_NONE;
}

kaa_error_t kaa_set_max_log_level(kaa_logger_t *self, kaa_log_level_t max_log_level)
{
    KAA_RETURN_IF_NIL(self, KAA_ERR_BADPARAM);
    if (max_log_level > KAA_MAX_LOG_LEVEL) {
        return KAA_ERR_BADPARAM;
    }
    self->max_log_level = max_log_level;
    return KAA_ERR_NONE;
}

kaa_error_t kaa_log_set_sink(kaa_logger_t *self, FILE *sink)
{
    KAA_RETURN_IF_NIL2(self, sink, KAA_ERR_BADPARAM);

    self->sink = sink;

    return KAA_ERR_NONE;
}

void kaa_log_write(kaa_logger_t *self, const char* source_file, int lineno, kaa_log_level_t log_level
        , kaa_error_t error_code, const char* format, ...)
{
    if (!self || (log_level > self->max_log_level))
        return;

    // Truncate the file name
    char* path_separator_pos = strrchr(source_file, '/');
    path_separator_pos = (path_separator_pos ? path_separator_pos : strrchr(source_file, '\\'));
    const char* truncated_name = (path_separator_pos ? path_separator_pos + 1 : source_file);

    // Convert to UTC time
    // TODO: Need to print milliseconds. For this purpose, timespec() from C11
    // standard may be used, but GCC 4.6.4 doesn't support this API.
    size_t consumed_len = 0;

    // Print log message prefix
    int res_len = ext_format_sprintf(self->log_buffer, self->buffer_size, KAA_LOG_PREFIX_FORMAT
                , kaa_log_level_name[log_level], truncated_name, lineno, error_code);

    if (res_len <= 0)   // Something terrible happened
        return;
    consumed_len += res_len;

    if (consumed_len > self->buffer_size - 2) {
        // Ran out of buffer space already (greedy log buffer:). Reserve space for '\n' and 0 at the end.
        consumed_len = self->buffer_size - 2;
    } else {
        // There's buffer space remaining: print log message body
        va_list args;
        va_start(args, format);
        res_len = ext_logger_sprintf(self->log_buffer + consumed_len
                                   , self->buffer_size - consumed_len
                                   , format
                                   , args);
        va_end(args);

        if (res_len <= 0)   // Something terrible happened
            return;
        consumed_len += res_len;
        if (consumed_len > self->buffer_size - 2) {
            // Ran out of buffer space
            consumed_len = self->buffer_size - 2;
        }
    }

    // Terminate buffer with '\n','\0'. Null-termination is used with buffer length specified.
    self->log_buffer[consumed_len++] = '\n';
    self->log_buffer[consumed_len++] = 0;
    ext_write_log(self->sink, self->log_buffer, consumed_len);
}


text:
package gwt.material.design.addins.client.inputmask;

import gwt.material.design.client.base.NumberBox;
import gwt.material.design.client.ui.MaterialFloatBox;

public class MaterialFloatInputMask extends AbstractInputMask<Float> {

    public MaterialFloatInputMask() {
        super(new NumberBox<>(new NumberBox.NumberHandler<>(new MaterialFloatBox())));
    }

    @Override
    public Float getValue() {
        String cleanValue = getCleanValue();
        if (cleanValue != null && !cleanValue.isEmpty()) {
            return Float.parseFloat(cleanValue);
        }
        return null;
    }
}


text:
using System;
using System.IO;
using System.Reflection;
using bv.common.Core;

namespace bv.common.Diagnostics
{
    public class DebugFileOutput : IDebugOutput
    {

        private string m_FileName;
        public const int MaxLogSize = 1000000;

        public void Init(string fileName, bool overwrite, bool useLock)
        {
            if (Utils.IsEmpty(fileName) && Utils.IsEmpty(m_FileName))
            {
                Assembly exeAssembly = @Assembly.GetEntryAssembly();
                if (exeAssembly != null)
                {
                    m_FileName = Path.ChangeExtension(exeAssembly.Location, ".log");
                }
            }
            if (!Utils.IsEmpty(fileName))
            {
                m_FileName = fileName;
            }
            if (useLock)
            {
                lock (m_LogFileSyncObject)
                {
                    if (overwrite)
                    {
                        DeleteFile(m_FileName);
                    }
                }
            }
            else
            {
                if (overwrite)
                {
                    DeleteFile(m_FileName);
                }
            }
        }

        private void DeleteFile(string fileName)
        {
            try
            {
                if (File.Exists(fileName))
                    File.Delete(fileName);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine("error during deleting debug log file: {0}", ex.ToString());
            }

        }
        public DebugFileOutput()
        {
            Init(null, false, true);
        }

        public DebugFileOutput(string fileName, bool overwrite)
        {
            Init(fileName, overwrite, true);
        }
        public static object m_LogFileSyncObject = new object();

        private StreamWriter CreateWriter()
        {
            try
            {
                if (!File.Exists(m_FileName))
                {
                    var f = File.Create(m_FileName);
                    f.Close();
                }
                FileAttributes attr = File.GetAttributes(m_FileName);
                if ((attr & FileAttributes.ReadOnly) != 0)
                {
                    attr = attr & ~FileAttributes.ReadOnly;
                    File.SetAttributes(m_FileName, attr);
                }
                return new StreamWriter(m_FileName, true);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine("error during opening debug log file writer: {0}", ex.ToString());
                return null;
            }
        }
        public void WriteLine(string line)
        {
            lock (m_LogFileSyncObject)
            {
                StreamWriter writer = CreateWriter();
                if (writer != null)
                {
                    if (writer.BaseStream.Length > MaxLogSize)
                    {
                        try
                        {
                            writer.Close();
                            writer.Dispose();
                            File.Delete(m_FileName);
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Trace.WriteLine("error during deleting debug log file with max log size: {0}", ex.ToString());
                        }
                        finally
                        {
                            Init(null, false, false);
                            writer = CreateWriter();
                        }
                    }
                }
                if (writer != null)
                {
                    using (writer)
                    {
                        try
                        {
                            writer.WriteLine(line);
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Trace.WriteLine("error during writing debug log file: {0}", ex.ToString());
                        }
                        finally
                        {
                            try
                            {
                                writer.Close();
                            }
                            catch
                            {
                            }
                        }
                    }

                }
            }
        }
    }
}