text:
'use strict';

var connect = function(){
    var napi = document.getElementById("api").value;
    if (napi != "/") {
        api = "http://" + napi;
    }
    $("#start").hide();
    $("#api").attr('disabled', true);

    new Promise(function(resolve, reject){
        navigator.getUserMedia({
            video:true,audio:true
        },function(stream){
            resolve(stream);
        }, function(error){
            reject(error);
        });
    }).then(function(stream){
        var lv = document.getElementById("local");
        try {
            lv.src = window.URL.createObjectURL(stream);
        } catch (error) {
            lv.srcObject = stream;
        }
        console.log("[navigator.getUserMedia] lv.src= " + lv.src);

        // Use a peer connection to share stream to responder.
        var conn = new window.webkitRTCPeerConnection({
            iceTransportPolicy: 'relay',
            iceServers:[{urls:["turn:stun.ossrs.net"], username:"winlin", credential:"12345678"
        }]});
        conn.addStream(stream);
        console.log("[conn.addStream] add stream to peer connection");

        // Render the remote initiator stream.
        conn.onaddstream = function(e) {
            var rv = document.getElementById("remote");
            try {
                rv.src = window.URL.createObjectURL(e.stream);
            } catch (error) {
                rv.srcObject = e.stream;
            }
            console.log("[conn.onaddstream] rv.src=remoteStream " + rv.src);

            checkRestart();
        };
        return conn;
    }).then(function(conn){
        Promise.all([new Promise(function(resolve, reject){
            conn.onicecandidate = function(e) {
                if (!e.candidate) {
                    return;
                }

                if (e.candidate.candidate.indexOf("relay") == -1) {
                    console.log("[conn.onicecandidate] ignore " + e.candidate.candidate);
                    return;
                }

                console.log("[conn.onicecandidate] " + e.candidate.candidate);
                console.log(e.candidate);

                // Transmit initiator candidates info to signaling server.
                var data = JSON.stringify(escapeCandicate(e.candidate));
                $.ajax({
                    type:"POST", async:true, url:api+"/api/webrtc/icandidates", contentType:"application/json", data:data,
                    success: function(){ resolve(data); }, error: function(xhr,err) { reject(err); }
                });
            };
        }), new Promise(function(resolve, reject){
            conn.createOffer(function(offer){
                // For chrome new API, we can delay set the TURN.
                //conn.setConfiguration({iceServers:[{urls:["turn:stun.ossrs.net"], username:"winlin", credential:"12345678"}]});

                conn.setLocalDescription(offer); // trigger conn.onicecandidate().
                console.log("[conn.createOffer] Request with offer " + offer.sdp.length + "B sdp as bellow:");
                console.log(offer); console.log(offer.sdp);

                // Create a offer so that the responder can answer.
                var data = JSON.stringify(escapeOffer(offer));
                $.ajax({
                    type:"POST", async:true, url:api+"/api/webrtc/offer", contentType:"application/json", data:data,
                    success: function(){ resolve(offer); }, error: function(xhr,err) { reject(err); }
                });
            }, function(error){
                reject(error);
            });
        })]).then(function([candidate, offer]){
            setTimeout(waitResponder, 5000, conn);
        });
    });
};

// https://codelabs.developers.google.com/codelabs/webrtc-web/#6
var api = "";
$("#start").click(connect);
connect();

function waitResponder(pcLocal) {
    new Promise(function(resolve, reject){
        var waitAnswer = function(){
            $.ajax({
                type:"GET", async:true, url:api+"/api/webrtc/answer", contentType:"application/json",
                success:function(data){
                    var answer = unescapeOffer(JSON.parse(JSON.parse(data)[0]));
                    resolve(answer);
                }, error:function(){
                    console.log("[waitAnswer] No answer, wait for a while.");
                    setTimeout(waitAnswer, 1000);
                }
            });
        };
        setTimeout(waitAnswer, 0);
    }).then(function(answer){
        // Wait for responder to reply the answer.
        pcLocal.setRemoteDescription(answer);
        console.log("[onLocalGotAnswer] Got answer " + answer.sdp.length + "B sdp as bellow:");
        console.log(answer);  console.log(answer.sdp);

        new Promise(function(resolve, reject){
            // When got answer from responder, request its candidates.
            var requestCandidates = function() {
                $.ajax({
                    type:"GET", async:true, url:api+"/api/webrtc/rcandidates", contentType:"application/json",
                    success:function(data){
                        data = JSON.parse(data) || [];

                        // Wait util the rcandidates are completed, we should got 1+ candidates.
                        if (data.length < 1) {
                            setTimeout(requestCandidates, 1000);
                            return;
                        }

                        resolve(data);
                    }, error:function(){
                        console.log("[requestCandidates] No responder candidates, wait for a while.");
                        setTimeout(requestCandidates, 1000);
                    }
                });
            };
            requestCandidates();
        }).then(function(data){
            for (var i = 0; i < data.length; i++) {
                var candidate = unescapeCandicate(JSON.parse(data[i]));
                // Before addIceCandidate, we should setRemoteDescription.
                pcLocal.addIceCandidate(new window.RTCIceCandidate(candidate));
                console.log("[requestCandidates] Got responder candidate " + JSON.stringify(candidate));
            }
        });
    });
}

function checkRestart() {
    new Promise(function(resolve, reject){
        $.ajax({
            type:"GET", async:true, url:api+"/api/webrtc/offer", contentType:"application/json",
            success:function(data){
                var offer = unescapeOffer(JSON.parse(JSON.parse(data)[0]));
                resolve(offer);
            }, error:function(){
                reject();
            }
        });
    }).then(function(offer){
        console.log(offer);
        setTimeout(checkRestart, 1000);
    }).catch(function(reason) {
        console.error("[heatbeat] Signaling reset.");
        setTimeout(function () {
            var url = window.location.href;
            var path = window.location.pathname;
            var url2 = url.substr(0, url.indexOf(path) + path.length);
            window.location.href = url2 + '?t=' + new Date().getTime();
        }, 1500);
    });
}

function escapeOffer(offer) {
    return {type:offer.type, sdp:escape(offer.sdp)};
}

function escapeCandicate(candidate) {
    return {sdpMid:candidate.sdpMid, sdpMLineIndex:candidate.sdpMLineIndex, candidate:escape(candidate.candidate)};
}

function unescapeOffer(offer) {
    return {type:offer.type, sdp:unescape(offer.sdp)};
}

function unescapeCandicate(candidate) {
    return {sdpMid:candidate.sdpMid, sdpMLineIndex:candidate.sdpMLineIndex, candidate:unescape(candidate.candidate)};
}


text:
/* --------------------------------------------------------------------------
 *    Name: remove.c
 * Purpose: Associative array implemented as a trie
 * ----------------------------------------------------------------------- */

#include <assert.h>
#include <stddef.h>
#include <string.h>

#include "base/memento/memento.h"

#include "datastruct/trie.h"

#include "impl.h"

/* To remove, we search for the specified node recursively. If we hit a leaf
 * node and it's the correct key then we detach the key from its parent and
 * return 1 meaning 'fix up the tree'. Otherwise we return -1 meaning 'not
 * found'.
 *
 * On return from recursion we then test the return code. If negative we
 * return that code immediately. If positive we examine the tree to see if
 * it needs fixing up. A tree with a left or right NULL subtree pointer where
 * the other direction is not a subtree is invalid, and needs fixing up.
 *
 * A tree with a valid structure can terminate immediately and returns -2.
 */
static int trie__remove_node(trie_t        *t,
                             trie__node_t **pn,
                             const void    *key,
                             size_t         keylen,
                             int            depth)
{
  const unsigned char *ukey    = key;
  const unsigned char *ukeyend = ukey + keylen;
  trie__node_t        *n = *pn;
  trie__node_t        *m;

  assert(n != NULL);

  if (IS_LEAF(n))
  {
    if (!(n->item.keylen == keylen && memcmp(n->item.key, key, keylen) == 0))
      return -1; /* not found */

    m = NULL; /* delete link from parent */
  }
  else
  {
    int           dir;
    int           rc;
    trie__node_t *left, *right;
    int           leafleft, leafright;

    dir = 0;
    if (ukey + (depth >> 3) < ukeyend)
      dir = (ukey[depth >> 3] >> (7 - (depth & 7))) & 1;

    if ((rc = trie__remove_node(t, &n->child[dir], key, keylen, depth + 1)) <= 0)
      return rc;

    left  = n->child[0];
    right = n->child[1];

    leafleft  = (right == NULL) && IS_LEAF(left);
    leafright = (left  == NULL) && IS_LEAF(right);
    if (!leafleft && !leafright)
      return -2; /* subtree is in a valid state */

    m = leafleft ? left : right;
    assert(m);
  }

  trie__node_destroy(t, n);
  *pn = m;

  return 1;
}

void trie_remove(trie_t *t, const void *key, size_t keylen)
{
  (void) trie__remove_node(t, &t->root, key, keylen, 0);
}

redpajama_set_name: RedPajamaGithub


text:
'''
Created on 2011-1-1\n
@author: zhuh
@version: 0.1.0
@change: \n
    - 2011-1-10 \n
        - finished the B{get_atom_list()} function.
    - 2011-01-18\n
        - Add the function B{Get_Atom_in_residue()}.
    - 2011-02-16\n
        - Add the function B{atom_2_PDBformat()} and B{atom_2_GROformat()}
    - 2011-04-21\n
        - Modified a bug.
'''
import unit_atom
import string
import re

class Atom_class:
    '''
    The core class, which contain all the atom pramaters in PDB file.
    It's can be initialized with all the paramaters or part.
    '''

    def __init__(self , character = "" , atom_serial = 0 , atom_name = "" ,
            alter_local_indicater = "" , residue_name = "" , chain_indicater = "" ,
            residue_serial = 0 , code_for_insertions_of_residues = "" ,
            atom_coor_x = 0.0 , atom_coor_y = 0.0 , atom_coor_z = 0.0 , occupancy = 0.0 ,
            temp_factor = 0 , segment_indent = "" , element_symbol = "" ,
            charge = ""):
        self.character = character
        self.atom_serial = atom_serial
        self.atom_name = atom_name
        self.alter_local_indicater = alter_local_indicater
        self.residue_name = residue_name
        self.chain_indicater = chain_indicater
        self.residue_serial = residue_serial
        self.code_for_insertions_of_residues = code_for_insertions_of_residues
        self.atom_coor_x = atom_coor_x
        self.atom_coor_y = atom_coor_y
        self.atom_coor_z = atom_coor_z
        self.occupancy = occupancy
        self.temp_factor = temp_factor
        self.segment_indent = segment_indent
        self.element_symbol = element_symbol
        self.charge = charge

    def atom_2_PDBformat(self):
        '''得到一个格式化的Atom sting'''
        temp_atom=""
        if re.match('^\d',self.atom_name) != None:
            temp_atom=self.atom_name.ljust(4)
        else:
            if len(self.atom_name) <4:
                temp_atom=(" "+self.atom_name).ljust(4)
            else:
                temp_atom=self.atom_name

        s = "%s%5d %s %3s %1s%4d%s    %8.3f%8.3f%8.3f%6.2f%6.2f      %4s%2s%2s" \
                % (self.character.ljust(6) , self.atom_serial , temp_atom,  self.residue_name.rjust(3) , \
                self.chain_indicater , self.residue_serial , self.code_for_insertions_of_residues , \
                self.atom_coor_x*10 , self.atom_coor_y*10 , self.atom_coor_z*10 , self.occupancy ,\
                self.temp_factor , self.segment_indent.ljust(4) , \
                self.element_symbol.rjust(2) , self.charge)
        return s

    def atom_2_GROformat(self):
        s="%5d%5s%5s%5d%8.3f%8.3f%8.3f" \
                %(self.residue_serial , string.ljust(self.residue_name,5) , self.atom_name , self.atom_serial , \
                self.atom_coor_x , self.atom_coor_y , self.atom_coor_z )
        return s

