text:
#include "konoha3.h"

#include "konoha3/import/methoddecl.h"
#include <stdio.h>

#ifdef __cplusplus
extern "C" {
#endif

/* ------------------------------------------------------------------------ */

static void kException_AddStackTrace(KonohaContext *kctx, KonohaStack *sfp, kException *e)
{
	kMethod *mtd = sfp[K_MTDIDX].calledMethod;
	KBuffer wb;
	KLIB KBuffer_Init(&kctx->stack->cwb, &wb);
	kfileline_t uline = sfp[K_RTNIDX].calledFileLine;
	if(uline > 0) {
		const char *file = KFileLine_textFileName(uline);
		KLIB KBuffer_printf(kctx, &wb, "(%s:%d) %s.%s%s" , PLATAPI shortFilePath(file), (kuhalfword_t)uline, kMethod_Fmt3(mtd));
	}
//	int i = 0, psize = kMethod_ParamSize(mtd);
//	kParam *pa = kMethod_GetParam(mtd);
//	KClass *thisClass = O_cid(sfp[0]);
//	for(i = 0; i < psize; i++) {
//		pa->paramtypeItems[0].typeAttr;
//		if(i > 0) {
//			knh_putc(ctx, cwb->w, ',');
//		}
//		knh_Write_fn(ctx, cwb->w, p->fn);
//		knh_putc(ctx, cwb->w, '=');
//		knh_Write_sfp(ctx, cwb->w, type, &sfp[i+1], FMT_line);
//	}
	const char *msg = KLIB KBuffer_text(kctx, &wb, EnsureZero);
	KLIB new_kString(kctx, e->StackTraceList, msg, strlen(msg), 0);
//	if((mtd)->mn != MN_LAMBDA) {
//		knh_uline_t uline = knh_stack_uline(ctx, sfp);
//		knh_Write_uline(ctx, cwb->w, uline);
//		knh_Write_type(ctx, cwb->w, (mtd)->cid);
//		knh_putc(ctx, cwb->w, '.');
//		knh_Write_mn(ctx, cwb->w, (mtd)->mn);
//		knh_putc(ctx, cwb->w, '(');
//		knh_putc(ctx, cwb->w, ')');
//		if(DP(e)->tracesNULL == NULL) {
//			KNH_INITv(DP(e)->tracesNULL, new_Array(ctx, CLASS_String, 0));
//		}
//		knh_Array_Add(ctx, DP(e)->tracesNULL, knh_cwb_newString(ctx, cwb));
//	}
}

static kbool_t isCalledMethod(KonohaContext *kctx, KonohaStack *sfp)
{
//	kMethod *mtd = sfp[0].calledMethod;
//	if(knh_isObject(kctx, mtd) && IS_Method(mtd)) {
//		//DBG_P("FOUND calledMethod: shift=%d, pc=%d", sfp[-2].shift, sfp[-1].pc);
//		return true;
//	}
	return false;
}

static void Kthrow(KonohaContext *kctx, KonohaStack *sfp, kException *e)
{
	if(IS_Exception(e)) {
		KonohaStack *p = (sfp == NULL) ? kctx->esp : sfp - 1;
		KonohaStack *bottom = kctx->stack->stack;
		while(bottom < p) {
			if(p[0].calledMethod != NULL && isCalledMethod(kctx, p)) {
				kException_AddStackTrace(kctx, p+1, e);
				p[0].calledMethod = 0;
				//p = p[-1];
			}
			p--;
		}
	}
	KLIB KRuntime_raise(kctx, e->symbol, SoftwareFault, NULL, sfp);
}

/* ------------------------------------------------------------------------ */

//## void System.throw(Object e);
static KMETHOD System_throw(KonohaContext *kctx, KonohaStack *sfp)
{
	KUnsafeFieldSet(kctx->stack->ThrownException, sfp[1].asException);
	Kthrow(kctx, sfp, sfp[1].asException);
}

//## Exception System.getThrownException();
static KMETHOD System_getThrownException(KonohaContext *kctx, KonohaStack *sfp)
{
	//KonohaExceptionContext *ctx = KonohaContext_getExceptionContext(kctx);
	//KReturn(ctx->thrownException);
}

static KMETHOD Exception_new(KonohaContext *kctx, KonohaStack *sfp)
{
	KReturn(sfp[0].asObject);
}

///* ------------------------------------------------------------------------ */
//static kNode *Node_LookupTryOrCatchNodeNULL(KonohaContext *kctx, kNode *stmt)
//{
//	int i;
//	kArray *bka = stmt->parentNodeNULL->NodeList;
//	ksymbol_t trySym = KSymbol_("try");
//	ksymbol_t catchSym = KSymbol_("catch");
//	for(i = 0; kArray_size(bka); i++) {
//		kNode *s = bka->NodeItems[i];
//		if(s == stmt) {
//			break;
//		}
//	}
//
//	for(i = i-1; i >= 0; i--) {
//		kNode *s = bka->NodeItems[i];
//		if(s->syn && (s->syn->keyword == trySym || s->syn->keyword == catchSym)) {
//			return s;
//		}
//	}
//	return NULL;
//}

static KMETHOD Statement_try(KonohaContext *kctx, KonohaStack *sfp)
{
	VAR_TypeCheck(stmt, ns, reqc);
	DBG_P("try statement .. \n");
	int ret = false;
	//kNode *tryNode, *catchNode, *finallyNode;
	//tryNode = KLIB kNode_GetNode(kctx, stmt, NULL, KSymbol_BlockPattern, K_NULLBLOCK);
	//ret = KLIB TypeCheckBlock(kctx, tryNode, gma);
	//if(ret == false) {
	//	KReturnUnboxValue(ret);
	//}

	//catchNode   = KLIB kNode_GetNode(kctx, stmt, NULL, KSymbol_("catch"),   K_NULLBLOCK);
	//finallyNode = KLIB kNode_GetNode(kctx, stmt, NULL, KSymbol_("finally"), K_NULLBLOCK);
	//ret = KLIB TypeCheckBlock(kctx, tryNode,   gma);
	//ret = KLIB TypeCheckBlock(kctx, catchNode, gma);
	//if(ret == false) {
	//	KReturnUnboxValue(ret);
	//}
	//if(finallyNode) {
	//	ret = KLIB TypeCheckBlock(kctx, finallyNode, gma);
	//}
	//if(ret) {
	//	kNode_Type(stmt, TRY);
	//}
	KReturnUnboxValue(ret);
}

static KMETHOD Statement_catch(KonohaContext *kctx, KonohaStack *sfp)
{
	VAR_TypeCheck(stmt, ns, reqc);
	DBG_P("catch statement .. \n");
	int ret = false;

	//// check "catch(...)"
	////ret = KLIB TypeCheckNodeByName(kctx, stmt, KSymbol_NodePattern, ns, KClass_Exception, 0);

	//kNode *catchNode = KLIB kNode_GetNode(kctx, stmt, NULL, KSymbol_NodePattern, K_NULLBLOCK);
	//kNode *parentNode = Node_LookupTryOrCatchNodeNULL(kctx, stmt);

	//if(catchNode != K_NULLBLOCK && parentNode != NULL) {
	//	ret = KLIB TypeCheckBlock(kctx, catchNode, gma);
	//	kNode *expr = KLIB kNode_GetNode(kctx, stmt, KSymbol_NodePattern, K_NULLNODE);
	//	KLIB kObjectProto_SetObject(kctx, parentNode, KSymbol_NodePattern, KType_Exception, expr);
	//	KLIB kObjectProto_SetObject(kctx, parentNode, KSymbol_("catch"), KType_Node, stmt);
	//	kNode_Type(stmt, KNode_Done, KType_void);
	//} else {
	//	kNode_Message(kctx, stmt, ErrTag, "upper stmt is not try/catch");
	//	KReturnUnboxValue(false);
	//}
	KReturnUnboxValue(ret);
}

static KMETHOD Statement_finally(KonohaContext *kctx, KonohaStack *sfp)
{
	VAR_TypeCheck(stmt, ns, reqc);
	DBG_P("finally statement .. \n");
	int ret = false;
	//kNode *finallyNode = KLIB kNode_GetNode(kctx, stmt, NULL, KSymbol_NodePattern, K_NULLBLOCK);

	//if(finallyNode != K_NULLBLOCK) {
	//	kNode *tryNode = Node_LookupTryOrCatchNodeNULL(kctx, stmt);
	//	if(tryNode != NULL) {
	//		ret = KLIB TypeCheckBlock(kctx, finallyNode, gma);
	//		KLIB kObjectProto_SetObject(kctx, tryNode, KSymbol_("finally"), KType_Node, finallyNode);
	//		kNode_Type(stmt, KNode_Done, KType_void);
	//	}
	//}

	KReturnUnboxValue(ret);
}

static kbool_t Exception_PackupNameSpace(KonohaContext *kctx, kNameSpace *ns, int option, KTraceInfo *trace)
{

	KDEFINE_METHOD MethodData[] = {
		_Public, _F(Exception_new), KType_Exception,  KType_Exception, KMethodName_("new"), 0, _Public|_Hidden, _F(System_throw), KType_void,  KType_System, KMethodName_("throw"), 1, KType_Exception, KFieldName_("e"),
		_Public|_Hidden, _F(System_getThrownException), KType_Exception, KType_System, KMethodName_("getThrownException"), 0,
		DEND,
	};
	KLIB kNameSpace_LoadMethodData(kctx, ns, MethodData, trace);

	KDEFINE_SYNTAX SYNTAX[] = {
		{ KSymbol_("try"), SYNFLAG_CTypeFunc, 0, 0, {SUGAR patternParseFunc}, {SUGARFUNC Statement_try}},
		{ KSymbol_("catch"), SYNFLAG_CTypeFunc, 0, 0, {SUGAR patternParseFunc}, {SUGARFUNC Statement_catch}},
		{ KSymbol_("finally"), SYNFLAG_CTypeFunc, 0, 0, {SUGAR patternParseFunc}, {SUGARFUNC Statement_finally}},
		{ KSymbol_END, },
	};
	KLIB kNameSpace_DefineSyntax(kctx, ns, SYNTAX, trace);

	KLIB kSyntax_AddPattern(kctx, kSyntax_(ns, KSymbol_("try")), "\"try\" $Node [ \"catch\" \"(\" $Type $Symbol \")\" catch: $Node ] [ \"finally\" finally: $Node ]", 0, trace);
	KLIB kSyntax_AddPattern(kctx, kSyntax_(ns, KSymbol_("catch")), "\"catch\" \"(\" $Type $Symbol \")\" $Node", 0, trace);
	KLIB kSyntax_AddPattern(kctx, kSyntax_(ns, KSymbol_("finally")), "\"finally\" $Node", 0, trace);

	return true;
}

static kbool_t Exception_ExportNameSpace(KonohaContext *kctx, kNameSpace *ns, kNameSpace *exportNS, int option, KTraceInfo *trace)
{
	return true;
}

KONOHA_EXPORT(KDEFINE_PACKAGE *) Exception_Init(void)
{
	static KDEFINE_PACKAGE d = {0};
	KSetPackageName(d, "Exception", "0.0");
	d.PackupNameSpace   = Exception_PackupNameSpace;
	d.ExportNameSpace   = Exception_ExportNameSpace;
	return &d;
}

#ifdef __cplusplus
}
#endif


text: JAVA Rest toolkit classes for better work with JAX-RS.

redpajama_set_name: RedPajamaGithub