def Get_Atom_list(filename):
    '''把每个atom的信息写到一个Atom_class的类中,然后输出一个Atom_class的list ,
    部分异常处理未完成。'''
    alist = list()
    try:
        fp = open(filename , 'r')
    except:
        print "Error: No such file: "+filename
        return alist
    allLines = fp.readlines()
    for eachline in allLines:
        if ( eachline.startswith("ATOM") or eachline.startswith("HETATM") ):
            temp_Atom_class = Atom_class()
            temp_Atom_class.character = string.strip(eachline[0:6])
            try:
                temp_Atom_class.atom_serial = int(string.strip(eachline[6:11]))
            except:
                pass
            temp_Atom_class.atom_name = string.strip(eachline[12:16])
            temp_Atom_class.alter_local_indicater = string.strip(eachline[16])
            temp_Atom_class.residue_name = string.strip(eachline[17:20])
            temp_Atom_class.chain_indicater = string.strip(eachline[21])
            try:
                temp_Atom_class.residue_serial = int(string.strip(eachline[22:26]))
            except:
                pass
            temp_Atom_class.code_for_insertions_of_residues = string.strip(eachline[27])
            try:
                temp_Atom_class.atom_coor_x = float(string.strip(eachline[30:38]))/10
                temp_Atom_class.atom_coor_y = float(string.strip(eachline[38:46]))/10
                temp_Atom_class.atom_coor_z = float(string.strip(eachline[46:54]))/10
                if len(eachline) > 59:
                    temp_Atom_class.occupancy = float(string.strip(eachline[54:60]))
                if len(eachline) > 65:
                    temp_Atom_class.temp_factor = float(string.strip(eachline[60:66]))
            except:
                pass
            if len(eachline) > 75:
                temp_Atom_class.segment_indent = string.strip(eachline[72:76])
            if len(eachline) > 77:
                temp_Atom_class.element_symbol = string.strip(eachline[76:78])
            if len(eachline) > 79:
                temp_Atom_class.charge = string.strip(eachline[78:80])

            alist.append(temp_Atom_class)

    return alist

def Read_PDB_2_SimpleAtom_list(filename):
    '''
    把每个atom的信息写到一个Simple_atom的类中,然后输出一个Atom_class的list ,
    部分异常处理未完成。
    '''
    try:
        fp = open(filename , 'r')
    except:
        print "Error: No such file: "+filename
        exit(1)
    allLines = fp.readlines()
    list = []
    for eachline in allLines:
        if ("ATOM" in eachline) or ("HETEAM" in eachline):
            temp_Atom = unit_atom.unit_atom()
            try:
                temp_Atom.atom_serial = int(string.strip(eachline[6:11]))
            except:
                pass
            temp_Atom.atom_name = string.strip(eachline[12:16])
            temp_Atom.residue_name = string.strip(eachline[17:20])
            try:
                temp_Atom.residue_serial = int(string.strip(eachline[22:26]))
            except:
                pass
            try:
                temp_Atom.coor_x = float(string.strip(eachline[30:38]))
                temp_Atom.coor_y = float(string.strip(eachline[38:46]))
                temp_Atom.coor_z = float(string.strip(eachline[46:54]))
            except:
                pass
            list.append(temp_Atom)

    return list


text:
//Mudar o for do iterator para o novo for.
package plp.functional1.expression;

import static java.util.Arrays.asList;
import static plp.expressions1.util.ToStringProvider.listToString;

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

import plp.expressions1.util.Tipo;
import plp.expressions2.expression.Expressao;
import plp.expressions2.expression.Id;
import plp.expressions2.expression.Valor;
import plp.expressions2.memory.AmbienteCompilacao;
import plp.expressions2.memory.AmbienteExecucao;
import plp.expressions2.memory.IdentificadorNaoDeclaradoException;
import plp.expressions2.memory.VariavelJaDeclaradaException;
import plp.expressions2.memory.VariavelNaoDeclaradaException;
import plp.functional1.memory.AmbienteExecucaoFuncional;
import plp.functional1.util.DefFuncao;
import plp.functional1.util.TipoFuncao;

public class Aplicacao implements Expressao {

	private Id func;
	private List<? extends Expressao> argsExpressao;

	public Aplicacao(Id f, Expressao... expressoes) {
		this(f, asList(expressoes));
	}

	public Aplicacao(Id f, List<? extends Expressao> expressoes) {
		func = f;
		argsExpressao = expressoes;
	}

	public Valor avaliar(AmbienteExecucao ambiente)
			throws VariavelNaoDeclaradaException, VariavelJaDeclaradaException {
		AmbienteExecucaoFuncional ambienteFuncional = (AmbienteExecucaoFuncional) ambiente;

		DefFuncao funcao;
		try {
			funcao = ambienteFuncional.getFuncao(func);
		} catch (IdentificadorNaoDeclaradoException e) {
			throw new VariavelJaDeclaradaException(func);
		}

		Map<Id, Valor> mapIdValor = resolveParametersBindings(ambiente, funcao);

		ambiente.incrementa();

		includeValueBindings(ambiente, mapIdValor);

		Valor vresult = funcao.getExp().avaliar(ambiente);
		ambiente.restaura();
		return vresult;
	}

	/**
	 * Realiza a verificacao de tipos desta expressao.
	 *
	 * @param amb
	 *            o ambiente de compilação.
	 * @return true se os tipos da expressao sao validos;
	 *         false caso contrario.
	 * @exception VariavelNaoDeclaradaException
	 *                se existir um identificador nao declarado no ambiente.
	 * @exception VariavelNaoDeclaradaException
	 *                se existir um identificador declarado mais de uma vez no
	 *                mesmo bloco do ambiente.
	 */
	public boolean checaTipo(AmbienteCompilacao ambiente)
			throws VariavelNaoDeclaradaException, VariavelJaDeclaradaException {
		boolean result;
		Tipo aux = ambiente.get(func);

		if (aux instanceof TipoFuncao) {
			TipoFuncao tipoFuncao = (TipoFuncao) aux;

			result = tipoFuncao.checaTipo(ambiente, argsExpressao);
		} else {
			// A função func não foi declarada.

			// TODO: lançar uma exceção ou separar variáveis de funções no
			// contexto de compilação.

			result = false;
		}
		return result;
	}

	/**
	 * Returns the args.
	 *
	 * @return ListaExpressao
	 */
	public List<? extends Expressao> getArgsExpressao() {
		return argsExpressao;
	}

	/**
	 * Returns the func.
	 *
	 * @return Id
	 */
	public Id getFunc() {
		return func;
	}

	/**
	 * Retorna os tipos possiveis desta expressao.
	 *
	 * @param amb
	 *            o ambiente de compilação.
	 * @return os tipos possiveis desta expressao.
	 * @exception VariavelNaoDeclaradaException
	 *                se existir um identificador nao declarado no ambiente.
	 * @exception VariavelNaoDeclaradaException
	 *                se existir um identificador declarado mais de uma vez no
	 *                mesmo bloco do ambiente.
	 * @precondition this.checaTipo();
	 */
	public Tipo getTipo(AmbienteCompilacao ambiente)
			throws VariavelNaoDeclaradaException, VariavelJaDeclaradaException {
		TipoFuncao tipoFuncao = (TipoFuncao) ambiente.get(func);
		return tipoFuncao.getTipo(ambiente, argsExpressao);
	}

	private void includeValueBindings(AmbienteExecucao ambiente,
			Map<Id, Valor> mapIdValor) throws VariavelJaDeclaradaException {
		for (Map.Entry<Id, Valor> mapeamento : mapIdValor.entrySet()) {
			Id id = mapeamento.getKey();
			Valor valor = mapeamento.getValue();
			ambiente.map(id, valor);
		}
	}

	private Map<Id, Valor> resolveParametersBindings(AmbienteExecucao ambiente,
			DefFuncao funcao) throws VariavelNaoDeclaradaException,
			VariavelJaDeclaradaException {
		List<Id> parametrosId = funcao.getListaId();
		List<? extends Expressao> expressoesValorReal = argsExpressao;

		Map<Id, Valor> mapIdValor = new HashMap<Id, Valor>();

		Iterator<? extends Expressao> iterExpressoesValor = expressoesValorReal
				.iterator();
		for (Id id : parametrosId) {
			Expressao exp = iterExpressoesValor.next();
			Valor valorReal = exp.avaliar(ambiente);
			mapIdValor.put(id, valorReal);
		}
		return mapIdValor;
	}

	/**
	 * Retorna uma representacao String desta expressao. Util para depuracao.
	 *
	 * @return uma representacao String desta expressao.
	 */
	@Override
	public String toString() {
		return String.format("%s(%s)", func, listToString(argsExpressao, ","));
	}

	public Expressao reduzir(AmbienteExecucao ambiente) {
		// TODO Auto-generated method stub
		return null;
	}

	public Aplicacao clone() {
		Aplicacao retorno;
		ArrayList<Expressao> novaLista = new ArrayList<Expressao>(this.argsExpressao.size());

		Iterator<? extends Expressao> iterator = argsExpressao.iterator();
		while (iterator.hasNext()){
			Expressao exp = iterator.next();
			novaLista.add(exp.clone());
		}

		retorno = new Aplicacao(this.func.clone(), novaLista);

		return retorno;
	}
}


text:
/** @jsx React.DOM */

/*
 * Copyright (c) Michael Polyak. All rights reserved.
 */

"use strict";

var url = require("url");

var React = require("react");

var Demo      = require("./views/demo.js");
var Meta      = require("./views/meta.js");
var Index     = require("./views/index.js");
var Report    = require("./views/report.js");
var Dashboard = require("./views/dashboard.js");

var query = url.parse(document.location.href, true).query;

var view;

if (query.eat) {
    view = <Dashboard token={query.eat} />;
}
else if (query.report) {
    view = <Report token={query.report} start={query.start} />;
}
else if (query.hasOwnProperty("demo")) {
    view = <Demo />;
}
else if (query.hasOwnProperty("meta")) {
    view = <Meta />;
}
else
    view = <Index />;

React.renderComponent(view, document.body);


text:
package org.apache.logging.log4j.web;

import org.apache.logging.log4j.util.PropertiesUtil;
import org.junit.Test;

import static org.junit.Assert.*;

/**
 *
 */
public class ShutdownPropertyTest {