text:
module Bio

  # Bio::FlatFile is a helper and wrapper class to read a biological data file.
  # It acts like a IO object.
  # It can automatically detect data format, and users do not need to tell
  # the class what the data is.
  class FlatFile

    autoload :AutoDetect,          'bio/io/flatfile/autodetection'
    autoload :Splitter,            'bio/io/flatfile/splitter'
    autoload :BufferedInputStream, 'bio/io/flatfile/buffer'

    include Enumerable

    #
    #   Bio::FlatFile.open(file, *arg)
    #   Bio::FlatFile.open(dbclass, file, *arg)
    #
    # Creates a new Bio::FlatFile object to read a file or a stream
    # which contains _dbclass_ data.
    #
    # _dbclass_ should be a class (or module) or nil.
    # e.g. Bio::GenBank, Bio::FastaFormat.
    #
    # If _file_ is a filename (which doesn't have gets method),
    # the method opens a local file named _file_
    # with File.open(filename, *arg).
    #
    # When _dbclass_ is omitted or nil is given to _dbclass_,
    # the method tries to determine database class
    # (file format) automatically.
    # When it fails to determine, dbclass is set to nil
    # and FlatFile#next_entry would fail.
    # You can still set dbclass using FlatFile#dbclass= method.
    #
    # * Example 1
    #     Bio::FlatFile.open(Bio::GenBank, "genbank/gbest40.seq")
    # * Example 2
    #     Bio::FlatFile.open(nil, "embl/est_hum17.dat")
    # * Example 3
    #     Bio::FlatFile.open("genbank/gbest40.seq")
    #
    # * Example 4
    #     Bio::FlatFile.open(Bio::GenBank, $stdin)
    #
    # If it is called with a block, the block will be executed with
    # a new Bio::FlatFile object. If filename is given,
    # the file is automatically closed when leaving the block.
    #
    # * Example 5
    #     Bio::FlatFile.open(nil, 'test4.fst') do |ff|
    #         ff.each { |e| print e.definition, "\n" }
    #     end
    #
    # * Example 6
    #     Bio::FlatFile.open('test4.fst') do |ff|
    #         ff.each { |e| print e.definition, "\n" }
    #     end
    #
    # Compatibility Note:
    # *arg is completely passed to the File.open
    # and you cannot specify ":raw => true" or ":raw => false".
    #
    def self.open(*arg, &block)
      # FlatFile.open(dbclass, file, mode, perm)
      # FlatFile.open(file, mode, perm)
      if arg.size <= 0
        raise ArgumentError, 'wrong number of arguments (0 for 1)'
      end
      x = arg.shift
      if x.is_a?(Module) then
        # FlatFile.open(dbclass, filename_or_io, ...)
        dbclass = x
      elsif x.nil? then
        # FlatFile.open(nil, filename_or_io, ...)
        dbclass = nil
      else
        # FlatFile.open(filename, ...)
        dbclass = nil
        arg.unshift(x)
      end
      if arg.size <= 0
        raise ArgumentError, 'wrong number of arguments (1 for 2)'
      end
      file = arg.shift
      # check if file is filename or IO object
      unless file.respond_to?(:gets)
        # 'file' is a filename
        _open_file(dbclass, file, *arg, &block)
      else
        # 'file' is a IO object
        ff = self.new(dbclass, file)
        block_given? ? (yield ff) : ff
      end
    end

    # Same as Bio::FlatFile.open(nil, filename_or_stream, mode, perm, options).
    #
    # * Example 1
    #    Bio::FlatFile.auto(ARGF)
    # * Example 2
    #    Bio::FlatFile.auto("embl/est_hum17.dat")
    # * Example 3
    #    Bio::FlatFile.auto(IO.popen("gzip -dc nc1101.flat.gz"))
    #
    def self.auto(*arg, &block)
      self.open(nil, *arg, &block)
    end

    # Same as FlatFile.auto(filename_or_stream, *arg).to_a
    #
    # (This method might be OBSOLETED in the future.)
    def self.to_a(*arg)
      self.auto(*arg) do |ff|
        raise 'cannot determine file format' unless ff.dbclass
        ff.to_a
      end
    end

    # Same as FlatFile.auto(filename, *arg),
    # except that it only accept filename and doesn't accept IO object.
    # File format is automatically determined.
    #
    # It can accept a block.
    # If a block is given, it returns the block's return value.
    # Otherwise, it returns a new FlatFile object.
    #
    def self.open_file(filename, *arg)
      _open_file(nil, filename, *arg)
    end

    # Same as FlatFile.open(dbclass, filename, *arg),
    # except that it only accept filename and doesn't accept IO object.
    #
    # It can accept a block.
    # If a block is given, it returns the block's return value.
    # Otherwise, it returns a new FlatFile object.
    #
    def self._open_file(dbclass, filename, *arg)
      if block_given? then
        BufferedInputStream.open_file(filename, *arg) do |stream|
          yield self.new(dbclass, stream)
        end
      else
        stream = BufferedInputStream.open_file(filename, *arg)
        self.new(dbclass, stream)
      end
    end
    private_class_method :_open_file

    # Opens URI specified as _uri_.
    # _uri_ must be a String or URI object.
    # *arg is passed to OpenURI.open_uri or URI#open.
    #
    # Like FlatFile#open, it can accept a block.
    #
    # Note that you MUST explicitly require 'open-uri'.
    # Because open-uri.rb modifies existing class,
    # it isn't required by default.
    #
    def self.open_uri(uri, *arg)
      if block_given? then
        BufferedInputStream.open_uri(uri, *arg) do |stream|
          yield self.new(nil, stream)
        end
      else
        stream = BufferedInputStream.open_uri(uri, *arg)
        self.new(nil, stream)
      end
    end

    # Executes the block for every entry in the stream.
    # Same as FlatFile.open(*arg) { |ff| ff.each { |entry| ... }}.
    #
    # * Example
    #     Bio::FlatFile.foreach('test.fst') { |e| puts e.definition }
    #
    def self.foreach(*arg)
      self.open(*arg) do |flatfileobj|
        flatfileobj.each do |entry|
          yield entry
        end
      end
    end

    # Same as FlatFile.open, except that 'stream' should be a opened
    # stream object (IO, File, ..., who have the 'gets' method).
    #
    # * Example 1
    #    Bio::FlatFile.new(Bio::GenBank, ARGF)
    # * Example 2
    #    Bio::FlatFile.new(Bio::GenBank, IO.popen("gzip -dc nc1101.flat.gz"))
    #
    # Compatibility Note:
    # Now, you cannot specify ":raw => true" or ":raw => false".
    # Below styles are DEPRECATED.
    #
    # * Example 3 (deprecated)
    #    # Bio::FlatFile.new(nil, $stdin, :raw=>true) # => ERROR
    #    # Please rewrite as below.
    #    ff = Bio::FlatFile.new(nil, $stdin)
    #    ff.raw = true
    # * Example 3 in old style (deprecated)
    #    # Bio::FlatFile.new(nil, $stdin, true) # => ERROR
    #    # Please rewrite as below.
    #    ff = Bio::FlatFile.new(nil, $stdin)
    #    ff.raw = true
    #
    def initialize(dbclass, stream)
      # 2nd arg: IO object
      if stream.kind_of?(BufferedInputStream)
        @stream = stream
      else
        @stream = BufferedInputStream.for_io(stream)
      end
      # 1st arg: database class (or file format autodetection)
      if dbclass then
	self.dbclass = dbclass
      else
	autodetect
      end
      #
      @skip_leader_mode = :firsttime
      @firsttime_flag = true
      # default raw mode is false
      self.raw = false
    end

    # The mode how to skip leader of the data.
    # :firsttime :: (DEFAULT) only head of file (= first time to read)
    # :everytime :: everytime to read entry
    # nil :: never skip
    attr_accessor :skip_leader_mode

    # (DEPRECATED) IO object in the flatfile object.
    #
    # Compatibility Note: Bio::FlatFile#io is deprecated.
    # Please use Bio::FlatFile#to_io instead.
    def io
      warn "Bio::FlatFile#io is deprecated."
      @stream.to_io
    end

    # IO object in the flatfile object.
    #
    # Compatibility Note: Bio::FlatFile#io is deprecated.
    def to_io
      @stream.to_io
    end

    # Pathname, filename or URI (or nil).
    def path
      @stream.path
    end

    # Exception class to be raised when data format hasn't been specified.
    class UnknownDataFormatError < IOError
    end

    # Get next entry.
    def next_entry
      raise UnknownDataFormatError,
      'file format auto-detection failed?' unless @dbclass
      if @skip_leader_mode and
          ((@firsttime_flag and @skip_leader_mode == :firsttime) or
             @skip_leader_mode == :everytime)
        @splitter.skip_leader
      end
      if raw then
        r = @splitter.get_entry
      else
        r = @splitter.get_parsed_entry
      end
      @firsttime_flag = false
      return nil unless r
      if raw then
	r
      else
        @entry = r
        @entry
      end
    end
    attr_reader :entry

    # Returns the last raw entry as a string.
    def entry_raw
      @splitter.entry
    end

    # a flag to write down entry start and end positions
    def entry_pos_flag
      @splitter.entry_pos_flag
    end

    # Sets flag to write down entry start and end positions
    def entry_pos_flag=(x)
      @splitter.entry_pos_flag = x
    end

    # start position of the last entry
    def entry_start_pos
      @splitter.entry_start_pos
    end

    # (end position of the last entry) + 1
    def entry_ended_pos
      @splitter.entry_ended_pos
    end

    # Iterates over each entry in the flatfile.
    #
    # * Example
    #    include Bio
    #    ff = FlatFile.open(GenBank, "genbank/gbhtg14.seq")
    #    ff.each_entry do |x|
    #      puts x.definition
    #    end
    def each_entry
      while e = self.next_entry
	yield e
      end
    end
    alias :each :each_entry

    # Resets file pointer to the start of the flatfile.
    # (similar to IO#rewind)
    def rewind
      r = (@splitter || @stream).rewind
      @firsttime_flag = true
      r
    end

    # Closes input stream.
    # (similar to IO#close)
    def close
      @stream.close
    end

    # Returns current position of input stream.
    # If the input stream is not a normal file,
    # the result is not guaranteed.
    # It is similar to IO#pos.
    # Note that it will not be equal to io.pos,
    # because FlatFile has its own internal buffer.
    def pos
      @stream.pos
    end

    # (Not recommended to use it.)
    # Sets position of input stream.
    # If the input stream is not a normal file,
    # the result is not guaranteed.
    # It is similar to IO#pos=.
    # Note that it will not be equal to io.pos=,
    # because FlatFile has its own internal buffer.
    def pos=(p)
      @stream.pos=(p)
    end

    # Returns true if input stream is end-of-file.
    # Otherwise, returns false.
    # (Similar to IO#eof?, but may not be equal to io.eof?,
    # because FlatFile has its own internal buffer.)
    def eof?
      @stream.eof?
    end

    # If true is given, the next_entry method returns
    # a entry as a text, whereas if false, returns as a parsed object.
    def raw=(bool)
      @raw = (bool ? true : false)
    end

    # If true, raw mode.
    attr_reader :raw

    # Similar to IO#gets.
    # Internal use only. Users should not call it directly.
    def gets(*arg)
      @stream.gets(*arg)
    end

    # Sets database class. Plese use only if autodetect fails.
    def dbclass=(klass)
      if klass then
	@dbclass = klass
        begin
          @splitter = @dbclass.flatfile_splitter(@dbclass, @stream)
        rescue NameError, NoMethodError
          begin
            splitter_class = @dbclass::FLATFILE_SPLITTER
          rescue NameError
            splitter_class = Splitter::Default
          end
          @splitter = splitter_class.new(klass, @stream)
        end
      else
	@dbclass = nil
	@splitter = nil
      end
    end

    # Returns database class which is automatically detected or
    # given in FlatFile#initialize.
    attr_reader :dbclass

    # Performs determination of database class (file format).
    # Pre-reads +lines+ lines for format determination (default 31 lines).
    # If fails, returns nil or false. Otherwise, returns database class.
    #
    # The method can be called anytime if you want (but not recommended).
    # This might be useful if input file is a mixture of muitiple format data.
    def autodetect(lines = 31, ad = AutoDetect.default)
      if r = ad.autodetect_flatfile(self, lines)
        self.dbclass = r
      else
        self.dbclass = nil unless self.dbclass
      end
      r
    end

    # Detects database class (== file format) of given file.
    # If fails to determine, returns nil.
    def self.autodetect_file(filename)
      self.open_file(filename).dbclass
    end

    # Detects database class (== file format) of given input stream.
    # If fails to determine, returns nil.
    # Caution: the method reads some data from the input stream,
    # and the data will be lost.
    def self.autodetect_io(io)
      self.new(nil, io).dbclass
    end

    # This is OBSOLETED. Please use autodetect_io(io) instead.
    def self.autodetect_stream(io)
      $stderr.print "Bio::FlatFile.autodetect_stream will be deprecated." if $VERBOSE
      self.autodetect_io(io)
    end

    # Detects database class (== file format) of given string.
    # If fails to determine, returns false or nil.
    def self.autodetect(text)
      AutoDetect.default.autodetect(text)
    end

  end #class FlatFile