    @Test
    public void testWebProperty() {
        assertFalse(PropertiesUtil.getProperties().getBooleanProperty("log4j.shutdownHookEnabled", true));
    }
}


text:
<amp-sidebar id='sidebar'
    layout="nodisplay"
    side="right">
  <amp-img class='amp-close-image'
      src="{{ site.baseurl }}/assets/img/close.png"
      width="20"
      height="20"
      alt="close sidebar"
      on="tap:sidebar.close"
      role="button"
      tabindex="0"></amp-img>
      {% for page in site.pages %}
        {% if page.title and page.navigation %}
        {{ page.title }}
        {% endif %}
      {% endfor %}
      WPF
      Language
      SUS
      SPP

</amp-sidebar>


text:
#region License

// Distributed under the MIT License
// ============================================================
// Copyright (c) 2019 Hotcakes Commerce, LLC
// Copyright (c) 2020 Upendo Ventures, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute,
// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Hotcakes.Commerce.Accounts;
using Hotcakes.Commerce.Analytics;
using Hotcakes.Commerce.BusinessRules;
using Hotcakes.Commerce.Catalog;
using Hotcakes.Commerce.Contacts;
using Hotcakes.Commerce.Content;
using Hotcakes.Commerce.Globalization;
using Hotcakes.Commerce.Marketing;
using Hotcakes.Commerce.Membership;
using Hotcakes.Commerce.Metrics;
using Hotcakes.Commerce.Orders;
using Hotcakes.Commerce.Scheduling;
using Hotcakes.Commerce.Social;
using Hotcakes.Commerce.Storage;
using Hotcakes.CommerceDTO.v1.Catalog;
using Hotcakes.Web.Data;
using Hotcakes.Web.Logging;

namespace Hotcakes.Commerce
{
    public class HotcakesApplication
    {
        private List<Promotion> _CurrentlyActiveSales;

        private WorkflowFactory _WorkflowFactory;

        public HotcakesApplication(HccRequestContext hccContext)
        {
            CurrentRequestContext = hccContext;
        }

        public WorkflowFactory WorkflowFactory
        {
            get
            {
                return _WorkflowFactory ??
                       (_WorkflowFactory = Factory.CreateWorklflowFactory(CurrentRequestContext));
            }
        }

        public static HotcakesApplication Current
        {
            get { return new HotcakesApplication(HccRequestContext.Current); }
        }

        public HccRequestContext CurrentRequestContext { get; set; }

        public Store CurrentStore
        {
            get { return CurrentRequestContext.CurrentStore; }
            set { CurrentRequestContext.CurrentStore = value; }
        }

        public string CurrentCustomerId
        {
            get
            {
                if (CurrentRequestContext.CurrentAccount != null)
                {
                    return CurrentRequestContext.CurrentAccount.Bvin;
                }

                return string.Empty;
            }
        }

        public CustomerAccount CurrentCustomer
        {
            get { return CurrentRequestContext.CurrentAccount; }
        }

        public string ViewsVirtualPath
        {
            get
            {
                var viewsVirtualPath = string.Empty;
                if (CurrentStore != null)
                    viewsVirtualPath = CurrentStore.Settings.Urls.ViewsVirtualPath;
                else
                    viewsVirtualPath = StoreSettingsUrls.DefaultViewsVirtualPath;
                return viewsVirtualPath;
            }
        }

        public List<Promotion> CurrentlyActiveSales
        {
            get
            {
                if (_CurrentlyActiveSales == null)
                {
                    _CurrentlyActiveSales = MarketingServices.Promotions.FindAllPotentiallyActiveSales(DateTime.Now);
                }
                return _CurrentlyActiveSales;
            }
        }

        public string StoreUrl(bool forceSecure, bool forceNonSecure)
        {
            var result = VirtualPathUtility.ToAbsolute("~");

            if (CurrentStore != null)
            {
                if (forceSecure)
                {
                    result = CurrentStore.RootUrlSecure();
                }
                else
                {
                    result = CurrentStore.RootUrl();
                }
            }
            if (!result.EndsWith("/"))
            {
                result += "/";
            }
            return result;
        }

        public bool IsCurrentRequestSecure()
        {
            var secure = false;
            try
            {
                secure = CurrentRequestContext.RoutingContext.HttpContext.Request.IsSecureConnection;
            }
            catch
            {
                secure = false;
            }
            return secure;
        }

        public bool UpdateCurrentStore()
        {
            return AccountServices.Stores.Update(CurrentStore);
        }

        public bool CalculateOrder(Order o)
        {
            var calc = new OrderCalculator(this);
            return calc.Calculate(o);
        }

        public bool CalculateOrderWithoutRepricing(Order o)
        {
            var calc = new OrderCalculator(this);
            calc.SkipRepricing = true;
            return calc.Calculate(o);
        }

        public bool CalculateOrderWithoutRepriceingWithoutDiscounts(Order o)
        {
            var calc = new OrderCalculator(this);
            calc.SkipDiscounts = true;
            calc.SkipRepricing = true;
            return calc.Calculate(o);
        }

        public bool CalculateOrderAndSave(Order o)
        {
            if (!CalculateOrder(o)) return false;
            return OrderServices.Orders.Upsert(o);
        }

        public bool CalculateOrderAndSaveWithoutRepricing(Order o)
        {
            if (!CalculateOrderWithoutRepricing(o)) return false;
            return OrderServices.Orders.Upsert(o);
        }

        public bool CalculateOrderAndSaveWithoutRepricingWithoutDiscounts(Order o)
        {
            if (!CalculateOrderWithoutRepriceingWithoutDiscounts(o)) return false;
            return OrderServices.Orders.Upsert(o);
        }

        public bool AddToOrderWithCalculateAndSave(Order o, LineItem li)
        {
            o.IsAbandonedEmailSent = false;
            o.TimeOfOrderUtc = DateTime.UtcNow;
            o.UsedCulture = CurrentRequestContext.MainContentCulture;
            OrderServices.AddItemToOrder(o, li);
            AnalyticsService.RegisterEvent(CurrentCustomerId, ActionTypes.ProductAddedToCart, li.ProductId);
            CalculateOrder(o);
            return OrderServices.Orders.Upsert(o);
        }

        public bool AddToOrderAndSave(Order o, LineItem li)
        {
            o.IsAbandonedEmailSent = false;
            o.TimeOfOrderUtc = DateTime.UtcNow;
            OrderServices.AddItemToOrder(o, li);
            AnalyticsService.RegisterEvent(CurrentCustomerId, ActionTypes.ProductAddedToCart, li.ProductId);
            return OrderServices.Orders.Upsert(o);
        }

        public void ClearOrder(Order order)
        {
            if (order == null)
                return;

            order.Items.Clear();
            CalculateOrderAndSave(order);
        }

        public SystemOperationResult CheckForStockOnItems(Order order)
        {
            // Build a list of product quantities to check
            var products = new Dictionary<string, ProductIdCombo>();
            foreach (var item in order.Items)
            {
                var product = item.GetAssociatedProduct(this);
                if (product == null || product.Status == ProductStatus.Disabled)
                {
                    var productNotAvailable = GlobalLocalization.GetFormattedString("ProductNotAvailable",
                        product.ProductName);
                    return new SystemOperationResult(false, productNotAvailable);
                }

                if (!product.IsBundle)
                {
                    var combo = new ProductIdCombo
                    {
                        ProductId = item.ProductId,
                        VariantId = item.VariantId,
                        ProductName = item.ProductName,
                        Quantity = item.Quantity,
                        Product = product
                    };

                    if (products.ContainsKey(combo.Key()))
                        products[combo.Key()].Quantity += combo.Quantity;
                    else
                        products.Add(combo.Key(), combo);
                }
                else
                {
                    foreach (var bundledProductAdv in product.BundledProducts)
                    {
                        var bundledProduct = bundledProductAdv.BundledProduct;
                        if (bundledProduct == null)
                            continue;

                        var optionSelection = item.SelectionData.GetSelections(bundledProductAdv.Id);
                        var variant = bundledProduct.Variants.FindBySelectionData(optionSelection,
                            bundledProduct.Options);
                        var variantId = variant != null ? variant.Bvin : string.Empty;

                        var combo = new ProductIdCombo
                        {
                            ProductId = bundledProduct.Bvin,
                            VariantId = variantId,
                            ProductName = bundledProduct.ProductName,
                            Quantity = bundledProductAdv.Quantity,
                            Product = bundledProduct
                        };

                        if (products.ContainsKey(combo.Key()))
                            products[combo.Key()].Quantity += combo.Quantity;
                        else
                            products.Add(combo.Key(), combo);
                    }
                }
            }

            // Now check each quantity for the order
            foreach (var key in products.Keys)
            {
                var checkcombo = products[key];
                var prod = checkcombo.Product;

                var data = CatalogServices.SimpleProductInventoryCheck(prod, checkcombo.VariantId, checkcombo.Quantity);

                if (!data.IsAvailableForSale)
                {
                    if (data.Qty == 0)
                    {
                        var cartOutOfStock = GlobalLocalization.GetFormattedString("CartOutOfStock", prod.ProductName);
                        return new SystemOperationResult(false, cartOutOfStock);
                    }
                    var message = GlobalLocalization.GetFormattedString("CartNotEnoughQuantity", prod.ProductName,
                        data.Qty);
                    return new SystemOperationResult(false, message);
                }
            }

            return new SystemOperationResult(true, string.Empty);
        }

        public SystemOperationResult CheckForStockOnItems(LineItem item)
        {
            // Build a list of product quantities to check
            var products = new Dictionary<string, ProductIdCombo>();

            var product = item.GetAssociatedProduct(this);
            if (product == null || product.Status == ProductStatus.Disabled)
            {
                var productNotAvailable = GlobalLocalization.GetFormattedString("ProductNotAvailable",
                    product.ProductName);
                return new SystemOperationResult(false, productNotAvailable);
            }

            if (!product.IsBundle)
            {
                var combo = new ProductIdCombo
                {
                    ProductId = item.ProductId,
                    VariantId = item.VariantId,
                    ProductName = item.ProductName,
                    Quantity = item.Quantity,
                    Product = product
                };

                if (products.ContainsKey(combo.Key()))
                    products[combo.Key()].Quantity += combo.Quantity;
                else
                    products.Add(combo.Key(), combo);
            }
            else
            {
                foreach (var bundledProductAdv in product.BundledProducts)
                {
                    var bundledProduct = bundledProductAdv.BundledProduct;
                    if (bundledProduct == null)
                        continue;

                    var optionSelection = item.SelectionData.GetSelections(bundledProductAdv.Id);
                    var variant = bundledProduct.Variants.FindBySelectionData(optionSelection, bundledProduct.Options);
                    var variantId = variant != null ? variant.Bvin : string.Empty;

                    var combo = new ProductIdCombo
                    {
                        ProductId = bundledProduct.Bvin,
                        VariantId = variantId,
                        ProductName = bundledProduct.ProductName,
                        Quantity = bundledProductAdv.Quantity,
                        Product = bundledProduct
                    };

                    if (products.ContainsKey(combo.Key()))
                        products[combo.Key()].Quantity += combo.Quantity;
                    else
                        products.Add(combo.Key(), combo);
                }
            }

            // Now check each quantity for the order
            foreach (var key in products.Keys)
            {
                var checkcombo = products[key];
                var prod = checkcombo.Product;

                var data = CatalogServices.SimpleProductInventoryCheck(prod, checkcombo.VariantId, checkcombo.Quantity);

                if (!data.IsAvailableForSale)
                {
                    if (data.Qty == 0)
                    {
                        var cartOutOfStock = GlobalLocalization.GetFormattedString("CartOutOfStock", prod.ProductName);
                        return new SystemOperationResult(false, cartOutOfStock);
                    }
                    var message = GlobalLocalization.GetFormattedString("CartNotEnoughQuantity", prod.ProductName,
                        data.Qty);
                    return new SystemOperationResult(false, message);
                }
            }

            return new SystemOperationResult(true, string.Empty);
        }