end #module Bio


text:
package com.gdn.venice.server.app.finance.presenter.commands;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.djarum.raf.utilities.JPQLAdvancedQueryCriteria;
import com.djarum.raf.utilities.JPQLSimpleQueryCriteria;
import com.djarum.raf.utilities.Locator;
import com.gdn.venice.client.app.DataNameTokens;
import com.gdn.venice.client.app.task.ProcessNameTokens;
import com.gdn.venice.facade.FinSalesRecordSessionEJBRemote;
import com.gdn.venice.facade.VenOrderItemAdjustmentSessionEJBRemote;
import com.gdn.venice.facade.VenOrderPaymentAllocationSessionEJBRemote;
import com.gdn.venice.persistence.FinSalesRecord;
import com.gdn.venice.persistence.VenOrderItemAdjustment;
import com.gdn.venice.persistence.VenOrderPaymentAllocation;
import com.gdn.venice.server.bpmenablement.BPMAdapter;
import com.gdn.venice.server.command.RafDsCommand;
import com.gdn.venice.server.data.RafDsRequest;
import com.gdn.venice.server.data.RafDsResponse;
import com.gdn.venice.server.util.DateToXsdDatetimeFormatter;

public class FetchSalesRecordDataCommand implements RafDsCommand {
	RafDsRequest request;
	String userName;

	public FetchSalesRecordDataCommand(RafDsRequest request, String userName) {
		this.request = request;
		this.userName = userName;
	}

	@Override
	public RafDsResponse execute() {
		JPQLAdvancedQueryCriteria criteria = request.getCriteria();
		JPQLAdvancedQueryCriteria criteriaAndTaskCriteria = null;

		Locator<Object> locator = null;

		//check for taskid parameter, it shall be there if this screen is called from ToDoList for approval purpose
		if (request.getParams()!=null && request.getParams().get(DataNameTokens.TASKID)!=null) {
			String taskId = request.getParams().get(DataNameTokens.TASKID);
			BPMAdapter bpmAdapter = BPMAdapter.getBPMAdapter(userName, BPMAdapter.getUserPasswordFromLDAP(userName));

			bpmAdapter.synchronize();
			HashMap<String,String> wcsOrderIds = bpmAdapter.getExternalDataVariableAsHashMap(new Long(taskId), ProcessNameTokens.WCSORDERID);

			criteriaAndTaskCriteria = new JPQLAdvancedQueryCriteria("and");
			if (criteria!=null) {
				criteriaAndTaskCriteria.add(criteria);
			}
			request.setCriteria(criteriaAndTaskCriteria);

			/*
			 * Build a new simple criteria as an IN() list
			 */
			JPQLSimpleQueryCriteria inCriteria = new JPQLSimpleQueryCriteria();
			inCriteria.setFieldClass(DataNameTokens.getDataNameToken().getFieldClass(DataNameTokens.FINSALESRECORD_VENORDERITEM_VENORDER_WCSORDERID));
			inCriteria.setFieldName(DataNameTokens.FINSALESRECORD_VENORDERITEM_VENORDER_WCSORDERID);

			String wcsOrderIdList = "";
			for(String value:wcsOrderIds.values()){
				if(wcsOrderIdList.isEmpty()){
					wcsOrderIdList = value;
				}
				else{
					wcsOrderIdList = wcsOrderIdList + "," + value;
				}
			}
			inCriteria.setValue(wcsOrderIdList);
			inCriteria.setOperator("IN");

			criteriaAndTaskCriteria.add(inCriteria);
		}

		//Check for journal Group Id, it will be there if the screen is called from Journal Screen
		String journalGroupId = null;
		if (request.getParams()!=null && request.getParams().get(DataNameTokens.FINJOURNALAPPROVALGROUP_JOURNALGROUPID)!=null) {
			journalGroupId = request.getParams().get(DataNameTokens.FINJOURNALAPPROVALGROUP_JOURNALGROUPID);
		}

		RafDsResponse rafDsResponse = new RafDsResponse();
		List<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();

		try {
			locator = new Locator<Object>();
			FinSalesRecordSessionEJBRemote sessionHome = (FinSalesRecordSessionEJBRemote) locator
			.lookup(FinSalesRecordSessionEJBRemote.class, "FinSalesRecordSessionEJBBean");

			List<FinSalesRecord> finSalesRecordList = null;

			//Check for journal Group Id, it will be there if the screen is called from Journal Screen
			//This section queries for finJournalTransactions that are part of the finJournalApprovalGroup
			if (journalGroupId!=null) {
				String select = "select distinct o from FinSalesRecord o join fetch o.finJournalTransactions t where t.finJournalApprovalGroup.journalGroupId = " + journalGroupId;
				finSalesRecordList = sessionHome.queryByRange(select, 0, 50);

			} else {
				if ((criteria == null && criteriaAndTaskCriteria == null)
						|| (criteria!=null && !criteria.getListIterator().hasNext())
						|| (criteriaAndTaskCriteria!=null && !criteriaAndTaskCriteria.getListIterator().hasNext())) {
					String select = "select o from FinSalesRecord o left join o.venOrderItem.venOrder.venOrderPaymentAllocations p";

					finSalesRecordList = sessionHome.queryByRange(select, 0, 50);
				} else {
					FinSalesRecord salesRecord = new FinSalesRecord();
					if (criteriaAndTaskCriteria!=null) {
						finSalesRecordList = sessionHome.findByFinSalesRecordLike(salesRecord, criteriaAndTaskCriteria, 0, 0);
					} else {
						finSalesRecordList = sessionHome.findByFinSalesRecordLike(salesRecord, criteria, 0, 0);
					}
				}
			}

			for (int i=0;i<finSalesRecordList.size();i++) {
				HashMap<String, String> map = new HashMap<String, String>();

				FinSalesRecord salesRecord = finSalesRecordList.get(i);

				DateToXsdDatetimeFormatter formatter = new DateToXsdDatetimeFormatter();

				map.put(DataNameTokens.FINSALESRECORD_SALESRECORDID, (salesRecord.getSalesRecordId()!=null)? salesRecord.getSalesRecordId().toString():"");
				map.put(DataNameTokens.FINSALESRECORD_VENORDERITEM_VENORDER_ORDERDATE, (salesRecord.getVenOrderItem()!=null && salesRecord.getVenOrderItem().getVenOrder()!=null && salesRecord.getVenOrderItem().getVenOrder().getOrderTimestamp()!=null)?formatter.format(new Timestamp(salesRecord.getVenOrderItem().getVenOrder().getOrderDate().getTime()-25200000)):"");
				map.put(DataNameTokens.FINSALESRECORD_VENORDERITEM_VENORDER_WCSORDERID, (salesRecord.getVenOrderItem()!=null && salesRecord.getVenOrderItem().getVenOrder()!=null)? salesRecord.getVenOrderItem().getVenOrder().getWcsOrderId():"");
				map.put(DataNameTokens.FINSALESRECORD_VENORDERITEM_VENMERCHANTPRODUCT_VENMERCHANT_WCSMERCHANTID, (salesRecord.getVenOrderItem()!=null && salesRecord.getVenOrderItem().getVenMerchantProduct()!=null && salesRecord.getVenOrderItem().getVenMerchantProduct().getVenMerchant()!=null)? salesRecord.getVenOrderItem().getVenMerchantProduct().getVenMerchant().getWcsMerchantId():"");
				map.put(DataNameTokens.FINSALESRECORD_VENORDERITEM_VENMERCHANTPRODUCT_VENMERCHANT_VENPARTY_FULLORLEGALNAME, (salesRecord.getVenOrderItem()!=null && salesRecord.getVenOrderItem().getVenMerchantProduct()!=null && salesRecord.getVenOrderItem().getVenMerchantProduct().getVenMerchant()!=null && salesRecord.getVenOrderItem().getVenMerchantProduct().getVenMerchant().getVenParty()!=null)? salesRecord.getVenOrderItem().getVenMerchantProduct().getVenMerchant().getVenParty().getFullOrLegalName():"");
				map.put(DataNameTokens.FINSALESRECORD_VENORDERITEM_WCSORDERITEMID, (salesRecord.getVenOrderItem()!=null)? salesRecord.getVenOrderItem().getWcsOrderItemId():"");
				map.put(DataNameTokens.FINSALESRECORD_VENORDERITEM_VENMERCHANTPRODUCT_WCSPRODUCTNAME, (salesRecord.getVenOrderItem()!=null && salesRecord.getVenOrderItem().getVenMerchantProduct()!=null)? salesRecord.getVenOrderItem().getVenMerchantProduct().getWcsProductName():"");
				map.put(DataNameTokens.FINSALESRECORD_VENORDERITEM_QUANTITY,  (salesRecord.getVenOrderItem()!=null && salesRecord.getVenOrderItem().getQuantity()!=null)? salesRecord.getVenOrderItem().getQuantity().toString():"");
				map.put(DataNameTokens.FINSALESRECORD_VENORDERITEM_PRICE, (salesRecord.getVenOrderItem()!=null && salesRecord.getVenOrderItem().getPrice()!=null)? salesRecord.getVenOrderItem().getPrice().toString():"");
				map.put(DataNameTokens.FINSALESRECORD_VENORDERITEM_TOTAL, (salesRecord.getVenOrderItem()!=null && salesRecord.getVenOrderItem().getTotal()!=null)? salesRecord.getVenOrderItem().getTotal().toString():"");
				map.put(DataNameTokens.FINSALESRECORD_GDNCOMMISIONAMOUNT, (salesRecord.getGdnCommissionAmount()!=null)? salesRecord.getGdnCommissionAmount().toString():"");
				map.put(DataNameTokens.FINSALESRECORD_GDNTRANSACTIONFEEAMOUNT, (salesRecord.getGdnTransactionFeeAmount()!=null)? salesRecord.getGdnTransactionFeeAmount().toString():"");
				map.put(DataNameTokens.FINSALESRECORD_VENORDERITEM_LOGLOGISTICSERVICE_LOGLOGISTICSPROVIDER_PROVIDER_CODE, (salesRecord.getVenOrderItem()!=null && salesRecord.getVenOrderItem().getLogLogisticService() != null && salesRecord.getVenOrderItem().getLogLogisticService().getLogLogisticsProvider() != null)? salesRecord.getVenOrderItem().getLogLogisticService().getLogLogisticsProvider().getLogisticsProviderCode():"");
				map.put(DataNameTokens.FINSALESRECORD_PAYMENT_STATUS, salesRecord.getPaymentStatus() != null?salesRecord.getPaymentStatus():"");
				map.put(DataNameTokens.FINSALESRECORD_VENORDERITEM_VENSETTLEMENTRECORDS_PPH23_FLAG, salesRecord.getVenOrderItem().getVenSettlementRecords()!=null? (salesRecord.getVenOrderItem().getVenSettlementRecords().get(0).getPph23()==true?"Yes":"No"):"");
				map.put(DataNameTokens.FINSALESRECORD_PPH23_AMOUNT, salesRecord.getPph23Amount() != null?salesRecord.getPph23Amount().toString():"");
				map.put(DataNameTokens.FINSALESRECORD_RECONCILEDATE, (salesRecord.getReconcileDate() != null)?formatter.format(new Timestamp(salesRecord.getReconcileDate().getTime()-25200000)):"");
				map.put(DataNameTokens.FINSALESRECORD_SALESTIMESTAMP, (salesRecord.getSalesTimestamp() != null)?formatter.format(new Timestamp(salesRecord.getSalesTimestamp().getTime()-25200000)):"");
				map.put(DataNameTokens.FINSALESRECORD_MCX_DATE, formatter.format(salesRecord.getCxMtaDate()));
				map.put(DataNameTokens.FINSALESRECORD_CXF_DATE, formatter.format(salesRecord.getCxFinanceDate()));

				BigDecimal shippingCost = new BigDecimal(0);
				BigDecimal insuranceCost = new BigDecimal(0);
				BigDecimal shippingAndInsuranceCost = new BigDecimal(0);

				if(salesRecord.getVenOrderItem()!=null && salesRecord.getVenOrderItem().getShippingCost()!=null){
					shippingCost =  salesRecord.getVenOrderItem().getShippingCost();
				}

				if(salesRecord.getVenOrderItem()!=null && salesRecord.getVenOrderItem().getInsuranceCost()!=null){
					insuranceCost = salesRecord.getVenOrderItem().getInsuranceCost();
				}

				shippingAndInsuranceCost = shippingCost.add(insuranceCost);

				map.put(DataNameTokens.FINSALESRECORD_VENORDERITEM_SHIPPINGCOST, (!shippingCost.toString().equals(0)?shippingCost.toString():""));
				map.put(DataNameTokens.FINSALESRECORD_VENORDERITEM_INSURANCECOST,(!insuranceCost.toString().equals(0)?insuranceCost.toString():""));
				map.put(DataNameTokens.FINSALESRECORD_VENORDERITEM_SHIPPINGCOST_INSURANCECOST,(!shippingAndInsuranceCost.toString().equals(0)?shippingAndInsuranceCost.toString():""));
				map.put(DataNameTokens.FINSALESRECORD_GDNHANDLINGFEEAMOUNT, (salesRecord.getGdnHandlingFeeAmount()!=null)? salesRecord.getGdnHandlingFeeAmount().toString():"");

				String commissionType = (salesRecord.getVenOrderItem().getVenSettlementRecords()!=null && salesRecord.getVenOrderItem().getVenSettlementRecords().size() > 0)?salesRecord.getVenOrderItem().getVenSettlementRecords().get(0).getCommissionType():"";
				if(commissionType.equals("CM")){
					commissionType="Commission";
				}else if(commissionType.equals("RB")){
					commissionType="Rebate";
				}else if(commissionType.equals("TD")){
					commissionType="Trading";
				}else if(commissionType.equals("MP")){
					commissionType="Trading MP";
				}else if(commissionType.equals("KS")){
					commissionType="Consignment";
				}else{
					commissionType="";
				}

				map.put(DataNameTokens.FINSALESRECORD_VENORDERITEM_VENSETTLEMENTRECORDS_COMMISIONTYPE, commissionType);

				//get payment data
				VenOrderPaymentAllocationSessionEJBRemote paymentSessionHome = (VenOrderPaymentAllocationSessionEJBRemote) locator.lookup(VenOrderPaymentAllocationSessionEJBRemote.class, "VenOrderPaymentAllocationSessionEJBBean");
				String paymentQuery = "select o from VenOrderPaymentAllocation o where o.venOrder.orderId = " + salesRecord.getVenOrderItem().getVenOrder().getOrderId();

				List<VenOrderPaymentAllocation> paymentList = paymentSessionHome.queryByRange(paymentQuery, 0, 1);
				String paymentType="";
				if(paymentList.size()>0){
					paymentType = paymentList.get(0).getVenOrderPayment().getVenWcsPaymentType().getWcsPaymentTypeCode();
				}

				map.put(DataNameTokens.FINSALESRECORD_VENORDERITEM_VENORDER_VENORDERPAYMENTALLOCATION_VENORDERPAYMENT_VENWCSPAYMENTTYPE_PAYMENTTYPECODE, paymentType);

				//get adjustment data
				VenOrderItemAdjustmentSessionEJBRemote adjustmentSessionHome = (VenOrderItemAdjustmentSessionEJBRemote) locator.lookup(VenOrderItemAdjustmentSessionEJBRemote.class, "VenOrderItemAdjustmentSessionEJBBean");
				String adjustmentQuery = "select o from VenOrderItemAdjustment o where o.venOrderItem.orderItemId = " + salesRecord.getVenOrderItem().getOrderItemId();

				List<VenOrderItemAdjustment> orderItemAdjustmentList = adjustmentSessionHome.queryByRange(adjustmentQuery, 0, 0);

				BigDecimal orderItemAdjustment = new BigDecimal(0);
				StringBuilder orderItemAdjustmentDetail = new StringBuilder();
				if (salesRecord.getVenOrderItem()!=null && orderItemAdjustmentList!=null) {
					for (int j=0;j<orderItemAdjustmentList.size();j++) {
						orderItemAdjustment = orderItemAdjustment.add(orderItemAdjustmentList.get(j).getAmount());
						orderItemAdjustmentDetail = orderItemAdjustmentDetail.append(orderItemAdjustmentList.get(j).getVenPromotion().getPromotionName());
						orderItemAdjustmentDetail = orderItemAdjustmentDetail.append(", Rp ");
						orderItemAdjustmentDetail = orderItemAdjustmentDetail.append(orderItemAdjustmentList.get(j).getAmount());
						if (j < orderItemAdjustmentList.size()-1){
							orderItemAdjustmentDetail = orderItemAdjustmentDetail.append(", ");
						}
					}
				}

				map.put(DataNameTokens.FINSALESRECORD_VENORDERITEM_VENORDERITEMADJUSTMENT_AMOUNT,orderItemAdjustment.toString());
				map.put(DataNameTokens.FINSALESRECORD_GDNGIFTWRAPCHARGEAMOUNT, (salesRecord.getGdnGiftWrapChargeAmount()!=null)? salesRecord.getGdnGiftWrapChargeAmount().toString():"");
				map.put(DataNameTokens.FINSALESRECORD_CUSTOMERDOWNPAYMENT, (salesRecord.getCustomerDownpayment()!=null)? salesRecord.getCustomerDownpayment().toString():"");
				map.put(DataNameTokens.FINSALESRECORD_FINAPPROVALSTATUS_APPROVALSTATUSDESC, (salesRecord.getFinApprovalStatus()!=null)? salesRecord.getFinApprovalStatus().getApprovalStatusDesc():"");
				map.put(DataNameTokens.FINSALESRECORD_VENORDERITEM_VENORDERITEMADJUSTMENT_DETAIL,orderItemAdjustmentDetail.toString());

				dataList.add(map);
			}
			rafDsResponse.setStatus(0);
			rafDsResponse.setStartRow(request.getStartRow());
			rafDsResponse.setTotalRows(dataList.size());
			rafDsResponse.setEndRow(request.getStartRow()+dataList.size());
		} catch (Exception e) {
			e.printStackTrace();
			rafDsResponse.setStatus(-1);
		} finally {
			try {
				if (locator!=null) {
					locator.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		rafDsResponse.setData(dataList);
		return rafDsResponse;
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Pay</title>

Customized Checkout (advanced)

    <form action="" method="post" id="form-pay-mp">
      <input id="amount" type="hidden" value="100"/>

Card number: <input data-checkout="cardNumber" type="text"/>

CVC: <input data-checkout="securityCode" type="text"/>

MM: <input data-checkout="cardExpirationMonth" type="text"/>

YYYY: <input data-checkout="cardExpirationYear" type="text"/>

Card holder name: <input data-checkout="cardholderName" type="text"/>

Id document number: <input data-checkout="docNumber" type="text"/>

      <input data-checkout="docType" type="hidden" value="DNI"/>

Banks: <select id="issuersOptions"></select>

Installments: <select id="installmentsOption"></select>

<input type="submit" value="Make payment">

    </form>


text:
import scala.annotation.tailrec

object FizzBuzz09 {

  def main(args: Array[String]) {

    def fizzbuzzRec(numbers: List[Int]): List[String] = {

      @tailrec
      def fizzbuzzRecLocal(accumulator: List[String],
          numbers: List[Int]): List[String] = {
        numbers match {
          case Nil => accumulator
          case number :: tail => fizzbuzzRecLocal(
            accumulator ::: List(
              number match {
                case x if (x % 3 == 0 && x % 5 == 0) => "FizzBuzz"
                case x if (x % 3 == 0) => "Fizz"
                case x if (x % 5 == 0) => "Buzz"
                case x => x.toString
              }
            ), tail
          )
        }
      }

      fizzbuzzRecLocal(Nil, numbers)
    }

    fizzbuzzRec(1 to 20 toList) foreach println
  }
}


text:
<?php

namespace AvalancheDevelopment\SwaggerRouterMiddleware\Parser;

use Psr\Http\Message\RequestInterface as Request;

class Query implements ParserInterface
{

    use ExplodeTrait;

    /** @var Request */
    protected $request;

    /** @var array */
    protected $parameter;

    /**
     * @param Request $request
     * @param array $parameter
     */
    public function __construct(Request $request, array $parameter)
    {
        $this->request = $request;
        $this->parameter = $parameter;
    }

    /**
     * @return mixed
     */
    public function getValue()
    {
        $query = $this->parseQueryString($this->request);
        if (!array_key_exists($this->parameter['name'], $query)) {
            return;
        }

        $value = $query[$this->parameter['name']];
        if ($this->parameter['type'] !== 'array') {
            return $value;
        }
        if (isset($this->parameter['collectionFormat']) && $this->parameter['collectionFormat'] === 'multi') {
            return (array) $value;
        }
        return $this->explodeValue($value, $this->parameter);
    }

    /**
     * @param Request $request
     * @return array
     */
    protected function parseQueryString(Request $request)
    {
        $params = [];
        $queryString = $request->getUri()->getQuery();
        $setList = explode('&', $queryString);

        foreach ($setList as $set) {
            if (empty($set)) {
                continue;
            }

            list($name, $value) = explode('=', $set);
            $name = urldecode($name);
            if (substr($name, -2) === '[]') {
                $name = substr($name, 0, -2);
            }
            if (!isset($params[$name])) {
                $params[$name] = $value;
                continue;
            }
            if (!is_array($params[$name])) {
                $params[$name] = [$params[$name]];
            }
            array_push($params[$name], $value);
        }

        return $params;
    }
}


text:
package org.jbpm.bpmn2.xml;

import java.util.List;

import org.drools.core.xml.ExtensibleXmlParser;
import org.jbpm.bpmn2.core.SequenceFlow;
import org.jbpm.process.core.context.variable.VariableScope;
import org.jbpm.workflow.core.Node;
import org.jbpm.workflow.core.node.DynamicNode;
import org.w3c.dom.Element;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

public class AdHocSubProcessHandler extends CompositeContextNodeHandler {

    protected Node createNode(Attributes attrs) {
        DynamicNode result = new DynamicNode();
        VariableScope variableScope = new VariableScope();
        result.addContext(variableScope);
        result.setDefaultContext(variableScope);
        return result;
    }

    @SuppressWarnings("unchecked")
	public Class generateNodeFor() {
        return DynamicNode.class;
    }

    @SuppressWarnings("unchecked")
	protected void handleNode(final Node node, final Element element, final String uri,
            final String localName, final ExtensibleXmlParser parser) throws SAXException {
    	super.handleNode(node, element, uri, localName, parser);
    	DynamicNode dynamicNode = (DynamicNode) node;
    	String cancelRemainingInstances = element.getAttribute("cancelRemainingInstances");
    	if ("false".equals(cancelRemainingInstances)) {
    		dynamicNode.setCancelRemainingInstances(false);
    	}
    	// by default it should not autocomplete as it's adhoc
    	dynamicNode.setAutoComplete(false);
    	org.w3c.dom.Node xmlNode = element.getFirstChild();
        while (xmlNode != null) {
        	String nodeName = xmlNode.getNodeName();
        	if ("completionCondition".equals(nodeName)) {
        		String expression = xmlNode.getTextContent();
        		if ("getActivityInstanceAttribute(\"numberOfActiveInstances\") == 0".equals(expression)) {
        			dynamicNode.setAutoComplete(true);
        		} else {
        			dynamicNode.setCompletionExpression(expression == null?"":expression);
        		}
        		org.w3c.dom.Node languageNode = xmlNode.getAttributes().getNamedItem("language");
                if (languageNode != null) {
                    String language = languageNode.getNodeValue();
                    if (XmlBPMNProcessDumper.MVEL_LANGUAGE.equals(language)) {
                        dynamicNode.setLanguage("mvel");
                    } else if (XmlBPMNProcessDumper.RULE_LANGUAGE.equals(language)) {
                        dynamicNode.setLanguage("rule");
                    } else {
                        throw new IllegalArgumentException("Unknown language " + language);
                    }
                } else {
                    dynamicNode.setLanguage("mvel");
                }
        	}
        	xmlNode = xmlNode.getNextSibling();
        }
    	List<SequenceFlow> connections = (List<SequenceFlow>)
			dynamicNode.getMetaData(ProcessHandler.CONNECTIONS);
    	ProcessHandler.linkConnections(dynamicNode, connections);
    	ProcessHandler.linkBoundaryEvents(dynamicNode);

        handleScript(dynamicNode, element, "onEntry");
        handleScript(dynamicNode, element, "onExit");
    }

    public void writeNode(Node node, StringBuilder xmlDump, int metaDataType) {
        DynamicNode dynamicNode = (DynamicNode) node;
		writeNode("adHocSubProcess", dynamicNode, xmlDump, metaDataType);
		if (!dynamicNode.isCancelRemainingInstances()) {
			xmlDump.append(" cancelRemainingInstances=\"false\"");
		}
		xmlDump.append(" ordering=\"Parallel\" >" + EOL);
		writeExtensionElements(dynamicNode, xmlDump);
		// nodes
		List<Node> subNodes = getSubNodes(dynamicNode);
		XmlBPMNProcessDumper.INSTANCE.visitNodes(subNodes, xmlDump, metaDataType);

        // connections
        visitConnectionsAndAssociations(dynamicNode, xmlDump, metaDataType);

        if (dynamicNode.isAutoComplete()) {
        	xmlDump.append("    <completionCondition xsi:type=\"tFormalExpression\">getActivityInstanceAttribute(\"numberOfActiveInstances\") == 0</completionCondition>" + EOL);
        }
		endNode("adHocSubProcess", xmlDump);
	}

}


text:
+++
Categories = []
Description = "[DevOpsDays Chicago](https://devopsdays.org/events/2016-chicago) took place on August 30th & 31st at Summit West in beautiful downtown Chicago. A sold-out, diverse crowd gathered for keynotes, presentations, lightning talks, and open spaces to learn, discuss, and promote all things DevOps."
Tags = []
date = "2016-12-12T16:31:00-06:00"
title = "Chicago 2016 in review"
Author = "Matt Stratton"

+++

*This post, written by Matt Stratton, first appeared on the [Chef Blog](https://blog.chef.io/2016/09/09/chef-devopsdays-chicago-wrap/) on Sept 19, 2016*

[DevOpsDays Chicago](https://devopsdays.org/events/2016-chicago) took place on August 30th & 31st at Summit West in beautiful downtown Chicago. A sold-out, diverse crowd gathered for keynotes, presentations, lightning talks, and open spaces to learn, discuss, and promote all things DevOps.

## Day One
### The Presentations

Leading off the presentations was a keynote by [Adam Jacob](https://twitter.com/adamhjk), who discussed [The Future of Automation](https://www.devopsdays.org/events/2016-chicago/program/adam-jacob). Topics such as the idea of "ubuntu" (not the Linux distro!), context, and the importance of ease over simplicity were markedly well-received by the audience. "When you suffer, I suffer. When you thrive, I thrive."

Other presentations included first-time presenter Joel Vasallo (Gogo), who walked us through ["The Five Phases of DevOps"](https://www.devopsdays.org/events/2016-chicago/program/joel-vasallo). Joel's enthusiasm was contagious, and his animated GIF game was truly on-point.

We can't talk about DevOps in 2016 without a talk about Serverless, and [Jeremy Edberg](https://www.devopsdays.org/events/2016-chicago/program/jeremy-edberg) described moving to AWS Lambda, replete with real-world examples and challenges. Serverless is a hot topic, and I learned quite a bit from his presentation.

Wrapping up the morning was Angela Dugan's talk ["Fear and (Self)-Loathing In IT"](https://www.devopsdays.org/events/2016-chicago/program/angela-dugan).

![imposter syndrome](/blog/2016-chicago/imposter.png)

The key takeaway is that everyone feels like an imposter sometimes – and we are better than we think we are.

### Ignite Sessions

Immediately following lunch were the lightning talk Ignite sessions. For those not familiar, Ignite talks are 5 minutes long consisting of 20 slides that advance every 15 seconds.The Ignite format can be one of the most challenging ways to present a talk (I speak from experience in this!), and all of the Ignites were thought-provoking. They included:

- [Alison Stanton – Ways DevOps Could Be More Accessible](https://www.devopsdays.org/events/2016-chicago/program/alison-stanton)
- [Allie Richards – What's that creature living in my cloud?](https://www.devopsdays.org/events/2016-chicago/program/allie-richards)
- [Jamesha Fisher – Out of the Basement: Demystifying Security and Operations](https://www.devopsdays.org/events/2016-chicago/program/jamesha-fisher)
- [Rebecca Miller-Webster – Building resilience in our organizations, our teams, and ourselves](https://www.devopsdays.org/events/2016-chicago/program/rebecca-miller-webster)
- [Jeff Smith – Dungeons and Dragons….and DevOps](https://www.devopsdays.org/events/2016-chicago/program/jeff-smith)

### Open Spaces

In my mind, the Open Spaces are one of the most powerful and thought-provoking experiences of a DevOpsDays event. As an event organizer, I firmly believe that the main goal of the talks is to drive the discussions in the open spaces. Attendees suggested topics for discussion, and then moved into smaller rooms. The vast majority of attendees had never experienced an Open Space before, and when I spoke with them privately, many told me it was their favorite part of the conference.

### Yakkity Yak (Don't Talk Back)

In DevOps, we often talk about the concept of ["yak shaving."](http://www.hanselman.com/blog/YakShavingDefinedIllGetThatDoneAsSoonAsIShaveThisYak.aspx) At DevOpsDays Chicago, we "leveled up" our commitment for our love of yaks by actually having a yak mascot wandering through the event for participants to take "yak selfies." Some of the best ones can be seen on the [@devopsyak Twitter account](https://www.twitter.com/devopsyak).

![we have a yak](/blog/2016-chicago/yak.png)

### Evening Event

On Tuesday evening, attendees retired to [10pin](http://www.10pinchicago.com/), for a night of board games, delightful beverages and snacks, and bowling! Prizes were awarded for the first people to bowl a turkey (three strikes in a row), and we were pleased to give away not one, but two Amazon Alexa devices for those excellent bowlers.

## Day Two

### Presentations

We kicked off Wednesday with an opening keynote from [Jill Jubinski](https://twitter.com/jilljubs), entitled ["Devopsing Recruitment."](https://www.devopsdays.org/events/2016-chicago/program/jill-jubinski) Jill helped us understand how to be empathetic to recruiters, to understand that they are actually hard-working people who want to help teams get the best people possible, and that there really isn't that big of a divide between recruiters and engineers. Plus, there were a lot of rainbows in the presentation, which makes for good DevOps.

Àbéjídé Àyodélé  followed up with ["Lessons learnt from 'Shipping' Containers,"](https://www.devopsdays.org/events/2016-chicago/program/abejide-ayodele) and he very well might have been the most engaging speaker of the entire event! Àbéjídé dug into some of the challenges his organization had with the lifecycle of their container creation and management, and the audience hung on his every word.

[Nell Shamrell-Harrington](https://twitter.com/nellshamrell) walked us through "Untangling Infrastructure Code Through Refactoring", which was a deep-dive into a practical approach for improving our code for efficiency, readability, and optimization. Nobody can accuse this event of being light on technical content after Àbéjídé and Nell's talks, that is for sure!

Wrapping up the morning was DevOpsDays Chicago alumn Brian Henerey, sharing with us his experiences in ["Leading an Enterprise to the Public Cloud."](https://www.devopsdays.org/events/2016-chicago/program/brian-henerey) Many folks in the audience identified with some of the "enterprise challenges" that Brian experienced, and while he (as he expected), ran out of time, his content was densely packed and very enlightening.

### Ignites

Day two ignites included:

- [Ken Mugrage – The answer to the "where do we start" question](https://www.devopsdays.org/events/2016-chicago/program/ken-mugrage)
- [Heidi Waterhouse – Fear of the Bus](https://www.devopsdays.org/events/2016-chicago/program/heidi-waterhouse)
- [Morgan Rhodes – Presenting Nervously](https://www.devopsdays.org/events/2016-chicago/program/morgan-rhodes)
- [Michael Stahnke – What I've learned interviewing more than 150 people face to face](https://www.devopsdays.org/events/2016-chicago/program/michael-stahnke)
- [Joshua Zimmerman – DevOps Deep Thoughts by Not Jack Handey](https://www.devopsdays.org/events/2016-chicago/program/joshua-zimmerman)

While as an organizer, I should love all of my presenters equally, Josh's Ignite might have been my favorite of the entire conference. It was super hilarious, and one of the most clever approaches I've seen at a DevOpsDays.

![deep thoughts](/blog/2016-chicago/deepthoughts.png)

## Wrap-up

This was the third iteration of DevOpsDays Chicago, and I have been an organizer of all three of them. As an organizer, I can say that this was the most smoothly run event we have ever done. Our content was top-notch, and we had over 380 attendees with a waiting list of over 150 people. In the future, we will be considering what we can do to expand the attendance to allow even more folks to join us in this great experience.

If you attended the event and want to give us feedback, please feel free to tweet to [@devopsdayschi](https://twitter.com/devopsdaysChi)! We would love to hear what you thought.

If you are in the Chicago area, please also join the [Chicago DevOps Meetup group](http://www.meetup.com/devops/) to collaborate with your local peers, and hear even more great talks.


text:
using UnityEngine;

namespace BehaviorDesigner.Runtime.Tasks.Basic.SharedVariables
{
    [TaskCategory("Basic/SharedVariable")]
    [TaskDescription("Gets the Transform from the GameObject. Returns Success.")]
    public class SharedGameObjectToTransform : Action
    {
        [Tooltip("The GameObject to get the Transform of")]
        public SharedGameObject sharedGameObject;
        [RequiredField]
        [Tooltip("The Transform to set")]
        public SharedTransform sharedTransform;

        public override TaskStatus OnUpdate()
        {
            if (sharedGameObject.Value == null) {
                return TaskStatus.Failure;
            }

            sharedTransform.Value = sharedGameObject.Value.GetComponent<Transform>();

            return TaskStatus.Success;
        }

        public override void OnReset()
        {
            sharedGameObject = null;
            sharedTransform = null;
        }
    }
}


text:
package com.bplow.deep.stock.mapper;

import com.bplow.deep.base.pagination.Page;
import com.bplow.deep.stock.domain.SkWarehousePositon;

public interface SkWarehousePositonMapper {
    Page<SkWarehousePositon> queryForPage(SkWarehousePositon record);

    SkWarehousePositon selectByPrimaryKey(String stockId);

    int update(SkWarehousePositon record);

    int insert(SkWarehousePositon record);

    int deleteByPrimaryKey(String stockId);
}


text:
@implementation Search (CoreDataProperties)

@dynamic historySearch;

@end


text:
package org.apache.activemq.artemis.core.server.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.core.server.Queue;
import org.apache.activemq.artemis.core.server.RouteContextList;
import org.apache.activemq.artemis.core.server.RoutingContext;
import org.apache.activemq.artemis.core.transaction.Transaction;

public final class RoutingContextImpl implements RoutingContext
{

   // The pair here is Durable and NonDurable
   private final Map<SimpleString, RouteContextList> map = new HashMap<SimpleString, RouteContextList>();

   private Transaction transaction;

   private int queueCount;

   public RoutingContextImpl(final Transaction transaction)
   {
      this.transaction = transaction;
   }

   public void clear()
   {
      transaction = null;

      map.clear();

      queueCount = 0;
   }

   public void addQueue(final SimpleString address, final Queue queue)
   {

      RouteContextList listing = getContextListing(address);

      if (queue.isDurable())
      {
         listing.getDurableQueues().add(queue);
      }
      else
      {
         listing.getNonDurableQueues().add(queue);
      }

      queueCount++;
   }

   @Override
   public void addQueueWithAck(SimpleString address, Queue queue)
   {
      addQueue(address, queue);
      RouteContextList listing = getContextListing(address);
      listing.addAckedQueue(queue);
   }

   @Override
   public boolean isAlreadyAcked(SimpleString address, Queue queue)
   {
      RouteContextList listing = map.get(address);
      return listing == null ? false : listing.isAlreadyAcked(queue);
   }

   public RouteContextList getContextListing(SimpleString address)
   {
      RouteContextList listing = map.get(address);
      if (listing == null)
      {
         listing = new ContextListing();
         map.put(address, listing);
      }
      return listing;
   }

   public Transaction getTransaction()
   {
      return transaction;
   }

   public void setTransaction(final Transaction tx)
   {
      transaction = tx;
   }

   public List<Queue> getNonDurableQueues(SimpleString address)
   {
      return getContextListing(address).getNonDurableQueues();
   }

   public List<Queue> getDurableQueues(SimpleString address)
   {
      return getContextListing(address).getDurableQueues();
   }

   public int getQueueCount()
   {
      return queueCount;
   }

   public Map<SimpleString, RouteContextList> getContexListing()
   {
      return this.map;
   }

   private static class ContextListing implements RouteContextList
   {
      private final List<Queue> durableQueue = new ArrayList<Queue>(1);

      private final List<Queue> nonDurableQueue = new ArrayList<Queue>(1);

      private final List<Queue> ackedQueues = new ArrayList<>();

      public int getNumberOfDurableQueues()
      {
         return durableQueue.size();
      }

      public int getNumberOfNonDurableQueues()
      {
         return nonDurableQueue.size();
      }

      @Override
      public List<Queue> getDurableQueues()
      {
         return durableQueue;
      }

      @Override
      public List<Queue> getNonDurableQueues()
      {
         return nonDurableQueue;
      }

      @Override
      public void addAckedQueue(Queue queue)
      {
         ackedQueues.add(queue);
      }

      @Override
      public boolean isAlreadyAcked(Queue queue)
      {
         return ackedQueues.contains(queue);
      }
   }

}


text:
import { valueOf } from './meta';

import Storage from './storage';
import Pathmap from './pathmap';

export default function Identity(microstate, observe = x => x) {
  let { Type } = microstate.constructor;
  let pathmap = Pathmap(Type, new Storage(valueOf(microstate), () => observe(pathmap.get())));
  return pathmap.get();
}


text:
In both options below, the [device authorization grant flow](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-device-code) is used.

In order to connect to Microsoft Teams Management using either Cortex XSOAR Azure App or the Self-Deployed Azure App:
1. Fill in the required parameters.
2. Run the ***!microsoft-teams-auth-start*** command.
3. Follow the instructions that appear.
4. Run the ***!microsoft-teams-auth-complete*** command.

At end of the process you'll see a message that you've logged in successfully.

#### Cortex XSOAR Azure App

In order to use the Cortex XSOAR Azure application, use the default application ID (3307a0ab-612c-47af-b3b5-8208247562db).

#### Self-Deployed Azure App

To use a self-configured Azure application, you need to add a new Azure App Registration in the Azure Portal, with mobile and desktop flows enabled.

Required Permissions
* Group.ReadWrite.All - Application
* Team.ReadBasic.All - Application
* TeamMember.ReadWrite.All - Application


text:
<?php

namespace frontend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\ElaporanPelaksanaanObjektif;

/**
 * ElaporanPelaksanaanObjektifSearch represents the model behind the search form about `app\models\ElaporanPelaksanaanObjektif`.
 */
class ElaporanPelaksanaanObjektifSearch extends ElaporanPelaksanaanObjektif
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['elaporan_pelaksanaan_objektif_id', 'elaporan_pelaksaan_id'], 'integer'],
            [['objektif_pelaksanaan', 'session_id'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = ElaporanPelaksanaanObjektif::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'elaporan_pelaksanaan_objektif_id' => $this->elaporan_pelaksanaan_objektif_id,
            'elaporan_pelaksaan_id' => $this->elaporan_pelaksaan_id,
        ]);

        $query->andFilterWhere(['like', 'objektif_pelaksanaan', $this->objektif_pelaksanaan])
                ->andFilterWhere(['like', 'session_id', $this->session_id]);

        return $dataProvider;
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Xml;

#if SILVERLIGHTXAML
using MS.Internal.Xaml.Parser;
using MS.Internal.Xaml.MS.Impl;
using MS.Internal.Xaml.Context;
#else
using System.Xaml.Parser;
using System.Xaml.MS.Impl;
using System.Windows.Markup;
#endif

#if SILVERLIGHTXAML
namespace MS.Internal.Xaml
#else
namespace System.Xaml
#endif
{
#if SILVERLIGHTXAML
    internal
#else
    public
#endif
    class XamlTextReader : XamlReader, IXamlLineInfo
    {
        XamlParserContext _context;
        IEnumerator<XamlNode> _nodeStream;

        XamlNode _current;
        XamlNode _endOfStreamNode;

        XamlTextReaderSettings _mergedSettings;

        public XamlTextReader(XmlReader xmlReader)
        {
            Initialize(xmlReader, null, null);
        }

        public XamlTextReader(XmlReader xmlReader, XamlTextReaderSettings settings)
        {
            Initialize(xmlReader, null, settings);
        }

        public XamlTextReader(XmlReader xmlReader, XamlSchemaContext schemaContext)
        {
            if (schemaContext == null)
                throw new ArgumentNullException("schemaContext");

            Initialize(xmlReader, schemaContext, null);
        }

        public XamlTextReader(XmlReader xmlReader, XamlSchemaContext schemaContext, XamlTextReaderSettings settings)
        {
            if (schemaContext == null)
                throw new ArgumentNullException("schemaContext");

            Initialize(xmlReader, schemaContext, settings);
        }

        private void Initialize(XmlReader givenXmlReader, XamlSchemaContext schemaContext, XamlTextReaderSettings settings)
        {
            XmlReader myXmlReader;

            if (givenXmlReader == null)
            {
                throw new ArgumentNullException("XmlReader is null");
            }

            _mergedSettings = (settings == null) ? new XamlTextReaderSettings() : new XamlTextReaderSettings(settings);

            //Wrap the xmlreader with a XmlCompatReader instance to apply MarkupCompat rules.
            if (!_mergedSettings.SkipXmlCompatibilityProcessing)
            {
                XmlCompatibilityReader mcReader =
                        new XmlCompatibilityReader(givenXmlReader,
                                new IsXmlNamespaceSupportedCallback(IsXmlNamespaceSupported)
                        );
                myXmlReader = mcReader;
            }
            else
            {   // Don't wrap the xmlreader with XmlCompatReader.
                // Useful for uses where users want to keep mc: content in the XamlNode stream.
                // Or have already processed the markup compat and want that extra perf.
                // We need to go make sure the parser thinks it knows mc: uri,
                // in case SkipXmlCompatibilityProcessing is true... likely won't work yet.
                myXmlReader = givenXmlReader;
            }
            // Pick up the XmlReader settings to override the "settings" defaults.
            if (!String.IsNullOrEmpty(myXmlReader.BaseURI))
            {
                _mergedSettings.BaseUri = new Uri(myXmlReader.BaseURI);
            }
            if (myXmlReader.XmlSpace == XmlSpace.Preserve)
            {
                _mergedSettings.XmlSpacePreserve = true;
            }
            if (!String.IsNullOrEmpty(myXmlReader.XmlLang))
            {
                _mergedSettings.XmlLang = myXmlReader.XmlLang;
            }

            if (schemaContext == null)
            {
                schemaContext = new XamlSchemaContext();
            }

            _endOfStreamNode = new InternalNode(InternalNodeType.EndOfStream);

            _context = (XamlParserContext)XamlContext.CreateContext(UsageMode.Parser, schemaContext,
                                                            _mergedSettings.LocalAssembly, false /*ignoreCanConvert*/);

            XamlScanner xamlScanner = new XamlScanner(_context, myXmlReader, _mergedSettings);
            XamlPullParser parser = new XamlPullParser(_context, xamlScanner, _mergedSettings);
            _nodeStream = new NodeStreamSorter(_context, parser, _mergedSettings);
            _current = _endOfStreamNode;  // user must call Read() before using properties.
        }

        #region XamlReader Members

        public override bool Read()
        {
            if (_nodeStream.MoveNext())
            {
                _current = _nodeStream.Current;
            }
            else
            {
                _current = _endOfStreamNode;
            }
            return !IsEof;
        }

        public override XamlNodeType NodeType
        {
            get { return _current.NodeType; }
        }

        public override bool IsEof
        {
            get { return XamlNode.IsEof(_current); }
        }

        public override NamespaceDeclaration Namespace
        {
            get { return XamlNode.GetNamespaceDeclaration(_current); }
        }

        public override XamlType Type
        {
            get { return XamlNode.GetXamlType(_current); }
        }

        public override object Value
        {
            get { return XamlNode.GetValue(_current); }
        }

        public override XamlProperty Member
        {
            get { return XamlNode.GetMember(_current); }
        }

        public override XamlSchemaContext SchemaContext
        {
            get { return _context.SchemaContext; }
        }

        public override bool IsObjectFromMember
        {
            get { return XamlNode.GetIsObjectFromMember(_current); }
        }

        #endregion

        #region IXamlLineInfo Members

        public bool HasLineInfo
        {
            get { return _mergedSettings.ProvideLineInfo; }
        }

        public int LineNumber
        {
            get { return XamlNode.GetLineNumber(_current); }
        }

        public int LinePosition
        {
            get { return XamlNode.GetLinePosition(_current); }
        }

        #endregion

        // Return true if the passed namespace is known, meaning that it maps
        // to a set of assemblies and clr namespaces
        internal bool IsXmlNamespaceSupported(string xmlNamespace, out string newXmlNamespace)
        {
            newXmlNamespace = null;

            bool isSupported = _context.SchemaContext.XamlNamespaceExists(xmlNamespace, _mergedSettings.LocalAssembly);
            newXmlNamespace = xmlNamespace; // should probalby be upgraded via CompatibleWith

            // we should treat all namespaces inside of XmlDataIslands as Supported.
            return isSupported;

            // we need to tree Freeze as known, if it is around... don't hardcode.
            //else if (xmlNamespace == XamlReaderHelper.PresentationOptionsNamespaceURI)
            //{
            //    // PresentationOptions is expected to be marked as 'ignorable' in most Xaml
            //    // so that other Xaml parsers don't have to interpret it, but this parser
            //    // does handle it to support it's Freeze attribute.
            //    return true;
            //}
        }

    }
}


text:
title: Nextech PD
---

# Nextech Professional Development

This workshop is being run by our regional partner for the state of Indiana, Nextech.  Please [visit their website](http://www.nextech.org) for more information about partnerships in the state.

## Exploring Computer Science

### Phase 1: Online Introduction (~2 hours) ###

The first phase of professional development is a two-hour introduction that focuses on providing a foundational knowledge of the ECS course resources. It creates a space for participants to become familiar with the curriculum and online PD platform.

### Phase 2: Blended Summer Study (5 days in-person & ~8 hours online) ###

**Save the dates:**

Monday, July 20, 2015 - Friday, July 24, 2015

Mon - Thurs: 8:30am - 3:30pm

Friday: 8:30am - 1:30pm

Breakfast and lunch will be served.

[Please reach out to nextech](mailto:pd@nextech.org) for more information about this workshop.

**What do I bring to Phase 2?**

Water Bottle

Snacks

Laptop optional, not required

### Phase 3: Academic Year Development (4 Saturdays in-person & ~12 hours online) ###

Phase 3 is composed of quarterly in-person meetings and monthly online activities. The meetings will continue to build pedagogical strategies and explore the essential elements of ECS. You will participate in activities such as teaching new content and keeping the classroom environment equitable and engaging for all students.

**Save the dates:**

Quarter 1: Saturday, October 10, 2015

Quarter 2: Saturday, December 5, 2015

Quarter 3: Saturday, January 9, 2016

Quarter 4: Saturday, May 7, 2016

8:30am - 3:30pm

Breakfast and lunch will be served.

**Location**

TBD

**What to bring to Phase 3 quarterly sessions:**

Laptop

ECS green journal and curriculum guide

Snacks

Water

### Phase 4: Summer Wrap-up (3 days in-person - Summer 2016) ###

More info coming soon!

[**Back to the top**](#top)


text:
namespace bookmarks {

namespace {

// Extension used for backup files (copy of main file created during startup).
const base::FilePath::CharType kBackupExtension[] = FILE_PATH_LITERAL("bak");

void BackupCallback(const base::FilePath& path) {
  base::FilePath backup_path = path.ReplaceExtension(kBackupExtension);
  base::CopyFile(path, backup_path);
}

}  // namespace

// static
constexpr base::TimeDelta BookmarkStorage::kSaveDelay;

BookmarkStorage::BookmarkStorage(BookmarkModel* model,
                                 const base::FilePath& profile_path)
    : model_(model),
      backend_task_runner_(base::ThreadPool::CreateSequencedTaskRunner(
          {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
           base::TaskShutdownBehavior::BLOCK_SHUTDOWN})),
      writer_(profile_path.Append(kBookmarksFileName),
              backend_task_runner_,
              kSaveDelay,
              "BookmarkStorage") {}

BookmarkStorage::~BookmarkStorage() {
  if (writer_.HasPendingWrite())
    writer_.DoScheduledWrite();
}

void BookmarkStorage::ScheduleSave() {
  // If this is the first scheduled save, create a backup before overwriting the
  // JSON file.
  if (!backup_triggered_) {
    backup_triggered_ = true;
    backend_task_runner_->PostTask(
        FROM_HERE, base::BindOnce(&BackupCallback, writer_.path()));
  }

  writer_.ScheduleWriteWithBackgroundDataSerializer(this);
}

void BookmarkStorage::BookmarkModelDeleted() {
  // We need to save now as otherwise by the time SerializeData() is invoked
  // the model is gone.
  if (writer_.HasPendingWrite()) {
    writer_.DoScheduledWrite();
    DCHECK(!writer_.HasPendingWrite());
  }

  model_ = nullptr;
}

base::ImportantFileWriter::BackgroundDataProducerCallback
BookmarkStorage::GetSerializedDataProducerForBackgroundSequence() {
  BookmarkCodec codec;
  base::Value value(
      codec.Encode(model_, model_->client()->EncodeBookmarkSyncMetadata()));

  return base::BindOnce(
      [](base::Value value, std::string* output) {
        // This runs on the background sequence.
        JSONStringValueSerializer serializer(output);
        serializer.set_pretty_print(true);
        return serializer.Serialize(value);
      },
      std::move(value));
}

bool BookmarkStorage::HasScheduledSaveForTesting() const {
  return writer_.HasPendingWrite();
}

}  // namespace bookmarks


text:
namespace {
  typedef std::tuple<int, int> tuple1;
  typedef std::tuple<float, float> tuple2;
  typedef std::tuple<float, std::tuple<float>> tuple3;

  static_assert(CompileUtils::is_tuple_convertible<tuple1, tuple2>::value,
      "Tuple values can't be converted");
  static_assert(!CompileUtils::is_tuple_convertible<tuple1, tuple3>::value,
      "Tuple values can be converted");
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mbean PUBLIC "-//JBoss//DTD JBOSS XMBEAN 1.1//EN" "http://www.jboss.org/j2ee/dtd/jboss_xmbean_1_1.dtd">

<mbean>
   <description>DICOM Storage Commitment SCU/SCP. Provides a DICOM Storage
   Commitment Service in the Service Class Provider
   (SCP) and the Service Class User (SCU) Role. When acting as the SCP,
   the service handles storage commitment requests that it receives
   from modalities or evidence creators (workstations).
   When acting as the SCU, it may request storage
   commitment for objects for itself that were retrieved from the archive to a remote
   application. Typically this application is a further archive
   instance acting as a long-term or central archive.</description>

   <descriptors>
      <persistence persistPolicy="OnUpdate"/>
      <persistence-manager value="org.jboss.mx.persistence.DelegatingPersistenceManager"/>
   </descriptors>

   <class>org.dcm4chex.archive.dcm.stgcmt.StgCmtScuScpService</class>

   <constructor>
      <description>The default constructor</description>
      <name>StgCmtScuScpService</name>
   </constructor>

   <attribute access="read-write"
      getMethod="getCalledAETs"
      setMethod="setCalledAETs">
      <description>Accepted called AE titles, separated by \ (backslash).
      </description>
      <name>CalledAETitles</name>
      <type>java.lang.String</type>
      <descriptors>
         <value value="DCM4CHEE"/>
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="getCallingAETs"
      setMethod="setCallingAETs">
      <description><![CDATA[
      	List of accepted calling AE titles, separated by \(backslash).

      	ANY = accept any.

      	CONFIGURED_AETS = accept any configured AE Title.
      	]]>
      </description>
      <name>CallingAETitles</name>
      <type>java.lang.String</type>
      <descriptors>
         <value value="ANY"/>
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="getReceiveResultInSameAssocTimeout"
      setMethod="setReceiveResultInSameAssocTimeout">
      <description>Time in milliseconds that the Storage Commit SCU waits to
      receive the Storage Commit Result in the same association
      as the storage commit was requested, before releasing the association.
      </description>
      <name>ReceiveResultInSameAssociationTimeout</name>
      <type>long</type>
      <descriptors>
         <value value="0"/>
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="getScuRetryIntervalls"
      setMethod="setScuRetryIntervalls">
      <description><![CDATA[Number and interval of retries by the SCU to invoke
      Storage Commitment Requests.

Format:

Comma separated list of number x interval pairs.

The interval can be specified in seconds (##s),
      minutes (##m), hours (##h) or days (##d).

Example:

5x1m,10x10m means retry a total of 5 times, one minute
      apart for each retry; then retry a total of 10 times, 10 minutes
      apart for each retry.]]>
      </description>
      <name>SCURetryIntervals</name>
      <type>java.lang.String</type>
      <descriptors>
         <value value="5x1m,12x5m"/>
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="getScpRetryIntervalls"
      setMethod="setScpRetryIntervalls">
      <description><![CDATA[Number and interval of retries by the SCP to send
      Storage Commitment Results to the SCU.

Format:

Comma separated list of numberxinterval pairs.

The interval can be specified in seconds (##s),
      minutes (##m), hours (##h) or days (##d).

Example: 5x1m,10x10m means retry a total of 5 times, one minute
      apart for each retry; then retry a total of 10 times, 10 minutes
      apart for each retry.]]>
      </description>
      <name>SCPRetryIntervals</name>
      <type>java.lang.String</type>
      <descriptors>
         <value value="5x1m,12x5m"/>
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="getAcceptedTransferSyntax"
      setMethod="setAcceptedTransferSyntax">
      <description><![CDATA[
        List of accepted Transfer Syntaxes. Order defines selection preference.
        Use either the  Transfer Syntaxes UID value or following defined
        symbolic names:
        ImplicitVRLittleEndian,
        ExplicitVRLittleEndian,
        DeflatedExplicitVRLittleEndian,
        ExplicitVRBigEndian
        ]]>
      </description>
      <name>AcceptedTransferSyntax</name>
      <type>java.lang.String</type>
      <descriptors>
         <value value="
           ExplicitVRLittleEndian
           ImplicitVRLittleEndian
         "/>
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="getConcurrency"
      setMethod="setConcurrency">
      <description>Maximum number of concurrent invoked or processed
      Storage Commit Requests.
      </description>
      <name>Concurrency</name>
      <type>int</type>
      <descriptors>
         <value value="1"/>
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="getMaxPDULength"
      setMethod="setMaxPDULength">
      <description>Maximum protocol data unit (PDU) package length for receiving PDUs.
      Attention: This property should be set to equal values for all DICOM SCP
      services with same called AE Title(s)! Otherwise it is non-deterministic,
      which configured value is effective!
      </description>
      <name>MaximumPDULength</name>
      <type>int</type>
      <descriptors>
         <value value="16352"/>
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="getMaxOpsInvoked"
      setMethod="setMaxOpsInvoked">
      <description>The maximum number of outstanding operations and/or
      sub-operations it allows the Association-requester to invoke asynchronously.
      A value of zero indicates an unlimited number of outstanding operations.
      Attention: This property should be set to equal values for all DICOM SCP
      services with same called AE Title(s)! Otherwise it is non-deterministic,
      which configured value is effective!
      </description>
      <name>MaximumOperationsInvoked</name>
      <type>int</type>
      <descriptors>
         <value value="1"/>
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="getMaxOpsPerformed"
      setMethod="setMaxOpsPerformed">
      <description>The maximum number of outstanding operations and/or
      sub-operations it allows the Association-requester to perform asynchronously.
      A value of zero indicates an unlimited number of outstanding operations.
      Attention: This property should be set to equal values for all DICOM SCP
      services with same called AE Title(s)! Otherwise it is non-deterministic,
      which configured value is effective!
      </description>
      <name>MaximumOperationsPerformed</name>
      <type>int</type>
      <descriptors>
         <value value="1"/>
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="getAcTimeout"
      setMethod="setAcTimeout">
      <description>A-Associate accept timeout in milliseconds. 0 = no timeout.
      </description>
      <name>AcceptTimeout</name>
      <type>int</type>
      <descriptors>
         <value value="10000"/>
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="getDimseTimeout"
      setMethod="setDimseTimeout">
      <description>DIMSE message timeout in milliseconds. 0 = no timeout.
      </description>
      <name>DIMSETimeout</name>
      <type>int</type>
      <descriptors>
         <value value="60000"/>
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="getSoCloseDelay"
      setMethod="setSoCloseDelay">
      <description>Socket close delay in milliseconds after an A-Release response.
      </description>
      <name>SocketCloseDelay</name>
      <type>int</type>
      <descriptors>
         <value value="50"/>
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="isTcpNoDelay"
      setMethod="setTcpNoDelay">
      <description>Send packets as quickly as possible (Disable Nagle's algorithmn).
      </description>
      <name>TcpNoDelay</name>
      <type>boolean</type>
      <descriptors>
         <value value="true" />
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="getSendBufferSize"
      setMethod="setSendBufferSize">
      <description>Buffer size used for socket output. 0 = use platform default.
      </description>
      <name>SendBufferSize</name>
      <type>int</type>
      <descriptors>
         <value value="0" />
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="getReceiveBufferSize"
      setMethod="setReceiveBufferSize">
      <description>Buffer size used for socket input. 0 = use platform default.
      </description>
      <name>ReceiveBufferSize</name>
      <type>int</type>
      <descriptors>
         <value value="0" />
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="getQueueName"
      setMethod="setQueueName">
      <description>Used internally. Do NOT modify.
      </description>
      <name>QueueName</name>
      <type>java.lang.String</type>
   </attribute>
   <attribute access="read-write"
      getMethod="getJmsServiceName"
      setMethod="setJmsServiceName">
      <description>Used internally. Do NOT modify.
      </description>
      <name>JMSServiceName</name>
      <type>javax.management.ObjectName</type>
   </attribute>
   <attribute access="read-write"
      getMethod="getFileSystemMgtName"
      setMethod="setFileSystemMgtName">
      <description>Used internally. Do NOT modify.
      </description>
      <name>FileSystemMgtName</name>
      <type>javax.management.ObjectName</type>
   </attribute>
   <attribute access="read-write"
      getMethod="getDcmServerName"
      setMethod="setDcmServerName">
      <description>Used internally. Do NOT modify.
      </description>
      <name>DcmServerName</name>
      <type>javax.management.ObjectName</type>
   </attribute>
   <attribute access="read-write"
      getMethod="getTLSConfigName"
      setMethod="setTLSConfigName">
      <description>Used internally. Do NOT modify.
      </description>
      <name>TLSConfigName</name>
      <type>javax.management.ObjectName</type>
   </attribute>
   <attribute access="read-write"
      getMethod="getAEServiceName"
      setMethod="setAEServiceName">
      <description>Used internally. Do NOT modify.
      </description>
      <name>AEServiceName</name>
      <type>javax.management.ObjectName</type>
   </attribute>
   &defaultAttributes;

   &defaultOperations;
   <operation impact="ACTION">
      <description>Used internally.</description>
      <name>queueStgCmtOrder</name>
      <parameter>
        <name>calling</name>
        <type>java.lang.String</type>
      </parameter>
      <parameter>
        <name>called</name>
        <type>java.lang.String</type>
      </parameter>
      <parameter>
        <name>actionInfo</name>
        <type>org.dcm4che.data.Dataset</type>
      </parameter>
      <parameter>
        <name>scpRole</name>
        <type>boolean</type>
      </parameter>
      <return-type>void</return-type>
   </operation>

</mbean>


text:
namespace Microsoft.Exchange.WebServices.Autodiscover
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.DirectoryServices;
    using System.DirectoryServices.ActiveDirectory;
    using System.Runtime.InteropServices;
    using Microsoft.Exchange.WebServices.Data;

    /// <summary>
    /// Represents a set of helper methods for using Active Directory services.
    /// </summary>
    internal class DirectoryHelper
    {
        #region Static members

        /// <summary>
        /// Maximum number of SCP hops in an SCP host lookup call.
        /// </summary>
        private const int AutodiscoverMaxScpHops = 10;

        /// <summary>
        /// GUID for SCP URL keyword
        /// </summary>
        private const string ScpUrlGuidString = @"77378F46-2C66-4aa9-A6A6-3E7A48B19596";

        /// <summary>
        /// GUID for SCP pointer keyword
        /// </summary>
        private const string ScpPtrGuidString = @"67661d7F-8FC4-4fa7-BFAC-E1D7794C1F68";

        /// <summary>
        /// Filter string to find SCP Ptrs and Urls.
        /// </summary>
        private const string ScpFilterString = "(&(objectClass=serviceConnectionPoint)(|(keywords=" + ScpPtrGuidString + ")(keywords=" + ScpUrlGuidString + ")))";

        #endregion

        #region Private members

        private ExchangeServiceBase service;

        #endregion

        /// <summary>
        /// Gets the SCP URL list for domain.
        /// </summary>
        /// <param name="domainName">Name of the domain.</param>
        /// <returns>List of Autodiscover URLs</returns>
        public List<string> GetAutodiscoverScpUrlsForDomain(string domainName)
        {
            int maxHops = AutodiscoverMaxScpHops;
            List<string> scpUrlList;

            try
            {
                scpUrlList = this.GetScpUrlList(domainName, null, ref maxHops);
            }
            catch (InvalidOperationException e)
            {
                this.TraceMessage(
                    string.Format("LDAP call failed, exception: {0}", e.ToString()));
                scpUrlList = new List<string>();
            }
            catch (NotSupportedException e)
            {
                this.TraceMessage(
                    string.Format("LDAP call failed, exception: {0}", e.ToString()));
                scpUrlList = new List<string>();
            }
            catch (COMException e)
            {
                this.TraceMessage(
                    string.Format("LDAP call failed, exception: {0}", e.ToString()));
                scpUrlList = new List<string>();
            }

            return scpUrlList;
        }

        /// <summary>
        /// Search Active Directory for any related SCP URLs for a given domain name.
        /// </summary>
        /// <param name="domainName">Domain name to search for SCP information</param>
        /// <param name="ldapPath">LDAP path to start the search</param>
        /// <param name="maxHops">The number of remaining allowed hops</param>
        private List<string> GetScpUrlList(
           string domainName,
           string ldapPath,
           ref int maxHops)
        {
            if (maxHops <= 0)
            {
                throw new ServiceLocalException(Strings.MaxScpHopsExceeded);
            }

            maxHops--;

            this.TraceMessage(
                string.Format("Starting SCP lookup for domainName='{0}', root path='{1}'", domainName, ldapPath));

            string scpUrl = null;
            string fallBackLdapPath = null;
            string rootDsePath = null;
            string configPath = null;

            // The list of SCP URLs.
            List<string> scpUrlList = new List<string>();

            // Get the LDAP root path.
            rootDsePath = (ldapPath == null) ? "LDAP://RootDSE" : ldapPath + "/RootDSE";

            // Get the root directory entry.
            using (DirectoryEntry rootDseEntry = new DirectoryEntry(rootDsePath))
            {
                // Get the configuration path.
                configPath = rootDseEntry.Properties["configurationNamingContext"].Value as string;
            }

            // The container for SCP pointers and URLs objects from Active Directory
            SearchResultCollection scpDirEntries = null;

            try
            {
                // Get the configuration entry path.
                using (DirectoryEntry configEntry = new DirectoryEntry("LDAP://" + configPath))
                {
                    // Use the configuration entry path to create a query.
                    using (DirectorySearcher configSearcher = new DirectorySearcher(configEntry))
                    {
                        // Filter for Autodiscover SCP URLs and SCP pointers.
                        configSearcher.Filter = ScpFilterString;

                        // Identify properties to retrieve using the the query.
                        configSearcher.PropertiesToLoad.Add("keywords");
                        configSearcher.PropertiesToLoad.Add("serviceBindingInformation");

                        this.TraceMessage(
                            string.Format("Searching for SCP entries in {0}", configEntry.Path));

                        // Query Active Directory for SCP entries.
                        scpDirEntries = configSearcher.FindAll();
                    }
                }

                // Identify the domain to match.
                string domainMatch = "Domain=" + domainName;

                // Contains a pointer to the LDAP path of a SCP object.
                string scpPtrLdapPath;

                this.TraceMessage(
                    string.Format("Scanning for SCP pointers {0}", domainMatch));

                foreach (SearchResult scpDirEntry in scpDirEntries)
                {
                    ResultPropertyValueCollection entryKeywords = scpDirEntry.Properties["keywords"];

                    // Identify SCP pointers.
                    if (entryKeywords.CaseInsensitiveContains(ScpPtrGuidString))
                    {
                        // Get the LDAP path to SCP pointer.
                        scpPtrLdapPath = scpDirEntry.Properties["serviceBindingInformation"][0] as string;

                        // If the SCP pointer matches the user's domain, then restart search from that point.
                        if (entryKeywords.CaseInsensitiveContains(domainMatch))
                        {
                            // Stop the current search, start another from a new location.
                            this.TraceMessage(
                                string.Format(
                                    "SCP pointer for '{0}' is found in '{1}', restarting seach in '{2}'",
                                    domainMatch,
                                    scpDirEntry.Path,
                                    scpPtrLdapPath));

                            return this.GetScpUrlList(domainName, scpPtrLdapPath, ref maxHops);
                        }
                        else
                        {
                            // Save the first SCP pointer ldapPath for a later call if a SCP URL is not found.
                            // Directory entries with a SCP pointer should have only one keyword=ScpPtrGuidString.
                            if ((entryKeywords.Count == 1) && string.IsNullOrEmpty(fallBackLdapPath))
                            {
                                fallBackLdapPath = scpPtrLdapPath;
                                this.TraceMessage(
                                    string.Format(
                                        "Fallback SCP pointer='{0}' for '{1}' is found in '{2}' and saved.",
                                        fallBackLdapPath,
                                        domainMatch,
                                        scpDirEntry.Path));
                            }
                        }
                    }
                }

                this.TraceMessage(
                    string.Format("No SCP pointers found for '{0}' in configPath='{1}'", domainMatch, configPath));

                // Get the computer's current site.
                string computerSiteName = this.GetSiteName();

                if (!string.IsNullOrEmpty(computerSiteName))
                {
                    // Search for SCP entries.
                    string sitePrefix = "Site=";
                    string siteMatch = sitePrefix + computerSiteName;
                    List<string> scpListNoSiteMatch = new List<string>();

                    this.TraceMessage(
                        string.Format("Scanning for SCP urls for the current computer {0}", siteMatch));

                    foreach (SearchResult scpDirEntry in scpDirEntries)
                    {
                        ResultPropertyValueCollection entryKeywords = scpDirEntry.Properties["keywords"];

                        // Identify SCP URLs.
                        if (entryKeywords.CaseInsensitiveContains(ScpUrlGuidString) && scpDirEntry.Properties["serviceBindingInformation"].Count > 0)
                        {
                            // Get the SCP URL.
                            scpUrl = scpDirEntry.Properties["serviceBindingInformation"][0] as string;

                            // If the SCP URL matches the exact ComputerSiteName.
                            if (entryKeywords.CaseInsensitiveContains(siteMatch))
                            {
                                // Priority 1 SCP URL. Add SCP URL to the list if it's not already there.
                                if (!scpUrlList.CaseInsensitiveContains(scpUrl))
                                {
                                    this.TraceMessage(
                                        string.Format(
                                            "Adding (prio 1) '{0}' for the '{1}' from '{2}' to the top of the list (exact match)",
                                            scpUrl,
                                            siteMatch,
                                            scpDirEntry.Path));

                                    scpUrlList.Add(scpUrl);
                                }
                            }

                            // No match between the SCP URL and the ComputerSiteName
                            else
                            {
                                bool hasSiteKeyword = false;

                                // Check if SCP URL entry has any keyword starting with "Site="
                                foreach (string keyword in entryKeywords)
                                {
                                    hasSiteKeyword |= keyword.StartsWith(sitePrefix, StringComparison.OrdinalIgnoreCase);
                                }

                                // Add SCP URL to the scpListNoSiteMatch list if it's not already there.
                                if (!scpListNoSiteMatch.CaseInsensitiveContains(scpUrl))
                                {
                                    // Priority 2 SCP URL. SCP entry doesn't have any "Site=<otherSite>" keywords, insert at the top of list.
                                    if (!hasSiteKeyword)
                                    {
                                        this.TraceMessage(
                                            string.Format(
                                                "Adding (prio 2) '{0}' from '{1}' to the middle of the list (wildcard)",
                                                scpUrl,
                                                scpDirEntry.Path));

                                        scpListNoSiteMatch.Insert(0, scpUrl);
                                    }

                                    // Priority 3 SCP URL. SCP entry has at least one "Site=<otherSite>" keyword, add to the end of list.
                                    else
                                    {
                                        this.TraceMessage(
                                            string.Format(
                                                "Adding (prio 3) '{0}' from '{1}' to the end of the list (site mismatch)",
                                                scpUrl,
                                                scpDirEntry.Path));

                                        scpListNoSiteMatch.Add(scpUrl);
                                    }
                                }
                            }
                        }
                    }

                    // Append SCP URLs to the list. List contains:
                    // Priority 1 URLs -- URLs with an exact match, "Site=<machineSite>"
                    // Priority 2 URLs -- URLs without a match, no any "Site=<anySite>" in the entry
                    // Priority 3 URLs -- URLs without a match, "Site=<nonMachineSite>"
                    if (scpListNoSiteMatch.Count > 0)
                    {
                        foreach (string url in scpListNoSiteMatch)
                        {
                            if (!scpUrlList.CaseInsensitiveContains(url))
                            {
                                scpUrlList.Add(url);
                            }
                        }
                    }
                }
            }
            finally
            {
                if (scpDirEntries != null)
                {
                    scpDirEntries.Dispose();
                }
            }

            // If no entries found, try fallBackLdapPath if it's non-empty.
            if (scpUrlList.Count == 0)
            {
                if (!string.IsNullOrEmpty(fallBackLdapPath))
                {
                    this.TraceMessage(
                        string.Format(
                        "Restarting search for domain '{0}' in SCP fallback pointer '{1}'",
                        domainName,
                        fallBackLdapPath));

                    return this.GetScpUrlList(domainName, fallBackLdapPath, ref maxHops);
                }
            }

            // Return the list with 0 or more SCP URLs.
            return scpUrlList;
        }

        /// <summary>
        /// Get the local site name.
        /// </summary>
        /// <returns>Name of the local site.</returns>
        private string GetSiteName()
        {
            try
            {
                using (ActiveDirectorySite site = ActiveDirectorySite.GetComputerSite())
                {
                    return site.Name;
                }
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// Traces message.
        /// </summary>
        /// <param name="message">The message.</param>
        private void TraceMessage(string message)
        {
            this.Service.TraceMessage(TraceFlags.AutodiscoverConfiguration, message);
        }

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="DirectoryHelper"/> class.
        /// </summary>
        /// <param name="service">The service.</param>
        public DirectoryHelper(ExchangeServiceBase service)
        {
            this.service = service;
        }
        #endregion

        #region Properties

        internal ExchangeServiceBase Service
        {
            get { return this.service; }
        }

        #endregion
    }
}