        // Product Pricing
        public UserSpecificPrice PriceProduct(string productBvin, string userId, OptionSelections selections)
        {
            var p = CatalogServices.Products.FindWithCache(productBvin);
            var customer = MembershipServices.Customers.Find(userId);
            return PriceProduct(p, customer, selections, CurrentlyActiveSales);
        }

        public UserSpecificPrice PriceProduct(Product p, CustomerAccount currentUser, OptionSelections selections,
            List<Promotion> currentSales)
        {
            if (p == null) return null;
            var result = new UserSpecificPrice(p, selections, CurrentStore.Settings);
            AdjustProductPriceForUser(result, p, currentUser);
            ApplySales(result, p, currentUser, currentSales);
            CheckForPricesBelowZero(result);

            return result;
        }

        private void ApplySales(UserSpecificPrice price, Product p, CustomerAccount currentUser, List<Promotion> sales)
        {
            if (sales == null) return;
            foreach (var promo in sales)
            {
                promo.ApplyToProduct(CurrentRequestContext, p, price, currentUser);
            }
        }

        private void AdjustProductPriceForUser(UserSpecificPrice price, Product p, CustomerAccount currentUser)
        {
            if (currentUser == null) return;
            if (currentUser.Bvin == string.Empty) return;
            if (currentUser.PricingGroupId == string.Empty) return;
            if (p == null) return;
            if (price == null) return;

            var startingPrice = price.PriceWithAdjustments();

            var pricingGroup = ContactServices.PriceGroups.Find(currentUser.PricingGroupId);
            if (pricingGroup == null) return;

            var nonGroupPrice = price.BasePrice;

            var groupPrice = nonGroupPrice;
            //groupPrice = pricingGroup.GetAdjustedPriceForThisGroup(p.SitePrice, p.ListPrice, p.SiteCost);
            groupPrice = pricingGroup.GetAdjustedPriceForThisGroup(startingPrice, p.ListPrice, p.SiteCost);

            var amountOfDiscount = groupPrice - nonGroupPrice;
            price.AddAdjustment(amountOfDiscount, "Price Group");
        }

        private void CheckForPricesBelowZero(UserSpecificPrice price)
        {
            var final = price.PriceWithAdjustments();

            if (final < 0)
            {
                var tweak = -1*final;
                price.AddAdjustment(tweak, "Price can not be below zero");
            }
        }

        // Orders
        public bool OrdersReserveInventoryForAllItems(Order o, List<string> errors)
        {
            var result = true;
            foreach (var li in o.Items)
            {
                li.QuantityReserved = CatalogServices.InventoryLineItemReserveInventory(li);
                if (li.QuantityReserved != li.Quantity)
                {
                    if (errors != null)
                    {
                        errors.Add("Item " + li.ProductName + " did not have enough quantity to complete order.");
                    }
                    EventLog.LogEvent("Reserve Inventory For All Items",
                        "Unable to reserve quantity of " + li.Quantity + " for product " + li.ProductId,
                        EventLogSeverity.Debug);
                    result = false;
                }
            }
            return result;
        }

        public bool OrdersUnreserveInventoryForAllItems(Order o)
        {
            var result = true;
            foreach (var li in o.Items)
            {
                if (CatalogServices.InventoryLineItemUnreserveInventory(li) == false)
                {
                    EventLog.LogEvent("Unreserve Inventory For All Items",
                        "Unable to unreserve quantity of " + li.Quantity + " for product " + li.ProductId,
                        EventLogSeverity.Debug);
                }
            }
            return result;
        }

        // Order Packages
        public bool OrdersShipAllPackages(Order o)
        {
            foreach (var p in o.Packages)
            {
                if (!p.HasShipped)
                {
                    OrdersShipPackage(p, o);
                }
            }
            OrderServices.Orders.Update(o);
            return true;
        }

        public bool OrdersShipPackage(OrderPackage package, Order order)
        {
            if (order == null)
                throw new NullReferenceException("order");

            if (package == null)
                throw new NullReferenceException("package");

            package.HasShipped = true;
            OrdersShipItems(package, order);

            var c = new OrderTaskContext(CurrentRequestContext);
            c.Order = order;
            c.UserId = CurrentCustomerId;
            if (!Workflow.RunByName(c, WorkflowNames.PackageShipped))
            {
                EventLog.LogEvent("PackageShippedWorkflow", "Package Shipped Workflow Failed", EventLogSeverity.Debug);
                foreach (var item in c.Errors)
                {
                    EventLog.LogEvent("PackageShippedWorkflow", item.Description, EventLogSeverity.Debug);
                }
            }
            return true;
        }

        private void OrdersShipItems(OrderPackage package, Order order)
        {
            if (package.Items.Count == 0)
                return;

            foreach (var pi in package.Items)
            {
                var li = order.GetLineItem(pi.LineItemId);
                if (li == null || li.IsNonShipping)
                    continue;

                // Prevent shipping more than ordered if order is not recurring
                if (!order.IsRecurring && pi.Quantity > li.Quantity - li.QuantityShipped)
                {
                    pi.Quantity = li.Quantity - li.QuantityShipped;
                }

                if (pi.Quantity <= 0)
                {
                    pi.Quantity = 0;
                }
                else
                {
                    CatalogServices.InventoryLineItemShipQuantity(li, pi.Quantity);
                }
            }
        }

        public bool OrdersUnshipItems(OrderPackage package, Order order)
        {
            if (order == null)
                throw new NullReferenceException("order");

            if (package == null)
                throw new NullReferenceException("package");

            var result = true;

            if (package.Items.Count == 0)
                return result;

            foreach (var pi in package.Items)
            {
                var li = order.GetLineItem(pi.LineItemId);
                if (li == null || li.IsNonShipping)
                    continue;

                // Prevent unshipping more than shipped if order is not recurring
                var quantityToUnship = pi.Quantity;
                if (!order.IsRecurring && pi.Quantity > li.QuantityShipped)
                {
                    quantityToUnship = li.QuantityShipped;
                }
                CatalogServices.InventoryLineItemUnShipQuantity(li, quantityToUnship);
            }

            return result;
        }

        //Reporting
        public List<Product> ReportingTop10Sellers()
        {
            var results = new List<Product>();

            var startDateUtc = DateTime.UtcNow.AddMonths(-2);
            var endDateUtc = DateTime.UtcNow;

            var idList = OrderServices.Orders.FindPopularItems(startDateUtc, endDateUtc, 10);
            var allKeys = idList.Select(y => y.Key).ToList();
            results = CatalogServices.Products.FindManyWithCache(allKeys);

            return results;
        }

        public List<Product> ReportingTopSellersByDate(DateTime startDateUtc, DateTime endDateUtc, int maxResults)
        {
            var results = new List<Product>();

            var idList = OrderServices.Orders.FindPopularItems(startDateUtc, endDateUtc, maxResults);
            var allKeys = idList.Select(y => y.Key).ToList();
            results = CatalogServices.Products.FindManyWithCache(allKeys);

            return results;
        }

        public Product ParseProductBySlug(string slug, out CustomUrl customUrl)
        {
            customUrl = null;
            var result = CatalogServices.Products.FindBySlug(slug);
            if (result == null || result.Status == ProductStatus.Disabled)
            {
                // Check for custom URL
                customUrl = ContentServices.CustomUrls.FindByRequestedUrl(slug, CustomUrlType.Product);
                if (customUrl != null)
                {
                    result = CatalogServices.Products.FindBySlug(customUrl.RedirectToUrl);
                }
            }

            return result;
        }

        public Category ParseCategoryBySlug(string slug, out CustomUrl customUrl)
        {
            customUrl = null;
            var result = CatalogServices.Categories.FindBySlug(slug);
            if (result == null)
            {
                // Check for custom URL
                customUrl = ContentServices.CustomUrls.FindByRequestedUrl(slug, CustomUrlType.Category);
                if (customUrl != null)
                {
                    result = CatalogServices.Categories.FindBySlug(customUrl.RedirectToUrl);
                }
            }

            return result;
        }

        public List<ProductRelationship> GetAutoSuggestedRelatedItems(string bvin, int maxItemsToReturn)
        {
            using (var context = Factory.CreateHccDbContext())
            {
                var storeId = CurrentRequestContext.CurrentStore.Id;
                var productGuid = DataTypeHelper.BvinToGuid(bvin);

                var results = (from a in
                    (from l in context.hcc_LineItem
                        join o in context.hcc_Order on new {l.OrderBvin} equals new {OrderBvin = o.bvin}
                        join p in context.hcc_Product on new {bvin = l.ProductId} equals new {p.bvin}
                        where
                            o.IsPlaced == 1 &&
                            p.IsAvailableForSale &&
                            p.StoreId == storeId &&
                            p.bvin != productGuid &&
                            (from hcc_lineitem in context.hcc_LineItem
                                where
                                    hcc_lineitem.ProductId == productGuid &&
                                    hcc_lineitem.StoreId == storeId
                                select new
                                {
                                    hcc_lineitem.OrderBvin
                                }).Contains(new {l.OrderBvin})
                        select new
                        {
                            ProductID = p.bvin,
                            l.Quantity
                        })
                    group a by new
                    {
                        a.ProductID
                    }
                    into g
                    orderby
                        g.Sum(p => p.Quantity) descending
                    select new
                    {
                        g.Key.ProductID,
                        Total_Ordered = g.Sum(p => p.Quantity)
                    }).Take(maxItemsToReturn);

                var relationships = new List<ProductRelationship>();
                foreach (var r in results)
                {
                    var relatedProductId = DataTypeHelper.GuidToBvin(r.ProductID);
                    relationships.Add(new ProductRelationship
                    {
                        ProductId = bvin,
                        RelatedProductId = relatedProductId,
                        IsSubstitute = false,
                        StoreId = storeId
                    });
                }
                return relationships;
            }
        }

        public bool DestroyAllCategories()
        {
            var current = DateTime.UtcNow;
            var availableUntil = CurrentRequestContext.CurrentStore.Settings.AllowApiToClearUntil;
            var compareResult = DateTime.Compare(current, availableUntil);
            if (compareResult >= 0)
            {
                return false;
            }

            var all = CatalogServices.Categories.FindAll();
            foreach (var snap in all)
            {
                CatalogServices.DestroyCategory(snap.Bvin);
            }

            return true;
        }

        internal void DestroyAllCategoriesForStore(long storeId)
        {
            CatalogServices.Categories.DestroyAllForStore(storeId);
        }

        public bool DestroyCustomerAccount(string bvin)
        {
            CatalogServices.WishListItems.DeleteForCustomerId(bvin);
            return MembershipServices.Customers.Delete(bvin);
        }

        public ClearProductsData ClearProducts(int howMany)
        {
            var result = new ClearProductsData();

            var current = DateTime.UtcNow;
            var availableUntil = CurrentRequestContext.CurrentStore.Settings.AllowApiToClearUntil;
            var compareResult = DateTime.Compare(current, availableUntil);
            if (compareResult >= 0)
            {
                result.ProductsCleared = 0;
                result.ProductsRemaining = -1;
                return result;
            }

            return DeleteSome(CurrentRequestContext.CurrentStore.Id, howMany);
        }

        private ClearProductsData DeleteSome(long storeId, int howMany)
        {
            var items = CatalogServices.Products.FindAllPagedWithCache(1, howMany);
            var totalCount = CatalogServices.Products.FindAllCount(storeId);

            if (items != null)
            {
                foreach (var p in items)
                {
                    CatalogServices.DestroyProduct(p.Bvin, p.StoreId);
                }
            }

            var left = totalCount - howMany;
            if (left < 0) left = 0;
            var cleared = howMany;
            if (totalCount < howMany) cleared = totalCount;
            var result = new ClearProductsData();
            result.ProductsCleared = cleared;
            result.ProductsRemaining = left;

            return result;
        }

        public bool DestroyAllProductsForStore(long storeId)
        {
            var bvins = CatalogServices.Products.FindAllBvinsForStore(storeId);
            foreach (var bvin in bvins)
            {
                CatalogServices.DestroyProduct(bvin, storeId);
            }
            return true;
        }

        // Multi-Store Destroy
        public bool DestroyStore(long storeId)
        {
            EventLog.LogEvent("System", "Destroying Store " + storeId, EventLogSeverity.Debug);

            var result = true;

            var s = AccountServices.Stores.FindById(storeId);
            if (s == null) return false;
            if (s.Id != storeId) return false;

            DiskStorage.DestroyAllFilesForStore(storeId);
            //this.AccountServices.RemoveAllUsersFromStore(storeId);

            // Store Address
            var storeAddress = ContactServices.Addresses.FindStoreContactAddress();
            if (storeAddress != null) ContactServices.Addresses.Delete(storeAddress.Bvin);

            // Get rid of URLs so they won't stop category/product deletes
            ContentServices.CustomUrls.DestoryAllForStore(storeId);

            // Catalog Services
            DestroyAllProductsForStore(storeId);
            DestroyAllCategoriesForStore(storeId);
            CatalogServices.ProductProperties.DestroyAllForStore(storeId);
            CatalogServices.ProductTypeDestoryAllForStore(storeId);
            CatalogServices.WishListItems.DestroyAllForStore(storeId);

            // Contact Services
            ContactServices.Affiliates.DestoryForStore(storeId);
            ContactServices.MailingLists.DestoryForStore(storeId);
            ContactServices.Manufacturers.DestoryAllForStore(storeId);
            ContactServices.PriceGroups.DestoryAllForStore(storeId);
            ContactServices.Vendors.DestoryAllForStore(storeId);

            // Content Services
            ContentServices.Columns.DestroyForStore(storeId);

            ContentServices.HtmlTemplates.DestroyAllForStore(storeId);

            // Customer Points
            CustomerPointsManager.DestroyAllForStore(storeId);

            // Membership
            MembershipServices.UserQuestions.DestroyAllForStore(storeId);
            MembershipServices.Customers.DestroyAllForStore(storeId);

            // Marketing
            MarketingServices.Promotions.DestroyAllForStore(storeId);

            // Metrics
            MetricsSerices.SearchQueries.DestoryAllForStore(storeId);

            // Orders
            OrderServices.Orders.DestoryAllForStore(storeId);
            OrderServices.ShippingMethods.DestoryAllForStore(storeId);
            OrderServices.ShippingZones.DestoryAllForStore(storeId);
            OrderServices.Taxes.DestoryAllForStore(storeId);
            OrderServices.TaxSchedules.DestoryAllForStore(storeId);
            OrderServices.Transactions.DestoryAllForStore(storeId);

            // Tasks
            ScheduleServices.QueuedTasks.DestoryAllForStore(storeId);

            // Account Services
            AccountServices.ApiKeys.DestoryAllForStore(storeId);
            AccountServices.Stores.Delete(storeId);

            if (result)
            {
                EventLog.LogEvent("System", "Finished Destroying Store " + storeId, EventLogSeverity.Debug);
            }
            else
            {
                EventLog.LogEvent("System", "Error Destroying Store " + storeId, EventLogSeverity.Warning);
            }

            return result;
        }

        private class ProductIdCombo
        {
            public string ProductId { get; set; }
            public string VariantId { get; set; }
            public string ProductName { get; set; }
            public int Quantity { get; set; }
            public Product Product { get; set; }

            public string Key()
            {
                return ProductId + VariantId;
            }
        }

        #region Services

        private AccountService _AccountService;

        public AccountService AccountServices
        {
            get
            {
                if (_AccountService == null)
                {
                    _AccountService = Factory.CreateService<AccountService>(CurrentRequestContext);
                }
                return _AccountService;
            }
        }

        private CatalogService _CatalogService;

        public CatalogService CatalogServices
        {
            get
            {
                if (_CatalogService == null)
                {
                    _CatalogService = Factory.CreateService<CatalogService>(CurrentRequestContext);
                }
                return _CatalogService;
            }
        }

        private ContactService _ContactServices;

        public ContactService ContactServices
        {
            get
            {
                if (_ContactServices == null)
                {
                    _ContactServices = Factory.CreateService<ContactService>(CurrentRequestContext);
                }
                return _ContactServices;
            }
        }

        private ContentService _ContentServices;

        public ContentService ContentServices
        {
            get
            {
                if (_ContentServices == null)
                {
                    _ContentServices = Factory.CreateService<ContentService>(CurrentRequestContext);
                }
                return _ContentServices;
            }
        }

        private OrderService _OrderServices;

        public OrderService OrderServices
        {
            get
            {
                if (_OrderServices == null)
                {
                    _OrderServices = Factory.CreateService<OrderService>(CurrentRequestContext);
                }
                return _OrderServices;
            }
        }

        private MarketingService _MarketingServices;

        public MarketingService MarketingServices
        {
            get
            {
                if (_MarketingServices == null)
                {
                    _MarketingServices = Factory.CreateService<MarketingService>(CurrentRequestContext);
                }
                return _MarketingServices;
            }
        }

        private ScheduleService _ScheduleServices;

        public ScheduleService ScheduleServices
        {
            get
            {
                if (_ScheduleServices == null)
                {
                    _ScheduleServices = Factory.CreateService<ScheduleService>(CurrentRequestContext);
                }
                return _ScheduleServices;
            }
        }

        private MembershipServices _MembershipServices;

        public MembershipServices MembershipServices
        {
            get
            {
                if (_MembershipServices == null)
                {
                    _MembershipServices = Factory.CreateService<MembershipServices>(CurrentRequestContext);
                }
                return _MembershipServices;
            }
        }

        private MetricsServices _MetricsServices;

        public MetricsServices MetricsSerices
        {
            get
            {
                if (_MetricsServices == null)
                {
                    _MetricsServices = Factory.CreateService<MetricsServices>(CurrentRequestContext);
                }
                return _MetricsServices;
            }
        }

        private CustomerPointsManager _CustomerPointsManager;

        public CustomerPointsManager CustomerPointsManager
        {
            get
            {
                if (_CustomerPointsManager == null)
                {
                    _CustomerPointsManager = Factory.CreateService<CustomerPointsManager>(CurrentRequestContext);
                }
                return _CustomerPointsManager;
            }
        }

        private AnalyticsService _AnalyticsService;

        public AnalyticsService AnalyticsService
        {
            get
            {
                if (_AnalyticsService == null)
                {
                    _AnalyticsService = Factory.CreateService<AnalyticsService>(CurrentRequestContext);
                }
                return _AnalyticsService;
            }
        }

        private GlobalizationService _GlobalizationService;

        public GlobalizationService GlobalizationServices
        {
            get
            {
                if (_GlobalizationService == null)
                {
                    _GlobalizationService = Factory.CreateService<GlobalizationService>(CurrentRequestContext);
                }
                return _GlobalizationService;
            }
        }

        private ISocialService _SocialService;

        public ISocialService SocialService
        {
            get
            {
                if (_SocialService == null)
                {
                    _SocialService = Factory.CreateSocialService(CurrentRequestContext);
                }
                return _SocialService;
            }
        }

        #endregion
    }
}


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

  <artifactId>website.integration-tests</artifactId>

  <properties>
    <!-- Root dir -->
    <root.dir>${basedir}/..</root.dir>
  </properties>

  <dependencies>

    <dependency>
      <groupId>net.larskristian</groupId>
      <artifactId>website.framework</artifactId>
      <version>${project.version}</version>
      <scope>system</scope>
      <systemPath>${root.dir}/framework/target/website.framework-1.0-SNAPSHOT.jar</systemPath>
    </dependency>

    <dependency>
      <groupId>net.larskristian</groupId>
      <artifactId>website.core</artifactId>
      <version>${project.version}</version>
      <scope>system</scope>
      <systemPath>${root.dir}/core/target/website.core-1.0-SNAPSHOT.jar</systemPath>
    </dependency>

    <dependency>
      <groupId>net.larskristian</groupId>
      <artifactId>website.ui</artifactId>
      <version>${project.version}</version>
      <scope>system</scope>
      <systemPath>${root.dir}/ui/target/website.ui-1.0-SNAPSHOT.jar</systemPath>
    </dependency>

    <dependency>
      <groupId>net.larskristian</groupId>
      <artifactId>website.api</artifactId>
      <version>${project.version}</version>
      <scope>system</scope>
      <systemPath>${root.dir}/api/target/website.api-1.0-SNAPSHOT.jar</systemPath>
    </dependency>

    <dependency>
      <groupId>net.larskristian</groupId>
      <artifactId>website.db</artifactId>
      <version>${project.version}</version>
      <scope>system</scope>
      <systemPath>${root.dir}/db/target/website.db-1.0-SNAPSHOT.jar</systemPath>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
      <scope>test</scope>
    </dependency>

  </dependencies>

  <build>
    <plugins>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>${maven.surefire.version}</version>
        <configuration>
          <includes>
            <include>**/*Tests.java</include>
          </includes>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.jacoco</groupId>
        <artifactId>jacoco-maven-plugin</artifactId>
        <version>${jacoco.version}</version>
        <executions>
          <execution>
            <id>pre-unit-test</id>
            <goals>
              <goal>prepare-agent</goal>
            </goals>
          </execution>
          <execution>
            <id>post-unit-test</id>
            <phase>test</phase>
            <goals>
              <goal>report</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

    </plugins>
  </build>

</project>


text:
die "Usage: $0 objectId\n" unless $ARGV[0];

use O2::Context;
my $ctx = O2::Context->new();

my $object = $ctx->getObjectById( $ARGV[0] );

die "Object cannot be seriazlized" unless $object->isSerializable();

my $serializedObj = $object->getObjectPlds();

print "This is a/n ".ref $object," object with ID $ARGV[0]\n";
print "=" x 70, "\n";

#use Data::Dumper;
#print Dumper( $serializedObj );

for my $heading ( qw/data meta/ ) {
    print $heading,"\n";
    print "-" x 70, "\n";
    foreach my $key ( keys %{$serializedObj->{$heading}} )  {
        printf "%-25s : %s\n", $key, $serializedObj->{$heading}->{$key};
    }
    print "\n";
}


text:
using namespace Eigen;

void foo(){
    MatrixXf m;
    TriangularView<CV_QUALIFIER MatrixXf,Upper>(m).coeffRef(0, 0) = 1.0f;
}

int main() {}


text:
@implementation DLFYapDatabaseViewAndMapping

+ (DLFYapDatabaseViewAndMapping *)viewMappingWithViewName:(NSString *)viewName
                                               collection:(NSString *)collection
                                                 database:(YapDatabase *)database
                                                  sortKey:(NSString *)sortKey
                                               sortKeyAsc:(BOOL)ascending
                                               completion:(void(^)(DLFYapDatabaseViewAndMapping *viewMapping))completionBlock {
    return [self.class viewMappingWithViewName:viewName collection:collection database:database sortKey:sortKey sortKeyAsc:ascending groupKey:nil groupSortAsc:NO isPersistent:YES completion:completionBlock filterBlock:nil];
}

+ (DLFYapDatabaseViewAndMapping *)viewMappingWithViewName:(NSString *)viewName
                                               collection:(NSString *)collection
                                                 database:(YapDatabase *)database
                                                  sortKey:(NSString *)sortKey
                                               sortKeyAsc:(BOOL)ascending {
    return [DLFYapDatabaseViewAndMapping viewMappingWithViewName:viewName collection:collection database:database sortKey:sortKey sortKeyAsc:ascending completion:nil];
}

+ (DLFYapDatabaseViewAndMapping *)viewMappingWithViewName:(NSString *)viewName
                                               collection:(NSString *)aCollection
                                                 database:(YapDatabase *)database
                                                  sortKey:(NSString *)sortKey
                                               sortKeyAsc:(BOOL)sortKeyAscending
                                                 groupKey:(NSString *)groupKey
                                             groupSortAsc:(BOOL)groupSortAscending {
    return [DLFYapDatabaseViewAndMapping viewMappingWithViewName:viewName collection:aCollection database:database sortKey:sortKey sortKeyAsc:sortKeyAscending groupKey:groupKey groupSortAsc:groupSortAscending isPersistent:YES completion:nil filterBlock:nil];
}

+ (DLFYapDatabaseViewAndMapping *)viewMappingWithViewName:(NSString *)viewName
                                               collection:(NSString *)collection
                                                 database:(YapDatabase *)database
                                                  sortKey:(NSString *)sortKey
                                               sortKeyAsc:(BOOL)ascending
                                             isPersistent:(BOOL)isPersistent
                                              filterBlock:(BOOL(^)(NSString *collection, NSString *key, id object))filterBlock {
    return [self.class viewMappingWithViewName:viewName collection:collection database:database sortKey:sortKey sortKeyAsc:ascending groupKey:nil groupSortAsc:NO isPersistent:isPersistent completion:nil filterBlock:filterBlock];
}

+ (DLFYapDatabaseViewAndMapping *)viewMappingWithViewName:(NSString *)viewName
                                               collection:(NSString *)aCollection
                                                 database:(YapDatabase *)database
                                                  sortKey:(NSString *)sortKey
                                               sortKeyAsc:(BOOL)sortKeyAscending
                                                 groupKey:(NSString *)groupKey
                                             groupSortAsc:(BOOL)groupSortAscending
                                             isPersistent:(BOOL)isPersistent
                                              filterBlock:(BOOL(^)(NSString *collection, NSString *key, id object))filterBlock {
    return [DLFYapDatabaseViewAndMapping viewMappingWithViewName:viewName collection:aCollection database:database sortKey:sortKey sortKeyAsc:sortKeyAscending groupKey:groupKey groupSortAsc:groupSortAscending isPersistent:isPersistent completion:nil filterBlock:filterBlock];
}

+ (DLFYapDatabaseViewAndMapping *)viewMappingWithViewName:(NSString *)viewName
                                               collection:(NSString *)aCollection
                                                 database:(YapDatabase *)database
                                                  sortKey:(NSString *)sortKey
                                               sortKeyAsc:(BOOL)sortKeyAscending
                                                 groupKey:(NSString *)groupKey
                                             groupSortAsc:(BOOL)groupSortAscending
                                             isPersistent:(BOOL)isPersistent
                                               completion:(void(^)(DLFYapDatabaseViewAndMapping *viewMapping))completionBlock
                                              filterBlock:(BOOL(^)(NSString *collection, NSString *key, id object))filterBlock {

    YapDatabaseViewGroupingWithObjectBlock groupingBlock = ^NSString *(NSString *collection, NSString *key, id object) {
        if (![collection isEqualToString:aCollection]) {
            return nil;
        }
        if (filterBlock) {
            BOOL include = filterBlock(collection, key, object);
            if (!include) {
                return nil;
            }
        }
        return (groupKey && [aCollection isEqualToString:collection])?[[object valueForKey:groupKey] description]:@"";
    };

    YapDatabaseViewSortingWithObjectBlock sortingBlock = ^NSComparisonResult(NSString *group,
                                                                             NSString *collection1, NSString *key1, id obj1,
                                                                             NSString *collection2, NSString *key2, id obj2){
        if (![collection1 isEqualToString:aCollection] || ![collection2 isEqualToString:aCollection]) {
            return NSOrderedSame;
        }
        return (sortKeyAscending)?[[obj1 valueForKey:sortKey] compare:[obj2 valueForKey:sortKey]]:[[obj2 valueForKey:sortKey] compare:[obj1 valueForKey:sortKey]];
    };

    YapDatabaseViewGrouping *grouping = [YapDatabaseViewGrouping withObjectBlock:groupingBlock];
    YapDatabaseViewSorting *sorting = [YapDatabaseViewSorting withObjectBlock:sortingBlock];

    YapDatabaseViewOptions *options = [[YapDatabaseViewOptions alloc] init];
    [options setIsPersistent:isPersistent];
    YapWhitelistBlacklist *whitelist = [[YapWhitelistBlacklist alloc] initWithWhitelist:[NSSet setWithObject:aCollection]];
    [options setAllowedCollections:whitelist];
    [options setSkipInitialViewPopulation:YES];

    YapDatabaseView *view = [[YapDatabaseView alloc] initWithGrouping:grouping sorting:sorting versionTag:@"1" options:options];

    DLFYapDatabaseViewAndMapping * (^viewMappingInit)() = ^DLFYapDatabaseViewAndMapping*() {
        YapDatabaseViewMappings *mappings = [[YapDatabaseViewMappings alloc] initWithGroupFilterBlock:^BOOL(NSString *group, YapDatabaseReadTransaction *transaction) {
            return (group)?YES:NO;
        } sortBlock:^NSComparisonResult(NSString *group1, NSString *group2, YapDatabaseReadTransaction *transaction) {
            return (groupSortAscending)?[group1 compare:group2]:[group2 compare:group1];
        } view:viewName];

        DLFYapDatabaseViewAndMapping *returnObject = [[DLFYapDatabaseViewAndMapping alloc] init];
        returnObject.view = view;
        returnObject.mapping = mappings;
        returnObject.viewName = viewName;
        returnObject.sortKey = sortKey;
        returnObject.sortKeyAscending = sortKeyAscending;
        returnObject.groupSortAscending = groupSortAscending;
        returnObject.groupKey = groupKey;
        returnObject.isPersistent = isPersistent;
        returnObject.filterBlock = filterBlock;
        returnObject.collection = aCollection;

        return returnObject;
    };

    if ([database registeredExtension:viewName]) {
        if (!completionBlock) {
            return viewMappingInit();
        } else {
            completionBlock(viewMappingInit());
            return nil;
        }
    }

    if (!completionBlock) {

        [database registerExtension:view withName:viewName];
        return viewMappingInit();
    } else {
        [database asyncRegisterExtension:view withName:viewName completionBlock:^(BOOL ready) {
            if (ready) {
                DLFYapDatabaseViewAndMapping *returnObject = viewMappingInit();
                completionBlock(returnObject);
            }
        }];
    }
    return nil;
}

+ (DLFYapDatabaseViewAndMapping *)filteredViewMappingFromViewName:(NSString *)fromViewName
                                                         database:(YapDatabase *)database
                                                       collection:(NSString *)collection
                                                     isPersistent:(BOOL)isPersistent
                                        skipInitialViewPopulation:(BOOL)skipInitialViewPopulation
                                                       filterName:(NSString *)filterName
                                                     groupSortAsc:(BOOL)groupSortAscending
                                                      filterBlock:(BOOL (^)(NSString *collection, NSString *key, id object))filterBlock {
    return [DLFYapDatabaseViewAndMapping filteredViewMappingFromViewName:fromViewName database:database collection:collection isPersistent:isPersistent skipInitialViewPopulation:skipInitialViewPopulation groupSortAsc:groupSortAscending filterName:filterName filterBlock:filterBlock completion:nil];
}

+ (DLFYapDatabaseViewAndMapping *)filteredViewMappingFromViewName:(NSString *)fromViewName
                                                         database:(YapDatabase *)database
                                                       collection:(NSString *)collection
                                                     isPersistent:(BOOL)isPersistent
                                        skipInitialViewPopulation:(BOOL)skipInitialViewPopulation
                                                     groupSortAsc:(BOOL)groupSortAscending
                                                       filterName:(NSString *)filterName
                                                      filterBlock:(BOOL (^)(NSString *collection, NSString *key, id object))filterBlock
                                                       completion:(void(^)(DLFYapDatabaseViewAndMapping *viewMapping))completionBlock {

    YapDatabaseViewFiltering *filtering = [YapDatabaseViewFiltering withObjectBlock:^BOOL(NSString *group, NSString *collection, NSString *key, id object) {
        return filterBlock(collection, key, object);
    }];
    YapDatabaseViewOptions *options = [[YapDatabaseViewOptions alloc] init];
    [options setIsPersistent:isPersistent];
    [options setSkipInitialViewPopulation:skipInitialViewPopulation];
    YapDatabaseFilteredView *filteredView = [[YapDatabaseFilteredView alloc] initWithParentViewName:fromViewName filtering:filtering versionTag:filterName options:options];

    NSString *viewName = [self.class filteredViewNameFromParentViewName:fromViewName filterName:filterName];

    DLFYapDatabaseViewAndMapping * (^viewMappingInit)() = ^DLFYapDatabaseViewAndMapping*() {
        YapDatabaseViewMappings *mappings = [[YapDatabaseViewMappings alloc] initWithGroupFilterBlock:^BOOL(NSString *group, YapDatabaseReadTransaction *transaction) {
            return (group)?YES:NO;
        } sortBlock:^NSComparisonResult(NSString *group1, NSString *group2, YapDatabaseReadTransaction *transaction) {
            return groupSortAscending?[group1 compare:group2]:[group2 compare:group1];
        } view:viewName];

        DLFYapDatabaseViewAndMapping *returnObject = [[DLFYapDatabaseViewAndMapping alloc] init];
        returnObject.view = filteredView;
        returnObject.viewName = viewName;
        returnObject.mapping = mappings;
        returnObject.isPersistent = isPersistent;
        returnObject.filterBlock = filterBlock;
        returnObject.collection = collection;

        return returnObject;
    };

    if ([database registeredExtension:viewName]) {
        if (!completionBlock) {
            return viewMappingInit();
        } else {
            DLFYapDatabaseViewAndMapping *returnObject = viewMappingInit();
            completionBlock(returnObject);
            return nil;
        }
    }

    CLS_LOG(@"Registering new view %@", viewName);
    if (!completionBlock) {
        [database registerExtension:filteredView withName:viewName];
        return viewMappingInit();
    } else {
        [database asyncRegisterExtension:filteredView withName:viewName completionBlock:^(BOOL ready) {
            if (ready) {
                DLFYapDatabaseViewAndMapping *returnObject = viewMappingInit();
                completionBlock(returnObject);
            }
        }];
    }
    return nil;
}

+ (DLFYapDatabaseViewAndMapping *)ungroupedViewMappingFromViewMapping:(DLFYapDatabaseViewAndMapping *)viewMappingSource database:(YapDatabase *)database {
    return [DLFYapDatabaseViewAndMapping ungroupedViewMappingFromViewMapping:viewMappingSource database:database completion:nil];
}

+ (DLFYapDatabaseViewAndMapping *)ungroupedViewMappingFromViewMapping:(DLFYapDatabaseViewAndMapping *)viewMappingSource database:(YapDatabase *)database completion:(void(^)(DLFYapDatabaseViewAndMapping *viewMapping))completionBlock {
    return [DLFYapDatabaseViewAndMapping viewMappingWithViewName:[DLFYapDatabaseViewAndMapping flattenedViewName:viewMappingSource.mapping.view] collection:viewMappingSource.collection database:database sortKey:viewMappingSource.sortKey sortKeyAsc:viewMappingSource.sortKeyAscending groupKey:nil groupSortAsc:NO isPersistent:viewMappingSource.isPersistent completion:completionBlock filterBlock:viewMappingSource.filterBlock];
}

+ (void)asyncViewMappingWithViewName:(NSString *)viewName
                          collection:(NSString *)collection
                            database:(YapDatabase *)database
                             sortKey:(NSString *)sortKey
                          sortKeyAsc:(BOOL)ascending
                          completion:(void(^)(DLFYapDatabaseViewAndMapping *viewMapping))completionBlock {
    [DLFYapDatabaseViewAndMapping viewMappingWithViewName:viewName collection:collection database:database sortKey:sortKey sortKeyAsc:ascending groupKey:nil groupSortAsc:NO isPersistent:YES completion:completionBlock filterBlock:nil];
}

+ (void)asyncViewMappingWithViewName:(NSString *)viewName
                          collection:(NSString *)collection
                            database:(YapDatabase *)database
                             sortKey:(NSString *)sortKey
                          sortKeyAsc:(BOOL)sortKeyAsc
                            groupKey:(NSString *)groupKey
                        groupSortAsc:(BOOL)groupSortAsc
                          completion:(void(^)(DLFYapDatabaseViewAndMapping *viewMapping))completionBlock {
    [DLFYapDatabaseViewAndMapping viewMappingWithViewName:viewName collection:collection database:database sortKey:sortKey sortKeyAsc:sortKeyAsc groupKey:groupKey groupSortAsc:groupSortAsc isPersistent:YES completion:completionBlock filterBlock:nil];
}

+ (void)asyncViewMappingWithViewName:(NSString *)viewName
                          collection:(NSString *)collection
                            database:(YapDatabase *)database
                             sortKey:(NSString *)sortKey
                          sortKeyAsc:(BOOL)ascending
                        isPersistent:(BOOL)isPersistent
                         filterBlock:(BOOL(^)(NSString *collection, NSString *key, id object))filterBlock
                          completion:(void(^)(DLFYapDatabaseViewAndMapping *viewMapping))completionBlock {
    [DLFYapDatabaseViewAndMapping viewMappingWithViewName:viewName collection:collection database:database sortKey:sortKey sortKeyAsc:ascending groupKey:nil groupSortAsc:NO isPersistent:isPersistent completion:completionBlock filterBlock:filterBlock];
}

+ (void)asyncViewMappingWithViewName:(NSString *)viewName
                          collection:(NSString *)collection
                            database:(YapDatabase *)database
                             sortKey:(NSString *)sortKey
                          sortKeyAsc:(BOOL)sortKeyAsc
                            groupKey:(NSString *)groupKey
                        groupSortAsc:(BOOL)groupSortAsc
                        isPersistent:(BOOL)isPersistent
                         filterBlock:(BOOL(^)(NSString *collection, NSString *key, id object))filterBlock
                          completion:(void(^)(DLFYapDatabaseViewAndMapping *viewMapping))completionBlock {
    [DLFYapDatabaseViewAndMapping viewMappingWithViewName:viewName collection:collection database:database sortKey:sortKey sortKeyAsc:sortKeyAsc groupKey:groupKey groupSortAsc:groupSortAsc isPersistent:isPersistent completion:completionBlock filterBlock:filterBlock];
}

+ (void)asyncUngroupedViewMappingFromViewMapping:(DLFYapDatabaseViewAndMapping *)viewMappingSource
                                        database:(YapDatabase *)database
                                      completion:(void(^)(DLFYapDatabaseViewAndMapping *viewMapping))completionBlock {
    [DLFYapDatabaseViewAndMapping ungroupedViewMappingFromViewMapping:viewMappingSource database:database completion:completionBlock];
}

+ (NSString *)flattenedViewName:(NSString *)viewName {
    return [NSString stringWithFormat:@"%@-flattened", viewName];
}

+ (NSString *)filteredViewNameFromParentViewName:(NSString *)parentViewName filterName:(NSString *)filterName{
    return [NSString stringWithFormat:@"%@-%@", filterName, parentViewName];
}

+ (void)asyncFilteredViewMappingFromViewName:(NSString *)fromViewName
                                    database:(YapDatabase *)database
                                  collection:(NSString *)collection
                                isPersistent:(BOOL)isPersistent
                   skipInitialViewPopulation:(BOOL)skipInitialViewPopulation
                                  filterName:(NSString *)filterName
                                groupSortAsc:(BOOL)groupSortAscending
                                 filterBlock:(BOOL (^)(NSString *, NSString *, id))filterBlock completion:(void(^)(DLFYapDatabaseViewAndMapping *viewMapping))completionBlock {
    [DLFYapDatabaseViewAndMapping filteredViewMappingFromViewName:fromViewName database:database collection:collection isPersistent:isPersistent skipInitialViewPopulation:skipInitialViewPopulation groupSortAsc:groupSortAscending filterName:filterName filterBlock:filterBlock completion:completionBlock];
}

@end


text:
package sample;

import com.gs.fw.common.mithra.MithraManager;
import com.gs.fw.common.mithra.MithraManagerProvider;
import com.gs.fw.common.mithra.MithraTransaction;
import com.gs.fw.common.mithra.finder.Operation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sample.domain.*;
import sample.util.H2ConnectionManager;

import java.io.InputStream;
import java.sql.Timestamp;
import java.time.LocalDateTime;

public class HelloReladomoApp
{
    private static Logger logger = LoggerFactory.getLogger(HelloReladomoApp.class.getName());
    private static final int MAX_TRANSACTION_TIMEOUT = 120;

    public static void main(String[] args)
    {
        HelloReladomoApp app = new HelloReladomoApp();
        initialize(app);

        Employee hanako = MithraManagerProvider.getMithraManager().executeTransactionalCommand(tx -> {
            //3月1日をシミュレートするためのコード。本番環境ではダメ、絶対!
            Timestamp procdate = Timestamp.valueOf(LocalDateTime.of(2017, 3, 1, 0, 0));
            Timestamp apr1 = Timestamp.valueOf(LocalDateTime.of(2017, 4, 1, 0, 0));
            simulateProcessingDateAs(procdate, tx);

            //3月1日にこのコードが実行される
            Employee hanakoNew = new Employee(apr1); //メモリ上にオブジェクト作成
            hanakoNew.setLastName("鈴木");
            hanakoNew.setFirstName("花子");
            hanakoNew.insert(); // データベースに挿入
            return hanakoNew; //トランザクション終了後に使用したいオブジェクトを返り値として与えることができる。
        });

        Timestamp jun6 = Timestamp.valueOf(LocalDateTime.of(2017, 6, 6, 0, 0));
        Operation opJun6 = EmployeeFinder.firstName().eq("花子").
                and(EmployeeFinder.businessDate().eq(jun6)); //6月6日付でフェッチ
        final Employee hanakoJun6 = EmployeeFinder.findOne(opJun6); //遅延ロードされるのでこの時点ではフェッチされない

        MithraManagerProvider.getMithraManager().executeTransactionalCommand(tx -> {
            Timestamp procdate = Timestamp.valueOf(LocalDateTime.of(2017, 6, 6, 0, 0));
            simulateProcessingDateAs(procdate, tx);

            //6月6日にこのコードが実行される
            hanakoJun6.setLastName("斉藤"); // この時点で遅延フェッチ&アップデート
            return null; //トランザクション終了後に使用したいオブジェクトを返り値として与えることができる。ここでは必要ないのでnullを返す。
        });

        MithraManagerProvider.getMithraManager().executeTransactionalCommand(tx -> {
            Timestamp procdate = Timestamp.valueOf(LocalDateTime.of(2017, 6, 8, 0, 0));
            simulateProcessingDateAs(procdate, tx);

            //6月8日にこのコードが実行される
            hanakoJun6.setLastName("斎藤"); // この時点で遅延フェッチ&アップデート
            return null; //トランザクション終了後に使用したいオブジェクトを返り値として与えることができる。ここでは必要ないのでnullを返す。
        });

        Timestamp dec1 = Timestamp.valueOf(LocalDateTime.of(2017, 12, 1, 0, 0));
        Operation opDec1 = EmployeeFinder.firstName().eq("花子").
                and(EmployeeFinder.businessDate().eq(dec1)); //12月1日付でフェッチ
        final Employee hanakoDec1 = EmployeeFinder.findOne(opDec1); //遅延ロードされるのでこの時点ではフェッチされない

        MithraManagerProvider.getMithraManager().executeTransactionalCommand(tx -> {
            Timestamp procdate = Timestamp.valueOf(LocalDateTime.of(2017, 12, 1, 0, 0));
            simulateProcessingDateAs(procdate, tx);

            //12月1日にこのコードが実行される
            hanako.terminate(); // OUT = NOW
            return null; //トランザクション終了後に使用したいオブジェクトを返り値として与えることができる。ここでは必要ないのでnullを返す。
        });

//
//        Timestamp mar5 = Timestamp.valueOf(LocalDateTime.of(2017, 3, 5, 0, 0));
//        Employee hanakoMar5 = EmployeeFinder.findOne(EmployeeFinder.processingDate().eq(mar5));
//        logger.info("Mar 5: " + hanakoMar5.getLastName() + " " + hanakoMar5.getFirstName());
//
//
//        Timestamp jun5 = Timestamp.valueOf(LocalDateTime.of(2017, 6, 5, 0, 0));
//        Employee hanakoJun5 = EmployeeFinder.findOne(EmployeeFinder.processingDate().eq(jun5));
//        logger.info("June 5: " + hanakoJun5.getLastName() + " " + hanakoJun5.getFirstName());
//        Timestamp jun6 = Timestamp.valueOf(LocalDateTime.of(2017, 6, 6, 0, 0));
//        Employee hanakoJun6 = EmployeeFinder.findOne(EmployeeFinder.processingDate().eq(jun6));
//        logger.info("June 6: " + hanakoJun6.getLastName() + " " + hanakoJun6.getFirstName());
//        Timestamp jun7 = Timestamp.valueOf(LocalDateTime.of(2017, 6, 7, 0, 0));
//        Employee hanakoJun7 = EmployeeFinder.findOne(EmployeeFinder.processingDate().eq(jun7));
//        logger.info("June 7: " + hanakoJun7.getLastName() + " " + hanakoJun7.getFirstName());
//        Timestamp jun8 = Timestamp.valueOf(LocalDateTime.of(2017, 6, 8, 0, 0));
//        Employee hanakoJun8 = EmployeeFinder.findOne(EmployeeFinder.processingDate().eq(jun8));
//        logger.info("June 8: " + hanakoJun8.getLastName() + " " + hanakoJun8.getFirstName());
////        logger.info("Jun 6 " + hanakoAsOfJun6BipassCache.getLastName() + " " + hanakoAsOfJun6BipassCache.getFirstName());
    }

    private static void simulateProcessingDateAs(Timestamp procdate, MithraTransaction tx) {
        tx.setProcessingStartTime(procdate.getTime());
    }

    private static void initialize(HelloReladomoApp app)
    {
        try
        {
            // This line is added to make in-memory tables ready.
            // It's not typically done in production app that usually connects to physical db
            H2ConnectionManager.getInstance().prepareTables();

            app.initialiseReladomo();
            app.loadReladomoConfigurationXml("reladomo/config/ReladomoRuntimeConfig.xml");
        }
        catch(Exception e)
        {
            logger.error("Couldn't run HelloReladomoApp.", e);
        }
    }

    private void initialiseReladomo() throws Exception
    {
        try
        {
            logger.info("Transaction Timeout is " + MAX_TRANSACTION_TIMEOUT);
            MithraManager mithraManager = MithraManagerProvider.getMithraManager();
            mithraManager.setTransactionTimeout(MAX_TRANSACTION_TIMEOUT);
            // Notification should be configured here. Refer to notification/Notification.html under reladomo-javadoc.jar.
        }
        catch (Exception e)
        {
            logger.error("Unable to initialise Reladomo!", e);
            throw new Exception("Unable to initialise Reladomo!", e);
        }
        logger.info("Reladomo has been initialised!");
    }

    private void loadReladomoConfigurationXml(String reladomoRuntimeConfig) throws Exception
    {
        logger.info("Reladomo configuration XML is " + reladomoRuntimeConfig);
        InputStream is = HelloReladomoApp.class.getClassLoader().getResourceAsStream(reladomoRuntimeConfig);
        if (is == null) throw new Exception("can't find file: " + reladomoRuntimeConfig + " in classpath");
        MithraManagerProvider.getMithraManager().readConfiguration(is);
        try
        {
            is.close();
        }
        catch (java.io.IOException e)
        {
            logger.error("Unable to initialise Reladomo!", e);
            throw new Exception("Unable to initialise Reladomo!", e);
        }
        logger.info("Reladomo configuration XML " + reladomoRuntimeConfig+" is now loaded.");
    }
}


text:
// Created by Ron 'Maxwolf' McDowell (ron.mcdowell@gmail.com)
// Timestamp 01/03/2016@1:50 AM

using System;
using System.Text;

namespace OregonTrail
{
    /// <summary>
    ///     Attached when the party leader dies, or the vehicle reaches the end of the trail.
    /// </summary>
    [ParentWindow(typeof (GameOver))]
    public sealed class GameWin : InputForm<GameOverInfo>
    {
        /// <summary>
        ///     Holds reference to end game text that will be shown to the user.
        /// </summary>
        private StringBuilder _gameOver;

        /// <summary>
        ///     Initializes a new instance of the <see cref="GameWin" /> class.
        ///     This constructor will be used by the other one
        /// </summary>
        /// <param name="window">The window.</param>
        public GameWin(IWindow window) : base(window)
        {
            _gameOver = new StringBuilder();
        }

        public override object MenuCommands
        {
            get { return new[] {"Ok"}; }
        }

        /// <summary>
        ///     Fired when dialog prompt is attached to active game Windows and would like to have a string returned.
        /// </summary>
        /// <returns>
        ///     The dialog prompt text.<see cref="string" />.
        /// </returns>
        protected override string OnDialogPrompt()
        {
            _gameOver.AppendLine(
                $"{Environment.NewLine}Congratulations! You have made it to Oregon! Let's see how many points you have received.{Environment.NewLine}");
            return _gameOver.ToString();
        }

        /// <summary>
        ///     Fired when the dialog receives favorable input and determines a response based on this. From this method it is
        ///     common to attach another state, or remove the current state based on the response.
        /// </summary>
        /// <param name="reponse">The response the dialog parsed from simulation input buffer.</param>
        protected override void OnDialogResponse(DialogResponse reponse)
        {
            SetForm(typeof (FinalPoints));
        }
    }
}


text:
import sys

OFFSET_BOOTLOADER = 0x1000
OFFSET_PARTITIONS = 0x8000
OFFSET_APPLICATION = 0x10000

files_in = [
    ('bootloader', OFFSET_BOOTLOADER, sys.argv[1]),
    ('partitions', OFFSET_PARTITIONS, sys.argv[2]),
    ('application', OFFSET_APPLICATION, sys.argv[3]),
]
file_out = sys.argv[4]

cur_offset = 0
with open(file_out, 'wb') as fout:
    for name, offset, file_in in files_in:
        assert offset >= cur_offset
        fout.write(b'\xff' * (offset - cur_offset))
        cur_offset = offset
        with open(file_in, 'rb') as fin:
            data = fin.read()
            fout.write(data)
            cur_offset += len(data)
            print('%-12s% 8d' % (name, len(data)))
    print('%-12s% 8d' % ('total', cur_offset))


text:
  Cloué est
       un village
       situé dans le département de Vienne en Poitou-Charentes. Elle comptait 445 habitants en 2008.

Si vous pensez emmenager à Cloué, vous pourrez facilement trouver une maison à vendre.

La ville offre quelques  équipements sportifs, elle propose entre autres un terrain de sport et un équipement de roller/skate.

À coté de Cloué sont localisées les communes de
Coulombiers à 5 km, 1 048 habitants,
Lusignan à 3 km, 2 565 habitants,
Curzay-sur-Vonne située à 10 km, 456 habitants,
Rouillé située à 9 km, 2 374 habitants,
Marigny-Chemereau localisée à 4 km, 491 habitants,
Marçay à 5 km, 764 habitants,
 entre autres. De plus, Cloué est située à seulement 21 km de Poitiers.

Le nombre d'habitations, à Cloué, était réparti en 2011 en deux appartements et 221 maisons soit
 un marché relativement équilibré.


text:
//TOSListener.java
package tos.system;

import java.rmi.*;
import tos.api.*;

/** This remote interface supplies the remote functionality
 * of the Listener thread all clients run.
 */

public interface TOSListener extends Remote
{
	/** Suspends a user thread.
	 * @param threadName Thread to suspend.
	 * @exception RemoteException if there has been an RMI error.
	 */
	void suspend(String threadName) throws RemoteException;

	/** Resumes a suspended thread.
	 * @param Concatenated TOS process identifier and thread name.
	 * @exception RemoteException if there has been an RMI error.
	 * @exception SyncException if an error occurs with the sync object.
	 */
	void resume(String name) throws RemoteException, SyncException;

	/** Kills a process.
	 * The Administrator uses this function to order a process to
	 * commit suicide.
	 * @exception RemoteException if there has been an RMI error.
	 */
	void killProcess() throws RemoteException;
}


text:
package pocket4j.action.modify;

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

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import pocket4j.action.Action;

public abstract class BaseModifyAction implements Action {

	/** The id of the item to perform the action on. */
	protected int itemId;
	/** The time the action occurred. */
	protected Date time;

	public BaseModifyAction(final int itemId) {
		this(itemId, null);
	}

	public BaseModifyAction(final int itemId, final Date time) {
		this.itemId = itemId;
		this.time = time;
	}

	/**
	 * アクション名を返す。
	 *
	 * @return アクション名
	 */
	public abstract String getActionName();

	@Override
	public Method getMethod() {
		return Method.GET;
	}

	@Override
	public Map<String, String> getRequestParams() {

		final JSONArray actions = new JSONArray();
		try {
			final JSONObject actionObject = new JSONObject();
			actionObject.put("action", getActionName());
			actionObject.put("item_id", itemId);
			if (time != null) {
				actionObject.put("time", time.getTime());
			}
			actions.put(actionObject);
		} catch (final JSONException e) {
			throw new RuntimeException(e);
		}

		final Map<String, String> params = new HashMap<String, String>();
		params.put("actions", actions.toString());
		return params;
	}

	public int getItemId() {
		return itemId;
	}

	public void setItemId(final int itemId) {
		this.itemId = itemId;
	}

	public Date getTime() {
		return time;
	}

	public void setTime(final Date time) {
		this.time = time;
	}
}


text:
// Code generated by injection-gen. DO NOT EDIT.

package istiofactory

import (
	"context"

	externalversions "github.com/knative/pkg/client/informers/externalversions"
	client "github.com/knative/pkg/client/injection/client"
	controller "github.com/knative/pkg/controller"
	injection "github.com/knative/pkg/injection"
	logging "github.com/knative/pkg/logging"
)

func init() {
	injection.Default.RegisterInformerFactory(withInformerFactory)
}

// Key is used as the key for associating information with a context.Context.
type Key struct{}

func withInformerFactory(ctx context.Context) context.Context {
	c := client.Get(ctx)
	return context.WithValue(ctx, Key{},
		externalversions.NewSharedInformerFactory(c, controller.GetResyncPeriod(ctx)))
}

// Get extracts the InformerFactory from the context.
func Get(ctx context.Context) externalversions.SharedInformerFactory {
	untyped := ctx.Value(Key{})
	if untyped == nil {
		logging.FromContext(ctx).Fatalf(
			"Unable to fetch %T from context.", (externalversions.SharedInformerFactory)(nil))
	}
	return untyped.(externalversions.SharedInformerFactory)
}